Example #1
0
class SpotLight:
    """Creates a simple spot light"""
    def __init__(self, manager, xml):
        self.light = PSpotLight('slight')
        lens = PerspectiveLens()
        self.light.setLens(lens)
        self.lightNode = render.attachNewNode(self.light)

        self.reload(manager, xml)

    def reload(self, manager, xml):
        color = xml.find('color')
        if color != None:
            self.light.setColor(
                VBase4(float(color.get('r')), float(color.get('g')),
                       float(color.get('b')), 1.0))

        pos = xml.find('pos')
        if pos != None:
            self.lightNode.setPos(render, float(pos.get('x')),
                                  float(pos.get('y')), float(pos.get('z')))

        lookAt = xml.find('lookAt')
        if lookAt != None:
            self.lightNode.lookAt(render, float(lookAt.get('x')),
                                  float(lookAt.get('y')),
                                  float(lookAt.get('z')))

    def start(self):
        render.setLight(self.lightNode)

    def stop(self):
        render.clearLight(self.lightNode)
Example #2
0
    def __init__(self, manager, xml):
        self.light = PSpotLight('slight')
        lens = PerspectiveLens()
        self.light.setLens(lens)
        self.lightNode = render.attachNewNode(self.light)

        self.reload(manager, xml)
Example #3
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)
Example #4
0
	def addLight(self, type, tag, pos, color, hpr):
		''' Create a light of the given type and assign the given properties.
			Dynamic class instantantiation is difficult due to the Panda module
			layout so we use conditionals
			TODO - support for attenuation.
		'''
		
		LOG.debug("[GXMgr] Adding light of type %s"%type)
		
		if hasattr(pandac.PandaModules, type):
			LOG.debug("[GXMgr] Found light class - %s"%type)
			
			if (type.lower() == 'ambientlight'):
				from pandac.PandaModules import AmbientLight
				l = AmbientLight(tag)
				if color:
					l.setColor(color)
				lnp = render.attachNewNode(l)
			elif (type.lower() == 'directionallight'):
				from pandac.PandaModules import DirectionalLight
				l = DirectionalLight(tag)
				if color:
					l.setColor(color)
				lnp = render.attachNewNode(l)
				if hpr:
					lnp.setHpr(hpr)
			elif (type.lower() == 'pointlight'):
				from pandac.PandaModules import PointLight
				l = PointLight(tag)
				if color:
					l.setColor(color)
				lnp = render.attachNewNode(l)
				if pos:
					lnp.setPos(pos)
			elif (type.lower() == 'spotlight'):
				from pandac.PandaModules import Spotlight
				l = Spotlight(tag)
				if lens:
					lightLens = PerspectiveLens()
					l.setLens(lightLens)
				if color:
					l.setColor(color)
				lnp = render.attachNewNode(l)
				if hpr:
					lnp.setHpr(hpr)
				if pos:
					lnp.setPos(pos)
			
			self.lightList.append(lnp)
			render.setLight(lnp)
		else:
			LOG.error("[GXMgr] Unknown light class - %s"%type)
Example #5
0
    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")
