Example #1
0
    def __init__(self, width=1, depth=1, height=1, thickness=1.0, origin=Point3(0, 0, 0)):
        def __Get3dPoint(pt, origin, axis):
            p = Point3(pt.x, pt.y, 0) - origin
            return RotatePoint3(p, Vec3(0, 0, 1), axis)

        # Create line segments
        self.ls = LineSegs()
        self.ls.setThickness(thickness)

        # axes = [Vec3(1, 0, 0), Vec3(0, 1, 0), Vec3(0, 0, 1), Vec3(1, 0, 0), Vec3(0, 1, 0), Vec3(0, 0, 1)]
        # origins = [origin, origin, origin, origin + Point3(0, 0, -1), origin + Point3(0, 0, -1), origin + Point3(0, 0, 1)]
        axes = [Vec3(1, 0, 0), Vec3(0, 1, 0), Vec3(-1, 0, 0), Vec3(0, -1, 0)]
        origins = [origin, origin, origin, origin]
        for m in range(len(axes)):

            # Get the points for square, append the first one to the end to
            # complete the square
            pts = GetPointsForSquare2(width, height)
            pts.append(pts[0])
            for i in range(len(pts) - 1):

                # Get the distance a third of the way along the edge
                dist = (pts[i + 1] - pts[i]) / 3

                # Draw one square
                self.ls.moveTo(__Get3dPoint(pts[i], origins[m], axes[m]))
                self.ls.drawTo(__Get3dPoint(pts[i] + dist, origins[m], axes[m]))
                self.ls.moveTo(__Get3dPoint(pts[i] + dist + dist, origins[m], axes[m]))
                self.ls.drawTo(__Get3dPoint(pts[i + 1], origins[m], axes[m]))

        # Init the node path, wrapping the lines
        node = self.ls.create()
        NodePath.__init__(self, node)
 def __init__(self, moveTrack, tOffset, posScale = 1.0):
     NodePath.__init__(self)
     self.assign(hidden.attachNewNode(base.localAvatar.uniqueName('ring')))
     self.setMoveTrack(moveTrack)
     self.setTOffset(tOffset)
     self.setPosScale(posScale)
     self.setT(0.0)
Example #3
0
	def abandon(self):# and all descendents
		c = NodePath(self).find('-PandaNode')
		if c:
			for child in c.getChildren():
				child.node().getPythonTag('extras').abandon() # abandon descendents
		#print 'abandoning-- ', self
		self.setPythonTag("extras", 'done') # abandon self
Example #4
0
    def __init__(self, phone, doneEvent=None):
        NodePath.__init__(self, aspect2d.attachNewNode('CatalogGUI'))
        DirectObject.__init__(self)

        CatalogGlobals.CatalogNodePath.find('**/CATALOG_GUI_BKGD').copyTo(self)
        self.setScale(CatalogGlobals.CatalogBKGDScale)

        self.phone = phone
        self.doneEvent = doneEvent

        self.arrowButtons = {}
        self.createArrowButtons()

        self.currentTab = None
        self.tabButtons = {}
        self.createTabButtons()

        self.radioButtons = []
        # self.createRadioButtons()

        self.activePage = 0
        self.gifting = -1

        guiItems = loader.loadModel('phase_5.5/models/gui/catalog_gui')
        hangupGui = guiItems.find('**/hangup')
        hangupRolloverGui = guiItems.find('**/hangup_rollover')
        self.hangup = DirectButton(self, relief=None, pos=(2.28, 0, -1.3),
                                   image=[hangupGui, hangupRolloverGui, hangupRolloverGui, hangupGui],
                                   text=['', TTLocalizer.CatalogHangUp, TTLocalizer.CatalogHangUp],
                                   text_fg=Vec4(1), text_scale=0.07, text_pos=(0.0, 0.14),
                                   command=self.hangUp)
        guiItems.removeNode()
 def __init__(self, game, id, x, y):
     NodePath.__init__(self, 'dropNode%s' % id)
     self.game = game
     self.id = id
     self.reparentTo(hidden)
     self.setPos(x, y, 0)
     shadow = loader.loadModel('phase_3/models/props/square_drop_shadow')
     shadow.setZ(0.2)
     shadow.setBin('ground', 10)
     shadow.setColor(1, 1, 1, 1)
     shadow.reparentTo(self)
     self.shadow = shadow
     drop = CogdoUtil.loadMazeModel('cabinetSmFalling')
     roll = random.randint(-15, 15)
     drop.setHpr(0, 0, roll)
     drop.setZ(Globals.DropHeight)
     self.collTube = CollisionTube(0, 0, 0, 0, 0, 4, Globals.DropCollisionRadius)
     self.collTube.setTangible(0)
     name = Globals.DropCollisionName
     self.collNode = CollisionNode(name)
     self.collNode.addSolid(self.collTube)
     self.collNodePath = drop.attachNewNode(self.collNode)
     self.collNodePath.hide()
     self.collNodePath.setTag('isFalling', str('True'))
     drop.reparentTo(self)
     self.drop = drop
     self._dropSfx = base.cogdoGameAudioMgr.createSfxIval('drop', volume=0.6)
Example #6
0
class BigWall(StaticObject):

    def __init__(self, game, width=200.0, thickness=4.0, height=10):
        self.game = game
        self.collGeom = OdeBoxGeom( self.game.physicsSpace, width, thickness, height)

        #self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(0x000000ff) )#ffffffff) )
        self.collGeom.setCollideBits( BitMask32(0x000000ff) )
        
        
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        
        model = loader.loadModel('BigWall.egg')
        model.setScale(width/50.0, thickness/4.0, height)
        model.reparentTo(self.visualNode)
        model.setZ(266)
#        tex = loader.loadTexture('seina.jpg')
#        model.setTexture(tex, 1)
        
        
    def osuminen(self, ship1):
         if OdeUtil.collide(ship1.collGeom, self.collGeom):
 
            print "sdfgfdhgdfhxfhdhghcfh"
            print "ship1 xdfhgxdgxdgfbcdll!!"
Example #7
0
def onEnter(menuRootID, itm, pos):
	taskMgr.remove(menuRootID+'leaver') # preempt possible pending onLeave()'s
	me = itm.getPythonTag("extras")
	me.menuRoot.clickBlock = True
	sibList=itm.getParent(0)
	for x in range(sibList.getNumChildren()):# hide sibling's kids
			bro = sibList.getChild(x)
			NodePath(bro).setBin("fixed", 11) 
			kind = bro.getPythonTag("extras").item['kind']
			if kind in ('parent', 'vertical', 'horizontal', 'titleBar', 'close') and bro.getNumChildren()>0:
				NodePath(bro.getChild(0)).hide()
			if bro.getState()!=DORMANT: bro.setState(SUBDUED)
	if itm.getState()!=DORMANT:
			itm.setState(HOVER)
			NodePath(itm).setBin("fixed", 50) 
			if itm.getNumChildren(): # show children
				cdrn=itm.getChild(0)
				np = NodePath(cdrn)
				np.show()
				for x in range(cdrn.getNumChildren()): #show HOVERed's children
						c=cdrn.getChild(x)
						ckind = c.getPythonTag("extras").item['kind']
						if ckind =='parent': # but not their children
							NodePath(c.getChild(0)).hide()
						if c.getState()!=DORMANT: c.setState(READY)    
	while sibList.getName() != 'root': #Hilite ancestors
			p=sibList.getParent(0)
			NodePath(p).show()
			p.setState(HOVER)    
			sibList=p.getParent(0)
Example #8
0
File: fpsTest.py Project: croza/RR2
    def __init__(self, parserClass, mainClass, mapLoaderClass, modelLoaderClass):
        self.switchState = False

        # self.t = Timer()

        self.keyMap = {"left": 0, "right": 0, "forward": 0, "backward": 0}
        self.ralph = Actor(
            "data/models/units/ralph/ralph",
            {"run": "data/models/units/ralph/ralph-run", "walk": "data/models/units/ralph/ralph-walk"},
        )
        self.ralph.reparentTo(render)
        # 		self.ralph.setPos(42, 30, 0)
        self.ralph.setPos(6, 10, 0)
        self.ralph.setScale(0.1)

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("arrow_down", self.setKey, ["backward", 1])
        self.accept("arrow_down-up", self.setKey, ["backward", 0])

        self.isMoving = False

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 1000)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode("ralphRay")
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)
        # self.ralphGroundCol.show()

        base.cam.reparentTo(self.ralph)
        base.cam.setPos(0, 9, 7)
        self.floater2 = NodePath(PandaNode("floater2"))
        self.floater2.reparentTo(self.ralph)
        self.floater2.setZ(self.floater2.getZ() + 6)
        base.cam.lookAt(self.floater2)

        # Uncomment this line to see the collision rays
        # 		self.ralphGroundColNp.show()
        # 		self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        # 		self.cTrav.showCollisions(render)

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        taskMgr.add(self.move, "movingTask", extraArgs=[mainClass, parserClass, mapLoaderClass, modelLoaderClass])
Example #9
0
 def loaderPhaseChecker(self, path, loaderOptions):
     if 'audio/' in path:
         return 1
     file = Filename(path)
     if not file.getExtension():
         file.setExtension('bam')
     mp = getModelPath()
     path = mp.findFile(file).cStr()
     if not path:
         return
     match = re.match('.*phase_([^/]+)/', path)
     if not match:
         if 'dmodels' in path:
             return
         else:
             self.errorAccumulatorBuffer += 'file not in phase (%s, %s)\n' % (file, path)
             return
     basePhase = float(match.groups()[0])
     if not launcher.getPhaseComplete(basePhase):
         self.errorAccumulatorBuffer += 'phase is not loaded for this model %s\n' % path
     model = loader.loader.loadSync(Filename(path), loaderOptions)
     if model:
         model = NodePath(model)
         for tex in model.findAllTextures():
             texPath = tex.getFullpath().cStr()
             match = re.match('.*phase_([^/]+)/', texPath)
             if match:
                 texPhase = float(match.groups()[0])
                 if texPhase > basePhase:
                     self.errorAccumulatorBuffer += 'texture phase is higher than the models (%s, %s)\n' % (path, texPath)
Example #10
0
    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()
Example #11
0
    def map_populate(self,task):
        self.init_collisions()
        for p in range(len(self.provinces)):
            city = loader.loadModel("models/house2.x")
            city.reparentTo(render)
            city.setName(self.provinces[p+1][0])
            city.setScale(2, 2, 2)
            x = float(self.provinces[p+1][2]*self.map_scale)-(self.map_width/2)
            y = self.map_height-float(self.provinces[p+1][3]*self.map_scale)-(self.map_height/2)
            city.setPos(x, y, 1.0)
            city_col = city.attachNewNode(CollisionNode("CityCNode%d"%p))
            city_col.setScale((3,3,3))
            city_col.node().addSolid(CollisionSphere(0,0,0,1))
            city_col.setTag("prov","city")
            city.setTag("id",str(p+1))
        for p in range(len(self.paths)):
            path_split = string.replace(self.paths[p],"-"," ")
            path_split = string.split(path_split)
            prov_a = int(path_split[0])
            prov_b = int(path_split[1])
            line = LineSegs()
            line.setColor(1, 0, 0, 1)
            line.setThickness(5)
            line.moveTo(self.provinces[prov_a][2]-600, -(self.provinces[prov_a][3])+350, 2)
            line.drawTo(self.provinces[prov_b][2]-600, -(self.provinces[prov_b][3])+350, 2)

            node = line.create()
            node_path = NodePath(node)
            node_path.reparentTo(render)
            print "line drawn",self.provinces[prov_a][2],self.provinces[prov_a][3]
        for a in range(len(self.armies)):
            self.army_create(a+1,self.armies[a+1][2])

        self.load_state = "Done!"
        task.done
