def __init__(self,table=None,mask=None):
     """
     @keyword table: filename of a table texture. See table_template.psd. Either
                     paint anywhere inside the mask for a complete background
                     or turn off the pads and spinner and paint in the table circle
                     for just a table texture that will have spinners and pads
                     put on top of it.
     @type mask: str
     @keyword mask: filename of a mask texture of the non-Jam-o-Drum area. probably
                    jod_mask.png that comes with the Jam-o-Drum library.
     @type mask: str
     """
     NodePath.__init__(self,"JamoDrum")
     
     totalHeight = max(1.0,math.sqrt(2)/4.0+SPINNER_RADIUS)*2
     
     cm = CardMaker("card")
     cm.setFrame(-1,1,-1,1)
     self.tableCard = self.attachNewNode(cm.generate())
     self.tableCard.setP(-90)
     self.tableCard.setScale(4.0/3.0)
     self.tableCard.setLightOff()
     self.tableCard.setBin("background",0)
     self.tableCard.setDepthTest(0)
     self.tableCard.setDepthWrite(0)
     self.tableCard.hide()
     
     if (table):
         self.setTableTexture(loader.loadTexture(table))
                    
     
     if (mask):
         cm = CardMaker("JOD Mask")
         cm.setFrame(-4.0/3.0,4.0/3.0,-4.0/3.0,4.0/3.0)
         self.mask = aspect2d.attachNewNode(cm.generate())
         #self.mask.setP(-90)
         self.mask.setTexture(loader.loadTexture(mask),1)
         self.mask.setTransparency(1)
         self.mask.setDepthTest(0)
     else:
         self.mask = None
     
     self.stations = []
     for i in range(4):
         station = Station(self,i)
         station.reparentTo(self)
         self.stations.append(station)
     
     self.reparentTo(render)
     base.disableMouse()
     self.lens = OrthographicLens()
     self.lens.setFilmSize(totalHeight*base.getAspectRatio(),totalHeight)
     base.cam.node().setLens(self.lens)
     camera.setPosHpr(0,0,10.0, 0,-90,0)
     base.setBackgroundColor(0,0,0)
     
     self.audio3d = Audio3DManager(base.sfxManagerList[0],self)
     self.audio3d.setDropOffFactor(0)
Ejemplo n.º 2
0
 def _initGUI(self):
     base.loadingScreen.beginStep('init Gui', 4, 55)
     cm = CardMaker('PotionBackground')
     cm.setFrame(-10, 10, -10, 10)
     cm.setColor(0, 0, 0, 1)
     self.background = NodePath(cm.generate())
     self.background.reparentTo(aspect2d)
     self.background.setBin('background', -100)
     self.xpBackground = NodePath('PotionXPBackground')
     self.xpBackground.reparentTo(aspect2d)
     self.xpBackground.setBin('background', -95)
     base.loadingScreen.tick()
     self.dialogs = NodePath('DialogBackground')
     self.dialogs.reparentTo(aspect2d)
     self.dialogs.setBin('background', -70)
     self.buttonsBackground = NodePath('PotionButtonBackground')
     self.buttonsBackground.reparentTo(base.a2dBottomRight)
     self.buttonsBackground.setBin('background', -90)
     textureCard = loader.loadModel('models/minigames/pir_m_gui_pot_textureCard')
     self.stretchedBackgroundTextureCard = textureCard.find('**/pir_t_gui_pot_background')
     self.stretchedBackgroundTextureCard.reparentTo(self.background)
     self.stretchedBackgroundTextureCard.setScale(3.3999999999999999, 1.0, 3.3999999999999999)
     self.stretchedBackgroundTextureCard.setPos(0.0, 20.0, 0.0)
     fadecm = CardMaker('card')
     fadecm.setFrameFullscreenQuad()
     self.fadeIn = render2d.attachNewNode(fadecm.generate())
     self.fadeIn.setBin('background', -50)
     self.fadeIn.setPos(0.0, -30.0, 0.0)
     self.fadeIn.setColor(0, 0, 0, 1.0)
     self.fadeIn.setTransparency(True)
     base.loadingScreen.tick()
     cm = CardMaker('card')
     cm.setFrame(0, 1, 0.01, 0.01)
     self.foregroundLayer = aspect2d.attachNewNode(cm.generate())
     self.foregroundTextureCard = textureCard.find('**/pir_t_gui_pot_foreground')
     self.foregroundTextureCard.setScale(0.80000000000000004, 1.0, 0.40000000000000002)
     self.foregroundTextureCard.setPos(-0.69999999999999996, -20.0, 0.80000000000000004)
     self.foregroundTextureCard.setBin('background', -80)
     self.foregroundTextureCard.copyTo(self.foregroundLayer)
     self.repMeter = ReputationMeter.ReputationMeter(InventoryType.PotionsRep, width = 0.56000000000000005)
     inv = localAvatar.getInventory()
     self.repMeter.reparentTo(self.xpBackground)
     self.repMeter.setPos(0, 0, -0.94999999999999996)
     self.repMeter.update(inv.getAccumulator(InventoryType.PotionsRep))
     localAvatar.guiMgr.registerReputationHandler(self.updateRepMeter)
     base.loadingScreen.tick()
     self.closeButton = GuiButton.GuiButton(image = (textureCard.find('**/pir_t_gui_pot_escape'), textureCard.find('**/pir_t_gui_pot_escapeOn'), textureCard.find('**/pir_t_gui_pot_escapeOn'), textureCard.find('**/pir_t_gui_pot_escape')), image_scale = (0.10000000000000001, 0.10000000000000001, 0.10000000000000001), image_pos = (0.074999999999999997, 0, 0.080000000000000002), hotkeys = [
         'Escape'], hotkeyLabel = PLocalizer.PotionGui['ExitButton'], pos = (-0.40000000000000002, 0.0, 0.01), text0_fg = PotionGlobals.TextColor, text1_fg = PiratesGuiGlobals.TextFG0, text2_fg = PiratesGuiGlobals.TextFG15, text3_fg = PotionGlobals.TextColorDisabled, parent = self.buttonsBackground, command = self.confirmQuit)
     self.returnButton = GuiButton.GuiButton(text = (PLocalizer.PotionGui['SwitchRecipe'], PLocalizer.PotionGui['SwitchRecipe'], PLocalizer.PotionGui['SwitchRecipe'], PLocalizer.PotionGui['SwitchRecipe']), pos = (-0.57999999999999996, 0.0, -0.62), text_scale = PiratesGuiGlobals.TextScaleExtraLarge, text_shadow = None, image = (None, None, None, None), text0_fg = PotionGlobals.TextColor, text1_fg = PiratesGuiGlobals.TextFG0, text2_fg = PiratesGuiGlobals.TextFG15, text3_fg = PotionGlobals.TextColorDisabled, parent = self.background, command = self.confirmReturn)
     self.returnButton.stash()
     self.hintsButton = GuiButton.GuiButton(text = (PLocalizer.PotionGui['ShowTutorial'], PLocalizer.PotionGui['ShowTutorial'], PLocalizer.PotionGui['ShowTutorial'], PLocalizer.PotionGui['ShowTutorial']), text_scale = PiratesGuiGlobals.TextScaleSmall, image_scale = (0.25, 0.10000000000000001, 0.17999999999999999), image_pos = (0, 0, 0), pos = (-0.53000000000000003, 0.0, 0.074999999999999997), parent = self.buttonsBackground, command = self.showLastHint)
     self.InfoButton = GuiButton.GuiButton(text = (PLocalizer.PotionGui['IngredientList'], PLocalizer.PotionGui['IngredientList'], PLocalizer.PotionGui['IngredientList'], PLocalizer.PotionGui['IngredientList']), text_scale = PiratesGuiGlobals.TextScaleSmall, image_scale = (0.29999999999999999, 0.10000000000000001, 0.17999999999999999), image_pos = (0, 0, 0), pos = (-0.83999999999999997, 0.0, 0.074999999999999997), parent = self.buttonsBackground, command = self.showInfo)
     textureCard.removeNode()
     base.loadingScreen.endStep('init Gui')
Ejemplo n.º 3
0
 def make_vertical_wall(self, pos):
     x, y = pos
     cm = CardMaker("wall")
     cm.setFrame(0, 1, 0, 2)
     front_card = cm.generate()
     front = self.render.attachNewNode(front_card)
     front.setH(0)
     front.setPos(x,y,0)
     back_card = cm.generate()
     back = self.render.attachNewNode(back_card)
     back.setH(180)
     back.setPos(x+1,y,0)
	def __init__(self):
		self.ticks=0

		base.setBackgroundColor(224.0/255.0, 188.0/255.0, 112.0/255.0)
		base.camera.setPos(100,100,100)
		self.correctAspectRatio()
		self.titleScreenTrack=loader.loadModel("models/titlescreentrack")
		self.titleScreenTrack.setScale(1.0)
		self.titleScreenTrack.reparentTo(render)
		self.titleScreenTrack.setPos(0.0,-10,-2.5)
		self.trackRotation=0

		self.titleScreenTitle=loader.loadModel("models/gridleader")
		self.titleScreenTitle.setScale(1.0)
		self.titleScreenTitle.setH(180.0)
		self.titleScreenTitle.reparentTo(render)
		self.titleScreenTitle.setPos(0.0,-10,0.3)

		self.titleScreenText=TitleScreenText()

		startLineCm=CardMaker('card')
		# left, right, top, bottom
		startLineCm.setFrame(0,2.25,0,0.6)
		startLineNode=self.titleScreenTrack.attachNewNode(startLineCm.generate())
		startLineNode.setTwoSided(True)
		startLineNode.setBillboardAxis()
		startLineNode.setTransparency(TransparencyAttrib.MAlpha)
		tex=loader.loadTexture('textures/titlestartline.png')
		tex.setWrapU(Texture.WMClamp)
		tex.setWrapV(Texture.WMClamp)
		startLineNode.setTexture(tex)
		startLineNode.setPos(-0.202,1.521,0)
		self.startLineNode=startLineNode

		base.accept('aspectRatioChanged',self.correctAspectRatio)
Ejemplo n.º 5
0
 def announceGenerate(self):
     # TODO - for some reason this is getting called hundreds of times when there are multiple districts
     DistributedObject.DistributedObject.announceGenerate(self)
     self.sendUpdate("enteredParty", [])
     globalClock.syncFrameTime()
     self.startPartyClock()
     base.localAvatar.chatMgr.chatInputSpeedChat.addInsidePartiesMenu()
     self.spawnTitleText()
     messenger.send(self.generatedEvent)
     if config.GetBool("show-debug-party-grid", 0):
         self.testGrid = NodePath("test_grid")
         self.testGrid.reparentTo(base.cr.playGame.hood.loader.geom)
         for i in xrange(len(self.grid)):
             for j in xrange(len(self.grid[i])):
                 cm = CardMaker("gridsquare")
                 np = NodePath(cm.generate())
                 np.setScale(12)
                 np.setP(-90.0)
                 np.setPos(
                     PartyUtils.convertDistanceFromPartyGrid(j, 0) - 6.0,
                     PartyUtils.convertDistanceFromPartyGrid(i, 1) - 6.0,
                     0.1,
                 )
                 np.reparentTo(self.testGrid)
                 if self.grid[i][j]:
                     np.setColorScale(0.0, 1.0, 0.0, 1.0)
                 else:
                     np.setColorScale(1.0, 0.0, 0.0, 1.0)
Ejemplo n.º 6
0
    def __init__( self, *args, **kwargs ):
        colour = kwargs.pop( 'colour', (1, 1, 1, .2) )
        p3d.SingleTask.__init__( self, *args, **kwargs )

        # Create a card maker
        cm = CardMaker( self.name )
        cm.setFrame( 0, 1, 0, 1 )
        
        # Init the node path, wrapping the card maker to make a rectangle
        NodePath.__init__( self, cm.generate() )
        self.setColor( colour )
        self.setTransparency( 1 )
        self.reparentTo( self.root2d )
        self.hide()
        
        # Create the rectangle border
        ls = LineSegs()
        ls.moveTo( 0, 0, 0 )
        ls.drawTo( 1, 0, 0 )
        ls.drawTo( 1, 0, 1 )
        ls.drawTo( 0, 0, 1 )
        ls.drawTo( 0, 0, 0 )
        
        # Attach border to rectangle
        self.attachNewNode( ls.create() )