Example #6
0
 def __init__(self):
     ShowBase.__init__(self)
     resize_window = ConfigVariableBool('viewer-resize-window', '#t')
     if resize_window.getValue():
         self.win_size = (800, 800)
     # Black background
     self.win.setClearColor((0.0, 0.0, 0.0, 1.0))
     # Set up lights.
     self.lights = NodePath("lights")
     # Spotlight. Casts shadows.
     slight = Spotlight("slight")
     slight.setScene(self.render)
     slight.setShadowCaster(True, 2**11, 2**11)
     # Set shadow mask, so we can exclude objects from casting shadows
     self.shadow_mask = BitMask32.bit(2)
     slight.setCameraMask(self.shadow_mask)
     slight.setColor((1.2, 1.2, 1.2, 1.))
     slight.getLens().setFov(45)
     slight.getLens().setNearFar(1, 100)
     slnp = self.lights.attachNewNode(slight)
     slnp.setPos((6, 8, 20))
     slnp.lookAt(0, 0, 0)
     self.render.setLight(slnp)
     # Ambient light.
     alight = AmbientLight("alight")
     a = 0.75
     alight.setColor((a, a, a, 1.0))
     #alight.setColor((0.8, 0.8, 0.8, 1.0))
     alnp = self.lights.attachNewNode(alight)
     self.render.setLight(alnp)
     self.lights.reparentTo(self.render)
     # Set auto shading for shadows
     use_shaders = ConfigVariableBool('viewer-use-shaders', '#t')
     if use_shaders.getValue():
         self.render.setShaderAuto()
     # Set antialiasing on
     self.render.setAntialias(AntialiasAttrib.MAuto)
     # Camera
     self.camera_rot = self.render.attachNewNode("camera_rot")
     self.cameras = self.camera_rot.attachNewNode("cameras")
     self.cameras.setPos(14, 32, 9.)
     self.look_at = self.render.attachNewNode("look_at")
     self.look_at.setPos(Point3(2, 0, 1))
     self.cameras.lookAt(self.look_at)
     self.camera.reparentTo(self.cameras)
     # Adjust the camera's lens
     lens = PerspectiveLens()
     self.camLens = lens
     self.camLens.setNearFar(0.01, 1000.0)
     setlens = ConfigVariableBool('viewer-set-cam-lens', '#t')
     if setlens:
         self.cam.node().setLens(self.camLens)
     #
     # Initialize / set variables
     self.sso = None
     self.ssos = []
     self.cache = None
     self.scene = SSO("scene")
     self.scene.reparentTo(self.render)
     # Key callbacks.
     self.accept("shift-control-escape", self.exit)
     self.accept("escape", self.exit)
     self.accept("0", self.reset_sso)
     self.accept("arrow_left", self.prev)
     self.accept("arrow_right", self.next)
     self.accept("page_down", self.prev, [100])
     self.accept("page_up", self.next, [100])
     self.accept("f1", self.toggle_debug)
     self.accept("o", self.physics_once, extraArgs=[1. / 10])
     self.accept("i", self.physics_once, extraArgs=[1. / 10000])
     # Remove existing keyboard tasks.
     self.mandatory_events = ("window-event", "async_loader_0",
                              "render-texture-targets-changed",
                              "shift-control-escape")
     # Task list: name: (key, args)
     events = {
         "physics": ("p", ),
         "repel": ("t", ),
         "bump": ("f", ),
         "rotate": ("r", 20),
         "rotate90": ("h", ),
         "ss_task": ("s", ),
         "ssa_task": ("w", ),
         "bp": ("b", )
     }
     # Add events
     for key, val in events.iteritems():
         call = [key] + list(val[1:])
         self.accept(val[0], self.toggle_task, call)
     # These are the key events that we will never ignore
     self.permanent_events = self.getAllAccepting()
     # These are the key events that we will never ignore
     self.permanent_tasks = [
         task.getName() for task in self.taskMgr.getAllTasks()
     ]
     self.start_time = -1
     self.old_elapsed = 0
Example #7
0
 def __init__(self):
     super(SimViewer, self).__init__()
     # Make a window.
     size = (700, 520)
     self.create_output(size, "SimViewer")
     self.output.setClearColor((0.0, 0.0, 0.0, 1.0))
     # Lights node
     self.lights = NodePath('lights')
     # Create a spotlight
     slight = Spotlight('slight')
     slight.setScene(self.root)
     slight.setShadowCaster(True, 2**11, 2**11)
     # Set shadow mask, so we can exclude objects from casting shadows
     self.shadow_mask = BitMask32.bit(2)
     slight.setCameraMask(self.shadow_mask)
     c = 1.4
     slight.setColor((c, c, c, 1.0))
     slight.getLens().setNearFar(4, 100)
     slight.getLens().setFov(45)
     slnp = self.lights.attachNewNode(slight)
     slnp.setPos((7, 10, 40))
     slnp.lookAt(2, 0, 1.5)
     self.root.setLight(slnp)
     # Create an ambient light.
     alight = AmbientLight('alight')
     c = 0.6
     alight.setColor((c, c, c, 1.0))
     alnp = self.lights.attachNewNode(alight)
     self.root.setLight(alnp)
     self.lights.reparentTo(self.root)
     # Set auto shading for shadows.
     self.root.setShaderAuto()
     # Set antialiasing on.
     self.root.setAntialias(AntialiasAttrib.MAuto)
     # Camera.
     lens = PerspectiveLens()
     self.lens = lens
     self.lens.setNearFar(0.1, 1000.)
     self.lens.setFov((40, 30))
     self.cameras = self.root.attachNewNode('cameras')
     self.camera = self.make_camera(self.output, lens=self.lens)
     self.camera.setPos(15, 44, 3.)
     self.camera.setPos(15, 35, 15.)
     self.camera.lookAt(0, 0, 1.)