Example #12
0
    def __init__(self, width=1, depth=1, height=1, origin=Point3(0, 0, 0)):

        # Create vetex data format
        gvf = GeomVertexFormat.getV3n3()
        gvd = GeomVertexData("vertexData", gvf, Geom.UHStatic)

        # Create vetex writers for each type of data we are going to store
        gvwV = GeomVertexWriter(gvd, "vertex")
        gvwN = GeomVertexWriter(gvd, "normal")

        # Write out all points
        for p in GetPointsForBox(width, depth, height):
            gvwV.addData3f(Point3(p) - origin)

        # Write out all the normals
        for n in ((-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)):
            for i in range(4):
                gvwN.addData3f(n)

        geom = Geom(gvd)
        for i in range(0, gvwV.getWriteRow(), 4):

            # Create and add both triangles
            geom.addPrimitive(GetGeomTriangle(i, i + 1, i + 2))
            geom.addPrimitive(GetGeomTriangle(i, i + 2, i + 3))

        # Init the node path, wrapping the box
        geomNode = GeomNode("box")
        geomNode.addGeom(geom)
        NodePath.__init__(self, geomNode)
Example #13
0
    def __init__(self, *args, **kwargs):
        NodePath.__init__(self, *args, **kwargs)
        DirectObject.__init__(self)

        self.scale_signal = Signal()

        self.reset()
 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)
Example #15
0
    def restart(self):
        """Start or restart the plugin."""

        self.draw = Draw() # Utility for drawing 2D lines and shapes in 3-space
        path = Path([Vec2(40,40),Vec2(40,-40),Vec2(-40,40),Vec2(-40,-40)])
        for vehicle in self.vehicles[:3]:
            vehicle._pos = SteerVec((random.random()-0.5)*100,(random.random()-0.5)*100)
            vehicle._velocity = SteerVec((random.random()-0.5)*2,(random.random()-0.5)*2)
            vehicle.followPath(path,loop=True)
        c=(.6,.6,.6,.3)
        t=1
        z=1.5
        self.draw.drawLine(Vec3(path[0].getX(),path[0].getY(),z),Vec3(path[1].getX(),path[1].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[1].getX(),path[1].getY(),z),Vec3(path[2].getX(),path[2].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[2].getX(),path[2].getY(),z),Vec3(path[3].getX(),path[3].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[3].getX(),path[3].getY(),z),Vec3(path[0].getX(),path[0].getY(),z),color=c,thickness=t)
        path = Path([Vec2(-40,-40),Vec2(40,-40),Vec2(-40,40),Vec2(40,40)])
        for vehicle in self.vehicles[3:]:
            vehicle._pos = SteerVec((random.random()-0.5)*100,(random.random()-0.5)*100)
            vehicle._velocity = SteerVec((random.random()-0.5)*2,(random.random()-0.5)*2)
            vehicle.followPath(path,loop=True)
        self.draw.drawLine(Vec3(path[0].getX(),path[0].getY(),z),Vec3(path[1].getX(),path[1].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[1].getX(),path[1].getY(),z),Vec3(path[2].getX(),path[2].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[2].getX(),path[2].getY(),z),Vec3(path[3].getX(),path[3].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[3].getX(),path[3].getY(),z),Vec3(path[0].getX(),path[0].getY(),z),color=c,thickness=t)        
        for vehicle in self.vehicles:
            vehicle.avoidObstacles = True
            vehicle.avoidVehicles = True
            vehicle.maxforce = 0.1
            vehicle.maxspeed = 0.5 + (random.random()/2)            
        node = self.draw.create()
        np = NodePath(node)   
        np.reparentTo(render)
 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()
Example #17
0
    def cleanup(self):
        for page in self.catalogItemPages:
            page.cleanup()

        self.tabButton.destroy()

        NodePath.removeNode(self)
Example #18
0
	def draw(self):
		# Draw attack radius
		attackRadLine = LineSegs()
		attackRadLine.setThickness(1)
		attackRadLine.setColor(self._color)
		attackRadLine.moveTo(self.attackRad, 0, 0)
		for i in range(self._EDGES + 1):
			newX = (self.attackRad * math.cos((2*math.pi/self._EDGES)*i))
			newY = (self.attackRad * math.sin((2*math.pi/self._EDGES)*i))
			attackRadLine.drawTo(newX, newY, 0)
		attackRadGeom = attackRadLine.create()
		self._attackRadCircleNP = NodePath(attackRadGeom)
		self._attackRadCircleNP.reparentTo(self._np)
		
		# Draw foot circle
		self._footCircle.setThickness(1)
		self._footCircle.setColor(self._color)
		self._footCircle.moveTo(self.footRad, 0, 0)
		for i in range(self._EDGES):
			newX = (self.footRad * math.cos((2*math.pi/self._EDGES)*i))
			newY = (self.footRad * math.sin((2*math.pi/self._EDGES)*i))
			self._footCircle.drawTo(newX, newY, 0)
		self._footCircle.drawTo(self.footRad, 0, 0)
		footCircleGeom = self._footCircle.create()
		self._footCircleNP = NodePath(footCircleGeom)
		self._footCircleNP.reparentTo(self._np)
Example #19
0
    def place_markers(self,nodes):
        for n in range(len(nodes)):
            town_node = NodePath("town")
            town = loader.loadModel("models/infantry_counter.egg")
            x = (nodes[n+1]["x"]-map_center[0])*amplification
            y = (nodes[n+1]["y"]-map_center[1])*amplification
            town.setPos(x,y,0)
            if nodes[n+1]["type"] == "city":
                scale = 12
            elif nodes[n+1]["type"] == "town":
                scale = 7
            elif nodes[n+1]["type"] == "village":
                scale = 4
            town.setScale(scale,scale,scale)
            town.reparentTo(town_node)
            town_node.reparentTo(render)

            text_node = TextNode("town_text_node")
            text_node.setText(nodes[n+1]["name"])
            text_node_path = town.attachNewNode(text_node)
            text_node_path.setPos(1,0,0)
            text_node_path.setHpr(0,-90,0)
            text_node_path.setScale(scale/2)
            text_node_path.setTransparency(TransparencyAttrib.MAlpha)
            text_node.setTextColor(0.8, 0.1, 0.1, 1)
            text_node.setAlign(TextNode.ALeft)
Example #20
0
class bigWall(StaticObject):


    
    def __init__(self, game):
        self.game = game
        
        
        self.collGeom = OdeBoxGeom( self.game.physicsSpace, 50, 15, 15)
        #self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(0x000000ff) )#ffffffff) )
        self.collGeom.setCollideBits( BitMask32(0x000000ff) )
        
        #remember to make wall model with "50" length... no idea 50 what, though
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        model = loader.loadModel('BigWall.egg')
        model.reparentTo(self.visualNode) 
        
        
   
        
        
    def osuminen(self, ship1):
         if OdeUtil.collide(ship1.collGeom, self.collGeom):
 
            print "sdfgfdhgdfhxfhdhghcfh"
            print "ship1 xdfhgxdgxdgfbcdll!!"