Ejemplo n.º 7
0
    def __init__(self, av, **kw):
        DirectFrame.__init__(self, relief=None, sortOrder=50)
        self.initialiseoptions(QuestMap)
        self.container = DirectFrame(parent=self, relief=None)
        self.marker = DirectFrame(parent=self.container, relief=None)
        self.cogInfoFrame = DirectFrame(parent=self.container, relief=None)
        cm = CardMaker('bg')
        cm.setFrame(-0.5, 0.5, -0.5, 0.5)
        bg = self.cogInfoFrame.attachNewNode(cm.generate())
        bg.setTransparency(1)
        bg.setColor(0.5, 0.5, 0.5, 0.5)
        bg.setBin('fixed', 0)
        self.cogInfoFrame['geom'] = bg
        self.cogInfoFrame['geom_pos'] = (0, 0, 0)
        self.cogInfoFrame['geom_scale'] = (6, 1, 2)
        self.cogInfoFrame.setScale(0.05)
        self.cogInfoFrame.setPos(0, 0, 0.6)
        self.buildingMarkers = []
        self.av = av
        self.wantToggle = base.config.GetBool('want-toggle-quest-map', True)
        self.updateMarker = True
        self.cornerPosInfo = None
        self.hqPosInfo = None
        self.fishingSpotInfo = None
        self.load()
        self.setScale(1.5)
        bg.removeNode()
        self.hoodId = None
        self.zoneId = None
        self.suitPercentage = {}
        for currHoodInfo in SuitPlannerBase.SuitPlannerBase.SuitHoodInfo:
            tracks = currHoodInfo[SuitPlannerBase.SuitPlannerBase.SUIT_HOOD_INFO_TRACK]
            self.suitPercentage[currHoodInfo[SuitPlannerBase.SuitPlannerBase.SUIT_HOOD_INFO_ZONE]] = tracks

        return
 def genArrow(self, pos, hpr, id):
     factory = CardMaker('factory')
     factory.setFrame(-.5, 0.5, -.5, 0.5)
     arrowNode = factory.generate()
     arrowRoot = NodePath('root')
     baseArrow = NodePath(arrowNode)
     baseArrow.setTransparency(1)
     baseArrow.setTexture(self.boostArrowTexture)
     baseArrow.reparentTo(arrowRoot)
     arrow2 = baseArrow.copyTo(baseArrow)
     arrow2.setPos(0, 0, 1)
     arrow3 = arrow2.copyTo(arrow2)
     arrowRoot.setPos(*pos)
     arrowRoot.setHpr(*hpr)
     baseArrow.setHpr(0, -90, 0)
     baseArrow.setScale(24)
     arrowRoot.reparentTo(self.geom)
     trigger = 'boostArrow' + str(id)
     cs = CollisionTube(Point3(0.6, -6, 0), Point3(0.6, 54, 0), 4.8)
     cs.setTangible(0)
     triggerEvent = 'imIn-' + trigger
     cn = CollisionNode(trigger)
     cn.addSolid(cs)
     cn.setIntoCollideMask(BitMask32(32768))
     cn.setFromCollideMask(BitMask32(32768))
     cnp = NodePath(cn)
     cnp.reparentTo(arrowRoot)
     self.accept(triggerEvent, self.hitBoostArrow)
     arrowVec = arrow2.getPos(self.geom) - baseArrow.getPos(self.geom)
     arrowVec.normalize()
     idStr = str(id)
     cnp.setTag('boostId', idStr)
     self.boostDir[idStr] = arrowVec
     base.arrows.append(arrowRoot)
Ejemplo n.º 9
0
	def __init__(self, name, nrplates, width, height, shaderfile, texturefile, uvlist, jitter=-1):
		self.name = name
		self.texturefile = texturefile
		self.shaderfile = shaderfile
		
		self.np = NodePath('leaf')
		
		self.tex = loader.loadTexture('textures/' + texturefile)
		self.tex.setMinfilter(Texture.FTLinearMipmapLinear)
		self.tex.setMagfilter(Texture.FTLinearMipmapLinear)
		self.tex.setAnisotropDegree(2)
		self.np.setTexture(self.tex)
		self.np.setTwoSided(True)
		self.np.setTransparency(TransparencyAttrib.MAlpha)
		self.np.setDepthWrite(False)
		
		maker = CardMaker('leaf')
		maker.setFrame(-width/2.0, width/2.0, 0, height)
		#maker.setFrame(0,1,0,1)
		for i in range(nrplates):
			if uvlist != None:
				maker.setUvRange(uvlist[i][0], uvlist[i][1])
			else:
				maker.setUvRange(Point2(0,0), Point2(1,0.98))
			node = self.np.attachNewNode(maker.generate())
			#node.setTwoSided(True)
			node.setHpr(i * 180.0 / nrplates,0,0)
		self.np.flattenStrong()
		#np.flattenLight()
		#np.setTwoSided(True)
		
		if jitter == -1:
			self.jitter = height/width/2
		else:
			self.jitter = jitter
Ejemplo n.º 10
0
        def __init__(self, scale=1, value=1, r=1, g=0, b=0):
                NodePath.__init__(self, 'healthbar')

                self.scale = scale
                cmfg = CardMaker('fg')
                cmfg.setFrame(- scale,  scale, -0.1 * scale, 0.1 * scale)
                self.fg = self.attachNewNode(cmfg.generate())

                cmbg = CardMaker('bg') 
                cmbg.setFrame(- scale, scale, -0.1 * scale, 0.1 * scale) 
                self.bg = self.attachNewNode(cmbg.generate()) 

                self.fg.setColor(r, g, b, 1) 
                self.bg.setColor(0.2, 0.2, 0.2, 1) 

                self.setValue(value) 
Ejemplo n.º 11
0
 def _createSimpleMarker(self, size, color = (1, 1, 1)):
     halfSize = size * 0.5
     cm = CardMaker('mazemap_simple_marker')
     cm.setFrame(-halfSize, halfSize, -halfSize, halfSize)
     markerNP = self.maskedLayer.attachNewNode(cm.generate())
     markerNP.setColor(*color)
     return markerNP
 def _initModel(self):
     baseName = '**/tt_t_gui_cmg_miniMap_'
     cardModel = CogdoUtil.loadMazeModel('miniMap_cards', group='gui')
     cm = CardMaker('bg')
     cm.setFrame(-1.1, 1.1, -1.1, 1.1)
     bg = self.attachNewNode(cm.generate())
     bg.setColor(*self._bgColor)
     bg.setBin('fixed', 0)
     frame = cardModel.find(baseName + 'frame')
     frame.reparentTo(self)
     frame.setScale(2.5)
     frame.setPos(0.01, 0, -0.01)
     self._entrance = cardModel.find(baseName + 'entrance')
     self._entrance.reparentTo(self)
     self._entrance.setScale(0.35)
     self._entrance.hide()
     self._exit = NodePath('exit')
     self._exit.setScale(0.35)
     self._exit.reparentTo(self)
     self._exitOpen = cardModel.find(baseName + 'exitOpen')
     self._exitOpen.reparentTo(self._exit)
     self._exitClosed = cardModel.find(baseName + 'exitClosed')
     self._exitClosed.reparentTo(self._exit)
     self._suitMarkerTemplate = cardModel.find(baseName + 'cogIcon')
     self._suitMarkerTemplate.detachNode()
     self._suitMarkerTemplate.setScale(0.225)
     self._waterCoolerTemplate = cardModel.find(baseName + 'waterDrop')
     self._waterCoolerTemplate.detachNode()
     self._waterCoolerTemplate.setScale(0.225)
     self._exit.hide()
     cardModel.removeNode()
Ejemplo n.º 13
0
    def _createMapTextureCard(self):
        mapImage = PNMImage(MAP_RESOLUTION, MAP_RESOLUTION)
        mapImage.fill(*self._bgColor)
        fgColor = VBase4D(*self._fgColor)
        for x in xrange(self._mazeHeight):
            for y in xrange(self._mazeWidth):
                if self._mazeCollTable[y][x] == 1:
                    ax = float(x) / self._mazeWidth * MAP_RESOLUTION
                    invertedY = self._mazeHeight - 1 - y
                    ay = float(invertedY) / self._mazeHeight * MAP_RESOLUTION
                    self._drawSquare(mapImage, int(ax), int(ay), 10, fgColor)

        mapTexture = Texture('mapTexture')
        mapTexture.setupTexture(Texture.TT2dTexture, self._maskResolution, self._maskResolution, 1, Texture.TUnsignedByte, Texture.FRgba)
        mapTexture.setMinfilter(Texture.FTLinear)
        mapTexture.load(mapImage)
        mapTexture.setWrapU(Texture.WMClamp)
        mapTexture.setWrapV(Texture.WMClamp)
        mapImage.clear()
        del mapImage
        cm = CardMaker('map_cardMaker')
        cm.setFrame(-1.0, 1.0, -1.0, 1.0)
        map = self.attachNewNode(cm.generate())
        map.setTexture(mapTexture, 1)
        return map
Ejemplo n.º 14
0
 def loadFlatQuad(self, fullFilename):
     cm = CardMaker("cm-%s" % fullFilename)
     cm.setColor(1.0, 1.0, 1.0, 1.0)
     aspect = base.camLens.getAspectRatio()
     htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH)
     htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT)
     cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0)
     bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1)
     bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1)
     cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1))
     card = cm.generate()
     quad = NodePath(card)
     jpgFile = PNMImage(WEB_WIDTH, WEB_HEIGHT)
     smallerJpgFile = PNMImage()
     readFile = smallerJpgFile.read(Filename(fullFilename))
     if readFile:
         jpgFile.copySubImage(smallerJpgFile, 0, 0)
         guiTex = Texture("guiTex")
         guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba)
         guiTex.setMinfilter(Texture.FTLinear)
         guiTex.load(jpgFile)
         guiTex.setWrapU(Texture.WMClamp)
         guiTex.setWrapV(Texture.WMClamp)
         ts = TextureStage("webTS")
         quad.setTexture(ts, guiTex)
         quad.setTransparency(0)
         quad.setTwoSided(True)
         quad.setColor(1.0, 1.0, 1.0, 1.0)
         result = quad
     else:
         result = None
     Texture.setTexturesPower2(1)
     return result
Ejemplo n.º 15
0
 def setupTexture(self):
     cm = CardMaker('quadMaker')
     cm.setColor(1.0, 1.0, 1.0, 1.0)
     aspect = base.camLens.getAspectRatio()
     htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH)
     htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT)
     cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0)
     bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1)
     bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1)
     cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1))
     card = cm.generate()
     self.quad = NodePath(card)
     self.quad.reparentTo(self.parent)
     self.guiTex = Texture('guiTex')
     self.guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba)
     self.guiTex.setMinfilter(Texture.FTLinear)
     self.guiTex.setKeepRamImage(True)
     self.guiTex.makeRamImage()
     self.guiTex.setWrapU(Texture.WMRepeat)
     self.guiTex.setWrapV(Texture.WMRepeat)
     ts = TextureStage('webTS')
     self.quad.setTexture(ts, self.guiTex)
     self.quad.setTexScale(ts, 1.0, -1.0)
     self.quad.setTransparency(0)
     self.quad.setTwoSided(True)
     self.quad.setColor(1.0, 1.0, 1.0, 1.0)
     self.calcMouseLimits()
Ejemplo n.º 16
0
 def createCARD(self, tex, sizeCELLS, sizeRAWS):
     card = CardMaker("tilesheet")
     tile = NodePath(card.generate())
     tile.reparentTo(render2d)
     tile.setTexScale(self.ts,sizeCELLS,sizeRAWS)
     tile.setTexture(self.ts, tex)
     return tile
Ejemplo n.º 17
0
    def load_floor(self):
        cm = CardMaker("floor")
        cm.setFrame(0, 1, 0, 1)
        card = cm.generate()

        grass_texture = self.loader.loadTexture(os.path.join("data", "images", "grass.png"))
        wood_texture = self.loader.loadTexture(os.path.join("data", "images", "floor_wood_0.png"))
        
        for x, row in enumerate(self.floor_data.layout):
            for y, tile in enumerate(row):
                floor = self.render.attachNewNode(cm.generate())
                floor.setP(270)
                floor.setPos(x,y,0)                
                if tile == floor_layout.GRASS:
                    floor.setTexture(grass_texture)
                elif tile == floor_layout.WOOD:
                    floor.setTexture(wood_texture)
Ejemplo n.º 18
0
        def __init__(self, scale=1.2):
                NodePath.__init__(self, 'healthbar')

                self.scale = scale
                cmfg = CardMaker('fg')
                cmfg.setFrame(- scale,  scale, -0.1 * scale, 0.1 * scale)
                self.fg = self.attachNewNode(cmfg.generate())

                cmbg = CardMaker('bg')
                cmbg.setFrame(- scale, scale, -0.1 * scale, 0.1 * scale)
                self.bg = self.attachNewNode(cmbg.generate())

                #cmbd = CardMaker('bd')
                #cmbd.setFrame(- scale * 1.3, scale * 1.3, -.2 * scale, .2 * scale)
                #self.bd = self.attachNewNode(cmbd.generate())

                self.fg.setColor(1, 0, 0, 1)
                self.bg.setColor(0.2, 0.2, 0.2, 1)

                self.setValue(1)
