def _initFog(self): self.fog = Fog("MazeFog") self.fog.setColor(VBase4(0.3, 0.3, 0.3, 1.0)) self.fog.setLinearRange(0.0, 100.0) self._renderFog = render.getFog() render.setFog(self.fog)
def _initFog(self): self.fog = Fog("FlyingFog") self.fog.setColor(VBase4(0.8, 0.8, 0.8, 1.0)) self.fog.setLinearRange(100.0, 400.0) self._renderFog = render.getFog() render.setFog(self.fog)
def __init__(self): # Make some nice fog colour = (0.3, 0.3, 0.3) linfog = Fog("A linear-mode Fog node") linfog.setColor(*colour) linfog.setLinearRange(0, 320) linfog.setLinearFallback(45, 160, 320) # Catchables positions catchables = [] for i in xrange(100): pos = (i * 10 + 10, 0, 2) catchables.append(pos) # Rocks positions and such rocks = [] rock1 = (0, 50, 0, 10) rocks.append(rock1) self.fog = linfog self.bgcolor = colour self.scale = (1, 1, 1) self.map = "worlds/maps/normalmap" self.catchables = catchables self.rocks = rocks
def doFixedFunction(self): fishFog = Fog('fishFogNode') fishFog.setMode(Fog.MLinear) fishFog.setColor(FishingGlobals.waterFogColor) fishFog.setLinearRange(0.0, 200.0) fishFogAttrib = FogAttrib.make(fishFog) self.objectsWithCaustics.setAttrib(fishFogAttrib)
def __init__(self, ancestor = None): print "____________________________________________________" print "Class Lights" self.ancestor = ancestor #Initialize bg colour colour = (0.2, 0.2, 0.6) base.setBackgroundColor(*colour) base.camLens.setFar(1000.0) self.alight = AmbientLight('ambient_light') self.alight.setColor(Vec4(0.7, 0.7, 0.7, 1)) self.alnp = base.render.attachNewNode(self.alight) base.render.setLight(self.alnp) self.plight = PointLight('sunlight') self.plight.setColor(Vec4(2.5, 2.5, 2.5, 1)) self.plnp = base.render.attachNewNode(self.plight) self.plnp.setPos(50, 0, 300) self.plnp.lookAt(self.ancestor.terrain.root) base.render.setLight(self.plnp) # Initialize linear fog self.fog = Fog("Fog object") self.fog.setMode(Fog.MLinear) self.fog.setLinearRange(14.0,40.0) self.fog.setColor(*colour)
def initFog(self): f = Fog("World Fog") f.setColor(0.5,0.5,0.5) f.setLinearOnsetPoint(0,0,0) f.setLinearOpaquePoint(0,0,-Thing.REVERTS_VISIBLE * 3)#THING_REVERT_DISTANCE) self.renderer.attachNewNode(f) self.renderer.setFog(f)
def doFixedFunction(self): fishFog = Fog("fishFogNode") fishFog.setMode(Fog.MLinear) fishFog.setColor(FishingGlobals.waterFogColor) fishFog.setLinearRange(0.0, 200.0) fishFogAttrib = FogAttrib.make(fishFog) self.objectsWithCaustics.setAttrib(fishFogAttrib)
class DistanceFog(ColoredByTime): def __init__(self): self.exponential() render.attachNewNode(self.fog) render.setFog(self.fog) #self.dayColor = Vec4(0.73, 0.82, 0.90, 1.0) #self.dayColor = Vec4(0.57, 0.75, 0.94, 1.0) self.dayColor = Vec4(0.58, 0.66, 0.82, 1) self.nightColor = Vec4(-0.5, -0.3, .0, 1.0) self.sunsetColor = Vec4(0.75, .60, .65, 1.0) ColoredByTime.__init__(self) self.setColor = self.fog.setColor self.getColor = self.fog.getColor def setTime(self, time): self.colorize(time) def linear(self): self.fog = Fog("A linear-mode Fog node") self.fog.setLinearRange(0, 320) self.fog.setLinearFallback(5, 20, 50) def exponential(self): self.fog = Fog("Scene-wide exponential Fog object") density = 1.38629436 / (MAX_VIEW_RANGE + 30) self.fog.setExpDensity(density)
def SetupLights(self): a = 0.5 d = 0.2 ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(a, a, a, 1)) ambientLightNP = render.attachNewNode(ambientLight) render.setLight(ambientLightNP) dir = [Vec3(1, 1, 1), Vec3(-1, -0.5, -1), Vec3(-0.5, -1, -1)] for i in xrange(3): directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(dir[i]) directionalLight.setColor(Vec4(d, d, d, 1)) render.setLight(render.attachNewNode(directionalLight)) myFog = Fog("Fog Name") myFog.setColor(*Globals.SKY_COLOR) myFog.setLinearRange(40, 70) base.camera.attachNewNode(myFog) render.setFog(myFog) base.setBackgroundColor(*Globals.SKY_COLOR)
def setupLighting(self, sizeVector, centerPos): x, y, z = centerPos sx, sy, sz = (Vec3(sizeVector) * 0.8) # Point lights, one in each ceiling corner. for i in (x-sx, x+sx): for j in (y-sy, y+sy): for k in (z+sz,): self.addPointLight((i, j, k)) # Ambient light. c = 0.4 lightA = AmbientLight("light-ambient") lightA.setColor(VBase4(c, c, c, 1)) lightANode = render.attachNewNode(lightA) render.setLight(lightANode) # Fog. fog = Fog("fog") fog.setColor(1, 1, 1) fog.setExpDensity(0.002) render.setFog(fog)
def setupFog( self ): '''defaultExpFogColor = (0.33, 0.5, 1.0) self.expFog = Fog("exponentialFog") self.expFog.setColor(*defaultExpFogColor) self.expFog.setExpDensity(DEFAULTFOG) render.setFog(self.expFog)''' defaultLinFogColor = (0.33, 0.5, 1.0) self.linFog = Fog("linearFog") self.linFog.setColor(*defaultLinFogColor) self.linFog.setLinearRange(0, linFogMinRange + linFogVarianceRange) self.linFog.setLinearFallback(30, 60, 240) base.camera.attachNewNode(self.linFog) render.setFog(self.linFog) base.setBackgroundColor( defaultLinFogColor )
def __init__(self): """Initialise the scene.""" # Show the framerate base.setFrameRateMeter(True) # Initialise terrain: # Make 4 terrain nodepath objects with different hilliness values # and arrange them side-by-side in a 2x2 grid, giving a big terrain # with variable hilly and flat areas. color = (0.6, 0.8, 0.5, 1) # Bright green-ish scale = 12 height = 18 # FIXME: For now we are raising the terrain so it # floats above the sea to prevent lakes from # appearing (but you still get them sometimes) t1 = Terrain(color=color, scale=scale, trees=0.7, pos=P.Point3(0, 0, height)) t1.prime.reparentTo(render) t2 = Terrain(color=color, scale=scale, h=24, pos=P.Point3(32 * scale, 0, height), trees=0.5) t2.prime.reparentTo(render) t3 = Terrain(color=color, scale=scale, h=16, pos=P.Point3(32 * scale, 32 * scale, height), trees=0.3) t3.prime.reparentTo(render) t4 = Terrain(color=color, scale=scale, h=2, pos=P.Point3(0, 32 * scale, height), trees=0.9) t4.prime.reparentTo(render) #tnp1.setPos(tnp1,-32,-32,terrainHeight) # Initialise sea sea = Sea() # Initialise skybox. self.box = loader.loadModel("models/skybox/space_sky_box.x") self.box.setScale(6) self.box.reparentTo(render) # Initialise characters self.characters = [] self.player = C.Character(model='models/eve', run='models/eve-run', walk='models/eve-walk') self.player.prime.setZ(100) self.player._pos = SteerVec(32 * 12 + random.random() * 100, 32 * 12 + random.random() * 100) self.player.maxforce = 0.4 self.player.maxspeed = 0.55 EdgeScreenTracker(self.player.prime, dist=200) # Setup camera for i in range(0, 11): self.characters.append(C.Character()) self.characters[i].prime.setZ(100) self.characters[i].wander() self.characters[i].maxforce = 0.3 self.characters[i].maxspeed = 0.2 self.characters[i]._pos = SteerVec(32 * 12 + random.random() * 100, 32 * 12 + random.random() * 100) C.setContainer( ContainerSquare(pos=SteerVec(32 * 12, 32 * 12), radius=31 * 12)) #C.toggleAnnotation() # Initialise keyboard controls. self.accept("c", C.toggleAnnotation) self.accept("escape", sys.exit) # Setup CollisionRay and CollisionHandlerQueue for mouse picking. self.pickerQ = P.CollisionHandlerQueue() self.picker = camera.attachNewNode( P.CollisionNode('Picker CollisionNode')) self.picker.node().addSolid(P.CollisionRay()) # We want the picker ray to collide with the floor and nothing else. self.picker.node().setFromCollideMask(C.floorMASK) self.picker.setCollideMask(P.BitMask32.allOff()) base.cTrav.addCollider(self.picker, self.pickerQ) try: handler.addCollider(self.picker, camera) except: pass self.accept('mouse1', self.onClick) # Set the far clipping plane to be far enough away that we can see the # skybox. base.camLens.setFar(10000) # Initialise lighting self.alight = AmbientLight('alight') self.alight.setColor(VBase4(0.35, 0.35, 0.35, 1)) self.alnp = render.attachNewNode(self.alight) render.setLight(self.alnp) self.dlight = DirectionalLight('dlight') self.dlight.setColor(VBase4(0.4, 0.4, 0.4, 1)) self.dlnp = render.attachNewNode(self.dlight) self.dlnp.setHpr(45, -45, 0) render.setLight(self.dlnp) self.plight = PointLight('plight') self.plight.setColor(VBase4(0.8, 0.8, 0.5, 1)) self.plnp = render.attachNewNode(self.plight) self.plnp.setPos(160, 160, 50) self.slight = Spotlight('slight') self.slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() self.slight.setLens(lens) self.slnp = render.attachNewNode(self.slight) self.slnp.setPos(-20, -20, 20) self.slnp.lookAt(50, 50, 0) # Initialise some scene-wide exponential fog colour = (0.5, 0.8, 0.8) self.expfog = Fog("Scene-wide exponential Fog object") self.expfog.setColor(*colour) self.expfog.setExpDensity(0.0005) render.setFog(self.expfog) base.setBackgroundColor(*colour) # Add a task for this Plant to the global task manager. self.stepcount = 0 taskMgr.add(self.step, "Plant step task")
def exponential(self): self.fog = Fog("Scene-wide exponential Fog object") density = 1.38629436 / (MAX_VIEW_RANGE + 30) self.fog.setExpDensity(density)
def linear(self): self.fog = Fog("A linear-mode Fog node") self.fog.setLinearRange(0, 320) self.fog.setLinearFallback(5, 20, 50)
class environmentClass: def __init__( self, cameraPos, heightfield ): self.cameraPos = cameraPos self.heightfield = heightfield if USELIGHT: self.setupLight() if USESKY: self.setupSky() if USEFOG: self.setupFog() if USESOUND: self.setupSound() if USERAIN: self.setupRain() #taskMgr.doMethodLater(DAYNIGHTCYCLETIME/60.0, self.dayNightCycle, 'UpdateDayNight') taskMgr.doMethodLater(0.25, self.dayNightCycle, 'UpdateDayNight') taskMgr.doMethodLater(0.25, self.updateScene, 'updateScene' ) def setupSound( self ): self.mySound1 = loader.loadSfx("data/sounds/rainshower.wav") self.mySound1.setLoop(True) self.mySound1.play() #self.walkSound = loader.loadSfx("sounds/walking/542581_SOUNDDOGS_Ho.mp3") #self.walkSound.setLoop(True) def setupSky( self ): self.skyNP = loader.loadModel( 'data/models/sky.bam.pz' ) self.skyNP.reparentTo( render ) self.skyNP.setScale( 4000, 4000, 1000 ) self.skyNP.setPos( 0, 0, 0 ) self.skyNP.setTexture( loader.loadTexture( 'data/textures/clouds.png' ) ) self.skyNP.setShader( loader.loadShader( 'data/sky.sha' ) ) '''self.skyFogNP = loader.loadModel( 'data/models/sphere.egg' ) self.skyFogNP.reparentTo( base.camera ) self.skyFogNP.setTwoSided( True ) self.skyFogNP.setScale( 10 ) self.skyFogNP.setPos( Vec3(0,0,4) ) self.skyFogNP.setTransparent( True )''' sky = Vec4( 0.25, 0.5, 1.0, 0.0 ) # r, g, b, skip sky2 = Vec4( 1.0, 1.0, 1.0, 0.0 ) clouds = Vec4( 0.004, 0.002, 0.008, 0.010 ) # vx, vy, vx, vy self.skyNP.setShaderInput( 'sky', sky ) self.skyNP.setShaderInput( 'sky2', sky2 ) self.skyNP.setShaderInput( 'clouds', clouds ) render.setShaderInput( 'time', 0 ) def setupLight( self ): ''' #Default lightAttrib with no lights self.lightAttrib = LightAttrib.makeAllOff() # Add a light to the scene. self.lightpivot = self.cameraPos.attachNewNode("lightpivot") #self.lightpivot.setPos(0,0,500) #self.lightpivot.hprInterval(MAPSIZE/4,Point3(360,0,0)).loop() self.plight = PointLight('plight') self.plight.setColor(Vec4(0.5, 0.5, 0.5, 1)) self.plight.setAttenuation(Vec3(0.1,0.0001,0)) self.plnp = self.lightpivot.attachNewNode(self.plight.upcastToPandaNode()) #self.plnp.setPos(45, 0, 0) render.setLight(self.plnp) self.lightAttrib = self.lightAttrib.addLight( self.plight ) # create a sphere to denote the light #sphere = loader.loadModel("data/models/sphere") #sphere.reparentTo(self.plnp) # Add an ambient light alight = AmbientLight('alight') alight.setColor(Vec4(0.2, 0.2, 0.2, 1.0)) alnp = render.attachNewNode(alight.upcastToPandaNode()) render.setLight(alnp) self.lightAttrib = self.lightAttrib.addLight( alight ) # Now we create a spotlight. Spotlights light objects in a given cone # They are good for simulating things like flashlights self.spotlight = Spotlight( "spotlight" ) self.spotlight.setColor( Vec4( .9, .9, .9, 1 ) ) #The cone of a spotlight is controlled by it's lens. This creates the lens self.spotlight.setLens( PerspectiveLens() ) #This sets the Field of View (fov) of the lens, in degrees for width and #height. The lower the numbers, the tighter the spotlight. self.spotlight.getLens().setFov( 16, 16 ) # Attenuation controls how the light fades with distance. The numbers are # The three values represent the three constants (constant, linear, and # quadratic) in the internal lighting equation. The higher the numbers the # shorter the light goes. self.spotlight.setAttenuation( Vec3( 1, 0.0, 0.0 ) ) # This exponent value sets how soft the edge of the spotlight is. 0 means a # hard edge. 128 means a very soft edge. self.spotlight.setExponent( 60.0 ) #self.spotlight.lookAt( Vec3( 0,1,0) ) # Unlike our previous lights, the spotlight needs a position in the world # We are attaching it to the camera so that it will appear is if we are # holding a flashlight, but it can be attached to any NodePath # # When attaching a spotlight to a NodePath, you must use the # upcastToLensNode function or Panda will crash self.spotLightNp = base.camera.attachNewNode( self.spotlight.upcastToLensNode() ) self.spotLightNp.lookAt( Point3(0,1,0) ) self.lightAttrib = self.lightAttrib.addLight( self.spotlight ) #self.spotlight.reparentTo( base.camera ) ''' #Default lightAttrib with no lights #self.lightAttrib = LightAttrib.makeAllOff() # First we create an ambient light. All objects are affected by ambient # light equally #Create and name the ambient light self.ambientLight = AmbientLight( "ambientLight" ) #Set the color of the ambient light self.ambientLight.setColor( Vec4( .1, .1, .1, 1 ) ) #add the newly created light to the lightAttrib render.setLight(render.attachNewNode(self.ambientLight)) #self.lightAttrib = self.lightAttrib.addLight( self.ambientLight ) ''' # Now we create a directional light. Directional lights add shading from a # given angle. This is good for far away sources like the sun self.directionalLight = DirectionalLight( "directionalLight" ) self.directionalLight.setColor( Vec4( .7, .7, .7, 1 ) ) # The direction of a directional light is set as a 3D vector self.directionalLight.setDirection( Vec3( 1, 1, -2 ) ) self.lightAttrib = self.lightAttrib.addLight( self.directionalLight ) ''' # Now we create a spotlight. Spotlights light objects in a given cone # They are good for simulating things like flashlights self.spotlight = Spotlight( "spotlight" ) self.spotlight.setColor( Vec4( .9, .9, .9, 1 ) ) #The cone of a spotlight is controlled by it's lens. This creates the lens self.spotlight.setLens( PerspectiveLens() ) #This sets the Field of View (fov) of the lens, in degrees for width and #height. The lower the numbers, the tighter the spotlight. self.spotlight.getLens().setFov( 30, 30 ) # Attenuation controls how the light fades with distance. The numbers are # The three values represent the three constants (constant, linear, and # quadratic) in the internal lighting equation. The higher the numbers the # shorter the light goes. self.spotlight.setAttenuation( Vec3( 0.0, 0.0075, 0.0 ) ) # This exponent value sets how soft the edge of the spotlight is. 0 means a # hard edge. 128 means a very soft edge. self.spotlight.setExponent( 60.0 ) # Unlike our previous lights, the spotlight needs a position in the world # We are attaching it to the camera so that it will appear is if we are # holding a flashlight, but it can be attached to any NodePath # # When attaching a spotlight to a NodePath, you must use the # upcastToLensNode function or Panda will crash #camera.attachNewNode( self.spotlight.upcastToLensNode() ) render.setLight(camera.attachNewNode( self.spotlight.upcastToLensNode() )) #self.lightAttrib = self.lightAttrib.addLight( self.spotlight ) ''' PLIGHTATT = Vec3( 0.0, 0.0, 0.0 ) # Now we create three colored Point lights. Point lights are lights that # radiate from a single point, like a light bulb. Like spotlights, they # are given position by attaching them to NodePaths in the world self.redPointLight = PointLight( "redPointLight" ) self.redPointLight.setColor( Vec4( .7, 0, 0, 1 ) ) self.redPointLight.setAttenuation( PLIGHTATT ) self.redHelper = loader.loadModelCopy('models/sphere') self.redHelper.setColor( Vec4( 1, 0, 0, 1 ) ) # To attach a point light to the scene, you must use the upcastToPandaNode # Again, if you don't do this Panda will crash self.redHelper.attachNewNode( self.redPointLight.upcastToPandaNode() ) self.redHelper.setPos( -6.5, -3.75, 0 ) self.redHelper.setScale(.25) #The green point light and helper self.greenPointLight = PointLight( "greenPointLight" ) self.greenPointLight.setAttenuation( PLIGHTATT ) self.greenPointLight.setColor( Vec4( 0, .7, 0, 1 ) ) self.greenHelper = loader.loadModelCopy('models/sphere') self.greenHelper.setColor( Vec4( 0, 1, 0, 1 ) ) self.greenHelper.attachNewNode( self.greenPointLight.upcastToPandaNode() ) self.greenHelper.setPos( 0, 7.5, 0 ) self.greenHelper.setScale(.25) #The blue point light and helper self.bluePointLight = PointLight( "bluePointLight" ) self.bluePointLight.setAttenuation( PLIGHTATT ) self.bluePointLight.setColor( Vec4( 0, 0, .7, 1 ) ) self.bluePointLight.setSpecularColor( Vec4( 1 ) ) self.blueHelper = loader.loadModelCopy('models/sphere') self.blueHelper.setColor( Vec4( 0, 0, 1, 1 ) ) self.blueHelper.attachNewNode( self.bluePointLight.upcastToPandaNode() ) self.blueHelper.setPos( 6.5, -3.75, 0 ) self.blueHelper.setScale(.25) #Create a dummy node so the lights can be spun with one command self.pointLightHelper = render.attachNewNode( "pointLightHelper" ) self.pointLightHelper.setPos(0, 50, 11) self.redHelper.reparentTo( self.pointLightHelper ) self.greenHelper.reparentTo( self.pointLightHelper ) self.blueHelper.reparentTo( self.pointLightHelper ) #Add the point lights we just made to our lightAttrib self.lightAttrib = self.lightAttrib.addLight( self.redPointLight ) self.lightAttrib = self.lightAttrib.addLight( self.greenPointLight ) self.lightAttrib = self.lightAttrib.addLight( self.bluePointLight ) ''' #Finally we set the light attrib to a node. In this case we are using render #so that the lights will effect everything, but you could put it on any #part of the scene #render.node().setAttrib( self.lightAttrib ) # Create and start interval to spin the lights, and a variable to # manage them. #self.pointLightsSpin = self.pointLightHelper.hprInterval(6, Vec3(360, 0, 0)) #self.pointLightsSpin.loop() def setupFog( self ): '''defaultExpFogColor = (0.33, 0.5, 1.0) self.expFog = Fog("exponentialFog") self.expFog.setColor(*defaultExpFogColor) self.expFog.setExpDensity(DEFAULTFOG) render.setFog(self.expFog)''' defaultLinFogColor = (0.33, 0.5, 1.0) self.linFog = Fog("linearFog") self.linFog.setColor(*defaultLinFogColor) self.linFog.setLinearRange(0, linFogMinRange + linFogVarianceRange) self.linFog.setLinearFallback(30, 60, 240) base.camera.attachNewNode(self.linFog) render.setFog(self.linFog) base.setBackgroundColor( defaultLinFogColor ) def setupRain( self ): base.enableParticles() self.rain = rainClass() self.rain.reparentTo( base.camera ) #self.rain.setPos( 0, 0, 5 ) self.rain.setScale( 200 ) #self.rain.particle.setPoolSize( 8192 ) #self.rain.particle.setBirthRate( 2.000 ) #self.rain.particle.renderer.setHeadColor(Vec4(1.00, 1.00, 1.00, 0.8)) #self.rain.particle.renderer.setTailColor(Vec4(1.00, 1.00, 1.00, 0.2)) self.rain.start( render ) def dayNightCycle( self, task ): #print "dayNight", rainStrenght if USERAIN: rainStrenght = (RAINCYCLEFUNC**((math.sin(time.time()/(DAYNIGHTCYCLETIME/24.))+1.0)/2.0)-1.0)/(RAINCYCLEFUNC-1.0) self.rain.particle.setBirthRate( max( rainStrenght, 0.01 ) ) dayNight = (DAYNIGHTCYCLEFUNC**((math.sin(time.time()/(DAYNIGHTCYCLETIME/6.))+1.0)/2.0)-1.0)/(DAYNIGHTCYCLEFUNC-1.0) if USELIGHT: #print dayNight c = (dayNight)/1.5 + 0.1 #print dayNight, c [commented by Finn] aLightCol = Vec4( c, c, c, 1 ) self.ambientLight.setColor( aLightCol ) # Time for clouds shader if USESKY: render.setShaderInput( 'time', task.time/4.0 ) #dayNight = 1.0 # color for clouds & fog #dayNight = ( math.sin(time.time()/DAYNIGHTCYCLETIME) + 1.0 ) / 2.0 # 0.0 for night, 1.0 for day sky = Vec4( dayNight/4.0, dayNight/2.0, dayNight, 0.0 ) # r, g, b, skip sky2 = Vec4( dayNight, dayNight, dayNight, 0.0 ) # set colors self.skyNP.setShaderInput( 'sky', sky ) self.skyNP.setShaderInput( 'sky2', sky2 ) if USEFOG: #expFogColor = dayNight/3.0,dayNight/2.0,dayNight #self.expFog.setColor( *expFogColor ) #self.expFog.setExpDensity(DEFAULTFOG*(NIGHTFOGMULTIPLIER-dayNight*(NIGHTFOGMULTIPLIER-1.0))) linFogColor = dayNight/3.0,dayNight/2.0,dayNight self.linFog.setColor( *linFogColor ) fogRange = linFogMinRange + linFogVarianceRange*dayNight self.linFog.setLinearRange( fogRange/4., fogRange ) self.linFog.setLinearFallback(fogRange/8., fogRange/4., fogRange) base.setBackgroundColor( linFogColor ) return Task.again def updateScene( self, task ): # set position of the particle system if USERAIN: self.rain.setPos( base.camera.getPos() + Vec3( 0,0,200) ) return Task.cont
def __init__(self): """Initialise the scene.""" # Show the framerate base.setFrameRateMeter(True) # Initialise terrain: # Make 4 terrain nodepath objects with different hilliness values # and arrange them side-by-side in a 2x2 grid, giving a big terrain # with variable hilly and flat areas. color = (0.6,0.8,0.5,1) # Bright green-ish scale = 12 height = 18 # FIXME: For now we are raising the terrain so it # floats above the sea to prevent lakes from # appearing (but you still get them sometimes) t1 = Terrain(color=color,scale=scale,trees=0.7,pos=P.Point3(0,0,height)) t1.prime.reparentTo(render) t2 = Terrain(color=color,scale=scale,h=24,pos=P.Point3(32*scale,0,height),trees=0.5) t2.prime.reparentTo(render) t3 = Terrain(color=color,scale=scale,h=16,pos=P.Point3(32*scale,32*scale,height),trees=0.3) t3.prime.reparentTo(render) t4 = Terrain(color=color,scale=scale,h=2,pos=P.Point3(0,32*scale,height),trees=0.9) t4.prime.reparentTo(render) #tnp1.setPos(tnp1,-32,-32,terrainHeight) # Initialise sea sea = Sea() # Initialise skybox. self.box = loader.loadModel("models/skybox/space_sky_box.x") self.box.setScale(6) self.box.reparentTo(render) # Initialise characters self.characters = [] self.player = C.Character(model='models/eve',run='models/eve-run', walk='models/eve-walk') self.player.prime.setZ(100) self.player._pos = SteerVec(32*12+random.random()*100,32*12+random.random()*100) self.player.maxforce = 0.4 self.player.maxspeed = 0.55 EdgeScreenTracker(self.player.prime,dist=200) # Setup camera for i in range(0,11): self.characters.append(C.Character()) self.characters[i].prime.setZ(100) self.characters[i].wander() self.characters[i].maxforce = 0.3 self.characters[i].maxspeed = 0.2 self.characters[i]._pos = SteerVec(32*12+random.random()*100,32*12+random.random()*100) C.setContainer(ContainerSquare(pos=SteerVec(32*12,32*12),radius=31*12)) #C.toggleAnnotation() # Initialise keyboard controls. self.accept("c",C.toggleAnnotation) self.accept("escape", sys.exit) # Setup CollisionRay and CollisionHandlerQueue for mouse picking. self.pickerQ = P.CollisionHandlerQueue() self.picker = camera.attachNewNode(P.CollisionNode('Picker CollisionNode')) self.picker.node().addSolid(P.CollisionRay()) # We want the picker ray to collide with the floor and nothing else. self.picker.node().setFromCollideMask(C.floorMASK) self.picker.setCollideMask(P.BitMask32.allOff()) base.cTrav.addCollider(self.picker,self.pickerQ) try: handler.addCollider(self.picker,camera) except: pass self.accept('mouse1',self.onClick) # Set the far clipping plane to be far enough away that we can see the # skybox. base.camLens.setFar(10000) # Initialise lighting self.alight = AmbientLight('alight') self.alight.setColor(VBase4(0.35, 0.35, 0.35, 1)) self.alnp = render.attachNewNode(self.alight) render.setLight(self.alnp) self.dlight = DirectionalLight('dlight') self.dlight.setColor(VBase4(0.4, 0.4, 0.4, 1)) self.dlnp = render.attachNewNode(self.dlight) self.dlnp.setHpr(45, -45, 0) render.setLight(self.dlnp) self.plight = PointLight('plight') self.plight.setColor(VBase4(0.8, 0.8, 0.5, 1)) self.plnp = render.attachNewNode(self.plight) self.plnp.setPos(160, 160, 50) self.slight = Spotlight('slight') self.slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() self.slight.setLens(lens) self.slnp = render.attachNewNode(self.slight) self.slnp.setPos(-20, -20, 20) self.slnp.lookAt(50,50,0) # Initialise some scene-wide exponential fog colour = (0.5,0.8,0.8) self.expfog = Fog("Scene-wide exponential Fog object") self.expfog.setColor(*colour) self.expfog.setExpDensity(0.0005) render.setFog(self.expfog) base.setBackgroundColor(*colour) # Add a task for this Plant to the global task manager. self.stepcount = 0 taskMgr.add(self.step,"Plant step task")
def __init__(self, world, x1, y1, x2, y2, z): self.world = world logging.info(('setting up water plane at z=' + str(z))) # Water surface maker = CardMaker('water') maker.setFrame(x1, x2, y1, y2) self.waterNP = render.attachNewNode(maker.generate()) self.waterNP.setHpr(0, -90, 0) self.waterNP.setPos(0, 0, z) self.waterNP.setTransparency(TransparencyAttrib.MAlpha) self.waterNP.setShader(loader.loadShader('shaders/water.sha')) self.waterNP.setShaderInput('wateranim', Vec4(0.03, -0.015, 64.0, 0)) # vx, vy, scale, skip # offset, strength, refraction factor (0=perfect mirror, 1=total refraction), refractivity self.waterNP.setShaderInput('waterdistort', Vec4(0.4, 4.0, 0.25, 0.45)) self.waterNP.setShaderInput('time', 0) # Reflection plane self.waterPlane = Plane(Vec3(0, 0, z + 1), Point3(0, 0, z)) planeNode = PlaneNode('waterPlane') planeNode.setPlane(self.waterPlane) # Buffer and reflection camera buffer = base.win.makeTextureBuffer('waterBuffer', 512, 512) buffer.setClearColor(Vec4(0, 0, 0, 1)) cfa = CullFaceAttrib.makeReverse() rs = RenderState.make(cfa) self.watercamNP = base.makeCamera(buffer) self.watercamNP.reparentTo(render) #sa = ShaderAttrib.make() #sa = sa.setShader(loader.loadShader('shaders/splut3Clipped.sha') ) cam = self.watercamNP.node() cam.getLens().setFov(base.camLens.getFov()) cam.getLens().setNear(1) cam.getLens().setFar(5000) cam.setInitialState(rs) cam.setTagStateKey('Clipped') #cam.setTagState('True', RenderState.make(sa)) # ---- water textures ----------------------------------------------- #reflection texture, created in realtime by the 'water camera' tex0 = buffer.getTexture() tex0.setWrapU(Texture.WMClamp) tex0.setWrapV(Texture.WMClamp) ts0 = TextureStage('reflection') self.waterNP.setTexture(ts0, tex0) # distortion texture tex1 = loader.loadTexture('textures/water.png') ts1 = TextureStage('distortion') self.waterNP.setTexture(ts1, tex1) # ---- Fog --- broken min = Point3(x1, y1, -999.0) max = Point3(x2, y2, z) boundry = BoundingBox(min, max self.waterFog = Fog('waterFog') self.waterFog.setBounds(boundry) colour = (0.2, 0.5, 0.8) self.waterFog.setColor(*colour) self.waterFog.setExpDensity(0.05) render.attachNewNode(self.waterFog) #render.setFog(world.waterFog) taskMgr.add(self.update, "waterTask") def update(self, task): # update matrix of the reflection camera mc = base.camera.getMat() mf = self.waterPlane.getReflectionMat() self.watercamNP.setMat(mc * mf) self.waterNP.setShaderInput('time', task.time) self.waterNP.setX(self.world.ralph.getX()) self.waterNP.setY(self.world.ralph.getY()) return task.cont
def start(self): self.textures.load_all() self.char = Actor("res/models/ralph", {"run": "res/models/ralph-run", "walk": "res/models/ralph-walk"}) self.char.pose("walk", 5) self.char.setScale(0.2) self.char.setH(180) self.gui.buttons.add_button( name="Exit", text=("Exit", "Exit", "Exit", "disabled"), pos=(1.23, 0, -0.95), scale=0.07, command=self.stop ) self.gui.screen_texts.add_text(name="status", text="Hello! Suber was started!", pos=(-1.3, -0.95), scale=0.07) # self.gui.entries.add_entry(name = 'console',text = "" , # pos = (-1.29, 0, -0.85), # scale=0.07,command=self.cmd_handler.cmd_handle, # initialText="", width = 37, numLines = 1,focus=0) self.gui.screen_texts.add_text( name="help", text="F5 - create world\nm - toggle map\nF1 - toggle" + " help\nEsc - exit\nF10 - render info\n" + "F2/F3 - 1st/3d person camera\n" + "F4 - toggle fly/terrain\n" + "F9 - Cam disable\n" + "F8 - Toggle Collisions\n" + "F11/F12 - toggle polygons / disable textures", pos=(-1, 0.8), scale=0.07, ) self.gui.hotkeys.accept("f1", self.toggle_help) self.gui.screen_images.add_image("sight", self.textures["sight"], scale=0.05, pos=(0, 0, 0)) self.gui.screen_images["sight"].setTransparency(TransparencyAttrib.MAlpha) plight = PointLight("plight") sun = self.gui.render.attachNewNode(plight) sun.setPos(-32768, 32768, 20000) self.gui.render.setLight(sun) alight = AmbientLight("alight") alight.setColor(VBase4(0.5, 0.5, 0.5, 1)) alnp = self.gui.render.attachNewNode(alight) self.gui.render.setLight(alnp) color = (0.28125, 0.53125, 0.80859375) fog = Fog("A linear-mode Fog node") fog.setColor(*color) fog.setLinearFallback(0, 500, 550) self.gui.camera.attachNewNode(fog) color = (0.28125, 0.53125, 0.80859375) self.gui.render.setFog(fog) self.gui.setBackgroundColor(*color) self.cam_manager = CamManager(self) self.move_avatar = MoveAvatar(self) self.vox_config = VoxConfig() self.coord_block = CoordBlock(self, self.vox_config) self.vox_params = VoxParams() self.vox_params.gui = self.gui self.vox_params.avatar = self.cam_manager.node self.vox_params.status = self.write self.vox_params.root_node = self.gui.render self.vox_params.chunks_tex = self.textures["world_blocks"] self.vox_params.get_coord_block = self.coord_block self.vox_params.tree_tex = self.textures["tree"] self.vox_params.water_tex = self.textures["water"] self.vox_params.leafModel = self.gui.loader.loadModel("res/models/shrubbery") self.vox_params.leafTex = self.textures["leaf"] self.vox_params.fog = fog self.world = World(self.vox_config, self.vox_params) self.collision_avatar = CollisionAvatar(self) # self.vox_params.sun = sun self.gui.taskMgr.setupTaskChain("Ticker", tickClock=True) self.gui.taskMgr.doMethodLater(0.05, self.ticker, "taskTicker", taskChain="Ticker") self.gui.start()
def load(self): ToonHood.load(self) self.fog = Fog('OZFog')
class CogdoFlyingGame(DirectObject): UPDATE_TASK_NAME = "CogdoFlyingGameUpdate" GAME_COMPLETE_TASK_NAME = "CogdoFlyingGameCompleteTask" def __init__(self, distGame): self.distGame = distGame # Unused currently self.players = {} self.localPlayer = CogdoFlyingLocalPlayer(self, base.localAvatar) # Unused currently self.toonDropShadows = [] self.startPlatform = None # self.currentPlatform = None self.endPlatform = None self.fuelPlatforms = {} self.isGameComplete = False self.upLimit = 0.0 self.downLimit = 0.0 self.leftLimit = 0.0 self.rightLimit = 0.0 def load(self): self.root = NodePath('root') self.root.reparentTo(render) self.root.stash() self.world = loadMockup("cogdominium/mockup.egg") self.world.reparentTo(self.root) self.world.stash() # Setup and placement of starting platform self.startPlatform = loadMockup("cogdominium/start_platform.egg") startPlatformLoc = self.world.find("**/start_platform_loc") self.startPlatform.reparentTo(startPlatformLoc) colModel = self.startPlatform.find("**/col_floor") colModel.setTag('start_platform', '%s' % base.localAvatar.doId) # Here we set the current platform for the local player self.localPlayer.setCheckpointPlatform(self.startPlatform) # Setup and placement of the end platform self.endPlatform = loadMockup("cogdominium/end_platform.egg") endPlatformLoc = self.world.find("**/end_platform_loc") self.endPlatform.reparentTo(endPlatformLoc) colModel = self.endPlatform.find("**/col_floor") colModel.setTag('end_platform', '%s' % base.localAvatar.doId) # Setup and placement for all the fuel platforms fuelPlatformModel = loadMockup("cogdominium/fuel_platform.egg") fuelIndex = 1 fuelLoc = self.world.find('**/fuel_platform_loc_%d' % fuelIndex) while not fuelLoc.isEmpty(): fuelModel = NodePath("fuel_platform_%d" % fuelIndex) fuelPlatformModel.copyTo(fuelModel) fuelModel.reparentTo(fuelLoc) colModel = fuelModel.find("**/col_floor") colModel.setTag('fuel_platform', '%s' % base.localAvatar.doId) colModel.setTag('isUsed', '%s' % 0) self.fuelPlatforms[fuelModel.getName()] = fuelModel fuelIndex += 1 fuelLoc = self.world.find('**/fuel_platform_loc_%d' % fuelIndex) self.accept("entercol_floor", self.handleCollision) self.skybox = self.world.find("**/skybox") self.upLimit = self.world.find("**/limit_up").getPos(render).getZ() self.downLimit = self.world.find("**/limit_down").getPos(render).getZ() self.leftLimit = self.world.find("**/limit_left").getPos(render).getX() self.rightLimit = self.world.find("**/limit_right").getPos( render).getX() del fuelPlatformModel self._initFog() def unload(self): self.__stopUpdateTask() self.__stopGameCompleteTask() self._destroyFog() # print "Unload Flying CogdoGame" self.localPlayer.unload() del self.localPlayer self.fuelPlatforms.clear() self.endPlatform = None self.world.detachNode() del self.world self.root.detachNode() del self.root self.ignore("entercol_floor") def handleCollision(self, collEntry): fromNodePath = collEntry.getFromNodePath() intoNodePath = collEntry.getIntoNodePath() intoName = intoNodePath.getName() fromName = fromNodePath.getName() if intoNodePath.getTag('fuel_platform') != "": if not int( intoNodePath.getTag('isUsed') ) or CogdoFlyingGameGlobals.FlyingGame.MULTIPLE_REFUELS_PER_STATION: intoNodePath.setTag('isUsed', '%s' % 1) self.localPlayer.setCheckpointPlatform( intoNodePath.getParent()) self.localPlayer.request("Refuel") if intoNodePath.getTag('end_platform') != "": self.localPlayer.request("WaitingForWin") def enable(self): self.localPlayer.request("FreeFly") self.__startUpdateTask() self.isGameComplete = False def disable(self): self.__stopUpdateTask() self.__stopGameCompleteTask() self.localPlayer.request("Inactive") def _initFog(self): self.fog = Fog("FlyingFog") self.fog.setColor(VBase4(0.8, 0.8, 0.8, 1.0)) self.fog.setLinearRange(100.0, 400.0) self._renderFog = render.getFog() render.setFog(self.fog) def _destroyFog(self): render.clearFog() del self.fog del self._renderFog def onstage(self): self.root.unstash() self.world.unstash() self.localPlayer.onstage() def offstage(self): self.__stopUpdateTask() self.world.stash() self.root.stash() self.localPlayer.offstage() #TODO: Temp solution, this is supposed to come from the minigame # Which means the minigame isn't getting cleaned up properly look into this self.unload() def handleToonJoined(self, toon): # Not used, no multiplayer support in yet if toon == base.localAvatar: player = CogdoFlyingLocalPlayer(toon) player.entersActivity() self.localPlayer = player else: player = CogdoFlyingPlayer(toon) player.entersActivity() self.players[toon.doId] = player def __startUpdateTask(self): self.__stopUpdateTask() taskMgr.add(self.__updateTask, CogdoFlyingGame.UPDATE_TASK_NAME, 45) def __stopUpdateTask(self): taskMgr.remove(CogdoFlyingGame.UPDATE_TASK_NAME) def __stopGameCompleteTask(self): taskMgr.remove(CogdoFlyingGame.GAME_COMPLETE_TASK_NAME) def gameComplete(self): self.localPlayer.request("Win") def __updateTask(self, task): self.localPlayer.update() #TODO:flying: make this win condition stuff work for multiple toons if self.localPlayer.state == "WaitingForWin" and not self.isGameComplete: self.isGameComplete = True taskMgr.doMethodLater(6.0, self.gameComplete, CogdoFlyingGame.GAME_COMPLETE_TASK_NAME, extraArgs=[]) self.skybox.setPos(self.skybox.getPos().getX(), self.localPlayer.toon.getPos().getY(), self.skybox.getPos().getZ()) return Task.cont
def __init__(self, world, x1, y1, x2, y2, z): self.world = world logging.info(('setting up water plane at z=' + str(z))) # Water surface maker = CardMaker('water') maker.setFrame(x1, x2, y1, y2) self.waterNP = render.attachNewNode(maker.generate()) self.waterNP.setHpr(0, -90, 0) self.waterNP.setPos(0, 0, z) self.waterNP.setTransparency(TransparencyAttrib.MAlpha) self.waterNP.setShader(loader.loadShader('shaders/water.sha')) self.waterNP.setShaderInput('wateranim', Vec4(0.03, -0.015, 64.0, 0)) # vx, vy, scale, skip # offset, strength, refraction factor (0=perfect mirror, 1=total refraction), refractivity self.waterNP.setShaderInput('waterdistort', Vec4(0.4, 4.0, 0.25, 0.45)) self.waterNP.setShaderInput('time', 0) # Reflection plane self.waterPlane = Plane(Vec3(0, 0, z + 1), Point3(0, 0, z)) planeNode = PlaneNode('waterPlane') planeNode.setPlane(self.waterPlane) # Buffer and reflection camera buffer = base.win.makeTextureBuffer('waterBuffer', 512, 512) buffer.setClearColor(Vec4(0, 0, 0, 1)) cfa = CullFaceAttrib.makeReverse() rs = RenderState.make(cfa) self.watercamNP = base.makeCamera(buffer) self.watercamNP.reparentTo(render) #sa = ShaderAttrib.make() #sa = sa.setShader(loader.loadShader('shaders/splut3Clipped.sha') ) cam = self.watercamNP.node() cam.getLens().setFov(base.camLens.getFov()) cam.getLens().setNear(1) cam.getLens().setFar(5000) cam.setInitialState(rs) cam.setTagStateKey('Clipped') #cam.setTagState('True', RenderState.make(sa)) # ---- water textures --------------------------------------------- # reflection texture, created in realtime by the 'water camera' tex0 = buffer.getTexture() tex0.setWrapU(Texture.WMClamp) tex0.setWrapV(Texture.WMClamp) ts0 = TextureStage('reflection') self.waterNP.setTexture(ts0, tex0) # distortion texture tex1 = loader.loadTexture('textures/water.png') ts1 = TextureStage('distortion') self.waterNP.setTexture(ts1, tex1) # ---- Fog --- broken min = Point3(x1, y1, -999.0) max = Point3(x2, y2, z) boundry = BoundingBox(min, max) self.waterFog = Fog('waterFog') self.waterFog.setBounds(boundry) colour = (0.2, 0.5, 0.8) self.waterFog.setColor(*colour) self.waterFog.setExpDensity(0.05) render.attachNewNode(self.waterFog) #render.setFog(world.waterFog) taskMgr.add(self.update, "waterTask")
def __init__(self,parent,segments,timeOfDay): super(VisualTrackSession, self).__init__() self.parent=parent self.ticks=0 self.cars=[] self.events=[] self.timerDependentObjects=[] self.segments=segments self.createdNodes=[] self.stencilReaders={} self.stencilWriters={} self.carShadowRefreshIndex=0 self.speed=-1 self.lapTimeSeconds=-1 self.lapTimeMilliseconds=-1 self.secondsRemaining=-1 self.topScore=-1 self.correctAspectRatio() base.setBackgroundColor(0.262,0.615,0.054) base.accept('aspectRatioChanged',self.correctAspectRatio ) self.carsAndSceneryNode=render.attachNewNode("CarsAndSceneryNode") self.carsAndSceneryNode.setColorScale(1.0,1.0,1.0,1.0) self.sunEffectsEnabled=False if timeOfDay==TimeOfDay.dusk: self.setBackgroundTexture('textures/mountains4x2blurredblended.png') self.setLightSourcePosition([12000,-800,1200]) self.addSunEffects() else: self.setBackgroundTexture('textures/mountainsx2blurredblended.png') self.setLightSourcePosition([-4000,-1800,2400]) m = loader.loadModel("models/newstartline") m.reparentTo(self.carsAndSceneryNode) m.setPos(self.segments[0].getMidPoint().getX(),self.segments[0].getMidPoint().getY(),0) m.setH(270) self.lights=m self.lightsIlluminated=False for i in range(1,5): self.setStartingLight(i,False) self.createdNodes.append(m) trackGeomNodes=TrackVisualGeometry.makeTrack(self.segments) track=render.attachNewNode(trackGeomNodes['tarmac']) texture=loader.loadTexture("textures/track256.png") texture.setAnisotropicDegree(4) texture.setMagfilter(Texture.FTNearest) texture.setMinfilter(Texture.FTLinearMipmapLinear) texture.setWrapU(Texture.WMRepeat) texture.setWrapV(Texture.WMRepeat) track.setTexture(texture) track.setTwoSided(False) track.setDepthWrite(False) track.setDepthTest(False) track.setBin("background",10) self.createdNodes.append(track) constantTwoStencil = StencilAttrib.make(1,StencilAttrib.SCFEqual,StencilAttrib.SOZero,StencilAttrib.SOKeep,StencilAttrib.SOReplace,2,0,2) track.node().setAttrib(constantTwoStencil) startLine=render.attachNewNode(trackGeomNodes['startline']) texture=loader.loadTexture("textures/startline.png") texture.setAnisotropicDegree(4) texture.setMagfilter(Texture.FTNearest) texture.setMinfilter(Texture.FTLinearMipmapLinear) texture.setWrapU(Texture.WMRepeat) texture.setWrapV(Texture.WMRepeat) startLine.setTexture(texture) startLine.setTwoSided(False) startLine.setDepthWrite(False) startLine.setDepthTest(False) startLine.setBin("background",11); self.createdNodes.append(startLine) backgroundGeomNodes=MountainsGeometry.makeMountains() mountainsGeomNode=backgroundGeomNodes['mountains'] mountains=render.attachNewNode(mountainsGeomNode) texture=loader.loadTexture(self.getBackgroundTexture()) texture.setAnisotropicDegree(4) texture.setWrapU(Texture.WMRepeat) texture.setWrapV(Texture.WMClamp) mountains.setTexture(texture) mountains.setTwoSided(False) mountains.setDepthWrite(False) mountains.setDepthTest(False) mountains.setBin("background",10); self.createdNodes.append(mountains) skyGeomNode=backgroundGeomNodes['sky'] sky=render.attachNewNode(skyGeomNode) sky.setDepthWrite(False) sky.setDepthTest(False) sky.setBin("background",11) self.createdNodes.append(sky) constantOneStencil = StencilAttrib.make(1,StencilAttrib.SCFEqual,StencilAttrib.SOZero,StencilAttrib.SOKeep,StencilAttrib.SOReplace,1,0,1) shadowX=self.segments[0].getMidPoint().getX() shadowY=self.segments[0].getMidPoint().getY() lightSourceX,lightSourceY,lightSourceZ=self.getLightSourcePosition() shadowGeomNode=ShadowGeometry.makeModelShadow("models/newstartlineshadow",shadowX,shadowY,0,lightSourceX,lightSourceY,lightSourceZ,270) shadow=render.attachNewNode(shadowGeomNode) shadow.setTwoSided(True) self.createdNodes.append(shadow) shadow.setPos(shadowX,shadowY,0) shadow.node().setAttrib(constantOneStencil) shadow.node().setAttrib(ColorWriteAttrib.make(0)) shadow.setBin('fixed',40) shadow.setDepthWrite(0) self.createdNodes.append(shadow) stencilReader = StencilAttrib.make(1,StencilAttrib.SCFEqual,StencilAttrib.SOKeep, StencilAttrib.SOKeep,StencilAttrib.SOKeep,1,1,0) cm2d = CardMaker('card') cm2d.setFrameFullscreenQuad() card = render2d.attachNewNode(cm2d.generate()) card.node().setAttrib(stencilReader) card.setDepthTest(False) card.setTransparency(TransparencyAttrib.MAlpha) card.setColor(0,0,0,0.40) self.createdNodes.append(card) trafficLightCm=CardMaker('card') trafficLightCm.setFrame(-0.20,0.20,0.20,-0.20) trafficLight = render.attachNewNode(trafficLightCm.generate()) trafficLight.reparentTo(self.lights) trafficLight.setDepthTest(True) trafficLight.setDepthWrite(False) trafficLight.setColor(1.0,0.0,0.0,1.0) trafficLight.setBin("unsorted",50) trafficLight.setBillboardAxis() trafficLight.setTwoSided(True) tex = loader.loadTexture('textures/roadhighlight.png') trafficLight.setTexture(tex) trafficLight.setTransparency(TransparencyAttrib.MAlpha) trafficLight.hide() self.trafficLight=trafficLight self.createdNodes.append(trafficLight) colour = (45.0/255.0,81.0/255.0,98.0/255.0) expfog = Fog("Scene-wide exponential Fog object") expfog.setColor(*colour) expfog.setExpDensity(0.002) self.carsAndSceneryNode.setFog(expfog) self.qualifyingEndBlimpFlightComplete=False self.qualifyingResultsDisplayComplete=False self.gearIndicator=GearIndicator() self.gearIndicator.setGear(Gearbox.low)
def start(self): self.textures.load_all() self.char = Actor("res/models/ralph", {"run":"res/models/ralph-run", "walk":"res/models/ralph-walk"}) self.char.pose('walk', 5) self.char.setScale(.2) self.char.setH(180) self.gui.buttons.add_button(name = 'Exit', text = ("Exit", "Exit", "Exit", "disabled"), pos = (1.23, 0, -0.95), scale = 0.07, command=self.stop) self.gui.screen_texts.add_text(name = 'status', text = 'Hello! Suber was started!', pos = (-1.3, -0.95), scale = 0.07) #self.gui.entries.add_entry(name = 'console',text = "" , #pos = (-1.29, 0, -0.85), #scale=0.07,command=self.cmd_handler.cmd_handle, #initialText="", width = 37, numLines = 1,focus=0) self.gui.screen_texts.add_text(name = 'help', text = 'F5 - create world\nm - toggle map\nF1 - toggle'+\ ' help\nEsc - exit\nF10 - render info\n'+\ 'F2/F3 - 1st/3d person camera\n'+\ 'F4 - toggle fly/terrain\n'+\ 'F9 - Cam disable\n'+\ 'F8 - Toggle Collisions\n'+\ 'F11/F12 - toggle polygons / disable textures', pos = (-1, 0.8), scale = 0.07) self.gui.hotkeys.accept('f1', self.toggle_help) self.gui.screen_images.add_image('sight', self.textures['sight'], scale = 0.05, pos = (0, 0, 0)) self.gui.screen_images['sight'].setTransparency(TransparencyAttrib.MAlpha) plight = PointLight('plight') sun = self.gui.render.attachNewNode(plight) sun.setPos(-32768, 32768, 20000) self.gui.render.setLight(sun) alight = AmbientLight('alight') alight.setColor(VBase4(0.5, 0.5, 0.5, 1)) alnp = self.gui.render.attachNewNode(alight) self.gui.render.setLight(alnp) color = (0.28125, 0.53125, 0.80859375) fog = Fog("A linear-mode Fog node") fog.setColor(*color) fog.setLinearFallback(0,500,550) self.gui.camera.attachNewNode(fog) color = (0.28125, 0.53125, 0.80859375) self.gui.render.setFog(fog) self.gui.setBackgroundColor(*color) self.cam_manager = CamManager(self) self.move_avatar = MoveAvatar(self) self.vox_config = VoxConfig() self.coord_block = CoordBlock(self, self.vox_config) self.vox_params = VoxParams() self.vox_params.gui = self.gui self.vox_params.avatar = self.cam_manager.node self.vox_params.status = self.write self.vox_params.root_node = self.gui.render self.vox_params.chunks_tex = self.textures['world_blocks'] self.vox_params.get_coord_block = self.coord_block self.vox_params.tree_tex = self.textures['tree'] self.vox_params.water_tex = self.textures['water'] self.vox_params.leafModel = self.gui.loader.loadModel("res/models/shrubbery") self.vox_params.leafTex = self.textures['leaf'] self.vox_params.fog = fog self.world = World(self.vox_config, self.vox_params) self.collision_avatar = CollisionAvatar(self) #self.vox_params.sun = sun self.gui.taskMgr.setupTaskChain('Ticker', tickClock = True) self.gui.taskMgr.doMethodLater(0.05, self.ticker, 'taskTicker', taskChain = 'Ticker') self.gui.start()
class Environment: def __init__(self): self.cameraPos = base.camera.getPos() # create a heightfield self.heightfield = heightfield.Heightfield(base.camera) if USELIGHT: self.setupLight() if USESKY: self.setupSky() if USEFOG: self.setupFog() if USESOUND: self.setupSound() if USERAIN: from src.rain import rainClass self.setupRain() if USENIGHT: self.setupNight() def setupLight(self): self.ambientLight = AmbientLight("ambientLight") self.ambientLight.setColor(Vec4(0.1, 0.1, 0.1, 1)) self.ambientLightNP = render.attachNewNode(self.ambientLight.upcastToPandaNode()) render.setLight(self.ambientLightNP) self.dlight = DirectionalLight("dlight") self.dlight.setColor(VBase4(0.8, 0.8, 0.5, 1)) self.dlnp = render.attachNewNode(self.dlight.upcastToPandaNode()) self.dlnp.setHpr(0, -30, 0) render.setLight(self.dlnp) """ # First we create an ambient light. All objects are affected by ambient # light equally #Create and name the ambient light self.ambientLight = AmbientLight( "ambientLight" ) #Set the color of the ambient light self.ambientLight.setColor( VBase4( 0.1, 0.1, 0.1, 1 ) ) #Make the light affect render (ie everything) render.setLight(render.attachNewNode(self.ambientLight.upcastToPandaNode())) """ def setupSky(self): self.skyNP = loader.loadModel("data/models/sky.bam.pz") self.skyNP.reparentTo(render) self.skyNP.setScale(4000, 4000, 1000) self.skyNP.setPos(0, 0, 0) self.skyNP.setTexture(loader.loadTexture("data/textures/clouds.png")) self.skyNP.setShader(loader.loadShader("data/sky.sha")) """self.skyFogNP = loader.loadModel( 'data/models/sphere.egg' ) self.skyFogNP.reparentTo( base.camera ) self.skyFogNP.setTwoSided( True ) self.skyFogNP.setScale( 10 ) self.skyFogNP.setPos( Vec3(0,0,4) ) self.skyFogNP.setTransparent( True )""" sky = Vec4(0.25, 0.5, 1.0, 0.0) # r, g, b, skip sky2 = Vec4(1.0, 1.0, 1.0, 0.0) clouds = Vec4(0.004, 0.002, 0.008, 0.010) # vx, vy, vx, vy self.skyNP.setShaderInput("sky", sky) self.skyNP.setShaderInput("sky2", sky2) self.skyNP.setShaderInput("clouds", clouds) render.setShaderInput("time", 0) def setupFog(self): """defaultExpFogColor = (0.33, 0.5, 1.0) self.expFog = Fog("exponentialFog") self.expFog.setColor(*defaultExpFogColor) self.expFog.setExpDensity(DEFAULTFOG) render.setFog(self.expFog)""" defaultLinFogColor = (0.165, 0.25, 0.5) self.linFog = Fog("linearFog") self.linFog.setColor(*defaultLinFogColor) self.linFog.setLinearRange(0, linFogMinRange + linFogVarianceRange) self.linFog.setLinearFallback(30, 60, 240) base.camera.attachNewNode(self.linFog) render.setFog(self.linFog) base.setBackgroundColor(defaultLinFogColor) def setupSound(self): self.mySound1 = loader.loadSfx("data/sounds/rainshower.wav") self.mySound1.setLoop(True) self.mySound1.play() def setupRain(self): base.enableParticles() self.rain = rainClass() self.rain.reparentTo(base.camera) self.rain.setScale(200) self.rain.start(render) def setupNight(self): taskMgr.doMethodLater(0.05, self.dayNightCycle, "UpdateDayNight") taskMgr.doMethodLater(0.05, self.updateScene, "updateScene") def dayNightCycle(self, task): # print "dayNight", rainStrenght if USERAIN: rainStrenght = ( RAINCYCLEFUNC ** ((math.sin(time.time() / (DAYNIGHTCYCLETIME / 24.0)) + 1.0) / 2.0) - 1.0 ) / (RAINCYCLEFUNC - 1.0) self.rain.particle.setBirthRate(max(rainStrenght, 0.01)) sunPos = time.time() / (DAYNIGHTCYCLETIME / (math.pi * 2)) % (math.pi * 2) dayNight = (math.sin(sunPos) + 1.0) / 2.0 # dayNight = (DAYNIGHTCYCLEFUNC**dayNight-1.0)/(DAYNIGHTCYCLEFUNC-1.0) if USELIGHT: # print dayNight c = (dayNight) / 1.5 + 0.1 # print dayNight, c [commented by Finn] aLightCol = Vec4(c, c, c, 1) # self.ambientLight.setColor( aLightCol ) self.dlnp.setHpr(0, (sunPos / (2 * math.pi) - 0.5) * 360, 0) # Time for clouds shader if USESKY: render.setShaderInput("time", task.time / 4.0) # dayNight = 1.0 # color for clouds & fog # dayNight = ( math.sin(time.time()/DAYNIGHTCYCLETIME) + 1.0 ) / 2.0 # 0.0 for night, 1.0 for day sky = Vec4(dayNight / 4.0, dayNight / 2.0, dayNight, 0.0) # r, g, b, skip sky2 = Vec4(dayNight, dayNight, dayNight, 0.0) # set colors self.skyNP.setShaderInput("sky", sky) self.skyNP.setShaderInput("sky2", sky2) if USEFOG: # expFogColor = dayNight/3.0,dayNight/2.0,dayNight # self.expFog.setColor( *expFogColor ) # self.expFog.setExpDensity(DEFAULTFOG*(NIGHTFOGMULTIPLIER-dayNight*(NIGHTFOGMULTIPLIER-1.0))) linFogColor = dayNight / 3.0, dayNight / 2.0, dayNight self.linFog.setColor(*linFogColor) fogRange = linFogMinRange + linFogVarianceRange * dayNight self.linFog.setLinearRange(fogRange / 4.0, fogRange) self.linFog.setLinearFallback(fogRange / 8.0, fogRange / 4.0, fogRange) base.setBackgroundColor(linFogColor) return Task.again def updateScene(self, task): # set position of the particle system if USERAIN: self.rain.setPos(base.camera.getPos() + Vec3(0, 0, 200)) return Task.cont
class CogdoMazeGame(DirectObject): """ Handles the visuals/looks of the cogdo maze game """ notify = directNotify.newCategory("CogdoMazeGame") UPDATE_TASK_NAME = "CogdoMazeGameUpdate" def __init__(self, distGame): self.distGame = distGame def load(self): self.maze = Maze(CogdoMazeGameGlobals.TempMazeFile) #self.maze.maze.setColorScale(0.0, 0, 5.0, 1.0) self.maze.setScale(2, 1.75) self.guiMgr = CogdoMazeGuiManager(self.maze) self.audioMgr = CogdoMazeAudioManager() self.toonId2Door = {} self.keyIdToKey = {} self.players = [] self.toonId2Player = {} self.lockId2Lock = {} self.localPlayer = CogdoMazeLocalPlayer(len(self.players), base.localAvatar, self, self.guiMgr) self._addPlayer(self.localPlayer) # TEMP... self.sprites = loader.loadModel("cogdominium/mazeSprites.egg") # Create door pos = self.maze.tile2world(int(self.maze.width / 2), self.maze.height - 1) gridPos = self.maze.world2tile(pos[0], pos[1]) # TEMP openDoorModel = self.sprites.find("**/door_open") openDoorModel.setScale(8) openDoorModel.setZ(0.25) closedDoorModel = self.sprites.find("**/door_closed") closedDoorModel.setScale(8) closedDoorModel.setZ(0.25) self.door = CogdoMazeDoor(closedDoorModel, openDoorModel) self.door.setPosition(pos[0], pos[1] - 0.05) self.door.offstage() self.guiMgr.mazeMapGui.addDoor(gridPos[0], gridPos[1], VBase4(1, 1, 1, 1)) # load key model, keys will be placed when everyone's there self.fuseModels = ( self.sprites.find("**/fuse_white"), self.sprites.find("**/fuse_blue"), self.sprites.find("**/fuse_yellow"), self.sprites.find("**/fuse_red"), ) for fuse in self.fuseModels: fuse.setScale(2) fuse.setBillboardPointEye() self.fuseBoxModels = ( (self.sprites.find("**/fusebox_white"), self.sprites.find("**/fusebox_white_plugged")), (self.sprites.find("**/fusebox_blue"), self.sprites.find("**/fusebox_blue_plugged")), (self.sprites.find("**/fusebox_yellow"), self.sprites.find("**/fusebox_yellow_plugged")), (self.sprites.find("**/fusebox_red"), self.sprites.find("**/fusebox_red_plugged")), ) for fuseBox in self.fuseBoxModels: fuseBox[0].setScale(4) fuseBox[1].setScale(4) #self._initFog() self.accept(self.distGame.getRemoteActionEventName(), self.handleRemoteAction) def unload(self): self.__stopUpdateTask() self.ignoreAll() #self._destroyFog() self.maze.destroy() del self.maze self.door.destroy() del self.door for key in self.keyIdToKey.values(): key.destroy() del self.keyIdToKey self.audioMgr.destroy() del self.audioMgr self.guiMgr.destroy() del self.guiMgr self.sprites.removeNode() del self.sprites del self.players del self.toonId2Player del self.localPlayer def _initFog(self): self.fog = Fog("MazeFog") self.fog.setColor(VBase4(0.3, 0.3, 0.3, 1.0)) self.fog.setLinearRange(0.0, 100.0) self._renderFog = render.getFog() render.setFog(self.fog) def _destroyFog(self): render.clearFog() del self.fog del self._renderFog def onstage(self): self.door.onstage() self.maze.onstage() self.placePlayer(self.localPlayer) self.localPlayer.ready() self.localPlayer.onstage() def offstage(self): self.maze.offstage() self.door.offstage() self.localPlayer.offstage() def ready(self): # Initialize remote players for avId in self.distGame.remoteAvIdList: toon = self.distGame.getAvatar(avId) if toon is not None: player = CogdoMazePlayer(len(self.players), toon) self._addPlayer(player) self.placePlayer(player) player.ready() assert len(self.distGame.lockInfoList) <= CogdoMazeGameGlobals.LockColors # Initialize locks and keys for i in range(len(self.distGame.lockInfoList)): lockInfo = self.distGame.lockInfoList[i] toon = base.cr.doId2do[lockInfo.toonId] color = CogdoMazeGameGlobals.LockColors[i] #toon.style.getHeadColor() pos = self.maze.tile2world(lockInfo.tileX, lockInfo.tileY) player = self.toonId2Player[lockInfo.toonId] # Create and place locks lock = CogdoMazeLock(i, lockInfo.toonId, self.fuseBoxModels[i][0], self.fuseBoxModels[i][1], color, pos[0], pos[1] + 1) self.door.addLock(lock) self.guiMgr.mazeMapGui.addLock(lockInfo.tileX, lockInfo.tileY, color) # Create and place keys key = CogdoMazeKey(lockInfo.toonId, self.fuseModels[i], color) self.keyIdToKey[key.id] = key lock.setKey(key) player.holdKey(key) if toon == self.localPlayer.toon: self.lockColorIndex = i def start(self): self.accept(self.door.enterCollisionEventName, self.handleDoorCollision) for lock in self.door.getLocks(): self.accept(lock.enterCollisionEventName, self.handleLockCollision) self.__startUpdateTask() self.localPlayer.enable() if __debug__: self.acceptOnce("escape", self.distGame.d_requestExit) self.acceptOnce("home", self.guiMgr.revealMazeMap) self.guiMgr.displayNotification("Find the %s fusebox!" % CogdoMazeGameGlobals.LockNames[self.lockColorIndex]) self.audioMgr.playMusic("normal") def exit(self): if __debug__: self.ignore("escape") self.ignore("home") self.ignore(self.door.enterCollisionEventName) for lock in self.door.getLocks(): self.ignore(lock.enterCollisionEventName) self.__stopUpdateTask() self.localPlayer.disable() def _addPlayer(self, player): self.players.append(player) self.toonId2Player[player.toon.doId] = player self.guiMgr.mazeMapGui.addPlayer(0, 0, player.toon.style.getHeadColor()) def _removePlayer(self, player): self.players.remove(player) self.players.remove(player.toon.doId) def __startUpdateTask(self): self.__stopUpdateTask() taskMgr.add(self.__updateTask, CogdoMazeGame.UPDATE_TASK_NAME, 45) def __stopUpdateTask(self): taskMgr.remove(CogdoMazeGame.UPDATE_TASK_NAME) def __updateTask(self, task): self.localPlayer.update() for player in self.players: curTX, curTY = self.maze.world2tile(player.toon.getX(), player.toon.getY()) self.guiMgr.updateMazeMapPlayer(player.id, curTX, curTY) return Task.cont def placePlayer(self, player): i = self.distGame.avIdList.index(player.toon.doId) pos = self.maze.tile2world(int(self.maze.width / 2), 2) player.toon.setPos( pos[0] + i * self.maze.cellWidth, pos[1], 0 ) def handleRemoteAction(self, action, data): if action == CogdoMazeGameGlobals.GameActions.Unlock: self.toonUnlocks(data) if action == CogdoMazeGameGlobals.GameActions.RevealDoor: self.toonRevealsDoor(data) if action == CogdoMazeGameGlobals.GameActions.RevealLock: self.toonRevealsLock(data) elif action == CogdoMazeGameGlobals.GameActions.GameOver: self.distGame.gameOver() def toonRevealsDoor(self, toonId): self.door.revealed = True message = None nextMessage = None if toonId == self.localPlayer.toon.doId: message = "You found the elevator door!" if self.localPlayer.hasKey(): nextMessage = "Find the %s fusebox\nto help open the elevator." % CogdoMazeGameGlobals.LockNames[self.lockColorIndex] else: toon = self.distGame.getAvatar(toonId) message = "%s found the elevator door!" % toon.getName() if message is not None: self.guiMgr.displayNotification(message, nextMessage) def toonRevealsLock(self, toonId): if toonId == self.localPlayer.toon.doId: self.guiMgr.displayNotification("Someone found your fusebox!", "Go to the %s fusebox!" % CogdoMazeGameGlobals.LockNames[self.lockColorIndex]) def toonEntersDoor(self, toonId): player = self.toonId2Player[toonId] player.disable() self.door.playerEntersDoor(player) message = None if self.door.getPlayerCount() == len(self.players): message = "" else: message = "Waiting for %d toons to get to elevator door..." % (len(self.players) - self.door.getPlayerCount()) if message is not None: self.guiMgr.displayNotification(message) def toonUnlocks(self, toonId): player = self.toonId2Player[toonId] self.door.unlock(player.getKey().lock.id) key = self.toonId2Player[toonId].dropKey() key.offstage() if player == self.localPlayer: self.audioMgr.playSfx("fusePlaced") if not self.door.isLocked(): self.door.open() self.audioMgr.playSfx("doorOpen") message = None nextMessage = None if not self.door.isLocked(): message = "All the fuseboxes are fixed!" nextMessage = "Find the elevator door!" elif self.door.isLocked() and player == self.localPlayer: message = "Help your friends find the other fuseboxes!" else: if player == self.localPlayer: message = "Good job! Now, find the exit!" #elif self.localPlayer.getKey() == key: #message = "[name] found your fusebox! Go to the [color] fusebox!" if message is not None: self.guiMgr.displayNotification(message, nextMessage) def handleLockCollision(self, collEntry): assert self.notify.debugCall() intoNodePath = collEntry.getIntoNodePath() intoName = intoNodePath.getName() nameParts = intoName.split("-") assert len(nameParts) > 1 id = int(nameParts[1]) lock = self.door.getLock(id) if self.localPlayer.hasKey(): key = self.localPlayer.getKey() if lock == key.lock: self.toonUnlocks(self.localPlayer.toon.doId) self.distGame.d_sendRequestAction(CogdoMazeGameGlobals.GameActions.Unlock, id) else: self.toonRevealsLock(lock.toonId) self.distGame.d_sendRequestAction(CogdoMazeGameGlobals.GameActions.RevealLock, lock.toonId) def handleDoorCollision(self, collEntry): assert self.notify.debugCall() if not self.door.revealed: if self.localPlayer.hasKey(): self.toonRevealsDoor(self.localPlayer.toon.doId) self.distGame.d_sendRequestAction(CogdoMazeGameGlobals.GameActions.RevealDoor, 0) if not self.localPlayer.hasKey(): self.toonEntersDoor(self.localPlayer.toon.doId) self.distGame.d_sendRequestAction(CogdoMazeGameGlobals.GameActions.EnterDoor, 0) def doMazeCollisions(self, oldPos, newPos): # we will calculate an offset vector that # keeps the toon out of the walls offset = newPos - oldPos # toons can only get this close to walls WALL_OFFSET = 1. # make sure we're not in a wall already curX = oldPos[0]; curY = oldPos[1] curTX, curTY = self.maze.world2tile(curX, curY) assert(not self.maze.collisionTable[curTY][curTX]) def calcFlushCoord(curTile, newTile, centerTile): # calculates resulting one-dimensional coordinate, # given that the object is moving from curTile to # newTile, where newTile is a wall EPSILON = 0.01 if newTile > curTile: return ((newTile-centerTile)*self.maze.cellWidth)\ -EPSILON-WALL_OFFSET else: return ((curTile-centerTile)*self.maze.cellWidth)+WALL_OFFSET offsetX = offset[0]; offsetY = offset[1] WALL_OFFSET_X = WALL_OFFSET if offsetX < 0: WALL_OFFSET_X = -WALL_OFFSET_X WALL_OFFSET_Y = WALL_OFFSET if offsetY < 0: WALL_OFFSET_Y = -WALL_OFFSET_Y # check movement in X direction newX = curX + offsetX + WALL_OFFSET_X; newY = curY newTX, newTY = self.maze.world2tile(newX, newY) if newTX != curTX: # we've crossed a tile boundary if self.maze.collisionTable[newTY][newTX]: # there's a wall # adjust the X offset so that the toon # hits the wall exactly offset.setX(calcFlushCoord(curTX, newTX, self.maze.originTX)-curX) newX = curX; newY = curY + offsetY + WALL_OFFSET_Y newTX, newTY = self.maze.world2tile(newX, newY) if newTY != curTY: # we've crossed a tile boundary if self.maze.collisionTable[newTY][newTX]: # there's a wall # adjust the Y offset so that the toon # hits the wall exactly offset.setY(calcFlushCoord(curTY, newTY, self.maze.originTY)-curY) # at this point, if our new position is in a wall, we're # running right into a protruding corner: # # \ # ### # ### # ### # offsetX = offset[0]; offsetY = offset[1] newX = curX + offsetX + WALL_OFFSET_X newY = curY + offsetY + WALL_OFFSET_Y newTX, newTY = self.maze.world2tile(newX, newY) if self.maze.collisionTable[newTY][newTX]: # collide in only one of the dimensions cX = calcFlushCoord(curTX, newTX, self.maze.originTX) cY = calcFlushCoord(curTY, newTY, self.maze.originTY) if (abs(cX - curX) < abs(cY - curY)): offset.setX(cX - curX) else: offset.setY(cY - curY) return oldPos + offset
class environmentClass: def __init__( self, cameraPos, heightfield ): self.cameraPos = cameraPos self.heightfield = heightfield if USELIGHT: self.setupLight() if USESKY: self.setupSky() if USEFOG: self.setupFog() if USESOUND: self.setupSound() if USERAIN: self.setupRain() #taskMgr.doMethodLater(DAYNIGHTCYCLETIME/60.0, self.dayNightCycle, 'UpdateDayNight') taskMgr.doMethodLater(0.1, self.dayNightCycle, 'UpdateDayNight') taskMgr.doMethodLater(0.1, self.updateScene, 'updateScene' ) def setupSound( self ): self.mySound1 = loader.loadSfx("data/sounds/rainshower.wav") self.mySound1.setLoop(True) self.mySound1.play() def setupSky( self ): self.skyNP = loader.loadModel( 'data/models/sky.bam.pz' ) self.skyNP.reparentTo( render ) self.skyNP.setScale( 4000, 4000, 1000 ) self.skyNP.setPos( 0, 0, 0 ) self.skyNP.setTexture( loader.loadTexture( 'data/textures/clouds.png' ) ) self.skyNP.setShader( loader.loadShader( 'data/sky.sha' ) ) '''self.skyFogNP = loader.loadModel( 'data/models/sphere.egg' ) self.skyFogNP.reparentTo( base.camera ) self.skyFogNP.setTwoSided( True ) self.skyFogNP.setScale( 10 ) self.skyFogNP.setPos( Vec3(0,0,4) ) self.skyFogNP.setTransparent( True )''' sky = Vec4( 0.25, 0.5, 1.0, 0.0 ) # r, g, b, skip sky2 = Vec4( 1.0, 1.0, 1.0, 0.0 ) clouds = Vec4( 0.004, 0.002, 0.008, 0.010 ) # vx, vy, vx, vy self.skyNP.setShaderInput( 'sky', sky ) self.skyNP.setShaderInput( 'sky2', sky2 ) self.skyNP.setShaderInput( 'clouds', clouds ) render.setShaderInput( 'time', 0 ) def setupLight( self ): #Default lightAttrib with no lights #self.lightAttrib = LightAttrib.makeAllOff() # First we create an ambient light. All objects are affected by ambient # light equally #Create and name the ambient light self.ambientLight = AmbientLight( "ambientLight" ) #Set the color of the ambient light self.ambientLight.setColor( Vec4( .1, .1, .1, 1 ) ) self.alnp = render.attachNewNode(self.ambientLight) render.setLight(self.alnp) self.heightfield.mHeightFieldNode.setLightOff() self.ambientLight2 = AmbientLight( "ambientLight2" ) #Set the color of the ambient light self.ambientLight2.setColor( Vec4( .1, .1, .1, 1 ) ) self.al2np = render.attachNewNode(self.ambientLight2) self.heightfield.mHeightFieldNode.setLight(self.al2np) self.dlight = DirectionalLight('dlight') self.dlight.setColor(VBase4(1.0, 1.0, 0.6, 1)) self.dlnp = render.attachNewNode(self.dlight.upcastToPandaNode()) self.dlnp.setHpr(-90, -30, 0) self.heightfield.mHeightFieldNode.setLight(self.dlnp) # Now we create a spotlight. Spotlights light objects in a given cone # They are good for simulating things like flashlights self.spotlight = Spotlight( "spotlight" ) self.spotlight.setColor( Vec4( .9, .9, .9, 1 ) ) #The cone of a spotlight is controlled by it's lens. This creates the lens self.spotlight.setLens( PerspectiveLens() ) #This sets the Field of View (fov) of the lens, in degrees for width and #height. The lower the numbers, the tighter the spotlight. self.spotlight.getLens().setFov( 30, 30 ) # Attenuation controls how the light fades with distance. The numbers are # The three values represent the three constants (constant, linear, and # quadratic) in the internal lighting equation. The higher the numbers the # shorter the light goes. self.spotlight.setAttenuation( Vec3( 0.0, 0.0075, 0.0 ) ) # This exponent value sets how soft the edge of the spotlight is. 0 means a # hard edge. 128 means a very soft edge. self.spotlight.setExponent( 60.0 ) # Unlike our previous lights, the spotlight needs a position in the world # We are attaching it to the camera so that it will appear is if we are # holding a flashlight, but it can be attached to any NodePath # # When attaching a spotlight to a NodePath, you must use the # upcastToLensNode function or Panda will crash #camera.attachNewNode( self.spotlight.upcastToLensNode() ) self.spnp = camera.attachNewNode( self.spotlight.upcastToLensNode() ) render.setLight(self.spnp) self.heightfield.mHeightFieldNode.setLight(self.spnp) #self.lightAttrib = self.lightAttrib.addLight( self.spotlight ) #Finally we set the light attrib to a node. In this case we are using render #so that the lights will effect everything, but you could put it on any #part of the scene #render.node().setAttrib( self.lightAttrib ) # Create and start interval to spin the lights, and a variable to # manage them. #self.pointLightsSpin = self.pointLightHelper.hprInterval(6, Vec3(360, 0, 0)) #self.pointLightsSpin.loop() def setupFog( self ): '''defaultExpFogColor = (0.33, 0.5, 1.0) self.expFog = Fog("exponentialFog") self.expFog.setColor(*defaultExpFogColor) self.expFog.setExpDensity(DEFAULTFOG) render.setFog(self.expFog)''' defaultLinFogColor = (0.33, 0.5, 1.0) self.linFog = Fog("linearFog") self.linFog.setColor(*defaultLinFogColor) self.linFog.setLinearRange(0, linFogMinRange + linFogVarianceRange) self.linFog.setLinearFallback(30, 60, 240) base.camera.attachNewNode(self.linFog) render.setFog(self.linFog) base.setBackgroundColor( defaultLinFogColor ) def setupRain( self ): base.enableParticles() self.rain = rainClass() self.rain.reparentTo( base.camera ) #self.rain.setPos( 0, 0, 5 ) self.rain.setScale( 200 ) #self.rain.particle.setPoolSize( 8192 ) #self.rain.particle.setBirthRate( 2.000 ) #self.rain.particle.renderer.setHeadColor(Vec4(1.00, 1.00, 1.00, 0.8)) #self.rain.particle.renderer.setTailColor(Vec4(1.00, 1.00, 1.00, 0.2)) self.rain.start( render ) def dayNightCycle( self, task ): #print "dayNight", rainStrenght if USERAIN: rainStrenght = (RAINCYCLEFUNC**((math.sin(time.time()/(DAYNIGHTCYCLETIME/24.))+1.0)/2.0)-1.0)/(RAINCYCLEFUNC-1.0) self.rain.particle.setBirthRate( max( rainStrenght, 0.01 ) ) sunPos = time.time()/(DAYNIGHTCYCLETIME/(math.pi*2))%(math.pi*2) dayNight = (math.sin(sunPos)+1.0)/2.0 dayNight = (DAYNIGHTCYCLEFUNC**dayNight-1.0)/(DAYNIGHTCYCLEFUNC-1.0) if USELIGHT: #print dayNight c = (dayNight)/1.2 + 0.01 #print dayNight, c [commented by Finn] aLightCol = Vec4( c, c, c, 1 ) self.ambientLight.setColor( aLightCol ) if abs(sunPos/math.pi-1) < 0.5: self.dlnp.setHpr(-90, 180 + (dayNight-0.3) * 108, 0) else: self.dlnp.setHpr(-90, 0 - (dayNight-0.3) * 108, 0) # Time for clouds shader if USESKY: render.setShaderInput( 'time', task.time/4.0 ) #dayNight = 1.0 # color for clouds & fog #dayNight = ( math.sin(time.time()/DAYNIGHTCYCLETIME) + 1.0 ) / 2.0 # 0.0 for night, 1.0 for day sky = Vec4( dayNight/4.0, dayNight/2.0, dayNight, 0.0 ) # r, g, b, skip sky2 = Vec4( dayNight, dayNight, dayNight, 0.0 ) # set colors self.skyNP.setShaderInput( 'sky', sky ) self.skyNP.setShaderInput( 'sky2', sky2 ) if USEFOG: #expFogColor = dayNight/3.0,dayNight/2.0,dayNight #self.expFog.setColor( *expFogColor ) #self.expFog.setExpDensity(DEFAULTFOG*(NIGHTFOGMULTIPLIER-dayNight*(NIGHTFOGMULTIPLIER-1.0))) linFogColor = dayNight/3.0,dayNight/2.0,dayNight self.linFog.setColor( *linFogColor ) fogRange = linFogMinRange + linFogVarianceRange*dayNight self.linFog.setLinearRange( fogRange/4., fogRange ) self.linFog.setLinearFallback(fogRange/8., fogRange/4., fogRange) base.setBackgroundColor( linFogColor ) return Task.again def updateScene( self, task ): # set position of the particle system if USERAIN: self.rain.setPos( base.camera.getPos() + Vec3( 0,0,200) ) return Task.cont