Example #8
0
	def __init__(self, controlScheme, camera, game, xStart = 0, yStart = 0, zStart = 0):
		models = MODELS_PATH + "SleekCraft"
		anims = {}
		Unit.__init__(self, models, anims, "**/CollisionSphere", game, xStart, yStart, zStart)
		
		self.controlScheme = controlScheme
		self.camera = camera
		self.game = game
		
		#set up sounds
		self.thrustSound = game.loader.loadSfx(SFX_PATH + "thrust.wav")
		self.electricSound = game.loader.loadSfx(SFX_PATH + "electricity.wav")
		self.magnetSound = game.loader.loadSfx(SFX_PATH + "magnet.wav")
		
		#set up the collisions in unit
		
		#set up the headlamp specific to the model
		headLampMain = Spotlight('headLampMain')
		#headLampMain.showFrustum()
		headLampMain.setColor(VBase4(1.5, 1.5, 1.5, 1))
		mlens = PerspectiveLens()
		mlens.setNearFar(0.25, 1500)
		headLampMain.setLens(mlens)
		headLampMainnode = self.attachNewNode(headLampMain)
		headLampMainnode.setPos(self.find("**/LightCubeMain").getPos())
		headLampMainnode.setHpr(-180, 0, 0)#reverse completely because our model is backwards
		game.render.setLight(headLampMainnode)
		
		headLampLeft = Spotlight('headLampLeft')
		#headLampLeft.showFrustum()
		headLampLeft.setColor(VBase4(0.6, 0.6, 0.6, 1))
		llens = PerspectiveLens()
		headLampLeft.setLens(llens)
		llens.setNearFar(0.25, 500)
		headLampLeftnode = self.attachNewNode(headLampLeft)
		headLampLeftnode.setPos(self.find("**/LightCubeLeft").getPos())
		headLampLeftnode.setHpr(-105, 0, 0)#reverse completely because our model is backwards
		game.render.setLight(headLampLeftnode)
		
		headLampRight = Spotlight('headLampRight')
		#headLampRight.showFrustum()
		headLampRight.setColor(VBase4(0.6, 0.6, 0.6, 1))
		rlens = PerspectiveLens()
		rlens.setNearFar(0.25, 500)
		headLampRight.setLens(rlens)
		headLampRightnode = self.attachNewNode(headLampRight)
		headLampRightnode.setPos(self.find("**/LightCubeRight").getPos())
		headLampRightnode.setHpr(105, 0, 0)#reverse completely because our model is backwards
		game.render.setLight(headLampRightnode)
		
		self.maxHealth = 50
		self.health = self.maxHealth
		self.collisionAttackPower = 0
		
		#the currently active weapon
		self.currentWeapon = AREA
		
		#the maximum amount of energy available
		self.maxEnergy = 2000
		
		#the amount of energy currently available
		self.energy = self.maxEnergy
		
		#the amount of energy that is restored each second
		self.energyRegen = 300
		
		#the energy cost of attacking with a given weapon for one second
		self.magnetCost = {NARROW:self.energyRegen + 100,
						   AREA:self.energyRegen + 120}
		
		#the strength of a sustained attack per unit of energy used
		self.magnetStrength = {NARROW:2.5, AREA:20}
		
		#the energy cost of a burst attack with a given weapon
		self.burstCost = {NARROW:0, AREA:600}
		
		#the strength of a burst attack with a given weapon
		#(yes, the area value really does have to be this high)
		self.burstStrength = {NARROW:90, AREA:7000}
		
		#the enemy that the narrow weapon has locked on to
		self.target = None
		
		#whether the player was attacking the previous frame; this is used
		#to determine whether to release a large burst or a smaller
		#sustained force
		self.sustainedAttack = False
		
		#action flag
		self.switchPressed = False
		
		self.extraForwardAccel = 2.2
		self.accelMultiplier *= 1.2
		self.maxTurnRate = 720
		
		#self.shooting = False
		
		#used in main to check if the unit can be shot with the narrow attack
		self.shootable = False
		self.immune = False
Example #9
0
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
Example #10
0
terrain.setScale(10)
floorcollider = terrain.find("**/floor_collide")
floorcollider.node().setFromCollideMask(BitMask32.allOff())
floorcollider.node().setIntoCollideMask(FLOOR_MASK)
wallcollider = terrain.find("**/wall_collide")
wallcollider.node().setFromCollideMask(BitMask32.allOff())
wallcollider.node().setIntoCollideMask(WALL_MASK)

