def update_rank(self, task):
        #self.display_rank.destroy()
        #self.display_lap.destroy()

        # Your Rank
        #rank = str(self.rm.rank) + "/" + str(self.rm.racers)
        # self.display_rank = OnscreenText(text=rank, style=1, fg=(1, 1, 1, 1),
        #                                  pos=(-.8, .85), align=TextNode.ALeft,
        #                                  scale=.15, font=self.font_digital)
        #
        # #laps = str(self.rm.laps) + " Laps - " + str(self.rm.checkpointspassed)
        # self.display_lap = OnscreenText(text=laps, style=1, fg=(1, 1, 1, 1), pos=(1.0, .89), align=TextNode.ALeft,
        #                                 font=self.font_digital, scale=.06)

        # Leader board
        self.leader1.destroy()
        self.leader2.destroy()
        self.leader3.destroy()
        lead1 = "1:" + self.lead1
        lead2 = "2:" + self.lead2
        lead3 = "3:" + self.lead3
        self.leader1 = OnscreenText(text=lead1, style=1, fg=(1, 1, 1, 1),
                                    pos=(-1.3, .5), align=TextNode.ALeft,
                                    scale=.07, font=self.font_digital)
        self.leader2 = OnscreenText(text=lead2, style=1, fg=(1, 1, 1, 1),
                                    pos=(-1.3, .45), align=TextNode.ALeft,
                                    scale=.07, font=self.font_digital)
        self.leader3 = OnscreenText(text=lead3, style=1, fg=(1, 1, 1, 1),
                                    pos=(-1.3, .4), align=TextNode.ALeft,
                                    scale=.07, font=self.font_digital)

        return task.cont
Example #2
0
class GameHUD:
     def __init__(self):
        #Creates the HUD elements.


        self.stabilityBar = OnscreenImage(image = "../images/100.png", pos = (1.2, 0, .1))
        self.stabilityBar.setScale(.05,1,.65)
        self.stabilityBar.setTransparency(TransparencyAttrib.MAlpha)

        self.actionCommand = OnscreenImage(image = '../images/open.png', pos = (.95, 0, -.75), scale = (0.33, 1, 0.2))
        self.actionCommand.setTransparency(TransparencyAttrib.MAlpha)

        self.score = OnscreenText(text = 'Score: 0', align = TextNode.ALeft, pos = (-1.3, -.9), scale = 0.10, fg = (1,1,1,1), mayChange = True)
        self.score.align = TextNode.ALeft
        self.score.setText('Depth: 0')
        #self.score.setScale(.2,.2,.2)

     def updateHud(self, NewStability, NewScore, NewActionCommand):
        #Updates the HUD using the inputted values.
        self.score.setText('Depth: ' + str(NewScore))

        if NewStability >= 100:
            self.stabilityBar.setImage('../images/100.png')
        elif NewStability >= 90:
            self.stabilityBar.setImage('../images/90.png')
        elif NewStability >= 80:
            self.stabilityBar.setImage('../images/80.png')
        elif NewStability >= 70:
            self.stabilityBar.setImage('../images/70.png')
        elif NewStability >= 60:
            self.stabilityBar.setImage('../images/60.png')
        elif NewStability >= 50:
            self.stabilityBar.setImage('../images/50.png')
        elif NewStability >= 40:
            self.stabilityBar.setImage('../images/40.png')
        elif NewStability >= 30:
            self.stabilityBar.setImage('../images/30.png')
        elif NewStability >= 20:
            self.stabilityBar.setImage('../images/20.png')
        elif NewStability >= 10:
            self.stabilityBar.setImage('../images/10.png')
        elif NewStability >= 0:
            self.stabilityBar.setImage('../images/0.png')

        if NewActionCommand == []:
            self.actionCommand.setImage('../images/open.png')
        elif NewActionCommand == ['l','d']:
            self.actionCommand.setImage('../images/left_down.png')
        elif NewActionCommand == ['r','d']:
            self.actionCommand.setImage('../images/right_down.png')
        elif NewActionCommand == ['l','u']:
            self.actionCommand.setImage('../images/left_up.png')
        elif NewActionCommand == ['r','u']:
            self.actionCommand.setImage('../images/right_up.png')
        elif NewActionCommand == ['u','d']:
            self.actionCommand.setImage('../images/up_down.png')
        elif NewActionCommand == ['l','r']:
            self.actionCommand.setImage('../images/left_right.png')

        self.actionCommand.setTransparency(TransparencyAttrib.MAlpha)
Example #3
0
    def guiLoop(self, task):
    
        #Scroll up and down to scroll through weapons
        if self.keys["swap-up"]:
            if self.wepCounter < 2:
                self.wepCounter += 1
            else:
                self.wepCounter = 0
            self.wepDisplay.remove()
            self.wepDisplay = OnscreenText(text = "%s" % (self.wepAmmo[self.wepCounter]), fg = (0,1,1,1), pos = (.95, -.9), scale = .125, font = self.font)
            self.wepIcon.remove()
            self.wepIcon = OnscreenImage(image = "../assets/2d/icons/weapon%s.png" % (self.wepCounter), pos = (1.19, 0, -.875), scale=(.1,1,.1))
            self.wepIcon.setTransparency(TransparencyAttrib.MAlpha)
            self.keys["swap-up"] = 0
        if self.keys["swap-down"]:
            if self.wepCounter > 0:
                self.wepCounter -= 1
            else:
                self.wepCounter = 2
            self.wepDisplay.remove()
            self.wepDisplay = OnscreenText(text = "%s" % (self.wepAmmo[self.wepCounter]), fg = (0,1,1,1), pos = (.95, -.9), scale = .125, font = self.font)
            self.wepIcon.remove()
            self.wepIcon = OnscreenImage(image = "../assets/2d/icons/weapon%s.png" % (self.wepCounter), pos = (1.19, 0, -.875), scale=(.1,1,.1))
            self.wepIcon.setTransparency(TransparencyAttrib.MAlpha)
            self.keys["swap-down"] = 0

        return Task.cont
Example #4
0
    def __init__(self, engine):
        print 'new hud'
        self.engine = engine
        self.node = aspect2d.attachNewNode('hud')#GUIOrder.ORDER[GUIOrder.HUD])
        self.node.setBin('fixed', GUIOrder.ORDER[GUIOrder.HUD])
        self.crossHair = CrossHair()
#        self.crossHair = OnscreenImage(image = 'Assets/Images/Crosshairs/cross.png', scale = 256.0 / 1024)
#        self.crossHair.setTransparency(TransparencyAttrib.MAlpha)
#        self.crossHair.reparentTo(self.node)
        
        if(engine):
            self.hudHotbar = HUDHotbar(engine.menuController.invGUI.mainInventory)
        
        self.selectedPlayerName =  OnscreenText(text = '', pos = (0, -0.7), scale = 0.06, fg = (1, 1, 1, 1), shadow = (0, 0, 0, 1), mayChange = True)
        self.selectedPlayerName.reparentTo(self.node)
        self.selectedPlayerName.setBin('fixed', GUIOrder.ORDER[GUIOrder.HUD])
        
        self.personalDeathMessage =  OnscreenText(text = '', pos = (0, -0.6), scale = 0.06, fg = (1, 1, 1, 1), shadow = (0, 0, 0, 1), mayChange = True)
        self.personalDeathMessage.reparentTo(self.node)
        self.personalDeathMessage.setBin('fixed', GUIOrder.ORDER[GUIOrder.HUD])
        
        self.HUDBL = HUDBottomLeft()
        self.HUDBR = HUDBottomRight()
        self.enemyFireIndicator = EnemyFireIndicator()
        self.hitMarker = HitMarker()
        
        self.accept(PlayerSelectedEvent.EventName, self.OnPlayerSelectedEvent)
        self.accept(PlayerDeathEvent.EventName, self.OnPlayerDeathEvent)
        self.accept(ADSEvent.EventName, self.OnADSEvent)
Example #5
0
    def collide(self, collEntry):
        global score,E1posY,gameover,adj, CposY
        if self.environ1.getY()==-100:
            return
        if(collEntry.getIntoNodePath().getParent().getName()== "icosahedron.egg"):
            #print collEntry.getIntoNodePath().getParent().getName() 
            collEntry.getIntoNodePath().getParent().remove()
            score= score +10
            print score
            self.title.detachNode()
            self.title = OnscreenText(text="SCORE: " + str(score), style=1, fg=(1,1,0,1), pos=(-0.95,0.85), scale = .07, mayChange = True)

        elif(collEntry.getIntoNodePath().getParent().getName()== "anvil.egg"):
                E1posY= E1posY-50
                CposY= CposY-50
                self.camera.setPos(CposX, CposY, CposZ)
                self.environ1.setPos(E1posX, E1posY, E1posZ)
                gameover= gameover - 1
                self.title1.detachNode()
                self.title1= OnscreenText(text="LIVES: " + str(int(gameover/2)), style=1, fg=(1,1,0,1), pos=(-0.95, 0.7), scale = .07, mayChange = True)
                print gameover
                if(gameover<=0):
                    print "Game Over"
##                    time2= int(time-(task.time*0.5))
##                    if time1!=time2:
##                    self.inst2.detachNode()
##                    self.inst2 = addInstructions(0.89, "Time: "+str(time2))   
##                    time1=time2
##                    if time2==0:
                    OnscreenText(text= "GAME OVER", style=1, fg=(1,1,1,1),pos=(-0.9,0), align=TextNode.ALeft, scale = 0.35)
                    OnscreenText(text= "Your Final Score is " + str(score), style=1, fg=(1,1,0,1), pos=(-0.95, -0.05), align=TextNode.ALeft, scale=0.015)
                    #time.sleep(10)
                    #sys.exit
                    self.environ1.detachNode()
                    self.camera.detachNode()
 def checkGameState(self, task, message = None):
     goodEndingText = OnscreenText(text="", style=1, fg=(0,0,1,0.01),
                         pos=(0,.4), align=TextNode.ACenter, scale = .25, mayChange = True)
     BaadEndingText = OnscreenText(text="", style=1, fg=(1,0,0,0.01),
                         pos=(0,.4), align=TextNode.ACenter, scale = .25, mayChange = True)
     if(self.fadeCounter > 0):
         if(self.__mainAgent.hasKey(self.room1Key) and self.__mainAgent.hasKey(self.room2Key) and self.__mainAgent.hasKey(self.room3Key)):
             self.hasAllKeys = True
             #goodEndingText.setText("You have all 3 keys!")
         if(self.hasAllKeys):
             goodEndingText.setText("You have all 3 keys!")
         if(PathFinder.distance(self.__mainAgent, self.__room1NPC) < 5 and self.__room1NPC.getState() != "returnKey"):
             if(not self.__mainAgent.hasKey(self.room1Key)):
                 self.playerWasKilledByNPC1 = True
         if(self.playerWasKilledByNPC1):
             self.fadeCounter = self.fadeCounter - 1
             BaadEndingText.setText("Killed by Eve clone Alpha")
         if(PathFinder.distance(self.__mainAgent, self.__room2NPC) < 5 and self.__room2NPC.getState() != "returnKey"):
             if(not self.__mainAgent.hasKey(self.room2Key)):
                 self.playerWasKilledByNPC2 = True
         if(self.playerWasKilledByNPC2):
             self.fadeCounter = self.fadeCounter - 1
             BaadEndingText.setText("Killed by Eve clone Beta")
         if(PathFinder.distance(self.__mainAgent, self.__room3NPC) < 5 and self.__room3NPC.getState() != "returnKey"):
             if(not self.__mainAgent.hasKey(self.room3Key)):
                 self.playerWasKilledByNPC3 = True
         if(self.playerWasKilledByNPC3):
             self.fadeCounter = self.fadeCounter - 1
             BaadEndingText.setText("Killed by Eve clone Gamma")
     return Task.cont
Example #7
0
    def LoadHUD(self):
        self.player1HUD = OnscreenText(
            text = "Player 1: " + str( self.ship1.getPoints() ),
            fg = (1,1,1,1),
            #pos = ( x, y )
            pos = (0.7,0.9),
            align = TextNode.ALeft,
            scale = Game.HUD_TEXT_SCALE
        )
        
        self.player2HUD = OnscreenText(
            text = "Player 2: " + str( self.ship2.getPoints() ),
            fg = (1,1,1,1),
            pos = (-0.7,0.9),
            align = TextNode.ALeft,
            scale = Game.HUD_TEXT_SCALE
        )

        
        self.winnerText = OnscreenText(
            text = "Tekstia, tekstia, tekstia",
            fg = (1,1,1,1),
            pos = (-0.2, 0),
            align = TextNode.ALeft,
            scale = Game.HUD_TEXT_SCALE*3
        )
#        self.winnerText.setZ(200)
        self.winnerText.hide()
Example #8
0
    def createCreateCharWindow(self):
        self.frame = DirectFrame(frameColor=(0, 0, 0, 1), #(R,G,B,A)
                                frameSize=(-3, 3, -3, 3),#(Left,Right,Bottom,Top)
                                pos=(-0.5, 0, 0.9))
        self.buttons = [
        DirectRadioButton(text = ' Sword ', variable=self.v, value=[0], scale=0.07, pos=(-0.4,0,0.32), command=self.setText),
        DirectRadioButton(text = ' Axe ', variable=self.v, value=[1], scale=0.07, pos=(0.2,0,0.32), command=self.setText)
        ]
 
        for button in self.buttons:
            button.setOthers(self.buttons)
        
        self.nameOfChar = OnscreenText(text = "Name The Character :", pos = (-0.2, -0.75), scale = 0.08,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=0)
        self.nameOfChar.reparentTo(self.frame)    
        self.nameOfCharTextbox = DirectEntry(text = "" ,scale=.07,pos=(0.25,0, -.75),command=self.setnameOfChar,initialText="name of character", numLines = 1,focus=0,focusInCommand=self.clearnameOfChar, focusOutCommand=self.getnameOfChar)
        self.nameOfCharTextbox.reparentTo(self.frame)   
        
        self.factionSelection = OnscreenText(text = "Faction Selection :", pos = (-0.15, -0.95), scale = 0.08,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=0)
        self.factionSelection.reparentTo(self.frame)
        
        self.factionBtns = [
        DirectRadioButton(text = ' Blue ', variable=self.v1, value=[0], scale=0.07, pos=(-0.05,0,-0.05), command=self.setfaction),
        DirectRadioButton(text = ' Red ', variable=self.v1, value=[1], scale=0.07, pos=(0.3,0,-0.05), command=self.setfaction)
        ]
         
        for button1 in self.factionBtns:
            button1.setOthers(self.factionBtns)
        self.okForCreateBtn = DirectButton(text = ("Ok", "Ok", "Ok", "disabled"), scale=.08, command=self.clickedOkForCreateBtn, pos=(-0.05, 0.0, -1.25))
        self.cancelForCreateBtn =  DirectButton(text = ("Cancel", "Cancel", "Cancel", "disabled"), scale=.08, command=self.clickedCancelForCreateBtn, pos=(0.4, 0.0, -1.25))
        self.okForCreateBtn.reparentTo(self.frame)
        self.cancelForCreateBtn.reparentTo(self.frame)
Example #9
0
    def __init__(self, vrc):
        self.vrc = vrc
        self.mode = OnscreenText(
            align = TextNode.ALeft,
            pos = (-0.99, 0.9),
            scale = 0.06,
            fg = (0,0,0,1),
            bg = (1,1,1,1),
            mayChange = True
        )
        self.visual = OnscreenText(
            align = TextNode.ALeft,
            pos = (-0.99, 0.8),
            scale = 0.06,
            fg = (0,0,0,1),
            bg = (1,1,1,1),
            mayChange = True
        )
        self.cam = OnscreenText(
            align = TextNode.ALeft,
            pos = (-0.99, 0.7),
            scale = 0.06,
            fg = (0,0,0,1),
            bg = (1,1,1,1),
            mayChange = True
        )

        self.mode.setText("mode: " + self.vrc.mode)
        self.visual.setText("visual: " + self.vrc.activeVisual.__class__.__name__)
        pos = self.vrc.cam.getPos()
        self.cam.setText("cam: " + str(pos[0]) + "/" + str(pos[1]) + "/" + str(pos[2]))
Example #10
0
 def __init__(self):
     ShowBase.__init__(self)
     Globals.OFFLINE = False
     self.client = 0
     self.engine = 0
     
     #PStatClient.connect()
     
     wp = WindowProperties()
     wp.setSize(Settings.WIDTH, Settings.HEIGHT)
     wp.setTitle("Modifire")
     wp.setMouseMode(WindowProperties.MRelative)
     #wp.setCursorHidden(True) 
     base.win.requestProperties(wp)
     base.setBackgroundColor(0.133, 0.133, 0.133) 
     self.disableMouse()
     self.client = Client()
     self.mainMenu = MainMenu()
     self.SetupEventHandlers()
     self.pid = -1
     self.loadingScreen = None
     
     SettingsController.LoadClientSettings()
     
     version = OnscreenText(text = Globals.VERSION, pos = (0.3, -0.07), scale = 0.07, fg = (1, 1, 1, 1))
     version.reparentTo(base.a2dTopLeft)
     version.setBin('fixed', 200)
     
     Preloader.Preload()
class SMGUIMeter():
	
	def __init__(self, maxValue):
		meterImg = None
		self.value = 0.0
		self.maxValue = maxValue
		self.text = OnscreenText(text = "0", style = 1, fg = (0,0,0,1), pos = (-1.2, -0.95), align = TextNode.ALeft, scale = .2)

	def fillBy(self, amt):
		if(self.value + amt > self.maxValue):
			self.value = self.maxValue
		else:
			self.value += amt
	
	def emptyBy(self, amt):
		if(self.value - amt < 0):
			self.value = self.maxValue
		else:
			self.value = 0
	
	def updateSnow(self, playerObj):
		self.value = playerObj.getSnow()
	
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Returns the GUI element type.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def getGUIType(self):
		return 2
		
	def updateGUI(self):
		self.text.setText(str(self.value))
Example #12
0
class TeamSelectMenu(Menu):
    
    def __init__(self):
        Menu.__init__(self)
        self.LoadContent()
        self.accept(ListOfConnectedPlayersReceivedEvent.EventName, self.OnListOfConnectedPlayersReceivedEvent)
        
    def LoadContent(self):
        self.text = OnscreenText(text = 'A - Team 1 (?)\nS - Team 2 (?)\nD - Spectate (?)',  pos = (0, -0.5), scale = 0.07, fg = (1, 1, 1, 1))
        self.text.reparentTo(self.node)
        
    def OnTeamSelect(self, team):
        Globals.MY_TEAM = team
        TeamSelectEvent(team).Fire() 
        
    def OnListOfConnectedPlayersReceivedEvent(self, event):
        team1 = 0
        team2 = 0
        spectators = 0
        for pState in event.GetPlayerStates():
            if(pState.GetValue(PlayerState.TEAM) == Game.TEAM_1):
                team1 += 1
            elif(pState.GetValue(PlayerState.TEAM) == Game.TEAM_2):
                team2 += 1
            elif(pState.GetValue(PlayerState.TEAM) == Game.SPECTATE):
                spectators += 1
                
        self.text.setText('A - Team 1 (%s)\nS - Team 2 (%s)\nD - Spectate (%s)' % (team1, team2, spectators))
Example #13
0
class Preloader():
    
    def __init__(self):
        self.progressBar = DirectWaitBar(text = "", value = 0, pos = (0,0,0), scale = 0.5, barColor = (1,0.3,0,1))
        self.textObject = OnscreenText(text = "", pos = (0.0,-0.15),
                              scale = 0.1,fg=(0,0,0,1),align=TextNode.ACenter,mayChange=1)
                              
        f = open('models_2.txt', 'r')
        self.models = f.readlines()
        f.close()
        
        for N in range(len(self.models)):
            self.models[N] = self.models[N].replace("\n", "")
            
        self.totalItems = len(self.models)
        
        base.graphicsEngine.renderFrame()
        base.graphicsEngine.renderFrame()
        
        self.itemCount = 0
        
        for M in self.models:
            print(M)
            item = loader.loadModel(M)
            progress = 100 / float(self.totalItems)
            self.progressBar['value'] += progress
            #text = str(self.progressBar['value'])+'%'
            self.textObject.setText("Loading")
            #self.loaderBar.setTexOffset(self.modTS, -progress + 0.15,0)
            base.graphicsEngine.renderFrame()
            base.graphicsEngine.renderFrame()
            
        self.textObject.destroy()
        self.progressBar.destroy()
Example #14
0
class TextHistoryLabel(NodePath):
    def __init__(self, text, speaker = None, voiceName = None, parent = None, height = 0):
        #TODO add a voice button in it
        NodePath.__init__(self,'texthistorylabel')
        
        self.parent = parent or aspect2d
        self.reparentTo(parent)
        
        if speaker:
            text = '\1th_name\1(' + speaker.strip() + ')\n\2' + text
        
        self.textcontent = OnscreenText(text = text,align = TextNode.ALeft, pos = (TEXTLEFT,-height),
                                   wordwrap = WORDWRAP, parent = self, **base.getStyle('historytext'))
        
        self.labelHeight = self.textcontent.textNode.getHeight() * self.textcontent.getScale()[1]

        
    def destroy(self):
        self.textcontent.destroy()
        self.removeNode()
        
    def getLabelHeight(self):
        return self.labelHeight
        
        
Example #15
0
    def createRegisterWindow(self):
        self.rframe = DirectFrame(frameColor=(0, 0, 0, 1), #(R,G,B,A)
                                frameSize=(-1, 1, -1, 1),#(Left,Right,Bottom,Top)
                                pos=(0, 0, 0))
       
        self.buttons = [
        DirectRadioButton(text = ' Ralph ', variable=self.v, value=[0], scale=0.07, pos=(-0.4,0.8,-0.6), command=self.setText),
        DirectRadioButton(text = ' Car ', variable=self.v, value=[1], scale=0.07, pos=(0,0.8,-0.6), command=self.setText),
        DirectRadioButton(text = ' Panda ', variable=self.v, value=[2], scale=0.07, pos=(0.4,0.8,-0.6), command=self.setText)
        ]
 
        for button in self.buttons:
            button.setOthers(self.buttons)
        
        self.rusername = OnscreenText(text = "Username:"******"Password: "******"Confirm Password: "******"" ,scale=.05,pos=(.1,0,0), command=self.setUserText,initialText="username", numLines = 1,focus=1,focusInCommand=self.clearUserText, focusOutCommand=self.getUserText)
        self.regInputPass = DirectEntry(text = "" ,scale=.05,pos=(.1,0, -.2),command=self.setPassText,initialText="password", numLines = 1,focus=0,focusInCommand=self.clearPassText, focusOutCommand=self.getPassText)
        self.regInputCPass = DirectEntry(text = "" ,scale=.05,pos=(.1,0, -.4),command=self.setPassText,initialText="confirm password", numLines = 1,focus=0,focusInCommand=self.clearPassText, focusOutCommand=self.getPassText)
        self.regInputUser.reparentTo(self.rframe)
        self.regInputPass.reparentTo(self.rframe)
        self.regInputCPass.reparentTo(self.rframe)
        self.rregisterBtn =  DirectButton(text = ("Register", "Register", "Register", "disabled"), scale=.075, command=self.clickedRegRegister, pos=(0.8, 0.0, -0.90))
        self.rcancelBtn =  DirectButton(text = ("Cancel", "Cancel", "Cancel", "disabled"), scale=.08, command=self.clickedRegCancel, pos=(0.2, 0.0, -0.90))
        self.rframe.statusText = OnscreenText(parent=self.rframe, text="", pos=(0.5, -0.5, 2), scale=0.06,fg=(1,0.5,0.5,1), align=TextNode.ACenter,mayChange=0)
        self.rcancelBtn.reparentTo(self.rframe)
        self.rregisterBtn.reparentTo(self.rframe)
class Shockley:
    def __init__(self, preload=False):
        self.sceneRoot = None
        self.preload = preload

    def load(self):
        self.sceneRoot = NodePath('Shockley')
        base.setBackgroundColor(0, 0, 0, 1)

        self.title = OnscreenText(text='Shockley ', pos=(0.6, 0.15, 0.0), scale=(0.15), fg=(1, 1, 1, 1), font=ToontownGlobals.getSignFont(), align=TextNode.ACenter)
        self.description = OnscreenText(text='Lead Developer\nNetwork Technician\nGame Systems Engineer', pos=(0.25, 0.05, 0.0), scale=(0.06), fg=(1, 1, 1, 1), font=ToontownGlobals.getMinnieFont(), align=TextNode.ALeft)
        self.image = OnscreenImage(image='phase_4/maps/news/11-17-13_garden.jpg', pos=(-0.5, 0.0, 0.0), scale=(0.5, 0.30, 0.30))

        self.elements = [self.title, self.description, self.image]
        for node in self.elements:
            node.setTransparency(1)
            if self.preload:
                node.setColorScale(1, 1, 1, 0)

    def makeInterval(self):
        return Sequence(
            ParentInterval(self.sceneRoot, render),
            # This fades in during the election's WrapUp state to prevent jittering when loading this first scene.
            Wait(3),
            Func(doFade, 'out', self.elements),
            Wait(0.5),
            ParentInterval(self.sceneRoot, hidden)
            )

    def unload(self):
        self.sceneRoot.removeNode()
        self.title.removeNode()
        self.description.removeNode()
        self.image.removeNode()
Example #17
0
 def loseGame(self):
     self.levelComplete = False
     #Clear stuff
     taskMgr.remove('rotateWorldTask')
     taskMgr.remove('textTask')
     taskMgr.remove('abductTask')
     taskMgr.remove('moveTask')
     taskMgr.remove('missileSeekTask')
     taskMgr.remove('ParticleTaskTask')
     
     self.env.removeNode()          
     del self.env
     self.saucer.ship.removeNode()         
     del self.saucer.ship
     self.saucer.beam.removeNode()         
     del self.saucer.beam
     #self.timeroutline.removeNode()
     #del self.timeroutline
     self.TimeText.destroy()
     del self.TimeText
     
     for i in range(0,len(self.pickupables)):
         self.pickupables[i].pickup.removeNode()
         del self.pickupables[i].pickup
     
     self.texte = OnscreenText(text="You Lose!",style=1, fg=(0.8,0,0.1,1),pos=(0, 0), scale = .2,mayChange = 1,align=TextNode.ACenter)
     self.textd = OnscreenText(text="Press Enter or Start to restart!",style=1, fg=(0.8,0,0.1,1),pos=(0, -.88), scale = .06,mayChange = 1,align=TextNode.ACenter)
     self.accept("enter", self.nextLevel)
     self.accept("C1_START_DOWN", self.nextLevel)
Example #18
0
    def update_rank(self, task):
        self.display_rank.destroy()

        # Your Rank
        rank = str(self.rank) + "/" + str(self.total_players)
        self.display_rank = OnscreenText(text=rank, style=1, fg=(1, 1, 1, 1),
                                         pos=(-.8, .85), align=TextNode.ALeft,
                                         scale=.15, font=self.font_digital)

        # Leader board
        self.leader1.destroy()
        self.leader2.destroy()
        self.leader3.destroy()
        lead1 = "1:"
        lead2 = "2:"
        lead3 = "3:"
        self.leader1 = OnscreenText(text=lead1, style=1, fg=(1, 1, 1, 1),
                                    pos=(-1.3, .5), align=TextNode.ALeft,
                                    scale=.07, font=self.font_digital)
        self.leader2 = OnscreenText(text=lead2, style=1, fg=(1, 1, 1, 1),
                                    pos=(-1.3, .45), align=TextNode.ALeft,
                                    scale=.07, font=self.font_digital)
        self.leader3 = OnscreenText(text=lead3, style=1, fg=(1, 1, 1, 1),
                                    pos=(-1.3, .4), align=TextNode.ALeft,
                                    scale=.07, font=self.font_digital)

        return task.cont
Example #19
0
  def loadHUD(self):
    self.winnerText = OnscreenText(
      text= "Insert Winner Text Here",
      style=1,
      fg=(1,1,1,1),
      pos=(-0.25, 0),
      align=TextNode.ALeft,
      scale = .07
    )
    self.winnerText.hide()
    self.scoreTextPlayerOne = OnscreenText(
      text= "Player 1:",
      style=1,
      fg=(1,1,1,1),
      pos=(Game.HUD_PLAYER_ONE_X, Game.HUD_Y_FIRST_LINE),
      align=TextNode.ALeft,
      scale = Game.HUD_TEXT_SCALE
    )
    self.scorePlayerOne = OnscreenText(
      text= "Score: 0",
      style=1,
      fg=(1,1,1,1),
      pos=(Game.HUD_PLAYER_ONE_X, Game.HUD_Y_SECOND_LINE),
      align=TextNode.ALeft,
      scale = Game.HUD_TEXT_SCALE
    )
    self.healthPlayerOne = OnscreenText(
      text= "Health: " + str(Ship.HEALTH),
      style=1,
      fg=(1,1,1,1),
      pos=(Game.HUD_PLAYER_ONE_X, Game.HUD_Y_THIRD_LINE),
      align=TextNode.ALeft,
      scale = Game.HUD_TEXT_SCALE
    )

    self.scoreTextPlayerTwo = OnscreenText(
      text= "Player 2:",
      style=1,
      fg=(1,1,1,1),
      pos=(Game.HUD_PLAYER_TWO_X, Game.HUD_Y_FIRST_LINE),
      align=TextNode.ALeft,
      scale = Game.HUD_TEXT_SCALE
    )
    self.scorePlayerTwo = OnscreenText(
      text= "Score: 0",
      style=1,
      fg=(1,1,1,1),
      pos=(Game.HUD_PLAYER_TWO_X, Game.HUD_Y_SECOND_LINE),
      align=TextNode.ALeft,
      scale = Game.HUD_TEXT_SCALE
    )
    self.healthPlayerTwo = OnscreenText(
      text= "Health: " + str(Ship.HEALTH),
      style=1,
      fg=(1,1,1,1),
      pos=(Game.HUD_PLAYER_TWO_X, Game.HUD_Y_THIRD_LINE),
      align=TextNode.ALeft,
      scale = Game.HUD_TEXT_SCALE
    )  
Example #20
0
class Crono():

	def __init__(self, app):


		self.app = app
		self.countRunning = False
		self.count = 0
		self.counttime = 0.5
		self.countMax = 30

		self.windowGui = self.app.loader.loadModel("models/window")

		self.windowGui.setDepthTest(True)
		self.windowGui.setDepthWrite(True)

	def draw(self, x, y):

		self.windowGui.setScale(0.06, 0.06, 0.06)
		self.windowGui.setPos(x, 0, y)
		self.windowGui.reparentTo(self.app.render2d)


		clockStr = "00:00:%s" % self.countMax

		self.clockMsg = OnscreenText(text=clockStr, style=1, fg=(1,1,1,1), pos=(x+0.1, y-0.01), align=TextNode.ALeft, scale = .05)

	def task(self, Task):

		#print strftime("%H:%M:%S", localtime())
		horas = int(strftime("%H", localtime()))
		minutos = int(strftime("%M", localtime()))
		segundos = int(strftime("%S", localtime()))

		sec = minutos*60
		minute = horas*60
		segundosTotales = segundos+sec+minute
		#print segundosTotales
		countStart = 0

		if self.countRunning:
			if ( (segundosTotales - self.count) > self.counttime ):
				self.count = segundosTotales
				self.countMax -= 1
				if self.countMax >= 0:
					clockStr = "00:00:%s" % self.countMax
					self.clockMsg.setText(clockStr)
				else:
					self.countRunning = False
					self.countMax = 30


		return Task.cont

	def start(self):

		self.countRunning = True
		print "countdown starts"
Example #21
0
 def screentexts(self,task):
     self.textObjectSpieler.destroy()
     self.textObjectSpieler = OnscreenText(text = self.spieler.name+":  "+str(self.spieler.energie)+"/"+str(self.spieler.maxenergie)+" HP", pos = (-0.90, -0.98), scale = 0.07, fg = (1,0,0,1))
     self.textObjectGegner.destroy()
     if self.kampf.active == True:
         self.textObjectGegner = OnscreenText(text = str(self.gegner.name)+": "+str(self.gegner.energie)+"/"+str(self.gegner.maxenergie)+" HP", pos = (0.90, -0.98), scale = 0.07, fg = (1,0,0,1))
     else:
         self.textObjectGegner = OnscreenText(text = "Kein Gegner vorhanden", pos = (0.90, -0.98), scale = 0.07, fg = (1,0,0,1))
     return Task.cont
Example #22
0
class HUD():
    def __init__(self):
        self.speedometer = OnscreenImage(image = 'img/speedometerDial.png', pos = (-1, 0, -.7) )
        self.speedometer.setScale(.25)
        self.speedometer.setTransparency(TransparencyAttrib.MAlpha)
        self.speedPin = OnscreenImage(image = 'img/speedometerNeedle.png', pos = (-1, 0, -.7))
        self.speedPin.setScale(.10)
        self.speedPin.setTransparency(TransparencyAttrib.MAlpha)
        self.speedPin.setHpr(0, 0, 0)
        
        self.minimap = OnscreenImage(image = 'img/minimap.png', pos = (1.05, 0, -.65))
        self.minimap.setScale(.19, .19, .3)
        self.dot = OnscreenImage(image = 'img/dot.png', pos = (1.01, 0, -.55))
        self.dot.setScale(.025)
        

        font1 = loader.loadFont('img/goodfish.ttf')
        self.lapText = OnscreenText(text = "0/10", font = font1, pos = (1, -.1, 0), fg = (1, 1, 1, 1) )
        self.lapText.setScale(.05)
        self.placeText = OnscreenText(text = "", font = font1, pos = (1, -.2, 0), fg = (1, 1, 1, 1))
        self.placeText.setScale(.05)
        self.timerText = OnscreenText(text = "Time: ", font = font1, pos = (1, -.3, 0), fg = (1, 1, 1, 1))

        
    def update(self, velocity, x, y, laps, place, time):
        if velocity < 0:
            velocity = -velocity


        self.dot.setPos(1.01+(x/4250), 0, -.55+(y/4250))
        self.lapText.setText("Laps: " + str(laps)+"/3")


        self.speedPin.setHpr(0, 0, 4*velocity)



        self.placeText.setText("Position: "+str(place))
        self.timerText.setText("Time: "+ str(round(time)))
    
    """def getDist(self, x, y, checkpoint):
        cx = checkpoint[0]
        cy = checkpoint[1]
        dist = math.sqrt((cx-x)**2 + (cy-y)**2)
        
        rotAngle = math.atan2(-y,x)
        
        newX = x*math.cos(rotAngle) - y*math.sin(rotAngle)
        
        dToCheckpoint = dist - newX
        return dToCheckpoint"""
    
    """def updateMiniMap(self, x, y):
        self.dot.setPos(1+(x/1000), 0, -.7+(y/1000))"""
        
        
