def loadAndBuildLevel(self, safezoneId): levelNode = NodePath('level') frameModel = CogdoUtil.loadFlyingModel('level') startPlatformModel = CogdoUtil.loadFlyingModel('levelStart') endPlatformModel = CogdoUtil.loadFlyingModel('levelEnd') for fan in frameModel.findAllMatches('**/*wallFan'): fan.flattenStrong() frameModel.find('**/fogOpaque').setBin('background', 1) frameModel.find('**/ceiling').setBin('background', 2) frameModel.find('**/fogTranslucent_bm').setBin('fixed', 1) frameModel.find('**/wallR').setBin('opaque', 2) frameModel.find('**/wallL').setBin('opaque', 2) frameModel.find('**/fogTranslucent_top').setBin('fixed', 2) frameModel.getChildren().reparentTo(levelNode) levelNode.hide() self._level = CogdoFlyingLevel(self.parent, levelNode, startPlatformModel, endPlatformModel, self.quadLengthUnits, self.quadVisibiltyAhead, self.quadVisibiltyBehind) if Globals.Dev.WantTempLevel: quads = Globals.Dev.DevQuadsOrder else: levelInfo = Globals.Level.DifficultyOrder[safezoneId] quads = [] for difficulty in levelInfo: quadList = Globals.Level.QuadsByDifficulty[difficulty] quads.append(quadList[self._rng.randint(0, len(quadList) - 1)]) for i in quads: filePath = CogdoUtil.getModelPath('quadrant%i' % i, 'flying') quadModel = loader.loadModel(filePath) for np in quadModel.findAllMatches('**/*lightCone*'): CogdoUtil.initializeLightCone(np, 'fixed', 3) self._level.appendQuadrant(quadModel) self._level.ready()
def __updateModel(self): if self.editModel: # create a image with the same size of the texture textureSize = (self.editTexture.getXSize(), self.editTexture.getYSize()) # create a dummy node, where we setup the parameters for the background rendering loadPaintNode = NodePath(PandaNode('paintnode')) loadPaintNode.setShader(Shader.make(self.backgroundShader), 10001) loadPaintNode.setShaderInput('texsize', textureSize[0], textureSize[1], 0, 0) # copy the state onto the camera self.modelColorCam.node().setInitialState(loadPaintNode.getState()) # the camera gets a special bitmask, to show/hide models from it self.modelColorCam.node().setCameraMask(BitMask32.bit(1)) if False: # doesnt work, but would be nicer (not messing with the default render state) hiddenNode = NodePath(PandaNode('hiddennode')) hiddenNode.hide(BitMask32.bit(1)) showTroughNode = NodePath(PandaNode('showtroughnode')) showTroughNode.showThrough(BitMask32.bit(1)) self.modelColorCam.node().setTagStateKey('show-on-backrender-cam') self.modelColorCam.node().setTagState('False', hiddenNode.getState()) self.modelColorCam.node().setTagState('True', showTroughNode.getState()) render.setTag('show-on-backrender-cam', 'False') self.editModel.setTag('show-on-backrender-cam', 'True') else: # make only the model visible to the background camera render.hide(BitMask32.bit(1)) self.editModel.showThrough(BitMask32.bit(1))
class Map(): ''' classdocs ''' def __init__(self, name): self.sectors = [] self.currentSector = None self.mapRoot = NodePath("Map:" + name) def addSector(self,sector): #TODO: check sector is a Sector self.sectors.append(sector) sector.getRoot().reparentTo(self.mapRoot) sector.hide() def getRoot(self): return self.mapRoot def getSectors(self): return self.sectors def getCurrentSector(self): return self.currentSector def setCurrentSector(self, sector): if self.currentSector != None: self.currentSector.hide() self.currentSector = sector if self.currentSector != None: self.currentSector.show() def enable(self): if self.currentSector != None: self.getCurrentSector.enable() def disable(self): if self.currentSector != None: self.getCurrentSector.disable() def hide(self): self.mapRoot.hide() self.disable() def show(self): self.mapRoot.show() for sector in self.sectors: if self.currentSector != sector: sector.hide() self.enable()
def loadAndBuildLevel(self, safezoneId): levelNode = NodePath("level") frameModel = CogdoUtil.loadFlyingModel("level") startPlatformModel = CogdoUtil.loadFlyingModel("levelStart") ver = "_org" if self.isOrg else "" endPlatformModel = CogdoUtil.loadFlyingModel("levelEnd%s" % ver) for fan in frameModel.findAllMatches("**/*wallFan"): fan.flattenStrong() frameModel.find("**/fogOpaque").setBin("background", 1) frameModel.find("**/ceiling").setBin("background", 2) frameModel.find("**/fogTranslucent_bm").setBin("fixed", 1) frameModel.find("**/wallR").setBin("opaque", 2) frameModel.find("**/wallL").setBin("opaque", 2) frameModel.find("**/fogTranslucent_top").setBin("fixed", 2) frameModel.getChildren().reparentTo(levelNode) if not self.isOrg: levelNode.hide() self._level = CogdoFlyingLevel( self.parent, levelNode, startPlatformModel, endPlatformModel, self.quadLengthUnits, self.quadVisibiltyAhead, self.quadVisibiltyBehind, ) if Globals.Dev.WantTempLevel: quads = Globals.Dev.DevQuadsOrder else: levelInfo = Globals.Level.DifficultyOrder[safezoneId] quads = [] for difficulty in levelInfo: quadList = Globals.Level.QuadsByDifficulty[difficulty] quads.append(quadList[self._rng.randint(0, len(quadList) - 1)]) for i in quads: ver = "_org" if self.isOrg else "" filePath = CogdoUtil.getModelPath("quadrant%i%s" % (i, ver), "flying") quadModel = loader.loadModel(filePath) for np in quadModel.findAllMatches("**/*lightCone*"): CogdoUtil.initializeLightCone(np, "fixed", 3) self._level.appendQuadrant(quadModel) self._level.ready()
def createHotspotCollisionGeom(self, hp): ''' Creates a collision box that covers the hotspot's interactive area in order to be able to detect a hotspot by raycasting from the mouse position. ''' dim = self.getFaceTextureDimensions(hp.face) # get world space coords of top left corner t1 = hp.xo / dim[0] t2 = hp.yo / dim[1] topLeft = self.getWorldPointFromFacePoint(hp.face, (t1, t2)) # get world space coords of top right corner t1 = hp.xe / dim[0] t2 = hp.yo / dim[1] topRight = self.getWorldPointFromFacePoint(hp.face, (t1, t2)) # get world space coords of bottom right corner t1 = hp.xe / dim[0] t2 = hp.ye / dim[1] bottomRight = self.getWorldPointFromFacePoint(hp.face, (t1, t2)) # get world space coords of bottom left corner t1 = hp.xo / dim[0] t2 = hp.ye / dim[1] bottomLeft = self.getWorldPointFromFacePoint(hp.face, (t1, t2)) # polygon = CollisionPolygon(topLeft, bottomLeft, bottomRight, topRight) polygon = CollisionPolygon(topLeft, topRight, bottomRight, bottomLeft) # name it as the hotspot, it will be convenient for raycasting cn = CollisionNode(hp.name) cn.addSolid(polygon) collisionNP = NodePath(cn) collisionNP.setName(hp.name) collisionNP.reparentTo(self.collisionsGeomsParent) if not hp.active: collisionNP.hide() else: collisionNP.show()
def __updateModel(self): if self.editModel: # create a image with the same size of the texture textureSize = (self.editTexture.getXSize(), self.editTexture.getYSize()) # create a dummy node, where we setup the parameters for the background rendering loadPaintNode = NodePath(PandaNode('paintnode')) loadPaintNode.setShader(Shader.make(self.backgroundShader), 10001) loadPaintNode.setShaderInput('texsize', textureSize[0], textureSize[1], 0, 0) # copy the state onto the camera self.modelColorCam.node().setInitialState(loadPaintNode.getState()) # the camera gets a special bitmask, to show/hide models from it self.modelColorCam.node().setCameraMask(BitMask32.bit(1)) if False: # doesnt work, but would be nicer (not messing with the default render state) hiddenNode = NodePath(PandaNode('hiddennode')) hiddenNode.hide(BitMask32.bit(1)) showTroughNode = NodePath(PandaNode('showtroughnode')) showTroughNode.showThrough(BitMask32.bit(1)) self.modelColorCam.node().setTagStateKey( 'show-on-backrender-cam') self.modelColorCam.node().setTagState('False', hiddenNode.getState()) self.modelColorCam.node().setTagState( 'True', showTroughNode.getState()) render.setTag('show-on-backrender-cam', 'False') self.editModel.setTag('show-on-backrender-cam', 'True') else: # make only the model visible to the background camera render.hide(BitMask32.bit(1)) self.editModel.showThrough(BitMask32.bit(1))
class Sector(): ''' classdocs ''' def __init__(self, name): self.links = [] self.heightfields = [] self.sectorRoot = NodePath("Sector:" + name) def addHeightfield(self, heightfield): self.heightfields.append(heightfield) heightfield.getRoot().reparentTo(self.sectorRoot) def getLinks(self): return self.links def getRoot(self): return self.sectorRoot def enable(self): for heightfield in self.heightfields: heightfield.enable() def disable(self): for heightfield in self.heightfields: heightfield.disable() def hide(self): self.sectorRoot.hide() self.disable() def show(self): self.sectorRoot.show() self.enable()
class Fish(NodePath): def __init__(self, fishManager, myData, index, trophy = 0): NodePath.__init__(self, '%s_%d' % (myData['name'], index)) self.trophy = trophy self.myData = myData if not self.trophy: self.fishManager = fishManager self.index = index self.fsm = FishFSM(self) self.weight = random.randint(self.myData['weightRange'][0], self.myData['weightRange'][1]) else: self.weight = trophy self.adjustedScale = (self.myData['scaleRange'][1] - self.myData['scaleRange'][0]) * (self.weight - self.myData['weightRange'][0]) / (self.myData['weightRange'][1] - self.myData['weightRange'][0]) + self.myData['scaleRange'][0] self.initActor() if not self.trophy: self.initVariables() self.initFishStatusIcon() if FishingGlobals.wantDebugCollisionVisuals: self.initCollisions() self.avoidingFish = False self.biteBubbleEffect = None self.idleBubbleEffect = None self.fightBubbleEffect = None self.behaviorNameToFunction = { 'straight': self.performStraightBehavior, 'sineStraight': self.performSineStraightBehavior, 'erratic': self.performErraticBehavior } self.sineDtAccumulator = 0.0 self.erraticDtAccumulator = 0.0 self.myZ = 0.0 if not self.trophy: self.setLightOff() def initActor(self): self.animDict = { } for anim in FishingGlobals.fishAnimations: self.animDict[anim] = 'models/char/pir_a_gam_fsh_%s_%s.bam' % (self.myData['model'], anim) self.actor = BlendActor('models/char/pir_r_gam_fsh_%s.bam' % self.myData['model'], self.animDict, FishingGlobals.defaultFishBlendTime, FishingGlobals.fishBlendTimeDict) self.actor.reparentTo(self) self.actor.setScale(self.adjustedScale) self.mouthJoint = self.actor.exposeJoint(None, 'modelRoot', 'hookAttach') self.attractionPoint = NodePath('AttractionPoint') self.attractionPoint.reparentTo(self.mouthJoint) self.attractionPoint.setPos(0.0, 0.0, 0.0) self.actor.setPlayRate(self.myData['speed'] * self.myData['swimAnimationMultiplier'], 'swimIdle') self.actor.setPlayRate(self.myData['speed'] * self.myData['swimAnimationMultiplier'], 'swimIdleOpposite') self.actor.setPlayRate(self.myData['speed'] * self.myData['turnAnimationMultiplier'], 'turn') self.actor.setPlayRate(self.myData['speed'] * self.myData['turnAnimationMultiplier'], 'turnOpposite') if not self.trophy: self.setBin('fishingGame', 10) def codeReload(self): self.actor.setPlayRate(self.myData['speed'] * self.myData['swimAnimationMultiplier'], 'swimIdle') self.actor.setPlayRate(self.myData['speed'] * self.myData['swimAnimationMultiplier'], 'swimIdleOpposite') self.actor.setPlayRate(self.myData['speed'] * self.myData['turnAnimationMultiplier'], 'turn') self.actor.setPlayRate(self.myData['speed'] * self.myData['turnAnimationMultiplier'], 'turnOpposite') def initFishStatusIcon(self): self.fishStatusIconTextNode = TextNode('fishBitingIcon') self.fishStatusIconNodePath = NodePath(self.fishStatusIconTextNode) self.fishStatusIconNodePath.setPos(0.0, 0.0, self.myData['indicatorHeightOffset']) self.fishStatusIconTextNode.setText('?') self.fishStatusIconTextNode.setTextColor(1.0, 0.0, 0.0, 1.0) self.fishStatusIconNodePath.reparentTo(self.mouthJoint) self.fishStatusIconNodePath.setBillboardPointEye() self.fishStatusIconNodePath.hide() self.fishStatusIconNodePath.setShaderOff() def initVariables(self): self.attractionVisual = None self.collisionVisual = None self.movingRight = True self.turnSpeed = 160.0 self.turnTowardLureInterval = None self.velocity = FishingGlobals.baseFishVelocity * self.myData['speed'] self.accel = FishingGlobals.baseFishAccel * self.myData['speed'] self.fishMoveSequence = None self.bubbleEffect = None def initCollisions(self): self.collisionVisual = loader.loadModel('models/props/crate') self.collisionVisual.setTransparency(1) self.collisionVisual.setColor(1.0, 1.0, 1.0, 0.29999999999999999) self.collisionVisual.setScale(*self.myData['collisionBoxSize']) self.collisionVisual.setPos(*self.myData['collisionBoxOffset']) self.collisionVisual.reparentTo(self) self.collisionVisual.hide() self.attractionVisual = loader.loadModel('models/ammunition/cannonball') self.attractionVisual.setTransparency(1) self.attractionVisual.setColor(0.0, 1.0, 0.0, 0.29999999999999999) self.attractionVisual.setScale(self.myData['attractionRadius']) self.attractionVisual.reparentTo(self.attractionPoint) self.attractionVisual.hide() self.collisionVisualVisible = False def hide(self): NodePath.hide(self) if self.idleBubbleEffect: self.idleBubbleEffect.hide() def show(self): NodePath.show(self) if self.idleBubbleEffect: self.idleBubbleEffect.show() def reloadCollisions(self): if FishingGlobals.wantDebugCollisionVisuals: self.collisionVisual.removeNode() self.attractionVisual.removeNode() self.initCollisions() def cleanFishData(self): pass def destroy(self): self.closeFish = [] self.actor.destroy() self.stopIdleBubbleEffect() self.stopFightBubbleEffect() if self.fishMoveSequence: self.fishMoveSequence.pause() self.fishMoveSequence = None if self.fsm: del self.fsm self.fsm = None self.behaviorNameToFunction = { } self.removeNode() def pickPositionAndSwim(self): self.initVariables() self.actor.clearControlEffectWeights() if self.myData['depth'] == 0: depth = random.uniform(FishingGlobals.fishingLevelBoundaries[self.myData['depth']], self.fishManager.gameObject.waterLevel + FishingGlobals.fishSpawnBelowWaterLevelHeight) else: depth = random.uniform(FishingGlobals.fishingLevelBoundaries[self.myData['depth']], FishingGlobals.fishingLevelBoundaries[self.myData['depth'] - 1]) startX = random.uniform(FishingGlobals.leftFishBarrier + 5.0, FishingGlobals.rightFishBarrier - 5.0) self.setPos(startX, 0.0, depth) if random.randint(0, 1): self.fsm.request('TurnAround', 'Swimming', False) else: self.fsm.request('Swimming') def turnAround(self, nextState, shouldMoveRight): if self.velocity[0] < 0 and shouldMoveRight: self.velocity[0] = -self.velocity[0] elif self.velocity[0] > 0 and not shouldMoveRight: self.velocity[0] = -self.velocity[0] self.movingRight = self.velocity[0] > 0 if self.fishMoveSequence: self.fishMoveSequence.pause() self.fishMoveSequence.clearToInitial() animationToTurn = 'turn' if self.movingRight: animationToTurn = 'turnOpposite' durationOfFishTurn = self.myData['durationOfFishTurn'] self.fishMoveSequence = Parallel(Sequence(Func(self.actor.changeAnimationTo, animationToTurn, False), Wait(durationOfFishTurn), Func(self.fsm.request, nextState)), Sequence(Wait(durationOfFishTurn * 0.33000000000000002), Func(self.setXVelocity, 0.0), Wait(durationOfFishTurn * 0.66000000000000003), Func(self.setXVelocity, self.velocity[0])), name = '%s_turnAroundInterval' % self.getName()) self.velocity[0] = -self.velocity[0] self.fishMoveSequence.start() def setXVelocity(self, newVel): self.velocity[0] = newVel def checkForBiting(self): if self.fishManager.activeFish is not None: return None if self.fishManager.gameObject.fsm.getCurrentOrNextState() not in [ 'Fishing', 'Reeling', 'LureStall', 'LegdFishShow']: return None inv = localAvatar.getInventory() rodLvl = inv.getItemQuantity(InventoryType.FishingRod) if self.myData['depth'] + 1 > rodLvl: return None self.fsm.request('Biting') def checkForBoxOverlap(self, otherFish): pos = self.getPos(self.fishManager.gameObject.fishingSpot) size = self.myData['collisionBoxSize'] offset = list(self.myData['collisionBoxOffset']) otherPos = otherFish.getPos() otherSize = otherFish.myData['collisionBoxSize'] otherOffset = list(otherFish.myData['collisionBoxOffset']) if pos[0] + size[0] / 2.0 + offset[0] > (otherPos[0] - otherSize[0] / 2.0) + otherOffset[0] and (pos[0] - size[0] / 2.0) + offset[0] < otherPos[0] + otherSize[0] / 2.0 + otherOffset[0] and pos[2] + size[2] / 2.0 + offset[2] > (otherPos[2] - otherSize[2] / 2.0) + otherOffset[2] and (pos[2] - size[2] / 2.0) + offset[2] < otherPos[2] + otherSize[2] / 2.0 + otherOffset[2]: return True return False def checkForCloseFish(self, index): if index < len(self.fishManager.uncaughtFish) - 1: for i in range(index + 1, len(self.fishManager.uncaughtFish)): if self.fishManager.uncaughtFish[i].index != self.index: if self.checkForBoxOverlap(self.fishManager.uncaughtFish[i]): self.closeFish.append(self.fishManager.uncaughtFish[i]) if FishingGlobals.wantDebugCollisionVisuals: self.collisionVisual.setColor(1, 0, 0, 0.29999999999999999) self.checkForBoxOverlap(self.fishManager.uncaughtFish[i]) if len(self.closeFish) == 0: if FishingGlobals.wantDebugCollisionVisuals: self.collisionVisual.setColor(1, 1, 1, 0.29999999999999999) def checkForLures(self, currentState, lurePos): if (self.getX() + FishingGlobals.fishAttractionOffset < lurePos[0] or self.movingRight or self.getX() - FishingGlobals.fishAttractionOffset > lurePos[0]) and not (self.movingRight): if self.attractionPoint.getDistance(self.fishManager.gameObject.lure) < self.myData['attractionRadius'] + self.fishManager.gameObject.lure.lureAttractRadius: self.checkForBiting() def update(self, dt, index, lurePos): currentState = self.fsm.getCurrentOrNextState() self.closeFish = [] if currentState in [ 'ScareAway', 'Swimming', 'Flee', 'TurnAround']: self.checkForCloseFish(index) if currentState in [ 'Swimming']: self.checkForLures(currentState, lurePos) self.updateBasedOnBehavior(dt, lurePos) elif currentState in [ 'Hooked', 'AboutToFight', 'HookedFighting']: self.checkForCloseFish(-1) for fish in self.closeFish: self.makeFishRunFromMe(fish) def makeFishRunFromMe(self, otherFish): if otherFish.fsm.getCurrentOrNextState() == 'Flee' or otherFish.fsm.getCurrentOrNextState() == 'TurnAround': return None if otherFish.getX() < self.getX(self.fishManager.gameObject.fishingSpot) and otherFish.movingRight: otherFish.fsm.request('TurnAround', 'Flee', False) elif otherFish.getX() > self.getX(self.fishManager.gameObject.fishingSpot) and not (otherFish.movingRight): otherFish.fsm.request('TurnAround', 'Flee', True) else: otherFish.fsm.request('Flee') def updateBasedOnBehavior(self, dt, lurePos): currentState = self.fsm.getCurrentOrNextState() newX = self.getX() newY = self.getY() newZ = self.getZ() for fish in self.closeFish: if self.myData['size'] == 'small' and fish.myData['size'] == 'large': if self.checkForEating(fish): return None self.avoidingFish = True if fish.velocity[1] > 0.0 and fish.avoidingFish: self.velocity[1] = -(FishingGlobals.fishAvoidYVelocity) else: self.velocity[1] = FishingGlobals.fishAvoidYVelocity if abs(fish.getY() - self.getY()) > self.myData['collisionBoxSize'][1] + fish.myData['collisionBoxSize'][1]: self.velocity[1] = 0.0 continue if len(self.closeFish) == 0 and abs(self.getY()) > FishingGlobals.fishYTolerance: self.avoidingFish = False if self.getY() > 0: self.velocity[1] = -(FishingGlobals.fishAvoidYVelocity) else: self.velocity[1] = FishingGlobals.fishAvoidYVelocity elif len(self.closeFish) == 0 and abs(self.getY()) < FishingGlobals.fishYTolerance: self.avoidingFish = False self.velocity[1] = 0.0 self.setY(0.0) newY = self.getY() + self.velocity[1] * dt + self.accel[1] * dt * dt if currentState in [ 'Swimming', 'TurnAround', 'Flee', 'ScareAway']: if currentState == 'ScareAway': (newX, newZ) = self.performScareAwayBehavior(dt, self.velocity, self.accel) elif currentState == 'Flee': (newX, newZ) = self.performFleeBehavior(dt, self.velocity, self.accel) else: (newX, newZ) = self.behaviorNameToFunction[self.myData['behaviorDict']['name']](dt, self.velocity, self.accel) currentState = self.fsm.getCurrentOrNextState() if newX < FishingGlobals.leftFishBarrier: if currentState == 'ScareAway': if newX < FishingGlobals.leftFishBarrier - FishingGlobals.fullyOffscreenXOffset: self.fsm.request('Offscreen') return None elif currentState != 'TurnAround' and not (self.movingRight): self.fsm.request('TurnAround', 'Swimming', True) elif newX > FishingGlobals.rightFishBarrier: if currentState != 'TurnAround' and self.movingRight: self.fsm.request('TurnAround', 'Swimming', False) newZ = min(max(FishingGlobals.fishingLevelBoundaries[len(FishingGlobals.fishingLevelBoundaries) - 1], newZ), self.fishManager.gameObject.waterLevel + FishingGlobals.fishSpawnBelowWaterLevelHeight) self.setPos(newX, newY, newZ) def checkForEating(self, fishThatWillEat): if (self.getX() < fishThatWillEat.getX() or not (fishThatWillEat.movingRight) or self.getX() > fishThatWillEat.getX() or fishThatWillEat.movingRight) and self.fsm.getCurrentOrNextState() == 'Swimming' and fishThatWillEat.fsm.getCurrentOrNextState() == 'Swimming' and random.random() < 1.0: self.fsm.request('BeingEaten', fishThatWillEat) fishThatWillEat.fsm.request('Eating', self.weight) return True return False def startIdleBubbleEffect(self): self.idleBubbleEffect = FishIdleBubbleEffect.getEffect(unlimited = True) if self.idleBubbleEffect: self.idleBubbleEffect.reparentTo(self.mouthJoint) self.idleBubbleEffect.setScale(1.0) self.idleBubbleEffect.setHpr(0, 0, 0) self.idleBubbleEffect.setLifespanBasedOnDepth(self.getPos(render)) self.idleBubbleEffect.setBubbleSizeBasedOnWeight(self.weight) self.idleBubbleEffect.particleDummy.setBin('fishingGame', 5) self.idleBubbleEffect.startLoop() def stopIdleBubbleEffect(self): if self.idleBubbleEffect: self.idleBubbleEffect.stopLoop() self.idleBubbleEffect = None def startBiteBubbleEffect(self): self.biteBubbleEffect = FishBitingBubbleEffect.getEffect(unlimited = True) if self.biteBubbleEffect: self.biteBubbleEffect.reparentTo(self.mouthJoint) self.biteBubbleEffect.setScale(1.0) self.biteBubbleEffect.setHpr(0, 0, 0) self.biteBubbleEffect.setLifespanBasedOnDepth(self.getPos(render)) self.biteBubbleEffect.setBubbleSizeBasedOnWeight(self.weight) self.biteBubbleEffect.particleDummy.setBin('fishingGame', 5) self.biteBubbleEffect.play() def stopBiteBubbleEffect(self): if self.biteBubbleEffect: self.biteBubbleEffect.stopLoop() self.biteBubbleEffect = None def startFightBubbleEffect(self): self.fightBubbleEffect = FishFightingHookedBubbleEffect.getEffect(unlimited = True) if self.fightBubbleEffect: self.fightBubbleEffect.reparentTo(self.mouthJoint) self.fightBubbleEffect.setScale(1.0) self.fightBubbleEffect.setHpr(0, 0, 0) self.fightBubbleEffect.setLifespanBasedOnDepth(self.getPos(render)) self.fightBubbleEffect.setBubbleSizeBasedOnWeight(self.weight) self.fightBubbleEffect.particleDummy.setBin('fishingGame', 5) self.fightBubbleEffect.startLoop() def stopFightBubbleEffect(self): if self.fightBubbleEffect: self.fightBubbleEffect.stopLoop() self.fightBubbleEffect = None def performStraightBehavior(self, dt, velocity, accel): newX = self.getX() + velocity[0] * dt + accel[0] * dt * dt newZ = self.getZ() + velocity[2] * dt + accel[2] * dt * dt return (newX, newZ) def performSineStraightBehavior(self, dt, velocity, accel): self.sineDtAccumulator += dt newX = self.getX() + velocity[0] * dt + accel[0] * dt * dt newZ = self.myZ + math.sin(self.sineDtAccumulator) * self.myData['behaviorDict']['sineMultiplier'] return (newX, newZ) def performScareAwayBehavior(self, dt, velocity, accel): newX = self.getX() + velocity[0] * FishingGlobals.scareAwayVelocityMultiplier * dt + accel[0] * dt * dt newZ = self.getZ() + velocity[2] * FishingGlobals.scareAwayVelocityMultiplier * dt + accel[2] * dt * dt return (newX, newZ) def performFleeBehavior(self, dt, velocity, accel): newX = self.getX() + velocity[0] * FishingGlobals.fleeVelocityMultiplier * dt + accel[0] * dt * dt newZ = self.getZ() + velocity[2] * FishingGlobals.fleeVelocityMultiplier * dt + accel[2] * dt * dt return (newX, newZ) def performErraticBehavior(self, dt, velocity, accel): self.erraticDtAccumulator += dt self.sineDtAccumulator += dt newX = self.getX() + velocity[0] * dt + accel[0] * dt * dt newZ = self.myZ + math.sin(self.sineDtAccumulator) * self.myData['behaviorDict']['sineMultiplier'] if self.erraticDtAccumulator > self.myData['behaviorDict']['secondsBetweenChanges']: self.erraticDtAccumulator = 0 if random.random() < self.myData['behaviorDict']['chanceOfTurning']: if self.fsm.getCurrentOrNextState() != 'TurnAround': self.fsm.request('TurnAround', 'Swimming', not (self.movingRight)) return (newX, newZ) def showAttractionCollisionVisuals(self): if FishingGlobals.wantDebugCollisionVisuals: self.attractionVisual.show() def hideAttractionCollisionVisuals(self): if FishingGlobals.wantDebugCollisionVisuals: self.attractionVisual.hide() def showAvoidanceCollisionVisuals(self): if FishingGlobals.wantDebugCollisionVisuals: self.collisionVisual.show() def hideAvoidanceCollisionVisuals(self): if FishingGlobals.wantDebugCollisionVisuals: self.collisionVisual.hide()
class LegendaryFishingGameGUI: def __init__(self, gameObject = None): base.loadingScreen.beginStep('LegendaryGameGUI', 4, 20) self.gameObject = gameObject self.guiImage = loader.loadModel('models/minigames/pir_m_gam_fsh_legendaryGui') self.UICompoments = { } self.uiBaseNode = NodePath('baseNode') self.uiBaseNode.reparentTo(aspect2d) self.uiBaseNode.show() self.leftBaseNode = NodePath('leftBaseNode') self.leftBaseNode.reparentTo(base.a2dLeftCenter) self.leftBaseNode.show() self.fishActor = None self.actorAnim = { } self.scaleSize = { InventoryType.Collection_Set11_Part1: 0.059999999999999998, InventoryType.Collection_Set11_Part2: 0.055, InventoryType.Collection_Set11_Part3: 0.12, InventoryType.Collection_Set11_Part4: 0.086999999999999994, InventoryType.Collection_Set11_Part5: 0.080000000000000002 } self.meterFrame = DirectFrame(parent = self.leftBaseNode, frameSize = (-0.29999999999999999, 0.29999999999999999, -1.0, 0.0), frameColor = (1.0, 1.0, 1.0, 0.0), relief = None, state = DGG.DISABLED, pos = (1.0, 0.0, -0.45000000000000001), hpr = (0, 0, 0), scale = (1.3, 0.0, 1.3), image = self.guiImage.find('**/pir_t_gui_fsh_meter'), image_scale = (0.20000000000000001, 0.0, 0.80000000000000004), image_pos = (0, 0, 0), text = '', textMayChange = 1, text_scale = PiratesGuiGlobals.TextScaleTitleLarge, text_pos = (-0.55000000000000004, 0.10000000000000001), text_shadow = PiratesGuiGlobals.TextShadow) self.UICompoments['meterFrame'] = self.meterFrame self.fishingRod = DirectFrame(parent = self.meterFrame, frameSize = (-0.29999999999999999, 0.29999999999999999, -1.0, 0.0), relief = None, state = DGG.DISABLED, pos = FishingGlobals.fishingRodScreenPosition, image = self.guiImage.find('**/pir_t_gui_fsh_fullRod'), image_scale = (1.0, 0.0, 0.125), image_pos = (0.20000000000000001, 0, 0)) self.fishingRod.setR(FishingGlobals.fishingRodInitSlope) self.UICompoments['fishingRod'] = self.fishingRod base.loadingScreen.tick() self.fishingHandleBaseFrame = DirectFrame(parent = self.uiBaseNode, frameSize = (-0.29999999999999999, 0.29999999999999999, -1.5, 1.5), frameColor = (1.0, 1.0, 1.0, 0.0), relief = None, state = DGG.DISABLED, pos = (0.0, 0.0, 0.0), hpr = (0, 0, 0), scale = (0.71999999999999997, 0.0, 0.71999999999999997), image = self.guiImage.find('**/pir_t_gui_fsh_partialRod'), image_scale = (3.7999999999999998, 0.0, 1.8999999999999999), image_pos = (0, 0, 0), image_hpr = (0.0, 0.0, 0)) self.fishingHandleBaseFrame.hide() self.UICompoments['fishingHandleBaseFrame'] = self.fishingHandleBaseFrame self.fishingHandle = DirectFrame(parent = self.fishingHandleBaseFrame, frameSize = (-0.080000000000000002, 0.080000000000000002, -0.20000000000000001, 0.20000000000000001), relief = None, state = DGG.DISABLED, pos = (-0.10000000000000001, 0.0, -0.050000000000000003), hpr = (0, 0, 0), image = self.guiImage.find('**/pir_t_gui_fsh_handleArm'), image_scale = (1.0, 0.0, 1.0), image_pos = (-0.042000000000000003, 0, -0.115), image_hpr = (0.0, 0.0, 0)) self.UICompoments['fishingHandle'] = self.fishingHandle self.arrowImage = DirectFrame(parent = self.fishingHandleBaseFrame, frameSize = (-0.40000000000000002, 0.40000000000000002, -0.40000000000000002, 0.40000000000000002), relief = None, state = DGG.DISABLED, pos = (0.0, 0.0, 0.0), hpr = (0, 0, 0), scale = (1.2, 0.0, 1.2), image = self.guiImage.find('**/pir_t_gui_fsh_arrow'), image_scale = (1.0, 0.0, 1.0), image_pos = (0.0, 0, 0.0), image_hpr = (0.0, 0.0, 0.0)) self.arrowImage.hide() self.UICompoments['arrowImage'] = self.arrowImage btnGeom = (self.guiImage.find('**/pir_t_gui_fsh_handle'), self.guiImage.find('**/pir_t_gui_fsh_handle'), self.guiImage.find('**/pir_t_gui_fsh_handleOn')) self.fishingHandleButton = GuiButton(pos = (-0.29999999999999999, 0, -0.55000000000000004), hpr = (0, 0, 0), scale = 0.45000000000000001, image = btnGeom, image_pos = (0, 0, 0), image_scale = 1.0, sortOrder = 2) self.fishingHandleButton.bind(DGG.B1PRESS, self.handleButtonClicked) self.fishingHandleButton.reparentTo(self.fishingHandle) self.UICompoments['fishingHandleButton'] = self.fishingHandleButton self.fishingHandleBaseFrame.setTransparency(TransparencyAttrib.MAlpha) self.meterFrame.setTransparency(TransparencyAttrib.MAlpha) self.lineOneTransitTextNode = TextNode('lineOneTransitText') self.lineOneTransitTextNode.setFont(PiratesGlobals.getPirateFont()) self.lineOneTransitTextNode.setText('') self.lineOneTransitTextNode.setAlign(TextNode.ACenter) self.lineOneTransitTextNode.setTextColor(1.0, 1.0, 1.0, 0.5) self.lineOneTransitTextNodePath = NodePath(self.lineOneTransitTextNode) self.lineOneTransitTextNodePath.setPos(0.0, 0.0, -0.80000000000000004) self.lineOneTransitTextNodePath.setScale(0.34999999999999998, 0.34999999999999998, 0.34999999999999998) self.lineOneTransitTextNodePath.reparentTo(self.uiBaseNode) self.lineOneTransitTextNodePath.hide() self.UICompoments['lineOneTransitText'] = self.lineOneTransitTextNodePath self.lineTwoTransitTextNode = TextNode('lineTwoTransitText') self.lineTwoTransitTextNode.setFont(PiratesGlobals.getPirateFont()) self.lineTwoTransitTextNode.setText('') self.lineTwoTransitTextNode.setAlign(TextNode.ACenter) self.lineTwoTransitTextNode.setTextColor(1.0, 1.0, 1.0, 0.5) self.lineTwoTransitTextNodePath = NodePath(self.lineTwoTransitTextNode) self.lineTwoTransitTextNodePath.setPos(-0.40000000000000002, 0.0, -0.94999999999999996) self.lineTwoTransitTextNodePath.setScale(0.12, 0.12, 0.12) self.lineTwoTransitTextNodePath.reparentTo(self.uiBaseNode) self.lineTwoTransitTextNodePath.hide() self.UICompoments['lineTwoTransitText'] = self.lineTwoTransitTextNodePath base.loadingScreen.tick() self.test_guiImage = loader.loadModel('models/gui/toplevel_gui') self.buttonIcon = (self.test_guiImage.find('**/treasure_chest_closed'), self.test_guiImage.find('**/treasure_chest_closed'), self.test_guiImage.find('**/treasure_chest_closed_over')) self.winImagePanel = GuiPanel.GuiPanel('', 2.6000000000000001, 1.8999999999999999, True) self.winImagePanel.setPos(-1.3, 0.0, -0.94999999999999996) self.winImagePanel.reparentTo(self.uiBaseNode) self.winImagePanel.background = OnscreenImage(parent = self.winImagePanel, scale = (2.3999999999999999, 0, 1.8), image = self.guiImage.find('**/pir_t_gui_fsh_posterBackground'), hpr = (0, 0, 0), pos = (1.3, 0, 0.94999999999999996)) self.winImagePanel.setBin('gui-popup', -4) self.winTitleTextNode = TextNode('winTitleTextNode') self.winTitleTextNode.setText('Congratulations!') self.winTitleTextNode.setAlign(TextNode.ACenter) self.winTitleTextNode.setFont(PiratesGlobals.getPirateFont()) self.winTitleTextNode.setTextColor(0.23000000000000001, 0.089999999999999997, 0.029999999999999999, 1.0) self.winTitleTextNodePath = NodePath(self.winTitleTextNode) self.winTitleTextNodePath.setPos(1.3500000000000001, 0.0, 1.6699999999999999) self.winTitleTextNodePath.setScale(0.17999999999999999) self.winTitleTextNodePath.reparentTo(self.winImagePanel) self.wholeStoryTextNode = TextNode('storyTextNode') self.wholeStoryTextNode.setText('') self.wholeStoryTextNode.setWordwrap(19.0) self.wholeStoryTextNode.setTextColor(0.23000000000000001, 0.089999999999999997, 0.029999999999999999, 1.0) self.wholeStoryTextNodePath = NodePath(self.wholeStoryTextNode) self.wholeStoryTextNodePath.setPos(0.33000000000000002, 0.0, 1.6399999999999999) self.wholeStoryTextNodePath.setScale(0.050000000000000003) self.wholeStoryTextNodePath.reparentTo(self.winImagePanel) self.winImagePanel.closeButton['command'] = self.closeDialogGotNextState self.winImagePanel.closeButton['extraArgs'] = [ 'winImagePanel', 'FarewellLegendaryFish', False] self.UICompoments['winImagePanel'] = self.winImagePanel self.winImagePanel.hide() self.luiCloseDialogSequence = Sequence() self.arrowImageRotationInterval = LerpHprInterval(self.arrowImage, 2.2000000000000002, self.arrowImage.getHpr() + Point3(0.0, 0.0, 280.0), self.arrowImage.getHpr()) self.luiArrowRotatingSequence = Sequence(Func(self.showGui, [ 'arrowImage']), Parallel(Func(self.arrowImageRotationInterval.start), Wait(2.2000000000000002)), Func(self.hideGui, [ 'arrowImage']), Func(self.arrowImage.setHpr, self.arrowImage.getHpr() + Point3(0.0, 0.0, 5.0)), name = self.gameObject.distributedFishingSpot.uniqueName('luiArrowRotatingSequence')) self.lineOneColorChange = LerpColorScaleInterval(self.lineOneTransitTextNodePath, FishingGlobals.legendaryTransitionTextDuration, (1.0, 1.0, 1.0, 0.0), (1.0, 1.0, 1.0, 1.0), blendType = 'easeOut') self.lineOnePosChange = LerpPosInterval(self.lineOneTransitTextNodePath, FishingGlobals.legendaryTransitionTextDuration, (0.0, 0.0, -0.20000000000000001), (0.0, 0.0, -0.80000000000000004), blendType = 'easeOut') self.lineTwoCholorChange = LerpColorScaleInterval(self.lineTwoTransitTextNodePath, FishingGlobals.legendaryTransitionTextDuration, (1.0, 1.0, 1.0, 1.0), (1.0, 1.0, 1.0, 1.0), blendType = 'easeOut') self.lineTwoPosChange = LerpPosInterval(self.lineTwoTransitTextNodePath, FishingGlobals.legendaryTransitionTextDuration, (0.0, 0.0, -0.32000000000000001), (0.0, 0.0, -0.94999999999999996), blendType = 'easeOut') self.transitionTextMovingSequence = Sequence(Func(self.lineOneTransitTextNodePath.show), Func(self.lineTwoTransitTextNodePath.show), Parallel(self.lineOnePosChange, self.lineTwoPosChange, self.lineOneColorChange, self.lineTwoCholorChange), Func(self.lineOneTransitTextNodePath.hide), Func(self.lineTwoTransitTextNodePath.hide), name = self.gameObject.distributedFishingSpot.uniqueName('transitionTextMovingSequence')) self.meterFadeInInterval = Sequence(Func(self.meterFrame.show), LerpColorScaleInterval(self.meterFrame, FishingGlobals.legendaryTransitionTextDuration, colorScale = (1.0, 1.0, 1.0, 1.0), startColorScale = (1.0, 1.0, 1.0, 0.0), blendType = 'easeOut'), name = 'FadeInLegendaryMeter') self.meterFadeOutInterval = Sequence(LerpColorScaleInterval(self.meterFrame, FishingGlobals.legendaryTransitionTextDuration, colorScale = (1.0, 1.0, 1.0, 0.0), startColorScale = (1.0, 1.0, 1.0, 1.0), blendType = 'easeOut'), Func(self.meterFrame.hide), name = 'FadeOutLegendaryMeter') self.rodFadeInInterval = Sequence(Func(self.fishingHandleBaseFrame.show), LerpColorScaleInterval(self.fishingHandleBaseFrame, FishingGlobals.legendaryTransitionTextDuration, colorScale = (1.0, 1.0, 1.0, 1.0), startColorScale = (1.0, 1.0, 1.0, 0.0), blendType = 'easeOut'), name = 'FadeInLegendaryRodInterface') self.rodFadeOutInterval = Sequence(LerpColorScaleInterval(self.fishingHandleBaseFrame, FishingGlobals.legendaryTransitionTextDuration, colorScale = (1.0, 1.0, 1.0, 0.0), startColorScale = (1.0, 1.0, 1.0, 1.0), blendType = 'easeOut'), Func(self.fishingHandleBaseFrame.hide), name = 'FadeOutLegendaryRodInterface') base.loadingScreen.tick() smallScale = self.fishingHandleButton['scale'] bigScale = self.fishingHandleButton['scale'] * 1.2 self.buttonGrowUpInterval = LerpScaleInterval(self.fishingHandleButton, 1.0, bigScale, smallScale) self.luiFightTransitSequence = Sequence(Parallel(Func(self.fishingHandleBaseFrame.show), Func(self.meterFadeOutInterval.start), Func(self.rodFadeInInterval.start), Func(self.buttonGrowUpInterval.start)), Wait(1.0), Func(self.meterFrame.hide), name = self.gameObject.distributedFishingSpot.uniqueName('luiFightTransitSequence')) self.luiReelTransitSequence = Sequence(Parallel(Func(self.fishingHandleBaseFrame.show), Func(self.meterFadeOutInterval.start), Func(self.rodFadeInInterval.start)), Wait(1.0), Func(self.meterFrame.hide), name = self.gameObject.distributedFishingSpot.uniqueName('luiReelTransitSequence')) self.luiStruggleTransitSequence = Sequence(Parallel(Func(self.meterFrame.show), Func(self.resetFishingRod), self.meterFadeInInterval, self.rodFadeOutInterval), Wait(1.0), Func(self.fishingHandleBaseFrame.hide), name = self.gameObject.distributedFishingSpot.uniqueName('luiStruggleTransitSequence')) self.meterFadeOutInterval.start() self.rodFadeOutInterval.start() self.hideAllGUI() base.loadingScreen.endStep('LegendaryGameGUI') def hideAllGUI(self): self.uiBaseNode.reparentTo(hidden) self.leftBaseNode.reparentTo(hidden) def showAllGUI(self): self.uiBaseNode.reparentTo(aspect2d) self.leftBaseNode.reparentTo(base.a2dLeftCenter) def hideGui(self, nameList): for ui in nameList: self.UICompoments[ui].hide() def showGui(self, nameList): for ui in nameList: self.UICompoments[ui].show() def destroy(self): self.arrowImageRotationInterval.pause() self.arrowImageRotationInterval.clearToInitial() self.luiArrowRotatingSequence.pause() self.luiArrowRotatingSequence.clearToInitial() self.luiCloseDialogSequence.pause() self.luiCloseDialogSequence.clearToInitial() totalKey = self.UICompoments.keys() for iKey in totalKey: del self.UICompoments[iKey] self.fishingHandle = None self.fishingHandleButton = None self.fishingRod.removeNode() self.leftBaseNode.removeNode() self.uiBaseNode.removeNode() if self.fishActor: self.fishActor.destroy() self.fishActor = None def handleButtonClicked(self, mouseKey): if self.gameObject.lfgFsm.getCurrentOrNextState() in [ 'CatchIt']: self.gameObject.lfgFsm.request('Transition', 'Struggle') self.gameObject.sfx['legendaryGreen'].play() def setTransitionText(self, state): self.lineOneTransitTextNode.setText(PLocalizer.LegendaryFishingGui[state][0]) self.lineTwoTransitTextNode.setText(PLocalizer.LegendaryFishingGui[state][1]) def resetInterval(self): self.transitionTextMovingSequence.pause() self.transitionTextMovingSequence.clearToInitial() self.lineOneColorChange.pause() self.lineOneColorChange.clearToInitial() self.lineOnePosChange.pause() self.lineOnePosChange.clearToInitial() self.lineTwoCholorChange.pause() self.lineTwoCholorChange.clearToInitial() self.lineTwoPosChange.pause() self.lineTwoPosChange.clearToInitial() self.luiReelTransitSequence.pause() self.luiReelTransitSequence.clearToInitial() self.luiStruggleTransitSequence.pause() self.luiStruggleTransitSequence.clearToInitial() self.luiFightTransitSequence.pause() self.luiFightTransitSequence.clearToInitial() self.buttonGrowUpInterval.pause() self.buttonGrowUpInterval.clearToInitial() self.meterFadeOutInterval.pause() self.meterFadeOutInterval.clearToInitial() self.rodFadeInInterval.pause() self.rodFadeInInterval.clearToInitial() self.meterFadeInInterval.pause() self.meterFadeInInterval.clearToInitial() self.rodFadeOutInterval.pause() self.rodFadeOutInterval.clearToInitial() def fightingTransit(self): self.luiFightTransitSequence.start() def reelTransit(self): self.luiReelTransitSequence.start() def struggleTransit(self): self.luiStruggleTransitSequence.start() def resetFishingRod(self): self.fishingRod.setR(FishingGlobals.fishingRodInitSlope) def showWinImage(self, fish): self.hideGui([ 'meterFrame', 'fishingHandleBaseFrame']) result = fish.myData['name'].split(' ') fileName = str(result[0]).capitalize() imgName = 'pir_t_gui_fsh_render%s' % fileName self.actorAnim['swimIdleOpposite'] = 'models/char/pir_a_gam_fsh_%s_%s.bam' % (fish.myData['model'], 'swimIdleOpposite') self.fishActor = BlendActor('models/char/pir_r_gam_fsh_%s.bam' % fish.myData['model'], self.actorAnim, FishingGlobals.defaultFishBlendTime, FishingGlobals.fishBlendTimeDict) self.fishActor.setPlayRate(fish.myData['speed'] * fish.myData['swimAnimationMultiplier'], 'swimIdleOpposite') self.fishActor.changeAnimationTo('swimIdleOpposite') self.fishActor.reparentTo(self.winImagePanel) self.fishActor.setScale(self.scaleSize[fish.myData['id']]) self.fishActor.setPos(1.7, 0, 1.0) self.fishActor.setHpr(0, 0, 35) self.fishActor.setDepthWrite(True) self.fishActor.setDepthTest(True) self.wholeStoryTextNode.setText(PLocalizer.LegendSelectionGui['wholeStory'][fish.myData['id']]) self.winImagePanel.show() def closeDialogGotNextState(self, object, targetState, ifFadeInAgain): if self.fishActor: self.fishActor.destroy() self.fishActor = None self.luiCloseDialogSequence = Sequence(Func(self.gameObject.distributedFishingSpot.fadeOut), Wait(0.40000000000000002), Func(self.UICompoments[object].hide), Func(self.gameObject.lfgFsm.request, targetState), name = self.gameObject.distributedFishingSpot.uniqueName('luiCloseDialogSequence')) self.luiCloseDialogSequence.start() def updateStruggleTimerText(self, time, percent): self.meterFrame['text'] = str(time) self.meterFrame['text_fg'] = (1.0 - percent, percent, 0.0, 1.0)
def hide(self): self.ignore('CatalogItemPurchaseRequest') self.ignore(localAvatar.uniqueName('moneyChange')) base.setBackgroundColor(ToontownGlobals.DefaultBackgroundColor) NodePath.hide(self) render.show()
class Fish(NodePath): def __init__(self, fishManager, myData, index, trophy=0): NodePath.__init__(self, '%s_%d' % (myData['name'], index)) self.trophy = trophy self.myData = myData if not self.trophy: self.fishManager = fishManager self.index = index self.fsm = FishFSM(self) self.weight = random.randint(self.myData['weightRange'][0], self.myData['weightRange'][1]) else: self.weight = trophy self.adjustedScale = (self.myData['scaleRange'][1] - self.myData['scaleRange'][0]) * (self.weight - self.myData['weightRange'][0]) / (self.myData['weightRange'][1] - self.myData['weightRange'][0]) + self.myData['scaleRange'][0] self.initActor() if not self.trophy: self.initVariables() self.initFishStatusIcon() if FishingGlobals.wantDebugCollisionVisuals: self.initCollisions() self.avoidingFish = False self.biteBubbleEffect = None self.idleBubbleEffect = None self.fightBubbleEffect = None self.behaviorNameToFunction = {'straight': self.performStraightBehavior,'sineStraight': self.performSineStraightBehavior,'erratic': self.performErraticBehavior} self.sineDtAccumulator = 0.0 self.erraticDtAccumulator = 0.0 self.myZ = 0.0 if not self.trophy: self.setLightOff() return def initActor(self): self.animDict = {} for anim in FishingGlobals.fishAnimations: self.animDict[anim] = 'models/char/pir_a_gam_fsh_%s_%s.bam' % (self.myData['model'], anim) self.actor = BlendActor('models/char/pir_r_gam_fsh_%s.bam' % self.myData['model'], self.animDict, FishingGlobals.defaultFishBlendTime, FishingGlobals.fishBlendTimeDict) self.actor.reparentTo(self) self.actor.setScale(self.adjustedScale) self.mouthJoint = self.actor.exposeJoint(None, 'modelRoot', 'hookAttach') self.attractionPoint = NodePath('AttractionPoint') self.attractionPoint.reparentTo(self.mouthJoint) self.attractionPoint.setPos(0.0, 0.0, 0.0) self.actor.setPlayRate(self.myData['speed'] * self.myData['swimAnimationMultiplier'], 'swimIdle') self.actor.setPlayRate(self.myData['speed'] * self.myData['swimAnimationMultiplier'], 'swimIdleOpposite') self.actor.setPlayRate(self.myData['speed'] * self.myData['turnAnimationMultiplier'], 'turn') self.actor.setPlayRate(self.myData['speed'] * self.myData['turnAnimationMultiplier'], 'turnOpposite') if not self.trophy: self.setBin('fishingGame', 10) return def codeReload(self): self.actor.setPlayRate(self.myData['speed'] * self.myData['swimAnimationMultiplier'], 'swimIdle') self.actor.setPlayRate(self.myData['speed'] * self.myData['swimAnimationMultiplier'], 'swimIdleOpposite') self.actor.setPlayRate(self.myData['speed'] * self.myData['turnAnimationMultiplier'], 'turn') self.actor.setPlayRate(self.myData['speed'] * self.myData['turnAnimationMultiplier'], 'turnOpposite') def initFishStatusIcon(self): self.fishStatusIconTextNode = TextNode('fishBitingIcon') self.fishStatusIconNodePath = NodePath(self.fishStatusIconTextNode) self.fishStatusIconNodePath.setPos(0.0, 0.0, self.myData['indicatorHeightOffset']) self.fishStatusIconTextNode.setText('?') self.fishStatusIconTextNode.setTextColor(1.0, 0.0, 0.0, 1.0) self.fishStatusIconNodePath.reparentTo(self.mouthJoint) self.fishStatusIconNodePath.setBillboardPointEye() self.fishStatusIconNodePath.hide() self.fishStatusIconNodePath.setShaderOff() def initVariables(self): self.attractionVisual = None self.collisionVisual = None self.movingRight = True self.turnSpeed = 160.0 self.turnTowardLureInterval = None self.velocity = FishingGlobals.baseFishVelocity * self.myData['speed'] self.accel = FishingGlobals.baseFishAccel * self.myData['speed'] self.fishMoveSequence = None self.bubbleEffect = None return def initCollisions(self): self.collisionVisual = loader.loadModel('models/props/crate') self.collisionVisual.setTransparency(1) self.collisionVisual.setColor(1.0, 1.0, 1.0, 0.3) self.collisionVisual.setScale(*self.myData['collisionBoxSize']) self.collisionVisual.setPos(*self.myData['collisionBoxOffset']) self.collisionVisual.reparentTo(self) self.collisionVisual.hide() self.attractionVisual = loader.loadModel('models/ammunition/cannonball') self.attractionVisual.setTransparency(1) self.attractionVisual.setColor(0.0, 1.0, 0.0, 0.3) self.attractionVisual.setScale(self.myData['attractionRadius']) self.attractionVisual.reparentTo(self.attractionPoint) self.attractionVisual.hide() self.collisionVisualVisible = False def hide(self): NodePath.hide(self) if self.idleBubbleEffect: self.idleBubbleEffect.hide() def show(self): NodePath.show(self) if self.idleBubbleEffect: self.idleBubbleEffect.show() def reloadCollisions(self): if FishingGlobals.wantDebugCollisionVisuals: self.collisionVisual.removeNode() self.attractionVisual.removeNode() self.initCollisions() def cleanFishData(self): pass def destroy(self): self.closeFish = [] self.actor.destroy() self.stopIdleBubbleEffect() self.stopFightBubbleEffect() if self.fishMoveSequence: self.fishMoveSequence.pause() self.fishMoveSequence = None if self.fsm: del self.fsm self.fsm = None self.behaviorNameToFunction = {} self.removeNode() return def pickPositionAndSwim(self): self.initVariables() self.actor.clearControlEffectWeights() if self.myData['depth'] == 0: depth = random.uniform(FishingGlobals.fishingLevelBoundaries[self.myData['depth']], self.fishManager.gameObject.waterLevel + FishingGlobals.fishSpawnBelowWaterLevelHeight) else: depth = random.uniform(FishingGlobals.fishingLevelBoundaries[self.myData['depth']], FishingGlobals.fishingLevelBoundaries[self.myData['depth'] - 1]) startX = random.uniform(FishingGlobals.leftFishBarrier + 5.0, FishingGlobals.rightFishBarrier - 5.0) self.setPos(startX, 0.0, depth) if random.randint(0, 1): self.fsm.request('TurnAround', 'Swimming', False) else: self.fsm.request('Swimming') def turnAround(self, nextState, shouldMoveRight): if self.velocity[0] < 0 and shouldMoveRight: self.velocity[0] = -self.velocity[0] elif self.velocity[0] > 0 and not shouldMoveRight: self.velocity[0] = -self.velocity[0] self.movingRight = self.velocity[0] > 0 if self.fishMoveSequence: self.fishMoveSequence.pause() self.fishMoveSequence.clearToInitial() animationToTurn = 'turn' if self.movingRight: animationToTurn = 'turnOpposite' durationOfFishTurn = self.myData['durationOfFishTurn'] self.fishMoveSequence = Parallel(Sequence(Func(self.actor.changeAnimationTo, animationToTurn, False), Wait(durationOfFishTurn), Func(self.fsm.request, nextState)), Sequence(Wait(durationOfFishTurn * 0.33), Func(self.setXVelocity, 0.0), Wait(durationOfFishTurn * 0.66), Func(self.setXVelocity, self.velocity[0])), name='%s_turnAroundInterval' % self.getName()) self.velocity[0] = -self.velocity[0] self.fishMoveSequence.start() def setXVelocity(self, newVel): self.velocity[0] = newVel def checkForBiting(self): if self.fishManager.activeFish is not None: return if self.fishManager.gameObject.fsm.getCurrentOrNextState() not in ['Fishing', 'Reeling', 'LureStall', 'LegdFishShow']: return inv = localAvatar.getInventory() rodLvl = inv.getItemQuantity(InventoryType.FishingRod) if self.myData['depth'] + 1 > rodLvl: return self.fsm.request('Biting') return def checkForBoxOverlap(self, otherFish): pos = self.getPos(self.fishManager.gameObject.fishingSpot) size = self.myData['collisionBoxSize'] offset = list(self.myData['collisionBoxOffset']) otherPos = otherFish.getPos() otherSize = otherFish.myData['collisionBoxSize'] otherOffset = list(otherFish.myData['collisionBoxOffset']) if pos[0] + size[0] / 2.0 + offset[0] > otherPos[0] - otherSize[0] / 2.0 + otherOffset[0] and pos[0] - size[0] / 2.0 + offset[0] < otherPos[0] + otherSize[0] / 2.0 + otherOffset[0] and pos[2] + size[2] / 2.0 + offset[2] > otherPos[2] - otherSize[2] / 2.0 + otherOffset[2] and pos[2] - size[2] / 2.0 + offset[2] < otherPos[2] + otherSize[2] / 2.0 + otherOffset[2]: return True return False def checkForCloseFish(self, index): if index < len(self.fishManager.uncaughtFish) - 1: for i in range(index + 1, len(self.fishManager.uncaughtFish)): if self.fishManager.uncaughtFish[i].index != self.index: if self.checkForBoxOverlap(self.fishManager.uncaughtFish[i]): self.closeFish.append(self.fishManager.uncaughtFish[i]) if FishingGlobals.wantDebugCollisionVisuals: self.collisionVisual.setColor(1, 0, 0, 0.3) if len(self.closeFish) == 0: if FishingGlobals.wantDebugCollisionVisuals: self.collisionVisual.setColor(1, 1, 1, 0.3) def checkForLures(self, currentState, lurePos): if self.getX() + FishingGlobals.fishAttractionOffset < lurePos[0] and self.movingRight or self.getX() - FishingGlobals.fishAttractionOffset > lurePos[0] and not self.movingRight: if self.attractionPoint.getDistance(self.fishManager.gameObject.lure) < self.myData['attractionRadius'] + self.fishManager.gameObject.lure.lureAttractRadius: self.checkForBiting() def update(self, dt, index, lurePos): currentState = self.fsm.getCurrentOrNextState() self.closeFish = [] if currentState in ['ScareAway', 'Swimming', 'Flee', 'TurnAround']: self.checkForCloseFish(index) if currentState in ['Swimming']: self.checkForLures(currentState, lurePos) self.updateBasedOnBehavior(dt, lurePos) elif currentState in ['Hooked', 'AboutToFight', 'HookedFighting']: self.checkForCloseFish(-1) for fish in self.closeFish: self.makeFishRunFromMe(fish) def makeFishRunFromMe(self, otherFish): if otherFish.fsm.getCurrentOrNextState() == 'Flee' or otherFish.fsm.getCurrentOrNextState() == 'TurnAround': return if otherFish.getX() < self.getX(self.fishManager.gameObject.fishingSpot) and otherFish.movingRight: otherFish.fsm.request('TurnAround', 'Flee', False) elif otherFish.getX() > self.getX(self.fishManager.gameObject.fishingSpot) and not otherFish.movingRight: otherFish.fsm.request('TurnAround', 'Flee', True) else: otherFish.fsm.request('Flee') def updateBasedOnBehavior(self, dt, lurePos): currentState = self.fsm.getCurrentOrNextState() newX = self.getX() newY = self.getY() newZ = self.getZ() for fish in self.closeFish: if self.myData['size'] == 'small' and fish.myData['size'] == 'large': if self.checkForEating(fish): return self.avoidingFish = True if fish.velocity[1] > 0.0 and fish.avoidingFish: self.velocity[1] = -FishingGlobals.fishAvoidYVelocity else: self.velocity[1] = FishingGlobals.fishAvoidYVelocity if abs(fish.getY() - self.getY()) > self.myData['collisionBoxSize'][1] + fish.myData['collisionBoxSize'][1]: self.velocity[1] = 0.0 if len(self.closeFish) == 0 and abs(self.getY()) > FishingGlobals.fishYTolerance: self.avoidingFish = False if self.getY() > 0: self.velocity[1] = -FishingGlobals.fishAvoidYVelocity else: self.velocity[1] = FishingGlobals.fishAvoidYVelocity elif len(self.closeFish) == 0 and abs(self.getY()) < FishingGlobals.fishYTolerance: self.avoidingFish = False self.velocity[1] = 0.0 self.setY(0.0) newY = self.getY() + self.velocity[1] * dt + self.accel[1] * dt * dt if currentState in ['Swimming', 'TurnAround', 'Flee', 'ScareAway']: if currentState == 'ScareAway': newX, newZ = self.performScareAwayBehavior(dt, self.velocity, self.accel) else: if currentState == 'Flee': newX, newZ = self.performFleeBehavior(dt, self.velocity, self.accel) else: newX, newZ = self.behaviorNameToFunction[self.myData['behaviorDict']['name']](dt, self.velocity, self.accel) currentState = self.fsm.getCurrentOrNextState() if newX < FishingGlobals.leftFishBarrier: if currentState == 'ScareAway': if newX < FishingGlobals.leftFishBarrier - FishingGlobals.fullyOffscreenXOffset: self.fsm.request('Offscreen') return elif currentState != 'TurnAround' and not self.movingRight: self.fsm.request('TurnAround', 'Swimming', True) elif newX > FishingGlobals.rightFishBarrier: if currentState != 'TurnAround' and self.movingRight: self.fsm.request('TurnAround', 'Swimming', False) newZ = min(max(FishingGlobals.fishingLevelBoundaries[len(FishingGlobals.fishingLevelBoundaries) - 1], newZ), self.fishManager.gameObject.waterLevel + FishingGlobals.fishSpawnBelowWaterLevelHeight) self.setPos(newX, newY, newZ) def checkForEating(self, fishThatWillEat): if (self.getX() < fishThatWillEat.getX() and not fishThatWillEat.movingRight or self.getX() > fishThatWillEat.getX() and fishThatWillEat.movingRight) and self.fsm.getCurrentOrNextState() == 'Swimming' and fishThatWillEat.fsm.getCurrentOrNextState() == 'Swimming' and random.random() < 1.0: self.fsm.request('BeingEaten', fishThatWillEat) fishThatWillEat.fsm.request('Eating', self.weight) return True return False def startIdleBubbleEffect(self): self.idleBubbleEffect = FishIdleBubbleEffect.getEffect(unlimited=True) if self.idleBubbleEffect: self.idleBubbleEffect.reparentTo(self.mouthJoint) self.idleBubbleEffect.setScale(1.0) self.idleBubbleEffect.setHpr(0, 0, 0) self.idleBubbleEffect.setLifespanBasedOnDepth(self.getPos(render)) self.idleBubbleEffect.setBubbleSizeBasedOnWeight(self.weight) self.idleBubbleEffect.particleDummy.setBin('fishingGame', 5) self.idleBubbleEffect.startLoop() def stopIdleBubbleEffect(self): if self.idleBubbleEffect: self.idleBubbleEffect.stopLoop() self.idleBubbleEffect = None return def startBiteBubbleEffect(self): self.biteBubbleEffect = FishBitingBubbleEffect.getEffect(unlimited=True) if self.biteBubbleEffect: self.biteBubbleEffect.reparentTo(self.mouthJoint) self.biteBubbleEffect.setScale(1.0) self.biteBubbleEffect.setHpr(0, 0, 0) self.biteBubbleEffect.setLifespanBasedOnDepth(self.getPos(render)) self.biteBubbleEffect.setBubbleSizeBasedOnWeight(self.weight) self.biteBubbleEffect.particleDummy.setBin('fishingGame', 5) self.biteBubbleEffect.play() def stopBiteBubbleEffect(self): if self.biteBubbleEffect: self.biteBubbleEffect.stopLoop() self.biteBubbleEffect = None return def startFightBubbleEffect(self): self.fightBubbleEffect = FishFightingHookedBubbleEffect.getEffect(unlimited=True) if self.fightBubbleEffect: self.fightBubbleEffect.reparentTo(self.mouthJoint) self.fightBubbleEffect.setScale(1.0) self.fightBubbleEffect.setHpr(0, 0, 0) self.fightBubbleEffect.setLifespanBasedOnDepth(self.getPos(render)) self.fightBubbleEffect.setBubbleSizeBasedOnWeight(self.weight) self.fightBubbleEffect.particleDummy.setBin('fishingGame', 5) self.fightBubbleEffect.startLoop() def stopFightBubbleEffect(self): if self.fightBubbleEffect: self.fightBubbleEffect.stopLoop() self.fightBubbleEffect = None return def performStraightBehavior(self, dt, velocity, accel): newX = self.getX() + velocity[0] * dt + accel[0] * dt * dt newZ = self.getZ() + velocity[2] * dt + accel[2] * dt * dt return ( newX, newZ) def performSineStraightBehavior(self, dt, velocity, accel): self.sineDtAccumulator += dt newX = self.getX() + velocity[0] * dt + accel[0] * dt * dt newZ = self.myZ + math.sin(self.sineDtAccumulator) * self.myData['behaviorDict']['sineMultiplier'] return ( newX, newZ) def performScareAwayBehavior(self, dt, velocity, accel): newX = self.getX() + velocity[0] * FishingGlobals.scareAwayVelocityMultiplier * dt + accel[0] * dt * dt newZ = self.getZ() + velocity[2] * FishingGlobals.scareAwayVelocityMultiplier * dt + accel[2] * dt * dt return ( newX, newZ) def performFleeBehavior(self, dt, velocity, accel): newX = self.getX() + velocity[0] * FishingGlobals.fleeVelocityMultiplier * dt + accel[0] * dt * dt newZ = self.getZ() + velocity[2] * FishingGlobals.fleeVelocityMultiplier * dt + accel[2] * dt * dt return ( newX, newZ) def performErraticBehavior(self, dt, velocity, accel): self.erraticDtAccumulator += dt self.sineDtAccumulator += dt newX = self.getX() + velocity[0] * dt + accel[0] * dt * dt newZ = self.myZ + math.sin(self.sineDtAccumulator) * self.myData['behaviorDict']['sineMultiplier'] if self.erraticDtAccumulator > self.myData['behaviorDict']['secondsBetweenChanges']: self.erraticDtAccumulator = 0 if random.random() < self.myData['behaviorDict']['chanceOfTurning']: if self.fsm.getCurrentOrNextState() != 'TurnAround': self.fsm.request('TurnAround', 'Swimming', not self.movingRight) return ( newX, newZ) def showAttractionCollisionVisuals(self): if FishingGlobals.wantDebugCollisionVisuals: self.attractionVisual.show() def hideAttractionCollisionVisuals(self): if FishingGlobals.wantDebugCollisionVisuals: self.attractionVisual.hide() def showAvoidanceCollisionVisuals(self): if FishingGlobals.wantDebugCollisionVisuals: self.collisionVisual.show() def hideAvoidanceCollisionVisuals(self): if FishingGlobals.wantDebugCollisionVisuals: self.collisionVisual.hide()
class Waypoint(NodePath): def __init__(self, position, ID = -1): NodePath.__init__(self, "Waypoint " + str(ID)) self.setPos(render, position) self.texture = loader.loadTexture("textures/blue.jpg") self.costToThisNode = 0 self.visited = False self.neighbors = [] self.ID = ID self.previousWaypoint = None torusModel = "models/Torus/Torus.egg" self.torus = loader.loadModel(torusModel) def getNodeID(self): return self.ID def setPreviousWaypoint(self, previousWaypoint): self.previousWaypoint = previousWaypoint def getPreviousWaypoint(self): return self.previousWaypoint def visit(self): self.visited = True def wasVisited(self): return self.visited def setNeighbors(self, neighbors): self.neighbors = neighbors def addNeighbor(self, neighbor): self.neighbors.append(neighbor) def getNeighbors(self): return self.neighbors def setCostToNode(self, cost): self.costToThisNode = cost def getCostToNode(self): return self.costToThisNode def changeToGreen(self): self.texture = loader.loadTexture("textures/green.jpg") self.torus.setTexture(self.texture, 1) def changeToYellow(self): self.texture = loader.loadTexture("textures/yellow.jpg") self.torus.setTexture(self.texture, 1) def changeToBlue(self): self.texture = loader.loadTexture("textures/blue.jpg") self.torus.setTexture(self.texture, 1) def changeToSnowish(self): self.texture = loader.loadTexture("textures/snowish.jpg") self.texture.setMinfilter(Texture.FTLinearMipmapLinear) self.torus.setTexture(self.texture, 1) def draw(self): torus = self.torus torus.setScale(5, 5, 5) torus.setTexture(self.texture, 1) torus.reparentTo(render) torus.setPos(render, self.getPos()) torus.show() self.drawLineToNeighbors() def drawLineToNeighbors(self): ls = LineSegs() ls.setThickness(1.0) for neighbor in self.neighbors: ls.setColor(1,1,1,1) ls.moveTo(self.getPos(render)) ls.drawTo(neighbor.getPos(render)) self.np = NodePath(ls.create("Neighbor Line Segment")) self.np.reparentTo(render) def erase(self): self.torus.hide() self.np.hide()
class HtmlView(DirectObject): notify = DirectNotifyGlobal.directNotify.newCategory('HtmlView') useHalfTexture = base.config.GetBool('news-half-texture', 0) def __init__(self, parent=aspect2d): global GlobalWebcore self.parent = parent self.mx = 0 self.my = 0 self.htmlFile = 'index.html' self.transparency = False if GlobalWebcore: pass else: GlobalWebcore = AwWebCore(AwWebCore.LOGVERBOSE, True, AwWebCore.PFBGRA) GlobalWebcore.setBaseDirectory('.') for errResponse in xrange(400, 600): GlobalWebcore.setCustomResponsePage(errResponse, 'error.html') self.webView = GlobalWebcore.createWebView(WEB_WIDTH, WEB_HEIGHT, self.transparency, False, 70) frameName = '' inGameNewsUrl = self.getInGameNewsUrl() self.imgBuffer = array.array('B') for i in xrange(WEB_WIDTH * WEB_HEIGHT): self.imgBuffer.append(0) self.imgBuffer.append(0) self.imgBuffer.append(0) self.imgBuffer.append(255) if self.useHalfTexture: self.leftBuffer = array.array('B') for i in xrange(WEB_HALF_WIDTH * WEB_HEIGHT): self.leftBuffer.append(0) self.leftBuffer.append(0) self.leftBuffer.append(0) self.leftBuffer.append(255) self.rightBuffer = array.array('B') for i in xrange(WEB_HALF_WIDTH * WEB_HEIGHT): self.rightBuffer.append(0) self.rightBuffer.append(0) self.rightBuffer.append(0) self.rightBuffer.append(255) self.setupTexture() if self.useHalfTexture: self.setupHalfTextures() self.accept('mouse1', self.mouseDown, [AwWebView.LEFTMOUSEBTN]) self.accept('mouse3', self.mouseDown, [AwWebView.RIGHTMOUSEBTN]) self.accept('mouse1-up', self.mouseUp, [AwWebView.LEFTMOUSEBTN]) self.accept('mouse3-up', self.mouseUp, [AwWebView.RIGHTMOUSEBTN]) def getInGameNewsUrl(self): result = base.config.GetString( 'fallback-news-url', 'http://cdn.toontown.disney.go.com/toontown/en/gamenews/') override = base.config.GetString('in-game-news-url', '') if override: self.notify.info( 'got an override url, using %s for in a game news' % override) result = override else: try: launcherUrl = base.launcher.getValue('GAME_IN_GAME_NEWS_URL', '') if launcherUrl: result = launcherUrl self.notify.info( 'got GAME_IN_GAME_NEWS_URL from launcher using %s' % result) else: self.notify.info( 'blank GAME_IN_GAME_NEWS_URL from launcher, using %s' % result) except: self.notify.warning( 'got exception getting GAME_IN_GAME_NEWS_URL from launcher, using %s' % result) return result def setupTexture(self): cm = CardMaker('quadMaker') cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH) htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT) cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0) bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1) bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1) cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1)) card = cm.generate() self.quad = NodePath(card) self.quad.reparentTo(self.parent) self.guiTex = Texture('guiTex') self.guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) self.guiTex.setMinfilter(Texture.FTLinear) self.guiTex.setKeepRamImage(True) self.guiTex.makeRamImage() self.guiTex.setWrapU(Texture.WMRepeat) self.guiTex.setWrapV(Texture.WMRepeat) ts = TextureStage('webTS') self.quad.setTexture(ts, self.guiTex) self.quad.setTexScale(ts, 1.0, -1.0) self.quad.setTransparency(0) self.quad.setTwoSided(True) self.quad.setColor(1.0, 1.0, 1.0, 1.0) self.calcMouseLimits() def setupHalfTextures(self): self.setupLeftTexture() self.setupRightTexture() self.fullPnmImage = PNMImage(WEB_WIDTH, WEB_HEIGHT, 4) self.leftPnmImage = PNMImage(WEB_HALF_WIDTH, WEB_HEIGHT, 4) self.rightPnmImage = PNMImage(WEB_HALF_WIDTH, WEB_HEIGHT, 4) def setupLeftTexture(self): cm = CardMaker('quadMaker') cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0 * aspect * WEB_WIDTH / float(WIN_WIDTH) htmlHeight = 2.0 * float(WEB_HEIGHT) / float(WIN_HEIGHT) cm.setFrame(-htmlWidth / 2.0, 0, -htmlHeight / 2.0, htmlHeight / 2.0) card = cm.generate() self.leftQuad = NodePath(card) self.leftQuad.reparentTo(self.parent) self.leftGuiTex = Texture('guiTex') self.leftGuiTex.setupTexture(Texture.TT2dTexture, WEB_HALF_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) self.leftGuiTex.setKeepRamImage(True) self.leftGuiTex.makeRamImage() self.leftGuiTex.setWrapU(Texture.WMClamp) self.leftGuiTex.setWrapV(Texture.WMClamp) ts = TextureStage('leftWebTS') self.leftQuad.setTexture(ts, self.leftGuiTex) self.leftQuad.setTexScale(ts, 1.0, -1.0) self.leftQuad.setTransparency(0) self.leftQuad.setTwoSided(True) self.leftQuad.setColor(1.0, 1.0, 1.0, 1.0) def setupRightTexture(self): cm = CardMaker('quadMaker') cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0 * aspect * WEB_WIDTH / float(WIN_WIDTH) htmlHeight = 2.0 * float(WEB_HEIGHT) / float(WIN_HEIGHT) cm.setFrame(0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0) card = cm.generate() self.rightQuad = NodePath(card) self.rightQuad.reparentTo(self.parent) self.rightGuiTex = Texture('guiTex') self.rightGuiTex.setupTexture(Texture.TT2dTexture, WEB_HALF_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) self.rightGuiTex.setKeepRamImage(True) self.rightGuiTex.makeRamImage() self.rightGuiTex.setWrapU(Texture.WMClamp) self.rightGuiTex.setWrapV(Texture.WMClamp) ts = TextureStage('rightWebTS') self.rightQuad.setTexture(ts, self.rightGuiTex) self.rightQuad.setTexScale(ts, 1.0, -1.0) self.rightQuad.setTransparency(0) self.rightQuad.setTwoSided(True) self.rightQuad.setColor(1.0, 1.0, 1.0, 1.0) def calcMouseLimits(self): ll = Point3() ur = Point3() self.quad.calcTightBounds(ll, ur) self.notify.debug('ll=%s ur=%s' % (ll, ur)) offset = self.quad.getPos(aspect2d) self.notify.debug('offset = %s ' % offset) ll.setZ(ll.getZ() + offset.getZ()) ur.setZ(ur.getZ() + offset.getZ()) self.notify.debug('new LL=%s, UR=%s' % (ll, ur)) relPointll = self.quad.getRelativePoint(aspect2d, ll) self.notify.debug('relPoint = %s' % relPointll) self.mouseLL = (aspect2d.getScale()[0] * ll[0], aspect2d.getScale()[2] * ll[2]) self.mouseUR = (aspect2d.getScale()[0] * ur[0], aspect2d.getScale()[2] * ur[2]) self.notify.debug('original mouseLL=%s, mouseUR=%s' % (self.mouseLL, self.mouseUR)) def writeTex(self, filename='guiText.png'): self.notify.debug('writing texture') self.guiTex.generateRamMipmapImages() self.guiTex.write(filename) def toggleRotation(self): if self.interval.isPlaying(): self.interval.finish() else: self.interval.loop() def mouseDown(self, button): messenger.send('wakeup') self.webView.injectMouseDown(button) def mouseUp(self, button): self.webView.injectMouseUp(button) def reload(self): pass def zoomIn(self): self.webView.zoomIn() def zoomOut(self): self.webView.zoomOut() def toggleTransparency(self): self.transparency = not self.transparency self.webView.setTransparent(self.transparency) def update(self, task): if base.mouseWatcherNode.hasMouse(): x, y = self._translateRelativeCoordinates( base.mouseWatcherNode.getMouseX(), base.mouseWatcherNode.getMouseY()) if self.mx - x != 0 or self.my - y != 0: self.webView.injectMouseMove(x, y) self.mx, self.my = x, y if self.webView.isDirty(): self.webView.render(self.imgBuffer.buffer_info()[0], WEB_WIDTH * 4, 4) Texture.setTexturesPower2(2) textureBuffer = self.guiTex.modifyRamImage() textureBuffer.setData(self.imgBuffer.tostring()) if self.useHalfTexture: self.guiTex.store(self.fullPnmImage) self.leftPnmImage.copySubImage(self.fullPnmImage, 0, 0, 0, 0, WEB_HALF_WIDTH, WEB_HEIGHT) self.rightPnmImage.copySubImage(self.fullPnmImage, 0, 0, WEB_HALF_WIDTH, 0, WEB_HALF_WIDTH, WEB_HEIGHT) self.leftGuiTex.load(self.leftPnmImage) self.rightGuiTex.load(self.rightPnmImage) self.quad.hide() Texture.setTexturesPower2(1) GlobalWebcore.update() return Task.cont def _translateRelativeCoordinates(self, x, y): sx = int((x - self.mouseLL[0]) / (self.mouseUR[0] - self.mouseLL[0]) * WEB_WIDTH_PIXELS) sy = WEB_HEIGHT_PIXELS - int( (y - self.mouseLL[1]) / (self.mouseUR[1] - self.mouseLL[1]) * WEB_HEIGHT_PIXELS) return (sx, sy) def unload(self): self.ignoreAll() self.webView.destroy() self.webView = None return def onCallback(self, name, args): if name == 'requestFPS': pass def onBeginNavigation(self, url, frameName): pass def onBeginLoading(self, url, frameName, statusCode, mimeType): pass def onFinishLoading(self): self.notify.debug('finished loading') def onReceiveTitle(self, title, frameName): pass def onChangeTooltip(self, tooltip): pass def onChangeCursor(self, cursor): pass def onChangeKeyboardFocus(self, isFocused): pass def onChangeTargetURL(self, url): pass
class AreaMap(Map): def __init__(self, area): Map.__init__(self, 'map-' + area.getName()) self.capturePoints = { } mapNode = area.getMapNode() if mapNode and not mapNode.isEmpty(): geom = mapNode.getChild(0) geom.setScale(mapNode.getScale()) geom.flattenStrong() mapNode.setScale(1) self.worldNode = mapNode self.map = self.worldNode.copyTo(NodePath()) (a, b) = self.map.getTightBounds() diff = b - a h = diff[1] w = diff[0] else: self.worldNode = area self.map = NodePath('no map found') (a, b) = self.worldNode.geom.getTightBounds() diff = b - a h = diff[1] w = diff[0] ratio = h / w if ratio < 0.98999999999999999: normalScale = 2 / w screenScale = 1 else: normalScale = 2 / h screenScale = 0.75 self.map.clearTransform() self.map.show() self.screenNode = NodePath('Minimap-screenNode') self.screenNode.setP(90) self.screenNode.setScale(screenScale * normalScale) self.screenNode.hide() self.map.reparentTo(self.screenNode) self.mapOverlay = self.map.attachNewNode('mapOverlay') self.mapOverlay.wrtReparentTo(self.screenNode) self.radarTransformNode = NodePath('radarTransform') self.radarTransformNode.setScale(self.worldNode.getScale()[0]) self.map.instanceTo(self.radarTransformNode) localAvatar.guiMgr.addMinimap(self) if self.allowOnScreen(): self.addObject(MinimapFootprint(area)) self.shops = set() if self.allowOnScreen(): if area.getUniqueId() not in [ LocationIds.RAVENS_COVE_ISLAND]: for shop in area.getShopNodes(): uid = shop.getTag('Uid') shopType = shop.getTag('ShopType') self.addObject(MinimapShop(uid, shop, shopType)) self.map.findAllMatches('**/=Holiday').stash() if base.cr.newsManager: for holiday in base.cr.newsManager.getHolidayList(): self.handleHolidayStarted(area, HolidayGlobals.getHolidayName(holiday)) self.zoomLevels = area.getZoomLevels() self.accept('landMapRadarAxisChanged', self.setRadarAxis) def destroy(self): self.ignore('landMapRadarAxisChanged') if hasattr(base, 'localAvatar'): localAvatar.guiMgr.removeMinimap(self) for shop in self.shops: self.removeObject(shop) self.shops = set() for holiday in self.capturePoints.keys(): zones = self.capturePoints.pop(holiday, { }) for object in zones.itervalues(): self.removeObject(object) Map.destroy(self) def allowOnScreen(self): return self.map.find('minimap-card').isEmpty() def getZoomLevels(self): return self.zoomLevels def getWorldNode(self): return self.worldNode def getScreenNode(self): return self.screenNode def getOverlayNode(self): return self.mapOverlay def getCapturePoint(self, holidayId, zone): if self.capturePoints.has_key(holidayId): return self.capturePoints[holidayId][zone] def updateTask(self, task): self.update() return task.cont def update(self): for obj in self.objects: obj.updateOnMap(self) def addObject(self, object): Map.addObject(self, object) mapNode = object.getMapNode() mapNode.reparentTo(self.map, sort = object.SORT) object.getOverlayNode().reparentTo(self.mapOverlay, sort = object.SORT) object.addedToMap(self) def removeObject(self, object): Map.removeObject(self, object) object.getMapNode().detachNode() object.getOverlayNode().detachNode() object.removedFromMap(self) def updateRadarTransform(self, av): if self.radarAxis == Options.RadarAxisMap: self.radarTransformNode.setPosHprScale(-av.getPos(self.worldNode), VBase3(0), VBase3(1)) else: holdHpr = av.getHpr() av.setH(camera.getH(render) - self.worldNode.getH(render)) self.radarTransformNode.setTransform(self.worldNode.getTransform(av)) av.setHpr(holdHpr) localAvatar.guiMgr.radarGui.updateDial(self) def getRadarNode(self): return self.radarTransformNode def handleHolidayStarted(self, area, holiday): self.map.findAllMatches('**/=Holiday=%s;+s' % (holiday,)).unstash() for node in area.getCapturePointNodes(holiday): zones = self.capturePoints.setdefault(holiday, { }) zone = int(node.getTag('Zone')) if zone not in zones: object = MinimapCapturePoint(node, holiday, zone) zones[zone] = object self.addObject(object) continue handleHolidayStarted = report(types = [ 'frameCount', 'args'], dConfigParam = 'minimap')(handleHolidayStarted) def handleHolidayEnded(self, area, holiday, override = False): if holiday in InvasionGlobals.INVASION_IDS and not override: taskMgr.doMethodLater(10, self.handleInvasionEnded, 'handleInvasionEnded', extraArgs = [ area, holiday]) else: self.map.findAllMatches('**/=Holiday=%s;+s' % (holiday,)).stash() for object in self.capturePoints.pop(holiday, { }).itervalues(): self.removeObject(object) handleHolidayEnded = report(types = [ 'frameCount', 'args'], dConfigParam = 'minimap')(handleHolidayEnded) def handleInvasionEnded(self, area, holiday): if not localAvatar.guiMgr.invasionScoreboard: self.map.findAllMatches('**/=Holiday=%s;+s' % (holiday,)).stash() for object in self.capturePoints.pop(holiday, { }).itervalues(): self.removeObject(object)
class Entity(DirectObject, object): def __init__(self, model = None): self.prime = None if model != None: self.set_model(model) def get_model(self): return self.prime def set_model(self, model): if model != None: if isinstance(model, PandaNode): self.prime = NodePath(model) elif isinstance(model, NodePath): self.prime = model else: if Filename(model).exists(): self.model = Filename(model).getBasenameWoExtension() path = model else: if isinstance(model, Filename): self.model = model.getBasenameWoExtension() path = model.getFullpath() else: path = APP_PATH + model print "path: ", path if Filename(path).exists(): pass elif Filename(path + ".bam").exists(): path += ".bam" elif Filename(path + ".bam.pz").exists(): path += ".bam.pz" elif Filename(path + ".egg").exists(): path += ".egg" elif Filename(path + ".egg.pz").exists(): path += ".egg.pz" elif Filename(path + ".x").exists(): path += ".x" else: print ":object(error): can't find model", model, "!" # Probably shouldn't exit because of this sys.exit(1) self.model = model self.prime = base.loader.loadModel(path) if self.prime == None: print ":object(error): can't load model", model, "!" # Probably shouldn't exit because of this sys.exit(1) def getX(self): return self.prime.getX(base.render) def getY(self): return self.prime.getY(base.render) def getZ(self): return self.prime.getZ(base.render) def getH(self): return self.prime.getH(base.render) def getP(self): return self.prime.getP(base.render) def getR(self): return self.prime.getR(base.render) def getSx(self): return self.prime.getSx(base.render) def getSy(self): return self.prime.getSy(base.render) def getSz(self): return self.prime.getSz(base.render) def getPos(self): return self.prime.getPos(base.render) def getHpr(self): return self.prime.getHpr(base.render) def getScale(self): return self.prime.getScale(base.render) def getCollideMask(self): return self.prime.getCollideMask() def getTransparency(self): return self.prime.getTransparency() def getTwoSided(self): return self.prime.getTwoSided() def getParent(self): return self.prime.getParent() def setX(self, *v): self.prime.setX(*v) def setY(self, *v): self.prime.setY(*v) def setZ(self, *v): self.prime.setZ(*v) def setH(self, *v): self.prime.setH(*v) def setP(self, *v): self.prime.setP(*v) def setR(self, *v): self.prime.setR(*v) def setSx(self, *v): self.prime.setSx(*v) def setSy(self, *v): self.prime.setSy(*v) def setSz(self, *v): self.prime.setSz(*v) def setPos(self, *v): self.prime.setPos(*v) def setHpr(self, *v): self.prime.setHpr(*v) def setScale(self, *v): self.prime.setScale(*v) def setCollideMask(self, *v): self.prime.setCollideMask(*v) def setTransparency(self, *v): self.prime.setTransparency(*v) def setTwoSided(self, *v): self.prime.setTwoSided(*v) def removeNode(self): self.prime.removeNode() def reparentTo(self, parent): if isinstance(parent, Entity): parent = parent.prime if isinstance(parent, str): if parent.startswith("render/"): parent = parent[7:] tv = parent parent = base.render.find(tv) if parent == NodePath(): parent = base.render.find("**/" + tv) if parent != NodePath() and parent != None: self.prime.reparentTo(parent) def wrtReparentTo(self, parent): if isinstance(parent, Entity): parent = parent.prime if isinstance(parent, str): if parent.startswith("render/"): parent = parent[7:] tv = parent parent = base.render.find(tv) if parent == NodePath(): parent = base.render.find("**/" + tv) if parent != NodePath(): self.prime.reparentTo(parent) def attachTo(self, parent): """This attaches the object to another object/nodepath. The caller object stays at the same place, with the same scale and rotation, but they become relative to the other object/nodepath. This is useful with for example a character that steps onto a moving ship or so.""" if isinstance(parent, Entity): parent = parent.prime if isinstance(parent, str): if(parent.startswith("render/")): parent = parent[7:] tv = parent parent = base.render.find(tv) if(parent == NodePath()): parent = base.render.find("**/" + tv) if(parent != NodePath()): self.prime.setPos(self.prime.getPos(parent)) self.prime.setHpr(self.prime.getHpr(parent)) self.prime.setScale(self.prime.getScale(parent)) self.prime.reparentTo(parent) def hide(self): self.prime.hide() def show(self): self.prime.show() def __del__(self): try: if isinstance(self.prime, NodePath): self.prime.removeNode() except AttributeError: pass def __getstate__(self): return [self.model, self.getX(), self.getY(), self.getZ(), self.getH(), self.getP(), self.getR(), self.getSx(), self.getSy(), self.getSz(), self.getCollideMask().getWord(), self.getTransparency(), self.getTwoSided(), str(self.getParent())] def __setstate__(self, p): if len(p) < 14: print ":object(error): This state is not compatible with this version!" sys.exit(1) self.setModel(p[0]) self.setX(p[1]) self.setY(p[2]) self.setZ(p[3]) self.setH(p[4]) self.setP(p[5]) self.setR(p[6]) self.setSx(p[7]) self.setSy(p[8]) self.setSz(p[9]) self.setCollideMask(BitMask32(p[10])) self.setTransparency(p[11]) self.setTwoSided(p[12]) self.reparentTo(p[13])
class Heightfield(): ''' classdocs ''' def __init__(self, name, heightmap = None, bruteforce = True, blockSize = 32, near = 512, far = 2048): self.geomRoot = None self.collRoot = None self.textures = [] self.updateTask = None self.name = name geomip = GeoMipTerrain("Heightfield:" + name) self.terrainRoot = NodePath("Terrain:" + name) self.geomip = geomip geomRoot = geomip.getRoot() self.geomRoot = geomRoot geomRoot.reparentTo(self.terrainRoot) geomRoot.setPos( -MAPSIZE/2, -MAPSIZE/2, -HEIGHTSCALE/2) geomRoot.setSx(HORIZONTALSCALE) geomRoot.setSy(HORIZONTALSCALE) geomRoot.setSz(HEIGHTSCALE) geomip.setBruteforce(bruteforce) geomip.setBlockSize(blockSize) geomip.setNear(near) geomip.setFar(far) self.collRoot = self.terrainRoot.attachNewNode("blagablaga") if heightmap != None: self.loadHeightmap(heightmap) def genCollTree(self): tempNode = NodePath('tempNode') toOctreefy = self.geomRoot.copyTo(tempNode) toOctreefy.flattenLight() print "begin octreefy" collRoot = nodeOctree.octreefy(toOctreefy) print "end octreefy" tempNode.removeNode() self.collRoot.removeNode() self.collRoot = collRoot collRoot.reparentTo(self.terrainRoot) def getRoot(self): return self.terrainRoot def getGeomRoot(self): return self.GeomRoot def loadHeightmap(self, heightmap): bruteforceChange = False if self.geomip.getBruteforce() == False: bruteforceChange = True self.geomip.setHeightfield(heightmap) #if bruteforce is off, turn it on for collTree generation if bruteforceChange: self.geomip.setBruteforce(True) print "generating heightfield" self.geomip.generate() self.geomip.update() self.genCollTree() if bruteforceChange: self.geomip.setBruteforce(False) self.geomip.generate() self.geomip.update() print "heightfield generated" def addTexture(self, texture, scale = 1.0, name = 'texture'): ts = TextureStage(name) self.textures.append(ts) self.geomRoot.setTexScale(ts, scale, scale) self.geomRoot.setTexture(ts, texture, 1 ) def updateFocalPoint(self, task): posX = base.camera.getX(render) + MAPSIZE/2 posY = base.camera.getY(render) + MAPSIZE/2 self.geomip.setFocalPoint(posX, posY) self.geomip.update() return task.again def enable(self): self.updateTask = taskMgr.doMethodLater(0.1, self.updateFocalPoint, 'update_heightfield') self.collRoot.reparentTo(self.terrainRoot) def disable(self): if self.updateTask != None: taskMgr.remove(self.updateTask) self.updateTask = None self.collRoot.detachNode() def hide(self): self.terrainRoot.hide() self.disable() def show(self): self.terrainRoot.show() self.enable() def world2MapPos( self, worldPos ): result = None posX = (worldPos[0] + MAPSIZE/2.0) / HORIZONTALSCALE posY = (worldPos[1] + MAPSIZE/2.0) / HORIZONTALSCALE result = (posX,posY) return result def getElevation( self, worldPos ): result = None if abs(worldPos[0]) <= MAPSIZE/2.0 and abs(worldPos[1]) <= MAPSIZE/2.0: mapPos = self.world2MapPos(worldPos) mapElevation = self.geomip.getElevation( mapPos[0] , mapPos[1] ) result = (mapElevation * HEIGHTSCALE) - HEIGHTSCALE/2 return result
def hide(self): self.ignore('CatalogItemPurchaseRequest') base.setBackgroundColor(ToontownGlobals.DefaultBackgroundColor) NodePath.hide(self) render.show()
class Waypoint(NodePath): def __init__(self, position, ID=-1): NodePath.__init__(self, "Waypoint " + str(ID)) self.setPos(render, position) self.texture = loader.loadTexture("textures/blue.jpg") self.costToThisNode = 0 self.visited = False self.neighbors = [] self.ID = ID self.previousWaypoint = None torusModel = "models/Torus/Torus.egg" self.torus = loader.loadModel(torusModel) def getNodeID(self): return self.ID def setPreviousWaypoint(self, previousWaypoint): self.previousWaypoint = previousWaypoint def getPreviousWaypoint(self): return self.previousWaypoint def visit(self): self.visited = True def wasVisited(self): return self.visited def setNeighbors(self, neighbors): self.neighbors = neighbors def addNeighbor(self, neighbor): self.neighbors.append(neighbor) def getNeighbors(self): return self.neighbors def setCostToNode(self, cost): self.costToThisNode = cost def getCostToNode(self): return self.costToThisNode def changeToGreen(self): self.texture = loader.loadTexture("textures/green.jpg") self.torus.setTexture(self.texture, 1) def changeToYellow(self): self.texture = loader.loadTexture("textures/yellow.jpg") self.torus.setTexture(self.texture, 1) def changeToBlue(self): self.texture = loader.loadTexture("textures/blue.jpg") self.torus.setTexture(self.texture, 1) def changeToSnowish(self): self.texture = loader.loadTexture("textures/snowish.jpg") self.texture.setMinfilter(Texture.FTLinearMipmapLinear) self.torus.setTexture(self.texture, 1) def draw(self): torus = self.torus torus.setScale(5, 5, 5) torus.setTexture(self.texture, 1) torus.reparentTo(render) torus.setPos(render, self.getPos()) torus.show() self.drawLineToNeighbors() def drawLineToNeighbors(self): ls = LineSegs() ls.setThickness(1.0) for neighbor in self.neighbors: ls.setColor(1, 1, 1, 1) ls.moveTo(self.getPos(render)) ls.drawTo(neighbor.getPos(render)) self.np = NodePath(ls.create("Neighbor Line Segment")) self.np.reparentTo(render) def erase(self): self.torus.hide() self.np.hide()
class RepairGridPiece(DirectButton, FSM.FSM): def __init__(self, name, parent, allWoodSquaresGeom, selectedOutlineGeom, command, location, **kw): optiondefs = () self.defineoptions(kw, optiondefs) DirectButton.__init__(self, parent) self.initialiseoptions(RepairGridPiece) FSM.FSM.__init__(self, 'RepairGridPiece_%sFSM' % name) self.name = name self.allWoodSquaresGeom = allWoodSquaresGeom self.selectedOutlineGeom = selectedOutlineGeom self.command = command self.location = location self._initVars() self._initGUI() self._initIntervals() self.accept(self.guiItem.getEnterEvent(), self.onMouseEnter) self.accept(self.guiItem.getExitEvent(), self.onMouseExit) self.bind(DGG.B1PRESS, self.onMouseDown) self.bind(DGG.B1RELEASE, self.onMouseUp) self.bind(DGG.B2PRESS, self.onMouseUp) self.bind(DGG.B2RELEASE, self.onMouseUp) self.bind(DGG.B3PRESS, self.onMouseUp) self.bind(DGG.B3RELEASE, self.onMouseUp) self.idleGeom = NodePath('idleGeom') self.highlightedGeom = NodePath('highlightedGeom') self.haveMoved = False self.grabPoint = None self.setType(GOAL_NONE) def _initVars(self): self.pieceType = GOAL_NONE self.enabled = True self.isMouseDown = False self.isMouseInButton = False def _initGUI(self): self.selectedOutlineGeom.reparentTo(self) self.selectedOutlineGeom.hide() self.selectedOutlineGeom.setBin('fixed', 38) def _initIntervals(self): self.moveInterval = LerpPosInterval(self, duration = RepairGlobals.Bracing.moveTime, pos = self.getPos(), name = 'RepairGridPiece_%s.moveInterval' % self.name) def destroy(self): taskMgr.remove(self.uniqueName('RepairGridPiece.updateTask')) taskMgr.remove(DGG.B1PRESS) taskMgr.remove(DGG.B1RELEASE) taskMgr.remove(DGG.B2PRESS) taskMgr.remove(DGG.B2RELEASE) taskMgr.remove(DGG.B3PRESS) taskMgr.remove(DGG.B3RELEASE) self.idleGeom.detachNode() self.idleGeom = None self.highlightedGeom.detachNode() self.highlightedGeom = None self.ignore(self.guiItem.getEnterEvent()) self.ignore(self.guiItem.getExitEvent()) self.moveInterval.clearToInitial() del self.moveInterval DirectFrame.destroy(self) self.clearPiece() self.allWoodSquaresGeom.removeNode() del self.allWoodSquaresGeom def setGeomState(self, state): if state == 'idle': self.idleGeom.show() self.highlightedGeom.hide() elif state == 'highlighted': self.highlightedGeom.show() self.idleGeom.hide() def onMouseEnter(self, event): self.isMouseInButton = True if self.isMouseDown: self.setGeomState('idle') else: self.setGeomState('highlighted') def onMouseExit(self, event): self.isMouseInButton = False self.setGeomState('idle') def onMouseDown(self, event): if self.isMouseInButton: self.selectedOutlineGeom.show() self.setGeomState('idle') self.isMouseDown = True self.haveMoved = False screenx = base.mouseWatcherNode.getMouseX() screeny = base.mouseWatcherNode.getMouseY() self.grabPoint = aspect2d.getRelativePoint(render2d, (screenx, 0, screeny)) taskMgr.add(self.updateTask, self.uniqueName('RepairGridPiece.updateTask'), extraArgs = []) def onMouseUp(self, event): if self.isMouseDown: self.isMouseDown = False if not self.haveMoved: self.checkMovePiece(True) self.grabPoint = None if self.isMouseInButton: self.setGeomState('highlighted') else: self.setGeomState('idle') self.selectedOutlineGeom.hide() taskMgr.remove(self.uniqueName('RepairGridPiece.updateTask')) def onMoveButtonPressed(self, dir1, dir2): if not self.moveInterval.isPlaying(): self.haveMoved = True args = self.location[:] args.append((dir1, dir2)) return self.command(*args) def updateTask(self): if not (self.isMouseInButton) and not self.moveInterval.isPlaying(): self.checkMovePiece() return Task.cont def checkMovePiece(self, isPush = False): directions = [ (0, 1), (0, -1), (-1, 0), (1, 0)] if self.grabPoint is None: self.grabPoint = self.getPos(aspect2d) screenx = base.mouseWatcherNode.getMouseX() screeny = base.mouseWatcherNode.getMouseY() cursorPos = aspect2d.getRelativePoint(render2d, (screenx, 0, screeny)) diff = self.grabPoint - cursorPos absX = math.fabs(diff.getX()) absZ = math.fabs(diff.getZ()) moveDirection = None if isPush: threshold = RepairGlobals.Bracing.pushPieceThreshold else: threshold = RepairGlobals.Bracing.movePieceThreshold if absZ > absX and diff.getZ() > 0.0 and absZ > threshold: moveDirection = directions[1] elif absZ > absX and diff.getZ() < 0.0 and absZ > threshold: moveDirection = directions[0] elif absX > absZ and diff.getX() > 0.0 and absX > threshold: moveDirection = directions[2] elif absX > absZ and diff.getX() < 0.0 and absX > threshold: moveDirection = directions[3] if moveDirection: if self.onMoveButtonPressed(*moveDirection) and self.grabPoint is not None: self.grabPoint += VBase3(SPACING * moveDirection[0], 0.0, SPACING * moveDirection[1]) def setType(self, type): self.pieceType = type activeWoodSquareGeom = self.allWoodSquaresGeom.find('**/%s' % GOAL_TO_TEXTURE[type]) self.idleGeom.detachNode() self.idleGeom = None self.highlightedGeom.detachNode() self.highlightedGeom = None self.idleGeom = NodePath('idleGeom') self.highlightedGeom = NodePath('highlightedGeom') self.idleGeom.reparentTo(self) self.highlightedGeom.reparentTo(self) if activeWoodSquareGeom.isEmpty(): self.stash() else: activeWoodSquareGeom.find('**/idle').copyTo(self.idleGeom) activeWoodSquareGeom.find('**/over').copyTo(self.highlightedGeom) self.setGeomState('idle') self.unstash() def setEnabled(self, enabled): self.onMouseUp(None) self.enabled = enabled if not enabled: self['state'] = DGG.DISABLED else: self['state'] = DGG.NORMAL def isGoalPiece(self): if self.pieceType != GOAL_NONE: pass return self.pieceType != GOAL_EMPTY def isEmptyPiece(self): return self.pieceType == GOAL_EMPTY def setGridLocation(self, location, pos): self.location = location self.setPos(pos) def enterIdle(self): self.stash() self.setEnabled(False) def exitIdle(self): self.unstash() def enterBlank(self): self.setType(GOAL_NONE) def exitBlank(self): self.unstash() def enterGoal(self, pieceType): self.setType(pieceType) def exitGoal(self): self.unstash() def enterEmpty(self): self.setEnabled(False) self.setType(GOAL_EMPTY) def exitEmpty(self): self.unstash()
class FishLure(NodePath): def __init__(self, gameObject, type): NodePath.__init__(self, "FishingLure_%s" % type) self.gameObject = gameObject self.type = type self.initLureModel() if FishingGlobals.wantDebugCollisionVisuals: self.initCollision() self.initLureHelpText() self.setLightOff() def initLureModel(self): self.lureModel = NodePath("lure") self.currentLureType = "regular" self.lureAttractRadius = FishingGlobals.lureTypeToAttractRadius[self.currentLureType] self.lureModel = loader.loadModel(FishingGlobals.lureTypeToModel[self.currentLureType]) self.lureModel.setScale(2.0) self.lureModel.reparentTo(self) self.lureModel.setDepthWrite(False) self.lureModel.setDepthTest(True) self.lureModel.setBin("ground", 25) self.mainGui = loader.loadModel("models/gui/gui_main") def initCollision(self): self.lureCollisionVisual = loader.loadModel("models/ammunition/cannonball") self.lureCollisionVisual.setTransparency(1) self.lureCollisionVisual.setColor(0.0, 0.0, 1.0, 0.29999999999999999) self.lureCollisionVisual.setScale(self.lureAttractRadius) self.lureCollisionVisual.reparentTo(self) self.lureCollisionVisual.hide() def initLureHelpText(self): self.helpTextNode = TextNode("fishBitingIcon") self.helpTextNodePath = NodePath(self.helpTextNode) self.helpTextNodePath.setPos(0.0, 0.0, 0.69999999999999996) self.helpTextNode.setText(" ") self.helpTextNode.setAlign(TextNode.ACenter) self.helpTextNode.setFont(PiratesGlobals.getPirateFont()) self.helpTextNode.setTextColor(1.0, 1.0, 1.0, 1.0) self.helpTextNodePath.reparentTo(self) self.helpTextNodePath.setBillboardPointEye() self.helpTextNodePath.setBin("fishingGame", 10) self.helpTextNodePath.hide() def enableLureGlow(self, glowType): self.lureGlow = LureGlow.getEffect() if self.lureGlow: if self.gameObject.fishManager.activeFish is not None: self.lureGlow.reparentTo(self.gameObject.fishManager.activeFish.mouthJoint) else: self.lureGlow.reparentTo(self) self.lureGlow.effectColor = _glowColors[glowType] self.lureGlow.setShaderOff() self.lureGlow.setBin("fishingGame", 5) self.lureGlow.play() def showHelpText(self, textToShow): taskMgr.remove(self.gameObject.distributedFishingSpot.uniqueName("ClearLureText")) if textToShow is None: self.helpTextNode.setText(" ") self.helpTextNodePath.hide() elif self.gameObject.fishManager.activeFish is not None: self.helpTextNodePath.setScale( FishingGlobals.fishSizeToHelpTextScale[self.gameObject.fishManager.activeFish.myData["size"]] ) else: self.helpTextNodePath.setScale(1.0) self.helpTextNode.setText(textToShow) self.helpTextNodePath.show() taskMgr.doMethodLater( FishingGlobals.lureHelpTextDuration, self.showHelpText, name=self.gameObject.distributedFishingSpot.uniqueName("ClearLureText"), extraArgs=[None], ) def setLureType(self, type): self.currentLureType = type if type == None: self.lureModel.hide() self.gameObject.gui.setTackleBoxPulse(True) elif type == "regular": self.gameObject.gui.setTackleBoxPulse(False) self.currentLureType = type self.lureModel.removeNode() self.lureAttractRadius = FishingGlobals.lureTypeToAttractRadius[type] self.lureModel = loader.loadModel(FishingGlobals.lureTypeToModel[type]) self.lureModel.setScale(2.0) self.lureModel.reparentTo(self) self.lureModel.setDepthWrite(False) self.lureModel.setDepthTest(True) self.lureModel.setBin("ground", 25) elif type == "legendary": self.gameObject.gui.setTackleBoxPulse(False) self.currentLureType = type self.lureModel.removeNode() self.lureAttractRadius = FishingGlobals.lureTypeToAttractRadius[type] self.lureModel = loader.loadModel(FishingGlobals.lureTypeToModel[type]) self.lureModel.setScale(2.0) self.lureModel.reparentTo(self) self.lureModel.setDepthWrite(False) self.lureModel.setDepthTest(True) self.lureModel.setBin("ground", 25) def showCollisionVisuals(self): if FishingGlobals.wantDebugCollisionVisuals: self.lureCollisionVisual.show() def hideCollisionVisuals(self): if FishingGlobals.wantDebugCollisionVisuals: self.lureCollisionVisual.hide() def requestPitch(self, fish): offset = fish.getPos() - self.getPos() if fish.getX() < self.getX(): return math.degrees(math.atan2(offset.getZ(), -offset.getX())) else: return math.degrees(math.atan2(-offset.getZ(), offset.getX())) def resetLureModel(self): self.lureModel.reparentTo(self) self.lureModel.show() self.lureModel.setPosHpr(0, 0, 0, 0, 0, 0.0) if self.currentLureType == None: self.lureModel.hide() self.gameObject.gui.setTackleBoxPulse(True) else: self.gameObject.gui.setTackleBoxPulse(False) def destroy(self): self.lureModel.removeNode() self.removeNode()
class HtmlView(DirectObject): notify = DirectNotifyGlobal.directNotify.newCategory('HtmlView') useHalfTexture = config.GetBool('news-half-texture', 0) def __init__(self, parent = aspect2d): global GlobalWebcore self.parent = parent self.mx = 0 self.my = 0 self.htmlFile = 'index.html' self.transparency = False if GlobalWebcore: pass else: GlobalWebcore = AwWebCore(AwWebCore.LOGVERBOSE, True, AwWebCore.PFBGRA) GlobalWebcore.setBaseDirectory('.') for errResponse in xrange(400, 600): GlobalWebcore.setCustomResponsePage(errResponse, 'error.html') self.webView = GlobalWebcore.createWebView(WEB_WIDTH, WEB_HEIGHT, self.transparency, False, 70) frameName = '' inGameNewsUrl = self.getInGameNewsUrl() self.imgBuffer = array.array('B') for i in xrange(WEB_WIDTH * WEB_HEIGHT): self.imgBuffer.append(0) self.imgBuffer.append(0) self.imgBuffer.append(0) self.imgBuffer.append(255) if self.useHalfTexture: self.leftBuffer = array.array('B') for i in xrange(WEB_HALF_WIDTH * WEB_HEIGHT): self.leftBuffer.append(0) self.leftBuffer.append(0) self.leftBuffer.append(0) self.leftBuffer.append(255) self.rightBuffer = array.array('B') for i in xrange(WEB_HALF_WIDTH * WEB_HEIGHT): self.rightBuffer.append(0) self.rightBuffer.append(0) self.rightBuffer.append(0) self.rightBuffer.append(255) self.setupTexture() if self.useHalfTexture: self.setupHalfTextures() self.accept('mouse1', self.mouseDown, [AwWebView.LEFTMOUSEBTN]) self.accept('mouse3', self.mouseDown, [AwWebView.RIGHTMOUSEBTN]) self.accept('mouse1-up', self.mouseUp, [AwWebView.LEFTMOUSEBTN]) self.accept('mouse3-up', self.mouseUp, [AwWebView.RIGHTMOUSEBTN]) def getInGameNewsUrl(self): result = config.GetString('fallback-news-url', 'http://cdn.toontown.disney.go.com/toontown/en/gamenews/') override = config.GetString('in-game-news-url', '') if override: self.notify.info('got an override url, using %s for in a game news' % override) result = override else: try: launcherUrl = base.launcher.getValue('GAME_IN_GAME_NEWS_URL', '') if launcherUrl: result = launcherUrl self.notify.info('got GAME_IN_GAME_NEWS_URL from launcher using %s' % result) else: self.notify.info('blank GAME_IN_GAME_NEWS_URL from launcher, using %s' % result) except: self.notify.warning('got exception getting GAME_IN_GAME_NEWS_URL from launcher, using %s' % result) return result def setupTexture(self): cm = CardMaker('quadMaker') cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH) htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT) cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0) bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1) bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1) cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1)) card = cm.generate() self.quad = NodePath(card) self.quad.reparentTo(self.parent) self.guiTex = Texture('guiTex') self.guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) self.guiTex.setMinfilter(Texture.FTLinear) self.guiTex.setKeepRamImage(True) self.guiTex.makeRamImage() self.guiTex.setWrapU(Texture.WMRepeat) self.guiTex.setWrapV(Texture.WMRepeat) ts = TextureStage('webTS') self.quad.setTexture(ts, self.guiTex) self.quad.setTexScale(ts, 1.0, -1.0) self.quad.setTransparency(0) self.quad.setTwoSided(True) self.quad.setColor(1.0, 1.0, 1.0, 1.0) self.calcMouseLimits() def setupHalfTextures(self): self.setupLeftTexture() self.setupRightTexture() self.fullPnmImage = PNMImage(WEB_WIDTH, WEB_HEIGHT, 4) self.leftPnmImage = PNMImage(WEB_HALF_WIDTH, WEB_HEIGHT, 4) self.rightPnmImage = PNMImage(WEB_HALF_WIDTH, WEB_HEIGHT, 4) def setupLeftTexture(self): cm = CardMaker('quadMaker') cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0 * aspect * WEB_WIDTH / float(WIN_WIDTH) htmlHeight = 2.0 * float(WEB_HEIGHT) / float(WIN_HEIGHT) cm.setFrame(-htmlWidth / 2.0, 0, -htmlHeight / 2.0, htmlHeight / 2.0) card = cm.generate() self.leftQuad = NodePath(card) self.leftQuad.reparentTo(self.parent) self.leftGuiTex = Texture('guiTex') self.leftGuiTex.setupTexture(Texture.TT2dTexture, WEB_HALF_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) self.leftGuiTex.setKeepRamImage(True) self.leftGuiTex.makeRamImage() self.leftGuiTex.setWrapU(Texture.WMClamp) self.leftGuiTex.setWrapV(Texture.WMClamp) ts = TextureStage('leftWebTS') self.leftQuad.setTexture(ts, self.leftGuiTex) self.leftQuad.setTexScale(ts, 1.0, -1.0) self.leftQuad.setTransparency(0) self.leftQuad.setTwoSided(True) self.leftQuad.setColor(1.0, 1.0, 1.0, 1.0) def setupRightTexture(self): cm = CardMaker('quadMaker') cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0 * aspect * WEB_WIDTH / float(WIN_WIDTH) htmlHeight = 2.0 * float(WEB_HEIGHT) / float(WIN_HEIGHT) cm.setFrame(0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0) card = cm.generate() self.rightQuad = NodePath(card) self.rightQuad.reparentTo(self.parent) self.rightGuiTex = Texture('guiTex') self.rightGuiTex.setupTexture(Texture.TT2dTexture, WEB_HALF_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) self.rightGuiTex.setKeepRamImage(True) self.rightGuiTex.makeRamImage() self.rightGuiTex.setWrapU(Texture.WMClamp) self.rightGuiTex.setWrapV(Texture.WMClamp) ts = TextureStage('rightWebTS') self.rightQuad.setTexture(ts, self.rightGuiTex) self.rightQuad.setTexScale(ts, 1.0, -1.0) self.rightQuad.setTransparency(0) self.rightQuad.setTwoSided(True) self.rightQuad.setColor(1.0, 1.0, 1.0, 1.0) def calcMouseLimits(self): ll = Point3() ur = Point3() self.quad.calcTightBounds(ll, ur) self.notify.debug('ll=%s ur=%s' % (ll, ur)) offset = self.quad.getPos(aspect2d) self.notify.debug('offset = %s ' % offset) ll.setZ(ll.getZ() + offset.getZ()) ur.setZ(ur.getZ() + offset.getZ()) self.notify.debug('new LL=%s, UR=%s' % (ll, ur)) relPointll = self.quad.getRelativePoint(aspect2d, ll) self.notify.debug('relPoint = %s' % relPointll) self.mouseLL = (aspect2d.getScale()[0] * ll[0], aspect2d.getScale()[2] * ll[2]) self.mouseUR = (aspect2d.getScale()[0] * ur[0], aspect2d.getScale()[2] * ur[2]) self.notify.debug('original mouseLL=%s, mouseUR=%s' % (self.mouseLL, self.mouseUR)) def writeTex(self, filename = 'guiText.png'): self.notify.debug('writing texture') self.guiTex.generateRamMipmapImages() self.guiTex.write(filename) def toggleRotation(self): if self.interval.isPlaying(): self.interval.finish() else: self.interval.loop() def mouseDown(self, button): messenger.send('wakeup') self.webView.injectMouseDown(button) def mouseUp(self, button): self.webView.injectMouseUp(button) def reload(self): pass def zoomIn(self): self.webView.zoomIn() def zoomOut(self): self.webView.zoomOut() def toggleTransparency(self): self.transparency = not self.transparency self.webView.setTransparent(self.transparency) def update(self, task): if base.mouseWatcherNode.hasMouse(): x, y = self._translateRelativeCoordinates(base.mouseWatcherNode.getMouseX(), base.mouseWatcherNode.getMouseY()) if self.mx - x != 0 or self.my - y != 0: self.webView.injectMouseMove(x, y) self.mx, self.my = x, y if self.webView.isDirty(): self.webView.render(self.imgBuffer.buffer_info()[0], WEB_WIDTH * 4, 4) Texture.setTexturesPower2(2) textureBuffer = self.guiTex.modifyRamImage() textureBuffer.setData(self.imgBuffer.tostring()) if self.useHalfTexture: self.guiTex.store(self.fullPnmImage) self.leftPnmImage.copySubImage(self.fullPnmImage, 0, 0, 0, 0, WEB_HALF_WIDTH, WEB_HEIGHT) self.rightPnmImage.copySubImage(self.fullPnmImage, 0, 0, WEB_HALF_WIDTH, 0, WEB_HALF_WIDTH, WEB_HEIGHT) self.leftGuiTex.load(self.leftPnmImage) self.rightGuiTex.load(self.rightPnmImage) self.quad.hide() Texture.setTexturesPower2(1) GlobalWebcore.update() return Task.cont def _translateRelativeCoordinates(self, x, y): sx = int((x - self.mouseLL[0]) / (self.mouseUR[0] - self.mouseLL[0]) * WEB_WIDTH_PIXELS) sy = WEB_HEIGHT_PIXELS - int((y - self.mouseLL[1]) / (self.mouseUR[1] - self.mouseLL[1]) * WEB_HEIGHT_PIXELS) return (sx, sy) def unload(self): self.ignoreAll() self.webView.destroy() self.webView = None return def onCallback(self, name, args): if name == 'requestFPS': pass def onBeginNavigation(self, url, frameName): pass def onBeginLoading(self, url, frameName, statusCode, mimeType): pass def onFinishLoading(self): self.notify.debug('finished loading') def onReceiveTitle(self, title, frameName): pass def onChangeTooltip(self, tooltip): pass def onChangeCursor(self, cursor): pass def onChangeKeyboardFocus(self, isFocused): pass def onChangeTargetURL(self, url): pass
def hide(self): NodePath.hide(self) if self.idleBubbleEffect: self.idleBubbleEffect.hide()
class RepairGridPiece(DirectButton, FSM.FSM): def __init__(self, name, parent, allWoodSquaresGeom, selectedOutlineGeom, command, location, **kw): optiondefs = () self.defineoptions(kw, optiondefs) DirectButton.__init__(self, parent, **None) self.initialiseoptions(RepairGridPiece) FSM.FSM.__init__(self, 'RepairGridPiece_%sFSM' % name) self.name = name self.allWoodSquaresGeom = allWoodSquaresGeom self.selectedOutlineGeom = selectedOutlineGeom self.command = command self.location = location self._initVars() self._initGUI() self._initIntervals() self.accept(self.guiItem.getEnterEvent(), self.onMouseEnter) self.accept(self.guiItem.getExitEvent(), self.onMouseExit) self.bind(DGG.B1PRESS, self.onMouseDown) self.bind(DGG.B1RELEASE, self.onMouseUp) self.bind(DGG.B2PRESS, self.onMouseUp) self.bind(DGG.B2RELEASE, self.onMouseUp) self.bind(DGG.B3PRESS, self.onMouseUp) self.bind(DGG.B3RELEASE, self.onMouseUp) self.idleGeom = NodePath('idleGeom') self.highlightedGeom = NodePath('highlightedGeom') self.haveMoved = False self.grabPoint = None self.setType(GOAL_NONE) def _initVars(self): self.pieceType = GOAL_NONE self.enabled = True self.isMouseDown = False self.isMouseInButton = False def _initGUI(self): self.selectedOutlineGeom.reparentTo(self) self.selectedOutlineGeom.hide() self.selectedOutlineGeom.setBin('fixed', 38) def _initIntervals(self): self.moveInterval = LerpPosInterval( self, duration=RepairGlobals.Bracing.moveTime, pos=self.getPos(), name='RepairGridPiece_%s.moveInterval' % self.name) def destroy(self): taskMgr.remove(self.uniqueName('RepairGridPiece.updateTask')) taskMgr.remove(DGG.B1PRESS) taskMgr.remove(DGG.B1RELEASE) taskMgr.remove(DGG.B2PRESS) taskMgr.remove(DGG.B2RELEASE) taskMgr.remove(DGG.B3PRESS) taskMgr.remove(DGG.B3RELEASE) self.idleGeom.detachNode() self.idleGeom = None self.highlightedGeom.detachNode() self.highlightedGeom = None self.ignore(self.guiItem.getEnterEvent()) self.ignore(self.guiItem.getExitEvent()) self.moveInterval.clearToInitial() del self.moveInterval DirectFrame.destroy(self) self.clearPiece() self.allWoodSquaresGeom.removeNode() del self.allWoodSquaresGeom def setGeomState(self, state): if state == 'idle': self.idleGeom.show() self.highlightedGeom.hide() elif state == 'highlighted': self.highlightedGeom.show() self.idleGeom.hide() def onMouseEnter(self, event): self.isMouseInButton = True if self.isMouseDown: self.setGeomState('idle') else: self.setGeomState('highlighted') def onMouseExit(self, event): self.isMouseInButton = False self.setGeomState('idle') def onMouseDown(self, event): if self.isMouseInButton: self.selectedOutlineGeom.show() self.setGeomState('idle') self.isMouseDown = True self.haveMoved = False screenx = base.mouseWatcherNode.getMouseX() screeny = base.mouseWatcherNode.getMouseY() self.grabPoint = aspect2d.getRelativePoint(render2d, (screenx, 0, screeny)) taskMgr.add(self.updateTask, self.uniqueName('RepairGridPiece.updateTask'), extraArgs=[]) def onMouseUp(self, event): if self.isMouseDown: self.isMouseDown = False if not self.haveMoved: self.checkMovePiece(True) self.grabPoint = None if self.isMouseInButton: self.setGeomState('highlighted') else: self.setGeomState('idle') self.selectedOutlineGeom.hide() taskMgr.remove(self.uniqueName('RepairGridPiece.updateTask')) def onMoveButtonPressed(self, dir1, dir2): if not self.moveInterval.isPlaying(): self.haveMoved = True args = self.location[:] args.append((dir1, dir2)) return self.command(*args) def updateTask(self): if not (self.isMouseInButton) and not self.moveInterval.isPlaying(): self.checkMovePiece() return Task.cont def checkMovePiece(self, isPush=False): directions = [(0, 1), (0, -1), (-1, 0), (1, 0)] if self.grabPoint is None: self.grabPoint = self.getPos(aspect2d) screenx = base.mouseWatcherNode.getMouseX() screeny = base.mouseWatcherNode.getMouseY() cursorPos = aspect2d.getRelativePoint(render2d, (screenx, 0, screeny)) diff = self.grabPoint - cursorPos absX = math.fabs(diff.getX()) absZ = math.fabs(diff.getZ()) moveDirection = None if isPush: threshold = RepairGlobals.Bracing.pushPieceThreshold else: threshold = RepairGlobals.Bracing.movePieceThreshold if absZ > absX and diff.getZ() > 0.0 and absZ > threshold: moveDirection = directions[1] elif absZ > absX and diff.getZ() < 0.0 and absZ > threshold: moveDirection = directions[0] elif absX > absZ and diff.getX() > 0.0 and absX > threshold: moveDirection = directions[2] elif absX > absZ and diff.getX() < 0.0 and absX > threshold: moveDirection = directions[3] if moveDirection: if self.onMoveButtonPressed( *moveDirection) and self.grabPoint is not None: self.grabPoint += VBase3(SPACING * moveDirection[0], 0.0, SPACING * moveDirection[1]) def setType(self, type): self.pieceType = type activeWoodSquareGeom = self.allWoodSquaresGeom.find( '**/%s' % GOAL_TO_TEXTURE[type]) self.idleGeom.detachNode() self.idleGeom = None self.highlightedGeom.detachNode() self.highlightedGeom = None self.idleGeom = NodePath('idleGeom') self.highlightedGeom = NodePath('highlightedGeom') self.idleGeom.reparentTo(self) self.highlightedGeom.reparentTo(self) if activeWoodSquareGeom.isEmpty(): self.stash() else: activeWoodSquareGeom.find('**/idle').copyTo(self.idleGeom) activeWoodSquareGeom.find('**/over').copyTo(self.highlightedGeom) self.setGeomState('idle') self.unstash() def setEnabled(self, enabled): self.onMouseUp(None) self.enabled = enabled if not enabled: self['state'] = DGG.DISABLED else: self['state'] = DGG.NORMAL def isGoalPiece(self): if self.pieceType != GOAL_NONE: pass return self.pieceType != GOAL_EMPTY def isEmptyPiece(self): return self.pieceType == GOAL_EMPTY def setGridLocation(self, location, pos): self.location = location self.setPos(pos) def enterIdle(self): self.stash() self.setEnabled(False) def exitIdle(self): self.unstash() def enterBlank(self): self.setType(GOAL_NONE) def exitBlank(self): self.unstash() def enterGoal(self, pieceType): self.setType(pieceType) def exitGoal(self): self.unstash() def enterEmpty(self): self.setEnabled(False) self.setType(GOAL_EMPTY) def exitEmpty(self): self.unstash()
def hide(self): self.disable() NodePath.hide(self)
class HtmlView(DirectObject): notify = DirectNotifyGlobal.directNotify.newCategory("HtmlView") useHalfTexture = base.config.GetBool("news-half-texture", 0) def __init__(self, parent=aspect2d): """Properly initialize ourself.""" #AwWebViewListener.AwWebViewListener.__init__(self) self.parent = parent self.mx = 0 self.my = 0 self.htmlFile = "index.html" self.transparency = False # this is important looks weird if it's true global GlobalWebcore if GlobalWebcore: # we get a C++ crash if we construct webcore a second time pass else: GlobalWebcore = AwWebCore(AwWebCore.LOGVERBOSE, True, AwWebCore.PFBGRA) GlobalWebcore.setBaseDirectory('.') for errResponse in xrange(400, 600): GlobalWebcore.setCustomResponsePage(errResponse, "error.html") self.webView = GlobalWebcore.createWebView(WEB_WIDTH, WEB_HEIGHT, self.transparency, False, 70) #self.webView.setListener(self) #self.webView.setCallback("requestFPS"); frameName = '' inGameNewsUrl = self.getInGameNewsUrl() #self.webView.loadURL2(inGameNewsUrl) self.imgBuffer = array.array('B') for i in xrange(WEB_WIDTH * WEB_HEIGHT): self.imgBuffer.append(0) self.imgBuffer.append(0) self.imgBuffer.append(0) self.imgBuffer.append(255) if self.useHalfTexture: self.leftBuffer = array.array('B') for i in xrange(WEB_HALF_WIDTH * WEB_HEIGHT): self.leftBuffer.append(0) self.leftBuffer.append(0) self.leftBuffer.append(0) self.leftBuffer.append(255) self.rightBuffer = array.array('B') for i in xrange(WEB_HALF_WIDTH * WEB_HEIGHT): self.rightBuffer.append(0) self.rightBuffer.append(0) self.rightBuffer.append(0) self.rightBuffer.append(255) self.setupTexture() if self.useHalfTexture: self.setupHalfTextures() #self.interval = LerpHprInterval(self.quad, 2, Vec3(360, 0, 0), Vec3(0, 0, 0)) #self.accept("escape", sys.exit, [0]) #self.accept("w", self.writeTex) self.accept("mouse1", self.mouseDown, [AwWebView.LEFTMOUSEBTN]) self.accept("mouse3", self.mouseDown, [AwWebView.RIGHTMOUSEBTN]) self.accept("mouse1-up", self.mouseUp, [AwWebView.LEFTMOUSEBTN]) self.accept("mouse3-up", self.mouseUp, [AwWebView.RIGHTMOUSEBTN]) #self.accept("f1", self.toggleRotation) #self.accept("f2", self.toggleTransparency) #self.accept("f3", self.reload) #self.accept("f4", self.zoomIn) #self.accept("f5", self.zoomOut) #taskMgr.doMethodLater(1.0, self.update, 'HtmlViewUpdateTask') # we get a problem if a mid-frame hearbeat fires of this task in conjunction with igLoop #taskMgr.add(self.update, 'HtmlViewUpdateTask', priority = 51) #taskMgr.add(self.update, 'HtmlViewUpdateTask') #base.newsFrame = self def getInGameNewsUrl(self): """Get the appropriate URL to use if we are in test, qa, or live.""" # First if all else fails, we hard code the live news url result = base.config.GetString( "fallback-news-url", "http://cdn.toontown.disney.go.com/toontown/en/gamenews/") # next check if we have an override, say they want to url to point to a file in their harddisk override = base.config.GetString("in-game-news-url", "") if override: self.notify.info( "got an override url, using %s for in a game news" % override) result = override else: try: launcherUrl = base.launcher.getValue("GAME_IN_GAME_NEWS_URL", "") if launcherUrl: result = launcherUrl self.notify.info( "got GAME_IN_GAME_NEWS_URL from launcher using %s" % result) else: self.notify.info( "blank GAME_IN_GAME_NEWS_URL from launcher, using %s" % result) except: self.notify.warning( "got exception getting GAME_IN_GAME_NEWS_URL from launcher, using %s" % result) return result def setupTexture(self): cm = CardMaker('quadMaker') cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH) htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT) # the html area will be center aligned and vertically top aligned #cm.setFrame(-htmlWidth/2.0, htmlWidth/2.0, 1.0 - htmlHeight, 1.0) cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0) bottomRightX = (WEB_WIDTH_PIXELS) / float(WEB_WIDTH + 1) bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1) #cm.setUvRange(Point2(0,0), Point2(bottomRightX, bottomRightY)) cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1)) card = cm.generate() self.quad = NodePath(card) self.quad.reparentTo(self.parent) self.guiTex = Texture("guiTex") self.guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) self.guiTex.setMinfilter(Texture.FTLinear) self.guiTex.setKeepRamImage(True) self.guiTex.makeRamImage() self.guiTex.setWrapU(Texture.WMRepeat) self.guiTex.setWrapV(Texture.WMRepeat) ts = TextureStage('webTS') self.quad.setTexture(ts, self.guiTex) self.quad.setTexScale(ts, 1.0, -1.0) self.quad.setTransparency(0) self.quad.setTwoSided(True) self.quad.setColor(1.0, 1.0, 1.0, 1.0) #self.quad.setZ(0.1) # shtickerbook is moved up by 0.1 self.calcMouseLimits() def setupHalfTextures(self): self.setupLeftTexture() self.setupRightTexture() self.fullPnmImage = PNMImage(WEB_WIDTH, WEB_HEIGHT, 4) self.leftPnmImage = PNMImage(WEB_HALF_WIDTH, WEB_HEIGHT, 4) self.rightPnmImage = PNMImage(WEB_HALF_WIDTH, WEB_HEIGHT, 4) def setupLeftTexture(self): cm = CardMaker('quadMaker') cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0 * aspect * WEB_WIDTH / float(WIN_WIDTH) htmlHeight = 2.0 * float(WEB_HEIGHT) / float(WIN_HEIGHT) # the html area will be center aligned and vertically top aligned #cm.setFrame(-htmlWidth/2.0, htmlWidth/2.0, 1.0 - htmlHeight, 1.0) cm.setFrame(-htmlWidth / 2.0, 0, -htmlHeight / 2.0, htmlHeight / 2.0) card = cm.generate() self.leftQuad = NodePath(card) self.leftQuad.reparentTo(self.parent) self.leftGuiTex = Texture("guiTex") self.leftGuiTex.setupTexture(Texture.TT2dTexture, WEB_HALF_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) self.leftGuiTex.setKeepRamImage(True) self.leftGuiTex.makeRamImage() self.leftGuiTex.setWrapU(Texture.WMClamp) self.leftGuiTex.setWrapV(Texture.WMClamp) ts = TextureStage('leftWebTS') self.leftQuad.setTexture(ts, self.leftGuiTex) self.leftQuad.setTexScale(ts, 1.0, -1.0) self.leftQuad.setTransparency(0) self.leftQuad.setTwoSided(True) self.leftQuad.setColor(1.0, 1.0, 1.0, 1.0) #self.quad.setZ(0.1) # shtickerbook is moved up by 0.1 def setupRightTexture(self): cm = CardMaker('quadMaker') cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0 * aspect * WEB_WIDTH / float(WIN_WIDTH) htmlHeight = 2.0 * float(WEB_HEIGHT) / float(WIN_HEIGHT) # the html area will be center aligned and vertically top aligned #cm.setFrame(-htmlWidth/2.0, htmlWidth/2.0, 1.0 - htmlHeight, 1.0) cm.setFrame(0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0) card = cm.generate() self.rightQuad = NodePath(card) self.rightQuad.reparentTo(self.parent) self.rightGuiTex = Texture("guiTex") self.rightGuiTex.setupTexture(Texture.TT2dTexture, WEB_HALF_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) self.rightGuiTex.setKeepRamImage(True) self.rightGuiTex.makeRamImage() self.rightGuiTex.setWrapU(Texture.WMClamp) self.rightGuiTex.setWrapV(Texture.WMClamp) ts = TextureStage('rightWebTS') self.rightQuad.setTexture(ts, self.rightGuiTex) self.rightQuad.setTexScale(ts, 1.0, -1.0) self.rightQuad.setTransparency(0) self.rightQuad.setTwoSided(True) self.rightQuad.setColor(1.0, 1.0, 1.0, 1.0) #self.quad.setZ(0.1) # shtickerbook is moved up by 0.1 def calcMouseLimits(self): ll = Point3() ur = Point3() self.quad.calcTightBounds(ll, ur) self.notify.debug("ll=%s ur=%s" % (ll, ur)) # we need to get our relative position to aspect2d, since shtiker books is shifted offset = self.quad.getPos(aspect2d) self.notify.debug("offset = %s " % offset) ll.setZ(ll.getZ() + offset.getZ()) ur.setZ(ur.getZ() + offset.getZ()) self.notify.debug("new LL=%s, UR=%s" % (ll, ur)) relPointll = self.quad.getRelativePoint(aspect2d, ll) self.notify.debug("relPoint = %s" % relPointll) self.mouseLL = (aspect2d.getScale()[0] * ll[0], aspect2d.getScale()[2] * ll[2]) self.mouseUR = (aspect2d.getScale()[0] * ur[0], aspect2d.getScale()[2] * ur[2]) self.notify.debug("original mouseLL=%s, mouseUR=%s" % (self.mouseLL, self.mouseUR)) def writeTex(self, filename="guiText.png"): self.notify.debug("writing texture") self.guiTex.generateRamMipmapImages() self.guiTex.write(filename) def toggleRotation(self): if self.interval.isPlaying(): self.interval.finish() else: self.interval.loop() def mouseDown(self, button): messenger.send('wakeup') self.webView.injectMouseDown(button) def mouseUp(self, button): self.webView.injectMouseUp(button) def reload(self): pass #self.webView.loadFile(self.htmlFile, '') def zoomIn(self): self.webView.zoomIn() def zoomOut(self): self.webView.zoomOut() def toggleTransparency(self): self.transparency = not self.transparency self.webView.setTransparent(self.transparency) def update(self, task): global GlobalWebcore if base.mouseWatcherNode.hasMouse(): x, y = self._translateRelativeCoordinates( base.mouseWatcherNode.getMouseX(), base.mouseWatcherNode.getMouseY()) #self.notify.debug('got mouse move %d %d' % (x,y)) #self.webView.injectMouseMove(x, y) if (self.mx - x) != 0 or (self.my - y) != 0: self.webView.injectMouseMove(x, y) #self.notify.debug('injecting mouse move %d %d' % (x,y)) self.mx, self.my = x, y if self.webView.isDirty(): #self.notify.debug("webview is dirty") self.webView.render(self.imgBuffer.buffer_info()[0], WEB_WIDTH * 4, 4) #Texture.setTexturesPower2(AutoTextureScale.ATSUp) Texture.setTexturesPower2(2) #self.notify.debug("about to modify ram image") textureBuffer = self.guiTex.modifyRamImage() #import pdb; pdb.set_trace() #self.notify.debug("about to call textureBuffer.setData") textureBuffer.setData(self.imgBuffer.tostring()) #self.notify.debug("done calling setData") if self.useHalfTexture: # TODO check with DRose, this feels inefficient self.guiTex.store(self.fullPnmImage) self.leftPnmImage.copySubImage(self.fullPnmImage, 0, 0, 0, 0, WEB_HALF_WIDTH, WEB_HEIGHT) self.rightPnmImage.copySubImage(self.fullPnmImage, 0, 0, WEB_HALF_WIDTH, 0, WEB_HALF_WIDTH, WEB_HEIGHT) self.leftGuiTex.load(self.leftPnmImage) self.rightGuiTex.load(self.rightPnmImage) self.quad.hide() #Texture.setTexturesPower2(AutoTextureScale.ATSDown) Texture.setTexturesPower2(1) GlobalWebcore.update() return Task.cont def _translateRelativeCoordinates(self, x, y): sx = int((x - self.mouseLL[0]) / (self.mouseUR[0] - self.mouseLL[0]) * WEB_WIDTH_PIXELS) sy = WEB_HEIGHT_PIXELS - int( (y - self.mouseLL[1]) / (self.mouseUR[1] - self.mouseLL[1]) * WEB_HEIGHT_PIXELS) return sx, sy def unload(self): """Clean up everything, especially the awesomium bits.""" self.ignoreAll() self.webView.destroy() self.webView = None #global GlobalWebcore #GlobalWebcore = None pass # --------------------[ WebViewListener implementation ]-------------------------- def onCallback(self, name, args): assert self.notify.debugStateCall(self) if name == "requestFPS": #self.webView.setProperty( "fps", JSValue("%.1f" % (1.0 / globalClock.getDt())) ) #self.webView.executeJavascript("updateFPS()", "") pass def onBeginNavigation(self, url, frameName): assert self.notify.debugStateCall(self) pass def onBeginLoading(self, url, frameName, statusCode, mimeType): assert self.notify.debugStateCall(self) pass def onFinishLoading(self): assert self.notify.debugStateCall(self) self.notify.debug("finished loading") pass def onReceiveTitle(self, title, frameName): assert self.notify.debugStateCall(self) pass def onChangeTooltip(self, tooltip): assert self.notify.debugStateCall(self) pass def onChangeCursor(self, cursor): assert self.notify.debugStateCall(self) pass def onChangeKeyboardFocus(self, isFocused): assert self.notify.debugStateCall(self) pass def onChangeTargetURL(self, url): assert self.notify.debugStateCall(self) pass
class CogdoMazeMapGui(MazeMapGui): def __init__(self, mazeCollTable): MazeMapGui.__init__(self, mazeCollTable, bgColor=Globals.MapGuiBgColor, fgColor=Globals.MapGuiFgColor) self._suit2marker = {} self._initModel() self.setPos(*Globals.MapGuiPos) self.setScale(Globals.MapGuiScale) self.reparentTo(base.a2dBottomRight) def destroy(self): for marker in self._suit2marker.values(): marker.removeNode() del self._suit2marker self._entrance.removeNode() del self._entrance self._exit.removeNode() del self._exit del self._exitOpen del self._exitClosed self._suitMarkerTemplate.removeNode() del self._suitMarkerTemplate self._waterCoolerTemplate.removeNode() del self._waterCoolerTemplate MazeMapGui.destroy(self) def _initModel(self): baseName = '**/tt_t_gui_cmg_miniMap_' cardModel = CogdoUtil.loadMazeModel('miniMap_cards', group='gui') cm = CardMaker('bg') cm.setFrame(-1.1, 1.1, -1.1, 1.1) bg = self.attachNewNode(cm.generate()) bg.setColor(*self._bgColor) bg.setBin('fixed', 0) frame = cardModel.find(baseName + 'frame') frame.reparentTo(self) frame.setScale(2.5) frame.setPos(0.01, 0, -0.01) self._entrance = cardModel.find(baseName + 'entrance') self._entrance.reparentTo(self) self._entrance.setScale(0.35) self._entrance.hide() self._exit = NodePath('exit') self._exit.setScale(0.35) self._exit.reparentTo(self) self._exitOpen = cardModel.find(baseName + 'exitOpen') self._exitOpen.reparentTo(self._exit) self._exitClosed = cardModel.find(baseName + 'exitClosed') self._exitClosed.reparentTo(self._exit) self._suitMarkerTemplate = cardModel.find(baseName + 'cogIcon') self._suitMarkerTemplate.detachNode() self._suitMarkerTemplate.setScale(0.225) self._waterCoolerTemplate = cardModel.find(baseName + 'waterDrop') self._waterCoolerTemplate.detachNode() self._waterCoolerTemplate.setScale(0.225) self._exit.hide() cardModel.removeNode() def addWaterCooler(self, tX, tY): marker = NodePath('WaterCoolerMarker-%i-%i' % (tX, tY)) self._waterCoolerTemplate.copyTo(marker) marker.reparentTo(self.maskedLayer) x, y = self.tile2gui(tX, tY) marker.setPos(*self.gui2pos(x, y)) def addSuit(self, suit): marker = NodePath('SuitMarker-%i' % len(self._suit2marker)) self._suitMarkerTemplate.copyTo(marker) marker.reparentTo(self) self._suit2marker[suit] = marker def removeSuit(self, suit): self._suit2marker[suit].removeNode() del self._suit2marker[suit] def updateSuit(self, suit, tX, tY): x, y = self.tile2gui(tX, tY) self._suit2marker[suit].setPos(*self.gui2pos(x, y)) def showExit(self): self._exit.show() self._exitClosed.hide() def hideExit(self): self._exit.hide() def placeExit(self, tX, tY): x, y = self.tile2gui(tX, tY) self._exit.setPos(*self.gui2pos(x, y)) self._exit.setZ(self._exit, 0.3) def placeEntrance(self, tX, tY): x, y = self.tile2gui(tX, tY) self._entrance.setPos(*self.gui2pos(x, y)) self._entrance.setZ(self._entrance, -0.35) self._entrance.show()
class LegendaryFishingGameGUI: def __init__(self, gameObject=None): base.loadingScreen.beginStep('LegendaryGameGUI', 4, 20) self.gameObject = gameObject self.guiImage = loader.loadModel( 'models/minigames/pir_m_gam_fsh_legendaryGui') self.UICompoments = {} self.uiBaseNode = NodePath('baseNode') self.uiBaseNode.reparentTo(aspect2d) self.uiBaseNode.show() self.leftBaseNode = NodePath('leftBaseNode') self.leftBaseNode.reparentTo(base.a2dLeftCenter) self.leftBaseNode.show() self.fishActor = None self.actorAnim = {} self.scaleSize = { InventoryType.Collection_Set11_Part1: 0.059999999999999998, InventoryType.Collection_Set11_Part2: 0.055, InventoryType.Collection_Set11_Part3: 0.12, InventoryType.Collection_Set11_Part4: 0.086999999999999994, InventoryType.Collection_Set11_Part5: 0.080000000000000002 } self.meterFrame = DirectFrame( parent=self.leftBaseNode, frameSize=(-0.29999999999999999, 0.29999999999999999, -1.0, 0.0), frameColor=(1.0, 1.0, 1.0, 0.0), relief=None, state=DGG.DISABLED, pos=(1.0, 0.0, -0.45000000000000001), hpr=(0, 0, 0), scale=(1.3, 0.0, 1.3), image=self.guiImage.find('**/pir_t_gui_fsh_meter'), image_scale=(0.20000000000000001, 0.0, 0.80000000000000004), image_pos=(0, 0, 0), text='', textMayChange=1, text_scale=PiratesGuiGlobals.TextScaleTitleLarge, text_pos=(-0.55000000000000004, 0.10000000000000001), text_shadow=PiratesGuiGlobals.TextShadow) self.UICompoments['meterFrame'] = self.meterFrame self.fishingRod = DirectFrame( parent=self.meterFrame, frameSize=(-0.29999999999999999, 0.29999999999999999, -1.0, 0.0), relief=None, state=DGG.DISABLED, pos=FishingGlobals.fishingRodScreenPosition, image=self.guiImage.find('**/pir_t_gui_fsh_fullRod'), image_scale=(1.0, 0.0, 0.125), image_pos=(0.20000000000000001, 0, 0)) self.fishingRod.setR(FishingGlobals.fishingRodInitSlope) self.UICompoments['fishingRod'] = self.fishingRod base.loadingScreen.tick() self.fishingHandleBaseFrame = DirectFrame( parent=self.uiBaseNode, frameSize=(-0.29999999999999999, 0.29999999999999999, -1.5, 1.5), frameColor=(1.0, 1.0, 1.0, 0.0), relief=None, state=DGG.DISABLED, pos=(0.0, 0.0, 0.0), hpr=(0, 0, 0), scale=(0.71999999999999997, 0.0, 0.71999999999999997), image=self.guiImage.find('**/pir_t_gui_fsh_partialRod'), image_scale=(3.7999999999999998, 0.0, 1.8999999999999999), image_pos=(0, 0, 0), image_hpr=(0.0, 0.0, 0)) self.fishingHandleBaseFrame.hide() self.UICompoments[ 'fishingHandleBaseFrame'] = self.fishingHandleBaseFrame self.fishingHandle = DirectFrame( parent=self.fishingHandleBaseFrame, frameSize=(-0.080000000000000002, 0.080000000000000002, -0.20000000000000001, 0.20000000000000001), relief=None, state=DGG.DISABLED, pos=(-0.10000000000000001, 0.0, -0.050000000000000003), hpr=(0, 0, 0), image=self.guiImage.find('**/pir_t_gui_fsh_handleArm'), image_scale=(1.0, 0.0, 1.0), image_pos=(-0.042000000000000003, 0, -0.115), image_hpr=(0.0, 0.0, 0)) self.UICompoments['fishingHandle'] = self.fishingHandle self.arrowImage = DirectFrame( parent=self.fishingHandleBaseFrame, frameSize=(-0.40000000000000002, 0.40000000000000002, -0.40000000000000002, 0.40000000000000002), relief=None, state=DGG.DISABLED, pos=(0.0, 0.0, 0.0), hpr=(0, 0, 0), scale=(1.2, 0.0, 1.2), image=self.guiImage.find('**/pir_t_gui_fsh_arrow'), image_scale=(1.0, 0.0, 1.0), image_pos=(0.0, 0, 0.0), image_hpr=(0.0, 0.0, 0.0)) self.arrowImage.hide() self.UICompoments['arrowImage'] = self.arrowImage btnGeom = (self.guiImage.find('**/pir_t_gui_fsh_handle'), self.guiImage.find('**/pir_t_gui_fsh_handle'), self.guiImage.find('**/pir_t_gui_fsh_handleOn')) self.fishingHandleButton = GuiButton(pos=(-0.29999999999999999, 0, -0.55000000000000004), hpr=(0, 0, 0), scale=0.45000000000000001, image=btnGeom, image_pos=(0, 0, 0), image_scale=1.0, sortOrder=2) self.fishingHandleButton.bind(DGG.B1PRESS, self.handleButtonClicked) self.fishingHandleButton.reparentTo(self.fishingHandle) self.UICompoments['fishingHandleButton'] = self.fishingHandleButton self.fishingHandleBaseFrame.setTransparency(TransparencyAttrib.MAlpha) self.meterFrame.setTransparency(TransparencyAttrib.MAlpha) self.lineOneTransitTextNode = TextNode('lineOneTransitText') self.lineOneTransitTextNode.setFont(PiratesGlobals.getPirateFont()) self.lineOneTransitTextNode.setText('') self.lineOneTransitTextNode.setAlign(TextNode.ACenter) self.lineOneTransitTextNode.setTextColor(1.0, 1.0, 1.0, 0.5) self.lineOneTransitTextNodePath = NodePath(self.lineOneTransitTextNode) self.lineOneTransitTextNodePath.setPos(0.0, 0.0, -0.80000000000000004) self.lineOneTransitTextNodePath.setScale(0.34999999999999998, 0.34999999999999998, 0.34999999999999998) self.lineOneTransitTextNodePath.reparentTo(self.uiBaseNode) self.lineOneTransitTextNodePath.hide() self.UICompoments[ 'lineOneTransitText'] = self.lineOneTransitTextNodePath self.lineTwoTransitTextNode = TextNode('lineTwoTransitText') self.lineTwoTransitTextNode.setFont(PiratesGlobals.getPirateFont()) self.lineTwoTransitTextNode.setText('') self.lineTwoTransitTextNode.setAlign(TextNode.ACenter) self.lineTwoTransitTextNode.setTextColor(1.0, 1.0, 1.0, 0.5) self.lineTwoTransitTextNodePath = NodePath(self.lineTwoTransitTextNode) self.lineTwoTransitTextNodePath.setPos(-0.40000000000000002, 0.0, -0.94999999999999996) self.lineTwoTransitTextNodePath.setScale(0.12, 0.12, 0.12) self.lineTwoTransitTextNodePath.reparentTo(self.uiBaseNode) self.lineTwoTransitTextNodePath.hide() self.UICompoments[ 'lineTwoTransitText'] = self.lineTwoTransitTextNodePath base.loadingScreen.tick() self.test_guiImage = loader.loadModel('models/gui/toplevel_gui') self.buttonIcon = ( self.test_guiImage.find('**/treasure_chest_closed'), self.test_guiImage.find('**/treasure_chest_closed'), self.test_guiImage.find('**/treasure_chest_closed_over')) self.winImagePanel = GuiPanel.GuiPanel('', 2.6000000000000001, 1.8999999999999999, True) self.winImagePanel.setPos(-1.3, 0.0, -0.94999999999999996) self.winImagePanel.reparentTo(self.uiBaseNode) self.winImagePanel.background = OnscreenImage( parent=self.winImagePanel, scale=(2.3999999999999999, 0, 1.8), image=self.guiImage.find('**/pir_t_gui_fsh_posterBackground'), hpr=(0, 0, 0), pos=(1.3, 0, 0.94999999999999996)) self.winImagePanel.setBin('gui-popup', -4) self.winTitleTextNode = TextNode('winTitleTextNode') self.winTitleTextNode.setText('Congratulations!') self.winTitleTextNode.setAlign(TextNode.ACenter) self.winTitleTextNode.setFont(PiratesGlobals.getPirateFont()) self.winTitleTextNode.setTextColor(0.23000000000000001, 0.089999999999999997, 0.029999999999999999, 1.0) self.winTitleTextNodePath = NodePath(self.winTitleTextNode) self.winTitleTextNodePath.setPos(1.3500000000000001, 0.0, 1.6699999999999999) self.winTitleTextNodePath.setScale(0.17999999999999999) self.winTitleTextNodePath.reparentTo(self.winImagePanel) self.wholeStoryTextNode = TextNode('storyTextNode') self.wholeStoryTextNode.setText('') self.wholeStoryTextNode.setWordwrap(19.0) self.wholeStoryTextNode.setTextColor(0.23000000000000001, 0.089999999999999997, 0.029999999999999999, 1.0) self.wholeStoryTextNodePath = NodePath(self.wholeStoryTextNode) self.wholeStoryTextNodePath.setPos(0.33000000000000002, 0.0, 1.6399999999999999) self.wholeStoryTextNodePath.setScale(0.050000000000000003) self.wholeStoryTextNodePath.reparentTo(self.winImagePanel) self.winImagePanel.closeButton[ 'command'] = self.closeDialogGotNextState self.winImagePanel.closeButton['extraArgs'] = [ 'winImagePanel', 'FarewellLegendaryFish', False ] self.UICompoments['winImagePanel'] = self.winImagePanel self.winImagePanel.hide() self.luiCloseDialogSequence = Sequence() self.arrowImageRotationInterval = LerpHprInterval( self.arrowImage, 2.2000000000000002, self.arrowImage.getHpr() + Point3(0.0, 0.0, 280.0), self.arrowImage.getHpr()) self.luiArrowRotatingSequence = Sequence( Func(self.showGui, ['arrowImage']), Parallel(Func(self.arrowImageRotationInterval.start), Wait(2.2000000000000002)), Func(self.hideGui, ['arrowImage']), Func(self.arrowImage.setHpr, self.arrowImage.getHpr() + Point3(0.0, 0.0, 5.0)), name=self.gameObject.distributedFishingSpot.uniqueName( 'luiArrowRotatingSequence')) self.lineOneColorChange = LerpColorScaleInterval( self.lineOneTransitTextNodePath, FishingGlobals.legendaryTransitionTextDuration, (1.0, 1.0, 1.0, 0.0), (1.0, 1.0, 1.0, 1.0), blendType='easeOut') self.lineOnePosChange = LerpPosInterval( self.lineOneTransitTextNodePath, FishingGlobals.legendaryTransitionTextDuration, (0.0, 0.0, -0.20000000000000001), (0.0, 0.0, -0.80000000000000004), blendType='easeOut') self.lineTwoCholorChange = LerpColorScaleInterval( self.lineTwoTransitTextNodePath, FishingGlobals.legendaryTransitionTextDuration, (1.0, 1.0, 1.0, 1.0), (1.0, 1.0, 1.0, 1.0), blendType='easeOut') self.lineTwoPosChange = LerpPosInterval( self.lineTwoTransitTextNodePath, FishingGlobals.legendaryTransitionTextDuration, (0.0, 0.0, -0.32000000000000001), (0.0, 0.0, -0.94999999999999996), blendType='easeOut') self.transitionTextMovingSequence = Sequence( Func(self.lineOneTransitTextNodePath.show), Func(self.lineTwoTransitTextNodePath.show), Parallel(self.lineOnePosChange, self.lineTwoPosChange, self.lineOneColorChange, self.lineTwoCholorChange), Func(self.lineOneTransitTextNodePath.hide), Func(self.lineTwoTransitTextNodePath.hide), name=self.gameObject.distributedFishingSpot.uniqueName( 'transitionTextMovingSequence')) self.meterFadeInInterval = Sequence( Func(self.meterFrame.show), LerpColorScaleInterval( self.meterFrame, FishingGlobals.legendaryTransitionTextDuration, colorScale=(1.0, 1.0, 1.0, 1.0), startColorScale=(1.0, 1.0, 1.0, 0.0), blendType='easeOut'), name='FadeInLegendaryMeter') self.meterFadeOutInterval = Sequence(LerpColorScaleInterval( self.meterFrame, FishingGlobals.legendaryTransitionTextDuration, colorScale=(1.0, 1.0, 1.0, 0.0), startColorScale=(1.0, 1.0, 1.0, 1.0), blendType='easeOut'), Func(self.meterFrame.hide), name='FadeOutLegendaryMeter') self.rodFadeInInterval = Sequence( Func(self.fishingHandleBaseFrame.show), LerpColorScaleInterval( self.fishingHandleBaseFrame, FishingGlobals.legendaryTransitionTextDuration, colorScale=(1.0, 1.0, 1.0, 1.0), startColorScale=(1.0, 1.0, 1.0, 0.0), blendType='easeOut'), name='FadeInLegendaryRodInterface') self.rodFadeOutInterval = Sequence( LerpColorScaleInterval( self.fishingHandleBaseFrame, FishingGlobals.legendaryTransitionTextDuration, colorScale=(1.0, 1.0, 1.0, 0.0), startColorScale=(1.0, 1.0, 1.0, 1.0), blendType='easeOut'), Func(self.fishingHandleBaseFrame.hide), name='FadeOutLegendaryRodInterface') base.loadingScreen.tick() smallScale = self.fishingHandleButton['scale'] bigScale = self.fishingHandleButton['scale'] * 1.2 self.buttonGrowUpInterval = LerpScaleInterval(self.fishingHandleButton, 1.0, bigScale, smallScale) self.luiFightTransitSequence = Sequence( Parallel(Func(self.fishingHandleBaseFrame.show), Func(self.meterFadeOutInterval.start), Func(self.rodFadeInInterval.start), Func(self.buttonGrowUpInterval.start)), Wait(1.0), Func(self.meterFrame.hide), name=self.gameObject.distributedFishingSpot.uniqueName( 'luiFightTransitSequence')) self.luiReelTransitSequence = Sequence( Parallel(Func(self.fishingHandleBaseFrame.show), Func(self.meterFadeOutInterval.start), Func(self.rodFadeInInterval.start)), Wait(1.0), Func(self.meterFrame.hide), name=self.gameObject.distributedFishingSpot.uniqueName( 'luiReelTransitSequence')) self.luiStruggleTransitSequence = Sequence( Parallel(Func(self.meterFrame.show), Func(self.resetFishingRod), self.meterFadeInInterval, self.rodFadeOutInterval), Wait(1.0), Func(self.fishingHandleBaseFrame.hide), name=self.gameObject.distributedFishingSpot.uniqueName( 'luiStruggleTransitSequence')) self.meterFadeOutInterval.start() self.rodFadeOutInterval.start() self.hideAllGUI() base.loadingScreen.endStep('LegendaryGameGUI') def hideAllGUI(self): self.uiBaseNode.reparentTo(hidden) self.leftBaseNode.reparentTo(hidden) def showAllGUI(self): self.uiBaseNode.reparentTo(aspect2d) self.leftBaseNode.reparentTo(base.a2dLeftCenter) def hideGui(self, nameList): for ui in nameList: self.UICompoments[ui].hide() def showGui(self, nameList): for ui in nameList: self.UICompoments[ui].show() def destroy(self): self.arrowImageRotationInterval.pause() self.arrowImageRotationInterval.clearToInitial() self.luiArrowRotatingSequence.pause() self.luiArrowRotatingSequence.clearToInitial() self.luiCloseDialogSequence.pause() self.luiCloseDialogSequence.clearToInitial() totalKey = self.UICompoments.keys() for iKey in totalKey: del self.UICompoments[iKey] self.fishingHandle = None self.fishingHandleButton = None self.fishingRod.removeNode() self.leftBaseNode.removeNode() self.uiBaseNode.removeNode() if self.fishActor: self.fishActor.destroy() self.fishActor = None def handleButtonClicked(self, mouseKey): if self.gameObject.lfgFsm.getCurrentOrNextState() in ['CatchIt']: self.gameObject.lfgFsm.request('Transition', 'Struggle') self.gameObject.sfx['legendaryGreen'].play() def setTransitionText(self, state): self.lineOneTransitTextNode.setText( PLocalizer.LegendaryFishingGui[state][0]) self.lineTwoTransitTextNode.setText( PLocalizer.LegendaryFishingGui[state][1]) def resetInterval(self): self.transitionTextMovingSequence.pause() self.transitionTextMovingSequence.clearToInitial() self.lineOneColorChange.pause() self.lineOneColorChange.clearToInitial() self.lineOnePosChange.pause() self.lineOnePosChange.clearToInitial() self.lineTwoCholorChange.pause() self.lineTwoCholorChange.clearToInitial() self.lineTwoPosChange.pause() self.lineTwoPosChange.clearToInitial() self.luiReelTransitSequence.pause() self.luiReelTransitSequence.clearToInitial() self.luiStruggleTransitSequence.pause() self.luiStruggleTransitSequence.clearToInitial() self.luiFightTransitSequence.pause() self.luiFightTransitSequence.clearToInitial() self.buttonGrowUpInterval.pause() self.buttonGrowUpInterval.clearToInitial() self.meterFadeOutInterval.pause() self.meterFadeOutInterval.clearToInitial() self.rodFadeInInterval.pause() self.rodFadeInInterval.clearToInitial() self.meterFadeInInterval.pause() self.meterFadeInInterval.clearToInitial() self.rodFadeOutInterval.pause() self.rodFadeOutInterval.clearToInitial() def fightingTransit(self): self.luiFightTransitSequence.start() def reelTransit(self): self.luiReelTransitSequence.start() def struggleTransit(self): self.luiStruggleTransitSequence.start() def resetFishingRod(self): self.fishingRod.setR(FishingGlobals.fishingRodInitSlope) def showWinImage(self, fish): self.hideGui(['meterFrame', 'fishingHandleBaseFrame']) result = fish.myData['name'].split(' ') fileName = str(result[0]).capitalize() imgName = 'pir_t_gui_fsh_render%s' % fileName self.actorAnim[ 'swimIdleOpposite'] = 'models/char/pir_a_gam_fsh_%s_%s.bam' % ( fish.myData['model'], 'swimIdleOpposite') self.fishActor = BlendActor( 'models/char/pir_r_gam_fsh_%s.bam' % fish.myData['model'], self.actorAnim, FishingGlobals.defaultFishBlendTime, FishingGlobals.fishBlendTimeDict) self.fishActor.setPlayRate( fish.myData['speed'] * fish.myData['swimAnimationMultiplier'], 'swimIdleOpposite') self.fishActor.changeAnimationTo('swimIdleOpposite') self.fishActor.reparentTo(self.winImagePanel) self.fishActor.setScale(self.scaleSize[fish.myData['id']]) self.fishActor.setPos(1.7, 0, 1.0) self.fishActor.setHpr(0, 0, 35) self.fishActor.setDepthWrite(True) self.fishActor.setDepthTest(True) self.wholeStoryTextNode.setText( PLocalizer.LegendSelectionGui['wholeStory'][fish.myData['id']]) self.winImagePanel.show() def closeDialogGotNextState(self, object, targetState, ifFadeInAgain): if self.fishActor: self.fishActor.destroy() self.fishActor = None self.luiCloseDialogSequence = Sequence( Func(self.gameObject.distributedFishingSpot.fadeOut), Wait(0.40000000000000002), Func(self.UICompoments[object].hide), Func(self.gameObject.lfgFsm.request, targetState), name=self.gameObject.distributedFishingSpot.uniqueName( 'luiCloseDialogSequence')) self.luiCloseDialogSequence.start() def updateStruggleTimerText(self, time, percent): self.meterFrame['text'] = str(time) self.meterFrame['text_fg'] = (1.0 - percent, percent, 0.0, 1.0)
def hide(self): self.visible = False NodePath.hide(self)
class CogdoMazeMapGui(MazeMapGui): def __init__(self, mazeCollTable): MazeMapGui.__init__(self, mazeCollTable, bgColor=Globals.MapGuiBgColor, fgColor=Globals.MapGuiFgColor) self._suit2marker = {} self._initModel() self.reparentTo(base.a2dBottomRight) self.setPos(*Globals.MapGuiPos) self.setScale(Globals.MapGuiScale) def destroy(self): for marker in self._suit2marker.values(): marker.removeNode() del self._suit2marker self._entrance.removeNode() del self._entrance self._exit.removeNode() del self._exit del self._exitOpen del self._exitClosed self._suitMarkerTemplate.removeNode() del self._suitMarkerTemplate self._waterCoolerTemplate.removeNode() del self._waterCoolerTemplate MazeMapGui.destroy(self) def _initModel(self): baseName = '**/tt_t_gui_cmg_miniMap_' cardModel = CogdoUtil.loadMazeModel('miniMap_cards', group='gui') cm = CardMaker('bg') cm.setFrame(-1.1, 1.1, -1.1, 1.1) bg = self.attachNewNode(cm.generate()) bg.setColor(*self._bgColor) bg.setBin('fixed', 0) frame = cardModel.find(baseName + 'frame') frame.reparentTo(self) frame.setScale(2.5) frame.setPos(0.01, 0, -0.01) self._entrance = cardModel.find(baseName + 'entrance') self._entrance.reparentTo(self) self._entrance.setScale(0.35) self._entrance.hide() self._exit = NodePath('exit') self._exit.setScale(0.35) self._exit.reparentTo(self) self._exitOpen = cardModel.find(baseName + 'exitOpen') self._exitOpen.reparentTo(self._exit) self._exitClosed = cardModel.find(baseName + 'exitClosed') self._exitClosed.reparentTo(self._exit) self._suitMarkerTemplate = cardModel.find(baseName + 'cogIcon') self._suitMarkerTemplate.detachNode() self._suitMarkerTemplate.setScale(0.225) self._waterCoolerTemplate = cardModel.find(baseName + 'waterDrop') self._waterCoolerTemplate.detachNode() self._waterCoolerTemplate.setScale(0.225) self._exit.hide() cardModel.removeNode() def addWaterCooler(self, tX, tY): marker = NodePath('WaterCoolerMarker-%i-%i' % (tX, tY)) self._waterCoolerTemplate.copyTo(marker) marker.reparentTo(self.maskedLayer) x, y = self.tile2gui(tX, tY) marker.setPos(*self.gui2pos(x, y)) def addSuit(self, suit): marker = NodePath('SuitMarker-%i' % len(self._suit2marker)) self._suitMarkerTemplate.copyTo(marker) marker.reparentTo(self) self._suit2marker[suit] = marker def removeSuit(self, suit): self._suit2marker[suit].removeNode() del self._suit2marker[suit] def updateSuit(self, suit, tX, tY): x, y = self.tile2gui(tX, tY) self._suit2marker[suit].setPos(*self.gui2pos(x, y)) def showExit(self): self._exit.show() self._exitClosed.hide() def hideExit(self): self._exit.hide() def placeExit(self, tX, tY): x, y = self.tile2gui(tX, tY) self._exit.setPos(*self.gui2pos(x, y)) self._exit.setZ(self._exit, 0.3) def placeEntrance(self, tX, tY): x, y = self.tile2gui(tX, tY) self._entrance.setPos(*self.gui2pos(x, y)) self._entrance.setZ(self._entrance, -0.35) self._entrance.show()
class AreaMap(Map): def __init__(self, area): Map.__init__(self, "map-" + area.getName()) self.capturePoints = {} mapNode = area.getMapNode() if mapNode and not mapNode.isEmpty(): geom = mapNode.getChild(0) geom.setScale(mapNode.getScale()) geom.flattenStrong() mapNode.setScale(1) self.worldNode = mapNode self.map = self.worldNode.copyTo(NodePath()) (a, b) = self.map.getTightBounds() diff = b - a h = diff[1] w = diff[0] else: self.worldNode = area self.map = NodePath("no map found") (a, b) = self.worldNode.geom.getTightBounds() diff = b - a h = diff[1] w = diff[0] ratio = h / w if ratio < 0.98999999999999999: normalScale = 2 / w screenScale = 1 else: normalScale = 2 / h screenScale = 0.75 self.map.clearTransform() self.map.show() self.screenNode = NodePath("Minimap-screenNode") self.screenNode.setP(90) self.screenNode.setScale(screenScale * normalScale) self.screenNode.hide() self.map.reparentTo(self.screenNode) self.mapOverlay = self.map.attachNewNode("mapOverlay") self.mapOverlay.wrtReparentTo(self.screenNode) self.radarTransformNode = NodePath("radarTransform") self.radarTransformNode.setScale(self.worldNode.getScale()[0]) self.map.instanceTo(self.radarTransformNode) localAvatar.guiMgr.addMinimap(self) if self.allowOnScreen(): self.addObject(MinimapFootprint(area)) if self.allowOnScreen(): if area.getUniqueId() not in [LocationIds.RAVENS_COVE_ISLAND]: for shop in area.getShopNodes(): uid = shop.getTag("Uid") shopType = shop.getTag("ShopType") self.addObject(MinimapShop(uid, shop, shopType)) self.map.findAllMatches("**/=Holiday").stash() if base.cr.newsManager: for holiday in base.cr.newsManager.getHolidayList(): self.handleHolidayStarted(area, HolidayGlobals.getHolidayName(holiday)) self.zoomLevels = area.getZoomLevels() self.accept("landMapRadarAxisChanged", self.setRadarAxis) def destroy(self): self.ignore("landMapRadarAxisChanged") if hasattr(base, "localAvatar"): localAvatar.guiMgr.removeMinimap(self) for holiday in self.capturePoints.keys(): zones = self.capturePoints.pop(holiday, {}) for object in zones.itervalues(): self.removeObject(object) Map.destroy(self) def allowOnScreen(self): return self.map.find("minimap-card").isEmpty() def getZoomLevels(self): return self.zoomLevels def getWorldNode(self): return self.worldNode def getScreenNode(self): return self.screenNode def getOverlayNode(self): return self.mapOverlay def getCapturePoint(self, holidayId, zone): if self.capturePoints.has_key(holidayId): return self.capturePoints[holidayId][zone] def updateTask(self, task): self.update() return task.cont def update(self): for obj in self.objects: obj.updateOnMap(self) def addObject(self, object): Map.addObject(self, object) mapNode = object.getMapNode() mapNode.reparentTo(self.map, sort=object.SORT) object.getOverlayNode().reparentTo(self.mapOverlay, sort=object.SORT) object.addedToMap(self) def removeObject(self, object): Map.removeObject(self, object) object.getMapNode().detachNode() object.getOverlayNode().detachNode() object.removedFromMap(self) def updateRadarTransform(self, av): if self.radarAxis == Options.RadarAxisMap: self.radarTransformNode.setPosHprScale(-av.getPos(self.worldNode), VBase3(0), VBase3(1)) else: holdHpr = av.getHpr() av.setH(camera.getH(render) - self.worldNode.getH(render)) self.radarTransformNode.setTransform(self.worldNode.getTransform(av)) av.setHpr(holdHpr) localAvatar.guiMgr.radarGui.updateDial(self) def getRadarNode(self): return self.radarTransformNode def handleHolidayStarted(self, area, holiday): self.map.findAllMatches("**/=Holiday=%s;+s" % (holiday,)).unstash() for node in area.getCapturePointNodes(holiday): zones = self.capturePoints.setdefault(holiday, {}) zone = int(node.getTag("Zone")) if zone not in zones: object = MinimapCapturePoint(node, holiday, zone) zones[zone] = object self.addObject(object) continue handleHolidayStarted = report(types=["frameCount", "args"], dConfigParam="minimap")(handleHolidayStarted) def handleHolidayEnded(self, area, holiday, override=False): if holiday in InvasionGlobals.INVASION_IDS and not override: taskMgr.doMethodLater(10, self.handleInvasionEnded, "handleInvasionEnded", extraArgs=[area, holiday]) else: self.map.findAllMatches("**/=Holiday=%s;+s" % (holiday,)).stash() for object in self.capturePoints.pop(holiday, {}).itervalues(): self.removeObject(object) handleHolidayEnded = report(types=["frameCount", "args"], dConfigParam="minimap")(handleHolidayEnded) def handleInvasionEnded(self, area, holiday): if not localAvatar.guiMgr.invasionScoreboard: self.map.findAllMatches("**/=Holiday=%s;+s" % (holiday,)).stash() for object in self.capturePoints.pop(holiday, {}).itervalues(): self.removeObject(object)
class FishLure(NodePath): def __init__(self, gameObject, type): NodePath.__init__(self, 'FishingLure_%s' % type) self.gameObject = gameObject self.type = type self.initLureModel() if FishingGlobals.wantDebugCollisionVisuals: self.initCollision() self.initLureHelpText() self.setLightOff() def initLureModel(self): self.lureModel = NodePath('lure') self.currentLureType = 'regular' self.lureAttractRadius = FishingGlobals.lureTypeToAttractRadius[ self.currentLureType] self.lureModel = loader.loadModel( FishingGlobals.lureTypeToModel[self.currentLureType]) self.lureModel.setScale(2.0) self.lureModel.reparentTo(self) self.lureModel.setDepthWrite(False) self.lureModel.setDepthTest(True) self.lureModel.setBin('ground', 25) self.mainGui = loader.loadModel('models/gui/gui_main') def initCollision(self): self.lureCollisionVisual = loader.loadModel( 'models/ammunition/cannonball') self.lureCollisionVisual.setTransparency(1) self.lureCollisionVisual.setColor(0.0, 0.0, 1.0, 0.29999999999999999) self.lureCollisionVisual.setScale(self.lureAttractRadius) self.lureCollisionVisual.reparentTo(self) self.lureCollisionVisual.hide() def initLureHelpText(self): self.helpTextNode = TextNode('fishBitingIcon') self.helpTextNodePath = NodePath(self.helpTextNode) self.helpTextNodePath.setPos(0.0, 0.0, 0.69999999999999996) self.helpTextNode.setText(' ') self.helpTextNode.setAlign(TextNode.ACenter) self.helpTextNode.setFont(PiratesGlobals.getPirateFont()) self.helpTextNode.setTextColor(1.0, 1.0, 1.0, 1.0) self.helpTextNodePath.reparentTo(self) self.helpTextNodePath.setBillboardPointEye() self.helpTextNodePath.setBin('fishingGame', 10) self.helpTextNodePath.hide() def enableLureGlow(self, glowType): self.lureGlow = LureGlow.getEffect() if self.lureGlow: if self.gameObject.fishManager.activeFish is not None: self.lureGlow.reparentTo( self.gameObject.fishManager.activeFish.mouthJoint) else: self.lureGlow.reparentTo(self) self.lureGlow.effectColor = _glowColors[glowType] self.lureGlow.setShaderOff() self.lureGlow.setBin('fishingGame', 5) self.lureGlow.play() def showHelpText(self, textToShow): taskMgr.remove( self.gameObject.distributedFishingSpot.uniqueName('ClearLureText')) if textToShow is None: self.helpTextNode.setText(' ') self.helpTextNodePath.hide() elif self.gameObject.fishManager.activeFish is not None: self.helpTextNodePath.setScale( FishingGlobals.fishSizeToHelpTextScale[ self.gameObject.fishManager.activeFish.myData['size']]) else: self.helpTextNodePath.setScale(1.0) self.helpTextNode.setText(textToShow) self.helpTextNodePath.show() taskMgr.doMethodLater( FishingGlobals.lureHelpTextDuration, self.showHelpText, name=self.gameObject.distributedFishingSpot.uniqueName( 'ClearLureText'), extraArgs=[None]) def setLureType(self, type): self.currentLureType = type if type == None: self.lureModel.hide() self.gameObject.gui.setTackleBoxPulse(True) elif type == 'regular': self.gameObject.gui.setTackleBoxPulse(False) self.currentLureType = type self.lureModel.removeNode() self.lureAttractRadius = FishingGlobals.lureTypeToAttractRadius[ type] self.lureModel = loader.loadModel( FishingGlobals.lureTypeToModel[type]) self.lureModel.setScale(2.0) self.lureModel.reparentTo(self) self.lureModel.setDepthWrite(False) self.lureModel.setDepthTest(True) self.lureModel.setBin('ground', 25) elif type == 'legendary': self.gameObject.gui.setTackleBoxPulse(False) self.currentLureType = type self.lureModel.removeNode() self.lureAttractRadius = FishingGlobals.lureTypeToAttractRadius[ type] self.lureModel = loader.loadModel( FishingGlobals.lureTypeToModel[type]) self.lureModel.setScale(2.0) self.lureModel.reparentTo(self) self.lureModel.setDepthWrite(False) self.lureModel.setDepthTest(True) self.lureModel.setBin('ground', 25) def showCollisionVisuals(self): if FishingGlobals.wantDebugCollisionVisuals: self.lureCollisionVisual.show() def hideCollisionVisuals(self): if FishingGlobals.wantDebugCollisionVisuals: self.lureCollisionVisual.hide() def requestPitch(self, fish): offset = fish.getPos() - self.getPos() if fish.getX() < self.getX(): return math.degrees(math.atan2(offset.getZ(), -offset.getX())) else: return math.degrees(math.atan2(-offset.getZ(), offset.getX())) def resetLureModel(self): self.lureModel.reparentTo(self) self.lureModel.show() self.lureModel.setPosHpr(0, 0, 0, 0, 0, 0.0) if self.currentLureType == None: self.lureModel.hide() self.gameObject.gui.setTackleBoxPulse(True) else: self.gameObject.gui.setTackleBoxPulse(False) def destroy(self): self.lureModel.removeNode() self.removeNode()