def main (): # pygame initialization pygame.init() screen = pygame.display.set_mode((640,480), OPENGL|DOUBLEBUF) clock = pygame.time.Clock() # OpenGL initializations glClearColor(0.0,0.0,0.4,0.0) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) # cull triangles facing away from camera #glEnable(GL_CULL_FACE) # make vertex array VertexArrayID = glGenVertexArrays(1) glBindVertexArray(VertexArrayID) # compile shaders programID = loadProgram( os.path.join("shaders","shader09checkers.vert"), os.path.join("shaders","shader09checkers.frag") ) print "programID:", programID # get handle for "MVP" uniform ProjectionMatrixID = glGetUniformLocation(programID, "P") ViewMatrixID = glGetUniformLocation(programID, "V") ModelMatrixID = glGetUniformLocation(programID, "M") print "P,V,M:",ProjectionMatrixID,ViewMatrixID,ModelMatrixID # texture Texture = loadTexture(os.path.join("images","grid.png")) # get handle TextureID = glGetUniformLocation(programID, "Texture") print "TextureID:", TextureID # vertex, normal, and texture uv data: vertNormUVData, vertNormUVIndices = sphere(1,32,64) # 4 point coords, 4 norm coords, 2 uvs: numberOfVertices = len(vertNormUVIndices) print "N Triangles:", numberOfVertices/3 # vertex buffer for points, norms, uvs vertNormUVBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vertNormUVBuffer) glBufferData(GL_ARRAY_BUFFER, vertNormUVData, GL_STATIC_DRAW) # vertex buffer for indices vertNormUVIndexBuffer = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertNormUVIndexBuffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, vertNormUVIndices, GL_STATIC_DRAW) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) # get handles for uniforms glUseProgram(programID) LightID = glGetUniformLocation(programID, "lightDirection") whichSpaceID = glGetUniformLocation(programID, "whichSpace") print "LightID, whichSpace:", LightID, whichSpaceID # get attribute locations PositionID = glGetAttribLocation(programID, "positionBuffer") NormalID = glGetAttribLocation(programID, "normalBuffer") uvID = glGetAttribLocation(programID, "uvBuffer") print "pos, norm, uv:", PositionID, NormalID, uvID # control object eye = vec((1,2,3)) focus = vec((0,0,0)) control = Control(pos=eye, fwd=focus-eye) lightDirection = normalize(vec((5,5,1,0))) whichSpace = 0 numberOfInstances = 1 time = 0.0 running = True while running: clock.tick(30) time += 0.0333 for event in pygame.event.get(): if event.type == QUIT: running = False if event.type == KEYUP: if event.key == K_ESCAPE: running = False elif event.key == K_SPACE: whichSpace = (whichSpace + 1) % 3 print whichSpace elif event.key == K_x: numberOfInstances += 1 print numberOfInstances elif event.key == K_z: numberOfInstances -= 1 print numberOfInstances if event.type == pygame.MOUSEBUTTONDOWN: control.handleMouseButton(event.button) control.handleMouseMotion() control.handleKeyboard() # compute MVP ProjectionMatrix = control.getProjectionMatrix() ViewMatrix = control.getViewMatrix() ModelMatrix = control.getModelMatrix() if False: # identity transform for testing ident = N.identity(4,dtype=N.float32) ProjectionMatrix = ident ViewMatrix = ident ModelMatrix = ident # draw into opengl context glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # use our shader glUseProgram(programID) # send our transform to the shader glUniformMatrix4fv(ProjectionMatrixID, 1, GL_TRUE, ProjectionMatrix) glUniformMatrix4fv(ModelMatrixID, 1, GL_TRUE, ModelMatrix) glUniformMatrix4fv(ViewMatrixID, 1, GL_TRUE, ViewMatrix) # GL_TRUE: transpose the matrix for opengl column major order ld = N.dot(rotationYMatrix(0), lightDirection) glUniform4fv(LightID, 1, ld) # utility variable glUniform1i(whichSpaceID, whichSpace) # bind our texture to unit 0 glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, Texture) # set our sampler glUniform1i(TextureID, 0) # only one attribute buffer: glBindBuffer(GL_ARRAY_BUFFER, vertNormUVBuffer) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertNormUVIndexBuffer) # three different attribute pointers: bytesPerFloat = 4 bytesPerShort = 2 # points: if PositionID >= 0: glEnableVertexAttribArray(PositionID) glVertexAttribPointer( PositionID, # attrib 4, # size GL_FLOAT, # type GL_FALSE, # normalized? 10*bytesPerFloat, # stride c_void_p(0) # array buffer offset ) # normals: if NormalID >= 0: glEnableVertexAttribArray(NormalID) glVertexAttribPointer( NormalID, 4, GL_FLOAT, GL_FALSE, 10*bytesPerFloat, c_void_p(4*bytesPerFloat)) # uvs: if uvID >= 0: glEnableVertexAttribArray(uvID) glVertexAttribPointer( uvID, 2, GL_FLOAT, GL_FALSE, 10*bytesPerFloat, c_void_p(8*bytesPerFloat)) # draw the triangles glDrawElementsInstanced(GL_TRIANGLES, numberOfVertices*bytesPerShort, GL_UNSIGNED_SHORT, c_void_p(0), numberOfInstances) if PositionID >= 0: glDisableVertexAttribArray(PositionID) if NormalID >= 0: glDisableVertexAttribArray(NormalID) if uvID >= 0: glDisableVertexAttribArray(uvID) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) # swap buffers pygame.display.flip() glDeleteProgram(programID)
def main(): #--------------------------------------------------------------------------------------- # Instrucciones para levantar ventana grafica pygame.init() cw = 800 ch = 600 display = (cw, ch) pygame.display.set_mode(display, DOUBLEBUF | OPENGL | OPENGLBLIT) #--------------------------------------------------------------------------------------- # Cargar archivos .obj. fondoList = obj().objAnimation("./Animaciones/fondo/", "fondo_", 0) fondo = fondoList[0] stand = 39 death = 5 deathSlow = 7 attack = 7 run = 5 crouch = 18 wave = 10 # .obj knight # stand knight_Stand = obj().objAnimation("./Animaciones/knight_animado/", "knight_stand_", stand) knight = knight_Stand[0] weaponK_Stand = obj().objAnimation("./Animaciones/weapon_knight_animada/", "weapon_k_stand_", stand) weapon_k = weaponK_Stand[0] # attack knight_Attack = obj().objAnimation("./Animaciones/knight_animado/", "knight_attack_", attack) weaponK_Attack = obj().objAnimation("./Animaciones/weapon_knight_animada/", "weapon_k_attack_", attack) # death knight_Death0 = obj().objAnimation("./Animaciones/knight_animado/", "knight_death_fallback_", death) weaponK_Death0 = obj().objAnimation("./Animaciones/weapon_knight_animada/", "weapon_k_death_fallback_", death) knight_Death1 = obj().objAnimation("./Animaciones/knight_animado/", "knight_death_fallforward_", death) weaponK_Death1 = obj().objAnimation("./Animaciones/weapon_knight_animada/", "weapon_k_death_fallforward_", death) knight_Death2 = obj().objAnimation("./Animaciones/knight_animado/", "knight_death_fallbackslow_", deathSlow) weaponK_Death2 = obj().objAnimation("./Animaciones/weapon_knight_animada/", "weapon_k_death_fallbackslow_", deathSlow) # run knight_Run = obj().objAnimation("./Animaciones/knight_animado/", "knight_run_", run) weaponK_Run = obj().objAnimation("./Animaciones/weapon_knight_animada/", "weapon_k_run_", run) #--------------------------------------------------------------------------------------- # .obj hueteotl # stand hueteotl_Stand = obj().objAnimation("./Animaciones/hueteotl_animado/", "hueteotl_stand_", stand) hueteotl = hueteotl_Stand[0] weaponH_Stand = obj().objAnimation( "./Animaciones/weapon_hueteotl_animada/", "weapon_stand_", stand) weapon_h = weaponH_Stand[0] # attack hueteotl_Attack = obj().objAnimation("./Animaciones/hueteotl_animado/", "hueteotl_attack_", attack) weaponH_Attack = obj().objAnimation( "./Animaciones/weapon_hueteotl_animada/", "weapon_attack_", attack) # death hueteotl_Death0 = obj().objAnimation("./Animaciones/hueteotl_animado/", "hueteotl_death_fallback_", death) weaponH_Death0 = obj().objAnimation( "./Animaciones/weapon_hueteotl_animada/", "weapon_death_fallback_", death) hueteotl_Death1 = obj().objAnimation("./Animaciones/hueteotl_animado/", "hueteotl_death_fallforward_", death) weaponH_Death1 = obj().objAnimation( "./Animaciones/weapon_hueteotl_animada/", "weapon_death_fallforward_", death) hueteotl_Death2 = obj().objAnimation("./Animaciones/hueteotl_animado/", "hueteotl_death_fallbackslow_", deathSlow) weaponH_Death2 = obj().objAnimation( "./Animaciones/weapon_hueteotl_animada/", "weapon_death_fallbackslow_", deathSlow) # run hueteotl_Run = obj().objAnimation("./Animaciones/hueteotl_animado/", "hueteotl_run_", run) weaponH_Run = obj().objAnimation("./Animaciones/weapon_hueteotl_animada/", "weapon_run_", run) #--------------------------------------------------------------------------------------- # Activo las texturas ( 8 disponibles ). glEnable(GL_TEXTURE_2D) glActiveTexture(GL_TEXTURE0) # Funcion que levanta la textura a memoria de video fondoIma = texture.loadTexture("./Animaciones/fondo/fondo2.jpg") tex = texture.loadTexture("./Animaciones/knight_animado/knight_good.png") tex2 = texture.loadTexture("./Animaciones/knight_animado/knight.png") tex3 = texture.loadTexture( "./Animaciones/weapon_knight_animada/weapon_k.png") tex5 = texture.loadTexture("./Animaciones/hueteotl_animado/hueteotl.png") tex6 = texture.loadTexture( "./Animaciones/weapon_hueteotl_animada/weapon.png") #--------------------------------------------------------------------------------------- #glShadeModel(GL_SMOOTH) # El pipeline estatico use Gouraud Shading (sombreado suave). # Seteao los parametros del material del objeto a dibujar. glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, [1, 1, 1, 1]) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, [0.2, 0.2, 0.2, 1]) glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, [1, 1, 1, 1]) glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 128) # Activo las luces ( 0 a 7 ) glEnable(GL_LIGHT0) glLight(GL_LIGHT0, GL_DIFFUSE, [1, 1, 1, 1]) glLight(GL_LIGHT0, GL_AMBIENT, [1, 1, 1, 1]) glLight(GL_LIGHT0, GL_POSITION, [0, 10, 20, 1 ]) # [0,0,0,1] es luz puntual, [0,0,0,0] es luz direccional glLight(GL_LIGHT0, GL_SPECULAR, [1, 0, 0, 1]) #--------------------------------------------------------------------------------------- glMatrixMode( GL_PROJECTION) # Activo el stack de matrices para la proyeccion. glLoadIdentity() # Cargo una identidad para asegurarme que comience vacio. glViewport( 0, 0, cw, ch ) # Crea la matriz de escala, transforma de unidades arbitrarias a pixels. glFrustum(-1, 1, -1, 1, 1, 1000) # Crea la matriz de Proyeccion. volumen de vista. glEnable( GL_DEPTH_TEST ) # Comparaciones de profundidad y actualizar el bufer de profundidad. #--------------------------------------------------------------------------------------- # Variables ang = 0.0 vel = 0.0 mode = GL_FILL zBuffer = True bfc = False bfcCW = True light = False # Variables de animaciones # Objetos de sonido y eventos sonido = sound() eventos = events_obj() eventos.setTimeEvents() # Variables logica del juego stand = True attack = False death = False eludir = False rendirse = False stand_h = True attack_h = False death_h = False eludir_h = False rendirse_h = False auxSound = False countKnight = 0 countHueteotl = 0 count_h = 0 count_k = 0 typeofDeath = 0 pos_h = 25 ang_h = 210 pos_k = -25 ang_k = 0 #--------------------------------------------------------------------------------------- while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() # Evento incial stand knight if event.type == eventos.knight: if stand: knight = knight_Stand[countKnight] weapon_k = weaponK_Stand[countKnight] if countKnight >= (len(knight_Stand) - 1): countKnight = 0 else: countKnight += 1 # Evento incial stand hueteotl if event.type == eventos.hueteotl: if stand_h: hueteotl = hueteotl_Stand[countHueteotl] weapon_h = weaponH_Stand[countHueteotl] if countHueteotl >= (len(hueteotl_Stand) - 1): countHueteotl = 0 else: countHueteotl += 1 # Evento ataque de knight if attack and death == False: knight = knight_Attack[countKnight] weapon_k = weaponK_Attack[countKnight] if countKnight >= (len(knight_Attack) - 1): stand = True attack = False if eludir_h == False and rendirse_h == False: death_h = True sonido.startAtaqueKnight() else: sonido.startAtaqueKnight() stand_h = False typeofDeath = random.randint(0, 2) countKnight = 0 countHueteotl = 0 else: countKnight += 1 # Evento ataque de hueteotl if attack_h and death_h == False: hueteotl = hueteotl_Attack[countHueteotl] weapon_h = weaponH_Attack[countHueteotl] if countHueteotl >= (len(hueteotl_Attack) - 1): stand_h = True attack_h = False if eludir == False and rendirse == False: death = True sonido.startAtaqueHueteolt() else: stand = True sonido.startAtaqueHueteolt() stand = False typeofDeath = random.randint(0, 2) countHueteotl = 0 countKnight = 0 else: countHueteotl += 1 # Evento muerte de hueteotl, random de sus 3 muertes if death_h and rendirse_h == False: if attack_h == False and stand_h == False: if typeofDeath == 0: hueteotl = hueteotl_Death0[countHueteotl] weapon_h = weaponH_Death0[countHueteotl] if countHueteotl >= (len(hueteotl_Death0) - 1): countHueteotl = len(hueteotl_Death0) - 1 else: countHueteotl += 1 if typeofDeath == 1: hueteotl = hueteotl_Death1[countHueteotl] weapon_h = weaponH_Death1[countHueteotl] if countHueteotl >= (len(hueteotl_Death1) - 1): countHueteotl = len(hueteotl_Death1) - 1 else: countHueteotl += 1 if typeofDeath == 2: hueteotl = hueteotl_Death2[countHueteotl] weapon_h = weaponH_Death2[countHueteotl] if countHueteotl >= (len(hueteotl_Death2) - 1): countHueteotl = len(hueteotl_Death2) - 1 else: countHueteotl += 1 # Evento muerte de knight, random de sus 3 muertes if death and rendirse == False: if attack == False and stand == False: if typeofDeath == 0: knight = knight_Death0[countKnight] weapon_k = weaponK_Death0[countKnight] if countKnight >= (len(knight_Death0) - 1): countKnight = len(knight_Death0) - 1 else: countKnight += 1 if typeofDeath == 1: knight = knight_Death1[countKnight] weapon_k = weaponK_Death1[countKnight] if countKnight >= (len(knight_Death1) - 1): countKnight = len(knight_Death1) - 1 else: countKnight += 1 if typeofDeath == 2: knight = knight_Death2[countKnight] weapon_k = weaponK_Death2[countKnight] if countKnight >= (len(knight_Death2) - 1): countKnight = len(knight_Death2) - 1 else: countKnight += 1 # Evento rendirse de hueteotl if stand_h == False and attack_h == False and death_h == False and eludir_h == False: rendirse_h = True if auxSound == False: sonido.startCorrer() auxSound = True ang_h = -20 hueteotl = hueteotl_Run[countHueteotl] weapon_h = weaponH_Run[countHueteotl] if countHueteotl >= (len(hueteotl_Run) - 1): count_h += 1 countHueteotl = 0 if count_h >= 8: stand_h = True count_h = 0 else: countHueteotl += 1 pos_h += 2 # Evento rendirse de knight if stand == False and attack == False and death == False and eludir == False: rendirse = True if auxSound == False: sonido.startCorrer() auxSound = True ang_k = 230 knight = knight_Run[countKnight] weapon_k = knight_Run[countKnight] if countKnight >= (len(knight_Run) - 1): count_k += 1 countKnight = 0 if count_k >= 8: stand = True count_k = 0 else: if countKnight < 0: sonido.startRendirseKnight() sonido.startCorrer() countKnight += 1 pos_k -= 2 # Evento eludir ataque de hueteotl if stand_h == False and attack_h == False and death_h == False and eludir_h: hueteotl = hueteotl_Run[countHueteotl] weapon_h = weaponH_Run[countHueteotl] if countHueteotl >= (len(hueteotl_Run) - 1): count_h += 1 countHueteotl = 0 if count_h >= 2: stand_h = True eludir_h = False count_h = 0 else: countHueteotl += 1 if count_h == 0: pos_h += 2 else: pos_h = 25 # Evento eludir ataque de knight if stand == False and attack == False and death == False and eludir: knight = knight_Run[countKnight] weapon_k = weaponK_Run[countKnight] if countKnight >= (len(knight_Run) - 1): count_k += 1 countKnight = 0 if count_k >= 2: stand = True eludir = False count_k = 0 else: countKnight += 1 if count_k == 0: pos_k -= 2 else: pos_k = -25 if event.type == pygame.KEYDOWN: # Evento tecla presionada. if event.key == pygame.K_w: # tecla w ataca knight if death == False and attack_h == False and rendirse == False: stand = False attack = True countKnight = 0 if event.key == pygame.K_o: # tecla o ataca hueteolt if death_h == False and attack == False and rendirse_h == False: stand_h = False attack_h = True countHueteotl = 0 if event.key == pygame.K_p: # tecla p rendirse hueteolt auxSound = False if death_h == False and rendirse_h == False: stand_h = False countHueteotl = 0 if event.key == pygame.K_e: # tecla e rendirse knight auxSound = False if death == False and rendirse == False: stand = False countKnight = 0 if event.key == pygame.K_i: # tecla i elude hueteotl if death_h == False and rendirse_h == False: stand_h = False eludir_h = True countHueteotl = 0 if event.key == pygame.K_q: # tecla q elude knight if death == False and rendirse == False: stand = False eludir = True countKnight = 0 if event.key == pygame.K_r: # tecla r, reinicia pelea stand = True attack = False death = False eludir = False rendirse = False stand_h = True attack_h = False death_h = False eludir_h = False rendirse_h = False auxSound = False sonido.stopSound() countKnight = 0 countHueteotl = 0 count_k = 0 count_h = 0 typeofDeath = 0 pos_h = 25 ang_h = 210 ang_k = 0 pos_k = -25 if event.key == pygame.K_ESCAPE: pygame.quit() quit() if event.key == pygame.K_l: # Con la tecla l prendo y apago la iluminacion light = not light if (light): glEnable(GL_LIGHTING) glClearColor(0, 0, 0, 1) else: glDisable(GL_LIGHTING) glClearColor(0.5, 0.5, 0.5, 1) if event.key == pygame.K_m: # Con la tecla m, lo deja en formato malla o no (con o sin fondo). if mode == GL_LINE: mode = GL_FILL else: mode = GL_LINE glPolygonMode(GL_FRONT_AND_BACK, mode) if event.key == pygame.K_z: # Con la tecla z, activa el z-buffer zBuffer = not zBuffer if (zBuffer): glEnable(GL_DEPTH_TEST) else: glDisable(GL_DEPTH_TEST) if event.key == pygame.K_b: # Con la tecla b, activo cullface bfc = not bfc if (bfc): glEnable(GL_CULL_FACE) else: glDisable(GL_CULL_FACE) #--------------------------------------------------------------------------------------- glMatrixMode(GL_MODELVIEW) # Activo el stack de matrices MODELVIEW. glLoadIdentity() # Limpio todas la transformaciones previas. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) # Limpio el buffer de colores donde voy a dibujar. # Habilito arrays. glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_NORMAL_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) #--------------------------------------------------------------------------------------- # fondo draw.drawBack(fondo, fondoIma) # knight draw.drawObject(pos_k, ang_k, knight, weapon_k, tex, tex3) #--------------------------------------------------------------------------------------- # hueteotl draw.drawObject(pos_h, ang_h, hueteotl, weapon_h, tex5, tex6) #--------------------------------------------------------------------------------------- # Luego de dibujar, desactivo todo. glBindTexture(GL_TEXTURE_2D, 0) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_NORMAL_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY) pygame.display.flip( ) # Hago flip de los buffers, para que se refresque la imagen en pantalla glDeleteTextures([text]) pygame.quit() quit()
def main (): # pygame initialization pygame.init() screen = pygame.display.set_mode((640,480), OPENGL|DOUBLEBUF) clock = pygame.time.Clock() # OpenGL initializations glClearColor(0.0,0.0,0.4,0.0) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) # make vertex array VertexArrayID = glGenVertexArrays(1) glBindVertexArray(VertexArrayID) # compile shaders programID = loadProgram( os.path.join("shaders","TransformVertexShader.vertexshader"), os.path.join("shaders","TextureFragmentShader.fragmentshader") ) # get handle for "MVP" uniform MatrixID = glGetUniformLocation(programID, "MVP") control = Control() # projection matrix Projection = control.getProjectionMatrix() # view matrix View = control.getViewMatrix() # model matrix Model = control.getModelMatrix() MVP = N.dot(Projection, N.dot(View, Model)) MVP = N.array(MVP, dtype=N.float32) g_vertex_buffer_data = vec([ -1.0,-1.0,-1.0, -1.0,-1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0, 1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0, 1.0, -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0,-1.0, 1.0, 1.0,-1.0, 1.0, 1.0, 1.0, 1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0, 1.0, 1.0,-1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0, 1.0,-1.0, 1.0, 1.0, 1.0, -1.0, 1.0,-1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0,-1.0, 1.0 ]) g_uv_buffer_data = vec([ 0.000059, 1.0-0.000004, 0.000103, 1.0-0.336048, 0.335973, 1.0-0.335903, 1.000023, 1.0-0.000013, 0.667979, 1.0-0.335851, 0.999958, 1.0-0.336064, 0.667979, 1.0-0.335851, 0.336024, 1.0-0.671877, 0.667969, 1.0-0.671889, 1.000023, 1.0-0.000013, 0.668104, 1.0-0.000013, 0.667979, 1.0-0.335851, 0.000059, 1.0-0.000004, 0.335973, 1.0-0.335903, 0.336098, 1.0-0.000071, 0.667979, 1.0-0.335851, 0.335973, 1.0-0.335903, 0.336024, 1.0-0.671877, 1.000004, 1.0-0.671847, 0.999958, 1.0-0.336064, 0.667979, 1.0-0.335851, 0.668104, 1.0-0.000013, 0.335973, 1.0-0.335903, 0.667979, 1.0-0.335851, 0.335973, 1.0-0.335903, 0.668104, 1.0-0.000013, 0.336098, 1.0-0.000071, 0.000103, 1.0-0.336048, 0.000004, 1.0-0.671870, 0.336024, 1.0-0.671877, 0.000103, 1.0-0.336048, 0.336024, 1.0-0.671877, 0.335973, 1.0-0.335903, 0.667969, 1.0-0.671889, 1.000004, 1.0-0.671847, 0.667979, 1.0-0.335851 ]) # vertex buffer vertexbuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer) glBufferData(GL_ARRAY_BUFFER, g_vertex_buffer_data, GL_STATIC_DRAW) # color buffer uvbuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, uvbuffer) glBufferData(GL_ARRAY_BUFFER, g_uv_buffer_data, GL_STATIC_DRAW) # get IDs from program positionID = glGetAttribLocation(programID, "vertexPosition_modelspace") uvID = glGetAttribLocation(programID, "vertexUV") # texture Texture = loadTexture(os.path.join("images","uvtemplate.tga")) # get a handle TextureID = glGetUniformLocation(programID, "myTextureSampler") running = True while running: clock.tick(30) for event in pygame.event.get(): if event.type == QUIT: running = False if event.type == KEYUP and event.key == K_ESCAPE: running = False if event.type == pygame.MOUSEBUTTONDOWN: control.handleMouseButton(event.button) control.handleMouseMotion() control.handleKeyboard() # compute MVP Projection = control.getProjectionMatrix() View = control.getViewMatrix() Model = control.getModelMatrix() MVP = N.dot(Projection, N.dot(View, Model)) MVP = N.array(MVP, dtype=N.float32) # draw into opengl context glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # use our shader glUseProgram(programID) # send our transform to the shader glUniformMatrix4fv(MatrixID, 1, GL_TRUE, MVP) # GL_TRUE: transpose the matrix for opengl column major order # bind our texture to texture unit textureUnit = 4 glActiveTexture(GL_TEXTURE0 + textureUnit) # use our texture data glBindTexture(GL_TEXTURE_2D, Texture) # set our sampler to use texture unit glUniform1i(TextureID, textureUnit) # 1st attribute buffer: vertices glEnableVertexAttribArray(positionID) glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer) bytesPerFloat = 4 glVertexAttribPointer( positionID, # attrib 0, no reason 3, # size GL_FLOAT, # type GL_FALSE, # normalized? 3*bytesPerFloat, # stride, can be 0 if nothing else in buffer c_void_p(0) # array buffer offset ) # 2nd attribute buffer: uvs glEnableVertexAttribArray(uvID) glBindBuffer(GL_ARRAY_BUFFER, uvbuffer) glVertexAttribPointer( uvID, 2, GL_FLOAT, GL_FALSE, 2*bytesPerFloat, c_void_p(0)) # draw the triangle glDrawArrays(GL_TRIANGLES, 0, 12*3) glDisableVertexAttribArray(positionID) glDisableVertexAttribArray(uvID) # swap buffers pygame.display.flip() glDeleteProgram(programID)
def main (): # pygame initialization pygame.init() screen = pygame.display.set_mode((640,480), OPENGL|DOUBLEBUF) clock = pygame.time.Clock() # OpenGL initializations glClearColor(0.0,0.0,0.4,0.0) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) # cull triangles facing away from camera #glEnable(GL_CULL_FACE) # make vertex array VertexArrayID = glGenVertexArrays(1) glBindVertexArray(VertexArrayID) # compile shaders programID = loadProgram( os.path.join("shaders","shader05.vert"), os.path.join("shaders","shader05.frag") ) print "programID:", programID # get handle for "MVP" uniform ViewMatrixID = glGetUniformLocation(programID, "V") ModelMatrixID = glGetUniformLocation(programID, "M") ProjectionMatrixID = glGetUniformLocation(programID, "P") print "P,V,M:",ProjectionMatrixID,ViewMatrixID,ModelMatrixID # texture Texture01 = loadTexture(os.path.join("images","texture_earth_clouds.jpg")) Texture02 = loadTexture(os.path.join("images","grid.png")) # get a handle TextureID = glGetUniformLocation(programID, "myTextureSampler") print "TextureID:", TextureID # vertex, normal, and texture uv data: vertNormUVData, vertNormUVIndices = sphere(1,32,64) # 4 point coords, 4 norm coords, 2 uvs: numberOfVertices = len(vertNormUVIndices) print "N Triangles:", numberOfVertices/3 # vertex buffer for points, norms, uvs vertNormUVBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vertNormUVBuffer) glBufferData(GL_ARRAY_BUFFER, vertNormUVData, GL_STATIC_DRAW) # vertex buffer for indices vertNormUVIndexBuffer = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertNormUVIndexBuffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, vertNormUVIndices, GL_STATIC_DRAW) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) # get handle for light position glUseProgram(programID) LightID = glGetUniformLocation(programID, "lightDirection") print "LightID:", LightID # get attribute locations PositionID = glGetAttribLocation(programID, "positionBuffer") NormalID = glGetAttribLocation(programID, "normalBuffer") uvID = glGetAttribLocation(programID, "uvBuffer") print "pos, norm, uv:", PositionID, NormalID, uvID # control object eye = vec((1,2,3)) focus = vec((0,0,0)) control = Control(pos=eye, fwd=focus-eye) # drawable objects globe = Drawable(control, programID, ProjectionMatrixID, ViewMatrixID, ModelMatrixID, TextureID, Texture01, vertNormUVBuffer, vertNormUVIndexBuffer, PositionID, NormalID, uvID, LightID, numberOfVertices) ball = Drawable(control, programID, ProjectionMatrixID, ViewMatrixID, ModelMatrixID, TextureID, Texture02, # different texture, all else the same here vertNormUVBuffer, vertNormUVIndexBuffer, PositionID, NormalID, uvID, LightID, numberOfVertices) lightDirection = normalize(vec((5,5,1,0))) time = 0.0 running = True while running: clock.tick(30) time += 0.0333 for event in pygame.event.get(): if event.type == QUIT: running = False if event.type == KEYUP and event.key == K_ESCAPE: running = False if event.type == pygame.MOUSEBUTTONDOWN: control.handleMouseButton(event.button) control.handleMouseMotion() control.handleKeyboard() # draw into opengl context glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # compute MVP ProjectionMatrix = control.getProjectionMatrix() ViewMatrix = control.getViewMatrix() ModelMatrix = control.getModelMatrix() # draw my objects globe.Draw(ModelMatrix, ViewMatrix, ProjectionMatrix, time, lightDirection) ball.Draw(translationMatrix(1,1,-1), # static model matrix ViewMatrix, ProjectionMatrix, time, lightDirection) # swap buffers pygame.display.flip() glDeleteProgram(programID)
def initTextures(self): self.texture = loadTexture(self.texImg, self.program) if self.texImg else None self.specTex = loadTexture(self.specTexImg, self.program) if self.specTexImg else None self.normalTex = loadTexture(self.normalMap, self.program) if self.normalMap else None