Example #23
0
    def __init__(self):
        ShowBase.__init__(self)
        # Print all events sent through the messenger
        #self.messenger.toggleVerbose()

        self.lblWarning = OnscreenText(
            text = "No devices found",
            fg=(1,0,0,1),
            scale = .25)

        self.lblAction = OnscreenText(
            text = "Action",
            fg=(1,1,1,1),
            scale = .15)
        self.lblAction.hide()

        # Is there a steering wheel connected?
        self.wheel = None
        devices = self.devices.getDevices(InputDevice.DeviceClass.steering_wheel)
        if devices:
            self.connect(devices[0])

        self.currentMoveSpeed = 0.0
        self.maxAccleration = 28.0
        self.deaccleration = 10.0
        self.deaclerationBreak = 37.0
        self.maxSpeed = 80.0

        # Accept device dis-/connection events
        self.accept("connect-device", self.connect)
        self.accept("disconnect-device", self.disconnect)

        self.accept("escape", exit)

        # Accept button events of the first connected steering wheel
        self.accept("steering_wheel0-face_a", self.action, extraArgs=["Action"])
        self.accept("steering_wheel0-face_a-up", self.actionUp)
        self.accept("steering_wheel0-hat_up", self.center_wheel)

        self.environment = loader.loadModel("environment")
        self.environment.reparentTo(render)

        # save the center position of the wheel
        # NOTE: here we assume, that the wheel is centered when the application get started.
        #       In real world applications, you should notice the user and give him enough time
        #       to center the wheel until you store the center position of the controler!
        self.wheelCenter = 0
        if self.wheel is not None:
            self.wheelCenter = self.wheel.findAxis(InputDevice.Axis.wheel).value

        # disable pandas default mouse-camera controls so we can handle the camera
        # movements by ourself
        self.disableMouse()
        self.reset()

        self.taskMgr.add(self.moveTask, "movement update task")
Example #24
0
 def tutorial(self):
     initial_menu = 1
     self.mainFrame.destroy()
     screenText = OnscreenText(text = 'Tutorial', pos = (0.2, 0.6), scale = 0.1, fg = (1, 1, 1, 1))
     b1 = DirectButton(text = ("Back to Main Menu"), frameColor=(1, 1, 1, 0), text_fg=(1, 1, 1, 1),
               text_scale=0.1, text_align = TextNode.ALeft, pos=(0.2, 0, -0.5),
               relief=2, command = self.mainMenu, clickSound=self.menu_click,rolloverSound=self.menu_rollover)
     self.mainFrame = DirectFrame(pos=(0,0,0))       
     screenText.reparentTo(self.mainFrame)
     b1.reparentTo(self.mainFrame)
Example #25
0
 def show_text(self, lines):
     if isinstance(lines, str): lines = [lines]
     self.cleanup_text()
     ypos = 0.9
     for line in lines:
         text = OnscreenText(text=line, pos=(-1.3,ypos), style=1, fg=(1,1,1,1),
                             align=TextNode.ALeft, scale=0.05, parent=self.aspect2d)
         text.reparentTo(self.aspect2d)
         self.texts.append(text)
         ypos -= 0.05
Example #26
0
    def loginScreen(self, statusText):
        # creates a basic login screen that asks for a username/password

        boxloc = Vec3(0.0, 0.0, 0.0)
        # all items in the login form will have a position relative to this
        # this makes it easier to shift the entire form around once we have
        # some graphics to display with it without having to change the
        # positioning of every form element

        # p is the position of the form element relative to the boxloc
        # coordinates set above it is changed for every form element
        p = boxloc + Vec3(-0.22, 0.090, 0.0)
        self.usernameText = OnscreenText(
            text="Username:"******"Username: "******""), pos=p, scale=0.04, initialText="hunter", numLines=1
        )  # My testing name :P
        # Username textbox where you type in your username

        p = boxloc + Vec3(-0.22, 0.0, 0.0)
        self.passwordText = OnscreenText(
            text="Password:"******"Password: "******"", pos=p, scale=0.04, initialText="hunter", numLines=1, obscured=1
        )  # Testing password.
        # Password textbox where you type in your password
        # Note - obscured = 1 denotes that all text entered will be replaced
        # with a * like a standard password box

        p = boxloc + Vec3(0, 0, -0.090)
        self.loginButton = DirectButton(text="Login", pos=p, scale=0.048, relief=DGG.GROOVE, command=self.attemptLogin)
        # The 'Quit' button that will trigger the Quit function
        # when clicked

        p = boxloc + Vec3(0.95, 0, -0.9)
        self.createAccButton = DirectButton(
            text="Create Account", scale=0.050, pos=p, relief=DGG.GROOVE, command=self.attemptCreateAccount
        )
        # Made a quick button for adding accounts. Its fugly

        p = boxloc + Vec3(1.20, 0, -0.9)
        self.quitButton = DirectButton(text="Exit", pos=p, scale=0.048, relief=DGG.GROOVE, command=self.game.quit)
        # The 'Quit' button that will trigger the Quit function
        # when clicked

        p = boxloc + Vec3(0, -0.4, 0)
        self.statusText = OnscreenText(text=statusText, pos=p, scale=0.043, fg=(1, 0.5, 0, 1), align=TextNode.ACenter)
    def load(self):
        self.sceneRoot = NodePath(self.toonName.replace(' ', '').replace('',''))
        base.setBackgroundColor(0, 0, 0, 1)

        if self.twoSlides:
            if self.side == 'left':
                # Left Top
                titlePos = (0.1, 0.5, 0.0)
                descriptionPos = (0.2, 0.4, 0.0)
                imagePos = (-0.55, 0.0, 0.4)
                textAlignment = TextNode.ALeft
                # Right Bottom
                title2Pos = (-0.1, -0.35, 0.0)
                description2Pos = (-0.1, -0.45, 0.0)
                image2Pos = (0.55, 0.0, -0.4)
                text2Alignment = TextNode.ARight
            else:
                # Right Top
                titlePos = (-0.1, 0.5, 0.0)
                descriptionPos = (-0.1, 0.4, 0.0)
                imagePos = (0.55, 0.0, 0.4)
                textAlignment = TextNode.ARight
                # Left Bottom
                title2Pos = (0.1, -0.35, 0.0)
                description2Pos = (0.25, -0.45, 0.0)
                image2Pos = (-0.55, 0.0, -0.4)
                text2Alignment = TextNode.ALeft
        elif self.side == 'left':
            # Left Middle
            titlePos = (0.1, 0.15, 0.0)
            descriptionPos = (0.2, 0.05, 0.0)
            imagePos = (-0.5, 0.0, 0.0)
            textAlignment = TextNode.ALeft
        else: 
            # Right Middle
            titlePos = (-0.1, 0.1, 0.0)
            descriptionPos = (-0.11, 0.0, 0.0)
            imagePos = (0.5, 0.0, 0.0)
            textAlignment = TextNode.ARight

        self.title = OnscreenText(text=self.toonName, pos=titlePos, scale=(0.15), fg=(1, 1, 1, 1), font=ToontownGlobals.getSignFont(), align=textAlignment)
        self.description = OnscreenText(text=self.toonDescription, pos=descriptionPos, scale=(0.06), fg=(1, 1, 1, 1), font=ToontownGlobals.getMinnieFont(), align=textAlignment)
        self.image = OnscreenImage(image='phase_4/maps/news/%s' % self.toonImage, pos=imagePos, scale=(0.5, 0.30, 0.30))
        self.elements = [self.title, self.description, self.image]

        if self.twoSlides:
            self.title2 = OnscreenText(text=self.toon2Name, pos=title2Pos, scale=(0.15), fg=(1, 1, 1, 1), font=ToontownGlobals.getSignFont(), align=text2Alignment)
            self.description2 = OnscreenText(text=self.toon2Description, pos=description2Pos, scale=(0.06), fg=(1, 1, 1, 1), font=ToontownGlobals.getMinnieFont(), align=text2Alignment)
            self.image2 = OnscreenImage(image='phase_4/maps/news/%s' % self.toon2Image, pos=image2Pos, scale=(0.5, 0.30, 0.30))
            self.elements.extend([self.title2, self.description2, self.image2])

        for node in self.elements:
            node.setTransparency(1)
            node.setColorScale(1, 1, 1, 0)
Example #28
0
def drawInds(adjLst):
    from direct.gui.OnscreenText import OnscreenText
    indNP = render.attachNewNode('indsgroup')
    for i in range(0, len(adjLst)):
        center = getCenterOfPoint3s(adjLst[i].tri)
        dummy = indNP.attachNewNode(str(i))
        txt = OnscreenText(text=str(i), pos=center, scale=1)
        txt.reparentTo(dummy)
        dummy.setP(dummy.getP() - 90)

    return indNP
Example #29
0
 def enterWorld(self, scenario=scenarios.TestEnvironment):
     #self.world = OdeWorld()
     #self.world.setGravity(0.0, 0.0, 0.0)
     #world.setGravity(0.0, 0.0, -9.81)
     loading = OnscreenText(text="LOADING", pos=(0,0), scale=0.1,
                            align=TextNode.ACenter, fg=(1,1,1,1))
     base.graphicsEngine.renderFrame()
     base.graphicsEngine.renderFrame()
     self.scenario = scenario()
     loading.destroy()
     self.scenario.start()
Example #30
0
 def displayClock(self, task):
     msg = "Time: %.2f" %(self.clock/100.0)
     if self.clockMSG == None:
         self.clockMSG = OnscreenText(text=msg, style=1, fg=(1,1,1,1),
                                      pos=(1.3, .95), align=TextNode.ALeft,
                                      scale = .05)
     else:
         self.clockMSG.destroy()
         self.clockMSG = OnscreenText(text=msg, style=1, fg=(1,1,1,1),
                                      pos=(1.3, .95), align=TextNode.ALeft,
                                      scale = .05)
     return task.cont
class World(DirectObject):

    # Degrees per second of rotation
    rotateSpeed = 90

    # Units per second of motion
    moveSpeed = 8

    def __init__(self):
        DirectObject.__init__(self)

        # No avatar yet.
        self.av = None

        # No pellets either.
        self.pellets = []

        # The list of keys that we will be monitoring.
        self.moveKeyList = [
            'arrow_left', 'arrow_right', 'arrow_up', 'arrow_down'
        ]

        # Initially, all keys are up.  Construct a dictionary that
        # maps each of the above keys to False, and hang the event to
        # manage that state.
        self.moveKeys = {}
        for key in self.moveKeyList:
            self.moveKeys[key] = False
            self.accept(key, self.moveKeyStateChanged, extraArgs=[key, True])
            self.accept(key + '-up',
                        self.moveKeyStateChanged,
                        extraArgs=[key, False])

        tcpPort = base.config.GetInt('server-port', 4400)
        hostname = base.config.GetString('server-host', '127.0.0.1')
        self.url = URLSpec('http://%s:%s' % (hostname, tcpPort))

        self.cr = MyClientRepository()
        self.cr.connect([self.url],
                        successCallback=self.connectSuccess,
                        failureCallback=self.connectFailure)

        self.waitingText = OnscreenText(
            'Connecting to %s.\nPress ESC to cancel.' % (self.url),
            scale=0.1,
            fg=(1, 1, 1, 1),
            shadow=(0, 0, 0, 1))

        self.accept('escape', self.escape)

        # Oobe mode is handy to have on all the time.  Why not?
        base.oobe()

        # We'll need a collision traverser in this demo.
        base.cTrav = CollisionTraverser()

    def moveKeyStateChanged(self, key, newState):
        """ A key event has been received.  Change the key state in
        the dictionary. """
        self.moveKeys[key] = newState

    def escape(self):
        """ The user pressed escape.  Exit the client. """
        sys.exit()

    def connectFailure(self, statusCode, statusString):
        self.waitingText.destroy()
        self.failureText = OnscreenText(
            'Failed to connect to %s: %s.\nPress ESC to quit.' %
            (self.url, statusString),
            scale=0.15,
            fg=(1, 0, 0, 1),
            shadow=(0, 0, 0, 1))

    def connectSuccess(self):
        """ Successfully connected.  But we still can't really do
        anything until we've got the doID range. """
        self.waitingText.destroy()
        self.waitingText = OnscreenText('Waiting for server.',
                                        scale=0.1,
                                        fg=(1, 1, 1, 1),
                                        shadow=(0, 0, 0, 1))

        # Make sure we have interest in the TimeManager zone, so we
        # always see it even if we switch to another zone.
        self.cr.setInterestZones([1])

        # We must wait for the TimeManager to be fully created and
        # synced before we attempt to visit the world and view any
        # real objects.
        self.acceptOnce('gotTimeSync', self.syncReady)

    def syncReady(self):
        """ Now we've got the TimeManager manifested, and we're in
        sync with the server time.  Now we can enter the world.  Check
        to see if we've received our doIdBase yet. """

        if self.cr.haveCreateAuthority():
            self.createReady()
        else:
            # Not yet, keep waiting a bit longer.
            self.acceptOnce('createReady', self.createReady)

    def createReady(self):
        """ Now we're ready to go! """
        self.waitingText.destroy()

        # Manifest an avatar for ourselves.
        self.av = self.cr.createDistributedObject(
            className='DistributedSmoothAvatar', zoneId=101)
        self.av.setupLocalAvatar()

        # The tab key changes your color.
        self.accept('tab', self.changeAvColor)

        # The space bar drops a new pellet.
        self.accept('space', self.dropPellet)

        # The 'c' key clears the pellets you've dropped.
        self.accept('c', self.clearPellets)

        # A number key (other than zero) changes your zone.  Here we
        # put you in zones 101 - 109, since we reserve zoneId 1 for
        # the TimeManager.
        for zoneId in range(1, 10):
            self.accept(str(zoneId),
                        self.changeAvZone,
                        extraArgs=[100 + zoneId])

        # Pop up some help text.
        self.title = OnscreenText(parent=base.a2dBottomRight,
                                  text='DistributedSmoothNode client demo',
                                  fg=(1, 1, 1, 1),
                                  pos=(-0.03, 0.03),
                                  align=TextNode.ARight,
                                  scale=0.1)

        self.help = OnscreenText(parent=base.a2dTopLeft,
                                 text=helpText,
                                 fg=(1, 1, 1, 1),
                                 pos=(0.03, -0.1),
                                 align=TextNode.ALeft,
                                 scale=0.07)

        # Update the local avatar's position every frame.
        self.moveTask = taskMgr.add(self.moveAvatar, 'moveAvatar')

        # Let the DistributedSmoothNode take care of broadcasting the
        # position updates several times a second.
        self.av.startPosHprBroadcast()

    def dropPellet(self):
        # Create a new DistributedSyncPellet, and put it right where the
        # avatar is.
        pellet = DistributedSyncPellet(self.cr)
        x, y, z = self.av.getPos()
        pellet.setInitialPos(x, y, z)
        pellet.startTime = globalClock.getFrameTime()
        self.cr.createDistributedObject(distObj=pellet, zoneId=self.av.zoneId)
        self.pellets.append(pellet)

    def clearPellets(self):
        # Remove all of the DistributedSyncPellets we've created.
        for p in self.pellets:
            self.cr.sendDeleteMsg(p.doId)

    def changeAvColor(self):
        """ The user pressed the tab key.  Change the color of the
        local avatar to a new random color. """
        r = random.uniform(0, 1)
        g = random.uniform(0, 1)
        b = random.uniform(0, 1)
        self.av.b_setAvColor(r, g, b)

    def changeAvZone(self, zoneId):
        """ The user pressed one of the number keys to change zones.
        Move the avatar into the indicated zone. """

        # Move our avatar into the indicated zone
        self.cr.setObjectZone(self.av, zoneId)

    def moveAvatar(self, task):
        """ This task runs each frame to move the avatar according to
        the set of arrow keys that are being held. """

        dt = globalClock.getDt()

        if self.moveKeys['arrow_left']:
            self.av.setH(self.av, dt * self.rotateSpeed)
        elif self.moveKeys['arrow_right']:
            self.av.setH(self.av, -dt * self.rotateSpeed)

        if self.moveKeys['arrow_up']:
            self.av.setY(self.av, dt * self.moveSpeed)
        elif self.moveKeys['arrow_down']:
            self.av.setY(self.av, -dt * self.moveSpeed)

        return task.cont
Example #32
0
class example_sounds(BaseNodeScript):
    '''
    Gives an example of how to play and manage sounds. 
    
    The code below runs as the managing script of the example_sounds node which is defined in example_sounds.node .
    Such managing scripts are termed NodeScript and are essentially an FSM linked with a node for the purpose of
    managing its state. Nodescripts are optional though, nodes can be defined without a nodescript.
    
    Being state machines in nature, you will methods such as 'enter', 'exit' and 'update'. The 'enter' method
    will be called only once, at the time the node becomes active. Likewise 'exit' will be called only once, when
    the node becomes inactive. On the other hand 'update' will be invoked with the game logic update, so many times
    per second.         
    '''

    def __init__(self, game, node):
        BaseNodeScript.__init__(self, game, 'SoundsExample', node)
        self.log = logging.getLogger('SoundsExample')
        
        # reference to sounds fx player
        self.sounds = None
        
        # the following set of fields are UI labels
        self.instructions = None
        self.soundsStatusText = None
        self.volumeText = None
        self.rateText = None
        self.balanceText = None
        self.loopText = None
        self.eventText = None
        
        # reference to the 'blah' sound 
        self.blahSound = None
        
        # holds the status of sounds, if True then sounds are globally enabled
        self.lastStatus = True
        
        # flags that indicate if the respective property has been update by the user
        self.updateVolume = False
        self.updateRate = False
        self.updateBalance = False
        self.updateLooping = False
        
        # 
        self.looping = 0

            
    def registerMessages(self):        
        '''
        The purpose of this method is to declare the list of messages IDs for which we are interested to receive. 
        Here we are interested in a single message besides the standard list of message IDs returned by the
        base class.
        It is not necessary to include the list of messages from the base class but it contains some very useful
        message IDs like game_paused, game_resumed, etc., so most probably you will want to do this.
        '''
        return ['sound_finished'].extend(BaseNodeScript.registerMessages(self))
            
            
    def enter(self):
        '''
        Here we initialize some fields and flags and setup our UI which constists only of labels.
        '''
        
        # call the super class implementation first, this is optional
        BaseNodeScript.enter(self)
        
        self.sounds = self.game.getSoundsFx()
                
        # hold the camera fixed
        self.game.getView().getCameraController().disable()
        
        # display instructions
        self.instructions = OnscreenText(text = 'Press 1 for blah-blah, 2 for cling and 3 for zipper',
                                         pos = (base.a2dLeft + 0.1, 0.9),
                                         align = TextNode.ALeft,
                                         scale = 0.07,
                                         fg = (1.0, 1.0, 1.0, 1.0),
                                         shadow = (0.0, 0.0, 0.0, 0.7)
                                         )
        
        # gets the status of sounds
        self.lastStatus = self.sounds.isEnabled()
        
        self.soundsStatusText = OnscreenText(text = 'Sounds status: %s' % self.lastStatus,
                                             pos = (base.a2dLeft + 0.1, 0.8),
                                             align = TextNode.ALeft,
                                             scale = 0.07,
                                             fg = (1.0, 1.0, 1.0, 1.0),
                                             shadow = (0.0, 0.0, 0.0, 0.7),
                                             mayChange = True
                                             )
        
        self.volumeText = OnscreenText(text = 'Volume: %.1f' % self.sounds.getVolume(),
                                             pos = (base.a2dLeft + 0.1, 0.7),
                                             align = TextNode.ALeft,
                                             scale = 0.07,
                                             fg = (1.0, 1.0, 1.0, 1.0),
                                             shadow = (0.0, 0.0, 0.0, 0.7),
                                             mayChange = True
                                             )
        
        self.rateText = OnscreenText(text = 'Rate: %.1f' % self.sounds.getPlayRate(),
                                             pos = (base.a2dLeft + 0.1, 0.6),
                                             align = TextNode.ALeft,
                                             scale = 0.07,
                                             fg = (1.0, 1.0, 1.0, 1.0),
                                             shadow = (0.0, 0.0, 0.0, 0.7),
                                             mayChange = True
                                             )
        
        self.balanceText = OnscreenText(text = 'Balance: %.1f' % self.sounds.getBalance(),
                                             pos = (base.a2dLeft + 0.1, 0.5),
                                             align = TextNode.ALeft,
                                             scale = 0.07,
                                             fg = (1.0, 1.0, 1.0, 1.0),
                                             shadow = (0.0, 0.0, 0.0, 0.7),
                                             mayChange = True
                                             )
        
        self.loopText = OnscreenText(text = 'Looping: %d' % self.looping,
                                             pos = (base.a2dLeft + 0.1, 0.4),
                                             align = TextNode.ALeft,
                                             scale = 0.07,
                                             fg = (1.0, 1.0, 1.0, 1.0),
                                             shadow = (0.0, 0.0, 0.0, 0.7),
                                             mayChange = True
                                             )
        
        self.eventText = OnscreenText(text = 'Finished event received',
                                             pos = (base.a2dLeft + 0.1, 0.3),
                                             align = TextNode.ALeft,
                                             scale = 0.07,
                                             fg = (1.0, 0.0, 0.0, 1.0),
                                             shadow = (0.0, 0.0, 0.0, 0.7),
                                             mayChange = True
                                             )
        self.eventText.hide()
        
        OnscreenText(text = 'Press P, R to pause/resume playing sounds',
                                             pos = (base.a2dLeft + 0.1, 0.2),
                                             align = TextNode.ALeft,
                                             scale = 0.05,
                                             fg = (1.0, 1.0, 1.0, 1.0),
                                             shadow = (0.0, 0.0, 0.0, 0.7),
                                             mayChange = True
                                             )
        OnscreenText(text = 'Press L, Shift-L to increase/decrease the loop count',
                                             pos = (base.a2dLeft + 0.1, 0.1),
                                             align = TextNode.ALeft,
                                             scale = 0.05,
                                             fg = (1.0, 1.0, 1.0, 1.0),
                                             shadow = (0.0, 0.0, 0.0, 0.7),
                                             mayChange = True
                                             )
        OnscreenText(text = 'Press +, - to increase/decrease playing rate',
                                             pos = (base.a2dLeft + 0.1, 0.0),
                                             align = TextNode.ALeft,
                                             scale = 0.05,
                                             fg = (1.0, 1.0, 1.0, 1.0),
                                             shadow = (0.0, 0.0, 0.0, 0.7),
                                             mayChange = True
                                             )
        OnscreenText(text = 'Press [, ] to decrease/increase sound volume',
                                             pos = (base.a2dLeft + 0.1, -0.1),
                                             align = TextNode.ALeft,
                                             scale = 0.05,
                                             fg = (1.0, 1.0, 1.0, 1.0),
                                             shadow = (0.0, 0.0, 0.0, 0.7),
                                             mayChange = True
                                             )
        OnscreenText(text = 'Press D, E to disable/enable sounds',
                                             pos = (base.a2dLeft + 0.1, -0.2),
                                             align = TextNode.ALeft,
                                             scale = 0.05,
                                             fg = (1.0, 1.0, 1.0, 1.0),
                                             shadow = (0.0, 0.0, 0.0, 0.7),
                                             mayChange = True
                                             )
        OnscreenText(text = 'Press B, Shift-B to increase/decrease balance',
                                             pos = (base.a2dLeft + 0.1, -0.3),
                                             align = TextNode.ALeft,
                                             scale = 0.05,
                                             fg = (1.0, 1.0, 1.0, 1.0),
                                             shadow = (0.0, 0.0, 0.0, 0.7),
                                             mayChange = True
                                             )
        
        
        
        # add our input mappings to the active mappings, the existing mappings were not deleted
        # but they can be partially overridden by this.
        self.game.getInput().addMappings('sounds')
        
        
    def exit(self):
        '''
        Performs some cleanup.
        '''
        
        # call the super class implementation first, this is optional
        BaseNodeScript.exit(self)
        if self.instructions is not None:
            self.instructions.destroy()                
            
        # this will stop all active sounds
        if self.sounds is not None:
            self.sounds.stopAll()
            
            
    def update(self, millis):
        '''
        Gets called on every logic update and we use it to update the UI texts based on user input actions.
        The millis parameter is the milliseconds that elapsed since the last logic update.
        '''
        
        # call the super class implementation first, this is optional
        BaseNodeScript.update(self, millis)
        
        # detects if sounds status has been toggled in order to update the UI label
        if self.lastStatus != self.sounds.isEnabled():
            self.lastStatus = self.sounds.isEnabled()
            self.soundsStatusText.setText('Sounds status: %s' % self.lastStatus)
            
        # updates the volume label if needed
        if self.updateVolume:
            self.volumeText.setText('Volume: %.1f' % self.sounds.getVolume())
            self.updateVolume = False
        
        # updates the rate label if needed
        if self.updateRate:
            self.rateText.setText('Rate: %.1f' % self.sounds.getPlayRate())
            self.updateRate = False
            
        # updates the balance label if needed
        if self.updateBalance:
            self.balanceText.setText('Balance: %.1f' % self.sounds.getBalance())
            self.updateBalance = False
            
        # updates the looping label if needed
        if self.updateLooping:
            self.loopText.setText('Looping: %d' % self.looping)
            self.updateLooping = False
            
    
    def onInputAction(self, action):
        '''
        When an input action occurs the active nodescript will get notified through this method. 
        The given parameter is the name of the action that occured.
        Here we just branch based on the action name. You can see the defined actions of this example in data/example_sounds/sounds.mappings. 
        
        You return a True value to indicate that you handled the action and False to indicate that you ignored it.
        '''
        if action == "play_blah":
            '''
            We play the blah sound but keep a reference to it in order to have only one instance of this sound.
            The first time we call sounds.playSound to create the sound and get back a SoundPlaybackInterface 
            which we use for controlling playback. Notice that in the call to playSound we don't provide a filename.
            That's because the sound's properties, along with the filename, is defined in a .sound file name blah.sound.
            The file is located at data/example_sounds/blah.sound
            On subsequent invocations of this action we only call SoundPlaybackInterface.play() to get the sound
            playing.                        
            '''
            if self.blahSound is None:
                self.blahSound = self.sounds.playSound('blah', rate = self.sounds.getPlayRate(), loop = self.looping)
            else:
                self.blahSound.play()
                
        elif action == "play_cling":
            '''
            The sound is defined in data/example_sounds/cling.sound. We do not keep a reference to the playback interface
            here. Instead we create a new sound each time the action gets invoked.
            '''
            self.sounds.playSound('cling', rate = self.sounds.getPlayRate(), loop = self.looping)
            
        elif action == "play_zipper":
            '''
            For the zipper sound we instead provide a filename and use Sounds.playSoundFile for that purpose.
            We also don't keep a reference to the playback interface so a new sound is created each time.
            '''
            self.sounds.playSoundFile('zipper_bag_1.ogg', rate = self.sounds.getPlayRate(), loop = self.looping)
            
        elif action == "pause_sounds":            
            if self.blahSound is not None:
                self.blahSound.pause()
                
            # Sounds.pauseAll just pauses all currently playing sounds
            self.sounds.pauseAll()
            
        elif action == "resume_sounds":
            if self.blahSound is not None:
                self.blahSound.play()
                
            # Sounds.resumeAll just pauses all paused sounds
            self.sounds.resumeAll()    
            
        elif action == "enable_sounds":
            # Sounds.enableSounds enables global sound playback
            self.sounds.enableSounds()
            
        elif action == "disable_sounds":
            # Sounds.enableSounds disables global sound playback, a sound that was playing prior to this call will get stopped
            self.sounds.disableSounds()
            
        elif action == "increase_volume":
            # this demonstrates updating the properties of a single sound
            if self.blahSound is not None:
                self.blahSound.setVolume(self.sounds.getVolume() + 0.1)
                
            # while here we update the volume property affecting all sounds at the same time
            self.sounds.setVolume(self.sounds.getVolume() + 0.1)
            self.updateVolume = True
            
        elif action == "decrease_volume":
            # same here as we did with the increase_volume action
            if self.blahSound is not None:
                self.blahSound.setVolume(self.sounds.getVolume() - 0.1)
            self.sounds.setVolume(self.sounds.getVolume() - 0.1)
            self.updateVolume = True
            
        elif action == "increase_rate":
            # same here as we did with the increase_volume action
            if self.blahSound is not None:
                self.blahSound.setPlayRate(self.sounds.getPlayRate() + 0.1)
            self.sounds.setPlayRate(self.sounds.getPlayRate() + 0.1)
            self.updateRate = True
            
        elif action == "decrease_rate":
            # same here as we did with the increase_volume action
            if self.blahSound is not None:
                self.blahSound.setPlayRate(self.sounds.getPlayRate() - 0.1)
            self.sounds.setPlayRate(self.sounds.getPlayRate() - 0.1)
            self.updateRate = True
            
        elif action == "increase_balance":
            # same here as we did with the increase_volume action
            if self.blahSound is not None:
                self.blahSound.setBalance(self.sounds.getBalance() + 0.1)
            self.sounds.setBalance(self.sounds.getBalance() + 0.1)
            self.updateBalance = True
            
        elif action == "decrease_balance":
            # same here as we did with the increase_volume action
            if self.blahSound is not None:
                self.blahSound.setBalance(self.sounds.getBalance() - 0.1)
            self.sounds.setBalance(self.sounds.getBalance() - 0.1)
            self.updateBalance = True
            
        elif action == "increase_loop":
            # looping in this example only affects the blah sound
            self.looping += 1
            self.updateLooping = True
            if self.blahSound is not None:
                self.blahSound.setLoop(self.looping)
                
        elif action == "decrease_loop":
            self.updateLooping = True
            self.looping -= 1            
            if self.looping < 0:
                self.looping = 0            
            if self.blahSound is not None:
                self.blahSound.setLoop(self.looping)
                    
        else:
            # we didn't handle this, indicate it by returning False
            return False 
            
        # action was handled, return True
        return True    
    
    
    def onMessage(self, msg, *args):
        '''
        Using Messenger objects any game component can broadcast messages which will become available to the active
        nodescript through this method.
        The msg parameter is the name of the message, while *args is a list of arguments provided by the sender.
        
        Each nodescript must first declare the list of messages for which it is interested to receive. The list is declared
        in the NodeScript.registerMessages method.
        '''
        
        # When a sound has finished playing the sound_finished message is broadcasted. 
        # We handle it here to get notified when the blah sound has finished and update the UI accordingly.
        if msg == 'sound_finished':
            print 'FINISHED'
            self.eventText.setFg((1.0, 0.0, 0.0, 0.0))
            self.eventText.show()
            Sequence(
                     LerpColorScaleInterval(self.eventText, 0.5, (1,1,1,1), (1,1,1,0)),
                     LerpColorScaleInterval(self.eventText, 0.5, (1,1,1,0), (1,1,1,1))
                     ).start()
                
                        