#** Here the sentinel - the only collider we put in it is the ray detector (see below)
sentinel = loader.loadModel("frowney")
sentinel.setCollideMask(BitMask32.allOff())
sentinel.reparentTo(render)
sentinel.setPos((7.83, -25.31, 24))
avatar_in_sight = False
# we create a spotlight that will be the sentinel's eye and will be used to fire the inView method
slight = Spotlight('slight')
slight.setColor((1, 1, 1, 1))
lens = PerspectiveLens()
lens.setFar(80)
slight.setLens(lens)
slnp = sentinel.attachNewNode(slight)
render.setLight(slnp)
# this is important: as we said the inView method don't cull geometry but take everything is in sight frustum - therefore to simulate an hide and seek feature we gotta cheat a little: this ray is masked to collide with walls and so if the avatar is behind a wall the ray will be 'deflected' (we'll see how later in the sent_traverse function) - so we know who's behind a wall but we fake we can't see it.
sentraygeom = CollisionRay(0, 0, 0, 0, 1, 0)
sentinelRay = sentinel.attachNewNode(CollisionNode('sentinelray'))
sentinelRay.node().addSolid(sentraygeom)
# we set to the ray a cumulative masking using the or operator to detect either the avatar's body and the wall geometry
sentinelRay.node().setFromCollideMask(SENTINEL_MASK | WALL_MASK)
sentinelRay.node().setIntoCollideMask(BitMask32.allOff())
# we add the ray to the sentinel collider and now it is ready to go
base.cTrav.addCollider(sentinelRay, sentinelHandler)
		drawBody(nodePath,bodydata, pos, vecList, length.getX(),False)
		drawLeaf(nodePath,bodydata, pos,vecList)



        #spin = nodePath.hprInterval(20, Vec3(360,0,0))
        #spin.loop()



alight = AmbientLight('alight')
alight.setColor(Vec4(0.5, 0.5, 0.5, 1))
alnp = render.attachNewNode(alight.upcastToPandaNode())
render.setLight(alnp)

slight = Spotlight('slight')
slight.setColor(Vec4(1, 1, 1, 1))
lens = PerspectiveLens()
slight.setLens(lens)
slnp = render.attachNewNode(slight.upcastToLensNode())
render.setLight(slnp)

slnp.setPos(0, 0,40)

#rotating light to show that normals are calculated correctly
def updateLight(task):
	global slnp
	currPos=slnp.getPos()
	currPos.setX(100*math.cos(task.time)/2)
	currPos.setY(100*math.sin(task.time)/2)
	slnp.setPos(currPos)
Example #12
0
  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")
