Example #1
0
	def init_node_path(self):
		if self.node_path:
			self.parent.node_path_mesh.clearLight(self.node_path)
			self.node_path.remove()
		from pandac.PandaModules import DirectionalLight
		dlight = DirectionalLight('dlight')
		dlight.setColor(VBase4(*[x / 2048.0 for x in self.color] + [1.0]))
		self.node_path = self.parent.node_path_mesh.attachNewNode(dlight)
		self.node_path.setPos(*coords_to_panda(*self.direction.coords))
		self.node_path.lookAt(0,0,0)
		self.parent.node_path_mesh.setLight(self.node_path)
Example #2
0
class DirLight:
    """Creates a simple directional light"""

    def __init__(self, manager, xml):
        self.light = PDirectionalLight("dlight")
        self.lightNode = NodePath(self.light)
        self.lightNode.setCompass()
        if hasattr(self.lightNode.node(), "setCameraMask"):
            self.lightNode.node().setCameraMask(BitMask32.bit(3))

        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(float(pos.get("x")), float(pos.get("y")), float(pos.get("z")))
        else:
            self.lightNode.setPos(0, 0, 0)

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

        lens = xml.find("lens")
        if lens != None and hasattr(self.lightNode.node(), "getLens"):
            if bool(int(lens.get("auto"))):
                self.lightNode.reparentTo(base.camera)
            else:
                self.lightNode.reparentTo(render)
            lobj = self.lightNode.node().getLens()
            lobj.setNearFar(float(lens.get("near", 1.0)), float(lens.get("far", 100000.0)))
            lobj.setFilmSize(float(lens.get("width", 1.0)), float(lens.get("height", 1.0)))
            lobj.setFilmOffset(float(lens.get("x", 0.0)), float(lens.get("y", 0.0)))

        if hasattr(self.lightNode.node(), "setShadowCaster"):
            shadows = xml.find("shadows")
            if shadows != None:
                self.lightNode.node().setShadowCaster(
                    True, int(shadows.get("width", 512)), int(shadows.get("height", 512)), int(shadows.get("sort", -10))
                )
                # self.lightNode.node().setPushBias(float(shadows.get('bias', 0.5)))
            else:
                self.lightNode.node().setShadowCaster(False)

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

    def stop(self):
        render.clearLight(self.lightNode)
Example #3
0
    def __init__( self ):
        DirectObject.__init__( self )
        # Create mouse
        base.disableMouse()
        self.mouse = p3d.Mouse()
        # Create camera
        self.camera = p3d.Camera( pos=(-250, -250, 200), style=
                                  p3d.CAM_USE_DEFAULT | 
                                  p3d.CAM_VIEWPORT_AXES )
        self.camera.Start()
        # Create scene root node
        self.rootNp = render.attachNewNode( 'rootNode' )
        # Create gizmo manager
        self.gizmoMgr = gizmos.Manager( {
            'pos' : gizmos.Translation ( 'pos', self.camera ),
            'rot' : gizmos.Rotation    ( 'rot', self.camera ),
            'scl' : gizmos.Scale       ( 'scl', self.camera )
                            })
        # Create node picker
        self.nodePicker = p3d.MousePicker( 'mouse',
                                           self.camera,
                                           self.rootNp,
                                           fromCollideMask = AXIS_COLLISION_MASK,
                                           #pickTag         = PICK_TAG,
                                           gizmos          = self.gizmoMgr)
        self.nodePicker.Start()
        # Bind node picker events
        #self.accept( 'mouse1', self.StartSelection )
        #self.accept( 'mouse1-up', self.StopSelection )

        # Create gizmo manager mouse picker
        #self.gizmoPicker = p3d.MousePicker( 'mouse', self.camera )
        #self.gizmoPicker.Start()
        # Create some objects
        #grid = DirectGrid( parent=render, planeColor=(0.5, 0.5, 0.5, 0.5) )
        #for i in range( 20 ):
            #ball = loader.loadModel( 'smiley' )
            #ball.setTag( PICK_TAG, '1' )
            #ball.reparentTo( self.rootNp )
            #ball.setPos( random.randint( -30, 30 ) * 2, random.randint( -30, 30 ) * 2, random.randint( -30, 30 ) * 2 )
            #ball.setScale( 10, 10, 10 )
        # Create a light
        dlight = DirectionalLight('dlight')
        dlight.setColor( ( 1, 1, 1, 1 ) )
        dlnp = render.attachNewNode(dlight)
        dlnp.setHpr(0, 0, 0)
        render.setLight(dlnp)
        dlnp.reparentTo( self.camera )
        # Create tasks
        taskMgr.add( self.MouseTask, 'mouseTask' )
        #==
        self.loader = loader
Example #4
0
    def start(self):
        self.resetCamera()
        self.loadPlanet()
        self.loadShips()
        self.loadPlayers()
        self.loadStars()
        self.loadHUD()

        light = DirectionalLight('light')
        light.setDirection(Vec3(-1, .1, -.5))
        light.setColor(Vec4(.7, .6, .6, 0))
        light.setSpecularColor(Vec4(.3, .5, .7, 0))
        lightnode = render.attachNewNode(light)
        render.setLight(lightnode)

        render.setShaderAuto()
        render.setShaderInput('light', lightnode)

        render.setAntialias(AntialiasAttrib.MAuto)

        # TODO: it might be necessary here to check that the task
        # does not already exist in the task manager because the
        # unit tests at the moment call the start method
        # continuously.
        taskMgr.add(self.tick, "gameloop")
        self.time = self.getTime()
        self.registerListeners()
        self.state = Game.STATE_RUNNING

        # Load music
        self.music = loader.loadSfx('MVi - Ilwrath Are Watching.mp3')
        self.music.setLoop(True)
        self.music.setVolume(0.5)
        self.music.play()
Example #5
0
  def __init__(self):
    self.yaw = 0
    self.pitch = 0
    self.roll = 0

    #load headsmall.egg 3d Model
    self.model = loader.loadModel("head.bam")

    # Put her in the scene.
    self.model.reparentTo(render)

    # Location Model
    self.model.setPosHpr(0,0,0,0,0,0)

    # Position Camera
    base.trackball.node().setPos(0, 10, 0)
    self.model.clearColor()

    # Change texture color
    self.model.setColorScale(0.90, 0.55, 0.40, 1.0)

    # Directional light
    self.directionalLight = DirectionalLight('directionalLight')
    self.directionalLight.setColor(Vec4(1, 1, 1, 1))
    self.directionalLightNP = render.attachNewNode(self.directionalLight)
    # This light is facing forwards, away from the camera.
    self.directionalLightNP.setHpr(0, -20, 0)
    render.setLight(self.directionalLightNP)
Example #6
0
  def __init__(self,manager,xml):
    self.light = PDirectionalLight('dlight')
    self.lightNode = NodePath(self.light)
    self.lightNode.setCompass()
    if hasattr(self.lightNode.node(), "setCameraMask"):
      self.lightNode.node().setCameraMask(BitMask32.bit(3))

    self.reload(manager,xml)
Example #7
0
    def __init__(self, manager, xml):
        self.light = PDirectionalLight("dlight")
        self.lightNode = NodePath(self.light)
        self.lightNode.setCompass()
        if hasattr(self.lightNode.node(), "setCameraMask"):
            self.lightNode.node().setCameraMask(BitMask32.bit(3))

        self.reload(manager, xml)
Example #8
0
  def start(self):
    self.resetCamera()
    self.loadPlanet()
    self.loadShips()
    self.loadPlayers()
    self.loadStars()
    self.loadHUD()
    
    light = DirectionalLight('light')
    light.setDirection( Vec3(-1, .1, -.5) )
    light.setColor( Vec4(.7, .6, .6, 0) )
    light.setSpecularColor( Vec4(.3, .5, .7, 0) )
    lightnode = render.attachNewNode(light)
    render.setLight(lightnode)

    render.setShaderAuto()
    render.setShaderInput('light', lightnode)

    render.setAntialias(AntialiasAttrib.MAuto)

    # TODO: it might be necessary here to check that the task
    # does not already exist in the task manager because the
    # unit tests at the moment call the start method
    # continuously.
    taskMgr.add(self.tick, "gameloop")
    self.time = self.getTime()
    self.registerListeners()
    self.state = Game.STATE_RUNNING
    
    # Load music
    self.music = loader.loadSfx('MVi - Ilwrath Are Watching.mp3')
    self.music.setLoop(True)
    self.music.setVolume(0.5)
    self.music.play()    
Example #9
0
    def __init__(self):
        # initialise ODE
        world = OdeWorld()
        #world.setGravity(0.0, 0.0, -9.81)
        world.setGravity(0.0, 0.0, 0.0)
        
        self.grid = DirectGrid(2000, 20, parent=render)
        self.grid.setZ(-0.001)
        setSky("bluesky")

        # lights
        sunlight = DirectionalLight("sun")
        sunlight.setColor(Vec4(1.0, 0.9, 0.8, 1))
        sunnp = render.attachNewNode(sunlight)
        sunnp.setP(-60)
        render.setLight(sunnp)

        alight = AmbientLight("alight")
        alight.setColor(Vec4(0.6, 0.6, 0.8, 1))
        alnp = render.attachNewNode(alight)
        render.setLight(alnp)

        #render.setShaderAuto(True)

        ## initialise physics engine
        #base.enableParticles()

        # load our plane(s)
        base.player = Aeroplane("griffin", world=world)
        base.player_camera = views.PlaneCamera(base.player)
        self.control = controls.PlaneFlight()

        # load some others
        #pirate1 = Aeroplane("griffin")
        #pirate1.node.setPosHpr(-15, -20, 12, -10, -10, 20)

        #pirate2 = Aeroplane("griffin")
        #pirate2.node.setPosHpr(18, -30, 6, 5, -5, -5)

        # set default camera
        base.player.hud = gui.HUD(base.player, base.camera)
        base.player.hud.update()
        self.control.activate()
Example #10
0
    def set_lighting(self):
        dlight = DirectionalLight('dlight')
        dlnp = self.render.attachNewNode(dlight)
        dlnp.setHpr(45,-45,0)
        self.render.setLight(dlnp)

        ambientLight = AmbientLight('ambientLight')
        ambientLight.setColor(VBase4(0.5, 0.5, 0.5, 1))
        ambientLightNP = render.attachNewNode(ambientLight)
        self.render.setLight(ambientLightNP)
Example #11
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 #12
0
    def create(self, lightAttrib):
        #create directional light
        directionalLight = DirectionalLight(self.name)
        directionalLight.setDirection(self.direction)
        directionalLight.setColor(self.color * self.intensity)
        directionalLight.setSpecularColor(Vec4(0.5, 0.5, 0.5, 0.5))
        lightAttrib = lightAttrib.addLight(directionalLight)

        #attach lights to scene graph
        render.attachNewNode(directionalLight)
        self.directionalLight = directionalLight

        return lightAttrib
