class TestContext( BaseContext ): ''' creates a simple vertex shader ''' def OnInit( self ): try: self.shader = compileProgram( compileShader( VERTEX_SHADER, gl.GL_VERTEX_SHADER ), compileShader( FRAGMENT_SHADER, gl.GL_FRAGMENT_SHADER ) ) except RuntimeError, err: sys.stderr.write( err.args[0] ) sys.exit( 1 ) self.vbo = vbo.VBO( array( VERTEX_DATA, 'f' ) ) self.position = gl.glGetAttribLocation( self.shader, 'position' ) self.tweened = gl.glGetAttribLocation( self.shader, 'tweened' ) self.color = gl.glGetAttribLocation( self.shader, 'color' ) self.tween = gl.glGetUniformLocation( self.shader, 'tween' ) self.time = Timer( duration = 2.0, repeating = 1 ) self.time.addEventHandler( "fraction", self.OnTimerFraction ) self.time.register( self ) self.time.start()
def OnInit(self, ): """Initialisation""" print("""You should see two bitmap images traversing the screen diagonally. If the GL.ARB.window_pos extension is not available then you will exit immediately. """) self.width, self.height, self.data = self.loadImage() global window_pos window_pos = self.extensions.initExtension("GL.ARB.window_pos") if not window_pos: print('GL_ARB_window_pos not supported!') sys.exit(testingcontext.REQUIRED_EXTENSION_MISSING) self.time = Timer(duration=8.0, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start() self.x = 0 self.y = 0 try: window_pos.glWindowPos2dvARB(()) except (error.CopyError, GLerror, ValueError) as err: print('Correct handling of incorrect parameters', err) except Exception as err: traceback.print_exc() print('Incorrect handling of incorrect parameters') try: window_pos.glWindowPos3dvARB(()) except (error.CopyError, GLerror, ValueError) as err: print('Correct handling of incorrect parameters', err) except Exception as err: traceback.print_exc() print('Incorrect handling of incorrect parameters')
def OnInit(self): self.sg = scene self.trans = self.sg.children[0] self.time = Timer(duration=8.0, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start()
def OnInit(self): """Initialize the context with GL active""" if not glInitShadowARB() or not glInitDepthTextureARB(): print 'Missing required extensions!' sys.exit(testingcontext.REQUIRED_EXTENSION_MISSING) '''Configure some parameters to make for nice shadows at the expense of some extra calculations''' glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST) glEnable(GL_POLYGON_SMOOTH) '''We create the geometry for our scene in a method to allow later tutorials to subclass and provide more interesting scenes. ''' self.geometry = self.createGeometry() '''We'll use OpenGLContext's rendering passes to render the geometry each time we need to do so...''' self.geometryPasses = flat.FlatPass(self.geometry, self) '''To make the demo a little more interesting, we're going to animate the first light's position and direction. Here we're setting up a raw Timer object. OpenGLContext scenegraph timers can't be used as we're not using the scenegraph mechanisms. ''' self.time = Timer(duration=8.0, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start() '''Here are the lights we're going to use to cast shadows.''' self.lights = self.createLights() self.addEventHandler("keypress", name="s", function=self.OnToggleTimer)
def OnInit( self ): """Load the image on initial load of the application""" print("""Should see a sine wave fading from green to red""") line = arange(0.0,1.0,.01) line2 = line[::-1] self.coordinate = Coordinate( point = map(None, line,[0]*len(line), [0]*len(line) ), ) self.color = Color( color = map(None,line, [0]*len(line), line2 ), ) self.sg = sceneGraph( children = [ Transform( translation = (-.5,0,0), children = [ Shape( geometry = PointSet( coord = self.coordinate, color = self.color, ), ), ], ), ], ) self.time = Timer( duration = 8.0, repeating = 1 ) self.time.addEventHandler( "fraction", self.OnTimerFraction ) self.time.register (self) self.time.start ()
def OnInit(self): """Load the image on initial load of the application""" print """Should see a rotating star-field""" starfield = random.rand(9110, 3) self.coordinate = Coordinate(point=starfield, ) self.color = Color(color=starfield, ) self.transform = Transform( scale=(200, 200, 200), children=[ Transform( translation=(-.5, -.5, -.5), children=[ Shape(geometry=PointSet( coord=self.coordinate, color=self.color, ), ), ], ), ], ) self.sg = sceneGraph(children=[ self.transform, ], ) self.time = Timer(duration=90.0, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start()
def OnInit(self): """Load the image on initial load of the application""" self.image = self.loadImage() print("""You should see a slowly rotating textured cube The animation is provided by a timer, rather than the crude time-module based animation we use for the other NeHe tutorials.""") print(' <r> reverse the time-sequence') print(' <s> make time pass more slowly') print(' <f> make time pass faster') '''Here we will register key-press handlers for the various operations the user can perform.''' self.addEventHandler("keypress", name="r", function=self.OnReverse) self.addEventHandler("keypress", name="s", function=self.OnSlower) self.addEventHandler("keypress", name="f", function=self.OnFaster) '''We'll create a Timer object. The duration is the total cycle length for the timer, the repeating flag tells the timer to continue running.''' self.time = Timer(duration=8.0, repeating=1) '''The timer generates events for "fractions" as well as for cycles. We use the fraction value to generate a smooth animation.''' self.time.addEventHandler("fraction", self.OnTimerFraction) '''Registering and starting the timer are only necessary because the node is not part of a scenegraph.''' self.time.register(self) self.time.start() '''As with the time.time() mechanism, we need to track our current rotation so that the rendering pass can perform the rotation calculated by the timer callback.''' self.rotation = 0
def OnInit( self ): self.sg = basenodes.sceneGraph( children = [ basenodes.Transform( children = [ basenodes.Shape( geometry = basenodes.Box( size = (2,3,4), ), appearance=basenodes.Appearance( material = basenodes.Material( diffuseColor = (1,0,0), ), ), ), ], ), basenodes.PointLight( location=(5,6,5), ), ], ) self.time = Timer( duration = 32.0, repeating = 1 ) self.time.addEventHandler( "fraction", self.OnTimerFraction ) self.time.register (self) self.time.start () self.rotation = 0
def OnInit( self ): self.sg = scene self.addEventHandler( "keypress", name="a", function = self.OnAdd) self.time = Timer( duration = .1, repeating = 1 ) self.time.addEventHandler( "cycle", self.OnAdd ) self.time.register (self) self.time.start ()
def OnInit(self): vshader = ''' //setup a tween (blending constant) uniform float tween; // the the original position // and the secondary position (tweened) attribute vec3 position; attribute vec3 tweened; attribute vec3 color; varying vec4 baseColor; void main(){ // create a new position for this vertex // by mixing the original position and the // secondary tweened position gl_Position = gl_ModelViewProjectionMatrix * mix( vec4(position, 1.0), vec4(tweened, 1.0), tween ); baseColor = vec4(color, 1.0); } ''' vertex = shaders.compileShader(vshader, GL_VERTEX_SHADER) fshader = ''' varying vec4 baseColor; void main(){ gl_FragColor = baseColor; } ''' fragment = shaders.compileShader(fshader, GL_FRAGMENT_SHADER) self.shader = shaders.compileProgram(vertex, fragment) # create a vbo with vertex position, color, and secondary position self.vbo = vbo.VBO( array([ [0, 1, 0, 1, 3, 0, 0, 1, 0], [-1, -1, 0, -1, -1, 0, 1, 1, 0], [1, -1, 0, 1, -1, 0, 0, 1, 1], [2, -1, 0, 2, -1, 0, 1, 0, 0], [4, -1, 0, 4, -1, 0, 0, 1, 0], [4, 1, 0, 4, 9, 0, 0, 0, 1], [2, -1, 0, 2, -1, 0, 1, 0, 0], [4, 1, 0, 1, 3, 0, 0, 0, 1], [2, 1, 0, 1, -1, 0, 0, 1, 1], ], 'f')) # get the memory locations in our shader # for our variables self.position_location = glGetAttribLocation(self.shader, 'position') self.tweened_location = glGetAttribLocation(self.shader, 'tweened') self.color_location = glGetAttribLocation(self.shader, 'color') self.tween_location = glGetUniformLocation(self.shader, 'tween') # setup an animation timer which updates the # tween fraction (called tween in our shader) self.time = Timer(duration=2.0, repeating=1) self.time.addEventHandler('fraction', self.OnTimerFraction) self.time.register(self) self.time.start()
def OnInit(self): """Do all of our setup functions...""" if not glMultiTexCoord2f: print('Multitexture not supported!') sys.exit(1) self.update_sim = False vBuffer, uvBuffer, nBuffer, tBuffer, bBuffer, cBuffer, iBuffer, triangles = \ loadMesh("TestMesh.obj", True, 0.001) self.indices = iBuffer self.vertices = vBuffer self.tex_coords = uvBuffer self.normals = nBuffer self.tangents = tBuffer self.biTangents = bBuffer self.colors = cBuffer normal_array = rasterizer.raster_vector_attrib(self.normals, self.tex_coords,\ triangles, SIM_SIZE, SIM_SIZE, UP) tangent_array = rasterizer.raster_vector_attrib(self.tangents, self.tex_coords,\ triangles, SIM_SIZE, SIM_SIZE, X_DIR) biTangent_array = rasterizer.raster_vector_attrib(self.biTangents, self.tex_coords,\ triangles, SIM_SIZE, SIM_SIZE, Y_DIR) self.fluid_sim = FluidSim.Fluid_Sim_2D(SIM_SIZE, SIM_SIZE, CELL_SIZE, DENSITY, GRAVITY,\ ATM_PRESSURE) for r in range(SIM_SIZE): for c in range(SIM_SIZE): self.fluid_sim.setNormal(r, c, normal_array[r][c]) self.fluid_sim.setXTangent(r, c, tangent_array[r][c]) self.fluid_sim.setYTangent(r, c, biTangent_array[r][c]) sources = [] for rc in INJECT_POINTS: for dr in range(-INJECT_RADIUS / 2, INJECT_RADIUS / 2 + 1): for dc in range(-INJECT_RADIUS / 2, INJECT_RADIUS / 2 + 1): if dr * dr + dc * dc <= INJECT_RADIUS * INJECT_RADIUS: sources.append((rc[0] + dr, rc[1] + dc)) self.fluid_sim.markSources(sources) self.addEventHandler("keypress", name="r", function=self.OnReverse) self.addEventHandler("keypress", name="s", function=self.OnSlower) self.addEventHandler("keypress", name="f", function=self.OnFaster) self.addEventHandler("keypress", name="w", function=self.incPhi) self.addEventHandler("keypress", name="s", function=self.decPhi) self.addEventHandler("keypress", name="d", function=self.incTheta) self.addEventHandler("keypress", name="a", function=self.decTheta) self.addEventHandler("keypress", name="u", function=self.promptUpdate) print('r -- reverse time\ns -- slow time\nf -- speed time') self.time = Timer(duration=8.0, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start() '''Load both of our textures.''' self.Load() self.frameCount = 0
def OnInit( self ): vertex = shaders.compileShader(""" uniform float tween; attribute vec3 position; attribute vec3 tweened; attribute vec3 color; varying vec4 baseColor; void main() { gl_Position = gl_ModelViewProjectionMatrix * mix( vec4( position,1.0), vec4( tweened,1.0), tween ); baseColor = vec4(color,1.0); }""",GL_VERTEX_SHADER) fragment = shaders.compileShader(""" varying vec4 baseColor; void main() { gl_FragColor = baseColor; }""",GL_FRAGMENT_SHADER) self.shader = shaders.compileProgram(vertex,fragment) self.vbo = vbo.VBO( array( [ #depan [ 1, 3, 1, 0.5, 3, 1.5, 0,1,0 ], [ -1, 3, 1, 0.5, 3, 0.5, 0,1,0 ], [ 1, -3, 1, 0.5, -3, 1.5, 0,1,0 ], [ -1, 3, 1, 0.5, 3, 0.5, 0,1,0 ], [ -1, -3, 1, 0.5, -3, 1.5, 0,1,0 ], [ 1, -3, 1, 0.5, -3, 1.5, 0,1,0 ], #depan [ 1, 3, -2, 0.5, 3, -1.5, 1,1,0 ], [ -1, 3, -2, 0.5, 3, -2.5, 1,1,0 ], [ 1, -3, -2, 0.5, -3, -1.5, 1,1,0 ], [ -1, 3, -2, 0.5, 3, -2.5, 1,1,0 ], [ -1, -3, -2, 0.5, -3, -1.5, 1,1,0 ], [ 1, -3, -2, 0.5, -3, -1.5, 1,1,0 ], ],'f') ) self.position_location = glGetAttribLocation( self.shader, 'position' ) self.tweened_location = glGetAttribLocation( self.shader, 'tweened', ) self.color_location = glGetAttribLocation( self.shader, 'color' ) self.tween_location = glGetUniformLocation( self.shader, 'tween', ) self.time = Timer( duration = 2.0, repeating = 1 ) self.time.addEventHandler( "fraction", self.OnTimerFraction ) self.time.register (self) self.time.start ()
def OnInit(self): """Load the image on initial load of the application""" print """This demo loads a VRML97 scenegraph and modifies the rotation of the transform which contains one of the two boxes. The ROUTE in the scene transmits this rotational change to the transform which contains the other box.""" self.sg = Loader.load(os.path.join("wrls", "box.wrl")) self.trans = self.sg.getDEF("Box01") self.time = Timer(duration=8.0, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start()
def OnInit(self): """Do all of our setup functions...""" if not glMultiTexCoord2f: print('Multitexture not supported!') sys.exit(1) self.addEventHandler("keypress", name="r", function=self.OnReverse) self.addEventHandler("keypress", name="s", function=self.OnSlower) self.addEventHandler("keypress", name="f", function=self.OnFaster) print('r -- reverse time\ns -- slow time\nf -- speed time') self.time = Timer(duration=8.0, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start() '''Load both of our textures.''' self.Load()
def OnInit( self ): """Load the image on initial load of the application""" haveExtension = self.extensions.initExtension( "GL.ARB.point_parameters") if not haveExtension: print('GL_ARB_point_parameters not supported!') sys.exit( testingcontext.REQUIRED_EXTENSION_MISSING ) print("""Should see a sine wave overhead""") print('press x toggle use of the extension') self.addEventHandler( 'keypress', name = 'x', function = self.OnDisableExtension ) line = arange(0.0,1.0,.01) line2 = line[::-1] self.coordinate = Coordinate( point = zip(line,[0]*len(line), [0]*len(line) ), ) self.color = Color( color = zip(line, [0]*len(line), line2 ), ) self.geometry = PointSet( coord = self.coordinate, color = self.color, size = 4.0, minSize = 0.25, maxSize = 4.0, attenuation = (0,0,1), ) self.sg = sceneGraph( children = [ Transform( translation = (-.5,.25,0), scale = (2,2,2), rotation = (1,0,0,1.57), children = [ Shape( geometry = self.geometry, ), ], ), ], ) self.time = Timer( duration = 8.0, repeating = 1 ) self.time.addEventHandler( "fraction", self.OnTimerFraction ) self.time.register (self) self.time.start ()
def OnInit(self): self.is_trans = True self.vertex_shaders = [st.ANIMATED_VERTEX_SHADER] self.fragment_shaders = [st.ANIMATED_FRAGMENT_SHADER] self.texture_name = 'wood.jpg' self.time = Timer(duration=2.0, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start() self.vertexes, self.indices, self.normals, self.uv = self.load_data() self.load_object() self.load_shader() self.load_texture() self.location = np.array([0.0, 0.0, 0.0]) self.EYE = np.array([0.0, 0.0, 10.0]) self.PREF = np.array([0.0, 0.0, -1.0]) self.vv = np.array([0.0, 1.0, 0.0]) self.N = (self.PREF - self.EYE) / np.linalg.norm(self.PREF - self.EYE) self.U = np.cross(self.N, self.vv) / np.linalg.norm(np.cross(self.N, self.vv)) self.EYE_UP = np.cross(self.U, self.N) self.d = 0.1 height = 500 width = 500 self.half_h = height / 2 self.f = 100.0 self.width = width self.height = height slope = np.sqrt((pow(self.d, 2) + pow((width / 2), 2))) self.fov = 2 * np.arctan(self.half_h / slope) left_bottom_near = self.EYE + self.d * self.N - self.half_h * self.U - self.half_h * self.EYE_UP right_top_near = self.EYE + self.d * self.N + self.half_h * self.U + self.half_h * self.EYE_UP self.VIEW = np.array([left_bottom_near[0], right_top_near[0], left_bottom_near[1], right_top_near[1], np.array([self.d]), np.array([self.f])]) self.LOOK_AT = np.array([0, 0, 0]) self.ProjectionMatrix = glm.perspective(self.fov, float(self.width) / float(self.height), self.d, self.f) self.ViewMatrix = glm.lookAt(glm.vec3(self.EYE[0], self.EYE[1], self.EYE[2]), glm.vec3(self.LOOK_AT[0], self.LOOK_AT[1], self.LOOK_AT[2]), glm.vec3(self.vv[0], self.vv[1], self.vv[2]) ) self.MVP = self.ProjectionMatrix * self.ViewMatrix * glm.mat4(1.0)
def OnInit( self ): """Scene set up and initial processing""" self.program = shaders.compileProgram( shaders.compileShader( ''' varying vec3 normal; void main() { normal = gl_NormalMatrix * gl_Normal; gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; } ''', GL_VERTEX_SHADER, ), shaders.compileShader( ''' uniform vec3 light_location; varying vec3 normal; void main() { float intensity; vec4 color; vec3 n = normalize(normal); vec3 l = normalize(light_location).xyz; // quantize to 5 steps (0, .25, .5, .75 and 1) intensity = (floor(dot(l, n) * 4.0) + 1.0)/4.0; color = vec4(intensity*1.0, intensity*0.5, intensity*0.5, intensity*1.0); gl_FragColor = color; } ''', GL_FRAGMENT_SHADER, ), ) self.light_uniform_loc = glGetUniformLocation( self.program, 'light_location' ) self.time = Timer( duration = 2.0, repeating = 1 ) self.time.addEventHandler( "fraction", self.OnTimerFraction ) self.time.register (self) self.time.start ()
def OnInit(self): """Scene set up and initial processing""" t = Transform(children=[ PointLight(location=(1, 4, 10), ), ], ) self.shaders = shaders self.shapes = [ Shape( appearance=self.shaders[0], geometry=Sphere(radius=2.0), ), Shape( appearance=self.shaders[0], geometry=Teapot(size=.75), ), Shape( appearance=self.shaders[0], geometry=Box(size=(3, 3, 3)), ), ] self.sg = sceneGraph(children=[ Transform( DEF='scene', children=[ self.shapes[0], Transform( translation=(-3, 0, 4), children=[self.shapes[1]], ), Transform( translation=(-2, 0, 6), children=[ Shape( appearance=Appearance( material=Material(diffuseColor=(0, 0, 1)), ), geometry=Sphere(radius=.25), ), ], ), ], ), t, Transform( translation=(5, 0, 3), children=[self.shapes[2]], ), PointLight(location=(10, 10, 10)), ], ) self.time = Timer(duration=30.0, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start() print 'press "n" for next shader' self.addEventHandler("keypress", name="n", function=self.OnNext) # MANDELBROT explorer... print 'Explore Orange-book mandelbrot with:\n asdw (center) zx (zoom) and rf (iterations)' self.addEventHandler("keypress", name="a", function=self.OnMand) self.addEventHandler("keypress", name="d", function=self.OnMand) self.addEventHandler("keypress", name="s", function=self.OnMand) self.addEventHandler("keypress", name="w", function=self.OnMand) self.addEventHandler("keypress", name="z", function=self.OnMand) self.addEventHandler("keypress", name="x", function=self.OnMand) self.addEventHandler("keypress", name="r", function=self.OnMand) self.addEventHandler("keypress", name="f", function=self.OnMand) self.addEventHandler("keypress", name="l", function=self.OnLeak)
def OnInit(self): """Load the image on initial load of the application""" print """Each dot is a request (y shows data transferred)""" self.log_queue = Queue.Queue(maxsize=self.dataPoints) self.coordinate = Coordinate(point=[(0, 0, 0)] * self.dataPoints, ) # should *not* be necessary, but is, to prevent a cached # bounding volume from dropping the graph boundingvolume.cacheVolume( self.coordinate, boundingvolume.UnboundedVolume(), ) # just an arbitrary format/style for the text self.fontstyle = FontStyle( family='SANS', format='bitmap', justify='BEGIN', ) # self.color = Color(color=[1.0, 0.0, 0.0], ) self.data_slider = Transform( translation=(0, 0, 0), scale=( 1 / 600., 1, 1, ), children=[ Shape( appearance=Appearance( texture=ImageTexture(url='_particle.png'), material=Material(diffuseColor=[1, 0, 0], )), geometry=PointSet( coord=self.coordinate, minSize=5.0, maxSize=5.0, ), ), ], ) self.axes = Transform(children=[ Transform( translation=(.25, coord, 0), children=[ Shape(geometry=Text( string=[label], fontStyle=self.fontstyle, )) ], ) for (coord, label) in [ (0, '0B'), (3, '1KB'), (6, '1MB'), (9, '1GB'), ] ] + [ Transform( translation=(coord, -.75, 0), children=[ Shape(geometry=Text( string=[label], fontStyle=self.fontstyle, )) ], ) for (coord, label) in [ (0, 'now'), (-1200 * self.data_slider.scale[0], '-20m'), (-2400 * self.data_slider.scale[0], '-40m'), (-3600 * self.data_slider.scale[0], '-60m'), ] ]) self.transform = Transform(translation=(3, -2, 0), children=[ self.data_slider, self.axes, ]) self.sg = sceneGraph(children=[ self.transform, ], ) self.time = Timer(duration=1, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start() thread = threading.Thread(target=log_reader, args=('epa-http.txt', self.log_queue)) thread.setDaemon(True) thread.start()
def OnInit(self): """Do all of our setup functions...""" BaseContext.OnInit(self) print("""You should see something that looks vaguely like a water-fountain, with individual droplets starting blue and turning white.""") '''The PointSet node will do the actual work of rendering our points into the GL. We start it off with all points at the emitter location and with initial colour.''' self.points = PointSet( coord=Coordinate(point=[emitter] * count), color=Color(color=[initialColor] * count), minSize=7.0, maxSize=10.0, attenuation=[0, 1, 0], ) '''We use a simple Appearance node to apply a texture to the PointSet, the PointSet will use this to enable sprite-based rendering if the extension(s) are available.''' self.shape = Shape( appearance=Appearance(texture=ImageTexture(url='_particle.png'), ), geometry=self.points, ) self.text = Text( string=["""Current multiplier: 1.0"""], fontStyle=FontStyle( family='SANS', format='bitmap', justify='MIDDLE', ), ) self.sg = sceneGraph(children=[ self.shape, SimpleBackground(color=(.5, .5, .5), ), Transform( translation=(0, -1, 0), children=[ Shape(geometry=self.text), ], ), ]) self.velocities = array([(0, 0, 0)] * count, 'd') self.colorVelocities = array(colorVelocities, 'd') print(' <s> make time pass more slowly') print(' <f> make time pass faster') print(' <h> higher') print(' <l> (L) lower') print(' <[> smaller drops') print(' <]> larger drops') self.addEventHandler("keypress", name="s", function=self.OnSlower) self.addEventHandler("keypress", name="f", function=self.OnFaster) self.addEventHandler("keypress", name="h", function=self.OnHigher) self.addEventHandler("keypress", name="l", function=self.OnLower) self.addEventHandler("keypress", name="]", function=self.OnLarger) self.addEventHandler("keypress", name="[", function=self.OnSmaller) '''First timer will provide the general simulation heartbeat.''' self.time = Timer(duration=1.0, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start() '''Second timer provides a cycle on which the fountain reduces/increases the speed at which droplets are started.''' self.time2 = Timer(duration=5.0, repeating=1) self.time2.addEventHandler("cycle", self.OnLower) self.time2.register(self) self.time2.start()
def OnInit(self): """Initialize the context""" '''We've defined a uniform "tween" which represents the current fractional mix between the two positions. When we were using the glVertexPointer/glColorPointer entry points, there were implicitly defined attribute values (gl_Vertex, gl_Color) that recieved our data-records. With legacy-free operation, we explicitly define the attribute values which will be used. They look very similar to the declarations for uniform values, save for the varying keyword. ''' vertex = shaders.compileShader( """ uniform float tween; attribute vec3 position; attribute vec3 tweened; attribute vec3 color; varying vec4 baseColor; void main() { gl_Position = gl_ModelViewProjectionMatrix * mix( vec4( position,1.0), vec4( tweened,1.0), tween ); baseColor = vec4(color,1.0); }""", GL_VERTEX_SHADER) fragment = shaders.compileShader( """ varying vec4 baseColor; void main() { gl_FragColor = baseColor; }""", GL_FRAGMENT_SHADER) self.shader = shaders.compileProgram(vertex, fragment) '''Since our VBO now has two position records and one colour record, we have an extra 3 floats for each vertex record.''' self.vbo = vbo.VBO( array([ [0, 1, 0, 1, 3, 0, 0, 1, 0], [-1, -1, 0, -1, -1, 0, 1, 1, 0], [1, -1, 0, 1, -1, 0, 0, 1, 1], [2, -1, 0, 2, -1, 0, 1, 0, 0], [4, -1, 0, 4, -1, 0, 0, 1, 0], [4, 1, 0, 4, 9, 0, 0, 0, 1], [2, -1, 0, 2, -1, 0, 1, 0, 0], [4, 1, 0, 1, 3, 0, 0, 0, 1], [2, 1, 0, 1, -1, 0, 0, 1, 1], ], 'f')) '''As with uniforms, we must use opaque "location" values to refer to our attributes when calling into the GL.''' self.position_location = glGetAttribLocation(self.shader, 'position') self.tweened_location = glGetAttribLocation( self.shader, 'tweened', ) self.color_location = glGetAttribLocation(self.shader, 'color') self.tween_location = glGetUniformLocation( self.shader, 'tween', ) '''The OpenGLContext timer class is setup here to provide a 0.0 -> 1.0 animation event and pass it to the given function.''' self.time = Timer(duration=2.0, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start()
def OnInit(self): """Scene set up and initial processing""" print """You should see a cone over a black background The cone should have a mapped texture (a stained-glass window) and should be centered on the window. """ print 'press i to choose another texture for the box' self.addEventHandler('keypress', name='i', function=self.OnImageSwitch) print 'press s to choose another size for the box' self.addEventHandler('keypress', name='s', function=self.OnSizeSwitch) self.appearance = Appearance( material=Material( diffuseColor=(1, 0, 0), specularColor=(.5, .5, .5), ), texture=ImageTexture(url=[images[0]]), ) self.cone = Shape( geometry=Cone(), appearance=self.appearance, ) self.cylinder = Shape( geometry=Cylinder(), appearance=self.appearance, ) self.box = Shape( geometry=Box(), appearance=self.appearance, ) self.gear = Shape( geometry=Gear(), appearance=self.appearance, ) self.teapot = Shape( geometry=Teapot(), appearance=self.appearance, ) self.sphere = Shape( geometry=Sphere(), appearance=self.appearance, ) self.ifs = Shape( geometry=IndexedFaceSet( coord=Coordinate(point=[[-1, 0, 0], [1, 0, 0], [1, 1, 0], [-1, 1, 0]], ), coordIndex=[0, 1, 2, -1, 0, 2, 3], color=Color(color=[[0, 0, 1], [1, 0, 0]], ), colorIndex=[0, 1, 0, -1, 0, 0, 1], solid=False, normalPerVertex=True, ), appearance=self.appearance, ) self.sg = Transform( children=[ Transform( translation=(4, 0, 0), children=[self.cone], ), Transform( translation=(0, 0, 0), children=[self.box], ), Transform( translation=(-4, 0, 0), children=[self.cylinder], ), Transform( translation=(0, 4, 0), children=[self.gear], scale=(3, 3, 3), ), Transform( translation=(0, -4, 0), children=[self.teapot], scale=(.5, .5, .5), ), Transform( translation=(4, -4, 0), children=[self.sphere], ), Transform( translation=(-4, -4, 0), children=[self.ifs], ), SimpleBackground(color=(.5, .5, .5), ), ], scale=(.75, .75, .75), ) self.time = Timer(duration=15.0, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start()
def OnInit(self): # draw the ground surface self.cars = 0 self.returnValues = None # for FullScreen self.sg = basenodes.sceneGraph( children=[ basenodes.Transform( translation=(0, 0, -1), children=[ # Ground basenodes.Shape( geometry=basenodes.Box(size=(100, 100, 1), ), appearance=basenodes.Appearance( material=basenodes.Material( diffuseColor=(0.3, 0.3, 0.15), transparency=0.0, ), #texture = imagetexture.ImageTexture(url = ["traffic.png"]), ), ), # Road 1 basenodes.Transform( translation=(0, -2.5, 0), children=[ basenodes.Shape( geometry=basenodes.Box(size=(100, 2, 1.5), ), appearance=basenodes.Appearance( material=basenodes.Material( diffuseColor=(0.6, 0.6, 0.3), transparency=0.0, ), ), ), ], ), # Road 2 basenodes.Transform( translation=(0, 2.5, 0), children=[ basenodes.Shape( geometry=basenodes.Box(size=(100, 2, 1.5), ), appearance=basenodes.Appearance( material=basenodes.Material( diffuseColor=(0.6, 0.6, 0.3), transparency=0.0, ), ), ), ], ), ], ), # Light basenodes.PointLight(location=(-25, -25, 25), ), basenodes.DirectionalLight( ambientIntensity=2.5, intensity=1.5, color=(1, 1, 1), direction=(1, 1, -1), ), ], ) self.sg.regDefName('Ground', self.sg.children[0]) self.sg.getDEF('Ground').translation = (0.0, 0.0, -1.0) self.addTunnel() # self.addTrafficLight() # self.addCar() self.time = Timer(duration=32.0, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start() self.rotation = 0.0
def OnInit(self): """Initialize the context""" '''== Phong and Blinn Reflectance == A shiny surface will tend to have a "bright spot" at the point on the surface where the angle of incidence for the reflected light ray and the viewer's ray are (close to) equal. A perfect mirror would have the brights spot solely when the two vectors are exactly equal, while a perfect Lambertian surface would have the "bright spot" spread across the entire surface. The Phong rendering process models this as a setting, traditionally called material "shininess" in Legacy OpenGL. This setting acts as a power which raises the cosine (dot product) of the angle between the reflected ray and the eye. The calculation of the cosine (dot product) of the two angles requires that we do a dot product of the two angles once for each vertex/fragment for which we wish to calculate the specular reflectance, we also have to find the angle of reflectance before we can do the calculation:''' """ L_dir = (V_pos-L_pos) R = 2N*(dot( N, L_dir))-L_dir // Note: in eye-coordinate system, Eye_pos == (0,0,0) Spec_factor = pow( dot( R, V_pos-Eye_pos ), shininess) """ '''which, as we can see, involves the vertex position in a number of stages of the operation, so requires recalculation all through the rendering operation. There is, however, a simplified version of Phong Lighting called [http://en.wikipedia.org/wiki/Blinn%E2%80%93Phong_shading_model Blinn-Phong] which notes that if we were to do all of our calculations in "eye space", and were to assume that (as is normal), the eye and light coordinates will not change for a rendering pass, (note: this limits us to directional lights!) we can use a pre-calculated value which is the bisecting angle between the light-vector and the view-vector, called the "half vector" to perform approximately the same calculation. With this value:''' """ // note that in Eye coordinates, Eye_EC_dir == 0,0,-1 H = normalize( Eye_EC_dir + Light_EC_dir ) Spec_factor = pow( dot( H, N ), shininess ) """ '''Note: however, that the resulting Spec_factor is not *precisely* the same value as the original calculation, so the "shininess" exponent must be slightly lower to approximate the value that Phong rendering would achieve. The value is, however, considered close to "real world" materials, so the Blinn method is generally preferred to Phong. Traditionally, n_dot_pos would be cut off at 0.0, but that would create extremely hard-edged cut-offs for specular color. Here we "fudge" the result by 0.05 ''' phong_weightCalc = """ vec2 phong_weightCalc( in vec3 light_pos, // light position in vec3 half_light, // half-way vector between light and view in vec3 frag_normal, // geometry normal in float shininess ) { // returns vec2( ambientMult, diffuseMult ) float n_dot_pos = max( 0.0, dot( frag_normal, light_pos )); float n_dot_half = 0.0; if (n_dot_pos > -.05) { n_dot_half = pow(max(0.0,dot( half_light, frag_normal )), shininess); } return vec2( n_dot_pos, n_dot_half); } """ '''We are going to use per-fragment rendering. As a result, our vertex shader becomes very simple, just arranging for the Normals to be varied across the surface. ''' vertex = shaders.compileShader( """ attribute vec3 Vertex_position; attribute vec3 Vertex_normal; varying vec3 baseNormal; void main() { gl_Position = gl_ModelViewProjectionMatrix * vec4( Vertex_position, 1.0 ); baseNormal = gl_NormalMatrix * normalize(Vertex_normal); }""", GL_VERTEX_SHADER) '''Our fragment shader looks much like our previous tutorial's vertex shader. As before, we have lots of uniform values, but now we also calculate the light's half-vector (in eye-space coordinates). The phong_weightCalc function does the core Blinn calculation, and we simply use the resulting factor to add to the colour value for the fragment. Note the use of the eye-coordinate-space to simplify the half-vector calculation, the eye-space eye-vector is always the same value (pointing down the negative Z axis), and the eye-space eye-coordinate is always (0,0,0), so the eye-to-vertex vector is always the eye-space vector position. ''' fragment = shaders.compileShader( phong_weightCalc + """ uniform vec4 Global_ambient; uniform vec4 Light_ambient; uniform vec4 Light_diffuse; uniform vec4 Light_specular; uniform vec3 Light_location; uniform float Material_shininess; uniform vec4 Material_specular; uniform vec4 Material_ambient; uniform vec4 Material_diffuse; varying vec3 baseNormal; void main() { // normalized eye-coordinate Light location vec3 EC_Light_location = normalize( gl_NormalMatrix * Light_location ); // half-vector calculation vec3 Light_half = normalize( EC_Light_location - vec3( 0,0,-1 ) ); vec2 weights = phong_weightCalc( EC_Light_location, Light_half, baseNormal, Material_shininess ); gl_FragColor = clamp( ( (Global_ambient * Material_ambient) + (Light_ambient * Material_ambient) + (Light_diffuse * Material_diffuse * weights.x) // material's shininess is the only change here... + (Light_specular * Material_specular * weights.y) ), 0.0, 1.0); } """, GL_FRAGMENT_SHADER) self.shader = shaders.compileProgram(vertex, fragment) '''Here's the call that creates the two VBOs and the count of records to render from them. If you're curious you can read through the source code of the OpenGLContext.scenegraph.quadrics module to read the mechanism that generates the values. The sphere is a simple rendering mechanism, as for a unit-sphere at the origin, the sphere's normals are the same as the sphere's vertex coordinate. The complexity comes primarily in generating the triangle indices that link the points generated. ''' #self.coords,self.indices,self.count = Sphere( # radius = 3 #).compile() self.coords, self.indices, self.count = Sphere(radius=3).compile() '''We have a few more uniforms to control the specular components. Real-world coding would also calculate the light's half-vector and provide it as a uniform (so that it would only need to be calculated once), but we are going to do the half-vector calculation in the shader to make it obvious what is going on. The legacy OpenGL pipeline provides the value pre-calculated as part of the light structure in GLSL. ''' for uniform in ( 'Global_ambient', 'Light_ambient', 'Light_diffuse', 'Light_location', 'Light_specular', 'Material_ambient', 'Material_diffuse', 'Material_shininess', 'Material_specular', ): location = glGetUniformLocation(self.shader, uniform) if location in (None, -1): print 'Warning, no uniform: %s' % (uniform) setattr(self, uniform + '_loc', location) for attribute in ( 'Vertex_position', 'Vertex_normal', ): location = glGetAttribLocation(self.shader, attribute) if location in (None, -1): print 'Warning, no attribute: %s' % (uniform) setattr(self, attribute + '_loc', location) #Add a timer self.time = Timer(duration=8.0, repeating=1) self.time.addEventHandler("fraction", self.OnTimerFraction) self.time.register(self) self.time.start() self.rotation = 0 self.sensor = PhotoSensor() self.sensor.calibrate_ambient()