Ejemplo n.º 19
0
    def __init__(self, x1, y1, x2, y2, z):
        Att_base.__init__(self, False, "Water1")
        # Water surface
        maker = CardMaker( 'water' )
        maker.setFrame( x1, x2, y1, y2 )

        self.waterNP = render.attachNewNode(maker.generate())
        self.waterNP.setHpr(0,-90,0)
        self.waterNP.setPos(0,0,z)
        self.waterNP.setTransparency(TransparencyAttrib.MAlpha )
        self.waterNP.setShader(loader.loadShader( 'Shaders/water1.sha' ))

        # Reflection plane
        self.waterPlane = Plane( Vec3( 0, 0, z+1 ), Point3( 0, 0, z ) )

        planeNode = PlaneNode( 'waterPlane' )
        planeNode.setPlane( self.waterPlane )

        # Buffer and reflection camera
        self.buffer = base.win.makeTextureBuffer( 'waterBuffer', 512, 512 )
        self.buffer.setClearColor( Vec4( 0, 0, 0, 1 ) )

        cfa = CullFaceAttrib.makeReverse( )
        rs = RenderState.make(cfa)

        self.watercamNP = base.makeCamera( self.buffer )
        self.watercamNP.reparentTo(render)

        sa = ShaderAttrib.make()
        sa = sa.setShader(loader.loadShader('Shaders/splut3Clipped.sha') )

        self.cam = self.watercamNP.node()
        self.cam.getLens( ).setFov( base.camLens.getFov( ) )
        self.cam.getLens().setNear(1)
        self.cam.getLens().setFar(5000)
        self.cam.setInitialState( rs )
        self.cam.setTagStateKey('Clipped')
        self.cam.setTagState('True', RenderState.make(sa))


        # ---- water textures ---------------------------------------------

        # reflection texture, created in realtime by the 'water camera'
        tex0 = self.buffer.getTexture( )
        tex0.setWrapU(Texture.WMClamp)
        tex0.setWrapV(Texture.WMClamp)
        ts0 = TextureStage( 'reflection' )
        self.waterNP.setTexture( ts0, tex0 )

        # distortion texture
        tex1 = loader.loadTexture('Textures/water.png')
        ts1 = TextureStage('distortion')
        self.waterNP.setTexture(ts1, tex1)
	def makeCard(self, color, width, height, i, j, divisions):
		divisions = float(divisions)
		x = i / divisions
		y = j / divisions
		d = 1 / divisions

		card = CardMaker("wall")
		card.setColor(*color)
		card.setFrame(width*(x*2-1), width*((x+d)*2-1), height*(y*2-1), height*((y+d)*2-1))
		card.setUvRange(Point2(width*x, height*y), Point2(width*(x+d), height*(y+d)))
		card.setHasUvs(True)
		card.setHasNormals(True)
		node = self.node.attachNewNode(card.generate())
Ejemplo n.º 21
0
    def __init__(self,width,height,texture,scale):
        self.width = width*scale
        self.height = height*scale
        print texture
        self.texture = loader.loadTexture(texture)

        cm = CardMaker("CardMaker")
        cm.setFrame((self.width/2,self.height/2,0),(-self.width/2,self.height/2,0),(-self.width/2,-self.height/2,0),(self.width/2,-self.height/2,0))
        card = render.attachNewNode(cm.generate())
        card.clearColor()
        card.setBin("background", 10)
        card.setHpr(180,0,0)
        card.setTransparency(TransparencyAttrib.MAlpha)

        card.setTexture(self.texture)
    def __init__(self,jod,index):
        """
        @param jod: containing Jam-o-Drum
        @type jod: L{JamoDrumNodePath}
        @param index: index of the station
        @type index: int
        """
        NodePath.__init__(self,"station%02d"%index)
        self.jod = jod
        self.index = index
        angle = 45.0-self.index*90.0
        self.setPos(math.cos((angle-90.0)*math.pi/180.0),math.sin((angle-90.0)*math.pi/180.0),0)
        self.setH(angle)
        
        cm = CardMaker("card")
        cm.setFrame(-1,1,-1,1)

        self.spinner = self.attachNewNode("spinner")
        self.spinnerCard = self.spinner.attachNewNode(cm.generate())
        self.spinnerCard.setTransparency(1)
        self.spinnerCard.setBin("background",1)
        self.spinnerCard.node().setAttrib(DepthOffsetAttrib.make(1))
        self.spinnerCard.setScale(1.0/3.0)
        self.spinnerCard.setP(-90)
        self.spinnerCard.setLightOff()
        self.spinnerCard.hide()
        
        self.pad = self.attachNewNode("pad")
        self.padCard = self.pad.attachNewNode(cm.generate())
        self.padCard.setTransparency(1)
        self.padCard.setBin("background",2)
        self.padCard.node().setAttrib(DepthOffsetAttrib.make(2))
        self.padCard.setScale(1.0/3.0)
        self.padCard.setP(-90)
        self.padCard.setLightOff()
        self.padCard.hide()
Ejemplo n.º 23
0
def setSky(directory, ext=".jpg"):
    """Sets up a skybox. 'directory' is the directory whitch contains 6
    pictures with the names right.ext, left.ext and so on (see template).
    ext is the extension the pictures have (with dot).
    """
    #TODO: accept all supported image file extensions without the need for an
    #      extra argument

    # remove the old sky first when loading a new one
    # TODO: get this working...
    #oldsky = render.find("*sky*")
    #print oldsky
    #for child in render.getChildren():
    #    child.remove()

    sky = NodePath().attachNewNode("sky")
    sides = {
        "right":  ( 1,  0,  0, -90,   0,  0),
        "left":   (-1,  0,  0,  90,   0,  0),
        "top":    ( 0,  0,  1,   0,  90,  0),
        "bottom": ( 0,  0, -1,  180,  -90,  0),
        "front":  ( 0,  1,  0,   0,   0,  0),
        "back":   ( 0, -1,  0, 180,   0,  0)
        }
    for name, poshpr in sides.iteritems():

        c = CardMaker(name)
        c.setFrame(-1, 1, -1, 1)
        card = c.generate()
        cardnode = sky.attachNewNode(card)
        cardnode.setPosHpr(*poshpr)
        tex = loader.loadTexture("skyboxes/" + directory + "/" + name + ext)
        tex.setWrapV(tex.WMClamp)
        tex.setMagfilter(tex.FTNearestMipmapNearest)
        tex.setMinfilter(tex.FTNearestMipmapNearest)
        cardnode.setTexture(tex)

    sky.flattenStrong()
    sky.setScale(10, 10, 10)
    sky.setCompass()
    sky.setBin('background', 0)
    sky.setDepthTest(False)
    sky.setDepthWrite(False)
    sky.setLightOff()
    sky.reparentTo(camera)

    geom = sky.getChild(0).node()
    geom.setName("cube")
 def __init__(self, potionGame):
     self.numColumns = 8
     self.numRows = 10
     DirectFrame.__init__(self, parent = potionGame.background, relief = None)
     cm = CardMaker('card')
     cm.setFrame(0, 0, 1.0, 1.0)
     self.background = self.attachNewNode(cm.generate())
     self.background.setColor(0.20000000000000001, 0.20000000000000001, 0.20000000000000001, 1)
     self.potionGame = potionGame
     self.pieceDropped = False
     self.pieceFlipped = False
     self.pieceNotDropped = False
     self.delayDropped = False
     self.experementMatched = False
     self.experementFailed = False
     self.initBoard()
Ejemplo n.º 25
0
 def createSprite(self,filename, x, z, sx, sz, transparent = 1):
     
     cm = CardMaker('spritesMaker') 
     cm.setFrame(-0.5, 0.5, -0.5, 0.5) 
     sprite = cm.generate()    
     
     tex = loader.loadTexture(filename) 
     
     spriteNP = NodePath(sprite)    
     
     spriteNP.setTexture(tex) 
     spriteNP.setPos(x, 0, z) 
     spriteNP.setScale(sx, 1.0, sz) 
     spriteNP.setTransparency(transparent)
      
     return spriteNP
Ejemplo n.º 26
0
    def _createMapTextureCard(self):
        """
        This will return a NodePath with a card textured with the minimap.  The
        minimap texture is dynamically created from the map data.
        """
        # create and fill empty map image
        mapImage = PNMImage(MAP_RESOLUTION, MAP_RESOLUTION)
        blockFiles = []
        for i in range(5):
            blockFiles.append(PNMImage())
            #blockFiles[i].read(Filename("mapBlock%i.jpg"%(i+1)))
            # TODO:maze either reference a set of textures for each piece or fill with color
            blockFiles[i].read(Filename('phase_4/maps/male_sleeve4New.jpg'))
        mapImage.fill(0.8, 0.8, 0.8)

        # iterate through the map data and place a block in the map image where appropriate
        for x in range( len(self._mazeLayout[0]) ):
            for y in range( len(self._mazeLayout) ):
                if self._mazeLayout[y][x]:
                    ax = float(x)/len(self._mazeLayout[0]) * MAP_RESOLUTION
                    ay = float(y)/len(self._mazeLayout) * MAP_RESOLUTION

                    #TODO:maze use different blocks for different wall types or items
                    #mapImage.copySubImage(random.choice(blockFiles), int(ax), int(ay), 20, 20, 32, 32)

                    #TODO:maze find the ideal block texture size for the map so we dont
                    #          have to do this strange offset
                    #mapImage.copySubImage(blockFiles[0], int(ax), int(ay), 0, 0, 32, 32)
                    self._drawSquare(mapImage, int(ax), int(ay), 10, VBase4D(0.5, 0.5, 0.5, 1.0))

        # create a texture from the map image
        mapTexture = Texture("mapTexture")
        mapTexture.setupTexture(Texture.TT2dTexture, self._maskResolution, self._maskResolution, 1, Texture.TUnsignedByte, Texture.FRgba)
        mapTexture.setMinfilter(Texture.FTLinear)
        mapTexture.load(mapImage)
        mapTexture.setWrapU(Texture.WMClamp)
        mapTexture.setWrapV(Texture.WMClamp)

        mapImage.clear()
        del mapImage

        # put the texture on a card and return it
        cm = CardMaker("map_cardMaker")
        cm.setFrame(-1.0,1.0,-1.0,1.0)
        map = self.attachNewNode(cm.generate())
        map.setTexture(mapTexture, 1)
        return map
Ejemplo n.º 27
0
class BulletHoles:
    """The name says it all."""
    def __init__(self, manager, xml):
        self.texture = loader.loadTexture('data/textures/bullet-hole.png')
        self.texture.setMinfilter(Texture.FTLinearMipmapLinear)
        self.container = render.attachNewNode(ModelRoot('bullet-holes'))
        self.card = CardMaker('bullet-hole')
        s = BULLETHOLE_SIZE * 0.5
        self.card.setFrame(-s, s, -s, s)
        self.card.setUvRange(Point2(0, 0), Point2(1, 1))

    def makeNew(self, pos, nor, parent=None):
        """Makes a new bullet hole."""
        if parent == None:
            parent = self.container
        else:
            # Add a subnode to the parent, if it's not already there
            child = parent.find('bullet-holes')
            if child.isEmpty():
                parent = parent.attachNewNode('bullet-holes')
            else:
                parent = child
        newhole = NodePath(self.card.generate())
        newhole.reparentTo(parent)
        newhole.lookAt(render, Point3(newhole.getPos(render) - nor))
        newhole.setR(newhole, random() * 360.0)
        newhole.setPos(render, pos)
        # Offset it a little to avoid z-fighting
        # Increase this value if you still see it.
        newhole.setY(newhole, -.001 - random() * 0.01)
        del newhole
        # We don't want one batch per bullet hole, so flatten it.
        # This could be made smarter to preserve culling, but
        # I have yet to see a performance loss.
        # The clearTexture() is a necessary hack.
        parent.clearTexture()
        parent.flattenStrong()
        parent.setTexture(self.texture)
        parent.setTransparency(TransparencyAttrib.MDual)
        parent.setShaderOff(1)
        parent.hide(BitMask32.bit(
            2))  # Invisible to volumetric lighting camera (speedup)
        parent.hide(BitMask32.bit(3))  # Invisible to shadow cameras (speedup)

    def destroy(self):
        self.container.removeNode()
Ejemplo n.º 28
0
 def create_floor(self, size_x_axis, size_y_axis, texture):
     
     card_maker = CardMaker('')
     card_maker.setFrame(0,size_x_axis,0,size_y_axis)
     '''
     for y in range(size_y_axis):
         for x in range(size_x_axis):
             new_node = self.floorNode.attachNewNode(card_maker.generate())
             new_node.setP(-90)
             new_node.setPos(x, y, 0)
     '''
     new_node = self.floor_node.attachNewNode(card_maker.generate())
     new_node.setP(-90)
     new_node.setPos(0, 0, 0)
     new_node.setTexture(textures[texture])    
     
     self.floor_node.flattenStrong()
Ejemplo n.º 29
0
 def __init__(self, potionGame):
     self.numColumns = 8
     self.numRows = 10
     DirectFrame.__init__(self, parent=potionGame.background, relief=None)
     cm = CardMaker('card')
     cm.setFrame(0, 0, 1.0, 1.0)
     self.background = self.attachNewNode(cm.generate())
     self.background.setColor(0.2, 0.2, 0.2, 1)
     self.potionGame = potionGame
     self.pieceDropped = False
     self.pieceFlipped = False
     self.pieceNotDropped = False
     self.delayDropped = False
     self.experementMatched = False
     self.experementFailed = False
     self.initBoard()
     return
Ejemplo n.º 30
0
class BulletHoles:
  """The name says it all."""
  def __init__(self,manager,xml):
    self.texture = loader.loadTexture('data/textures/bullet-hole.png')
    self.texture.setMinfilter(Texture.FTLinearMipmapLinear)
    self.container = render.attachNewNode(ModelRoot('bullet-holes'))
    self.card = CardMaker('bullet-hole')
    s = BULLETHOLE_SIZE * 0.5
    self.card.setFrame(-s, s, -s, s)
    self.card.setUvRange(Point2(0, 0), Point2(1, 1))

  def makeNew(self, pos, nor, parent = None):
    """Makes a new bullet hole."""
    if parent == None:
      parent = self.container
    else:
      # Add a subnode to the parent, if it's not already there
      child = parent.find('bullet-holes')
      if child.isEmpty():
        parent = parent.attachNewNode('bullet-holes')
      else:
        parent = child
    newhole = NodePath(self.card.generate())
    newhole.reparentTo(parent)
    newhole.lookAt(render, Point3(newhole.getPos(render) - nor))
    newhole.setR(newhole, random() * 360.0)
    newhole.setPos(render, pos)
    # Offset it a little to avoid z-fighting
    # Increase this value if you still see it.
    newhole.setY(newhole, -.001 - random() * 0.01)
    del newhole
    # We don't want one batch per bullet hole, so flatten it.
    # This could be made smarter to preserve culling, but
    # I have yet to see a performance loss.
    # The clearTexture() is a necessary hack.
    parent.clearTexture()
    parent.flattenStrong()
    parent.setTexture(self.texture)
    parent.setTransparency(TransparencyAttrib.MDual)
    parent.setShaderOff(1)
    parent.hide(BitMask32.bit(2)) # Invisible to volumetric lighting camera (speedup)
    parent.hide(BitMask32.bit(3)) # Invisible to shadow cameras (speedup)

  def destroy(self):
    self.container.removeNode()
    def __init__(self,
                 name,
                 nrplates,
                 width,
                 height,
                 shaderfile,
                 texturefile,
                 uvlist,
                 jitter=-1):
        #print name, nrplates, width, height, shaderfile, texturefile, uvlist, jitter
        self.name = name
        self.texturefile = texturefile
        self.shaderfile = shaderfile

        self.np = NodePath('leaf')

        self.tex = loader.loadTexture('textures/' + texturefile)
        self.tex.setMinfilter(Texture.FTLinearMipmapLinear)
        self.tex.setMagfilter(Texture.FTLinearMipmapLinear)
        self.tex.setAnisotropicDegree(2)
        self.np.setTexture(self.tex)
        self.np.setTwoSided(True)
        self.np.setTransparency(TransparencyAttrib.MAlpha)
        #self.np.setTransparency( TransparencyAttrib.MMultisample )
        self.np.setDepthWrite(False)

        maker = CardMaker('leaf')
        maker.setFrame(-width / 2.0, width / 2.0, 0, height)
        #maker.setFrame( 0,1,0,1)
        for i in range(nrplates):
            if uvlist != None:
                maker.setUvRange(uvlist[i][0], uvlist[i][1])
            else:
                maker.setUvRange(Point2(0, 0), Point2(1, 0.98))
            node = self.np.attachNewNode(maker.generate())
            #node.setTwoSided( True )
            node.setHpr(i * 180.0 / nrplates, 0, 0)
        self.np.flattenStrong()
        #np.flattenLight()
        #np.setTwoSided( True )

        if jitter == -1:
            self.jitter = height / width / 2
        else:
            self.jitter = jitter
    def __init__(self):
        self.music = loader.loadMusic('phase_4/audio/bgm/science_fair_credits.ogg')

        cm = CardMaker('screen-cover')
        cm.setFrameFullscreenQuad()
        self.screenCover = render2d.attachNewNode(cm.generate())
        self.screenCover.hide()
        self.screenCover.setScale(100)
        self.screenCover.setColor((0, 0, 0, 1))

        self.logo = OnscreenImage(image='phase_3/maps/toontown-logo.png',
                                  scale=(1.0 * (4.0/3.0), 1, 1.0 / (4.0/3.0)),
                                  pos=(-0.05, 1, -0.85))
        self.logo.setTransparency(TransparencyAttrib.MAlpha)
        self.logo.reparentTo(base.a2dTopCenter)
        self.logo.hide()

        self.creditsSeq = None
 def __setupEnvironment(self):
     cm = CardMaker("ground")
     size = 200
     cm.setFrame(-size, size, -size, size)
     environment = render.attachNewNode(cm.generate())
     environment.lookAt(0, 0, -1)
     environment.setPos(100, -100, 0)
     environment.setCollideMask(BitMask32.allOn())
     environment.reparentTo(render)
     
     texture = loader.loadTexture("textures/ground.png")
     
     # This is so the textures can look better from a distance
     texture.setMinfilter(Texture.FTLinearMipmapLinear)
     
     environment.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) 
     environment.setTexScale(TextureStage.getDefault(), 0.02, 0.02)
     environment.setTexture(texture, 1)
Ejemplo n.º 34
0
    def __init__(self, width, height, texture, scale):
        self.width = width * scale
        self.height = height * scale
        self.texture = loader.loadTexture(
            texture)  #"textures/map/"+texture+".jpg")

        cm = CardMaker("CardMaker")
        cm.setFrame((self.width / 2, self.height / 2, 0),
                    (-self.width / 2, self.height / 2, 0),
                    (-self.width / 2, -self.height / 2, 0),
                    (self.width / 2, -self.height / 2, 0))
        card = render.attachNewNode(cm.generate())
        card.clearColor()
        card.setBin("background", 10)
        card.setHpr(180, 0, 0)
        card.setTransparency(TransparencyAttrib.MAlpha)

        card.setTexture(self.texture)
    def __setupEnvironment(self):
        cm = CardMaker("ground")
        size = 100
        cm.setFrame(-size, size, -size, size)
        environment = render.attachNewNode(cm.generate())
        environment.lookAt(0, 0, -1)
        environment.setPos(0, 0, 0)
        environment.setCollideMask(BitMask32.allOn())
        environment.reparentTo(render)

        texture = loader.loadTexture("textures/ground.png")

        # This is so the textures can look better from a distance
        texture.setMinfilter(Texture.FTLinearMipmapLinear)

        environment.setTexGen(TextureStage.getDefault(),
                              TexGenAttrib.MWorldPosition)
        environment.setTexScale(TextureStage.getDefault(), 0.02, 0.02)
        environment.setTexture(texture, 1)
Ejemplo n.º 36
0
    def _createMaskTextureCard(self):
        self._maskImage = PNMImage(self._maskResolution, self._maskResolution, 4)
        for x in range(self._maskResolution):
            for y in range(self._maskResolution):
                self._maskImage.setXelA(x, y, 0, 0, 0, 1)

        self.maskTexture = Texture('maskTexture')
        self.maskTexture.setupTexture(Texture.TT2dTexture, self._maskResolution, self._maskResolution, 1, Texture.TUnsignedByte, Texture.FRgba)
        self.maskTexture.setMinfilter(Texture.FTLinear)
        self.maskTexture.setWrapU(Texture.WMClamp)
        self.maskTexture.setWrapV(Texture.WMClamp)
        self.maskTexture.load(self._maskImage)
        base.graphicsEngine.renderFrame()
        cm = CardMaker('mask_cardMaker')
        cm.setFrame(-1.1, 1.1, -1.1, 1.1)
        mask = self.attachNewNode(cm.generate())
        mask.setTexture(self.maskTexture, 1)
        mask.setTransparency(1)
        return mask
Ejemplo n.º 37
0
    def addLock(self, x, y, color):
        """
        Adds a lock to the minimap.  This will add a colored dot to the map
        that represents a lock.
        --- This is subject to change pending a new player-lock data system. ---
        """
        assert self.notify.debugCall()

        x, y = self._tileToActualPosition(x, y)

        # TODO:maze: replace with lock model / texture
        cm = CardMaker("lock_cardMaker")
        cm.setFrame(-0.04,0.04,-0.04,0.04)
        lock = self.maskedLayer.attachNewNode(cm.generate())

        lock.setColor(color)
        lock.setPos(x/self._maskResolution*2.0 - 0.97, 0, y/self._maskResolution*-2.0 + 1.02)

        self._locks.append(lock)
Ejemplo n.º 38
0
    def _createMaskTextureCard(self):
        self._maskImage = PNMImage(self._maskResolution, self._maskResolution, 4)
        for x in xrange(self._maskResolution):
            for y in xrange(self._maskResolution):
                self._maskImage.setXelA(x, y, 0, 0, 0, 1)

        self.maskTexture = Texture('maskTexture')
        self.maskTexture.setupTexture(Texture.TT2dTexture, self._maskResolution, self._maskResolution, 1, Texture.TUnsignedByte, Texture.FRgba)
        self.maskTexture.setMinfilter(Texture.FTLinear)
        self.maskTexture.setWrapU(Texture.WMClamp)
        self.maskTexture.setWrapV(Texture.WMClamp)
        self.maskTexture.load(self._maskImage)
        base.graphicsEngine.renderFrame()
        cm = CardMaker('mask_cardMaker')
        cm.setFrame(-1.1, 1.1, -1.1, 1.1)
        mask = self.attachNewNode(cm.generate())
        mask.setTexture(self.maskTexture, 1)
        mask.setTransparency(1)
        return mask
Ejemplo n.º 39
0
    def setupTexture(self):
        cm = CardMaker('quadMaker')
        cm.setColor(1.0, 1.0, 1.0, 1.0)

        aspect = base.camLens.getAspectRatio()
        htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH)
        htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT)

        # the html area will be center aligned and vertically top aligned
        #cm.setFrame(-htmlWidth/2.0, htmlWidth/2.0, 1.0 - htmlHeight, 1.0)
        cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0,
                    htmlHeight / 2.0)

        bottomRightX = (WEB_WIDTH_PIXELS) / float(WEB_WIDTH + 1)
        bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1)

        #cm.setUvRange(Point2(0,0), Point2(bottomRightX, bottomRightY))
        cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1))

        card = cm.generate()
        self.quad = NodePath(card)
        self.quad.reparentTo(self.parent)

        self.guiTex = Texture("guiTex")
        self.guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1,
                                 Texture.TUnsignedByte, Texture.FRgba)
        self.guiTex.setMinfilter(Texture.FTLinear)
        self.guiTex.setKeepRamImage(True)
        self.guiTex.makeRamImage()
        self.guiTex.setWrapU(Texture.WMRepeat)
        self.guiTex.setWrapV(Texture.WMRepeat)

        ts = TextureStage('webTS')
        self.quad.setTexture(ts, self.guiTex)
        self.quad.setTexScale(ts, 1.0, -1.0)

        self.quad.setTransparency(0)
        self.quad.setTwoSided(True)
        self.quad.setColor(1.0, 1.0, 1.0, 1.0)
        #self.quad.setZ(0.1) # shtickerbook is moved up by 0.1

        self.calcMouseLimits()
Ejemplo n.º 40
0
    def addPlayer(self, x, y, color):
        """
        Adds a player to the minimap.  This will add a colored dot to the map
        that represents the player.  The dot location can then be updated
        using the revealCell call.
        --- This is subject to change pending a new player-lock data system. ---
        """
        assert self.notify.debugCall()

        x, y = self._tileToActualPosition(x, y)

        # TODO:maze: replace with player model / texture
        cm = CardMaker("player_cardMaker")
        cm.setFrame(-0.04,0.04,-0.04,0.04)
        player = self.visibleLayer.attachNewNode(cm.generate())

        player.setColor(color)
        player.setPos(x/self._maskResolution*2.0 - 0.97, 0, y/self._maskResolution*-2.0 + 1.02)

        self._players.append(player)
Ejemplo n.º 41
0
    def __init__(self):
        self.music = loader.loadMusic(
            'phase_4/audio/bgm/science_fair_credits.ogg')

        cm = CardMaker('screen-cover')
        cm.setFrameFullscreenQuad()
        self.screenCover = render2d.attachNewNode(cm.generate())
        self.screenCover.hide()
        self.screenCover.setScale(100)
        self.screenCover.setColor((0, 0, 0, 1))

        self.logo = OnscreenImage(image='phase_3/maps/toontown-logo.png',
                                  scale=(1.0 * (4.0 / 3.0), 1,
                                         1.0 / (4.0 / 3.0)),
                                  pos=(-0.05, 1, -0.85))
        self.logo.setTransparency(TransparencyAttrib.MAlpha)
        self.logo.reparentTo(base.a2dTopCenter)
        self.logo.hide()

        self.creditsSeq = None
Ejemplo n.º 42
0
    def __init__(self, pickableList=[]):
        self.pickable = pickableList
        tempCard = CardMaker('')
        tempCard.setFrame(0, 1, 0, 1)

        #Lets render our frame so we can hide / show /resize it as needed
        self.selectFrame = render2d.attachNewNode(tempCard.generate())
        self.selectFrame.setColor(1, 1, 0, .2)
        self.selectFrame.setTransparency(1)
        self.selectFrame.hide()

        #Set up our line segmants for a border
        ls = LineSegs()
        ls.moveTo(0, 0, 0)
        ls.drawTo(1, 0, 0)
        ls.drawTo(1, 0, 1)
        ls.drawTo(0, 0, 1)
        ls.drawTo(0, 0, 0)

        self.selectFrame.attachNewNode(ls.create())

        self.selected = []
        self.previousSelect = []
        self.selectable = []

        #Init our mouse locations
        self.pt2InitMousePos = (-1, -1)
        self.pt2LastMousePos = (-1, -1)
        self.fFovh, self.fFovv = base.camLens.getFov()

        self.fTimeLastUpdateRect = 0
        self.fTimeLastUpdateSelected = 0
        self.UpdateTimeRect = 0.015
        self.UpdateTimeSelected = 0.015

        print "Running Select Tools"

        self.accept("mouse1", self.OnStartSelect)
        self.accept("control-mouse1", self.OnStartSelect)
        self.accept("mouse1-up", self.OnMouseRelease)
        self.taskUpdateSelectRect = 0
Ejemplo n.º 43
0
    def renderQuadInto(self, mul=1, div=1, align=1, depthtex=None, colortex=None, auxtex0=None, auxtex1=None):

        """ Creates an offscreen buffer for an intermediate
        computation. Installs a quad into the buffer.  Returns
        the fullscreen quad.  The size of the buffer is initially
        equal to the size of the main window.  The parameters 'mul',
        'div', and 'align' can be used to adjust that size. """

        texgroup = (depthtex, colortex, auxtex0, auxtex1)

        winx, winy = self.getScaledSize(mul, div, align)
        
        depthbits = bool(depthtex != None)
        
        buffer = self.createBuffer("filter-stage", winx, winy, texgroup, depthbits)

        if (buffer == None):
            return None

        cm = CardMaker("filter-stage-quad")
        cm.setFrameFullscreenQuad()
        quad = NodePath(cm.generate())
        quad.setDepthTest(0)
        quad.setDepthWrite(0)
        quad.setColor(Vec4(1,0.5,0.5,1))

        quadcamnode = Camera("filter-quad-cam")
        lens = OrthographicLens()
        lens.setFilmSize(2, 2)
        lens.setFilmOffset(0, 0)
        lens.setNearFar(-1000, 1000)
        quadcamnode.setLens(lens)
        quadcam = quad.attachNewNode(quadcamnode)
        
        buffer.getDisplayRegion(0).setCamera(quadcam)
        buffer.getDisplayRegion(0).setActive(1)

        self.buffers.append(buffer)
        self.sizes.append((mul, div, align))
        
        return quad
Ejemplo n.º 44
0
 def __setupPreview(self):
   """Creates the preview."""
   if not self.previewCheck.Value: return
   if self.preview != None:
     self.__destroyPreview()
   self.preview = wx.StaticBitmap(self, style = wx.SUNKEN_BORDER, size = PREVIEW_SIZE)
   self.sizer.Add(self.preview, 0, wx.ADJUST_MINSIZE | wx.ALIGN_CENTER, 0)
   cm = CardMaker("preview")
   cm.setFrame(-1, 1, -1, 1)
   cm.setUvRange(Point2(0, 0), Point2(1, 1))
   self.previewTexture = Texture()
   self.previewBuffer = WindowManager.windows[0].win.makeTextureBuffer("preview", *PREVIEW_SIZE)
   self.previewBuffer.setClearColor(Vec4(1, 1, 1, 1))
   self.previewCamera = base.makeCamera2d(self.previewBuffer)
   self.previewPlane = NodePath(cm.generate())
   self.previewPlane.setFogOff(1000)
   self.previewPlane.setLightOff(1000)
   self.previewCamera.node().setScene(self.previewPlane)
   self.previewBuffer.addRenderTexture(self.previewTexture, GraphicsOutput.RTMCopyRam)
   self.previewCamera.node().setActive(texturePainter.texturePainterStatus == TEXTURE_PAINTER_STATUS_ENABLED)
   self.Layout()
Ejemplo n.º 45
0
    def __init__(self, baseDimension):
        #public props
        self.walkable = True
        self.resources = []
        self.textures = [
        ]  #list that holds every texture in the tile, ordered from bottom to top
        self.objects = [
        ]  #list that holds every object in the tile, ordered from bottom to top
        self.lights = [
        ]  #list that holds every light in the tile, ordered from bottom to top
        self.typeName = 'tile'  #needed by xml

        self.tileProperties = {
            'id': '',  #still no used, polymorph
            'url': '',
            'onWalked': '',
            'onPicked': '',
            'walkable': ''
        }

        self.innerX = 0
        self.innerY = 0
        self.innerDimension = 0

        self.baseDimension = baseDimension

        self.node = NodePath('tilenode')
        self.node.setTwoSided(True)
        self.onPicked = ''

        #storing gamenode address, mainly used for node searching
        self.node.setPythonTag("gamenode", self)

        #generating groundnode
        cm = CardMaker("tiletexture")
        cm.setFrame(0, 1, 0, 1)

        self.groundnode = NodePath('groundtilenode')
        self.groundnode.attachNewNode(cm.generate())
        self.groundnode.reparentTo(self.node)
Ejemplo n.º 46
0
    def __init__(self, av, **kw):
        DirectFrame.__init__(self, relief=None, sortOrder=50)
        self.initialiseoptions(QuestMap)
        self.container = DirectFrame(parent=self, relief=None)
        self.marker = DirectFrame(parent=self.container, relief=None)
        self.cogInfoFrame = DirectFrame(parent=self.container, relief=None)
        cm = CardMaker('bg')
        cm.setFrame(-0.5, 0.5, -0.5, 0.5)
        bg = self.cogInfoFrame.attachNewNode(cm.generate())
        bg.setTransparency(1)
        bg.setColor(0.5, 0.5, 0.5, 0.5)
        bg.setBin('fixed', 0)
        self.cogInfoFrame['geom'] = bg
        self.cogInfoFrame['geom_pos'] = (0, 0, 0)
        self.cogInfoFrame['geom_scale'] = (6, 1, 2)
        self.cogInfoFrame.setScale(0.05)
        self.cogInfoFrame.setPos(0, 0, 0.6)
        self.buildingMarkers = []
        self.av = av
        self.wantToggle = False
        if base.config.GetBool('want-toggle-quest-map', True):
            self.wantToggle = True
        self.updateMarker = True
        self.cornerPosInfo = None
        self.hqPosInfo = None
        self.fishingSpotInfo = None
        self.load()
        self.setScale(1.5)
        bg.removeNode()
        self.hoodId = None
        self.zoneId = None
        self.suitPercentage = {}
        for currHoodInfo in SuitPlannerBase.SuitPlannerBase.SuitHoodInfo:
            tracks = currHoodInfo[
                SuitPlannerBase.SuitPlannerBase.SUIT_HOOD_INFO_TRACK]
            self.suitPercentage[currHoodInfo[
                SuitPlannerBase.SuitPlannerBase.SUIT_HOOD_INFO_ZONE]] = tracks

        return
Ejemplo n.º 47
0
 def setupRightTexture(self):
     cm = CardMaker('quadMaker')
     cm.setColor(1.0, 1.0, 1.0, 1.0)
     aspect = base.camLens.getAspectRatio()
     htmlWidth = 2.0 * aspect * WEB_WIDTH / float(WIN_WIDTH)
     htmlHeight = 2.0 * float(WEB_HEIGHT) / float(WIN_HEIGHT)
     cm.setFrame(0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0)
     card = cm.generate()
     self.rightQuad = NodePath(card)
     self.rightQuad.reparentTo(self.parent)
     self.rightGuiTex = Texture('guiTex')
     self.rightGuiTex.setupTexture(Texture.TT2dTexture, WEB_HALF_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba)
     self.rightGuiTex.setKeepRamImage(True)
     self.rightGuiTex.makeRamImage()
     self.rightGuiTex.setWrapU(Texture.WMClamp)
     self.rightGuiTex.setWrapV(Texture.WMClamp)
     ts = TextureStage('rightWebTS')
     self.rightQuad.setTexture(ts, self.rightGuiTex)
     self.rightQuad.setTexScale(ts, 1.0, -1.0)
     self.rightQuad.setTransparency(0)
     self.rightQuad.setTwoSided(True)
     self.rightQuad.setColor(1.0, 1.0, 1.0, 1.0)
 def announceGenerate(self):
     DistributedObject.DistributedObject.announceGenerate(self)
     self.sendUpdate('avIdEnteredParty', [base.localAvatar.doId])
     globalClock.syncFrameTime()
     self.startPartyClock()
     base.localAvatar.chatMgr.chatInputSpeedChat.addInsidePartiesMenu()
     self.spawnTitleText()
     messenger.send(self.generatedEvent)
     if config.GetBool('show-debug-party-grid', 0):
         self.testGrid = NodePath('test_grid')
         self.testGrid.reparentTo(base.cr.playGame.hood.loader.geom)
         for i in range(len(self.grid)):
             for j in range(len(self.grid[i])):
                 cm = CardMaker('gridsquare')
                 np = NodePath(cm.generate())
                 np.setScale(12)
                 np.setP(-90.0)
                 np.setPos(PartyUtils.convertDistanceFromPartyGrid(j, 0) - 6.0, PartyUtils.convertDistanceFromPartyGrid(i, 1) - 6.0, 0.1)
                 np.reparentTo(self.testGrid)
                 if self.grid[i][j]:
                     np.setColorScale(0.0, 1.0, 0.0, 1.0)
                 else:
                     np.setColorScale(1.0, 0.0, 0.0, 1.0)
Ejemplo n.º 49
0
 def _setBackgroundTexture(self):
     '''
     Sets the background texture for 2D nodes.
     It creates a full screen quad that has the corresponding texture applied to it.
     Note: The field node.parent2d specifies if the quad will be parented to render2d or aspect2d.
     '''
     bgTex = self.resources.loadTexture(self.node.image)
     if bgTex is not None:
         cm = CardMaker('node_bg')
         cm.setFrame(self.bounds[0], self.bounds[1], self.bounds[2],
                     self.bounds[3])
         cm.setHasUvs(True)
         self.bgCard = NodePath(cm.generate())
         self.bgCard.setName('2dnode_image')
         self.bgCard.setTexture(bgTex)
         bgTex.setMinfilter(Texture.FTNearest)
         bgTex.setMagfilter(Texture.FTNearest)
         self.bgCard.reparentTo(self.sceneRoot)
         self.bgCard.setBin("fixed",
                            PanoConstants.RENDER_ORDER_BACKGROUND_IMAGE)
     else:
         self.log.error('Failed to set background texture for node %s.' %
                        self.node.name)
Ejemplo n.º 50
0
    def generateNode(self):
        self.node.remove_node()
        self.node = NodePath('brush')

        for i in range(self.properties['density']):
            x = random.uniform(0.0, 1.0)
            y = random.uniform(0.0, 1.0)

            scale = random.uniform(self.properties['minuniform'],
                                   self.properties['maxuniform'])

            tex = loader.loadTexture(
                resourceManager.getResource('misc/grass_special.png'))
            tex.setWrapV(Texture.WM_clamp)
            tex.setWrapU(Texture.WM_clamp)

            #this is true pixel art
            #change to FTLinear for linear interpolation between pixel colors
            tex.setMagfilter(Texture.FTNearest)
            tex.setMinfilter(Texture.FTNearest)

            xscaled = tex.getOrigFileXSize() / self.baseDimension
            yscaled = tex.getOrigFileYSize() / self.baseDimension

            cm = CardMaker("tileobject")
            cm.setFrame(-xscaled / 2, xscaled / 2, 0, yscaled)

            grassnodenp = NodePath(cm.generate())
            grassnodenp.setTexture(tex)
            grassnodenp.setTransparency(3)
            #grassnodenp.setTransparency(TransparencyAttrib.MMultisample)
            grassnodenp.reparentTo(self.node)
            grassnodenp.setP(-355)
            grassnodenp.setX(x)
            grassnodenp.setZ(y)
            grassnodenp.setScale(scale)
Ejemplo n.º 51
0
    def getGameOverNode(self):
        gameOverNode = NodePath("GameOver")

        letterGeometry = LetterGeometry.getCardGeometryByPhrase('game over')

        for letter in letterGeometry:
            letterCm = CardMaker('card')
            letterCm.setFrame(letter['left'], letter['right'], letter['top'],
                              letter['bottom'])
            letterNode = gameOverNode.attachNewNode(letterCm.generate())
            self.letterNodes.append(letterNode)
            letterNode.setTwoSided(True)
            letterNode.setTransparency(TransparencyAttrib.MAlpha)
            letterNode.setBin('unsorted', 50)
            letterNode.setDepthTest(False)
            letterNode.setDepthWrite(False)
            tex = loader.loadTexture('textures/letter-' + letter['letter'] +
                                     '.png')
            tex.setWrapU(Texture.WMClamp)
            tex.setWrapV(Texture.WMClamp)
            letterNode.setTexture(tex)
            letterNode.setPos(letter['originx'], letter['originy'], 0)

        return gameOverNode
Ejemplo n.º 52
0
    def create_clickable_box(self):
        """
        Creates clickable card around the text label, and returns the click event
        message used when the card is clicked.
        """
        # Get the label text length.
        text_length = len(self.label_text)
        cm = CardMaker('card-' + self.label_text)
        card = self.card_np.attachNewNode(cm.generate())
        tex = loader.loadTexture('static/images/menu_left3.tif')

        card.setTexture(tex)
        card.setTransparency(TransparencyAttrib.MAlpha)
        #card.setScale(1.2*len(self.label_text),1,1)
        #card.setPos((-0.14*len(self.label_text)), 0.01, -0.3)

        card.setScale(0.5 * text_length, 1, 1)
        card.setPos((-0.25 * text_length, 0.01, -0.3))

        card.setTwoSided(True)

        # make the card pickable
        message = mouse_handler.makeNPPickableLeft(self.np)
        return message