Example #21
0
 def draw(self):
     format=GeomVertexFormat.getV3n3cpt2()
     vdata=GeomVertexData('square', format, Geom.UHDynamic)
     vertex=GeomVertexWriter(vdata, 'vertex')
     normal=GeomVertexWriter(vdata, 'normal')
     color=GeomVertexWriter(vdata, 'color')
     circle=Geom(vdata)
     # Create vertices
     vertex.addData3f(self.pos)
     color.addData4f(self.color)
     for v in range(self._EDGES):
         x = self.pos.getX() + (self.size * math.cos((2*math.pi/self._EDGES)*v))
         y = self.pos.getY() + (self.size * math.sin((2*math.pi/self._EDGES)*v))
         z = self.pos.getZ()
         vertex.addData3f(x, y, z)
         color.addData4f(self.color)
     
     # Create triangles
     for t in range(self._EDGES):
         tri = GeomTriangles(Geom.UHDynamic)
         tri.addVertex(0)
         tri.addVertex(t+1)
         if (t+2) > self._EDGES:
             tri.addVertex(1)
         else:
             tri.addVertex(t+2)
         tri.closePrimitive()
         circle.addPrimitive(tri)
     
     gn = GeomNode('Circle')
     gn.addGeom(circle)
     np = NodePath(gn)
     np.setHpr(0, 90, 0)
     return np
 def enable(self):
     if self._enabled:
         return
     self._toon.detachCamera()
     self._prevToonY = 0.0
     levelBounds = self._level.getBounds()
     l = Globals.Camera.LevelBoundsFactor
     self._bounds = (
         (levelBounds[0][0] * l[0], levelBounds[0][1] * l[0]),
         (levelBounds[1][0] * l[1], levelBounds[1][1] * l[1]),
         (levelBounds[2][0] * l[2], levelBounds[2][1] * l[2]),
     )
     self._lookAtZ = self._toon.getHeight() + Globals.Camera.LookAtToonHeightOffset
     self._camParent = NodePath("CamParent")
     self._camParent.reparentTo(self._parent)
     self._camParent.setPos(self._toon, 0, 0, 0)
     self._camParent.setHpr(180, Globals.Camera.Angle, 0)
     self._camera.reparentTo(self._camParent)
     self._camera.setPos(0, Globals.Camera.Distance, 0)
     self._camera.lookAt(self._toon, 0, 0, self._lookAtZ)
     self._cameraLookAtNP = NodePath("CameraLookAt")
     self._cameraLookAtNP.reparentTo(self._camera.getParent())
     self._cameraLookAtNP.setPosHpr(self._camera.getPos(), self._camera.getHpr())
     self._levelBounds = self._level.getBounds()
     self._enabled = True
     self._frozen = False
     self._initCollisions()
 def _initVisuals(self):
     RepairMincroGame._initVisuals(self)
     self.model = loader.loadModel('models/gui/pir_m_gui_srp_bracing_main')
     self.background = self.model.find('**/background')
     self.background.reparentTo(self)
     self.background.setZ(0.17499999999999999)
     self.gridParent = self.attachNewNode('gridParent')
     self.grid = []
     for xpos in range(GRID_SIZE):
         col = []
         for ypos in range(GRID_SIZE):
             allWoodSquaresGeom = NodePath('wood_squares')
             for i in range(self.model.find('**/wood_squares').getNumChildren()):
                 self.model.find('**/wood_squares').getChild(i).copyTo(allWoodSquaresGeom)
             
             tempGeom = NodePath('tempGeom')
             self.model.find('**/wood_squares').getChild(0).copyTo(tempGeom)
             selectedOutlineGeom = NodePath('selectedOutlineGeom')
             self.model.find('**/selected').copyTo(selectedOutlineGeom)
             selectedOutlineGeom.setScale(0.90000000000000002)
             piece = RepairGridPiece(name = 'piece%i' % (xpos * GRID_SIZE + ypos), parent = self.gridParent, allWoodSquaresGeom = allWoodSquaresGeom, selectedOutlineGeom = selectedOutlineGeom, scale = (0.90000000000000002, 0.90000000000000002, 0.90000000000000002), pos = (-0.22 + xpos * SPACING, 0.0, -0.029999999999999999 + ypos * SPACING), command = self.onPiecePressed, location = [
                 xpos,
                 ypos], clickSound = None, pressEffect = 0, geom = tempGeom, relief = None)
             col.append(piece)
         
         self.grid.append(col)
     
     self.createGoalPieces()
    def _optimize(self):
        lightCones = NodePath('lightCones')
        for np in self._platformsRoot.findAllMatches('**/*lightCone*'):
            np.wrtReparentTo(lightCones)

        lightCones.reparentTo(self._model)
        node = self._model.find('**/ducts')
        if not node.isEmpty():
            node.flattenStrong()
            for np in node.getChildren():
                np.wrtReparentTo(self._model)

        node = self._model.find('**/nests')
        if not node.isEmpty():
            for np in node.getChildren():
                np.flattenStrong()
                np.wrtReparentTo(self._model)

        for np in self._model.findAllMatches('**/*LayerStack*'):
            np.wrtReparentTo(self._model)

        if not self._model.find('**/static').isEmpty():
            for np in self._model.find('**/static').getChildren():
                np.wrtReparentTo(self._model)

        self._model.flattenMedium()
 def __init__(self, cr, proximityText):
     NodePath.__init__(self, self.__class__.__name__)
     DistributedInteractive.__init__(self, cr)
     self.holiday = ""
     self.interactRadius = 10
     self.interactMode = 0
     self.proximityText = proximityText
 def initFishStaminaBar(self):
     self.legendaryGui = loader.loadModel('models/minigames/pir_m_gam_fsh_legendaryGui')
     self.iconBaseFrame = DirectFrame(relief = None, state = DGG.DISABLED, pos = (0, 0, 0), sortOrder = 30, image = self.legendaryGui.find('**/pir_t_gui_fsh_fishPortraitFrame'), image_scale = 0.17999999999999999, image_pos = (0, 0, 0))
     self.iconBaseFrame.setTransparency(TransparencyAttrib.MAlpha)
     self.fishUINodePath = NodePath(self.iconBaseFrame)
     self.fishUINodePath.setPos(-0.29999999999999999, 0.0, 0.82999999999999996)
     self.fishUINodePath.reparentTo(hidden)
     self.iconCard = loader.loadModel('models/gui/treasure_gui')
     self.iconBaseFrame.iconImage = OnscreenImage(parent = self.iconBaseFrame, image = self.iconCard.find('**/%s*' % CollectionMap.Assets[self.myData['id']]), scale = 0.34999999999999998, hpr = (0, 0, 0), pos = (0.0, 0, 0.0))
     self.fishNameLabel = TextNode('fishNameLabel')
     name = self.getName().split('_')
     self.fishNameLabel.setText(name[0])
     self.fishNameLabel.setTextColor(1.0, 1.0, 1.0, 1.0)
     self.fishNameLabelNodePath = NodePath(self.fishNameLabel)
     self.fishNameLabelNodePath.setPos(0.29999999999999999, 0, 0.040000000000000001)
     self.fishNameLabelNodePath.setScale(0.044999999999999998)
     self.fishNameLabelNodePath.reparentTo(self.iconBaseFrame)
     self.fishStaminaBar = DirectWaitBar(parent = self.iconBaseFrame, relief = DGG.FLAT, state = DGG.DISABLED, range = 100, value = 0, sortOrder = 20, frameColor = (0, 0, 0, 1.0), pos = (0.070000000000000007, 0.0, -0.014999999999999999), hpr = (0, 0, 0), frameSize = (0, 0.71999999999999997, 0, 0.028000000000000001))
     self.fishStaminaBar['value'] = self.staminaValue
     self.fishStaminaBar['barColor'] = FishingGlobals.fishingStaminaBarColor[int((self.staminaValue / 100.0) * (len(FishingGlobals.fishingStaminaBarColor) - 1))]
     self.fishStaminaValueLabel = TextNode('fishStaminaValueLabel')
     self.fishStaminaValueLabel.setText(str(self.staminaValue) + '//' + str(self.staminaValue))
     self.fishStaminaValueLabel.setTextColor(1.0, 1.0, 1.0, 1.0)
     self.fishStaminaValueLabelNodePath = NodePath(self.fishStaminaValueLabel)
     self.fishStaminaValueLabelNodePath.setPos(0.66000000000000003, 0, -0.059999999999999998)
     self.fishStaminaValueLabelNodePath.setScale(0.044999999999999998)
     self.fishStaminaValueLabelNodePath.reparentTo(self.iconBaseFrame)
     self.fishStaminaBarFrame = DirectLabel(parent = self.iconBaseFrame, relief = None, state = DGG.DISABLED, frameColor = (1, 1, 1, 0.10000000000000001), pos = (0.44, 0.0, 0.0), hpr = (0, 0, 0), sortOrder = 25, image = self.legendaryGui.find('**/pir_t_gui_fsh_staminaBarForeground'), image_scale = (1.0, 0.0, 0.050000000000000003), image_pos = (0.0, 0.0, 0.0), image_hpr = (0.0, 0.0, 0.0))
     self.fishStaminaBarFrame.setTransparency(TransparencyAttrib.MAlpha)
     self.fishStaminaBarFrame.setDepthTest(True)
     self.fishStaminaBarFrame.setDepthWrite(True)
Example #27
0
 def attachNewCollidableNode( self, node, bitmask=None ):
   if bitmask is None:
     bitmask = self.bitmask
   # attach a new node which is colliable
   NodePath.attachNewNode( self, node )
   self.setTag('objectId', self.objectId )
   self.setCollideMask( bitMaskOr(bitmask) )
    def __init__(self, cogMenu, dept):
        NodePath.__init__(self, 'CogMenuBar-%s' % dept)

        self.dept = dept
        self.deptIndex = CogDisguiseGlobals.dept2deptIndex(self.dept)

        icons = loader.loadModel('phase_3/models/gui/cog_icons')
        self.icon = icons.find(ICON_NODES[self.deptIndex]).copyTo(self)
        self.icon.setColor(ICON_COLORS[self.deptIndex])
        self.icon.setScale(0.07)
        self.icon.setX(-0.25)
        icons.removeNode()

        self.progressBar = DirectWaitBar(parent=self, relief=DirectGuiGlobals.SUNKEN,
                                         frameSize=(-1, 1, -0.15, 0.15),
                                         borderWidth=(0.02, 0.02),
                                         scale=0.20,
                                         frameColor=(DisguisePage.DeptColors[self.deptIndex][0] * 0.7,
                                                     DisguisePage.DeptColors[self.deptIndex][1] * 0.7,
                                                     DisguisePage.DeptColors[self.deptIndex][2] * 0.7,
                                                     1),
                                         barColor=(DisguisePage.DeptColors[self.deptIndex][0],
                                                   DisguisePage.DeptColors[self.deptIndex][1],
                                                   DisguisePage.DeptColors[self.deptIndex][2],
                                                   1),
                                         text='0/0 ' + TTLocalizer.RewardPanelMeritBarLabels[self.deptIndex],
                                         text_scale=TTLocalizer.RPmeritBarLabels, text_fg=(0, 0, 0, 1),
                                         text_align=TextNode.ALeft, text_pos=(-0.96, -0.05))

        self.reparentTo(cogMenu)
Example #29
0
 def __init__(self, x, y, z, environment, blocks, node, geomId):
     self.x = x
     self.y = y
     self.z = z
     self.environment = environment  # The environment object for the world
     self.blocks = blocks            # The 3D array of Block objects
     self.geom = 0                   # A dict used to hold all of the data for geometry creation
     self.node = node                # The parent node of the geometry
     self.geomId = geomId            # The id of the geometry wrt the parent (needed for updating the geometry)
     self.dirty = 0                  # A flag for whether the Chunk needs updating
     
     self.wallCollisionGeom = NodePath('wallCollisionGeom') 
     self.wallCollisionGeom.reparentTo(render)
     self.floorCollisionGeom = NodePath('floorCollisionGeom') 
     self.floorCollisionGeom.reparentTo(render)
     
     self.geomGen = BlockGeometryGenerator()
     self.queue = Queue.Queue()
     
     self.blockTexture = loader.loadTexture('Assets/Images/Textures/blocks.png')
     self.lightMapTexture = loader.loadTexture('Assets/Images/Textures/lightMap.png')
     
     self.CreateVertexFormat()
     self.geom = ChunkOfBlocks.CreateNewGeomDict(self.blockTexture, self.lightMapTexture, self.geomVertexFormat)
     ChunkOfBlocks.UpdateCollisionAndGeom(self, self.wallCollisionGeom, self.floorCollisionGeom, self.geom, self.geomGen, self.environment, blocks, x, y, z)
     self.AddGeom()
Example #30
0
File: camera.py Project: LBdN/labs
 def __init__( self, 
               name='camera', 
               pos=Vec3( 0, 0, 0 ), 
               targetPos=Vec3( 0, 0, 0 ),
               style=CAM_DEFAULT_STYLE ):
     self.zoomLevel = 2
     self.defaultPos = pos
     self.style = style
     # Use Panda's default camera
     if self.style & CAM_USE_DEFAULT:
         self.cam = getBase().cam
         #self.camNode = getBase().camNode
     # Otherwise create a new one
     else:
         # Create camera
         self.cam = NodePath( PCamera( name ) )
         # Create lens
         lens = PerspectiveLens()
         lens.setAspectRatio( 800.0 / 300.0 )
         self.cam.node().setLens( lens )
     # Wrap the camera in this node path class
     NodePath.__init__( self, self.cam )
     # Create camera styles
     if self.style & CAM_VIEWPORT_AXES:
         self.axes = self.Axes()
         self.axes.reparentTo( pixel2d )
     # Create camera target
     self.target = self.Target( pos=targetPos )
     self.Reset()
Example #31
0
 def createThrowGag(self, gag):
     throwGag = gag.copyTo(NodePath('gag'))
     return throwGag
Example #32
0
    def createSprite(self, sprite):
        '''
        Creates a new sprite and returns a SpriteRenderInterface for controlling this sprite instance.
        The newly created sprite is located at (0,0) in screen coordinates its dimensions are specified
        by the given Sprite argument.
        @param sprite: A Sprite resource that describes the properties of the sprite to created.
        @return: A SpriteRenderInterface instance or None if it failed to create the sprite.
        '''
        if sprite.eggFile is not None:
            spriteNP = self.resources.loadModel(sprite.eggFile)
            tex = None
        else:
            if sprite.video is not None:
                card = self.cardMaker.generate()
                tex = VideoPlayer.renderToTexture(self.resources,
                                                  video=sprite.video,
                                                  audio=sprite.audio)
            elif sprite.image is not None:
                card = self.cardMaker.generate()
                tex = self.resources.loadTexture(sprite.image)
                sprite.width = tex.getXSize()
                sprite.height = tex.getYSize()
            else:
                self.log.error('Could not determine type for sprite: %s' %
                               sprite.name)
                return None

            spriteNP = NodePath(card)
            spriteNP.setTexture(tex)

        nodeName = self.getSpriteNodeName(sprite.name)
        spriteNP.setName(nodeName)
        spriteNP.setPos(0, 1, 0)
        spriteNP.setScale(sprite.width, 1.0, sprite.height)
        spriteNP.setTransparency(1)

        spriteNP.reparentTo(self.sprite2d)

        spriteNP.setDepthTest(False)
        spriteNP.setDepthWrite(False)
        spriteNP.setBin("fixed", PanoConstants.RENDER_ORDER_SPRITES)
        spriteNP.setPythonTag('sprite', sprite)

        if sprite.video is not None:
            spriteNP.setPythonTag('video', tex)
            tex.setLoop(True)
            tex.play()

        return SpriteRenderInterface(spriteNP)