Example #33
0
class MouseTunnel(ShowBase):
    def __init__(self):
        # Initialize the ShowBase class from which we inherit, which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)
        self.stimtype = 'random image'

        # session_start
        self.session_start_time = datetime.datetime.now()

        # self.accept("escape", sys.exit, [0])#don't let the user do this, because then the data isn't saved.
        self.accept('q', self.close)
        self.accept('Q', self.close)

        self.upArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.up())
        self.downArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.down())
        self.rightArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.right())
        self.leftArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.left())

        self.AUTO_REWARD = AUTO_REWARD
        # disable mouse control so that we can place the camera
        base.disableMouse()
        camera.setPosHpr(0, 0, 10, 0, -90, 0)
        mat = Mat4(camera.getMat())
        mat.invertInPlace()
        base.mouseInterfaceNode.setMat(mat)
        # base.enableMouse()

        props = WindowProperties()
        # props.setOrigin(0, 0)
        props.setFullscreen(True)
        props.setCursorHidden(True)
        props.setMouseMode(WindowProperties.M_relative)
        base.win.requestProperties(props)
        base.setBackgroundColor(0, 0, 0)  # set the background color to black

        print('FULSCREEN:')
        print(props.getFullscreen())
        print('=============')
        # set up the textures
        # we now get buffer thats going to hold the texture of our new scene
        altBuffer = self.win.makeTextureBuffer("hello", 1524, 1024)
        # altBuffer.getDisplayRegion(0).setDimensions(0.5,0.9,0.5,0.8)
        # altBuffer = base.win.makeDisplayRegion()
        # altBuffer.makeDisplayRegion(0,1,0,1)

        # now we have to setup a new scene graph to make this scene
        self.dr2 = base.win.makeDisplayRegion(0, 0.001, 0, 0.001)#make this really,really small so it's not seeable by the subject

        altRender = NodePath("new render")
        # this takes care of setting up ther camera properly
        self.altCam = self.makeCamera(altBuffer)
        self.dr2.setCamera(self.altCam)
        self.altCam.reparentTo(altRender)
        self.altCam.setPos(0, -10, 0)

        self.bufferViewer.setPosition("lrcorner")
        # self.bufferViewer.position = (-.1,-.4,-.1,-.4)
        self.bufferViewer.setCardSize(1.0, 0.0)
        print(self.bufferViewer.position)

        self.imagesTexture = MovieTexture("image_sequence")
        # success = self.imagesTexture.read("models/natural_images.avi")
        # success = self.imagesTexture.read("models/movie_5hz.mpg")
        self.imagesTexture.setPlayRate(1.0)
        self.imagesTexture.setLoopCount(10)
        # self.imageTexture =loader.loadTexture("models/NaturalImages/BSDs_8143.tiff")
        # self.imagesTexture.reparentTo(altRender)

        self.fixationPoint = OnscreenImage(image='models/fixationpoint.jpg', pos=(0, 0,0),scale=0.01)

        cm = CardMaker("stimwindow")
        cm.setFrame(-4, 4, -3, 3)
        # cm.setUvRange(self.imagesTexture)
        self.card = NodePath(cm.generate())
        self.card.reparentTo(altRender)
        if self.stimtype == 'image_sequence':
            self.card.setTexture(self.imagesTexture, 1)

        # add the score display
        self.scoreLabel = OnscreenText(text='Current Score:', pos=(-1, 0.9), scale=0.1, fg=(0.8, 0.8, 0.8, 1))
        self.scoreText = OnscreenText(text=str(0), pos=(-1, 0.76), scale=0.18, fg=(0, 1, 0, 1),
                                      shadow=(0.1, 1, 0.1, 0.5))
        self.feebackScoreText = OnscreenText(text='+ ' + str(0), pos=(-0.5, 0.5), scale=0.3, fg=(0, 1, 0, 1),
                                             shadow=(0.1, 1, 0.1, 0.5))
        self.feebackScoreText.setX(3.)

        # self.imagesTexture.play()

        # self.bufferViewer.setPosition("lrcorner")
        # self.bufferViewer.setCardSize(1.0, 0.0)
        self.accept("v", self.bufferViewer.toggleEnable)
        self.accept("V", self.bufferViewer.toggleEnable)

        # Load the tunnel
        self.initTunnel()

        # initialize some things
        # for the tunnel construction:
        self.boundary_to_add_next_segment = -1 * TUNNEL_SEGMENT_LENGTH
        self.current_number_of_segments = 8
        # task flow booleans
        self.in_waiting_period = False
        self.stim_started = False
        self.looking_for_a_cue_zone = True
        self.in_reward_window = False
        self.show_stimulus = False
        # for task control
        self.interval = 0
        self.time_waiting_in_cue_zone = 0
        self.wait_time = 1.83
        self.stim_duration = 0  # in seconds
    
#        self.distribution_type = np.random.uniform#
#        self.distribution_type_inputs = [0.016,0.4] #change the min & max stim duration times

    #New lines    EAS: set weights higher for faster image durations
        self.durWeights = list()
        a = np.linspace(0.016,0.4,10)
        for i,j in enumerate(a):
            if j<0.1:
                p1 = 0.25
                self.durWeights.append(p1)
            elif j > 0.1 and j < 0.21:
                p1 = 0.1
                self.durWeights.append(p1)
            elif j> 0.21:
                p1 = 0.04
                self.durWeights.append(p1)
        self.rng = np.random.default_rng()
        a = np.asarray(a)
        self.distribution_type_inputs = a
        #subset_size = len(p)

    #End new lines
      
#        self.distribution_type_inputs = [0.05,1.5]  #can be anytong should match 
#        self.distribution_type_inputs = [0.016,0.4] #change the min & max stim duration times
#        self.distribution_type_inputs = [0.016,0.4, 10] #change the min & max stim duration times

        self.max_stim_duration = 1.0  # in seconds
        self.stim_elapsed = 0.0       # in seconds
        self.last_position = base.camera.getZ()
        self.position_on_track = base.camera.getZ()
        # for reward control
        self.reward_window = REWARD_WINDOW  # in seconds
        self.reward_elapsed = 0.0
        
#        self.new_dt = list()
        
        # self.reward_volume = 0.008 # in mL. this is for the hardcoded 0.1 seconds of reward time
        self.reward_volume = int(REWARD_VOLUME)  # in uL, for the stepper motor
        self.reward_time = 0.1  # in sec, based on volume. hard coded right now but should be modified by the (1) calibration and (2) optionally by the main loop for dynamic reward scheduling
        # self.lick_buffer = []
        self.current_score = 0
        self.score = 0
        self.feedback_score_startime = -2

        # INITIALIZE NIDAQ
        self.nidevice = 'Dev2'
        self.encodervinchannel = 1
        self.encodervsigchannel = 0
        self.invertdo = False
        self.diport = 1
        self.lickline = 1
        self.doport = 0
        self.rewardline = 0
        self.rewardlines = [0]
        self.encoder_position_diff = 0
        if have_nidaq:
            self._setupDAQ()
            self.do.WriteBit(1, 1)
            self.do.WriteBit(3,
                             1)  # set reward high, because the logic is flipped somehow. possibly by haphazard wiring of the circuit (12/24/2018 djd)
            self.previous_encoder_position = self.ai.data[0][self.encodervsigchannel]
        else:
            self.previous_encoder_position = 0
        self.encoder_gain = 3

        # INITIALIZE LICK SENSOR
        self._lickSensorSetup()

        # INITIALIZE  output data
        self.lickData = []
        self.x = []
        self.t = []
        self.trialData = []
        self.reactionTimeData = []
        self.rewardData = []
        self.rightKeyData = []
        self.leftKeyData = []
        self.imageData = []
        self.imageTimeData = []
        self.scoreData = []
        self.trialDurationData = []
        self.new_dt = []

        # INITIALIZE KEY SENSOR, for backup inputs and other user controls
        self.keys = key.KeyStateHandler()
        self.accept('r', self._give_reward, [self.reward_volume])
        self.accept('l', self._toggle_reward)

        # initialize the image list and populate what images you want included


#        self.img_list = glob.glob('models/2AFC_IMAGES_HUMAN/*.tif')
#        self.img_list = glob.glob('models/2AFC_IMAGES_HUMAN2/*.tif')  
#        self.img_list = glob.glob('/Users/elizabethstubblefield/Desktop/cheetah_or_elephant/composite_images/masks/all_same_num_ea/*.tif')  #Newest images
        self.img_list = glob.glob('models/all_same_ea/*.tif')  #Newest images

        #No longer hard-coded:
        self.original_indices = [0,0]  #this was manually counted... first number must was the index of the first easy img; was [43, -18]
        for ndx, name in enumerate(self.img_list):
            if 'Cheetah255' in name:
                self.original_indices[0] = ndx
            elif 'Elephant0' in name:
                self.original_indices[1] = ndx

        # print(self.img_list)
        
#        self.original_indices = [43,-18] #manually counted, grump  #Problematic w/out at least 43 images in the folder        

        self.imageTextures =[loader.loadTexture(img) for img in self.img_list]
        self.img_id = None   #this variable is used so we know which stimulus is being presented
        self.img_mask = None #this tells us what the image mask being presented is

        # self._setupEyetracking()
        # self._startEyetracking()

        if AUTO_MODE:
            self.gameTask = taskMgr.add(self.autoLoop2, "autoLoop2")
            self.rewardTask = taskMgr.add(self.rewardControl, "reward")
            self.cue_zone = concatenate((self.cue_zone, arange( \
                self.current_number_of_segments * -TUNNEL_SEGMENT_LENGTH-50, \
                self.current_number_of_segments * -TUNNEL_SEGMENT_LENGTH - TUNNEL_SEGMENT_LENGTH - 100, \
                -1)))
            self.auto_position_on_track = 0
            self.auto_restart = False
            self.auto_running = True
            self.contTunnel()
        else:
            # Now we create the task. taskMgr is the task manager that actually
            # calls the function each frame. The add method creates a new task.
            # The first argument is the function to be called, and the second
            # argument is the name for the task.  It returns a task object which
            # is passed to the function each frame.
            self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")
            # self.stimulusTask = taskMgr.add(self.stimulusControl, "stimulus")
            self.lickTask = taskMgr.add(self.lickControl, "lick")
            self.rewardTask = taskMgr.add(self.rewardControl, "reward")
            self.keyTask = taskMgr.add(self.keyControl, "Key press")

    # Code to initialize the tunnel
    def initTunnel(self):
        self.tunnel = [None] * 8

        for x in range(8):
            # Load a copy of the tunnel
            self.tunnel[x] = loader.loadModel('models/tunnel')
            # The front segment needs to be attached to render
            if x == 0:
                self.tunnel[x].reparentTo(render)
            # The rest of the segments parent to the previous one, so that by moving
            # the front segement, the entire tunnel is moved
            else:
                self.tunnel[x].reparentTo(self.tunnel[x - 1])
                # We have to offset each segment by its length so that they stack onto
            # each other. Otherwise, they would all occupy the same space.
            self.tunnel[x].setPos(0, 0, -TUNNEL_SEGMENT_LENGTH)
            # Now we have a tunnel consisting of 4 repeating segments with a
            # hierarchy like this:
            # render<-tunnel[0]<-tunnel[1]<-tunnel[2]<-tunnel[3]

        self.tunnel[0] = loader.loadModel('models/grating')
        self.tunnel[0].reparentTo(render)
        self.cue_zone = arange(0, TUNNEL_SEGMENT_LENGTH, -1)-280

    # This function is called to snap the front of the tunnel to the back
    # to simulate traveling through it
    def contTunnel(self):
        self.auto_position_on_track -= 50
        position_on_track = self.auto_position_on_track
        print(str(int(position_on_track)) + '   ' + str(self.cue_zone))
        if int(position_on_track) in np.array(self.cue_zone):  # check for cue zone
            if not self.auto_restart:
                print('STOP!')
                self.tunnelMove.pause()
                self.auto_presentation = True
                # self.current_number_of_segments +=1
            else:
                self.auto_restart = True
                self.tunnelMove.resume()

        else:
            self.in_waiting_period = False
            self.auto_presentation = False

            # base.setBackgroundColor([1,0 , 0])
            if self.looking_for_a_cue_zone == False:
                self.looking_for_a_cue_zone = True
            if self.stim_started == True:
                self.stop_a_presentation()

            # This line uses slices to take the front of the list and put it on the
            # back. For more information on slices check the Python manual
            self.tunnel = self.tunnel[1:] + self.tunnel[0:1]

            # Set the front segment (which was at TUNNEL_SEGMENT_LENGTH) to 0, which
            # is where the previous segment started
            self.tunnel[0].setZ(0)
            # Reparent the front to render to preserve the hierarchy outlined above
            self.tunnel[0].reparentTo(render)
            # Set the scale to be apropriate (since attributes like scale are
            # inherited, the rest of the segments have a scale of 1)
            self.tunnel[0].setScale(.155, .155, .305)
            # Set the new back to the values that the rest of the segments have
            self.tunnel[3].reparentTo(self.tunnel[2])
            self.tunnel[3].setZ(-TUNNEL_SEGMENT_LENGTH)
            self.tunnel[3].setScale(1)

            # Set up the tunnel to move one segment and then call contTunnel again
            # to make the tunnel move infinitely
            self.tunnelMove = Sequence(
                LerpFunc(self.tunnel[0].setZ,
                         duration=TUNNEL_TIME,
                         fromData=0,
                         toData=TUNNEL_SEGMENT_LENGTH * .305),
                Func(self.contTunnel)
            )
            self.tunnelMove.start()
    
    def get_trial_duration(self):      #EAS updated 10.5.20
        self.stim_duration = self.rng.choice(self.distribution_type_inputs, 1, p=self.durWeights)  #pull out one value in array a, w/ probability based on weights
        return self.stim_duration[0]

#        return self.distribution_type(*self.distribution_type_inputs)

    def start_a_presentation(self):
        self.save_data()
        self.stim_duration = self.get_trial_duration()
        
        self.fixationPoint.destroy()
#        import pickle
#        with open('objs.pkl', 'wb') as f:  # Python 3: open(..., 'wb')
#            pickle.dump([self.stim_duration,self.distribution_type_inputs], f)
#            print('variables saved!!!')

        self.in_reward_window = True
        print("start")
        if have_nidaq:
            self.do.WriteBit(2, 1)
        # self.bufferViewer.toggleEnable()

        self.lick_buffer = []
        self.trialData.extend([globalClock.getFrameTime()])
        self.reactionTimeData.extend([-1])

        if self.stimtype == 'random image':

            if len(self.trialData) < 4:
                i=self.original_indices[int(np.round(np.random.random()))]   #commented out due to <43 images [see l. 290ish]
                self.stim_duration = 2.0
            else:                                                            #commented out due to <43 images
                i = randint(len(self.imageTextures))
                
            self.card.setTexture(self.imageTextures[i],0)
            self.dr2.setDimensions(0.25, 0.75, 0.25, 0.75)  # floats (left, right, bottom, top)
            self.img_id = self.img_list[i] #this assigns the current presented image to self.image_id
            print(self.img_id)
            self.imageData.extend(self.img_id)                    
        
        if self.stimtype == 'image_sequence':
            self.imagesTexture.setTime(0.)
            self.dr2.setDimensions(0.4, 0.8, 0.4, 0.70)  # floats (left, right, bottom, top)
            self.imagesTexture.play()
        self.imageTimeData.extend([globalClock.getFrameTime()])
        self.imageData.extend(self.img_id)
  
    def check_arrows(self):
        # this function will report which arrow was pressed. right = 1, left = 2, no press = 0
        if self.rightArrowIsPressed:
            #print('check arrows RIGHT')
            return 1
            # time.sleep(2)
        elif self.leftArrowIsPressed:
            #print('check arrows LEFT')
            return 2
            # time.sleep(2)
        else:
            return 0

    def stop_a_presentation(self):
        if self.stim_started == True:
            if self.stim_elapsed > self.stim_duration:
                self.trialDurationData.append(self.stim_duration)
            else: self.trialDurationData.append(self.stim_duration)
            self.dr2.setDimensions(0, 0.001, 0, 0.001)#make this really,really small so it's not seeable by the subject
            # self.bufferViewer.toggleEnable()
            self.stim_started = False
            self.stim_elapsed = 0.
            self.stim_duration = 0.
            self.stim_off_time = globalClock.getFrameTime()
            if have_nidaq:
                self.do.WriteBit(2, 0)
            # if globalClock.getFrameTime() > self.feedback_score_startime + 1.5:  # arbitrary wait to make sure this isn't after a correct trial
            #     self.feebackScoreText.setText('+' + str(0))
            #     self.feebackScoreText.setFg((1, 0, 0, 1))
            #     self.feebackScoreText.setX(.5)
            #     self.feedback_score_startime = globalClock.getFrameTime()
            self.scoreData.append(self.current_score)
            self.fixationPoint = OnscreenImage(image='models/fixationpoint.jpg', pos=(0, 0,0),scale=0.01)

            
    #   def keySensorSetup(self):


    def show_the_score(self):
            self.feebackScoreText.setText('+' + str(self.score))
            if self.score == 0:
                self.feebackScoreText.setFg((1, 0, 0, 1))
            else:
                self.feebackScoreText.setFg((0, 1, 0, 1))
            self.feebackScoreText.setX(.5)
            self.feedback_score_startime = globalClock.getFrameTime()
    # sets up the task to listen for user input from the keys

    def _lickSensorSetup(self):

        """ Attempts to set up lick sensor NI task. """
        ##TODO: Make lick sensor object if necessary. Let user select port and line.
        if have_nidaq:
            if self.di:
                self.lickSensor = self.di  # just use DI for now
                licktest = []
                for i in range(30):
                    licktest.append(self.rightArrowIsPressed.Read()[self.lickline])
                    time.sleep(0.01)
                licktest = np.array(licktest, dtype=np.uint8)
                if len(licktest[np.where(licktest > 0)]) > 25:
                    self.lickSensor = None
                    self.lickData = [np.zeros(len(self.rewardlines))]
                    print("Lick sensor failed startup test.")
                else:
                    print('lick sensor setup succeeded.')
                self.keycontrol = True
            else:
                print("Could not initialize lick sensor.  Ensure that NIDAQ is connected properly.")
                self.keycontrol = True
                self.lickSensor = None
                self.lickData = [np.zeros(len(self.rewardlines))]
                self.keys = key.KeyStateHandler()
                # self.window.winHandle.push_handlers(self.keys)
        else:
            print("Could not initialize lick sensor.  Ensure that NIDAQ is connected properly.")
            self.keycontrol = True
            self.lickSensor = None
            self.lickData = [np.zeros(len(self.rewardlines))]
            self.keys = key.KeyStateHandler()

    def reactiontime_to_score(self):
        rt = globalClock.getFrameTime() - self.trialData[-1]
        self.reactionTimeData[-1] = rt
        score = 100. / rt  # scale the reaction time, with faster producing more points
        return int(score / 20.)

    # def _read_licks(self): # not yet implemented; should be replaces with check to beam break
    def _give_reward(self, volume):
        print("reward!")
        self.rewardData.extend([globalClock.getFrameTime()])

        # for humans
        self.score = self.reactiontime_to_score()
        self.current_score += self.score
        self.show_the_score()
        self.scoreText.setText(str(self.current_score))
        

        # for mice
        if have_nidaq:
            self.do.WriteBit(3, 0)
            time.sleep(self.reward_time)
            self.do.WriteBit(3, 1)  # put a TTL on a line to indicate that a reward was given
            s.dispense(volume)  # pass # not yet implemented

    def _toggle_reward(self):
        if self.AUTO_REWARD:
            self.AUTO_REWARD = False
            print('switched to lick sensing for reward.')
        else:
            self.AUTO_REWARD = True
            print('switched to automatic rewards after stimuli.')

    def autoLoop2(self, task):
        dt = globalClock.getDt()
        current_time = globalClock.getFrameTime()

        self.x.extend([self.auto_position_on_track])
        self.t.extend([globalClock.getFrameTime()])

        if self.auto_presentation:
            self.auto_running = False
            if self.in_waiting_period:
                self.time_waited += dt
            else:
                self.time_waited = 0
                self.in_waiting_period = True
            if self.time_waited > self.wait_time:  # if in cue zone,see if we have been ther for long enough
                # start a trial
                self.start_position = self.auto_position_on_track
                self.start_time = current_time
                if not self.stim_started:
                    self.start_a_presentation()
                    # print(self.stim_duration)
                    self.stim_started = True
                    self.show_stimulus = True
                else:
                    self.stim_elapsed += dt
                    if self.stim_elapsed > self.stim_duration:
                        self.show_stimulus = False
                        self.in_reward_window = True
                        self.stop_a_presentation()
                        self.auto_restart = False
                        # print(self.current_number_of_segments)
                        self.current_number_of_segments += 9
                        # redefine the cue zone as the next one
                        self.cue_zone = arange(self.current_number_of_segments * -TUNNEL_SEGMENT_LENGTH,
                                               self.current_number_of_segments * -TUNNEL_SEGMENT_LENGTH - TUNNEL_SEGMENT_LENGTH - 280,
                                               -1)
                        # extend cue zone, keeping old ones
                        # self.cue_zone = concatenate((self.cue_zone,arange(self.current_number_of_segments*-TUNNEL_SEGMENT_LENGTH-40,
                        #                             self.current_number_of_segments*-TUNNEL_SEGMENT_LENGTH-TUNNEL_SEGMENT_LENGTH-40,
                        #                             -1)))
                        self.contTunnel()
                        self.time_waited = 0
                        self.looking_for_a_cue_zone = False
                # base.setBackgroundColor([0, 0, 1])
            else:
                pass  # base.setBackgroundColor([0, 1, 0])
        else:
            self.auto_running = True
        return Task.cont  # Since every return is Task.cont, the task will

    def gameLoop(self, task):
        # get the time elapsed since the next frame.
        dt = globalClock.getDt()
        self.new_dt.append(dt)                  #Store the append here for dt
        
        current_time = globalClock.getFrameTime()    #This is for the key press
        if current_time > self.feedback_score_startime + 1.5:
            self.feebackScoreText.setX(3.)
        # get the camera position.
        position_on_track = base.camera.getZ()

        # get the encoder position from NIDAQ Analog Inputs channel 2
        if have_nidaq:
            encoder_position = self.ai.data[0][self.encodervsigchannel]  # zeroth sample in buffer [0], from ai2 [2]
            # convert to track coordinates
            encoder_position_diff = (encoder_position - self.previous_encoder_position)
            if encoder_position_diff > 4.5: encoder_position_diff -= 5.
            if encoder_position_diff < -4.5: encoder_position_diff += 5.
            self.encoder_position_diff = encoder_position_diff * self.encoder_gain
            self.previous_encoder_position = encoder_position
        else:
            self.read_keys()
            if self.upArrowIsPressed:
                self.encoder_position_diff = -1 * self.encoder_gain
            if self.downArrowIsPressed:
                self.encoder_position_diff = 1 * self.encoder_gain
            if not self.downArrowIsPressed:
                if not self.upArrowIsPressed:
                    self.encoder_position_diff = 0
        position_on_track = base.camera.getZ() + self.encoder_position_diff
        # reset the camera position
        self.camera.setPos(base.camera.getX(), base.camera.getY(), position_on_track)

        self.x.extend([position_on_track])
        self.t.extend([globalClock.getFrameTime()])

        # first check if the mouse moved on the last frame.
        if abs(self.last_position - position_on_track) < 1.5:  # the mouse didn't move more than 0.5 units on the track
            self.moved = False
            if int(position_on_track) in self.cue_zone:  # check for cue zone
                if self.looking_for_a_cue_zone:  # make sure we transitioning from the tunnel to a cue zone
                    # increment how long we've been waiting in the cue zone.
                    if self.in_waiting_period:
                        self.time_waited += dt
                    else:
                        self.time_waited = 0
                        self.in_waiting_period = True
                    if self.time_waited > self.wait_time:  # if in cue zone,see if we have been ther for long enough
                        # start a trial
                        self.start_position = position_on_track
                        self.start_time = current_time
                        if not self.stim_started:
                            self.start_a_presentation()
                            print(self.stim_duration)
                            self.stim_started = True
                            self.show_stimulus = True
                        else:
                            self.stim_elapsed += dt
                            if self.stim_elapsed > self.stim_duration:
                                self.show_stimulus = False
                                self.stop_a_presentation()
                                self.time_waited = 0
                                self.looking_for_a_cue_zone = False
                        # base.setBackgroundColor([0, 0, 1])
                    else:
                        pass  # base.setBackgroundColor([0, 1, 0])
            else:
                self.in_waiting_period = False
                # base.setBackgroundColor([1,0 , 0])
                if self.looking_for_a_cue_zone == False:
                    self.looking_for_a_cue_zone = True
                if self.stim_started == True:
                    self.stop_a_presentation()
        else:  # the mouse did move
            self.moved = True
            if self.stim_started == True:  # check if it moved during a presenation
                self.stop_a_presentation()
                self.time_waited = 0
                self.looking_for_a_cue_zone = False
                self.show_stimulus = False

        # if we need to add another segment, do so
        if position_on_track < self.boundary_to_add_next_segment:
            self.tunnel.extend([None])
            x = self.current_number_of_segments
            if x % 8 == 0:
                self.tunnel[x] = loader.loadModel('models/grating')
                self.cue_zone = concatenate((self.cue_zone, arange( \
                    self.current_number_of_segments * -TUNNEL_SEGMENT_LENGTH - 50, \
                    self.current_number_of_segments * -TUNNEL_SEGMENT_LENGTH - TUNNEL_SEGMENT_LENGTH - 100, \
                    -1)))
            else:
                self.tunnel[x] = loader.loadModel('models/tunnel')
            self.tunnel[x].setPos(0, 0, -TUNNEL_SEGMENT_LENGTH)
            self.tunnel[x].reparentTo(self.tunnel[x - 1])
            # increment
            self.boundary_to_add_next_segment -= TUNNEL_SEGMENT_LENGTH
            self.current_number_of_segments += 1
        else:
            pass  # print('current:'+str(position_on_track) +'      next boundary:' + str(self.boundary_to_add_next_segment))

        self.last_position = position_on_track

        # lick_times = self.
        # self._read_licks()
        return Task.cont  # Since every return is Task.cont, the task will
        # continue indefinitely, under control of the mouse (animal)

    def stimulusControl(self, task):
        if self.show_stimulus and not self.bufferViewer.isEnabled():
            # self.bufferViewer.toggleEnable()
            self.dr2.setDimensions(0.5, 0.9, 0.5, 0.8)
        if not self.show_stimulus and self.bufferViewer.isEnabled():
            # self.bufferViewer.toggleEnable()
            self.dr2.setDimensions(0, 0.1, 0, 0.1)
        return Task.cont

    def lickControl(self, task):
        """ Checks to see if a lick is occurring. """
        ##TODO: Let user select line for lick sensing.
        if self.lickSensor:
            if self.lickSensor.Read()[self.lickline]:
                self.lickData.extend([globalClock.getFrameTime()])
                print('lick happened at: ' + str(self.lickData[-1]))
        elif self.keycontrol == True:  # NO NI BOARD.  KEY INPUT?
            if self.keys[key.SPACE]:
                data = [globalClock.getFrameTime()]
            elif self.keys[key.NUM_1]:
                # print(self.lickData)
                # elif self.keys[key.NUM_3]:
                #     data = [0,1]
                # else:
                #     data = [0,0]
                self.lickData.extend(data)
        return Task.cont

    def keyControl(self, task):
        # listen to and record when the arrows are pressed
        self.read_keys()
        if self.rightArrowIsPressed:
            self.rightKeyData.extend([globalClock.getFrameTime()])
            print('right arrow at: ' + str(self.rightKeyData[-1]))
#            time.sleep(.2)  #EAS changed this only allows for one keystroke to be recorded every 0.5s
        elif self.leftArrowIsPressed:
            self.leftKeyData.extend([globalClock.getFrameTime()])
            print('left arrow at: ' + str(self.leftKeyData[-1]))
#            time.sleep(.2)  #EAS changed this only allows for one keystroke to be recorded every 0.5s
        return Task.cont

    def rewardControl(self, task):
        # print(self.in_reward_window)
        if self.in_reward_window == True:
            if self.reward_elapsed < self.reward_window:
            
                self.reward_elapsed += globalClock.getDt()
#                self.new_reward_elapsed.append(self.reward_elapsed)
                
#                import pickle
#                with open('objs.pkl', 'wb') as f:  # Python 3: open(..., 'wb')
#                    pickle.dump([self.stim_duration,self.distribution_type_inputs, self.new_rew_control], f)
#                    print('variables saved!!!')

                self.check_arrows()
                if not self.AUTO_REWARD:
                    
                    if self.check_arrows() == 1:  # if check arrows returns a 1 the right arrow was pressed during stimulus presentation
                        # note reaction time
                        if self.img_id.find("Elephant") != -1: #if the current image file contains the string in () the value is not -1
                            self._give_reward(self.reward_volume)
                            print('correct: image was mostly elephant')
                            self.in_reward_window = False;
                            self.reward_elapsed = 0.  # reset
                        
                        elif 'Same' in self.img_id:                     #updated 8.24.20: reward 50/50 images 1/2 the time
                            if round(np.random.random(1)[0]):
                                self._give_reward(self.reward_volume)
                                print('correct: image was same')
                                self.in_reward_window = False;
                                self.reward_elapsed = 0.  # reset
                            else:
                                print(self.img_mask)
                                print('incorrect: image was same')
                                self.in_reward_window = False
                                self.reward_elapsed = 0.  # reset
                                self.score=0
                                self.show_the_score()
                        else:
                            print(self.img_mask)
                            print('image was not mostly elephant!')
                            self.in_reward_window = False
                            self.reward_elapsed = 0.  # reset
                            self.score=0
                            self.show_the_score()
                                                        
                    if self.check_arrows() == 2:                          #if check arrows returns a 2 the left arrow was pressed during stimulus presentation
                        if self.img_id.find("Cheetah") != -1:             #if the current image file contains the string in () the value is not -1
                            self._give_reward(self.reward_volume)
                            print('correct: image was mostly cheetah')
                            self.in_reward_window = False;
                            self.reward_elapsed = 0.  # reset
                        
                        elif 'Same' in self.img_id:                      #updated 8.24.20: reward 50/50 images 1/2 the time
                            if round(np.random.random(1)[0]):
                                self._give_reward(self.reward_volume)
                                print('correct: image was same')
                                self.in_reward_window = False;
                                self.reward_elapsed = 0.  # reset
                            else:
                                print(self.img_mask)
                                print('incorrect: image was same')
                                self.in_reward_window = False
                                self.reward_elapsed = 0.  # reset
                                self.score=0
                                self.show_the_score()
                        else:
                            print(self.img_mask)
                            print('image was not mostly cheetah!')
                            self.in_reward_window = False
                            self.reward_elapsed = 0.  # reset
                            self.score=0
                            self.show_the_score()
                    
                        

                else:
                    self._give_reward(self.reward_volume)
                    self.in_reward_window = False;
                    self.reward_elapsed = 0.  # reset
                    # base.setBackgroundColor([1, 1, 0])

#            # if self.keys[key.NUM_1]:
#            #     print('reward!')
            else:
                self.score=0
                self.show_the_score()
                self.in_reward_window = False
                self.reward_elapsed = 0.
        else:
            pass#print('not listening for reward'+str(globalClock.getFrameTime()))
        return Task.cont

    def _setupEyetracking(self):
        """ sets up eye tracking"""
        try:
            eyetrackerip = "DESKTOP-EE5KKDO"
            eyetrackerport = 10000
            trackeyepos = False
            from aibs.Eyetracking.EyetrackerClient import Client
            self.eyetracker = Client(outgoing_ip=eyetrackerip,
                                     outgoing_port=eyetrackerport,
                                     output_filename=str(datetime.datetime.now()).replace(':', '').replace('.',
                                                                                                           '').replace(
                                         ' ', '-'))
            self.eyetracker.setup()
            # eyedatalog = []
            # if trackeyepos:
            #     eyeinitpos = None
        except:
            print("Could not initialize eyetracker:")
            self.eyetracker = None

    def _startEyetracking(self):
        if self.eyetracker:
            self.eyetracker.recordStart()

    def _setupDAQ(self):
        """ Sets up some digital IO for sync and tiggering. """
        print('SETTING UP DAQ')
        try:
            if self.invertdo:
                istate = 'low'
            else:
                istate = 'high'
            self.do = DigitalOutput(self.nidevice, self.doport,
                                    initial_state='low')
            self.do.StartTask()
        except:  # Exception, e:
            print("Error starting DigitalOutput task:")
            self.do = None
        try:
            self.di = DigitalInput(self.nidevice, self.diport)
            self.di.StartTask()
        except:  # Exception, e:
            print("Error starting DigitalInput task:")
            self.di = None
        # try:
        # set up 8 channels, only use 2 though for now
        self.ai = AnalogInput(self.nidevice, range(8), buffer_size=25, terminal_config='RSE',
                              clock_speed=6000.0, voltage_range=[-5.0, 5.0])
        self.ai.StartTask()
        # except:# Exception, e:
        # print("Error starting AnalogInput task:")
        # self.ai = None
        try:
            self.ao = AnalogOutput(self.nidevice, channels=[0, 1], terminal_config='RSE',
                                   voltage_range=[0.0, 5.0])
            self.ao.StartTask()
        except:  # Exception, e:
            print("Error starting AnalogOutput task:")
            self.ao = None

    def read_keys(self):
        self.upArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.up())
        self.downArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.down())
        self.rightArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.right())
        self.leftArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.left())

    def save_data(self):
        if not os.path.isdir(os.path.join(os.getcwd(), 'data')):
            os.mkdir(os.path.join(os.getcwd(), 'data'))
        save_path = os.path.join(os.getcwd(), 'data', str(MOUSE_ID) + '_' + \
                                 str(self.session_start_time.year) + '_' + \
                                 str(self.session_start_time.month) + '_' + \
                                 str(self.session_start_time.day) + '-' + \
                                 str(self.session_start_time.hour) + '_' + \
                                 str(self.session_start_time.minute) + '_' + \
                                 str(self.session_start_time.second))
        if not os.path.isdir(save_path):
            os.mkdir(save_path)

        print("saving data to " + save_path)
        np.save(os.path.join(save_path, 'licks.npy'), self.lickData)
        np.save(os.path.join(save_path, 'x.npy'), self.x)
        np.save(os.path.join(save_path, 't.npy'), self.t)
        np.save(os.path.join(save_path, 'trialData.npy'), self.trialData)
        np.save(os.path.join(save_path, 'rewardData.npy'), self.rewardData)
        np.save(os.path.join(save_path, 'rtData.npy'), self.reactionTimeData)
        np.save(os.path.join(save_path, 'rightKeyData.npy'), self.rightKeyData)
        np.save(os.path.join(save_path, 'leftKeyData.npy'), self.leftKeyData)
        np.save(os.path.join(save_path, 'imageData.npy'), self.imageData)
        np.save(os.path.join(save_path, 'imageTimeData.npy'), self.imageTimeData)
        np.save(os.path.join(save_path, 'scoreData.npy'), self.scoreData)
        np.save(os.path.join(save_path, 'trialDurationData.npy'), self.trialDurationData)
        np.save(os.path.join(save_path, 'dT.npy'), self.new_dt)

    def close(self):
        self.save_data()

        print('rewardData:')
        print(np.shape(self.rewardData))
        try:
            #push anonymized data to Denman Lab Open Science Framework project for human psychophysics
            subprocess.call('osf -p 7xruh -u [email protected] upload -r '+save_path+' data/'+os.path.basename(save_path),shell=True)     #commented these lines out to test if saving to osf is the hangup; it's not
        except:pass

        sys.exit(0)