Example #13
0
class Head3D:
  def __init__(self):
    self.yaw = 0
    self.pitch = 0
    self.roll = 0

    #load headsmall.egg 3d Model
    self.model = loader.loadModel("head.bam")

    # Put her in the scene.
    self.model.reparentTo(render)

    # Location Model
    self.model.setPosHpr(0,0,0,0,0,0)

    # Position Camera
    base.trackball.node().setPos(0, 10, 0)
    self.model.clearColor()

    # Change texture color
    self.model.setColorScale(0.90, 0.55, 0.40, 1.0)

    # Directional light
    self.directionalLight = DirectionalLight('directionalLight')
    self.directionalLight.setColor(Vec4(1, 1, 1, 1))
    self.directionalLightNP = render.attachNewNode(self.directionalLight)
    # This light is facing forwards, away from the camera.
    self.directionalLightNP.setHpr(0, -20, 0)
    render.setLight(self.directionalLightNP)

  def Orientation(self, yaw, pitch, roll = 0):
    self.yaw = yaw
    self.pitch = pitch
    self.roll = roll
    taskMgr.add(self.AddOrientationTask, 'ChangeOrientation')
    taskMgr.step()
    taskMgr.step()

  def AddOrientationTask(self, task):
    self.model.setPosHpr(0,0,0,self.yaw,self.pitch,self.roll)
    return task.done