class CogdoMazeGameIntro(CogdoGameMovie):

    def __init__(self, maze, exit, rng):
        CogdoGameMovie.__init__(self)
        self._maze = maze
        self._exit = exit
        self._rng = RandomNumGen(rng)
        self._camTarget = None
        self._state = 0
        self._suits = []
        return

    def _getRandomLine(self, lineList):
        return CogdoUtil.getRandomDialogueLine(lineList, self._rng)

    def displayLine(self, who, text):
        self._dialogueLabel.node().setText(text)
        if who == 'toon':
            self.toonHead.reparentTo(aspect2d)
            self.cogHead.reparentTo(hidden)
            self._toonDialogueSfx.play()
            self.toonHead.setClipPlane(self.clipPlane)
        else:
            self.toonHead.reparentTo(hidden)
            self.cogHead.reparentTo(aspect2d)
            self._cogDialogueSfx.play()
            self.cogHead.setClipPlane(self.clipPlane)

    def makeSuit(self, suitType):
        suit = Suit.Suit()
        dna = SuitDNA.SuitDNA()
        dna.newSuit(suitType)
        suit.setStyle(dna)
        suit.isDisguised = 1
        suit.generateSuit()
        suit.setScale(1, 1, 2)
        suit.setPos(0, 0, -4.4)
        suit.reparentTo(self.toonHead)
        for part in suit.getHeadParts():
            part.hide()

    def load(self):
        CogdoGameMovie.load(self)
        self.toonDNA = ToonDNA.ToonDNA()
        self.toonDNA.newToonFromProperties('dss', 'ss', 'm', 'm', 2, 0, 2, 2, 1, 8, 1, 8, 1, 14)
        self.toonHead = Toon.Toon()
        self.toonHead.setDNA(self.toonDNA)
        self.makeSuit('sc')
        self.toonHead.getGeomNode().setDepthWrite(1)
        self.toonHead.getGeomNode().setDepthTest(1)
        self.toonHead.loop('neutral')
        self.toonHead.setPosHprScale(-0.73, 0, -1.27, 180, 0, 0, 0.18, 0.18, 0.18)
        self.toonHead.reparentTo(hidden)
        self.toonHead.startBlink()
        self.cogHead = Suit.Suit()
        self.cogDNA = SuitDNA.SuitDNA()
        self.cogDNA.newSuit('ms')
        self.cogHead.setDNA(self.cogDNA)
        self.cogHead.getGeomNode().setDepthWrite(1)
        self.cogHead.getGeomNode().setDepthTest(1)
        self.cogHead.loop('neutral')
        self.cogHead.setPosHprScale(-0.73, 0, -1.46, 180, 0, 0, 0.14, 0.14, 0.14)
        self.cogHead.reparentTo(hidden)
        self.clipPlane = self.toonHead.attachNewNode(PlaneNode('clip'))
        self.clipPlane.node().setPlane(Plane(0, 0, 1, 0))
        self.clipPlane.setPos(0, 0, 2.45)
        audioMgr = base.cogdoGameAudioMgr
        self._cogDialogueSfx = audioMgr.createSfx('cogDialogue')
        self._toonDialogueSfx = audioMgr.createSfx('toonDialogue')
        suitData = Globals.SuitData[Globals.SuitTypes.Boss]
        bossSuit = Suit.Suit()
        bossSuit.nametag3d.stash()
        bossSuit.nametag.destroy()
        d = SuitDNA.SuitDNA()
        d.newSuit('ms')
        bossSuit.setDNA(d)
        bossSuit.setScale(suitData['scale'])
        bossSuit.loop('neutral')
        bossSuit.reparentTo(render)
        bossSuit.setPos(self._exit, -5, -5, 0)
        bossSuit.lookAt(self._exit)
        self._suits.append(bossSuit)
        self._camHelperNode = NodePath('CamHelperNode')
        self._camHelperNode.reparentTo(render)
        dialogue = TTLocalizer.CogdoMazeIntroMovieDialogue
        introDuration = Globals.IntroDurationSeconds
        waitDuration = introDuration / len(dialogue)

        def start():
            camera.wrtReparentTo(render)
            self._exit.open(animate=False)

        def showBoss():
            self._setCamTarget(bossSuit, 20, offset=Point3(0, 0, 7), angle=Point3(0, 15, 0))
            bossSuit.loop('victory')
            self._state = 1

        def showExit():
            self._setCamTarget(self._exit, 10, offset=Point3(0, 0, 0), angle=Point3(0, 60, 0))
            self._exit.close()
            self._state = 2

        showExitIval = Parallel(camera.posInterval(waitDuration * 0.5, (10, -25, 20), other=self._exit, blendType='easeInOut'), Sequence(Wait(waitDuration * 0.25), Func(bossSuit.play, 'effort'), camera.hprInterval(waitDuration * 0.25, (30, -30, 0), blendType='easeInOut'), Func(self._exit.close), Wait(waitDuration * 0.5)))

        def showWaterCooler():
            wc = self._maze.getWaterCoolers()[0]
            self._setCamTarget(wc, 25, angle=Point3(-30, 60, 0))
            camera.wrtReparentTo(self._camHelperNode)
            self._state = 3

        def end():
            self._stopUpdateTask()

        self._ival = Sequence(Func(start), Func(self.displayLine, 'toon', self._getRandomLine(dialogue[0])), showExitIval, Func(showWaterCooler), Func(self.displayLine, 'toon', self._getRandomLine(dialogue[1])), Wait(waitDuration), Func(showBoss), bossSuit.hprInterval(1.0, bossSuit.getHpr() + Point3(180, 0, 0), blendType='easeInOut'), Func(self.displayLine, 'toon', self._getRandomLine(dialogue[2])), Wait(waitDuration - 1.0), Func(end))
        self._startUpdateTask()

    def _setCamTarget(self, targetNP, distance, offset = Point3(0, 0, 0), angle = Point3(0, 0, 0)):
        camera.wrtReparentTo(render)
        self._camTarget = targetNP
        self._camOffset = offset
        self._camAngle = angle
        self._camDistance = distance
        self._camHelperNode.setPos(self._camTarget, self._camOffset)
        self._camHelperNode.setHpr(self._camTarget, 180 + self._camAngle[0], self._camAngle[1], self._camAngle[2])
        camera.setPos(self._camHelperNode, 0, self._camDistance, 0)

    def _updateTask(self, task):
        dt = globalClock.getDt()
        if self._state == 1:
            self._camHelperNode.setPos(self._camTarget.getPos() + self._camOffset)
            camera.setPos(self._camHelperNode, 0, self._camDistance, 0)
            camera.lookAt(self._camTarget, 0, 0, 4)
        elif self._state == 2:
            camera.lookAt(self._camTarget, 0, 0, 5)
        elif self._state == 3:
            self._camHelperNode.setHpr(self._camHelperNode, dt, dt, 0)
            camera.setY(camera, 0.8 * dt)
            camera.lookAt(self._camTarget, 0, 0, 3)
        return task.cont

    def unload(self):
        self._exit = None
        self._camTarget = None
        self._camHelperNode.removeNode()
        del self._camHelperNode
        for suit in self._suits:
            suit.cleanup()
            suit.removeNode()
            suit.delete()

        self._suits = []
        CogdoGameMovie.unload(self)
        del self._cogDialogueSfx
        del self._toonDialogueSfx
        self.toonHead.stopBlink()
        self.toonHead.stop()
        self.toonHead.removeNode()
        self.toonHead.delete()
        del self.toonHead
        self.cogHead.stop()
        self.cogHead.removeNode()
        self.cogHead.delete()
        del self.cogHead
        return