Example #13
0
    def collectPlayer(self, task):
        '''
        Wait until all players are ready
        '''
        if len(self._players) > 0 and self.player_buttonpressed[0] < task.time:
            if self._players[0].device.boost and self.countdown <= 0:
                loading = False
                for player in self._players:
                    if player.vehicle.model_loading:
                        loading = True
                        break
                self._notify.debug("Loading vehicle: %s" % (loading))
                if not loading:
                    taskMgr.remove("selectVehicle")
                    self.track = trackgen3d.Track3d(1000, 1800, 1600, 1200,
                                                    5)  # len(self._players))
                    self.streetPath = render.attachNewNode(
                        self.track.createRoadMesh())
                    # self.borderleftPath = render.attachNewNode(self.track.createBorderLeftMesh())
                    self.borderleftPath = render.attachNewNode(
                        self.track.createBorderLeftMesh())
                    self.borderrightPath = render.attachNewNode(
                        self.track.createBorderRightMesh())
                    self.borderleftcollisionPath = NodePath(
                        self.track.createBorderLeftCollisionMesh())
                    self.borderrightcollisionPath = NodePath(
                        self.track.createBorderRightCollisionMesh())
                    # #self.borderPath = render.attachNewNode(self.track.createBorderMesh())

                    textures = ["tube", "tube2", "street"]
                    tex = textures[random.randint(0, len(textures) - 1)]
                    roadtex = loader.loadTexture('data/textures/' + tex +
                                                 '.png')
                    bordertex = loader.loadTexture('data/textures/border.png')
                    self.streetPath.setTexture(roadtex)
                    self.borderleftPath.setTexture(bordertex)
                    self.borderrightPath.setTexture(bordertex)

                    # self.streetPath = loader.loadModel('data/models/Street.egg')
                    # self.streetPath = loader.loadModel('data/models/Street.egg')
                    # tex = loader.loadTexture('data/models/StreetTex.png')
                    # self.nodePath.setTexture(tex)

                    self._parent.startGame(self.streetPath,
                                           self.borderleftPath,
                                           self.borderrightPath,
                                           self.track.trackpoints,
                                           self.borderleftcollisionPath,
                                           self.borderrightcollisionPath)
                    return task.done

        for device in self.unusedDevices:
            if device.boost:
                self.countdown = COUNTDOWN_START
                self.player_buttonpressed.append(0)
                self._parent.addPlayer(device)

                # Set the PlayerCam to the Vehicle select menu Node
                vehicleSelectNode = NodePath("VehicleSelectNode")
                self._players[-1].camera.camera.reparentTo(vehicleSelectNode)

                # Light, that casts shadows
                plight = Spotlight('plight')
                plight.setColor(VBase4(10.0, 10.0, 10.0, 1))
                if (base.win.getGsg().getSupportsBasicShaders() != 0):
                    pass
                    # plight.setShadowCaster(True, 2048, 2048)#enable shadows for this light ##TODO wegen Linux

                # Light
                plight.getLens().setFov(80)
                plnp = vehicleSelectNode.attachNewNode(plight)
                plnp.setPos(2, -10, 10)
                plnp.lookAt(0, 0, 0)
                vehicleSelectNode.setLight(plnp)
                # vehicleSelectNode.setShaderAuto()#enable autoshader so we can use shadows

                # Light
                ambilight = AmbientLight('ambilight')
                ambilight.setColor(VBase4(0.2, 0.2, 0.2, 1))
                vehicleSelectNode.setLight(
                    vehicleSelectNode.attachNewNode(ambilight))
                self.platform.instanceTo(
                    vehicleSelectNode)  # Load the platform

                # instance shown text
                self.countdown_node.instanceTo(
                    vehicleSelectNode)  # Instance the Countdown
                self.loading.instanceTo(
                    vehicleSelectNode)  # Show the Loading-Text
                self.attributes.copyTo(vehicleSelectNode).hide()
                self._players[-1].vehicle.model_loading = True

                # start loading the model
                loader.loadModel(self.vehicle_list[0],
                                 callback=self._players[-1].setVehicle)
                self._notify.debug("Loading initial vehicle: %s" %
                                   (self.vehicle_list[0]))
                self.unusedDevices.remove(device)
                self.player_buttonpressed[-1] = task.time + self.KEY_DELAY

                # Add the Skybox
                skybox = loader.loadModel("data/models/skybox.egg")
                t = Texture()
                t.load(PNMImage("data/textures/skybox_hangar.png"))
                skybox.setTexture(t)
                skybox.setBin("background", 1)
                skybox.setDepthWrite(0)
                skybox.setDepthTest(0)
                skybox.setLightOff()
                skybox.setScale(10000)
                skybox.reparentTo(vehicleSelectNode)

        for player in self._players:
            if self.player_buttonpressed[self._players.index(
                    player)] < task.time:
                if player.device.use_item:
                    self.countdown = COUNTDOWN_START
                    self._notify.debug("Removing player: %s" % (player))
                    self.unusedDevices.append(player.device)
                    self.player_buttonpressed.pop(self._players.index(player))
                    self._parent.removePlayer(player)
        return task.cont