Example #14
0
    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)
        """
Example #15
0
class MapCreator( DirectObject ):
	def __init__( self ):
		#render.setShaderAuto()
		base.disableMouse()
		
		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)
		
		self.mapBuilder = mapBuilder.MapBuilder()
		self.sectorBuilder = sectorBuilder.SectorBuilder()
		
		render.setLight(self.dlnp)
		self.camera = camera.Camera(self.sectorBuilder.heightfield)
		
		self.step()
	
	def step( self ):
		# render next frame
		taskMgr.step()
Example #16
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 #17
0
 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)
Example #18
0
 def setupLights(self):
     lAttrib = LightAttrib.makeAllOff()
     ambientLight = AmbientLight( "ambientLight" )
     ambientLight.setColor( Vec4(.4, .4, .35, 1) )
     lAttrib = lAttrib.addLight( ambientLight )
     directionalLight = DirectionalLight( "directionalLight" )
     directionalLight.setDirection( Vec3( 0, 8, -2.5 ) )
     directionalLight.setColor( Vec4( 0.9, 0.8, 0.9, 1 ) )
     lAttrib = lAttrib.addLight( directionalLight )
     render.attachNewNode( directionalLight.upcastToPandaNode() ) 
     render.attachNewNode( ambientLight.upcastToPandaNode() ) 
     render.node().setAttrib( lAttrib )
 def create( self, lightAttrib ):
     #create directional light
     directionalLight = DirectionalLight( self.name )
     directionalLight.setDirection( self.direction )
     directionalLight.setColor( self.color * self.intensity )
     directionalLight.setSpecularColor( Vec4(0.5,0.5,0.5,0.5) )
     lightAttrib = lightAttrib.addLight( directionalLight )
     
     #attach lights to scene graph
     render.attachNewNode( directionalLight )
     self.directionalLight = directionalLight
     
     return lightAttrib
Example #20
0
 def __init__( self, *args, **kwargs ):
     p3d.Object.__init__( self, *args, **kwargs )
     
     self._gizmos = {}
     self._activeGizmo = None
     
     # Create gizmo manager mouse picker
     self.picker = p3d.MousePicker( 'mouse', *args, **kwargs )
     self.picker.Start()
     
     # Create a directional light and attach it to the camera so the gizmos
     # don't look flat
     dl = DirectionalLight( 'gizmoManagerDirLight' )
     self.dlNp = self.camera.attachNewNode( dl )
     self.rootNp.setLight( self.dlNp )
Example #21
0
    def setLights(self):
        # Ambient Light
        ambientLight = AmbientLight('ambientLight')
        ambientLight.setColor(Vec4(0.1, 0.1, 0.1, 1))
        ambientLightNP = render.attachNewNode(ambientLight.upcastToPandaNode())
        render.setLight(ambientLightNP)

        # Directional light 01
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLightNP = render.attachNewNode(
            directionalLight.upcastToPandaNode())
        directionalLightNP.setPos(10, -20, 20)
        directionalLightNP.lookAt(0, 0, 0)
        render.setLight(directionalLightNP)

        # Directional light 02
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLightNP = render.attachNewNode(
            directionalLight.upcastToPandaNode())
        directionalLightNP.lookAt(0, 0, 0)
        directionalLightNP.setPos(10, 20, 20)
        render.setLight(directionalLightNP)
Example #22
0
 def createScene(self):
     self._log.debug(u"Creating scene...")
     base.setBackgroundColor(0.3, 0.3, 0.3)
     self.gl_dlight = DirectionalLight('dlight')
     self.gl_dlight.setColor(Vec4(1, 1, 1, 1))
     self.np_dlight = render.attachNewNode(self.gl_dlight)
     #self.np_dlight.setHpr(90, 0, 0)
     self.np_dlight.lookAt(1, 1, -10)
     self.l_marker = loader.loadModel("models/misc/Dirlight")
     self.l_marker.reparentTo(self.np_dlight)
     self.l_marker.setScale(0.1, 0.1, 0.1)
     render.setLight(self.np_dlight)
     render.setTransparency(TransparencyAttrib.MAlpha)
     self._camera_control = CameraHandler()
     self.clearScene()
     self.rotate_light(0)
Example #23
0
 def createScene(self):
     self._log.debug(u"Creating scene...")
     base.setBackgroundColor(0, 0, 0)
     self.gl_dlight = DirectionalLight('dlight')
     self.gl_dlight.setColor(Vec4(1, 1, 1, 1))
     self.np_dlight = render.attachNewNode(self.gl_dlight)
     #self.np_dlight.setHpr(90, 0, 0)
     self.np_dlight.lookAt(1, 1, -10)
     render.setLight(self.np_dlight)
     render.setTransparency(TransparencyAttrib.MAlpha)
     CameraHandler()
     self.surface = None
     self.plane = None
     self.mls_surface = None
     self.bezier_surface = None
     self.point_cloud = None
Example #24
0
	def setupLights(self):
		lAttrib = LightAttrib.makeAllOff()
		ambientLight = AmbientLight( "ambientLight" )
		ambientLight.setColor( Vec4(.6, .6, .55, 1) )
		lAttrib = lAttrib.addLight( ambientLight )
		directionalLight = DirectionalLight( "directionalLight" )
		directionalLight.setDirection( Vec3( 0, 8, -2.5 ) )
		directionalLight.setColor( Vec4( 0.9, 0.8, 0.9, 1 ) )
		lAttrib = lAttrib.addLight( directionalLight )
		#set lighting on teapot so steam doesn't get affected
		#self.t.attachNewNode( directionalLight.upcastToPandaNode() )
		self.t.attachNewNode( directionalLight ) 
		#self.t.attachNewNode( ambientLight.upcastToPandaNode() )
		self.t.attachNewNode( ambientLight) 
		self.t.node().setAttrib( lAttrib )
Example #25
0
 def init_lights(self):
     from pandac.PandaModules import AmbientLight, DirectionalLight
     from pandac.PandaModules import ShadeModelAttrib
     # Set flat shading
     flatShade = ShadeModelAttrib.make(ShadeModelAttrib.MFlat)
     self.nodePath.setAttrib(flatShade)
     # Create directional light
     dlight1 = DirectionalLight('dlight1')
     dlight1.setColor(VBase4(1.0, 1.0, 1.0, 1.0))
     dlnp1 = self.nodePath.attachNewNode(dlight1)
     dlnp1.setHpr(-10, -30, 0)
     self.nodePath.setLight(dlnp1)
     # Create second directional light
     dlight2 = DirectionalLight('dlight2')
     dlight2.setColor(VBase4(0.0, 0.1, 0.2, 1.0))
     dlnp2 = self.nodePath.attachNewNode(dlight2)
     dlnp2.setHpr(170, 0, 0)
     self.nodePath.setLight(dlnp2)
     # Create ambient light
     alight = AmbientLight('alight')
     alight.setColor(VBase4(0.3, 0.3, 0.3, 1.0))
     alnp = self.nodePath.attachNewNode(alight)
     self.nodePath.setLight(alnp)
Example #26
0
 def init_lights(self):
     from pandac.PandaModules import AmbientLight, DirectionalLight
     from pandac.PandaModules import ShadeModelAttrib
     # Set flat shading
     flatShade = ShadeModelAttrib.make(ShadeModelAttrib.MFlat)
     self.nodePath.setAttrib(flatShade)
     # Create directional light
     dlight1 = DirectionalLight('dlight1')
     dlight1.setColor(VBase4(1.0, 1.0, 1.0, 1.0))
     dlnp1 = self.nodePath.attachNewNode(dlight1)
     dlnp1.setHpr(-10, -30, 0)
     self.nodePath.setLight(dlnp1)
     # Create second directional light
     dlight2 = DirectionalLight('dlight2')
     dlight2.setColor(VBase4(0.0, 0.1, 0.2, 1.0))
     dlnp2 = self.nodePath.attachNewNode(dlight2)
     dlnp2.setHpr(170, 0, 0)
     self.nodePath.setLight(dlnp2)
     # Create ambient light
     alight = AmbientLight('alight')
     alight.setColor(VBase4(0.3, 0.3, 0.3, 1.0))
     alnp = self.nodePath.attachNewNode(alight)
     self.nodePath.setLight(alnp)
Example #27
0
# demonstrate growing
last = [0]  # a bit hacky


def grow(task):
    if task.time > last[0] + 1:
        t.grow()
        last[0] = task.time
        # t.leaves.detachNode()
    if last[0] > 10:
        return task.done
    return task.cont
base.taskMgr.add(grow, "growTask")


dlight = DirectionalLight('dlight')

dlnp = render.attachNewNode(dlight)
dlnp.setHpr(0, 0, 0)
render.setLight(dlnp)

alight = AmbientLight('alight')

alnp = render.attachNewNode(alight)
render.setLight(alnp)

# rotating light to show that normals are calculated correctly


def updateLight(task):
    base.camera.setHpr(task.time / 20.0 * 360, 0, 0)
    def __init__(self, filters):
        self.filters = filters
        self.updateTask = None
        self.finalQuad = None

        self.sun = base.cam.attachNewNode('sun')
        loader.loadModel("models/sphere").reparentTo(self.sun)
        self.sun.setScale(0.08)
        self.sun.setTwoSided(True)
        self.sun.setColorScale(1.0, 1.0, 1.0, 1.0, 10001)
        self.sun.setLightOff(1)
        self.sun.setShaderOff(1)
        self.sun.setFogOff(1)
        self.sun.setCompass()
        self.sun.setBin('background', 2)
        self.sun.setDepthWrite(False)
        self.sun.setDepthTest(False)
        # Workaround an annoyance in Panda. No idea why it's needed.
        self.sun.node().setBounds(OmniBoundingVolume())     

        direct = Vec4(2.0, 1.9, 1.8, 1) #bright for hdr
        #direct = Vec4(0.7, 0.65, 0.6, 1)
        self.dlight = DirectionalLight('dlight')
        self.dlight.setColor(direct)
        dlnp = self.sun.attachNewNode(self.dlight)
        render.setLight(dlnp)
        render.setShaderInput('dlight0', dlnp)

        self.setTime(700.0)

        pandaVolumetricLighting = False


        if pandaVolumetricLighting:
            self.filters.setVolumetricLighting( dlnp )
        else:
            self.vlbuffer = base.win.makeTextureBuffer('volumetric-lighting', base.win.getXSize() / 2, base.win.getYSize() / 2)
            self.vlbuffer.setClearColor(Vec4(0, 0, 0, 1))
            cam = base.makeCamera(self.vlbuffer)
            cam.node().setLens(base.camLens)
            cam.reparentTo(base.cam)
            initstatenode = NodePath('InitialState')
            initstatenode.setColorScale(0, 0, 0, 1, 10000)
            initstatenode.setShaderOff(10000)
            initstatenode.setFogOff(1)
            initstatenode.setLightOff(10000)
            initstatenode.setMaterialOff(10000)
            initstatenode.setTransparency(TransparencyAttrib.MBinary, 10000)
            cam.node().setCameraMask(BitMask32.bit(2))
            cam.node().setInitialState(initstatenode.getState())
            self.vltexture = self.vlbuffer.getTexture()
            self.vltexture.setWrapU(Texture.WMClamp)
            self.vltexture.setWrapV(Texture.WMClamp)
            card = CardMaker('VolumetricLightingCard')
            card.setFrameFullscreenQuad()
            self.finalQuad = render2d.attachNewNode(card.generate())
            self.finalQuad.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingColor, ColorBlendAttrib.OFbufferColor))
            self.finalQuad.setShader(Shader.load("shaders/filter-vlight.cg"))
            self.finalQuad.setShaderInput('src', self.vltexture)
            self.finalQuad.setShaderInput('vlparams', 32, 0.95 / 32.0, 0.985, 0.5) # Note - first 32 is now hardcoded into shader for cards that don't support variable sized loops.
            self.finalQuad.setShaderInput('casterpos', 0.5, 0.5, 0, 0)
            # Last parameter to vlcolor is the exposure
            vlcolor = Vec4(1, 0.99, 0.80, 0.03)
            self.finalQuad.setShaderInput('vlcolor', vlcolor)

        self.start()
Example #29
0
class DirLight:
  """Creates a simple directional light"""
  def __init__(self,manager,xml):
    self.light = PDirectionalLight('dlight')
    self.lightNode = NodePath(self.light)
    self.lightNode.setCompass()
    if hasattr(self.lightNode.node(), "setCameraMask"):
      self.lightNode.node().setCameraMask(BitMask32.bit(3))

    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(float(pos.get('x')),
                            float(pos.get('y')),
                            float(pos.get('z')))
    else:
      self.lightNode.setPos(0, 0, 0)

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

    lens = xml.find('lens')
    if lens!=None and hasattr(self.lightNode.node(), 'getLens'):
      if bool(int(lens.get('auto'))):
        self.lightNode.reparentTo(base.camera)
      else:
        self.lightNode.reparentTo(render)
      lobj = self.lightNode.node().getLens()

      lobj.setNearFar(float(lens.get('near', 1.0)),
                      float(lens.get('far', 100000.0)))

      lobj.setFilmSize(float(lens.get('width', 1.0)),
                       float(lens.get('height', 1.0)))

      lobj.setFilmOffset(float(lens.get('x', 0.0)),
                         float(lens.get('y', 0.0)))

    if hasattr(self.lightNode.node(), 'setShadowCaster'):
      shadows = xml.find('shadows')
      if shadows!=None:
        self.lightNode.node().setShadowCaster(True, int(shadows.get('width', 512)),
                                                    int(shadows.get('height', 512)),
                                                    int(shadows.get('sort', -10)))
        #self.lightNode.node().setPushBias(float(shadows.get('bias', 0.5)))
      else:
        self.lightNode.node().setShadowCaster(False)

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

  def stop(self):
    render.clearLight(self.lightNode)
class Sun:
    """Represents the sun, handles godrays, etc."""
    def __init__(self, filters):
        self.filters = filters
        self.updateTask = None
        self.finalQuad = None

        self.sun = base.cam.attachNewNode('sun')
        loader.loadModel("models/sphere").reparentTo(self.sun)
        self.sun.setScale(0.08)
        self.sun.setTwoSided(True)
        self.sun.setColorScale(1.0, 1.0, 1.0, 1.0, 10001)
        self.sun.setLightOff(1)
        self.sun.setShaderOff(1)
        self.sun.setFogOff(1)
        self.sun.setCompass()
        self.sun.setBin('background', 2)
        self.sun.setDepthWrite(False)
        self.sun.setDepthTest(False)
        # Workaround an annoyance in Panda. No idea why it's needed.
        self.sun.node().setBounds(OmniBoundingVolume())     

        direct = Vec4(2.0, 1.9, 1.8, 1) #bright for hdr
        #direct = Vec4(0.7, 0.65, 0.6, 1)
        self.dlight = DirectionalLight('dlight')
        self.dlight.setColor(direct)
        dlnp = self.sun.attachNewNode(self.dlight)
        render.setLight(dlnp)
        render.setShaderInput('dlight0', dlnp)

        self.setTime(700.0)

        pandaVolumetricLighting = False


        if pandaVolumetricLighting:
            self.filters.setVolumetricLighting( dlnp )
        else:
            self.vlbuffer = base.win.makeTextureBuffer('volumetric-lighting', base.win.getXSize() / 2, base.win.getYSize() / 2)
            self.vlbuffer.setClearColor(Vec4(0, 0, 0, 1))
            cam = base.makeCamera(self.vlbuffer)
            cam.node().setLens(base.camLens)
            cam.reparentTo(base.cam)
            initstatenode = NodePath('InitialState')
            initstatenode.setColorScale(0, 0, 0, 1, 10000)
            initstatenode.setShaderOff(10000)
            initstatenode.setFogOff(1)
            initstatenode.setLightOff(10000)
            initstatenode.setMaterialOff(10000)
            initstatenode.setTransparency(TransparencyAttrib.MBinary, 10000)
            cam.node().setCameraMask(BitMask32.bit(2))
            cam.node().setInitialState(initstatenode.getState())
            self.vltexture = self.vlbuffer.getTexture()
            self.vltexture.setWrapU(Texture.WMClamp)
            self.vltexture.setWrapV(Texture.WMClamp)
            card = CardMaker('VolumetricLightingCard')
            card.setFrameFullscreenQuad()
            self.finalQuad = render2d.attachNewNode(card.generate())
            self.finalQuad.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingColor, ColorBlendAttrib.OFbufferColor))
            self.finalQuad.setShader(Shader.load("shaders/filter-vlight.cg"))
            self.finalQuad.setShaderInput('src', self.vltexture)
            self.finalQuad.setShaderInput('vlparams', 32, 0.95 / 32.0, 0.985, 0.5) # Note - first 32 is now hardcoded into shader for cards that don't support variable sized loops.
            self.finalQuad.setShaderInput('casterpos', 0.5, 0.5, 0, 0)
            # Last parameter to vlcolor is the exposure
            vlcolor = Vec4(1, 0.99, 0.80, 0.03)
            self.finalQuad.setShaderInput('vlcolor', vlcolor)

        self.start()

    def setPos(self, pos):
        pos.normalize()
        self.sun.setPos(pos)
        self.sun.lookAt(base.cam)

    def setTime(self, time):
        self.time = time
        if time < 500.0 or time > 1900.0:
            self.sun.hide()
            self.dlight.setColor(Vec4(0, 0, 0, 0))
            return

        self.sun.show()
        noonOffset = (1200.0 - time) / 600.0
        sunsetStrength = noonOffset * noonOffset

        directColor = Vec4(2.7, 2.5, 2.1, 1) #bright for hdr
        sunsetColor = Vec4(1.8, 1.1, 0.6, 1)

        if sunsetStrength < 1.0:
            directColor *= 1-sunsetStrength
            sunsetColor *= sunsetStrength
            #logging.info( str(directColor)+ str(sunsetColor))
            lightColor = directColor + sunsetColor

        else:
            maxSunsetStrength = (1.0 + 1.0 / 6.0) * (1.0 + 1.0 / 6.0)
            duskTime = maxSunsetStrength - 1.0
            duskMultiplier = ((1.0 + duskTime) - sunsetStrength) / duskTime
            #logging.info( duskMultiplier)
            if duskMultiplier < 0:
                lightColor = Vec4(0, 0, 0, 1)
            else:
                lightColor = sunsetColor * duskMultiplier
                
        lightColor.w = 1
        self.dlight.setColor(lightColor)

        directColor = Vec4(1.0, 1.0, 1.0, 1)
        sunsetColor = Vec4(1.0, 0.9, 0.7, 1)
        directColor *= 1-sunsetStrength
        sunsetColor *= sunsetStrength
        #logging.info( str(directColor)+ str(sunsetColor))
        lightColor = directColor + sunsetColor
        self.sun.setColorScale(lightColor, 1000)        

        if self.finalQuad != None:
            directColor = Vec4(1, 0.99, 0.80, 0.03)
            sunsetColor = Vec4(1, 0.65, 0.25, 0.025)
            sunsetColor *= sunsetStrength
            directColor *= 1-sunsetStrength
            vlColor = directColor + sunsetColor
            self.finalQuad.setShaderInput('vlcolor', vlColor)

        angle = noonOffset * math.pi / 2
        y = math.sin(angle)
        z = math.cos(angle)
        #logging.info( "sun angle, x, z: ", angle, x, z)
        self.setPos(Vec3(0, y, z))

    def start(self):
        if self.finalQuad != None:
            self.updateTask = taskMgr.add(self.update, 'sun-update')

    def stop(self):
        if self.updateTask != None:
            taskMgr.remove(self.updateTask)

    def update(self, task):
        casterpos = Point2()
        base.camLens.project(self.sun.getPos(base.cam), casterpos)
        self.finalQuad.setShaderInput('casterpos', Vec4(casterpos.getX() * 0.5 + 0.5, (casterpos.getY() * 0.5 + 0.5), 0, 0))

        return task.cont
Example #31
0
class FreeBLiTZ(ShowBase):
    def __init__(self):
        from pandac.PandaModules import CollisionHandlerFloor, CollisionHandlerPusher, CollisionHandlerEvent, CollisionTraverser
        from pandac.PandaModules import DirectionalLight, AmbientLight, VBase4
        ShowBase.__init__(self)

        self.sky = self.loader.loadModel('models/sky-sphere')
        self.sky.reparentTo(self.render)
        self.stage = self.loader.loadModel('models/test-collide')
        self.stage.reparentTo(self.render)
        self.floor = self.stage.findAllMatches('**/=CollideType=floor')
        self.floor.setCollideMask(FLOOR_MASK)
        self.obstacles = self.stage.findAllMatches('**/=CollideType=obstacle')
        if self.obstacles:
            self.obstacles.setCollideMask(OBSTACLE_MASK)
        self.zones = self.stage.findAllMatches('**/=CollideType=zone')
        if self.zones:
            self.zones.setCollideMask(ZONE_MASK)
        self.create_stanchions()

        # Character rig, which allows camera to follow character
        self.char_rig = self.stage.attachNewNode('char_rig')

        self.active_char = Character('mainchar', self.char_rig)

        self.cam.reparentTo(self.char_rig)
        self.cam.setPos(0.5, -3, 1.5)
        self.cam.lookAt(0.5, 0, 1.5)

        self.light = DirectionalLight('dlight')
        self.light.setColor(VBase4(0.3, 0.28, 0.26, 1.0))
        self.lightNP = self.stage.attachNewNode(self.light)
        self.lightNP.setHpr(-75, -45, 0)
        self.stage.setLight(self.lightNP)

        self.amblight = AmbientLight('amblight')
        self.amblight.setColor(VBase4(0.7, 0.68, 0.66, 1.0))
        self.amblightNP = self.stage.attachNewNode(self.amblight)
        self.stage.setLight(self.amblightNP)

        self.accept('w', self.active_char.begin_forward)
        self.accept('a', self.active_char.begin_left)
        self.accept('s', self.active_char.begin_backward)
        self.accept('d', self.active_char.begin_right)
        self.accept('w-up', self.active_char.end_forward)
        self.accept('a-up', self.active_char.end_left)
        self.accept('s-up', self.active_char.end_backward)
        self.accept('d-up', self.active_char.end_right)
        self.taskMgr.add(self.active_char.MoveTask, 'MoveTask')

        self.look = False
        self.prev_pos = None
        self.accept('mouse2', self.begin_look)
        self.accept('mouse2-up', self.end_look)
        self.accept('mouse3', self.active_char.begin_spin)
        self.accept('mouse3-up', self.active_char.end_spin)
        self.taskMgr.add(self.MouseTask, 'MouseTask')

        self.floor_handler = CollisionHandlerFloor()
        self.floor_handler.addCollider(self.active_char.actor_from_floor,
                                       self.char_rig)
        self.wall_handler = CollisionHandlerPusher()
        self.wall_handler.addCollider(self.active_char.actor_from_obstacle,
                                      self.char_rig)
        self.zone_handler = CollisionHandlerEvent()
        self.zone_handler.addInPattern('%fn-into')
        self.zone_handler.addOutPattern('%fn-out')

        def foo(entry):
            print 'You are in the zone'

        def bar(entry):
            print 'You are not in the zone'

        self.accept('blockchar_zone-into', foo)
        self.accept('blockchar_zone-out', bar)
        self.cTrav = CollisionTraverser('main traverser')
        self.cTrav.setRespectPrevTransform(True)
        self.cTrav.addCollider(self.active_char.actor_from_floor,
                               self.floor_handler)
        self.cTrav.addCollider(self.active_char.actor_from_obstacle,
                               self.wall_handler)
        self.cTrav.addCollider(self.active_char.actor_from_zone,
                               self.zone_handler)
        #self.cTrav.showCollisions(self.stage)

    def create_stanchions(self):
        from pandac.PandaModules import GeomVertexReader, CollisionNode, CollisionTube
        self.stanchions = self.stage.findAllMatches('**/=Stanchion')
        for stanchion in self.stanchions:
            geomnode = stanchion.node()
            radius = float(stanchion.getTag('Stanchion'))
            geom = geomnode.getGeom(0)
            vdata = geom.getVertexData()
            for gp in range(geom.getNumPrimitives()):
                vreader = GeomVertexReader(vdata, 'vertex')
                prim = geom.getPrimitive(gp)
                prim = prim.decompose()
                for p in range(prim.getNumPrimitives()):
                    start = prim.getPrimitiveStart(p)
                    end = prim.getPrimitiveEnd(p)
                    vertices = []
                    for v in range(start, end):
                        vi = prim.getVertex(v)
                        vreader.setRow(vi)
                        vertex = vreader.getData3f()
                        vertices.append(vertex)
                    vertices.append(vertices[0])
                    for i in range(1, len(vertices)):
                        a, b = vertices[i - 1], vertices[i]
                        stanchion_np = stanchion.attachNewNode(
                            CollisionNode('stanchion'))
                        print 'creating cyl with radius %f from %s to %s' % (
                            radius, a, b)
                        stanchion_np.node().addSolid(
                            CollisionTube(a[0], a[1], a[2], b[0], b[1], b[2],
                                          radius))
                        stanchion_np.node().setFromCollideMask(OBSTACLE_MASK)
            geomnode.removeAllGeoms()

    def begin_look(self):
        self.look = True

    def end_look(self):
        self.look = False
        self.prev_pos = None

    def MouseTask(self, task):
        if self.mouseWatcherNode.hasMouse():
            (x, y) = self.mouseWatcherNode.getMouse()
            if self.prev_pos:
                if self.look or self.active_char.spinning:
                    h_diff = (x - self.prev_pos[0]) * 180
                    p_diff = (y - self.prev_pos[1]) * 90
                    new_h = clamp_deg_sign(self.char_rig.getH() - h_diff)
                    self.char_rig.setH(new_h)
                    self.cam.setP(self.cam.getP() + p_diff)
                    self.active_char.spin(new_h)
            self.prev_pos = (x, y)
        return task.cont
Example #32
0
    def __init__(self):
        from pandac.PandaModules import CollisionHandlerFloor, CollisionHandlerPusher, CollisionHandlerEvent, CollisionTraverser
        from pandac.PandaModules import DirectionalLight, AmbientLight, VBase4
        ShowBase.__init__(self)

        self.sky = self.loader.loadModel('models/sky-sphere')
        self.sky.reparentTo(self.render)
        self.stage = self.loader.loadModel('models/test-collide')
        self.stage.reparentTo(self.render)
        self.floor = self.stage.findAllMatches('**/=CollideType=floor')
        self.floor.setCollideMask(FLOOR_MASK)
        self.obstacles = self.stage.findAllMatches('**/=CollideType=obstacle')
        if self.obstacles:
            self.obstacles.setCollideMask(OBSTACLE_MASK)
        self.zones = self.stage.findAllMatches('**/=CollideType=zone')
        if self.zones:
            self.zones.setCollideMask(ZONE_MASK)
        self.create_stanchions()

        # Character rig, which allows camera to follow character
        self.char_rig = self.stage.attachNewNode('char_rig')

        self.active_char = Character('mainchar', self.char_rig)

        self.cam.reparentTo(self.char_rig)
        self.cam.setPos(0.5, -3, 1.5)
        self.cam.lookAt(0.5, 0, 1.5)

        self.light = DirectionalLight('dlight')
        self.light.setColor(VBase4(0.3, 0.28, 0.26, 1.0))
        self.lightNP = self.stage.attachNewNode(self.light)
        self.lightNP.setHpr(-75, -45, 0)
        self.stage.setLight(self.lightNP)

        self.amblight = AmbientLight('amblight')
        self.amblight.setColor(VBase4(0.7, 0.68, 0.66, 1.0))
        self.amblightNP = self.stage.attachNewNode(self.amblight)
        self.stage.setLight(self.amblightNP)

        self.accept('w', self.active_char.begin_forward)
        self.accept('a', self.active_char.begin_left)
        self.accept('s', self.active_char.begin_backward)
        self.accept('d', self.active_char.begin_right)
        self.accept('w-up', self.active_char.end_forward)
        self.accept('a-up', self.active_char.end_left)
        self.accept('s-up', self.active_char.end_backward)
        self.accept('d-up', self.active_char.end_right)
        self.taskMgr.add(self.active_char.MoveTask, 'MoveTask')

        self.look = False
        self.prev_pos = None
        self.accept('mouse2', self.begin_look)
        self.accept('mouse2-up', self.end_look)
        self.accept('mouse3', self.active_char.begin_spin)
        self.accept('mouse3-up', self.active_char.end_spin)
        self.taskMgr.add(self.MouseTask, 'MouseTask')

        self.floor_handler = CollisionHandlerFloor()
        self.floor_handler.addCollider(self.active_char.actor_from_floor,
                                       self.char_rig)
        self.wall_handler = CollisionHandlerPusher()
        self.wall_handler.addCollider(self.active_char.actor_from_obstacle,
                                      self.char_rig)
        self.zone_handler = CollisionHandlerEvent()
        self.zone_handler.addInPattern('%fn-into')
        self.zone_handler.addOutPattern('%fn-out')

        def foo(entry):
            print 'You are in the zone'

        def bar(entry):
            print 'You are not in the zone'

        self.accept('blockchar_zone-into', foo)
        self.accept('blockchar_zone-out', bar)
        self.cTrav = CollisionTraverser('main traverser')
        self.cTrav.setRespectPrevTransform(True)
        self.cTrav.addCollider(self.active_char.actor_from_floor,
                               self.floor_handler)
        self.cTrav.addCollider(self.active_char.actor_from_obstacle,
                               self.wall_handler)
        self.cTrav.addCollider(self.active_char.actor_from_zone,
                               self.zone_handler)
Example #33
0
        if self.steer2d:
            base.cam.setX(self.avatar.getX())
            base.cam.setZ(self.avatar.getZ() + self.camdistZ)
        base.cam.lookAt(self.avatar)

        return Task.cont


#=========================================================================
# Main
#=========================================================================

alight = AmbientLight('alight')
alight.setColor((.3, .3, .3, 1))
alnp = render.attachNewNode(alight)
render.setLight(alnp)

dlight = DirectionalLight('dlight')
lv = .6
dlight.setColor((lv, lv, lv, 1))
dlnp = render.attachNewNode(dlight)
render.setLight(dlnp)
dlnp.setPos(0, -20, 35)
dlnp.lookAt(0, 0, 0)

DO = DirectObject()
DO.accept('c', toggle_collisions)
DO.accept('h', toggle_info)
DO.accept('x', toggle_wire)
DO.accept('escape', sys.exit)
Example #34
0
    def __init__(self):
        from pandac.PandaModules import CollisionHandlerFloor, CollisionHandlerPusher, CollisionHandlerEvent, CollisionTraverser
        from pandac.PandaModules import DirectionalLight, AmbientLight, VBase4
        ShowBase.__init__(self)

        self.sky = self.loader.loadModel('models/sky-sphere')
        self.sky.reparentTo(self.render)
        self.stage = self.loader.loadModel('models/test-collide')
        self.stage.reparentTo(self.render)
        self.floor = self.stage.findAllMatches('**/=CollideType=floor')
        self.floor.setCollideMask(FLOOR_MASK)
        self.obstacles = self.stage.findAllMatches('**/=CollideType=obstacle')
        if self.obstacles:
            self.obstacles.setCollideMask(OBSTACLE_MASK)
        self.zones = self.stage.findAllMatches('**/=CollideType=zone')
        if self.zones:
            self.zones.setCollideMask(ZONE_MASK)
        self.create_stanchions()

        # Character rig, which allows camera to follow character
        self.char_rig = self.stage.attachNewNode('char_rig')

        self.active_char = Character('mainchar', self.char_rig)

        self.cam.reparentTo(self.char_rig)
        self.cam.setPos(0.5, -3, 1.5)
        self.cam.lookAt(0.5, 0, 1.5)

        self.light = DirectionalLight('dlight')
        self.light.setColor(VBase4(0.3, 0.28, 0.26, 1.0))
        self.lightNP = self.stage.attachNewNode(self.light)
        self.lightNP.setHpr(-75, -45, 0)
        self.stage.setLight(self.lightNP)

        self.amblight = AmbientLight('amblight')
        self.amblight.setColor(VBase4(0.7, 0.68, 0.66, 1.0))
        self.amblightNP = self.stage.attachNewNode(self.amblight)
        self.stage.setLight(self.amblightNP)

        self.accept('w', self.active_char.begin_forward)
        self.accept('a', self.active_char.begin_left)
        self.accept('s', self.active_char.begin_backward)
        self.accept('d', self.active_char.begin_right)
        self.accept('w-up', self.active_char.end_forward)
        self.accept('a-up', self.active_char.end_left)
        self.accept('s-up', self.active_char.end_backward)
        self.accept('d-up', self.active_char.end_right)
        self.taskMgr.add(self.active_char.MoveTask, 'MoveTask')

        self.look = False
        self.prev_pos = None
        self.accept('mouse2', self.begin_look)
        self.accept('mouse2-up', self.end_look)
        self.accept('mouse3', self.active_char.begin_spin)
        self.accept('mouse3-up', self.active_char.end_spin)
        self.taskMgr.add(self.MouseTask, 'MouseTask')

        self.floor_handler = CollisionHandlerFloor()
        self.floor_handler.addCollider(self.active_char.actor_from_floor, self.char_rig)
        self.wall_handler = CollisionHandlerPusher()
        self.wall_handler.addCollider(self.active_char.actor_from_obstacle, self.char_rig)
        self.zone_handler = CollisionHandlerEvent()
        self.zone_handler.addInPattern('%fn-into')
        self.zone_handler.addOutPattern('%fn-out')
        def foo(entry):
            print 'You are in the zone'
        def bar(entry):
            print 'You are not in the zone'
        self.accept('blockchar_zone-into', foo)
        self.accept('blockchar_zone-out', bar)
        self.cTrav = CollisionTraverser('main traverser')
        self.cTrav.setRespectPrevTransform(True)
        self.cTrav.addCollider(self.active_char.actor_from_floor, self.floor_handler)
        self.cTrav.addCollider(self.active_char.actor_from_obstacle, self.wall_handler)
        self.cTrav.addCollider(self.active_char.actor_from_zone, self.zone_handler)
Example #35
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 #36
0
	def __init__(self):
		ShowBase.__init__(self)
		
		#start the time
		self.globalTime = 0
		self.nextEnemy = 1
		
		#setup your collision event handlers, apparently needs a direct object
		
		self.do = DirectObject()
		self.do.accept('unit-into-unit', self.handleUnitIntoCollision)
		self.do.accept('unit-out-unit', self.handleUnitOutCollision)
		self.do.accept('unit-into-cube', self.handleCubeIntoCollision)
		self.do.accept('unit-into-wing', self.handleWingIntoCollision)
		self.do.accept('unit-into-bar', self.handleBarIntoCollision)
		
		#get window properties
		self.winProps = WindowProperties()
		#self.winProps.setFullscreen(True)
		self.winProps.setCursorHidden(True)
		base.win.requestProperties(self.winProps)
		
		self.winProps = base.win.getProperties()
		self.screenHeight = self.winProps.getYSize()
		
		#set up the control scheme
		self.controlScheme = ControlScheme(base.mouseWatcherNode, base.win, \
										[LEFT, RIGHT, UP, DOWN, PAUSE, PULL, PUSH, SWITCH, QUIT])
		
		#disable the automatic task to move the camera
		#(this does not actually disable the mouse)
		base.disableMouse()
		
		#declare null values for variables, fill them in later
		self.environment = None
		self.player = None
		
		#a node for holding all in-game units
		self.unitNodePath = NodePath('unit holder')
		self.unitNodePath.reparentTo(self.render)
		
		#object lists
		self.enemies = []
		self.obstacles = []
		self.projectiles = []
		#list of enemies to be spawned
		self.eSpawnList = []
		
		#not paused by default
		self.paused = False
		self.pauseWasPressed = False
		
		#variables for tracking time
		self.previousFrameTime = 0
		
		#start the collision traverser
		traverser = CollisionTraverser()
		base.cTrav = traverser#run every frame
		self.cTrav = base.cTrav
		#set the check for units accidentally passing through level geometry
		self.cTrav.setRespectPrevTransform(True)
		
		#self.cTrav.showCollisions(self.render)
		#self.cTrav.showCollisions(self.unitNodePath)#show the collisions
		
		#load terrain and enemies
		
		#load the environment, it seems that an x value of zero, a y value of -50 puts the origin point relatively in the middle of the crater
		filename = PARAMS_PATH + "environment.txt"
		self.loadLevelGeom(filename)
		#load the enemies
		filename = PARAMS_PATH + "enemies.txt"
		self.loadLevelEnemies(filename)
		
		#lookup table for actors
		self.actors = {}
		
		#place the player in the environment
		self.player = Player(self.controlScheme, self.camera, self, 0, 0, 0)
		self.player.setName("player")
		self.player.setH(180)
		self.player.reparentTo(self.unitNodePath)
		self.player.nodePath = self.render.find("player")
		self.actors["player"] = self.player
		
		
		#add some lights
		topLight = DirectionalLight("top light")
		topLight.setColor(Vec4(0.5, 0.5, 0.5, 1))
		topLight.setDirection(Vec3(0, -90, 0))
		self.render.setLight(self.render.attachNewNode(topLight))
		
		ambientLight = AmbientLight("ambient light")
		ambientLight.setColor(Vec4(0.5, 0.5, 0.5, 1))
		self.render.setLight(self.render.attachNewNode(ambientLight))
		
		#the distance the camera is from the player
		self.cameraHOffset = 45
		self.cameraVOffset = 10
		
		#add the collision sound
		self.collisionSound = self.loader.loadSfx(SFX_PATH + "collide.wav")
		
		#register the update task
		self.taskMgr.add(self.updateGame, "updateGame")
		
		#add targeting to the world
		self.setupTargeting()
		
		#seed the random number generator
		random.seed()

		# configure the entire GUI
		self.setupGUI()

		# configure the title screen
		self.setupTitleScreen()
Example #37
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 #38
0
class BaseApp(AppShell):
    appname = 'CG2'
    usecommandarea = 1
    usestatusarea  = 1
    frameHeight = 600

    def _get_filename(self):
        return self.getVariable('surface', 'filename').get()
    surface_filename = property(_get_filename)

    def _get_invert_normals(self):
        return bool(self.getVariable('surface', 'invert normals').get())
    surface_invert_normals = property(_get_invert_normals)

    def _get_regular_grids(self):
        return [ bool(self.getVariable('surface', 'regular grid %d' % index).get()) for index in range(self._num_surfaces) ]
    surface_regular_grids = property(_get_regular_grids)

    def _get_implicit_surfaces(self):
        return [ bool(self.getVariable('surface', 'implicit surface %d' % index).get()) for index in range(self._num_surfaces) ]
    surface_implicit_surfaces = property(_get_implicit_surfaces)

    def _get_point_cloud(self):
        return bool(self.getVariable('surface', 'point cloud').get())
    surface_point_cloud = property(_get_point_cloud)

    def _get_halfedge_mesh(self):
        return bool(self.getVariable('surface', 'halfedge mesh').get())
    surface_halfedge_mesh = property(_get_halfedge_mesh)

    def _get_subdivisions(self):
        return [int(widget.get()) for widget in self.tk_subdivisions]
    surface_subdivisions = property(_get_subdivisions)

    def _get_degree(self):
        return int(self.tk_degree.get())
    surface_degree = property(_get_degree)

    def _get_radius(self):
        return float(self.tk_radius.get())
    surface_radius = property(_get_radius)

    def _get_light_angle(self):
        return int(self.tk_light_angle.get())
    surface_light_angle = property(_get_light_angle)

    def _get_optimization_choice(self):
        return int(self.var_optimization_choice.get())
    surface_optimization_choice = property(_get_optimization_choice)

    def _get_face_count(self):
        return float(self.tk_face_count.get())
    surface_face_count = property(_get_face_count)

    def _get_improvement_rate(self):
        return float(self.tk_improvement_rate.get())
    surface_improvement_rate = property(_get_improvement_rate)

    def __init__(self):
        self._log = logging.getLogger('BaseApp')
        self._num_surfaces = 1
        AppShell.__init__(self)
        self.initialiseoptions(BaseApp)
        self.createScene()

    def createInterface(self):
        self._log.info(u"Creating interface...")
        self.var_optimization_choice = IntVar()
        self.tk_filename = self.newCreateLabeledEntry(
                parent   = self.interior(),
                category = "surface",
                text     = "filename",
                side     = TOP,
                fill     = X,
                expand   = 0)
        self.tk_invert_normals = self.newCreateCheckbutton(
                parent   = self.interior(),
                category = "surface",
                text     = "invert normals",
                side     = TOP,
                fill     = X,
                expand   = 0)
        self.tk_light_angle = self.newCreateEntryScale(
                parent   = self.interior(),
                category = "surface",
                text     = "light angle",
                max      = 360,
                min      = 1,
                resolution = 1,
                command  = self.rotate_light,
                side     = TOP,
                fill     = X,
                expand   = 0)
        self.tk_subdivisions = []
        for index in range(self._num_surfaces):
            self.tk_subdivisions.append(self.newCreateEntryScale(
                    parent   = self.interior(),
                    category = "surface",
                    text     = "subdivisions %d" % index,
                    max      = 30,
                    resolution = 1,
                    side     = TOP,
                    fill     = X,
                    expand   = 0))
        self.tk_degree = self.newCreateEntryScale(
                parent   = self.interior(),
                category = "surface",
                text     = "degree",
                max      = 3,
                min      = 1,
                resolution = 1,
                side     = TOP,
                fill     = X,
                expand   = 0)
        self.tk_radius = self.newCreateEntryScale(
                parent   = self.interior(),
                category = "surface",
                text     = "radius",
                max      = 0.5,
                min      = 0,
                resolution = 0.01,
                side     = TOP,
                fill     = X,
                expand   = 0)
        self.tk_face_count = self.newCreateEntryScale(
                parent   = self.interior(),
                category = "surface",
                text     = "face count",
                max      = 1,
                min      = 0.05,
                resolution = 0.05,
                side     = TOP,
                fill     = X,
                expand   = 0)
        self.tk_improvement_rate = self.newCreateEntryScale(
                parent   = self.interior(),
                category = "surface",
                text     = "improvement rate",
                max      = 1,
                min      = 0.05,
                resolution = 0.05,
                side     = TOP,
                fill     = X,
                expand   = 0)
        self.tk_optimization_choice_0 = self.newCreateRadiobutton(
                parent   = self.interior(),
                category = "surface",
                text     = "optimize until face count",
                variable = self.var_optimization_choice,
                value    = 0,
                side     = TOP,
                fill     = X,
                expand   = 0)
        self.tk_optimization_choice_1 = self.newCreateRadiobutton(
                parent   = self.interior(),
                category = "surface",
                text     = "optimize until improvement rate",
                variable = self.var_optimization_choice,
                value    = 1,
                side     = TOP,
                fill     = X,
                expand   = 0)
        self.tk_optimization_choice_2 = self.newCreateRadiobutton(
                parent   = self.interior(),
                category = "surface",
                text     = "don't optimize",
                variable = self.var_optimization_choice,
                value    = 2,
                side     = TOP,
                fill     = X,
                expand   = 0)
        self.tk_point_cloud = self.newCreateCheckbutton(
                parent   = self.interior(),
                category = "surface",
                text     = "point cloud",
                command  = self._toggle_point_cloud,
                side     = TOP,
                fill     = X,
                expand   = 0)
        self.tk_regular_grids = []
        for index in range(self._num_surfaces):
            self.tk_regular_grids.append(self.newCreateCheckbutton(
                    parent   = self.interior(),
                    category = "surface",
                    text     = "regular grid %d" % index,
                    command  = self._toggle_regular_grids,
                    side     = TOP,
                    fill     = X,
                    expand   = 0))
        self.tk_implicit_surfaces = []
        for index in range(self._num_surfaces):
            self.tk_implicit_surfaces.append(self.newCreateCheckbutton(
                    parent   = self.interior(),
                    category = "surface",
                    text     = "implicit surface %d" % index,
                    command  = self._toggle_implicit_surfaces,
                    side     = TOP,
                    fill     = X,
                    expand   = 0))
        self.tk_halfedge_mesh = self.newCreateCheckbutton(
                parent   = self.interior(),
                category = "surface",
                text     = "halfedge mesh",
                command  = self._toggle_halfedge_mesh,
                side     = TOP,
                fill     = X,
                expand   = 0)
        self.tk_apply = self.buttonAdd(
                buttonName    = 'Apply',
                helpMessage   = 'Apply',
                statusMessage = 'Apply',
                command       = self.apply)
        self.tk_apply_halfedge_mesh = self.buttonAdd(
                buttonName    = 'Apply Halfedge only',
                helpMessage   = 'Apply Halfedge only',
                statusMessage = 'Apply Halfedge only',
                command       = self.apply_halfedge)

        # set default values
        self.getVariable('surface', 'filename').set("pointdata/cat.off")
        self.tk_degree.set(1)
        self.tk_radius.set(0.05)
        self.tk_light_angle.set(1)
        self.getVariable('surface', 'regular grid 0').set(1)
        self.getVariable('surface', 'point cloud').set(1)

    def createScene(self):
        self._log.debug(u"Creating scene...")
        base.setBackgroundColor(0.3, 0.3, 0.3)
        self.gl_dlight = DirectionalLight('dlight')
        self.gl_dlight.setColor(Vec4(1, 1, 1, 1))
        self.np_dlight = render.attachNewNode(self.gl_dlight)
        #self.np_dlight.setHpr(90, 0, 0)
        self.np_dlight.lookAt(1, 1, -10)
        self.l_marker = loader.loadModel("models/misc/Dirlight")
        self.l_marker.reparentTo(self.np_dlight)
        self.l_marker.setScale(0.1, 0.1, 0.1)
        render.setLight(self.np_dlight)
        render.setTransparency(TransparencyAttrib.MAlpha)
        self._camera_control = CameraHandler()
        self.clearScene()
        self.rotate_light(0)

    def clearScene(self):
        if not hasattr(self, 'surfaces'):
            self.surfaces = [None,] * self._num_surfaces
        if not hasattr(self, 'grids'):
            self.grids = [None,] * self._num_surfaces
        if not hasattr(self, 'implicit_surfaces'):
            self.implicit_surfaces = [None,] * self._num_surfaces

        for surface_index in range(self._num_surfaces):
            if self.surfaces[surface_index]:
                self.surfaces[surface_index] = None
                if self.grids[surface_index]:
                    self.grids[surface_index].removeNode()
                self.grids[surface_index] = None
                if self.implicit_surfaces[surface_index]:
                    self.implicit_surfaces[surface_index].removeNode()
                self.implicit_surfaces[surface_index] = None

        if hasattr(self, 'point_cloud') and self.point_cloud:
            self.point_cloud.removeNode()
        self.point_cloud = None

        if hasattr(self, 'halfedge_mesh') and self.halfedge_mesh:
            self.halfedge_mesh.removeNode()
        self.halfedge_mesh = None

    @log_exceptions
    @profile(immediate=True)
    def apply(self):
        self._log.info("Applying values...")
        self.clearScene()
        for index in range(self._num_surfaces):
            self.surfaces[index] = ImplicitSurface.from_file(self.surface_filename, self.surface_invert_normals)
        self._toggle_implicit_surfaces()
        self._toggle_regular_grids()
        self._toggle_point_cloud()
        self._toggle_halfedge_mesh()
        self._camera_control.setTarget(*self.surfaces[0].center[0:3])

    @log_exceptions
    @profile(immediate=True)
    def apply_halfedge(self):
        self._log.info(u"Applying halfedge changes...")
        if hasattr(self, 'halfedge_mesh') and self.halfedge_mesh:
            self.halfedge_mesh.removeNode()
        self.halfedge_mesh = None
        self._toggle_halfedge_mesh()

    @log_exceptions
    def _toggle_regular_grids(self):
        for index in range(self._num_surfaces):
            self._toggle_regular_grid(index)

    def _toggle_regular_grid(self, index):
        if self.surfaces[index]:
            self._log.debug(u"Toggling regular grid %d display..." % index)
            if not self.grids[index]:
                self._log.debug(u"Creating regular grid %d..." % index)
                self.grids[index] = render.attachNewNode(self.surfaces[index].get_parameter_grid(self.surface_subdivisions[index], self.surface_degree, self.surface_radius))
                self.grids[index].setLightOff()
            if self.surface_regular_grids[index]:
                self._log.debug(u"Regular grid %d is now visible." % index)
                self.grids[index].show()
            else:
                self._log.debug(u"Regular grid %d is now hidden." % index)
                self.grids[index].hide()
        else:
            self._log.debug(u"No surface loaded, cannot create regular grid %d..." % index)

    @log_exceptions
    def _toggle_implicit_surfaces(self):
        for index in range(self._num_surfaces):
            self._toggle_implicit_surface(index)

    def _toggle_implicit_surface(self, index):
        if self.surfaces[index] and self.surface_subdivisions[index] > 0:
            self._log.debug(u"Toggling implicit surface %d display..." % index)
            if not self.implicit_surfaces[index]:
                self._log.debug(u"Creating implicit surface %d with %d subdivisions..." % (index, self.surface_subdivisions[index]))
                self.implicit_surfaces[index] = render.attachNewNode(self.surfaces[index].get_implicit_surface(self.surface_subdivisions[index], self.surface_degree, self.surface_radius))
            if self.surface_implicit_surfaces[index]:
                self._log.debug(u"implicit surface %d is now visible." % index)
                self.implicit_surfaces[index].show()
            else:
                self._log.debug(u"implicit surface %d is now hidden." % index)
                self.implicit_surfaces[index].hide()
        else:
            self._log.debug(u"No surface loaded or 0 subdivisions requested, cannot create implicit surface %d..." % index)

    @log_exceptions
    def _toggle_point_cloud(self):
        if self.surfaces[0]:
            self._log.debug(u"Toggling point cloud display...")
            if not self.point_cloud:
                self._log.debug(u"Creating point_cloud...")
                self.point_cloud = render.attachNewNode(self.surfaces[0].get_original_point_cloud())
                self.point_cloud.setLightOff()
            if self.surface_point_cloud:
                self._log.debug(u"point cloud is now visible.")
                self.point_cloud.show()
            else:
                self._log.debug(u"point cloud is now hidden.")
                self.point_cloud.hide()
        else:
            self._log.debug(u"No surface loaded, cannot create point cloud...")

    @log_exceptions
    def _toggle_halfedge_mesh(self):
        if self.surfaces[0]:
            self._log.debug(u"Toggling halfedge mesh display...")
            if not self.halfedge_mesh:
                self._log.debug(u"Creating halfedge mesh...")
                if self.surface_optimization_choice == 0:
                    self.halfedge_mesh = render.attachNewNode(self.surfaces[0].get_halfedge_mesh(self.surface_optimization_choice, self.surface_face_count))
                elif self.surface_optimization_choice == 1:
                    self.halfedge_mesh = render.attachNewNode(self.surfaces[0].get_halfedge_mesh(self.surface_optimization_choice, self.surface_improvement_rate))
                else:
                    self.halfedge_mesh = render.attachNewNode(self.surfaces[0].get_halfedge_mesh(self.surface_optimization_choice, None))
            if self.surface_halfedge_mesh:
                self._log.debug(u"halfedge mesh is now visible.")
                self.halfedge_mesh.show()
            else:
                self._log.debug(u"halfedge mesh is now hidden.")
                self.halfedge_mesh.hide()
        else:
            self._log.debug(u"No surface loaded, cannot create halfedge mesh...")

    @log_exceptions
    def rotate_light(self, val):
        if hasattr(self, 'np_dlight'):
            #self._log.debug(u"Setting light angle %d..." % self.surface_light_angle)
            angle_radians = self.surface_light_angle * (math.pi / 180.0)
            self.np_dlight.setPos(1.0*math.sin(angle_radians), -1.0*math.cos(angle_radians), 1)
            #self._log.debug(u"Light pos: %f, %f, %f" % self.np_dlight.getPos())
            self.np_dlight.lookAt(0, 0, 0)
Example #39
0
	def __init__(self):
		ShowBase.__init__(self)

		# generate a new game
		game = Game()
		game.create_player('Player One')
		game.create_player('Player Two')
		game.create_player('Player Three')

		game.initialize_board()

		# place some random cities
		for player in game.players.values():
			# give the player some random resources
			for resource in player.resources:
				player.resources[resource] = random.randint(0,8)
			while True:
				n = random.choice(game.board.network.nodes())
				if game.board.node_available(n):
					game.board.update_building(n, player, 'city')

					# place a random road
					m = random.choice(game.board.network.neighbors(n))
					game.board.network.edge[n][m]['road'] = True
					game.board.network.edge[n][m]['player'] = player
					break

		self.board_renderer = BoardRenderer(self, game.board)
		self.hand_renderer = HandRenderer(self, game.players.values()[0])

		# setup some 3-point lighting for the whole board
		lKey = DirectionalLight('lKey')
		lKey.setColor(VBase4(0.9,0.9,0.9,1))
		lKeyNode = render.attachNewNode(lKey)
		lKeyNode.setH(-63)
		lKeyNode.setP(-60)
		lKeyNode.setR(-30)
		render.setLight(lKeyNode)

		lFill = DirectionalLight('lFill')
		lFill.setColor(VBase4(0.4,0.4,0.4,1))
		lFillNode = render.attachNewNode(lFill)
		lFillNode.setH(27)
		lFillNode.setP(-15)
		lFillNode.setR(-30)
		render.setLight(lFillNode)

		lBack = DirectionalLight('lBack')
		lBack.setColor(VBase4(0.3,0.3,0.3,1))
		lBackNode = render.attachNewNode(lBack)
		lBackNode.setH(177)
		lBackNode.setP(-20)
		lBackNode.setR(0)
		render.setLight(lBackNode)

		lBelow = DirectionalLight('lBelow')
		lBelow.setColor(VBase4(0.4,0.4,0.4,1))
		lBelowNode = render.attachNewNode(lBelow)
		lBelowNode.setH(0)
		lBelowNode.setP(90)
		lBelowNode.setR(0)
		render.setLight(lBelowNode)

		self.accept('a', self.on_toggle_anti_alias)
		self.mouse_controlled = True
		self.on_toggle_mouse_control()
		self.accept('m', self.on_toggle_mouse_control)
		self.accept('q', self.on_quit)

		# onto-board selection collision test
		select_mask = BitMask32(0x100)
		self.select_ray = CollisionRay()
		select_node = CollisionNode('mouseToSurfaceRay')
		select_node.setFromCollideMask(select_mask)
		select_node.addSolid(self.select_ray)
		select_np = self.camera.attachNewNode(select_node)

		self.select_queue = CollisionHandlerQueue()
		self.select_traverser = CollisionTraverser()
		self.select_traverser.addCollider(select_np, self.select_queue)

		# create a plane that only collides with the mouse ray
		select_plane = CollisionPlane(Plane(Vec3(0,0,1), Point3(0,0,0)))

		# add plane to render
		self.select_node = CollisionNode('boardCollisionPlane')
		self.select_node.setCollideMask(select_mask)
		self.select_node.addSolid(select_plane)
		self.select_plane_np = self.render.attachNewNode(self.select_node)

		self.debug_select = draw_debugging_arrow(self, Vec3(0,0,0), Vec3(0,1,0))

		self.taskMgr.add(self.update_mouse_target, "mouseTarget")
		self.taskMgr.add(self.update_debug_arrow, "updateDebugArrow")
Example #40
0
class FreeBLiTZ(ShowBase):

    def __init__(self):
        from pandac.PandaModules import CollisionHandlerFloor, CollisionHandlerPusher, CollisionHandlerEvent, CollisionTraverser
        from pandac.PandaModules import DirectionalLight, AmbientLight, VBase4
        ShowBase.__init__(self)

        self.sky = self.loader.loadModel('models/sky-sphere')
        self.sky.reparentTo(self.render)
        self.stage = self.loader.loadModel('models/test-collide')
        self.stage.reparentTo(self.render)
        self.floor = self.stage.findAllMatches('**/=CollideType=floor')
        self.floor.setCollideMask(FLOOR_MASK)
        self.obstacles = self.stage.findAllMatches('**/=CollideType=obstacle')
        if self.obstacles:
            self.obstacles.setCollideMask(OBSTACLE_MASK)
        self.zones = self.stage.findAllMatches('**/=CollideType=zone')
        if self.zones:
            self.zones.setCollideMask(ZONE_MASK)
        self.create_stanchions()

        # Character rig, which allows camera to follow character
        self.char_rig = self.stage.attachNewNode('char_rig')

        self.active_char = Character('mainchar', self.char_rig)

        self.cam.reparentTo(self.char_rig)
        self.cam.setPos(0.5, -3, 1.5)
        self.cam.lookAt(0.5, 0, 1.5)

        self.light = DirectionalLight('dlight')
        self.light.setColor(VBase4(0.3, 0.28, 0.26, 1.0))
        self.lightNP = self.stage.attachNewNode(self.light)
        self.lightNP.setHpr(-75, -45, 0)
        self.stage.setLight(self.lightNP)

        self.amblight = AmbientLight('amblight')
        self.amblight.setColor(VBase4(0.7, 0.68, 0.66, 1.0))
        self.amblightNP = self.stage.attachNewNode(self.amblight)
        self.stage.setLight(self.amblightNP)

        self.accept('w', self.active_char.begin_forward)
        self.accept('a', self.active_char.begin_left)
        self.accept('s', self.active_char.begin_backward)
        self.accept('d', self.active_char.begin_right)
        self.accept('w-up', self.active_char.end_forward)
        self.accept('a-up', self.active_char.end_left)
        self.accept('s-up', self.active_char.end_backward)
        self.accept('d-up', self.active_char.end_right)
        self.taskMgr.add(self.active_char.MoveTask, 'MoveTask')

        self.look = False
        self.prev_pos = None
        self.accept('mouse2', self.begin_look)
        self.accept('mouse2-up', self.end_look)
        self.accept('mouse3', self.active_char.begin_spin)
        self.accept('mouse3-up', self.active_char.end_spin)
        self.taskMgr.add(self.MouseTask, 'MouseTask')

        self.floor_handler = CollisionHandlerFloor()
        self.floor_handler.addCollider(self.active_char.actor_from_floor, self.char_rig)
        self.wall_handler = CollisionHandlerPusher()
        self.wall_handler.addCollider(self.active_char.actor_from_obstacle, self.char_rig)
        self.zone_handler = CollisionHandlerEvent()
        self.zone_handler.addInPattern('%fn-into')
        self.zone_handler.addOutPattern('%fn-out')
        def foo(entry):
            print 'You are in the zone'
        def bar(entry):
            print 'You are not in the zone'
        self.accept('blockchar_zone-into', foo)
        self.accept('blockchar_zone-out', bar)
        self.cTrav = CollisionTraverser('main traverser')
        self.cTrav.setRespectPrevTransform(True)
        self.cTrav.addCollider(self.active_char.actor_from_floor, self.floor_handler)
        self.cTrav.addCollider(self.active_char.actor_from_obstacle, self.wall_handler)
        self.cTrav.addCollider(self.active_char.actor_from_zone, self.zone_handler)
        #self.cTrav.showCollisions(self.stage)

    def create_stanchions(self):
        from pandac.PandaModules import GeomVertexReader, CollisionNode, CollisionTube
        self.stanchions = self.stage.findAllMatches('**/=Stanchion')
        for stanchion in self.stanchions:
            geomnode = stanchion.node()
            radius = float(stanchion.getTag('Stanchion'))
            geom = geomnode.getGeom(0)
            vdata = geom.getVertexData()
            for gp in range(geom.getNumPrimitives()):
                vreader = GeomVertexReader(vdata, 'vertex')
                prim = geom.getPrimitive(gp)
                prim = prim.decompose()
                for p in range(prim.getNumPrimitives()):
                    start = prim.getPrimitiveStart(p)
                    end = prim.getPrimitiveEnd(p)
                    vertices = []
                    for v in range(start, end):
                        vi = prim.getVertex(v)
                        vreader.setRow(vi)
                        vertex = vreader.getData3f()
                        vertices.append(vertex)
                    vertices.append(vertices[0])
                    for i in range(1, len(vertices)):
                        a, b =  vertices[i-1], vertices[i]
                        stanchion_np = stanchion.attachNewNode(CollisionNode('stanchion'))
                        print 'creating cyl with radius %f from %s to %s' % (radius, a, b)
                        stanchion_np.node().addSolid(CollisionTube(a[0], a[1], a[2], b[0], b[1], b[2], radius))
                        stanchion_np.node().setFromCollideMask(OBSTACLE_MASK)
            geomnode.removeAllGeoms()

    def begin_look(self):
        self.look = True

    def end_look(self):
        self.look = False
        self.prev_pos = None

    def MouseTask(self, task):
        if self.mouseWatcherNode.hasMouse():
            (x, y) = self.mouseWatcherNode.getMouse()
            if self.prev_pos:
                if self.look or self.active_char.spinning:
                    h_diff = (x - self.prev_pos[0]) * 180
                    p_diff = (y - self.prev_pos[1]) * 90
                    new_h = clamp_deg_sign(self.char_rig.getH() - h_diff)
                    self.char_rig.setH(new_h)
                    self.cam.setP(self.cam.getP() + p_diff)
                    self.active_char.spin(new_h)
            self.prev_pos = (x, y)
        return task.cont
Example #41
0
    def __init__(self):
        """ Initializes the Simulator object """


        props = WindowProperties( )
        props.setTitle( 'IsisWorld v0.3' )
        base.win.requestProperties( props )
        # initialize GUI components 
        self.title = OnscreenText(text="IsisWorld",
                              style=1, fg=(0,1,1,1), font = self.font,
                              pos=(0.85,0.95,1), scale = .07)
        self.escapeEventText = self.genLabelText("ESC: quit", 0)
        self.instuctText_3   = self.genLabelText("a,s: Rotate world camera", 1)
        self.pauseEventText  = self.genLabelText("p: (un)pause; SPACE advances simulator one time step.",2)
        self.instuctText_1   = self.genLabelText("up,down,left,right: to control Ralph's direction", 3)
        self.instuctText_2   = self.genLabelText("h,j,k,l: to control Ralph's head orientation", 4)
        self.objectText      = self.genLabelText("o: display objects in Ralph's visual field", 5)
       
        self.teacher_utterances = [] # last message typed
        # main dialogue box
        def disable_keys(x):
            # print "disabling"
            x.command_box.enterText("")
            x.command_box.suppressKeys=True
            x.command_box["frameColor"]=(0.631, 0.219, 0.247,1)

        def enable_keys(x):
            # print "enabling"
            x.command_box["frameColor"]=(0.631, 0.219, 0.247,.25)
            x.command_box.suppressKeys=False

        def accept_message(message,x):
            x.teacher_utterances.append(message)
            x.command_box.enterText("")
            

        #text_fg=((.094,0.137,0.0039,1),
        self.command_box = DirectEntry(pos=(-1.2,-0.95,-0.95), text_fg=(0.282, 0.725, 0.850,1), frameColor=(0.631, 0.219, 0.247,0.25), suppressKeys=1, initialText="enter text and hit return", enableEdit=0,scale=0.07, focus=0, focusInCommand=disable_keys, focusOutCommand=enable_keys, focusInExtraArgs=[self], focusOutExtraArgs=[self], command=accept_message, extraArgs=[self], entryFont=self.font,  width=15, numLines=1)
        #base.win.setColor(0.5,0.8,0.8)
        base.win.setClearColor(Vec4(0,0,0,1))
	
        self.initialize_simulator_relax_thread_task()
        

        # setup terrain
        self.env = loader.loadModel("models/world/world")
        self.env.reparentTo(render)
        self.env.setPos(0,0,0)
        self.env.setCollideMask(BitMask32.bit(1))
        self.env.setColor(0.5,0.8,0.8)
        render.showBounds()
        
        #self.goal_sleep = Bar(100,1)
        #self.goal_sleep.reparentTo(render)

        dlight = DirectionalLight('dlight')
        dlight.setColor(VBase4(0.6, 0.6, 0.6, 1))
        dlnp = render.attachNewNode(dlight)
        dlnp.setHpr(-60, -60, 0)
        render.setLight(dlnp)

        alight = AmbientLight('alight')
        alight.setColor(VBase4(1.0, 1.0, 1.0, 1))
        alnp = render.attachNewNode(alight)
        render.setLight(alnp)
	
        self.agent = Character(self, "models/ralph/ralph", {"walk":"models/ralph/ralph-walk", "run": "models/ralph/ralph-run"}, VBase3(6, 2, 0), .2)

        self.agent.control__say("Hi, I'm Ralph. Please build me.")
        ### Set up displays and cameras ###
        self.camera = FloatingCamera(self.agent.actor)
        # set up picture in picture
        dr = base.camNode.getDisplayRegion(0)
        aspect_ratio = 16.0 / 9.0
        window = dr.getWindow()
        pip_size = 0.40 # percentage of width of screen
        dr_pip = window.makeDisplayRegion(1-pip_size,1,0,(1.0 / aspect_ratio) * float(dr.getPixelWidth())/float(dr.getPixelHeight()) * pip_size)
        dr_pip.setCamera(self.agent.fov)
        dr_pip.setSort(dr.getSort())
        dr_pip.setClearColor(VBase4(0, 0, 0, 1))
        dr_pip.setClearColorActive(True)
        dr_pip.setClearDepthActive(True)
        #self.agent.fov.node().getLens().setAspectRatio(aspect_ratio)
        dr_pip.setActive(1)
	
        ## SET UP I/O ##
        base.disableMouse()
        # Accept some keys to move the camera.
        self.accept("a-up", self.camera.setControl, ["right", 0])
        self.accept("a",    self.camera.setControl, ["right", 1])
        self.accept("s-up", self.camera.setControl, ["left",  0])
        self.accept("s",    self.camera.setControl, ["left",  1])
        # control keys to move the character
        self.accept("arrow_left",     self.agent.control__turn_left__start,     [])
        self.accept("arrow_left-up",  self.agent.control__turn_left__stop,      [])
        self.accept("arrow_right",    self.agent.control__turn_right__start,    [])
        self.accept("arrow_right-up", self.agent.control__turn_right__stop,     [])
        self.accept("arrow_up",       self.agent.control__move_forward__start,  [])
        self.accept("arrow_up-up",    self.agent.control__move_forward__stop,   [])
        self.accept("arrow_down",     self.agent.control__move_backward__start, [])
        self.accept("arrow_down-up",  self.agent.control__move_backward__stop,  [])
        # head movement controls (vi direction map)  
        self.accept("k",              self.agent.control__look_up__start, [])
        self.accept("k-up",           self.agent.control__look_up__stop, [])
        self.accept("j",              self.agent.control__look_down__start, [])
        self.accept("j-up",           self.agent.control__look_down__stop, [])
        self.accept("h",              self.agent.control__look_left__start, [])
        self.accept("h-up",           self.agent.control__look_left__stop, [])
        self.accept("l",              self.agent.control__look_right__start, [])
        self.accept("l-up",           self.agent.control__look_right__stop, [])
        # key input
        self.accept("escape", self.user_requests_quit)
        self.accept("space",  self.step_simulation, [.1]) # argument is amount of second to advance
        self.accept("o", self.print_objects) # displays objects in field of view 
        self.accept("p", self.toggle_paused)
        self.accept("r", self.reset_simulation)

        taskMgr.add(self.move,"moveTask") # Note: deriving classes DO NOT need
	
        # xmlrpc server command handler
        xmlrpc_command_handler = Command_Handler(self)
	
        # xmlrpc server
        self.server_object = HomeSim_XMLRPC_Server()
        self.server = self.server_object.server
        self.server.register_function(xmlrpc_command_handler.command_handler,'do')
        self.server_thread = Thread(group=None, target=self.server.serve_forever, name='xmlrpc')
        self.server_thread.start()
        
	
        self.reset_simulation()
Example #42
0
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
 def buildDirectionalLight(self, hpr, pos, color, near, far, casts_shadow,
                           shadow_caster, film_size):
     """
 Builds a Panda3D directional light with the specified rotation, position
 and color. 
 NOTE: This light tends to be buggy. Requires at least one spotlight for it 
 to work properly. 
 """
     if not self.has_dlight:
         self.light_counter += 1
         dlight = DirectionalLight("light%s" % self.light_counter)
         dlight.getLens().setFilmSize(*film_size)
         dlight.getLens().setNearFar(near, far)
         if shadow_caster:
             x, y = shadow_caster
             dlight.setShadowCaster(True, x, y)
         else:
             dlight.setShadowCaster(False)
         #dlight.showFrustum()
         dlightnp = render.attachNewNode(dlight)
         dlightnp.setPos(VBase3(*pos))
         dlightnp.setHpr(VBase3(*hpr))
         dlight.setColor(VBase4(*color))
         render.setLight(dlightnp)
         return dlightnp
     else:
         return 0
Example #44
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
Example #45
0
  def __init_kepler_scene(self):
    self.hud_count_down = 0
    self.alpha = 0.
    self.beta = 0.  
    self._set_title("Hugomatic 3D sim")
    self.alpha_rot_speed = 0.
    self.beta_rot_speed = 0.
    
    #This code puts the standard title and instruction text on screen
    self.title = OnscreenText(text="Kepler simulation tool 1",
                              style=1, fg=(1,1,1,1),
                              pos=(0.7,-0.95), scale = .07, font = font)
    
    self.instructions = OnscreenText(text="alpha: 0.000\nbeta: 0.000",
                                     pos = (-1.3, .95), fg=(1,1,1,1), font = font,
                                     align = TextNode.ALeft, scale = .05)
    
    if DISABLE_MOUSE:
        base.disableMouse()                    #Disable mouse-based camera control
    camera.setPosHpr(-10, -10, 25, 0, -90, 0)  #Place the camera

    #Load the maze and place it in the scene
    self.maze = loader.loadModel("models/maze")
    process_model(self.maze)
    self.maze.reparentTo(render)

    #Most times, you want collisions to be tested against invisible geometry
    #rather than every polygon. This is because testing against every polygon
    #in the scene is usually too slow. You can have simplified or approximate
    #geometry for the solids and still get good results.
    #
    #Sometimes you'll want to create and position your own collision solids in
    #code, but it's often easier to have them built automatically. This can be
    #done by adding special tags into an egg file. Check maze.egg and ball.egg
    #and look for lines starting with <Collide>. The part is brackets tells
    #Panda exactly what to do. Polyset means to use the polygons in that group
    #as solids, while Sphere tells panda to make a collision sphere around them
    #Keep means to keep the polygons in the group as visable geometry (good
    #for the ball, not for the triggers), and descend means to make sure that
    #the settings are applied to any subgroups.
    #
    #Once we have the collision tags in the models, we can get to them using
    #NodePath's find command

    #Find the collision node named wall_collide
    self.walls = self.maze.find("**/wall_collide")

    #Collision objects are sorted using BitMasks. BitMasks are ordinary numbers
    #with extra methods for working with them as binary bits. Every collision
    #solid has both a from mask and an into mask. Before Panda tests two
    #objects, it checks to make sure that the from and into collision masks
    #have at least one bit in common. That way things that shouldn't interact
    #won't. Normal model nodes have collision masks as well. By default they
    #are set to bit 20. If you want to collide against actual visible polygons,
    #set a from collide mask to include bit 20
    #
    #For this example, we will make everything we want the ball to collide with
    #include bit 0
    self.walls.node().setIntoCollideMask(BitMask32.bit(0))
    #CollisionNodes are usually invisible but can be shown. Uncomment the next
    #line to see the collision walls
    if VISIBLE_WALLS:
        self.walls.show()

    #Ground_collide is a single polygon on the same plane as the ground in the
    #maze. We will use a ray to collide with it so that we will know exactly
    #what height to put the ball at every frame. Since this is not something
    #that we want the ball itself to collide with, it has a different
    #bitmask.
    self.mazeGround = self.maze.find("**/ground_collide")
    self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1))
    
    #Load the ball and attach it to the scene
    #It is on a root dummy node so that we can rotate the ball itself without
    #rotating the ray that will be attached to it
    self.ballRoot = render.attachNewNode("ballRoot")
    self.ball = loader.loadModel("models/ball")
    self.ball.reparentTo(self.ballRoot)

    #Find the collison sphere for the ball which was created in the egg file
    #Notice that it has a from collision mask of bit 0, and an into collison
    #mask of no bits. This means that the ball can only cause collisions, not
    #be collided into
    self.ballSphere = self.ball.find("**/ball")
    self.ballSphere.node().setFromCollideMask(BitMask32.bit(0))
    self.ballSphere.node().setIntoCollideMask(BitMask32.allOff())

    #No we create a ray to start above the ball and cast down. This is to
    #Determine the height the ball should be at and the angle the floor is
    #tilting. We could have used the sphere around the ball itself, but it
    #would not be as reliable
    self.ballGroundRay = CollisionRay()     #Create the ray
    self.ballGroundRay.setOrigin(0,0,10)    #Set its origin
    self.ballGroundRay.setDirection(0,0,-1) #And its direction
    #Collision solids go in CollisionNode
    self.ballGroundCol = CollisionNode('groundRay') #Create and name the node
    self.ballGroundCol.addSolid(self.ballGroundRay) #Add the ray
    self.ballGroundCol.setFromCollideMask(BitMask32.bit(1)) #Set its bitmasks
    self.ballGroundCol.setIntoCollideMask(BitMask32.allOff())
    #Attach the node to the ballRoot so that the ray is relative to the ball
    #(it will always be 10 feet over the ball and point down)
    self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol)
    #Uncomment this line to see the ray
    self.ballGroundColNp.show()

    #Finally, we create a CollisionTraverser. CollisionTraversers are what
    #do the job of calculating collisions
    self.cTrav = CollisionTraverser()
    #Collision traverservs tell collision handlers about collisions, and then
    #the handler decides what to do with the information. We are using a
    #CollisionHandlerQueue, which simply creates a list of all of the
    #collisions in a given pass. There are more sophisticated handlers like
    #one that sends events and another that tries to keep collided objects
    #apart, but the results are often better with a simple queue
    self.cHandler = CollisionHandlerQueue()
    #Now we add the collision nodes that can create a collision to the
    #traverser. The traverser will compare these to all others nodes in the
    #scene. There is a limit of 32 CollisionNodes per traverser
    #We add the collider, and the handler to use as a pair
    self.cTrav.addCollider(self.ballSphere, self.cHandler)
    self.cTrav.addCollider(self.ballGroundColNp, self.cHandler)

    #Collision traversers have a built in tool to help visualize collisions.
    #Uncomment the next line to see it.
    if VISIBLE_WALLS:
        self.cTrav.showCollisions(render)
    
    #This section deals with lighting for the ball. Only the ball was lit
    #because the maze has static lighting pregenerated by the modeler
    lAttrib = LightAttrib.makeAllOff()
    ambientLight = AmbientLight( "ambientLight" )
    ambientLight.setColor( Vec4(.55, .55, .55, 1) )
    lAttrib = lAttrib.addLight( ambientLight )
    directionalLight = DirectionalLight( "directionalLight" )
    directionalLight.setDirection( Vec3( 0, 0, -1 ) )
    directionalLight.setColor( Vec4( 0.375, 0.375, 0.375, 1 ) )
    directionalLight.setSpecularColor(Vec4(1,1,1,1))
    lAttrib = lAttrib.addLight( directionalLight )
    self.ballRoot.node().setAttrib( lAttrib )
    
    #This section deals with adding a specular highlight to the ball to make
    #it look shiny
    m = Material()
    m.setSpecular(Vec4(1,1,1,1))
    m.setShininess(96)
    self.ball.setMaterial(m, 1)

    #Finally, we call start for more initialization
    # self.start()
  
      
    #def start(self):
    #The maze model also has a locator in it for where to start the ball
    #To access it we use the find command
    startPos = (0,0,0)#= self.maze.find("**/start").getPos()
    self.ballRoot.setPos(startPos)   #Set the ball in the starting position
    self.ballV = Vec3(0,0,0)         #Initial velocity is 0
    self.accelV = Vec3(0,0,0)        #Initial acceleration is 0
    
    #For a traverser to actually do collisions, you need to call
    #traverser.traverse() on a part of the scene. Fortunatly, base has a
    #task that does this for the entire scene once a frame. This sets up our
    #traverser as the one to be called automatically
    base.cTrav = self.cTrav
Example #46
0
 def loadLights(self):
     light1 = DirectionalLight('light1')
     lightNode1 = render.attachNewNode(light1)
     light1.setDirection( Vec3(-1, 0.5, -0.25) )
     light1.setColor( Vec4(0.5, 0.9, 0.9, 0) )
     render.setLight(lightNode1)
Example #47
0
    base.cam.setY(self.avatar.getY()-self.camdistY)
    if self.steer2d:
      base.cam.setX(self.avatar.getX())
      base.cam.setZ(self.avatar.getZ()+self.camdistZ)
    base.cam.lookAt(self.avatar)

    return Task.cont

#=========================================================================
# Main
#=========================================================================

alight = AmbientLight('alight')
alight.setColor((.3, .3, .3, 1))
alnp = render.attachNewNode(alight)
render.setLight(alnp)

dlight = DirectionalLight('dlight')
lv=.6
dlight.setColor((lv,lv,lv, 1))
dlnp = render.attachNewNode(dlight)
render.setLight(dlnp)
dlnp.setPos(0,-20,35)
dlnp.lookAt(0,0,0)

DO=DirectObject()
DO.accept('c', toggle_collisions)
DO.accept('h', toggle_info)
DO.accept('x', toggle_wire)
DO.accept('escape',sys.exit)