Example #34
0
class PartyEditorGridElement(DirectButton):
    __module__ = __name__
    notify = directNotify.newCategory('PartyEditorGridElement')

    def __init__(self, partyEditor, id, isDecoration,
                 checkSoldOutAndPaidStatusAndAffordability, **kw):
        self.partyEditor = partyEditor
        self.id = id
        self.isDecoration = isDecoration
        self.checkSoldOutAndPaidStatusAndAffordability = checkSoldOutAndPaidStatusAndAffordability
        if self.isDecoration:
            self.name = TTLocalizer.PartyDecorationNameDict[self.id]['editor']
            colorList = ((1.0, 1.0, 1.0, 1.0), (0.0, 0.0, 1.0, 1.0),
                         (0.0, 1.0, 1.0, 1.0), (0.5, 0.5, 0.5, 1.0))
            self.geom = self.partyEditor.partyPlanner.gui.find(
                '**/%s' %
                PartyGlobals.DecorationInformationDict[self.id]['gridAsset'])
        else:
            self.name = TTLocalizer.PartyActivityNameDict[self.id]['editor']
            colorList = ((1.0, 1.0, 1.0, 1.0), (0.0, 1.0, 0.0, 1.0),
                         (1.0, 1.0, 0.0, 1.0), (0.5, 0.5, 0.5, 1.0))
            self.geom = self.partyEditor.partyPlanner.gui.find(
                '**/%s' %
                PartyGlobals.ActivityInformationDict[self.id]['gridAsset'])
        optiondefs = (('geom', self.geom, None), ('geom_scale', 1.0, None),
                      ('geom_color', colorList[0],
                       None), ('geom1_color', colorList[0],
                               None), ('geom2_color', colorList[0],
                                       None), ('geom3_color', colorList[0],
                                               None), ('relief', None, None))
        self.defineoptions(kw, optiondefs)
        DirectButton.__init__(self, self.partyEditor.parent)
        self.initialiseoptions(PartyEditorGridElement)
        self.setName('%sGridElement' % self.name)
        self.bind(DirectGuiGlobals.B1PRESS, self.clicked)
        self.bind(DirectGuiGlobals.B1RELEASE, self.released)
        self.bind(DirectGuiGlobals.ENTER, self.mouseEnter)
        self.bind(DirectGuiGlobals.EXIT, self.mouseExit)
        self.uprightNodePath = NodePath('%sUpright' % self.name)
        self.uprightNodePath.reparentTo(self)
        rollOverZOffset = self.getGridSize()[1] / 30.0
        self.rolloverTitle = DirectLabel(relief=None,
                                         parent=self.uprightNodePath,
                                         pos=Point3(0.0, 0.0, rollOverZOffset),
                                         text=self.name,
                                         text_fg=(1.0, 1.0, 1.0, 1.0),
                                         text_shadow=(0.0, 0.0, 0.0, 1.0),
                                         text_scale=0.075)
        self.rolloverTitle.stash()
        self.stash()
        self.overValidSquare = False
        self.lastValidPosition = None
        self.setColorScale(0.9, 0.9, 0.9, 0.7)
        self.setTransparency(True)
        self.mouseOverTrash = False
        self.centerGridSquare = None
        return

    def getCorrectRotation(self):
        r = self.getR()
        if r == 90.0:
            r = 270.0
        elif r == 270.0:
            r = 90.0
        if self.id == PartyGlobals.ActivityIds.PartyCannon:
            return PartyUtils.convertDegreesToPartyGrid(r + 180.0)
        return PartyUtils.convertDegreesToPartyGrid(r)

    def getDecorationTuple(self, x, y):
        return (self.id, self.centerGridSquare.x,
                PartyGlobals.PartyEditorGridSize[1] - 1 -
                self.centerGridSquare.y, self.getCorrectRotation())

    def getActivityTuple(self, x, y):
        return (self.id, self.centerGridSquare.x,
                PartyGlobals.PartyEditorGridSize[1] - 1 -
                self.centerGridSquare.y, self.getCorrectRotation())

    def attach(self, mouseEvent):
        PartyEditorGridElement.notify.debug('attached grid element %s' %
                                            self.name)
        taskMgr.remove('gridElementDragTask%s' % self.name)
        vWidget2render2d = self.getPos(render2d)
        vMouse2render2d = Point3(mouseEvent.getMouse()[0], 0,
                                 mouseEvent.getMouse()[1])
        taskMgr.add(self.elementDragTask, 'gridElementDragTask%s' % self.name)
        self.unstash()
        self.rolloverTitle.unstash()
        self.uprightNodePath.reparentTo(self)
        self.setPosHprToDefault()

    def elementDragTask(self, state):
        mwn = base.mouseWatcherNode
        if mwn.hasMouse():
            vMouse2render2d = Point3(mwn.getMouse()[0], 0, mwn.getMouse()[1])
            newPos = vMouse2render2d
            if newPos[0] > PartyGlobals.PartyEditorGridBounds[0][0] and newPos[
                    0] < PartyGlobals.PartyEditorGridBounds[1][0] and newPos[
                        2] < PartyGlobals.PartyEditorGridBounds[0][
                            1] and newPos[
                                2] > PartyGlobals.PartyEditorGridBounds[1][1]:
                centerGridSquare = self.snapToGrid(newPos)
                if centerGridSquare is not None:
                    self.centerGridSquare = centerGridSquare
                    if not self.overValidSquare:
                        self.setOverValidSquare(True)
                    if self.mouseOverTrash:
                        self.setOverTrash(False)
                    return Task.cont
            if self.id != PartyGlobals.ActivityIds.PartyClock and newPos[
                    0] > PartyGlobals.PartyEditorTrashBounds[0][0] and newPos[
                        0] < PartyGlobals.PartyEditorTrashBounds[1][
                            0] and newPos[
                                2] < PartyGlobals.PartyEditorTrashBounds[0][
                                    1] and newPos[
                                        2] > PartyGlobals.PartyEditorTrashBounds[
                                            1][1]:
                if not self.mouseOverTrash:
                    self.setOverTrash(True)
            elif self.mouseOverTrash:
                self.setOverTrash(False)
            self.setPos(render2d, newPos)
            if self.overValidSquare:
                self.setOverValidSquare(False)
        return Task.cont

    def setOverTrash(self, value):
        self.mouseOverTrash = value
        if value:
            self.partyEditor.trashCanButton[
                'state'] = DirectGuiGlobals.DISABLED
            self.setColorScale(1.0, 0.0, 0.0, 1.0)
        else:
            self.partyEditor.trashCanButton['state'] = DirectGuiGlobals.NORMAL
            self.setColorScale(0.9, 0.9, 0.9, 0.7)

    def setOverValidSquare(self, value):
        self.overValidSquare = value
        if value:
            self.setColorScale(1.0, 1.0, 1.0, 1.0)
        else:
            self.setColorScale(0.9, 0.9, 0.9, 0.7)

    def removeFromGrid(self):
        if self.centerGridSquare is not None:
            self.partyEditor.partyEditorGrid.removeElement(
                self.centerGridSquare, self.getGridSize())
        self.setOverValidSquare(False)
        self.lastValidPosition = None
        self.stash()
        return

    def snapToGrid(self, newPos):
        gridSquare = self.getGridSquareFromPosition(newPos)
        if gridSquare == None:
            self.setPosHprToDefault()
            self.setPos(render2d, newPos)
            return
        elif not self.partyEditor.partyEditorGrid.checkGridSquareForAvailability(
                gridSquare, self.getGridSize()):
            self.setPos(render2d, newPos)
            return
        self.setPosHprBasedOnGridSquare(gridSquare)
        return gridSquare

    def getGridSize(self):
        if self.isDecoration:
            return PartyGlobals.DecorationInformationDict[self.id]['gridsize']
        else:
            return PartyGlobals.ActivityInformationDict[self.id]['gridsize']

    def setPosHprToDefault(self):
        self.setR(0.0)
        self.uprightNodePath.setR(0.0)

    def setPosHprBasedOnGridSquare(self, gridSquare):
        gridPos = gridSquare.getPos()
        if self.getGridSize()[0] % 2 == 0:
            gridPos.setX(gridPos[0] +
                         PartyGlobals.PartyEditorGridSquareSize[0] / 2.0)
        if self.getGridSize()[1] % 2 == 0:
            gridPos.setZ(gridPos[2] +
                         PartyGlobals.PartyEditorGridSquareSize[1] / 2.0)
        if self.id != PartyGlobals.ActivityIds.PartyFireworks:
            if gridPos[0] > PartyGlobals.PartyEditorGridCenter[
                    0] + PartyGlobals.PartyEditorGridRotateThreshold:
                self.setR(90.0)
                self.uprightNodePath.setR(-90.0)
            elif gridPos[0] < PartyGlobals.PartyEditorGridCenter[
                    0] - PartyGlobals.PartyEditorGridRotateThreshold:
                self.setR(270.0)
                self.uprightNodePath.setR(-270.0)
            elif gridPos[2] < PartyGlobals.PartyEditorGridCenter[
                    1] - PartyGlobals.PartyEditorGridRotateThreshold:
                self.setR(180.0)
                self.uprightNodePath.setR(-180.0)
            else:
                self.setR(0.0)
                self.uprightNodePath.setR(0.0)
        else:
            self.setR(270.0)
            self.uprightNodePath.setR(-270.0)
        self.setPos(render2d, gridPos)
        self.lastValidPosition = gridPos

    def getGridSquareFromPosition(self, newPos):
        localX = newPos[0] - PartyGlobals.PartyEditorGridBounds[0][0]
        localY = newPos[2] - PartyGlobals.PartyEditorGridBounds[1][1]
        x = int(localX / PartyGlobals.PartyEditorGridSquareSize[0])
        y = int(localY / PartyGlobals.PartyEditorGridSquareSize[1])
        y = PartyGlobals.PartyEditorGridSize[1] - 1 - y
        return self.partyEditor.partyEditorGrid.getGridSquare(x, y)

    def detach(self, mouseEvent):
        taskMgr.remove('gridElementDragTask%s' % self.name)
        self.rolloverTitle.stash()
        if self.overValidSquare:
            self.partyEditor.partyEditorGrid.registerNewElement(
                self, self.centerGridSquare, self.getGridSize())
            self.partyEditor.updateCostsAndBank()
            self.partyEditor.handleMutuallyExclusiveActivities()
        elif self.lastValidPosition is not None:
            if self.mouseOverTrash:
                self.partyEditor.trashCanButton[
                    'state'] = DirectGuiGlobals.NORMAL
                self.lastValidPosition = None
                self.partyEditor.updateCostsAndBank()
                self.stash()
            else:
                self.setPos(render2d, self.lastValidPosition)
                self.setOverValidSquare(True)
                self.partyEditor.partyEditorGrid.registerNewElement(
                    self, self.centerGridSquare, self.getGridSize())
                self.partyEditor.updateCostsAndBank()
                self.partyEditor.handleMutuallyExclusiveActivities()
        else:
            self.stash()
        self.checkSoldOutAndPaidStatusAndAffordability()
        return

    def placeInPartyGrounds(self, desiredXY=None):
        self.centerGridSquare = self.partyEditor.partyEditorGrid.getClearGridSquare(
            self.getGridSize(), desiredXY)
        if self.centerGridSquare is not None:
            self.setOverValidSquare(True)
            self.unstash()
            self.setPosHprBasedOnGridSquare(self.centerGridSquare)
            self.partyEditor.partyEditorGrid.registerNewElement(
                self, self.centerGridSquare, self.getGridSize())
            self.partyEditor.updateCostsAndBank()
            self.partyEditor.partyPlanner.instructionLabel[
                'text'] = TTLocalizer.PartyPlannerEditorInstructionsPartyGrounds
            self.checkSoldOutAndPaidStatusAndAffordability()
            return True
        else:
            return False
        return

    def clicked(self, mouseEvent):
        PartyEditorGridElement.notify.debug('clicked grid element %s' %
                                            self.name)
        if self.centerGridSquare is not None:
            self.attach(mouseEvent)
            self.partyEditor.partyEditorGrid.removeElement(
                self.centerGridSquare, self.getGridSize())
        return

    def released(self, mouseEvent):
        PartyEditorGridElement.notify.debug('released grid element %s' %
                                            self.name)
        self.detach(mouseEvent)

    def mouseEnter(self, mouseEvent):
        parent = self.getParent()
        self.reparentTo(parent)
        self.rolloverTitle.unstash()

    def mouseExit(self, mouseEvent):
        self.rolloverTitle.stash()

    def destroy(self):
        self.unbind(DirectGuiGlobals.B1PRESS)
        self.unbind(DirectGuiGlobals.B1RELEASE)
        self.unbind(DirectGuiGlobals.ENTER)
        self.unbind(DirectGuiGlobals.EXIT)
        DirectButton.destroy(self)
Example #35
0
class CogdoExecutiveSuiteIntro(CogdoGameMovie):
    __module__ = __name__
    notify = DirectNotifyGlobal.directNotify.newCategory(
        'CogdoExecutiveSuiteIntro')
    introDuration = 7
    cameraMoveDuration = 3

    def __init__(self, shopOwner):
        CogdoGameMovie.__init__(self)
        self._shopOwner = shopOwner
        self._lookAtCamTarget = False
        self._camTarget = None
        self._camHelperNode = None
        self._toonDialogueSfx = None
        self.toonHead = None
        self.frame = None
        return

    def displayLine(self, text):
        self.notify.debug('displayLine')
        self._dialogueLabel.node().setText(text)
        self.toonHead.reparentTo(aspect2d)
        self._toonDialogueSfx.play()
        self.toonHead.setClipPlane(self.clipPlane)

    def makeSuit(self, suitType):
        self.notify.debug('makeSuit()')
        suit = Suit.Suit()
        dna = SuitDNA.SuitDNA()
        dna.newSuit(suitType)
        suit.setStyle(dna)
        suit.isDisguised = 1
        suit.generateSuit()
        suit.setScale(1, 1, 2)
        suit.setPos(0, 0, -4.4)
        suit.reparentTo(self.toonHead)
        for part in suit.getHeadParts():
            part.hide()

        suit.loop('neutral')

    def load(self):
        self.notify.debug('load()')
        CogdoGameMovie.load(self)
        backgroundGui = loader.loadModel(
            'phase_5/models/cogdominium/tt_m_gui_csa_flyThru')
        self.bg = backgroundGui.find('**/background')
        self.chatBubble = backgroundGui.find('**/chatBubble')
        self.chatBubble.setScale(6.5, 6.5, 7.3)
        self.chatBubble.setPos(0.32, 0, -0.78)
        self.bg.setScale(5.2)
        self.bg.setPos(0.14, 0, -0.6667)
        self.bg.reparentTo(aspect2d)
        self.chatBubble.reparentTo(aspect2d)
        self.frame = DirectFrame(geom=self.bg,
                                 relief=None,
                                 pos=(0.2, 0, -0.6667))
        self.bg.wrtReparentTo(self.frame)
        self.gameTitleText = DirectLabel(
            parent=self.frame,
            text=TTLocalizer.CogdoExecutiveSuiteTitle,
            scale=TTLocalizer.MRPgameTitleText * 0.8,
            text_align=TextNode.ACenter,
            text_font=getSignFont(),
            text_fg=(1.0, 0.33, 0.33, 1.0),
            pos=TTLocalizer.MRgameTitleTextPos,
            relief=None)
        self.chatBubble.wrtReparentTo(self.frame)
        self.frame.hide()
        backgroundGui.removeNode()
        self.toonDNA = ToonDNA.ToonDNA()
        self.toonDNA.newToonFromProperties('dss', 'ss', 'm', 'm', 2, 0, 2, 2,
                                           1, 8, 1, 8, 1, 14)
        self.toonHead = Toon.Toon()
        self.toonHead.setDNA(self.toonDNA)
        self.makeSuit('sc')
        self.toonHead.getGeomNode().setDepthWrite(1)
        self.toonHead.getGeomNode().setDepthTest(1)
        self.toonHead.loop('neutral')
        self.toonHead.setPosHprScale(-0.73, 0, -1.27, 180, 0, 0, 0.18, 0.18,
                                     0.18)
        self.toonHead.reparentTo(hidden)
        self.toonHead.startBlink()
        self.clipPlane = self.toonHead.attachNewNode(PlaneNode('clip'))
        self.clipPlane.node().setPlane(Plane(0, 0, 1, 0))
        self.clipPlane.setPos(0, 0, 2.45)
        self._toonDialogueSfx = loader.loadSfx(
            'phase_3.5/audio/dial/AV_dog_long.mp3')
        self._camHelperNode = NodePath('CamHelperNode')
        self._camHelperNode.reparentTo(render)
        dialogue = TTLocalizer.CogdoExecutiveSuiteIntroMessage

        def start():
            self.frame.show()
            base.setCellsAvailable(
                base.bottomCells + base.leftCells + base.rightCells, 0)

        def showShopOwner():
            self._setCamTarget(self._shopOwner, -10, offset=Point3(0, 0, 5))

        def end():
            self._dialogueLabel.reparentTo(hidden)
            self.toonHead.reparentTo(hidden)
            self.frame.hide()
            base.setCellsAvailable(
                base.bottomCells + base.leftCells + base.rightCells, 1)
            self._stopUpdateTask()

        self._ival = Sequence(
            Func(start), Func(self.displayLine, dialogue), Func(showShopOwner),
            ParallelEndTogether(
                camera.posInterval(self.cameraMoveDuration,
                                   Point3(8, 0, 13),
                                   blendType='easeInOut'),
                camera.hprInterval(0.5,
                                   self._camHelperNode.getHpr(),
                                   blendType='easeInOut')),
            Wait(self.introDuration), Func(end))
        self._startUpdateTask()
        return

    def _setCamTarget(self,
                      targetNP,
                      distance,
                      offset=Point3(0, 0, 0),
                      angle=Point3(0, 0, 0)):
        camera.wrtReparentTo(render)
        self._camTarget = targetNP
        self._camOffset = offset
        self._camAngle = angle
        self._camDistance = distance
        self._camHelperNode.setPos(self._camTarget, self._camOffset)
        self._camHelperNode.setHpr(self._camTarget, 180 + self._camAngle[0],
                                   self._camAngle[1], self._camAngle[2])
        self._camHelperNode.setPos(self._camHelperNode, 0, self._camDistance,
                                   0)

    def _updateTask(self, task):
        dt = globalClock.getDt()
        return task.cont

    def unload(self):
        self._shopOwner = None
        self._camTarget = None
        if hasattr(self, '_camHelperNode') and self._camHelperNode:
            self._camHelperNode.removeNode()
            del self._camHelperNode
        self.frame.destroy()
        del self.frame
        self.bg.removeNode()
        del self.bg
        self.chatBubble.removeNode()
        del self.chatBubble
        self.toonHead.stopBlink()
        self.toonHead.stop()
        self.toonHead.removeNode()
        self.toonHead.delete()
        del self.toonHead
        CogdoGameMovie.unload(self)
        return
    def load(self):
        CogdoGameMovie.load(self)
        self.toonDNA = ToonDNA.ToonDNA()
        self.toonDNA.newToonFromProperties('dss', 'ss', 'm', 'm', 2, 0, 2, 2, 1, 8, 1, 8, 1, 14)
        self.toonHead = Toon.Toon()
        self.toonHead.setDNA(self.toonDNA)
        self.makeSuit('sc')
        self.toonHead.getGeomNode().setDepthWrite(1)
        self.toonHead.getGeomNode().setDepthTest(1)
        self.toonHead.loop('neutral')
        self.toonHead.setPosHprScale(-0.73, 0, -1.27, 180, 0, 0, 0.18, 0.18, 0.18)
        self.toonHead.reparentTo(hidden)
        self.toonHead.startBlink()
        self.cogHead = Suit.Suit()
        self.cogDNA = SuitDNA.SuitDNA()
        self.cogDNA.newSuit('ms')
        self.cogHead.setDNA(self.cogDNA)
        self.cogHead.getGeomNode().setDepthWrite(1)
        self.cogHead.getGeomNode().setDepthTest(1)
        self.cogHead.loop('neutral')
        self.cogHead.setPosHprScale(-0.73, 0, -1.46, 180, 0, 0, 0.14, 0.14, 0.14)
        self.cogHead.reparentTo(hidden)
        self.clipPlane = self.toonHead.attachNewNode(PlaneNode('clip'))
        self.clipPlane.node().setPlane(Plane(0, 0, 1, 0))
        self.clipPlane.setPos(0, 0, 2.45)
        audioMgr = base.cogdoGameAudioMgr
        self._cogDialogueSfx = audioMgr.createSfx('cogDialogue')
        self._toonDialogueSfx = audioMgr.createSfx('toonDialogue')
        suitData = Globals.SuitData[Globals.SuitTypes.Boss]
        bossSuit = Suit.Suit()
        bossSuit.nametag3d.stash()
        bossSuit.nametag.destroy()
        d = SuitDNA.SuitDNA()
        d.newSuit('ms')
        bossSuit.setDNA(d)
        bossSuit.setScale(suitData['scale'])
        bossSuit.loop('neutral')
        bossSuit.reparentTo(render)
        bossSuit.setPos(self._exit, -5, -5, 0)
        bossSuit.lookAt(self._exit)
        self._suits.append(bossSuit)
        self._camHelperNode = NodePath('CamHelperNode')
        self._camHelperNode.reparentTo(render)
        dialogue = TTLocalizer.CogdoMazeIntroMovieDialogue
        introDuration = Globals.IntroDurationSeconds
        waitDuration = introDuration / len(dialogue)

        def start():
            camera.wrtReparentTo(render)
            self._exit.open(animate=False)

        def showBoss():
            self._setCamTarget(bossSuit, 20, offset=Point3(0, 0, 7), angle=Point3(0, 15, 0))
            bossSuit.loop('victory')
            self._state = 1

        def showExit():
            self._setCamTarget(self._exit, 10, offset=Point3(0, 0, 0), angle=Point3(0, 60, 0))
            self._exit.close()
            self._state = 2

        showExitIval = Parallel(camera.posInterval(waitDuration * 0.5, (10, -25, 20), other=self._exit, blendType='easeInOut'), Sequence(Wait(waitDuration * 0.25), Func(bossSuit.play, 'effort'), camera.hprInterval(waitDuration * 0.25, (30, -30, 0), blendType='easeInOut'), Func(self._exit.close), Wait(waitDuration * 0.5)))

        def showWaterCooler():
            wc = self._maze.getWaterCoolers()[0]
            self._setCamTarget(wc, 25, angle=Point3(-30, 60, 0))
            camera.wrtReparentTo(self._camHelperNode)
            self._state = 3

        def end():
            self._stopUpdateTask()

        self._ival = Sequence(Func(start), Func(self.displayLine, 'toon', self._getRandomLine(dialogue[0])), showExitIval, Func(showWaterCooler), Func(self.displayLine, 'toon', self._getRandomLine(dialogue[1])), Wait(waitDuration), Func(showBoss), bossSuit.hprInterval(1.0, bossSuit.getHpr() + Point3(180, 0, 0), blendType='easeInOut'), Func(self.displayLine, 'toon', self._getRandomLine(dialogue[2])), Wait(waitDuration - 1.0), Func(end))
        self._startUpdateTask()
Example #37
0
def getWheel():
    return wheel.copyTo(NodePath())
Example #38
0
    def load(self):
        self.notify.debug('load()')
        CogdoGameMovie.load(self)
        backgroundGui = loader.loadModel(
            'phase_5/models/cogdominium/tt_m_gui_csa_flyThru')
        self.bg = backgroundGui.find('**/background')
        self.chatBubble = backgroundGui.find('**/chatBubble')
        self.chatBubble.setScale(6.5, 6.5, 7.3)
        self.chatBubble.setPos(0.32, 0, -0.78)
        self.bg.setScale(5.2)
        self.bg.setPos(0.14, 0, -0.6667)
        self.bg.reparentTo(aspect2d)
        self.chatBubble.reparentTo(aspect2d)
        self.frame = DirectFrame(geom=self.bg,
                                 relief=None,
                                 pos=(0.2, 0, -0.6667))
        self.bg.wrtReparentTo(self.frame)
        self.gameTitleText = DirectLabel(
            parent=self.frame,
            text=TTLocalizer.CogdoExecutiveSuiteTitle,
            scale=TTLocalizer.MRPgameTitleText * 0.8,
            text_align=TextNode.ACenter,
            text_font=getSignFont(),
            text_fg=(1.0, 0.33, 0.33, 1.0),
            pos=TTLocalizer.MRgameTitleTextPos,
            relief=None)
        self.chatBubble.wrtReparentTo(self.frame)
        self.frame.hide()
        backgroundGui.removeNode()
        self.toonDNA = ToonDNA.ToonDNA()
        self.toonDNA.newToonFromProperties('dss', 'ss', 'm', 'm', 2, 0, 2, 2,
                                           1, 8, 1, 8, 1, 14)
        self.toonHead = Toon.Toon()
        self.toonHead.setDNA(self.toonDNA)
        self.makeSuit('sc')
        self.toonHead.getGeomNode().setDepthWrite(1)
        self.toonHead.getGeomNode().setDepthTest(1)
        self.toonHead.loop('neutral')
        self.toonHead.setPosHprScale(-0.73, 0, -1.27, 180, 0, 0, 0.18, 0.18,
                                     0.18)
        self.toonHead.reparentTo(hidden)
        self.toonHead.startBlink()
        self.clipPlane = self.toonHead.attachNewNode(PlaneNode('clip'))
        self.clipPlane.node().setPlane(Plane(0, 0, 1, 0))
        self.clipPlane.setPos(0, 0, 2.45)
        self._toonDialogueSfx = loader.loadSfx(
            'phase_3.5/audio/dial/AV_dog_long.mp3')
        self._camHelperNode = NodePath('CamHelperNode')
        self._camHelperNode.reparentTo(render)
        dialogue = TTLocalizer.CogdoExecutiveSuiteIntroMessage

        def start():
            self.frame.show()
            base.setCellsAvailable(
                base.bottomCells + base.leftCells + base.rightCells, 0)

        def showShopOwner():
            self._setCamTarget(self._shopOwner, -10, offset=Point3(0, 0, 5))

        def end():
            self._dialogueLabel.reparentTo(hidden)
            self.toonHead.reparentTo(hidden)
            self.frame.hide()
            base.setCellsAvailable(
                base.bottomCells + base.leftCells + base.rightCells, 1)
            self._stopUpdateTask()

        self._ival = Sequence(
            Func(start), Func(self.displayLine, dialogue), Func(showShopOwner),
            ParallelEndTogether(
                camera.posInterval(self.cameraMoveDuration,
                                   Point3(8, 0, 13),
                                   blendType='easeInOut'),
                camera.hprInterval(0.5,
                                   self._camHelperNode.getHpr(),
                                   blendType='easeInOut')),
            Wait(self.introDuration), Func(end))
        self._startUpdateTask()
        return
Example #39
0
def generateHullCache(modelClass):
    geom = loader.loadModel('models/shipparts/pir_m_shp_%s' % HullDict[modelClass])
    stripPrefix(geom, 'model:')
    for node in geom.findAllMatches('**/omit'):
        parent = node.getParent()
        omit = parent.attachNewNode(ModelNode('omit'))
        node.reparentTo(omit)
        node.setName('geom')
    
    preFlatten(geom)
    logic = loader.loadModel('models/shipparts/pir_m_shp_%s_logic' % HullDict[modelClass])
    locators = logic.find('**/locators')
    for side in [
        'left',
        'right']:
        bad = locators.find('**/location_ropeLadder_0_%s' % side)
        if bad:
            bad.setName('location_ropeLadder_%s_0' % side)
        
        bad = locators.find('**/location_ropeLadder_1_%s' % side)
        if bad:
            bad.setName('location_ropeLadder_%s_1' % side)
        
        bad = locators.find('**/location_ropeLadder_1_%s1' % side)
        if bad:
            bad.setName('location_ropeLadder_%s_2' % side)
    
    collisions = logic.find('**/collisions')
    badPanel = collisions.find('**/collision_panel_3')
    if badPanel:
        badPanel.setName('collision_panel_2')
    
    collisions.find('**/collision_panel_0').setTag('Hull Code', '0')
    collisions.find('**/collision_panel_1').setTag('Hull Code', '1')
    collisions.find('**/collision_panel_2').setTag('Hull Code', '2')
    walls = collisions.find('**/collision_walls')
    if walls:
        walls.setTag('Hull Code', '255')
    else:
        collisions.attachNewNode('collision_walls')
    shipToShipCollide = collisions.find('**/collision_shiptoship')
    shipToShipCollide.setCollideMask(PiratesGlobals.ShipCollideBitmask)
    deck = collisions.find('**/collision_deck')
    if not deck:
        deck = collisions.attachNewNode('deck')
    
    mask = deck.getCollideMask()
    mask ^= PiratesGlobals.FloorBitmask
    mask |= PiratesGlobals.ShipFloorBitmask
    deck.setCollideMask(mask)
    floors = collisions.find('**/collision_floors')
    if not floors:
        floors = collisions.find('**/collision_floor')
    
    mask = floors.getCollideMask()
    mask ^= PiratesGlobals.FloorBitmask
    mask |= PiratesGlobals.ShipFloorBitmask
    floors.setCollideMask(mask)
    floors.setTag('Hull Code', str(255))
    geomHigh = geom.find('**/lod_high')
    geomMed = geom.find('**/lod_medium')
    if not geomMed:
        geomMed = geom.find('**/low_medium')
    
    if not geomMed:
        geomMed = geomHigh.copyTo(NodePath())
    
    geomLow = geom.find('**/lod_low')
    if not geomLow:
        geomLow = geomMed.copyTo(NodePath())
    
    geomSuperLow = geom.find('**/lod_superlow')
    if not geomSuperLow:
        geomSuperLow = geomLow.copyTo(NodePath())
    
    geomHigh.setName('high')
    geomMed.setName('med')
    geomLow.setName('low')
    geomSuperLow.setName('superlow')
    if modelClass in [
        21,
        22,
        23]:
        spike = loader.loadModel('models/shipparts/pir_m_shp_ram_spike')
        spikeTrans = locators.find('**/location_ram').getTransform(locators)
        spike.setTransform(spikeTrans)
        spike.flattenLight()
        spikeHi = spike.find('**/lod_high')
        spikeMed = spike.find('**/lod_medium')
        spikeLow = spike.find('**/lod_low')
        spikeHi.copyTo(geomHigh)
        spikeMed.copyTo(geomMed)
        spikeLow.copyTo(geomLow)
        spikeLow.copyTo(geomSuperLow)
    
    flipRoot = NodePath('root')
    collisions.reparentTo(flipRoot)
    locators.reparentTo(flipRoot)
    geomHigh.reparentTo(flipRoot)
    geomMed.reparentTo(flipRoot)
    geomLow.reparentTo(flipRoot)
    geomSuperLow.reparentTo(flipRoot)
    flipRoot.setH(180)
    flipRoot.flattenLight()
    omits = flipRoot.findAllMatches('**/omit')
    for node in omits:
        node.flattenStrong()
    
    for group in [
        'static',
        'transparent',
        'ropeLadder_*',
        'stripeA',
        'stripeB',
        'pattern']:
        for node in flipRoot.findAllMatches('**/%s' % group):
            name = node.getName()
            for subNode in node.findAllMatches('**/*'):
                subNode.setName(name)
            
            node.flattenStrong()
            node.setName(name)
        
    
    geomHigh.detachNode()
    geomMed.detachNode()
    geomLow.detachNode()
    geomSuperLow.detachNode()
    locators.detachNode()
    collisions.detachNode()
    genericGeoms = [
        geomHigh,
        geomMed,
        geomLow,
        geomSuperLow]
    customGeoms = [ x.copyTo(NodePath()) for x in genericGeoms ]
    for np in genericGeoms:
        trans = np.find('**/transparent')
        if trans:
            trans.stash()
        
        np.flattenLight()
        sails = np.findAllMatches('**/sails')
        sails.stash()
        omits = np.findAllMatches('**/omit')
        omits.stash()
        for node in omits:
            node.node().setPreserveTransform(node.node().PTDropNode)
        
        generic = NodePath('generic')
        np.findAllMatches('**/+GeomNode').wrtReparentTo(generic)
        np.findAllMatches('*').detach()
        generic.flattenStrong()
        generic.reparentTo(np)
        stripAttribs(generic, TextureAttrib)
        stripAttribs(generic, TransparencyAttrib)
        stripAttribs(generic, CullBinAttrib)
        generic.setBin('ground', 1)
        collapse(generic)
        sails.unstash()
        sails.reparentTo(np)
        for node in sails:
            node.node().setPreserveTransform(node.node().PTDropNode)
        
        if trans:
            trans.unstash()
            trans.flattenStrong()
            if trans.node().isOfType(ModelNode.getClassType()):
                trans.node().setPreserveTransform(ModelNode.PTDropNode)
            
        
        deck = np.find('**/=cam=shground')
        if deck:
            deck.setName('deck')
        
        omits.unstash()
    
    for np in customGeoms:
        collapse(np.find('**/static'))
    
    data = HullCache()
    data.root = NodePath('hull')
    data.genericGeoms = genericGeoms
    data.customGeoms = customGeoms
    data.collisions = collisions
    data.locators = locators
    return data
