Advertisement
noTformaT

Python and OpenGL :^)

Jan 17th, 2012
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.50 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. #
  4. # This code was created by Richard Campbell '99 (ported to Python/PyOpenGL by John Ferguson 2000)
  5. #
  6. # The port was based on the PyOpenGL tutorial module: dots.py  
  7. #
  8. # If you've found this code useful, please let me know (email John Ferguson at hakuin@voicenet.com).
  9. #
  10. # See original source and C based tutorial at http://nehe.gamedev.net
  11. #
  12. # Note:
  13. # -----
  14. # This code is not a good example of Python and using OO techniques.  It is a simple and direct
  15. # exposition of how to use the Open GL API in Python via the PyOpenGL package.  It also uses GLUT,
  16. # which in my opinion is a high quality library in that it makes my work simpler.  Due to using
  17. # these APIs, this code is more like a C program using function based programming (which Python
  18. # is in fact based upon, note the use of closures and lambda) than a "good" OO program.
  19. #
  20. # To run this code get and install OpenGL, GLUT, PyOpenGL (see http://www.python.org), and PyNumeric.
  21. # Installing PyNumeric means having a C compiler that is configured properly, or so I found.  For
  22. # Win32 this assumes VC++, I poked through the setup.py for Numeric, and chased through disutils code
  23. # and noticed what seemed to be hard coded preferences for VC++ in the case of a Win32 OS.  However,
  24. # I am new to Python and know little about disutils, so I may just be not using it right.
  25. #
  26. # BTW, since this is Python make sure you use tabs or spaces to indent, I had numerous problems since I
  27. # was using editors that were not sensitive to Python.
  28. #
  29. from OpenGL.GL import *
  30. from OpenGL.GLUT import *
  31. from OpenGL.GLU import *
  32.  
  33. # Some api in the chain is translating the keystrokes to this octal string
  34. # so instead of saying: ESCAPE = 27, we use the following.
  35. ESCAPE = '\033'
  36.  
  37. # Number of the glut window.
  38. window = 0
  39.  
  40. # A general OpenGL initialization function.  Sets all of the initial parameters.
  41. def InitGL(Width, Height):              # We call this right after our OpenGL window is created.
  42.     glClearColor(0.0, 0.0, 0.0, 0.0)    # This Will Clear The Background Color To Black
  43.     glClearDepth(1.0)                   # Enables Clearing Of The Depth Buffer
  44.     glDepthFunc(GL_LESS)                # The Type Of Depth Test To Do
  45.     glEnable(GL_DEPTH_TEST)             # Enables Depth Testing
  46.     glShadeModel(GL_SMOOTH)             # Enables Smooth Color Shading
  47.    
  48.     glMatrixMode(GL_PROJECTION)
  49.     glLoadIdentity()                    # Reset The Projection Matrix
  50.                                         # Calculate The Aspect Ratio Of The Window
  51.     gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
  52.  
  53.     glMatrixMode(GL_MODELVIEW)
  54.  
  55. # The function called when our window is resized (which shouldn't happen if you enable fullscreen, below)
  56. def ReSizeGLScene(Width, Height):
  57.     if Height == 0:                     # Prevent A Divide By Zero If The Window Is Too Small
  58.         Height = 1
  59.  
  60.     glViewport(0, 0, Width, Height)     # Reset The Current Viewport And Perspective Transformation
  61.     glMatrixMode(GL_PROJECTION)
  62.     glLoadIdentity()
  63.     gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
  64.     glMatrixMode(GL_MODELVIEW)
  65.  
  66. # The main drawing function.
  67. def DrawGLScene():
  68.     # Clear The Screen And The Depth Buffer
  69.     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
  70.     glLoadIdentity()                    # Reset The View
  71.  
  72.     # Move Left 1.5 units and into the screen 6.0 units.
  73.     glTranslatef(-1.5, 0.0, -6.0)
  74.  
  75.     # Since we have smooth color mode on, this will be great for the Phish Heads :-).
  76.     # Draw a triangle
  77.     glBegin(GL_POLYGON)                 # Start drawing a polygon
  78.     glColor3f(1.0, 0.0, 0.0)            # Red
  79.     glVertex3f(0.0, 1.0, 0.0)           # Top
  80.     glColor3f(0.0, 1.0, 0.0)            # Green
  81.     glVertex3f(1.0, -1.0, 0.0)          # Bottom Right
  82.     glColor3f(0.0, 0.0, 1.0)            # Blue
  83.     glVertex3f(-1.0, -1.0, 0.0)         # Bottom Left
  84.     glEnd()                             # We are done with the polygon
  85.  
  86.  
  87.     # Move Right 3.0 units.
  88.     glTranslatef(3.0, 0.0, 0.0)
  89.  
  90.     # Draw a square (quadrilateral)
  91.     glColor3f(0.3, 0.5, 1.0)            # Bluish shade
  92.     glBegin(GL_QUADS)                   # Start drawing a 4 sided polygon
  93.     glVertex3f(-1.0, 1.0, 0.0)          # Top Left
  94.     glVertex3f(1.0, 1.0, 0.0)           # Top Right
  95.     glVertex3f(1.0, -1.0, 0.0)          # Bottom Right
  96.     glVertex3f(-1.0, -1.0, 0.0)         # Bottom Left
  97.     glEnd()                             # We are done with the polygon
  98.  
  99.     #  since this is double buffered, swap the buffers to display what just got drawn.
  100.     glutSwapBuffers()
  101.  
  102. # The function called whenever a key is pressed. Note the use of Python tuples to pass in: (key, x, y)  
  103. def keyPressed(*args):
  104.     # If escape is pressed, kill everything.
  105.     if args[0] == ESCAPE:
  106.         glutDestroyWindow(window)
  107.         sys.exit()
  108.  
  109. def main():
  110.     global window
  111.     # For now we just pass glutInit one empty argument. I wasn't sure what should or could be passed in (tuple, list, ...)
  112.     # Once I find out the right stuff based on reading the PyOpenGL source, I'll address this.
  113.     glutInit("")
  114.  
  115.     # Select type of Display mode:  
  116.     #  Double buffer
  117.     #  RGBA color
  118.     # Alpha components supported
  119.     # Depth buffer
  120.     glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH)
  121.    
  122.     # get a 640 x 480 window
  123.     glutInitWindowSize(640, 480)
  124.    
  125.     # the window starts at the upper left corner of the screen
  126.     glutInitWindowPosition(0, 0)
  127.    
  128.     # Okay, like the C version we retain the window id to use when closing, but for those of you new
  129.     # to Python (like myself), remember this assignment would make the variable local and not global
  130.     # if it weren't for the global declaration at the start of main.
  131.     window = glutCreateWindow("Jeff Molofee's GL Code Tutorial ... NeHe '99")
  132.  
  133.     # Register the drawing function with glut, BUT in Python land, at least using PyOpenGL, we need to
  134.     # set the function pointer and invoke a function to actually register the callback, otherwise it
  135.     # would be very much like the C version of the code.   
  136.     glutSetDisplayFuncCallback(DrawGLScene)
  137.     glutDisplayFunc()
  138.    
  139.     # Uncomment this line to get full screen.
  140.     #glutFullScreen()
  141.  
  142.     # When we are doing nothing, redraw the scene.
  143.     glutSetIdleFuncCallback(DrawGLScene)
  144.     glutIdleFunc()
  145.    
  146.     # Register the function called when our window is resized.
  147.     glutSetReshapeFuncCallback(ReSizeGLScene)
  148.     glutReshapeFunc()
  149.    
  150.     # Register the function called when the keyboard is pressed.  
  151.     glutSetKeyboardFuncCallback(keyPressed)
  152.     glutKeyboardFunc()
  153.  
  154.     # Initialize our window.
  155.     InitGL(640, 480)
  156.  
  157.     # Start Event Processing Engine
  158.     glutMainLoop()
  159.  
  160. # Print message to console, and kick off the main to get it rolling.
  161. print "Hit ESC key to quit."
  162. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement