def renderQuadInto(self, mul=1, div=1, align=1, depthtex=None, colortex=None, auxtex0=None, auxtex1=None): texgroup = (depthtex, colortex, auxtex0, auxtex1) (winx, winy) = self.getScaledSize(mul, div, align) depthbits = bool(depthtex != None) buffer = self.createBuffer('filter-stage', winx, winy, texgroup, depthbits) if buffer == None: return None cm = CardMaker('filter-stage-quad') cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setColor(Vec4(1, 0.5, 0.5, 1)) quadcamnode = Camera('filter-quad-cam') lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) buffer.getDisplayRegion(0).setCamera(quadcam) buffer.getDisplayRegion(0).setActive(1) self.buffers.append(buffer) self.sizes.append((mul, div, align)) return quad
def __init__(self): global taskMgr, base # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) lens = OrthographicLens() lens.setFilmSize(WINDOW_SZ, WINDOW_SZ) base.cam.node().setLens(lens) # Disable default mouse-based camera control. This is a method on the # ShowBase class from which we inherit. self.disableMouse() # point camera down onto x-y plane camera.setPos(LVector3(0, 0, 1)) camera.setP(-90) self.setBackgroundColor((0, 0, 0, 1)) self.bg = loadObject("stars.jpg", WINDOW_SZ, (0, 0, 0, 1)) self.accept("escape", sys.exit) # Escape quits self.accept("space", self.newGame, []) # Escape quits self.startupSeparateOne() #self.startupPerformMany() #self.startupDetective() self.newGame() self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")
def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None): if textures: colortex = textures.get('color', None) depthtex = textures.get('depth', None) auxtex = textures.get('aux', None) if colortex == None: colortex = Texture('filter-base-color') colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex, colortex, auxtex, None) (winx, winy) = self.getScaledSize(1, 1, 1) buffer = self.createBuffer('filter-base', winx, winy, texgroup) if buffer == None: return None cm = CardMaker('filter-base-quad') cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(Vec4(1, 0.5, 0.5, 1)) cs = NodePath('dummy') cs.setState(self.camstate) if auxbits: cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera('filter-quad-cam') lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) dr = buffer.getDisplayRegion(0) self.setStackedClears(dr, self.rclears, self.wclears) if auxtex: dr.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) dr.setClearValue(GraphicsOutput.RTPAuxRgba0, Vec4(0.5, 0.5, 1.0, 0.0)) self.region.disableClears() if self.isFullscreen(): self.win.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1, 1)) return quad
def __init__(self): global taskMgr, base # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) lens = OrthographicLens() lens.setFilmSize(FIELD_SZ, FIELD_SZ) base.cam.node().setLens(lens) # This code puts the standard title and instruction text on screen # self.scoreBrd = genLabelText("Test", 0) self.scoreBrd = genTextNode("TEST") # Disable default mouse-based camera control. This is a method on the # ShowBase class from which we inherit. self.disableMouse() # point camera down onto x-y plane camera.setPos(LVector3(0, 0, 1)) camera.setP(-90) # Load the background starfield. self.setBackgroundColor((0, 0, 0, 1)) self.bg = loadObject("stars.jpg", scale=FIELD_SZ, transparency=False) # Load the ship and set its initial velocity. self.ship = loadObject("ship.png", scale=2*SHIP_RAD) self.setTag("velocity", self.ship, LVector3.zero()) self.accept("escape", sys.exit) # Escape quits self.accept("space", self.endGame, [0]) # Escape quits # Now we create the task. taskMgr is the task manager that actually # calls the function each frame. The add method creates a new task. # The first argument is the function to be called, and the second # argument is the name for the task. It returns a task object which # is passed to the function each frame. self.gameTask = taskMgr.add(self.gameLoop, "gameLoop") # Stores the time at which the next bullet may be fired. self.nextBullet = 0.0 # This list will stored fired bullets. self.bullets = [] self.shipAI = ShipAI(FIELD_SZ, AI_TIME, TURN_RATE, BULLET_SPEED, BULLET_REPEAT, BULLET_RAD, AST_SPEEDS, AST_DIAMS, NUM_FRAMES, PTS) self.currFrame = 0 self.currGame = 0 self.totalScore = 0 self.bullets = [] self.asteroids = [] self.ship.setColor(1,1,1) self.newGame() self.shieldActive = False self.shieldFrames = 0
def renderQuadInto(self, mul=1, div=1, align=1, depthtex=None, colortex=None, auxtex0=None, auxtex1=None): """ Creates an offscreen buffer for an intermediate computation. Installs a quad into the buffer. Returns the fullscreen quad. The size of the buffer is initially equal to the size of the main window. The parameters 'mul', 'div', and 'align' can be used to adjust that size. """ texgroup = (depthtex, colortex, auxtex0, auxtex1) winx, winy = self.getScaledSize(mul, div, align) depthbits = bool(depthtex != None) buffer = self.createBuffer("filter-stage", winx, winy, texgroup, depthbits) if (buffer == None): return None cm = CardMaker("filter-stage-quad") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setColor(Vec4(1, 0.5, 0.5, 1)) quadcamnode = Camera("filter-quad-cam") lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) dr = buffer.makeDisplayRegion((0, 1, 0, 1)) dr.disableClears() dr.setCamera(quadcam) dr.setActive(True) dr.setScissorEnabled(False) # This clear stage is important if the buffer is padded, so that # any pixels accidentally sampled in the padded region won't # be reading from unititialised memory. buffer.setClearColor((0, 0, 0, 1)) buffer.setClearColorActive(True) self.buffers.append(buffer) self.sizes.append((mul, div, align)) return quad
def __init__(self, scene_file, pedestrian_file, dir, mode): ShowBase.__init__(self) self.globalClock = ClockObject.getGlobalClock() self.globalClock.setMode(ClockObject.MSlave) self.directory = dir self.model = Model(dir) self.loadScene(scene_file) self.loadPedestrians(pedestrian_file) self.cam_label = OST("Top Down", pos=(0, 0.95), fg=(1, 1, 1, 1), scale=0.05, mayChange=True) self.time_label = OST("Time: 0.0", pos=(-1.3, 0.95), fg=(1, 1, 1, 1), scale=0.06, mayChange=True, align=TextNode.ALeft) self.accept("arrow_right", self.changeCamera, [1]) self.accept("arrow_left", self.changeCamera, [-1]) self.accept("escape", self.exit) self.accept("aspectRatioChanged", self.setAspectRatio) self.accept("window-event", self.windowChanged) #base.disableMouse() lens = OrthographicLens() lens.setFilmSize(1550, 1000) self.display_region = base.win.makeDisplayRegion() self.default_camera = render.attachNewNode(Camera("top down")) self.default_camera.node().setLens(lens) self.default_camera.setPosHpr(Vec3(-75, 0, 2200), Vec3(0, -90, 0)) self.setCamera(0) self.controller = Controller(self, mode) self.taskMgr.add(self.updateCameraModules, "Update Camera Modules", 80) self.globalClock.setFrameTime(0.0) self.width = WIDTH self.height = HEIGHT props = WindowProperties() props.setTitle('Virtual Vision Simulator') base.win.requestProperties(props)
def initialize(self): asp = base.getAspectRatio() lens = OrthographicLens() lens.setFilmSize(2.0, 2.0) lens.setNearFar(-1000, 1000) self.getCamera().node().setLens(lens) # creates the root node if self.sceneRoot is None: self.sceneRoot = render2d.attachNewNode( PanoConstants.NODE2D_ROOT_NODE) self.raycaster = NodeRaycaster(self) self.raycaster.initialize()
def __init__(self): global taskMgr, base # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) lens = OrthographicLens() lens.setFilmSize(WINDOW_SZ, WINDOW_SZ) base.cam.node().setLens(lens) # Disable default mouse-based camera control. This is a method on the # ShowBase class from which we inherit. self.disableMouse() # point camera down onto x-y plane camera.setPos(LVector3(0, 0, 1)) camera.setP(-90) self.setBackgroundColor((0, 0, 0, 1)) self.bg = loadObject("stars.jpg", WINDOW_SZ, (0, 0, 0, 1)) self.accept("escape", sys.exit) # Escape quits self.accept("space", self.newGame, []) # Escape quits speed = random.random() * 45 + 5 N = WINDOW_SZ / 2 targetColor = (1, 0, 0, 1) target = loadObject("ship.png", 2*AVATAR_RAD, targetColor) targetKinematic = Kinematic(Point2(0, 0), 0, speed, target, WINDOW_SZ) #targetSteering = KinematicCircular(targetKinematic) #targetSteering = KinematicStationary(targetKinematic) targetSteering = KinematicLinear(targetKinematic) self.target = PlayerAndMovement(targetKinematic, targetSteering) avatarColor = (0, 1, 0, 1) avatar = loadObject("ship.png", 2*AVATAR_RAD, avatarColor) avatarKinematic = Kinematic(Point2(0, 0), 0, speed, avatar, WINDOW_SZ) avatarLinear = KinematicLinear(avatarKinematic) avatarSeek = KinematicSeek(avatarKinematic, targetKinematic) avatarFlee = KinematicFlee(avatarKinematic, targetKinematic) steerings = { 'Linear' : avatarLinear, 'Seek' : avatarSeek, 'Flee' : avatarFlee } fsm = SteeringFSM() self.avatarSteering = KinematicFSM(avatarKinematic, targetKinematic, fsm, steerings) self.avatar = PlayerAndMovement(avatarKinematic, self.avatarSteering) self.newGame() self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")
def renderQuadInto(self, mul=1, div=1, align=1, depthtex=None, colortex=None, auxtex0=None, auxtex1=None): """ Creates an offscreen buffer for an intermediate computation. Installs a quad into the buffer. Returns the fullscreen quad. The size of the buffer is initially equal to the size of the main window. The parameters 'mul', 'div', and 'align' can be used to adjust that size. """ texgroup = (depthtex, colortex, auxtex0, auxtex1) winx, winy = self.getScaledSize(mul, div, align) depthbits = bool(depthtex != None) buffer = self.createBuffer("filter-stage", winx, winy, texgroup, depthbits) if (buffer == None): return None cm = CardMaker("filter-stage-quad") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setColor(Vec4(1, 0.5, 0.5, 1)) quadcamnode = Camera("filter-quad-cam") lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) buffer.getDisplayRegion(0).setCamera(quadcam) buffer.getDisplayRegion(0).setActive(1) self.buffers.append(buffer) self.sizes.append((mul, div, align)) return quad
def __init__(self, scene_file, pedestrian_file, dir, mode): ShowBase.__init__(self) self.globalClock = ClockObject.getGlobalClock() self.globalClock.setMode(ClockObject.MSlave) self.directory = dir self.model = Model(dir) self.loadScene(scene_file) self.loadPedestrians(pedestrian_file) self.cam_label = OST("Top Down", pos=(0, 0.95), fg=(1,1,1,1), scale=0.05, mayChange=True) self.time_label = OST("Time: 0.0", pos=(-1.3, 0.95), fg=(1,1,1,1), scale=0.06, mayChange=True, align=TextNode.ALeft) self.accept("arrow_right", self.changeCamera, [1]) self.accept("arrow_left", self.changeCamera, [-1]) self.accept("escape", self.exit) self.accept("aspectRatioChanged", self.setAspectRatio) self.accept("window-event", self.windowChanged) #base.disableMouse() lens = OrthographicLens() lens.setFilmSize(1550, 1000) self.display_region = base.win.makeDisplayRegion() self.default_camera = render.attachNewNode(Camera("top down")) self.default_camera.node().setLens(lens) self.default_camera.setPosHpr(Vec3( -75, 0, 2200), Vec3(0, -90, 0)) self.setCamera(0) self.controller = Controller(self, mode) self.taskMgr.add(self.updateCameraModules, "Update Camera Modules", 80) self.globalClock.setFrameTime(0.0) self.width = WIDTH self.height = HEIGHT props = WindowProperties( ) props.setTitle( 'Virtual Vision Simulator' ) base.win.requestProperties( props )
def renderQuadInto(self, mul=1, div=1, align=1, depthtex=None, colortex=None, auxtex0=None, auxtex1=None): """ Creates an offscreen buffer for an intermediate computation. Installs a quad into the buffer. Returns the fullscreen quad. The size of the buffer is initially equal to the size of the main window. The parameters 'mul', 'div', and 'align' can be used to adjust that size. """ texgroup = (depthtex, colortex, auxtex0, auxtex1) winx, winy = self.getScaledSize(mul, div, align) depthbits = bool(depthtex != None) buffer = self.createBuffer("filter-stage", winx, winy, texgroup, depthbits) if (buffer == None): return None cm = CardMaker("filter-stage-quad") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setColor(Vec4(1,0.5,0.5,1)) quadcamnode = Camera("filter-quad-cam") lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) buffer.getDisplayRegion(0).setCamera(quadcam) buffer.getDisplayRegion(0).setActive(1) self.buffers.append(buffer) self.sizes.append((mul, div, align)) return quad
def __init__(self): global taskMgr, base, camera, render ShowBase.__init__(self) lens = OrthographicLens() lens.setFilmSize(GAME_SZ, GAME_SZ) base.cam.node().setLens(lens) self.disableMouse() camera.setPos(LVector3(0, 0, 1)) camera.setP(-90) self.accept("escape", sys.exit) self.accept("space", self.nextConfig) self.gameTask = taskMgr.add(self.gameLoop, "gameLoop") self.whichConfig = NUM_CONFIGS - 1 self.envNP = None self.pathNP = None self.nextConfig()
class JamoDrumNodePath(NodePath): """ A C{NodePath} of a heirarchy of a Jam-o-Drum. Creating one of these sets up the camera as well for displaying an orthographic view of this Jam-o-drum @ivar stations: list of 4 L{Station} objects representing each Jam-o-Drum station @type stations: L{Station}[] """ def __init__(self,table=None,mask=None): """ @keyword table: filename of a table texture. See table_template.psd. Either paint anywhere inside the mask for a complete background or turn off the pads and spinner and paint in the table circle for just a table texture that will have spinners and pads put on top of it. @type mask: str @keyword mask: filename of a mask texture of the non-Jam-o-Drum area. probably jod_mask.png that comes with the Jam-o-Drum library. @type mask: str """ NodePath.__init__(self,"JamoDrum") totalHeight = max(1.0,math.sqrt(2)/4.0+SPINNER_RADIUS)*2 cm = CardMaker("card") cm.setFrame(-1,1,-1,1) self.tableCard = self.attachNewNode(cm.generate()) self.tableCard.setP(-90) self.tableCard.setScale(4.0/3.0) self.tableCard.setLightOff() self.tableCard.setBin("background",0) self.tableCard.setDepthTest(0) self.tableCard.setDepthWrite(0) self.tableCard.hide() if (table): self.setTableTexture(loader.loadTexture(table)) if (mask): cm = CardMaker("JOD Mask") cm.setFrame(-4.0/3.0,4.0/3.0,-4.0/3.0,4.0/3.0) self.mask = aspect2d.attachNewNode(cm.generate()) #self.mask.setP(-90) self.mask.setTexture(loader.loadTexture(mask),1) self.mask.setTransparency(1) self.mask.setDepthTest(0) else: self.mask = None self.stations = [] for i in range(4): station = Station(self,i) station.reparentTo(self) self.stations.append(station) self.reparentTo(render) base.disableMouse() self.lens = OrthographicLens() self.lens.setFilmSize(totalHeight*base.getAspectRatio(),totalHeight) base.cam.node().setLens(self.lens) camera.setPosHpr(0,0,10.0, 0,-90,0) base.setBackgroundColor(0,0,0) self.audio3d = Audio3DManager(base.sfxManagerList[0],self) self.audio3d.setDropOffFactor(0) # end __init__ def setTableTexture(self,texture,scale=None): """ sets the background texture on the table @param texture: C{Texture} or image file to show on the table @type texture: C{Texture} or string @keyword scale: scale of the texture. Default is set for the table_template.psd @type scale: float """ if (not isinstance(texture,Texture)): texture = loader.loadTexture(texture) self.tableCard.setTexture(texture) if (scale): self.tableCard.setScale(scale) self.showTable() # end setTableTexture def showTable(self): """ displays the table's background texture """ self.tableCard.show() # end showTable def hideTable(self): """ hides the table's background texture """ self.tableCard.hide() # end hideSpinner def loadSfx(self,file,object=None): """ load a sound with positional audio support @param file: wav file to load. Must be mono. @type file: string @keyword object: object to attach sound to @type object: C{NodePath} @return: a Panda sound object @rtype: C{AudioSound} """ sfx = self.audio3d.loadSfx(file) if (object): self.attachSoundToObject(sfx,object) return sfx # loadSfx def attachSoundToObject(self,sound,object): """ attach a positional sound to an object it will come from @param sound: positional sound object to attach @type sound: C{AudioSound} @param object: object sound should come from @type object: C{NodePath} """ self.audio3d.attachSoundToObject(sound,object) # end attachSoundToObject def detachSound(self,sound): """ detach a positional sound from it's object. It will no longer move. @param sound: positional sound object to detach @type sound: C{AudioSound} """ self.audio3d.detachSound(sound)
def __init__(self, scene_file, pedestrian_file, dir, mode): ShowBase.__init__(self) self.globalClock = ClockObject.getGlobalClock() self.globalClock.setMode(ClockObject.MSlave) self.directory = dir self.model = Model(dir) self.loadScene(scene_file) self.loadPedestrians(pedestrian_file) #self.cam_label = OST("Top Down", pos=(0, 0.95), fg=(1,1,1,1), # scale=0.05, mayChange=True) #self.time_label = OST("Time: 0.0", pos=(-1.3, 0.95), fg=(1,1,1,1), # scale=0.06, mayChange=True, align=TextNode.ALeft) #self.accept("arrow_right", self.changeCamera, [1]) #self.accept("arrow_left", self.changeCamera, [-1]) self.accept("escape", self.exit) self.accept("aspectRatioChanged", self.setAspectRatio) self.accept("window-event", self.windowChanged) new_window_fbp = FrameBufferProperties.getDefault() new_window_properties = WindowProperties.getDefault() self.new_window = base.graphicsEngine.makeOutput(base.pipe, 'Top Down View Window', 0, new_window_fbp, new_window_properties, GraphicsPipe.BFRequireWindow) self.new_window_display_region = self.new_window.makeDisplayRegion() #base.disableMouse() lens = OrthographicLens() lens.setFilmSize(1500, 1500) lens.setNearFar(-5000, 5000) self.default_camera = render.attachNewNode(Camera("top down")) self.default_camera.node().setLens(lens) #self.default_camera.setPosHpr(Vec3( -75, 0, 2200), Vec3(0, -90, 0)) self.default_camera.setPosHpr(Vec3(-75, 0, 0), Vec3(0, -90, 0)) #self.new_window = base.openWindow() self.display_regions = [] self.display_regions.append(self.new_window_display_region) self.display_regions.append(base.win.makeDisplayRegion(0, 0.32, 0.52, 1)) self.display_regions.append(base.win.makeDisplayRegion(0.34, 0.66, 0.52, 1)) self.display_regions.append(base.win.makeDisplayRegion(0.68, 1, 0.52, 1)) self.display_regions.append(base.win.makeDisplayRegion(0, 0.32, 0, 0.48)) self.display_regions.append(base.win.makeDisplayRegion(0.34, 0.66, 0, 0.48)) self.display_regions.append(base.win.makeDisplayRegion(0.68, 1, 0, 0.48)) self.display_regions[0].setCamera(self.default_camera) self.border_regions = [] self.border_regions.append(base.win.makeDisplayRegion(0.32, 0.34, 0.52, 1)) self.border_regions.append(base.win.makeDisplayRegion(0.66, 0.68, 0.52, 1)) self.border_regions.append(base.win.makeDisplayRegion(0, 1, 0.48, 0.52)) self.border_regions.append(base.win.makeDisplayRegion(0.32, 0.34, 0, 0.48)) self.border_regions.append(base.win.makeDisplayRegion(0.66, 0.68, 0, 0.48)) for i in range(0, len(self.border_regions)): border_region = self.border_regions[i] border_region.setClearColor(VBase4(0, 0, 0, 1)) border_region.setClearColorActive(True) border_region.setClearDepthActive(True) #self.setCamera(0) self.controller = Controller(self, mode) self.taskMgr.add(self.updateCameraModules, "Update Camera Modules", 80) self.globalClock.setFrameTime(0.0) self.width = WIDTH self.height = HEIGHT props = WindowProperties( ) props.setTitle( 'Virtual Vision Simulator' ) base.win.requestProperties( props ) """new_window_2d_display_region = self.new_window.makeDisplayRegion() new_window_2d_display_region.setSort(20) new_window_camera_2d = NodePath(Camera('2d camera of new window')) lens_2d = OrthographicLens() lens_2d.setFilmSize(2, 2) lens_2d.setNearFar(-1000, 1000) new_window_camera_2d.node().setLens(lens_2d) new_window_render_2d = NodePath('render2d of new window') new_window_render_2d.setDepthTest(False) new_window_render_2d.setDepthWrite(False) new_window_camera_2d.reparentTo(new_window_render_2d) new_window_2d_display_region.setCamera(new_window_camera_2d)""" """aspectRatio = base.getAspectRatio() self.new_window_aspect2d = new_window_render_2d.attachNewNode(PGTop('Aspect2d of new window')) self.new_window_aspect2d.setScale(1.0 / aspectRatio, 1.0, 1.0)""" render.analyze()
def __init__(self, actor, state, lvl): #Setzte die Parameter self.CActor = actor #Spieler erstellen self.CGame = state #FSM - Gamestate erstellen self.mission = lvl #Aktuelle Mission self.mMission = None #Grundeinstellen fuer die Welt base.disableMouse() #Mouse ausmachen self.slowdown = 1 #Schnelligkeitsfaktor 1=Normal self.hud = False file, filename, description = imp.find_module("mission" + str(self.mission)) self.mMission = imp.load_module("mission" + str(self.mission), file, filename, description) #SPIELER - Variablen self.oldactorlevel = self.CActor.getLevel() self.CActor.CActorShip.setX( -165) #Setze den Spieler links im Bildschirm self.CActor.CActorShip.setY(0) self.CActor.nActorShip.reparentTo(render) self.CActor.CActorShip.getWeapon().setWeapon( "laserGun") #Standardwaffe setzen self.maxshield = self.CActor.CActorShip.getShield( ) #Schild speichern um Prozent berechnen zu koennen self.hitted = False #Variable um abzufragen ob man getroffen wurde self.dead = False #Spieler lebt self.lbullets = [] #Spielerbullets self.lbulletsspeed = [] self.lcanon = [] #Spielercanonbullets self.lcanonspeed = [] self.cameraeffectx = 0 #X-Wert der Camera um eine Sinuskurve zu implementieren self.cameraeffectamplitude = 5 #Die Amplitude der Sinuswelle - Maxima self.exppercent = (self.CActor.getExperience() * 100 ) / self.CActor.getMaxExperience() #EXP in Prozent self.oldcash = self.CActor.getMoney() self.secweapon = 3 #Resultattexte, wenn die Mission zu ende ist self.txtresultmission = addText(-0.15, 0.35, "") self.txtresultkills = addText(-0.15, 0.25, "") self.txtresultleft = addText(-0.15, 0.20, "") self.txtresultcash = addText(-0.15, 0.15, "") self.txtresultlevel = addText(-0.15, 0.10, "") self.txtresultmessage = addText(-0.15, 0.0, "") #ALLES FUER MOTION BLUR *********************************************************************** #Eine Texture erstellen, welches in das Hauptfenster kopiert wird self.CTex = Texture() self.CTex.setMinfilter(Texture.FTLinear) base.win.addRenderTexture(self.CTex, GraphicsOutput.RTMTriggeredCopyTexture) #Eine andere 2D Kamera erstellen, welches vor der Hauptkamera gerendert wird self.backcam = base.makeCamera2d(base.win, sort=-10) self.background = NodePath("background") self.backcam.reparentTo(self.background) self.background.setDepthTest(0) self.background.setDepthWrite(0) self.backcam.node().getDisplayRegion(0).setClearDepthActive(0) #Zwei Texturekarten ersten. Eins bevor, eins danach self.bcard = base.win.getTextureCard() self.bcard.reparentTo(self.background) self.bcard.setTransparency(1) self.fcard = base.win.getTextureCard() self.fcard.reparentTo(render2d) self.fcard.setTransparency(1) #********************************************************************************************** #Drops als Liste self.ldrop = [] #Explosionen - oder besser gesagt Splittereffekt als Liste self.lexplosions = [] #Soundklasse erstellen um Zugriff auf die Sound zu haben self.CSound = SoundMng() self.CSound.sndFlyAmbience.play() #GEGNER - Variablen self.destroyedenemy = 0 self.lostenemy = 0 self.lenemys = [] #Gegnerspeicher self.lbulletsenemy = [] #Gegnerbullets self.newwave = False #Boolean,welches eine neue Gegnerwelle angibt #Effekte self.CEffects = Effects() #Effektklasse erstellen #self.CEffects.createSpaceStars("particle/background.ptf") #Hintergrundeffekt erstellen #Die Game-Loop Voreinstellungen self.gameTask = taskMgr.add(self.gameLoop, "gameLoop") self.gameTask.last = 0 self.gameTask.nextbullet = 0 #Timer wann geschossen werden darf, vom Spieler self.gameTask.gotHit = 0 self.gameTask.lnextenemybullet = [ ] #Timer wann geschossen werden darf, unabhaengig von welche Gegner self.gameTask.resultkills = 0 #Timer fuer die Kills, im Resultat self.gameTask.resultleft = 0 #Timer fuer die geflohenen Gegner, im Resultat self.gameTask.introduction = 0 self.gameTask.introdelete = 0 self.gameTask.won = 0 self.resultcounter = 0 #Zeahler der die Nummern der Kills im Result aktualisiert self.resultcounterleft = 0 #Zeahler der die Nummern der geflohenen Gegner im Result aktualisiert self.introcounter = 0 self.ldata = [] self.readytospawn = False self.musicplayed = False self.musicplayed2 = False self.resultplayed = False #2D Kamera erstellen lens = OrthographicLens() lens.setFilmSize(350, 250) base.cam.node().setLens(lens)
def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None): """ Causes the scene to be rendered into the supplied textures instead of into the original window. Puts a fullscreen quad into the original window to show the render-to-texture results. Returns the quad. Normally, the caller would then apply a shader to the quad. To elaborate on how this all works: * An offscreen buffer is created. It is set up to mimic the original display region - it is the same size, uses the same clear colors, and contains a DisplayRegion that uses the original camera. * A fullscreen quad and an orthographic camera to render that quad are both created. The original camera is removed from the original window, and in its place, the orthographic quad-camera is installed. * The fullscreen quad is textured with the data from the offscreen buffer. A shader is applied that tints the results pink. * Automatic shader generation NOT enabled. If you have a filter that depends on a render target from the auto-shader, you either need to set an auto-shader attrib on the main camera or scene, or, you need to provide these outputs in your own shader. * All clears are disabled on the original display region. If the display region fills the whole window, then clears are disabled on the original window as well. It is assumed that rendering the full-screen quad eliminates the need to do clears. Hence, the original window which used to contain the actual scene, now contains a pink-tinted quad with a texture of the scene. It is assumed that the user will replace the shader on the quad with a more interesting filter. """ if (textures): colortex = textures.get("color", None) depthtex = textures.get("depth", None) auxtex = textures.get("aux", None) if (colortex == None): colortex = Texture("filter-base-color") colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex, colortex, auxtex, None) # Choose the size of the offscreen buffer. (winx, winy) = self.getScaledSize(1,1,1) buffer = self.createBuffer("filter-base", winx, winy, texgroup) if (buffer == None): return None cm = CardMaker("filter-base-quad") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(Vec4(1,0.5,0.5,1)) cs = NodePath("dummy") cs.setState(self.camstate) # Do we really need to turn on the Shader Generator? #cs.setShaderAuto() if (auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera("filter-quad-cam") lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) dr = buffer.getDisplayRegion(0) self.setStackedClears(dr, self.rclears, self.wclears) if (auxtex): dr.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) dr.setClearValue(GraphicsOutput.RTPAuxRgba0, Vec4(0.5,0.5,1.0,0.0)) self.region.disableClears() if (self.isFullscreen()): self.win.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1, 1)) return quad
def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None): """ Causes the scene to be rendered into the supplied textures instead of into the original window. Puts a fullscreen quad into the original window to show the render-to-texture results. Returns the quad. Normally, the caller would then apply a shader to the quad. To elaborate on how this all works: * An offscreen buffer is created. It is set up to mimic the original display region - it is the same size, uses the same clear colors, and contains a DisplayRegion that uses the original camera. * A fullscreen quad and an orthographic camera to render that quad are both created. The original camera is removed from the original window, and in its place, the orthographic quad-camera is installed. * The fullscreen quad is textured with the data from the offscreen buffer. A shader is applied that tints the results pink. * Automatic shader generation NOT enabled. If you have a filter that depends on a render target from the auto-shader, you either need to set an auto-shader attrib on the main camera or scene, or, you need to provide these outputs in your own shader. * All clears are disabled on the original display region. If the display region fills the whole window, then clears are disabled on the original window as well. It is assumed that rendering the full-screen quad eliminates the need to do clears. Hence, the original window which used to contain the actual scene, now contains a pink-tinted quad with a texture of the scene. It is assumed that the user will replace the shader on the quad with a more interesting filter. """ if (textures): colortex = textures.get("color", None) depthtex = textures.get("depth", None) auxtex = textures.get("aux", None) auxtex0 = textures.get("aux0", auxtex) auxtex1 = textures.get("aux1", None) else: auxtex0 = auxtex auxtex1 = None if (colortex == None): colortex = Texture("filter-base-color") colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex, colortex, auxtex0, auxtex1) # Choose the size of the offscreen buffer. (winx, winy) = self.getScaledSize(1,1,1) buffer = self.createBuffer("filter-base", winx, winy, texgroup) if (buffer == None): return None cm = CardMaker("filter-base-quad") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(Vec4(1,0.5,0.5,1)) cs = NodePath("dummy") cs.setState(self.camstate) # Do we really need to turn on the Shader Generator? #cs.setShaderAuto() if (auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera("filter-quad-cam") lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) self.setStackedClears(buffer, self.rclears, self.wclears) if (auxtex0): buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, Vec4(0.5, 0.5, 1.0, 0.0)) if (auxtex1): buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1) self.region.disableClears() if (self.isFullscreen()): self.win.disableClears() dr = buffer.makeDisplayRegion() dr.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1, 1)) return quad
class JamoDrumNodePath(NodePath): """ A C{NodePath} of a heirarchy of a Jam-o-Drum. Creating one of these sets up the camera as well for displaying an orthographic view of this Jam-o-drum @ivar stations: list of 4 L{Station} objects representing each Jam-o-Drum station @type stations: L{Station}[] """ def __init__(self, table=None, mask=None): """ @keyword table: filename of a table texture. See table_template.psd. Either paint anywhere inside the mask for a complete background or turn off the pads and spinner and paint in the table circle for just a table texture that will have spinners and pads put on top of it. @type mask: str @keyword mask: filename of a mask texture of the non-Jam-o-Drum area. probably jod_mask.png that comes with the Jam-o-Drum library. @type mask: str """ NodePath.__init__(self, "JamoDrum") totalHeight = max(1.0, math.sqrt(2) / 4.0 + SPINNER_RADIUS) * 2 cm = CardMaker("card") cm.setFrame(-1, 1, -1, 1) self.tableCard = self.attachNewNode(cm.generate()) self.tableCard.setP(-90) self.tableCard.setScale(4.0 / 3.0) self.tableCard.setLightOff() self.tableCard.setBin("background", 0) self.tableCard.setDepthTest(0) self.tableCard.setDepthWrite(0) self.tableCard.hide() if (table): self.setTableTexture(loader.loadTexture(table)) if (mask): cm = CardMaker("JOD Mask") cm.setFrame(-4.0 / 3.0, 4.0 / 3.0, -4.0 / 3.0, 4.0 / 3.0) self.mask = aspect2d.attachNewNode(cm.generate()) #self.mask.setP(-90) self.mask.setTexture(loader.loadTexture(mask), 1) self.mask.setTransparency(1) self.mask.setDepthTest(0) else: self.mask = None self.stations = [] for i in range(4): station = Station(self, i) station.reparentTo(self) self.stations.append(station) self.reparentTo(render) base.disableMouse() self.lens = OrthographicLens() self.lens.setFilmSize(totalHeight * base.getAspectRatio(), totalHeight) base.cam.node().setLens(self.lens) camera.setPosHpr(0, 0, 10.0, 0, -90, 0) base.setBackgroundColor(0, 0, 0) self.audio3d = Audio3DManager(base.sfxManagerList[0], self) self.audio3d.setDropOffFactor(0) # end __init__ def setTableTexture(self, texture, scale=None): """ sets the background texture on the table @param texture: C{Texture} or image file to show on the table @type texture: C{Texture} or string @keyword scale: scale of the texture. Default is set for the table_template.psd @type scale: float """ if (not isinstance(texture, Texture)): texture = loader.loadTexture(texture) self.tableCard.setTexture(texture) if (scale): self.tableCard.setScale(scale) self.showTable() # end setTableTexture def showTable(self): """ displays the table's background texture """ self.tableCard.show() # end showTable def hideTable(self): """ hides the table's background texture """ self.tableCard.hide() # end hideSpinner def loadSfx(self, file, object=None): """ load a sound with positional audio support @param file: wav file to load. Must be mono. @type file: string @keyword object: object to attach sound to @type object: C{NodePath} @return: a Panda sound object @rtype: C{AudioSound} """ sfx = self.audio3d.loadSfx(file) if (object): self.attachSoundToObject(sfx, object) return sfx # loadSfx def attachSoundToObject(self, sound, object): """ attach a positional sound to an object it will come from @param sound: positional sound object to attach @type sound: C{AudioSound} @param object: object sound should come from @type object: C{NodePath} """ self.audio3d.attachSoundToObject(sound, object) # end attachSoundToObject def detachSound(self, sound): """ detach a positional sound from it's object. It will no longer move. @param sound: positional sound object to detach @type sound: C{AudioSound} """ self.audio3d.detachSound(sound)
class ShadowCasterClass: texXSize = 2048 texYSize = 2048 groundPath = None objectPath = None def __init__(self, objectPath, groundPath, lightPos=Vec3(0,0,1)): """ ShadowCaster::__init__ objectPath is the shadow casting object groundPath is the shadow receiving object lightPos is the lights relative position to the objectPath """ # uniq id-number for each shadow global shadowCasterObjectCounter shadowCasterObjectCounter += 1 self.objectShadowId = shadowCasterObjectCounter # the object which will cast shadows self.objectPath = objectPath # get the objects bounds center and radius to # define the shadowrendering camera position and filmsize try: objectBoundRadius = self.objectPath.getBounds().getRadius() objectBoundCenter = self.objectPath.getBounds().getCenter() except: print "failed" objectBoundCenter = Point3( 0,0,0 ) objectBoundRadius = 1 lightPath = objectPath.attachNewNode('lightPath%i'%self.objectShadowId) # We can change this position at will to change the angle of the sun. lightPath.setPos( objectPath.getParent(), objectBoundCenter ) self.lightPath = lightPath # the film size is the diameter of the object self.filmSize = objectBoundRadius * 2 # Create an offscreen buffer to render the view of the avatar # into a texture. self.buffer = base.win.makeTextureBuffer( 'shadowBuffer%i'%self.objectShadowId, self.texXSize, self.texYSize) # The background of this buffer--and the border of the # texture--is pure white. clearColor = VBase4(1, 1, 1, 1) self.buffer.setClearColor(clearColor) self.tex = self.buffer.getTexture() self.tex.setBorderColor(clearColor) self.tex.setWrapU(Texture.WMBorderColor) self.tex.setWrapV(Texture.WMBorderColor) # Set up a display region on this buffer, and create a camera. dr = self.buffer.makeDisplayRegion() self.camera = Camera('shadowCamera%i'%self.objectShadowId) self.cameraPath = self.lightPath.attachNewNode(self.camera) self.camera.setScene(self.objectPath) dr.setCamera(self.cameraPath) self.setLightPos( lightPos ) # Use a temporary NodePath to define the initial state for the # camera. The initial state will render everything in a # flat-shaded gray, as if it were a shadow. initial = NodePath('initial%i'%self.objectShadowId) initial.setColor( *SHADOWCOLOR ) initial.setTextureOff(2) self.camera.setInitialState(initial.getState()) # Use an orthographic lens for this camera instead of the # usual perspective lens. An orthographic lens is better to # simulate sunlight, which is (almost) orthographic. We set # the film size large enough to render a typical avatar (but # not so large that we lose detail in the texture). self.lens = OrthographicLens() self.lens.setFilmSize(self.filmSize, self.filmSize) self.camera.setLens(self.lens) # Finally, we'll need a unique TextureStage to apply this # shadow texture to the world. self.stage = TextureStage('shadow%i'%self.objectShadowId) # Make sure the shadowing object doesn't get its own shadow # applied to it. self.objectPath.setTextureOff(self.stage) # the object which will receive shadows self.setGround( groundPath ) def setLightPos( self, lightPos ): """ sets the position of the light """ self.cameraPath.setPos( lightPos ) self.cameraPath.lookAt( self.lightPath, 0,0,0 ) def setGround(self, groundPath): """ Specifies the part of the world that is to be considered the ground: this is the part onto which the rendered texture will be applied. """ if self.groundPath: self.groundPath.clearProjectTexture(self.stage) self.groundPath = groundPath self.groundPath.projectTexture(self.stage, self.tex, self.cameraPath) def clear(self): """ Undoes the effect of the ShadowCaster. """ if self.groundPath: self.groundPath.clearProjectTexture(self.stage) self.groundPath = None if self.lightPath: self.lightPath.detachNode() self.lightPath = None if self.cameraPath: self.cameraPath.detachNode() self.cameraPath = None self.camera = None self.lens = None if self.buffer: base.graphicsEngine.removeWindow(self.buffer) self.tex = None self.buffer = None
def __init__(self, scene_file, pedestrian_file, dir, mode): ShowBase.__init__(self) self.globalClock = ClockObject.getGlobalClock() self.globalClock.setMode(ClockObject.MSlave) self.directory = dir self.model = Model(dir) self.loadScene(scene_file) self.loadPedestrians(pedestrian_file) #self.cam_label = OST("Top Down", pos=(0, 0.95), fg=(1,1,1,1), # scale=0.05, mayChange=True) #self.time_label = OST("Time: 0.0", pos=(-1.3, 0.95), fg=(1,1,1,1), # scale=0.06, mayChange=True, align=TextNode.ALeft) #self.accept("arrow_right", self.changeCamera, [1]) #self.accept("arrow_left", self.changeCamera, [-1]) self.accept("escape", self.exit) self.accept("aspectRatioChanged", self.setAspectRatio) self.accept("window-event", self.windowChanged) new_window_fbp = FrameBufferProperties.getDefault() new_window_properties = WindowProperties.getDefault() self.new_window = base.graphicsEngine.makeOutput( base.pipe, 'Top Down View Window', 0, new_window_fbp, new_window_properties, GraphicsPipe.BFRequireWindow) self.new_window_display_region = self.new_window.makeDisplayRegion() #base.disableMouse() lens = OrthographicLens() lens.setFilmSize(1500, 1500) lens.setNearFar(-5000, 5000) self.default_camera = render.attachNewNode(Camera("top down")) self.default_camera.node().setLens(lens) #self.default_camera.setPosHpr(Vec3( -75, 0, 2200), Vec3(0, -90, 0)) self.default_camera.setPosHpr(Vec3(-75, 0, 0), Vec3(0, -90, 0)) #self.new_window = base.openWindow() self.display_regions = [] self.display_regions.append(self.new_window_display_region) self.display_regions.append( base.win.makeDisplayRegion(0, 0.32, 0.52, 1)) self.display_regions.append( base.win.makeDisplayRegion(0.34, 0.66, 0.52, 1)) self.display_regions.append( base.win.makeDisplayRegion(0.68, 1, 0.52, 1)) self.display_regions.append( base.win.makeDisplayRegion(0, 0.32, 0, 0.48)) self.display_regions.append( base.win.makeDisplayRegion(0.34, 0.66, 0, 0.48)) self.display_regions.append( base.win.makeDisplayRegion(0.68, 1, 0, 0.48)) self.display_regions[0].setCamera(self.default_camera) self.border_regions = [] self.border_regions.append( base.win.makeDisplayRegion(0.32, 0.34, 0.52, 1)) self.border_regions.append( base.win.makeDisplayRegion(0.66, 0.68, 0.52, 1)) self.border_regions.append(base.win.makeDisplayRegion( 0, 1, 0.48, 0.52)) self.border_regions.append( base.win.makeDisplayRegion(0.32, 0.34, 0, 0.48)) self.border_regions.append( base.win.makeDisplayRegion(0.66, 0.68, 0, 0.48)) for i in range(0, len(self.border_regions)): border_region = self.border_regions[i] border_region.setClearColor(VBase4(0, 0, 0, 1)) border_region.setClearColorActive(True) border_region.setClearDepthActive(True) #self.setCamera(0) self.controller = Controller(self, mode) self.taskMgr.add(self.updateCameraModules, "Update Camera Modules", 80) self.globalClock.setFrameTime(0.0) self.width = WIDTH self.height = HEIGHT props = WindowProperties() props.setTitle('Virtual Vision Simulator') base.win.requestProperties(props) """new_window_2d_display_region = self.new_window.makeDisplayRegion() new_window_2d_display_region.setSort(20) new_window_camera_2d = NodePath(Camera('2d camera of new window')) lens_2d = OrthographicLens() lens_2d.setFilmSize(2, 2) lens_2d.setNearFar(-1000, 1000) new_window_camera_2d.node().setLens(lens_2d) new_window_render_2d = NodePath('render2d of new window') new_window_render_2d.setDepthTest(False) new_window_render_2d.setDepthWrite(False) new_window_camera_2d.reparentTo(new_window_render_2d) new_window_2d_display_region.setCamera(new_window_camera_2d)""" """aspectRatio = base.getAspectRatio() self.new_window_aspect2d = new_window_render_2d.attachNewNode(PGTop('Aspect2d of new window')) self.new_window_aspect2d.setScale(1.0 / aspectRatio, 1.0, 1.0)""" render.analyze()
class GXOStar(GXOBase): def __init__(self, parent=render, pos=Vec3(50,0,0)): GXOBase.__init__(self, parent, pos) self._initializeFlare() 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') ## this function returns the aspect2d position of a light source, if it enters the cameras field of view def _get2D(self, nodePath): #get the position of the light source relative to the cam p3d = base.cam.getRelativePoint(nodePath, Point3(0,0,0)) p2d = Point2() #project the light source into the viewing plane and return 2d coordinates, if it is in the visible area(read: not behind the cam) if base.cam.node().getLens().project(p3d, p2d): return p2d return None def _getObscured(self, color): # This originally looked for the radius of the light but that caused # assertion errors. Now I use the radius of the hdr model. bounds = self.starcard.getBounds() #print ("bounds=%s rad=%s"%(bounds,bounds.getRadius())) if not bounds.isEmpty(): r = bounds.getRadius() # Setting the film size sets the field-of-view and the aspect ratio # Maybe this should be done with setAspectRation() and setFov() self.ortlens.setFilmSize(r * self.radius, r * self.radius) # Point the flarecamera at the sun so we can determine if anything # is obscurring the sun self.flarecamera.lookAt(self.baseNode) # Renders the next frame in all the registered windows, and flips # all of the frame buffers. This will populate flaretexture since # it's attached to the flarebuffer. # Save the rendered frame in flaredata base.graphicsEngine.renderFrame() self.flaretexture.store(self.flaredata) #print ("flaredata=%s | color=%s"%(self.flaredata.getXel(5,5), color)) # Initialize the obscured factor obscured = 100.0 color = VBase3D(color[0],color[1],color[2]) for x in xrange(0,9): for y in xrange(0,9): if color.almostEqual(self.flaredata.getXel(x,y), self.threshold): obscured -= 1.0 else: obscured = 0 return obscured def _flareTask(self, task): #going through the list of lightNodePaths #for index in xrange(0, len(self.lightNodes)): pos2d = self._get2D(self.sunlight) #if the light source is visible from the cam's point of view, # display the lens-flare if pos2d: #print ("Flare visible") # The the obscured factor obscured = self._getObscured(self.suncardcolor) # Scale it to [0,1] self.obscured = obscured/100 ##print obscured # Length is the length of the vector that goes from the screen # middle to the pos of the light. The length gets smaller the # closer the light is to the screen middle, however, since # length is used to calculate the brightness of the effect we # actually need an inverse behaviour, since the brightness # will be greates when center of screen= pos of light length = math.sqrt(pos2d.getX()*pos2d.getX()+pos2d.getY()*pos2d.getY()) invLength= 1.0-length*2 # Subtract the obscured factor from the inverted distence and # we have a value that simulates the power of the flare #brightness flarePower=invLength-self.obscured #print("light pos=%s | length=%s"%(pos2d,length)) print("obs=%s | length=%s | inv=%s | pow=%s"%(self.obscured,length,invLength,flarePower)) # Clamp the flare power to some values if flarePower < 0 and self.obscured > 0: flarePower = 0.0 if flarePower < 0 and self.obscured <= 0: flarePower = 0.3 if flarePower > 1 : flarePower = 1 print("flarepower=%s"%(flarePower)) # if self.obscured >= 0.8: self.texcardNP.find('**/Sun:starburstNode').hide() else: self.texcardNP.find('**/Sun:starburstNode').show() #drawing the lens-flare effect... r= self.suncolor.getX() g= self.suncolor.getY() b= self.suncolor.getZ() r = math.sqrt(r*r+length*length) * self.strength g = math.sqrt(g*g+length*length) * self.strength b = math.sqrt(b*b+length*length) * self.strength print("%s,%s,%s"%(r,g,b)) # if self.obscured > 0.19: a = self.obscured - 0.2 else: a = 0.4 - flarePower # if a < 0 : a = 0 if a > 0.8 : a = 0.8 # self.hdr.setColor(r,g,b,0.8-a) self.hdr.setR(90*length) self.texcardNP.find('**/Sun:starburstNode').setColor(r,g,b,0.5+length) self.hdr.setPos(pos2d.getX(),0,pos2d.getY()) self.hdr.setScale(8.5+(5*length)) vecMid = Vec2(self.mid2d.getX(), self.mid2d.getZ()) vec2d = Vec2(vecMid-pos2d) vec3d = Vec3(vec2d.getX(), 0, vec2d.getY()) self.starburst_0.setPos(self.hdr.getPos()-(vec3d*10)) self.starburst_1.setPos(self.hdr.getPos()-(vec3d*5)) self.starburst_2.setPos(self.hdr.getPos()-(vec3d*10)) self.texcardNP.show() #print "a",a else: #hide the lens-flare effect for a light source, if it is not visible... self.texcardNP.hide() return Task.cont
class GXOStar(GXOBase): def __init__(self, parent=render, pos=Vec3(50, 0, 0)): GXOBase.__init__(self, parent, pos) self._initializeFlare() 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') ## this function returns the aspect2d position of a light source, if it enters the cameras field of view def _get2D(self, nodePath): #get the position of the light source relative to the cam p3d = base.cam.getRelativePoint(nodePath, Point3(0, 0, 0)) p2d = Point2() #project the light source into the viewing plane and return 2d coordinates, if it is in the visible area(read: not behind the cam) if base.cam.node().getLens().project(p3d, p2d): return p2d return None def _getObscured(self, color): # This originally looked for the radius of the light but that caused # assertion errors. Now I use the radius of the hdr model. bounds = self.starcard.getBounds() #print ("bounds=%s rad=%s"%(bounds,bounds.getRadius())) if not bounds.isEmpty(): r = bounds.getRadius() # Setting the film size sets the field-of-view and the aspect ratio # Maybe this should be done with setAspectRation() and setFov() self.ortlens.setFilmSize(r * self.radius, r * self.radius) # Point the flarecamera at the sun so we can determine if anything # is obscurring the sun self.flarecamera.lookAt(self.baseNode) # Renders the next frame in all the registered windows, and flips # all of the frame buffers. This will populate flaretexture since # it's attached to the flarebuffer. # Save the rendered frame in flaredata base.graphicsEngine.renderFrame() self.flaretexture.store(self.flaredata) #print ("flaredata=%s | color=%s"%(self.flaredata.getXel(5,5), color)) # Initialize the obscured factor obscured = 100.0 color = VBase3D(color[0], color[1], color[2]) for x in xrange(0, 9): for y in xrange(0, 9): if color.almostEqual(self.flaredata.getXel(x, y), self.threshold): obscured -= 1.0 else: obscured = 0 return obscured def _flareTask(self, task): #going through the list of lightNodePaths #for index in xrange(0, len(self.lightNodes)): pos2d = self._get2D(self.sunlight) #if the light source is visible from the cam's point of view, # display the lens-flare if pos2d: #print ("Flare visible") # The the obscured factor obscured = self._getObscured(self.suncardcolor) # Scale it to [0,1] self.obscured = obscured / 100 ##print obscured # Length is the length of the vector that goes from the screen # middle to the pos of the light. The length gets smaller the # closer the light is to the screen middle, however, since # length is used to calculate the brightness of the effect we # actually need an inverse behaviour, since the brightness # will be greates when center of screen= pos of light length = math.sqrt(pos2d.getX() * pos2d.getX() + pos2d.getY() * pos2d.getY()) invLength = 1.0 - length * 2 # Subtract the obscured factor from the inverted distence and # we have a value that simulates the power of the flare #brightness flarePower = invLength - self.obscured #print("light pos=%s | length=%s"%(pos2d,length)) print("obs=%s | length=%s | inv=%s | pow=%s" % (self.obscured, length, invLength, flarePower)) # Clamp the flare power to some values if flarePower < 0 and self.obscured > 0: flarePower = 0.0 if flarePower < 0 and self.obscured <= 0: flarePower = 0.3 if flarePower > 1: flarePower = 1 print("flarepower=%s" % (flarePower)) # if self.obscured >= 0.8: self.texcardNP.find('**/Sun:starburstNode').hide() else: self.texcardNP.find('**/Sun:starburstNode').show() #drawing the lens-flare effect... r = self.suncolor.getX() g = self.suncolor.getY() b = self.suncolor.getZ() r = math.sqrt(r * r + length * length) * self.strength g = math.sqrt(g * g + length * length) * self.strength b = math.sqrt(b * b + length * length) * self.strength print("%s,%s,%s" % (r, g, b)) # if self.obscured > 0.19: a = self.obscured - 0.2 else: a = 0.4 - flarePower # if a < 0: a = 0 if a > 0.8: a = 0.8 # self.hdr.setColor(r, g, b, 0.8 - a) self.hdr.setR(90 * length) self.texcardNP.find('**/Sun:starburstNode').setColor( r, g, b, 0.5 + length) self.hdr.setPos(pos2d.getX(), 0, pos2d.getY()) self.hdr.setScale(8.5 + (5 * length)) vecMid = Vec2(self.mid2d.getX(), self.mid2d.getZ()) vec2d = Vec2(vecMid - pos2d) vec3d = Vec3(vec2d.getX(), 0, vec2d.getY()) self.starburst_0.setPos(self.hdr.getPos() - (vec3d * 10)) self.starburst_1.setPos(self.hdr.getPos() - (vec3d * 5)) self.starburst_2.setPos(self.hdr.getPos() - (vec3d * 10)) self.texcardNP.show() #print "a",a else: #hide the lens-flare effect for a light source, if it is not visible... self.texcardNP.hide() return Task.cont