class CogdoFlyingLevelQuadrant:
    notify = directNotify.newCategory('CogdoFlyingLevelQuadrant')

    def __init__(self, serialNum, model, level, parent):
        self.serialNum = serialNum
        self._model = model
        self._level = level
        self._root = NodePath('Quadrant' + repr(serialNum))
        self._model.reparentTo(self._root)
        self._root.reparentTo(parent)
        self._visible = True
        self.platforms = {}
        self.gatherables = []
        self.obstacles = []
        self._playing = False
        self._obstaclesRoot = NodePath('obstacles')
        self._obstaclesRoot.reparentTo(self._root)
        self._initObstacles(self._obstaclesRoot)
        self._gatherablesRoot = NodePath('gatherables')
        self._gatherablesRoot.reparentTo(self._root)
        self._initGatherables(self._gatherablesRoot)
        self._platformsRoot = NodePath('platforms')
        self._platformsRoot.reparentTo(self._model)
        self._initPlatforms(self._platformsRoot)
        self._optimize()
        self.place()

    def _optimize(self):
        lightCones = NodePath('lightCones')
        for np in self._platformsRoot.findAllMatches('**/*lightCone*'):
            np.wrtReparentTo(lightCones)

        lightCones.reparentTo(self._model)
        node = self._model.find('**/ducts')
        if not node.isEmpty():
            node.flattenStrong()
            for np in node.getChildren():
                np.wrtReparentTo(self._model)

        node = self._model.find('**/nests')
        if not node.isEmpty():
            for np in node.getChildren():
                np.flattenStrong()
                np.wrtReparentTo(self._model)

        for np in self._model.findAllMatches('**/*LayerStack*'):
            np.wrtReparentTo(self._model)

        if not self._model.find('**/static').isEmpty():
            for np in self._model.find('**/static').getChildren():
                np.wrtReparentTo(self._model)

        self._model.flattenMedium()

    def _initPlatforms(self, parent):
        platformModels = self._model.findAllMatches('**/%s' %
                                                    Globals.Level.PlatformName)
        for platformModel in platformModels:
            platform = CogdoFlyingPlatform(platformModel, parent=parent)
            self.platforms[platform.getName()] = platform

    def _destroyPlatforms(self):
        for platform in list(self.platforms.values()):
            platform.destroy()

        del self.platforms

    def _initGatherables(self, parent):
        self.generateGatherables(self._model, parent=parent)
        if Globals.Level.SpawnLaffPowerupsInNests:
            self.generateNestPowerups(self._model, parent=parent)

    def generateNestPowerups(self, gatherableModel, parent):
        nests = gatherableModel.findAllMatches(
            '**/%s;+s' % Globals.Level.LegalEagleNestName)
        for nest in nests:
            offset = Globals.Level.LaffPowerupNestOffset
            pickup = self._level.gatherableFactory.createPowerup(
                Globals.Level.GatherableTypes.LaffPowerup)
            pickup.reparentTo(parent)
            pickup.setPos(parent, nest.getPos(parent) + offset)
            if Globals.Level.AddSparkleToPowerups:
                sparkles = self._level.gatherableFactory.createSparkles(
                    Vec4(1, 1, 1, 1), Vec4(1, 1, 0, 1), 10.0)
                sparkles.reparentTo(pickup)
                sparkles.setPos(0, 0, 1)
                sparkles.start()
            self.gatherables.append(pickup)

    def generateGatherables(self,
                            gatherableModel,
                            parent=None,
                            spread=Globals.Level.GatherablesDefaultSpread):
        parent = parent or self._root
        mopath = Mopath.Mopath(name='gatherables')

        def generateMemos():
            gatherPaths = gatherableModel.findAllMatches(
                '**/%s' % Globals.Level.GatherablesPathName)
            for gatherPath in gatherPaths:
                mopath.loadNodePath(gatherPath)
                t = 0.0
                while t < mopath.getMaxT():
                    pickup = self._level.gatherableFactory.createMemo()
                    pickup.reparentTo(parent)
                    mopath.goTo(pickup, t)
                    self.gatherables.append(pickup)
                    t += spread

                gatherPath.removeNode()

            angleSpread = 360.0 / Globals.Level.NumMemosInRing
            gatherPaths = gatherableModel.findAllMatches(
                '**/%s' % Globals.Level.GatherablesRingName)
            for gatherPath in gatherPaths:
                mopath.loadNodePath(gatherPath)
                t = 0.0
                while t < mopath.getMaxT():
                    angle = 0
                    r = 3
                    while angle < 360.0:
                        pickup = self._level.gatherableFactory.createMemo()
                        pickup.reparentTo(parent)
                        mopath.goTo(pickup, t)
                        pickup.setX(
                            parent,
                            pickup.getX() + r * math.cos(math.radians(angle)))
                        pickup.setZ(
                            parent,
                            pickup.getZ() + r * math.sin(math.radians(angle)))
                        self.gatherables.append(pickup)
                        angle += angleSpread

                    t += spread + 0.5

                gatherPath.removeNode()

        def generatePropellers():
            gatherables = gatherableModel.findAllMatches(
                '**/%s' % Globals.Level.PropellerName)
            for gatherable in gatherables:
                pickup = self._level.gatherableFactory.createPropeller()
                pickup.reparentTo(gatherable.getParent())
                pickup.setPos(parent, gatherable.getPos(parent))
                self.gatherables.append(pickup)
                gatherable.removeNode()

        def generatePowerUps():
            for powerupType, locName in Globals.Level.PowerupType2Loc.items():
                gatherables = gatherableModel.findAllMatches('**/%s' % locName)
                for gatherable in gatherables:
                    pickup = self._level.gatherableFactory.createPowerup(
                        powerupType)
                    pickup.reparentTo(parent)
                    pickup.setPos(parent, gatherable.getPos(parent))
                    if Globals.Level.AddSparkleToPowerups:
                        sparkles = self._level.gatherableFactory.createSparkles(
                            Vec4(1, 1, 1, 1), Vec4(1, 1, 0, 1), 10.0)
                        sparkles.reparentTo(pickup)
                        sparkles.setPos(0, 0, 1)
                        sparkles.start()
                    self.gatherables.append(pickup)
                    gatherable.removeNode()

        generateMemos()
        generatePropellers()
        generatePowerUps()

    def _initObstacles(self, parent):
        def initWhirlwinds():
            obstacles = self._root.findAllMatches('**/%s' %
                                                  Globals.Level.WhirlwindName)
            for obstacleLoc in obstacles:
                motionPath = self._model.find(
                    '**/%s%s' %
                    (obstacleLoc.getName(), Globals.Level.WhirlwindPathName))
                if motionPath.isEmpty():
                    motionPath = None
                obstacle = self._level.obstacleFactory.createWhirlwind(
                    motionPath=motionPath)
                obstacle.model.reparentTo(parent)
                obstacle.model.setPos(parent, obstacleLoc.getPos(parent))
                self.obstacles.append(obstacle)
                obstacleLoc.removeNode()

            return

        def initStreamers():
            obstacles = self._model.findAllMatches('**/%s' %
                                                   Globals.Level.StreamerName)
            for obstacleLoc in obstacles:
                obstacle = self._level.obstacleFactory.createFan()
                obstacle.model.reparentTo(parent)
                obstacle.model.setPos(parent, obstacleLoc.getPos(parent))
                obstacle.model.setHpr(parent, obstacleLoc.getHpr(parent))
                obstacle.model.setScale(parent, obstacleLoc.getScale(parent))
                obstacle.setBlowDirection()
                if Globals.Level.AddParticlesToStreamers:
                    particles = self._level.obstacleFactory.createStreamerParticles(
                        Vec4(1, 1, 1, 1), Vec4(1, 1, 1, 1), 10.0)
                    particles.reparentTo(obstacle.model)
                    particles.start()
                self.obstacles.append(obstacle)
                obstacleLoc.removeNode()

        def initWalkingMinions():
            motionPaths = self._model.findAllMatches(
                '**/%s' % Globals.Level.MinionWalkingPathName)
            for motionPath in motionPaths:
                obstacle = self._level.obstacleFactory.createWalkingMinion(
                    motionPath=motionPath)
                obstacle.model.reparentTo(parent)
                obstacle.model.setPos(parent, motionPath.getPos(parent))
                self.obstacles.append(obstacle)

        def initFlyingMinions():
            motionPaths = self._model.findAllMatches(
                '**/%s' % Globals.Level.MinionFlyingPathName)
            for motionPath in motionPaths:
                obstacle = self._level.obstacleFactory.createFlyingMinion(
                    motionPath=motionPath)
                obstacle.model.reparentTo(parent)
                obstacle.model.setPos(parent, motionPath.getPos(parent))
                self.obstacles.append(obstacle)

        initWhirlwinds()
        initStreamers()
        initWalkingMinions()
        initFlyingMinions()

    def place(self):
        self._root.setPos(0, self._level.convertQuadNumToY(self.serialNum), 0)

    def destroy(self):
        if self._visible:
            self.offstage()
        self._destroyPlatforms()
        for obstacle in self.obstacles:
            obstacle.destroy()

        for gatherable in self.gatherables:
            gatherable.destroy()

        self._root.removeNode()
        del self._root
        del self._gatherablesRoot
        del self._obstaclesRoot
        del self._platformsRoot
        del self._level

    def onstage(self, elapsedTime=0.0):
        if self._visible:
            return
        self._root.unstash()
        for obstacle in self.obstacles:
            obstacle.startMoving(elapsedTime)

        for gatherable in self.gatherables:
            gatherable.show()

        self._visible = True

    def offstage(self):
        if not self._visible:
            return
        self._root.stash()
        for obstacle in self.obstacles:
            obstacle.stopMoving()

        for gatherable in self.gatherables:
            gatherable.hide()

        self._visible = False

    def update(self, dt):
        if self._visible:
            for gatherable in self.gatherables:
                gatherable.update(dt)

            for obstacle in self.obstacles:
                obstacle.update(dt)

    def getModel(self):
        return self._root
Example #41
0
 def getAsset(self):
     return (self.high.copyTo(NodePath()), self.med.copyTo(NodePath()), self.low.copyTo(NodePath()))
Example #42
0
def generateMastCache(mastClass):
    data = MastCache()
    prefix = MastData[mastClass]['prefix']
    height = MastData[mastClass]['maxHeight']
    model_prefix = 'models/char/pir_r_shp_mst_%s' % prefix
    anim_prefix = 'models/char/pir_a_shp_mst_%s_' % prefix
    geom = loader.loadModel(model_prefix).find('**/+Character')
    stripPrefix(geom, 'model:')
    if mastClass == ShipGlobals.Masts.Fore_Multi:
        geom.findAllMatches('**/sail_0*').detach()
        for name in ('_1', '_1_rope', '_2', '_2_rope'):
            for node in geom.findAllMatches('**/boom%s' % name):
                node.setName('boom')
            
        
    
    preFlatten(geom)
    if mastClass in (6, 7, 8, 9, 10):
        for node in geom.findAllMatches('**/sail_0'):
            node.setName('skel_sail_0')
        
        for node in geom.findAllMatches('**/sail_1'):
            node.setName('skel_sail_1')
        
        for node in geom.findAllMatches('**/sail_2'):
            node.setName('skel_sail_2')
        
    
    for node in geom.findAllMatches('**/sail_0'):
        stripAttribs(node, TextureAttrib)
    
    for node in geom.findAllMatches('**/sail_1'):
        stripAttribs(node, TextureAttrib)
    
    for node in geom.findAllMatches('**/sail_2'):
        stripAttribs(node, TextureAttrib)
    
    geomSet = [
        geom.find('**/lod_high'),
        geom.find('**/lod_medium'),
        geom.find('**/lod_low'),
        geom.find('**/lod_superlow')]
    tex = geomSet[0].find('**/static').findAllTextures('*')[0]
    logic = loader.loadModel(model_prefix + '_logic')
    stripPrefix(logic, 'model:')
    data.collisions = logic.find('**/collisions')
    if not data.collisions.find('**/collision_masts'):
        data.collisions.find('**/collision_mast_0').setName('collision_masts')
    
    sails = data.collisions.findAllMatches('**/collision_sails')
    for node in sails:
        node.setTag('Sail', '1')
    
    sails.wrtReparentTo(data.collisions.find('**/collision_masts'))
    geomSet[0].setName('high')
    geomSet[1].setName('med')
    geomSet[2].setName('low')
    geomSet[3].setName('superlow')
    data.charRoot = geom.node()
    data.breakAnim = (anim_prefix + 'break', anim_prefix + 'broken')
    data.hitAnim = anim_prefix + 'hit'
    for anim in metaAnims:
        data.metaAnims[anim] = anim_prefix + anim
    
    geom.findAllMatches('**/rigging_anchors').detach()
    geom.findAllMatches('**/breaks').detach()
    geom.findAllMatches('**/def_mast_base').detach()
    height = MastData[mastClass]['maxHeight']
    matchSet = range(height)
    for i in range(height):
        matchSet = _[1]
        reducedSet = []
        foundReduction = False
        for j in range(len(geomSet)):
            currGeom = geomSet[j].copyTo(NodePath())
            for match in matchSet:
                cruft = currGeom.findAllMatches('**/*_%s*' % match)
                if cruft:
                    cruft.detach()
                    foundReduction = True
                []
            
            if foundReduction or not matchSet:
                for group in [
                    'static',
                    'transparent']:
                    for node in currGeom.findAllMatches('**/%s' % group):
                        node.flattenStrong()
                        node.setName(group)
                    
                
                reducedSet.append(currGeom)
        
        customSet = []
        for np in reducedSet:
            sails = np.find('**/sails;+s')
            if not sails:
                np.attachNewNode(ModelNode('sails'))
            
            customSet.append(np.copyTo(NodePath()))
        
        for np in reducedSet:
            np.find('static').node().setPreserveTransform(ModelNode.PTDropNode)
            np.find('custom').node().setPreserveTransform(ModelNode.PTDropNode)
            np.find('**/sails').node().setPreserveTransform(ModelNode.PTDropNode)
            np.flattenStrong()
            trans = np.findAllMatches('**/transparent')
            if trans:
                for node in trans:
                    node.node().setPreserveTransform(ModelNode.PTDropNode)
                    node.stash()
                
                stripAttribs(np, TextureAttrib)
                for node in trans:
                    node.unstash()
                
            stripAttribs(np, TextureAttrib)
        
        for np in customSet:
            np.flattenStrong()
            np.find('static').node().setPreserveTransform(ModelNode.PTDropNode)
            np.find('custom').node().setPreserveTransform(ModelNode.PTDropNode)
            np.find('**/sails').node().setPreserveTransform(ModelNode.PTDropNode)
            trans = np.findAllMatches('**/transparent')
            if trans:
                for node in trans:
                    node.node().setPreserveTransform(ModelNode.PTDropNode)
                    node.stash()
                
                stripAttribs(np, TextureAttrib)
                for node in trans:
                    node.unstash()
                
        
        data.genericGeomSets.append(reducedSet)
        data.customGeomSets.append(customSet)
    
    NodePath(data.charRoot).removeChildren()
    data.collisions.reparentTo(NodePath(data.charRoot))
    return data