Ejemplo n.º 53
0
 def generateNode(self):
     self.destroy()
     
     self.node = NodePath('gameobjectnode')
     self.node.setTwoSided(True)
     self.node.reparentTo(self.parent.node)
     
     if self.properties['avoidable'] == True:
         self.node.setTag("avoidable", 'true')
     else:
         self.node.setTag("avoidable", 'false')
     
     #setting scripting part
     self.node.setTag("onWalked", self.onWalked)
     self.node.setTag("onPicked", self.onPicked)
     #set unique id
     self.node.setTag("id", self.properties['id'])
     
     tex = loader.loadTexture(resourceManager.getResource(self.properties['url'])+'.png')
     tex.setWrapV(Texture.WM_clamp)
     tex.setWrapU(Texture.WM_clamp)
     
     #this is true pixel art
     #change to FTLinear for linear interpolation between pixel colors
     tex.setMagfilter(Texture.FTNearest)
     tex.setMinfilter(Texture.FTNearest)
     
     xorig = tex.getOrigFileXSize() / self.baseDimension
     yorig = tex.getOrigFileYSize() / self.baseDimension
     xscaled = (tex.getOrigFileXSize() / self.baseDimension) * self.properties['scale']
     yscaled = (tex.getOrigFileYSize() / self.baseDimension) * self.properties['scale']
     
     self.node.setTag("xscaled", str(xscaled))
     self.node.setTag("yscaled", str(yscaled))
     
     cm = CardMaker("tileobject")
     cm.setFrame(0,xorig,0,yorig)
     
     ts = TextureStage('ts')
     ts.setMode(TextureStage.MDecal)
     
     # distinguish between 3d collisions (for objects with an height and sensible self.properties['inclination'])
     # and 2d collisions for plain sprites
     if self.properties['walkable'] == 'false':
         if self.properties['collisionmode'] == "3d":
             #must handle differently objects which are small and big
             if xscaled < 1:
                 self.collisionTube = CollisionBox(LPoint3f(0.5 - xscaled/2 - self.properties['offsetwidth'],0,0),LPoint3f(0.5 + xscaled/2 + self.properties['offsetwidth'],0.1,0.3 + self.properties['offsetheight']))
                 
             if xscaled >= 1:
                 self.collisionTube = CollisionBox(LPoint3f(0 - self.properties['offsetwidth'],0,0),LPoint3f(xscaled + self.properties['offsetwidth'],0.1,0.3 + self.properties['offsetheight']))
             
             self.collisionNode = CollisionNode('objectSphere')
             self.collisionNode.addSolid(self.collisionTube)
             self.collisionNodeNp = self.node.attachNewNode(self.collisionNode)
             self.collisionNodeNp.setX(self.properties['offsethorizontal'])
             self.collisionNodeNp.setZ(self.properties['offsetvertical'])
             self.collisionNodeNp.setX(self.collisionNodeNp.getX()+self.properties['offsetcollisionh'])
             self.collisionNodeNp.setZ(self.collisionNodeNp.getZ()+self.properties['offsetcollisionv']+0.1)
             if main.editormode:
                 self.collisionNodeNp.show()
             
         elif self.properties['collisionmode'] == "2d":
             #must handle differently objects which are small and big
             if xscaled < 1:
                 self.collisionTube = CollisionBox(LPoint3f(0.5 - xscaled/2,0,0),LPoint3f(0.5 + xscaled/2,yscaled,0.3))
                 
             if xscaled >= 1:
                 self.collisionTube = CollisionBox(LPoint3f(0,0,0),LPoint3f(xscaled,yscaled,0.3))
             
             self.collisionNode = CollisionNode('objectSphere')
             self.collisionNode.addSolid(self.collisionTube)
             self.collisionNodeNp = self.node.attachNewNode(self.collisionNode)
             self.collisionNodeNp.setP(-(270-int(self.properties['inclination'])))
             self.collisionNodeNp.setX(self.properties['offsethorizontal'])
             self.collisionNodeNp.setZ(self.properties['offsetvertical'])
             self.collisionNodeNp.setX(self.collisionNodeNp.getX()+self.properties['offsetcollisionh'])
             self.collisionNodeNp.setZ(self.collisionNodeNp.getZ()+self.properties['offsetcollisionv']+0.1)
             if main.editormode:
                 self.collisionNodeNp.show()
     
     geomnode = NodePath(cm.generate())
     if xscaled >= 1:
         geomnode.setX(0)
     if xscaled < 1:
         geomnode.setX(0.5 - xscaled/2)
     geomnode.setScale(self.properties['scale'])
     geomnode.setX(geomnode.getX()+self.properties['offsethorizontal'])
     geomnode.setZ(geomnode.getZ()+self.properties['offsetvertical'])
     geomnode.setY(-self.properties['elevation'])
     geomnode.setP(-(360-int(self.properties['inclination'])))
     geomnode.setTexture(tex)
     geomnode.setTransparency(TransparencyAttrib.MAlpha)
     geomnode.reparentTo(self.node)
Ejemplo n.º 54
0
	def __init__(self,parent,segments,timeOfDay):

		super(VisualTrackSession, self).__init__()

		self.parent=parent
		self.ticks=0
		self.cars=[]
		self.events=[]
		self.timerDependentObjects=[]
		self.segments=segments
		self.createdNodes=[]
		self.stencilReaders={}
		self.stencilWriters={}
		self.carShadowRefreshIndex=0

		self.speed=-1
		self.lapTimeSeconds=-1
		self.lapTimeMilliseconds=-1
		self.secondsRemaining=-1
		self.topScore=-1

		self.correctAspectRatio()
		base.setBackgroundColor(0.262,0.615,0.054)
		base.accept('aspectRatioChanged',self.correctAspectRatio )

		self.carsAndSceneryNode=render.attachNewNode("CarsAndSceneryNode")
		self.carsAndSceneryNode.setColorScale(1.0,1.0,1.0,1.0)

		self.sunEffectsEnabled=False
		if timeOfDay==TimeOfDay.dusk:
			self.setBackgroundTexture('textures/mountains4x2blurredblended.png')
			self.setLightSourcePosition([12000,-800,1200])
			self.addSunEffects()
		else:
			self.setBackgroundTexture('textures/mountainsx2blurredblended.png')
			self.setLightSourcePosition([-4000,-1800,2400])

		m = loader.loadModel("models/newstartline")
		m.reparentTo(self.carsAndSceneryNode)
		m.setPos(self.segments[0].getMidPoint().getX(),self.segments[0].getMidPoint().getY(),0)
		m.setH(270)
		self.lights=m
		self.lightsIlluminated=False
		for i in range(1,5):
			self.setStartingLight(i,False)
		self.createdNodes.append(m)

		trackGeomNodes=TrackVisualGeometry.makeTrack(self.segments)

		track=render.attachNewNode(trackGeomNodes['tarmac'])
		texture=loader.loadTexture("textures/track256.png")
		texture.setAnisotropicDegree(4)
		texture.setMagfilter(Texture.FTNearest)
		texture.setMinfilter(Texture.FTLinearMipmapLinear)
		texture.setWrapU(Texture.WMRepeat)
		texture.setWrapV(Texture.WMRepeat)
		track.setTexture(texture)
		track.setTwoSided(False)
		track.setDepthWrite(False)
		track.setDepthTest(False)
		track.setBin("background",10)
		self.createdNodes.append(track)

		constantTwoStencil = StencilAttrib.make(1,StencilAttrib.SCFEqual,StencilAttrib.SOZero,StencilAttrib.SOKeep,StencilAttrib.SOReplace,2,0,2)
		track.node().setAttrib(constantTwoStencil)

		startLine=render.attachNewNode(trackGeomNodes['startline'])
		texture=loader.loadTexture("textures/startline.png")
		texture.setAnisotropicDegree(4)
		texture.setMagfilter(Texture.FTNearest)
		texture.setMinfilter(Texture.FTLinearMipmapLinear)
		texture.setWrapU(Texture.WMRepeat)	
		texture.setWrapV(Texture.WMRepeat)
		startLine.setTexture(texture)
		startLine.setTwoSided(False)
		startLine.setDepthWrite(False)
		startLine.setDepthTest(False)
		startLine.setBin("background",11);
		self.createdNodes.append(startLine)

		backgroundGeomNodes=MountainsGeometry.makeMountains()

		mountainsGeomNode=backgroundGeomNodes['mountains']
		mountains=render.attachNewNode(mountainsGeomNode)
		texture=loader.loadTexture(self.getBackgroundTexture())
		texture.setAnisotropicDegree(4)
		texture.setWrapU(Texture.WMRepeat)	
		texture.setWrapV(Texture.WMClamp)
		mountains.setTexture(texture)
		mountains.setTwoSided(False)
		mountains.setDepthWrite(False)
		mountains.setDepthTest(False)
		mountains.setBin("background",10);
		self.createdNodes.append(mountains)

		skyGeomNode=backgroundGeomNodes['sky']
		sky=render.attachNewNode(skyGeomNode)
		sky.setDepthWrite(False)
		sky.setDepthTest(False)
		sky.setBin("background",11)
		self.createdNodes.append(sky)

		constantOneStencil = StencilAttrib.make(1,StencilAttrib.SCFEqual,StencilAttrib.SOZero,StencilAttrib.SOKeep,StencilAttrib.SOReplace,1,0,1)
		shadowX=self.segments[0].getMidPoint().getX()
		shadowY=self.segments[0].getMidPoint().getY()
		lightSourceX,lightSourceY,lightSourceZ=self.getLightSourcePosition()
		shadowGeomNode=ShadowGeometry.makeModelShadow("models/newstartlineshadow",shadowX,shadowY,0,lightSourceX,lightSourceY,lightSourceZ,270)
		shadow=render.attachNewNode(shadowGeomNode)
		shadow.setTwoSided(True)
		self.createdNodes.append(shadow)
		shadow.setPos(shadowX,shadowY,0)
		shadow.node().setAttrib(constantOneStencil)
		shadow.node().setAttrib(ColorWriteAttrib.make(0))
		shadow.setBin('fixed',40)
		shadow.setDepthWrite(0)
		self.createdNodes.append(shadow)

		stencilReader = StencilAttrib.make(1,StencilAttrib.SCFEqual,StencilAttrib.SOKeep, StencilAttrib.SOKeep,StencilAttrib.SOKeep,1,1,0) 
		cm2d = CardMaker('card')
		cm2d.setFrameFullscreenQuad()
		card = render2d.attachNewNode(cm2d.generate())
		card.node().setAttrib(stencilReader)
		card.setDepthTest(False)
		card.setTransparency(TransparencyAttrib.MAlpha)
		card.setColor(0,0,0,0.40)
		self.createdNodes.append(card)

		trafficLightCm=CardMaker('card')
		trafficLightCm.setFrame(-0.20,0.20,0.20,-0.20)
		trafficLight = render.attachNewNode(trafficLightCm.generate())
		trafficLight.reparentTo(self.lights)
		trafficLight.setDepthTest(True)
		trafficLight.setDepthWrite(False)
		trafficLight.setColor(1.0,0.0,0.0,1.0)
		trafficLight.setBin("unsorted",50)
		trafficLight.setBillboardAxis()
		trafficLight.setTwoSided(True)
		tex = loader.loadTexture('textures/roadhighlight.png')
		trafficLight.setTexture(tex)
		trafficLight.setTransparency(TransparencyAttrib.MAlpha)
		trafficLight.hide()
		self.trafficLight=trafficLight
		self.createdNodes.append(trafficLight)

		colour = (45.0/255.0,81.0/255.0,98.0/255.0)
		expfog = Fog("Scene-wide exponential Fog object")
		expfog.setColor(*colour)
		expfog.setExpDensity(0.002)
		self.carsAndSceneryNode.setFog(expfog)

		self.qualifyingEndBlimpFlightComplete=False
		self.qualifyingResultsDisplayComplete=False	

		self.gearIndicator=GearIndicator()
		self.gearIndicator.setGear(Gearbox.low)
Ejemplo n.º 55
0
	def addSunEffects(self):
		self.sunEffectsEnabled=True

		dazzlerCm = CardMaker('card')
		dazzlerCm.setFrameFullscreenQuad()
		self.dazzler = render2d.attachNewNode(dazzlerCm.generate())
		self.dazzler.setDepthTest(False)
		self.dazzler.setTransparency(TransparencyAttrib.MAlpha)
		self.dazzler.setColor(1.0,1.0,1.0,0.0)
		self.dazzler.setBin("fixed",40)
		self.createdNodes.append(self.dazzler)

		sunCm=CardMaker('card')
		sunCm.setFrame(-500,500,500,-500)
		sun = render.attachNewNode(sunCm.generate())
		sun.setDepthTest(True)
		sun.setDepthWrite(False)
		sun.setColor(1.0,0.8,0.4,1.0)
		sun.setBin("unsorted",50)
		sunX,sunY,sunZ=self.getLightSourcePosition()
		sun.setPos(sunX,sunY,sunZ)
		sun.setBillboardAxis()
		sun.setTwoSided(True)
		tex = loader.loadTexture('textures/sun.png')
		sun.setTexture(tex)
		sun.setTransparency(TransparencyAttrib.MAlpha)
		self.createdNodes.append(sun)

		sunSurroundCm=CardMaker('card')
		sunSurroundCm.setFrame(-1500,1500,1500,-1500)
		sunSurround = render.attachNewNode(sunSurroundCm.generate())
		sunSurround.setDepthTest(True)
		sunSurround.setDepthWrite(False)
		sunSurround.setColor(1.0,1.0,1.0,1.0)
		sunSurround.setBin("unsorted",50)
		sunX,sunY,sunZ=self.getLightSourcePosition()
		sunSurround.setPos(sunX,sunY,sunZ)
		sunSurround.setBillboardAxis()
		sunSurround.setTwoSided(True)
		tex = loader.loadTexture('textures/roadhighlight.png')
		sunSurround.setTexture(tex)
		sunSurround.setTransparency(TransparencyAttrib.MAlpha)
		self.sunSurround=sunSurround
		self.createdNodes.append(sunSurround)

		stencilReader2 = StencilAttrib.make(1,StencilAttrib.SCFEqual,StencilAttrib.SOKeep, StencilAttrib.SOKeep,StencilAttrib.SOKeep,2,2,0) 
		roadHighlightCm=CardMaker('card')
		roadHighlightCm.setFrame(-3000,3000,3000,-3000)
		roadHighlight = render.attachNewNode(roadHighlightCm.generate())
		roadHighlight.setDepthTest(True)
		roadHighlight.setDepthWrite(False)
		roadHighlight.setColor(1.0,1.0,1.0,0.4)
		roadHighlight.setBin("unsorted",50)
		sunX,sunY,sunZ=self.getLightSourcePosition()
		roadHighlight.setPos(sunX,sunY,sunZ)
		roadHighlight.setBillboardAxis()
		roadHighlight.setTwoSided(True)
		tex = loader.loadTexture('textures/roadhighlight.png')
		roadHighlight.setTexture(tex)
		roadHighlight.setTransparency(TransparencyAttrib.MAlpha)
		self.createdNodes.append(roadHighlight)
		roadHighlight.node().setAttrib(stencilReader2)