Example #34
0
class Credits:
    def __init__(self,
                 name,
                 description,
                 image,
                 side='left',
                 number=1,
                 name2=None,
                 description2=None,
                 image2=None,
                 special=None):
        self.sceneRoot = None
        self.twoSlides = None
        self.toonName = name
        self.toonDescription = description
        self.toonImage = image
        self.side = side
        self.special = special  # For special types of slides, like the final one
        if number > 1:
            self.toon2Name = name2
            self.toon2Description = description2
            self.toon2Image = image2
            self.twoSlides = True

    def load(self):
        self.sceneRoot = NodePath(
            self.toonName.replace(' ', '').replace('', ''))
        base.setBackgroundColor(0, 0, 0, 1)

        if self.twoSlides:
            if self.side == 'left':
                # Left Top
                titlePos = (0.1, 0.5, 0.0)
                descriptionPos = (0.2, 0.4, 0.0)
                imagePos = (-0.55, 0.0, 0.4)
                textAlignment = TextNode.ALeft
                # Right Bottom
                title2Pos = (-0.1, -0.35, 0.0)
                description2Pos = (-0.1, -0.45, 0.0)
                image2Pos = (0.55, 0.0, -0.4)
                text2Alignment = TextNode.ARight
            else:
                # Right Top
                titlePos = (-0.1, 0.5, 0.0)
                descriptionPos = (-0.1, 0.4, 0.0)
                imagePos = (0.55, 0.0, 0.4)
                textAlignment = TextNode.ARight
                # Left Bottom
                title2Pos = (0.1, -0.35, 0.0)
                description2Pos = (0.25, -0.45, 0.0)
                image2Pos = (-0.55, 0.0, -0.4)
                text2Alignment = TextNode.ALeft
        elif self.side == 'left':
            # Left Middle
            titlePos = (0.1, 0.15, 0.0)
            descriptionPos = (0.2, 0.05, 0.0)
            imagePos = (-0.5, 0.0, 0.0)
            textAlignment = TextNode.ALeft
        else:
            # Right Middle
            titlePos = (-0.1, 0.1, 0.0)
            descriptionPos = (-0.11, 0.0, 0.0)
            imagePos = (0.5, 0.0, 0.0)
            textAlignment = TextNode.ARight

        self.title = OnscreenText(text=self.toonName,
                                  pos=titlePos,
                                  scale=0.15,
                                  fg=(1, 1, 1, 1),
                                  font=ToontownGlobals.getSignFont(),
                                  align=textAlignment)
        self.description = OnscreenText(text=self.toonDescription,
                                        pos=descriptionPos,
                                        scale=0.06,
                                        fg=(1, 1, 1, 1),
                                        font=ToontownGlobals.getMinnieFont(),
                                        align=textAlignment)
        self.image = OnscreenImage(image='phase_4/maps/news/%s' %
                                   self.toonImage,
                                   pos=imagePos,
                                   scale=(0.5, 0.30, 0.30))
        self.elements = [self.title, self.description, self.image]

        if self.twoSlides:
            self.title2 = OnscreenText(text=self.toon2Name,
                                       pos=title2Pos,
                                       scale=0.15,
                                       fg=(1, 1, 1, 1),
                                       font=ToontownGlobals.getSignFont(),
                                       align=text2Alignment)
            self.description2 = OnscreenText(
                text=self.toon2Description,
                pos=description2Pos,
                scale=0.06,
                fg=(1, 1, 1, 1),
                font=ToontownGlobals.getMinnieFont(),
                align=text2Alignment)
            self.image2 = OnscreenImage(image='phase_4/maps/news/%s' %
                                        self.toon2Image,
                                        pos=image2Pos,
                                        scale=(0.5, 0.30, 0.30))
            self.elements.extend([self.title2, self.description2, self.image2])

        for node in self.elements:
            node.setTransparency(1)
            node.setColorScale(1, 1, 1, 0)

    def makeInterval(self):
        if self.special == 'final':
            # Hide the last slide, rather than fade out
            return Sequence(ParentInterval(self.sceneRoot, render),
                            Func(doFade, 'in', self.elements), Wait(3),
                            Func(doFade, 'hide', self.elements),
                            ParentInterval(self.sceneRoot, hidden))
        else:
            # Just a normal slide
            return Sequence(ParentInterval(self.sceneRoot, render),
                            Func(doFade, 'in', self.elements), Wait(3.5),
                            Func(doFade, 'out', self.elements), Wait(0.5),
                            ParentInterval(self.sceneRoot, hidden))

    def unload(self):
        self.sceneRoot.removeNode()
        self.title.removeNode()
        self.description.removeNode()
        self.image.removeNode()
        self.elements = None
        self.toonName = None
        self.toonDescription = None
        self.toonImage = None
        self.side = None
 def _initScore(self):
     self._scoreLabel = OnscreenText(text = '0', pos = PartyGlobals.CogActivityScorePos, scale = PartyGlobals.TugOfWarTextWordScale, fg = (1.0, 1.0, 0.0, 1.0), align = TextNode.ARight, font = ToontownGlobals.getSignFont(), mayChange = True)
     self._scoreTitle = OnscreenText(text = TTLocalizer.PartyCogGuiScoreLabel, pos = PartyGlobals.CogActivityScoreTitle, scale = 0.050000000000000003, fg = (1.0, 1.0, 1.0, 1.0), align = TextNode.ARight)
     self._scoreLabel.hide()
     self._scoreTitle.hide()
    def __init__(self, planeten):
        """
        Konstruktor hier wird alles gemanaget
        :param planeten: Planeten die erzeugt werden sollen
        """
        ShowBase.__init__(self)
        base.disableMouse()

        self.t = True

        # Pseudo-constants
        self.titleString = "Beste SolarSystem ever."
        self.renderRatio = 1.0e-6
        self.degPerSecond = 60.0
        self.minCameraDistance = 4.0
        self.maxCameraDistance = 4000.0
        self.zoomPerSecond = 1.8

        base.setBackgroundColor(0, 0, 0)

        # Init camera move variables
        self.keyMap = {"left":0, "right":0, "up":0, "down":0, "pageup":0, "pagedown":0, "wheelup":0, "wheeldown":0, "mouse3":0, "tab":0}
        self.angleLongitudeDegrees = 0.0
        self.angleLatitudeDegrees = 0.0
        self.cameraDistance = 10.0
        self.targetNode = render
        self.light = False

        #This code puts the standard title and instruction text on screen
        self.titleText = OnscreenText(text=self.titleString,
                                      style=1, fg=(1,1,0,1),
                                      pos=(0.8,-0.95), scale = .07)

        # Create empty node for world origin
        self.worldOrigin = render.attachNewNode("World Origin")
        self.planeten = planeten
        # Texture aender
        self.planeteninstance = []
        for p in planeten:
            if p[0] == "sun":
                self.su = Planetimpl(self.worldOrigin, 8.37800000E+06, 0, self.renderRatio, "sun", 10, 0)
                self.sun = self.su.impl()
                self.planeteninstance.extend([self.su])
                self.o = self.su
            else:
                self.o = Planetimpl(self.worldOrigin, p[1], p[2], self.renderRatio, p[0], p[3], p[4])
                self.orbit = self.o.impl()
                self.planeteninstance.extend([self.o])
            self.orbitOrbitVertexWriter = self.o.line()
            self.taskMgr.add(self.o.rotatePlanet, "rotate"+p[0], sort=1)
            self.taskMgr.add(self.o.translatePlanet, "move"+p[0]+"Orbit", sort=1)

        shadow = [[1.25, 1.25, 1.25]]
        self.plnp = []
        for s in shadow:
            self.plnp.append(self.pointlight(s[0], s[1], s[2]))
        # Attach the camera to the Earth to begin with
        self.targetNode = self.sun
        self.targetSize = float(self.targetNode.getTag("targetSize"))
        self.listener()
        self.cameraview()
        self.taskMgr.add(self.moveOrbitalCameraTask, "moveOrbitalCameraTask", sort=2)
class PartyCogActivityGui(DirectObject):
    notify = directNotify.newCategory('PartyCogActivityGui')
    
    def __init__(self):
        DirectObject.__init__(self)
        self._piePowerMeter = None
        self._victoryBalanceBar = None
        self._scoreLabel = None
        self._cogTracker = None
        self._piePowerTitle = None
        self._victoryBalanceTitle = None
        self._scoreTitle = None
        self._spamWarning = None
        self._spamWarningIvalName = 'PartyCogActivityGui-SpamWarning'

    
    def load(self):
        self._initPiePowerMeter()
        self._initScore()
        self._initCogTracker()
        self._initSpamWarning()
        self._initControlGui()
        self._initVictoryBalanceBar()

    
    def unload(self):
        if self._cogTracker is not None:
            self._cogTracker.destory()
            self._cogTracker = None
        
        if self._piePowerMeter is not None:
            self._piePowerMeter.destroy()
            self._piePowerMeter = None
        
        if self._piePowerTitle is not None:
            self._piePowerTitle.destroy()
            self._piePowerTitle = None
        
        if self._scoreLabel is not None:
            self._scoreLabel.destroy()
            self._scoreLabel = None
        
        if self._scoreTitle is not None:
            self._scoreTitle.destroy()
            self._scoreTitle = None
        
        taskMgr.remove(self._spamWarningIvalName)
        if self._spamWarning:
            self._spamWarning.destroy()
            self._spamWarning = None
        
        if hasattr(self, '_attackKeys'):
            self._attackKeys.detachNode()
            del self._attackKeys
        
        if hasattr(self, '_moveKeys'):
            self._moveKeys.detachNode()
            del self._moveKeys
        
        if self._victoryBalanceBar:
            self._victoryBalanceBar.detachNode()
            self._victoryBalanceBar = None
        
        if self._victoryBalanceBarOrange:
            self._victoryBalanceBarOrange.detachNode()
            self._victoryBalanceBarOrange = None
        
        if self._victoryBalanceBarPie:
            self._victoryBalanceBarPie.detachNode()
            self._victoryBalanceBarPie = None
        
        if self._victoryBalanceBarArrow:
            self._victoryBalanceBarArrow.detachNode()
            self._victoryBalanceBarArrow = None
        

    
    def _initVictoryBalanceBar(self):
        h = PartyGlobals.CogActivityPowerMeterHeight / 2.0
        w = PartyGlobals.CogActivityPowerMeterWidth / 2.0
        victoryBalanceBar = loader.loadModel('phase_13/models/parties/tt_m_gui_pty_pieToss_balanceBar')
        self._victoryBalanceBar = victoryBalanceBar.find('**/*tt_t_gui_pty_pieToss_balanceBarBG')
        self._victoryBalanceBar.reparentTo(aspect2d)
        self._victoryBalanceBar.setBin('fixed', 0)
        self._victoryBalanceBar.setPos(PartyGlobals.CogActivityVictoryBarPos)
        self._victoryBalanceBar.setScale(1)
        self._victoryBalanceBarOrange = victoryBalanceBar.find('**/*tt_t_gui_pty_pieToss_balanceBarOrange')
        self._victoryBalanceBarOrange.reparentTo(self._victoryBalanceBar)
        self._victoryBalanceBarOrange.setBin('fixed', 1)
        self._victoryBalanceBarOrange.setPos(PartyGlobals.CogActivityVictoryBarOrangePos)
        self._victoryBalanceBarOrange.setScale(PartyGlobals.CogActivityBarStartScale, 1.0, 1.0)
        self._victoryBalanceBarPie = victoryBalanceBar.find('**/*tt_t_gui_pty_pieToss_balanceBarPie')
        self._victoryBalanceBarPie.reparentTo(self._victoryBalanceBar)
        self._victoryBalanceBarPie.setBin('fixed', 2)
        self._victoryBalanceBarPie.setX(PartyGlobals.CogActivityVictoryBarPiePos[0])
        self._victoryBalanceBarPie.setY(PartyGlobals.CogActivityVictoryBarPiePos[1])
        self._victoryBalanceBarPie.setZ(PartyGlobals.CogActivityVictoryBarPiePos[2])
        self._victoryBalanceBarPie.setScale(PartyGlobals.CogActivityBarPieScale)
        self._victoryBalanceBarArrow = victoryBalanceBar.find('**/*tt_t_gui_pty_pieToss_balanceArrow')
        self._victoryBalanceBarArrow.reparentTo(self._victoryBalanceBarPie)
        self._victoryBalanceBarArrow.setBin('fixed', 2)
        self._victoryBalanceBarArrow.setPos(PartyGlobals.CogActivityVictoryBarArrow)
        self._victoryBalanceBarArrow.setScale(1 / PartyGlobals.CogActivityBarPieScale)

    
    def _initControlGui(self):
        self._attackIvalName = 'PartyCogActivityGui-attackKeys'
        self._moveIvalName = 'PartyCogActivityGui-moveKeys'
        pieTossControls = loader.loadModel('phase_13/models/parties/tt_m_gui_pty_pieToss_controls')
        self._attackKeys = pieTossControls.find('**/*control*')
        self._moveKeys = pieTossControls.find('**/*arrow*')
        self._moveKeys.reparentTo(aspect2d)
        self._moveKeys.setPos(1.0, 0.0, -0.435)
        self._moveKeys.setScale(0.14999999999999999)
        self._attackKeys.reparentTo(aspect2d)
        self._attackKeys.setPos(0.84999999999999998, 0.0, -0.45000000000000001)
        self._attackKeys.setScale(0.14999999999999999)
        self._moveKeys.hide()
        self._attackKeys.hide()

    
    def _initPiePowerMeter(self):
        h = PartyGlobals.CogActivityPowerMeterHeight / 2.0
        w = PartyGlobals.CogActivityPowerMeterWidth / 2.0
        self._piePowerMeter = DirectWaitBar(frameSize = (-h, h, -w, w), relief = DGG.GROOVE, frameColor = (0.90000000000000002, 0.90000000000000002, 0.90000000000000002, 1.0), borderWidth = (0.01, 0.01), barColor = PartyGlobals.CogActivityColors[0], pos = PartyGlobals.CogActivityPowerMeterPos, hpr = (0.0, 0.0, -90.0))
        self._piePowerMeter.setBin('fixed', 0)
        self._piePowerTitle = OnscreenText(text = TTLocalizer.PartyCogGuiPowerLabel, pos = PartyGlobals.CogActivityPowerMeterTextPos, scale = 0.050000000000000003, fg = (1.0, 1.0, 1.0, 1.0), align = TextNode.ACenter)
        self._piePowerTitle.setBin('fixed', 0)
        self._piePowerMeter.hide()
        self._piePowerTitle.hide()

    
    def _initScore(self):
        self._scoreLabel = OnscreenText(text = '0', pos = PartyGlobals.CogActivityScorePos, scale = PartyGlobals.TugOfWarTextWordScale, fg = (1.0, 1.0, 0.0, 1.0), align = TextNode.ARight, font = ToontownGlobals.getSignFont(), mayChange = True)
        self._scoreTitle = OnscreenText(text = TTLocalizer.PartyCogGuiScoreLabel, pos = PartyGlobals.CogActivityScoreTitle, scale = 0.050000000000000003, fg = (1.0, 1.0, 1.0, 1.0), align = TextNode.ARight)
        self._scoreLabel.hide()
        self._scoreTitle.hide()

    
    def _initCogTracker(self):
        self._cogTracker = PartyCogTrackerGui()

    
    def _initSpamWarning(self):
        self._spamWarning = OnscreenText(text = TTLocalizer.PartyCogGuiSpamWarning, scale = 0.14999999999999999, fg = (1.0, 1.0, 0, 1.0), shadow = (0, 0, 0, 0.62), mayChange = False, pos = (0, 0.33000000000000002))
        self._spamWarning.hide()

    
    def showScore(self):
        self._scoreLabel.show()
        self._scoreTitle.show()

    
    def hideScore(self):
        self._scoreLabel.hide()
        self._scoreTitle.hide()

    
    def setScore(self, score = 0):
        self._scoreLabel['text'] = str(score)

    
    def resetPiePowerMeter(self):
        self._piePowerMeter['value'] = 0

    
    def showPiePowerMeter(self):
        self._piePowerMeter.show()
        self._piePowerTitle.show()

    
    def hidePiePowerMeter(self):
        self._piePowerMeter.hide()
        self._piePowerTitle.hide()

    
    def updatePiePowerMeter(self, value):
        self._piePowerMeter['value'] = value

    
    def getPiePowerMeterValue(self):
        return self._piePowerMeter['value']

    
    def hideSpamWarning(self):
        taskMgr.remove(self._spamWarningIvalName)
        if self._spamWarning:
            self._spamWarning.hide()
        

    
    def showSpamWarning(self):
        if self._spamWarning.isHidden():
            self._spamWarning.show()
            taskMgr.remove(self._spamWarningIvalName)
            Sequence(ToontownIntervals.getPulseLargerIval(self._spamWarning, ''), Wait(PartyGlobals.CogActivitySpamWarningShowTime), Func(self.hideSpamWarning), name = self._spamWarningIvalName, autoFinish = 1).start()
        

    
    def hide(self):
        self.hidePiePowerMeter()
        self.hideScore()
        self.hideSpamWarning()
        self.hideControls()

    
    def disableToontownHUD(self):
        base.localAvatar.hideName()
        base.localAvatar.laffMeter.hide()
        base.setCellsAvailable(base.bottomCells + [
            base.rightCells[1]], False)

    
    def enableToontownHUD(self):
        base.localAvatar.showName()
        base.localAvatar.laffMeter.show()
        base.setCellsAvailable(base.bottomCells + [
            base.rightCells[1]], True)

    
    def setTeam(self, team):
        self.team = team
        if team == 0:
            self._cogTracker.frame.setR(180)
        
        self._piePowerMeter['barColor'] = PartyGlobals.CogActivityColors[team]

    
    def startTrackingCogs(self, cogs):
        self.cogs = cogs
        taskMgr.add(self.trackCogs, 'trackCogs')

    
    def trackCogs(self, task):
        if self.cogs is None:
            return None
        
        self._updateVictoryBar()
        for (i, cog) in enumerate(self.cogs):
            self._cogTracker.updateCog(i, cog, self.team)
        
        return task.cont

    
    def _updateVictoryBar(self):
        if not hasattr(self, '_victoryBalanceBar') and self._victoryBalanceBar:
            return None
        
        netDistance = 0
        for cog in self.cogs:
            netDistance = netDistance + cog.targetDistance
        
        teamDistance = netDistance / 6.0
        self._victoryBalanceBarOrange.setScale(PartyGlobals.CogActivityBarStartScale + teamDistance * 10 * PartyGlobals.CogActivityBarUnitScale, 1.0, 1.0)
        self._victoryBalanceBarPie.setX(PartyGlobals.CogActivityVictoryBarPiePos[0] + teamDistance * 10 * PartyGlobals.CogActivityBarPieUnitMove)
        self._victoryBalanceBarPie.setY(PartyGlobals.CogActivityVictoryBarPiePos[1])
        self._victoryBalanceBarPie.setZ(PartyGlobals.CogActivityVictoryBarPiePos[2])
        if teamDistance > 0.0:
            self._victoryBalanceBarArrow.setColor(PartyGlobals.CogActivityColors[1])
        elif teamDistance < 0.0:
            self._victoryBalanceBarArrow.setColor(PartyGlobals.CogActivityColors[0])
        else:
            self._victoryBalanceBarArrow.setColor(VBase4(1.0, 1.0, 1.0, 1.0))

    
    def stopTrackingCogs(self):
        taskMgr.remove('trackCogs')

    
    def showAttackControls(self):
        if self._attackKeys.isHidden():
            self._attackKeys.show()
            taskMgr.remove(self._attackIvalName)
            Sequence(ToontownIntervals.getPulseLargerIval(self._attackKeys, '', scale = 0.14999999999999999), Wait(PartyGlobals.CogActivityControlsShowTime), Func(self.hideAttackControls), name = self._attackIvalName, autoFinish = 1).start()
        

    
    def showMoveControls(self):
        if self._moveKeys.isHidden() and not self._attackKeys.isHidden():
            self._moveKeys.show()
            taskMgr.remove(self._moveIvalName)
            Sequence(ToontownIntervals.getPulseLargerIval(self._moveKeys, '', scale = 0.14999999999999999), Wait(PartyGlobals.CogActivityControlsShowTime), Func(self.hideMoveControls), name = self._moveIvalName, autoFinish = 1).start()
        

    
    def hideAttackControls(self):
        taskMgr.remove(self._attackIvalName)
        if hasattr(self, '_attackKeys') and self._attackKeys:
            self._attackKeys.hide()
        

    
    def hideMoveControls(self):
        taskMgr.remove(self._moveIvalName)
        if hasattr(self, '_moveKeys') and self._moveKeys:
            self._moveKeys.hide()
        

    
    def hideControls(self):
        self.hideMoveControls()
        self.hideAttackControls()
Example #38
0
def grabPie(pieCount):
    return OnscreenText(text = "Pies Scavenged: " + str(pieCount), style = 3, pos = (-1.3, .90), fg=(1,0.3,0.3,1),
        align = TextNode.ALeft, scale = .1)
 def connectFailure(self, statusCode, statusString):
     self.waitingText.destroy()
     self.failureText = OnscreenText(
         'Failed to connect to %s: %s.\nPress ESC to quit.' % (self.url, statusString),
         scale = 0.15, fg = (1, 0, 0, 1), shadow = (0, 0, 0, 1))
Example #40
0
def displayGameOver():
    return OnscreenText(text = "Game Over!", style = 3, pos = (0, .95-.05*14), fg=(1,0.3,0.3,1),
        align = TextNode.ACenter, scale = .10)
Example #41
0
    def __init__(self, camera, vehicle, control):
        self.vehicle = vehicle
        self.control = control

        self.camera = camera
        self.camera.node().get_lens().set_near(0.1)
        self.camera_gimbal = NodePath("camera gimbal")
        self.camera.reparent_to(self.camera_gimbal)
        self.set_camera_mode(CameraModes.FOLLOW)
        self.accept(GE_CAMERA_MODE, self.switch_camera_mode)

        self.speed = OnscreenText(
            text = '',
            pos = (1.3, 0.8),
            scale = 0.15,
            fg = (1.0, 1.0, 0.5, 1.0),
            shadow = (0.2, 0.2, 0.2, 1.0),
            align = TextNode.ARight,
        )
        self.driving_mode = OnscreenText(
            text = '',
            pos = (1.3, 0.7),
            scale = 0.1,
            fg = (0.0, 0.0, 0.0, 1.0),
            shadow = (0.2, 0.2, 0.2, 1.0),
            align = TextNode.ARight,
        )
        self.repulsor_power_needed = DirectWaitBar(
            text = "",
            value = 0,
            pos = (0.9, 0, 0.65),
            scale = 0.4,
        )
        self.gyro_power_needed = DirectWaitBar(
            text = "",
            value = 0,
            pos = (0.9, 0, 0.58),
            scale = 0.4,
        )
        self.thruster_heat = DirectWaitBar(
            text = "",
            value = 0,
            pos = (0.9, 0, 0.51),
            scale = 0.4,
        )

        self.flight_height = OnscreenText(
            text = '',
            pos = (1.3, -0.65),
            scale = 0.1,
            fg = (0.0, 0.0, 0.0, 1.0),
            shadow = (0.2, 0.2, 0.2, 1.0),
            align = TextNode.ARight,
        )
        self.target_flight_height = OnscreenText(
            text = '',
            pos = (1.3, -0.75),
            scale = 0.1,
            fg = (0.2, 0.8, 0.2, 1.0),
            shadow = (0.2, 0.2, 0.2, 1.0),
            align = TextNode.ARight,
        )
        self.climb_rate = OnscreenText(
            text = '',
            pos = (1.3, -0.85),
            scale = 0.1,
            fg = (0.0, 0.0, 0.0, 1.0),
            shadow = (0.2, 0.2, 0.2, 1.0),
            align = TextNode.ARight,
        )

        # Height meters and repulsor self-control
        self.heights = base.render2d.attach_new_node("height meters")
        self.heights.set_pos(-0.8, 0.0, -0.6)

        self.height_null = base.loader.load_model('models/box')
        self.height_null.set_scale(0.3, 0.3, 0.01)
        self.height_null.set_pos(-0.15, -0.15, -0.005)
        self.height_null.reparent_to(self.heights)

        self.height_over_target = base.loader.load_model('models/smiley')
        self.height_over_target.set_scale(0.01, 0.1, 0.1)
        self.height_over_target.set_pos(-0.1, 0, 0)
        self.height_over_target.reparent_to(self.heights)
        self.height_over_target.hide()

        self.height_over_target_projected = base.loader.load_model('models/smiley')
        self.height_over_target_projected.set_scale(0.01, 0.1, 0.1)
        self.height_over_target_projected.set_pos(-0.05, 0, 0)
        self.height_over_target_projected.reparent_to(self.heights)
        self.height_over_target_projected.hide()

        self.repulsor_hud = self.camera.attach_new_node('repulsor HUD')
        self.repulsor_hud.set_pos(-2, 10, 2)
        self.repulsor_hud.set_p(90)
        self.repulsor_models = []
Example #42
0
    def __init__(self):
        ShowBase.__init__(self)

        self.viewDistanceChunks = 4
        self.viewDistance = (self.viewDistanceChunks + 0.5) * CHUNK_SIDE

        self.visibleChunksXY = set()
        self.visibleChunks = {}
        self.chunksForLoader = {}

        # Disable the camera trackball controls.
        self.disableMouse()

        self.camAngleA = 0
        self.camAngleB = 0

        self.currChunkXY = (None, None)
        self.currChunk = None

        self.accept('arrow_left', self.evtArrowLeft)
        self.accept('arrow_left-repeat', self.evtArrowLeft)
        self.accept('arrow_right', self.evtArrowRight)
        self.accept('arrow_right-repeat', self.evtArrowRight)
        self.accept('arrow_up', self.evtArrowUp)
        self.accept('arrow_up-repeat', self.evtArrowUp)
        self.accept('arrow_down', self.evtArrowDown)
        self.accept('arrow_down-repeat', self.evtArrowDown)
        self.accept('w', self.evtForward)
        self.accept('w-repeat', self.evtForward)
        self.accept('s', self.evtBack)
        self.accept('s-repeat', self.evtBack)
        self.accept('i', self.render.analyze)

        self.texture = self.loader.loadTexture("dirt.png")
        self.texture.setMagfilter(Texture.FTNearest)
        self.texture.setMinfilter(Texture.FTLinearMipmapLinear)

        self.xyzInfo = OnscreenText(text="text",
                                    align=TextNode.ALeft,
                                    parent=pixel2d,
                                    fg=(1, 1, 1, 1),
                                    bg=(0, 0, 0, 0.7))
        self.xyzInfo.setScale(18, 20)
        self.xyzInfo.setPos(5, -20)

        #self.messenger.toggleVerbose()

        self.setFrameRateMeter(True)
        #self.chunkLoaderThread = threading.Thread(target=chunkLoader)
        #self.chunkLoaderThread.start()

        taskMgr.doMethodLater(0.01, self.refreshChunksTask,
                              'refreshChunksTask')
        taskMgr.setupTaskChain('chunkLoaderTaskChain', numThreads=1)

        bgColor = (0.3, 0.5, 1)
        self.setBackgroundColor(*bgColor)
        self.initFog(bgColor)
        self.camLens.setFar(self.viewDistance)

        self.setCamPos(CHUNK_SIDE / 2, CHUNK_SIDE / 2, 32)

        dlight = DirectionalLight('dlight')
        dlight.setColor(VBase4(0.8, 0.8, 0.5, 1))
        dlnp = render.attachNewNode(dlight)
        dlnp.setHpr(-30, -60, 0)
        render.setLight(dlnp)

        alight = AmbientLight('alight')
        alight.setColor(VBase4(0.4, 0.4, 0.4, 1))
        alnp = render.attachNewNode(alight)
        render.setLight(alnp)
