def __init__(self, parent, entity, foot=1): self.entity = entity self._moveRadCircleNP = NodePath("Movement Radius Node") self._moveLine = LineSegs() self._moveLineNP = NodePath("Movement Direction Line Node") self._moveZLine = LineSegs() self._moveZLineNP = NodePath("Movement Z Line Node") self._moveZFootNP = NodePath("Movement Z Foot Node") self._moveFootCircle = LineSegs() self._moveFootCircleNP = NodePath("Movement Foot Circle Node") self._attackRadCircle = LineSegs() self._attackRadCircleNP = NodePath("Attack Radius Node") self._np = NodePath("Movement Node") self.attackables = [] Event.Dispatcher().register(self, 'E_Key_ZUp', self.onZChange) Event.Dispatcher().register(self, 'E_Key_ZDown', self.onZChange) Event.Dispatcher().register(self, 'E_Key_ZUp-up', self.onZChange) Event.Dispatcher().register(self, 'E_Key_ZDown-up', self.onZChange) self.aaLevel = int(GameSettings().getSetting('ANTIALIAS')) self.parent = parent self.start = Vec3(0, 0, 0) self.moveRad = entity.moveRad self.footRad = foot self.attackRad = entity.attackRad self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0)) self.draw() self._np.reparentTo(self.parent) if self.aaLevel > 0: self._np.setAntialias(AntialiasAttrib.MLine, self.aaLevel) taskMgr.add(self.updateMovePos, 'Movement Indicator Update Task')
def makePerspective(parent): v = Viewport('persp', parent) v.camPos = Point3(-19, -19, 19) v.camLookAt = Point3(0, 0, 0) v.grid = DirectGrid(parent=render) collPlane = CollisionNode('PerspGridCol') collPlane.addSolid(CollisionPlane(Plane(0, 0, 1, 0))) #oldBitmask = collPlane.getIntoCollideMask() #collPlane.setIntoCollideMask(BitMask32.bit(21)|oldBitmask) collPlane.setIntoCollideMask(BitMask32.bit(21)) v.collPlane = NodePath(collPlane) v.collPlane.reparentTo(v.grid) collPlane2 = CollisionNode('PerspGridCol2') collPlane2.addSolid(CollisionPlane(Plane(0, 0, -1, 0))) #oldBitmask = collPlane2.getIntoCollideMask() #collPlane2.setIntoCollideMask(BitMask32.bit(21)|oldBitmask) collPlane2.setIntoCollideMask(BitMask32.bit(21)) v.collPlane2 = NodePath(collPlane2) v.collPlane2.reparentTo(v.grid) #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_perspViewGridBack") LE_showInOneCam(v.grid, 'persp') return v
def __init__(self,manager,xml): self.surface = getWaterSurface(manager) self.surface.reparentTo(render) self.surface.hide(BitMask32.bit(1)) # Invisible to reflection camera (speedup) self.surface.hide(BitMask32.bit(2)) # Invisible to volumetric lighting camera (speedup) self.surface.hide(BitMask32.bit(3)) # Invisible to shadow cameras (speedup) self.surface.setShader(loader.loadShader(manager.get('paths').getConfig().find('shaders').get('path')+'/water.cg')) self.surface.setShaderInput('time', 0.0, 0.0, 0.0, 0.0) ntex = loader.loadTexture(manager.get('paths').getConfig().find('textures').get('path')+'/water-normal.png') ntex.setMinfilter(Texture.FTLinearMipmapLinear) self.surface.setShaderInput('normal', ntex) self.surface.setShaderInput('camera', base.cam) self.surface.setTransparency(TransparencyAttrib.MDual, 10) self.surface.setTwoSided(True) self.surface.setShaderInput('waveInfo', Vec4(0.4, 0.4, 0.4, 0)) self.surface.setShaderInput('param2', Vec4(-0.015,0.005, 0.05, 0.05)) self.surface.setShaderInput('param3', Vec4(0.7, 0.3, 0, 0)) self.surface.setShaderInput('param4', Vec4(2.0, 0.5, 0.5, 0.0)) #self.surface.setShaderInput('speed', Vec4(-.8, -.4, -.9, .3)) self.surface.setShaderInput('speed', Vec4(0.2, -1.2, -0.2, -0.7)) self.surface.setShaderInput('deepcolor', Vec4(0.0,0.3,0.5,1.0)) self.surface.setShaderInput('shallowcolor', Vec4(0.0,1.0,1.0,1.0)) self.surface.setShaderInput('reflectioncolor', Vec4(0.95,1.0,1.0,1.0)) self.surface.hide() self.wbuffer = base.win.makeTextureBuffer('water', 512, 512) self.wbuffer.setClearColorActive(True) self.wbuffer.setClearColor(base.win.getClearColor()) self.wcamera = base.makeCamera(self.wbuffer) if manager.get('sky') != None and manager.get('sky').model != None: self.sky = manager.get('sky').model.copyTo(self.wcamera) self.sky.setTwoSided(True) self.sky.setSz(self.sky, -1) self.sky.setClipPlaneOff(1) self.sky.show() self.sky.hide(BitMask32.bit(0)) # Hide for normal camera self.sky.hide(BitMask32.bit(2)) # Hide for volumetric lighting camera self.sky.hide(BitMask32.bit(3)) # Hide for shadow camera(s), if any else: self.sky = None self.wcamera.reparentTo(render) self.wcamera.node().setLens(base.camLens) self.wcamera.node().setCameraMask(BitMask32.bit(1)) self.surface.hide(BitMask32.bit(1)) wtexture = self.wbuffer.getTexture() wtexture.setWrapU(Texture.WMClamp) wtexture.setWrapV(Texture.WMClamp) wtexture.setMinfilter(Texture.FTLinearMipmapLinear) self.surface.setShaderInput('reflection', wtexture) self.wplane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0)) self.wplanenp = render.attachNewNode(PlaneNode('water', self.wplane)) tmpnp = NodePath('StateInitializer') tmpnp.setClipPlane(self.wplanenp) tmpnp.setAttrib(CullFaceAttrib.makeReverse()) self.wcamera.node().setInitialState(tmpnp.getState()) #self.fog = Fog('UnderwaterFog') #self.fog.setColor(0.0,0.3,0.5) self.fogEnabled = False
def makeOrthographic(parent, name, campos): v = Viewport(name, parent) v.lens = OrthographicLens() v.lens.setFilmSize(30) v.camPos = campos v.camLookAt = Point3(0, 0, 0) v.grid = DirectGrid(parent=render) if name == 'left': v.grid.setHpr(0, 0, 90) collPlane = CollisionNode('LeftGridCol') collPlane.addSolid(CollisionPlane(Plane(1, 0, 0, 0))) collPlane.setIntoCollideMask(BitMask32.bit(21)) v.collPlane = NodePath(collPlane) v.collPlane.wrtReparentTo(v.grid) #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_leftViewGridBack") LE_showInOneCam(v.grid, name) elif name == 'front': v.grid.setHpr(90, 0, 90) collPlane = CollisionNode('FrontGridCol') collPlane.addSolid(CollisionPlane(Plane(0, -1, 0, 0))) collPlane.setIntoCollideMask(BitMask32.bit(21)) v.collPlane = NodePath(collPlane) v.collPlane.wrtReparentTo(v.grid) #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_frontViewGridBack") LE_showInOneCam(v.grid, name) else: collPlane = CollisionNode('TopGridCol') collPlane.addSolid(CollisionPlane(Plane(0, 0, 1, 0))) collPlane.setIntoCollideMask(BitMask32.bit(21)) v.collPlane = NodePath(collPlane) v.collPlane.reparentTo(v.grid) #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_topViewGridBack") LE_showInOneCam(v.grid, name) return v
def __init__(self, x1, y1, x2, y2, z): Att_base.__init__(self, False, "Water1") # Water surface maker = CardMaker( 'water' ) maker.setFrame( x1, x2, y1, y2 ) self.waterNP = render.attachNewNode(maker.generate()) self.waterNP.setHpr(0,-90,0) self.waterNP.setPos(0,0,z) self.waterNP.setTransparency(TransparencyAttrib.MAlpha ) self.waterNP.setShader(loader.loadShader( 'Shaders/water1.sha' )) # Reflection plane self.waterPlane = Plane( Vec3( 0, 0, z+1 ), Point3( 0, 0, z ) ) planeNode = PlaneNode( 'waterPlane' ) planeNode.setPlane( self.waterPlane ) # Buffer and reflection camera self.buffer = base.win.makeTextureBuffer( 'waterBuffer', 512, 512 ) self.buffer.setClearColor( Vec4( 0, 0, 0, 1 ) ) cfa = CullFaceAttrib.makeReverse( ) rs = RenderState.make(cfa) self.watercamNP = base.makeCamera( self.buffer ) self.watercamNP.reparentTo(render) sa = ShaderAttrib.make() sa = sa.setShader(loader.loadShader('Shaders/splut3Clipped.sha') ) self.cam = self.watercamNP.node() self.cam.getLens( ).setFov( base.camLens.getFov( ) ) self.cam.getLens().setNear(1) self.cam.getLens().setFar(5000) self.cam.setInitialState( rs ) self.cam.setTagStateKey('Clipped') self.cam.setTagState('True', RenderState.make(sa)) # ---- water textures --------------------------------------------- # reflection texture, created in realtime by the 'water camera' tex0 = self.buffer.getTexture( ) tex0.setWrapU(Texture.WMClamp) tex0.setWrapV(Texture.WMClamp) ts0 = TextureStage( 'reflection' ) self.waterNP.setTexture( ts0, tex0 ) # distortion texture tex1 = loader.loadTexture('Textures/water.png') ts1 = TextureStage('distortion') self.waterNP.setTexture(ts1, tex1)
def Transform( self ): startVec = self.startVec axis = self.GetSelectedAxis() print axis if axis is not None and axis.vector == CAMERA_VECTOR: endVec = self.getRelativeVector( render, self.GetAxisPoint( axis ) - self.getPos() ) cross = startVec.cross( endVec ) direction = self.getRelativeVector( self.camera, Vec3(0, -1, 0) ).dot( cross ) sign = math.copysign( 1, direction ) # Get the rotation axis rotAxis = self.getRelativeVector( self.camera, Vec3(0, -1, 0) ) * sign else: if self.collEntry.getIntoNode() == self.initCollEntry.getIntoNode(): endVec = self.collEntry.getSurfaceNormal( self ) else: endVec = self.getRelativeVector( render, self.GetAxisPoint( self.foobar ) - self.getPos() ) # If an axis is selected then constrain the vectors by projecting # them onto a plane whose normal is the axis vector if axis is not None: plane = Plane( axis.vector, Point3( 0 ) ) startVec = Vec3( plane.project( Point3( startVec ) ) ) endVec = Vec3( plane.project( Point3( endVec ) ) ) # Get the rotation axis rotAxis = endVec.cross( startVec ) * -1 # Return if the rotation vector is not valid, ie it does not have any # length if not rotAxis.length(): return # Normalize all vectors startVec.normalize() endVec.normalize() rotAxis.normalize() # Get the amount of degrees to rotate degs = startVec.angleDeg( endVec ) # Transform the gizmo if in local rotation mode newRotMat = Mat4().rotateMat( degs, rotAxis ) if self.local: self.setMat( newRotMat * self.getMat() ) # Transform all attached node paths for i, np in enumerate( self.attachedNps ): # Split the transform into scale, rotation and translation # matrices transMat, rotMat, scaleMat = commonUtils.GetTrsMatrices( np.getTransform() ) # Perform transforms in local or world space if self.local: np.setMat( scaleMat * newRotMat * rotMat * transMat ) else: self.initNpXforms[i].getQuat().extractToMatrix( rotMat ) np.setMat( scaleMat * rotMat * newRotMat * transMat )
def __init__(self, parent, entity, foot=1): self.entity = entity self._moveRadCircleNP = NodePath("Movement Radius Node") self._moveLine = LineSegs() self._moveLineNP = NodePath("Movement Direction Line Node") self._moveZLine = LineSegs() self._moveZLineNP = NodePath("Movement Z Line Node") self._moveZFootNP = NodePath("Movement Z Foot Node") self._moveFootCircle = LineSegs() self._moveFootCircleNP = NodePath("Movement Foot Circle Node") self._attackRadCircle = LineSegs() self._attackRadCircleNP= NodePath("Attack Radius Node") self._np = NodePath("Movement Node") self.attackables = [] Event.Dispatcher().register(self, 'E_Key_ZUp', self.onZChange) Event.Dispatcher().register(self, 'E_Key_ZDown', self.onZChange) Event.Dispatcher().register(self, 'E_Key_ZUp-up', self.onZChange) Event.Dispatcher().register(self, 'E_Key_ZDown-up', self.onZChange) self.aaLevel= int(GameSettings().getSetting('ANTIALIAS')) self.parent = parent self.start = Vec3(0, 0, 0) self.moveRad = entity.moveRad self.footRad = foot self.attackRad = entity.attackRad self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0)) self.draw() self._np.reparentTo(self.parent) if self.aaLevel > 0: self._np.setAntialias(AntialiasAttrib.MLine, self.aaLevel) taskMgr.add(self.updateMovePos, 'Movement Indicator Update Task')
def _initCollisions(self): self.collPlane = CollisionPlane(Plane(Vec3(0, 0, 1.0), Point3(0, 0, 10))) self.collPlane.setTangible(0) self.collNode = CollisionNode('fogPlane') self.collNode.setIntoCollideMask(OTPGlobals.FloorBitmask) self.collNode.addSolid(self.collPlane) self.collNodePath = self.root.attachNewNode(self.collNode) self.collNodePath.hide()
def Collision(self): self.mpos3d=0 self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0)) base.cTrav = CollisionTraverser() self.collHandler = CollisionHandlerQueue() self.pickerNode = CollisionNode('mouseRay') self.pickerNP = camera.attachNewNode(self.pickerNode) self.pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask()) self.pickerRay = CollisionRay() self.pickerNode.addSolid(self.pickerRay) base.cTrav.addCollider(self.pickerNP, self.collHandler)
def makeWater(self): self.water = loader.loadModel("models/water.egg") self.water.setPos(0,0,1) self.water.setShader(loader.loadShader('shaders/water.sha')) self.water.setShaderInput('wateranim', Vec4(0.03, -0.015, 64.0, 0)) self.water.setShaderInput('waterdistort', Vec4(0.4, 4.0, 0.25, 0.45)) self.water.setShaderInput('time', 0) buffer = base.win.makeTextureBuffer('waterBuffer', 512, 512) #buffer.setClearColor(Vec4(0.3, 0.3, 1, 1)) cfa = CullFaceAttrib.makeReverse() rs = RenderState.make(cfa) self.watercamNP = base.makeCamera(buffer) self.watercamNP.reparentTo(render) cam = self.watercamNP.node() cam.getLens().setFov(base.camLens.getFov()) cam.getLens().setNear(1) cam.getLens().setFar(5000) cam.setInitialState(rs) self.waterPlane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0)) planeNode = PlaneNode('waterPlane') planeNode.setPlane(self.waterPlane) #cam.lookAt(0,0,-1) cam.setTagStateKey('Clipped') tex0 = buffer.getTexture() tex0.setWrapU(Texture.WMClamp) tex0.setWrapV(Texture.WMClamp) ts0 = TextureStage('reflection') self.water.setTexture(ts0, tex0) tex1 = loader.loadTexture('texture/water.png') ts1 = TextureStage('distortion') self.water.setTexture(ts1, tex1) self.keyMap={}; self.keyMap["sit"]=0 self.keyMap["call"]=0 self.keyMap["left"]=0 self.keyMap["forward"]=0 self.keyMap["right"]=0 taskMgr.add(self.waterUpdate, "waterTask") taskMgr.add(self.cameraControl,"cameraControl") self.water.reparentTo(render)
def GetMousePlaneCollisionPoint( self, pos, nrml ): """ Return the collision point of a ray fired through the mouse and a plane with the specified normal. """ # Fire a ray from the camera through the mouse mp = self.mouseWatcherNode.getMouse() p1 = Point3() p2 = Point3() self.camera.node().getLens().extrude( mp, p1, p2 ) p1 = self.rootNp.getRelativePoint( self.camera, p1 ) p2 = self.rootNp.getRelativePoint( self.camera, p2 ) # Get the point of intersection with a plane with the normal # specified p = Point3() Plane( nrml, pos ).intersectsLine( p, p1, p2 ) return p
def setupCollision(self): # create collision traverser self.picker = CollisionTraverser() # create collision handler self.pq = CollisionHandlerQueue() # create collision node self.pickerNode = CollisionNode('mouseRay') # create collision node # attach new collision node to camera node self.pickerNP = camera.attachNewNode( self.pickerNode) # attach collision node to camera # set bit mask to one self.pickerNode.setFromCollideMask(BitMask32.bit(1)) # set bit mask # create a collision ray self.pickerRay = CollisionRay() # create collision ray # add picker ray to the picker node self.pickerNode.addSolid( self.pickerRay) # add the collision ray to the collision node # make the traverser know about the picker node and its even handler queue self.picker.addCollider( self.pickerNP, self.pq) # add the colision node path and collision handler queue #self.picker.showCollisions( render ) # render or draw the collisions #self.pickerNP.show( ) # render picker ray # create col node self.colPlane = CollisionNode('colPlane') # add solid to col node plane self.colPlane.addSolid( CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0)))) # attach new node to the render self.colPlanePath = render.attachNewNode(self.colPlane) #self.colPlanePath.show( ) # render node # make the col plane look at the camera # this makes it alway look at the camera no matter the orientation # we need this because the ray nees to intersect a plane parallel # to the camera self.colPlanePath.lookAt(camera) # prop up the col plane self.colPlanePath.setP(-45) # set bit mask to one # as I understand it, this makes all col nodes with bit mask one # create collisions while ignoring others of other masks self.colPlanePath.node().setIntoCollideMask(BitMask32.bit(1))
def createGuiObjects(self): self.dayButton = DirectButton(parent=self.dayButtonLocator, image=self.selectedFrame, relief=None, command=self.__clickedOnDay, pressEffect=1, rolloverSound=None, clickSound=None) self.numberWidget = DirectLabel(parent=self.numberLocator, relief=None, text=str(self.myDate.day), text_scale=0.04, text_align=TextNode.ACenter, text_font=ToontownGlobals.getInterfaceFont(), text_fg=Vec4(110 / 255.0, 126 / 255.0, 255 / 255.0, 1)) self.attachMarker(self.numberLocator) self.listXorigin = 0 self.listFrameSizeX = self.scrollBottomRightLocator.getX() - self.scrollLocator.getX() self.scrollHeight = self.scrollLocator.getZ() - self.scrollBottomRightLocator.getZ() self.listZorigin = self.scrollBottomRightLocator.getZ() self.listFrameSizeZ = self.scrollLocator.getZ() - self.scrollBottomRightLocator.getZ() self.arrowButtonXScale = 1 self.arrowButtonZScale = 1 self.itemFrameXorigin = 0 self.itemFrameZorigin = 0 self.buttonXstart = self.itemFrameXorigin + 0.21 self.gui = loader.loadModel('phase_3.5/models/gui/friendslist_gui') buttonOffSet = -0.01 incButtonPos = (0.0, 0, 0) decButtonPos = (0.0, 0, 0) itemFrameMinZ = self.listZorigin itemFrameMaxZ = self.listZorigin + self.listFrameSizeZ arrowUp = self.find('**/downScroll_up') arrowDown = self.find('**/downScroll_down') arrowHover = self.find('**/downScroll_hover') self.scrollList = DirectScrolledList(parent=self.scrollLocator, relief=None, pos=(0, 0, 0), incButton_image=(arrowUp, arrowDown, arrowHover, arrowUp), incButton_relief=None, incButton_scale=(self.arrowButtonXScale, 1, self.arrowButtonZScale), incButton_pos=incButtonPos, incButton_image3_color=Vec4(1, 1, 1, 0.2), decButton_image=(arrowUp, arrowDown, arrowHover, arrowUp), decButton_relief=None, decButton_scale=(self.arrowButtonXScale, 1, -self.arrowButtonZScale), decButton_pos=decButtonPos, decButton_image3_color=Vec4(1, 1, 1, 0.2), itemFrame_pos=(self.itemFrameXorigin, 0, -0.03), numItemsVisible=4, incButtonCallback=self.scrollButtonPressed, decButtonCallback=self.scrollButtonPressed) itemFrameParent = self.scrollList.itemFrame.getParent() self.scrollList.incButton.reparentTo(self.scrollDownLocator) self.scrollList.decButton.reparentTo(self.scrollUpLocator) arrowUp.removeNode() arrowDown.removeNode() arrowHover.removeNode() clipper = PlaneNode('clipper') clipper.setPlane(Plane(Vec3(-1, 0, 0), Point3(0.23, 0, 0))) clipNP = self.scrollList.component('itemFrame').attachNewNode(clipper) self.scrollList.component('itemFrame').setClipPlane(clipNP) return
def __init__(self, game_data, gfx_manager): self.game_data = game_data self.gui_traverser = CollisionTraverser() self.handler = CollisionHandlerQueue() self.selectable_objects = {} for cid, model in gfx_manager.character_models.items(): new_collision_node = CollisionNode('person_' + str(cid)) new_collision_node.addSolid( CollisionTube(0, 0, 0.5, 0, 0, 1.5, 0.5)) new_collision_nodepath = model.attachNewNode(new_collision_node) new_collision_nodepath.setTag("type", "character") new_collision_nodepath.setTag("id", str(cid)) picker_node = CollisionNode('mouseRay') picker_np = camera.attachNewNode(picker_node) self.picker_ray = CollisionRay() picker_node.addSolid(self.picker_ray) self.gui_traverser.addCollider(picker_np, self.handler) self.floor = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0))) self.floor_np = render.attachNewNode(CollisionNode('floor')) self.floor_np.setTag("type", "ground") self.floor_np.node().addSolid(self.floor)
class MoveCursor(object): _EDGES = 40 _zPos = 0 _movingUp = False _movingDown = False _color = Vec4(0.3, 0.3, 0.8, 1) _currentPos = Vec3(0, 0, 0) def __init__(self, parent, entity, foot=1): self.entity = entity self._moveRadCircleNP = NodePath("Movement Radius Node") self._moveLine = LineSegs() self._moveLineNP = NodePath("Movement Direction Line Node") self._moveZLine = LineSegs() self._moveZLineNP = NodePath("Movement Z Line Node") self._moveZFootNP = NodePath("Movement Z Foot Node") self._moveFootCircle = LineSegs() self._moveFootCircleNP = NodePath("Movement Foot Circle Node") self._attackRadCircle = LineSegs() self._attackRadCircleNP = NodePath("Attack Radius Node") self._np = NodePath("Movement Node") self.attackables = [] Event.Dispatcher().register(self, 'E_Key_ZUp', self.onZChange) Event.Dispatcher().register(self, 'E_Key_ZDown', self.onZChange) Event.Dispatcher().register(self, 'E_Key_ZUp-up', self.onZChange) Event.Dispatcher().register(self, 'E_Key_ZDown-up', self.onZChange) self.aaLevel = int(GameSettings().getSetting('ANTIALIAS')) self.parent = parent self.start = Vec3(0, 0, 0) self.moveRad = entity.moveRad self.footRad = foot self.attackRad = entity.attackRad self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0)) self.draw() self._np.reparentTo(self.parent) if self.aaLevel > 0: self._np.setAntialias(AntialiasAttrib.MLine, self.aaLevel) taskMgr.add(self.updateMovePos, 'Movement Indicator Update Task') def draw(self): # Setup curr mouse pos in 3d space posXY = self.getMouseXY() x = posXY.getX() y = posXY.getY() z = 0 # Draw movement radius moveRadLine = LineSegs() moveRadLine.setThickness(1) moveRadLine.setColor(self._color) moveRadLine.moveTo(self.moveRad, 0, 0) for i in range(self._EDGES + 1): newX = (self.moveRad * math.cos((2 * math.pi / self._EDGES) * i)) newY = (self.moveRad * math.sin((2 * math.pi / self._EDGES) * i)) moveRadLine.drawTo(newX, newY, 0) moveRadGeom = moveRadLine.create() self._moveRadCircleNP = NodePath(moveRadGeom) self._moveRadCircleNP.reparentTo(self._np) # Draw movement foot circle self._moveFootCircle.setThickness(1) self._moveFootCircle.setColor(self._color) self._moveFootCircle.moveTo(self.footRad, 0, 0) for i in range(self._EDGES): newX = (self.footRad * math.cos((2 * math.pi / self._EDGES) * i)) newY = (self.footRad * math.sin((2 * math.pi / self._EDGES) * i)) self._moveFootCircle.drawTo(newX, newY, 0) self._moveFootCircle.drawTo(self.footRad, 0, 0) moveFootCircleGeom = self._moveFootCircle.create() self._moveFootCircleNP = NodePath(moveFootCircleGeom) self._moveFootCircleNP.reparentTo(self._np) # Draw movement direction line self._moveLine.setThickness(1) self._moveLine.setColor(self._color) self._moveLine.moveTo(0, 0, 0) self._moveLine.drawTo(x, y, z) moveLine = self._moveLine.create() self._moveLineNP = NodePath(moveLine) self._moveLineNP.reparentTo(self._np) # Draw Z line self._moveZLine.setThickness(1) self._moveZLine.setColor(self._color) self._moveZLine.moveTo(self.start) self._moveZLine.drawTo(x, y, z) moveZLine = self._moveZLine.create() self._moveZLineNP = NodePath(moveZLine) self._moveZLineNP.reparentTo(self._np) # Draw Attack Radius self._attackRadCircle.setThickness(1) self._attackRadCircle.setColor(0.8, 0.0, 0.0, 1) self._attackRadCircle.moveTo(self.attackRad, 0, 0) for i in range(self._EDGES + 1): newX = (self.attackRad * math.cos((2 * math.pi / self._EDGES) * i)) newY = (self.attackRad * math.sin((2 * math.pi / self._EDGES) * i)) self._attackRadCircle.drawTo(newX, newY, 0) attackRadCircleGeom = self._attackRadCircle.create() self._attackRadCircleNP = NodePath(attackRadCircleGeom) self._attackRadCircleNP.reparentTo(self._np) def updateMovePos(self, Task): # endPos must be transformed in the the coord sys of the model m_pos = self.getMouseXY() if m_pos is not None: # Transform current mouse pos endPos = self.parent.getRelativePoint(render, m_pos) # Adjust Z coord if needed if self._movingUp: self._zPos += 0.1 elif self._movingDown: self._zPos -= 0.1 endPos.setZ(self._zPos) # Check if we're trying to move too far, if not update pos dist = math.sqrt(endPos.getX()**2 + endPos.getY()**2 + 2 * (endPos.getZ()**2)) if dist <= self.moveRad: self._moveLine.setVertex(1, endPos) self._moveFootCircleNP.setPos(endPos) self._moveZLine.setVertex( 0, Point3(endPos.getX(), endPos.getY(), 0)) self._moveZLine.setVertex(1, endPos) self._attackRadCircleNP.setPos(endPos) self._currentPos = render.getRelativePoint(self._np, endPos) # Check for attackable ships in range of current pos attackables = Entity.EntityManager().getEntitiesWithin( self._currentPos, self.attackRad) # Unhighlight ships no longer in range for e in self.attackables: if e not in attackables and isinstance( e, Entity.EntityShip): e.representation.unsetAttackable() # Highlight ships in range for e in attackables: if isinstance( e, Entity.EntityShip ) and e != self.entity and e.owner != self.entity.owner: e.representation.setAttackable() self.attackables = attackables return Task.cont def onZChange(self, event): if event.type == 'E_Key_ZUp': self._movingDown = False self._movingUp = True if event.type == 'E_Key_ZDown': self._movingUp = False self._movingDown = True if event.type == 'E_Key_ZUp-up': self._movingUp = False self._movingDown = False if event.type == 'E_Key_ZDown-up': self._movingUp = False self._movingDown = False def getMouseXY(self): # NOTE - this returns the mouse pos in the ships coord sys if base.mouseWatcherNode.hasMouse(): mpos = base.mouseWatcherNode.getMouse() pos3d = Point3() nearPoint = Point3() farPoint = Point3() base.camLens.extrude(mpos, nearPoint, farPoint) if self.plane.intersectsLine( pos3d, render.getRelativePoint(camera, nearPoint), render.getRelativePoint(camera, farPoint)): #print("Mouse ray intersects ground plane at " + str(pos3d)) return pos3d def getPosition(self): return self._currentPos def removeNode(self): taskMgr.remove('Movement Indicator Update Task') for e in self.attackables: if isinstance(e, Entity.EntityShip): e.representation.unsetAttackable() self._moveRadCircleNP.removeNode() self._moveLineNP.removeNode() self._moveZLineNP.removeNode() self._moveZFootNP.removeNode() self._moveFootCircleNP.removeNode() self._attackRadCircleNP.removeNode() self._np.removeNode() def __del__(self): # TODO - This isn't calling self.removeNode() correctly self._np.removeNode()
class WaterNode(Att_base): def __init__(self, x1, y1, x2, y2, z): Att_base.__init__(self, False, "Water1") # Water surface maker = CardMaker( 'water' ) maker.setFrame( x1, x2, y1, y2 ) self.waterNP = render.attachNewNode(maker.generate()) self.waterNP.setHpr(0,-90,0) self.waterNP.setPos(0,0,z) self.waterNP.setTransparency(TransparencyAttrib.MAlpha ) self.waterNP.setShader(loader.loadShader( 'Shaders/water1.sha' )) # Reflection plane self.waterPlane = Plane( Vec3( 0, 0, z+1 ), Point3( 0, 0, z ) ) planeNode = PlaneNode( 'waterPlane' ) planeNode.setPlane( self.waterPlane ) # Buffer and reflection camera self.buffer = base.win.makeTextureBuffer( 'waterBuffer', 512, 512 ) self.buffer.setClearColor( Vec4( 0, 0, 0, 1 ) ) cfa = CullFaceAttrib.makeReverse( ) rs = RenderState.make(cfa) self.watercamNP = base.makeCamera( self.buffer ) self.watercamNP.reparentTo(render) sa = ShaderAttrib.make() sa = sa.setShader(loader.loadShader('Shaders/splut3Clipped.sha') ) self.cam = self.watercamNP.node() self.cam.getLens( ).setFov( base.camLens.getFov( ) ) self.cam.getLens().setNear(1) self.cam.getLens().setFar(5000) self.cam.setInitialState( rs ) self.cam.setTagStateKey('Clipped') self.cam.setTagState('True', RenderState.make(sa)) # ---- water textures --------------------------------------------- # reflection texture, created in realtime by the 'water camera' tex0 = self.buffer.getTexture( ) tex0.setWrapU(Texture.WMClamp) tex0.setWrapV(Texture.WMClamp) ts0 = TextureStage( 'reflection' ) self.waterNP.setTexture( ts0, tex0 ) # distortion texture tex1 = loader.loadTexture('Textures/water.png') ts1 = TextureStage('distortion') self.waterNP.setTexture(ts1, tex1) def removeNode(self): self.cam.setInitialState(RenderState.makeEmpty()) self.watercamNP.removeNode() self.waterNP.clearShader() self.waterNP.removeNode() def Destroy(self): base.graphicsEngine.removeWindow(self.buffer) self.cam.setInitialState(RenderState.makeEmpty()) self.watercamNP.removeNode() self.waterNP.clearShader() self.waterNP.removeNode() def setParams(self, offset, strength, refractionfactor, refractivity, vx, vy, scale): self.waterNP.setShaderInput('waterdistort', Vec4( offset, strength, refractionfactor, refractivity )) self.waterNP.setShaderInput('wateranim', Vec4( vx, vy, scale, 0 )) # vx, vy, scale, skip def changeCameraPos(self, pos, mc=None): if mc != None: # update matrix of the reflection camera mf = self.waterPlane.getReflectionMat( ) self.watercamNP.setMat(mc * mf) def changeParams(self, object): self.setParams(self.att_offset.v,self.att_strength.v,self.att_refractionfactor.v,self.att_refractivity.v, self.att_vx.v, self.att_vy.v, self.att_scale.v) def setStandardControl(self): self.att_offset = Att_FloatRange(False, "Water:Offset", 0.0, 1.0, 0.4) self.att_strength = Att_FloatRange(False, "Water:Strength", 0.0, 100.0, 4) self.att_refractionfactor = Att_FloatRange(False, "Water:Refraction Factor", 0.0, 1.0, 0.2) self.att_refractivity = Att_FloatRange(False, "Water:Refractivity", 0.0, 1.0, 0.45) self.att_vx = Att_FloatRange(False, "Water:Speed X", -1.0, 1.0, 0.1) self.att_vy = Att_FloatRange(False, "Water:Speed Y", -1.0, 1.0, -0.1) self.att_scale = Att_FloatRange(False, "Water:Scale", 1.0, 200.0, 64.0,0) self.att_offset.setNotifier(self.changeParams) self.att_strength.setNotifier(self.changeParams) self.att_refractionfactor.setNotifier(self.changeParams) self.att_refractivity.setNotifier(self.changeParams) self.att_vx.setNotifier(self.changeParams) self.att_vy.setNotifier(self.changeParams) self.att_scale.setNotifier(self.changeParams) self.changeParams(None) def hide(self): self.waterNP.hide() def show(self): self.waterNP.show() def setFov(self, fov): # the reflection cam has to follow the base.cam fov self.cam.getLens().setFov(fov) def setCubeMap(self, cubemapfile): pass
def __init__(self, manager, xml): self.surface = getWaterSurface(manager) self.surface.reparentTo(render) self.surface.hide(BitMask32.bit(1)) # Invisible to reflection camera (speedup) self.surface.hide(BitMask32.bit(2)) # Invisible to volumetric lighting camera (speedup) self.surface.hide(BitMask32.bit(3)) # Invisible to shadow cameras (speedup) self.surface.setShader( loader.loadShader(manager.get("paths").getConfig().find("shaders").get("path") + "/water.cg") ) self.surface.setShaderInput("time", 0.0, 0.0, 0.0, 0.0) ntex = loader.loadTexture(manager.get("paths").getConfig().find("textures").get("path") + "/water-normal.png") ntex.setMinfilter(Texture.FTLinearMipmapLinear) self.surface.setShaderInput("normal", ntex) self.surface.setShaderInput("camera", base.cam) self.surface.setTransparency(TransparencyAttrib.MDual, 10) self.surface.setTwoSided(True) self.surface.setShaderInput("waveInfo", Vec4(0.4, 0.4, 0.4, 0)) self.surface.setShaderInput("param2", Vec4(-0.015, 0.005, 0.05, 0.05)) self.surface.setShaderInput("param3", Vec4(0.7, 0.3, 0, 0)) self.surface.setShaderInput("param4", Vec4(2.0, 0.5, 0.5, 0.0)) # self.surface.setShaderInput('speed', Vec4(-.8, -.4, -.9, .3)) self.surface.setShaderInput("speed", Vec4(0.2, -1.2, -0.2, -0.7)) self.surface.setShaderInput("deepcolor", Vec4(0.0, 0.3, 0.5, 1.0)) self.surface.setShaderInput("shallowcolor", Vec4(0.0, 1.0, 1.0, 1.0)) self.surface.setShaderInput("reflectioncolor", Vec4(0.95, 1.0, 1.0, 1.0)) self.surface.hide() self.wbuffer = base.win.makeTextureBuffer("water", 512, 512) self.wbuffer.setClearColorActive(True) self.wbuffer.setClearColor(base.win.getClearColor()) self.wcamera = base.makeCamera(self.wbuffer) if manager.get("sky") != None and manager.get("sky").model != None: self.sky = manager.get("sky").model.copyTo(self.wcamera) self.sky.setTwoSided(True) self.sky.setSz(self.sky, -1) self.sky.setClipPlaneOff(1) self.sky.show() self.sky.hide(BitMask32.bit(0)) # Hide for normal camera self.sky.hide(BitMask32.bit(2)) # Hide for volumetric lighting camera self.sky.hide(BitMask32.bit(3)) # Hide for shadow camera(s), if any else: self.sky = None self.wcamera.reparentTo(render) self.wcamera.node().setLens(base.camLens) self.wcamera.node().setCameraMask(BitMask32.bit(1)) self.surface.hide(BitMask32.bit(1)) wtexture = self.wbuffer.getTexture() wtexture.setWrapU(Texture.WMClamp) wtexture.setWrapV(Texture.WMClamp) wtexture.setMinfilter(Texture.FTLinearMipmapLinear) self.surface.setShaderInput("reflection", wtexture) self.wplane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0)) self.wplanenp = render.attachNewNode(PlaneNode("water", self.wplane)) tmpnp = NodePath("StateInitializer") tmpnp.setClipPlane(self.wplanenp) tmpnp.setAttrib(CullFaceAttrib.makeReverse()) self.wcamera.node().setInitialState(tmpnp.getState()) # self.fog = Fog('UnderwaterFog') # self.fog.setColor(0.0,0.3,0.5) self.fogEnabled = False
def __init__(self, parent, entity, foot=1): # We keep a reference to the entity self.entity = entity # Setup the components of the cursor self._moveRadCircleNP = NodePath("Movement Radius Node") self._moveLine = LineSegs() self._moveLineNP = NodePath("Movement Direction Line Node") self._moveZLine = LineSegs() self._moveZLineNP = NodePath("Movement Z Line Node") self._moveZFootNP = NodePath("Movement Z Foot Node") self._moveFootCircle = LineSegs() self._moveFootCircleNP = NodePath("Movement Foot Circle Node") self._np = NodePath("Movement Node") self.aaLevel = 16 self.parent = parent self.start = Vec3(0, 0, 0) self.moveRad = entity.moveRadius self.footRad = foot self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0)) if self.aaLevel > 0: self._np.setAntialias(AntialiasAttrib.MLine, self.aaLevel) x = 0 y = 0 z = 0 # Draw movement radius moveRadLine = LineSegs() moveRadLine.setThickness(1) moveRadLine.setColor(self._color) moveRadLine.moveTo(self.moveRad, 0, 0) for i in range(self._EDGES + 1): newX = (self.moveRad * math.cos((2*math.pi/self._EDGES)*i)) newY = (self.moveRad * math.sin((2*math.pi/self._EDGES)*i)) moveRadLine.drawTo(newX, newY, 0) moveRadGeom = moveRadLine.create() self._moveRadCircleNP = NodePath(moveRadGeom) self._moveRadCircleNP.reparentTo(self._np) # Draw movement foot circle self._moveFootCircle.setThickness(1) self._moveFootCircle.setColor(self._color) self._moveFootCircle.moveTo(self.footRad, 0, 0) for i in range(self._EDGES): newX = (self.footRad * math.cos((2*math.pi/self._EDGES)*i)) newY = (self.footRad * math.sin((2*math.pi/self._EDGES)*i)) self._moveFootCircle.drawTo(newX, newY, 0) self._moveFootCircle.drawTo(self.footRad, 0, 0) moveFootCircleGeom = self._moveFootCircle.create() self._moveFootCircleNP = NodePath(moveFootCircleGeom) self._moveFootCircleNP.reparentTo(self._np) # Draw movement direction line self._moveLine.setThickness(1) self._moveLine.setColor(self._color) self._moveLine.moveTo(0, 0, 0) self._moveLine.drawTo(x, y, z) self.moveLineGO = self._moveLine.create(True) self._moveLineNP = NodePath(self.moveLineGO) self._moveLineNP.reparentTo(self._np)
class MoveCursor(object): _EDGES = 40 _zPos = 0 _movingUp = False _movingDown = False _color = Vec4(0.3, 0.3, 0.8, 1) _currentPos = Vec3(0, 0, 0) def __init__(self, parent, entity, foot=1): # We keep a reference to the entity self.entity = entity # Setup the components of the cursor self._moveRadCircleNP = NodePath("Movement Radius Node") self._moveLine = LineSegs() self._moveLineNP = NodePath("Movement Direction Line Node") self._moveZLine = LineSegs() self._moveZLineNP = NodePath("Movement Z Line Node") self._moveZFootNP = NodePath("Movement Z Foot Node") self._moveFootCircle = LineSegs() self._moveFootCircleNP = NodePath("Movement Foot Circle Node") self._np = NodePath("Movement Node") self.aaLevel = 16 self.parent = parent self.start = Vec3(0, 0, 0) self.moveRad = entity.moveRadius self.footRad = foot self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0)) if self.aaLevel > 0: self._np.setAntialias(AntialiasAttrib.MLine, self.aaLevel) x = 0 y = 0 z = 0 # Draw movement radius moveRadLine = LineSegs() moveRadLine.setThickness(1) moveRadLine.setColor(self._color) moveRadLine.moveTo(self.moveRad, 0, 0) for i in range(self._EDGES + 1): newX = (self.moveRad * math.cos((2*math.pi/self._EDGES)*i)) newY = (self.moveRad * math.sin((2*math.pi/self._EDGES)*i)) moveRadLine.drawTo(newX, newY, 0) moveRadGeom = moveRadLine.create() self._moveRadCircleNP = NodePath(moveRadGeom) self._moveRadCircleNP.reparentTo(self._np) # Draw movement foot circle self._moveFootCircle.setThickness(1) self._moveFootCircle.setColor(self._color) self._moveFootCircle.moveTo(self.footRad, 0, 0) for i in range(self._EDGES): newX = (self.footRad * math.cos((2*math.pi/self._EDGES)*i)) newY = (self.footRad * math.sin((2*math.pi/self._EDGES)*i)) self._moveFootCircle.drawTo(newX, newY, 0) self._moveFootCircle.drawTo(self.footRad, 0, 0) moveFootCircleGeom = self._moveFootCircle.create() self._moveFootCircleNP = NodePath(moveFootCircleGeom) self._moveFootCircleNP.reparentTo(self._np) # Draw movement direction line self._moveLine.setThickness(1) self._moveLine.setColor(self._color) self._moveLine.moveTo(0, 0, 0) self._moveLine.drawTo(x, y, z) self.moveLineGO = self._moveLine.create(True) self._moveLineNP = NodePath(self.moveLineGO) self._moveLineNP.reparentTo(self._np) def updateMovePos(self, Task): # endPos must be transformed in the the coord sys of the model m_pos = self.getMouseXY() if m_pos is not None: # Transform current mouse pos endPos = self.parent.getRelativePoint(render, m_pos) # Adjust Z coord if needed if self._movingUp: self._zPos += 0.1 elif self._movingDown: self._zPos -= 0.1 endPos.setZ(self._zPos) # Check if we're trying to move too far, if not update pos dist = math.sqrt(endPos.getX()**2 + endPos.getY()**2 + 2*(endPos.getZ()**2)) if dist <= self.moveRad: self._moveLine.setVertex(1, endPos) self._moveFootCircleNP.setPos(endPos) #self._currentPos = self.parent.getRelativePoint(self.parent, endPos) #print("endPos=%s"%endPos) #print("myRelPos=%s"%self._currentPos) self._currentPos = endPos return Task.cont def getMouseXY(self): # NOTE - this returns the mouse pos in the ships coord sys if base.mouseWatcherNode.hasMouse(): mpos = base.mouseWatcherNode.getMouse() pos3d = Point3() nearPoint = Point3() farPoint = Point3() base.camLens.extrude(mpos, nearPoint, farPoint) if self.plane.intersectsLine(pos3d, render.getRelativePoint(camera, nearPoint), render.getRelativePoint(camera, farPoint)): return pos3d return None def getPosition(self): return self._currentPos def startDrawing(self): self._np.reparentTo(self.parent) taskMgr.add(self.updateMovePos, 'Movement Indicator Update Task') def stopDrawing(self): taskMgr.remove('Movement Indicator Update Task') self._np.detachNode()
def __init__(self, world, x1, y1, x2, y2, z): self.world = world logging.info(('setting up water plane at z=' + str(z))) # Water surface maker = CardMaker('water') maker.setFrame(x1, x2, y1, y2) self.waterNP = render.attachNewNode(maker.generate()) self.waterNP.setHpr(0, -90, 0) self.waterNP.setPos(0, 0, z) self.waterNP.setTransparency(TransparencyAttrib.MAlpha) self.waterNP.setShader(loader.loadShader('shaders/water.sha')) self.waterNP.setShaderInput('wateranim', Vec4(0.03, -0.015, 64.0, 0)) # vx, vy, scale, skip # offset, strength, refraction factor (0=perfect mirror, 1=total refraction), refractivity self.waterNP.setShaderInput('waterdistort', Vec4(0.4, 4.0, 0.25, 0.45)) self.waterNP.setShaderInput('time', 0) # Reflection plane self.waterPlane = Plane(Vec3(0, 0, z + 1), Point3(0, 0, z)) planeNode = PlaneNode('waterPlane') planeNode.setPlane(self.waterPlane) # Buffer and reflection camera buffer = base.win.makeTextureBuffer('waterBuffer', 512, 512) buffer.setClearColor(Vec4(0, 0, 0, 1)) cfa = CullFaceAttrib.makeReverse() rs = RenderState.make(cfa) self.watercamNP = base.makeCamera(buffer) self.watercamNP.reparentTo(render) #sa = ShaderAttrib.make() #sa = sa.setShader(loader.loadShader('shaders/splut3Clipped.sha') ) cam = self.watercamNP.node() cam.getLens().setFov(base.camLens.getFov()) cam.getLens().setNear(1) cam.getLens().setFar(5000) cam.setInitialState(rs) cam.setTagStateKey('Clipped') #cam.setTagState('True', RenderState.make(sa)) # ---- water textures ----------------------------------------------- #reflection texture, created in realtime by the 'water camera' tex0 = buffer.getTexture() tex0.setWrapU(Texture.WMClamp) tex0.setWrapV(Texture.WMClamp) ts0 = TextureStage('reflection') self.waterNP.setTexture(ts0, tex0) # distortion texture tex1 = loader.loadTexture('textures/water.png') ts1 = TextureStage('distortion') self.waterNP.setTexture(ts1, tex1) # ---- Fog --- broken min = Point3(x1, y1, -999.0) max = Point3(x2, y2, z) boundry = BoundingBox(min, max self.waterFog = Fog('waterFog') self.waterFog.setBounds(boundry) colour = (0.2, 0.5, 0.8) self.waterFog.setColor(*colour) self.waterFog.setExpDensity(0.05) render.attachNewNode(self.waterFog) #render.setFog(world.waterFog) taskMgr.add(self.update, "waterTask") def update(self, task): # update matrix of the reflection camera mc = base.camera.getMat() mf = self.waterPlane.getReflectionMat() self.watercamNP.setMat(mc * mf) self.waterNP.setShaderInput('time', task.time) self.waterNP.setX(self.world.ralph.getX()) self.waterNP.setY(self.world.ralph.getY()) return task.cont
def Transform( self ): startVec = self.startVec axis = self.GetSelectedAxis() if axis is not None and axis.vector == CAMERA_VECTOR: endVec = self.getRelativeVector( self.rootNp, self.GetAxisPoint( axis ) - self.getPos() ) cross = startVec.cross( endVec ) direction = self.getRelativeVector( self.camera, Vec3(0, -1, 0) ).dot( cross ) sign = math.copysign( 1, direction ) # Get the rotation axis rotAxis = self.getRelativeVector( self.camera, Vec3(0, -1, 0) ) * sign else: if self.collEntry.getIntoNode() == self.initCollEntry.getIntoNode(): endVec = self.collEntry.getSurfaceNormal( self ) else: endVec = self.getRelativeVector( self.rootNp, self.GetAxisPoint( self.foobar ) - self.getPos() ) # If an axis is selected then constrain the vectors by projecting # them onto a plane whose normal is the axis vector if axis is not None: plane = Plane( axis.vector, Point3( 0 ) ) startVec = Vec3( plane.project( Point3( startVec ) ) ) endVec = Vec3( plane.project( Point3( endVec ) ) ) # Get the rotation axis rotAxis = endVec.cross( startVec ) * -1 # Return if the rotation vector is not valid, ie it does not have any # length if not rotAxis.length(): return # Normalize all vectors startVec.normalize() endVec.normalize() rotAxis.normalize() # Get the amount of degrees to rotate degs = startVec.angleDeg( endVec ) # Transform the gizmo if in local rotation mode newRotMat = Mat4().rotateMat( degs, rotAxis ) if self.local: self.setMat( newRotMat * self.getMat() ) # Transform all attached node paths for i, np in enumerate( self.attachedNps ): # Split the transform into scale, rotation and translation # matrices transMat, rotMat, scaleMat = commonUtils.GetTrsMatrices( np.getTransform() ) # Perform transforms in local or world space if self.local: np.setMat( scaleMat * newRotMat * rotMat * transMat ) else: self.initNpXforms[i].getQuat().extractToMatrix( rotMat ) np.setMat( scaleMat * rotMat * newRotMat * transMat )
class CameraHandler(DirectObject.DirectObject): def __init__(self, showbase): self.showbase = showbase self.showbase.disableMouse() # This disables the default mouse based camera control used by panda. This default control is awkward, and won't be used. self.showbase.camera.setPos(0, -150, 200) self.showbase.camera.lookAt(0, 0, 0) # Gives the camera an initial position and rotation. self.mx, self.my = 0, 0 # Sets up variables for storing the mouse coordinates self.orbiting = False # A boolean variable for specifying whether the camera is in orbiting mode. Orbiting mode refers to when the camera is being moved # because the user is holding down the right mouse button. self.target = Vec3() # sets up a vector variable for the camera's target. The target will be the coordinates that the camera is currently focusing on. self.camDist = 150 # A variable that will determine how far the camera is from it's target focus self.panRateDivisor = 10 # This variable is used as a divisor when calculating how far to move the camera when panning. Higher numbers will yield slower panning # and lower numbers will yield faster panning. This must not be set to 0. self.panZoneSize = .1 # This variable controls how close the mouse cursor needs to be to the edge of the screen to start panning the camera. It must be less than 1, # and I recommend keeping it less than .2 self.panLimitsX = Vec2(-1000, 1000) self.panLimitsY = Vec2(-1000, 1000) # These two vairables will serve as limits for how far the camera can pan, so you don't scroll away from the map. self.maxZoomOut = 500 self.maxZoomIn = 25 #These two variables set the max distance a person can zoom in or out self.orbitRate = 75 # This is the rate of speed that the camera will rotate when middle mouse is pressed and mouse moved # recommended rate 50-100 self.setTarget(0, 0, 0) # calls the setTarget function to set the current target position to the origin. self.turnCameraAroundPoint(0, 0) # calls the turnCameraAroundPoint function with a turn amount of 0 to set the camera position based on the target and camera distance self.accept("mouse2", self.startOrbit) # sets up the camrea handler to accept a right mouse click and start the "drag" mode. self.accept("mouse2-up", self.stopOrbit) # sets up the camrea handler to understand when the right mouse button has been released, and ends the "drag" mode when # the release is detected. self.storeX = 0 self.storeY = 0 # for storing of the x and y for the orbit # The next pair of lines use lambda, which creates an on-the-spot one-shot function. self.accept("wheel_up", self.zoomIn) # sets up the camera handler to detet when the mouse wheel is rolled upwards and uses a lambda function to call the # adjustCamDist function with the argument 0.9 self.accept("wheel_down", self.zoomOut) # sets up the camera handler to detet when the mouse wheel is rolled upwards and uses a lambda function to call the # adjustCamDist function with the argument 1.1 # Keys array (down if 1, up if 0) self.keys = { "cam-left": 0, "cam-right": 0, "cam-up": 0, "cam-down": 0 } # Using Arrow Keys self.accept("arrow_left", self.setValue, [self.keys, "cam-left", 1]) self.accept("arrow_right", self.setValue, [self.keys, "cam-right", 1]) self.accept("arrow_up", self.setValue, [self.keys, "cam-up", 1]) self.accept("arrow_down", self.setValue, [self.keys, "cam-down", 1]) self.accept("arrow_left-up", self.setValue, [self.keys, "cam-left", 0]) self.accept("arrow_right-up", self.setValue, [self.keys, "cam-right", 0]) self.accept("arrow_up-up", self.setValue, [self.keys, "cam-up", 0]) self.accept("arrow_down-up", self.setValue, [self.keys, "cam-down", 0]) self.keyPanRate = 1.5 # pan rate for when user presses the arrow keys # set up plane for checking collision with for mouse-3d world self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0)) def destroy(self): self.ignoreAll() def setValue(self, array, key, value): array[key] = value def clamp(self, val, minVal, maxVal): val = min(max(val, minVal), maxVal) return val def zoomOut(self): if self.camDist <= self.maxZoomOut: self.adjustCamDist(1.1) return True def zoomIn(self): if self.camDist >= self.maxZoomIn: self.adjustCamDist(0.9) return True def turnCameraAroundPoint(self, deltaX, deltaY): # This function performs two important tasks. First, it is used for the camera orbital movement that occurs when the # right mouse button is held down. It is also called with 0s for the rotation inputs to reposition the camera during the # panning and zooming movements. # The delta inputs represent the change in rotation of the camera, which is also used to determine how far the camera # actually moves along the orbit. newCamHpr = Vec3() newCamPos = Vec3() # Creates temporary containers for the new rotation and position values of the camera. camHpr = self.showbase.camera.getHpr() # Creates a container for the current HPR of the camera and stores those values. newCamHpr.setX(camHpr.getX() + deltaX) newCamHpr.setY(self.clamp(camHpr.getY() - deltaY, -85, -10)) newCamHpr.setZ(camHpr.getZ()) # Adjusts the newCamHpr values according to the inputs given to the function. The Y value is clamped to prevent # the camera from orbiting beneath the ground plane and to prevent it from reaching the apex of the orbit, which # can cause a disturbing fast-rotation glitch. self.showbase.camera.setHpr(newCamHpr) # Sets the camera's rotation to the new values. angleradiansX = newCamHpr.getX() * (math.pi / 180.0) angleradiansY = newCamHpr.getY() * (math.pi / 180.0) # Generates values to be used in the math that will calculate the new position of the camera. newCamPos.setX(self.camDist * math.sin(angleradiansX) * math.cos(angleradiansY) + self.target.getX()) newCamPos.setY(-self.camDist * math.cos(angleradiansX) * math.cos(angleradiansY) + self.target.getY()) newCamPos.setZ(-self.camDist * math.sin(angleradiansY) + self.target.getZ()) self.showbase.camera.setPos(newCamPos.getX(), newCamPos.getY(), newCamPos.getZ()) # Performs the actual math to calculate the camera's new position and sets the camera to that position. #Unfortunately, this math is over my head, so I can't fully explain it. self.showbase.camera.lookAt(self.target.getX(), self.target.getY(), self.target.getZ()) # Points the camera at the target location. def getTarget(self): return self.target # returns the cur def setTarget(self, x, y, z): #This function is used to give the camera a new target position. x = self.clamp(x, self.panLimitsX.getX(), self.panLimitsX.getY()) self.target.setX(x) y = self.clamp(y, self.panLimitsY.getX(), self.panLimitsY.getY()) self.target.setY(y) self.target.setZ(z) # Stores the new target position values in the target variable. The x and y values are clamped to the pan limits. def setPanLimits(self, xMin, xMax, yMin, yMax): # This function is used to set the limitations of the panning movement. self.panLimitsX = (xMin, xMax) self.panLimitsY = (yMin, yMax) # Sets the inputs into the limit variables. def startOrbit(self): # This function puts the camera into orbiting mode. # Get windows properties props = WindowProperties() # Set Hide Cursor Property #props.setCursorHidden(True) # Set properties self.showbase.win.requestProperties(props) # hide cursor if self.showbase.mouseWatcherNode.hasMouse(): # We're going to use the mouse, so we have to make sure it's in the game window. If it's not and we try to use it, we'll get # a crash error. mpos = self.showbase.mouseWatcherNode.getMouse() self.storeX = mpos.getX() self.storeY = mpos.getY() # take current cursor values self.showbase.win.movePointer(0, self.showbase.win.getXSize() / 2, self.showbase.win.getYSize() / 2) # set to center self.mx = 0 self.my = 0 self.orbiting = True # Sets the orbiting variable to true to designate orbiting mode as on. def stopOrbit(self): # This function takes the camera out of orbiting mode. self.orbiting = False # Sets the orbiting variable to false to designate orbiting mode as off. self.showbase.win.movePointer(0, int((self.storeX + 1.0) / 2 * self.showbase.win.getXSize()), int(self.showbase.win.getYSize() - ((self.storeY + 1.0) / 2 * self.showbase.win.getYSize()))) # set to taken cursor values from startOrbit if self.showbase.mouseWatcherNode.hasMouse(): # We're going to use the mouse, so we have to make sure it's in the game window. If it's not and we try to use it, we'll get # a crash error. mpos = self.showbase.mouseWatcherNode.getMouse() self.mx = mpos.getX() self.my = mpos.getY() # Get windows properties props = WindowProperties() # Set Hide Cursor Property props.setCursorHidden(False) # Set properties self.showbase.win.requestProperties(props) # reshow cursor def adjustCamDist(self, distFactor): # This function increases or decreases the distance between the camera and the target position to simulate zooming in and out. # The distFactor input controls the amount of camera movement. # For example, inputing 0.9 will set the camera to 90% of it's previous distance. self.camDist = self.camDist * distFactor # Sets the new distance into self.camDist. self.turnCameraAroundPoint(0, 0) # Calls turnCameraAroundPoint with 0s for the rotation to reset the camera to the new position. def camMoveTask(self, dt): # This task is the camera handler's work house. It's set to be called every frame and will control both orbiting and panning the camera. if self.showbase.mouseWatcherNode.hasMouse(): # We're going to use the mouse, so we have to make sure it's in the game window. If it's not and we try to use it, we'll get # a crash error. mpos = self.showbase.mouseWatcherNode.getMouse() # Gets the mouse position if self.orbiting: # Checks to see if the camera is in orbiting mode. Orbiting mode overrides panning, because it would be problematic if, while # orbiting the camera the mouse came close to the screen edge and started panning the camera at the same time. self.turnCameraAroundPoint((self.mx - mpos.getX()) * self.orbitRate * dt, (self.my - mpos.getY()) * self.orbitRate * dt) else: # If the camera isn't in orbiting mode, we check to see if the mouse is close enough to the edge of the screen to start panning moveY = False moveX = False # these two booleans are used to denote if the camera needs to pan. X and Y refer to the mouse position that causes the # panning. X is the left or right edge of the screen, Y is the top or bottom. if self.my > (1 - self.panZoneSize): angleradiansX1 = self.showbase.camera.getH() * (math.pi / 180.0) panRate1 = (1 - self.my - self.panZoneSize) * (self.camDist / self.panRateDivisor) moveY = True if self.my < (-1 + self.panZoneSize): angleradiansX1 = self.showbase.camera.getH() * (math.pi / 180.0) + math.pi panRate1 = (1 + self.my - self.panZoneSize) * (self.camDist / self.panRateDivisor) moveY = True if self.mx > (1 - self.panZoneSize): angleradiansX2 = self.showbase.camera.getH() * (math.pi / 180.0) + math.pi * 0.5 panRate2 = (1 - self.mx - self.panZoneSize) * (self.camDist / self.panRateDivisor) moveX = True if self.mx < (-1 + self.panZoneSize): angleradiansX2 = self.showbase.camera.getH() * (math.pi / 180.0) - math.pi * 0.5 panRate2 = (1 + self.mx - self.panZoneSize) * (self.camDist / self.panRateDivisor) moveX = True # These four blocks check to see if the mouse cursor is close enough to the edge of the screen to start panning and then # perform part of the math necessary to find the new camera position. Once again, the math is a bit above my head, so # I can't properly explain it. These blocks also set the move booleans to true so that the next lines will move the camera. # If up or down keys are pressed if self.keys["cam-up"] ^ self.keys["cam-down"]: moveY = True panRate1 = self.keyPanRate # Update warlock position on z plane if self.keys["cam-up"]: angleradiansX1 = self.showbase.camera.getH() * (math.pi / 180.0) + math.pi if self.keys["cam-down"]: angleradiansX1 = self.showbase.camera.getH() * (math.pi / 180.0) # If left or right keys are pressed if self.keys["cam-left"] ^ self.keys["cam-right"]: moveX = True panRate2 = self.keyPanRate # Update warlock position on x plane if self.keys["cam-left"]: angleradiansX2 = self.showbase.camera.getH() * (math.pi / 180.0) + math.pi * 0.5 if self.keys["cam-right"]: angleradiansX2 = self.showbase.camera.getH() * (math.pi / 180.0) - math.pi * 0.5 if moveY: tempX = self.target.getX() + math.sin(angleradiansX1) * panRate1 * dt * 50 tempX = self.clamp(tempX, self.panLimitsX.getX(), self.panLimitsX.getY()) self.target.setX(tempX) tempY = self.target.getY() - math.cos(angleradiansX1) * panRate1 * dt * 50 tempY = self.clamp(tempY, self.panLimitsY.getX(), self.panLimitsY.getY()) self.target.setY(tempY) self.turnCameraAroundPoint(0, 0) if moveX: tempX = self.target.getX()-math.sin(angleradiansX2) * panRate2 * dt * 50 tempX = self.clamp(tempX, self.panLimitsX.getX(), self.panLimitsX.getY()) self.target.setX(tempX) tempY = self.target.getY() + math.cos(angleradiansX2) * panRate2 * dt * 50 tempY = self.clamp(tempY, self.panLimitsY.getX(), self.panLimitsY.getY()) self.target.setY(tempY) self.turnCameraAroundPoint(0, 0) # These two blocks finalize the math necessary to find the new camera position and apply the transformation to the # camera's TARGET. Then turnCameraAroundPoint is called with 0s for rotation, and it resets the camera position based # on the position of the target. The x and y values are clamped to the pan limits before they are applied. #print(self.target) self.mx = mpos.getX() self.my = mpos.getY() # The old mouse positions are updated to the current mouse position as the final step. # Finds 3d world point on the z = 0 plane for destination/target def getMouse3D(self): # make sure process has the mouse to not cause error if self.showbase.mouseWatcherNode.hasMouse(): # get screen coordinates of mouse mpos = self.showbase.mouseWatcherNode.getMouse() pos3d = Point3() nearPoint = Point3() farPoint = Point3() # find vector of cameras facing from mouse screen coordinates and get near and far points on frustrum self.showbase.camLens.extrude(mpos, nearPoint, farPoint) # check for intersection with z = 0 plane if self.plane.intersectsLine(pos3d, self.showbase.render.getRelativePoint(self.showbase.camera, nearPoint), self.showbase.render.getRelativePoint(self.showbase.camera, farPoint)): # return this position if exists return pos3d # or return (-1, -1, -1) return Vec3(-1, -1, -1)
def __init__(self, showbase): self.showbase = showbase self.showbase.disableMouse() # This disables the default mouse based camera control used by panda. This default control is awkward, and won't be used. self.showbase.camera.setPos(0, -150, 200) self.showbase.camera.lookAt(0, 0, 0) # Gives the camera an initial position and rotation. self.mx, self.my = 0, 0 # Sets up variables for storing the mouse coordinates self.orbiting = False # A boolean variable for specifying whether the camera is in orbiting mode. Orbiting mode refers to when the camera is being moved # because the user is holding down the right mouse button. self.target = Vec3() # sets up a vector variable for the camera's target. The target will be the coordinates that the camera is currently focusing on. self.camDist = 150 # A variable that will determine how far the camera is from it's target focus self.panRateDivisor = 10 # This variable is used as a divisor when calculating how far to move the camera when panning. Higher numbers will yield slower panning # and lower numbers will yield faster panning. This must not be set to 0. self.panZoneSize = .1 # This variable controls how close the mouse cursor needs to be to the edge of the screen to start panning the camera. It must be less than 1, # and I recommend keeping it less than .2 self.panLimitsX = Vec2(-1000, 1000) self.panLimitsY = Vec2(-1000, 1000) # These two vairables will serve as limits for how far the camera can pan, so you don't scroll away from the map. self.maxZoomOut = 500 self.maxZoomIn = 25 #These two variables set the max distance a person can zoom in or out self.orbitRate = 75 # This is the rate of speed that the camera will rotate when middle mouse is pressed and mouse moved # recommended rate 50-100 self.setTarget(0, 0, 0) # calls the setTarget function to set the current target position to the origin. self.turnCameraAroundPoint(0, 0) # calls the turnCameraAroundPoint function with a turn amount of 0 to set the camera position based on the target and camera distance self.accept("mouse2", self.startOrbit) # sets up the camrea handler to accept a right mouse click and start the "drag" mode. self.accept("mouse2-up", self.stopOrbit) # sets up the camrea handler to understand when the right mouse button has been released, and ends the "drag" mode when # the release is detected. self.storeX = 0 self.storeY = 0 # for storing of the x and y for the orbit # The next pair of lines use lambda, which creates an on-the-spot one-shot function. self.accept("wheel_up", self.zoomIn) # sets up the camera handler to detet when the mouse wheel is rolled upwards and uses a lambda function to call the # adjustCamDist function with the argument 0.9 self.accept("wheel_down", self.zoomOut) # sets up the camera handler to detet when the mouse wheel is rolled upwards and uses a lambda function to call the # adjustCamDist function with the argument 1.1 # Keys array (down if 1, up if 0) self.keys = { "cam-left": 0, "cam-right": 0, "cam-up": 0, "cam-down": 0 } # Using Arrow Keys self.accept("arrow_left", self.setValue, [self.keys, "cam-left", 1]) self.accept("arrow_right", self.setValue, [self.keys, "cam-right", 1]) self.accept("arrow_up", self.setValue, [self.keys, "cam-up", 1]) self.accept("arrow_down", self.setValue, [self.keys, "cam-down", 1]) self.accept("arrow_left-up", self.setValue, [self.keys, "cam-left", 0]) self.accept("arrow_right-up", self.setValue, [self.keys, "cam-right", 0]) self.accept("arrow_up-up", self.setValue, [self.keys, "cam-up", 0]) self.accept("arrow_down-up", self.setValue, [self.keys, "cam-down", 0]) self.keyPanRate = 1.5 # pan rate for when user presses the arrow keys # set up plane for checking collision with for mouse-3d world self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0))
class Game(DirectObject): def __init__(self): self.count_tree=0 self.playVideo("intro.mp4") base.disableMouse() self.environ = loader.loadModel("models/scene.egg.pz") self.objects=loader.loadModel("models/objects.egg") self.plants=loader.loadModel("models/plants.egg") self.plants.reparentTo(render) self.objects.reparentTo(render) self.environ.reparentTo(render) self.makeSkyBox() self.makingActor() self.makeRacers() self.controlSkater() self.makeLights() self.makeWater() #self.controlRacer() self.addCollisions() self.addDuck() #self.makeRacingai() self.tree_array={} self.stone_array={} self.count_stone=0 self.isSitted=False self.bench={} self.count_bench=0; self.AddBench(-40,-30) self.AddBench(-40,-40,180) self.AddBench(40,-30) self.AddBench(40,-40,180) self.AddBench(40,30) self.AddBench(40,40,180) self.AddBench(-40,30) self.AddBench(-40,40,180) for i in range(-70,70,6): #for j in range (-80,-70,3): self.AddTree(i,-65) for i in range(-70,70,6): #for j in range (-80,-70,3): self.AddTree(i+5,-70) for i in range(-70,70,6): #for j in range (60,70,3): self.AddTree(i,65) for i in range(-70,70,6): #for j in range (60,70,3): self.AddTree(i+5,70) for j in range(-70,70,6): #for i in range (60,70,3): self.AddTree(65,j) for j in range(-70,70,6): #for i in range (60,70,3): self.AddTree(70,j+5) for j in range(-70,70,6): #for i in range (-80,-70,3): self.AddTree(-70,j) for j in range(-70,70,6): #for i in range (-80,-70,3): self.AddTree(-65,j+5) self.initailState() render.setShaderAuto() def playVideo(self,src): tex = MovieTexture("name") assert tex.read(src), "Failed to load video!" cm = CardMaker("My Fullscreen Card"); cm.setFrameFullscreenQuad() cm.setUvRange(tex) card = NodePath(cm.generate()) card.reparentTo(render2d) card.setTexture(tex) card.setTexScale(TextureStage.getDefault(), tex.getTexScale()) sound=loader.loadSfx(src) tex.synchronizeTo(sound) tex.setLoop(False) sound.play() def myTask(task): i=14 if(src=='talk.mp4'): i=7 if (int(tex.getTime()) >=i): #print "Stoping" card.remove() return task.done # if myMovieTexture.getTime() == myMovieLength: # print "movie puri" return task.cont taskMgr.add(myTask, "Task") def addDuck(self): self.duck={} self.count_duck=0 self.interval1={};self.interval11={} self.interval2={};self.interval22={} for i in range(0,3,1): self.duck[self.count_duck]=loader.loadModel("models/duck.egg") self.duck[self.count_duck].setScale(random.uniform(5,7)) self.duck[self.count_duck].setZ(0.65) self.duck[self.count_duck].setX(i*3-3) self.duck[self.count_duck].reparentTo(render) self.interval1[self.count_duck]= self.duck[self.count_duck].posInterval(10,Point3(i*3-3, random.uniform(0,12),0.65),startPos=Point3(i*3-3,-1*random.uniform(0,12),0.65)) self.interval11[self.count_duck]=self.duck[self.count_duck].hprInterval(0.1, Vec3(0, 0, 0)) self.interval2[self.count_duck]= self.duck[self.count_duck].posInterval(10,Point3(i*3-3,-1*random.uniform(0,12),0.65),startPos=Point3(i*3-3,random.uniform(0,12),0.65)) self.interval22[self.count_duck]=self.duck[self.count_duck].hprInterval(0.1, Vec3(180, 0, 0)) if(self.count_duck==0): self.mySequence=Sequence(self.interval1[self.count_duck], name="duck") self.mySequence.append(self.interval11[self.count_duck]) self.mySequence.append(self.interval2[self.count_duck]) self.mySequence.append(self.interval22[self.count_duck]) self.count_duck=self.count_duck+1 self.mySequence.loop() def makeSkyBox(self): #colour = (0.5,0.8,0.5) self.skybox=loader.loadModel("models/skybox.egg") self.skybox.reparentTo(render) self.skybox.setLightOff(1) self.skybox.setZ(-10) self.skybox.setScale(140,140,70) def makingActor(self): self.skater = Actor("models/scater.egg",{"fall":"models/scaterfall.egg","skate":"models/scater.egg", "walk":"models/scaterwalk.egg","run":"models/scaterrun.egg","sit":"models/scatersit.egg"}) self.skater.setPos(-20.67,-41.99,0) self.skater.setScale(0.075,0.075,0.075) #self.skater.setH(180) self.skater.reparentTo(render) def makeWater(self): self.water = loader.loadModel("models/water.egg") self.water.setPos(0,0,1) self.water.setShader(loader.loadShader('shaders/water.sha')) self.water.setShaderInput('wateranim', Vec4(0.03, -0.015, 64.0, 0)) self.water.setShaderInput('waterdistort', Vec4(0.4, 4.0, 0.25, 0.45)) self.water.setShaderInput('time', 0) buffer = base.win.makeTextureBuffer('waterBuffer', 512, 512) #buffer.setClearColor(Vec4(0.3, 0.3, 1, 1)) cfa = CullFaceAttrib.makeReverse() rs = RenderState.make(cfa) self.watercamNP = base.makeCamera(buffer) self.watercamNP.reparentTo(render) cam = self.watercamNP.node() cam.getLens().setFov(base.camLens.getFov()) cam.getLens().setNear(1) cam.getLens().setFar(5000) cam.setInitialState(rs) self.waterPlane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0)) planeNode = PlaneNode('waterPlane') planeNode.setPlane(self.waterPlane) #cam.lookAt(0,0,-1) cam.setTagStateKey('Clipped') tex0 = buffer.getTexture() tex0.setWrapU(Texture.WMClamp) tex0.setWrapV(Texture.WMClamp) ts0 = TextureStage('reflection') self.water.setTexture(ts0, tex0) tex1 = loader.loadTexture('texture/water.png') ts1 = TextureStage('distortion') self.water.setTexture(ts1, tex1) self.keyMap={}; self.keyMap["sit"]=0 self.keyMap["call"]=0 self.keyMap["left"]=0 self.keyMap["forward"]=0 self.keyMap["right"]=0 taskMgr.add(self.waterUpdate, "waterTask") taskMgr.add(self.cameraControl,"cameraControl") self.water.reparentTo(render) def controlSkater(self): self.isMoving = False self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) self.accept("arrow_up", self.setKey, ["forward",1]) self.accept("arrow_up-repeat",self.setKey, ["forward",1]) self.accept("arrow_up-up",self.setKey, ["forward",0]) self.accept("arrow_down", self.setKey, ["forward",-1]) self.accept("arrow_down-repeat",self.setKey, ["forward",-1]) self.accept("arrow_down-up",self.setKey, ["forward",0]) self.accept("e",self.setKey,["sit",1]) self.accept("q",self.setKey,["sit",0]) self.accept("c",self.setKey,["call",1]) #self.accept("c-up",self.setKey,["call",0]) self.accept("arrow_left", self.setKey, ["left",1]) self.accept("arrow_left-repeat",self.setKey, ["left",1]) self.accept("arrow_left-up",self.setKey,["left",0]) self.accept("arrow_right", self.setKey, ["right",1]) self.accept("arrow_right-repeat",self.setKey, ["right",1]) self.accept("arrow_right-up",self.setKey,["right",0]) self.accept("escape", sys.exit) def makeRacers(self): #self.floater=0 self.racers={} self.racersCount=0 self.racers[self.racersCount] = Actor("models/scater.egg",{"skate":"models/scater.egg", "walk":"models/scaterwalk.egg","sit":"models/scatersit.egg","standup":"models/scaterstandup.egg"}) self.racers[self.racersCount].setTexture(loader.loadTexture("texture/racer.tga"),1) self.racers[self.racersCount].setPos(-30,30,0) self.racers[self.racersCount].setScale(0.075,0.075,0.075) #self.racers[self.racersCount].setH(90) self.racers[self.racersCount].reparentTo(render) #self.racerMoveTo(self.racersCount,-60,0) #self.interval={} #self.controlRacer(self.racersCount) #self.racersCount=self.racersCount+1 def racerMoveTo(self,no,x,y,direcation,anim='skate'): if(x-self.racers[no].getX()!=0): self.angle=atan(float(y-self.racers[no].getY())/float(x-self.racers[no].getX()))+90 if(x<self.racers[no].getX()): self.angle=self.angle+90 else: if(y>self.racers[no].getY()): self.angle=180 if(y<self.racers[no].getY()): self.angle=0 self.racers[no].setH(self.angle*180/pi) self.interval= self.racers[no].posInterval(direcation,Point3(x,y,0),startPos=self.racers[no].getPos()) #self.pace = Sequence(interval,name="skatePose") self.interval.start() #s while (interval.isPlaying()) self.racers[no].loop(anim) #while (self.racers[no].getY()!=y and self.racers[no].getX()!=x): # self.racers[no].setY(self.racers[no], -100 * globalClock.getDt()) def controlRacer(self,no): self.pointNo=1; taskMgr.add(self.controlRacerTask, "race") self.racers[self.racersCount].setPos(-12.3668,42.92,0) self.racerMoveTo(no,-12.3668,42.92,3) #y={42.92,10.61,-4.685,-29.29,-41.99,-45,-40.87,-33.22,-17.81,-1.14,21.30,36.82,45.5} #for i in range(0,13,1): #self.racerMoveTo(self.racersCount,x[i],y[0],7) #time.sleep(7) def controlRacerTask(self,task): if(self.interval.isPlaying()==False and self.exploringMode==False): self.racerMoveTo(self.racersCount,self.x[self.pointNo],self.y[self.pointNo],2) self.pointNo=(self.pointNo+1)%13 #print self.pointNo #time.sleep(7) return task.cont def addCollisions(self): self.cTrav = CollisionTraverser() self.skaterGroundRay = CollisionRay() self.skaterGroundRay.setOrigin(0,0,1000) self.skaterGroundRay.setDirection(0,0,-1) self.skaterGroundCol = CollisionNode('skater') self.skaterGroundCol.addSolid(self.skaterGroundRay) self.skaterGroundCol.addSolid(CollisionTube(0,0,0,0,0,50,10)) #self.skaterGroundCol.setFromCollideMask(BitMask32.bit(0)) #self.skaterGroundCol.setIntoCollideMask(BitMask32.allOff()) self.skaterGroundColNp = self.skater.attachNewNode(self.skaterGroundCol) self.skaterGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.skaterGroundColNp, self.skaterGroundHandler) #self.skaterGroundColNp.show() #self.cTrav.showCollisions(render) self.angle=180/pi; self.isFall=False def setKey(self,key,value): self.keyMap[key] = value def Move(self,task): if(self.isSitted ): if(self.keyMap['sit']==0): self.isSitted=False self.skater.pose("walk",12) self.isMoving = False return task.cont startpos = self.skater.getPos() if (self.keyMap["left"]!=0): self.skater.setH(self.skater.getH() + 100 * globalClock.getDt()) if (self.keyMap["right"]!=0): self.skater.setH(self.skater.getH() - 100 * globalClock.getDt()) #if (self.keyMap["right"]!=0): # self.ralph.setH(self.ralph.getH() - 300 * globalClock.getDt()) dx=100 if(self.raceingStart==True): dx=150 if (self.keyMap["forward"]!=0): if(self.exploringMode==False and self.raceingStart==True and self.startingTime>=3): self.skater.setY(self.skater, -dx * globalClock.getDt()) else: if(self.exploringMode==True): self.skater.setY(self.skater, -dx * globalClock.getDt()) if (self.keyMap["forward"]!=0) : if self.isMoving == False: if self.exploringMode==True: self.skater.loop("walk") else: self.skater.loop("skate") self.isMoving = True else: #if self.isSitted: # @self.skater.loop("sit") if self.isMoving : #if(self.skater.getCurrentAnim()=='skate'): self.skater.stop() self.skater.pose("walk",12) self.isMoving = False """ if(self.isFall==True): if(self.skater.getCurrentAnim()=='fall'): if(self.skater.getCurrentFrame('fall')>=20): self.isFall=False self.skater.pose("skate",5)""" for i in range(0,self.count_bench,1): x=self.bench[i].getX() y=self.bench[i].getY() X=self.skater.getX();Y=self.skater.getY(); dist=sqrt((x-X)*(x-X)+(y-Y)*(y-Y)) if(dist<=5): if(self.isSitted==False and self.keyMap['sit']==1): self.skater.stop() self.skater.setPos(self.bench[i].getPos()) #self.skater.setY(self.skater.getY()+3) self.skater.setH(self.bench[i].getH()+270) self.skater.play('sit') self.isSitted=True if(self.isMoving==True): """if(self.isFall==True): if(self.skater.getCurrentFrame('fall')==25): self.isFall=False""" self.cTrav.traverse(render) entries = [] for i in range(self.skaterGroundHandler.getNumEntries()): entry = self.skaterGroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) print entries[0].getIntoNode().getName() if (len(entries)>0 and entries[0].getIntoNode().getName() == "character"): self.skater.setZ(entries[0].getSurfacePoint(render).getZ()) else: self.skater.setPos(startpos) #self.skater.setPos(startpos) #self.skater.play('fall') #self.isFall=True return task.cont def AddBench(self,x,y,angle=0): self.bench[self.count_bench]=loader.loadModel("models/bench.egg") self.bench[self.count_bench].reparentTo(render) self.bench[self.count_bench].setH(angle) self.bench[self.count_bench].setPos(x,y,0) self.bench[self.count_bench].setTexture(loader.loadTexture("texture/wood.jpg"),1) self.count_bench=self.count_bench+1 #self.bench[self.count_bench].setScale(0.03,0.03,0.03) def AddTree(self,x,y): self.tree_array[self.count_tree]=loader.loadModel("models/smalltree.egg") self.tree_array[self.count_tree].reparentTo(render) self.tree_array[self.count_tree].setPos(x,y,-2) self.tree_array[self.count_tree].setScale( random.uniform(0.01,0.02),random.uniform(0.01, 0.02),random.uniform(0.01, 0.02)) self.tree_array[self.count_tree].setTexture(loader.loadTexture("models/smalltree.png"),1) self.tree_array[self.count_tree].setTransparency(TransparencyAttrib.MDual) self.tree_array[self.count_tree].setShaderAuto() self.tree_array[self.count_tree].setColor(VBase4(0.5+random.uniform(0,0.5),1,0.5+random.uniform(0,0.5),1)) self.count_tree=self.count_tree+1 def AddStone(self,x,y): self.stone_array[self.count_stone]=loader.loadModel("models/stone1.egg") self.stone_array[self.count_stone].reparentTo(render) self.stone_array[self.count_stone].setPos(x,y,0) self.stone_array[self.count_stone].setH(random.uniform(0,360)) self.stone_array[self.count_stone].setTexture(loader.loadTexture("texture/Stone_2_DiffuseMap.jpg"),1) self.stone_array[self.count_stone].setScale(random.uniform(0.005,0.015)) self.stone_array[self.count_stone].setShaderAuto() self.count_stone=self.count_stone+1 def cameraControl(self,task): self.floater.setPos(self.skater.getPos()) self.floater.setZ(self.skater.getZ() + 10.0) #camera.lookAt(self.floater) return task.cont def waterUpdate(self,task): self.slnp.lookAt(self.skater) #print self.skater.getX(),self.skater.getY() base.camera.setPos(self.skater.getPos()) base.camera.setZ(self.skater.getZ() + 10.0) base.camera.setY(self.skater.getY() - 30*sin((-self.skater.getH()-90)*pi/180)) base.camera.setX(self.skater.getX() + 30*cos((-self.skater.getH()-90)*pi/180)) if base.mouseWatcherNode.hasMouse(): x=base.mouseWatcherNode.getMouseX() y=base.mouseWatcherNode.getMouseY() base.camera.lookAt(self.skater.getX() ,self.skater.getY(),self.skater.getZ()+((y+1)/2)*10+0.5) #base.camera.setH(self.skater.getH()) #base.camera.lookAt(self.skater) mc = base.camera.getMat() mf = self.waterPlane.getReflectionMat() self.mc = base.camera.getMat() mf = self.waterPlane.getReflectionMat() self.watercamNP.setMat(mc * mf) self.water.setShaderInput('time', task.time) return task.cont def makeLights(self): slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) #slight.setFov(90) self.slnp = render.attachNewNode(slight) self.slnp.setPos(0, 0, 70) self.ambientLight=AmbientLight('AmbientLight') self.ambientLight.setColor(VBase4(0.3, 0.3, 0.3, 0.3)) # self.ambientNP = render.attachNewNode(self.ambientLight) render.setLight(self.ambientNP) render.setLight(self.slnp) #render.setLight(self.ambientNP) def racingInteraction(self,task): if(self.raceingStart==True): self.startingTime=task.time x=self.racers[self.racersCount].getX() y=self.racers[self.racersCount].getY() X=self.skater.getX();Y=self.skater.getY(); dist=sqrt((x-X)*(x-X)+(y-Y)*(y-Y)) if(self.exploringMode==False): if((task.time-self.startedTime)<=3): self.txt.setText(str(int(task.time-self.startedTime))) #self.keyMap["forward"]=0 self.isRacing=True else: self.txt.setText("") if(dist<=5): if(self.keyMap["call"]==1 and self.raceingStart==False): self.racers[self.racersCount].play('standup') self.raceingStart=True else: if(self.keyMap["call"]==1 and self.raceingStart==True): if(self.racers[self.racersCount].getAnimControl('standup').isPlaying()==False and self.exploringMode==True): self.startedTime=task.time #self.playVideo('talk.mp4') #mytimer.setY(0) self.exploringMode=False self.skater.setH(0) self.skater.setPos(-15.3668,44,0) self.controlRacer(self.racersCount) #print self.skater.getX(),self.skater.getY() if( self.exploringMode==False and self.skater.getX()>=-5 and self.skater.getX()<=5 and self.skater.getY()>=42 and self.skater.getY()<=55): self.exploringMode=True self.raceingStart=False self.txt.setText("Finish \n You Win") self.finishTime=task.time; self.interval.finish() self.racers[self.racersCount].setPos(-40,-30,0) self.keyMap["call"]=0 self.skater.setPos(-15.3668,44,0) self.racers[self.racersCount].setH(self.bench[0].getH()+270) self.racers[self.racersCount].pose('standup',0) if(self.exploringMode==False and self.racers[self.racersCount].getX()>=-5 and self.racers[self.racersCount].getX()<=5 and self.racers[self.racersCount].getY()>=42 and self.racers[self.racersCount].getY()<=55): self.exploringMode=True self.raceingStart=False self.txt.setText(" Finish \n You Lose") self.finishTime=task.time; self.interval.finish() self.racers[self.racersCount].setPos(-40,-30,0) self.keyMap["call"]=0 self.racers[self.racersCount].setH(self.bench[0].getH()+270) self.racers[self.racersCount].pose('standup',0) if(task.time-self.finishTime>=1 and self.finishTime!=0): self.txt.setText("") return task.cont def initailState(self): OnscreenText(text="[1] Press E for sit ", style=1, fg=(1,1,1,1),pos=(-1.75, 0.9), align=TextNode.ALeft, scale = 0.06) OnscreenText(text="[2] Press Q for stand", style=1, fg=(1,1,1,1),pos=(-1.75, 0.8), align=TextNode.ALeft, scale = 0.06) OnscreenText(text="[3] Press C for Challenge", style=1, fg=(1,1,1,1),pos=(-1.75, 0.7), align=TextNode.ALeft, scale = 0.06) self.finishX=0 self.finishTime=0 map_data = Image.open("texture/map.png") pix_data = map_data.load() for i in range(0,80,3): for j in range (0,80,3): #print pix_data[i,j] if pix_data[i,j]==0: self.AddStone(i-40,j-40) else: if pix_data[i,j]==3: self.AddTree(i-40,j-40) self.txt=OnscreenText(text="", style=1, fg=(1,1,1,1),pos=(0, 0), align=TextNode.ALeft, scale = 0.06) self.raceingStart=False self.exploringMode=True self.racers[self.racersCount].setPos(-40,-30,0) self.racers[self.racersCount].setH(self.bench[0].getH()+270) self.racers[self.racersCount].pose('standup',0) self.x={}; self.x[0]=-12.3668;self.x[1]=-19.79;self.x[2]=-21.90;self.x[3]=-26.53;self.x[4]=-20.67; self.x[5]=-3;self.x[6]=13.93;self.x[7]=22.65;self.x[8]=24.74;self.x[9]=24.38; self.x[10]=18.65;self.x[11]=12.10;self.x[12]=-1.92; #x={-12.3668,-19.79,-21.90,-26.53,-20.67,-3,13.93,22.65,24.74,24.38,18.65,12.10,-1.92} self.y={} self.y[0]=42.92;self.y[1]=10.61;self.y[2]=-4.685;self.y[3]=-29.29;self.y[4]=-41.99; self.y[5]=-45;self.y[6]=-40.87;self.y[7]=-33.22;self.y[8]=-17.81;self.y[9]=-1.14; self.y[10]=21.30;self.y[11]=36.82;self.y[12]=45.5 taskMgr.add(self.Move,"moveTask") taskMgr.add(self.racingInteraction,"moveTask")
class MoveCursor(object): _EDGES = 40 _zPos = 0 _movingUp = False _movingDown = False _color = Vec4(0.3, 0.3, 0.8, 1) _currentPos = Vec3(0, 0, 0) def __init__(self, parent, entity, foot=1): self.entity = entity self._moveRadCircleNP = NodePath("Movement Radius Node") self._moveLine = LineSegs() self._moveLineNP = NodePath("Movement Direction Line Node") self._moveZLine = LineSegs() self._moveZLineNP = NodePath("Movement Z Line Node") self._moveZFootNP = NodePath("Movement Z Foot Node") self._moveFootCircle = LineSegs() self._moveFootCircleNP = NodePath("Movement Foot Circle Node") self._attackRadCircle = LineSegs() self._attackRadCircleNP= NodePath("Attack Radius Node") self._np = NodePath("Movement Node") self.attackables = [] Event.Dispatcher().register(self, 'E_Key_ZUp', self.onZChange) Event.Dispatcher().register(self, 'E_Key_ZDown', self.onZChange) Event.Dispatcher().register(self, 'E_Key_ZUp-up', self.onZChange) Event.Dispatcher().register(self, 'E_Key_ZDown-up', self.onZChange) self.aaLevel= int(GameSettings().getSetting('ANTIALIAS')) self.parent = parent self.start = Vec3(0, 0, 0) self.moveRad = entity.moveRad self.footRad = foot self.attackRad = entity.attackRad self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0)) self.draw() self._np.reparentTo(self.parent) if self.aaLevel > 0: self._np.setAntialias(AntialiasAttrib.MLine, self.aaLevel) taskMgr.add(self.updateMovePos, 'Movement Indicator Update Task') def draw(self): # Setup curr mouse pos in 3d space posXY = self.getMouseXY() x = posXY.getX() y = posXY.getY() z = 0 # Draw movement radius moveRadLine = LineSegs() moveRadLine.setThickness(1) moveRadLine.setColor(self._color) moveRadLine.moveTo(self.moveRad, 0, 0) for i in range(self._EDGES + 1): newX = (self.moveRad * math.cos((2*math.pi/self._EDGES)*i)) newY = (self.moveRad * math.sin((2*math.pi/self._EDGES)*i)) moveRadLine.drawTo(newX, newY, 0) moveRadGeom = moveRadLine.create() self._moveRadCircleNP = NodePath(moveRadGeom) self._moveRadCircleNP.reparentTo(self._np) # Draw movement foot circle self._moveFootCircle.setThickness(1) self._moveFootCircle.setColor(self._color) self._moveFootCircle.moveTo(self.footRad, 0, 0) for i in range(self._EDGES): newX = (self.footRad * math.cos((2*math.pi/self._EDGES)*i)) newY = (self.footRad * math.sin((2*math.pi/self._EDGES)*i)) self._moveFootCircle.drawTo(newX, newY, 0) self._moveFootCircle.drawTo(self.footRad, 0, 0) moveFootCircleGeom = self._moveFootCircle.create() self._moveFootCircleNP = NodePath(moveFootCircleGeom) self._moveFootCircleNP.reparentTo(self._np) # Draw movement direction line self._moveLine.setThickness(1) self._moveLine.setColor(self._color) self._moveLine.moveTo(0, 0, 0) self._moveLine.drawTo(x, y, z) moveLine = self._moveLine.create() self._moveLineNP = NodePath(moveLine) self._moveLineNP.reparentTo(self._np) # Draw Z line self._moveZLine.setThickness(1) self._moveZLine.setColor(self._color) self._moveZLine.moveTo(self.start) self._moveZLine.drawTo(x, y, z) moveZLine = self._moveZLine.create() self._moveZLineNP = NodePath(moveZLine) self._moveZLineNP.reparentTo(self._np) # Draw Attack Radius self._attackRadCircle.setThickness(1) self._attackRadCircle.setColor(0.8, 0.0, 0.0, 1) self._attackRadCircle.moveTo(self.attackRad, 0, 0) for i in range(self._EDGES + 1): newX = (self.attackRad * math.cos((2*math.pi/self._EDGES)*i)) newY = (self.attackRad * math.sin((2*math.pi/self._EDGES)*i)) self._attackRadCircle.drawTo(newX, newY, 0) attackRadCircleGeom = self._attackRadCircle.create() self._attackRadCircleNP = NodePath(attackRadCircleGeom) self._attackRadCircleNP.reparentTo(self._np) def updateMovePos(self, Task): # endPos must be transformed in the the coord sys of the model m_pos = self.getMouseXY() if m_pos is not None: # Transform current mouse pos endPos = self.parent.getRelativePoint(render, m_pos) # Adjust Z coord if needed if self._movingUp: self._zPos += 0.1 elif self._movingDown: self._zPos -= 0.1 endPos.setZ(self._zPos) # Check if we're trying to move too far, if not update pos dist = math.sqrt(endPos.getX()**2 + endPos.getY()**2 + 2*(endPos.getZ()**2)) if dist <= self.moveRad: self._moveLine.setVertex(1, endPos) self._moveFootCircleNP.setPos(endPos) self._moveZLine.setVertex(0, Point3(endPos.getX(), endPos.getY(), 0)) self._moveZLine.setVertex(1, endPos) self._attackRadCircleNP.setPos(endPos) self._currentPos = render.getRelativePoint(self._np, endPos) # Check for attackable ships in range of current pos attackables = Entity.EntityManager().getEntitiesWithin(self._currentPos, self.attackRad) # Unhighlight ships no longer in range for e in self.attackables: if e not in attackables and isinstance(e, Entity.EntityShip): e.representation.unsetAttackable() # Highlight ships in range for e in attackables: if isinstance(e, Entity.EntityShip) and e != self.entity and e.owner != self.entity.owner: e.representation.setAttackable() self.attackables = attackables return Task.cont def onZChange(self, event): if event.type == 'E_Key_ZUp': self._movingDown = False self._movingUp = True if event.type == 'E_Key_ZDown': self._movingUp = False self._movingDown = True if event.type == 'E_Key_ZUp-up': self._movingUp = False self._movingDown = False if event.type == 'E_Key_ZDown-up': self._movingUp = False self._movingDown = False def getMouseXY(self): # NOTE - this returns the mouse pos in the ships coord sys if base.mouseWatcherNode.hasMouse(): mpos = base.mouseWatcherNode.getMouse() pos3d = Point3() nearPoint = Point3() farPoint = Point3() base.camLens.extrude(mpos, nearPoint, farPoint) if self.plane.intersectsLine(pos3d, render.getRelativePoint(camera, nearPoint), render.getRelativePoint(camera, farPoint)): #print("Mouse ray intersects ground plane at " + str(pos3d)) return pos3d def getPosition(self): return self._currentPos def removeNode(self): taskMgr.remove('Movement Indicator Update Task') for e in self.attackables: if isinstance(e, Entity.EntityShip): e.representation.unsetAttackable() self._moveRadCircleNP.removeNode() self._moveLineNP.removeNode() self._moveZLineNP.removeNode() self._moveZFootNP.removeNode() self._moveFootCircleNP.removeNode() self._attackRadCircleNP.removeNode() self._np.removeNode() def __del__(self): # TODO - This isn't calling self.removeNode() correctly self._np.removeNode()
def createGuiObjects(self): """Create the other gui objects in the month, assumes we have proper locators.""" # we create an invisible button so the day can be clicked on self.dayButton = DirectButton( parent=self.dayButtonLocator, image=self.selectedFrame, relief=None, command=self.__clickedOnDay, # next three settings are for debug pressEffect=1, rolloverSound=None, clickSound=None) self.numberWidget = DirectLabel( parent=self.numberLocator, relief=None, text=str(self.myDate.day), text_scale=0.04, text_align=TextNode.ACenter, text_font=ToontownGlobals.getInterfaceFont(), text_fg=Vec4(110 / 255.0, 126 / 255.0, 255 / 255.0, 1), ) self.attachMarker(self.numberLocator) self.listXorigin = 0 self.listFrameSizeX = self.scrollBottomRightLocator.getX( ) - self.scrollLocator.getX() self.scrollHeight = self.scrollLocator.getZ( ) - self.scrollBottomRightLocator.getZ() self.listZorigin = self.scrollBottomRightLocator.getZ() self.listFrameSizeZ = self.scrollLocator.getZ( ) - self.scrollBottomRightLocator.getZ() self.arrowButtonXScale = 1 self.arrowButtonZScale = 1 self.itemFrameXorigin = 0 self.itemFrameZorigin = 0 self.buttonXstart = self.itemFrameXorigin + 0.21 self.gui = loader.loadModel("phase_3.5/models/gui/friendslist_gui") buttonOffSet = -0.01 # these settings put the arrow buttons on the top incButtonPos = (0.0, 0, 0) decButtonPos = (0.0, 0, 0) # these settings put the arrow buttons on the right side # incButtonPos = (self.buttonXstart,0,self.listZorigin - buttonOffSet) # decButtonPos = (self.buttonXstart, 0, self.listZorigin + self.listFrameSizeZ + buttonOffSet) itemFrameMinZ = self.listZorigin itemFrameMaxZ = self.listZorigin + self.listFrameSizeZ arrowUp = self.find("**/downScroll_up") arrowDown = self.find("**/downScroll_down") arrowHover = self.find("**/downScroll_hover") self.scrollList = DirectScrolledList( parent=self.scrollLocator, relief=None, pos=(0, 0, 0), # inc and dec are DirectButtons # incButton is on the bottom of page, decButton is on the top! incButton_image=( arrowUp, arrowDown, arrowHover, arrowUp, ), incButton_relief=None, incButton_scale=(self.arrowButtonXScale, 1, self.arrowButtonZScale), incButton_pos=incButtonPos, # Make the disabled button fade out incButton_image3_color=Vec4(1, 1, 1, 0.2), decButton_image=( arrowUp, arrowDown, arrowHover, arrowUp, ), decButton_relief=None, decButton_scale=(self.arrowButtonXScale, 1, -self.arrowButtonZScale), decButton_pos=decButtonPos, # Make the disabled button fade out decButton_image3_color=Vec4(1, 1, 1, 0.2), # itemFrame is a DirectFrame, shift it down a bit to match top left scroll itemFrame_pos=(self.itemFrameXorigin, 0, -0.03), # each item is a button with text on it numItemsVisible=4, # so we select the day when we click on a scroll button incButtonCallback=self.scrollButtonPressed, decButtonCallback=self.scrollButtonPressed, ) # make sure the arrow buttons appear over item frame itemFrameParent = self.scrollList.itemFrame.getParent() self.scrollList.incButton.reparentTo(self.scrollDownLocator) self.scrollList.decButton.reparentTo(self.scrollUpLocator) arrowUp.removeNode() arrowDown.removeNode() arrowHover.removeNode() # Set up a clipping plane to truncate names that would extend # off the right end of the scrolled list. clipper = PlaneNode('clipper') clipper.setPlane(Plane(Vec3(-1, 0, 0), Point3(0.23, 0, 0))) clipNP = self.scrollList.component('itemFrame').attachNewNode(clipper) self.scrollList.component('itemFrame').setClipPlane(clipNP)
def __init__(self, parent): self.parent = parent self.baseNode = self.parent.attachNewNode(self.__class__.__name__) x1 = -200 y1 = -200 x2 = 200 y2 = 200 z = 0.0 #waterNP = NodePath("Water Node Parent") #waterNP.reparentTo(parent) #sn = self.drawSquare(-100, -100, 0, 100, 100, 0); #sn.reparentTo(self.baseNode) water = Square(self.baseNode, Point3(x1, y1, 0.2), Point3(x2, y2, 0.2), Vec4(0.0, 0.0, 0.5, 0.5)) wNp = water.draw() t1 = loader.loadTexture('assets/textures/wave.png') t1.setWrapU(Texture.WMRepeat) t1.setWrapV(Texture.WMRepeat) wNp.setTexture(t1) # Water Shader from # http://www.panda3d.org/forums/viewtopic.php?p=70853&sid=53d92b5ae1683bd9458f21d6026ad36e # anim: vx, vy, scale, skip # distort: offset, strength, refraction factor (0 = perfect mirror, # 1 = total refraction), refractivity anim = (.022, -.012, 2.5, 0) distort = (.1, 2, .5, .45) self.buffer = base.win.makeTextureBuffer('waterBuffer', 512, 512) self.watercamNP = base.makeCamera(self.buffer) # Create water surface using a card # The surface will be centered and maker = CardMaker('water') # Water surface maker.setFrame(x1, x2, y1, y2) self.waterNP = self.baseNode.attachNewNode(maker.generate()) self.waterNP.setPosHpr((0, 0, z), (0, -90, 0)) self.waterNP.setTransparency(TransparencyAttrib.MAlpha) self.waterNP.setTwoSided(True) # Attach the water shader to the water shader surface waterShader = Shader.load("shaders/water.sha") self.waterNP.setShader(waterShader) self.waterNP.setShaderInput('wateranim', anim) self.waterNP.setShaderInput('waterdistort', distort) self.waterNP.setShaderInput('time', 0) self.waterPlane = Plane((0, 0, z + 1), (0, 0, z)) # Reflection plane PlaneNode('waterPlane').setPlane(self.waterPlane) self.buffer.setClearColor((0, 0, 0.5, 1)) # buffer self.watercamNP.reparentTo(self.baseNode) # reflection camera cam = self.watercamNP.node() cam.getLens().setFov(base.camLens.getFov()) cam.getLens().setNearFar(1, 5000) cam.setInitialState(RenderState.make(CullFaceAttrib.makeReverse())) cam.setTagStateKey('Clipped') cam.setTagState( 'True', RenderState.make(ShaderAttrib.make().setShader( loader.loadShader('shaders/splut3Clipped.sha')))) tex0 = self.buffer.getTexture() # reflection texture, created in # realtime by the 'water camera' tex0.setWrapU(Texture.WMClamp) tex0.setWrapV(Texture.WMClamp) self.waterNP.setTexture(TextureStage('reflection'), tex0) self.waterNP.setTexture( TextureStage('distortion'), loader.loadTexture( 'assets/textures/water.png')) # distortion texture self.task = taskMgr.add(self.update, 'waterUpdate', sort=50)
class CameraHandler(DirectObject.DirectObject): def __init__(self, showbase): self.showbase = showbase self.showbase.disableMouse() # This disables the default mouse based camera control used by panda. This default control is awkward, and won't be used. self.showbase.camera.setPos(0, -150, 200) self.showbase.camera.lookAt(0, 0, 0) # Gives the camera an initial position and rotation. self.mx, self.my = 0, 0 # Sets up variables for storing the mouse coordinates self.orbiting = False # A boolean variable for specifying whether the camera is in orbiting mode. Orbiting mode refers to when the camera is being moved # because the user is holding down the right mouse button. self.target = Vec3() # sets up a vector variable for the camera's target. The target will be the coordinates that the camera is currently focusing on. self.camDist = 150 # A variable that will determine how far the camera is from it's target focus self.panRateDivisor = 10 # This variable is used as a divisor when calculating how far to move the camera when panning. Higher numbers will yield slower panning # and lower numbers will yield faster panning. This must not be set to 0. self.panZoneSize = .1 # This variable controls how close the mouse cursor needs to be to the edge of the screen to start panning the camera. It must be less than 1, # and I recommend keeping it less than .2 self.panLimitsX = Vec2(-1000, 1000) self.panLimitsY = Vec2(-1000, 1000) # These two vairables will serve as limits for how far the camera can pan, so you don't scroll away from the map. self.maxZoomOut = 500 self.maxZoomIn = 25 #These two variables set the max distance a person can zoom in or out self.orbitRate = 75 # This is the rate of speed that the camera will rotate when middle mouse is pressed and mouse moved # recommended rate 50-100 self.setTarget(0, 0, 0) # calls the setTarget function to set the current target position to the origin. self.turnCameraAroundPoint(0, 0) # calls the turnCameraAroundPoint function with a turn amount of 0 to set the camera position based on the target and camera distance self.accept("mouse2", self.startOrbit) # sets up the camrea handler to accept a right mouse click and start the "drag" mode. self.accept("mouse2-up", self.stopOrbit) # sets up the camrea handler to understand when the right mouse button has been released, and ends the "drag" mode when # the release is detected. self.storeX = 0 self.storeY = 0 # for storing of the x and y for the orbit # The next pair of lines use lambda, which creates an on-the-spot one-shot function. self.accept("wheel_up", self.zoomIn) # sets up the camera handler to detet when the mouse wheel is rolled upwards and uses a lambda function to call the # adjustCamDist function with the argument 0.9 self.accept("wheel_down", self.zoomOut) # sets up the camera handler to detet when the mouse wheel is rolled upwards and uses a lambda function to call the # adjustCamDist function with the argument 1.1 # Keys array (down if 1, up if 0) self.keys = {"cam-left": 0, "cam-right": 0, "cam-up": 0, "cam-down": 0} # Using Arrow Keys self.accept("arrow_left", self.setValue, [self.keys, "cam-left", 1]) self.accept("arrow_right", self.setValue, [self.keys, "cam-right", 1]) self.accept("arrow_up", self.setValue, [self.keys, "cam-up", 1]) self.accept("arrow_down", self.setValue, [self.keys, "cam-down", 1]) self.accept("arrow_left-up", self.setValue, [self.keys, "cam-left", 0]) self.accept("arrow_right-up", self.setValue, [self.keys, "cam-right", 0]) self.accept("arrow_up-up", self.setValue, [self.keys, "cam-up", 0]) self.accept("arrow_down-up", self.setValue, [self.keys, "cam-down", 0]) self.keyPanRate = 1.5 # pan rate for when user presses the arrow keys # set up plane for checking collision with for mouse-3d world self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0)) def destroy(self): self.ignoreAll() def setValue(self, array, key, value): array[key] = value def clamp(self, val, minVal, maxVal): val = min(max(val, minVal), maxVal) return val def zoomOut(self): if self.camDist <= self.maxZoomOut: self.adjustCamDist(1.1) return True def zoomIn(self): if self.camDist >= self.maxZoomIn: self.adjustCamDist(0.9) return True def turnCameraAroundPoint(self, deltaX, deltaY): # This function performs two important tasks. First, it is used for the camera orbital movement that occurs when the # right mouse button is held down. It is also called with 0s for the rotation inputs to reposition the camera during the # panning and zooming movements. # The delta inputs represent the change in rotation of the camera, which is also used to determine how far the camera # actually moves along the orbit. newCamHpr = Vec3() newCamPos = Vec3() # Creates temporary containers for the new rotation and position values of the camera. camHpr = self.showbase.camera.getHpr() # Creates a container for the current HPR of the camera and stores those values. newCamHpr.setX(camHpr.getX() + deltaX) newCamHpr.setY(self.clamp(camHpr.getY() - deltaY, -85, -10)) newCamHpr.setZ(camHpr.getZ()) # Adjusts the newCamHpr values according to the inputs given to the function. The Y value is clamped to prevent # the camera from orbiting beneath the ground plane and to prevent it from reaching the apex of the orbit, which # can cause a disturbing fast-rotation glitch. self.showbase.camera.setHpr(newCamHpr) # Sets the camera's rotation to the new values. angleradiansX = newCamHpr.getX() * (math.pi / 180.0) angleradiansY = newCamHpr.getY() * (math.pi / 180.0) # Generates values to be used in the math that will calculate the new position of the camera. newCamPos.setX(self.camDist * math.sin(angleradiansX) * math.cos(angleradiansY) + self.target.getX()) newCamPos.setY(-self.camDist * math.cos(angleradiansX) * math.cos(angleradiansY) + self.target.getY()) newCamPos.setZ(-self.camDist * math.sin(angleradiansY) + self.target.getZ()) self.showbase.camera.setPos(newCamPos.getX(), newCamPos.getY(), newCamPos.getZ()) # Performs the actual math to calculate the camera's new position and sets the camera to that position. #Unfortunately, this math is over my head, so I can't fully explain it. self.showbase.camera.lookAt(self.target.getX(), self.target.getY(), self.target.getZ()) # Points the camera at the target location. def getTarget(self): return self.target # returns the cur def setTarget(self, x, y, z): #This function is used to give the camera a new target position. x = self.clamp(x, self.panLimitsX.getX(), self.panLimitsX.getY()) self.target.setX(x) y = self.clamp(y, self.panLimitsY.getX(), self.panLimitsY.getY()) self.target.setY(y) self.target.setZ(z) # Stores the new target position values in the target variable. The x and y values are clamped to the pan limits. def setPanLimits(self, xMin, xMax, yMin, yMax): # This function is used to set the limitations of the panning movement. self.panLimitsX = (xMin, xMax) self.panLimitsY = (yMin, yMax) # Sets the inputs into the limit variables. def startOrbit(self): # This function puts the camera into orbiting mode. # Get windows properties props = WindowProperties() # Set Hide Cursor Property #props.setCursorHidden(True) # Set properties self.showbase.win.requestProperties(props) # hide cursor if self.showbase.mouseWatcherNode.hasMouse(): # We're going to use the mouse, so we have to make sure it's in the game window. If it's not and we try to use it, we'll get # a crash error. mpos = self.showbase.mouseWatcherNode.getMouse() self.storeX = mpos.getX() self.storeY = mpos.getY() # take current cursor values self.showbase.win.movePointer(0, self.showbase.win.getXSize() / 2, self.showbase.win.getYSize() / 2) # set to center self.mx = 0 self.my = 0 self.orbiting = True # Sets the orbiting variable to true to designate orbiting mode as on. def stopOrbit(self): # This function takes the camera out of orbiting mode. self.orbiting = False # Sets the orbiting variable to false to designate orbiting mode as off. self.showbase.win.movePointer( 0, int((self.storeX + 1.0) / 2 * self.showbase.win.getXSize()), int(self.showbase.win.getYSize() - ((self.storeY + 1.0) / 2 * self.showbase.win.getYSize()))) # set to taken cursor values from startOrbit if self.showbase.mouseWatcherNode.hasMouse(): # We're going to use the mouse, so we have to make sure it's in the game window. If it's not and we try to use it, we'll get # a crash error. mpos = self.showbase.mouseWatcherNode.getMouse() self.mx = mpos.getX() self.my = mpos.getY() # Get windows properties props = WindowProperties() # Set Hide Cursor Property props.setCursorHidden(False) # Set properties self.showbase.win.requestProperties(props) # reshow cursor def adjustCamDist(self, distFactor): # This function increases or decreases the distance between the camera and the target position to simulate zooming in and out. # The distFactor input controls the amount of camera movement. # For example, inputing 0.9 will set the camera to 90% of it's previous distance. self.camDist = self.camDist * distFactor # Sets the new distance into self.camDist. self.turnCameraAroundPoint(0, 0) # Calls turnCameraAroundPoint with 0s for the rotation to reset the camera to the new position. def camMoveTask(self, dt): # This task is the camera handler's work house. It's set to be called every frame and will control both orbiting and panning the camera. if self.showbase.mouseWatcherNode.hasMouse(): # We're going to use the mouse, so we have to make sure it's in the game window. If it's not and we try to use it, we'll get # a crash error. mpos = self.showbase.mouseWatcherNode.getMouse() # Gets the mouse position if self.orbiting: # Checks to see if the camera is in orbiting mode. Orbiting mode overrides panning, because it would be problematic if, while # orbiting the camera the mouse came close to the screen edge and started panning the camera at the same time. self.turnCameraAroundPoint( (self.mx - mpos.getX()) * self.orbitRate * dt, (self.my - mpos.getY()) * self.orbitRate * dt) else: # If the camera isn't in orbiting mode, we check to see if the mouse is close enough to the edge of the screen to start panning moveY = False moveX = False # these two booleans are used to denote if the camera needs to pan. X and Y refer to the mouse position that causes the # panning. X is the left or right edge of the screen, Y is the top or bottom. if self.my > (1 - self.panZoneSize): angleradiansX1 = self.showbase.camera.getH() * (math.pi / 180.0) panRate1 = (1 - self.my - self.panZoneSize) * ( self.camDist / self.panRateDivisor) moveY = True if self.my < (-1 + self.panZoneSize): angleradiansX1 = self.showbase.camera.getH() * ( math.pi / 180.0) + math.pi panRate1 = (1 + self.my - self.panZoneSize) * ( self.camDist / self.panRateDivisor) moveY = True if self.mx > (1 - self.panZoneSize): angleradiansX2 = self.showbase.camera.getH() * ( math.pi / 180.0) + math.pi * 0.5 panRate2 = (1 - self.mx - self.panZoneSize) * ( self.camDist / self.panRateDivisor) moveX = True if self.mx < (-1 + self.panZoneSize): angleradiansX2 = self.showbase.camera.getH() * ( math.pi / 180.0) - math.pi * 0.5 panRate2 = (1 + self.mx - self.panZoneSize) * ( self.camDist / self.panRateDivisor) moveX = True # These four blocks check to see if the mouse cursor is close enough to the edge of the screen to start panning and then # perform part of the math necessary to find the new camera position. Once again, the math is a bit above my head, so # I can't properly explain it. These blocks also set the move booleans to true so that the next lines will move the camera. # If up or down keys are pressed if self.keys["cam-up"] ^ self.keys["cam-down"]: moveY = True panRate1 = self.keyPanRate # Update warlock position on z plane if self.keys["cam-up"]: angleradiansX1 = self.showbase.camera.getH() * ( math.pi / 180.0) + math.pi if self.keys["cam-down"]: angleradiansX1 = self.showbase.camera.getH() * ( math.pi / 180.0) # If left or right keys are pressed if self.keys["cam-left"] ^ self.keys["cam-right"]: moveX = True panRate2 = self.keyPanRate # Update warlock position on x plane if self.keys["cam-left"]: angleradiansX2 = self.showbase.camera.getH() * ( math.pi / 180.0) + math.pi * 0.5 if self.keys["cam-right"]: angleradiansX2 = self.showbase.camera.getH() * ( math.pi / 180.0) - math.pi * 0.5 if moveY: tempX = self.target.getX( ) + math.sin(angleradiansX1) * panRate1 * dt * 50 tempX = self.clamp(tempX, self.panLimitsX.getX(), self.panLimitsX.getY()) self.target.setX(tempX) tempY = self.target.getY( ) - math.cos(angleradiansX1) * panRate1 * dt * 50 tempY = self.clamp(tempY, self.panLimitsY.getX(), self.panLimitsY.getY()) self.target.setY(tempY) self.turnCameraAroundPoint(0, 0) if moveX: tempX = self.target.getX( ) - math.sin(angleradiansX2) * panRate2 * dt * 50 tempX = self.clamp(tempX, self.panLimitsX.getX(), self.panLimitsX.getY()) self.target.setX(tempX) tempY = self.target.getY( ) + math.cos(angleradiansX2) * panRate2 * dt * 50 tempY = self.clamp(tempY, self.panLimitsY.getX(), self.panLimitsY.getY()) self.target.setY(tempY) self.turnCameraAroundPoint(0, 0) # These two blocks finalize the math necessary to find the new camera position and apply the transformation to the # camera's TARGET. Then turnCameraAroundPoint is called with 0s for rotation, and it resets the camera position based # on the position of the target. The x and y values are clamped to the pan limits before they are applied. #print(self.target) self.mx = mpos.getX() self.my = mpos.getY() # The old mouse positions are updated to the current mouse position as the final step. # Finds 3d world point on the z = 0 plane for destination/target def getMouse3D(self): # make sure process has the mouse to not cause error if self.showbase.mouseWatcherNode.hasMouse(): # get screen coordinates of mouse mpos = self.showbase.mouseWatcherNode.getMouse() pos3d = Point3() nearPoint = Point3() farPoint = Point3() # find vector of cameras facing from mouse screen coordinates and get near and far points on frustrum self.showbase.camLens.extrude(mpos, nearPoint, farPoint) # check for intersection with z = 0 plane if self.plane.intersectsLine( pos3d, self.showbase.render.getRelativePoint( self.showbase.camera, nearPoint), self.showbase.render.getRelativePoint( self.showbase.camera, farPoint)): # return this position if exists return pos3d # or return (-1, -1, -1) return Vec3(-1, -1, -1)
class Hero(DirectObject): def __init__(self,no): self.HeroStats(no) self.display() # self.displaynot() self.SetupEvents() self.Collision() self.Loader() self.SkillStatus() self.sec=0 self.min=0 self.heroPace=None self.timesec = OnscreenText(text = '', pos = (1.2,-0.725),fg=(1,1,1,1),mayChange=1,scale=0.05) self.timemin = OnscreenText(text = '', pos = (1,-0.725),fg=(1,1,1,1),mayChange=1,scale=0.05) self.deathtxt=OnscreenText(text="",pos=(0.5,0.9),scale=0.5) taskMgr.add(self.update,"update") taskMgr.doMethodLater(1,self.Second,"second") taskMgr.add(self.MousePos,"mouse") def HeroStats(self,no): self.char={} self.char=hero[no] self.name=self.char['name'] self.model=Actor(MYDIRMODEL+self.char['model']+'.egg') self.type=None self.heroicon=self.char['icon'][0] self.skillicons=(self.char['icon'][1],self.char['icon'][2],self.char['icon'][3],self.char['icon'][4]) self.StartPos=Point3(25,25,0) self.gold=4000 self.goldrate = 1 self.items=[-1,-1,-1,-1,-1,-1] #each stores the no of the item self.itemindex=0 self.itemname="self.itemb" self.range=self.char['range'] self.strdt=self.char['strdt'] self.agidt=self.char['agidt'] self.intdt=self.char['intdt'] self.type=self.char['type'] self.Delta1=0 self.Delta2=0 self.Delta3=0 self.Delta4=0 self.Delta5=0 self.lvl=0 self.xp=0 self.Input=None self.str=self.char['str']+(self.strdt*self.lvl) self.agi=self.char['agi'] + (self.agidt*self.lvl) self.int=self.char['int'] +(self.intdt*self.lvl) self.basehp=590+self.str*19 self.basemp=220+(self.int*13) self.maxhp=590 +(self.str*19) self.curhp=self.maxhp self.maxmp=220 +(self.int*13) self.curmp=self.maxmp self.armor=self.char['armor'] +(self.agi/7) self.atkspeed=1.5/self.agi if self.type=='str': self.TYPESTR() if self.type=='agi': self.TYPEAGI() if self.type=='int': self.TYPEINT() self.healrate=0.003 *self.str self.mprate=0.02 *self.int self.res=0.25 self.speed=self.char['speed'] self.skill=0 self.isDead=False self.lon=pi*(self.getX()+10)*(self.getY()+10) def Loader(self): self.model=Actor("models/ralph", {"run": "models/ralph-run"}) # self.model=Actor(MYDIRMODEL+self.model+'.egg') self.model.setScale(3) # self.model.setHpr(90,270,0) self.model.setTransparency(0.5) # self.model.setScale(0.1) self.model.setPos(self.StartPos) self.model.reparentTo(render) # self.model.setColor(0, 0, 0, 0) self.model.loop("run") # self.Input=Input(self.model) Flame(self,self.model) #-------------------------------------------------------------Display Function---------------------------------------------------# def TYPESTR(self): self.mindamage=self.char['min']+self.str+self.Delta1 self.maxdamage=self.char['max']+self.str+self.Delta1 self.damage=range(int(self.mindamage),int(self.maxdamage)) def TYPEAGI(self): self.mindamage=self.char['min']+self.agi+self.Delta1 self.maxdamage=self.char['max']+self.agi+self.Delta1 self.damage=range(int(self.mindamage),int(self.maxdamage)) def TYPEINT(self): self.mindamage=self.char['min']+self.int+self.Delta1 self.maxdamage=self.char['max']+self.int+self.Delta1 self.damage=range(int(self.mindamage),int(self.maxdamage)) def TYPE(self): pass def display(self): x,y,z=self.model.getX(),self.model.getY(),self.model.getZ() base.camera.setPos(x,y,z+180) base.camera.setP(-30) base.camera.lookAt(self.model) self.panel=aspect2d.attachNewNode("panel") self.panel.setTransparency(1) self.SKNode=aspect2d.attachNewNode("skl") self.SKNode.setTransparency(0) self.HP=DirectLabel(text='',parent = self.panel,text_fg=(0,0.9,0,1),frameColor=(0,0,0,0),pos=(-0.41,0,-0.850),scale=0.04) self.MP=DirectLabel(text='',parent = self.panel,text_fg=(0,0,0.8,1),frameColor=(0,0,0,0),pos=(-0.41,0,-0.912),scale=0.04) self.LVL=DirectLabel(text ="Level %d"%(self.lvl+1),parent = self.panel,text_fg=(0,0,0,1),frameColor=(0,0,0,0),pos =(-0.5,0,-0.79),scale=Sc) Text1(self,"Damage",-0.26,-0.02,-1) Text1(self,"Armor",-0.27,0.03,-1) Text1(self,"Str",-0.25,0.085,-1) Text1(self,"Agi",-0.25,0.13,-1) Text1(self,"Int",-0.25,0.17,-1) self.DAM=Text2(self,"%d-%d",(self.mindamage-self.Delta1,self.maxdamage-self.Delta1),-0.40,-0.02,-1) self.ARM=Text2(self,"%d",(self.armor-self.Delta2),-0.40,0.03,-1) self.STR=Text2(self,"%d",(self.str-self.Delta3),-0.40,0.085,-1) self.AGI=Text2(self,"%d",(self.agi-self.Delta4),-0.40,0.13,-1) self.INT=Text2(self,"%d",(self.int-self.Delta5),-0.40,0.17,-1) if self.Delta1!=0: self.damdelta=Text3(self,"%d",self.Delta1,-0.4,-0.02,-1) if self.Delta2!=0: self.armdelta=Text3(self,"%d",self.Delta2,-0.4,0.03,-1) if self.Delta3!=0: self.strdelta=Text3(self,"%d",self.Delta3,-0.36,0.085,-1) if self.Delta4!=0: self.agidelta=Text3(self,"%d",self.Delta4,-0.44,0.13,-1) if self.Delta5!=0: self.intdelta=Text3(self,"%d",self.Delta5,-0.44,0.17,-1) self.hpbar = DirectWaitBar(barColor=(0,0.176470,0,1),parent = self.panel,scale=(0.3,0,0.23), frameColor=(0,0,0,1),pos = (0,0,-0.84)) self.mpbar=DirectWaitBar(barColor=(0,0,0.6,1),parent = self.panel,scale=(0.3,0,0.23), frameColor=(0,0,0,1),pos = (0,0,-0.90)) self.lvlbar=DirectWaitBar(barColor=(0,0,0.2,1),parent = self.panel,image='glue/lvlbar.png',image_scale=(1.1,0,0.2),scale=0.35, pos = (0,0,-0.8)) self.lvlbar.setTransparency(1) self.lvlbar.detachNode() self.skbtn1=DirectButton(image=self.skillicons[0]+'.png',parent=self.SKNode,pos=(posx-1.3,0,posy-1.2),pad=(-0.1,-0.1),scale=biconscale,command=self.SkillNo,extraArgs=[0]) self.skbtn2=DirectButton(image=self.skillicons[1]+'.png',parent=self.SKNode,pos=(posx-1.3+0.14,0,posy-1.2),pad=(-0.1,-0.1),scale=biconscale,command=self.SkillNo,extraArgs=[1]) self.skbtn3=DirectButton(image=self.skillicons[2]+'.png',parent=self.SKNode,pos=(posx-1.3+0.28,0,posy-1.2),pad=(-0.1,-0.1),scale=biconscale,command=self.SkillNo,extraArgs=[2]) self.skbtn4=DirectButton(image=self.skillicons[3]+'.png',parent=self.SKNode,pos=(posx-1.3+0.42,0,posy-1.2),pad=(-0.1,-0.1),scale=biconscale,command=self.SkillNo,extraArgs=[3]) self.b2 = DirectButton(text ="dam",parent = self.panel,pos=(-0.5,0,0),enableEdit=1,scale=(0.25,0,0.1),command=self.hurt,extraArgs=[200]) self.b3 = DirectButton(text ="",image='tome.tga',pos=(0.5,0,0),frameColor=(0,0,0,0),pad=(-0.1,-0.1),enableEdit=1,scale=(0.07,0,0.07),command=self.itemBuy,extraArgs=[0,300]) self.GOLD=OnscreenText(text='',fg=(1,1,1,1),pos=(1.225,-0.84),scale=0.05) # self.escapeEvent = OnscreenText(text=HELPTEXT, font = font,style=1, fg=(1,1,1,1), pos=(-0.82, -0.725),align=TextNode.ALeft, scale = .045) def displaynot(self): self.panel.detachNode() self.SKNode.detachNode() #------------------------------------------------------------Set Functions--------------------------------------------------------# def setDamage(self,amt): if delta >1: self.damage+=delta else: self.damage=self.damage+self.damage*delta def Delta(self,amt1,amt2,amt3,amt4,amt5): if amt1!=0: #After changes occur for that period the taks sets the values to zero self.Delta1+=amt1 if amt2!=0: self.Delta2+=amt2 if amt3!=0: self.Delta3+=amt3 if amt4!=0: self.Delta4+=amt3 if amt5!=0: self.Delta5+=amt3 def hurt(self,amt): if self.curhp>0: if self.curhp<=self.maxhp: self.curhp-=amt*1 def hurtMag(self,delta): if self.curhp>0: if self.curhp<=self.maxhp: self.curhp-=delta*self.res def heal(self,delta): if self.curhp!=self.maxhp: if self.curhp < self.maxhp: self.curhp+=delta def replenish(self,delta): if self.curmp!=self.maxmp: if self.curmp < self.maxmp: if self.curmp>0: self.curmp+=delta def manaspend(self,amt): if self.curmp>amt: self.curmp-=amt def setSpeed(self,delta): if delta > 1: self.speed+=delta else: self.speed=self.speed+self.speed*delta def setArmor(self,delta): self.armor+=delta def setPos(self,x,y,z): self.model.setPos(x,y,z) def setHPColor(self): if self.curhp<0.25*self.maxhp: self.hpbar['barColor']=(1,0,0,1) elif self.curhp<0.5*self.maxhp: self.hpbar['barColor']=(1,0.5,0,1) elif self.curhp<0.75*self.maxhp: self.hpbar['barColor']=(1,1,0,1) else: self.hpbar['barColor']=(0,0.176470,0,1) #-------------------------------------------------------------Setup Keys And EVENTS--------------------------------------------------# def SetupEvents(self): self.dt=0 self.keyMap = {"left":0, "right":0, "forward":0} self.isMoving = False self.Change=False self.Animate=False self.pos3d=None self.target=Point3() self.dist=0 self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) self.Text = OnscreenText(text="Set PanRate",pos=(-1.25,-0.15),scale=0.1) self.slider = DirectSlider(range=(20,100), value=50, pageSize=2, pos=(-1.25,0,-0.2),scale= (0.2,0.2,0.2), command=self.setScrollSpeed) self.dumm=loader.loadModel("models/panda.egg") self.dumm.reparentTo(render) self.dumm.setTag("Unit",'1') self.dumm.setPos(0,0,0) self.mini=0 self.x1,self.y1=self.model.getX(),self.model.getY() self.x2,self.y2=self.dumm.getX(),self.dumm.getY() self.fired=False self.atk=Attack(self.model,self.dumm,1.4) self.accept("arrow_left", self.setKey1, ["left",1,True]) self.accept("arrow_right", self.setKey1, ["right",1,True]) self.accept("arrow_up", self.setKey1, ["forward",1,True]) self.accept("arrow_left-up", self.setKey1, ["left",0,False]) self.accept("arrow_right-up", self.setKey1, ["right",0,False]) self.accept("arrow_up-up", self.setKey1, ["forward",0,False]) self.accept("mouse1",self.ObjectClick) self.accept("mouse3",self.MoveHero) def MoveHero(self): self.startR=self.model.getHpr() self.target=self.mpos3d x2,y2,z2=self.target.getX(),self.target.getY(),self.target.getZ() h1,p1,r1=self.model.getH(),self.model.getP(),self.model.getR() self.dist=sqrt(pow(self.x1-x2,2)+pow(self.y1-y2,2)) self.sptime=self.dist/(self.speed) self.hall=270-degrees(y2/x2) # self.model.setPos(self.model,self.spd,0,self.spd) self.Inter=LerpPosHprInterval(self.model,self.sptime,pos=self.target ,startPos=self.model.getPos(),startHpr=self.startR,hpr=self.startR)#(h1,p1,self.hall)) #Inter2=Func(self.model.lookAt(self.target),Wait(0.3)) self.heroPace = Sequence(self.Inter,name="heroPace") self.heroPace.start() def Collision(self): self.mpos3d=0 self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0)) base.cTrav = CollisionTraverser() self.collHandler = CollisionHandlerQueue() self.pickerNode = CollisionNode('mouseRay') self.pickerNP = camera.attachNewNode(self.pickerNode) self.pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask()) self.pickerRay = CollisionRay() self.pickerNode.addSolid(self.pickerRay) base.cTrav.addCollider(self.pickerNP, self.collHandler) def ObjectClick(self): if base.mouseWatcherNode.hasMouse(): mpos = base.mouseWatcherNode.getMouse() self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY()) base.cTrav.traverse(render) # Assume for simplicity's sake that myHandler is a CollisionHandlerQueue. if self.collHandler.getNumEntries() > 0: # This is so we get the closest object. self.collHandler.sortEntries() self.pickedObj = self.collHandler.getEntry(0).getIntoNodePath() self.pickedObj = self.pickedObj.findNetTag('Unit') if not self.pickedObj.isEmpty(): self.Attack(self.pickedObj.getPos()) #Handles the object def setKey1(self, key, value,value2): self.keyMap[key] = value self.Change=value2 def checkKeys(self): if (self.keyMap["left"]!=0): self.model.setH(self.model.getH() + self.dt*300) if (self.keyMap["right"]!=0): self.model.setH(self.model.getH() - self.dt*300) if (self.keyMap["forward"]!=0): self.model.setX(self.model, +(self.dt*25*SPEED)) def checkAnim(self): if self.Change: #(self.keyMap["forward"]!=0) or (self.keyMap["left"]!=0) or (self.keyMap["right"]!=0): if self.isMoving is False: self.model.loop("run") self.isMoving = True else: if self.isMoving: self.model.stop() self.model.pose("walk",5) self.isMoving = False if self.Animate: pass def Attack(self,pos): self.atk.setWeil(self.model) self.atk.setTarg(self.dumm) self.atk.setDist(self.mini) if self.mini<=60: self.Animate=self.atk.ATT() else: messenger.send('mouse3') if self.mini<=60: self.atk.ATT() def setScrollSpeed(self): SCROLLSPEED=self.slider['value'] def UnSetupEvents(self): self.ignore("arrow_left") self.ignore("arrow_right") self.ignore("arrow_up") self.ignore("arrow_left-up") self.ignore("arrow_right-up") self.ignore("arrow_up-up") self.ignore("enter") self.ignore("mouse1") self.ignore("mouse3") taskMgr.remove("update") taskMgr.remove("second") taskMgr.remove("mouse") #--------------------------------------------------------------Return Functions------------------------------------------------------# def getDamage(self): return self.damage def getPos(self): return self.model.getPos() def getX(self): return self.model.getX() def getY(self): return self.model.getY() def getZ(self): return self.model.getZ() def getlvl(self): return self.lvl def getModel(self): return self.model def gainxp(self,unit): self.xp+=unit def gainGold(self,gain): self.gold+=gain def sendTime(self,min,sec): self.min=min self.sec=sec #----------------------------------------------------------------ITEM FUNCTIONS--------------------------------------------------------# def itemBuy(self,arg,cost): if self.gold>=0: if self.itemindex<=5: del self.items[self.itemindex] self.items.insert(self.itemindex,arg) self.gainGold(-cost) if self.items[self.itemindex]!=-1: if self.itemindex==0: self.itm0= aspect2d.attachNewNode("item0") DirectButton(text ="",parent=self.itm0,image='tome.tga',pos=(0+0.12*self.itemindex,0,-0.90),pad=(-0.1,-0.1),scale=(0.05,0,0.05),extraArgs=[arg,cost],command=self.itemSold)#,commandButtons=DGG.RMB) if self.itemindex==1: self.itm1= aspect2d.attachNewNode("item1") DirectButton(text ="",parent=self.itm1,image='tome.tga',pos=(0+0.12*self.itemindex,0,-0.90),pad=(-0.1,-0.1),scale=(0.05,0,0.05),extraArgs=[arg,cost],command=self.itemSold)#,commandButtons=DGG.RMB) if self.itemindex==2: self.itm2= aspect2d.attachNewNode("item2") DirectButton(text ="",parent=self.itm2,image='tome.tga',pos=(0+0.12*self.itemindex,0,-0.90),pad=(-0.1,-0.1),scale=(0.05,0,0.05),extraArgs=[arg,cost],command=self.itemSold)#,commandButtons=DGG.RMB) if self.itemindex==3: self.itm3= aspect2d.attachNewNode("item3") DirectButton(text ="",parent=self.itm3,image='tome.tga',pos=(0+0.12*self.itemindex,0,-0.90),pad=(-0.1,-0.1),scale=(0.05,0,0.05),extraArgs=[arg,cost],command=self.itemSold)#,commandButtons=DGG.RMB) if self.itemindex==4: self.itm4= aspect2d.attachNewNode("item4") DirectButton(text ="",parent=self.itm4,image='tome.tga',pos=(0+0.12*self.itemindex,0,-0.90),pad=(-0.1,-0.1),scale=(0.05,0,0.05),extraArgs=[arg,cost],command=self.itemSold)#,commandButtons=DGG.RMB) if self.itemindex==5: self.itm5= aspect2d.attachNewNode("item5") DirectButton(text ="",parent=self.itm5,image='tome.tga',pos=(0+0.12*self.itemindex,0,-0.90),pad=(-0.1,-0.1),scale=(0.05,0,0.05),extraArgs=[arg,cost],command=self.itemSold)#,commandButtons=DGG.RMB) self.itemindex+=1 else: Error("No Empty Slots") else: Error("No Gold") def itemSold(self,itemtosell,cost): self.ind=self.items.index(itemtosell) del self.items[self.ind] self.items.insert(self.ind,-1) self.gainGold(cost/2) if self.ind==0: self.itm0.detachNode() if self.ind==1: self.itm1.detachNode() if self.ind==2: self.itm2.detachNode() if self.ind==3: self.itm3.detachNode() if self.ind==4: self.itm4.detachNode() if self.ind==5: self.itm5.detachNode() self.itemindex-=1 def lvlup(self): self.lvl+=1 self.str=self.char['str'] +(self.strdt*self.lvl) self.str=self.char['str'] +(self.agidt*self.lvl) self.int=self.char['int'] +(self.intdt*self.lvl) self.hpgain=(self.strdt+self.Delta1)*19 self.mpgain=(self.intdt+self.Delta3)*13 self.maxhp=590+self.str*19 self.maxmp=290+self.int*13 #some error here self.heal(self.hpgain) self.replenish(self.mpgain) self.xp =0 #---------------------------------------------------------SKILL FUNCTIONS-------------------------------------# def SkillStatus(self): self.sp1=0 self.sp2=0 self.sp3=0 self.sp4=0 self.sp1dam=0 self.sp2dam=0 self.sp3dam=0 self.sp4dam=0 if self.sp1==1: self.range=400 self.sp1dam=130 self.raduis=100 self.sp2dam=30 self.sp3dam=90 self.pulses=6 def SkillNo(self,arg): if arg==0: if self.curmp>=100: self.accept("mouse1",Blink,extraArgs=[self]) self.skbtn1['image']='cancel.png' # self.skbtn1['command']=self.setOpen() else: Error("NO MANA") elif arg==1: StatUp(self) elif arg==2: StatDn(self) else: Ulti(self) def setOpen(self): self.open=False self.ignore("mouse1") self.skbtn1['image']=self.skillicons[0]+'.png' self.accept("mouse1",self.ObjectClick) #----------------------------------------TASK FUNCTIONS------------------------------------------------------# def Delay(self,task): self.Delta(-2,-2,-2) return task.done def Second(self,task): self.gainGold(self.goldrate) self.heal(self.healrate) self.replenish(self.mprate) return task.again def update(self,task): self.timemin.setText(str(self.min)) self.timesec.setText(str(self.sec)) self.str=self.char['str'] +(self.strdt*self.lvl)+self.Delta3 self.agi=self.char['agi'] + (self.agidt*self.lvl)+self.Delta4 self.int=self.char['int']+(self.intdt*self.lvl)+self.Delta5 self.hpgain=(self.strdt+self.Delta1)*19 self.mpgain=(self.intdt+self.Delta3)*13 self.maxhp=590+self.str*19 self.maxmp=290+self.int*13 #some error here # self.heal(self.hpgain) # self.replenish(self.mpgain) self.armor=self.char['armor'] +(self.agi/7)+self.Delta2 self.atkspeed=1.5/self.agi if self.type=='str': self.TYPESTR() if self.type=='agi': self.TYPEAGI() if self.type=='int': self.TYPEINT() self.healrate=0.03 *self.str self.mprate=0.02 *self.int self.GOLD.setText(str(self.gold)) self.hpbar['range']=int(self.maxhp) self.hpbar['value']=int(self.curhp) self.mpbar['range']=int(self.maxmp) self.mpbar['value']=int(self.curmp) self.lvlbar['range']=int(10*self.lvl) self.lvlbar['value']=int(self.xp) self.HP['text']="HP"+str(int(self.curhp))+"/"+str(int(self.maxhp)) self.MP['text']="MP"+str(int(self.curmp))+"/"+str(int(self.maxmp)) self.DAM['text']=str(int(self.mindamage))+'-'+str(int(self.maxdamage)) self.ARM['text']=str(int(self.armor)) self.STR['text']=str(int(self.str)) self.AGI['text']=str(int(self.agi)) self.INT['text']=str(int(self.int)) self.LVL['text']="LEVEL "+str(int(self.lvl)) if self.xp>=20*20: self.lvlup() if self.curhp<=0: taskMgr.add(self.Death,"death") self.x1,self.y1=self.model.getX(),self.model.getY() self.x2,self.y2=self.dumm.getX(),self.dumm.getY() self.mini=sqrt(pow(self.x1-self.x2,2)+pow(self.y1-self.y2,2)) Debug2(self,str(self.mini)) elapsed = globalClock.getDt() self.dt=elapsed self.setHPColor() self.checkAnim() self.checkKeys() # base.camera.lookAt(self.model) # self.floater.setPos(self.model.getPos()) # base.camera.lookAt(self.floater) return task.cont def Death(self,task): self.isDead=True Debug2(self,str(task.time)) if self.isDead==True: self.model.reparentTo(hidden) self.panel.detachNode() self.deathtime=(self.lvl+1)*3 self.isDead=False if int(task.time)==self.deathtime: self.model.setPos(self.StartPos) self.model.reparentTo(render) self.curhp=self.maxhp self.model.loop("walk") self.display() taskMgr.remove("death") # self.deathtxt.destroy() return task.cont def MousePos(self, task): #This Took me 1.5 Months to Learn if base.mouseWatcherNode.hasMouse(): mpos = base.mouseWatcherNode.getMouse() self.mpos3d = Point3() nearPoint = Point3() farPoint = Point3() base.camLens.extrude(mpos, nearPoint, farPoint) if self.plane.intersectsLine(self.mpos3d, render.getRelativePoint(camera, nearPoint),render.getRelativePoint(camera, farPoint)): pass return task.again def destroy(self): self.panel.detachNode() self.t1.destroy() self.t2.destroy() self.model.remove() self.timesec.destroy() self.timemin.destroy() self.UnsetupEvents()
def __init__(self, showbase): self.showbase = showbase self.showbase.disableMouse() # This disables the default mouse based camera control used by panda. This default control is awkward, and won't be used. self.showbase.camera.setPos(0, -150, 200) self.showbase.camera.lookAt(0, 0, 0) # Gives the camera an initial position and rotation. self.mx, self.my = 0, 0 # Sets up variables for storing the mouse coordinates self.orbiting = False # A boolean variable for specifying whether the camera is in orbiting mode. Orbiting mode refers to when the camera is being moved # because the user is holding down the right mouse button. self.target = Vec3() # sets up a vector variable for the camera's target. The target will be the coordinates that the camera is currently focusing on. self.camDist = 150 # A variable that will determine how far the camera is from it's target focus self.panRateDivisor = 10 # This variable is used as a divisor when calculating how far to move the camera when panning. Higher numbers will yield slower panning # and lower numbers will yield faster panning. This must not be set to 0. self.panZoneSize = .1 # This variable controls how close the mouse cursor needs to be to the edge of the screen to start panning the camera. It must be less than 1, # and I recommend keeping it less than .2 self.panLimitsX = Vec2(-1000, 1000) self.panLimitsY = Vec2(-1000, 1000) # These two vairables will serve as limits for how far the camera can pan, so you don't scroll away from the map. self.maxZoomOut = 500 self.maxZoomIn = 25 #These two variables set the max distance a person can zoom in or out self.orbitRate = 75 # This is the rate of speed that the camera will rotate when middle mouse is pressed and mouse moved # recommended rate 50-100 self.setTarget(0, 0, 0) # calls the setTarget function to set the current target position to the origin. self.turnCameraAroundPoint(0, 0) # calls the turnCameraAroundPoint function with a turn amount of 0 to set the camera position based on the target and camera distance self.accept("mouse2", self.startOrbit) # sets up the camrea handler to accept a right mouse click and start the "drag" mode. self.accept("mouse2-up", self.stopOrbit) # sets up the camrea handler to understand when the right mouse button has been released, and ends the "drag" mode when # the release is detected. self.storeX = 0 self.storeY = 0 # for storing of the x and y for the orbit # The next pair of lines use lambda, which creates an on-the-spot one-shot function. self.accept("wheel_up", self.zoomIn) # sets up the camera handler to detet when the mouse wheel is rolled upwards and uses a lambda function to call the # adjustCamDist function with the argument 0.9 self.accept("wheel_down", self.zoomOut) # sets up the camera handler to detet when the mouse wheel is rolled upwards and uses a lambda function to call the # adjustCamDist function with the argument 1.1 # Keys array (down if 1, up if 0) self.keys = {"cam-left": 0, "cam-right": 0, "cam-up": 0, "cam-down": 0} # Using Arrow Keys self.accept("arrow_left", self.setValue, [self.keys, "cam-left", 1]) self.accept("arrow_right", self.setValue, [self.keys, "cam-right", 1]) self.accept("arrow_up", self.setValue, [self.keys, "cam-up", 1]) self.accept("arrow_down", self.setValue, [self.keys, "cam-down", 1]) self.accept("arrow_left-up", self.setValue, [self.keys, "cam-left", 0]) self.accept("arrow_right-up", self.setValue, [self.keys, "cam-right", 0]) self.accept("arrow_up-up", self.setValue, [self.keys, "cam-up", 0]) self.accept("arrow_down-up", self.setValue, [self.keys, "cam-down", 0]) self.keyPanRate = 1.5 # pan rate for when user presses the arrow keys # set up plane for checking collision with for mouse-3d world self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0))
def __init__(self, parent): self.parent = parent self.baseNode = self.parent.attachNewNode(self.__class__.__name__) x1 = -200 y1 = -200 x2 = 200 y2 = 200 z = 0.0 #waterNP = NodePath("Water Node Parent") #waterNP.reparentTo(parent) #sn = self.drawSquare(-100, -100, 0, 100, 100, 0); #sn.reparentTo(self.baseNode) water = Square(self.baseNode, Point3(x1, y1, 0.2), Point3(x2, y2, 0.2), Vec4(0.0,0.0,0.5,0.5)) wNp = water.draw() t1 = loader.loadTexture( 'assets/textures/wave.png' ) t1.setWrapU(Texture.WMRepeat) t1.setWrapV(Texture.WMRepeat) wNp.setTexture(t1) # Water Shader from # http://www.panda3d.org/forums/viewtopic.php?p=70853&sid=53d92b5ae1683bd9458f21d6026ad36e # anim: vx, vy, scale, skip # distort: offset, strength, refraction factor (0 = perfect mirror, # 1 = total refraction), refractivity anim = ( .022, -.012, 2.5, 0 ) distort = ( .1, 2, .5, .45 ) self.buffer = base.win.makeTextureBuffer( 'waterBuffer', 512, 512 ) self.watercamNP = base.makeCamera( self.buffer ) # Create water surface using a card # The surface will be centered and maker = CardMaker( 'water' ) # Water surface maker.setFrame( x1, x2, y1, y2 ) self.waterNP = self.baseNode.attachNewNode( maker.generate() ) self.waterNP.setPosHpr( ( 0, 0, z ), ( 0, -90, 0 ) ) self.waterNP.setTransparency( TransparencyAttrib.MAlpha ) self.waterNP.setTwoSided(True) # Attach the water shader to the water shader surface waterShader = Shader.load("shaders/water.sha") self.waterNP.setShader(waterShader) self.waterNP.setShaderInput('wateranim', anim ) self.waterNP.setShaderInput('waterdistort', distort ) self.waterNP.setShaderInput('time', 0 ) self.waterPlane = Plane( ( 0, 0, z + 1 ), ( 0, 0, z ) ) # Reflection plane PlaneNode( 'waterPlane' ).setPlane( self.waterPlane ) self.buffer.setClearColor( ( 0, 0, 0.5, 1 ) ) # buffer self.watercamNP.reparentTo( self.baseNode ) # reflection camera cam = self.watercamNP.node() cam.getLens().setFov( base.camLens.getFov() ) cam.getLens().setNearFar( 1, 5000 ) cam.setInitialState( RenderState.make( CullFaceAttrib.makeReverse() ) ) cam.setTagStateKey( 'Clipped' ) cam.setTagState('True', RenderState.make( ShaderAttrib.make().setShader( loader.loadShader( 'shaders/splut3Clipped.sha' ) ) ) ) tex0 = self.buffer.getTexture() # reflection texture, created in # realtime by the 'water camera' tex0.setWrapU( Texture.WMClamp ); tex0.setWrapV( Texture.WMClamp ) self.waterNP.setTexture( TextureStage( 'reflection' ), tex0 ) self.waterNP.setTexture( TextureStage( 'distortion' ), loader.loadTexture( 'assets/textures/water.png' ) ) # distortion texture self.task = taskMgr.add( self.update, 'waterUpdate', sort = 50 )
def __init__(self, world, x1, y1, x2, y2, z): self.world = world logging.info(('setting up water plane at z=' + str(z))) # Water surface maker = CardMaker('water') maker.setFrame(x1, x2, y1, y2) self.waterNP = render.attachNewNode(maker.generate()) self.waterNP.setHpr(0, -90, 0) self.waterNP.setPos(0, 0, z) self.waterNP.setTransparency(TransparencyAttrib.MAlpha) self.waterNP.setShader(loader.loadShader('shaders/water.sha')) self.waterNP.setShaderInput('wateranim', Vec4(0.03, -0.015, 64.0, 0)) # vx, vy, scale, skip # offset, strength, refraction factor (0=perfect mirror, 1=total refraction), refractivity self.waterNP.setShaderInput('waterdistort', Vec4(0.4, 4.0, 0.25, 0.45)) self.waterNP.setShaderInput('time', 0) # Reflection plane self.waterPlane = Plane(Vec3(0, 0, z + 1), Point3(0, 0, z)) planeNode = PlaneNode('waterPlane') planeNode.setPlane(self.waterPlane) # Buffer and reflection camera buffer = base.win.makeTextureBuffer('waterBuffer', 512, 512) buffer.setClearColor(Vec4(0, 0, 0, 1)) cfa = CullFaceAttrib.makeReverse() rs = RenderState.make(cfa) self.watercamNP = base.makeCamera(buffer) self.watercamNP.reparentTo(render) #sa = ShaderAttrib.make() #sa = sa.setShader(loader.loadShader('shaders/splut3Clipped.sha') ) cam = self.watercamNP.node() cam.getLens().setFov(base.camLens.getFov()) cam.getLens().setNear(1) cam.getLens().setFar(5000) cam.setInitialState(rs) cam.setTagStateKey('Clipped') #cam.setTagState('True', RenderState.make(sa)) # ---- water textures --------------------------------------------- # reflection texture, created in realtime by the 'water camera' tex0 = buffer.getTexture() tex0.setWrapU(Texture.WMClamp) tex0.setWrapV(Texture.WMClamp) ts0 = TextureStage('reflection') self.waterNP.setTexture(ts0, tex0) # distortion texture tex1 = loader.loadTexture('textures/water.png') ts1 = TextureStage('distortion') self.waterNP.setTexture(ts1, tex1) # ---- Fog --- broken min = Point3(x1, y1, -999.0) max = Point3(x2, y2, z) boundry = BoundingBox(min, max) self.waterFog = Fog('waterFog') self.waterFog.setBounds(boundry) colour = (0.2, 0.5, 0.8) self.waterFog.setColor(*colour) self.waterFog.setExpDensity(0.05) render.attachNewNode(self.waterFog) #render.setFog(world.waterFog) taskMgr.add(self.update, "waterTask")