def __init__(self, *args, **kwargs): ViewTowers.__init__(self, *args, **kwargs) # ignore keys set by viewer for key in self.getAllAccepting(): if key in ("s", "escape"): continue self.ignore(key) self.permanent_events = self.getAllAccepting() # global variables self.text_bg = (1, 1, 1, 0.7) self.font = self.loader.loadFont('cmr12.egg') self.question = ( "Use the mouse to indicate the direction that " "the tower will fall.") self.feedback_time = 3.0 self.buffer_time = 0.75 # create text self.create_all_text() # create direction line self.line = LineSegs() self.line_node = None self.angle = None alight = AmbientLight('alight3') alight.setColor((0.8, 0.8, 0.8, 1)) self.line_light = self.lights.attachNewNode(alight)
def __init__(self, *args, **kwargs): ViewTowers.__init__(self, *args, **kwargs) # ignore keys set by viewer for key in self.getAllAccepting(): if key in ("s", "escape"): continue self.ignore(key) self.permanent_events = self.getAllAccepting() # global variables self.text_bg = (1, 1, 1, 0.7) self.font = self.loader.loadFont("cmr12.egg") self.question = "Use the mouse to indicate the direction that " "the tower will fall." self.feedback_time = 3.0 self.buffer_time = 0.75 # create text self.create_all_text() # create direction line self.line = LineSegs() self.line_node = None self.angle = None alight = AmbientLight("alight3") alight.setColor((0.8, 0.8, 0.8, 1)) self.line_light = self.lights.attachNewNode(alight)
class Lighting: def __init__(self, ancestor = None): print "____________________________________________________" print "Class Lights" self.ancestor = ancestor #Initialize bg colour colour = (0.2, 0.2, 0.6) base.setBackgroundColor(*colour) base.camLens.setFar(1000.0) self.alight = AmbientLight('ambient_light') self.alight.setColor(Vec4(0.7, 0.7, 0.7, 1)) self.alnp = base.render.attachNewNode(self.alight) base.render.setLight(self.alnp) self.plight = PointLight('sunlight') self.plight.setColor(Vec4(2.5, 2.5, 2.5, 1)) self.plnp = base.render.attachNewNode(self.plight) self.plnp.setPos(50, 0, 300) self.plnp.lookAt(self.ancestor.terrain.root) base.render.setLight(self.plnp) # Initialize linear fog self.fog = Fog("Fog object") self.fog.setMode(Fog.MLinear) self.fog.setLinearRange(14.0,40.0) self.fog.setColor(*colour)
def __init__(self): # Display nodes creation self.patches_node = render.attachNewNode("patches_node") self.agents_node = render.attachNewNode("agents_node") self.lines_node = render.attachNewNode("lines_node") self.light_node = render.attachNewNode("light_node") self.floor_node = render.attachNewNode("floor_node") self.frame_node = render.attachNewNode("frame_node") self.env_node = render.attachNewNode("env_node") # Light settings self.light = True self.dlight = PointLight("dlight") self.dlight.setColor(Vec4(.8,.8,.5,1)) self.dlnp = render.attachNewNode(self.dlight) self.dlnp.setPos(0,100,100) render.setLight(self.dlnp) ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.4, .4, .4, 1)) render.setLight(render.attachNewNode(ambientLight)) #self.create_floor(121, 121, "grass_floor") self.create_frame(121, 121, 0) self.add_model(self.env_node, "env", (60,60,-0.5), 200) self.fill_env() taskMgr.add(self.game_loop, "game_loop") taskMgr.add(self.close_window, "close_window")
def create( self ): lightAttrib = LightAttrib.makeAllOff() #create ambient light ambientLight = AmbientLight( "ambientLight" ) ambientLight.setColor( self.ambientColor ) lightAttrib = lightAttrib.addLight( ambientLight ) render.attachNewNode( ambientLight.upcastToPandaNode() ) self.ambientLight = ambientLight #default light settings """colors = [ Vec4(1,0,0,0), Vec4(0,1,0,0), Vec4(0,0,1,0), Vec4(1,1,0,0) ] directions = [ Vec3(1,0,0), Vec3(0,1,0), Vec3(-1,0,0), Vec3(0,-1,0) ] intensities = [ 3.0, 0.1, 3.0, 0.1 ]""" colors = [ Vec4(1,1,1,0), Vec4(0,1,0,0), Vec4(0,0,1,0), Vec4(1,1,0,0) ] # basic 3+1 point lighting directions = [ Vec3(0,1,-0.2), Vec3(0,1,0), Vec3(-1,0.3,0), Vec3(0,-1,0) ] intensities = [ 1.0, 0.0, 0.5, 0.0 ] #add directional lights self.directionalLights = [] for i in range(4): self.directionalLights.append( ShaderDirectionalLight( colors[i], directions[i], intensities[i], i ) ) lightAttrib = self.directionalLights[i].create( lightAttrib ) #set light attributes render.node().setAttrib( lightAttrib )
def __init__(self): ShowBase.__init__(self) wp = WindowProperties() wp.setSize(850, 480) wp.setTitle("GAME") base.win.requestProperties(wp) bgg = BlockGeometryGenerator() blocks = [] for x in xrange(1): for y in xrange(512): for z in xrange(64): bid = random.randint(0, 255) blocks.append(bid) bgg.GenerateBlockGeometry(x, y, z, Block(bid), [0]) #blocks[x * 512 * 64 + y * 64 + z] = 1 print x ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) ambientLightNP = render.attachNewNode(ambientLight) render.setLight(ambientLightNP)
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 AmbientLight alight = AmbientLight('alight') alight.setColor(VBase4(*[x / 127.0 for x in self.color] + [1.0])) self.node_path = self.parent.node_path_mesh.attachNewNode(alight) self.parent.node_path_mesh.setLight(self.node_path)
def setLight(self): pLight = PointLight('pLight') plnp = base.render.attachNewNode(pLight) plnp.setPos(37, 10, 15) alight = AmbientLight('alight') alight.setColor(VBase4(0.2, 0.25, 0.25, 1)) alnp = base.render.attachNewNode(alight) base.render.setLight(plnp) base.render.setLight(alnp)
def loadStars(self): ambientlight = AmbientLight('alight') ambientlight.setColor(Vec4(1, 1, 1, 0)) lightnode = render.attachNewNode(ambientlight) self.stars = loader.loadModel("stars.bam") self.stars.setLight(lightnode) self.stars.setScale(1000) self.stars.setPos(0, 0, 0) self.stars.reparentTo(render) self.starsRotation = self.stars.getQuat()
def loadStars(self): ambientlight = AmbientLight('alight') ambientlight.setColor( Vec4(1, 1, 1, 0) ) lightnode = render.attachNewNode(ambientlight) self.stars = loader.loadModel("stars.bam") self.stars.setLight(lightnode) self.stars.setScale(1000) self.stars.setPos(0,0,0) self.stars.reparentTo(render) self.starsRotation = self.stars.getQuat()
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)
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)
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 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 )
def loadLights(self): plight = AmbientLight('my plight') plight.setColor(VBase4(0.12, 0.12, 0.12, 1)) self.plnp = self.render.attachNewNode(plight) self.render.setLight(self.plnp) light4 = PointLight('pointlight3') plnp4 = self.render.attachNewNode(light4) plnp4.setPos(10, 0, 8) light5 = PointLight('pointlight5') self.plnp5 = self.render.attachNewNode(light5) self.plnp5.setPos(10,0, 8) self.render.setLight(self.plnp5)
def _set_light_sources(self): light_positions = [(1, -1, 1), (-1, -5, 1)] intensity = 0.8 for l_pos in light_positions: plight = PointLight('plight') plight.setColor(VBase4(intensity, intensity, intensity, 1)) plnp = render.attachNewNode(plight) plnp.setPos(l_pos[0], l_pos[1], l_pos[2]) render.setLight(plnp) light = AmbientLight('') light.setColor(VBase4(0.4, 0.4, 0.4, 1)) light_np = render.attachNewNode(light) light_np.setPos(0, 0, 0) render.setLight(light_np) pass
def __init__(self): ShowBase.__init__(self) base.setFrameRateMeter(True) # base.disableMouse() # initialise the lights alight = AmbientLight('alight') alight.setColor(VBase4(0.2, 0.2, 0.2, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) # Initialise the Ode world self.world = OdeWorld() self.world.setGravity(0, 0, -9.81) # load the models # environment self.environ = self.loader.loadModel("data/models/Plane") # Reparent the model to render. self.environ.reparentTo(self.render) # Apply scale and position transforms on the model. self.environ.setScale(10, 10, 10) self.environ.setPos(0, 0, 0) # racer self.glider = self.loader.loadModel("data/models/vehicle01") # Reparent the model to render. self.glider.reparentTo(self.render) # Apply scale and position transforms on the model. self.glider.setScale(1, 1, 1) self.glider.setPos(0, 0, 50) self.myBody = OdeBody(self.world) self.myBody.setPosition(self.glider.getPos(render)) self.myBody.setQuaternion(self.glider.getQuat(render)) self.myMass = OdeMass() self.myMass.setBox(11340, 1, 1, 1) self.myBody.setMass(self.myMass) # set up the camera base.camera.reparentTo(self.glider) base.camera.setPos(0, -30, 10) base.camera.lookAt(self.glider) # add physics to taskmgr taskMgr.add(self.physicsTask, 'physics')
def initAnchor(self): self.anchor = loader.loadModel(self.main.modeld + "planet") self.anchor.reparentTo(self.main.systemNP) self.anchor.setScale(15) self.anchor_tex = loader.loadTexture(self.main.modeld + "anchor.jpg") self.anchor.setTexture(self.anchor_tex) self.anchor_sp = self.main.getPlist()[0] # anchor가 선택한 행성 (혹은 항성) self.anchor.setPos(self.anchor_sp.getPos()) self.anchor.setZ(self.anchor_sp.getZ() + 2 * self.anchor_sp.getScale().getX()) al = AmbientLight("d") al.setColor(VBase4(1, 1, 1, 1)) alnp = self.anchor.attachNewNode(al) self.anchor.setLight(alnp) self.anchor_spin = self.anchor.hprInterval(3.0, VBase3(360, 0, 0)) self.anchor_spin.loop()
def buildAmbientLight(self, color): """ Builds a Panda3D Ambient Light with the specified color. """ alight = render.attachNewNode(AmbientLight("Ambient")) alight.node().setColor(Vec4(*color)) render.setLight(alight) return alight
def _set_light_sources(self): light_positions = [(1,-1,1),(-1,-5,1)] intensity = 0.8 for l_pos in light_positions: plight = PointLight('plight') plight.setColor(VBase4(intensity, intensity, intensity, 1)) plnp = render.attachNewNode(plight) plnp.setPos(l_pos[0], l_pos[1], l_pos[2]) render.setLight(plnp) light = AmbientLight('') light.setColor(VBase4(0.4,0.4,0.4,1)) light_np = render.attachNewNode(light) light_np.setPos(0,0,0) render.setLight(light_np) pass
def __init__(self, game): super(World, self).__init__() self.game = game self.things = [] #initialize the rendering self.renderer = self.game.render self.initFog() #FIXME do better lighting alight = AmbientLight('alight') alight.setColor(VBase4(0.2, 0.2, 0.2, 1)) alnp = self.renderer.attachNewNode(alight) self.renderer.setLight(alnp) #initialize a hud self.hud = HUD() self.add(self.hud) #physics self.world = OdeWorld() self.world.setGravity(0, -20, 0) #FIXME (0,-9.81) would be realistic physics self.world.initSurfaceTable(1) self.world.setSurfaceEntry(0, 0, 0.6, 0.0, 9.1, 0.9, 0.00001, 1.0, 0.02) #FIXME I have no idea what this means self.space = OdeSimpleSpace() self.space.setAutoCollideWorld(self.world) self.contactGroup = OdeJointGroup() self.space.setAutoCollideJointGroup(self.contactGroup) #constrain to 2d self.plane = OdePlane2dJoint(self.world) self.timeAccumulator = 0 self.dt = 1.0 / 60.0 #give it a player self.player = Player(self, Point3(0,10,0)) self.add(self.player) self.game.taskMgr.add(self.player.move, "movePlayer")
def __init__(self): super(SimViewer, self).__init__() # Make a window. size = (700, 520) self.create_output(size, "SimViewer") self.output.setClearColor((0.0, 0.0, 0.0, 1.0)) # Lights node self.lights = NodePath('lights') # Create a spotlight slight = Spotlight('slight') slight.setScene(self.root) slight.setShadowCaster(True, 2**11, 2**11) # Set shadow mask, so we can exclude objects from casting shadows self.shadow_mask = BitMask32.bit(2) slight.setCameraMask(self.shadow_mask) c = 1.4 slight.setColor((c, c, c, 1.0)) slight.getLens().setNearFar(4, 100) slight.getLens().setFov(45) slnp = self.lights.attachNewNode(slight) slnp.setPos((7, 10, 40)) slnp.lookAt(2, 0, 1.5) self.root.setLight(slnp) # Create an ambient light. alight = AmbientLight('alight') c = 0.6 alight.setColor((c, c, c, 1.0)) alnp = self.lights.attachNewNode(alight) self.root.setLight(alnp) self.lights.reparentTo(self.root) # Set auto shading for shadows. self.root.setShaderAuto() # Set antialiasing on. self.root.setAntialias(AntialiasAttrib.MAuto) # Camera. lens = PerspectiveLens() self.lens = lens self.lens.setNearFar(0.1, 1000.) self.lens.setFov((40, 30)) self.cameras = self.root.attachNewNode('cameras') self.camera = self.make_camera(self.output, lens=self.lens) self.camera.setPos(15, 44, 3.) self.camera.setPos(15, 35, 15.) self.camera.lookAt(0, 0, 1.)
def __init__(self, filters): self.skybox = SkyBox() self.sun = Sun(filters) self.clouds = CloudLayer() self.fog = DistanceFog() #self.addDirectLight() self.dayLength = 120 #in seconds self.setTime(800.0) self.previousTime = 0 self.nightSkip = True self.paused = False ambient = Vec4(0.55, 0.65, 1.0, 1) #bright for hdr alight = AmbientLight('alight') alight.setColor(ambient) alnp = render.attachNewNode(alight) render.setLight(alnp) render.setShaderInput('alight0', alnp)
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()
def setupLights( self ): # create a point light plight = PointLight('plight') # set its color plight.setColor(VBase4( 0.2, 0.2, 0.2, 1 ) ) # attach it to the render as a new node # 'upcast' to a node otherwise Panda will crash # heard this will change in version 1.1.? plnp = render.attachNewNode( plight ) # set the position of the node plnp.setPos( 0, 0, 0 ) # set the light or 'turn' it on render.setLight( plnp ) # the following code makes the 'shadows' less black or dark # same as above but we create a ambient light that affects all faces alight = AmbientLight( 'alight' ) # light alight.setColor( VBase4( 0.2, 0.2, 0.2, 1 ) ) # color alnp = render.attachNewNode( alight ) # attach render.setLight( alnp ) # turn on
def __init__(self): ShowBase.__init__(self) # ambient light, so we can see colors on models alight = AmbientLight('alight') alight.setColor(VBase4(1, 1, 1, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) # this piece of code loads a model, and places it at (1,3,0) # it will be visible as soon as the program is started self.cityModel = self.loader.loadModel('models/City.egg') self.cityModel.setPos(1, 3, 0) # reparenting to "render" causes it to be displayed (render is the # root of the object tree self.cityModel.reparentTo(self.render) self.taskMgr.add(self.move_city, "move_city")
def create(self): lightAttrib = LightAttrib.makeAllOff() #create ambient light ambientLight = AmbientLight("ambientLight") ambientLight.setColor(self.ambientColor) lightAttrib = lightAttrib.addLight(ambientLight) render.attachNewNode(ambientLight.upcastToPandaNode()) self.ambientLight = ambientLight #default light settings """colors = [ Vec4(1,0,0,0), Vec4(0,1,0,0), Vec4(0,0,1,0), Vec4(1,1,0,0) ] directions = [ Vec3(1,0,0), Vec3(0,1,0), Vec3(-1,0,0), Vec3(0,-1,0) ] intensities = [ 3.0, 0.1, 3.0, 0.1 ]""" colors = [ Vec4(1, 1, 1, 0), Vec4(0, 1, 0, 0), Vec4(0, 0, 1, 0), Vec4(1, 1, 0, 0) ] # basic 3+1 point lighting directions = [ Vec3(0, 1, -0.2), Vec3(0, 1, 0), Vec3(-1, 0.3, 0), Vec3(0, -1, 0) ] intensities = [1.0, 0.0, 0.5, 0.0] #add directional lights self.directionalLights = [] for i in range(4): self.directionalLights.append( ShaderDirectionalLight(colors[i], directions[i], intensities[i], i)) lightAttrib = self.directionalLights[i].create(lightAttrib) #set light attributes render.node().setAttrib(lightAttrib)
class AmbLight: """Creates a simple ambient light""" def __init__(self, manager, xml): self.light = PAmbientLight('alight') self.lightNode = render.attachNewNode(self.light) self.reload(manager, xml) def reload(self, manager, xml): color = xml.find('color') if color != None: self.light.setColor( VBase4(float(color.get('r')), float(color.get('g')), float(color.get('b')), 1.0)) def start(self): render.setLight(self.lightNode) def stop(self): render.clearLight(self.lightNode)
def startGame(self): ''' Start the game ''' base.enableParticles() # self.p = ParticleEffect() # self.loadParticleConfig('./data.parcticles/blowout_fire.ptf') # Start of the code from steam.ptf # self.p.cleanup() self.p = ParticleEffect() self.p.loadConfig('./data/particles/blowout_test.ptf') # Sets particles to birth relative to the teapot, but to render at toplevel self.p.start(render) self.p.setPos(0.000, 0.000, 0) # Load the Lights ambilight = AmbientLight('ambilight') ambilight.setColor(VBase4(0.2, 0.2, 0.2, 1)) render.setLight(render.attachNewNode(ambilight))
class AmbLight: """Creates a simple ambient light""" def __init__(self,manager,xml): self.light = PAmbientLight('alight') self.lightNode = render.attachNewNode(self.light) self.reload(manager,xml) def reload(self,manager,xml): color = xml.find('color') if color!=None: self.light.setColor(VBase4(float(color.get('r')), float(color.get('g')), float(color.get('b')), 1.0)) def start(self): render.setLight(self.lightNode) def stop(self): render.clearLight(self.lightNode)
def __init__(self, gameManager, gameData, *args, **kwargs): BaseState.__init__(self, gameManager, *args, **kwargs) self._gameData = gameData self._gameData.scene.reparentTo(render) base.camera.display() plight = PointLight('plight') plight.setColor(VBase4(0.2, 0.2, 0.2, 1)) plnp = self._gameData.scene.attachNewNode(plight) plnp.setPos(10, 20, 0) self._gameData.scene.setLight(plnp) alight = AmbientLight('alight') alight.setColor(VBase4(0.2, 0.2, 0.2, 1)) alnp = self._gameData.scene.attachNewNode(alight) self._gameData.scene.setLight(alnp) self.addTask(self.updateTask, 'globalUpdate')
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) """
def SetupLights(self): a = 0.5 d = 0.2 ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(a, a, a, 1)) ambientLightNP = render.attachNewNode(ambientLight) render.setLight(ambientLightNP) dir = [Vec3(1, 1, 1), Vec3(-1, -0.5, -1), Vec3(-0.5, -1, -1)] for i in xrange(3): directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(dir[i]) directionalLight.setColor(Vec4(d, d, d, 1)) render.setLight(render.attachNewNode(directionalLight)) myFog = Fog("Fog Name") myFog.setColor(*Globals.SKY_COLOR) myFog.setLinearRange(40, 70) base.camera.attachNewNode(myFog) render.setFog(myFog) base.setBackgroundColor(*Globals.SKY_COLOR)
def __init__( self, name=NAME_DEFAULT, pos=POS_DEFAULT, heading=HEADING_DEFAULT, vel=VEL_DEFAULT, acc=ACC_DEFAULT # player controlled acceleration. Can be 0.0 - 1.0 ): """@param name string""" self.name = name self.pos = pos self.vel = vel self.acc = acc self.heading = heading self.rotateLeft = False self.rotateRight = False self.visualNode = self.createVisualNode(self.pos) self.bullets = [] self.collisionHandler = colHandler self.collisions = [] self.collisionSphere = OdeSphereGeom(4) self.collisionSphere.setCategoryBits(BitMask32(0xffffffff)) self.collisionSphere.setCollideBits(BitMask32(0xffffffff)) self.collisionSphere.setPosition(pos[0], pos[1], 0) self.forces = [] self.mass = 1.0 self.health = Ship.HEALTH self.isAlive = True self.shootingSound = loader.loadSfx('anti_tank_gun_single_shot.mp3') self.destroySound = loader.loadSfx('large_explosion.mp3') self.bulletHitSound = loader.loadSfx( 'explosion_loud_internal_explosion_very_reverberant.mp3') self.collisionSound = loader.loadSfx('car_door_close.mp3') self.bulletParent = NodePath("Bullet Parent") self.bulletParent.reparentTo(render) self.bulletAmbientLight = AmbientLight('Bullet Light') self.bulletAmbientLight.setColor(Vec4(.0, .1, .2, .0)) lightnode = render.attachNewNode(self.bulletAmbientLight) self.bulletParent.setLight(lightnode)
def setupLighting(self, sizeVector, centerPos): x, y, z = centerPos sx, sy, sz = (Vec3(sizeVector) * 0.8) # Point lights, one in each ceiling corner. for i in (x-sx, x+sx): for j in (y-sy, y+sy): for k in (z+sz,): self.addPointLight((i, j, k)) # Ambient light. c = 0.4 lightA = AmbientLight("light-ambient") lightA.setColor(VBase4(c, c, c, 1)) lightANode = render.attachNewNode(lightA) render.setLight(lightANode) # Fog. fog = Fog("fog") fog.setColor(1, 1, 1) fog.setExpDensity(0.002) render.setFog(fog)
def 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)
def __init__(self): base.setBackgroundColor(0, 0, 0) render.setAntialias(AntialiasAttrib.MMultisample, 1) #Lighting # dirLight = DirectionalLight("directional") # dirLight.setColor(Vec4(1.0, 1.0, 1.0, 1.0)) # dirNode = render.attachNewNode(dirLight) # dirNode.setHpr(60, 0, 90) # render.setLight(dirNode) alight = AmbientLight('alight') alight.setColor(VBase4(0.5, 0.5, 0.75, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) render.setShaderAuto() self.sky = loader.loadModel("models/environment/solar_sky_sphere") self.sky_tex = loader.loadTexture("models/environment/universe.png") self.sky.setTexture(self.sky_tex, 1) self.sky.reparentTo(render) self.sky.setScale(UNIVERSE_SCALE*5)
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)
class Ship: NAME_DEFAULT = "unnamed" POS_DEFAULT = (0, 30) VEL_DEFAULT = (0, 0) ACC_DEFAULT = 0.0 # 0.0 - 1.0 HEADING_DEFAULT = -90.0 ACC_COEFFICIENT = 35.0 # This is how much acceleration affects speed ROTATION_SPEED = 200 MODEL_ROTATION_OFFSET = (0.0, 0.0, -5.0) HEALTH = 10.0 BULLET_OFFSET = 5.0 # This is how far ahead the bullet spawns at BULLET_SPEED = 200 BULLET_SHIP_SPEED_CORRELATION = 40.0 BULLET_MAX_LIFE_TIME = 100 BULLET_DAMAGE = 1.0 PLANET_DAMAGE = 0.5 SPEED_MAX = 50.0 def __init__( self, name=NAME_DEFAULT, pos=POS_DEFAULT, heading=HEADING_DEFAULT, vel=VEL_DEFAULT, acc=ACC_DEFAULT # player controlled acceleration. Can be 0.0 - 1.0 ): """@param name string""" self.name = name self.pos = pos self.vel = vel self.acc = acc self.heading = heading self.rotateLeft = False self.rotateRight = False self.visualNode = self.createVisualNode(self.pos) self.bullets = [] self.collisionHandler = colHandler self.collisions = [] self.collisionSphere = OdeSphereGeom(4) self.collisionSphere.setCategoryBits(BitMask32(0xffffffff)) self.collisionSphere.setCollideBits(BitMask32(0xffffffff)) self.collisionSphere.setPosition(pos[0], pos[1], 0) self.forces = [] self.mass = 1.0 self.health = Ship.HEALTH self.isAlive = True self.shootingSound = loader.loadSfx('anti_tank_gun_single_shot.mp3') self.destroySound = loader.loadSfx('large_explosion.mp3') self.bulletHitSound = loader.loadSfx( 'explosion_loud_internal_explosion_very_reverberant.mp3') self.collisionSound = loader.loadSfx('car_door_close.mp3') self.bulletParent = NodePath("Bullet Parent") self.bulletParent.reparentTo(render) self.bulletAmbientLight = AmbientLight('Bullet Light') self.bulletAmbientLight.setColor(Vec4(.0, .1, .2, .0)) lightnode = render.attachNewNode(self.bulletAmbientLight) self.bulletParent.setLight(lightnode) def createVisualNode(self, pos=(0, 0)): # modelNode is the actualy ship model modelNode = loader.loadModel("indicator.bam") # visualNode is the node we operate on to move and rotate the ship visualNode = NodePath('Ship: ' + self.name) visualNode.setPos(tupleToVec3(pos)) visualNode.setHpr(Vec3(0, -90, 90)) # TODO: add scale parameter to this or some other aggregator class visualNode.setScale(1) # Reparent the actual modelNode to the visualNode modelNode.reparentTo(visualNode) # Offset the model node relative to the parent modelNode.setPos(tripleToVec3(Ship.MODEL_ROTATION_OFFSET)) visualNode.reparentTo(render) return visualNode def applyForce(self, force): self.forces.append(force) def setCollisionHandler(self, handler): self.collisionHandler = handler def addCollision(self, col): self.collisions.append(col) self.collisionSound.play() def getCollisions(self): return self.collisions def getVisualNode(self): return self.visualNode def getMass(self): return self.mass def isVisible(self): result = False visualNode = self.getVisualNode() # To be visible the ship has to be not hidden and has to have render as # the master parent (aka getTop). result = (not visualNode.isHidden()) and (visualNode.getTop() == render) return result def setPos(self, pos): self.pos = pos def getPos(self): return self.pos def setVel(self, vel): self.vel = vel self.momentum = vel def getVel(self): return self.vel def getAcc(self): return self.acc def getHeading(self): return self.heading def shoot(self): # TODO: add proper unit tests! angle = self.heading * math.pi / 180.0 headingX = math.cos(angle) headingY = math.sin(angle) offset = Vec3(headingX, headingY, 0) * Ship.BULLET_OFFSET shipPos = self.getPos() bulletPos = (offset[0] + shipPos[0], offset[1] + shipPos[1], offset[2]) bulletVisual = loader.loadModel("bullet.bam") bulletVisual.setPos(tupleToVec3(bulletPos)) bulletVisual.setHpr(tupleToVec3((self.heading + 90, 180))) bulletVisual.setScale(1.5) bulletVisual.reparentTo(self.bulletParent) # Create physics for bullet collisionSphere = OdeSphereGeom(1.5) collisionSphere.setCategoryBits(BitMask32(0xffffffff)) collisionSphere.setCollideBits(BitMask32(0xffffffff)) collisionSphere.setPosition(bulletPos[0], bulletPos[1], bulletPos[2]) shipVel = self.getVel() bullet = { 'vel': (headingX * Ship.BULLET_SPEED + shipVel[0] / Ship.BULLET_SHIP_SPEED_CORRELATION, headingY * Ship.BULLET_SPEED + shipVel[1] / Ship.BULLET_SHIP_SPEED_CORRELATION), 'visual': bulletVisual, 'physical': collisionSphere, 'isAlive': True, 'timeToLive': Ship.BULLET_MAX_LIFE_TIME } self.bullets.append(bullet) self.shootingSound.play() def bulletHit(self): self.health -= Ship.BULLET_DAMAGE if self.health <= 0: self.destroy() self.bulletHitSound.play() def planetHit(self): self.health -= Ship.PLANET_DAMAGE if self.health <= 0.0: self.destroy() self.bulletHitSound.play() def destroyBullet(self, bullet): bullet['visual'].removeNode() #bullet['physical'].destroy() bullet['physical'].disable() # If the "bullet['physical'].destroy()" line is giving errors use the # following one instead: #bullet['physical'].disable() self.bullets.remove(bullet) bullet = None def destroy(self): self.isAlive = False self.visualNode.hide() self.destroySound.play() def thrustOn(self): self.acc = 1.0 def thrustOff(self): self.acc = 0.0 def rotateLeftOn(self): self.rotateLeft = True def rotateLeftOff(self): self.rotateLeft = False def isRotatingLeft(self): return self.rotateLeft def rotateRightOn(self): self.rotateRight = True def rotateRightOff(self): self.rotateRight = False def isRotatingRight(self): return self.rotateRight def update(self, deltaTime): """@param deltaTime float, how many seconds have passed since last tick""" # TODO: refactor the updating code into different methods # Update the bullets # TODO: Add test for this in testUpdate! for bullet in self.bullets: bullet['timeToLive'] -= 1 if bullet['timeToLive'] <= 0: bullet['isAlive'] = False if not bullet['isAlive']: self.destroyBullet(bullet) continue pos = bullet['visual'].getPos() bulletPos = Vec3(bullet['vel'][0] * deltaTime + pos[0], bullet['vel'][1] * deltaTime + pos[1], 0) bullet['visual'].setPos(bulletPos) bullet['physical'].setPosition(bulletPos) # If the ship is not alive anymore, we don't move it if not self.isAlive: return # update the heading. Must be done before position updating! if self.rotateLeft: self.heading = self.heading + Ship.ROTATION_SPEED * deltaTime elif self.rotateRight: self.heading = self.heading - Ship.ROTATION_SPEED * deltaTime for c in self.collisions: self.collisionHandler(self, c) # update position gainedSpeedScalar = self.acc * deltaTime * Ship.ACC_COEFFICIENT # convert degrees to radians angle = self.heading * math.pi / 180.0 #correction = math.pi / 2 deltaVelX = gainedSpeedScalar * math.cos(angle) deltaVelY = gainedSpeedScalar * math.sin(angle) for f in self.forces: deltaVelX += f[0] deltaVelY += f[1] self.forces = [] self.vel = (self.vel[0] + deltaVelX, self.vel[1] + deltaVelY) # Limit the ship's speed to Ship.SPEED_MAX self.limitVelocity() deltaPosX = deltaTime * self.vel[0] deltaPosY = deltaTime * self.vel[1] newPosX = self.pos[0] + deltaPosX newPosY = self.pos[1] + deltaPosY self.pos = (newPosX, newPosY) # Rotate the visual representation of the ship self.visualNode.setH(self.heading) # Move the actual visual representation self.visualNode.setPos(tupleToVec3(self.pos)) self.collisionSphere.setPosition(self.pos[0], self.pos[1], 0) def limitVelocity(self): shipVel = self.getVel() newVelScalar = tupleLength(shipVel) if newVelScalar > Ship.SPEED_MAX: newVelScale = Ship.SPEED_MAX / newVelScalar newVel = scaleTuple(shipVel, newVelScale) self.setVel(newVel)
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
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) base.camera.setPos(0, 0, 0) base.camera.setPos(base.cam, 0, -80, 15) base.camera.setP(-4) h = task.time / 10.0 * 360 + 180
def __init__(self, manager, xml): self.light = PAmbientLight('alight') self.lightNode = render.attachNewNode(self.light) self.reload(manager, xml)
def make_lights(light_spec=None, lname=None): """ Create one point light and an ambient light.""" if lname is None: lname = 'lights' lights = NodePath(lname) if light_spec is None: # Create point lights plight = PointLight('plight1') light = lights.attachNewNode(plight) plight.setColor((0.1, 0.1, 0.1, 1.0)) light.setPos((-2, -6, 4)) light.lookAt(0, 0, 0) # Create ambient light alight = AmbientLight('alight') alight.setColor((1, 1, 1, 1.0)) lights.attachNewNode(alight) else: for lspec in light_spec: light_type = lspec['type'] light_name = lspec['name'] assert light_type in ['AmbientLight', 'PointLight', 'DirectionalLight', 'SpotLight'], light_type if light_type == 'AmbientLight': light = AmbientLight(light_name) light.setColor(lspec['color']) lights.attachNewNode(light) elif light_type == 'PointLight': light = PointLight(light_name) lights.attachNewNode(light) light.setColor(lspec['color']) light.setPoint(lspec['pos']) elif light_type == 'DirectionalLight': light = DirectionalLight(light_name) lights.attachNewNode(light) light.setColor(lspec['color']) light.setPoint(lspec['pos']) light.setDirection(lspec['direction']) return lights
def __init__(self): """Initialise the scene.""" # Show the framerate base.setFrameRateMeter(True) # Initialise terrain: # Make 4 terrain nodepath objects with different hilliness values # and arrange them side-by-side in a 2x2 grid, giving a big terrain # with variable hilly and flat areas. color = (0.6, 0.8, 0.5, 1) # Bright green-ish scale = 12 height = 18 # FIXME: For now we are raising the terrain so it # floats above the sea to prevent lakes from # appearing (but you still get them sometimes) t1 = Terrain(color=color, scale=scale, trees=0.7, pos=P.Point3(0, 0, height)) t1.prime.reparentTo(render) t2 = Terrain(color=color, scale=scale, h=24, pos=P.Point3(32 * scale, 0, height), trees=0.5) t2.prime.reparentTo(render) t3 = Terrain(color=color, scale=scale, h=16, pos=P.Point3(32 * scale, 32 * scale, height), trees=0.3) t3.prime.reparentTo(render) t4 = Terrain(color=color, scale=scale, h=2, pos=P.Point3(0, 32 * scale, height), trees=0.9) t4.prime.reparentTo(render) #tnp1.setPos(tnp1,-32,-32,terrainHeight) # Initialise sea sea = Sea() # Initialise skybox. self.box = loader.loadModel("models/skybox/space_sky_box.x") self.box.setScale(6) self.box.reparentTo(render) # Initialise characters self.characters = [] self.player = C.Character(model='models/eve', run='models/eve-run', walk='models/eve-walk') self.player.prime.setZ(100) self.player._pos = SteerVec(32 * 12 + random.random() * 100, 32 * 12 + random.random() * 100) self.player.maxforce = 0.4 self.player.maxspeed = 0.55 EdgeScreenTracker(self.player.prime, dist=200) # Setup camera for i in range(0, 11): self.characters.append(C.Character()) self.characters[i].prime.setZ(100) self.characters[i].wander() self.characters[i].maxforce = 0.3 self.characters[i].maxspeed = 0.2 self.characters[i]._pos = SteerVec(32 * 12 + random.random() * 100, 32 * 12 + random.random() * 100) C.setContainer( ContainerSquare(pos=SteerVec(32 * 12, 32 * 12), radius=31 * 12)) #C.toggleAnnotation() # Initialise keyboard controls. self.accept("c", C.toggleAnnotation) self.accept("escape", sys.exit) # Setup CollisionRay and CollisionHandlerQueue for mouse picking. self.pickerQ = P.CollisionHandlerQueue() self.picker = camera.attachNewNode( P.CollisionNode('Picker CollisionNode')) self.picker.node().addSolid(P.CollisionRay()) # We want the picker ray to collide with the floor and nothing else. self.picker.node().setFromCollideMask(C.floorMASK) self.picker.setCollideMask(P.BitMask32.allOff()) base.cTrav.addCollider(self.picker, self.pickerQ) try: handler.addCollider(self.picker, camera) except: pass self.accept('mouse1', self.onClick) # Set the far clipping plane to be far enough away that we can see the # skybox. base.camLens.setFar(10000) # Initialise lighting self.alight = AmbientLight('alight') self.alight.setColor(VBase4(0.35, 0.35, 0.35, 1)) self.alnp = render.attachNewNode(self.alight) render.setLight(self.alnp) self.dlight = DirectionalLight('dlight') self.dlight.setColor(VBase4(0.4, 0.4, 0.4, 1)) self.dlnp = render.attachNewNode(self.dlight) self.dlnp.setHpr(45, -45, 0) render.setLight(self.dlnp) self.plight = PointLight('plight') self.plight.setColor(VBase4(0.8, 0.8, 0.5, 1)) self.plnp = render.attachNewNode(self.plight) self.plnp.setPos(160, 160, 50) self.slight = Spotlight('slight') self.slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() self.slight.setLens(lens) self.slnp = render.attachNewNode(self.slight) self.slnp.setPos(-20, -20, 20) self.slnp.lookAt(50, 50, 0) # Initialise some scene-wide exponential fog colour = (0.5, 0.8, 0.8) self.expfog = Fog("Scene-wide exponential Fog object") self.expfog.setColor(*colour) self.expfog.setExpDensity(0.0005) render.setFog(self.expfog) base.setBackgroundColor(*colour) # Add a task for this Plant to the global task manager. self.stepcount = 0 taskMgr.add(self.step, "Plant step task")
def loadLight(self): #Sets the lights plight = AmbientLight('my plight') light = self.parserClass.userConfig.getfloat('display', 'light') plight.setColor(VBase4(light, light, light, 0.5)) plnp = render.attachNewNode(plight) render.setLight(plnp)
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
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)
task.last = task.time self.keybControl(dt) 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)
def startGame(self): ''' Start the game ''' # Create the Track self.track = trackgen3d.Track3d(1000, 800, 600, 200, 5) self.trackmesh = NodePath(self.track.createRoadMesh()) tex = loader.loadTexture('data/textures/street.png') self.trackmesh.setTexture(tex) self.trackmesh2 = NodePath(self.track.createUninterpolatedRoadMesh()) self.trackmesh2.setTexture(tex) # nodePath.setTwoSided(True) self.trackmesh.reparentTo(render) # LICHT self.plight = PointLight('kkkplight') self.plight.setColor(VBase4(21, 0, 0, 1)) self.plnp = NodePath(self.plight) self.plnp.reparentTo(render) self.plnp.setPos(0, 0, 2000) self.plnp.node().setAttenuation(Point3(0, 0, 1)) self.plnp.setScale(.5, .5, .5) # self.plnp.setHpr(0,-90,0) # print plight.getAttenuation() # plnp.setPos(-10, -800, 20) render.setLight(self.plnp) self.accept("w", self.setA, [100]) self.accept("s", self.setA, [-10]) self.accept("e", self.setB, [10]) self.accept("d", self.setB, [-10]) self.accept("r", self.setC, [100]) self.accept("f", self.setC, [-100]) self.accept("z", self.setRotation, [0, 10]) self.accept("h", self.setRotation, [0, -10]) self.accept("u", self.setRotation, [1, 10]) self.accept("j", self.setRotation, [1, -10]) self.accept("i", self.setRotation, [2, 10]) self.accept("k", self.setRotation, [2, -10]) self.accept("n", self.setExponent, [-50]) self.accept("m", self.setExponent, [50]) # load our model tron = loader.loadModel("data/models/vehicles/vehicle02") self.tron = tron # self.tron.loadAnims({"running":"models/tron_anim"}) tron.reparentTo(render) tron.setPos(0, 0, 15) tron.setHpr(0, -90, 0) # nodePath2 = self.render.attachNewNode(self.track.createBorderLeftMesh()) # tex2 = loader.loadTexture('data/textures/border.png') # nodePath2.setTexture(tex2) # # nodePath3 = self.render.attachNewNode(self.track.createBorderRightMesh()) # tex2 = loader.loadTexture('data/textures/border.png') # nodePath3.setTexture(tex2) ring = loader.loadModel("data/models/ring.egg") ring.setScale(24) ring.setZ(-25) ring.setY(100) ring.setTransparency(TransparencyAttrib.MAlpha) ring.reparentTo(render) # Load the Lights ambilight = AmbientLight('ambilight') ambilight.setColor(VBase4(0.8, 0.8, 0.8, 1)) render.setLight(render.attachNewNode(ambilight))
def collectPlayer(self, task): ''' Wait until all players are ready ''' if len(self._players) > 0 and self.player_buttonpressed[0] < task.time: if self._players[0].device.boost and self.countdown <= 0: loading = False for player in self._players: if player.vehicle.model_loading: loading = True break self._notify.debug("Loading vehicle: %s" % (loading)) if not loading: taskMgr.remove("selectVehicle") self.track = trackgen3d.Track3d(1000, 1800, 1600, 1200, 5) # len(self._players)) self.streetPath = render.attachNewNode( self.track.createRoadMesh()) # self.borderleftPath = render.attachNewNode(self.track.createBorderLeftMesh()) self.borderleftPath = render.attachNewNode( self.track.createBorderLeftMesh()) self.borderrightPath = render.attachNewNode( self.track.createBorderRightMesh()) self.borderleftcollisionPath = NodePath( self.track.createBorderLeftCollisionMesh()) self.borderrightcollisionPath = NodePath( self.track.createBorderRightCollisionMesh()) # #self.borderPath = render.attachNewNode(self.track.createBorderMesh()) textures = ["tube", "tube2", "street"] tex = textures[random.randint(0, len(textures) - 1)] roadtex = loader.loadTexture('data/textures/' + tex + '.png') bordertex = loader.loadTexture('data/textures/border.png') self.streetPath.setTexture(roadtex) self.borderleftPath.setTexture(bordertex) self.borderrightPath.setTexture(bordertex) # self.streetPath = loader.loadModel('data/models/Street.egg') # self.streetPath = loader.loadModel('data/models/Street.egg') # tex = loader.loadTexture('data/models/StreetTex.png') # self.nodePath.setTexture(tex) self._parent.startGame(self.streetPath, self.borderleftPath, self.borderrightPath, self.track.trackpoints, self.borderleftcollisionPath, self.borderrightcollisionPath) return task.done for device in self.unusedDevices: if device.boost: self.countdown = COUNTDOWN_START self.player_buttonpressed.append(0) self._parent.addPlayer(device) # Set the PlayerCam to the Vehicle select menu Node vehicleSelectNode = NodePath("VehicleSelectNode") self._players[-1].camera.camera.reparentTo(vehicleSelectNode) # Light, that casts shadows plight = Spotlight('plight') plight.setColor(VBase4(10.0, 10.0, 10.0, 1)) if (base.win.getGsg().getSupportsBasicShaders() != 0): pass # plight.setShadowCaster(True, 2048, 2048)#enable shadows for this light ##TODO wegen Linux # Light plight.getLens().setFov(80) plnp = vehicleSelectNode.attachNewNode(plight) plnp.setPos(2, -10, 10) plnp.lookAt(0, 0, 0) vehicleSelectNode.setLight(plnp) # vehicleSelectNode.setShaderAuto()#enable autoshader so we can use shadows # Light ambilight = AmbientLight('ambilight') ambilight.setColor(VBase4(0.2, 0.2, 0.2, 1)) vehicleSelectNode.setLight( vehicleSelectNode.attachNewNode(ambilight)) self.platform.instanceTo( vehicleSelectNode) # Load the platform # instance shown text self.countdown_node.instanceTo( vehicleSelectNode) # Instance the Countdown self.loading.instanceTo( vehicleSelectNode) # Show the Loading-Text self.attributes.copyTo(vehicleSelectNode).hide() self._players[-1].vehicle.model_loading = True # start loading the model loader.loadModel(self.vehicle_list[0], callback=self._players[-1].setVehicle) self._notify.debug("Loading initial vehicle: %s" % (self.vehicle_list[0])) self.unusedDevices.remove(device) self.player_buttonpressed[-1] = task.time + self.KEY_DELAY # Add the Skybox skybox = loader.loadModel("data/models/skybox.egg") t = Texture() t.load(PNMImage("data/textures/skybox_hangar.png")) skybox.setTexture(t) skybox.setBin("background", 1) skybox.setDepthWrite(0) skybox.setDepthTest(0) skybox.setLightOff() skybox.setScale(10000) skybox.reparentTo(vehicleSelectNode) for player in self._players: if self.player_buttonpressed[self._players.index( player)] < task.time: if player.device.use_item: self.countdown = COUNTDOWN_START self._notify.debug("Removing player: %s" % (player)) self.unusedDevices.append(player.device) self.player_buttonpressed.pop(self._players.index(player)) self._parent.removePlayer(player) return task.cont
class environmentClass: def __init__( self, cameraPos, heightfield ): self.cameraPos = cameraPos self.heightfield = heightfield if USELIGHT: self.setupLight() if USESKY: self.setupSky() if USEFOG: self.setupFog() if USESOUND: self.setupSound() if USERAIN: self.setupRain() #taskMgr.doMethodLater(DAYNIGHTCYCLETIME/60.0, self.dayNightCycle, 'UpdateDayNight') taskMgr.doMethodLater(0.1, self.dayNightCycle, 'UpdateDayNight') taskMgr.doMethodLater(0.1, self.updateScene, 'updateScene' ) def setupSound( self ): self.mySound1 = loader.loadSfx("data/sounds/rainshower.wav") self.mySound1.setLoop(True) self.mySound1.play() def setupSky( self ): self.skyNP = loader.loadModel( 'data/models/sky.bam.pz' ) self.skyNP.reparentTo( render ) self.skyNP.setScale( 4000, 4000, 1000 ) self.skyNP.setPos( 0, 0, 0 ) self.skyNP.setTexture( loader.loadTexture( 'data/textures/clouds.png' ) ) self.skyNP.setShader( loader.loadShader( 'data/sky.sha' ) ) '''self.skyFogNP = loader.loadModel( 'data/models/sphere.egg' ) self.skyFogNP.reparentTo( base.camera ) self.skyFogNP.setTwoSided( True ) self.skyFogNP.setScale( 10 ) self.skyFogNP.setPos( Vec3(0,0,4) ) self.skyFogNP.setTransparent( True )''' sky = Vec4( 0.25, 0.5, 1.0, 0.0 ) # r, g, b, skip sky2 = Vec4( 1.0, 1.0, 1.0, 0.0 ) clouds = Vec4( 0.004, 0.002, 0.008, 0.010 ) # vx, vy, vx, vy self.skyNP.setShaderInput( 'sky', sky ) self.skyNP.setShaderInput( 'sky2', sky2 ) self.skyNP.setShaderInput( 'clouds', clouds ) render.setShaderInput( 'time', 0 ) def setupLight( self ): #Default lightAttrib with no lights #self.lightAttrib = LightAttrib.makeAllOff() # First we create an ambient light. All objects are affected by ambient # light equally #Create and name the ambient light self.ambientLight = AmbientLight( "ambientLight" ) #Set the color of the ambient light self.ambientLight.setColor( Vec4( .1, .1, .1, 1 ) ) self.alnp = render.attachNewNode(self.ambientLight) render.setLight(self.alnp) self.heightfield.mHeightFieldNode.setLightOff() self.ambientLight2 = AmbientLight( "ambientLight2" ) #Set the color of the ambient light self.ambientLight2.setColor( Vec4( .1, .1, .1, 1 ) ) self.al2np = render.attachNewNode(self.ambientLight2) self.heightfield.mHeightFieldNode.setLight(self.al2np) self.dlight = DirectionalLight('dlight') self.dlight.setColor(VBase4(1.0, 1.0, 0.6, 1)) self.dlnp = render.attachNewNode(self.dlight.upcastToPandaNode()) self.dlnp.setHpr(-90, -30, 0) self.heightfield.mHeightFieldNode.setLight(self.dlnp) # Now we create a spotlight. Spotlights light objects in a given cone # They are good for simulating things like flashlights self.spotlight = Spotlight( "spotlight" ) self.spotlight.setColor( Vec4( .9, .9, .9, 1 ) ) #The cone of a spotlight is controlled by it's lens. This creates the lens self.spotlight.setLens( PerspectiveLens() ) #This sets the Field of View (fov) of the lens, in degrees for width and #height. The lower the numbers, the tighter the spotlight. self.spotlight.getLens().setFov( 30, 30 ) # Attenuation controls how the light fades with distance. The numbers are # The three values represent the three constants (constant, linear, and # quadratic) in the internal lighting equation. The higher the numbers the # shorter the light goes. self.spotlight.setAttenuation( Vec3( 0.0, 0.0075, 0.0 ) ) # This exponent value sets how soft the edge of the spotlight is. 0 means a # hard edge. 128 means a very soft edge. self.spotlight.setExponent( 60.0 ) # Unlike our previous lights, the spotlight needs a position in the world # We are attaching it to the camera so that it will appear is if we are # holding a flashlight, but it can be attached to any NodePath # # When attaching a spotlight to a NodePath, you must use the # upcastToLensNode function or Panda will crash #camera.attachNewNode( self.spotlight.upcastToLensNode() ) self.spnp = camera.attachNewNode( self.spotlight.upcastToLensNode() ) render.setLight(self.spnp) self.heightfield.mHeightFieldNode.setLight(self.spnp) #self.lightAttrib = self.lightAttrib.addLight( self.spotlight ) #Finally we set the light attrib to a node. In this case we are using render #so that the lights will effect everything, but you could put it on any #part of the scene #render.node().setAttrib( self.lightAttrib ) # Create and start interval to spin the lights, and a variable to # manage them. #self.pointLightsSpin = self.pointLightHelper.hprInterval(6, Vec3(360, 0, 0)) #self.pointLightsSpin.loop() def setupFog( self ): '''defaultExpFogColor = (0.33, 0.5, 1.0) self.expFog = Fog("exponentialFog") self.expFog.setColor(*defaultExpFogColor) self.expFog.setExpDensity(DEFAULTFOG) render.setFog(self.expFog)''' defaultLinFogColor = (0.33, 0.5, 1.0) self.linFog = Fog("linearFog") self.linFog.setColor(*defaultLinFogColor) self.linFog.setLinearRange(0, linFogMinRange + linFogVarianceRange) self.linFog.setLinearFallback(30, 60, 240) base.camera.attachNewNode(self.linFog) render.setFog(self.linFog) base.setBackgroundColor( defaultLinFogColor ) def setupRain( self ): base.enableParticles() self.rain = rainClass() self.rain.reparentTo( base.camera ) #self.rain.setPos( 0, 0, 5 ) self.rain.setScale( 200 ) #self.rain.particle.setPoolSize( 8192 ) #self.rain.particle.setBirthRate( 2.000 ) #self.rain.particle.renderer.setHeadColor(Vec4(1.00, 1.00, 1.00, 0.8)) #self.rain.particle.renderer.setTailColor(Vec4(1.00, 1.00, 1.00, 0.2)) self.rain.start( render ) def dayNightCycle( self, task ): #print "dayNight", rainStrenght if USERAIN: rainStrenght = (RAINCYCLEFUNC**((math.sin(time.time()/(DAYNIGHTCYCLETIME/24.))+1.0)/2.0)-1.0)/(RAINCYCLEFUNC-1.0) self.rain.particle.setBirthRate( max( rainStrenght, 0.01 ) ) sunPos = time.time()/(DAYNIGHTCYCLETIME/(math.pi*2))%(math.pi*2) dayNight = (math.sin(sunPos)+1.0)/2.0 dayNight = (DAYNIGHTCYCLEFUNC**dayNight-1.0)/(DAYNIGHTCYCLEFUNC-1.0) if USELIGHT: #print dayNight c = (dayNight)/1.2 + 0.01 #print dayNight, c [commented by Finn] aLightCol = Vec4( c, c, c, 1 ) self.ambientLight.setColor( aLightCol ) if abs(sunPos/math.pi-1) < 0.5: self.dlnp.setHpr(-90, 180 + (dayNight-0.3) * 108, 0) else: self.dlnp.setHpr(-90, 0 - (dayNight-0.3) * 108, 0) # Time for clouds shader if USESKY: render.setShaderInput( 'time', task.time/4.0 ) #dayNight = 1.0 # color for clouds & fog #dayNight = ( math.sin(time.time()/DAYNIGHTCYCLETIME) + 1.0 ) / 2.0 # 0.0 for night, 1.0 for day sky = Vec4( dayNight/4.0, dayNight/2.0, dayNight, 0.0 ) # r, g, b, skip sky2 = Vec4( dayNight, dayNight, dayNight, 0.0 ) # set colors self.skyNP.setShaderInput( 'sky', sky ) self.skyNP.setShaderInput( 'sky2', sky2 ) if USEFOG: #expFogColor = dayNight/3.0,dayNight/2.0,dayNight #self.expFog.setColor( *expFogColor ) #self.expFog.setExpDensity(DEFAULTFOG*(NIGHTFOGMULTIPLIER-dayNight*(NIGHTFOGMULTIPLIER-1.0))) linFogColor = dayNight/3.0,dayNight/2.0,dayNight self.linFog.setColor( *linFogColor ) fogRange = linFogMinRange + linFogVarianceRange*dayNight self.linFog.setLinearRange( fogRange/4., fogRange ) self.linFog.setLinearFallback(fogRange/8., fogRange/4., fogRange) base.setBackgroundColor( linFogColor ) return Task.again def updateScene( self, task ): # set position of the particle system if USERAIN: self.rain.setPos( base.camera.getPos() + Vec3( 0,0,200) ) return Task.cont
def loadLight(self): #Sets the lights plight = AmbientLight('my plight') plight.setColor(VBase4(1.0,1.0,1.0,0.5)) plnp = render.attachNewNode(plight) render.setLight(plnp)
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)
def __init__(self): ShowBase.__init__(self) resize_window = ConfigVariableBool('viewer-resize-window', '#t') if resize_window.getValue(): self.win_size = (800, 800) # Black background self.win.setClearColor((0.0, 0.0, 0.0, 1.0)) # Set up lights. self.lights = NodePath("lights") # Spotlight. Casts shadows. slight = Spotlight("slight") slight.setScene(self.render) slight.setShadowCaster(True, 2**11, 2**11) # Set shadow mask, so we can exclude objects from casting shadows self.shadow_mask = BitMask32.bit(2) slight.setCameraMask(self.shadow_mask) slight.setColor((1.2, 1.2, 1.2, 1.)) slight.getLens().setFov(45) slight.getLens().setNearFar(1, 100) slnp = self.lights.attachNewNode(slight) slnp.setPos((6, 8, 20)) slnp.lookAt(0, 0, 0) self.render.setLight(slnp) # Ambient light. alight = AmbientLight("alight") a = 0.75 alight.setColor((a, a, a, 1.0)) #alight.setColor((0.8, 0.8, 0.8, 1.0)) alnp = self.lights.attachNewNode(alight) self.render.setLight(alnp) self.lights.reparentTo(self.render) # Set auto shading for shadows use_shaders = ConfigVariableBool('viewer-use-shaders', '#t') if use_shaders.getValue(): self.render.setShaderAuto() # Set antialiasing on self.render.setAntialias(AntialiasAttrib.MAuto) # Camera self.camera_rot = self.render.attachNewNode("camera_rot") self.cameras = self.camera_rot.attachNewNode("cameras") self.cameras.setPos(14, 32, 9.) self.look_at = self.render.attachNewNode("look_at") self.look_at.setPos(Point3(2, 0, 1)) self.cameras.lookAt(self.look_at) self.camera.reparentTo(self.cameras) # Adjust the camera's lens lens = PerspectiveLens() self.camLens = lens self.camLens.setNearFar(0.01, 1000.0) setlens = ConfigVariableBool('viewer-set-cam-lens', '#t') if setlens: self.cam.node().setLens(self.camLens) # # Initialize / set variables self.sso = None self.ssos = [] self.cache = None self.scene = SSO("scene") self.scene.reparentTo(self.render) # Key callbacks. self.accept("shift-control-escape", self.exit) self.accept("escape", self.exit) self.accept("0", self.reset_sso) self.accept("arrow_left", self.prev) self.accept("arrow_right", self.next) self.accept("page_down", self.prev, [100]) self.accept("page_up", self.next, [100]) self.accept("f1", self.toggle_debug) self.accept("o", self.physics_once, extraArgs=[1. / 10]) self.accept("i", self.physics_once, extraArgs=[1. / 10000]) # Remove existing keyboard tasks. self.mandatory_events = ("window-event", "async_loader_0", "render-texture-targets-changed", "shift-control-escape") # Task list: name: (key, args) events = { "physics": ("p", ), "repel": ("t", ), "bump": ("f", ), "rotate": ("r", 20), "rotate90": ("h", ), "ss_task": ("s", ), "ssa_task": ("w", ), "bp": ("b", ) } # Add events for key, val in events.iteritems(): call = [key] + list(val[1:]) self.accept(val[0], self.toggle_task, call) # These are the key events that we will never ignore self.permanent_events = self.getAllAccepting() # These are the key events that we will never ignore self.permanent_tasks = [ task.getName() for task in self.taskMgr.getAllTasks() ] self.start_time = -1 self.old_elapsed = 0