Example #43
0
class RacingGame(ShowBase):
    # method completely taken from RoamingRalph demo:
    def addInstructions(self, pos, msg):
        return OnscreenText(text=msg,
                            style=1,
                            fg=(1, 1, 1, 1),
                            scale=.05,
                            shadow=(0, 0, 0, 1),
                            parent=base.a2dTopLeft,
                            pos=(0.08, -pos - 0.04),
                            align=TextNode.ALeft)

    def addWin(self, time):
        msg = (
            "You finished the course in: \n%d seconds \n press z to race again"
            % (time))
        self.winText = OnscreenText(text=msg,
                                    style=1,
                                    fg=(1, 1, 1, 1),
                                    scale=.2,
                                    shadow=(0, 0, 0, 1),
                                    parent=base.a2dTopLeft,
                                    pos=(0.10, -0.5),
                                    align=TextNode.ALeft)

    def destroyWin(self):
        if (self.winText != None):
            self.winText.destroy()

    def setUpFlyingInstructions(self):
        self.inst[0] = self.addInstructions(.06, "Arrow Keys to move around")
        self.inst[1] = self.addInstructions(.12, "w and s to control pitch")
        self.inst[2] = self.addInstructions(.18, "a and d to control yaw")
        self.inst[3] = self.addInstructions(.24, "h to switch to driving mode")
        self.inst[4] = self.addInstructions(.3, "mouse click to add object")
        self.inst[5] = self.addInstructions(.36, "m to go to main")

    def startMovement(self):
        taskMgr.add(self.move, "moveTask")

    def destroyInstructions(self):
        # got way to destroy text from:
        # https://www.panda3d.org/manual/index.php/OnscreenText
        for element in self.inst:
            element.destroy()

    def startCreating(self):
        self.switchToCreateMode()
        self.destroyStartScreenButtons()
        self.startMovement()

    def startDriving(self):
        self.switchToDrivingMode()
        self.destroyStartScreenButtons()
        self.startMovement()

    def startTutorial(self):
        self.mode = self.modeTutorial
        self.setUpTutorial()
        self.destroyStartScreenButtons()
        self.startMovement()

    def setUpStartScreenButtons(self):
        self.creatingButton = DirectButton(text="Start Creating",
                                           scale=.1,
                                           command=self.startCreating,
                                           pos=(0, 0, .2))
        self.drivingButton = DirectButton(text="Start Driving",
                                          scale=.1,
                                          command=self.startDriving,
                                          pos=(0, 0, 0))
        self.tutorialButton = DirectButton(text="Start Tutorial",
                                           scale=.1,
                                           command=self.startTutorial,
                                           pos=(0, 0, -.2))

    def destroyStartScreenButtons(self):
        self.creatingButton.destroy()
        self.drivingButton.destroy()
        self.tutorialButton.destroy()

    def setAddObjectTree(self):
        self.createdObject = self.createTree

    def setAddObjectRock(self):
        self.createdObject = self.createRock

    def setAddObjectPole(self):
        self.createdObject = self.createPole

    def setUpCreateButtons(self):
        # todo: add toggle for instructions so that they do not always interfere with button
        self.treeButton = DirectButton(text="Add Block",
                                       scale=.1,
                                       command=self.setAddObjectTree,
                                       pos=(0, 0, .85))
        #self.rockButton = DirectButton(text="Add Rock", scale=.1, command=self.setAddObjectRock, pos=(-.5,.9,.85))
        self.poleButton = DirectButton(text="Add Pole",
                                       scale=.1,
                                       command=self.setAddObjectPole,
                                       pos=(.5, 0, .85))

    def setUpCreateObjects(self):
        self.createdObject = 0
        self.createTree = 0
        self.createRock = 1
        self.createPole = 2

    def destroyCreateButtons(self):
        self.treeButton.destroy()
        #self.rockButton.destroy()
        self.poleButton.destroy()

    def setUpDrivingInstructions(self):
        self.inst[0] = self.addInstructions(
            .06, "Right arrow and left arrow to turn")
        self.inst[1] = self.addInstructions(
            .12, "Forward and Backward arrow to go forward and backward")
        self.inst[2] = self.addInstructions(.18,
                                            "h to switch to add object mode")
        self.inst[3] = self.addInstructions(.24,
                                            "z to switch to start the race")
        self.inst[4] = self.addInstructions(.30, "m to go to main")

    def setUpWindow(self):
        # set up the egg files needed
        # since this method is made for python 2.7 but these objects are made for python 3.5, seems to be incompatible
        #m = Mountain("TestMountain", 60)
        #m.editFile()
        #p = Pole("TestPole", 0, 0, 0)
        #p.editFile()
        #c = Car("TestCar", 0,0,0)
        #c.editFile()
        #b = BeaconLight("BeaconLight",0,0,0)
        #b.editFile()
        # Set up the window, camera, etc
        ShowBase.__init__(self)

        # Set the background color to black
        self.win.setClearColor((0, 1, 1, 1))
        # this is the model I created using mountainMaker.py
        self.environ = loader.loadModel("TestMountain1")
        self.environ.reparentTo(render)

        self.car = loader.loadModel("TestCar")
        # found how to solve the problem of only being able to see objects from
        # certain angles with this:
        # http://www.panda3d.org/manual/index.php/Backface_Culling_and_Frontface_Culling
        self.car.setTwoSided(True)
        self.car.reparentTo(render)

        # Create some lighting
        # this is a part that is completely unchanged from demo
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        # to get light from other direction to light up things on both sides
        directionalLight2 = DirectionalLight("directionalLight")
        directionalLight2.setDirection((5, 5, 5))
        directionalLight2.setColor((1, 1, 1, 1))
        directionalLight2.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
        render.setLight(render.attachNewNode(directionalLight2))

    def setUpCar(self):
        # for adjusting so that the position is the center of the car
        self.adjustedXForCenter = 10 / 2
        self.adjustedYForCenter = 20 / 2

        # for some reason can't change this or the collisions do not work
        self.carPositionX = 20
        self.carPositionY = 20
        self.carPositionZ = 100
        # note for rotating camera: from this website:
        # https://www.panda3d.org/manual/index.php/Common_State_Changes
        # setHpr(Yaw, Pitch, Roll)

        # setting up initial conditions for which way camera is rotated
        self.carYaw = 0
        self.carPitch = 0
        (actualXPos, actualYPos) = RacingGame.findActualCenter(
            self, self.carPositionX, self.carPositionY,
            self.adjustedXForCenter, self.adjustedYForCenter, self.carYaw)
        self.car.setX(actualXPos)
        self.car.setY(actualYPos)
        self.car.setZ(self.carPositionZ)
        self.car.setHpr(self.carYaw, self.carPitch, 0)

    def setUpCamera(self):
        # for flying mode
        self.cameraPositionX = 500
        self.cameraPositionY = 500
        self.cameraPositionZ = 40
        # note for rotating camera: from this website:
        # https://www.panda3d.org/manual/index.php/Common_State_Changes
        # setHpr(Yaw, Pitch, Roll)

        # setting up initial conditions for which way camera is rotated
        self.cameraYaw = 0
        self.cameraPitch = 0

        # Set up the camera
        self.disableMouse()

        # should probably clean up these magic numbers
        self.camera.setPos(self.cameraPositionX, self.cameraPositionY,
                           self.cameraPositionZ)

    def setUpKeyMap(self):
        # This is used to store which keys are currently pressed.
        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "cam-left": 0,
            "cam-right": 0,
            "backward": 0,
            "cam-up": 0,
            "cam-down": 0,
            "add-car": 0,
            "switch-mode": 0,
            "mouse-click": 0,
            "race-start": 0,
            "to-main": 0
        }
        # Accept the control keys for movement and rotation

        #setting up keys for movement
        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["forward", True])
        self.accept("arrow_down", self.setKey, ["backward", True])
        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["forward", False])
        self.accept("arrow_down-up", self.setKey, ["backward", False])

        self.accept("m", self.setKey, ["to-main", True])
        self.accept("m-up", self.setKey, ["to-main", False])

        # starting race
        self.accept("z", self.setKey, ["race-start", True])
        self.accept("z-up", self.setKey, ["race-start", False])

        # adding car
        self.accept("mouse1", self.setKey, ["mouse-click", True])
        self.accept("mouse1-up", self.setKey, ["mouse-click", False])

        # setting up orientation of the camera
        self.accept("a", self.setKey, ["cam-left", True])
        self.accept("s", self.setKey, ["cam-down", True])
        self.accept("a-up", self.setKey, ["cam-left", False])
        self.accept("s-up", self.setKey, ["cam-down", False])
        self.accept("d", self.setKey, ["cam-right", True])
        self.accept("d-up", self.setKey, ["cam-right", False])
        self.accept("w", self.setKey, ["cam-up", True])
        self.accept("w-up", self.setKey, ["cam-up", False])

        # to switch between tasks
        self.accept("h", self.setKey, ["switch-mode", True])
        self.accept("h-up", self.setKey, ["switch-mode", False])

    def __init__(self):
        self.setUpWindow()
        self.setUpKeyMap()
        #instructions
        self.inst = [""] * 6
        self.setUpFlyingInstructions()

        self.mouseClicked = False

        self.winText = None

        # important for setting the size relative to everything else
        # found it here : https://www.panda3d.org/manual/index.php/Common_State_Changes
        # set the mode that the player is currently in
        self.mode = 0
        self.modeFly = 2
        self.modeRace = 1
        self.modeStart = 0
        self.modeTutorial = 3
        # to ensure that when pressing h it only switches once each press
        self.hasSwitched = False
        self.raceBegan = False
        self.raceTime = 0
        self.poleOn = 0

        self.setUpCamera()
        self.setUpCar()
        self.setUpCarCollider()
        self.setUpMouseCollider()
        self.setUpStartScreenButtons()
        # make the rocks and other stuff that will show up
        self.setUpCreateObjects()
        self.objects = []
        self.poles = []
        self.beaconLight = None
        self.beaconLightZ = 50
        self.target = None

        taskMgr.add(self.move, "moveTask")

    def findCollisionTube(self):
        # using bassically same formula as Y position
        # decided not to use this because possible problems with ground getting
        # hit instead of things in front
        degToRad = math.pi / 180
        xAddition = (
            self.adjustedXForCenter * math.cos(self.carYaw * degToRad) +
            self.adjustedYForCenter * math.sin(self.carYaw * degToRad)) / 2
        yAddition = (
            self.adjustedXForCenter * math.cos(self.carYaw * degToRad) +
            self.adjustedYForCenter * math.sin(self.carYaw * degToRad))

    def findCarFrontDir(self):
        degToRad = math.pi / 180
        xDir = -1 * math.sin(degToRad * self.carYaw) * math.cos(
            degToRad * self.carPitch)
        yDir = 1 * math.cos(degToRad * self.carYaw) * math.cos(
            degToRad * self.carPitch)
        zDir = 1 * math.sin(degToRad * self.carPitch)
        return (xDir, yDir, zDir)

    def setUpCarCollider(self):
        self.carCollideTrav = CollisionTraverser()
        base.cTrav = self.carCollideTrav
        self.handler = CollisionHandlerQueue()
        self.carRay = CollisionRay(self.carPositionX, self.carPositionY,
                                   self.carPositionZ, 0, 0, -1)
        self.carForwardHandler = CollisionHandlerQueue()
        # so that it doesn't collide with things forward and backward.
        degToRad = math.pi / 180
        (xDir, yDir, zDir) = self.findCarFrontDir()
        self.carRayForward = CollisionRay(self.carPositionX, self.carPositionY,
                                          self.carPositionZ, xDir, yDir, zDir)
        self.carForwardCollision = CollisionNode("forwardCollision")
        self.carForwardCollision.addSolid(self.carRayForward)
        self.carForwardCollision.setIntoCollideMask(CollideMask.allOff())
        self.carForwardCollisionNode = self.car.attachNewNode(
            self.carForwardCollision)
        (centerX,
         centerY) = self.findActualCenter(0, 0, self.adjustedXForCenter,
                                          self.adjustedYForCenter, self.carYaw)
        self.carRayForward.setOrigin(5, 10, 5)
        self.carCollision = CollisionNode("groundCollision")
        self.carCollision.addSolid(self.carRay)
        self.carCollision.setIntoCollideMask(CollideMask.allOff())
        self.carCollisionNode = self.car.attachNewNode(self.carCollision)
        self.carCollideTrav.addCollider(self.carCollisionNode, self.handler)
        self.carCollideTrav.addCollider(self.carForwardCollisionNode,
                                        self.carForwardHandler)
        self.carForwardCollisionNode.show()

    def setUpMouseCollider(self):
        # clicking on objects stuff came from here:
        # https://www.panda3d.org/manual/index.php/Collision_Traversers
        # https://www.panda3d.org/manual/index.php/Collision_Handlers
        # will not use the traverser set up by car because slow
        # instead we will render each time clicked
        self.mouseCollideTrav = CollisionTraverser("mouseTraverse")
        self.mousehandler = CollisionHandlerQueue()
        # edit this so that from Object is the camera
        # self.mouseCollideTrav.addCollider(fromObject, queue)
        # self.mouseCollideTrav.traverse(render)
        # this next part came from:
        # https://www.panda3d.org/manual/index.php/Clicking_on_3D_Objects
        pickerNode = CollisionNode("mouseRay")
        pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
        pickerNode.setIntoCollideMask(CollideMask.allOff())
        self.pickerRay = CollisionRay()
        pickerNode.addSolid(self.pickerRay)
        pickerNp = camera.attachNewNode(pickerNode)
        self.mouseCollideTrav.addCollider(pickerNp, self.mousehandler)

    # Records the state of the arrow keys
    def setKey(self, key, value):
        self.keyMap[key] = value

    def switchToCreateMode(self):
        self.mode = self.modeFly
        self.destroyInstructions()
        self.setUpFlyingInstructions()
        self.hasSwitched = True
        self.setUpCreateButtons()

    def switchToDrivingMode(self):
        self.mode = self.modeRace
        self.destroyInstructions()
        self.setUpDrivingInstructions()
        self.hasSwitched = True

    def switchToMainMode(self):
        self.mode = 0
        self.setUpStartScreenButtons()

    def setTutorialText(self, str):
        # reusing inst so that it is easy to erase
        self.inst[0] = self.addInstructions(.06, str)

    def move(self, task):
        if (self.keyMap["to-main"]):
            self.switchToMainMode()
        elif (self.mode == self.modeFly):
            if self.keyMap["switch-mode"] and not self.hasSwitched:
                self.switchToDrivingMode()
                self.destroyCreateButtons()
            elif not self.keyMap["switch-mode"]:
                # to ensure switch mode only happens once per button pressed
                self.hasSwitched = False
            self.findNewCameraPosition()
            self.checkAndAddNewObject()
        elif (self.mode == self.modeRace):
            if self.keyMap["switch-mode"] and not self.hasSwitched:
                self.destroyWin()
                self.switchToCreateMode()
            elif not self.keyMap["switch-mode"]:
                # this ensures that when key is pressed only switch states once
                self.hasSwitched = False
            self.findCarNewXandY()
            # when implementing the use of the mouse look here:
            # https://www.panda3d.org/manual/index.php/Clicking_on_3D_Objects
            self.setCarZ()
            self.setCameraPositionBehindCar()
            if (self.keyMap["race-start"] and not self.raceBegan
                    and len(self.poles) >= 2):
                self.destroyWin()
                # try so that if there are not enough poles then the game
                # doesn't crash
                try:
                    self.raceBegan = True
                    self.raceTime = time.time()
                    # puts in the car where the first two poles are
                    # first col of poles is model, second x coord, thrid y coord, fourth z coord
                    self.carPositionX = (self.poles[0][1] +
                                         self.poles[1][1]) / 2
                    self.carPositionY = (self.poles[0][2] +
                                         self.poles[1][2]) / 2
                    # meant to show where car should go
                    # got info on how to do point lights from here:
                    # https://www.panda3d.org/manual/index.php/Lighting
                    self.beaconLight = PointLight("beaconLight")
                    self.beaconLight.setColor((1, 1, 1, 1))
                    self.beaconLight.setAttenuation((0, 0, 1))
                    self.beaconLightHolder = render.attachNewNode(
                        self.beaconLight)
                    (beaconLightX, beaconLightY) = self.getNextGateCenter()
                    # target for driver
                    if (self.target == None):
                        self.target = loader.loadModel("BeaconLight.egg")
                    self.target.setTwoSided(True)
                    self.target.reparentTo(render)
                    if (beaconLightX != None):
                        self.beaconLightHolder.setPos(beaconLightX,
                                                      beaconLightY,
                                                      self.beaconLightZ)
                        render.setLight(self.beaconLightHolder)
                        self.target.setPos(beaconLightX, beaconLightY,
                                           self.beaconLightZ)
                except:
                    # not enough poles
                    pass
            if (self.raceBegan):
                # minus 1 just in case non even
                if (self.poleOn + 1 >= len(self.poles)):
                    self.raceBegan = False
                    self.addWin(time.time() - self.raceTime)
                    # since race ended
                    try:
                        self.target.destroy()
                    except:
                        pass
                    self.beaconLight = None  # use object + lights
                    self.beaconLightHolder = None
                    self.poleOn = 0
                else:
                    acceptableError = 100
                    # formula I created: (p2y-p1y)/(p2x-p1x)*(p2x-pAx)+p2y =
                    # expected pAy
                    # so if the actual car positionY is within acceptableError of
                    # pAy then the car is between the two poles
                    # if in between poles
                    middleX = (self.poles[self.poleOn][1] +
                               self.poles[self.poleOn + 1][1]) / 2
                    middleY = (self.poles[self.poleOn][2] +
                               self.poles[self.poleOn + 1][2]) / 2
                    expectedCarY = (
                        (self.poles[self.poleOn][2] -
                         self.poles[self.poleOn + 1][2]) /
                        (self.poles[self.poleOn][1] -
                         self.poles[self.poleOn + 1][1]) *
                        (self.poles[self.poleOn][1] - self.carPositionX) +
                        self.poles[self.poleOn][2])
                    # do not really care about car being inbetween pole in z axis
                    # because 2 demensional
                    if (expectedCarY + acceptableError > self.carPositionY
                            and expectedCarY - acceptableError <
                            self.carPositionY):
                        self.poleOn += 2
                        # only when last pole found is it necesary to add light
                        # to guide to next place elsewhere
                        (beaconLightX, beaconLightY) = self.getNextGateCenter()
                        if (beaconLightX != None):
                            self.beaconLightHolder.setPos(
                                beaconLightX, beaconLightY, self.beaconLightZ)
                            self.target.setPos(beaconLightX, beaconLightY,
                                               self.beaconLightZ)
        elif (self.mode == self.modeTutorial):
            self.destroyWin()
            # do the tutorial part for the creating
            timeBeforeNext = 2
            if (self.tutorialPause == True):
                if (time.time() - self.tutorialActionTime > timeBeforeNext):
                    self.tutorialPause = False
            else:
                if (self.tutorialStep == -1):
                    self.destroyInstructions()
                    self.setTutorialText(
                        "use w and s to move camera up and down")
                    self.tutorialStep += 1
                # do this until the user has completed all of the task
                self.checkTutorialStep(
                    0, (self.keyMap["cam-up"] or self.keyMap["cam-down"]),
                    "use a and d to rotate camera right and left")
                self.checkTutorialStep(
                    1, (self.keyMap["cam-left"] or self.keyMap["cam-right"]),
                    "use up-arrow and down-arrow to turn camera forward and backward"
                )
                self.checkTutorialStep(
                    2, (self.keyMap["forward"] or self.keyMap["backward"]),
                    "use left-arrow and right-arrow to slide camera left and right"
                )
                self.checkTutorialStep(
                    3, (self.keyMap["left"] or self.keyMap["right"]),
                    "use mouse click to place objects on terrain")
                self.checkTutorialStep(
                    4, (self.keyMap["mouse-click"]),
                    "use up-arrow and down-arrow to move car forward and backward",
                    (self.switchToDrivingMode, self.destroyInstructions))
                # need to ensure that the mode stays as tutorial
                self.mode = self.modeTutorial
                # then tutorial part for the driving
                self.checkTutorialStep(
                    5, (self.keyMap["forward"] or self.keyMap["backward"]),
                    "use right-arrow and left-arrow to rotate car left and right"
                )
                self.checkTutorialStep(
                    6, (self.keyMap["left"] or self.keyMap["right"]),
                    "Use poles to make the race course\n use z to start race")
                self.checkTutorialStep(
                    7, True,
                    "Follow yellow block through the gates till you win")
                self.checkTutorialStep(
                    8, True,
                    "Watch for high Terrain and blocks because you can not get through those"
                )
                self.checkTutorialStep(9, True, "")
                if (self.tutorialStep > 9):
                    # switch to main
                    self.switchToMainMode()
            # for movement
            if (self.tutorialStep <= 4):
                self.findNewCameraPosition()
                self.checkAndAddNewObject()
            if (self.tutorialStep > 4 and self.tutorialStep <= 9):
                self.findCarNewXandY()
                self.setCarZ()
                self.setCameraPositionBehindCar()
        return task.cont

    def getNextGateCenter(self):
        if (len(self.poles) > self.poleOn + 1):
            positionX = (self.poles[self.poleOn][1] +
                         self.poles[self.poleOn + 1][1]) / 2
            positionY = (self.poles[self.poleOn][2] +
                         self.poles[self.poleOn + 1][2]) / 2
            return (positionX, positionY)
        else:
            return (None, None)

    def checkTutorialStep(self, step, keysNeeded, nextText, functions=None):
        if (self.tutorialStep == step and self.tutorialNextStep == True):
            if (functions != None):
                for func in functions:
                    func()
            self.destroyInstructions()
            self.setTutorialText(nextText)
            self.tutorialStep += 1
            self.tutorialNextStep = False
        elif (self.tutorialStep == step and keysNeeded):
            self.tutorialNextStep = True
            self.tutorialActionTime = time.time()
            self.tutorialPause = True

    def setUpTutorial(self):
        self.tutorialStep = -1
        self.tutorialPause = False
        # this records when last tutorial action taken
        self.tutorialActionTime = 0
        self.tutorialNextStep = False

    def checkAndAddNewObject(self):
        # clicking on 3D objects comes from here:
        # https://www.panda3d.org/manual/index.php/Clicking_on_3D_Objects
        # checks if it needs to add any objects:
        if (self.keyMap["mouse-click"] and self.mouseClicked == False):
            self.mouseClicked = True
            # found way to speed this up by only doing collision check
            # when mouse clicked by not using cTrav like in this method
            # the way I did it I found here:
            # https://www.panda3d.org/manual/index.php/Clicking_on_3D_Objects
            # self.mouseCollideTrav.traverse(render)
            if (base.mouseWatcherNode.hasMouse()):
                mousePos = base.mouseWatcherNode.getMouse()
                self.pickerRay.setFromLens(base.camNode, mousePos.getX(),
                                           mousePos.getY())
                # do not put this before previous line, will get the coordinates
                # of last mouse click and where pickerRay was
                # ahhhhhhh!!!!!!!!!!!
                self.mouseCollideTrav.traverse(render)
                if (self.mousehandler.getNumEntries() > 0):
                    entries = list(self.mousehandler.getEntries())
                    # pathagorean formula for sorting
                    entries.sort(
                        key=lambda x: ((x.getSurfacePoint(render).getX(
                        ) - self.cameraPositionX)**2 + (x.getSurfacePoint(
                            render).getY() - self.cameraPositionY)**2)**.5)
                    newX = entries[0].getSurfacePoint(render).getX()
                    newY = entries[0].getSurfacePoint(render).getY()
                    newZ = entries[0].getSurfacePoint(render).getZ()
                    adjustedX = 10 / 2
                    adjustedY = 20 / 2
                    yaw = 0
                    # have to adjust this once there are different sized
                    # objects added
                    (actualXPos, actualYPos) = RacingGame.findActualCenter(
                        self, newX, newY, adjustedX, adjustedY, yaw)
                    if (self.createdObject == self.createPole):
                        self.poles.append([
                            loader.loadModel("TestPole.egg"), actualXPos,
                            actualYPos, newZ
                        ])
                        self.poles[len(self.poles) - 1][0].reparentTo(render)
                        self.poles[len(self.poles) - 1][0].setTwoSided(True)
                        self.poles[len(self.poles) - 1][0].setPos(
                            actualXPos, actualYPos, newZ)
                    else:
                        newCar = loader.loadModel("TestCar.egg")
                        newCar.reparentTo(render)
                        newCar.setPos(actualXPos, actualYPos, newZ)
                        # should take out because slow, but objects can not be
                        # seen without this because only seen from one direction
                        # even though normal vectors set up.
                        newCar.setTwoSided(True)
                        self.objects.append(newCar)
        elif (not self.keyMap["mouse-click"]):
            # elif because for some reason mouseClicked was becoming false
            # while click still pressed
            self.mouseClicked = False

    def findNewCameraPosition(self):
        # Get the time that elapsed since last frame.  We multiply this with
        # the desired speed in order to find out with which distance to move
        # in order to achieve that desired speed.
        dt = globalClock.getDt()
        # the angle is in degrees with 360 equal to full rotation
        angleAdjustment = 100
        if self.keyMap["cam-left"]:
            self.cameraYaw += angleAdjustment * dt
        if self.keyMap["cam-right"]:
            self.cameraYaw -= angleAdjustment * dt
        if self.keyMap["cam-up"]:
            self.cameraPitch += angleAdjustment * dt
        if self.keyMap["cam-down"]:
            self.cameraPitch -= angleAdjustment * dt

        positionAdjustment = 500
        # should switch rad and Deg in variable name
        radToDeg = math.pi / 180
        # the x and y component of left and right moves, do not need to
        # compensate in z axis because not doing any roll, so there should be
        # no zComponent
        xComponent = math.cos(self.cameraYaw * radToDeg)
        yComponent = math.sin(self.cameraYaw * radToDeg)

        if self.keyMap["left"]:
            self.cameraPositionX -= positionAdjustment * dt * xComponent
            self.cameraPositionY -= positionAdjustment * dt * yComponent
        if self.keyMap["right"]:
            self.cameraPositionX += positionAdjustment * dt * xComponent
            self.cameraPositionY += positionAdjustment * dt * yComponent

        # for going forward, the orientation is rotated 90 degrees so need to
        # change components
        xComponent = math.cos(self.cameraYaw * radToDeg + math.pi /
                              2) * math.cos(self.cameraPitch * radToDeg)
        yComponent = math.sin(self.cameraYaw * radToDeg + math.pi /
                              2) * math.cos(self.cameraPitch * radToDeg)
        zComponent = math.sin(self.cameraPitch * radToDeg)

        if self.keyMap["forward"]:
            self.cameraPositionX += positionAdjustment * dt * xComponent
            self.cameraPositionY += positionAdjustment * dt * yComponent
            self.cameraPositionZ += positionAdjustment * dt * zComponent
        if self.keyMap["backward"]:
            self.cameraPositionX -= positionAdjustment * dt * xComponent
            self.cameraPositionY -= positionAdjustment * dt * yComponent
            self.cameraPositionZ -= positionAdjustment * dt * zComponent

        self.camera.setX(self.cameraPositionX)
        self.camera.setY(self.cameraPositionY)
        self.camera.setZ(self.cameraPositionZ)
        self.camera.setHpr(self.cameraYaw, self.cameraPitch, 0)

    def carForwardImpact(self):
        # update position so that it is pointing right directions
        #(dirX, dirY, dirZ) = self.findCarFrontDir()
        #self.carRayForward.setDirection(dirX, dirY, dirZ)
        degToRad = math.pi / 180
        # + math.pi since it is taking corner and going to center rather
        # than opposite that function actually does
        #(centerX,centerY) = self.findActualCenter(0,0,self.adjustedXForCenter,
        #                                   self.adjustedYForCenter, self.carYaw
        #                                   +math.pi)
        posAboveGround = 5
        # need to update with new coordinates
        self.carCollideTrav.traverse(render)
        collisions = list(self.carForwardHandler.getEntries())
        # closest collision using pythagorean formula
        collisions.sort(
            key=lambda x:
            (x.getSurfacePoint(render).getX() - self.carPositionX)**2 +
            (x.getSurfacePoint(render).getY() - self.carPositionY)**2)
        if (len(collisions) > 0):
            (actualX, actualY) = RacingGame.findActualCenter(
                self, self.carPositionX, self.carPositionY,
                self.adjustedXForCenter, self.adjustedYForCenter, self.carYaw)
            distance = (
                (collisions[0].getSurfacePoint(render).getX() - actualX)**2 +
                (collisions[0].getSurfacePoint(render).getY() - actualY)**
                2)**.5
            error = .9  # so that the collisionray does not detect car itself
            return distance / 2 <= self.adjustedYForCenter * .9
        else:
            return False

    def findCarNewXandY(self):
        # Get the time that elapsed since last frame.  We multiply this with
        # the desired speed in order to find out with which distance to move
        # in order to achieve that desired speed.
        deltaTime = globalClock.getDt()
        degreeAdjustment = 60
        positionAdjustment = 100
        # should switch rad and Deg in variable name
        radToDeg = math.pi / 180
        # the x and y component of left and right moves, do not need to
        # compensate in z axis because not doing any roll, so there should be
        # no zComponent
        xComponent = math.sin(self.carYaw * radToDeg)
        yComponent = math.cos(self.carYaw * radToDeg)
        if self.keyMap["left"]:
            self.carYaw += degreeAdjustment * deltaTime
        if self.keyMap["right"]:
            self.carYaw -= degreeAdjustment * deltaTime
        if (self.keyMap["forward"] and not self.carForwardImpact()):
            self.carPositionX -= positionAdjustment * deltaTime * xComponent
            self.carPositionY += positionAdjustment * deltaTime * yComponent
        if self.keyMap["backward"]:
            self.carPositionX += positionAdjustment * deltaTime * xComponent
            self.carPositionY -= positionAdjustment * deltaTime * yComponent
        # need to consider both the x and y component of offset for both
        # because x slowly changes to y as it turns
        (actualXPos, actualYPos) = RacingGame.findActualCenter(
            self, self.carPositionX, self.carPositionY,
            self.adjustedXForCenter, self.adjustedYForCenter, self.carYaw)
        self.car.setX(actualXPos)
        self.car.setY(actualYPos)
        self.car.setZ(self.carPositionZ)
        self.car.setHpr(self.carYaw, self.carPitch, 0)

    def setCarZ(self):
        # almost directly taken from ralph example
        entries = list(self.handler.getEntries())
        entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())
        # worry about which thing it collides with later
        if (len(entries) > 0):
            # and entries[0].getIntoNode().getName() == "mountainCollide":
            self.carPositionZ = (entries[0].getSurfacePoint(render).getZ())
        else:
            # because at 25 everything should be below car and do not want
            # to continually go up or else it may go up forever.
            self.carPositionZ = 25
        self.setCameraPositionBehindCar()

    def setCameraPositionBehindCar(self):
        # Modify view of camera so that it is behind car
        # should be named degToRad
        radToDeg = math.pi / 180
        distanceBehind = 200
        distanceAbove = 60
        self.camera.setHpr(self.carYaw, -.5, 0)
        (actualXPos, actualYPos) = self.findActualCenter(
            self.carPositionX, self.carPositionY, self.adjustedXForCenter,
            self.adjustedXForCenter, self.carYaw)
        camX = actualXPos + distanceBehind * math.sin(radToDeg * self.carYaw)
        camY = actualYPos - distanceBehind * math.cos(radToDeg * self.carYaw)
        camZ = self.carPositionZ + distanceAbove
        self.camera.setPos(camX, camY, camZ)

    def findActualCenter(self, positionX, positionY, adjustedX, adjustedY,
                         yaw):
        # will need to fix this later, it seems to be adjusting wrong
        # so that it is puting box away from click instead of on it
        # update, I think this is fixed?!?
        degToRad = math.pi / 180
        actualXPos = (positionX - adjustedX * math.cos(degToRad * yaw) +
                      adjustedY * math.sin(degToRad * yaw))
        actualYPos = (positionY - adjustedY * math.cos(degToRad * yaw) -
                      adjustedX * math.sin(degToRad * yaw))
        return (actualXPos, actualYPos)
Example #44
0
 def enter(self):
     '''
     Here we initialize some fields and flags and setup our UI which constists only of labels.
     '''
     
     # call the super class implementation first, this is optional
     BaseNodeScript.enter(self)
     
     self.sounds = self.game.getSoundsFx()
             
     # hold the camera fixed
     self.game.getView().getCameraController().disable()
     
     # display instructions
     self.instructions = OnscreenText(text = 'Press 1 for blah-blah, 2 for cling and 3 for zipper',
                                      pos = (base.a2dLeft + 0.1, 0.9),
                                      align = TextNode.ALeft,
                                      scale = 0.07,
                                      fg = (1.0, 1.0, 1.0, 1.0),
                                      shadow = (0.0, 0.0, 0.0, 0.7)
                                      )
     
     # gets the status of sounds
     self.lastStatus = self.sounds.isEnabled()
     
     self.soundsStatusText = OnscreenText(text = 'Sounds status: %s' % self.lastStatus,
                                          pos = (base.a2dLeft + 0.1, 0.8),
                                          align = TextNode.ALeft,
                                          scale = 0.07,
                                          fg = (1.0, 1.0, 1.0, 1.0),
                                          shadow = (0.0, 0.0, 0.0, 0.7),
                                          mayChange = True
                                          )
     
     self.volumeText = OnscreenText(text = 'Volume: %.1f' % self.sounds.getVolume(),
                                          pos = (base.a2dLeft + 0.1, 0.7),
                                          align = TextNode.ALeft,
                                          scale = 0.07,
                                          fg = (1.0, 1.0, 1.0, 1.0),
                                          shadow = (0.0, 0.0, 0.0, 0.7),
                                          mayChange = True
                                          )
     
     self.rateText = OnscreenText(text = 'Rate: %.1f' % self.sounds.getPlayRate(),
                                          pos = (base.a2dLeft + 0.1, 0.6),
                                          align = TextNode.ALeft,
                                          scale = 0.07,
                                          fg = (1.0, 1.0, 1.0, 1.0),
                                          shadow = (0.0, 0.0, 0.0, 0.7),
                                          mayChange = True
                                          )
     
     self.balanceText = OnscreenText(text = 'Balance: %.1f' % self.sounds.getBalance(),
                                          pos = (base.a2dLeft + 0.1, 0.5),
                                          align = TextNode.ALeft,
                                          scale = 0.07,
                                          fg = (1.0, 1.0, 1.0, 1.0),
                                          shadow = (0.0, 0.0, 0.0, 0.7),
                                          mayChange = True
                                          )
     
     self.loopText = OnscreenText(text = 'Looping: %d' % self.looping,
                                          pos = (base.a2dLeft + 0.1, 0.4),
                                          align = TextNode.ALeft,
                                          scale = 0.07,
                                          fg = (1.0, 1.0, 1.0, 1.0),
                                          shadow = (0.0, 0.0, 0.0, 0.7),
                                          mayChange = True
                                          )
     
     self.eventText = OnscreenText(text = 'Finished event received',
                                          pos = (base.a2dLeft + 0.1, 0.3),
                                          align = TextNode.ALeft,
                                          scale = 0.07,
                                          fg = (1.0, 0.0, 0.0, 1.0),
                                          shadow = (0.0, 0.0, 0.0, 0.7),
                                          mayChange = True
                                          )
     self.eventText.hide()
     
     OnscreenText(text = 'Press P, R to pause/resume playing sounds',
                                          pos = (base.a2dLeft + 0.1, 0.2),
                                          align = TextNode.ALeft,
                                          scale = 0.05,
                                          fg = (1.0, 1.0, 1.0, 1.0),
                                          shadow = (0.0, 0.0, 0.0, 0.7),
                                          mayChange = True
                                          )
     OnscreenText(text = 'Press L, Shift-L to increase/decrease the loop count',
                                          pos = (base.a2dLeft + 0.1, 0.1),
                                          align = TextNode.ALeft,
                                          scale = 0.05,
                                          fg = (1.0, 1.0, 1.0, 1.0),
                                          shadow = (0.0, 0.0, 0.0, 0.7),
                                          mayChange = True
                                          )
     OnscreenText(text = 'Press +, - to increase/decrease playing rate',
                                          pos = (base.a2dLeft + 0.1, 0.0),
                                          align = TextNode.ALeft,
                                          scale = 0.05,
                                          fg = (1.0, 1.0, 1.0, 1.0),
                                          shadow = (0.0, 0.0, 0.0, 0.7),
                                          mayChange = True
                                          )
     OnscreenText(text = 'Press [, ] to decrease/increase sound volume',
                                          pos = (base.a2dLeft + 0.1, -0.1),
                                          align = TextNode.ALeft,
                                          scale = 0.05,
                                          fg = (1.0, 1.0, 1.0, 1.0),
                                          shadow = (0.0, 0.0, 0.0, 0.7),
                                          mayChange = True
                                          )
     OnscreenText(text = 'Press D, E to disable/enable sounds',
                                          pos = (base.a2dLeft + 0.1, -0.2),
                                          align = TextNode.ALeft,
                                          scale = 0.05,
                                          fg = (1.0, 1.0, 1.0, 1.0),
                                          shadow = (0.0, 0.0, 0.0, 0.7),
                                          mayChange = True
                                          )
     OnscreenText(text = 'Press B, Shift-B to increase/decrease balance',
                                          pos = (base.a2dLeft + 0.1, -0.3),
                                          align = TextNode.ALeft,
                                          scale = 0.05,
                                          fg = (1.0, 1.0, 1.0, 1.0),
                                          shadow = (0.0, 0.0, 0.0, 0.7),
                                          mayChange = True
                                          )
     
     
     
     # add our input mappings to the active mappings, the existing mappings were not deleted
     # but they can be partially overridden by this.
     self.game.getInput().addMappings('sounds')
