class PointLight: """Creates a simple point light""" def __init__(self, manager, xml): self.light = PPointLight('plight') 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'))) def start(self): render.setLight(self.lightNode) def stop(self): render.clearLight(self.lightNode)
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 addPointLight(self, pos): k = 12 light = PointLight("light-point") light.setColor(VBase4(k, k, k, 1)) light.setAttenuation(Point3(0.2, 0.1, 0.01)) node = render.attachNewNode(light) node.setPos(*pos) render.setLight(node)
def setupLights( self ): # create a point light plight = PointLight( 'plight' ) # set its color plight.setColor( VBase4( 1.0, 1.0, 1.0, 1 ) ) # attach the light to the render plnp = render.attachNewNode( plight ) # set position plnp.setPos( 0.0, 0.0, 2.0 ) # turn on light render.setLight( plnp )
def setupLights(self): # create a point light plight = PointLight('plight') # set its color plight.setColor(VBase4(1.0, 1.0, 1.0, 1)) # attach the light to the render plnp = render.attachNewNode(plight) # set position plnp.setPos(0.0, 0.0, 2.0) # turn on light render.setLight(plnp)
def inspect_planet(self, planet): plight = PointLight('plight') plight.setColor(Vec4(1,1,1,1)) plnp = self.base.render.attachNewNode(plight) plnp.setPos(-50,-100,50) view = PlanetView(self.base, planet) view.set_light(plnp) self.base.camera.setPos(0, 0, -4) self.base.camera.lookAt(view.node) self.base.accept("enter", lambda: self.inspect(random.choice(planet.galaxy.planets))) self.slowly_rotate(view) self.view = view
def loadLights(self): plight = PointLight('plight') plight.setColor(VBase4(1, 1, 1, 1)) self.plnp = render.attachNewNode(plight) self.plnp.setPos(0, 0, 0) render.setLight(self.plnp) 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)
def __init__(self): self.scrollingSpeed = 15 base.disableMouse() camera.setP(-90) camera.setZ(15) self.accept('wheel_up',self.cameraZoomIn) self.accept('wheel_down',self.cameraZoomOut) taskMgr.add(self.cameraMovements,"cameraMovements") self.cameraLightNode = PointLight("cameraLight") self.cameraLightNode.setColor(Vec4(1,1,1,1)) self.cameraLight = render.attachNewNode(self.cameraLightNode) render.setLight(self.cameraLight)
def inspect_planet(self, planet): plight = PointLight('plight') plight.setColor(Vec4(1, 1, 1, 1)) plnp = self.base.render.attachNewNode(plight) plnp.setPos(-50, -100, 50) view = PlanetView(self.base, planet) view.set_light(plnp) self.base.camera.setPos(0, 0, -4) self.base.camera.lookAt(view.node) self.base.accept( "enter", lambda: self.inspect(random.choice(planet.galaxy.planets))) self.slowly_rotate(view) self.view = view
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 __init__ (self, parent, color, radius, halfat=None, subnode=None, litnode=None, pos=Point3(), selfmanaged=False, name=None): self.parent = parent if halfat is None: halfat = 0.5 if name is None: name = "aplight%d" % AutoPointLight._count self.name = name self._pntlt = PointLight(self.name) pnode = subnode if subnode is not None else self.parent.node self.node = pnode.attachNewNode(self._pntlt) self.node.setPos(pos) self.litnode = litnode if litnode is not None else self.parent.node self.litnode.setLight(self.node) self.update(color, radius, halfat, pos) self.alive = True AutoPointLight._count += 1 if selfmanaged: base.taskMgr.add(self._loop, "autopointlight-loop") else: self.parent.world.register_plight(self)
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 _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 showStartScreen(self): ''' the first screen with "press any Key" the device with the first key press will be the first player ''' self._notify.info("Initializing StartScreen") self.wii = [] # StartScreen Node self.startNode = NodePath("StartNode") self.startNode.reparentTo(render) self.startNode.setPos(-5, 15, 3) # Headline model headline = loader.loadModel("data/models/logo.egg") headline.setX(4.7) headline.setY(-4) headline.setZ(-2) headline.setP(90) headline.reparentTo(self.startNode) # Press any key text presskey = TextNode("PressAnyKey") presskey.setFont(self.font) presskey.setText(_("Press any key!!")) textNodePath = NodePath("PressAnyNode") textNodePath.attachNewNode(presskey) textNodePath.setPos(0, 10, -9.5) textNodePath.reparentTo(self.startNode) # Show the start screen self.startNode.show() # LICHT plight = PointLight('plight') plight.setColor(VBase4(10, 10, 10, 1)) plnp = self.startNode.attachNewNode(plight) plnp.setPos(20, -800, 30) self.startNode.setLight(plnp) # Camera self.camera = base.makeCamera(base.win) self._notify.info("StarScreen initialized")
class Camera(DirectObject.DirectObject): def __init__(self): self.scrollingSpeed = 15 base.disableMouse() camera.setP(-90) camera.setZ(15) self.accept('wheel_up',self.cameraZoomIn) self.accept('wheel_down',self.cameraZoomOut) taskMgr.add(self.cameraMovements,"cameraMovements") self.cameraLightNode = PointLight("cameraLight") self.cameraLightNode.setColor(Vec4(1,1,1,1)) self.cameraLight = render.attachNewNode(self.cameraLightNode) render.setLight(self.cameraLight) def cameraZoomIn(self): if camera.getZ() > 10: camera.setY(camera, 1) def cameraZoomOut(self): if camera.getZ() < 20: camera.setY(camera, -1) def cameraMovements(self, task): if base.mouseWatcherNode.hasMouse() and not objSelectionTool.booSelecting: x = base.mouseWatcherNode.getMouseX() y = base.mouseWatcherNode.getMouseY() self.dt = globalClock.getDt() * self.scrollingSpeed if x < -0.99 and camera.getX(): camera.setX(camera.getX()-self.dt) if x > 0.99 and camera.getX(): camera.setX(camera.getX()+self.dt) if y > 0.99 and camera.getY(): camera.setY(camera.getY()+self.dt) if y < -0.99 and camera.getY(): camera.setY(camera.getY()-self.dt) self.cameraLight.setX(camera.getX()) self.cameraLight.setY(camera.getY()) self.cameraLight.setZ(camera.getZ()) return task.cont
def __init__(self, game, color): self.game = game self.visualNode = NodePath('Visual node') self.visualNode.reparentTo(render) model = loader.loadModel('testipalikka.egg') model.reparentTo(self.visualNode) plight = PointLight('plight') plight.setPoint( Point3(0.6, 0, 5) ) plight.setColor( color ) plight.setAttenuation( Vec3(0.5, 0.01, 0.01) ) plightNodePath = model.attachNewNode(plight) model.setLight(plightNodePath) self.body = OdeBody(game.physicsWorld) self.mass = OdeMass() self.mass.setBox(10,1,1,1) self.body.setMass(self.mass) self.body.setGravityMode(False) #self.juttu = OdeUtil() self.collGeom = OdeSphereGeom( self.game.physicsSpace, 2) self.collGeom.setBody(self.body) self.collGeom.setCategoryBits( BitMask32(0xffffffff) ) self.collGeom.setCollideBits( BitMask32(0xffffffff) )
def __init__(self, game): self.game = game #poista se fysiikka-avaruus ja vaan tee se alue... justiinsa self.collGeom = OdeBoxGeom( 24,8,2 ) #self.collGeom.setBody(self.body) self.collGeom.setCategoryBits( BitMask32(1) ) self.collGeom.setCollideBits( BitMask32(1) ) # self.collGeomOuter = OdeBoxGeom( self.game.physicsSpace, 28,6,2) # #self.collGeom.setBody(self.body) # self.collGeomOuter.setCategoryBits( BitMask32(1) ) # self.collGeomOuter.setCollideBits( BitMask32(1) ) self.visualNode = NodePath('Visual node') self.visualNode.reparentTo(render) model = loader.loadModel('Base.egg') model.reparentTo(self.visualNode) plight = PointLight('baselight') plight.setPoint( Point3(0, 0, 12) ) plight.setColor( Vec4(1,1,1,1) ) plight.setAttenuation( Vec3(0.1, 0.1, 0.005) ) self.visualNode.setLight(model.attachNewNode(plight))
def setColor(self, color): plight = PointLight('plight') plight.setPoint( Point3(0.6, 0, 5) ) plight.setColor( color ) plight.setAttenuation( Vec3(0.5, 0.01, 0.01) ) plightNodePath = self.model.attachNewNode(plight) self.model.setLight(plightNodePath)
def __init__(self, game, color): #self.POWER = 100 self.game = game self.thrust = False self.thrustLeft = False self.thrustRight = False self.thrustBack = False self.rotation = 0 self.body = OdeBody(game.physicsWorld) self.mass = OdeMass() self.mass.setBox(10,1,1,1) self.body.setMass(self.mass) #odespheregeom(... , size of hitbox sphere) self.collGeom = OdeSphereGeom( self.game.physicsSpace, 5) self.collGeom.setBody(self.body) self.collGeom.setCategoryBits( BitMask32(0xffffffff) ) self.collGeom.setCollideBits( BitMask32(0xffffffff) ) self.visualNode = NodePath('Visual node') self.visualNode.reparentTo(render) model = loader.loadModel('lautanen2.egg') model.reparentTo(self.visualNode) plight = PointLight('plight') plight.setPoint( Point3(0.6, 0, 5) ) plight.setColor( color ) plight.setAttenuation( Vec3(0.5, 0.01, 0.01) ) plightNodePath = model.attachNewNode(plight) model.setLight(plightNodePath)
def __init__(self, game, color, value = 1, drain = 20): self.game = game self.VALUE = value self.DRAIN = drain #self.idnumber = id self.visualNode = NodePath('Visual node') self.visualNode.reparentTo(render) model = loader.loadModel('Ball2.egg') model.setScale(2.5) model.reparentTo(self.visualNode) plight = PointLight('plight') plight.setPoint( Point3(0, 0, 3) ) plight.setColor( color ) plight.setAttenuation( Vec3(0.05, 0.01, 0.01) ) self.plightNodePath = model.attachNewNode(plight) model.setLight(self.plightNodePath) self.body = OdeBody(game.physicsWorld) self.mass = OdeMass() self.mass.setBox(10,1,1,1) self.body.setMass(self.mass) self.body.setGravityMode(True) #self.body.setGravityMode(False) #self.juttu = OdeUtil() self.collGeom = OdeSphereGeom( self.game.physicsSpace, 3.5) self.collGeom.setBody(self.body) self.collGeom.setCategoryBits( BitMask32(0xffffffff) ) self.collGeom.setCollideBits( BitMask32(0xffffffff) )
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, 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 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 initNode(self): ''' Create a clear menu ''' self.camera = None self.selected = 0 self.options = [] self.optionsModells = [] self.menuNode = NodePath("menuNode") self.menuNode.reparentTo(render) self.menuNode.setPos(-4.5, 15, 3) self.menuNode.setH(40) self.colorA = Vec4(1, 1, 0, 0) self.colorB = Vec4(0, 1, 1, 0) # LICHT plight = PointLight('plight') plight.setColor(VBase4(10, 10, 10, 1)) plnp = self.menuNode.attachNewNode(plight) plnp.setPos(-10, -800, 20) self.menuNode.setLight(plnp)
def createScene(self): self._log.debug(u"Creating scene...") base.setBackgroundColor(0.3, 0.3, 0.3) self.gl_dlight = PointLight("dlight") self.gl_dlight.setColor(Vec4(0.5, 0.5, 0.5, 1)) self.np_dlight = render.attachNewNode(self.gl_dlight) # self.np_dlight.setHpr(90, 0, 0) # self.np_dlight.lookAt(1, 1, -10) render.setLight(self.np_dlight) render.setTransparency(TransparencyAttrib.MAlpha) self._camera_control = CameraHandler() self.clearScene() self.rotate_light()
class PointLight: """Creates a simple point light""" def __init__(self,manager,xml): self.light = PPointLight('plight') 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'))) def start(self): render.setLight(self.lightNode) def stop(self): render.clearLight(self.lightNode)
def __init__ (self, parent, color, radius, halfat=None, subnode=None, pos=Point3(), name=None): self.parent = parent if halfat is None: halfat = 0.5 if name is None: name = "poverbright%d" % PointOverbright._count self.name = name self._pntlt = PointLight(self.name) pnode = subnode if subnode is not None else self.parent.node self.node = pnode.attachNewNode(self._pntlt) self.node.setPos(pos) self.update(color, radius, halfat, pos) self.alive = True PointOverbright._count += 1 base.taskMgr.add(self._loop, "poverbright-loop")
def __init__(self, parent, star, **kwargs): super(StarView, self).__init__(parent, star, **kwargs) if not StarView.ready: StarView.setup(self.base.loader) self.seed = random.random() self.node = NodePath('star') plight = PointLight("starlight") self.light = self.node.attachNewNode(plight) self.light.setColor(self.obj.color) self.model = self.light.attachNewNode(SphereNode(subdivides=4)) self.model.setShader(Shader.load("shader/star.cg")) self.cloudtime = 0.0 #self.seed = hash("fish") self.param_set = ParamSet(self.seed) min_scale = Vec4(0.5, 0.5, 0.5, 0.5) max_scale = Vec4(1, 1, 1, 1) max_radius = StellarClass.highest_radius min_radius = StellarClass.lowest_radius radius_factor = log(self.obj.radius * (1 / min_radius), 100) / log( max_radius * (1 / min_radius), 100) self.param_set.vectors['scale'] = min_scale + ( max_scale - min_scale) * radius_factor self.compute_seed_param() for stage, tex in StarView.texture_set: self.model.setTexture(stage, tex) self.speed = 0.00000001 self.setup_shader_inputs() self.node.setScale(1 / self.node.getBounds().getRadius()) self.node.reparentTo(self.parent.node)
def __init__(self, game, color): self.POWER = 200 self.game = game self.SHIP_TYPE = "RAKETTI" self.Ball_offset = 10.0 # self.hasBall = False self.thrust = False self.thrustLeft = False self.thrustRight = False self.thrustBack = False self.rotation = 0 self.body = OdeBody(game.physicsWorld) self.mass = OdeMass() self.mass.setBox(10,1,1,1) self.body.setMass(self.mass) #self.body.setGravityMode(False) #odespheregeom(... , size of hitbox sphere) self.collGeom = OdeSphereGeom( self.game.physicsSpace, 3) self.collGeom.setBody(self.body) self.collGeom.setCategoryBits( BitMask32(0xffffffff) ) self.collGeom.setCollideBits( BitMask32(0xffffffff) ) self.visualNode = NodePath('Visual node') self.visualNode.reparentTo(render) model = loader.loadModel('spaceship.egg') model.setH(180) model.setY(15) model.reparentTo(self.visualNode) self.visualNode.setScale(0.4) plight = PointLight('plight') plight.setPoint( Point3(0.6, 0, 5) ) plight.setColor( color ) plight.setAttenuation( Vec3(0.5, 0.01, 0.01) ) plightNodePath = model.attachNewNode(plight) model.setLight(plightNodePath)
class Main(DirectObject): 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 toggle_lights(self): self.light = not(self.light) if self.light: render.setLight(self.dlnp) else: render.setLightOff(self.dlnp) def add_model(self, rendering_node, model, position, scale, heading=0): new_model = loader.loadModel("eggs/"+model) new_model.setPos(*position) new_model.setScale(scale) new_model.setH(heading) new_model.reparentTo(rendering_node) def add_line(self, rendering_node, color, thickness, start, end): linesegs = LineSegs() linesegs.setColor(*color) linesegs.setThickness(thickness) linesegs.drawTo((start[0], start[1], start[2])) linesegs.drawTo((end[0], end[1], end[2])) new_node = linesegs.create() rendering_node.attachNewNode(new_node) def fill_env(self): for _ in range (100) : self.add_model(self.env_node, "daisy", (random.random()*121,random.random()*121,0), 2) self.add_model(self.env_node, "Fern", (random.random()*121,random.random()*121,0), 0.01, random.random()*360) self.add_model(self.env_node, "rock", (random.random()*121,random.random()*121,0), random.random()*0.1+0.1, random.random()*360) self.env_node.flattenStrong() def game_loop(self, task): for lock in worlds_locks : worlds_locks[lock].acquire() for world_name in worlds : patch_center = worlds[world_name].patches_size / 2.0 for patch in worlds[world_name].updated_patches : if patch.check_visibility() : patch.draw(self.patches_node) if len(worlds[world_name].updated_patches) > 0 : worlds[world_name].updated_patches = list() for lines in worlds[world_name].updated_lines : start = (lines[1][0]+patch_center, lines[1][1]+patch_center, lines[1][2]+patch_center) end = (lines[2][0]+patch_center, lines[2][1]+patch_center, lines[2][2]+patch_center) self.add_line(self.lines_node, (1,0,0,1), lines[0].pen_size, start, end) if len(worlds[world_name].updated_lines) > 0 : self.lines_node.flattenStrong() worlds[world_name].updated_lines = list() for turtle_type in worlds[world_name].turtles_dictionary : for turtle in worlds[world_name].turtles_dictionary[turtle_type] : if not turtle.hidden : turtle.model.setPos(turtle._x+patch_center, turtle._y+patch_center, turtle._z+patch_center) turtle.draw(self.agents_node) for lock in worlds_locks : worlds_locks[lock].release() return Task.cont def close_window(self, task): if base.win.isClosed() : for world_name in worlds : worlds[world_name].stop() def create_floor(self, size_x_axis, size_y_axis, texture): card_maker = CardMaker('') card_maker.setFrame(0,size_x_axis,0,size_y_axis) ''' for y in range(size_y_axis): for x in range(size_x_axis): new_node = self.floorNode.attachNewNode(card_maker.generate()) new_node.setP(-90) new_node.setPos(x, y, 0) ''' new_node = self.floor_node.attachNewNode(card_maker.generate()) new_node.setP(-90) new_node.setPos(0, 0, 0) new_node.setTexture(textures[texture]) self.floor_node.flattenStrong() def create_frame(self, size_x_axis, size_y_axis, size_z_axis): edges = [((0,0,0),(size_x_axis, 0, 0)), ((0,0,0),(0, size_y_axis, 0)), ((0,0,0),(0, 0, size_z_axis)), ((0,0,size_z_axis),(size_x_axis, 0, size_z_axis)), ((size_x_axis,0,0),(size_x_axis, 0, size_z_axis)), ((size_x_axis,0,0),(size_x_axis, size_y_axis, 0)), ((size_x_axis,0,size_z_axis),(size_x_axis, size_y_axis, size_z_axis)), ((size_x_axis,size_y_axis,0),(size_x_axis, size_y_axis, size_z_axis)), ((0,0,size_z_axis),(0, size_y_axis, size_z_axis)), ((0,size_y_axis,0),(0, size_y_axis, size_z_axis)), ((0,size_y_axis,0),(size_x_axis, size_y_axis, 0)), ((0,size_y_axis,size_z_axis),(size_x_axis, size_y_axis, size_z_axis)), ] for edge in edges : self.add_line(self.frame_node, (0,0,0,0), 3, edge[0], edge[1])
class PointOverbright (object): _count = 0 def __init__ (self, parent, color, radius, halfat=None, subnode=None, pos=Point3(), name=None): self.parent = parent if halfat is None: halfat = 0.5 if name is None: name = "poverbright%d" % PointOverbright._count self.name = name self._pntlt = PointLight(self.name) pnode = subnode if subnode is not None else self.parent.node self.node = pnode.attachNewNode(self._pntlt) self.node.setPos(pos) self.update(color, radius, halfat, pos) self.alive = True PointOverbright._count += 1 base.taskMgr.add(self._loop, "poverbright-loop") def destroy (self): if not self.alive: return self.alive = False self.node.removeNode() def update (self, color=None, radius=None, halfat=None, pos=None): if color is not None: self._pntlt.setColor(color) self.color = color self._colamp = Vec3(color[0], color[1], color[2]).length() if radius is not None or halfat is not None: if radius is None: radius = self.radius if halfat is None: halfat = self.halfat assert 0.0 < halfat < 1.0 radpow = log(0.5) / log(halfat) self._pntlt.setAttenuation(Vec3(radius, radpow, 0.0)) self.radius = radius self.halfat = halfat self._radpow = radpow if pos is not None: self.node.setPos(pos) def strength (self, dist): if self._colamp > 0.0: att = 1.0 if dist > 0.0: att -= pow(min(dist / self.radius, 1.0), self._radpow) return self._colamp * att else: return 0.0 def _loop (self, task): if not self.alive: return task.done if not self.parent.alive: self.destroy() return task.done return task.cont
def __init__(self): """Initialise the scene.""" # Show the framerate base.setFrameRateMeter(True) # Initialise terrain: # Make 4 terrain nodepath objects with different hilliness values # and arrange them side-by-side in a 2x2 grid, giving a big terrain # with variable hilly and flat areas. color = (0.6, 0.8, 0.5, 1) # Bright green-ish scale = 12 height = 18 # FIXME: For now we are raising the terrain so it # floats above the sea to prevent lakes from # appearing (but you still get them sometimes) t1 = Terrain(color=color, scale=scale, trees=0.7, pos=P.Point3(0, 0, height)) t1.prime.reparentTo(render) t2 = Terrain(color=color, scale=scale, h=24, pos=P.Point3(32 * scale, 0, height), trees=0.5) t2.prime.reparentTo(render) t3 = Terrain(color=color, scale=scale, h=16, pos=P.Point3(32 * scale, 32 * scale, height), trees=0.3) t3.prime.reparentTo(render) t4 = Terrain(color=color, scale=scale, h=2, pos=P.Point3(0, 32 * scale, height), trees=0.9) t4.prime.reparentTo(render) #tnp1.setPos(tnp1,-32,-32,terrainHeight) # Initialise sea sea = Sea() # Initialise skybox. self.box = loader.loadModel("models/skybox/space_sky_box.x") self.box.setScale(6) self.box.reparentTo(render) # Initialise characters self.characters = [] self.player = C.Character(model='models/eve', run='models/eve-run', walk='models/eve-walk') self.player.prime.setZ(100) self.player._pos = SteerVec(32 * 12 + random.random() * 100, 32 * 12 + random.random() * 100) self.player.maxforce = 0.4 self.player.maxspeed = 0.55 EdgeScreenTracker(self.player.prime, dist=200) # Setup camera for i in range(0, 11): self.characters.append(C.Character()) self.characters[i].prime.setZ(100) self.characters[i].wander() self.characters[i].maxforce = 0.3 self.characters[i].maxspeed = 0.2 self.characters[i]._pos = SteerVec(32 * 12 + random.random() * 100, 32 * 12 + random.random() * 100) C.setContainer( ContainerSquare(pos=SteerVec(32 * 12, 32 * 12), radius=31 * 12)) #C.toggleAnnotation() # Initialise keyboard controls. self.accept("c", C.toggleAnnotation) self.accept("escape", sys.exit) # Setup CollisionRay and CollisionHandlerQueue for mouse picking. self.pickerQ = P.CollisionHandlerQueue() self.picker = camera.attachNewNode( P.CollisionNode('Picker CollisionNode')) self.picker.node().addSolid(P.CollisionRay()) # We want the picker ray to collide with the floor and nothing else. self.picker.node().setFromCollideMask(C.floorMASK) self.picker.setCollideMask(P.BitMask32.allOff()) base.cTrav.addCollider(self.picker, self.pickerQ) try: handler.addCollider(self.picker, camera) except: pass self.accept('mouse1', self.onClick) # Set the far clipping plane to be far enough away that we can see the # skybox. base.camLens.setFar(10000) # Initialise lighting self.alight = AmbientLight('alight') self.alight.setColor(VBase4(0.35, 0.35, 0.35, 1)) self.alnp = render.attachNewNode(self.alight) render.setLight(self.alnp) self.dlight = DirectionalLight('dlight') self.dlight.setColor(VBase4(0.4, 0.4, 0.4, 1)) self.dlnp = render.attachNewNode(self.dlight) self.dlnp.setHpr(45, -45, 0) render.setLight(self.dlnp) self.plight = PointLight('plight') self.plight.setColor(VBase4(0.8, 0.8, 0.5, 1)) self.plnp = render.attachNewNode(self.plight) self.plnp.setPos(160, 160, 50) self.slight = Spotlight('slight') self.slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() self.slight.setLens(lens) self.slnp = render.attachNewNode(self.slight) self.slnp.setPos(-20, -20, 20) self.slnp.lookAt(50, 50, 0) # Initialise some scene-wide exponential fog colour = (0.5, 0.8, 0.8) self.expfog = Fog("Scene-wide exponential Fog object") self.expfog.setColor(*colour) self.expfog.setExpDensity(0.0005) render.setFog(self.expfog) base.setBackgroundColor(*colour) # Add a task for this Plant to the global task manager. self.stepcount = 0 taskMgr.add(self.step, "Plant step task")
def start(self): self.textures.load_all() self.char = Actor("res/models/ralph", {"run":"res/models/ralph-run", "walk":"res/models/ralph-walk"}) self.char.pose('walk', 5) self.char.setScale(.2) self.char.setH(180) self.gui.buttons.add_button(name = 'Exit', text = ("Exit", "Exit", "Exit", "disabled"), pos = (1.23, 0, -0.95), scale = 0.07, command=self.stop) self.gui.screen_texts.add_text(name = 'status', text = 'Hello! Suber was started!', pos = (-1.3, -0.95), scale = 0.07) #self.gui.entries.add_entry(name = 'console',text = "" , #pos = (-1.29, 0, -0.85), #scale=0.07,command=self.cmd_handler.cmd_handle, #initialText="", width = 37, numLines = 1,focus=0) self.gui.screen_texts.add_text(name = 'help', text = 'F5 - create world\nm - toggle map\nF1 - toggle'+\ ' help\nEsc - exit\nF10 - render info\n'+\ 'F2/F3 - 1st/3d person camera\n'+\ 'F4 - toggle fly/terrain\n'+\ 'F9 - Cam disable\n'+\ 'F8 - Toggle Collisions\n'+\ 'F11/F12 - toggle polygons / disable textures', pos = (-1, 0.8), scale = 0.07) self.gui.hotkeys.accept('f1', self.toggle_help) self.gui.screen_images.add_image('sight', self.textures['sight'], scale = 0.05, pos = (0, 0, 0)) self.gui.screen_images['sight'].setTransparency(TransparencyAttrib.MAlpha) plight = PointLight('plight') sun = self.gui.render.attachNewNode(plight) sun.setPos(-32768, 32768, 20000) self.gui.render.setLight(sun) alight = AmbientLight('alight') alight.setColor(VBase4(0.5, 0.5, 0.5, 1)) alnp = self.gui.render.attachNewNode(alight) self.gui.render.setLight(alnp) color = (0.28125, 0.53125, 0.80859375) fog = Fog("A linear-mode Fog node") fog.setColor(*color) fog.setLinearFallback(0,500,550) self.gui.camera.attachNewNode(fog) color = (0.28125, 0.53125, 0.80859375) self.gui.render.setFog(fog) self.gui.setBackgroundColor(*color) self.cam_manager = CamManager(self) self.move_avatar = MoveAvatar(self) self.vox_config = VoxConfig() self.coord_block = CoordBlock(self, self.vox_config) self.vox_params = VoxParams() self.vox_params.gui = self.gui self.vox_params.avatar = self.cam_manager.node self.vox_params.status = self.write self.vox_params.root_node = self.gui.render self.vox_params.chunks_tex = self.textures['world_blocks'] self.vox_params.get_coord_block = self.coord_block self.vox_params.tree_tex = self.textures['tree'] self.vox_params.water_tex = self.textures['water'] self.vox_params.leafModel = self.gui.loader.loadModel("res/models/shrubbery") self.vox_params.leafTex = self.textures['leaf'] self.vox_params.fog = fog self.world = World(self.vox_config, self.vox_params) self.collision_avatar = CollisionAvatar(self) #self.vox_params.sun = sun self.gui.taskMgr.setupTaskChain('Ticker', tickClock = True) self.gui.taskMgr.doMethodLater(0.05, self.ticker, 'taskTicker', taskChain = 'Ticker') self.gui.start()
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((1, 1, 1, 1)) # Set up lights. ablight = AmbientLight("ambientlight") ablight.setColor(Vec4(0.5, 0.5, 0.5, 1)) ablightnode = self.render.attachNewNode(ablight) self.render.setLight(ablightnode) ptlight0 = PointLight("pointlight0") ptlight0.setColor(VBase4(1, 1, 1, 1)) ptlightnode0 = self.render.attachNewNode(ptlight0) ptlightnode0.setPos(500, 0, 500) base.render.setLight(ptlightnode0) ptlight1 = PointLight("pointlight1") ptlight1.setColor(VBase4(1, 1, 1, 1)) ptlightnode1 = base.render.attachNewNode(ptlight1) ptlightnode1.setPos(0, 500, 500) base.render.setLight(ptlightnode1) # 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
def __init__(self,manager,xml): self.light = PPointLight('plight') self.lightNode = render.attachNewNode(self.light) self.reload(manager,xml)
def __init__(self): """Initialise the scene.""" # Show the framerate base.setFrameRateMeter(True) # Initialise terrain: # Make 4 terrain nodepath objects with different hilliness values # and arrange them side-by-side in a 2x2 grid, giving a big terrain # with variable hilly and flat areas. color = (0.6,0.8,0.5,1) # Bright green-ish scale = 12 height = 18 # FIXME: For now we are raising the terrain so it # floats above the sea to prevent lakes from # appearing (but you still get them sometimes) t1 = Terrain(color=color,scale=scale,trees=0.7,pos=P.Point3(0,0,height)) t1.prime.reparentTo(render) t2 = Terrain(color=color,scale=scale,h=24,pos=P.Point3(32*scale,0,height),trees=0.5) t2.prime.reparentTo(render) t3 = Terrain(color=color,scale=scale,h=16,pos=P.Point3(32*scale,32*scale,height),trees=0.3) t3.prime.reparentTo(render) t4 = Terrain(color=color,scale=scale,h=2,pos=P.Point3(0,32*scale,height),trees=0.9) t4.prime.reparentTo(render) #tnp1.setPos(tnp1,-32,-32,terrainHeight) # Initialise sea sea = Sea() # Initialise skybox. self.box = loader.loadModel("models/skybox/space_sky_box.x") self.box.setScale(6) self.box.reparentTo(render) # Initialise characters self.characters = [] self.player = C.Character(model='models/eve',run='models/eve-run', walk='models/eve-walk') self.player.prime.setZ(100) self.player._pos = SteerVec(32*12+random.random()*100,32*12+random.random()*100) self.player.maxforce = 0.4 self.player.maxspeed = 0.55 EdgeScreenTracker(self.player.prime,dist=200) # Setup camera for i in range(0,11): self.characters.append(C.Character()) self.characters[i].prime.setZ(100) self.characters[i].wander() self.characters[i].maxforce = 0.3 self.characters[i].maxspeed = 0.2 self.characters[i]._pos = SteerVec(32*12+random.random()*100,32*12+random.random()*100) C.setContainer(ContainerSquare(pos=SteerVec(32*12,32*12),radius=31*12)) #C.toggleAnnotation() # Initialise keyboard controls. self.accept("c",C.toggleAnnotation) self.accept("escape", sys.exit) # Setup CollisionRay and CollisionHandlerQueue for mouse picking. self.pickerQ = P.CollisionHandlerQueue() self.picker = camera.attachNewNode(P.CollisionNode('Picker CollisionNode')) self.picker.node().addSolid(P.CollisionRay()) # We want the picker ray to collide with the floor and nothing else. self.picker.node().setFromCollideMask(C.floorMASK) self.picker.setCollideMask(P.BitMask32.allOff()) base.cTrav.addCollider(self.picker,self.pickerQ) try: handler.addCollider(self.picker,camera) except: pass self.accept('mouse1',self.onClick) # Set the far clipping plane to be far enough away that we can see the # skybox. base.camLens.setFar(10000) # Initialise lighting self.alight = AmbientLight('alight') self.alight.setColor(VBase4(0.35, 0.35, 0.35, 1)) self.alnp = render.attachNewNode(self.alight) render.setLight(self.alnp) self.dlight = DirectionalLight('dlight') self.dlight.setColor(VBase4(0.4, 0.4, 0.4, 1)) self.dlnp = render.attachNewNode(self.dlight) self.dlnp.setHpr(45, -45, 0) render.setLight(self.dlnp) self.plight = PointLight('plight') self.plight.setColor(VBase4(0.8, 0.8, 0.5, 1)) self.plnp = render.attachNewNode(self.plight) self.plnp.setPos(160, 160, 50) self.slight = Spotlight('slight') self.slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() self.slight.setLens(lens) self.slnp = render.attachNewNode(self.slight) self.slnp.setPos(-20, -20, 20) self.slnp.lookAt(50,50,0) # Initialise some scene-wide exponential fog colour = (0.5,0.8,0.8) self.expfog = Fog("Scene-wide exponential Fog object") self.expfog.setColor(*colour) self.expfog.setExpDensity(0.0005) render.setFog(self.expfog) base.setBackgroundColor(*colour) # Add a task for this Plant to the global task manager. self.stepcount = 0 taskMgr.add(self.step,"Plant step task")
def __init__(self, manager, xml): self.light = PPointLight('plight') self.lightNode = render.attachNewNode(self.light) self.reload(manager, xml)
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((1,1,1,1)) # Set up lights. ablight = AmbientLight("ambientlight") ablight.setColor(Vec4(0.5, 0.5, 0.5, 1)) ablightnode = self.render.attachNewNode(ablight) self.render.setLight(ablightnode) ptlight0 = PointLight("pointlight0") ptlight0.setColor(VBase4(1, 1, 1, 1)) ptlightnode0 = self.render.attachNewNode(ptlight0) ptlightnode0.setPos(500, 0, 500) base.render.setLight(ptlightnode0) ptlight1 = PointLight("pointlight1") ptlight1.setColor(VBase4(1, 1, 1, 1)) ptlightnode1 = base.render.attachNewNode(ptlight1) ptlightnode1.setPos(0, 500, 500) base.render.setLight(ptlightnode1) # 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
base.camLens.setFov(45.0) camera.setPos(0.0, -20.0, 10.0) camera.lookAt(0.0, 0.0, 0.0) root = render.attachNewNode("Root") """ We set up a default point light here. You may modify the color of the light, but in the next examples we assume, that the light has no attenuation and is white. There is a dummy model attached to this node, to see where the light should be. Because this light is parented to render, and we only enable light on the cubes, this model does not influence the lighting nor is it lit by the light itself. """ pointlight = PointLight("Light") light = render.attachNewNode(pointlight) modelLight = loader.loadModel("misc/Pointlight.egg.pz") modelLight.reparentTo(light) """ DIRTY Replace cube.egg with cube-smooth.egg and try to understand why both outputs differ. """ modelCube = loader.loadModel("cube.egg") cubes = [] for x in [-3.0, 0.0, 3.0]: cube = modelCube.copyTo(root) cube.setPos(x, 0.0, 0.0)
def _initializeFlare(self): # Parameters self.distance = 130000.0 self.threshold = 0.3 self.radius = 0.8 self.strength = 1.0 self.suncolor = Vec4(1, 1, 1, 1) self.suncardcolor = Vec4(1, 1, 0, 0) # Initialize some values self.obscured = 0.0 # flaredata will hold the rendered image self.flaredata = PNMImage() # flaretexture will store the rendered buffer self.flaretexture = Texture() # Create a 10x10 texture buffer for the flare self.flarebuffer = base.win.makeTextureBuffer("Flare Buffer", 10, 10) # Attach the texture to the buffer self.flarebuffer.addRenderTexture(self.flaretexture, GraphicsOutput.RTMCopyRam) self.flarebuffer.setSort(-100) # Camera that renders the flare buffer self.flarecamera = base.makeCamera(self.flarebuffer) #self.flarecamera.reparentTo(base.cam) #self.flarecamera.setPos(-50,0,0) self.ortlens = OrthographicLens() self.ortlens.setFilmSize( 10, 10) # or whatever is appropriate for your scene self.ortlens.setNearFar(1, self.distance) self.flarecamera.node().setLens(self.ortlens) self.flarecamera.node().setCameraMask(GXMgr.MASK_GXM_HIDDEN) # Create a light for the flare self.sunlight = self.baseNode.attachNewNode( PointLight("Sun:Point Light")) self.sunlight.node().setColor(self.suncolor) self.sunlight.node().setAttenuation(Vec3(0.1, 0.04, 0.0)) # Load texture cards # Create a nodepath that'll hold the texture cards for the new lens-flare self.texcardNP = aspect2d.attachNewNode('Sun:flareNode1') self.texcardNP.attachNewNode('Sun:fakeHdr') self.texcardNP.attachNewNode('Sun:starburstNode') # Load a circle and assign it a color. This will be used to calculate # Flare occlusion self.starcard = loader.loadModel('../data/models/unitcircle.egg') self.starcard.reparentTo(self.baseNode) self.starcard.setColor(self.suncardcolor) self.starcard.setScale(1) #self.starcard.setTransparency(TransparencyAttrib.MAlpha) # This is necessary since a billboard always rotates the y-axis to the # target but we need the z-axis self.starcard.setP(-90) self.starcard.setBillboardPointEye(self.flarecamera, 0.0) # Don't let the main camera see the star card self.starcard.show(GXMgr.MASK_GXM_HIDDEN) self.starcard.hide(GXMgr.MASK_GXM_VISIBLE) #the models are really just texture cards create with egg-texture-cards # from the actual pictures self.hdr = loader.loadModel('../data/models/fx_flare.egg') self.hdr.reparentTo(self.texcardNP.find('**/Sun:fakeHdr')) # Flare specs self.starburst_0 = loader.loadModel( '../data/models/fx_starburst_01.egg') self.starburst_1 = loader.loadModel( '../data/models/fx_starburst_02.egg') self.starburst_2 = loader.loadModel( '../data/models/fx_starburst_03.egg') self.starburst_0.setPos(0.5, 0, 0.5) self.starburst_1.setPos(0.5, 0, 0.5) self.starburst_2.setPos(0.5, 0, 0.5) self.starburst_0.setScale(.2) self.starburst_1.setScale(.2) self.starburst_2.setScale(.2) self.starburst_0.reparentTo( self.texcardNP.find('**/Sun:starburstNode')) self.starburst_1.reparentTo( self.texcardNP.find('**/Sun:starburstNode')) self.starburst_2.reparentTo( self.texcardNP.find('**/Sun:starburstNode')) self.texcardNP.setTransparency(TransparencyAttrib.MAlpha) # Put the texture cards in the background bin self.texcardNP.setBin('background', 0) # The texture cards do not affect the depth buffer self.texcardNP.setDepthWrite(False) #attach a node to the screen middle, used for some math self.mid2d = aspect2d.attachNewNode('mid2d') #start the task that implements the lens-flare taskMgr.add(self._flareTask, 'Sun:flareTask')
arrow.set_length(start_length) else: t = task.time % time_to_full_length t = t / time_to_full_length length_diff = max_length - start_length new_length = start_length + t * length_diff arrow.set_length(new_length) return Task.cont if __name__ == "__main__": from direct.directbase import DirectStart global base, render print "Arrow::main" arrow = Arrow() arrow.set_angle_x_z_plane(45) #arrow.set_length(0.5) base.disableMouse() base.camera.setPos(0, -5, .5) #taskMgr.add(rotate, 'rotate', extraArgs=[arrow.root_node_path,0.05,0], appendTask=True) #taskMgr.add(scale, 'scale', extraArgs=[arrow,1.0,0.5,1.0], appendTask=True) plight = PointLight('plight') plight.setColor(VBase4(1, 1, 1, 1)) plnp = render.attachNewNode(plight) plnp.setPos(0, -10, 0) render.setLight(plnp) run()
arrow.set_length(start_length) else: t = task.time % time_to_full_length t = t/time_to_full_length length_diff = max_length - start_length new_length = start_length+t*length_diff arrow.set_length(new_length) return Task.cont if __name__ == "__main__": from direct.directbase import DirectStart global base, render print "Arrow::main" arrow = Arrow() arrow.set_angle_x_z_plane(45) #arrow.set_length(0.5) base.disableMouse() base.camera.setPos(0,-5,.5) #taskMgr.add(rotate, 'rotate', extraArgs=[arrow.root_node_path,0.05,0], appendTask=True) #taskMgr.add(scale, 'scale', extraArgs=[arrow,1.0,0.5,1.0], appendTask=True) plight = PointLight('plight') plight.setColor(VBase4(1, 1, 1, 1)) plnp = render.attachNewNode(plight) plnp.setPos(0, -10, 0) render.setLight(plnp) run()
class BaseApp(AppShell): appname = "CG2" usecommandarea = 1 usestatusarea = 1 def _get_filename(self): return self.getVariable("surface", "filename").get() surface_filename = property(_get_filename) def _get_regular_grids(self): return [ bool(self.getVariable("surface", "regular grid %d" % index).get()) for index in range(self._num_surfaces) ] surface_regular_grids = property(_get_regular_grids) def _get_implicit_surfaces(self): return [ bool(self.getVariable("surface", "implicit surface %d" % index).get()) for index in range(self._num_surfaces) ] surface_implicit_surfaces = property(_get_implicit_surfaces) def _get_point_cloud(self): return bool(self.getVariable("surface", "point cloud").get()) surface_point_cloud = property(_get_point_cloud) def _get_subdivisions(self): return [int(widget.get()) for widget in self.tk_subdivisions] surface_subdivisions = property(_get_subdivisions) def _get_degree(self): return int(self.tk_degree.get()) surface_degree = property(_get_degree) def _get_light_angle(self): return int(self.tk_light_angle.get()) surface_light_angle = property(_get_light_angle) def __init__(self): self._log = logging.getLogger("BaseApp") self._num_surfaces = 2 AppShell.__init__(self) self.initialiseoptions(BaseApp) self.createScene() def createInterface(self): self._log.info(u"Creating interface...") self.tk_filename = self.newCreateLabeledEntry( parent=self.interior(), category="surface", text="filename", side=TOP, fill=X, expand=0 ) self.tk_light_angle = self.newCreateEntryScale( parent=self.interior(), category="surface", text="light angle", max=360, min=1, resolution=1, command=self.rotate_light, side=TOP, fill=X, expand=0, ) self.tk_subdivisions = [] for index in range(self._num_surfaces): self.tk_subdivisions.append( self.newCreateEntryScale( parent=self.interior(), category="surface", text="subdivisions %d" % index, max=30, resolution=1, side=TOP, fill=X, expand=0, ) ) self.tk_degree = self.newCreateEntryScale( parent=self.interior(), category="surface", text="degree", max=3, min=1, resolution=1, side=TOP, fill=X, expand=0, ) self.tk_point_cloud = self.newCreateCheckbutton( parent=self.interior(), category="surface", text="point cloud", command=self._toggle_point_cloud, side=TOP, fill=X, expand=0, ) self.tk_regular_grids = [] for index in range(self._num_surfaces): self.tk_regular_grids.append( self.newCreateCheckbutton( parent=self.interior(), category="surface", text="regular grid %d" % index, command=self._toggle_regular_grids, side=TOP, fill=X, expand=0, ) ) self.tk_implicit_surfaces = [] for index in range(self._num_surfaces): self.tk_implicit_surfaces.append( self.newCreateCheckbutton( parent=self.interior(), category="surface", text="implicit surface %d" % index, command=self._toggle_implicit_surfaces, side=TOP, fill=X, expand=0, ) ) self.tk_apply = self.buttonAdd( buttonName="Apply", helpMessage="Apply", statusMessage="Apply", command=self.apply ) # set default values self.getVariable("surface", "filename").set("pointdata/cat.off") self.tk_degree.set(1) self.tk_light_angle.set(1) self.getVariable("surface", "regular grid 0").set(1) self.getVariable("surface", "point cloud").set(1) def createScene(self): self._log.debug(u"Creating scene...") base.setBackgroundColor(0.3, 0.3, 0.3) self.gl_dlight = PointLight("dlight") self.gl_dlight.setColor(Vec4(0.5, 0.5, 0.5, 1)) self.np_dlight = render.attachNewNode(self.gl_dlight) # self.np_dlight.setHpr(90, 0, 0) # self.np_dlight.lookAt(1, 1, -10) render.setLight(self.np_dlight) render.setTransparency(TransparencyAttrib.MAlpha) self._camera_control = CameraHandler() self.clearScene() self.rotate_light() def clearScene(self): if not hasattr(self, "surfaces"): self.surfaces = [None] * self._num_surfaces if not hasattr(self, "grids"): self.grids = [None] * self._num_surfaces if not hasattr(self, "implicit_surfaces"): self.implicit_surfaces = [None] * self._num_surfaces for surface_index in range(self._num_surfaces): if self.surfaces[surface_index]: self.surfaces[surface_index] = None if self.grids[surface_index]: self.grids[surface_index].removeNode() self.grids[surface_index] = None if self.implicit_surfaces[surface_index]: self.implicit_surfaces[surface_index].removeNode() self.implicit_surfaces[surface_index] = None if hasattr(self, "point_cloud") and self.point_cloud: self.point_cloud.removeNode() self.point_cloud = None @log_exceptions @profile(immediate=True) def apply(self): self._log.info("Applying values...") self.clearScene() for index in range(self._num_surfaces): self.surfaces[index] = ImplicitSurface.from_file(self.surface_filename) self._toggle_implicit_surfaces() self._toggle_regular_grids() self._toggle_point_cloud() self._camera_control.setTarget(*self.surfaces[0].center[0:3]) @log_exceptions def _toggle_regular_grids(self): for index in range(self._num_surfaces): self._toggle_regular_grid(index) def _toggle_regular_grid(self, index): if self.surfaces[index]: self._log.debug(u"Toggling regular grid %d display..." % index) if not self.grids[index]: self._log.debug(u"Creating regular grid %d..." % index) self.grids[index] = render.attachNewNode( self.surfaces[index].get_parameter_grid(self.surface_subdivisions[index], self.surface_degree) ) self.grids[index].setLightOff() if self.surface_regular_grids[index]: self._log.debug(u"Regular grid %d is now visible." % index) self.grids[index].show() else: self._log.debug(u"Regular grid %d is now hidden." % index) self.grids[index].hide() else: self._log.debug(u"No surface loaded, cannot create regular grid %d..." % index) @log_exceptions def _toggle_implicit_surfaces(self): for index in range(self._num_surfaces): self._toggle_implicit_surface(index) def _toggle_implicit_surface(self, index): if self.surfaces[index]: self._log.debug(u"Toggling implicit surface %d display..." % index) if not self.implicit_surfaces[index]: self._log.debug(u"Creating implicit surface %d..." % index) self.implicit_surfaces[index] = render.attachNewNode( self.surfaces[index].get_implicit_surface(self.surface_subdivisions[index], self.surface_degree) ) if self.surface_implicit_surfaces[index]: self._log.debug(u"implicit surface %d is now visible." % index) self.implicit_surfaces[index].show() else: self._log.debug(u"implicit surface %d is now hidden." % index) self.implicit_surfaces[index].hide() else: self._log.debug(u"No surface loaded, cannot create implicit surface %d..." % index) @log_exceptions def _toggle_point_cloud(self): if self.surfaces[0]: self._log.debug(u"Toggling point cloud display...") if not self.point_cloud: self._log.debug(u"Creating point_cloud...") self.point_cloud = render.attachNewNode(self.surfaces[0].get_original_point_cloud()) self.point_cloud.setLightOff() if self.surface_point_cloud: self._log.debug(u"point cloud is now visible.") self.point_cloud.show() else: self._log.debug(u"point cloud is now hidden.") self.point_cloud.hide() else: self._log.debug(u"No surface loaded, cannot create point cloud...") @log_exceptions def rotate_light(self, val=None): if hasattr(self, "np_dlight"): self._log.debug(u"Setting light angle %d..." % self.surface_light_angle) angle_radians = self.surface_light_angle * (math.pi / 180.0) self.np_dlight.setPos(1000.0 * math.sin(angle_radians), -1000.0 * math.cos(angle_radians), 0)