Ejemplo n.º 56
0
    def __init__(self, image_path, rowPerFace, name=None,\
         rows=1, cols=1, scale=1.0,\
         twoSided=False, alpha=TRANS_ALPHA,\
         repeatX=1, repeatY=1,\
         anchorX=ALIGN_CENTER, anchorY=ALIGN_BOTTOM):
        """
		Create a card textured with an image. The card is sized so that the ratio between the
		card and image is the same.
		"""

        global SpriteId
        self.spriteNum = str(SpriteId)
        SpriteId += 1

        scale *= self.PIXEL_SCALE

        self.animations = {}

        self.scale = scale
        self.repeatX = repeatX
        self.repeatY = repeatY
        self.flip = {'x': False, 'y': False}
        self.rows = rows
        self.cols = cols

        self.currentFrame = 0
        self.currentAnim = None
        self.loopAnim = False
        self.frameInterrupt = True

        # Create the NodePath
        if name:
            self.node = NodePath("Sprite2d:%s" % name)
        else:
            self.node = NodePath("Sprite2d:%s" % image_path)

        # Set the attribute for transparency/twosided
        self.node.node().setAttrib(TransparencyAttrib.make(alpha))
        if twoSided:
            self.node.setTwoSided(True)

        # Make a filepath
        self.imgFile = Filename(image_path)
        if self.imgFile.empty():
            raise IOError, "File not found"

        # Instead of loading it outright, check with the PNMImageHeader if we can open
        # the file.
        imgHead = PNMImageHeader()
        if not imgHead.readHeader(self.imgFile):
            raise IOError, "PNMImageHeader could not read file. Try using absolute filepaths"

        # Load the image with a PNMImage
        image = PNMImage()
        image.read(self.imgFile)

        self.sizeX = image.getXSize()
        self.sizeY = image.getYSize()

        # We need to find the power of two size for the another PNMImage
        # so that the texture thats loaded on the geometry won't have artifacts
        textureSizeX = self.nextsize(self.sizeX)
        textureSizeY = self.nextsize(self.sizeY)

        # The actual size of the texture in memory
        self.realSizeX = textureSizeX
        self.realSizeY = textureSizeY

        self.paddedImg = PNMImage(textureSizeX, textureSizeY)
        if image.hasAlpha():
            self.paddedImg.alphaFill(0)
        # Copy the source image to the image we're actually using
        self.paddedImg.blendSubImage(image, 0, 0)
        # We're done with source image, clear it
        image.clear()

        # The pixel sizes for each cell
        self.colSize = self.sizeX / self.cols
        self.rowSize = self.sizeY / self.rows

        # How much padding the texture has
        self.paddingX = textureSizeX - self.sizeX
        self.paddingY = textureSizeY - self.sizeY

        # Set UV padding
        self.uPad = float(self.paddingX) / textureSizeX
        self.vPad = float(self.paddingY) / textureSizeY

        # The UV dimensions for each cell
        self.uSize = (1.0 - self.uPad) / self.cols
        self.vSize = (1.0 - self.vPad) / self.rows

        self.cards = []
        self.rowPerFace = rowPerFace
        for i in range(len(rowPerFace)):
            card = CardMaker("Sprite2d-Geom")

            # The positions to create the card at
            if anchorX == self.ALIGN_LEFT:
                posLeft = 0
                posRight = (self.colSize / scale) * repeatX
            elif anchorX == self.ALIGN_CENTER:
                posLeft = -(self.colSize / 2.0 / scale) * repeatX
                posRight = (self.colSize / 2.0 / scale) * repeatX
            elif anchorX == self.ALIGN_RIGHT:
                posLeft = -(self.colSize / scale) * repeatX
                posRight = 0

            if anchorY == self.ALIGN_BOTTOM:
                posTop = 0
                posBottom = (self.rowSize / scale) * repeatY
            elif anchorY == self.ALIGN_CENTER:
                posTop = -(self.rowSize / 2.0 / scale) * repeatY
                posBottom = (self.rowSize / 2.0 / scale) * repeatY
            elif anchorY == self.ALIGN_TOP:
                posTop = -(self.rowSize / scale) * repeatY
                posBottom = 0

            card.setFrame(posLeft, posRight, posTop, posBottom)
            card.setHasUvs(True)
            self.cards.append(self.node.attachNewNode(card.generate()))
            self.cards[-1].setH(i * 360 / len(rowPerFace))

        # Since the texture is padded, we need to set up offsets and scales to make
        # the texture fit the whole card
        self.offsetX = (float(self.colSize) / textureSizeX)
        self.offsetY = (float(self.rowSize) / textureSizeY)

        # self.node.setTexScale(TextureStage.getDefault(), self.offsetX * repeatX, self.offsetY * repeatY)
        # self.node.setTexOffset(TextureStage.getDefault(), 0, 1-self.offsetY)

        self.texture = Texture()

        self.texture.setXSize(textureSizeX)
        self.texture.setYSize(textureSizeY)
        self.texture.setZSize(1)

        # Load the padded PNMImage to the texture
        self.texture.load(self.paddedImg)

        self.texture.setMagfilter(Texture.FTNearest)
        self.texture.setMinfilter(Texture.FTNearest)

        #Set up texture clamps according to repeats
        if repeatX > 1:
            self.texture.setWrapU(Texture.WMRepeat)
        else:
            self.texture.setWrapU(Texture.WMClamp)
        if repeatY > 1:
            self.texture.setWrapV(Texture.WMRepeat)
        else:
            self.texture.setWrapV(Texture.WMClamp)

        self.node.setTexture(self.texture)
        self.setFrame(0)
Ejemplo n.º 57
0
class ToonBlitzAssetMgr(DirectObject):
    notify = DirectNotifyGlobal.directNotify.newCategory(
        'DistributedToonBlitzAssets')

    def __init__(self, game):
        self.__defineConstants()
        self.game = game
        self.load()

    def __defineConstants(self):
        pass

    def load(self):
        self.world = NodePath('ToonBlitzWorld')
        self.background = loader.loadModel(
            'phase_4/models/minigames/toonblitz_game')
        self.background.reparentTo(self.world)
        self.startingWall = loader.loadModel(
            'phase_4/models/minigames/toonblitz_game_wall')
        self.startingPipe = loader.loadModel(
            'phase_4/models/minigames/toonblitz_game_start')
        self.exitElevator = loader.loadModel(
            'phase_4/models/minigames/toonblitz_game_elevator')
        self.arrow = loader.loadModel(
            'phase_4/models/minigames/toonblitz_game_arrow')
        self.sprayProp = loader.loadModel(
            'phase_4/models/minigames/prop_waterspray')
        self.treasureModelList = []
        salesIcon = loader.loadModel('phase_4/models/minigames/salesIcon')
        self.treasureModelList.append(salesIcon)
        moneyIcon = loader.loadModel('phase_4/models/minigames/moneyIcon')
        self.treasureModelList.append(moneyIcon)
        legalIcon = loader.loadModel('phase_4/models/minigames/legalIcon')
        self.treasureModelList.append(legalIcon)
        corpIcon = loader.loadModel('phase_4/models/minigames/corpIcon')
        self.treasureModelList.append(corpIcon)
        self.particleGlow = loader.loadModel(
            'phase_4/models/minigames/particleGlow')
        self.blockTypes = []
        for i in xrange(4):
            blockType = loader.loadModel(
                'phase_4/models/minigames/toonblitz_game_block0' + str(i))
            self.blockTypes.append(blockType)

        self.stomper = loader.loadModel(
            'phase_4/models/minigames/toonblitz_game_stomper')
        plane = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, -50)))
        dropPlane = CollisionNode('dropPlane')
        dropPlane.addSolid(plane)
        dropPlane.setCollideMask(ToontownGlobals.FloorBitmask)
        self.world.attachNewNode(dropPlane)
        self.gameMusic = base.loadMusic('phase_4/audio/bgm/MG_TwoDGame.ogg')
        self.treasureGrabSound = loader.loadSfx(
            'phase_4/audio/sfx/SZ_DD_treasure.ogg')
        self.sndOof = base.loadSfx('phase_4/audio/sfx/MG_cannon_hit_dirt.ogg')
        self.soundJump = base.loadSfx(
            'phase_4/audio/sfx/MG_sfx_vine_game_jump.ogg')
        self.fallSound = base.loadSfx(
            'phase_4/audio/sfx/MG_sfx_vine_game_fall.ogg')
        self.watergunSound = base.loadSfx(
            'phase_4/audio/sfx/AA_squirt_seltzer_miss.ogg')
        self.splashSound = base.loadSfx(
            'phase_4/audio/sfx/Seltzer_squirt_2dgame_hit.ogg')
        self.threeSparkles = loader.loadSfx(
            'phase_4/audio/sfx/threeSparkles.ogg')
        self.sparkleSound = loader.loadSfx('phase_4/audio/sfx/sparkly.ogg')
        self.headCollideSound = loader.loadSfx(
            'phase_3.5/audio/sfx/AV_collision.ogg')
        self.faceStartPos = Vec3(-0.8, 0, -0.87)
        self.faceEndPos = Vec3(0.8, 0, -0.87)
        self.aspect2dRoot = aspect2d.attachNewNode('TwoDGuiAspect2dRoot')
        self.aspect2dRoot.setDepthWrite(1)
        self.cardMaker = CardMaker('card')
        self.cardMaker.reset()
        self.cardMaker.setName('ProgressLine')
        self.cardMaker.setFrame(-0.5, 0.5, -0.5, 0.5)
        self.progressLine = self.aspect2dRoot.attachNewNode(
            self.cardMaker.generate())
        self.progressLine.setScale(self.faceEndPos[0] - self.faceStartPos[0],
                                   1, 0.01)
        self.progressLine.setPos(0, 0, self.faceStartPos[2])
        self.cardMaker.setName('RaceProgressLineHash')
        for n in xrange(
                ToonBlitzGlobals.NumSections[self.game.getSafezoneId()] + 1):
            hash = self.aspect2dRoot.attachNewNode(self.cardMaker.generate())
            hash.setScale(self.progressLine.getScale()[2], 1,
                          self.progressLine.getScale()[2] * 5)
            t = float(n) / ToonBlitzGlobals.NumSections[
                self.game.getSafezoneId()]
            hash.setPos(
                self.faceStartPos[0] * (1 - t) + self.faceEndPos[0] * t,
                self.faceStartPos[1], self.faceStartPos[2])

    def destroy(self):
        while len(self.blockTypes):
            blockType = self.blockTypes[0]
            self.blockTypes.remove(blockType)
            del blockType

        self.blockTypes = None
        while len(self.treasureModelList):
            treasureModel = self.treasureModelList[0]
            self.treasureModelList.remove(treasureModel)
            del treasureModel

        self.treasureModelList = None
        self.startingWall.removeNode()
        del self.startingWall
        self.startingPipe.removeNode()
        del self.startingPipe
        self.exitElevator.removeNode()
        del self.exitElevator
        self.stomper.removeNode()
        del self.stomper
        self.arrow.removeNode()
        del self.arrow
        self.sprayProp.removeNode()
        del self.sprayProp
        self.aspect2dRoot.removeNode()
        del self.aspect2dRoot
        self.world.removeNode()
        del self.world
        del self.gameMusic
        del self.treasureGrabSound
        del self.sndOof
        del self.soundJump
        del self.fallSound
        del self.watergunSound
        del self.splashSound
        del self.threeSparkles
        del self.sparkleSound
        del self.headCollideSound
        self.game = None
        return

    def onstage(self):
        self.world.reparentTo(render)
        base.playMusic(self.gameMusic, looping=1, volume=0.9)

    def offstage(self):
        self.world.hide()
        self.gameMusic.stop()

    def enterPlay(self):
        pass

    def exitPlay(self):
        pass

    def enterPause(self):
        pass

    def exitPause(self):
        pass

    def playJumpSound(self):
        base.localAvatar.soundRun.stop()
        base.playSfx(self.soundJump, looping=0)

    def playWatergunSound(self):
        self.watergunSound.stop()
        base.playSfx(self.watergunSound, looping=0)

    def playSplashSound(self):
        self.splashSound.stop()
        base.playSfx(self.splashSound, looping=0)

    def playHeadCollideSound(self):
        self.headCollideSound.stop()
        base.playSfx(self.headCollideSound, looping=0)