class World(DirectObject):

    # Degrees per second of rotation
    rotateSpeed = 90

    # Units per second of motion
    moveSpeed = 8
    
    def __init__(self):
        DirectObject.__init__(self)

        # No avatar yet.
        self.av = None

        # No pellets either.
        self.pellets = []

        # The list of keys that we will be monitoring.
        self.moveKeyList = [
            'arrow_left', 'arrow_right', 'arrow_up', 'arrow_down'
            ]

        # Initially, all keys are up.  Construct a dictionary that
        # maps each of the above keys to False, and hang the event to
        # manage that state.
        self.moveKeys = {}
        for key in self.moveKeyList:
            self.moveKeys[key] = False
            self.accept(key, self.moveKeyStateChanged, extraArgs = [key, True])
            self.accept(key + '-up', self.moveKeyStateChanged, extraArgs = [key, False])


        tcpPort = base.config.GetInt('server-port', 4400)
        hostname = base.config.GetString('server-host', '127.0.0.1')
        self.url = URLSpec('http://%s:%s' % (hostname, tcpPort))

        self.cr = MyClientRepository()
        self.cr.connect([self.url],
                        successCallback = self.connectSuccess,
                        failureCallback = self.connectFailure)
        
        self.waitingText = OnscreenText(
            'Connecting to %s.\nPress ESC to cancel.' % (self.url),
            scale = 0.1, fg = (1, 1, 1, 1), shadow = (0, 0, 0, 1))

        self.accept('escape', self.escape)

        # Oobe mode is handy to have on all the time.  Why not?
        base.oobe()

    def moveKeyStateChanged(self, key, newState):
        """ A key event has been received.  Change the key state in
        the dictionary. """
        self.moveKeys[key] = newState

    def escape(self):
        """ The user pressed escape.  Exit the client. """
        sys.exit()
        
    def connectFailure(self, statusCode, statusString):
        self.waitingText.destroy()
        self.failureText = OnscreenText(
            'Failed to connect to %s: %s.\nPress ESC to quit.' % (self.url, statusString),
            scale = 0.15, fg = (1, 0, 0, 1), shadow = (0, 0, 0, 1))

    def connectSuccess(self):
        """ Successfully connected.  But we still can't really do
        anything until we've got the doID range. """
        self.waitingText.destroy()
        self.waitingText = OnscreenText(
            'Waiting for server.',
            scale = 0.1, fg = (1, 1, 1, 1), shadow = (0, 0, 0, 1))
        self.acceptOnce('createReady', self.createReady)

    def createReady(self):
        """ Now we're ready to go! """
        self.waitingText.destroy()
        
        # Manifest an avatar for ourselves.
        self.av = self.cr.createDistributedObject(
            className = 'DistributedAvatar', zoneId = 1)

        # The tab key changes your color.
        self.accept('tab', self.changeAvColor)

        # The space bar drops a new pellet.
        self.accept('space', self.dropPellet)

        # The 'c' key clears the pellets you've dropped.
        self.accept('c', self.clearPellets)

        # A number key (other than zero) changes your zone.
        for zoneId in range(1, 10):
            self.accept(str(zoneId), self.changeAvZone, extraArgs = [zoneId])

        # Pop up some help text.
        self.title = OnscreenText(
            parent = base.a2dBottomRight,
            text = 'DistributedNode client demo',
            fg = (1, 1, 1, 1),
            pos = (-0.03, 0.03), align = TextNode.ARight, scale = 0.1)

        self.help = OnscreenText(
            parent = base.a2dTopLeft,
            text = helpText,
            fg = (1, 1, 1, 1),
            pos=(0.03, -0.1), align = TextNode.ALeft, scale = 0.07)

        # Update the local avatar's position every frame.
        self.moveTask = taskMgr.add(self.moveAvatar, 'moveAvatar')

        # Send position updates only several times a second, instead
        # of every frame, or we will flood the network.
        self.lastBroadcastTransform = self.av.getTransform()
        self.updateTask = taskMgr.doMethodLater(0.2, self.updateAvatar, 'updateAvatar')

    def dropPellet(self):
        # Create a new DistributedPellet, and put it right where the
        # avatar is.
        pellet = DistributedPellet(self.cr)
        x, y, z = self.av.getPos()
        pellet.setInitialPos(x, y, z)
        self.cr.createDistributedObject(
            distObj = pellet, zoneId = self.av.zoneId)
        self.pellets.append(pellet)

    def clearPellets(self):
        # Remove all of the DistributedPellets we've created.
        for p in self.pellets:
            self.cr.sendDeleteMsg(p.doId)

    def changeAvColor(self):
        """ The user pressed the tab key.  Change the color of the
        local avatar to a new random color. """
        r = random.uniform(0, 1)
        g = random.uniform(0, 1)
        b = random.uniform(0, 1)
        self.av.b_setAvColor(r, g, b)

    def changeAvZone(self, zoneId):
        """ The user pressed one of the number keys to change zones.
        Move the avatar into the indicated zone. """

        # Move our avatar into the indicated zone
        self.cr.setObjectZone(self.av, zoneId)

    def moveAvatar(self, task):
        """ This task runs each frame to move the avatar according to
        the set of arrow keys that are being held. """

        dt = globalClock.getDt()
        
        if self.moveKeys['arrow_left']:
            self.av.setH(self.av, dt * self.rotateSpeed)
        elif self.moveKeys['arrow_right']:
            self.av.setH(self.av, -dt * self.rotateSpeed)

        if self.moveKeys['arrow_up']:
            self.av.setY(self.av, dt * self.moveSpeed)
        elif self.moveKeys['arrow_down']:
            self.av.setY(self.av, -dt * self.moveSpeed)

        return task.cont

    def updateAvatar(self, task):
        """ This task runs five times a second to broadcast the
        avatar's position to all of the other clients. """

        currentTransform = self.av.getTransform()
        if self.lastBroadcastTransform == currentTransform:
            # No change since last broadcast.
            return task.again

        self.lastBroadcastTransform = currentTransform
        x, y, z = self.av.getPos()
        h, p, r = self.av.getHpr()
        self.av.d_setPosHpr(x, y, z, h, p, r)

        return task.again
Example #46
0
    def init_trial(self):
        if self.reverse_now == True and self.reversal == 0:
            self.reversal = 1
            # need to reset all of these variables back to zero!!
            self.RunningTotal = 0
            self.TrialScoreList = []
            self.TrialScoreLastFiveSix = []
            self.LastFiveSixCount = 0
            self.trial_num_phase = 0
            self.reverse_now = False
            self.correctbox = fluffle(
                [i for i in range(3) if i != self.correctbox])[0]
            self.textures[-1] = self.tex5
        elif self.reverse_now == True and self.reversal == 1:
            self.GameOver = True

    #  if self.RunningTotal == self.revafter and self.reversal == 0:
    #     self.reversal = 1
    #    self.RunningTotal = 0
    #   self.trial_num_phase = 0
    #  self.correctbox = fluffle([i for i in range(3) if i != self.correctbox])[0]
    # self.textures[-1] = self.tex5
    #elif self.RunningTotal == self.revafter and self.reversal == 1:
    #   self.GameOver = True
        self.camspinning = 0
        self.camspin = False
        self.render.setLightOff(self.plnp)
        self.new_trial = False
        self.boxcam = False
        self.go = True
        self.goscale = 0
        self.ReadyText = OnscreenText(text="Ready...",
                                      pos=(-100, -0.5),
                                      scale=0.1 * self.goscale)
        self.GoText = OnscreenText(text="Go!",
                                   pos=(-100, -0.5),
                                   scale=0.1 * self.goscale)
        self.floater.setZ(2.0)
        self.spin = 0
        self.dragback = False
        self.dragtime = 0
        self.trial_no += 1
        self.trial_num_phase += 1
        self.trialscore = 0
        self.trial = [self.correctbox]
        self.pos = [0., 0.]
        self.kiki.setPos(0, 0, 1.)
        self.kiki.setH(0)
        self.presLoc = [0, 1, 2, 3]
        self.canMove = True
        self.digging = False
        self.atbox = -1
        self.addstar = -1
        self.clouddisp = 1
        self.presLoc = fluffle(self.presLoc)
        self.boxloca = [[-12., -12.], [12., -12.], [12., 12.], [-12., 12.]]
        if self.trial_no > 0:
            self.presents[self.dug].reparentTo(self.render)
        self.dug = -1
        for pres, loc in zip(self.presents, self.presLoc):
            pres.setPos(self.boxloca[loc][0], self.boxloca[loc][1], 2.1)
            pres.setTexture(self.texgrey)
            if self.boxloca[loc][1] == -12:
                pres.setH(180)
            else:
                pres.setH(0)
            pres.currentframe = 0
            pres.pose("go", 0)

        self.visits = [0, 0, 0, 0]
class Planet(ShowBase):
    #Macro-like function used to reduce the amount to code needed to create the
    #on screen instructions
    help=False
    text=None
    def genLabelText(self, text, i):
        """
        Generiert und erzeugt die Helpseite fuer unser Solarsystem
        :param text der angezeigte Text
        :param i: Position
        :return: die Bildschirmausgabe bzw. Helpseite
        """
        self.help = not self.help
        if(self.text != None):
            self.text.destroy()
        self.text= OnscreenText(text = text, pos = (-1.3, .95-.05*i), fg=(1,1,1,1),
                            align = TextNode.ALeft, scale = .05, mayChange = 1)
        return self.text

    def __init__(self, planeten):
        """
        Konstruktor hier wird alles gemanaget
        :param planeten: Planeten die erzeugt werden sollen
        """
        ShowBase.__init__(self)
        base.disableMouse()

        self.t = True

        # Pseudo-constants
        self.titleString = "Beste SolarSystem ever."
        self.renderRatio = 1.0e-6
        self.degPerSecond = 60.0
        self.minCameraDistance = 4.0
        self.maxCameraDistance = 4000.0
        self.zoomPerSecond = 1.8

        base.setBackgroundColor(0, 0, 0)

        # Init camera move variables
        self.keyMap = {"left":0, "right":0, "up":0, "down":0, "pageup":0, "pagedown":0, "wheelup":0, "wheeldown":0, "mouse3":0, "tab":0}
        self.angleLongitudeDegrees = 0.0
        self.angleLatitudeDegrees = 0.0
        self.cameraDistance = 10.0
        self.targetNode = render
        self.light = False

        #This code puts the standard title and instruction text on screen
        self.titleText = OnscreenText(text=self.titleString,
                                      style=1, fg=(1,1,0,1),
                                      pos=(0.8,-0.95), scale = .07)

        # Create empty node for world origin
        self.worldOrigin = render.attachNewNode("World Origin")
        self.planeten = planeten
        # Texture aender
        self.planeteninstance = []
        for p in planeten:
            if p[0] == "sun":
                self.su = Planetimpl(self.worldOrigin, 8.37800000E+06, 0, self.renderRatio, "sun", 10, 0)
                self.sun = self.su.impl()
                self.planeteninstance.extend([self.su])
                self.o = self.su
            else:
                self.o = Planetimpl(self.worldOrigin, p[1], p[2], self.renderRatio, p[0], p[3], p[4])
                self.orbit = self.o.impl()
                self.planeteninstance.extend([self.o])
            self.orbitOrbitVertexWriter = self.o.line()
            self.taskMgr.add(self.o.rotatePlanet, "rotate"+p[0], sort=1)
            self.taskMgr.add(self.o.translatePlanet, "move"+p[0]+"Orbit", sort=1)

        shadow = [[1.25, 1.25, 1.25]]
        self.plnp = []
        for s in shadow:
            self.plnp.append(self.pointlight(s[0], s[1], s[2]))
        # Attach the camera to the Earth to begin with
        self.targetNode = self.sun
        self.targetSize = float(self.targetNode.getTag("targetSize"))
        self.listener()
        self.cameraview()
        self.taskMgr.add(self.moveOrbitalCameraTask, "moveOrbitalCameraTask", sort=2)


    def pointlight(self, x, y, z):
        """
        Erzeugt einen Schatten, je nach Position der Sonne
        :return: die Schattierung des Planeten
        """
        plight = PointLight('plight')
        plight.setColor(VBase4(0.8, 0.8, 0.8, 1))
        plnp = render.attachNewNode(plight)
        plnp.setPos(x, y, z)
        return plnp


    def cameraview(self):
        """
        Cameraview
        """
        # Create picker Node and CollisionRay
        self.pickerNode = CollisionNode('mouseRay')
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        self.pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)

        # Create Collision Traverser and Queue
        self.cameraPickingTraverser = CollisionTraverser('Camera Picking Traverser')
        self.cameraPickingQueue = CollisionHandlerQueue()

        # Link Picker Node to Traverser and Queue
        self.cameraPickingTraverser.addCollider(self.pickerNP, self.cameraPickingQueue)

        # Set tags on Earth and Moon to be pickable

        # Add text to display the camera position
        self.text = OnscreenText(text = "Help: h", pos = (-1.3, .95-.05), fg=(1,1,1,1),align = TextNode.ALeft, scale = .05, mayChange = 1)
        """ self.displayCameraDistanceText = self.genLabelText("Camera distance : " + str(self.cameraDistance * self.planeten[0][1]) + " m", 0)
        self.displayCameraLatitudeText = self.genLabelText("Camera latitude : " + str(self.angleLatitudeDegrees) + " deg", 1)
        self.displayCameraLongitudeText = self.genLabelText("Camera longitude : " + str(self.angleLongitudeDegrees) + " deg", 2)
        self.displayTargetNodePositionText = self.genLabelText("Target position : (" + str(self.targetNode.getX()) + "; " + str(self.targetNode.getY()) + "; " + str(self.targetNode.getZ()) + ")", 3)
        self.help = False """

    def listener(self):
        """
        Hier werden alle Listener definiert
        """
        # Setup events for escape : exit from app
        self.accept("escape", sys.exit)


        self.accept("t", self.texturAnAus)  # textur an/aus
        self.accept("space", self.startstop)  # animation stoppen und wieder startet
        self.accept("w", self.speedup)  # animation wird schneller
        self.accept("s", self.speeddown)  # animation wird langsamer
        self.accept("l", self.changeLight)  # punktlichtwuelle setzen
        self.accept("h",self.showHelp) # Hilfe anzeigen lassen

        # Setup down events for arrow keys : rotating camera latitude and longitude
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["up",1])
        self.accept("arrow_down", self.setKey, ["down",1])

        # Setup up events for control keys
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["up",0])
        self.accept("arrow_down-up", self.setKey, ["down",0])

        # Setup events for mouse wheel
        self.accept("wheel_up", self.setKey, ["wheelup",1])
        self.accept("wheel_down", self.setKey, ["wheeldown",1])

        # Setup events for the Left Mouse Button : picking
        self.accept("mouse1", self.pickFromCamera)

        # Setup events for the Right Mouse Button : rotating camera latitude and longitude
        self.accept("mouse3", self.setKey, ["mouse3",1])
        self.accept("mouse3-up", self.setKey, ["mouse3",0])


    def changeLight(self):
        """
        Punktlichtquelle an/aus
        """
        if (self.light == True):
            self.light = False
            for p in self.plnp:
                render.clearLight(p)
        else:
            self.light = True
            for p in self.plnp:
                render.setLight(p)

    def texturAnAus(self):
        """
        Die bestehende Texture wird durch eine neue geaendert
        """
        if (self.t == True):
            self.t = False
            for p in self.planeteninstance:
                p.chooseTexture("models/borm.JPG")
        else:
            self.t = True
            for index, p in enumerate(self.planeteninstance):
                p.chooseTexture("models/"+self.planeten[index][0]+"_1k_tex.jpg")


    def startstop(self):
        """
        Startet oder stop den Weltraum
        """
        for index, p in enumerate(self.planeteninstance):
                if p.setstartstop():
                    self.taskMgr.add(p.rotatePlanet, "rotate"+self.planeten[index][0], sort=1)
                    self.taskMgr.add(p.translatePlanet, "move"+self.planeten[index][0]+"Orbit", sort=1)

    def showHelp(self):
        """
        Zeigt am Bildschirm die Bedienungsanleitung an oder nicht
        """
        if(self.help == True):
            self.help=False
            self.text.destroy()
            self.text = OnscreenText(text = "Help: h"
                                   , pos = (-1.3, .95-.05), fg=(1,1,1,1),
                       align = TextNode.ALeft, scale = .05, mayChange = 1)

        else:
            self.help=True
            if(self.text != None):
                self.text.destroy()
            self.text = OnscreenText(text = "Kamera: Maus\nAnimation start/stop: space\nAnimation schneller/langsamer: w/d\nTextur an/aus: t\nPunktlichtquelle setzen: l\nBeenden: Esc"
                                   , pos = (-1.3, .95-.05), fg=(1,1,1,1),
                       align = TextNode.ALeft, scale = .05, mayChange = 1)



    def speedup(self):
        """
        Erhoeht die Geschwindigkeit der Planet
        """
        for p in self.planeteninstance:
                p.rotation *= 10
                p.translation *= 10

    def speeddown(self):
        """
        Reduziert die Geschwindigkeit der Planet
        """
        for p in self.planeteninstance:
                p.rotation /= 10
                p.translation /= 10


    def pickFromCamera(self):
        """
        Erlaubt es einen Planeten anzuklicke um diesen zu vergrössern
        """
        mpos = base.mouseWatcherNode.getMouse()
        self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())

        self.cameraPickingTraverser.traverse(render)

        # Assume for simplicity's sake that myHandler is a CollisionHandlerQueue.
        if self.cameraPickingQueue.getNumEntries() > 0:
            # This is so we get the closest object.
            self.cameraPickingQueue.sortEntries()
            pickedObj = self.cameraPickingQueue.getEntry(0).getIntoNodePath()
            pickedObj = pickedObj.findNetTag('isPickable')
            if not pickedObj.isEmpty():
                self.targetNode = pickedObj
                self.targetSize = float(self.targetNode.getTag("targetSize"))

    def moveOrbitalCameraTask(self, task):
        """
        Define a procedure to move the camera.
        In fact, never moves the camera, but instead the world origin
        But always keeps the camera oriented towards the world origin
        :param task: Task
        :return: gibt einen Task zurueck der wiederholt ausgefuehrt wird
        """
        # Get mouse
        md = base.win.getPointer(0)
        x = md.getX()
        y = md.getY()



        if (self.keyMap["mouse3"]!=0):
            # Use mouse moves to change longitude and latitude
            self.angleLongitudeDegrees = self.angleLongitudeDegrees - (x - self.lastMouseX) * 0.2
            self.angleLatitudeDegrees = self.angleLatitudeDegrees - (y - self.lastMouseY) * 0.2
            # Restore position as frozen when the MB1 was depressed
            #base.win.movePointer(0, self.mouseFreezeX, self.mouseFreezeX)

        # Store latest mouse position for the next frame
        self.lastMouseX = x
        self.lastMouseY = y

        # First compute new camera angles and distance
        if (self.keyMap["left"]!=0):
            self.angleLongitudeDegrees = self.angleLongitudeDegrees - self.degPerSecond * globalClock.getDt()
        if (self.keyMap["right"]!=0):
            self.angleLongitudeDegrees = self.angleLongitudeDegrees + self.degPerSecond * globalClock.getDt()
        if (self.keyMap["up"]!=0):
            self.angleLatitudeDegrees = self.angleLatitudeDegrees - self.degPerSecond * globalClock.getDt()
        if (self.keyMap["down"]!=0):
            self.angleLatitudeDegrees = self.angleLatitudeDegrees + self.degPerSecond * globalClock.getDt()
        if (self.keyMap["wheelup"]!=0):
            self.cameraDistance = self.cameraDistance * (1 + (self.zoomPerSecond-1) * globalClock.getDt())
            self.setKey("wheelup",0)
        if (self.keyMap["wheeldown"]!=0):
            self.cameraDistance = self.cameraDistance / (1 + (self.zoomPerSecond-1) * globalClock.getDt())
            self.setKey("wheeldown",0)

        # Limit angles to [-180;+180]x[-90;+90] and distance between set min and max
        if (self.angleLongitudeDegrees > 180.0):
            self.angleLongitudeDegrees = self.angleLongitudeDegrees - 360.0
        if (self.angleLongitudeDegrees < -180.0):
            self.angleLongitudeDegrees = self.angleLongitudeDegrees + 360.0
        if (self.angleLatitudeDegrees > (90.0 - 0.001)):
            self.angleLatitudeDegrees = 90.0 - 0.001
        if (self.angleLatitudeDegrees < (-90.0 + 0.001)):
            self.angleLatitudeDegrees = -90.0 + 0.001
        if (self.cameraDistance < self.minCameraDistance):
            self.cameraDistance = self.minCameraDistance
        if (self.cameraDistance > self.maxCameraDistance):
            self.cameraDistance = self.maxCameraDistance

        # Convert to Radians
        angleLongitudeRadians = self.angleLongitudeDegrees * (pi / 180.0)
        angleLatitudeRadians = self.angleLatitudeDegrees * (pi / 180.0)

        # Compute the target object's position with respect to the camera
        x = -self.cameraDistance * self.targetSize * sin(angleLongitudeRadians) * cos(angleLatitudeRadians)
        y =  self.cameraDistance * self.targetSize * cos(angleLongitudeRadians) * cos(angleLatitudeRadians)
        z =  self.cameraDistance * self.targetSize * sin(angleLatitudeRadians)

        # Compute the world origin's position with respect to the camera
        x = (x * self.renderRatio) - self.targetNode.getX(self.worldOrigin)
        y = (y * self.renderRatio) - self.targetNode.getY(self.worldOrigin)
        z = (z * self.renderRatio) - self.targetNode.getZ(self.worldOrigin)

        # Apply the position
        self.worldOrigin.setPos(x, y, z)

        # Rotate the camera
        self.camera.setHpr(self.angleLongitudeDegrees, self.angleLatitudeDegrees, 0)

        # Display camera position
        """self.displayCameraDistanceText.setText("Camera distance : " + str(self.cameraDistance * self.targetSize) + " m")
        self.displayCameraLatitudeText.setText("Camera latitude : " + str(self.angleLatitudeDegrees) + " deg")
        self.displayCameraLongitudeText.setText("Camera longitude : " + str(self.angleLongitudeDegrees) + " deg")
        self.displayTargetNodePositionText.setText("Target position : (" + str(self.targetNode.getX()) + "; " + str(self.targetNode.getY()) + "; " + str(self.targetNode.getZ()) + ")")"""

        # End task
        return Task.cont

    #Records the state of the keyboard and mouse
    def setKey(self, key, value):
        """
        Mappt den Key mit einer Value
        :param key: Listener Key
        :param value: Value des Keys
        """
        # Store mouse position at the time of freeze
        if (key == "mouse3"):
            md = base.win.getPointer(0)
            self.lastMouseX = md.getX()
            self.lastMouseY = md.getY()
        #Store key/button press/release
        self.keyMap[key] = value
Example #48
0
class KeyCodesGui(DirectObject):
    notify = directNotify.newCategory('KeyCodesGui')
    TIMEOUT_TASK = 'KeyCodeGui_TIMEOUT_TASK'

    def __init__(self, keyCodes, yOffset=0.55, keyToIndex=KEY_TO_INDEX):
        self._keyCodes = keyCodes
        self._keyToIndex = keyToIndex
        self._arrowWidth = 0.18
        self._arrowSpaceInBetween = 0.05
        self._yOffset = yOffset
        self._danceMoveLabel = None
        self._arrowNodes = []
        self.timeoutTask = None
        return

    def load(self):
        matchingGameGui = loader.loadModel(
            'phase_3.5/models/gui/matching_game_gui')
        minnieArrow = matchingGameGui.find('**/minnieArrow')
        minnieArrow.setScale(0.6)
        minnieArrow.setZ(self._yOffset + 0.2)
        maxLength = self._keyCodes.getLargestPatternLength()
        for i in range(maxLength):
            arrow = minnieArrow.copyTo(hidden)
            self._arrowNodes.append(arrow)

        matchingGameGui.removeNode()
        self._danceMoveLabel = OnscreenText(parent=aspect2d,
                                            text='',
                                            pos=(0, self._yOffset),
                                            scale=0.15,
                                            align=TextNode.ACenter,
                                            font=ToontownGlobals.getSignFont(),
                                            fg=Vec4(1, 1, 1, 1),
                                            mayChange=True)
        self._danceMoveLabel.hide()
        self.enable()

    def unload(self):
        self.disable()
        for arrow in self._arrowNodes:
            arrow.removeNode()
            arrow = None

        self._arrowNodes = []
        if self._danceMoveLabel is not None:
            self._danceMoveLabel.removeNode()
            self._danceMoveLabel = None
        return

    def enable(self):
        self.notify.debug('KeyCodeGui enabled.')
        self.accept(KeyCodes.KEY_DOWN_EVENT, self.__handleKeyDown)
        self.accept(KeyCodes.CLEAR_CODE_EVENT, self.hideAll)

    def disable(self):
        self.notify.debug('KeyCodeGui disabled.')
        self.__stopTimeout()
        self.ignoreAll()

    def hideArrows(self, startIndex=0):
        length = len(self._arrowNodes)
        if startIndex < length:
            for i in range(startIndex, length):
                self._arrowNodes[i].reparentTo(hidden)

    def hideAll(self, startIndex=0):
        self.hideArrows(startIndex)
        if self._danceMoveLabel:
            self._danceMoveLabel.hide()

    def showArrow(self, index, key):
        self._arrowNodes[index].setR(-(90 - 90 * self._keyToIndex[key]))
        self._arrowNodes[index].setColor(1, 1, 1, 1)
        self.__centerArrows()
        self._arrowNodes[index].reparentTo(aspect2d)
        self.hideAll(index + 1)
        self.__startTimeout()

    def showText(self, text=''):
        self.notify.debug('"Showing text "%s"' % text)
        self._danceMoveLabel['text'] = text
        self._danceMoveLabel.show()

    def setColor(self, r, g, b):
        for arrow in self._arrowNodes:
            arrow.setColor(r, g, b)

        self._danceMoveLabel.setColorScale(r, g, b, 1)

    def __startTimeout(self):
        self.__stopTimeout()
        self.timeoutTask = taskMgr.doMethodLater(KEYCODE_TIMEOUT_SECONDS,
                                                 self.__handleTimeoutTask,
                                                 KeyCodesGui.TIMEOUT_TASK)

    def __stopTimeout(self):
        if self.timeoutTask is not None:
            taskMgr.remove(self.timeoutTask)
            self.timeoutTask = None
        return

    def __handleTimeoutTask(self, task):
        self.hideAll()
        return Task.done

    def __centerArrows(self):
        length = self._keyCodes.getCurrentInputLength()
        for i in range(length):
            x = -(length * self._arrowWidth * 0.5) + self._arrowWidth * (i +
                                                                         0.5)
            self._arrowNodes[i].setX(x)

    def __handleKeyDown(self, key, index):
        if index >= 0:
            self.showArrow(index, key)
 def _initSpamWarning(self):
     self._spamWarning = OnscreenText(text = TTLocalizer.PartyCogGuiSpamWarning, scale = 0.14999999999999999, fg = (1.0, 1.0, 0, 1.0), shadow = (0, 0, 0, 0.62), mayChange = False, pos = (0, 0.33000000000000002))
     self._spamWarning.hide()
Example #50
0
    def __init__(self):
        #Define variables and file path locations
        self.currentScreen = 0
        self.name = 'New Cog'
        self.currentDirectory = os.path.abspath(sys.path[0])
        self.pandaDirectory = Filename.fromOsSpecific(
            self.currentDirectory).getFullpath()

        #Define UI Background
        self.UIBackground = loader.loadModel(
            self.pandaDirectory + '/resources/gui/tt_m_gui_ups_panelBg.bam')
        self.UIBackground.reparentTo(aspect2d)
        self.UIBackground.setPos(-0.75, 0, 0)
        self.UIBackground.setScale(1, 1, 1.75)

        #Set the title text
        self.remingtonFont = loader.loadFont(
            self.pandaDirectory + '/resources/gui/vtRemingtonPortable.ttf')
        self.instructionText = OnscreenText(pos=(0, 0.35),
                                            wordwrap=10,
                                            font=self.remingtonFont,
                                            parent=self.UIBackground,
                                            mayChange=True)

        #Establish where the buttons are located
        self.buttonMaps = loader.loadModel(
            self.pandaDirectory + '/resources/gui/tt_m_gui_mat_mainGui.bam')

        #Define the head selector, its title text, and its scroll buttons
        self.headSelector = OnscreenImage(
            image=self.buttonMaps.find('**/tt_t_gui_mat_shuffleFrame'),
            parent=self.UIBackground,
            scale=(0.7, 1, 0.5),
            pos=(0, 0, 0.18))

        self.headSelectorText = OnscreenText(text='Head',
                                             parent=self.headSelector,
                                             pos=(0, -0.04),
                                             scale=(0.15, 0.15),
                                             fg=(255, 255, 255, 1),
                                             font=self.remingtonFont)

        self.headLeftButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowDown')),
            relief=None,
            parent=self.headSelector,
            pos=(-0.33, 0, 0),
            command=self.headLeftClick)

        self.headRightButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowDown')),
            relief=None,
            parent=self.headSelector,
            pos=(0.33, 0, 0),
            scale=(-1, 1, 1),
            command=self.headRightClick)
        self.headSelector.hide()

        #Define the body selector, its title text, and its scroll buttons
        self.bodySelector = OnscreenImage(
            image=self.buttonMaps.find('**/tt_t_gui_mat_shuffleFrame'),
            parent=self.UIBackground,
            scale=(-0.7, 1, 0.5),
            pos=(0, 0, 0))

        self.bodySelectorText = OnscreenText(text='Body',
                                             parent=self.bodySelector,
                                             pos=(0, -0.04),
                                             scale=(-0.15, 0.15),
                                             fg=(255, 255, 255, 1),
                                             font=self.remingtonFont)

        self.bodyLeftButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowDown')),
            relief=None,
            parent=self.bodySelector,
            pos=(0.33, 0, 0),
            scale=(-1, 1, 1),
            command=self.bodyLeftClick)

        self.bodyRightButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowDown')),
            relief=None,
            parent=self.bodySelector,
            pos=(-0.33, 0, 0),
            command=self.bodyRightClick)
        self.bodySelector.hide()

        #Define the department selector, its title text, and its scroll buttons
        self.deptSelector = OnscreenImage(
            image=self.buttonMaps.find('**/tt_t_gui_mat_shuffleFrame'),
            parent=self.UIBackground,
            scale=(0.7, 1, 0.5),
            pos=(0, 0, -0.18))

        self.deptSelectorText = OnscreenText(text='Dept.',
                                             parent=self.deptSelector,
                                             pos=(0, -0.04),
                                             scale=(0.15, 0.15),
                                             fg=(255, 255, 255, 1),
                                             font=self.remingtonFont)

        self.deptLeftButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowDown')),
            relief=None,
            parent=self.deptSelector,
            pos=(-0.33, 0, 0),
            command=self.deptLeftClick)

        self.deptRightButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowDown')),
            relief=None,
            parent=self.deptSelector,
            pos=(0.33, 0, 0),
            scale=(-1, 1, 1),
            command=self.deptRightClick)
        self.deptSelector.hide()

        #Define the name input
        self.nameEntryBackground = OnscreenImage(
            image=loader.loadModel(self.pandaDirectory +
                                   "/resources/gui/ChatPanel.bam"),
            parent=self.UIBackground,
            scale=(0.6, 1, 0.1),
            pos=(-0.3, 0, 0.2))

        self.nameEntry = DirectEntry(parent=self.nameEntryBackground,
                                     relief=None,
                                     text='',
                                     width=5.5,
                                     numLines=2,
                                     entryFont=self.remingtonFont,
                                     scale=(0.2, 1, 0.4),
                                     pos=(-0.05, 0, -0.35),
                                     command=self.enterName,
                                     focusOutCommand=self.entryUnfocused,
                                     focus=False)
        self.nameEntryBackground.hide()

        #Define the screen changing buttons
        self.nextButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_nextUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_nextDown')),
            relief=None,
            command=self.nextButtonClick,
            parent=self.UIBackground,
            scale=(0.4, 1, 0.25),
            pos=(0.3, 0, -0.35))

        self.backButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_nextUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_nextDown')),
            relief=None,
            command=self.backButtonClick,
            parent=self.UIBackground,
            scale=(-0.4, 1, 0.25),
            pos=(-0.3, 0, -0.35))
        self.backButton.hide()

        #Call the Cog class to establish the Actor
        self.cog = Cog()

        #Change the current UI screen
        self.screenDirector()
