def __init__(self): self.keyMap = { "arrow_left": 0, "arrow_right": 0, "arrow_up": 0, "arrow_down": 0, "cam-left": 0, "cam-right": 0, "make-bunny": 0, "do-something": 0, "ignore": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) # Track all of the bunnies self.bunnies = [] # Post the instructions self.title = addTitle("Keyboard Roaming") self.inst1 = addInstructions(0.95, "[Shift+ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst4 = addInstructions(0.75, "[Down Arrow]: Run Ralph Backward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(0.3) self.ralph.setPos(ralphStartPos) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Shift+ESC key exits self.accept("shift-escape", sys.exit) # Tke keyboard is divided into six sections or tiles: # # 1 2 # +----------------+ +-------------+ # | f1 ... F5 | | F6 ... F12 | # +----------------+ +-------------+ # # 3 4 # +----------------+ +-------------------------+ # | ` 1 2 3 4 5 6 | | 7 8 9 0 - = BACKSPACE | # | Q W E R T Y | | Y U I O P [ ] \ | # | A S D F G | | H J K L ; ' ENTER | # | Z X C V B | | N M , . / | # | CTRL WIN ALT | | SPACE ALT WIN MENU CTRL | # +----------------+ +-------------------------+ # # 5 # +----------------------+ # | PRT SCR PAUSE | # | INSERT HOME PAGEUP | # | DELETE END PAGEDOWN | # +----------------------+ # 6 # +----------------------+ # | UP LEFT DOWN RIGHT | # +----------------------+ # Section1 = ["f1", "f2", "f3", "f4", "f5"] Section2 = ["f6", "f7", "f8", "f9", "f10", "f11", "f12"] Section3 = [ "`", "1", "2", "3", "4", "5", "6", "q", "w", "e", "r", "t", "y", "a", "s", "d", "f", "g", "lshift", "z", "x", "c", "v", "b" ] Section4 = [ "7", "8", "9", "0", "backspace", "y", "u", "i", "o", "p", "[", "]", "\\", "h", "j", "k", "l", ";", "'", "enter", "n", "m", ",", ".", "/", "rshift" ] Section5 = [ "print_screen", "scroll_lock", "pause", "insert", "home", "page_up", "delete", "end", "page_down" ] Section6 = ["arrow_left", "arrow_right", "arrow_up", "arrow_down"] # Map each section action = "cam-left" for k in Section1: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "cam-right" for k in Section2: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "arrow_up" for k in Section3: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "arrow_down" for k in Section4: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "make-bunny" for k in Section5: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) for k in Section6: self.accept(k, self.setKey, [k, 1]) self.accept("shift-" + k, self.setKey, [k, 1]) self.accept(k + "-up", self.setKey, [k, 0]) self.accept("shift-" + k + "-up", self.setKey, [k, 0]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 1000) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # Set up some sounds self.runSound = base.loader.loadSfx( "sounds/54779__bevangoldswain__running-hard-surface.wav") self.bumpSound = base.loader.loadSfx( "sounds/31126__calethos__bump.wav") self.spawnSound = base.loader.loadSfx( "sounds/51710__bristolstories__u-chimes3.mp3")
def removeNode(self, node): self.world.removeRigidBody(node) if node == self.sphere: self.sphere = None if node == self.box: self.box = None np = NodePath(node) np.removeNode()
#: :meth:`panda3d.core.ClockObject.getGlobalClock()`. globalClock = ClockObject.getGlobalClock() #: See :meth:`panda3d.core.ConfigPageManager.getGlobalPtr()`. cpMgr = ConfigPageManager.getGlobalPtr() #: See :meth:`panda3d.core.ConfigVariableManager.getGlobalPtr()`. cvMgr = ConfigVariableManager.getGlobalPtr() #: See :meth:`panda3d.core.PandaSystem.getGlobalPtr()`. pandaSystem = PandaSystem.getGlobalPtr() #: The root of the 2-D scene graph. The coordinate system of this node runs #: from -1 to 1, with the X axis running from left to right and the Z axis from #: bottom to top. render2d = NodePath("render2d") #: The root of the 2-D scene graph used for GUI rendering. Unlike render2d, #: which may result in elements being stretched in windows that do not have a #: square aspect ratio, this node is scaled automatically to ensure that nodes #: parented to it do not appear stretched. aspect2d = render2d.attachNewNode(PGTop("aspect2d")) #: A dummy scene graph that is not being rendered by anything. hidden = NodePath("hidden") # Set direct notify categories now that we have config directNotify.setDconfigLevels() def run():
def loadPlaceGeom(self, zoneId): self.notify.info('loadPlaceGeom: %s' % zoneId) zoneId = zoneId - zoneId % 100 if zoneId == ToontownGlobals.SellbotHQ: self.geom = loader.loadModel(self.cogHQExteriorModelPath) dgLinkTunnel = self.geom.find('**/Tunnel1') dgLinkTunnel.setName('linktunnel_dg_5316_DNARoot') factoryLinkTunnel = self.geom.find('**/Tunnel2') factoryLinkTunnel.setName('linktunnel_sellhq_11200_DNARoot') cogSignModel = loader.loadModel( 'phase_4/models/props/sign_sellBotHeadHQ') cogSign = cogSignModel.find('**/sign_sellBotHeadHQ').copyTo( NodePath()) cogSign.flattenStrong() cogSignModel.removeNode() cogSignSF = 23 dgSign = cogSign.copyTo(dgLinkTunnel) dgSign.setPosHprScale(0.0, -291.5, 29, 180.0, 0.0, 0.0, cogSignSF, cogSignSF, cogSignSF * aspectSF) dgSign.node().setEffect(DecalEffect.make()) dgText = DirectGui.OnscreenText(text=TTLocalizer.DaisyGardens[-1], font=ToontownGlobals.getSuitFont(), pos=(0, -0.3), scale=TTLocalizer.SCHQLdgText, mayChange=False, parent=dgSign) dgText.setDepthWrite(0) dgText.flattenStrong() factorySign = cogSign.copyTo(factoryLinkTunnel) factorySign.setPosHprScale(148.625, -155, 27, -90.0, 0.0, 0.0, cogSignSF, cogSignSF, cogSignSF * aspectSF) factorySign.node().setEffect(DecalEffect.make()) factoryTypeText = DirectGui.OnscreenText( text=TTLocalizer.Sellbot, font=ToontownGlobals.getSuitFont(), pos=TTLocalizer.SellbotFactoryPosPart1, scale=TTLocalizer.SellbotFactoryScalePart1, mayChange=False, parent=factorySign) factoryTypeText.setDepthWrite(0) factoryTypeText.flattenStrong() factoryText = DirectGui.OnscreenText( text=TTLocalizer.Factory, font=ToontownGlobals.getSuitFont(), pos=TTLocalizer.SellbotFactoryPosPart2, scale=TTLocalizer.SellbotFactoryScalePart2, mayChange=False, parent=factorySign) factoryText.setDepthWrite(0) factoryText.flattenStrong() doors = self.geom.find('**/doors') door0 = doors.find('**/door_0') door1 = doors.find('**/door_1') door2 = doors.find('**/door_2') door3 = doors.find('**/door_3') for door in [door0, door1, door2, door3]: doorFrame = door.find('**/doorDoubleFlat/+GeomNode') door.find('**/doorFrameHoleLeft').wrtReparentTo(doorFrame) door.find('**/doorFrameHoleRight').wrtReparentTo(doorFrame) doorTrigger = door.find('**/door_trigger*') doorTrigger.setY(doorTrigger.getY() - 1.5) doorFrame.node().setEffect(DecalEffect.make()) doorFrame.flattenStrong() door.flattenMedium() cogSign.removeNode() self.geom.flattenMedium() elif zoneId == ToontownGlobals.SellbotFactoryExt: self.geom = loader.loadModel(self.factoryExteriorModelPath) factoryLinkTunnel = self.geom.find('**/tunnel_group2') factoryLinkTunnel.setName('linktunnel_sellhq_11000_DNARoot') factoryLinkTunnel.find('**/tunnel_sphere').setName( 'tunnel_trigger') cogSignModel = loader.loadModel( 'phase_4/models/props/sign_sellBotHeadHQ') cogSign = cogSignModel.find('**/sign_sellBotHeadHQ').copyTo( NodePath()) cogSign.flattenStrong() cogSignModel.removeNode() cogSignSF = 23 elevatorSignSF = 15 hqSign = cogSign.copyTo(factoryLinkTunnel) hqSign.setPosHprScale(0.0, -353, 27.5, -180.0, 0.0, 0.0, cogSignSF, cogSignSF, cogSignSF * aspectSF) hqSign.node().setEffect(DecalEffect.make()) hqTypeText = DirectGui.OnscreenText( text=TTLocalizer.Sellbot, font=ToontownGlobals.getSuitFont(), pos=(0, -0.25), scale=0.075, mayChange=False, parent=hqSign) hqTypeText.setDepthWrite(0) hqTypeText.flattenStrong() hqText = DirectGui.OnscreenText(text=TTLocalizer.Headquarters, font=ToontownGlobals.getSuitFont(), pos=(0, -0.34), scale=0.1, mayChange=False, parent=hqSign) hqText.setDepthWrite(0) hqText.flattenStrong() frontDoor = self.geom.find('**/doorway1') fdSign = cogSign.copyTo(frontDoor) fdSign.setPosHprScale(62.74, -87.99, 17.26, 2.72, 0.0, 0.0, elevatorSignSF, elevatorSignSF, elevatorSignSF * aspectSF) fdSign.node().setEffect(DecalEffect.make()) fdTypeText = DirectGui.OnscreenText( text=TTLocalizer.Factory, font=ToontownGlobals.getSuitFont(), pos=(0, -0.25), scale=TTLocalizer.SCHQLfdTypeText, mayChange=False, parent=fdSign) fdTypeText.setDepthWrite(0) fdTypeText.flattenStrong() fdText = DirectGui.OnscreenText( text=TTLocalizer.SellbotFrontEntrance, font=ToontownGlobals.getSuitFont(), pos=(0, -0.34), scale=TTLocalizer.SCHQLdgText, mayChange=False, parent=fdSign) fdText.setDepthWrite(0) fdText.flattenStrong() sideDoor = self.geom.find('**/doorway2') sdSign = cogSign.copyTo(sideDoor) sdSign.setPosHprScale(-164.78, 26.28, 17.25, -89.89, 0.0, 0.0, elevatorSignSF, elevatorSignSF, elevatorSignSF * aspectSF) sdSign.node().setEffect(DecalEffect.make()) sdTypeText = DirectGui.OnscreenText( text=TTLocalizer.Factory, font=ToontownGlobals.getSuitFont(), pos=(0, -0.25), scale=0.075, mayChange=False, parent=sdSign) sdTypeText.setDepthWrite(0) sdTypeText.flattenStrong() sdText = DirectGui.OnscreenText( text=TTLocalizer.SellbotSideEntrance, font=ToontownGlobals.getSuitFont(), pos=(0, -0.34), scale=0.1, mayChange=False, parent=sdSign) sdText.setDepthWrite(0) sdText.flattenStrong() cogSign.removeNode() self.geom.flattenMedium() elif zoneId == ToontownGlobals.SellbotLobby: if base.config.GetBool('want-qa-regression', 0): self.notify.info('QA-REGRESSION: COGHQ: Visit SellbotLobby') self.geom = loader.loadModel(self.cogHQLobbyModelPath) front = self.geom.find('**/frontWall') front.node().setEffect(DecalEffect.make()) door = self.geom.find('**/door_0') parent = door.getParent() door.wrtReparentTo(front) doorFrame = door.find('**/doorDoubleFlat/+GeomNode') door.find('**/doorFrameHoleLeft').wrtReparentTo(doorFrame) door.find('**/doorFrameHoleRight').wrtReparentTo(doorFrame) doorFrame.node().setEffect(DecalEffect.make()) door.find('**/leftDoor').wrtReparentTo(parent) door.find('**/rightDoor').wrtReparentTo(parent) self.geom.flattenStrong() else: self.notify.warning('loadPlaceGeom: unclassified zone %s' % zoneId) CogHQLoader.CogHQLoader.loadPlaceGeom(self, zoneId)
def __init__(self): self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) self.speed = 0 self.font_digital = loader.loadFont('font/SFDigitalReadout-Heavy.ttf') # Speedometer self.speed_img = OnscreenImage(image="models/speedometer.png", scale=.5, pos=(1.1, 0, -.95)) self.speed_img.setTransparency(TransparencyAttrib.MAlpha) OnscreenText(text="km\n/h", style=1, fg=(1, 1, 1, 1), font=self.font_digital, scale=.07, pos=(1.25, -.92)) # Display Speed self.display_speed = OnscreenText(text=str(self.speed), style=1, fg=(1, 1, 1, 1), pos=(1.3, -0.95), align=TextNode.ARight, scale=.07, font=self.font_digital) # Health Bar self.bars = {'H': 100, 'EH': 0, 'A': 0} # bk_text = "This is my Demo" # self.textObject = OnscreenText(text = bk_text, pos = (0.55,-0.05),scale = 0.07,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=1) self.Health_bar = DirectWaitBar(text="", value=100, pos=(0.280, 0, 0.475), barColor=(1, 0, 0, 1), frameSize=(0, .705, .3, .35)) self.EHealth_bar = DirectWaitBar(text="", value=0, pos=(1, 0, 0.475), barColor=(0, 1, 0, 1), frameSize=(0, .23, .3, .35), range=50) self.Armour_bar = DirectWaitBar(text="", value=0, pos=(.43, 0, .593), barColor=(159, 0, 255, 1), frameSize=(0, .8, .3, .35)) self.Health = DirectWaitBar(text="", value=100, barColor=(1, 0, 0, 1), frameSize=(-1, 1, .3, .5), scale=2) # create a frame # myFrame = DirectFrame(frameColor=(1, 0, 0, 1), # frameSize=(0, .8, 0, .2)) # self.bar = DirectWaitBar(text = "hi", # value = 0, # range = 500, # pos = ( 0,0,0), # barColor = (0.97,0,0,1), # frameSize = (-0.3,0.3,0.5,0.8), # text_mayChange = 1, # text_shadow =(0,0,0,0.8), # text_fg = (0.9,0.9,0.9,1), # text_scale = 0.025, # text_pos = (0,0.01,0)) def getHealthStatus(): return self.bars def displayBars(): health = getHealthStatus() self.Health_bar['value'] = health['H'] self.EHealth_bar['value'] = health['EH'] self.Armour_bar['value'] = health['A'] self.Health['value'] = health['H'] def armourPickup(): self.bars['A'] += 25 displayBars() def healthPickup(): self.bars['EH'] += 25 displayBars() def decHealth(): self.bars['H'] -= 10 displayBars() def initialiseSound(audioManager): """Start the engine sound and set collision sounds""" # Set sounds to play for collisions # self.collisionSound = CollisionSound( # nodePath=self.np, # sounds=["data/sounds/09.wav"], # thresholdForce=600.0, # maxForce=800000.0) # np - nodePath self.engineSound = audioManager.loadSfx("sound/engine.wav") audioManager.attachSoundToObject(self.engineSound, self.ralph) self.engineSound.setLoop(True) self.engineSound.setPlayRate(0.6) self.engineSound.play() # self.gearSpacing = (self.specs["sound"]["maxExpectedRotationRate"] / # self.specs["sound"]["numberOfGears"]) self.gearSpacing = (150 / 4) self.reversing = False # Post the instructions self.frame = OnscreenImage(image="models/gframe.png", pos=(0, 0, 0), scale=(1.25, 1, 1)) self.frame.setTransparency(TransparencyAttrib.MAlpha) # self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") # Set up the environment # self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.environ.setScale(100, 100, 1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) # Create the main character, Ralph self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(0, 0, 0) # # Load and place the model # self.eNode = render.attachNewNode('enemyBaseNode') # self.eNode.setPos( 0,0,0 ) # self.model = loader.loadModel( 'models/ralph' ) # self.model.reparentTo( self.eNode ) # # Setup the rest of what the enemy needs # self.setupHealthBar() # self.Health.setBillboardAxis() # self.Health.setBillboardPointWorld() # self.Health.setBillboardPointEye() # self.Health.setLightOff() self.Health.setPos(0, 0, 5) self.Health.setBillboardPointEye() self.Health.setBin('fixed', 0) self.Health.setDepthWrite(False) self.Health.reparentTo(self.ralph) # myFrame.setPos(0, 0, 8) # myFrame.setBillboardPointEye() # myFrame.reparentTo(self.ralph) # self.Health.clearBillboard() # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) self.accept("h", decHealth) self.accept("j", healthPickup) self.accept("k", armourPickup) taskMgr.add(self.move, "moveTask") taskMgr.doMethodLater(.1, self.show_speed, 'updateSpeed') # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # Create an audio manager. This is attached to the camera for # player 1, so sounds close to other players might not be very # loud self.audioManager = Audio3DManager.Audio3DManager( base.sfxManagerList[0], base.camera) # Distance should be in m, not feet self.audioManager.setDistanceFactor(3.28084) initialiseSound(self.audioManager) displayBars()
def __init__(self, camera=None): #camera setup self.camera = camera if self.camera == None: self.camera = base.camera #XXX note, when moving cam target we need to make sure the camera doesnt move too... cameraBase = GeomNode('cameraBase') #utility node for pan targetGeom = makeCameraTarget() cameraBase.addGeom(targetGeom) self.cameraBase = render.attachNewNode(cameraBase) #self.cameraBase.setTwoSided(True) #backface culling issue with my tristrip fail self.cameraTarget = NodePath( 'cameraTarget') #utility node for rot, zoom, reattach self.cameraTarget.reparentTo(self.cameraBase) #self.cameraTarget.reparentTo(render) self.camera.reparentTo(self.cameraTarget) self.track = self.camera.attachNewNode( 'track') #hack for pointing vector self.track.setPos(LVecBase3f(0, 50, 0)) #nn = GeomNode('helper') #ng = makeCameraTarget() #nn.addGeom(targetGeom) #self.track.attachNewNode(nn) #keybind setup self.__ends__ = defaultdict(list) #self.accept("escape", sys.exit) #no, exit_cleanup will handle this... for function_name, key in keybinds['view'].items(): #self.accept(key,taskMgr.add,(getattr(self,function),function+'Task')) self.accept( key, self.makeTask, [function_name ]) # TODO split out functions that don't require tasks keytest = key.split('-')[-1] #print(keytest) if keytest in {'mouse1', 'mouse2', 'mouse3'}: self.addEndTask(keytest, function_name) self.accept(keytest + '-up', self.endTask, [keytest, function_name]) #gains #TODO tweak me! self.XGAIN = .01 self.YGAIN = .01 #window setup self.getWindowSize() self.accept('window-event', self.getWindowSize) #self.accept('mouse1') #mouse 1 by itself does selection? #self.accpet('mouse3') #pan #self.accpet('mouse2') #--camera moves relatvie to arbitrary origin-- #pan in plane #zoom #this needs to be on a log scale, linear is balls #rotate #--camera in place-- #roll camera in place #yaw #pitch #look at selection/origin/center of mass of #--camera lense changes-- #fov (for perspective) #perspective/orthographic #--worldcraft-- #z mode wasd + mouse to orient for zooming #--selection functions we need to leave space for-- #drop origin if we don't have something selected #click select #drag select, logial intersec #right click for menu self.__ch__ = None self.__cp__ = None self.__cr__ = None self.__cth__ = None self.__ctp__ = None pass
def draw_planes(self): # draw extra planes if self._draw_planes: if self.planenodes is not None: for nodepath in self.planenodes.children: nodepath.removeNode() nodepath.clear() self.planenodes = NodePath("the Planes") self.planenodes.reparentTo(self.boxnode) start = 2 * self.box.dimensions if self._draw_box_planes: start = 0 for plane in self.box.planes[start:]: # for plane in self.box.planes[2*self.box.dimensions:]: # for plane in self.box.planes: if self.box.dimensions == 3: vertices = plane.box_intersections if not vertices: continue poly_vertices = [v[:3] for v in vertices] poly = Polygon(poly_vertices) node = poly.create_geom_node() circle_np = NodePath(node) # nodepath.reparentTo(self.render) # circle_np.reparentTo(self.boxnode) circle_np.reparentTo(self.planenodes) circle_np.setTwoSided(True) circle_np.setTransparency(TransparencyAttrib.M_dual, 1) if not plane.color: # color = (0.5, 0.5, 1) color = (random.random(), random.random(), random.random()) else: color = [c / 255 for c in plane.color] transparency = 0.3 circle_np.setColor(*color, transparency) # nodepath.setColor(0.5,0.5,1,0.3) self.draw_plane_holes(plane) for (i, j) in plane.edges: p1 = plane.box_intersections[i] p2 = plane.box_intersections[j] if self.box.dimensions < 3: p1 = self._project3d(p1) p2 = self._project3d(p2) lines = LineSegs(f"edge[{i},{j}]") # lines.setColor(1, 1, 1, 1) lines.moveTo(*p1[:3]) lines.drawTo(*p2[:3]) lines.setThickness(2) node = lines.create() circle_np = NodePath(node) # nodepath.setColor((1, 1, 1, 1)) # nodepath.reparentTo(self.render) # circle_np.reparentTo(self.boxnode) circle_np.reparentTo(self.planenodes)
def __init__(self, recipe): _Body_.__init__(self, recipe) self.path = "{}/{}".format(_path.BODIES, self.name) self.MODEL_NP = NodePath("model") self.MODEL_NP.setShaderInput("atmos_vals", LVector4f(0, 0, 0, 0)) self.__Reset()
def __init__(self): # Load the default configuration.prc. This is recommended, as it # contains some important panda options loadPrcFile("../../Config/configuration.prc") ShowBase.__init__(self) # Create a new pipeline instance self.renderPipeline = RenderingPipeline(self) # Set the base path for the pipeline. This is required as we are in # a subdirectory self.renderPipeline.getMountManager().setBasePath("../../") # Also set the write path self.renderPipeline.getMountManager().setWritePath("../../Temp/") # Load the default settings self.renderPipeline.loadSettings("../../Config/pipeline.ini") # Now create the pipeline self.renderPipeline.create() # Add a directional light dPos = Vec3(40, 40, 15) dirLight = DirectionalLight() dirLight.setPos(dPos * 1000000.0) dirLight.setShadowMapResolution(1024) dirLight.setCastsShadows(True) dirLight.setColor(Vec3(8)) self.renderPipeline.addLight(dirLight) self.renderPipeline.setScatteringSource(dirLight) self.dirLight = dirLight self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") # Set up the environment # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.environ.find("**/wall").removeNode() # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos) self.renderPipeline.setEffect(self.ralph, "Effects/Default/Default.effect", {"dynamic": True}) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) # NOTICE: It is important that your update tasks have a lower priority # than -10000 taskMgr.add(self.move, "moveTask", priority=-20000) self.accept("r", self.reloadShader) # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 1.2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 1000) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays # self.ralphGroundColNp.show() # self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring # self.cTrav.showCollisions(render) # Create some ocean self.water = ProjectedWaterGrid(self.renderPipeline) self.water.setWaterLevel(-3.0) # Create the skybox self.skybox = self.renderPipeline.getDefaultSkybox() self.skybox.reparentTo(render) self.prepareSRGB(render) self.reloadShader() self.renderPipeline.onSceneInitialized() # Add demo slider to move the sun position if self.renderPipeline.settings.displayOnscreenDebugger: self.renderPipeline.guiManager.demoSlider.node[ "command"] = self.setSunPos self.renderPipeline.guiManager.demoSlider.node["value"] = 50
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor(BACKGROUND_COLOR) # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # Create the main character playerStartPos = self.environ.find("**/start_point").getPos() self.player = Actor("models/player", {"run": "models/player-run", "walk": "models/player-walk"}) self.player.reparentTo(render) self.player.setScale(.2) self.player.setPos(playerStartPos + (0, 0, 0.5)) # Create a floater object, which floats 2 units above player. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.player) self.floater.setZ(CAMERA_TARGET_HEIGHT_DELTA) self.first_person = False def key_dn(name): return lambda: self.setKey(name, True) def key_up(name): return lambda: self.setKey(name, False) def quit(): self.destroy() def toggle_first(): self.first_person = not self.first_person # Accept the control keys for movement and rotation key_map = [ # key command action help # --- ------- ------ ---- ("escape", "esc", lambda: quit(), '[ESC]: Quit'), ("arrow_left", 'left', key_dn("left"), "[Left Arrow]: Rotate Left"), ("arrow_left-up", 'left', key_up("left"), None), ("arrow_right", 'right', key_dn("right"), "[Right Arrow]: Rotate Right"), ("arrow_right-up", 'right', key_up("right"), None), ("arrow_up", 'forward', key_dn("forward"), "[Up Arrow]: Run Forward"), ("arrow_up-up", 'forward', key_up("forward"), None), ("arrow_down", 'backward', key_dn("backward"), "[Down Arrow]: Run Backward"), ("arrow_down-up", 'backward', key_up("backward"), None), ("a", 'cam-left', key_dn("cam-left"), "[A]: Rotate Camera Left"), ("a-up", 'cam-left', key_up("cam-left"), None), ("s", 'cam-right', key_dn("cam-right"), "[S]: Rotate Camera Right"), ("s-up", 'cam-right', key_up("cam-right"), None), ('f', 'first-pers', lambda: toggle_first(), '[F]: Toggle first-person'), ] self.keyMap = {} inst = Instructions() for key, command, action, description in key_map: if command: self.setKey(command, False) self.accept(key, action) if description: inst.add(description) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera self.disableMouse() self.camera.setPos(self.player.getX(), self.player.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above player's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.playerGroundRay = CollisionRay() self.playerGroundRay.setOrigin(0, 0, 9) self.playerGroundRay.setDirection(0, 0, -1) self.playerGroundCol = CollisionNode('playerRay') self.playerGroundCol.addSolid(self.playerGroundRay) self.playerGroundCol.setFromCollideMask(CollideMask.bit(0)) self.playerGroundCol.setIntoCollideMask(CollideMask.allOff()) self.playerGroundColNp = self.player.attachNewNode(self.playerGroundCol) self.playerGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.playerGroundColNp, self.playerGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays self.playerGroundColNp.show() self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def load(self): self.notify.debug('load()') CogdoGameMovie.load(self) backgroundGui = loader.loadModel( 'phase_5/models/cogdominium/tt_m_gui_csa_flyThru') self.bg = backgroundGui.find('**/background') self.chatBubble = backgroundGui.find('**/chatBubble') self.chatBubble.setScale(6.5, 6.5, 7.3) self.chatBubble.setPos(0.32, 0, -0.78) self.bg.setScale(5.2) self.bg.setPos(0.14, 0, -0.6667) self.bg.reparentTo(aspect2d) self.chatBubble.reparentTo(aspect2d) self.frame = DirectFrame(geom=self.bg, relief=None, pos=(0.2, 0, -0.6667)) self.bg.wrtReparentTo(self.frame) self.gameTitleText = DirectLabel( parent=self.frame, text=TTLocalizer.CogdoExecutiveSuiteTitle, scale=TTLocalizer.MRPgameTitleText * 0.8, text_align=TextNode.ACenter, text_font=getSignFont(), text_fg=(1.0, 0.33, 0.33, 1.0), pos=TTLocalizer.MRgameTitleTextPos, relief=None) self.chatBubble.wrtReparentTo(self.frame) self.frame.hide() backgroundGui.removeNode() self.toonDNA = ToonDNA.ToonDNA() self.toonDNA.newToonFromProperties('dss', 'ss', 'm', 'm', 2, 0, 2, 2, 1, 8, 1, 8, 1, 14) self.toonHead = Toon.Toon() self.toonHead.setDNA(self.toonDNA) self.makeSuit('sc') self.toonHead.getGeomNode().setDepthWrite(1) self.toonHead.getGeomNode().setDepthTest(1) self.toonHead.loop('neutral') self.toonHead.setPosHprScale(-0.73, 0, -1.27, 180, 0, 0, 0.18, 0.18, 0.18) self.toonHead.reparentTo(hidden) self.toonHead.startBlink() self.clipPlane = self.toonHead.attachNewNode(PlaneNode('clip')) self.clipPlane.node().setPlane(Plane(0, 0, 1, 0)) self.clipPlane.setPos(0, 0, 2.45) self._toonDialogueSfx = loader.loadSfx( 'phase_3.5/audio/dial/AV_dog_long.ogg') self._camHelperNode = NodePath('CamHelperNode') self._camHelperNode.reparentTo(render) dialogue = TTLocalizer.CogdoElevatorRewardLaff def start(): self.frame.show() base.setCellsAvailable( base.bottomCells + base.leftCells + base.rightCells, 0) def end(): self._dialogueLabel.reparentTo(hidden) self.toonHead.reparentTo(hidden) self.frame.hide() base.setCellsAvailable( base.bottomCells + base.leftCells + base.rightCells, 1) self._stopUpdateTask() self._ival = Sequence(Func(start), Func(self.displayLine, dialogue), Wait(self.elevatorDuration), Func(end)) self._startUpdateTask() return
def create(self): # Create the voxel grid used to generate the voxels self.voxel_temp_grid = Image.create_3d("VoxelsTemp", self.voxel_resolution, self.voxel_resolution, self.voxel_resolution, "RGBA8") self.voxel_temp_grid.set_clear_color(Vec4(0)) self.voxel_temp_nrm_grid = Image.create_3d("VoxelsTemp", self.voxel_resolution, self.voxel_resolution, self.voxel_resolution, "R11G11B10") self.voxel_temp_nrm_grid.set_clear_color(Vec4(0)) # Create the voxel grid which is a copy of the temporary grid, but stable self.voxel_grid = Image.create_3d("Voxels", self.voxel_resolution, self.voxel_resolution, self.voxel_resolution, "RGBA8") self.voxel_grid.set_clear_color(Vec4(0)) self.voxel_grid.set_minfilter(SamplerState.FT_linear_mipmap_linear) # Create the camera for voxelization self.voxel_cam = Camera("VoxelizeCam") self.voxel_cam.set_camera_mask( self._pipeline.tag_mgr.get_mask("voxelize")) self.voxel_cam_lens = OrthographicLens() self.voxel_cam_lens.set_film_size(-2.0 * self.voxel_world_size, 2.0 * self.voxel_world_size) self.voxel_cam_lens.set_near_far(0.0, 2.0 * self.voxel_world_size) self.voxel_cam.set_lens(self.voxel_cam_lens) self.voxel_cam_np = Globals.base.render.attach_new_node(self.voxel_cam) self._pipeline.tag_mgr.register_camera("voxelize", self.voxel_cam) # Create the voxelization target self.voxel_target = self.create_target("VoxelizeScene") self.voxel_target.size = self.voxel_resolution self.voxel_target.prepare_render(self.voxel_cam_np) # Create the target which copies the voxel grid self.copy_target = self.create_target("CopyVoxels") self.copy_target.size = self.voxel_resolution self.copy_target.prepare_buffer() # TODO! Does not work with the new render target yet - maybe add option # to post process region for instances? self.copy_target.instance_count = self.voxel_resolution self.copy_target.set_shader_inputs(SourceTex=self.voxel_temp_grid, DestTex=self.voxel_grid) # Create the target which generates the mipmaps self.mip_targets = [] mip_size, mip = self.voxel_resolution, 0 while mip_size > 1: mip_size, mip = mip_size // 2, mip + 1 mip_target = self.create_target("GenMipmaps:" + str(mip)) mip_target.size = mip_size mip_target.prepare_buffer() mip_target.instance_count = mip_size mip_target.set_shader_inputs(SourceTex=self.voxel_grid, sourceMip=(mip - 1)) mip_target.set_shader_input("DestTex", self.voxel_grid, False, True, -1, mip, 0) self.mip_targets.append(mip_target) # Create the initial state used for rendering voxels initial_state = NodePath("VXGIInitialState") initial_state.set_attrib( CullFaceAttrib.make(CullFaceAttrib.M_cull_none), 100000) initial_state.set_attrib(DepthTestAttrib.make(DepthTestAttrib.M_none), 100000) initial_state.set_attrib(ColorWriteAttrib.make(ColorWriteAttrib.C_off), 100000) self.voxel_cam.set_initial_state(initial_state.get_state()) Globals.base.render.set_shader_inputs( voxelGridPosition=self.pta_next_grid_pos, VoxelGridDest=self.voxel_temp_grid)
def createThrowGag(self, gag): throwGag = gag.copyTo(NodePath('gag')) return throwGag
def __init__(self): self.keyMap = {"left":0, "right":0, "forward":0, "back":0, "cam-left":0, "cam-right":0} self.flag1=0 self.flag2=0 self.flag3=0 self.flag4=0 self.count=0 self.health = 100 self.points = -5 self.flagd=1 self.player_points = 0 base.win.setClearColor(Vec4(0,0,0,1)) self.mySound=base.loader.loadSfx("sounds/trial.mp3") self.mySound.play() self.title = addTitle("Bumping Cars") #Full Screen props = WindowProperties.getDefault() w=base.pipe.getDisplayWidth() h=base.pipe.getDisplayHeight() props.setSize(w,h) props.setFullscreen(True) props.setCursorHidden(True) base.win.requestProperties(props) # Load World self.environ = loader.loadModel("models/world.egg") self.environ.reparentTo(render) self.environ.setPos(0,0,0) #Load Sky self.sky = loader.loadModel("models/clouds.egg") self.sky.reparentTo(render) self.sky.setPos(60,0,-450) # Create Player Car carStartPos = self.environ.find("**/start_point").getPos() self.car = Actor("models/carnsx") self.car.reparentTo(render) self.car.setScale(0.25) #self.car.place() self.car.setPos(carStartPos) # Create Enemy Car 1 enemyCarStartPos1 = (-108,-1,-.5) self.car1 = Actor("models/enemy_cars/monstercar/carmonster") self.car1.reparentTo(render) self.car1.setScale(0.25) #self.car1.place() self.car1.setPos(enemyCarStartPos1) # Create Enemy Car 2 enemyCarStartPos2 = (-104,-26,-.02) self.car2 = Actor("models/enemy_cars/yugo/yugo") self.car2.reparentTo(render) self.car2.setScale(0.15) #self.car2.place() self.car2.setPos(enemyCarStartPos2) # Create Enemy Car 3 enemyCarStartPos3 = (-111,-26,0) self.car3 = Actor("models/enemy_cars/truck/cartruck") self.car3.reparentTo(render) self.car3.setScale(0.25) #self.car3.place() self.car3.setPos(enemyCarStartPos3) # Create Enemy Car 4 enemyCarStartPos4 = (-111,-2,-.5) self.car4 = Actor("models/enemy_cars/truck/cartruck-purple") self.car4.reparentTo(render) self.car4.setScale(0.25) #self.car4.place() self.car4.setPos(enemyCarStartPos4) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("a", self.setKey, ["cam-left",1]) self.accept("s", self.setKey, ["cam-right",1]) self.accept("arrow_up",self.setKey, ["forward",1]) self.accept("arrow_left",self.setKey, ["left",1]) self.accept("arrow_down",self.setKey, ["back",1]) self.accept("arrow_right",self.setKey, ["right",1]) self.accept("a-up", self.setKey, ["cam-left",0]) self.accept("s-up", self.setKey, ["cam-right",0]) self.accept("arrow_up-up",self.setKey, ["forward",0]) self.accept("arrow_left-up",self.setKey, ["left",0]) self.accept("arrow_right-up",self.setKey, ["right",0]) self.accept("arrow_down-up",self.setKey, ["back",0]) taskMgr.add(self.move,"moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.car.getX(),self.car.getY()+10,2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # AI self.AIworld = AIWorld(render) # AI Car 1 self.AIchar1 = AICharacter("car1",self.car1, 70, 0.1, 3) self.AIworld.addAiChar(self.AIchar1) self.AIbehaviors1 = self.AIchar1.getAiBehaviors() self.AIbehaviors1.pursue(self.car) # AI Car 2 self.AIchar2 = AICharacter("car2",self.car2, 180, 0.1, 1) self.AIworld.addAiChar(self.AIchar2) self.AIbehaviors2 = self.AIchar2.getAiBehaviors() self.AIbehaviors2.pursue(self.car4) # AI Car 3 self.AIchar3 = AICharacter("car3",self.car3, 70, 0.1, 3) self.AIworld.addAiChar(self.AIchar3) self.AIbehaviors3 = self.AIchar3.getAiBehaviors() self.AIbehaviors3.pursue(self.car) # AI Car 4 self.AIchar4 = AICharacter("car4",self.car4, 200, 0.5, 2) self.AIworld.addAiChar(self.AIchar4) self.AIbehaviors4 = self.AIchar4.getAiBehaviors() self.AIbehaviors4.pursue(self.car3) # Obstacle avoidance self.AIbehaviors1.obstacleAvoidance(1.0) self.AIworld.addObstacle(self.car2) self.AIworld.addObstacle(self.car3) self.AIworld.addObstacle(self.car4) self.AIbehaviors2.obstacleAvoidance(1.0) self.AIbehaviors3.obstacleAvoidance(1.0) self.AIbehaviors4.obstacleAvoidance(1.0) #AI World update taskMgr.add(self.AIUpdate,"AIUpdate") self.cTrav = CollisionTraverser() #self.cTrav.showCollisions(render) self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0,0,1000) self.ralphGroundRay.setDirection(0,0,-1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.carGroundColNp = self.car.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.carGroundColNp, self.ralphGroundHandler) #car1 self.car1Ray = CollisionSphere(0,0,0,4) self.car1GroundCol = CollisionNode('car1Ray') self.car1GroundCol.addSolid(self.car1Ray) self.car1GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car1GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car1GroundColNp = self.car.attachNewNode(self.car1GroundCol) self.car1GroundHandler = CollisionHandlerQueue() #self.car1GroundColNp.show() self.cTrav.addCollider(self.car1GroundColNp, self.car1GroundHandler) cnodePath = self.car1.attachNewNode(CollisionNode('cnode1')) cnodePath.node().addSolid(self.car1Ray) #cnodePath.show() #car2 self.car2Ray = CollisionSphere(0,0,0,4) self.car2GroundCol = CollisionNode('car2Ray') self.car2GroundCol.addSolid(self.car2Ray) self.car2GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car2GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car2GroundColNp = self.car.attachNewNode(self.car2GroundCol) self.car2GroundHandler = CollisionHandlerQueue() #self.car2GroundColNp.show() self.cTrav.addCollider(self.car2GroundColNp, self.car2GroundHandler) cnodePath = self.car2.attachNewNode(CollisionNode('cnode2')) cnodePath.node().addSolid(self.car2Ray) #cnodePath.show() #car3 self.car3Ray = CollisionSphere(0,0,0,4) self.car3GroundCol = CollisionNode('car3Ray') self.car3GroundCol.addSolid(self.car3Ray) self.car3GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car3GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car3GroundColNp = self.car.attachNewNode(self.car3GroundCol) self.car3GroundHandler = CollisionHandlerQueue() #self.car3GroundColNp.show() self.cTrav.addCollider(self.car3GroundColNp, self.car3GroundHandler) cnodePath = self.car3.attachNewNode(CollisionNode('cnode3')) cnodePath.node().addSolid(self.car3Ray) #cnodePath.show() #car4 self.car4Ray = CollisionSphere(0,0,0,4) self.car4GroundCol = CollisionNode('car4Ray') self.car4GroundCol.addSolid(self.car4Ray) self.car4GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car4GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car4GroundColNp = self.car.attachNewNode(self.car4GroundCol) self.car4GroundHandler = CollisionHandlerQueue() #self.car4GroundColNp.show() self.cTrav.addCollider(self.car4GroundColNp, self.car4GroundHandler) cnodePath = self.car4.attachNewNode(CollisionNode('cnode4')) cnodePath.node().addSolid(self.car4Ray) #cnodePath.show() #camera self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0,0,1000) self.camGroundRay.setDirection(0,0,-1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)
def renderQuadInto(self, name="filter-stage", mul=1, div=1, align=1, depthtex=None, colortex=None, auxtex0=None, auxtex1=None, size=None, addToList=True): """ 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) if not size: winx, winy = self.getScaledSize(mul, div, align) else: winx, winy = size depthbits = bool(depthtex != None) buffer = self.createBuffer(name, 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(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(False) if addToList: self.buffers.append(buffer) self.sizes.append((mul, div, align)) self.forceSizes.append((size is not None)) return quad else: return [quad, buffer]
def __init__(self): DebugObject.__init__(self, "LightManager") self._initArrays() # create arrays to store lights & shadow sources self.lights = [] self.shadowSources = [] self.allLightsArray = ShaderStructArray(Light, 30) self.cullBounds = None self.shadowScene = render ## SHADOW ATLAS ## # todo: move to separate class # When you change this, change also SHADOW_MAP_ATLAS_SIZE in configuration.include, # and reduce the default shadow map resolution of point lights self.shadowAtlasSize = 512 self.maxShadowMaps = 24 # When you change it , change also SHAODOW_GEOMETRY_MAX_VERTICES and # SHADOW_MAX_UPDATES_PER_FRAME in configuration.include! self.maxShadowUpdatesPerFrame = 2 self.tileSize = 128 self.tileCount = self.shadowAtlasSize / self.tileSize self.tiles = [] self.updateShadowsArray = ShaderStructArray( ShadowSource, self.maxShadowUpdatesPerFrame) self.allShadowsArray = ShaderStructArray(ShadowSource, self.maxShadowMaps) # self.shadowAtlasTex = Texture("ShadowAtlas") # self.shadowAtlasTex.setup2dTexture( # self.shadowAtlasSize, self.shadowAtlasSize, Texture.TFloat, Texture.FRg16) # self.shadowAtlasTex.setMinfilter(Texture.FTLinear) # self.shadowAtlasTex.setMagfilter(Texture.FTLinear) self.debug("Init shadow atlas with tileSize =", self.tileSize, ", tileCount =", self.tileCount) for i in xrange(self.tileCount): self.tiles.append([None for j in xrange(self.tileCount)]) # create shadow compute buffer self.shadowComputeCamera = Camera("ShadowComputeCamera") self.shadowComputeCameraNode = self.shadowScene.attachNewNode( self.shadowComputeCamera) self.shadowComputeCamera.getLens().setFov(90, 90) self.shadowComputeCamera.getLens().setNearFar(10.0, 100000.0) self.shadowComputeCameraNode.setPos(0, 0, 150) self.shadowComputeCameraNode.lookAt(0, 0, 0) self.shadowComputeTarget = RenderTarget("ShadowCompute") self.shadowComputeTarget.setSize(self.shadowAtlasSize, self.shadowAtlasSize) # self.shadowComputeTarget.setLayers(self.maxShadowUpdatesPerFrame) self.shadowComputeTarget.addRenderTexture(RenderTargetType.Depth) self.shadowComputeTarget.setDepthBits(32) self.shadowComputeTarget.setSource(self.shadowComputeCameraNode, base.win) self.shadowComputeTarget.prepareSceneRender() self.shadowComputeTarget.getInternalRegion().setSort(3) self.shadowComputeTarget.getRegion().setSort(3) self.shadowComputeTarget.getInternalRegion().setNumRegions( self.maxShadowUpdatesPerFrame + 1) self.shadowComputeTarget.getInternalRegion().setDimensions( 0, (0, 1, 0, 1)) self.shadowComputeTarget.setClearDepth(False) self.depthClearer = [] for i in xrange(self.maxShadowUpdatesPerFrame): buff = self.shadowComputeTarget.getInternalBuffer() dr = buff.makeDisplayRegion() dr.setSort(2) dr.setClearDepthActive(True) dr.setClearDepth(1.0) dr.setClearColorActive(False) dr.setDimensions(0, 0, 0, 0) self.depthClearer.append(dr) self.queuedShadowUpdates = [] # Assign copy shader self._setCopyShader() # self.shadowComputeTarget.setShaderInput("atlas", self.shadowComputeTarget.getColorTexture()) # self.shadowComputeTarget.setShaderInput( # "renderResult", self.shadowComputeTarget.getDepthTexture()) # self.shadowComputeTarget.setActive(False) # Create shadow caster shader self.shadowCasterShader = BetterShader.load( "Shader/DefaultShadowCaster.vertex", "Shader/DefaultShadowCaster.fragment", "Shader/DefaultShadowCaster.geometry") self.shadowComputeCamera.setTagStateKey("ShadowPass") initialState = NodePath("ShadowCasterState") initialState.setShader(self.shadowCasterShader, 30) self.shadowComputeCamera.setInitialState( RenderState.make(ColorWriteAttrib.make(ColorWriteAttrib.C_off), DepthWriteAttrib.make(DepthWriteAttrib.M_on), 100)) self.shadowComputeCamera.setTagState("True", initialState.getState()) self.shadowScene.setTag("ShadowPass", "True") self._createDebugTexts() self.updateShadowsArray.bindTo(self.shadowScene, "updateSources") self.updateShadowsArray.bindTo(self.shadowComputeTarget, "updateSources") self.numShadowUpdatesPTA = PTAInt.emptyArray(1) # Set initial inputs for target in [self.shadowComputeTarget, self.shadowScene]: target.setShaderInput("numUpdates", self.numShadowUpdatesPTA) self.lightingComputator = None self.lightCuller = None
def __init__(self): DirectObject.__init__(self) if ConfigVariableBool("want-pstats", False): PStatClient.connect() self.docTitle = "" self.viewportName = "" self.renderRequested = False ################################################################### # Minimal emulation of ShowBase glue code. Note we're not using # ShowBase because there's too much going on in there that assumes # too much (one camera, one lens, one aspect2d, lots of bloat). self.graphicsEngine = GraphicsEngine.getGlobalPtr() self.pipe = GraphicsPipeSelection.getGlobalPtr().makeDefaultPipe() if not self.pipe: self.notify.error("No graphics pipe is available!") return self.globalClock = ClockObject.getGlobalClock() # Since we have already started up a TaskManager, and probably # a number of tasks; and since the TaskManager had to use the # TrueClock to tell time until this moment, make sure the # globalClock object is exactly in sync with the TrueClock. trueClock = TrueClock.getGlobalPtr() self.globalClock.setRealTime(trueClock.getShortTime()) self.globalClock.tick() builtins.globalClock = self.globalClock self.loader = CogInvasionLoader(self) self.graphicsEngine.setDefaultLoader(self.loader.loader) builtins.loader = self.loader self.taskMgr = taskMgr builtins.taskMgr = self.taskMgr self.dgTrav = DataGraphTraverser() self.dataRoot = NodePath("data") self.hidden = NodePath("hidden") self.aspect2d = NodePath("aspect2d") builtins.aspect2d = self.aspect2d # Messages that are sent regardless of the active document. self.messenger = messenger builtins.messenger = self.messenger builtins.base = self builtins.hidden = self.hidden ################################################################### self.clickTrav = CollisionTraverser() # All open documents. self.documents = [] # The focused document. self.document = None TextNode.setDefaultFont( loader.loadFont("resources/models/fonts/consolas.ttf")) self.initialize()
def __init__(self, name="directional light", color=Vec4(1,1,1,1)): AssetBase.__init__(self) self.light = DL("directional light") self.light.setColor(color) self.node = NodePath(self.light)
def __init__(self): #basic init start base.disableMouse() self.wp = WindowProperties() self.wp.setCursorHidden(True) base.win.requestProperties(self.wp) cm = CardMaker("cursor") cm.setFrame(0, 0.1, -0.13, 0) self.cust_mouse = render.attachNewNode(cm.generate()) self.cust_mouse_tex = [] self.cust_mouse_tex.append( loader.loadTexture("models/cursors/blank_cursor.png")) self.cust_mouse_tex.append( loader.loadTexture("models/cursors/main_cursor.png")) self.cust_mouse.setTexture(self.cust_mouse_tex[0]) self.cust_mouse.setTransparency(TransparencyAttrib.MAlpha) self.cust_mouse.reparentTo(render2d) self.cust_mouse.setBin("gui-popup", 100) base.mouseWatcherNode.setGeometry(self.cust_mouse.node()) #text and background textVersion = OnscreenText(text="v0.0", font=arcFont, pos=(1.15, -0.95), fg=(0, 0, 0, 1), bg=(1, 1, 1, 0.8)) base.setBackgroundColor(1, 1, 1) self.curdir = (appRunner.p3dFilename.getDirname() if appRunner else "..") self.main_config = json.loads("".join([ line.rstrip().lstrip() for line in file(self.curdir + "/config.json", "rb") ])) #arrows (GENERAL) self.arrow = loader.loadModel("models/static/arrow") self.lst_arrows = [] self.c_arr = CardMaker("arrow_hide") self.c_arr.setFrame(-1, 1, -0.8, 0.6) #light ramp self.rampnode = NodePath(PandaNode("temp node")) self.rampnode.setAttrib(LightRampAttrib.makeSingleThreshold(0.1, 0.7)) self.rampnode.setShaderAuto() base.cam.node().setInitialState(self.rampnode.getState()) #ink filter self.filters = CommonFilters(base.win, base.cam) self.filterok = self.filters.setCartoonInk(separation=1) #keyboard inputs self.accept("escape", sys.exit, [0]) #lights self.lst_lghts = [] #ambient light (permanent) self.alghtnode = AmbientLight("amb light") self.alghtnode.setColor(Vec4(0.4, 0.4, 0.4, 1)) self.alght = render.attachNewNode(self.alghtnode) render.setLight(self.alght) #language recup self.langtab = self.main_config["lang"][self.main_config["lang_chx"]] self.lang = json.loads("".join([ line.rstrip().lstrip() for line in file("misc/lang/" + self.langtab[0] + ".json", "rb") ])) #common gui elements self.voile = [] self.voile.append( DirectFrame(frameSize=(-2, 2, -2, 2), frameColor=(0, 0, 0, 0.8))) self.voile[0].setBin("gui-popup", 1) self.voile[0].hide() self.voile.append(arcLabel("", (0, 0, 0.3), txtalgn=TextNode.ACenter)) self.voile[1].setBin("gui-popup", 1) self.voile[1].reparentTo(self.voile[0]) self.voile.append(arcLabel("", (0, 0, 0.17), txtalgn=TextNode.ACenter)) self.voile[2].setBin("gui-popup", 1) self.voile[2].reparentTo(self.voile[0]) self.voile.append( arcButton(self.lang["main_dialog"]["valid"], (-0.2, 0, 0), None, txtalgn=TextNode.ACenter)) self.voile[3].setBin("gui-popup", 1) self.voile[3].reparentTo(self.voile[0]) self.voile.append( arcButton(self.lang["main_dialog"]["cancel"], (0.2, 0, 0), None, txtalgn=TextNode.ACenter)) self.voile[4].setBin("gui-popup", 1) self.voile[4].reparentTo(self.voile[0]) #mouse handler self.mouse_trav = CollisionTraverser() self.mouse_hand = CollisionHandlerQueue() self.pickerNode = CollisionNode('mouseRay') self.pickerNP = camera.attachNewNode(self.pickerNode) self.pickerNode.setFromCollideMask(BitMask32.bit(1)) self.pickerRay = CollisionRay() self.pickerNode.addSolid(self.pickerRay) self.mouse_trav.addCollider(self.pickerNP, self.mouse_hand) self.pickly_node = render.attachNewNode("pickly_node") #init main scene self.scene = mainScene(self)
def __init__(self, name="ambient light", color=Vec4(0.6, 0.6, 0.8, 1)): AssetBase.__init__(self) self.light = AL("ambient light") self.light.setColor(color) self.node = NodePath(self.light)
def __init__(self): base.disableMouse() camera.setPos(0, -50, 0) # Check video card capabilities. if (base.win.getGsg().getSupportsBasicShaders() == 0): addTitle( "Toon Shader: Video driver reports that shaders are not supported." ) return # Post the instructions. self.title = addTitle( "Panda3D: Tutorial - Toon Shading with Normals-Based Inking") self.inst1 = addInstructions(0.95, "ESC: Quit") self.inst2 = addInstructions( 0.90, "Up/Down: Increase/Decrease Line Thickness") self.inst3 = addInstructions( 0.85, "Left/Right: Decrease/Increase Line Darkness") self.inst4 = addInstructions(0.80, "V: View the render-to-texture results") # This shader's job is to render the model with discrete lighting # levels. The lighting calculations built into the shader assume # a single nonattenuating point light. tempnode = NodePath(PandaNode("temp node")) tempnode.setShader(loader.loadShader("lightingGen.sha")) base.cam.node().setInitialState(tempnode.getState()) # This is the object that represents the single "light", as far # the shader is concerned. It's not a real Panda3D LightNode, but # the shader doesn't care about that. light = render.attachNewNode("light") light.setPos(30, -50, 0) # this call puts the light's nodepath into the render state. # this enables the shader to access this light by name. render.setShaderInput("light", light) # The "normals buffer" will contain a picture of the model colorized # so that the color of the model is a representation of the model's # normal at that point. normalsBuffer = base.win.makeTextureBuffer("normalsBuffer", 0, 0) normalsBuffer.setClearColor(Vec4(0.5, 0.5, 0.5, 1)) self.normalsBuffer = normalsBuffer normalsCamera = base.makeCamera(normalsBuffer, lens=base.cam.node().getLens()) normalsCamera.node().setScene(render) tempnode = NodePath(PandaNode("temp node")) tempnode.setShader(loader.loadShader("normalGen.sha")) normalsCamera.node().setInitialState(tempnode.getState()) #what we actually do to put edges on screen is apply them as a texture to #a transparent screen-fitted card drawnScene = normalsBuffer.getTextureCard() drawnScene.setTransparency(1) drawnScene.setColor(1, 1, 1, 0) drawnScene.reparentTo(render2d) self.drawnScene = drawnScene # this shader accepts, as input, the picture from the normals buffer. # it compares each adjacent pixel, looking for discontinuities. # wherever a discontinuity exists, it emits black ink. self.separation = 0.001 self.cutoff = 0.3 inkGen = loader.loadShader("inkGen.sha") drawnScene.setShader(inkGen) drawnScene.setShaderInput("separation", Vec4(self.separation, 0, self.separation, 0)) drawnScene.setShaderInput( "cutoff", Vec4(self.cutoff, self.cutoff, self.cutoff, self.cutoff)) # Panda contains a built-in viewer that lets you view the results of # your render-to-texture operations. This code configures the viewer. self.accept("v", base.bufferViewer.toggleEnable) self.accept("V", base.bufferViewer.toggleEnable) base.bufferViewer.setPosition("llcorner") # Load a dragon model and animate it. self.character = Actor() self.character.loadModel('models/nik-dragon') self.character.reparentTo(render) self.character.loadAnims({'win': 'models/nik-dragon'}) self.character.loop('win') self.character.hprInterval(15, Point3(360, 0, 0)).loop() # these allow you to change cartooning parameters in realtime self.accept("escape", sys.exit, [0]) self.accept("arrow_up", self.increaseSeparation) self.accept("arrow_down", self.decreaseSeparation) self.accept("arrow_left", self.increaseCutoff) self.accept("arrow_right", self.decreaseCutoff)
def __init__(self): ShowBase.__init__(self) base.win.set_clear_color((0, 0, 0, 0)) simplepbr.init() self.multitex_reducer = MultitexReducer() #load textures self.textures = {} texture_files = "plaid", "shirtnjeans", "jacket" for file in texture_files: self.textures[file] = loader.loadTexture( "textures/{}.png".format(file)) # camera/control self.cam_pivot = NodePath("cam pivot") self.cam_pivot.reparentTo(render) base.cam.reparent_to(self.cam_pivot) base.cam.set_pos(0, -2.7, 1.8) self.cam_pivot.set_h(180) self.cam_pivot.set_y(0.2) self.move_speed = 0.5 self.zoom_speed = 0.5 self.last_mouse = [0, 0] self.accept("wheel_up", self.zoom_in) self.accept("wheel_down", self.zoom_out) self.taskMgr.add(self.update_camera) # sliders self.sliders = {} self.y_pos = 0.9 # jan model self.jan = Actor( { "body": "jan/jan.bam", "palisa": "jan/acc/palisa-mije.bam", "hair": "jan/acc/hair_raz.bam", "clothing": "jan/clothing.bam", }, { "body": {}, "palisa": {}, "hair": {}, "clothing": {}, }) self.jan.attach("hair", "body", "head") self.jan.attach("palisa", "body", "waist") self.jan.attach("clothing", "body", "root") self.jan.play("loop") self.jan.setTwoSided(True) self.jan.hide_part("palisa") self.make_sliders(self.jan) #self.jan.flatten_strong() #self.jan.post_flatten() #self.multitex_reducer.scan(self.jan) #self.multitex_reducer.flatten(base.win) self.jan.reparent_to(render) self.jan.set_transparency(True) # talk gender = "mije" #meli self.speech = Speech(loader.loadSfx("toki-{}-a.wav".format(gender))) self.speech.say("to ki") self.speech.say("mi to ki po na") self.speech.say("mi o li n si na") self.taskMgr.add(self.speech.update) self.light_scene() render.ls() render.analyze()
def __init__(self): # 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) self.setBackgroundColor((0, 0, 0, 0)) # Preliminary capabilities check. if not self.win.getGsg().getSupportsBasicShaders(): self.t = addTitle("Firefly Demo: Video driver reports that Cg " "shaders are not supported.") return if not self.win.getGsg().getSupportsDepthTexture(): self.t = addTitle("Firefly Demo: Video driver reports that depth " "textures are not supported.") return # This algorithm uses two offscreen buffers, one of which has # an auxiliary bitplane, and the offscreen buffers share a single # depth buffer. This is a heck of a complicated buffer setup. self.modelbuffer = self.makeFBO("model buffer", 1) self.lightbuffer = self.makeFBO("light buffer", 0) # Creation of a high-powered buffer can fail, if the graphics card # doesn't support the necessary OpenGL extensions. if self.modelbuffer is None or self.lightbuffer is None: self.t = addTitle("Firefly Demo: Video driver does not support " "multiple render targets") return # Create four render textures: depth, normal, albedo, and final. # attach them to the various bitplanes of the offscreen buffers. self.texDepth = Texture() self.texDepth.setFormat(Texture.FDepthStencil) self.texAlbedo = Texture() self.texNormal = Texture() self.texFinal = Texture() self.modelbuffer.addRenderTexture(self.texDepth, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepthStencil) self.modelbuffer.addRenderTexture(self.texAlbedo, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) self.modelbuffer.addRenderTexture(self.texNormal, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0) self.lightbuffer.addRenderTexture(self.texFinal, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) # Set the near and far clipping planes. self.cam.node().getLens().setNear(50.0) self.cam.node().getLens().setFar(500.0) lens = self.cam.node().getLens() # This algorithm uses three cameras: one to render the models into the # model buffer, one to render the lights into the light buffer, and # one to render "plain" stuff (non-deferred shaded) stuff into the # light buffer. Each camera has a bitmask to identify it. self.modelMask = 1 self.lightMask = 2 self.plainMask = 4 self.modelcam = self.makeCamera(self.modelbuffer, lens=lens, scene=render, mask=self.modelMask) self.lightcam = self.makeCamera(self.lightbuffer, lens=lens, scene=render, mask=self.lightMask) self.plaincam = self.makeCamera(self.lightbuffer, lens=lens, scene=render, mask=self.plainMask) # Panda's main camera is not used. self.cam.node().setActive(0) # Take explicit control over the order in which the three # buffers are rendered. self.modelbuffer.setSort(1) self.lightbuffer.setSort(2) self.win.setSort(3) # Within the light buffer, control the order of the two cams. self.lightcam.node().getDisplayRegion(0).setSort(1) self.plaincam.node().getDisplayRegion(0).setSort(2) # By default, panda usually clears the screen before every # camera and before every window. Tell it not to do that. # Then, tell it specifically when to clear and what to clear. self.modelcam.node().getDisplayRegion(0).disableClears() self.lightcam.node().getDisplayRegion(0).disableClears() self.plaincam.node().getDisplayRegion(0).disableClears() self.cam.node().getDisplayRegion(0).disableClears() self.cam2d.node().getDisplayRegion(0).disableClears() self.modelbuffer.disableClears() self.win.disableClears() self.modelbuffer.setClearColorActive(1) self.modelbuffer.setClearDepthActive(1) self.lightbuffer.setClearColorActive(1) self.lightbuffer.setClearColor((0, 0, 0, 1)) # Miscellaneous stuff. self.disableMouse() self.camera.setPos(-9.112, -211.077, 46.951) self.camera.setHpr(0, -7.5, 2.4) random.seed() # Calculate the projection parameters for the final shader. # The math here is too complex to explain in an inline comment, # I've put in a full explanation into the HTML intro. proj = self.cam.node().getLens().getProjectionMat() proj_x = 0.5 * proj.getCell(3, 2) / proj.getCell(0, 0) proj_y = 0.5 * proj.getCell(3, 2) proj_z = 0.5 * proj.getCell(3, 2) / proj.getCell(2, 1) proj_w = -0.5 - 0.5 * proj.getCell(1, 2) # Configure the render state of the model camera. tempnode = NodePath(PandaNode("temp node")) tempnode.setAttrib( AlphaTestAttrib.make(RenderAttrib.MGreaterEqual, 0.5)) tempnode.setShader(loader.loadShader("model.sha")) tempnode.setAttrib(DepthTestAttrib.make(RenderAttrib.MLessEqual)) self.modelcam.node().setInitialState(tempnode.getState()) # Configure the render state of the light camera. tempnode = NodePath(PandaNode("temp node")) tempnode.setShader(loader.loadShader("light.sha")) tempnode.setShaderInput("texnormal", self.texNormal) tempnode.setShaderInput("texalbedo", self.texAlbedo) tempnode.setShaderInput("texdepth", self.texDepth) tempnode.setShaderInput("proj", (proj_x, proj_y, proj_z, proj_w)) tempnode.setAttrib( ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne, ColorBlendAttrib.OOne)) tempnode.setAttrib( CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise)) # The next line causes problems on Linux. # tempnode.setAttrib(DepthTestAttrib.make(RenderAttrib.MGreaterEqual)) tempnode.setAttrib(DepthWriteAttrib.make(DepthWriteAttrib.MOff)) self.lightcam.node().setInitialState(tempnode.getState()) # Configure the render state of the plain camera. rs = RenderState.makeEmpty() self.plaincam.node().setInitialState(rs) # Clear any render attribs on the root node. This is necessary # because by default, panda assigns some attribs to the root # node. These default attribs will override the # carefully-configured render attribs that we just attached # to the cameras. The simplest solution is to just clear # them all out. render.setState(RenderState.makeEmpty()) # My artist created a model in which some of the polygons # don't have textures. This confuses the shader I wrote. # This little hack guarantees that everything has a texture. white = loader.loadTexture("models/white.jpg") render.setTexture(white, 0) # Create two subroots, to help speed cull traversal. self.lightroot = NodePath(PandaNode("lightroot")) self.lightroot.reparentTo(render) self.modelroot = NodePath(PandaNode("modelroot")) self.modelroot.reparentTo(render) self.lightroot.hide(BitMask32(self.modelMask)) self.modelroot.hide(BitMask32(self.lightMask)) self.modelroot.hide(BitMask32(self.plainMask)) # Load the model of a forest. Make it visible to the model camera. # This is a big model, so we load it asynchronously while showing a # load text. We do this by passing in a callback function. self.loading = addTitle("Loading models...") self.forest = NodePath(PandaNode("Forest Root")) self.forest.reparentTo(render) self.forest.hide(BitMask32(self.lightMask | self.plainMask)) loader.loadModel([ "models/background", "models/foliage01", "models/foliage02", "models/foliage03", "models/foliage04", "models/foliage05", "models/foliage06", "models/foliage07", "models/foliage08", "models/foliage09" ], callback=self.finishLoading) # Cause the final results to be rendered into the main window on a # card. self.card = self.lightbuffer.getTextureCard() self.card.setTexture(self.texFinal) self.card.reparentTo(render2d) # Panda contains a built-in viewer that lets you view the results of # your render-to-texture operations. This code configures the viewer. self.bufferViewer.setPosition("llcorner") self.bufferViewer.setCardSize(0, 0.40) self.bufferViewer.setLayout("vline") self.toggleCards() self.toggleCards() # Firefly parameters self.fireflies = [] self.sequences = [] self.scaleseqs = [] self.glowspheres = [] self.fireflysize = 1.0 self.spheremodel = loader.loadModel("misc/sphere") # Create the firefly model, a fuzzy dot dotSize = 1.0 cm = CardMaker("firefly") cm.setFrame(-dotSize, dotSize, -dotSize, dotSize) self.firefly = NodePath(cm.generate()) self.firefly.setTexture(loader.loadTexture("models/firefly.png")) self.firefly.setAttrib( ColorBlendAttrib.make(ColorBlendAttrib.M_add, ColorBlendAttrib.O_incoming_alpha, ColorBlendAttrib.O_one)) # these allow you to change parameters in realtime self.accept("escape", sys.exit, [0]) self.accept("arrow_up", self.incFireflyCount, [1.1111111]) self.accept("arrow_down", self.decFireflyCount, [0.9000000]) self.accept("arrow_right", self.setFireflySize, [1.1111111]) self.accept("arrow_left", self.setFireflySize, [0.9000000]) self.accept("v", self.toggleCards) self.accept("V", self.toggleCards)
def windowMaker(base, label): # find an open slot, if none, return false windict = dict() grid = None for i in range(grid_size[0]): for j in range(grid_size[1]): if occupied[i][j] == False: grid = (i, j) occupied[i][j] = True break else: continue break if not grid: return False windict['grid'] = grid position = grid_to_screen_pos(*grid) #open window newwin = base.openWindow(name=label) newwin.setWindowEvent(label + "-event") listener.accept(newwin.getWindowEvent(), windowEvent) windict['win'] = newwin #format window wp = WindowProperties() wp.setOrigin(*position) wp.setSize(*ws) newwin.requestProperties(wp) #make 3d-mousewatcher display region displayRegion = newwin.getDisplayRegion(0) displayRegion.setDimensions(.3, 1, 0, 1) mkNode = MouseAndKeyboard(newwin, 0, label + "_keyboard_mouse") mk = base.dataRoot.attachNewNode(mkNode) windict['mk'] = mk modis = ModifierButtons() modis.addButton(ButtonHandle('shift')) modis.addButton(ButtonHandle('control')) mwNode = MouseWatcher(label) mwNode.setModifierButtons(modis) mwNode.setDisplayRegion(displayRegion) mw = mk.attachNewNode(mwNode) windict['mw'] = mw bt = ButtonThrower(label + "_button_thrower") bt.setModifierButtons(modis) windict['bt'] = bt bt.setPrefix(label + "_") mw.attachNewNode(bt) #listen for default button events for button in buttons: listener.accept(bt.prefix + button, buttons[button]) #format render display region render_dr = newwin.getDisplayRegion(1) windict['render_dr'] = render_dr render_dr.setDimensions(.3, 1, 0, 1) #create a display region for Gui Elements gui_dr = newwin.makeDisplayRegion(0, .3, .3, 1) # gui_dr.setSort(20) mwNodegui = MouseWatcher(label + "gui") mwNodegui.setDisplayRegion(gui_dr) mwgui = mk.attachNewNode(mwNodegui) #create a 2d render/aspect for gui rendergui = NodePath('render2d') rendergui.setDepthWrite(0) rendergui.setMaterialOff(1) rendergui.setTwoSided(1) #set up aspect2d aspectgui = rendergui.attachNewNode(PGTop('aspectgui')) aspectgui.node().setMouseWatcher(mwgui.node()) #set up camera camNodegui = Camera("camNode2d") cameragui = rendergui.attachNewNode(camNodegui) cameragui.setPos(0, 0, 0) cameragui.setDepthTest(False) cameragui.setDepthWrite(False) lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setNearFar(-1000, 1000) cameragui.node().setLens(lens) gui_dr.setCamera(cameragui) #make frame for gui frame = DirectFrame(frameSize=(-1, 1, -1, 1), frameColor=(.5, .5, .5, 1), relief='ridge') frame.reparentTo(aspectgui) frame.setTransparency(0) windict['gui_frame'] = frame #create Gui elements guibuttons = dict() # guibuttons['Create'] = label+"_mode_create" guibuttons['Preview'] = label + "_preview" # createButton(base, frame, .7, "Create", label+"_mode_create") createButton(base, frame, .7, "Preview", label + "_preview") windict['guibuttons'] = guibuttons #create a display region for math data preview preview_dr = newwin.makeDisplayRegion(0, .3, 0, .3) windict['preview_dr'] = preview_dr # preview_label = label+"_preview" # preview_mwNode = MouseWatcher(preview_label) # preview_mwNode.setDisplayRegion(preview_dr) # preview_mw = mk.attachNewNode(preview_mwNode) # preview_bt = ButtonThrower(preview_label+"_button_thrower") # preview_bt.setPrefix(preview_label+"_") # preview_mw.attachNewNode(preview_bt) # preview_dr.setSort(30) win_to_windict[newwin] = windict return windict
def __init__(self, base, envedit_data): self.base = base self.envedit_data = envedit_data self.target_gizmo = None self.focus_gizmo = None self.drag_gizmo = None self.mouse_x = 0 self.mouse_y = 0 self.raw_mouse_x = 0 self.raw_mouse_y = 0 GizmoSystem.gizmo_system = self # Create frame buffer self.frame_buffer = self.base.win.makeTextureBuffer( "Color Picker Buffer", self.base.win.getXSize(), self.base.win.getYSize(), to_ram=True) self.frame_buffer.setSort(-100) self.frame_buffer.setClearColor((0, 0, 0, 1)) # Load object selection shaders shader_folder_path = Path(path.realpath( __file__)).parent.parent.parent.parent / "res/shaders" self.color_picker_shader = Shader.load( Shader.SL_GLSL, vertex=Filename(shader_folder_path / "picker.vert").cStr(), fragment=Filename(shader_folder_path / "picker.frag").cStr()) self.skinned_shader = Shader.load( Shader.SL_GLSL, vertex=Filename(shader_folder_path / "skinned.vert").cStr(), fragment=Filename(shader_folder_path / "picker.frag").cStr()) self.gizmo_shader = Shader.load( Shader.SL_GLSL, vertex=Filename(shader_folder_path / "gizmo.vert").cStr(), fragment=Filename(shader_folder_path / "picker.frag").cStr()) # Set up color picking camera self.color_cam = self.base.makeCamera(self.frame_buffer) color_cam_options = NodePath("color_cam_options") color_cam_options.setShader(self.color_picker_shader) self.color_cam.node().setInitialState(color_cam_options.getState()) skinned_render_state = NodePath("") skinned_render_state.set_shader(self.skinned_shader) self.color_cam.node().setTagStateKey("skinned") self.color_cam.node().setTagState("True", skinned_render_state.get_state()) gizmo_render_state = NodePath("") gizmo_render_state.set_shader(self.gizmo_shader) self.color_cam.node().setTagStateKey("gizmo") self.color_cam.node().setTagState("True", gizmo_render_state.get_state()) # Register events self.accept("window-event", self.handle_window) self.accept("mouse1", self.handle_left_mouse_pressed) self.accept("mouse1-up", self.handle_left_mouse_released) self.accept("mouse3", self.handle_right_mouse_pressed) self.accept("mouse3-up", self.handle_right_mouse_released) # DEBUG: View color picking framebuffer # self.accept("v", self.base.bufferViewer.toggleEnable) # Remove background from selection GizmoSystem.gizmos[0] = 1 # Add object selection task self.add_task(self.handle_object_selection)
def __init__(self): base.cTrav = CollisionTraverser() self.col_handler = CollisionHandlerEvent() self.selected = -1 self.selected_node = None self.selecteds = [] self.multi_select = False self.multi_selecting = False self.select_box = NodePath() picker_node = CollisionNode("mouseRayNode") pickerNPos = base.camera.attachNewNode(picker_node) self.pickerRay = CollisionRay() picker_node.addSolid(self.pickerRay) plane_node = CollisionNode("base_plane") plane = base.render.attachNewNode(plane_node) self.plane_col = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0))) picker_node.addSolid(self.pickerRay) picker_node.setTag("rays", "mray") base.cTrav.addCollider(pickerNPos, self.col_handler) self.col_handler.addInPattern("%(rays)ft-into-%(type)it") self.col_handler.addOutPattern("%(rays)ft-out-%(type)it") self.col_handler.addAgainPattern("ray_again_all%(" "rays" ")fh%(" "type" ")ih") self.DO = DirectObject() self.DO.accept('mray-into-army', self.col_in_object) self.DO.accept('mray-out-army', self.col_out_object) self.DO.accept('mray-into-battle', self.col_in_object) self.DO.accept('mray-out-battle', self.col_out_object) self.DO.accept('mray-into-tower', self.col_in_object) self.DO.accept('mray-out-tower', self.col_out_object) self.DO.accept('ray_again_all', self.col_against_object) if base.client == False: self.col_handler.addInPattern("%(player)ft-into-%(player)it") self.col_handler.addInPattern("%(type)ft-into-%(type)it") self.DO.accept('army-into-battle', self.col_army_against_battle) self.DO.accept('army-into-tower', self.col_army_against_tower) self.DO.accept('1-into-2', self.col_p1_into_p2) self.pickable = None self.DO.accept('mouse1', self.mouse_click, ["down"]) self.DO.accept('mouse1-up', self.mouse_click, ["up"]) self.DO.accept('mouse3-up', self.mouse_order) taskMgr.add(self.ray_update, "updatePicker") taskMgr.add(self.task_select_check, "updatePicker") taskMgr.add(self.get_mouse_plane_pos, "MousePositionOnPlane") z = 0 self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, z)) self.model = loader.loadModel("models/chest.egg") self.model.reparentTo(render) self.model.hide() cm = CardMaker("blah") cm.setFrame(-100, 100, -100, 100) pnode = render.attachNewNode(cm.generate()) #.lookAt(0, 0, -1) pnode.hide()
def __init__(self): # 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) self.stimtype = 'image_sequence' #session_start self.session_start_time = datetime.datetime.now() # self.accept("escape", sys.exit, [0])#don't let the user do this, because then the data isn't saved. self.accept('q', self.close) self.accept('Q', self.close) self.AUTO_REWARD = AUTO_REWARD # disable mouse control so that we can place the camera base.disableMouse() camera.setPosHpr(0, 0, 10, 0, -90, 0) mat = Mat4(camera.getMat()) mat.invertInPlace() base.mouseInterfaceNode.setMat(mat) # base.enableMouse() props = WindowProperties() props.setOrigin(1920, 0) props.setFullscreen(True) props.setCursorHidden(True) props.setMouseMode(WindowProperties.M_relative) base.win.requestProperties(props) base.setBackgroundColor(0, 0, 0) # set the background color to black #set up the textures # we now get buffer thats going to hold the texture of our new scene altBuffer = self.win.makeTextureBuffer("hello", 1524, 1024) # altBuffer.getDisplayRegion(0).setDimensions(0.5,0.9,0.5,0.8) # altBuffer = base.win.makeDisplayRegion() # altBuffer.makeDisplayRegion(0,1,0,1) # now we have to setup a new scene graph to make this scene self.dr2 = base.win.makeDisplayRegion(0, 0.1, 0, 0.1) altRender = NodePath("new render") # this takes care of setting up ther camera properly self.altCam = self.makeCamera(altBuffer) self.dr2.setCamera(self.altCam) self.altCam.reparentTo(altRender) self.altCam.setPos(0, -10, 0) self.bufferViewer.setPosition("llcorner") # self.bufferViewer.position = (.1,.4,.1,.4) self.bufferViewer.setCardSize(1.0, 0.0) print(self.bufferViewer.position) self.imagesTexture = MovieTexture("image_sequence") # success = self.imagesTexture.read("models/natural_images.avi") success = self.imagesTexture.read("models/movie_5hz.mpg") self.imagesTexture.setPlayRate(1.0) self.imagesTexture.setLoopCount(10) # self.imageTexture =loader.loadTexture("models/NaturalImages/BSDs_8143.tiff") # self.imagesTexture.reparentTo(altRender) cm = CardMaker("stimwindow") cm.setFrame(-4, 4, -3, 3) # cm.setUvRange(self.imagesTexture) self.card = NodePath(cm.generate()) self.card.reparentTo(altRender) if self.stimtype == 'image_sequence': self.card.setTexture(self.imagesTexture, 1) # self.imagesTexture.play() # self.bufferViewer.setPosition("lrcorner") # self.bufferViewer.setCardSize(1.0, 0.0) self.accept("v", self.bufferViewer.toggleEnable) self.accept("V", self.bufferViewer.toggleEnable) # Load the tunnel self.initTunnel() #initialize some things # for the tunnel construction: self.boundary_to_add_next_segment = -1 * TUNNEL_SEGMENT_LENGTH self.current_number_of_segments = 8 #task flow booleans self.in_waiting_period = False self.stim_started = False self.looking_for_a_cue_zone = True self.in_reward_window = False self.show_stimulus = False #for task control self.interval = 0 self.time_waiting_in_cue_zone = 0 self.wait_time = 1.83 self.stim_duration = 4.0 # in seconds self.max_stim_duration = 6.0 # in seconds self.stim_elapsed = 0.0 # in seconds self.last_position = base.camera.getZ() self.position_on_track = base.camera.getZ() #for reward control self.reward_window = 1.0 # in seconds self.reward_elapsed = 0.0 # self.reward_volume = 0.008 # in mL. this is for the hardcoded 0.1 seconds of reward time self.reward_volume = REWARD_VOLUME # in uL, for the stepper motor self.reward_time = 0.1 # in sec, based on volume. hard coded right now but should be modified by the (1) calibration and (2) optionally by the main loop for dynamic reward scheduling # self.lick_buffer = [] #INITIALIZE NIDAQ self.nidevice = 'Dev2' self.encodervinchannel = 1 self.encodervsigchannel = 0 self.invertdo = False self.diport = 1 self.lickline = 1 self.doport = 0 self.rewardline = 0 self.rewardlines = [0] self._setupDAQ() self.do.WriteBit(1, 1) self.do.WriteBit( 3, 1 ) #set reward high, because the logic is flipped somehow. possibly by haphazard wiring of the circuit (12/24/2018 djd) self.previous_encoder_position = self.ai.data[0][ self.encodervsigchannel] self.encoder_gain = -10 #INITIALIZE LICK SENSOR self._lickSensorSetup() #INITIALIZE output data self.lickData = [] self.x = [] self.t = [] self.trialData = [] self.rewardData = [] #INITIALIZE KEY SENSOR, for backup inputs and other user controls self.keys = key.KeyStateHandler() self.accept('r', self._give_reward, [self.reward_volume]) self.accept('l', self._toggle_reward) img_list = glob.glob('models/NaturalImages/*.tiff')[:10] print(img_list) self.imageTextures = [loader.loadTexture(img) for img in img_list] self._setupEyetracking() self._startEyetracking() if AUTO_MODE: self.gameTask = taskMgr.add(self.autoLoop2, "autoLoop2") self.rewardTask = taskMgr.add(self.rewardControl, "reward") self.cue_zone = concatenate((self.cue_zone,arange(\ self.current_number_of_segments*-TUNNEL_SEGMENT_LENGTH,\ self.current_number_of_segments*-TUNNEL_SEGMENT_LENGTH-TUNNEL_SEGMENT_LENGTH-80,\ -1))) self.auto_position_on_track = 0 self.auto_restart = False self.auto_running = True self.contTunnel() else: # 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") # self.stimulusTask = taskMgr.add(self.stimulusControl, "stimulus") self.lickTask = taskMgr.add(self.lickControl, "lick") self.rewardTask = taskMgr.add(self.rewardControl, "reward")
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(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, (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)) self.forceSizes.append(False) return quad
def load(self, loadModels=1, arenaModel='partyCatchTree'): self.notify.info('load()') DistributedPartyCatchActivity.notify.debug('PartyCatch: load') self.activityFSM = CatchActivityFSM(self) if __dev__: for o in range(3): print { 0: 'SPOTS PER PLAYER', 1: 'DROPS PER MINUTE PER SPOT DURING NORMAL DROP PERIOD', 2: 'DROPS PER MINUTE PER PLAYER DURING NORMAL DROP PERIOD' }[o] for i in range(1, self.FallRateCap_Players + 10): self.defineConstants(forceNumPlayers=i) numDropLocations = self.DropRows * self.DropColumns numDropsPerMin = 60.0 / self.DropPeriod if o == 0: spotsPerPlayer = numDropLocations / float(i) print '%2d PLAYERS: %s' % (i, spotsPerPlayer) elif o == 1: numDropsPerMinPerSpot = numDropsPerMin / numDropLocations print '%2d PLAYERS: %s' % (i, numDropsPerMinPerSpot) elif i > 0: numDropsPerMinPerPlayer = numDropsPerMin / i print '%2d PLAYERS: %s' % (i, numDropsPerMinPerPlayer) self.defineConstants() self.treesAndFence = loader.loadModel('phase_13/models/parties/%s' % arenaModel) self.treesAndFence.setScale(0.9) self.treesAndFence.find('**/fence_floor').setPos(0.0, 0.0, 0.1) self.treesAndFence.reparentTo(self.root) ground = self.treesAndFence.find('**/groundPlane') ground.setBin('ground', 1) DistributedPartyActivity.load(self) exitText = TextNode('PartyCatchExitText') exitText.setCardAsMargin(0.1, 0.1, 0.1, 0.1) exitText.setCardDecal(True) exitText.setCardColor(1.0, 1.0, 1.0, 0.0) exitText.setText(TTLocalizer.PartyCatchActivityExit) exitText.setTextColor(0.0, 8.0, 0.0, 0.9) exitText.setAlign(exitText.ACenter) exitText.setFont(ToontownGlobals.getBuildingNametagFont()) exitText.setShadowColor(0, 0, 0, 1) exitText.setBin('fixed') if TTLocalizer.BuildingNametagShadow: exitText.setShadow(*TTLocalizer.BuildingNametagShadow) exitTextLoc = self.treesAndFence.find('**/loc_exitSignText') exitTextNp = exitTextLoc.attachNewNode(exitText) exitTextNp.setDepthWrite(0) exitTextNp.setScale(4) exitTextNp.setZ(-.5) self.sign.reparentTo(self.treesAndFence.find('**/loc_eventSign')) self.sign.wrtReparentTo(self.root) self.avatarNodePath = NodePath('PartyCatchAvatarNodePath') self.avatarNodePath.reparentTo(self.root) self._avatarNodePathParentToken = 3 base.cr.parentMgr.registerParent(self._avatarNodePathParentToken, self.avatarNodePath) self.toonSDs = {} self.dropShadow = loader.loadModelOnce( 'phase_3/models/props/drop_shadow') self.dropObjModels = {} if loadModels: self.__loadDropModels() self.sndGoodCatch = base.loadSfx( 'phase_4/audio/sfx/SZ_DD_treasure.mp3') self.sndOof = base.loadSfx('phase_4/audio/sfx/MG_cannon_hit_dirt.mp3') self.sndAnvilLand = base.loadSfx( 'phase_4/audio/sfx/AA_drop_anvil_miss.mp3') self.sndPerfect = base.loadSfx('phase_4/audio/sfx/ring_perfect.mp3') self.__textGen = TextNode('partyCatchActivity') self.__textGen.setFont(ToontownGlobals.getSignFont()) self.__textGen.setAlign(TextNode.ACenter) self.activityFSM.request('Idle')
def loadHouseFromJson(houseId, datasetRoot): filename = SunCgSceneLoader.getHouseJsonPath(datasetRoot, houseId) with open(filename) as f: data = json.load(f) assert houseId == data['id'] houseId = str(data['id']) # Create new node for house instance houseNp = NodePath('house-' + str(houseId)) houseNp.setTag('house-id', str(houseId)) objectIds = {} for levelId, level in enumerate(data['levels']): logger.debug('Loading Level %s to scene' % (str(levelId))) # Create new node for level instance levelNp = houseNp.attachNewNode('level-' + str(levelId)) levelNp.setTag('level-id', str(levelId)) roomNpByNodeIndex = {} for nodeIndex, node in enumerate(level['nodes']): if not node['valid'] == 1: continue modelId = str(node['modelId']) if node['type'] == 'Room': logger.debug('Loading Room %s to scene' % (modelId)) # Create new nodes for room instance instanceId = str(modelId) + '-0' roomNp = levelNp.attachNewNode('room-' + instanceId) roomNp.setTag('model-id', modelId) roomNp.setTag('instance-id', instanceId) roomLayoutsNp = roomNp.attachNewNode('layouts') roomObjectsNp = roomNp.attachNewNode('objects') # Include some semantic information roomTypes = node['roomTypes'] roomTypes = [roomType.lower() for roomType in roomTypes] roomNp.setTag('room-types', ','.join(roomTypes)) # Load models defined for this room for roomObjFilename in reglob( os.path.join(datasetRoot, 'room', houseId), modelId + '[a-z].obj'): # NOTE: loading the BAM format is faster and more efficient # Convert extension from OBJ + MTL to BAM format f, _ = os.path.splitext(roomObjFilename) modelFilename = f + ".bam" if not os.path.exists(modelFilename): raise Exception( 'The SUNCG dataset object models need to be convert to Panda3D EGG format!' ) # Create new node for object instance instanceId = str(modelId) + '-0' modelId = os.path.splitext( os.path.basename(roomObjFilename))[0] objectNp = NodePath('object-' + instanceId) objectNp.reparentTo(roomLayoutsNp) objectNp.setTag('model-id', modelId) objectNp.setTag('instance-id', instanceId) model = loadModel(modelFilename) model.setName('model-' + os.path.basename(f)) model.reparentTo(objectNp) model.hide() if 'nodeIndices' in node: for childNodeIndex in node['nodeIndices']: roomNpByNodeIndex[childNodeIndex] = roomObjectsNp elif node['type'] == 'Object': logger.debug('Loading Object %s to scene' % (modelId)) # Instance identification if modelId in objectIds: objectIds[modelId] = objectIds[modelId] + 1 else: objectIds[modelId] = 0 # Create new node for object instance instanceId = str(modelId) + '-' + str(objectIds[modelId]) objectNp = NodePath('object-' + instanceId) objectNp.setTag('model-id', modelId) objectNp.setTag('instance-id', instanceId) # NOTE: loading the BAM format is faster and more efficient # Convert extension from OBJ + MTL to BAM format objFilename = os.path.join(datasetRoot, 'object', node['modelId'], node['modelId'] + '.obj') assert os.path.exists(objFilename) f, _ = os.path.splitext(objFilename) modelFilename = f + ".bam" if not os.path.exists(modelFilename): raise Exception( 'The SUNCG dataset object models need to be convert to Panda3D BAM format!' ) model = loadModel(modelFilename) model.setName('model-' + os.path.basename(f)) model.reparentTo(objectNp) model.hide() # 4x4 column-major transformation matrix from object coordinates to scene coordinates transform = np.array(node['transform']).reshape((4, 4)) # Transform from Y-UP to Z-UP coordinate systems #TODO: use Mat4.convertMat(CS_zup_right, CS_yup_right) yupTransform = np.array([[1, 0, 0, 0], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) zupTransform = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1]]) transform = np.dot(np.dot(yupTransform, transform), zupTransform) transform = TransformState.makeMat( LMatrix4f(*transform.ravel())) # Calculate the center of this object minBounds, maxBounds = model.getTightBounds() centerPos = minBounds + (maxBounds - minBounds) / 2.0 # Add offset transform to make position relative to the center objectNp.setTransform( transform.compose(TransformState.makePos(centerPos))) model.setTransform(TransformState.makePos(-centerPos)) # Get the parent nodepath for the object (room or level) if nodeIndex in roomNpByNodeIndex: objectNp.reparentTo(roomNpByNodeIndex[nodeIndex]) else: objectNp.reparentTo(levelNp) # Validation assert np.allclose(mat4ToNumpyArray( model.getNetTransform().getMat()), mat4ToNumpyArray(transform.getMat()), atol=1e-6) elif node['type'] == 'Ground': logger.debug('Loading Ground %s to scene' % (modelId)) # Create new nodes for ground instance instanceId = str(modelId) + '-0' groundNp = levelNp.attachNewNode('ground-' + instanceId) groundNp.setTag('instance-id', instanceId) groundNp.setTag('model-id', modelId) groundLayoutsNp = groundNp.attachNewNode('layouts') # Load model defined for this ground for groundObjFilename in reglob( os.path.join(datasetRoot, 'room', houseId), modelId + '[a-z].obj'): # NOTE: loading the BAM format is faster and more efficient # Convert extension from OBJ + MTL to BAM format f, _ = os.path.splitext(groundObjFilename) modelFilename = f + ".bam" if not os.path.exists(modelFilename): raise Exception( 'The SUNCG dataset object models need to be convert to Panda3D BAM format!' ) instanceId = str(modelId) + '-0' modelId = os.path.splitext( os.path.basename(groundObjFilename))[0] objectNp = NodePath('object-' + instanceId) objectNp.reparentTo(groundLayoutsNp) objectNp.setTag('model-id', modelId) objectNp.setTag('instance-id', instanceId) model = loadModel(modelFilename) model.setName('model-' + os.path.basename(f)) model.reparentTo(objectNp) model.hide() else: raise Exception('Unsupported node type: %s' % (node['type'])) scene = Scene() houseNp.reparentTo(scene.scene) # Recenter objects in rooms for room in scene.scene.findAllMatches('**/room*'): # Calculate the center of this room minBounds, maxBounds = room.getTightBounds() centerPos = minBounds + (maxBounds - minBounds) / 2.0 # Add offset transform to room node room.setTransform(TransformState.makePos(centerPos)) # Add recentering transform to all children nodes for childNp in room.getChildren(): childNp.setTransform(TransformState.makePos(-centerPos)) # Recenter objects in grounds for ground in scene.scene.findAllMatches('**/ground*'): # Calculate the center of this ground minBounds, maxBounds = ground.getTightBounds() centerPos = minBounds + (maxBounds - minBounds) / 2.0 # Add offset transform to ground node ground.setTransform(TransformState.makePos(centerPos)) # Add recentering transform to all children nodes for childNp in ground.getChildren(): childNp.setTransform(TransformState.makePos(-centerPos)) return scene