This document discusses the NeHe4 tutorial by Jeff Molofee. It adds simple glRotate-based rotation to the polygons defined in NeHe3. It also demonstrates the OpenGLContext OnIdle handler.
See NeHe3 for discussion of the Context
setup procedure here...
from OpenGLContext import testingcontext
BaseContext, MainFunction = testingcontext.getInteractive()
from OpenGL.GL import *
We import the time module as well to provide crude animation
support, then go back to the previously-seen code.
import time
class TestContext( BaseContext ):
# set initial camera position, tutorial does the re-positioning
initialPosition = (0,0,0)
def Render( self, mode = 0):
"""Render the geometry for the scene."""
BaseContext.Render( self, mode )
glDisable( GL_CULL_FACE )
glDisable( GL_LIGHTING)
glTranslatef(-1.5,0.0,-6.0);
Now we do the rotation. We use time.time() with some mucking
about to get a nice angular rotation which cycles once every 3 seconds,
then use that to rotate about the y axis (0,1,0).
glRotated( time.time()%(3.0)/3 * 360, 0,1,0)
The rest of the Render function is taken from the original NeHe
tutorial.
glBegin(GL_TRIANGLES)
glColor3f(1,0,0)
glVertex3f( 0.0, 1.0, 0.0)
glColor3f(0,1,0)
glVertex3f(-1.0, -1.0, 0.0)
glColor3f(0,0,1)
glVertex3f( 1.0, -1.0, 0.0)
glEnd()
glLoadIdentity resets the model-view matrix to the identity matrix, eliminating the effects of the previous rotation.
Normally you would use glPushMatrix/glPopMatrix to prevent messing up higher-level abstractions, but that's not an issue for these stand-alone tutorials.
glLoadIdentity()
glTranslatef(1.5,0.0,-6.0);
Same basic approach as above, save that we use 1 rps instead of 3.
glRotated( time.time()%(1.0)/1 * -360, 1,0,0)
glColor3f(0.5,0.5,1.0)
glBegin(GL_QUADS)
glVertex3f(-1.0,-1.0, 0.0)
glVertex3f( 1.0,-1.0, 0.0)
glVertex3f( 1.0, 1.0, 0.0)
glVertex3f(-1.0, 1.0, 0.0)
glEnd()
Another of OpenGLContext's Context customisation points is the
OnIdle method. If present, it is called when the Context becomes
idle (no pending redraw events). In this case, we just tell the
context to redraw itself whenever the OnIdle handler is called.
This is not how you would normally want an
animation to run, as it will suck up 100% of your CPU's power just for
the animation. For the stand-alone test, however, it doesn't
really bother us to do so.
def OnIdle( self, ):
"""Request refresh of the context whenever idle"""
self.triggerRedraw(1)
return 1
And finally, we make the script run MainFunction with an instance of
our TestContext if the module is run as a script.
if __name__ == "__main__":
## We only want to run the main function if we
## are actually being executed as a script
MainFunction ( TestContext)
You can find the complete code for this sample in
OpenGLContext/tests/nehe4.py