Example #51
0
class ConstructACogGUI():
    def __init__(self):
        #Define variables and file path locations
        self.currentScreen = 0
        self.name = 'New Cog'
        self.currentDirectory = os.path.abspath(sys.path[0])
        self.pandaDirectory = Filename.fromOsSpecific(
            self.currentDirectory).getFullpath()

        #Define UI Background
        self.UIBackground = loader.loadModel(
            self.pandaDirectory + '/resources/gui/tt_m_gui_ups_panelBg.bam')
        self.UIBackground.reparentTo(aspect2d)
        self.UIBackground.setPos(-0.75, 0, 0)
        self.UIBackground.setScale(1, 1, 1.75)

        #Set the title text
        self.remingtonFont = loader.loadFont(
            self.pandaDirectory + '/resources/gui/vtRemingtonPortable.ttf')
        self.instructionText = OnscreenText(pos=(0, 0.35),
                                            wordwrap=10,
                                            font=self.remingtonFont,
                                            parent=self.UIBackground,
                                            mayChange=True)

        #Establish where the buttons are located
        self.buttonMaps = loader.loadModel(
            self.pandaDirectory + '/resources/gui/tt_m_gui_mat_mainGui.bam')

        #Define the head selector, its title text, and its scroll buttons
        self.headSelector = OnscreenImage(
            image=self.buttonMaps.find('**/tt_t_gui_mat_shuffleFrame'),
            parent=self.UIBackground,
            scale=(0.7, 1, 0.5),
            pos=(0, 0, 0.18))

        self.headSelectorText = OnscreenText(text='Head',
                                             parent=self.headSelector,
                                             pos=(0, -0.04),
                                             scale=(0.15, 0.15),
                                             fg=(255, 255, 255, 1),
                                             font=self.remingtonFont)

        self.headLeftButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowDown')),
            relief=None,
            parent=self.headSelector,
            pos=(-0.33, 0, 0),
            command=self.headLeftClick)

        self.headRightButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowDown')),
            relief=None,
            parent=self.headSelector,
            pos=(0.33, 0, 0),
            scale=(-1, 1, 1),
            command=self.headRightClick)
        self.headSelector.hide()

        #Define the body selector, its title text, and its scroll buttons
        self.bodySelector = OnscreenImage(
            image=self.buttonMaps.find('**/tt_t_gui_mat_shuffleFrame'),
            parent=self.UIBackground,
            scale=(-0.7, 1, 0.5),
            pos=(0, 0, 0))

        self.bodySelectorText = OnscreenText(text='Body',
                                             parent=self.bodySelector,
                                             pos=(0, -0.04),
                                             scale=(-0.15, 0.15),
                                             fg=(255, 255, 255, 1),
                                             font=self.remingtonFont)

        self.bodyLeftButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowDown')),
            relief=None,
            parent=self.bodySelector,
            pos=(0.33, 0, 0),
            scale=(-1, 1, 1),
            command=self.bodyLeftClick)

        self.bodyRightButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowDown')),
            relief=None,
            parent=self.bodySelector,
            pos=(-0.33, 0, 0),
            command=self.bodyRightClick)
        self.bodySelector.hide()

        #Define the department selector, its title text, and its scroll buttons
        self.deptSelector = OnscreenImage(
            image=self.buttonMaps.find('**/tt_t_gui_mat_shuffleFrame'),
            parent=self.UIBackground,
            scale=(0.7, 1, 0.5),
            pos=(0, 0, -0.18))

        self.deptSelectorText = OnscreenText(text='Dept.',
                                             parent=self.deptSelector,
                                             pos=(0, -0.04),
                                             scale=(0.15, 0.15),
                                             fg=(255, 255, 255, 1),
                                             font=self.remingtonFont)

        self.deptLeftButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowDown')),
            relief=None,
            parent=self.deptSelector,
            pos=(-0.33, 0, 0),
            command=self.deptLeftClick)

        self.deptRightButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_shuffleArrowDown')),
            relief=None,
            parent=self.deptSelector,
            pos=(0.33, 0, 0),
            scale=(-1, 1, 1),
            command=self.deptRightClick)
        self.deptSelector.hide()

        #Define the name input
        self.nameEntryBackground = OnscreenImage(
            image=loader.loadModel(self.pandaDirectory +
                                   "/resources/gui/ChatPanel.bam"),
            parent=self.UIBackground,
            scale=(0.6, 1, 0.1),
            pos=(-0.3, 0, 0.2))

        self.nameEntry = DirectEntry(parent=self.nameEntryBackground,
                                     relief=None,
                                     text='',
                                     width=5.5,
                                     numLines=2,
                                     entryFont=self.remingtonFont,
                                     scale=(0.2, 1, 0.4),
                                     pos=(-0.05, 0, -0.35),
                                     command=self.enterName,
                                     focusOutCommand=self.entryUnfocused,
                                     focus=False)
        self.nameEntryBackground.hide()

        #Define the screen changing buttons
        self.nextButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_nextUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_nextDown')),
            relief=None,
            command=self.nextButtonClick,
            parent=self.UIBackground,
            scale=(0.4, 1, 0.25),
            pos=(0.3, 0, -0.35))

        self.backButton = DirectButton(
            geom=(self.buttonMaps.find('**/tt_t_gui_mat_nextUp'),
                  self.buttonMaps.find('**/tt_t_gui_mat_nextDown')),
            relief=None,
            command=self.backButtonClick,
            parent=self.UIBackground,
            scale=(-0.4, 1, 0.25),
            pos=(-0.3, 0, -0.35))
        self.backButton.hide()

        #Call the Cog class to establish the Actor
        self.cog = Cog()

        #Change the current UI screen
        self.screenDirector()

    def headLeftClick(self):
        #switch to the previous head
        self.cog.previousHead()

    def headRightClick(self):
        #switch to the next head
        self.cog.nextHead()

    def bodyLeftClick(self):
        #switch to the previous body
        self.cog.previousBody()

    def bodyRightClick(self):
        #switch to the next body
        self.cog.nextBody()

    def deptLeftClick(self):
        #switch to the previous department
        self.cog.previousDept()

    def deptRightClick(self):
        #switch to the next department
        self.cog.nextDept()

    def enterName(self, text):
        #Assign the entry text to name, then switch to the next screen
        self.name = text
        self.currentScreen = 3

        #Change the current UI screen
        self.screenDirector()

    def setEntryFocus(self):
        #Determine if to focus or unfocus the DirectEntry depending if the screen is visible
        if self.currentScreen == 2:
            self.nameEntry['focus'] = True
        else:
            self.nameEntry['focus'] = False
            self.entryUnfocused()

        self.nameEntry.setFocus()

    def entryUnfocused(self):
        #Set whatever is currently in the box to the name variable
        self.name = self.nameEntry.get()

    def nextButtonClick(self):
        #Add 1 to the currentScreen, then switch to the new screen
        self.currentScreen += 1

        #Constrain current screen to always be less than 3
        if self.currentScreen > 3:
            self.currentScreen = 3
            return

        #Set the focus of the text entry box
        self.setEntryFocus()

        #Change the current UI screen
        self.screenDirector()

    def backButtonClick(self):
        #Subtract 1 from the currentScreen, then switch to the new screen
        self.currentScreen -= 1

        #Constrain current screen to always be greater than 0
        if self.currentScreen < 0:
            self.currentScreen = 0
            return

        #Set the focus of the text entry box
        self.setEntryFocus()

        #Change the current UI screen
        self.screenDirector()

    def screenDirector(self):
        #Determine which screen to shift to
        if self.currentScreen == 0:
            self.welcomeScreen()

        elif self.currentScreen == 1:
            self.cogDesignScreen()

        elif self.currentScreen == 2:
            self.namingScreen()

        elif self.currentScreen == 3:
            self.finishedScreen()

        else:
            raise Exception('UH OH! currentScreen is not between 0 and 3! \
							The value of currentScreen is {}'.format(self.currentScreen))

    def welcomeScreen(self):
        #Show/hide respective GUI elements
        self.instructionText.setText('Salutations, new Cog. \
									Click the button below to continue.')
        self.backButton.hide()
        self.headSelector.hide()
        self.bodySelector.hide()
        self.deptSelector.hide()

        #Determine whether the cog should exit the scene if its in view already
        if (self.cog.isInView):
            self.cog.exitScene()

    def cogDesignScreen(self):
        #Show/hide respective GUI elements
        self.instructionText.setText('Select a design.')
        self.backButton.show()
        self.headSelector.show()
        self.bodySelector.show()
        self.deptSelector.show()
        self.nameEntryBackground.hide()

        #Determine whether the cog should reenter the scene if its in view already
        if (not self.cog.isInView):
            self.cog.enterScene()

    def namingScreen(self):
        #Show/hide respective GUI elements
        self.instructionText.setText('Type in a name.')
        self.nextButton.show()
        self.headSelector.hide()
        self.bodySelector.hide()
        self.deptSelector.hide()
        self.nameEntryBackground.show()

        #See if the cog is playing the victory animation and change to keep the animation smooth
        if self.cog.getAnimPlaying() == 'victory':
            self.cog.playNeutral()

    def finishedScreen(self):
        #Show/hide respective GUI elements
        self.instructionText.setText('Welcome to COGS, Inc., ' + self.name +
                                     '.\
									If you wish to make changes, click the back button.')
        self.nextButton.hide()
        self.nameEntryBackground.hide()

        #Have the cog dance
        self.cog.playVictory()
class Player(object, DirectObject.DirectObject):
    def __init__(self):
        self.node = 0  #the player main node
        self.modelNode = 0  #the node of the actual model
        self.cNode = 0  #the player collision node attached to node
        self.cNodePath = 0  #node path to cNode
        self.contrail = ParticleEffect(
        )  #QUANDO BATE, CRIA EFEITO (LINHA DE BAIXO TB)
        self.contrail.setTransparency(TransparencyAttrib.MDual)
        self.contrail2 = ParticleEffect(
        )  #QUANDO ACIONA TURBO, CRIA EFEITO (LINHA DE BAIXO TB)
        self.contrail2.setTransparency(TransparencyAttrib.MDual)
        self.landing = False
        self.freeLook = False
        self.speed = 10
        self.speedMax = 100
        self.agility = 3
        self.HP = 10
        self.collisionHandler = CollisionHandlerEvent(
        )  # the collision handlers
        self.collisionHandlerQueue = CollisionHandlerQueue()
        self.zoom = -5
        self.gnodePath = 0  #node to phisics
        self.gNode = 0  #node of gravity
        self.gNodePath = 0  #node path to actorNode
        #self

        self.textSpeed = OnscreenText(text='Speed: ' + str(self.speed),
                                      pos=(-1.34, 0.95),
                                      scale=0.07,
                                      fg=(1, 1, 1, 1),
                                      bg=(0.2, 0.2, 0.2, 0.4),
                                      align=TextNode.ALeft)
        self.textHP = OnscreenText(text='Health:    ' + str(self.HP),
                                   pos=(-1.33, 0.85),
                                   scale=0.07,
                                   fg=(1, 1, 1, 1),
                                   bg=(0.2, 0.2, 0.2, 0.4),
                                   align=TextNode.ALeft)
        self.roll = 0
        self.camHeight = 0

        base.win.movePointer(0,
                             base.win.getXSize() / 2,
                             base.win.getYSize() / 2)

        self.myImage = OnscreenImage(image='cursor.png',
                                     pos=(0, 0, -0.02),
                                     scale=(0.05))
        self.myImage.setTransparency(TransparencyAttrib.MAlpha)

        self.loadModel()
        self.addCamera()
        self.addEvents()
        self.addCollisions()
        self.addSound()

        self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task')
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        self.zoomTaskPointer = taskMgr.add(self.zoomTask, 'zoom-task')

    '''
    loadModel
    This will load all the visible stuff
    '''

    def loadModel(self):
        """ make the nodepath for player """
        self.node = NodePath('player')
        self.node.setPos(1000, 1000, 200)
        self.node.reparentTo(render)
        self.node.lookAt(0, 0, 200)

        self.modelNode = loader.loadModel('gaivota')
        self.modelNode.reparentTo(self.node)
        self.modelNode.setScale(0.3)
        playerMaterial = Material()
        playerMaterial.setShininess(22.0)  #Make this material shiny
        playerMaterial.setAmbient(VBase4(1, 1, 1, 1))
        playerMaterial.setSpecular(VBase4(0.7, 0.7, 0.7, 0.7))
        self.modelNode.setMaterial(playerMaterial)
        self.modelNode.setShaderAuto()

        self.aimNode = NodePath('aimNode')
        self.aimNode.reparentTo(self.node)
        self.aimNode.setPos(0, 15, 2)

        #self.contrail.loadConfig('media/contrail.ptf')
        #self.contrail.start(self.node,render)

        #gravity (aceleration 9.82)
        self.gravityFN = ForceNode('world-forces')
        self.gravityFNP = render.attachNewNode(self.gravityFN)
        self.gravityForce = LinearVectorForce(0, 0, -9.82)
        self.gravityFN.addForce(self.gravityForce)

        #add gravity to engine
        #base.physicsMgr.addLinerForce(self.gravityForce)

        #Physics node
        self.gnodePath = NodePath(PandaNode("physics"))
        self.gNode = ActorNode("plane-actornode")
        self.gNodePath = self.gnodePath.attachNewNode(self.gNode)

        #object weigth
        self.gNode.getPhysicsObject().setMass(0.004)

        #add gravity force
        base.physicsMgr.addLinearForce(self.gravityForce)
        base.physicsMgr.attachPhysicalNode(self.gNode)

        #render object with physics
        self.gnodePath.reparentTo(render)
        self.node.reparentTo(self.gNodePath)

    '''
    addCamera
    camera setup
    '''

    def addCamera(self):
        base.disableMouse()
        base.camera.reparentTo(self.node)
        base.camera.setPos(0, self.zoom, 2)
        base.camera.lookAt(self.aimNode)

    '''
    addEvents
    This will set up the events the class will accept
    '''

    def addEvents(self):
        self.accept("wheel_up", self.evtSpeedUp)
        self.accept("wheel_down", self.evtSpeedDown)
        self.accept('hit', self.evtHit)
        self.accept('f', self.evtFreeLookON)
        self.accept('f-up', self.evtFreeLookOFF)
        self.accept('mouse3', self.evtBoostOn)
        self.accept("menuOpen", self.evtMenuOpen)
        self.accept("menuClosed", self.evtMenuClose)

    '''
    addCollisions
    This will add a collision sphere for the player
    and a segment to check weather the ground is close/flat enough for landing
    '''

    def addCollisions(self):
        self.cNode = CollisionNode('player')
        self.cNode.addSolid(CollisionSphere(0, 0, 0, 2.3))
        self.cNode.setFromCollideMask(BitMask32(0x1A))
        self.cNode.setIntoCollideMask(BitMask32(0x4))

        self.cNodePath = self.node.attachNewNode(self.cNode)
        #self.cNodePath.show()
        self.collisionHandler.addInPattern('hit')
        base.cTrav.addCollider(self.cNodePath, self.collisionHandler)

        # landing segment:
        self.landingCNodeSegment = CollisionNode('playerRay')
        self.landingCNodeSegment.addSolid(CollisionSegment(0, 0, 0, 0, 0, -20))
        self.landingCNodeSegment.setIntoCollideMask(BitMask32.allOff())
        self.landingCNodeSegment.setFromCollideMask(BitMask32(0x8))

        self.landingCNodeSegmentPath = self.node.attachNewNode(
            self.landingCNodeSegment)
        #self.landingCNodeSegmentPath.show()
        base.cTrav.addCollider(self.landingCNodeSegmentPath,
                               self.collisionHandlerQueue)

    '''
    addSound
    adds the engine sound
    @TODO add more
    '''

    def addSound(self):
        self.engineSound = loader.loadSfx("engine.mp3")
        self.engineSound.setLoop(True)
        self.engineSound.play()
        self.engineSound.setVolume(2.0)
        self.engineSound.setPlayRate(0)

    '''
    deleteTask
    task which calls the destructor after a given time (after the explosion animation)
    '''

    def deleteTask(self, task):
        self.__del__()
        return task.done

    '''
    mouseUpdateTask
    This task will handle mouse movement and control the planes rotation.
    If free look is enabled, it will rotate the camera around the player.
    '''

    def mouseUpdateTask(self, task):
        """ this task updates the mouse """
        md = base.win.getPointer(0)
        x = md.getX()
        y = md.getY()
        deltaX = 0
        deltaY = 0
        if base.win.movePointer(0,
                                base.win.getXSize() / 2,
                                base.win.getYSize() / 2):
            deltaX = (
                x - base.win.getXSize() / 2
            ) * 0.06  #* globalClock.getDt() *70 #* self.agility * (0.5+abs(self.roll)/50)
            deltaY = (y - base.win.getYSize() / 2) * 0.06
            if deltaX > self.agility:
                deltaX = self.agility
            if deltaX < -self.agility:
                deltaX = -self.agility
            if deltaY > self.agility:
                deltaY = self.agility
            if deltaY < -self.agility:
                deltaY = -self.agility

            # don't move ship while in freelook mode
            if not self.freeLook:
                self.node.setH(self.node.getH() - deltaX)
                self.node.setP(self.node.getP() - deltaY)

        # don't move ship while in freelook mode
        if not self.freeLook:
            self.roll += deltaX
            self.camHeight += deltaY

        self.roll *= 0.95  #/ (globalClock.getDt() * 60)#* globalClock.getDt() * 700
        self.camHeight *= 0.95  #* globalClock.getDt() * 700

        if self.roll < -25 * self.speed / self.speedMax:
            self.roll = -25 * self.speed / self.speedMax
        if self.roll > 25 * self.speed / self.speedMax:
            self.roll = 25 * self.speed / self.speedMax

        self.node.setR(self.roll * 3)
        base.camera.setZ(2 - self.camHeight * 0.5 * self.speed / self.speedMax)
        base.camera.lookAt(self.aimNode)
        base.camera.setR(-self.roll * 2)
        #base.camera.setY(-30+self.speed/10)
        #base.camera.setX(self.roll*0.5)

        # freelook mode:
        if self.freeLook:
            self.camRotH -= deltaX * 3
            self.camRotV -= deltaY * 3
            if self.camRotV < 1:
                self.camRotV = 1
            if self.camRotV > 179:
                self.camRotV = 179

            base.camera.setX(
                math.cos(math.radians(self.camRotH)) *
                math.sin(math.radians(self.camRotV)) * 30)
            base.camera.setY(
                math.sin(math.radians(self.camRotH)) *
                math.sin(math.radians(self.camRotV)) * 30)
            base.camera.setZ(math.cos(math.radians(self.camRotV)) * 30)
            base.camera.lookAt(self.node)

        return task.cont

    '''
    moveUpdateTask
    Will update players position depending on speed and direction
    '''

    def moveUpdateTask(self, task):
        """ this task makes the player move """
        # move where the keys set it
        self.node.setPos(self.node,
                         Vec3(0, 1.0 * globalClock.getDt() * self.speed, 0))

        #self.node.setPos(self.node,self.strafe*globalClock.getDt()*self.speed)
        return task.cont

    '''
    explode
    this will cause the plane to explode with a nice particle effect.
    '''

    def explode(self):
        self.ignoreAll()
        self.cNode.setIntoCollideMask(BitMask32.allOff())
        taskMgr.remove(self.moveTask)
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.zoomTaskPointer)
        self.moveTask = 0
        self.mouseTask = 0

        if self.contrail != 0:
            self.contrail.cleanup()
        self.modelNode.hide()

        self.contrail = ParticleEffect()
        self.contrail.loadConfig('media/explosion.ptf')
        self.contrail.start(self.node)
        self.contrail.setLightOff()
        self.contrail2.cleanup()
        self.deleteTask = taskMgr.doMethodLater(4, self.deleteTask,
                                                'delete task')

    '''
    zoomTask
    will adjust camera position according to zoom factor specified in self.zoom
    in a smooth way.
    '''

    def zoomTask(self, task):
        if base.camera.getY() != self.zoom and self.freeLook == False:
            base.camera.setY(base.camera.getY() +
                             (self.zoom - base.camera.getY()) *
                             globalClock.getDt() * 2)
        return task.cont

    '''
    evtBoostOn
    Will set most inputs to ignore, add a speed boost and an additional
    particle effect     
    '''

    def evtBoostOn(self):
        #taskMgr.remove(self.mouseTask)
        self.ignore("wheel_up")
        self.ignore("wheel_down")
        self.ignore('f')
        self.ignore('f-up')
        self.accept('mouse3-up', self.evtBoostOff)
        self.speed += 200
        self.textSpeed.setText('Speed: ' + str(self.speed))
        self.contrail2.loadConfig('media/contrail-boost.ptf')
        self.contrail2.start(self.node)
        self.zoom = -25
        self.evtFreeLookOFF()

    '''
    evtBoostOff
    Will reactivate inputs, substract speed boost and stop the additional
    particle effect     
    '''

    def evtBoostOff(self):
        self.speed -= 200
        self.textSpeed.setText('Speed: ' + str(self.speed))
        self.ignore('mouse3-up')
        self.addEvents()
        #self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        #self.contrail.loadConfig('../../media/contrail.ptf')
        self.contrail2.softStop()
        self.zoom = -5 - (self.speed / 10)

    '''
    evtHit
    This event will be called if the player gets hit by an object.
    It will reduce the HP by 1 each time we hit a missile.
    If HP reaches 0, the player will explode.
    If we hit an other object like a rock, the player will explode imidiatly
    '''

    def evtHit(self, entry):
        if entry.getIntoNodePath().getParent().getTag(
                "orign") != self.node.getName():

            #if entry.getIntoNodePath().getName() == "projectile":
            #self.HP -= 1
            #self.textHP.setText('HP   : '+str(self.HP))
            if self.HP == 0:
                self.explode()
            else:
                self.explode()

    '''
    evtFreeLookON
    Event that activates free look mode and therefore changes cam position
    '''

    def evtFreeLookON(self):
        if self.landing == False:
            self.freeLook = True
            self.camRotH = 270
            self.camRotV = 80
            self.myImage.hide()

    '''
    evtFreeLookOFF
    Event that deactivates free look mode and therefore changes cam position
    back to original
    '''

    def evtFreeLookOFF(self):
        if self.landing == False:
            self.freeLook = False
            base.camera.setPos(0, -20, 2)
            base.camera.lookAt(self.aimNode)
            self.myImage.show()

    '''
    __del__
    destructor will remove particle effect, tasks and the whole node
    '''

    def __del__(self):
        self.ignoreAll()
        self.contrail.cleanup()
        base.camera.reparentTo(render)
        base.camera.setPos(2000, 2000, 800)
        base.camera.lookAt(0, 0, 0)
        if self.moveTask != 0:
            taskMgr.remove(self.moveTask)
        if self.mouseTask != 0:
            taskMgr.remove(self.mouseTask)
        self.node.removeNode()
        messenger.send('player-death')

    '''
    evtSpeedUp
    Will be called if player wants to increase speed.
    - engine sound will become louder
    - camera will zoom out
    - speed display will be updated
    '''

    def evtSpeedUp(self):
        if self.landing:
            return 0
        self.speed += 5
        self.engineSound.setPlayRate(self.engineSound.getPlayRate() + 0.05)
        if self.speed > self.speedMax:
            self.speed = self.speedMax
            #self.engineSound.setVolume(1)
            self.engineSound.setPlayRate(1.5)
        self.zoom = -5 - (self.speed / 10)
        self.textSpeed.setText('Speed: ' + str(self.speed))

    '''
    evtSpeedDown
    Will be called if player wants to decrease speed.
    - engine sound will become more silent
    - camera will zoom in
    - speed display will be updated
    '''

    def evtSpeedDown(self):
        if self.landing:
            return 0
        self.textSpeed.setText('Speed: ' + str(self.speed))
        self.speed -= 5
        self.engineSound.setPlayRate(self.engineSound.getPlayRate() - 0.05)
        if self.speed < 0:
            self.speed = 0
            #self.engineSound.setVolume(0)
            self.engineSound.setPlayRate(0.5)
        self.zoom = -5 - (self.speed / 10)

    def evtMenuOpen(self):
        """event that will be called if main menu is opened (esc)"""
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.moveTask)
        self.myImage.hide()
        props = WindowProperties()
        props.setCursorHidden(0)
        base.win.requestProperties(props)

    def evtMenuClose(self):
        """event that will be called if main menu is closed (esc)"""
        #self.addEvents()
        props = WindowProperties()
        props.setCursorHidden(1)
        base.win.requestProperties(props)
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task')
        self.myImage.show()
Example #53
0
    def load(self):
        self.sceneRoot = NodePath(
            self.toonName.replace(' ', '').replace('', ''))
        base.setBackgroundColor(0, 0, 0, 1)

        if self.twoSlides:
            if self.side == 'left':
                # Left Top
                titlePos = (0.1, 0.5, 0.0)
                descriptionPos = (0.2, 0.4, 0.0)
                imagePos = (-0.55, 0.0, 0.4)
                textAlignment = TextNode.ALeft
                # Right Bottom
                title2Pos = (-0.1, -0.35, 0.0)
                description2Pos = (-0.1, -0.45, 0.0)
                image2Pos = (0.55, 0.0, -0.4)
                text2Alignment = TextNode.ARight
            else:
                # Right Top
                titlePos = (-0.1, 0.5, 0.0)
                descriptionPos = (-0.1, 0.4, 0.0)
                imagePos = (0.55, 0.0, 0.4)
                textAlignment = TextNode.ARight
                # Left Bottom
                title2Pos = (0.1, -0.35, 0.0)
                description2Pos = (0.25, -0.45, 0.0)
                image2Pos = (-0.55, 0.0, -0.4)
                text2Alignment = TextNode.ALeft
        elif self.side == 'left':
            # Left Middle
            titlePos = (0.1, 0.15, 0.0)
            descriptionPos = (0.2, 0.05, 0.0)
            imagePos = (-0.5, 0.0, 0.0)
            textAlignment = TextNode.ALeft
        else:
            # Right Middle
            titlePos = (-0.1, 0.1, 0.0)
            descriptionPos = (-0.11, 0.0, 0.0)
            imagePos = (0.5, 0.0, 0.0)
            textAlignment = TextNode.ARight

        self.title = OnscreenText(text=self.toonName,
                                  pos=titlePos,
                                  scale=0.15,
                                  fg=(1, 1, 1, 1),
                                  font=ToontownGlobals.getSignFont(),
                                  align=textAlignment)
        self.description = OnscreenText(text=self.toonDescription,
                                        pos=descriptionPos,
                                        scale=0.06,
                                        fg=(1, 1, 1, 1),
                                        font=ToontownGlobals.getMinnieFont(),
                                        align=textAlignment)
        self.image = OnscreenImage(image='phase_4/maps/news/%s' %
                                   self.toonImage,
                                   pos=imagePos,
                                   scale=(0.5, 0.30, 0.30))
        self.elements = [self.title, self.description, self.image]

        if self.twoSlides:
            self.title2 = OnscreenText(text=self.toon2Name,
                                       pos=title2Pos,
                                       scale=0.15,
                                       fg=(1, 1, 1, 1),
                                       font=ToontownGlobals.getSignFont(),
                                       align=text2Alignment)
            self.description2 = OnscreenText(
                text=self.toon2Description,
                pos=description2Pos,
                scale=0.06,
                fg=(1, 1, 1, 1),
                font=ToontownGlobals.getMinnieFont(),
                align=text2Alignment)
            self.image2 = OnscreenImage(image='phase_4/maps/news/%s' %
                                        self.toon2Image,
                                        pos=image2Pos,
                                        scale=(0.5, 0.30, 0.30))
            self.elements.extend([self.title2, self.description2, self.image2])

        for node in self.elements:
            node.setTransparency(1)
            node.setColorScale(1, 1, 1, 0)
Example #54
0
    def __init__(self):
        ShowBase.__init__(self)

        self.t = 0
        self.starttime = None
        self.setFrameRateMeter(True)
        cour = self.loader.loadFont('cmtt12.egg')
        self.textObject = OnscreenText(font=cour,
                                       text='abcdefghijklmnopqrstuvwxyz',
                                       pos=(0, -0.045),
                                       parent=self.a2dTopCenter,
                                       bg=(0, 0, 0, 0.5),
                                       fg=(1, 1, 1, 1),
                                       scale=0.07,
                                       mayChange=True)
        cm = CardMaker("ground")
        cm.setFrame(-2000, 2000, -2000, 2000)
        cm.setUvRange(Point2(-2000 / 5, -2000 / 5), Point2(2000 / 5, 2000 / 5))

        tmp = self.render.attachNewNode(cm.generate())
        tmp.reparentTo(self.render)
        self.camLens.setNear(0.1)

        tmp.setPos(0, 0, 0)
        tmp.lookAt((0, 0, -2))
        tmp.setColor(1.0, 1.0, 1.0, 0.)
        #tmp.setTexScale(TextureStage.getDefault(), 1, 1)
        tex = self.loader.loadTexture('textures/grid2.png')
        tex.setWrapU(Texture.WMRepeat)
        tex.setWrapV(Texture.WMRepeat)
        tmp.setTexture(tex, 1)
        self.setBackgroundColor(0.0, 191.0 / 255.0, 1.0,
                                1.0)  #color of the sky

        ambientLight = AmbientLight('ambientLight')
        ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1))
        ambientLightNP = self.render.attachNewNode(ambientLight)
        self.render.setLight(ambientLightNP)

        # Directional light 01
        directionalLight = DirectionalLight('directionalLight')
        directionalLight.setColor(Vec4(0.8, 0.8, 0.8, 1))
        directionalLightNP = self.render.attachNewNode(directionalLight)
        # This light is facing backwards, towards the camera.
        directionalLightNP.setHpr(-120, -50, 0)
        directionalLightNP.node().setScene(self.render)
        directionalLightNP.node().setShadowCaster(True)
        directionalLightNP.node().getLens().setFov(40)
        directionalLightNP.node().getLens().setNearFar(10, 100)
        self.render.setLight(directionalLightNP)

        # Add the spinCameraTask procedure to the task manager.
        self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")

        self.physics = TheanoRigid3DBodyEngine()
        self.benchmark_physics = None  #Rigid3DBodyEngine()
        # Load the environment model.
        self.objects = dict()

        #self.load_robot_model("robotmodel/test.json")
        self.load_robot_model("robotmodel/predator.json")
        #self.load_robot_model("robotmodel/simple_predator.json")
        if self.benchmark_physics:
            self.benchmark_physics.compile()

        print "Compiling..."
        self.positions, self.velocities, self.rotations = self.physics.getInitialState(
        )
        self.physics.compile()

        import theano.tensor as T
        positions = T.fmatrix()
        velocities = T.fmatrix()
        rotations = T.ftensor3()

        a, b, c = self.physics.step_from_this_state(
            (positions, velocities, rotations),
            dt=0.001,
            motor_signals=[-1, 1, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
        self.timestep = theano.function(
            inputs=[positions, velocities, rotations],
            outputs=[a, b, c],
            allow_input_downcast=True)
Example #55
0
    def __init__(self):
        # Initialize the ShowBase class from which we inherit, which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)
        self.stimtype = 'random image'

        # session_start
        self.session_start_time = datetime.datetime.now()

        # self.accept("escape", sys.exit, [0])#don't let the user do this, because then the data isn't saved.
        self.accept('q', self.close)
        self.accept('Q', self.close)

        self.upArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.up())
        self.downArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.down())
        self.rightArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.right())
        self.leftArrowIsPressed = base.mouseWatcherNode.isButtonDown(KeyboardButton.left())

        self.AUTO_REWARD = AUTO_REWARD
        # disable mouse control so that we can place the camera
        base.disableMouse()
        camera.setPosHpr(0, 0, 10, 0, -90, 0)
        mat = Mat4(camera.getMat())
        mat.invertInPlace()
        base.mouseInterfaceNode.setMat(mat)
        # base.enableMouse()

        props = WindowProperties()
        # props.setOrigin(0, 0)
        props.setFullscreen(True)
        props.setCursorHidden(True)
        props.setMouseMode(WindowProperties.M_relative)
        base.win.requestProperties(props)
        base.setBackgroundColor(0, 0, 0)  # set the background color to black

        print('FULSCREEN:')
        print(props.getFullscreen())
        print('=============')
        # set up the textures
        # we now get buffer thats going to hold the texture of our new scene
        altBuffer = self.win.makeTextureBuffer("hello", 1524, 1024)
        # altBuffer.getDisplayRegion(0).setDimensions(0.5,0.9,0.5,0.8)
        # altBuffer = base.win.makeDisplayRegion()
        # altBuffer.makeDisplayRegion(0,1,0,1)

        # now we have to setup a new scene graph to make this scene
        self.dr2 = base.win.makeDisplayRegion(0, 0.001, 0, 0.001)#make this really,really small so it's not seeable by the subject

        altRender = NodePath("new render")
        # this takes care of setting up ther camera properly
        self.altCam = self.makeCamera(altBuffer)
        self.dr2.setCamera(self.altCam)
        self.altCam.reparentTo(altRender)
        self.altCam.setPos(0, -10, 0)

        self.bufferViewer.setPosition("lrcorner")
        # self.bufferViewer.position = (-.1,-.4,-.1,-.4)
        self.bufferViewer.setCardSize(1.0, 0.0)
        print(self.bufferViewer.position)

        self.imagesTexture = MovieTexture("image_sequence")
        # success = self.imagesTexture.read("models/natural_images.avi")
        # success = self.imagesTexture.read("models/movie_5hz.mpg")
        self.imagesTexture.setPlayRate(1.0)
        self.imagesTexture.setLoopCount(10)
        # self.imageTexture =loader.loadTexture("models/NaturalImages/BSDs_8143.tiff")
        # self.imagesTexture.reparentTo(altRender)

        self.fixationPoint = OnscreenImage(image='models/fixationpoint.jpg', pos=(0, 0,0),scale=0.01)

        cm = CardMaker("stimwindow")
        cm.setFrame(-4, 4, -3, 3)
        # cm.setUvRange(self.imagesTexture)
        self.card = NodePath(cm.generate())
        self.card.reparentTo(altRender)
        if self.stimtype == 'image_sequence':
            self.card.setTexture(self.imagesTexture, 1)

        # add the score display
        self.scoreLabel = OnscreenText(text='Current Score:', pos=(-1, 0.9), scale=0.1, fg=(0.8, 0.8, 0.8, 1))
        self.scoreText = OnscreenText(text=str(0), pos=(-1, 0.76), scale=0.18, fg=(0, 1, 0, 1),
                                      shadow=(0.1, 1, 0.1, 0.5))
        self.feebackScoreText = OnscreenText(text='+ ' + str(0), pos=(-0.5, 0.5), scale=0.3, fg=(0, 1, 0, 1),
                                             shadow=(0.1, 1, 0.1, 0.5))
        self.feebackScoreText.setX(3.)

        # self.imagesTexture.play()

        # self.bufferViewer.setPosition("lrcorner")
        # self.bufferViewer.setCardSize(1.0, 0.0)
        self.accept("v", self.bufferViewer.toggleEnable)
        self.accept("V", self.bufferViewer.toggleEnable)

        # Load the tunnel
        self.initTunnel()

        # initialize some things
        # for the tunnel construction:
        self.boundary_to_add_next_segment = -1 * TUNNEL_SEGMENT_LENGTH
        self.current_number_of_segments = 8
        # task flow booleans
        self.in_waiting_period = False
        self.stim_started = False
        self.looking_for_a_cue_zone = True
        self.in_reward_window = False
        self.show_stimulus = False
        # for task control
        self.interval = 0
        self.time_waiting_in_cue_zone = 0
        self.wait_time = 1.83
        self.stim_duration = 0  # in seconds
    
#        self.distribution_type = np.random.uniform#
#        self.distribution_type_inputs = [0.016,0.4] #change the min & max stim duration times

    #New lines    EAS: set weights higher for faster image durations
        self.durWeights = list()
        a = np.linspace(0.016,0.4,10)
        for i,j in enumerate(a):
            if j<0.1:
                p1 = 0.25
                self.durWeights.append(p1)
            elif j > 0.1 and j < 0.21:
                p1 = 0.1
                self.durWeights.append(p1)
            elif j> 0.21:
                p1 = 0.04
                self.durWeights.append(p1)
        self.rng = np.random.default_rng()
        a = np.asarray(a)
        self.distribution_type_inputs = a
        #subset_size = len(p)

    #End new lines
      
#        self.distribution_type_inputs = [0.05,1.5]  #can be anytong should match 
#        self.distribution_type_inputs = [0.016,0.4] #change the min & max stim duration times
#        self.distribution_type_inputs = [0.016,0.4, 10] #change the min & max stim duration times

        self.max_stim_duration = 1.0  # in seconds
        self.stim_elapsed = 0.0       # in seconds
        self.last_position = base.camera.getZ()
        self.position_on_track = base.camera.getZ()
        # for reward control
        self.reward_window = REWARD_WINDOW  # in seconds
        self.reward_elapsed = 0.0
        