Example #14
0
 def __init__(self):
     ShowBase.__init__(self)
     resize_window = ConfigVariableBool('viewer-resize-window', '#t')
     if resize_window.getValue():
         self.win_size = (800, 800)
     # Black background
     self.win.setClearColor((0.0, 0.0, 0.0, 1.0))
     # Set up lights.
     self.lights = NodePath("lights")
     # Spotlight. Casts shadows.
     slight = Spotlight("slight")
     slight.setScene(self.render)
     slight.setShadowCaster(True, 2 ** 11, 2 ** 11)
     # Set shadow mask, so we can exclude objects from casting shadows
     self.shadow_mask = BitMask32.bit(2)
     slight.setCameraMask(self.shadow_mask)
     slight.setColor((1.2, 1.2, 1.2, 1.))
     slight.getLens().setFov(45)
     slight.getLens().setNearFar(1, 100)
     slnp = self.lights.attachNewNode(slight)
     slnp.setPos((6, 8, 20))
     slnp.lookAt(0, 0, 0)
     self.render.setLight(slnp)
     # Ambient light.
     alight = AmbientLight("alight")
     a = 0.75
     alight.setColor((a, a, a, 1.0))
     #alight.setColor((0.8, 0.8, 0.8, 1.0))
     alnp = self.lights.attachNewNode(alight)
     self.render.setLight(alnp)
     self.lights.reparentTo(self.render)
     # Set auto shading for shadows
     use_shaders = ConfigVariableBool('viewer-use-shaders', '#t')
     if use_shaders.getValue():
         self.render.setShaderAuto()
     # Set antialiasing on
     self.render.setAntialias(AntialiasAttrib.MAuto)
     # Camera
     self.camera_rot = self.render.attachNewNode("camera_rot")
     self.cameras = self.camera_rot.attachNewNode("cameras")
     self.cameras.setPos(14, 32, 9.)
     self.look_at = self.render.attachNewNode("look_at")
     self.look_at.setPos(Point3(2, 0, 1))
     self.cameras.lookAt(self.look_at)
     self.camera.reparentTo(self.cameras)
     # Adjust the camera's lens
     lens = PerspectiveLens()
     self.camLens = lens
     self.camLens.setNearFar(0.01, 1000.0)
     setlens = ConfigVariableBool('viewer-set-cam-lens', '#t')
     if setlens:
         self.cam.node().setLens(self.camLens)
     #
     # Initialize / set variables
     self.sso = None
     self.ssos = []
     self.cache = None
     self.scene = SSO("scene")
     self.scene.reparentTo(self.render)
     # Key callbacks.
     self.accept("shift-control-escape", self.exit)
     self.accept("escape", self.exit)
     self.accept("0", self.reset_sso)
     self.accept("arrow_left", self.prev)
     self.accept("arrow_right", self.next)
     self.accept("page_down", self.prev, [100])
     self.accept("page_up", self.next, [100])
     self.accept("f1", self.toggle_debug)
     self.accept("o", self.physics_once, extraArgs=[1. / 10])
     self.accept("i", self.physics_once, extraArgs=[1. / 10000])
     # Remove existing keyboard tasks.
     self.mandatory_events = ("window-event", "async_loader_0",
                              "render-texture-targets-changed",
                              "shift-control-escape")
     # Task list: name: (key, args)
     events = {"physics": ("p",),
               "repel": ("t",),
               "bump": ("f",),
               "rotate": ("r", 20),
               "rotate90": ("h",),
               "ss_task": ("s",),
               "ssa_task": ("w",),
               "bp": ("b",)}
     # Add events
     for key, val in events.iteritems():
         call = [key] + list(val[1:])
         self.accept(val[0], self.toggle_task, call)
     # These are the key events that we will never ignore
     self.permanent_events = self.getAllAccepting()
     # These are the key events that we will never ignore
     self.permanent_tasks = [task.getName()
                             for task in self.taskMgr.getAllTasks()]
     self.start_time = -1
     self.old_elapsed = 0
Example #15
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 )
		
		'''
Example #16
0
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
    def buildSpotlight(self, pos, fov, exponent, casts_shadow, shadow_caster,
                       pitch, near, far, color):
        """
    Builds a Panda3D Spotlight at the specified position with the specified
    field of view and color
    """
        self.light_counter += 1
        light = Spotlight("light%s" % self.light_counter)
        if casts_shadow:
            x, y = shadow_caster
            light.setShadowCaster(True, x, y)
            light.getLens().setFar(far)
        else:
            light.setShadowCaster(False)
            light.getLens().setFar(2)
        light.setColor(VBase4(*color))
        light.getLens().setNear(near)
        lightnp = render.attachNewNode(light)
        lightnp.setPos(*pos)
        lightnp.setP(pitch)
        light.getLens().setFov(fov)

        light.setExponent(exponent)
        return lightnp
 def buildSpotlight(self, pos, fov, exponent, casts_shadow, shadow_caster, pitch, near, far, color):
   """
   Builds a Panda3D Spotlight at the specified position with the specified
   field of view and color
   """
   self.light_counter += 1
   light = Spotlight("light%s" % self.light_counter)
   if casts_shadow:
     x, y = shadow_caster
     light.setShadowCaster(True, x, y)
     light.getLens().setFar(far)
   else:
     light.setShadowCaster(False)
     light.getLens().setFar(2)
   light.setColor(VBase4(*color))
   light.getLens().setNear(near)
   lightnp = render.attachNewNode(light)
   lightnp.setPos(*pos)
   lightnp.setP(pitch)
   light.getLens().setFov(fov)
   
   light.setExponent(exponent)
   return lightnp