class Shooter(FSM):
	def __init__(self, character):
		FSM.__init__(self, "ShooterFSM")
		
		self.character = character
		self.world = self.character.world

		# Set firing control handlers.
		base.accept("mouse1", self.request, ["Shooting"])
		base.accept("mouse1-up", self.request, ["Waiting"])

		# Create power meter.
		self.meter = base.render2d.attachNewNode("powerMeter")
		self.meter.setPos(-0.2, 0.0, 0.0)
		self.meter.hide()

		self.meterBGCard = CardMaker("powerMeterBG")
		self.meterBGCard.setFrame(0.0, 0.4, -0.9, -0.95)
		self.meterBGCard.setColor(0.5, 0.0, 0.0, 1.0)
		self.meterBG = self.meter.attachNewNode(self.meterBGCard.generate())

		self.meterFGCard = CardMaker("powerMeterFG")
		self.meterFGCard.setFrame(0.0, 0.4, -0.9, -0.95)
		self.meterFGCard.setColor(1.0, 0.0, 0.0, 1.0)
		self.meterFG = self.meter.attachNewNode(self.meterFGCard.generate())

		# Create gun.
		self.gun = loader.loadModel("models/ak47.egg")
		self.gun.reparentTo(base.camera)
		self.gun.setHpr(60, 104, 232)
		self.gun.setPos(4.0, 14.0, -3.5)
		self.gun.setScale(1.75)
		self.gunRecoil = None

		# Make gun get drawn on top.
		self.gun.setBin("fixed", 40)
		self.gun.setDepthTest(False)
		self.gun.setDepthWrite(False)

		# Load gunshot sound
		self.gunSfx = base.loader.loadSfx("media/gun.wav")
		self.gunSfx.setVolume(0.6)

	def exitShooting(self):
		angSpeed = 20.0 + (40.0 * self.powerLevel)
		linSpeed = 80.0 + (320.0 * self.powerLevel)
		color = (0.7 + 0.1*random(), 0.7 + 0.1*random(), 0.7 + 0.1*random())

		dir = self.character.getDir()
		bullet = Bullet(self.world, base.render, color, (0.0, 0.0, 0.0), dir, 0.3, 80, self.character.node)
		bullet.body.setLinearVel(dir * linSpeed)
		bullet.body.setAngularVel(dir * angSpeed)

		self.gunSfx.play()
		self.meter.hide()
		base.taskMgr.remove("powerMeterGauge")

		# Recoil and camera flash
		self.recoil()
		self.character.recoil(12)
		self.world.game.cameraHandler.flash((1,1,1,0.5), 0.2)

	def enterShooting(self):
		self.powerLevel = 0.5
		self.powerDir = 1
		self.meter.show()
		self.refreshMeter()
		base.taskMgr.add(self.gaugeTask, "powerMeterGauge")

	def gaugeTask(self, task):
		self.powerLevel += globalClock.getDt() * self.powerDir
		if self.powerLevel > 1:
			self.powerLevel = 1
			self.powerDir = -1
		elif self.powerLevel < 0:
			self.powerLevel = 0
			self.powerDir = 1
		self.refreshMeter()
		return task.cont

	def refreshMeter(self):
		self.meterFG.setSx(self.powerLevel)

	def recoil(self):
		if self.gunRecoil != None:
			self.gunRecoil.finish()
		self.gunRecoil = Sequence(LerpPosInterval(self.gun, 0.1, Point3(4.0, 12.0, -3.5)),
			LerpPosInterval(self.gun, 0.6, Point3(4.0, 14.0, -3.5), Point3(4.0, 12.0, -3.5)))
		self.gunRecoil.start()
Ejemplo n.º 59
0
    def __init__(self, manager, xml):
        self.updateTask = None

        self.sun = base.cam.attachNewNode('sun')
        loader.loadModel(
            manager.get('paths').getConfig().find('misc').get('path') +
            '/sphere').reparentTo(self.sun)
        self.sun.setScale(0.1)
        self.sun.setTwoSided(True)
        self.sun.setColorScale(10.0, 10.0, 10.0, 1.0, 10001)
        self.sun.setLightOff(1)
        self.sun.setShaderOff(1)
        self.sun.setFogOff(1)
        self.sun.setCompass()
        self.sun.setBin('background', 10)
        self.sun.setDepthWrite(False)
        self.sun.setDepthTest(False)
        # Workaround an annoyance in Panda. No idea why it's needed.
        self.sun.node().setBounds(OmniBoundingVolume())
        isa = xml.find('isa')
        inst = xml.find('instance')
        if isa != None or inst != None:
            if inst != None:
                orig = Vec3(float(inst.get('x',
                                           '0')), float(inst.get('y', '0')),
                            float(inst.get('z', '0')))
            else:
                level = manager.get(isa.get('source'))
                orig = Vec3(level.getByIsA(isa.get('name'))[0].getPos(render))
            orig.normalize()
            self.sun.setPos(orig)

        godrays = xml.find('godrays')
        if godrays != None:
            self.vlbuffer = base.win.makeTextureBuffer('volumetric-lighting',
                                                       base.win.getXSize() / 2,
                                                       base.win.getYSize() / 2)
            self.vlbuffer.setClearColor(Vec4(0, 0, 0, 1))
            cam = base.makeCamera(self.vlbuffer)
            cam.node().setLens(base.camLens)
            cam.reparentTo(base.cam)
            initstatenode = NodePath('InitialState')
            initstatenode.setColorScale(0, 0, 0, 1, 10000)
            initstatenode.setShaderOff(10000)
            initstatenode.setLightOff(10000)
            initstatenode.setMaterialOff(10000)
            initstatenode.setTransparency(TransparencyAttrib.MBinary, 10000)
            cam.node().setCameraMask(BitMask32.bit(2))
            cam.node().setInitialState(initstatenode.getState())
            self.vltexture = self.vlbuffer.getTexture()
            self.vltexture.setWrapU(Texture.WMClamp)
            self.vltexture.setWrapV(Texture.WMClamp)
            card = CardMaker('VolumetricLightingCard')
            card.setFrameFullscreenQuad()
            self.finalQuad = render2d.attachNewNode(card.generate())
            self.finalQuad.setAttrib(
                ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                      ColorBlendAttrib.OIncomingColor,
                                      ColorBlendAttrib.OFbufferColor))

            self.finalQuad.setShader(
                Shader.load(
                    posixpath.join(
                        manager.get('paths').getConfig().find('shaders').get(
                            'path'), 'filter-vlight.cg')))
            self.finalQuad.setShaderInput('src', self.vltexture)
            self.finalQuad.setShaderInput(
                'vlparams', 32, 0.9 / 32.0, 0.97, 0.5
            )  # Note - first 32 is now hardcoded into shader for cards that don't support variable sized loops.
            self.finalQuad.setShaderInput('casterpos', 0.5, 0.5, 0, 0)
            # Last parameter to vlcolor is the exposure
            vlcolor = Vec4(float(godrays.get('r', '1')),
                           float(godrays.get('g', '1')),
                           float(godrays.get('b', '1')), 0.04)

            self.finalQuad.setShaderInput('vlcolor', vlcolor)
        else:
            self.finalQuad = None
Ejemplo n.º 60
0
 def _initGUI(self):
     base.loadingScreen.beginStep('init Gui', 4, 55)
     cm = CardMaker('PotionBackground')
     cm.setFrame(-10, 10, -10, 10)
     cm.setColor(0, 0, 0, 1)
     self.background = NodePath(cm.generate())
     self.background.reparentTo(aspect2d)
     self.background.setBin('background', -100)
     self.xpBackground = NodePath('PotionXPBackground')
     self.xpBackground.reparentTo(aspect2d)
     self.xpBackground.setBin('background', -95)
     base.loadingScreen.tick()
     self.dialogs = NodePath('DialogBackground')
     self.dialogs.reparentTo(aspect2d)
     self.dialogs.setBin('background', -70)
     self.buttonsBackground = NodePath('PotionButtonBackground')
     self.buttonsBackground.reparentTo(base.a2dBottomRight)
     self.buttonsBackground.setBin('background', -90)
     textureCard = loader.loadModel(
         'models/minigames/pir_m_gui_pot_textureCard')
     self.stretchedBackgroundTextureCard = textureCard.find(
         '**/pir_t_gui_pot_background')
     self.stretchedBackgroundTextureCard.reparentTo(self.background)
     self.stretchedBackgroundTextureCard.setScale(3.4, 1.0, 3.4)
     self.stretchedBackgroundTextureCard.setPos(0.0, 20.0, 0.0)
     fadecm = CardMaker('card')
     fadecm.setFrameFullscreenQuad()
     self.fadeIn = render2d.attachNewNode(fadecm.generate())
     self.fadeIn.setBin('background', -50)
     self.fadeIn.setPos(0.0, -30.0, 0.0)
     self.fadeIn.setColor(0, 0, 0, 1.0)
     self.fadeIn.setTransparency(True)
     base.loadingScreen.tick()
     cm = CardMaker('card')
     cm.setFrame(0, 1, 0.01, 0.01)
     self.foregroundLayer = aspect2d.attachNewNode(cm.generate())
     self.foregroundTextureCard = textureCard.find(
         '**/pir_t_gui_pot_foreground')
     self.foregroundTextureCard.setScale(0.8, 1.0, 0.4)
     self.foregroundTextureCard.setPos(-0.7, -20.0, 0.8)
     self.foregroundTextureCard.setBin('background', -80)
     self.foregroundTextureCard.copyTo(self.foregroundLayer)
     self.repMeter = ReputationMeter.ReputationMeter(
         InventoryType.PotionsRep, width=0.56)
     inv = localAvatar.getInventory()
     self.repMeter.reparentTo(self.xpBackground)
     self.repMeter.setPos(0, 0, -0.95)
     self.repMeter.update(inv.getAccumulator(InventoryType.PotionsRep))
     localAvatar.guiMgr.registerReputationHandler(self.updateRepMeter)
     base.loadingScreen.tick()
     self.closeButton = GuiButton.GuiButton(
         image=(textureCard.find('**/pir_t_gui_pot_escape'),
                textureCard.find('**/pir_t_gui_pot_escapeOn'),
                textureCard.find('**/pir_t_gui_pot_escapeOn'),
                textureCard.find('**/pir_t_gui_pot_escape')),
         image_scale=(0.1, 0.1, 0.1),
         image_pos=(0.075, 0, 0.08),
         hotkeys=['Escape'],
         hotkeyLabel=PLocalizer.PotionGui['ExitButton'],
         pos=(-0.4, 0.0, 0.01),
         text0_fg=PotionGlobals.TextColor,
         text1_fg=PiratesGuiGlobals.TextFG0,
         text2_fg=PiratesGuiGlobals.TextFG15,
         text3_fg=PotionGlobals.TextColorDisabled,
         parent=self.buttonsBackground,
         command=self.confirmQuit)
     self.returnButton = GuiButton.GuiButton(
         text=(PLocalizer.PotionGui['SwitchRecipe'],
               PLocalizer.PotionGui['SwitchRecipe'],
               PLocalizer.PotionGui['SwitchRecipe'],
               PLocalizer.PotionGui['SwitchRecipe']),
         pos=(-0.58, 0.0, -0.62),
         text_scale=PiratesGuiGlobals.TextScaleExtraLarge,
         text_shadow=None,
         image=(None, None, None, None),
         text0_fg=PotionGlobals.TextColor,
         text1_fg=PiratesGuiGlobals.TextFG0,
         text2_fg=PiratesGuiGlobals.TextFG15,
         text3_fg=PotionGlobals.TextColorDisabled,
         parent=self.background,
         command=self.confirmReturn)
     self.returnButton.stash()
     self.hintsButton = GuiButton.GuiButton(
         text=(PLocalizer.PotionGui['ShowTutorial'],
               PLocalizer.PotionGui['ShowTutorial'],
               PLocalizer.PotionGui['ShowTutorial'],
               PLocalizer.PotionGui['ShowTutorial']),
         text_scale=PiratesGuiGlobals.TextScaleSmall,
         image_scale=(0.25, 0.1, 0.18),
         image_pos=(0, 0, 0),
         pos=(-0.53, 0.0, 0.075),
         parent=self.buttonsBackground,
         command=self.showLastHint)
     self.InfoButton = GuiButton.GuiButton(
         text=(PLocalizer.PotionGui['IngredientList'],
               PLocalizer.PotionGui['IngredientList'],
               PLocalizer.PotionGui['IngredientList'],
               PLocalizer.PotionGui['IngredientList']),
         text_scale=PiratesGuiGlobals.TextScaleSmall,
         image_scale=(0.3, 0.1, 0.18),
         image_pos=(0, 0, 0),
         pos=(-0.84, 0.0, 0.075),
         parent=self.buttonsBackground,
         command=self.showInfo)
     textureCard.removeNode()
     base.loadingScreen.endStep('init Gui')
     return