#        self.new_dt = list()
        
        # self.reward_volume = 0.008 # in mL. this is for the hardcoded 0.1 seconds of reward time
        self.reward_volume = int(REWARD_VOLUME)  # in uL, for the stepper motor
        self.reward_time = 0.1  # in sec, based on volume. hard coded right now but should be modified by the (1) calibration and (2) optionally by the main loop for dynamic reward scheduling
        # self.lick_buffer = []
        self.current_score = 0
        self.score = 0
        self.feedback_score_startime = -2

        # INITIALIZE NIDAQ
        self.nidevice = 'Dev2'
        self.encodervinchannel = 1
        self.encodervsigchannel = 0
        self.invertdo = False
        self.diport = 1
        self.lickline = 1
        self.doport = 0
        self.rewardline = 0
        self.rewardlines = [0]
        self.encoder_position_diff = 0
        if have_nidaq:
            self._setupDAQ()
            self.do.WriteBit(1, 1)
            self.do.WriteBit(3,
                             1)  # set reward high, because the logic is flipped somehow. possibly by haphazard wiring of the circuit (12/24/2018 djd)
            self.previous_encoder_position = self.ai.data[0][self.encodervsigchannel]
        else:
            self.previous_encoder_position = 0
        self.encoder_gain = 3

        # INITIALIZE LICK SENSOR
        self._lickSensorSetup()

        # INITIALIZE  output data
        self.lickData = []
        self.x = []
        self.t = []
        self.trialData = []
        self.reactionTimeData = []
        self.rewardData = []
        self.rightKeyData = []
        self.leftKeyData = []
        self.imageData = []
        self.imageTimeData = []
        self.scoreData = []
        self.trialDurationData = []
        self.new_dt = []

        # INITIALIZE KEY SENSOR, for backup inputs and other user controls
        self.keys = key.KeyStateHandler()
        self.accept('r', self._give_reward, [self.reward_volume])
        self.accept('l', self._toggle_reward)

        # initialize the image list and populate what images you want included


#        self.img_list = glob.glob('models/2AFC_IMAGES_HUMAN/*.tif')
#        self.img_list = glob.glob('models/2AFC_IMAGES_HUMAN2/*.tif')  
#        self.img_list = glob.glob('/Users/elizabethstubblefield/Desktop/cheetah_or_elephant/composite_images/masks/all_same_num_ea/*.tif')  #Newest images
        self.img_list = glob.glob('models/all_same_ea/*.tif')  #Newest images

        #No longer hard-coded:
        self.original_indices = [0,0]  #this was manually counted... first number must was the index of the first easy img; was [43, -18]
        for ndx, name in enumerate(self.img_list):
            if 'Cheetah255' in name:
                self.original_indices[0] = ndx
            elif 'Elephant0' in name:
                self.original_indices[1] = ndx

        # print(self.img_list)
        
#        self.original_indices = [43,-18] #manually counted, grump  #Problematic w/out at least 43 images in the folder        

        self.imageTextures =[loader.loadTexture(img) for img in self.img_list]
        self.img_id = None   #this variable is used so we know which stimulus is being presented
        self.img_mask = None #this tells us what the image mask being presented is

        # self._setupEyetracking()
        # self._startEyetracking()

        if AUTO_MODE:
            self.gameTask = taskMgr.add(self.autoLoop2, "autoLoop2")
            self.rewardTask = taskMgr.add(self.rewardControl, "reward")
            self.cue_zone = concatenate((self.cue_zone, arange( \
                self.current_number_of_segments * -TUNNEL_SEGMENT_LENGTH-50, \
                self.current_number_of_segments * -TUNNEL_SEGMENT_LENGTH - TUNNEL_SEGMENT_LENGTH - 100, \
                -1)))
            self.auto_position_on_track = 0
            self.auto_restart = False
            self.auto_running = True
            self.contTunnel()
        else:
            # Now we create the task. taskMgr is the task manager that actually
            # calls the function each frame. The add method creates a new task.
            # The first argument is the function to be called, and the second
            # argument is the name for the task.  It returns a task object which
            # is passed to the function each frame.
            self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")
            # self.stimulusTask = taskMgr.add(self.stimulusControl, "stimulus")
            self.lickTask = taskMgr.add(self.lickControl, "lick")
            self.rewardTask = taskMgr.add(self.rewardControl, "reward")
            self.keyTask = taskMgr.add(self.keyControl, "Key press")
Example #56
0
class MyApp(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)

        self.t = 0
        self.starttime = None
        self.setFrameRateMeter(True)
        cour = self.loader.loadFont('cmtt12.egg')
        self.textObject = OnscreenText(font=cour,
                                       text='abcdefghijklmnopqrstuvwxyz',
                                       pos=(0, -0.045),
                                       parent=self.a2dTopCenter,
                                       bg=(0, 0, 0, 0.5),
                                       fg=(1, 1, 1, 1),
                                       scale=0.07,
                                       mayChange=True)
        cm = CardMaker("ground")
        cm.setFrame(-2000, 2000, -2000, 2000)
        cm.setUvRange(Point2(-2000 / 5, -2000 / 5), Point2(2000 / 5, 2000 / 5))

        tmp = self.render.attachNewNode(cm.generate())
        tmp.reparentTo(self.render)
        self.camLens.setNear(0.1)

        tmp.setPos(0, 0, 0)
        tmp.lookAt((0, 0, -2))
        tmp.setColor(1.0, 1.0, 1.0, 0.)
        #tmp.setTexScale(TextureStage.getDefault(), 1, 1)
        tex = self.loader.loadTexture('textures/grid2.png')
        tex.setWrapU(Texture.WMRepeat)
        tex.setWrapV(Texture.WMRepeat)
        tmp.setTexture(tex, 1)
        self.setBackgroundColor(0.0, 191.0 / 255.0, 1.0,
                                1.0)  #color of the sky

        ambientLight = AmbientLight('ambientLight')
        ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1))
        ambientLightNP = self.render.attachNewNode(ambientLight)
        self.render.setLight(ambientLightNP)

        # Directional light 01
        directionalLight = DirectionalLight('directionalLight')
        directionalLight.setColor(Vec4(0.8, 0.8, 0.8, 1))
        directionalLightNP = self.render.attachNewNode(directionalLight)
        # This light is facing backwards, towards the camera.
        directionalLightNP.setHpr(-120, -50, 0)
        directionalLightNP.node().setScene(self.render)
        directionalLightNP.node().setShadowCaster(True)
        directionalLightNP.node().getLens().setFov(40)
        directionalLightNP.node().getLens().setNearFar(10, 100)
        self.render.setLight(directionalLightNP)

        # Add the spinCameraTask procedure to the task manager.
        self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")

        self.physics = TheanoRigid3DBodyEngine()
        self.benchmark_physics = None  #Rigid3DBodyEngine()
        # Load the environment model.
        self.objects = dict()

        #self.load_robot_model("robotmodel/test.json")
        self.load_robot_model("robotmodel/predator.json")
        #self.load_robot_model("robotmodel/simple_predator.json")
        if self.benchmark_physics:
            self.benchmark_physics.compile()

        print "Compiling..."
        self.positions, self.velocities, self.rotations = self.physics.getInitialState(
        )
        self.physics.compile()

        import theano.tensor as T
        positions = T.fmatrix()
        velocities = T.fmatrix()
        rotations = T.ftensor3()

        a, b, c = self.physics.step_from_this_state(
            (positions, velocities, rotations),
            dt=0.001,
            motor_signals=[-1, 1, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
        self.timestep = theano.function(
            inputs=[positions, velocities, rotations],
            outputs=[a, b, c],
            allow_input_downcast=True)

    def addSphere(self, name, radius, position, rotation, velocity,
                  **parameters):
        #smiley = self.loader.loadModel("zup-axis")
        smiley = self.loader.loadModel("smiley")
        smiley.setScale(radius, radius, radius)
        smiley.setTexture(self.loader.loadTexture('textures/soccer.png'), 1)

        # Reparent the model to render.
        smiley.reparentTo(self.render)
        # Apply scale and position transforms on the model.
        smiley.setPos(*position)
        smiley.setQuat(self.render, fixQuat(rotation))

        self.objects[name] = smiley
        self.physics.add_sphere(name, radius, position, rotation, velocity)
        if self.benchmark_physics:
            self.benchmark_physics.add_sphere(name, radius,
                                              position + rotation, velocity)

    def addCube(self, name, dimensions, position, rotation, velocity,
                **parameters):
        #smiley = self.loader.loadModel("zup-axis")
        cube = self.loader.loadModel("textures/box.egg")
        cube.setScale(*dimensions)
        cube.setTexture(self.loader.loadTexture('maps/noise.rgb'), 1)

        tex = self.loader.loadTexture('textures/square.png')
        tex.setWrapU(Texture.WMClamp)
        tex.setWrapV(Texture.WMClamp)
        cube.setTexture(tex, 1)
        if "color" in parameters:
            cube.setColor(*parameters["color"])

        # Reparent the model to render.
        cube.reparentTo(self.render)
        # Apply scale and position transforms on the model.
        cube.setPos(*position)
        cube.setQuat(self.render, fixQuat(rotation))

        self.objects[name] = cube
        self.physics.add_cube(name, dimensions, position, rotation, velocity)
        if self.benchmark_physics:
            self.benchmark_physics.add_cube(name, dimensions,
                                            position + rotation, velocity)

    def load_robot_model(self, filename):
        robot_dict = json.load(open(filename, "rb"))
        for elementname, element in robot_dict["model"].iteritems():
            primitive = element[0]
            parameters = dict(
                robot_dict["default_model_parameters"]["default"])  # copy
            if primitive["shape"] in robot_dict["default_model_parameters"]:
                parameters.update(
                    robot_dict["default_model_parameters"][primitive["shape"]])
            parameters.update(primitive)
            if primitive["shape"] == "cube":
                self.addCube(elementname, **parameters)
            elif primitive["shape"] == "sphere":
                self.addSphere(elementname, **parameters)

        for jointname, joint in robot_dict["joints"].iteritems():
            parameters = dict(
                robot_dict["default_constraint_parameters"]["default"])  # copy
            if joint["type"] in robot_dict["default_constraint_parameters"]:
                parameters.update(
                    robot_dict["default_constraint_parameters"][joint["type"]])
            parameters.update(joint)
            if joint["type"] == "hinge":
                self.physics.add_hinge_constraint(jointname, **parameters)
                if self.benchmark_physics:
                    self.benchmark_physics.add_hinge_constraint(
                        jointname, **parameters)

            elif joint["type"] == "ground":
                self.physics.add_ground_constraint(jointname, **parameters)
                if self.benchmark_physics:
                    self.benchmark_physics.add_ground_constraint(
                        jointname, **parameters)

            elif joint["type"] == "fixed":
                self.physics.add_fixed_constraint(jointname, **parameters)
                if self.benchmark_physics:
                    self.benchmark_physics.add_fixed_constraint(
                        jointname, **parameters)

            elif joint["type"] == "ball":
                self.physics.add_ball_and_socket_constraint(
                    jointname, **parameters)
                if self.benchmark_physics:
                    self.benchmark_physics.add_ball_and_socket_constraint(
                        jointname, **parameters)

            if "limits" in parameters:
                for limit in parameters["limits"]:
                    limitparameters = dict(
                        robot_dict["default_constraint_parameters"]["default"])
                    if "limit" in robot_dict["default_constraint_parameters"]:
                        limitparameters.update(
                            robot_dict["default_constraint_parameters"]
                            ["limit"])
                    limitparameters.update(limit)
                    self.physics.addLimitConstraint(joint["object1"],
                                                    joint["object2"],
                                                    **limitparameters)
                    if self.benchmark_physics:
                        self.benchmark_physics.addLimitConstraint(
                            joint["object1"], joint["object2"],
                            **limitparameters)

            #"""
            if "motors" in parameters:
                for motor in parameters["motors"]:
                    motorparameters = dict(
                        robot_dict["default_constraint_parameters"]["default"])
                    if "motor" in robot_dict["default_constraint_parameters"]:
                        motorparameters.update(
                            robot_dict["default_constraint_parameters"]
                            ["motor"])
                    motorparameters.update(motor)
                    self.physics.addMotorConstraint(joint["object1"],
                                                    joint["object2"],
                                                    **motorparameters)
                    if self.benchmark_physics:
                        self.benchmark_physics.addMotorConstraint(
                            joint["object1"], joint["object2"],
                            **motorparameters)
            #"""

    # Define a procedure to move the camera.
    def spinCameraTask(self, task):
        if self.starttime is None:
            self.starttime = time.time()
        DT = 0.01
        self.t += DT

        self.positions, self.velocities, self.rotations = self.timestep(
            self.positions, self.velocities, self.rotations)
        #print positions, rotations, velocity

        for obj_name, obj in self.objects.iteritems():
            sc = obj.getScale()

            idx = self.physics.get_object_index(obj_name)
            obj.setMat(
                self.render,
                LMatrix4f(LMatrix3f(*self.rotations[idx, :, :].flatten())))
            obj.setPos(*self.positions[idx, :])
            obj.setScale(sc)

        # change camera movement
        self.camera.setPos(0, 2, 0.3)
        #self.camera.lookAt(0,0,3)
        self.camera.lookAt(
            *self.positions[self.physics.get_object_index("spine"), :])

        real_time = time.time() - self.starttime

        self.textObject.setText('Time: %3.3f s\n%3.3fx real time\n%s' %
                                (self.t, self.t / real_time, ""))
        #time.sleep(0.001)
        if real_time > 100:
            self.userExit()

        return Task.cont
Example #57
0
 def genLabelText(self, text, i):
     return OnscreenText(text=text, pos=(0.06, -.06 * (i + 0.5)), fg=(1, 1, 1, 1),
                         parent=base.a2dTopLeft,align=TextNode.ALeft, scale=.05)
Example #58
0
def update(textNode, task):
    if textNode[0] is not None:
        textNode[0].detachNode()
        textNode[1].detachNode()
        textNode[2].detachNode()
    cam_pos = base.cam.getPos()
    textNode[0] = OnscreenText(
        text = str(cam_pos[0])[0:5],
        fg = (1,0,0,1),
        pos = (1.0,0.8),
        align = TextNode.ALeft)
    textNode[1] = OnscreenText(
        text=str(cam_pos[1])[0:5],
        fg=(0, 1, 0, 1),
        pos=(1.3, 0.8),
        align=TextNode.ALeft)
    textNode[2] = OnscreenText(
        text=str(cam_pos[2])[0:5],
        fg=(0, 0, 1, 1),
        pos=(1.6, 0.8),
        align=TextNode.ALeft)
    return task.again
cam_view_text = OnscreenText(
        text="Camera View: ",
        fg=(0, 0, 0, 1),
        pos=(1.15, 0.9),
        align=TextNode.ALeft)
testNode = [None, None, None]
taskMgr.add(update, "addobject", extraArgs=[testNode], appendTask=True)

base.run()
Example #59
0
class Creature(UsesAnimationMixer, Avatar.Avatar, UsesEffectNode):
    FailsafeAnims = (('idle', 1.0), ('idle', 1.0), ('idle', 1.0), ('idle', 1.0), ('idle', 1.0), ('idle', 1.0), ('idle', 1.0), ('idle', 1.0), ('idle', 1.0), ('idle', 1.0), ('idle', 1.0), ('idle', 1.0), ('idle', 1.0), ('idle', 1.0))
    SfxNames = {
        'death': SoundGlobals.SFX_MONSTER_DEATH }
    sfx = { }
    actor = None
    animInfo = { }
    
    class AnimationMixer(AnimationMixer):
        LOOP = AnimationMixer.LOOP
        ACTION = dict(AnimationMixer.ACTION)
        ACTION['MOVIE'] = AnimationMixer.ACTION_INDEX + 1

    
    def __init__(self, animationMixer = None):
        Avatar.Avatar.__init__(self)
        UsesEffectNode.__init__(self)
        self.setPickable(0)
        self.shadowFileName = 'models/misc/drop_shadow'
        self.dimensions = VBase3(0.0, 0.0, 0.0)
        self.nameText = None
        self.avatarType = None
        self.level = None
        self.nametagOffset = 2.0
        self.headNode = self.find('**/def_head')
        if not Creature.sfx:
            for name in Creature.SfxNames:
                Creature.sfx[name] = loadSfx(Creature.SfxNames[name])
            
        
        self.setupReflection()
        if not animationMixer:
            pass
        animationMixer = self.AnimationMixer
        UsesAnimationMixer.__init__(self, animationMixer)
        self.deathEffect = None
        self.shockwaveRingIval = None
        self.shockwaveRingEffect = None
        self.spiritIval = None
        self.spiritEffect = None

    
    def delete(self):
        if self.deathEffect:
            self.deathEffect.stop()
            self.deathEffect = None
        
        if self.shockwaveRingIval:
            self.shockwaveRingIval.pause()
            self.shockwaveRingIval = None
        
        if self.shockwaveRingEffect:
            self.shockwaveRingEffect.stop()
            self.shockwaveRingEffect = None
        
        if self.spiritIval:
            self.spiritIval.pause()
            self.spiritIval = None
        
        if self.spiritEffect:
            self.spiritEffect.stop()
            self.spiritEffect = None
        
        Avatar.Avatar.delete(self)
        UsesAnimationMixer.delete(self)
        UsesEffectNode.delete(self)

    
    def setupReflection(self):
        OTPRender.renderReflection(False, self, 'p_creature', None)

    
    def forceLoadAnimDict(self):
        for anim in self.animDict:
            self.getAnimControls(anim)
        

    
    def generateCreature(self):
        if self.actor:
            self.copyActor(self.actor)
        
        self.headNode = self.find('**/def_head')
        if base.options.character_detail_level == PiratesGlobals.CD_LOW:
            self.setLODAnimation(100, 5, 0.10000000000000001)
        
        self.enableMixing()

    
    def setAvatarType(self, avatarType):
        self.avatarType = avatarType
        self.height = EnemyGlobals.getHeight(avatarType)
        self.initializeDropShadow()
        if base.options.terrain_detail_level == PiratesGlobals.CD_LOW:
            self.shadowPlacer.off()
        
        self.initializeNametag3d()

    setAvatarType = report(types = [
        'module',
        'args'], dConfigParam = 'nametag')(setAvatarType)
    
    def setLevel(self, level):
        self.level = level

    
    def getLevel(self):
        return self.level

    
    def initializeNametag3d(self):
        Avatar.Avatar.initializeNametag3d(self)
        self.nametag3d.setFogOff()
        self.nametag3d.setLightOff()
        self.nametag3d.setColorScaleOff(100)
        self.nametag3d.setH(self.getGeomNode().getH())
        self.nametag.setFont(PiratesGlobals.getPirateBoldOutlineFont())
        self.iconNodePath = self.nametag.getNameIcon()
        if self.iconNodePath.isEmpty():
            self.notify.warning('empty iconNodePath in initializeNametag3d')
            return 0
        
        if not self.nameText:
            self.nameText = OnscreenText(fg = Vec4(1, 1, 1, 1), bg = Vec4(0, 0, 0, 0), scale = 1.1000000000000001, align = TextNode.ACenter, mayChange = 1, font = PiratesGlobals.getPirateBoldOutlineFont())
            self.nameText.reparentTo(self.iconNodePath)
            self.nameText.setTransparency(TransparencyAttrib.MDual, 2)
            self.nameText.setColorScaleOff(100)
            self.nameText.setLightOff()
            self.nameText.setFogOff()
        

    initializeNametag3d = report(types = [
        'module',
        'args'], dConfigParam = 'nametag')(initializeNametag3d)
    
    def initializeNametag3dPet(self):
        pass

    
    def getNameText(self):
        return self.nameText

    
    def scaleAnimRate(self, forwardSpeed):
        rate = 1.0
        myMaxSpeed = self.getMaxSpeed()
        if myMaxSpeed > 0 and forwardSpeed > 0:
            currTime = globalClockDelta.globalClock.getFrameTime()
            maxSpeed = myMaxSpeed * (currTime - self.prevSpeedClock)
            prevTime = self.prevSpeedClock
            self.prevSpeedClock = currTime
            rate = min(1.25, forwardSpeed / maxSpeed)
        
        return rate

    
    def getNametagJoints(self):
        joints = []
        for lodName in self.getLODNames():
            bundle = self.getPartBundle('modelRoot', lodName)
            joint = bundle.findChild('name_tag')
            if joint:
                joints.append(joint)
                continue
        
        return joints

    getNametagJoints = report(types = [
        'module',
        'args'], dConfigParam = 'nametag')(getNametagJoints)
    
    def adjustNametag3d(self, parentScale = 1.0):
        self.nametag3d.setZ(self.scale * parentScale * self.nametagOffset - self.nametagOffset)

    
    def getAirborneHeight(self):
        return 0.0

    
    def getMaxSpeed(self):
        return 0

    
    def getRadius(self):
        return self.battleTubeRadius

    
    def play(self, *args, **kwArgs):
        UsesAnimationMixer.play(self, *args, **args)

    
    def loop(self, *args, **kwArgs):
        UsesAnimationMixer.loop(self, *args, **args)

    
    def pingpong(self, *args, **kwArgs):
        UsesAnimationMixer.pingpong(self, *args, **args)

    
    def pose(self, *args, **kwArgs):
        UsesAnimationMixer.pose(self, *args, **args)

    
    def stop(self, *args, **kwArgs):
        UsesAnimationMixer.stop(self, *args, **args)

    
    def getDeathAnimName(self, animNum = None):
        animStrings = [
            'death']
        if animNum not in range(len(animStrings)):
            animNum = random.choice([
                0])
        
        return animStrings[animNum]

    
    def getAnimInfo(self, state):
        return self.animInfo.get(state, self.FailsafeAnims)

    
    def setupAnimInfoState(cls, state, info):
        if len(info) < len(cls.FailsafeAnims):
            info += cls.FailsafeAnims[len(info) - len(cls.FailsafeAnims):]
        
        cls.animInfo[state] = info

    setupAnimInfoState = classmethod(setupAnimInfoState)
    
    def setupAnimInfo(cls):
        cls.setupAnimInfoState('LandRoam', cls.FailsafeAnims)
        cls.setupAnimInfoState('WaterRoam', cls.FailsafeAnims)

    setupAnimInfo = classmethod(setupAnimInfo)
    
    def setLODs(self):
        avatarDetail = base.config.GetString('avatar-detail', 'high')
        if avatarDetail == 'high':
            dist = [
                0,
                20,
                80,
                280]
        elif avatarDetail == 'med':
            dist = [
                0,
                10,
                40,
                280]
        elif avatarDetail == 'low':
            dist = [
                0,
                5,
                20,
                280]
        else:
            raise StandardError, 'Invalid avatar-detail: %s' % avatarDetail
        self.addLOD('hi', dist[1], dist[0])
        self.addLOD('med', dist[2], dist[1])
        self.addLOD('low', dist[3], dist[2])

    
    def setupAssets(cls):
        cls.animInfo = Creature.animInfo.copy()
        cls.setupAnimInfo()
        filePrefix = cls.ModelInfo[1]
        animList = cls.AnimList
        animDict = { }
        for anim in animList:
            animDict[anim[0]] = filePrefix + anim[1]
        
        cls.animDict = animDict
        filePrefix = cls.ModelInfo[1]
        for name in cls.SfxNames:
            cls.sfx[name] = loadSfx(cls.SfxNames[name])
        
        cls.actor = Actor.Actor()
        if loader.loadModel(filePrefix + 'med') != None:
            avatarDetail = base.config.GetString('avatar-detail', 'high')
            if avatarDetail == 'high':
                dist = [
                    0,
                    20,
                    80,
                    280]
            elif avatarDetail == 'med':
                dist = [
                    0,
                    10,
                    40,
                    280]
            elif avatarDetail == 'low':
                dist = [
                    0,
                    6,
                    20,
                    280]
            else:
                raise StandardError, 'Invalid avatar-detail: %s' % avatarDetail
            cls.actor.setLODNode()
            cls.actor.addLOD('hi', dist[1], dist[0])
            cls.actor.addLOD('med', dist[2], dist[1])
            cls.actor.addLOD('low', dist[3], dist[2])
            creatureDetail = base.config.GetBool('want-high-creature-detail', 0)
            if creatureDetail:
                cls.actor.loadModel(filePrefix + 'hi', 'modelRoot', 'hi')
                cls.actor.loadModel(filePrefix + 'med', 'modelRoot', 'med')
                cls.actor.loadModel(filePrefix + 'low', 'modelRoot', 'low')
            else:
                cls.actor.loadModel(filePrefix + 'med', 'modelRoot', 'hi')
                cls.actor.loadModel(filePrefix + 'low', 'modelRoot', 'med')
                cls.actor.loadModel(filePrefix + 'super', 'modelRoot', 'low')
            cls.actor.loadAnims(cls.animDict, 'modelRoot', 'all')
        else:
            cls.actor.loadModel(cls.ModelInfo[0])
            cls.actor.loadAnims(cls.animDict)
        cls.actor.getGeomNode().setH(180)

    setupAssets = classmethod(setupAssets)
    
    def getSfx(self, name):
        return self.sfx.get(name)

    
    def shouldNotice(self):
        return 1

    
    def endShuffle(self):
        idleAnimInfo = self.animInfo['LandRoam'][PiratesGlobals.STAND_INDEX]
        
        try:
            self.loop(idleAnimInfo[0], blendDelay = 0.29999999999999999, rate = idleAnimInfo[1])
        except TypeError:
            e = None
            self.notify.error('Invalid animation %s for %s' % (idleAnimInfo, self))


    
    def getSplashOverride(self):
        pass
Example #60
0
class KubikiApp(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)

        self.viewDistanceChunks = 4
        self.viewDistance = (self.viewDistanceChunks + 0.5) * CHUNK_SIDE

        self.visibleChunksXY = set()
        self.visibleChunks = {}
        self.chunksForLoader = {}

        # Disable the camera trackball controls.
        self.disableMouse()

        self.camAngleA = 0
        self.camAngleB = 0

        self.currChunkXY = (None, None)
        self.currChunk = None

        self.accept('arrow_left', self.evtArrowLeft)
        self.accept('arrow_left-repeat', self.evtArrowLeft)
        self.accept('arrow_right', self.evtArrowRight)
        self.accept('arrow_right-repeat', self.evtArrowRight)
        self.accept('arrow_up', self.evtArrowUp)
        self.accept('arrow_up-repeat', self.evtArrowUp)
        self.accept('arrow_down', self.evtArrowDown)
        self.accept('arrow_down-repeat', self.evtArrowDown)
        self.accept('w', self.evtForward)
        self.accept('w-repeat', self.evtForward)
        self.accept('s', self.evtBack)
        self.accept('s-repeat', self.evtBack)
        self.accept('i', self.render.analyze)

        self.texture = self.loader.loadTexture("dirt.png")
        self.texture.setMagfilter(Texture.FTNearest)
        self.texture.setMinfilter(Texture.FTLinearMipmapLinear)

        self.xyzInfo = OnscreenText(text="text",
                                    align=TextNode.ALeft,
                                    parent=pixel2d,
                                    fg=(1, 1, 1, 1),
                                    bg=(0, 0, 0, 0.7))
        self.xyzInfo.setScale(18, 20)
        self.xyzInfo.setPos(5, -20)

        #self.messenger.toggleVerbose()

        self.setFrameRateMeter(True)
        #self.chunkLoaderThread = threading.Thread(target=chunkLoader)
        #self.chunkLoaderThread.start()

        taskMgr.doMethodLater(0.01, self.refreshChunksTask,
                              'refreshChunksTask')
        taskMgr.setupTaskChain('chunkLoaderTaskChain', numThreads=1)

        bgColor = (0.3, 0.5, 1)
        self.setBackgroundColor(*bgColor)
        self.initFog(bgColor)
        self.camLens.setFar(self.viewDistance)

        self.setCamPos(CHUNK_SIDE / 2, CHUNK_SIDE / 2, 32)

        dlight = DirectionalLight('dlight')
        dlight.setColor(VBase4(0.8, 0.8, 0.5, 1))
        dlnp = render.attachNewNode(dlight)
        dlnp.setHpr(-30, -60, 0)
        render.setLight(dlnp)

        alight = AmbientLight('alight')
        alight.setColor(VBase4(0.4, 0.4, 0.4, 1))
        alnp = render.attachNewNode(alight)
        render.setLight(alnp)

    def initFog(self, color):
        self.fog = Fog("fog")
        self.fog.setColor(*color)
        self.fog.setLinearRange(self.viewDistance * 0.8, self.viewDistance)
        self.render.setFog(self.fog)

    @staticmethod
    def coordConvert(angA, angB, l):
        #Преобразование из системы коородинат Panda3d в координаты для формулы
        angA = radians(90 + angA)
        angB = radians(90 - angB)
        x = sin(angB) * cos(angA) * l
        y = sin(angB) * sin(angA) * l
        z = cos(angB) * l
        return x, y, z

    #----------Events--------------
    def evtArrowLeft(self):
        self.camAngleA += 1

        if self.camAngleA > 180:
            self.camAngleA = -179

        self.camera.setH(self.camAngleA)

    def evtArrowRight(self):
        self.camAngleA -= 1

        if self.camAngleA < -179:
            self.camAngleA = 180

        self.camera.setH(self.camAngleA)

    def evtArrowUp(self):
        self.camAngleB += 1

        if self.camAngleB > 90:
            self.camAngleB = 90

        self.camera.setP(self.camAngleB)

    def evtArrowDown(self):
        self.camAngleB -= 1

        if self.camAngleB < -90:
            self.camAngleB = -90

        self.camera.setP(self.camAngleB)

    def evtForward(self):
        dx, dy, dz = self.coordConvert(self.camAngleA, self.camAngleB, 0.2)
        x, y, z = self.camera.getPos()
        self.setCamPos(x + dx, y + dy, z + dz)

    def evtBack(self):
        dx, dy, dz = self.coordConvert(self.camAngleA, self.camAngleB, -0.2)
        x, y, z = self.camera.getPos()
        self.setCamPos(x + dx, y + dy, z + dz)

    #------------------------------
    def setCamPos(self, x, y, z):
        self.camera.setPos(x, y, z)

        chunkXY = (int(floor(x / CHUNK_SIDE)), int(floor(y / CHUNK_SIDE)))
        if chunkXY != self.currChunkXY:
            self.setCurrChunk(chunkXY)

        self.xyzInfo.setText("x=%2.2f\ny=%2.2f\nz=%2.2f" % (x, y, z))

    def setCurrChunk(self, chunkXY):
        print chunkXY
        self.currChunkXY = chunkXY
        self.updateVisibleChunkSet()

    @staticmethod
    def loadChunk(chunkXY):
        return Chunk(chunkXY)

    def createVisibleChunkList(self):

        currChunkX, currChunkY = self.currChunkXY

        #Создаём список смещений чанков от текущего, и фильтруем его через функцию чтобы скруглить
        #слишком удалённые углы
        viewDistSquare = (self.viewDistanceChunks + 1)**2
        #chunkList = filter( lambda xy : xy[0]**2 + xy[1]**2 <=  viewDistSquare,
        #                    product(xrange(-self.viewDistanceChunks, self.viewDistanceChunks + 1),
        #                            xrange(-self.viewDistanceChunks, self.viewDistanceChunks + 1)))
        chunkList = product(
            xrange(-self.viewDistanceChunks, self.viewDistanceChunks + 1),
            xrange(-self.viewDistanceChunks, self.viewDistanceChunks + 1))

        def maxXY(xy1, xy2):
            x1, y1 = xy1
            x2, y2 = xy2
            max1 = max(abs(x1), abs(y1))
            max2 = max(abs(x2), abs(y2))
            return cmp(max1, max2)

        chunkList = [(x + currChunkX, y + currChunkY)
                     for x, y in sorted(chunkList, maxXY)]

        return chunkList

    def updateVisibleChunkSet(self):
        #Новый массив с видимыми чанками
        self.visibleChunksXY = self.createVisibleChunkList()
        self.chunkRefreshNeeded = True

    def refreshChunksTask(self, task):
        if not self.chunkRefreshNeeded:
            return task.again

        if taskMgr.hasTaskNamed('chunkLoaderTask'):
            return task.again

        self.chunkRefreshNeeded = False

        print "thinking..."

        chunksToUnload = {}
        oldVisibleChunks = self.visibleChunks
        self.visibleChunks = {}

        #Старые видимые чанки переносим в новые или готовим к выгрузке
        for xy, chunk in oldVisibleChunks.iteritems():
            if isinstance(chunk, Chunk):
                if xy in self.visibleChunksXY:
                    self.visibleChunks[xy] = chunk
                else:
                    chunksToUnload[xy] = chunk
                    chunk.hide()
                    chunk.setFree(True)

        chunksToLoadXY = set()

        #Недостающие чанки получаем из загруженных или готовим задание на загрузку
        for xy in self.visibleChunksXY:
            if not self.visibleChunks.has_key(xy):
                chunk = self.chunksForLoader.get(xy, None)
                if isinstance(chunk, Chunk):
                    chunk.show(self)
                    self.visibleChunks[xy] = chunk
                    del self.chunksForLoader[xy]
                else:
                    if len(chunksToLoadXY) <= 2:
                        chunksToLoadXY.add(xy)

        #Загруженные, но ненужные чанки - на выгрузку

        for xy, chunk in self.chunksForLoader.iteritems():
            chunk.setFree(True)

        #Задание на выгрузку
        for xy, chunk in chunksToUnload.iteritems():
            self.chunksForLoader[xy] = chunk

        #Задание на загрузку
        for xy in chunksToLoadXY:

            self.chunksForLoader[xy] = True

        #Запускаем задачу загрузки-выгрузки
        taskMgr.add(self.chunkLoaderTask,
                    'chunkLoaderTask',
                    taskChain='chunkLoaderTaskChain')

        print "end of thinking"

        return task.again

    def chunkLoaderTask(self, task):
        """
        Запускается при необходимости загрузить-выгрузить чанки.
        Выполняется в отдельном потоке
        """
        print "loader Task"

        for xy, chunk in self.chunksForLoader.items():
            if chunk == True:
                #Грузим новый чанк
                newChunk = Chunk(xy)
                self.chunksForLoader[xy] = newChunk
                self.chunkRefreshNeeded = True
            elif isinstance(chunk, Chunk) and chunk.getFree():
                #Выгружаем ненужный чанк
                chunk.unload()
                del self.chunksForLoader[xy]
            else:
                print "chunkLoaderTask:unexpected chunk"

        print "loader Task end"
        return Task.done