class SpotLight: """Creates a simple spot light""" def __init__(self, manager, xml): self.light = PSpotLight('slight') lens = PerspectiveLens() self.light.setLens(lens) self.lightNode = render.attachNewNode(self.light) self.reload(manager, xml) def reload(self, manager, xml): color = xml.find('color') if color != None: self.light.setColor( VBase4(float(color.get('r')), float(color.get('g')), float(color.get('b')), 1.0)) pos = xml.find('pos') if pos != None: self.lightNode.setPos(render, float(pos.get('x')), float(pos.get('y')), float(pos.get('z'))) lookAt = xml.find('lookAt') if lookAt != None: self.lightNode.lookAt(render, float(lookAt.get('x')), float(lookAt.get('y')), float(lookAt.get('z'))) def start(self): render.setLight(self.lightNode) def stop(self): render.clearLight(self.lightNode)
def addLight(self, id, parent, attenuation, position, color, specular, stroboscopic, spot, lookat): if spot: slight = Spotlight(id) slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) light = render.attachNewNode(slight) light.setPos(LVector3(position[0], position[1], position[2])) if lookat == None: light.lookAt(parent) else: light.lookAt(render.find("**/"+lookat)) else: light = parent.attachNewNode(PointLight(id)) light.node().setAttenuation(attenuation) light.setPos(LVector3(position[0], position[1], position[2])) light.node().setColor(color) light.node().setSpecularColor(specular) render.setLight(light) self.light_elements[id] = light if stroboscopic: self.stroboscopic_lights.append(id) if id: self.nodes_by_id[id] = light return light
def generate(self): data = CIGlobals.SuitBodyData[self.SUIT] type = data[0] team = data[1] self.team = team self.level = 12 self.suit = type Suit.generate(self, SuitBank.MrHollywood, 0, hideFirst=False) self.suit = type base.taskMgr.add(self.__viewDistance, self.viewDistanceTaskName) self.setPythonTag('guard', self) self.eyeLight = Spotlight('eyes') self.eyeLens = PerspectiveLens() self.eyeLens.setMinFov(90.0 / (4.0 / 3.0)) self.eyeLight.setLens(self.eyeLens) self.eyeNode = self.headModel.attachNewNode(self.eyeLight) self.eyeNode.setZ(-5) self.eyeNode.setY(-4.5) self.trav = CollisionTraverser(self.uniqueName('eyeTrav')) ray = CollisionRay(0, 0, 0, 0, 1, 0) rayNode = CollisionNode('ToonFPS.rayNode') rayNode.addSolid(ray) rayNode.setFromCollideMask(CGG.GuardBitmask | CIGlobals.WallBitmask) rayNode.setIntoCollideMask(BitMask32.allOff()) self.rayNP = base.camera.attachNewNode(rayNode) self.rayNP.setZ(3) self.queue = CollisionHandlerQueue() self.trav.addCollider(self.rayNP, self.queue) self.trav.addCollider(self.gameWorld.mg.avatarBody, self.queue) self.request('Guard')
def toggle_flashlight(): current_flashlight = self.render.find_all_matches("**/flashlight") if self.flashlight_state == 0: if len(current_flashlight) == 0: self.slight = 0 self.slight = Spotlight('flashlight') self.slight.set_shadow_caster(True, 1024, 1024) self.slight.set_color(VBase4(0.5, 0.6, 0.6, 1)) # slightly bluish lens = PerspectiveLens() lens.set_near_far(0.5, 5000) self.slight.set_lens(lens) self.slight.set_attenuation((0.5, 0, 0.0000005)) self.slight = self.render.attach_new_node(self.slight) self.slight.set_pos(-0.1, 0.3, -0.4) self.slight.reparent_to(self.camera) self.flashlight_state = 1 self.render.set_light(self.slight) elif len(current_flashlight) > 0: self.render.set_light(self.slight) self.flashlight_state = 1 elif self.flashlight_state > 0: self.render.set_light_off(self.slight) self.flashlight_state = 0
def launch_panda_window(panda_widget, size) : """ Configure and create Panda window Connect to the gtk widget resize event Load a panda """ props = WindowProperties().getDefault() props.setOrigin(0, 0) props.setSize(*size) props.setParentWindow(panda_widget.window.xid) base.openDefaultWindow(props=props) # == panda_widget.connect("size_allocate", resize_panda_window) # == panda = loader.loadModel("panda") panda.reparentTo(render) panda.setPos(0, 40, -5) pl = render.attachNewNode( PointLight( "redPointLight" ) ) pl.node().setColor( Vec4( .9, .8, .8, 1 ) ) render.setLight(pl) pl.node().setAttenuation( Vec3( 0, 0, 0.05 ) ) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) slnp = render.attachNewNode(slight) slnp.setPos(2, 20, 0) mid = PandaNode('mid') panda.attachNewNode(mid) # slnp.lookAt(mid) render.setLight(slnp)
def __init__(self): loadPrcFile('config.prc') ShowBase.__init__(self) base.disableMouse() self.render.setShaderAuto() self.accept("escape", sys.exit) # Model model = self.loader.loadModel("twisted") model.reparent_to(self.render) self.model = model # For reference in the rotation task # Light light = Spotlight('light') light_np = self.render.attachNewNode(light) light_np.set_pos(25, 25, 25) light_np.look_at(0, 0, 0) # Model-light interaction light.setShadowCaster(True) light.getLens().setNearFar(1, 50) self.render.setLight(light_np) # Camera self.camera.set_pos(0, -60, 30) self.camera.look_at(0, 0, 0) # Rotating the object self.taskMgr.add(self.rotate_object, 'rotate object') self.render.setAntialias(AntialiasAttrib.MMultisample)
def setupLights(self): panda = self.app.panda panda.setBackgroundColor(.9, .9, .9, 1) panda.render.clearLight() keylight = Spotlight('keylight') keylight.setLens(PerspectiveLens()) np = self._insertLight( keylight, colour=(1, 1, 1, 1), pos=(0, -5, 2), ) np.lookAt((0, 0, 0.9)) # Turn off shadows until we have fix for # https://bugs.launchpad.net/panda3d/+bug/1212752 # keylight.setShadowCaster(True, 512, 512) sunlight = PointLight('sunlight') self._insertLight( sunlight, colour=(1, 1, 1, 1), pos=(1, -2, 20), ) self._insertLight( AmbientLight('ambientLight'), colour=(.25, .25, .25, 1), )
def generate(self): self.level = 12 self.maxHealth = 200 self.health = 200 Suit.generate(self, FactorySneakGuardSuit.SUIT, FactorySneakGuardSuit.VARIANT, hideFirst=False) self.setName(self.suitPlan.getName(), None) self.cleanupPropeller() base.taskMgr.add(self.__viewDistance, self.viewDistanceTaskName) self.setPythonTag('guard', self) self.eyeLight = Spotlight('eyes') self.eyeLens = PerspectiveLens() self.eyeLens.setMinFov(90.0 / (4. / 3.)) self.eyeLight.setLens(self.eyeLens) self.eyeNode = self.headModel.attachNewNode(self.eyeLight) self.eyeNode.setZ(-5) self.eyeNode.setY(-4.5) self.trav = CollisionTraverser(self.uniqueName('eyeTrav')) ray = CollisionRay(0, 0, 0, 0, 1, 0) rayNode = CollisionNode('ToonFPS.rayNode') rayNode.addSolid(ray) rayNode.setFromCollideMask(CGG.GuardBitmask | CIGlobals.WallBitmask) rayNode.setIntoCollideMask(BitMask32.allOff()) self.rayNP = base.camera.attachNewNode(rayNode) self.rayNP.setZ(3) self.queue = CollisionHandlerQueue() self.trav.addCollider(self.rayNP, self.queue) self.trav.addCollider(self.gameWorld.mg.avatarBody, self.queue) self.request('Guard')
def initLights(self): # Create some lighting #self.environ.ls() #print(self.environ.findAllMatches("**/Spot")) ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(0.8, 0.8, 0.8, 0.65)) """ directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-10, -10, 5)) directionalLight.showFrustum() directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) dirnp = render.attachNewNode(directionalLight) dirnp.setPos(10, 0, 6) """ plight1 = PointLight('plight1') plight1.setColor(VBase4(1, 1, 1, 1)) plight1.showFrustum() #plight1.setShadowCaster(True) plnp1 = render.attachNewNode(plight1) plnp1.setPos(26.71, -33.2, 26) plight2 = PointLight('plight2') plight2.setColor(VBase4(1, 1, 1, 1)) plight2.showFrustum() plnp2 = render.attachNewNode(plight2) plnp2.setPos(-25, 25, 25) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() lens.setFilmSize(1, 1) # Or whatever is appropriate for your scene slight.setLens(lens) slight.setShadowCaster(True, 512, 512) slight.showFrustum() slnp = render.attachNewNode(slight) slnp.setPos(0, 0, 100) slnp.lookAt(Vec3(0,0,0)) render.setLight(slnp) render.setLight(plnp1) render.setLight(plnp2) #render.setLight(render.attachNewNode(ambientLight)) #render.setLight(dirnp) render.setShaderAuto() #render.setLight(render.attachNewNode(directionalLight)) """
def buildSubType(self): """Build the light with the given subType""" if self.subType == "pointType": # make a point light c = self.color pointLight = PointLight(self.name) pointLight.setColor(VBase4(c[0], c[1], c[2], c[3])) plnp = self.renderObjectsLight.attachNewNode(pointLight) plnp.setPos(self.position) self.lightNP = plnp self.setLightSwitch(True) if self.subType == "directType": # make a directional light c = self.color directLight = DirectionalLight(self.name) directLight.setColor(VBase4(c[0], c[1], c[2], c[3])) dlnp = self.renderObjectsLight.attachNewNode(directLight) dlnp.setHpr(0, -60, 0) # no idea why its like that.. but it works self.lightNP = dlnp self.setLightSwitch(True) if self.subType == "ambientType": # make a ambient light c = self.color ambientLight = AmbientLight(self.name) ambientLight.setColor(VBase4(c[0], c[1],c[2], c[3])) alnp = self.renderObjectsLight.attachNewNode(ambientLight) self.lightNP = alnp self.setLightSwitch(True) if self.subType == "spotType": # make a spot light # lookAtObj = _object.getTag("lookAt") get rid of this. c = self.color spotLight = Spotlight(self.name) spotLight.setColor(VBase4(c[0], c[1], c[2], c[3])) lens = PerspectiveLens() spotLight.setLens(lens) slnp = self.renderObjectsLight.attachNewNode(spotLight) slnp.setPos(self.position) slnp.setHpr(self.hpr) # Find out if this is really the only option # because setHpr doesnt seem to have any effect. # lookAt would be okay but that means adding anothe type #slnp.lookAt(self.main.GameObjects["player"].collisionBody) self.lightNP = slnp self.setLightSwitch(True)
def __init__(self): self.testTexture = loader.loadTexture("maps/envir-reeds.png") self.accept("1", self.toggleTex) self.accept("2", self.toggleLightsSide) self.accept("3", self.toggleLightsUp) self.LightsOn = False self.LightsOn1 = False slight = Spotlight('slight') slight.setColor((1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) self.slnp = render.attachNewNode(slight) self.slnp1 = render.attachNewNode(slight)
def setupLights(self): """Setup extrnal lights""" # ambient light alight = AmbientLight('alight') alight.setColor((0.2, 0.2, 0.2, 1)) alnp = self.render.attachNewNode(alight) self.render.setLight(alnp) # directional light dlight = DirectionalLight('dlight') dlight.setColor((0.8, 0.8, 0.5, 1)) lens = PerspectiveLens() lens.setNearFar(1, 5) dlight.setLens(lens) dlight.setShadowCaster(True, args.shadow_resolution, args.shadow_resolution) dlnp = self.render.attachNewNode(dlight) dlnp.setPos(2, -2, 3) dlnp.lookAt(0, 0, 0) self.render.setLight(dlnp) # spotlight slight = Spotlight('slight') slight.setColor((0.7, 0.7, 1.0, 1)) lens = PerspectiveLens() lens.setNearFar(1, 5) slight.setLens(lens) slight.setShadowCaster(True, args.shadow_resolution, args.shadow_resolution) slnp = self.render.attachNewNode(slight) slnp.setPos(1, 1, 2) slnp.lookAt(0, 0, 0) self.render.setLight(slnp)
def set_spotlight(self, col, exp, cutoff, pos, look_at): lgt = Spotlight('spotlight') lgt.setColor(col) lgt.setExponent(exp) lgt.getLens().setFov(cutoff, cutoff) self.__set_lgt(lgt) self.lights[-1].setPos(*pos) self.lights[-1].lookAt(*look_at)
def _make_light_direct(self, index, color, pos, target=(0, 0, 0)): if self._spotlight: light = Spotlight('Spotlight {:02d}'.format(index)) else: light = DirectionalLight('Directional Light{:02d}'.format(index)) light.set_color(Vec3(*color)) light.set_camera_mask(self.LightMask) light.set_shadow_buffer_size((self._shadow_size, self._shadow_size)) lens = light.get_lens() lens.set_film_size(5.5, 5.5) lens.set_near_far(10, 30) node = self.render.attach_new_node(light) node.set_pos(*pos) node.look_at(*target) return node
def __init__(self, manager, xml): self.light = PSpotLight('slight') lens = PerspectiveLens() self.light.setLens(lens) self.lightNode = render.attachNewNode(self.light) self.reload(manager, xml)
def __init__(self, screen_manager): ''' Creates a new trunk screen with a reference to the given screen manager. This function also loads all of our models and stage backgrounds and positions them on the scene accordingly ''' super(TrunkScreen, self).__init__(screen_manager, "trunk_screen") # Load our trunk model self.cube = base.loader.loadModel("assets/models/trunk.egg") # Set its position to: # X: -0.4 (just to the left of h-center) # Y: 40 (way far back away from the viewer) # Z: 0 (vertically center) self.cube.setPos(-0.4, 40, 0) # Set the scaling size of the trunk self.cube.setScale(1.5, 1.5, 1.5) if base.displayFlipped: self.cube.setAttrib( CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise)) # Insert the trunk into this screen's rendering tree self.cube.reparentTo(self.node) # Set up a splotlight to project onto the trunk self.dlight = Spotlight('my dlight') # Associate the spotlight to the rendering system self.dlnp = render.attachNewNode(self.dlight) # Set this trunk's light explicitly so it only takes light from this light self.cube.setLight(self.dlnp) # Load the curtain background self.loadBackground("assets/images/stage-background.png")
def __init__(self, name, owner, scene, pos, fov=60, near=0.01, far=100, resol=(1920, 1080)): self.owner = owner self.scene = scene self.last = 0.0 self.power = 1.0 self.on = True self.powerrate = Flashlight.POWER_DRAIN_RATE #TODO: Change lens parameters for a unique 'lens' parameter lens = PerspectiveLens() lens.setFov(fov) lens.setNearFar(near, far) lens.setFilmSize(resol[0], resol[1]) self.light = Spotlight(name + '/wide') self.light.setLens(lens) #TODO: Shadows don't work well anymore #self.light.setShadowCaster(True, resol[0], resol[1]) self.light.setColor(Flashlight.COLOR) self.light.setExponent(40) self.nodepath = owner.cam.attachNewNode(self.light) self.nodepath.setPos(pos) self.nodepath.setHpr((5,5,0)) self.scene.setLight(self.nodepath)
def set_spotlight(self): self.light = self.render.attachNewNode(Spotlight("Spot")) self.light.node().setScene(self.render) self.light.node().setShadowCaster(True) self.light.node().setColor(Vec4(0.1, 0.1, 0.1, 1)) # self.light.node().showFrustum() self.light.node().getLens().setFov(40) self.light.node().getLens().setNearFar(10, 10000) pos = self.box.center.copy() if self.box.dimensions < 3: pos = self._project3d(pos) pos[1] = -500 pos[2] = 3000 self.light.setPos(*pos[:3]) # self.light.setP(-60) self.light.setHpr(45, -80, 0) self.render.setLight(self.light) self.alight = self.render.attachNewNode(AmbientLight("Ambient")) self.alight.node().setColor(Vec4(0.2, 0.2, 0.2, 1)) self.render.setLight(self.alight) # Important! Enable the shader generator. self.render.setShaderAuto() # default values self.cameraSelection = 0 self.lightSelection = 0
def setup_lights(self): pl = PointLight('pl') pl.setColor((1, 1, 1, 1)) plNP = self.render.attachNewNode(pl) plNP.setPos(-10, -10, 10) self.render.setLight(plNP) pos = [[[0, 0, 50], [0, 0, -10]], [[0, -50, 0], [0, 10, 0]], [[-50, 0, 0], [10, 0, 0]]] for i in pos: dl = Spotlight('dl') dl.setColor((1, 1, 1, 1)) dlNP = self.render.attachNewNode(dl) dlNP.setPos(*i[0]) dlNP.lookAt(*i[1]) dlNP.node().setShadowCaster(False) self.render.setLight(dlNP)
def makeSpot(parent, color=VBase4(1, 1, 1, 1), fov=8, atten=.003): x = parent.attachNewNode(Spotlight("spot")) x.node().setColor(color) lens = PerspectiveLens() lens.setFov(fov) x.node().setLens(lens) x.node().setAttenuation(VBase3(0, 0, atten)) return x
def __init__(self, _base): self.game = _base # Player object self.playerObject = self.game.meotech.engine.GameObjects["player"] # Attach the flashlight cone to the player (self, _height, _radius, _pos, _hpr) self.flashlightConeBody = self.game.meotech.engine.factory.basePhysics.buildConeShape(10.0, 1.5, self.playerObject.bulletBody.getPos(), self.playerObject.bulletBody.getHpr()) # Attach the flashlight model to the player self.flashlight = loader.loadModel("game/models/flashlight") self.flashlight.setScale(0.2) self.flashlight.reparentTo(self.flashlightConeBody) # Attach the light to the flashlight model slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() lens.setFar(25) lens.setFov(40, 40) slight.setLens(lens) slight.setShadowCaster(True, 512, 512) self.flashlightLight = render.attachNewNode(slight) self.flashlightLight.reparentTo(self.flashlight.find("LightPos")) render.setLight(self.flashlightLight) self.flashlightConeBody.reparentTo(self.playerObject.bulletBody) self.flashlightConeBody.setPos(base.cam.getPos())
def __create_spot_light(self, lightId, lightColor, lightPos, targetId, shadow = True): spotLight = Spotlight(lightId) spotLight.setColor(lightColor) spotLight.setLens(PerspectiveLens()) spotLight.setShadowCaster(shadow) spotLightNP = NodePath(spotLight) spotLightNP.setPos(lightPos) if isinstance(targetId, list) is True: spotLightNP.lookAt(self.__sceneMgr.get_res(targetId[0])) else: spotLightNP.lookAt(self.__sceneMgr.get_res(targetId)) if self.__targetMap.has_key(lightId) is False: self.__targetMap[lightId] = [] self.__targetMap[lightId].append(targetId) return spotLightNP
def __init__(self): ShowBase.__init__(self) ambLight = AmbientLight("ambient") ambLight.setColor(Vec4(0.1,0.11,0.12,1.0)) ambNode = render.attachNewNode(ambLight) render.setLight(ambNode) dirLight = DirectionalLight("directional") dirLight.setColor(Vec4(0.7,0.7,0.68,1.0)) dirNode = render.attachNewNode(dirLight) dirNode.setHpr(60,-40,90) render.setLight(dirNode) sptLight = Spotlight("spot") sptLens = PerspectiveLens() sptLight.setLens(sptLens) sptLight.setColor(Vec4(0.6,0.6,0.6,1.0)) sptLight.setShadowCaster(True) sptNode = render.attachNewNode(sptLight) sptNode.setPos(0,0,20) sptNode.lookAt(0,0,0) render.setLight(sptNode) render.setShaderAuto() base.camLens.setFov(70) base.camLens.setNear(0.1) base.camLens.setFar(50) self.cam.setPos(-1,-4,4) self.cam.lookAt(0,-1,1)
def __setSpotlight(self, props): light = Spotlight(props['name']) light.setShadowCaster(props['castShadows'], 2048, 2048) light.setAttenuation(props['attenuation']) lens = PerspectiveLens() fov = math.degrees(props['range'].x) lens.setFov(fov) lens.setFilmSize(5096) light.setLens(lens) return self.__createLight(light, props)
def __init__(self): ShowBase.__init__(self) self.gameTask = taskMgr.add(self.gameLoop, "gameLoop") base.disableMouse() base.camera.setPos(500, 500, 2000) base.camera.lookAt(500,500,0) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) # create rebel ships self.rebels = [Xwing('xwing' + str(x)) for x in xrange(20)] self.rebels += [Ywing('ywing' + str(x)) for x in xrange(20)] self.rebels += [Awing('awing' + str(x)) for x in xrange(20)] self.rebels += [Bwing('bwing' + str(x)) for x in xrange(20)] # create imperial ships self.imperials = [TieFighter('tiefighter' + str(x)) for x in xrange(80)] self.imperials += [TieInterceptor('tieinterceptor' + str(x)) for x in xrange(80)] self.shipList = [] self.shipList += self.rebels + self.imperials for i, ship in enumerate(self.shipList): ship.reparentTo(render) ship.setScale(2) ship.setPos(Point3(random()*1000, random()*1000, random()*1000)) directionalLight = DirectionalLight('directionalLight') directionalLightNP = render.attachNewNode(directionalLight) directionalLightNP.setHpr(180, -20, 0) ship.setLight(directionalLightNP) self.outFile = open('rebels_20_each_imperial_80_each_ship2ship','w') self.camFilter = LpfVec3(Vec3(0,0,0),20)
def init_light(self, x, y, z): light = self.base.render.attachNewNode(Spotlight("Spot")) light.node().setScene(self.base.render) light.node().setShadowCaster(True, 1024 * 2, 1024 * 2) light.node().getLens().setFov(35) #light.node().showFrustum() light.node().getLens().setNearFar(10, 30) light.setPos(x, y, z) light.lookAt(0, 0, 0) return light
def __init__(self, name, root, route, mass, movforce, maxforce): AICharacter.__init__(self, name, root, mass, movforce, maxforce) self.state = Hooded.STATE_PATROL self.initTimer = True self.attackTimer = True # we create a spotlight that will be the sentinel's eye and will be used to fire the inView method self.slight = Spotlight('slight') self.slight.setColor((1, 1, 1, 1)) lens = PerspectiveLens() lens.setNear(0.1) lens.setFar(Hooded.SIGHT) lens.setFov(Hooded.FOV) self.slight.setLens(lens) self.slnp = self.get_node_path().attachNewNode(self.slight) #TODO: Substitute for a collision polygon, so that the player class alerts an enemy of its presence #self.slight.showFrustum() self.slnp.setH(self.slnp.getH()-180) self.slnp.setPos(0, 0, Hooded.HEIGHT) self.hearing = 5.0 self.dynamicObstacles = [] self.detected = False self.pathfinding = False self.lostTarget = False self.countTime = False self.goingBack = False self.heard = False self.isProtected = False self.attacked = False self.started = False self.sentinelHandler = CollisionHandlerQueue() #TODO: Intruders should be added via an external method self.intruders = [] # this is important: as we said the inView method don't cull geometry but take everything is in sight frustum - therefore to simulate an hide and seek feature we gotta cheat a little: this ray is masked to collide with walls and so if the avatar is behind a wall the ray will be 'deflected' (we'll see how later in the sent_traverse function) - so we know who's behind a wall but we fake we can't see it. sentraygeom = CollisionSegment(0, 0, Hooded.HEIGHT, 0, Hooded.SIGHT, Hooded.HEIGHT) sentinelRay = self.get_node_path().attachNewNode(CollisionNode('sentinelray')) sentinelRay.node().addSolid(sentraygeom) # we set to the ray a cumulative masking using the or operator to detect either the avatar's body and the wall geometry sentinelRay.node().setFromCollideMask(CollisionMask.PLAYER) sentinelRay.node().setIntoCollideMask(CollisionMask.NONE) # we add the ray to the sentinel collider and now it is ready to go base.cTrav.addCollider(sentinelRay, self.sentinelHandler) self.screechsound = loader.loadSfx("assets/sounds/enemies/nazgul_scream.mp3") self.setPatrolPos(route)
def launch_panda_window(panda_widget, size): """ Configure and create Panda window Connect to the gtk widget resize event Load a panda """ props = WindowProperties().getDefault() props.setOrigin(0, 0) props.setSize(*size) props.setParentWindow(panda_widget.window.xid) base.openDefaultWindow(props=props) # == panda_widget.connect("size_allocate", resize_panda_window) # == panda = loader.loadModel("panda") panda.reparentTo(render) panda.setPos(0, 40, -5) pl = render.attachNewNode(PointLight("redPointLight")) pl.node().setColor(Vec4(.9, .8, .8, 1)) render.setLight(pl) pl.node().setAttenuation(Vec3(0, 0, 0.05)) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) slnp = render.attachNewNode(slight) slnp.setPos(2, 20, 0) mid = PandaNode('mid') panda.attachNewNode(mid) # slnp.lookAt(mid) render.setLight(slnp)
def initLights(self): torches = self.level.findAllMatches("**/TorchTop*") self.lights = [] for torch in torches: tLight = PointLight(torch.getName()) tLight.setColor((.4, .2, .0, 1)) tlnp = render.attachNewNode(tLight) tlnp.setPos(torch.getPos(render)) render.setLight(tlnp) self.lights.append(tlnp) windows = self.level.findAllMatches("**/Window*") plates = self.level.findAllMatches("**/Plate*") spikes = self.level.findAllMatches("**/Spikes*") for window in windows: wLight = Spotlight(window.getName()) lens = PerspectiveLens() wLight.setLens(lens) wLight.setColor((0.5, 0.4, 0.5, 1)) wlnp = render.attachNewNode(wLight) wlnp.setPos(window.getPos(render)) wlnp.lookAt((0, window.getY(), 0)) for plate in plates: plate.setLight(wlnp) self.lights.append(wlnp) ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.1, .1, .025, 1)) render.setLight(render.attachNewNode(ambientLight))
def addLight(self, id, parent, attenuation, position, color, specular, stroboscopic, spot, lookat): if spot: slight = Spotlight(id) slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) light = render.attachNewNode(slight) light.setPos(LVector3(position[0], position[1], position[2])) if lookat == None: light.lookAt(parent) else: light.lookAt(render.find("**/" + lookat)) else: light = parent.attachNewNode(PointLight(id)) light.node().setAttenuation(attenuation) light.setPos(LVector3(position[0], position[1], position[2])) light.node().setColor(color) light.node().setSpecularColor(specular) render.setLight(light) self.light_elements[id] = light if stroboscopic: self.stroboscopic_lights.append(id) if id: self.nodes_by_id[id] = light return light
def setup_world_lightning(self): """ Sets up the ambient and specular lighting of the world :return: """ ambientLight = AmbientLight("ambientLight") ambientLight.setColor((2, 2, 2, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setShadowCaster(True) directionalLight.setDirection(LVector3(-1, -1, -1)) directionalLight.setColor((.5, .5, .5, 1)) dir_light_node = self.render.attachNewNode(directionalLight) # dir_light_node.setPos(10, 2, 7) # dir_light_node.lookAt(2, 2, 0) self.render.setLight(dir_light_node) self.render.setLight(self.render.attachNewNode(ambientLight)) spot = Spotlight("Spot") spot.setColorTemperature(9000) spot.setColor(LVector3(1, 1, 1)) light = self.render.attachNewNode(spot) light.node().setScene(self.render) light.node().setShadowCaster(True) # light.node().showFrustum() light.node().getLens().setFov(40) light.node().getLens().setNearFar(2, 100) # light.setPos(10, 2, 7) light.setPos(10, 20, 20) light.lookAt(2, 2, 0) self.render.setLight(light)
def __init__(self): """initialise and start the Game""" ShowBase.__init__(self) self.accept("escape", exit) render.setShaderAuto(True) # # SIMPLE LEVEL SETUP # self.ralph = Actor("Ralph", { "idle": "Ralph-Idle", "walk": "Ralph-Walk", "run": "Ralph-Run" }) self.ralph.loop("idle") self.ralph.reparentTo(render) self.ralph.setPos(0, 3, -2) #self.ralph.setScale(10) self.ralphIval = self.ralph.hprInterval(5.0, Vec3(-360, 0, 0)) self.ralphIval.loop() #self.ralph.setH(-20) self.environment = loader.loadModel("environment") self.environment.reparentTo(render) self.environment.setScale(0.08) self.environment.setPos(-0.5, 15, -2) base.trackball.node().setHpr(0, 22, 0) # # Lights # alight = AmbientLight("Ambient") alight.setColor(VBase4(0.3, 0.3, 0.3, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) slight = Spotlight("slight") slight.setColor(VBase4(1, 1, 1, 1)) # Use a 512x512 resolution shadow map slight.setShadowCaster(True, 2048, 2048) lens = PerspectiveLens() lens.setFov(45) slight.setLens(lens) slnp = render.attachNewNode(slight) slnp.setPos(5, -10, 5) slnp.lookAt(0, 3, -2) render.setLight(slnp)
def __setSpotlight(self,props): light = Spotlight(props['name']) light.setShadowCaster(props['castShadows'],2048,2048) light.setAttenuation(props['attenuation']) lens = PerspectiveLens() fov = math.degrees( props['range'].x ) lens.setFov(fov) lens.setFilmSize(5096); light.setLens(lens) return self.__createLight(light,props)
def setup_lights(self): pl = PointLight('pl') pl.setColor((1, 1, 1, 1)) plNP = render.attachNewNode(pl) plNP.setPos(0, 0, 0) render.setLight(plNP) # make shadows less black al = AmbientLight('al') al.setColor((0.1, 0.1, 0.1, 1)) alNP = render.attachNewNode(al) render.setLight(alNP) positions = [[[0, 0, 3], [0, 0, -1]], [[0, -3, 0], [0, 1, 0]], [[-3, 0, 0], [1, 0, 0]]] # set up directional lights (shadow casting) for i in positions: dl = Spotlight('dl') dl.setColor((1, 1, 1, 1)) dlNP = render.attachNewNode(dl) dlNP.setPos(*i[0]) # unpack the args dlNP.lookAt(*i[1]) dlNP.node().setShadowCaster(True) render.setLight(dlNP)
def makeSpotlight(name, color, pos, hpr): spot = Spotlight(name + "-spotlight") spot.setColor(color) if metadata.USE_REAL_SHADOWS: spot.setShadowCaster(True, 512, 512) snp = render.attachNewNode(spot) snp.setHpr(hpr) snp.setPos(pos) return snp
def __init__(self): ShowBase.__init__(self) #setting background self.environ = self.loader.loadModel("models/world") #Reparent the model to render #self.environ.reparentTo(self.render) #Apply scale and position transforms on the model self.environ.setScale(1000, 1000, 1000) self.environ.setPos(0, 0, 0) self.gameTask = taskMgr.add(self.gameLoop, "gameLoop") base.disableMouse() base.camera.setPos(0, -300, 100) base.camera.lookAt(0, 0, 0) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) self.shipList = [ Xwing("xwing1"), # Ywing("ywing1"), # Awing("awing1")#, # Bwing("bwing1"), # TieFighter("tiefighter1"), # TieInterceptor("tieinterceptor1") ] lightColors = [ Vec4(0.9, 0.9, 0.9, 1), Vec4(1, 1, 0, 1), Vec4(1, 0, 0, 1), Vec4(0, 0, 1, 1), Vec4(0.4, 0.4, 0.4, 1), Vec4(0.1, 0.1, 0.1, 1) ] for i, ship in enumerate(self.shipList): ship.reparentTo(render) ship.setPos(Point3(i * 10, 0, 0)) directionalLight = DirectionalLight('directionalLight') directionalLight.setColor(lightColors[i]) directionalLightNP = render.attachNewNode(directionalLight) directionalLightNP.setHpr(180, -20, 0) ship.setLight(directionalLightNP) self.count = 0 self.fire = False
def generate(self): data = CIGlobals.SuitBodyData[self.SUIT] type = data[0] team = data[1] self.generateSuit(type, self.SUIT, team, self.MAX_HP, 0, False) base.taskMgr.add(self.__viewDistance, self.viewDistanceTaskName) self.setPythonTag('guard', self) self.eyeLight = Spotlight('eyes') self.eyeLens = PerspectiveLens() self.eyeLens.setMinFov(90.0 / (4.0 / 3.0)) self.eyeLight.setLens(self.eyeLens) self.eyeNode = self.headModel.attachNewNode(self.eyeLight) self.eyeNode.setZ(-5) self.eyeNode.setY(-4.5) self.request('Guard')
def setup_spot_light(self, x, y, z): slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = self.base.camLens slight.setLens(lens) light = self.base.render.attachNewNode(slight) light.setPos(x, y, z) light.lookAt(0, 0, 0) self.direct_light.append(light) self.base.render.setLight(light)
def __init__(self, screen_size=84): ShowBase.__init__(self, windowType='offscreen') # Spotlight self.light = Spotlight('light') self.lightNP = self.render.attachNewNode(self.light) self.lightNP.setPos(0, 10, 10) self.lightNP.lookAt(0, 0, 0) self.render.setLight(self.lightNP) # Block node = PandaNode('Block') block_np = self.render.attachNewNode(node) model = loader.loadModel('box.egg') model.reparentTo(block_np) self.start_time = time.time()
def __init__(self): """initialise and start the Game""" ShowBase.__init__(self) self.accept("escape", exit) render.setShaderAuto(True) # # SIMPLE LEVEL SETUP # self.ralph = Actor("Ralph", {"idle": "Ralph-Idle", "walk": "Ralph-Walk", "run": "Ralph-Run"}) self.ralph.loop("idle") self.ralph.reparentTo(render) self.ralph.setPos(0, 3, -2) #self.ralph.setScale(10) self.ralphIval = self.ralph.hprInterval(5.0, Vec3(-360, 0, 0)) self.ralphIval.loop() #self.ralph.setH(-20) self.environment = loader.loadModel("environment") self.environment.reparentTo(render) self.environment.setScale(0.08) self.environment.setPos(-0.5, 15, -2) base.trackball.node().setHpr(0, 22, 0) # # Lights # alight = AmbientLight("Ambient") alight.setColor(VBase4(0.3, 0.3, 0.3, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) slight = Spotlight("slight") slight.setColor(VBase4(1, 1, 1, 1)) # Use a 512x512 resolution shadow map slight.setShadowCaster(True, 2048, 2048) lens = PerspectiveLens() lens.setFov(45) slight.setLens(lens) slnp = render.attachNewNode(slight) slnp.setPos(5, -10, 5) slnp.lookAt(0, 3, -2) render.setLight(slnp)
def __init__(self,filename): self.height = 0 self.width = 0 self.waterheight = 0 self.countries = [] self.tileList = [] self.tileReference = {} self.node = render.attachNewNode('BaseMap') self.snow = loader.loadModel("data/models/snow.bam") self.ice = loader.loadModel("data/models/ice.bam") self.plains = loader.loadModel("data/models/plains.bam") self.forest = loader.loadModel("data/models/forest.bam") self.jaggedrocks = loader.loadModel("data/models/jaggedrocks.bam") self.mountain = loader.loadModel("data/models/mountains.bam") self.desert = loader.loadModel("data/models/desert.bam") self.hills = loader.loadModel("data/models/hills.bam") self.water = loader.loadModel("data/models/water.bam") self.water.setTransparency(TransparencyAttrib.MAlpha) self.watertop = loader.loadModel("data/models/watertop.bam") self.waterbottom = loader.loadModel("data/models/waterbottom.bam") render.setShaderAuto() self.spot = Spotlight('World spot') self.spot.setColor((.7,.7,.7,1)) self.spot.getLens().setFov(180) self.spot.getLens().setNearFar(1,10000000) self.spotNode = render.attachNewNode(self.spot) self.spotNode.setPos(2000,2000,5000) self.spotNode.lookAt(self.node) render.setLight(self.spotNode) self.createMap(filename) self.watertop.reparentTo(self.node) self.watertop.setScale(9,9,9) self.watertop.setPos((self.width*60)/2,-(self.height*17)/2,5) self.waterbottom.reparentTo(self.node) self.waterbottom.setScale(9,9,9) self.waterbottom.setPos((self.width*60)/2,-(self.height*17)/2,1)
def __init__(self): self.accept("1", self.breakProgram) #lighting slight = Spotlight('slight') slight.setColor((1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) #attaching lighting self.slnp = render.attachNewNode(slight) self.slnp1 = render.attachNewNode(slight) #runs as a thread to change the HPR of the plane taskMgr.add(rotatemycube)
def __set_light(self): if self.props.shaders: eng.set_amb_lgt((.15, .15, .15, 1)) eng.set_dir_lgt((.8, .8, .8, 1), (-25, -65, 0)) return ambient_lgt = AmbientLight('ambient light') ambient_lgt.setColor((.7, .7, .55, 1)) self.ambient_np = render.attachNewNode(ambient_lgt) render.setLight(self.ambient_np) self.spot_lgt = render.attachNewNode(Spotlight('Spot')) self.spot_lgt.node().setScene(render) self.spot_lgt.node().setShadowCaster(True, 1024, 1024) self.spot_lgt.node().getLens().setFov(40) self.spot_lgt.node().getLens().setNearFar(20, 200) self.spot_lgt.node().setCameraMask(BitMask32.bit(0)) self.spot_lgt.setPos(*self.props.shadow_src) self.spot_lgt.lookAt(0, 0, 0) render.setLight(self.spot_lgt) render.setShaderAuto()
def buildSubType(self): """Build the light with the given subType""" if self.subType == "pointType": # make a point light c = self.color pointLight = PointLight(self.name) pointLight.setColor(VBase4(c[0], c[1], c[2], c[3])) plnp = self.renderObjectsLight.attachNewNode(pointLight) plnp.setPos(self.position) self.lightNP = plnp self.setLightSwitch(True) if self.subType == "directType": # make a directional light c = self.color directLight = DirectionalLight(self.name) directLight.setColor(VBase4(c[0], c[1], c[2], c[3])) dlnp = self.renderObjectsLight.attachNewNode(directLight) dlnp.setHpr(0, -60, 0) # no idea why its like that.. but it works self.lightNP = dlnp self.setLightSwitch(True) if self.subType == "ambientType": # make a ambient light c = self.color ambientLight = AmbientLight(self.name) ambientLight.setColor(VBase4(c[0], c[1], c[2], c[3])) alnp = self.renderObjectsLight.attachNewNode(ambientLight) self.lightNP = alnp self.setLightSwitch(True) if self.subType == "spotType": # make a spot light # lookAtObj = _object.getTag("lookAt") get rid of this. c = self.color spotLight = Spotlight(self.name) spotLight.setColor(VBase4(c[0], c[1], c[2], c[3])) lens = PerspectiveLens() spotLight.setLens(lens) slnp = self.renderObjectsLight.attachNewNode(spotLight) slnp.setPos(self.position) slnp.setHpr(self.hpr) # Find out if this is really the only option # because setHpr doesnt seem to have any effect. # lookAt would be okay but that means adding anothe type #slnp.lookAt(self.main.GameObjects["player"].collisionBody) self.lightNP = slnp self.setLightSwitch(True)
class FactorySneakGuardSuit(Suit, FSM): notify = directNotify.newCategory('FactorySneakGuardSuit') SUIT = 'mrhollywood' VIEW_DISTANCE_TASK_NAME = 'ViewDistanceTask' MAX_VIEW_DISTANCE = 100.0 GUARD_DIED_DELAY = 6.0 MAX_HP = 200 IN_VIEW = 'somethingInSight' HEARD = 'heard' TRY_TO_CONFIRM_TIME = 5.0 def __init__(self, world, guardKey): Suit.__init__(self) FSM.__init__(self, 'FactorySneakGuardSuit') self.gameWorld = world self.guardKey = guardKey self.viewDistanceTaskName = self.VIEW_DISTANCE_TASK_NAME + '-' + str(id(self)) self.diedTaskName = 'GuardDied-' + str(id(self)) self.health = 0 self.maxHealth = self.MAX_HP self.eyeLight = None self.eyeLens = None self.eyeNode = None self.moveTrack = None return def enterGuard(self): self.loop('neutral') pos, hpr = CGG.FactoryGuardPoints[self.guardKey] self.setHpr(hpr - (180, 0, 0)) self.setPos(pos) base.taskMgr.add(self.__guard, self.taskName('guard')) def __guard(self, task): if self.eyeNode.node().isInView(base.localAvatar.getPos(self.eyeNode)): self.request('SeekTarget', self.IN_VIEW) return task.done return task.cont def exitGuard(self): base.taskMgr.remove(self.taskName('guard')) def enterTurnToGuardSpot(self): self.loop('walk') _, hpr = CGG.FactoryGuardPoints[self.guardKey] self.moveTrack = LerpHprInterval(self, duration=1.0, hpr=hpr, startHpr=self.getHpr()) self.moveTrack.setDoneEvent(self.uniqueName('TurnedToGuardSpot')) self.acceptOnce(self.moveTrack.getDoneEvent(), self.request, ['Guard']) self.moveTrack.start() def exitTurnToGuardSpot(self): if self.moveTrack: self.ignore(self.moveTrack.getDoneEvent()) self.moveTrack.finish() self.moveTrack = None return def enterSeekTarget(self, event): dialogue = random.choice(CGG.GuardDialog[event]) self.setChat(dialogue) self.loop('walk') self.moveTrack = NPCLookInterval(self, base.localAvatar) self.moveTrack.setDoneEvent(self.uniqueName('SeekLocalAvatar')) self.acceptOnce(self.moveTrack.getDoneEvent(), self.request, ['TryToConfirmTarget']) self.moveTrack.start() def exitSeekTarget(self): if self.moveTrack: self.ignore(self.moveTrack.getDoneEvent()) self.moveTrack.finish() self.moveTrack = None return def enterTryToConfirmTarget(self): self.loop('neutral') base.taskMgr.add(self.__tryToConfirmTarget, self.uniqueName('TryToConfirmTarget')) def __tryToConfirmTarget(self, task): if task.time >= self.TRY_TO_CONFIRM_TIME: chat = random.choice(CGG.GuardDialog['disregard']) self.setChat(chat) self.request('TurnToGuardSpot') return task.done if self.eyeNode.node().isInView(base.localAvatar.getPos(self.eyeNode)): chat = random.choice(CGG.GuardDialog['spot']) self.setChat(chat) return task.done return task.cont def exitTryToConfirmTarget(self): base.taskMgr.remove(self.uniqueName('TryToConfirmTarget')) def uniqueName(self, name): return self.taskName(name) def taskName(self, name): return name + '-' + str(id(self)) def setHealth(self, hp): self.health = hp def getHealth(self): return self.health def shot(self): dialogue = random.choice(CGG.GuardDialog['shot']) self.setChat(dialogue) def dead(self): self.animFSM.request('die') base.taskMgr.doMethodLater(self.GUARD_DIED_DELAY, self.__diedDone, self.diedTaskName) def __diedDone(self, task): self.gameWorld.deleteGuard(self) return task.done def generate(self): data = CIGlobals.SuitBodyData[self.SUIT] type = data[0] team = data[1] self.generateSuit(type, self.SUIT, team, self.MAX_HP, 0, False) base.taskMgr.add(self.__viewDistance, self.viewDistanceTaskName) self.setPythonTag('guard', self) self.eyeLight = Spotlight('eyes') self.eyeLens = PerspectiveLens() self.eyeLens.setMinFov(90.0 / (4.0 / 3.0)) self.eyeLight.setLens(self.eyeLens) self.eyeNode = self.headModel.attachNewNode(self.eyeLight) self.eyeNode.setZ(-5) self.eyeNode.setY(-4.5) self.request('Guard') def __viewDistance(self, task): if self.getDistance(base.localAvatar) > self.MAX_VIEW_DISTANCE: if not self.isHidden(): self.hide() elif self.isHidden(): self.show() task.delayTime = 1.0 return task.again def disable(self): base.taskMgr.remove(self.diedTaskName) base.taskMgr.remove(self.viewDistanceTaskName) if self.eyeNode: self.eyeNode.removeNode() self.eyeNode = None self.eyeLens = None self.eyeLight = None self.viewDistanceTaskName = None self.guardKey = None self.gameWorld = None Suit.disable(self) return
class Hooded(AICharacter): SIGHT=7.5 FOV=60.0 HEIGHT = 1.3 STATE_PATROL = 0 STATE_SEARCH = 1 STATE_WANDER = 2 STATE_ATTACK = 3 STATE_PAUSED = 4 class StatePatrol: pass def __init__(self, name, root, route, mass, movforce, maxforce): AICharacter.__init__(self, name, root, mass, movforce, maxforce) self.state = Hooded.STATE_PATROL self.initTimer = True self.attackTimer = True # we create a spotlight that will be the sentinel's eye and will be used to fire the inView method self.slight = Spotlight('slight') self.slight.setColor((1, 1, 1, 1)) lens = PerspectiveLens() lens.setNear(0.1) lens.setFar(Hooded.SIGHT) lens.setFov(Hooded.FOV) self.slight.setLens(lens) self.slnp = self.get_node_path().attachNewNode(self.slight) #TODO: Substitute for a collision polygon, so that the player class alerts an enemy of its presence #self.slight.showFrustum() self.slnp.setH(self.slnp.getH()-180) self.slnp.setPos(0, 0, Hooded.HEIGHT) self.hearing = 5.0 self.dynamicObstacles = [] self.detected = False self.pathfinding = False self.lostTarget = False self.countTime = False self.goingBack = False self.heard = False self.isProtected = False self.attacked = False self.started = False self.sentinelHandler = CollisionHandlerQueue() #TODO: Intruders should be added via an external method self.intruders = [] # this is important: as we said the inView method don't cull geometry but take everything is in sight frustum - therefore to simulate an hide and seek feature we gotta cheat a little: this ray is masked to collide with walls and so if the avatar is behind a wall the ray will be 'deflected' (we'll see how later in the sent_traverse function) - so we know who's behind a wall but we fake we can't see it. sentraygeom = CollisionSegment(0, 0, Hooded.HEIGHT, 0, Hooded.SIGHT, Hooded.HEIGHT) sentinelRay = self.get_node_path().attachNewNode(CollisionNode('sentinelray')) sentinelRay.node().addSolid(sentraygeom) # we set to the ray a cumulative masking using the or operator to detect either the avatar's body and the wall geometry sentinelRay.node().setFromCollideMask(CollisionMask.PLAYER) sentinelRay.node().setIntoCollideMask(CollisionMask.NONE) # we add the ray to the sentinel collider and now it is ready to go base.cTrav.addCollider(sentinelRay, self.sentinelHandler) self.screechsound = loader.loadSfx("assets/sounds/enemies/nazgul_scream.mp3") self.setPatrolPos(route) def __del__(self): self.slnp.removeNode() def addIntruder(self, intruder): self.intruders.append(intruder) def setPatrolPos(self, route): self.currentTarget = 0 self.route = route self.numTargets = len(route) self.increment = 1 self.getAiBehaviors().seek(self.route[0]) #to update the AIWorld def update(self): if (self.started == False): return False captured = self.sent_detect() if (captured): if (self.isProtected): self.state = Hooded.STATE_PAUSED elif (self.state != Hooded.STATE_SEARCH): self.state = Hooded.STATE_SEARCH self.getAiBehaviors().pauseAi("all") self.lostTarget = False self.heard = False self.resetTimer() """elif (self.heard): self.heard = False self.pursueTarget = self.hearingPos self.getAiBehaviors().pauseAi("all") self.state = Hooded.STATE_SEARCH elif (self.state == Hooded.STATE_SEARCH and self.lostTarget == False and self.goingBack == False): self.startTimer(1.5) hasFinished = self.timer() if (hasFinished == True): self.lostTarget = True self.getAiBehaviors().pauseAi("all") #self.state = 4 self.pursueTarget = self.TargetPos else: self.lostTarget = False""" if self.state == Hooded.STATE_PATROL: self.patrol() elif self.state == Hooded.STATE_SEARCH: self.pursue() elif self.state == Hooded.STATE_WANDER: self.wander() elif self.state == Hooded.STATE_ATTACK: self.kill() elif self.state == Hooded.STATE_PAUSED: self.pause() #elif self.state == Hooded.STATE_SEARCH: #self.pathfind() if (self.attacked): self.attacked = False return True return False #TODO: Patrol is ready for refactoring, if needed PATROL_PAUSE = 3.0 PATROL_DISTANCE = 1.0 def patrol(self): distance = self.get_node_path().getDistance(self.route[self.currentTarget]) if (distance < Hooded.PATROL_DISTANCE): self.startTimer(Hooded.PATROL_PAUSE) self.getAiBehaviors().pauseAi("all") if self.timer(): self.currentTarget = (self.currentTarget + 1) % len(self.route) self.resetTimer() self.getAiBehaviors().pauseAi("all") self.getAiBehaviors().seek(self.route[self.currentTarget]) self.getAiBehaviors().resumeAi("seek") def pathfind(self): if (not self.getAiBehaviors().behaviorStatus("pathfollow") in ["active", "done"]): self.getAiBehaviors().initPathFind("assets/navmesh.csv") self.getAiBehaviors().pauseAi("all") if isinstance(self.pursueTarget, NodePath): self.getAiBehaviors().pathFindTo(self.pursueTarget) else: self.getAiBehaviors().pathFindTo(self.pursueTarget.getNodePath()) for i in self.dynamicObstacles: self.getAiBehaviors().addDynamicObstacle(i) #self.pathfinding = True currentPos = self.get_node_path().getPos(render) if (isinstance(self.pursueTarget, NodePath)): self.TargetPos = self.pursueTarget else: self.TargetPos = self.pursueTarget.getNodePath() # print currentPos, self.TargetPos distance = self.get_node_path().getDistance(self.TargetPos) if (self.getAiBehaviors().behaviorStatus("pathfollow") == "done"): if (distance > 5): self.getAiBehaviors().pauseAi("all") return if (self.lostTarget == False): if (self.goingBack == True): self.getAiBehaviors().pauseAi("all") self.getAiBehaviors().seek(self.route[self.currentTarget]) self.state = Hooded.STATE_PATROL self.getAiBehaviors().resumeAi("seek") self.resetTimer() self.goingBack = False elif (self.heard == True): if (isinstance(self.pursueTarget, NodePath)): self.getAiBehaviors().pauseAi("all") self.state = Hooded.STATE_ATTACK else: self.startTimer(5) self.countTime = True self.pathfinding = False self.state = Hooded.STATE_WANDER self.radius = 5 self.aoe = 10 else: self.getAiBehaviors().pauseAi("all") self.state = Hooded.STATE_ATTACK else: self.startTimer(5) self.countTime = True self.pathfinding = False self.state = Hooded.STATE_WANDER self.radius = 5 self.aoe = 10 def wander(self): if (self.getAiBehaviors().behaviorStatus("wander") != "active"): self.getAiBehaviors().pauseAi("all") self.getAiBehaviors().wander(self.radius, 0,self.aoe, 1.0) #self.getAiBehaviors().resumeAi("wander") if (self.lostTarget == True and self.countTime == True): self.startTimer(5) hasFinished = self.timer() if (hasFinished == True): self.currentTarget += self.increment if (self.currentTarget == self.numTargets - 1): self.increment = -1 else: if (self.currentTarget == 0): self.increment = 1 self.pursueTarget = self.route[self.currentTarget] self.state = Hooded.STATE_SEARCH self.goingBack = True self.lostTarget= False self.getAiBehaviors().pauseAi("all") #self.getAiBehaviors().seek(self.route[self.currentTarget]) def kill(self): if (self.attackTimer): self.attacked = True self.attackTimer = False self.startTimer(3) self.pause() else: hasFinished = self.timer() if (hasFinished): self.attackTimer = True self.resetTimer() self.state = Hooded.STATE_SEARCH else: self.attacked = False #TODO: Use event handling, instead? def sent_traverse(self, suspect): if (self.sentinelHandler.getNumEntries() > 0): self.sentinelHandler.sortEntries() # for i in range(self.sentinelHandler.getNumEntries()): # print self.sentinelHandler.getEntry(i) entry = self.sentinelHandler.getEntry(0) self.sentinelHandler.clearEntries() colliderNP = entry.getIntoNodePath() if colliderNP.getParent() == suspect.getNodePath(): # self = False if self.detected == False: self.detected = True self.screechsound.play() suspect.boo() return True #TODO: This was meant for the implementation of safe areas, where the player could not be reached elif colliderNP.getName() == 'lightarea': newEntry = self.sentinelHandler.getEntry(1) newColliderNode = newEntry.getIntoNode() if (newColliderNode.getName() == 'playercol'): #check if player is really inside light area self.isProtected = True return True return False #** Here then we'll unleash the power of isInView method - this function is just a query if a 3D point is inside its frustum so it works for objects with lens, such as cameras or even, as in this case, a spotlight. But to make this happen, we got cheat a little, knowing in advance who we're going to seek, to query its position afterwards, and that's what the next line is about: to collect all the references for objects named 'smiley' def sent_detect(self): for o in self.intruders: # query the spotlight if something listed as 'intruders' is-In-View at its position and if this is the case we'll call the traverse function above to see if is open air or hidden from the sentinel's sight if self.slnp.node().isInView(o.getNodePath().getPos(self.slnp)): self.get_node_path().lookAt(o.getNodePath()) if self.sent_traverse(o): self.pursueTarget = o return True return False def timer(self): currentTime = time.time() diff = currentTime - self.time if (diff > self.interval): self.initTimer = True return True else: return False def resetTimer(self): self.initTimer = True def startTimer(self, interval): if (self.initTimer == True): self.interval = interval self.initTimer = False self.time = time.time() def addDynamicObject(self, dynamicObject): self.dynamicObstacles.append(dynamicObject) def hear(self, noisePos): dist = self.get_node_path().getDistance(noisePos) if (dist <= self.hearing): self.heard = True self.hearingPos = noisePos def pause(self): self.getAiBehaviors().pauseAi("all") #print "nao pausei?" def start(self): self.started = True def stop(self): self.started = False def clean(self): loader.unloadSfx(self.screechsound) def pursue(self): self.getAiBehaviors().pursue(self.pursueTarget.getNodePath()) if (self.get_node_path().getDistance(self.pursueTarget.getNodePath()) < 1): self.state = Hooded.STATE_ATTACK
class Map: def __init__(self,filename): self.height = 0 self.width = 0 self.waterheight = 0 self.countries = [] self.tileList = [] self.tileReference = {} self.node = render.attachNewNode('BaseMap') self.snow = loader.loadModel("data/models/snow.bam") self.ice = loader.loadModel("data/models/ice.bam") self.plains = loader.loadModel("data/models/plains.bam") self.forest = loader.loadModel("data/models/forest.bam") self.jaggedrocks = loader.loadModel("data/models/jaggedrocks.bam") self.mountain = loader.loadModel("data/models/mountains.bam") self.desert = loader.loadModel("data/models/desert.bam") self.hills = loader.loadModel("data/models/hills.bam") self.water = loader.loadModel("data/models/water.bam") self.water.setTransparency(TransparencyAttrib.MAlpha) self.watertop = loader.loadModel("data/models/watertop.bam") self.waterbottom = loader.loadModel("data/models/waterbottom.bam") render.setShaderAuto() self.spot = Spotlight('World spot') self.spot.setColor((.7,.7,.7,1)) self.spot.getLens().setFov(180) self.spot.getLens().setNearFar(1,10000000) self.spotNode = render.attachNewNode(self.spot) self.spotNode.setPos(2000,2000,5000) self.spotNode.lookAt(self.node) render.setLight(self.spotNode) self.createMap(filename) self.watertop.reparentTo(self.node) self.watertop.setScale(9,9,9) self.watertop.setPos((self.width*60)/2,-(self.height*17)/2,5) self.waterbottom.reparentTo(self.node) self.waterbottom.setScale(9,9,9) self.waterbottom.setPos((self.width*60)/2,-(self.height*17)/2,1) def getCountry(self,countryNum): return self.countries[countryNum] def drawMap(self): pass def createMap(self,filename): filein = open(filename,"rb") countryCounter = 0 tileCounter = 0 countryTiles = [] countryIncome = 0 for line in filein: words = line.split() if len(words) > 0: if words[0] == "<map>": pass elif words[0] == "<height>": self.height = eval(words[1]) elif words[0] == "<width>": self.width = eval(words[1]) elif words[0] == "<waterheight>": self.waterheight = eval(words[1]) elif words[0] == "<tile>": terrainType = eval(words[1]) newNode = self.node.attachNewNode('terrain'+str(tileCounter)) newNode.setTag('tile',str(tileCounter)) if terrainType == TERRAIN_WATER: self.water.instanceTo(newNode) elif terrainType == TERRAIN_SNOW: self.snow.instanceTo(newNode) elif terrainType == TERRAIN_ICE: self.ice.instanceTo(newNode) elif terrainType == TERRAIN_PLAINS: self.plains.instanceTo(newNode) elif terrainType == TERRAIN_FOREST: self.forest.instanceTo(newNode) elif terrainType == TERRAIN_JAGGEDROCKS: self.jaggedrocks.instanceTo(newNode) elif terrainType == TERRAIN_MOUNTAIN: self.mountain.instanceTo(newNode) elif terrainType == TERRAIN_DESERT: self.desert.instanceTo(newNode) elif terrainType == TERRAIN_HILLS: self.hills.instanceTo(newNode) x = (tileCounter % self.width) y = (tileCounter / self.width) if y % 2 == 0: newNode.setPos(x*60,-y*17,0) else: newNode.setPos(x*60+30,-y*17,0) newTile = Tile(terrainType,newNode,x,y,tileCounter) self.tileList.append(newTile) tileCounter += 1 elif words[0] == "<income>": countryIncome = eval(words[1]) elif words[0] == "<tileNum>": countryTiles.append(self.tileList[eval(words[1])]) elif words[0] == "</country>": newCountry = Country(countryTiles,countryIncome) self.countries.append(newCountry) countryCounter += 1 countryTiles = [] countryIncome = 0 else: pass #end loop for country in range(len(self.countries)): for tile in self.countries[country].getTiles(): x = tile.getX() y = tile.getY() self.tileReference[(x,y)]=country filein.close() #end init def getTile(self,x,y): #get the tile from the country it is in from spectile return self.countries[self.tileReference[(x,y)]].getSpecTile(x,y) def getPlayerCountries(self,playerNum): #return the list of countries that belong to that player playerCountries = [] for country in self.countries: if country.getOwner() == playerNum: playerCountries.append(country) return playerCountries
# just make another branch connected to this one with a small # variation in direction makeFractalTree(bodydata, nodePath, length, newPos, numIterations - 1, numCopies, smallRandomAxis(vecList)) else: drawBody(nodePath, bodydata, pos, vecList, length.getX(), False) drawLeaf(nodePath, bodydata, pos, vecList) alight = AmbientLight('alight') alight.setColor((0.5, 0.5, 0.5, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) slight = Spotlight('slight') slight.setColor((1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) slnp = render.attachNewNode(slight) render.setLight(slnp) slnp.setPos(0, 0, 40) # rotating light to show that normals are calculated correctly def updateLight(task): global slnp currPos = slnp.getPos() currPos.setX(100 * math.cos(task.time) / 2) currPos.setY(100 * math.sin(task.time) / 2) slnp.setPos(currPos)
else: #just make another branch connected to this one with a small variation in direction makeFractalTree(bodydata, nodePath,length,newPos, numIterations-1,numCopies,smallRandomAxis(vecList)) else: drawBody(nodePath,bodydata, pos, vecList, length.getX(),False) drawLeaf(nodePath,bodydata, pos,vecList) alight = AmbientLight('alight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) slight = Spotlight('slight') slight.setColor(Vec4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) slnp = render.attachNewNode(slight) render.setLight(slnp) slnp.setPos(0, 0,40) #rotating light to show that normals are calculated correctly def updateLight(task): global slnp currPos=slnp.getPos() currPos.setX(100*math.cos(task.time)/2) currPos.setY(100*math.sin(task.time)/2) slnp.setPos(currPos)
def parse_scene(self,scene,parent=None): tmp_statics = scene["statics"]; lst_statics = {}; it = 0 for elt in tmp_statics["sol"]: if not self.dic_statics.has_key(elt): self.dic_statics[elt] = base.loader.loadModel(elt+".bam") for posrot in tmp_statics["sol"][elt]: tmp_inst = render.attachNewNode("sol_"+str(it)); self.dic_statics[elt].instanceTo(tmp_inst) tmp_inst.setPos(posrot[0][0]*4.8,posrot[0][1]*4.8,posrot[0][2]*4.8); tmp_inst.setHpr(posrot[1][0],posrot[1][1],posrot[1][2]) tmp_inst.reparentTo(render); lst_statics["sol_"+str(it)] = tmp_inst # # TODO : génération de la carte si besoin # # TODO : voir pour le navigational mesh ici # it += 1 for key in ["nord","sud","est","ouest"]: for elt in tmp_statics["bords"][key]: # print elt # if key == "nord": # # pass elif key == "sud": # # pass elif key == "est": # # pass elif key == "ouest": # # pass # pass for elt in tmp_statics["murs"][key]: # print elt # # pass for elt in tmp_statics["decors"][key]: # print elt # # pass # # TODO : chargement des animations # tmp_dynamics = scene["dynamics"]; lst_dynamics = {} # for elt in tmp_dynamics: # # # pass # # tmp_lights = scene["lights"]; lst_lights = {} for lght in tmp_lights: tmp_lght = None if lght[0] == 0: spot_light = Spotlight("spotlight"); spot_light.setColor(Vec4(lght[1][0],lght[1][1],lght[1][2],lght[1][3])) lens = PerspectiveLens(); spot_light.setLens(lens); tmp_lght = render.attachNewNode(spot_light) tmp_lght.lookAt(lght[3][0],lght[3][1],lght[3][2]); tmp_lght.setPos(lght[2][0],lght[2][1],lght[2][2]) elif lght[0] == 1: dir_light = DirectionalLight("dir_light"); dir_light.setColor(Vec4(lght[1][0],lght[1][1],lght[1][2],lght[1][3])) tmp_lght = render.attachNewNode(dir_light); tmp_lght.setHpr(lght[3][0],lght[3][1],lght[3][2]) if lght[4]: if lght[5] != None: lght[5].setLight(tmp_lght) else: render.setLight(tmp_lght) lst_lights[lght[6]] = tmp_lght # # # return lst_statics, lst_dynamics, lst_lights
def runViewer(mesh): scene_members = getSceneMembers(mesh) loadPrcFileData('', 'win-size 300 300') base = ShowBase() globNode = GeomNode("collada") nodePath = base.render.attachNewNode(globNode) rotateNode = GeomNode("rotater") rotatePath = nodePath.attachNewNode(rotateNode) matrix = numpy.identity(4) if mesh.assetInfo.upaxis == collada.asset.UP_AXIS.X_UP: r = collada.scene.RotateTransform(0,1,0,90) matrix = r.matrix elif mesh.assetInfo.upaxis == collada.asset.UP_AXIS.Y_UP: r = collada.scene.RotateTransform(1,0,0,90) matrix = r.matrix rotatePath.setMat(Mat4(*matrix.T.flatten().tolist())) basecollada = GeomNode("basecollada") basecolladaNP = rotatePath.attachNewNode(basecollada) for geom, renderstate, mat4 in scene_members: node = GeomNode("primitive") node.addGeom(geom) if renderstate is not None: node.setGeomState(0, renderstate) geomPath = basecolladaNP.attachNewNode(node) geomPath.setMat(mat4) for boundlight in mesh.scene.objects('light'): if len(boundlight.color) == 3: color = (boundlight.color[0], boundlight.color[1], boundlight.color[2], 1) else: color = boundlight.color if isinstance(boundlight, collada.light.BoundDirectionalLight): dl = DirectionalLight('dirLight') dl.setColor(Vec4(color[0], color[1], color[2], color[3])) lightNP = rotatePath.attachNewNode(dl) lightNP.lookAt(Point3(boundlight.direction[0],boundlight.direction[1],boundlight.direction[2])) elif isinstance(boundlight, collada.light.BoundAmbientLight): ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(color[0], color[1], color[2], color[3])) lightNP = rotatePath.attachNewNode(ambientLight) elif isinstance(boundlight, collada.light.BoundPointLight): pointLight = PointLight('pointLight') pointLight.setColor(Vec4(color[0], color[1], color[2], color[3])) pointLight.setAttenuation(Vec3(boundlight.constant_att, boundlight.linear_att, boundlight.quad_att)) lightNP = rotatePath.attachNewNode(pointLight) lightNP.setPos(Vec3(boundlight.position[0], boundlight.position[1], boundlight.position[2])) elif isinstance(boundlight, collada.light.BoundSpotLight): spotLight = Spotlight('spotLight') spotLight.setColor(Vec4(color[0], color[1], color[2], color[3])) spotLight.setAttenuation(Vec3(boundlight.constant_att, boundlight.linear_att, boundlight.quad_att)) spotLight.setExponent(boundlight.falloff_exp) lightNP = rotatePath.attachNewNode(spotLight) lightNP.setPos(Vec3(boundlight.position[0], boundlight.position[1], boundlight.position[2])) lightNP.lookAt(Point3(boundlight.direction[0], boundlight.direction[1], boundlight.direction[2]), Vec3(boundlight.up[0], boundlight.up[1], boundlight.up[2])) else: print('Unknown light type', boundlight) continue base.render.setLight(lightNP) for boundcam in mesh.scene.objects('camera'): if isinstance(boundcam, collada.camera.BoundPerspectiveCamera): base.camera.reparentTo(rotatePath) base.camLens.setNear(boundcam.znear) base.camLens.setFar(boundcam.zfar) if boundcam.xfov is not None and boundcam.yfov is not None: #xfov + yfov base.camLens.setFov(boundcam.xfov, boundcam.yfov) elif boundcam.xfov is not None and boundcam.aspect_ratio is not None: #xfov + aspect_ratio base.camLens.setFov(boundcam.xfov) base.camLens.setAspectRatio(boundcam.aspect_ratio) elif boundcam.yfov is not None and boundcam.aspect_ratio is not None: #yfov + aspect_ratio #aspect_ratio = tan(0.5*xfov) / tan(0.5*yfov) xfov = math.degrees(2.0 * math.atan(boundcam.aspect_ratio * math.tan(math.radians(0.5 * boundcam.yfov)))) base.camLens.setFov(xfov, boundcam.yfov) elif boundcam.yfov is not None: #yfov only #aspect_ratio = tan(0.5*xfov) / tan(0.5*yfov) xfov = math.degrees(2.0 * math.atan(base.camLens.getAspectRatio() * math.tan(math.radians(0.5 * boundcam.yfov)))) base.camLens.setFov(xfov, boundcam.yfov) elif boundcam.xfov is not None: base.camLens.setFov(boundcam.xfov) base.camera.setPos(Vec3(boundcam.position[0], boundcam.position[1], boundcam.position[2])) base.camera.lookAt(Point3(boundcam.direction[0], boundcam.direction[1], boundcam.direction[2]), Vec3(boundcam.up[0], boundcam.up[1], boundcam.up[2])) elif isinstance(boundcam, collada.camera.BoundOrthographicCamera): lens = OrthographicLens() base.cam.node().setLens(lens) base.camLens = lens base.camera.reparentTo(rotatePath) base.camLens.setNear(boundcam.znear) base.camLens.setFar(boundcam.zfar) if boundcam.xmag is not None and boundcam.ymag is not None: #xmag + ymag base.camLens.setFilmSize(boundcam.xmag, boundcam.ymag) elif boundcam.xmag is not None and boundcam.aspect_ratio is not None: #xmag + aspect_ratio base.camLens.setFilmSize(boundcam.xmag) base.camLens.setAspectRatio(boundcam.aspect_ratio) elif boundcam.ymag is not None and boundcam.aspect_ratio is not None: #ymag + aspect_ratio xmag = boundcam.aspect_ratio * boundcam.ymag base.camLens.setFilmSize(xmag, boundcam.ymag) elif boundcam.ymag is not None: #ymag only xmag = base.camLens.getAspectRatio() * boundcam.ymag base.camLens.setFilmSize(xmag, boundcam.ymag) elif boundcam.xmag is not None: base.camLens.setFilmSize(boundcam.xmag) base.camera.setPos(Vec3(boundcam.position[0], boundcam.position[1], boundcam.position[2])) base.camera.lookAt(Point3(boundcam.direction[0], boundcam.direction[1], boundcam.direction[2]), Vec3(boundcam.up[0], boundcam.up[1], boundcam.up[2])) else: print('Unknown camera type', boundcam) continue base.disableMouse() base.render.setShaderAuto() base.render.setTransparency(TransparencyAttrib.MDual, 1) KeyboardMovement() MouseDrag(basecolladaNP) MouseScaleZoom(basecolladaNP) base.run()
def __init__(self): ShowBase.__init__(self) self.gameTask = taskMgr.add(self.flyCircles, "circles") base.disableMouse() base.camera.setPos(-400, 00, 400) base.camera.lookAt(00, 000, 0) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) self.rebels = [] self.imperials = [] # add rebel ships self.rebels += [Xwing('xwing' + str(x)) for x in xrange(1)] #self.rebels += [Ywing('ywing' + str(x)) for x in xrange(1)] #self.rebels += [Awing('awing' + str(x)) for x in xrange(1)] #self.rebels += [Bwing('bwing' + str(x)) for x in xrange(1)] # add imperial ships self.imperials += [TieFighter('tiefighter' + str(x)) for x in xrange(1)] #self.imperials += [TieInterceptor('tieinterceptor' + str(x)) for x in xrange(2)] # add rebel ships self.rebels += [Xwing('xwing' + str(x) + 'second') for x in xrange(1)] #self.rebels += [Ywing('ywing' + str(x) + 'second') for x in xrange(1)] #self.rebels += [Awing('awing' + str(x) + 'second') for x in xrange(1)] #self.rebels += [Bwing('bwing' + str(x) + 'second') for x in xrange(1)] # add more imperial ships #self.imperials += [TieFighter('tiefighter' + str(x) + 'second') for x in xrange(2)] self.imperials += [TieInterceptor('tieinterceptor' + str(x) + 'second') for x in xrange(1)] # create ship list self.shipList = self.rebels + self.imperials #self.shipList = [ # Xwing("xwing1"), TieFighter("tie1"), Bwing("xwing2")] lightColors = [ Vec4(0.9, 0.9, 0.9, 1), Vec4(0.9, 0.9, 0.9, 1),] for i, ship in enumerate(self.shipList): ship.reparentTo(render) ship.setScale(2) ship.setPos(Point3(i*50+50,i*100+100,i*50+50)) directionalLight = DirectionalLight('directionalLight') directionalLightNP = render.attachNewNode(directionalLight) directionalLightNP.setHpr(180, -20, 0) ship.setLight(directionalLightNP) #ship.navSystem.setPursue() self.count = 0 self.iter = 0 camera.lookAt(self.shipList[1].getPos())
def __init__(self): ShowBase.__init__(self) #Setup scene = BulletWorld() scene.setGravity(Vec3(0, 0, -9.81)) base.setBackgroundColor(0.6,0.9,0.9) fog = Fog("The Fog") fog.setColor(0.9,0.9,1.0) fog.setExpDensity(0.003) render.setFog(fog) #Lighting #Sun light sun = DirectionalLight("The Sun") sun_np = render.attachNewNode(sun) sun_np.setHpr(0,-60,0) render.setLight(sun_np) #Ambient light amb = AmbientLight("The Ambient Light") amb.setColor(VBase4(0.39,0.39,0.39, 1)) amb_np = render.attachNewNode(amb) render.setLight(amb_np) #Variables self.gear = 0 self.start = 0 self.Pbrake = 0 self.terrain_var = 1 self.time = 0 self.headlight_var = 0 self.RPM = 0 self.clutch = 0 self.carmaxspeed = 100 #KPH self.carmaxreversespeed = -40 #KPH self.steering = 0 #Functions def V1(): camera.setPos(0.25,-1.2,0.5) camera.setHpr(0,-13,0) def V2(): camera.setPos(0,-15,3) camera.setHpr(0,-10,0) def V3(): camera.setPos(0,0,9) camera.setHpr(0,-90,0) def up(): self.gear = self.gear -1 if self.gear < -1: self.gear = -1 def down(): self.gear = self.gear +1 if self.gear > 1: self.gear = 1 def start_function(): self.start = 1 self.start_sound.play() self.engine_idle_sound.play() self.RPM = 1000 def stop_function(): self.start = 0 self.engine_idle_sound.stop() def parkingbrake(): self.Pbrake = (self.Pbrake + 1) % 2 def rotate(): Car_np.setHpr(0, 0, 0) def horn(): self.horn_sound.play() def set_time(): if self.time == -1: sun.setColor(VBase4(0.4, 0.3, 0.3, 1)) base.setBackgroundColor(0.8,0.7,0.7) if self.time == 0: sun.setColor(VBase4(0.7, 0.7, 0.7, 1)) base.setBackgroundColor(0.6,0.9,0.9) if self.time == 1: sun.setColor(VBase4(0.2, 0.2, 0.2, 1)) base.setBackgroundColor(0.55,0.5,0.5) if self.time == 2: sun.setColor(VBase4(0.02, 0.02, 0.05, 1)) base.setBackgroundColor(0.3,0.3,0.3) if self.time == -2: self.time = -1 if self.time == 3: self.time = 2 def time_forward(): self.time = self.time + 1 def time_backward(): self.time = self.time -1 def set_terrain(): if self.terrain_var == 1: self.ground_model.setTexture(self.ground_tex, 1) self.ground_model.setScale(3) if self.terrain_var == 2: self.ground_model.setTexture(self.ground_tex2, 1) self.ground_model.setScale(3) if self.terrain_var == 3: self.ground_model.setTexture(self.ground_tex3, 1) self.ground_model.setScale(4) if self.terrain_var == 4: self.terrain_var = 1 if self.terrain_var == 0: self.terrain_var = 3 def next_terrain(): self.terrain_var = self.terrain_var + 1 def previous_terrain(): self.terrain_var = self.terrain_var - 1 def show_menu(): self.menu_win.show() self.a1.show() self.a2.show() self.a3.show() self.a4.show() self.t1.show() self.t2.show() self.ok.show() self.exit_button.show() def hide_menu(): self.menu_win.hide() self.a1.hide() self.a2.hide() self.a3.hide() self.a4.hide() self.ok.hide() self.t1.hide() self.t2.hide() self.exit_button.hide() def Menu(): self.menu_win = OnscreenImage(image = "Textures/menu.png", pos = (0.9,0,0), scale = (0.5)) self.menu_win.setTransparency(TransparencyAttrib.MAlpha) #The Arrow Buttons self.a1 = DirectButton(text = "<", scale = 0.2, pos = (0.55,0,0.25), command = previous_terrain) self.a2 = DirectButton(text = ">", scale = 0.2, pos = (1.15,0,0.25), command = next_terrain) self.a3 = DirectButton(text = "<", scale = 0.2, pos = (0.55,0,0.0), command = time_backward) self.a4 = DirectButton(text = ">", scale = 0.2, pos = (1.15,0,0.0), command = time_forward) #The Text self.t1 = OnscreenText(text = "Terrain", pos = (0.85,0.25,0), scale = 0.1, fg = (0.4,0.4,0.5,1)) self.t2 = OnscreenText(text = "Time", pos = (0.85,0,0), scale = 0.1, fg = (0.4,0.4,0.5,1)) #The Buttons self.ok = DirectButton(text = "Okay", scale = 0.11, pos = (0.87,0,-0.25), command = hide_menu) self.exit_button = DirectButton(text = "Quit", scale = 0.11, pos = (0.87,0,-0.42), command = sys.exit) Menu() def take_screenshot(): base.screenshot("Screenshot") def set_headlights(): if self.headlight_var == 1: Headlight1.setColor(VBase4(9.0,8.9,8.9,1)) Headlight2.setColor(VBase4(9.0,8.9,8.9,1)) if self.headlight_var == 0: Headlight1.setColor(VBase4(0,0,0,1)) Headlight2.setColor(VBase4(0,0,0,1)) def headlights(): self.headlight_var = (self.headlight_var + 1) % 2 def update_rpm(): #Simulate RPM if self.start == 1: if self.gear == 0: self.RPM = self.RPM - self.RPM / 400 else: self.RPM = self.RPM + self.carspeed / 9 self.RPM = self.RPM - self.RPM / 200 #Reset RPM to 0 when engine is off if self.start == 0: if self.RPM > 0.0: self.RPM = self.RPM - 40 if self.RPM < 10: self.RPM = 0.0 #Idle RPM power if self.start == 1: if self.RPM < 650: self.RPM = self.RPM + 4 if self.RPM < 600: self.clutch = 1 else: self.clutch = 0 #RPM limit if self.RPM > 6000: self.RPM = 6000 #Controls inputState.watchWithModifiers("F", "arrow_up") inputState.watchWithModifiers("B", "arrow_down") inputState.watchWithModifiers("L", "arrow_left") inputState.watchWithModifiers("R", "arrow_right") do = DirectObject() do.accept("escape", show_menu) do.accept("1", V1) do.accept("2", V2) do.accept("3", V3) do.accept("page_up", up) do.accept("page_down", down) do.accept("x-repeat", start_function) do.accept("x", stop_function) do.accept("p", parkingbrake) do.accept("backspace", rotate) do.accept("enter", horn) do.accept("f12", take_screenshot) do.accept("h", headlights) #The ground self.ground = BulletPlaneShape(Vec3(0, 0, 1,), 1) self.ground_node = BulletRigidBodyNode("The ground") self.ground_node.addShape(self.ground) self.ground_np = render.attachNewNode(self.ground_node) self.ground_np.setPos(0, 0, -2) scene.attachRigidBody(self.ground_node) self.ground_model = loader.loadModel("Models/plane.egg") self.ground_model.reparentTo(render) self.ground_model.setPos(0,0,-1) self.ground_model.setScale(3) self.ground_tex = loader.loadTexture("Textures/ground.png") self.ground_tex2 = loader.loadTexture("Textures/ground2.png") self.ground_tex3 = loader.loadTexture("Textures/ground3.png") self.ground_model.setTexture(self.ground_tex, 1) #The car Car_shape = BulletBoxShape(Vec3(1, 2.0, 1.0)) Car_node = BulletRigidBodyNode("The Car") Car_node.setMass(1200.0) Car_node.addShape(Car_shape) Car_np = render.attachNewNode(Car_node) Car_np.setPos(0,0,3) Car_np.setHpr(0,0,0) Car_np.node().setDeactivationEnabled(False) scene.attachRigidBody(Car_node) Car_model = loader.loadModel("Models/Car.egg") Car_model.reparentTo(Car_np) Car_tex = loader.loadTexture("Textures/Car1.png") Car_model.setTexture(Car_tex, 1) self.Car_sim = BulletVehicle(scene, Car_np.node()) self.Car_sim.setCoordinateSystem(ZUp) scene.attachVehicle(self.Car_sim) #The inside of the car Car_int = loader.loadModel("Models/inside.egg") Car_int.reparentTo(Car_np) Car_int_tex = loader.loadTexture("Textures/inside.png") Car_int.setTexture(Car_int_tex, 1) Car_int.setTransparency(TransparencyAttrib.MAlpha) #The steering wheel Sw = loader.loadModel("Models/Steering wheel.egg") Sw.reparentTo(Car_np) Sw.setPos(0.25,0,-0.025) #The first headlight Headlight1 = Spotlight("Headlight1") lens = PerspectiveLens() lens.setFov(180) Headlight1.setLens(lens) Headlight1np = render.attachNewNode(Headlight1) Headlight1np.reparentTo(Car_np) Headlight1np.setPos(-0.8,2.5,-0.5) Headlight1np.setP(-15) render.setLight(Headlight1np) #The second headlight Headlight2 = Spotlight("Headlight2") Headlight2.setLens(lens) Headlight2np = render.attachNewNode(Headlight2) Headlight2np.reparentTo(Car_np) Headlight2np.setPos(0.8,2.5,-0.5) Headlight2np.setP(-15) render.setLight(Headlight2np) #Sounds self.horn_sound = loader.loadSfx("Sounds/horn.ogg") self.start_sound = loader.loadSfx("Sounds/enginestart.ogg") self.engine_idle_sound = loader.loadSfx("Sounds/engineidle.ogg") self.engine_idle_sound.setLoop(True) self.accelerate_sound = loader.loadSfx("Sounds/enginethrottle.ogg") #Camera base.disableMouse() camera.reparentTo(Car_np) camera.setPos(0,-15,3) camera.setHpr(0,-10,0) #Wheel function def Wheel(pos, np, r, f): w = self.Car_sim.createWheel() w.setNode(np.node()) w.setChassisConnectionPointCs(pos) w.setFrontWheel(f) w.setWheelDirectionCs(Vec3(0, 0, -1)) w.setWheelAxleCs(Vec3(1, 0, 0)) w.setWheelRadius(r) w.setMaxSuspensionTravelCm(40) w.setSuspensionStiffness(120) w.setWheelsDampingRelaxation(2.3) w.setWheelsDampingCompression(4.4) w.setFrictionSlip(50) w.setRollInfluence(0.1) #Wheels w1_np = loader.loadModel("Models/Lwheel") w1_np.reparentTo(render) w1_np.setColorScale(0,6) Wheel(Point3(-1,1,-0.6), w1_np, 0.4, False) w2_np = loader.loadModel("Models/Rwheel") w2_np.reparentTo(render) w2_np.setColorScale(0,6) Wheel(Point3(-1.1,-1.2,-0.6), w2_np, 0.4, True) w3_np = loader.loadModel("Models/Lwheel") w3_np.reparentTo(render) w3_np.setColorScale(0,6) Wheel(Point3(1.1,-1,-0.6), w3_np, 0.4, True) w4_np = loader.loadModel("Models/Rwheel") w4_np.reparentTo(render) w4_np.setColorScale(0,6) Wheel(Point3(1,1,-0.6), w4_np, 0.4, False) #The engine and steering def processInput(dt): #Vehicle properties self.steeringClamp = 35.0 self.steeringIncrement = 70 engineForce = 0.0 brakeForce = 0.0 #Get the vehicle's current speed self.carspeed = self.Car_sim.getCurrentSpeedKmHour() #Engage clutch when in gear 0 if self.gear == 0: self.clutch = 1 #Slow the steering when at higher speeds self.steeringIncrement = self.steeringIncrement - self.carspeed / 1.5 #Reset the steering if not inputState.isSet("L") and not inputState.isSet("R"): if self.steering < 0.00: self.steering = self.steering + 0.6 if self.steering > 0.00: self.steering = self.steering - 0.6 if self.steering < 1.0 and self.steering > -1.0: self.steering = 0 #Slow the car down while it's moving if self.clutch == 0: brakeForce = brakeForce + self.carspeed / 5 else: brakeForce = brakeForce + self.carspeed / 15 #Forward if self.start == 1: if inputState.isSet("F"): self.RPM = self.RPM + 35 self.accelerate_sound.play() if self.clutch == 0: if self.gear == -1: if self.carspeed > self.carmaxreversespeed: engineForce = -self.RPM / 3 if self.gear == 1: if self.carspeed < self.carmaxspeed: engineForce = self.RPM / 1 #Brake if inputState.isSet("B"): engineForce = 0.0 brakeForce = 12.0 if self.gear != 0 and self.clutch == 0: self.RPM = self.RPM - 20 #Left if inputState.isSet("L"): if self.steering < 0.0: #This makes the steering reset at the correct speed when turning from right to left self.steering += dt * self.steeringIncrement + 0.6 self.steering = min(self.steering, self.steeringClamp) else: #Normal steering self.steering += dt * self.steeringIncrement self.steering = min(self.steering, self.steeringClamp) #Right if inputState.isSet("R"): if self.steering > 0.0: #This makes the steering reset at the correct speed when turning from left to right self.steering -= dt * self.steeringIncrement + 0.6 self.steering = max(self.steering, -self.steeringClamp) else: #Normal steering self.steering -= dt * self.steeringIncrement self.steering = max(self.steering, -self.steeringClamp) #Park if self.Pbrake == 1: brakeForce = 10.0 if self.gear != 0 and self. clutch == 0: self.RPM = self.RPM - 20 #Apply forces to wheels self.Car_sim.applyEngineForce(engineForce, 0); self.Car_sim.applyEngineForce(engineForce, 3); self.Car_sim.setBrake(brakeForce, 1); self.Car_sim.setBrake(brakeForce, 2); self.Car_sim.setSteeringValue(self.steering, 0); self.Car_sim.setSteeringValue(self.steering, 3); #Steering wheel Sw.setHpr(0,0,-self.steering*10) #The HUD self.gear_hud = OnscreenImage(image = "Textures/gear_hud.png", pos = (-1,0,-0.85), scale = (0.2)) self.gear_hud.setTransparency(TransparencyAttrib.MAlpha) self.gear2_hud = OnscreenImage(image = "Textures/gear2_hud.png", pos = (-1,0,-0.85), scale = (0.2)) self.gear2_hud.setTransparency(TransparencyAttrib.MAlpha) self.starter = OnscreenImage(image = "Textures/starter.png", pos = (-1.2,0,-0.85), scale = (0.15)) self.starter.setTransparency(TransparencyAttrib.MAlpha) self.park = OnscreenImage(image = "Textures/pbrake.png", pos = (-0.8,0,-0.85), scale = (0.1)) self.park.setTransparency(TransparencyAttrib.MAlpha) self.rev_counter = OnscreenImage(image = "Textures/dial.png", pos = (-1.6, 0.0, -0.70), scale = (0.6,0.6,0.4)) self.rev_counter.setTransparency(TransparencyAttrib.MAlpha) self.rev_needle = OnscreenImage(image = "Textures/needle.png", pos = (-1.6, 0.0, -0.70), scale = (0.5)) self.rev_needle.setTransparency(TransparencyAttrib.MAlpha) self.rev_text = OnscreenText(text = " ", pos = (-1.6, -0.90, 0), scale = 0.05) self.speedometer = OnscreenImage(image = "Textures/dial.png", pos = (-1.68, 0.0, -0.10), scale = (0.7,0.7,0.5)) self.speedometer.setTransparency(TransparencyAttrib.MAlpha) self.speedometer_needle = OnscreenImage(image = "Textures/needle.png", pos = (-1.68, 0.0, -0.10), scale = (0.5)) self.speedometer_needle.setTransparency(TransparencyAttrib.MAlpha) self.speedometer_text = OnscreenText(text = " ", pos = (-1.68, -0.35, 0), scale = 0.05) #Update the HUD def Update_HUD(): #Move gear selector if self.gear == -1: self.gear2_hud.setPos(-1,0,-0.785) if self.gear == 0: self.gear2_hud.setPos(-1,0,-0.85) if self.gear == 1: self.gear2_hud.setPos(-1,0,-0.91) #Rotate starter if self.start == 0: self.starter.setHpr(0,0,0) else: self.starter.setHpr(0,0,45) #Update the parking brake light if self.Pbrake == 1: self.park.setImage("Textures/pbrake2.png") self.park.setTransparency(TransparencyAttrib.MAlpha) else: self.park.setImage("Textures/pbrake.png") self.park.setTransparency(TransparencyAttrib.MAlpha) #Update the rev counter self.rev_needle.setR(self.RPM/22) rev_string = str(self.RPM)[:4] self.rev_text.setText(rev_string+" RPM") #Update the speedometer if self.carspeed > 0.0: self.speedometer_needle.setR(self.carspeed*2.5) if self.carspeed < 0.0: self.speedometer_needle.setR(-self.carspeed*2.5) speed_string = str(self.carspeed)[:3] self.speedometer_text.setText(speed_string+" KPH") #Update the program def update(task): dt = globalClock.getDt() processInput(dt) Update_HUD() set_time() set_terrain() set_headlights() update_rpm() scene.doPhysics(dt, 5, 1.0/180.0) return task.cont taskMgr.add(update, "Update")
class Flashlight: POWER_MIN = 0.06 POWER_DRAIN_RATE = -1/240.0 POWER_GAIN_RATE = 1/480.0 EXPONENET = 40 COLOR = Vec4(1.0, 1.0, 0.9, 1) ATT_CONST = 0 ATT_LIN = 0.3 ATT_QUAD = 0.05 def __init__(self, name, owner, scene, pos, fov=60, near=0.01, far=100, resol=(1920, 1080)): self.owner = owner self.scene = scene self.last = 0.0 self.power = 1.0 self.on = True self.powerrate = Flashlight.POWER_DRAIN_RATE #TODO: Change lens parameters for a unique 'lens' parameter lens = PerspectiveLens() lens.setFov(fov) lens.setNearFar(near, far) lens.setFilmSize(resol[0], resol[1]) self.light = Spotlight(name + '/wide') self.light.setLens(lens) #TODO: Shadows don't work well anymore #self.light.setShadowCaster(True, resol[0], resol[1]) self.light.setColor(Flashlight.COLOR) self.light.setExponent(40) self.nodepath = owner.cam.attachNewNode(self.light) self.nodepath.setPos(pos) self.nodepath.setHpr((5,5,0)) self.scene.setLight(self.nodepath) def __del__(self): self.nodepath.removeNode() def toggle(self): self.on = not self.on if self.on: self.scene.setLight(self.nodepath) self.powerrate = Flashlight.POWER_DRAIN_RATE else: self.scene.clearLight(self.nodepath) self.powerrate = Flashlight.POWER_GAIN_RATE def updatePower(self, task): elapsed = task.time - self.last self.last = task.time self.power = max(Flashlight.POWER_MIN, min(1.0, self.power + elapsed * self.powerrate)) self.light.setAttenuation((Flashlight.ATT_CONST, Flashlight.ATT_LIN, Flashlight.ATT_QUAD / self.power)) return task.cont def getNodePath(self): return self.nodepath def setHpr(self, vec): self.nodepath.setHpr(vec) def isOn(self): return self.on