Advertisement
Guest User

Texturing in Python,Numpy,Pygame,PyOpenGL

a guest
Mar 6th, 2012
707
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.15 KB | None | 0 0
  1. #python2.6
  2. #pygame
  3. #numpy
  4. #pyopengl
  5.  
  6. import numpy
  7. from OpenGL.GL import *
  8. from OpenGL.arrays import vbo
  9. from OpenGLContext.arrays import *
  10. from OpenGL.GL import shaders
  11. from OpenGL.GLU import *
  12. import pygame
  13. from pygame.locals import *
  14.  
  15. from gameobjects.matrix44 import *
  16. from gameobjects.vector3 import *
  17. #DOWNLOADED AS PART OF THE DEMO AT http://www.willmcgugan.com/blog/tech/2007/6/4/opengl-sample-code-for-pygame/
  18. #THIS FILE ALSO USES THAT CAMERA CODE
  19.  
  20.  
  21. def resize(width, height):
  22.    
  23.     glViewport(0, 0, width, height) # sets the viewport
  24.     glMatrixMode(GL_PROJECTION) # the matrix that transforms 3d into a 2d perspective picture
  25.     glLoadIdentity() # resets the matrix to a default state - anythign multiplied by this returns itself, like 1
  26.    
  27.     gluPerspective(60.0, float(width)/height, .1, 1000.)
  28.     '''
  29.     (   GLdouble    fovy,   -- field of view
  30.     GLdouble    aspect,     -- aspect ratio, basically unnecessary with width/height set?
  31.     GLdouble    zNear,      -- closest a thing can be seen from the camera
  32.     GLdouble    zFar);      -- furthest away a thing can be seen from the camera
  33.    '''
  34.    
  35.     glMatrixMode(GL_MODELVIEW) # the matrix that sort of draws it into the world space, in front of the camera
  36.     glLoadIdentity() # reset again
  37.  
  38.  
  39. def init():
  40.     global shader, avbo, UNIFORM_LOCATIONS, position, texcoords, texture
  41.     glEnable(GL_DEPTH_TEST) #let's be rash and have a z buffer
  42.    
  43.     glShadeModel(GL_FLAT) # no shading!
  44.     glClearColor(0.6, 0.0, 1.0, 0.0) #purple
  45.  
  46.     glEnable(GL_COLOR_MATERIAL) #coloured material
  47.     glEnable(GL_TEXTURE_2D)
  48.     glEnable(GL_BLEND)
  49.     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
  50.    
  51.     glEnable(GL_LIGHTING)#lightingplz
  52.     glEnable(GL_LIGHT0)        #enable the light
  53.     glLight(GL_LIGHT0, GL_POSITION,  (0, 1, 1, 0))    #set it to be in a place.
  54.  
  55.    
  56.     #Generate PyOpenGL Texture
  57.     texture = glGenTextures(1)
  58.     #Load the image file
  59.     Surface = pygame.image.load('test.png')
  60.     #Convert it to load any alpha channel
  61.     Surface.convert_alpha()
  62.     #Convert to PyOpenGL Data
  63.     Data = pygame.image.tostring(Surface, "RGBA", 1)
  64.     #Select our Texture Object
  65.     glActiveTexture(GL_TEXTURE0)
  66.     glBindTexture(GL_TEXTURE_2D, texture)
  67.     #Load the Data into the Texture
  68.     glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, Surface.get_width(), Surface.get_height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, Data )
  69.     #Define some Parameters for this Texture
  70.     glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
  71.     glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
  72.  
  73.    
  74.    
  75.    
  76.     VERTEX_SHADER = shaders.compileShader('''
  77.        uniform float xpos;
  78.        uniform float ypos;
  79.        
  80.        attribute vec3 position;
  81.        attribute vec2 texcoords;
  82.        attribute int texid;
  83.        
  84.        varying vec2 texcoords_v;
  85.        
  86.        void main() {
  87.            gl_Position = gl_ModelViewProjectionMatrix * (vec4(position,1.0) + vec4(
  88.                xpos, ypos, 0.0, 0.0
  89.            ));
  90.            
  91.            texcoords_v = texcoords;
  92.            
  93.        }''', GL_VERTEX_SHADER)
  94.  
  95.     FRAGMENT_SHADER = shaders.compileShader('''
  96.        varying vec2 texcoords_v;
  97.        
  98.        uniform sampler2D thetexture;
  99.        //s[2]
  100.        
  101.        void main() {
  102.            
  103.            gl_FragColor = texture2D(thetexture, texcoords_v);
  104.            
  105.        }''', GL_FRAGMENT_SHADER)
  106.  
  107.     shader = shaders.compileProgram(VERTEX_SHADER,FRAGMENT_SHADER) #shaders have to be compiled to be used.
  108.  
  109.     position = glGetAttribLocation(
  110.         shader, 'position'
  111.     )
  112.     texcoords = glGetAttribLocation(
  113.         shader, 'texcoords'
  114.     )
  115.     avbo =  vbo.VBO(
  116.         numpy.array( [ #x, y, z ; texx, texy
  117.             [  0, 1, 0,  0.5,1],#top
  118.             [ -1,-1, 0,  0,  0],#botleft
  119.             [  1,-1, 0,  1,  0],#botright
  120.            
  121.             [  2,-1, 0,  0,  0],#botleft
  122.             [  4,-1, 0,  1,  0],#botright
  123.             [  4, 1, 0,  1,  1],#topright
  124.             [  2,-1, 0,  0,  0],#botleft
  125.             [  4, 1, 0,  1,  1],#topright
  126.             [  2, 1, 0,  0,  1],#topleft
  127.         ], 'f')
  128.     )#a triangle and a square
  129.     UNIFORM_LOCATIONS = { #set up some linkages!
  130.         'xpos': glGetUniformLocation( shader, 'xpos' ),
  131.         'ypos': glGetUniformLocation( shader, 'ypos' ),
  132.         'thetexture': glGetUniformLocation( shader, 'thetexture' ),
  133.     }
  134.  
  135. SCREEN_SIZE = (800, 600)
  136. def run():
  137.     global shader, avbo, UNIFORM_LOCATIONS, position, texcoords, texture
  138.    
  139.     pygame.init()
  140.     screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE|OPENGL|DOUBLEBUF)
  141.     pygame.display.set_caption("TRIANGLES", "TRIANGLES")
  142.    
  143.     resize(*SCREEN_SIZE)# also starts gl and sets up the projection things
  144.     init()# load shaders and vbo
  145.    
  146.     clock = pygame.time.Clock()    
  147.    
  148.     # Camera transform matrix
  149.     camera_matrix = Matrix44() #I think this probably just loads a default matrix
  150.     camera_matrix.translate = (5.0, .6, 10.0) #translates to this position
  151.  
  152.     # Initialize speeds and directions
  153.     rotation_direction = Vector3() # 0,0,0
  154.     rotation_speed = radians(90.0)
  155.     movement_direction = Vector3()
  156.     movement_speed = 5.0
  157.    
  158.     xpos = 0.
  159.     ypos = 0.
  160.  
  161.     while True:
  162.        
  163.         for event in pygame.event.get():
  164.             if event.type == QUIT:
  165.                 return
  166.             if event.type == KEYUP and event.key == K_ESCAPE:
  167.                 return                
  168.            
  169.         # Clear the screen, and z-buffer
  170.         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  171.                        
  172.         time_passed = clock.tick()
  173.         time_passed_seconds = time_passed / 1000.
  174.        
  175.         pressed = pygame.key.get_pressed()
  176.        
  177.         # Reset rotation and movement directions
  178.         rotation_direction.set(0.0, 0.0, 0.0)
  179.         movement_direction.set(0.0, 0.0, 0.0)
  180.        
  181.         # Modify direction vectors for key presses
  182.         if pressed[K_LEFT]:
  183.             rotation_direction.y = +1.0
  184.         elif pressed[K_RIGHT]:
  185.             rotation_direction.y = -1.0
  186.         if pressed[K_UP]:
  187.             rotation_direction.x = -1.0
  188.         elif pressed[K_DOWN]:
  189.             rotation_direction.x = +1.0
  190.         if pressed[K_z]:
  191.             rotation_direction.z = -1.0
  192.         elif pressed[K_x]:
  193.             rotation_direction.z = +1.0            
  194.         if pressed[K_q]:
  195.             movement_direction.z = -1.0
  196.         elif pressed[K_a]:
  197.             movement_direction.z = +1.0
  198.        
  199.        
  200.         if pressed[K_j]:
  201.             xpos -= 0.1
  202.         elif pressed[K_l]:
  203.             xpos += 0.1
  204.         if pressed[K_i]:
  205.             ypos += 0.1
  206.         elif pressed[K_k]:
  207.             ypos -= 0.1
  208.        
  209.         # Calculate rotation matrix and multiply by camera matrix    
  210.         rotation = rotation_direction * rotation_speed * time_passed_seconds
  211.         rotation_matrix = Matrix44.xyz_rotation(*rotation)        
  212.         camera_matrix *= rotation_matrix
  213.        
  214.         # Calcluate movment and add it to camera matrix translate
  215.         heading = Vector3(camera_matrix.forward)
  216.         movement = heading * movement_direction.z * movement_speed                    
  217.         camera_matrix.translate += movement * time_passed_seconds
  218.        
  219.         # Upload the inverse camera matrix to OpenGL
  220.         glLoadMatrixd(camera_matrix.get_inverse().to_opengl())
  221.                
  222.         # Light must be transformed as well
  223.         glLight(GL_LIGHT0, GL_POSITION,  (0, 1.5, 1, 0))
  224.        
  225.        
  226.        
  227.         shaders.glUseProgram(shader)#bind the shader
  228.         glUniform1f(UNIFORM_LOCATIONS['xpos'],xpos)
  229.         glUniform1f(UNIFORM_LOCATIONS['ypos'],ypos)
  230.  
  231.         #glActiveTexture(GL_TEXTURE0)
  232.         #glBindTexture(GL_TEXTURE_2D, texture)
  233.         glUniform1i(UNIFORM_LOCATIONS['thetexture'],0)
  234.         #texture RETURNS 1, but IS #0, so lists might be wise.
  235.        
  236.         #print texture
  237.         try:
  238.             avbo.bind()#bind the vertex object
  239.             try:
  240.                
  241.                 glEnableVertexAttribArray( position )
  242.                 glEnableVertexAttribArray( texcoords )
  243.                
  244.                 #4 bytes per number, 5 numbers, so 4*5 bytes between the start of each record.
  245.                 stride = 5*4
  246.                 glVertexAttribPointer(
  247.                     position,
  248.                     3, GL_FLOAT,False, stride, avbo
  249.                 )
  250.                 glVertexAttribPointer(
  251.                     texcoords,
  252.                     2, GL_FLOAT,False, stride, avbo+12
  253.                 )
  254.                 glDrawArrays(GL_TRIANGLES, 0, 9)
  255.  
  256.                
  257.                
  258.             finally:
  259.                 avbo.unbind() #unbind the vertex objct
  260.                 glDisableVertexAttribArray( position )
  261.                 glDisableVertexAttribArray( texcoords )
  262.  
  263.         finally:
  264.             shaders.glUseProgram( 0 )#unbind the shader
  265.        
  266.        
  267.        
  268.        
  269.         pygame.display.set_caption("TRIANGLES AT"+str(clock.get_fps())+" FPS", "TRIANGLES")
  270.        
  271.         # Show the screen by flipping buffers
  272.         pygame.display.flip()
  273.  
  274. run()#do the running
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement