Ejemplo n.º 1
0
def TrialCountDownTask():
    """Task that count downs to time limit for trial"""
    # Action for text fading out
    text_fade = vizact.parallel(
        vizact.fadeTo(0, time=0.8, interpolate=vizact.easeOut),
        vizact.sizeTo([1.5, 1.5, 1.0], time=0.8, interpolate=vizact.easeOut))

    # Reset time text
    time_text.clearActions()
    time_text.alpha(1.0)
    time_text.color(viz.WHITE)
    time_text.setScale([1, 1, 1])
    time_text.message(str(int(TRIAL_DURATION)))

    # Countdown from time limit
    start_time = viz.getFrameTime()
    last_remain = int(TRIAL_DURATION)
    while (viz.getFrameTime() - start_time) < TRIAL_DURATION:
        # Compute remaining whole seconds
        remain = int(
            math.ceil(TRIAL_DURATION - (viz.getFrameTime() - start_time)))
        # Update text if time remaining changed
        if remain != last_remain:
            if remain <= 5:
                time_text.alpha(1.0)
                time_text.color(viz.RED)
                time_text.setScale([1] * 3)
                time_text.runAction(text_fade)
                viz.playSound('sounds/beep.wav')
            time_text.message(str(remain))
            last_remain = remain

        # Wait tenth of second
        yield viztask.waitTime(0.1)
Ejemplo n.º 2
0
 def playDescription(self):
     """Play the Bone description audio"""
     try:
         #print ("play " + boneObj.name + " description")
         viz.playSound(path + "audio_descriptions2\\" + self.name + ".wav")
     except ValueError:
         print("the name of the audio description file was wrong")
Ejemplo n.º 3
0
def timer3():
	viz.playSound('boing!.wav')
	global reaction_timer_initial
	a=viz.tick()
	print('in timer!')
	global timer2
	reaction_timer_initial=viz.tick()
Ejemplo n.º 4
0
    def PlaySound(self, audioindex):

        t = viz.tick()
        myaudio = self.AudioFiles[audioindex]
        viz.playSound(myaudio)

        print("PLAY SOUND: ", viz.tick() - t)
Ejemplo n.º 5
0
def MainTask():
    """Top level task that controls the game"""

    # Display instructions and wait for key press to continue
    yield DisplayInstructionsTask()

    # Create panel to display trial results
    resultPanel = vizinfo.InfoPanel("", align=viz.ALIGN_CENTER, fontSize=25, icon=False, key=None)
    resultPanel.visible(False)

    viztask.waitDirector(getData)

    while True:

        num_trials += 1

        # Randomly choose hiding spots from list
        locations = random.sample(HIDING_SPOTS, TRIAL_COUNT)

        # Reset score
        score = 0
        UpdateScore(score)

        # Go through each position
        for pos in locations:

            # Perform a trial
            found = yield TrialTask(pos)

            # Update score and display status text
            if found:
                viz.playSound("sounds/pigeon_catch.wav")
                score += 1
                total_score += 1
                UpdateScore(score)
                tracker.runAction(vizact.spinTo(point=pos, time=0.8, interpolate=vizact.easeOutStrong))
                resultPanel.setText(TRIAL_SUCCESS)
            else:
                viz.playSound("sounds/pigeon_fly.wav")
                viztask.schedule(FadeToGrayTask())
                resultPanel.setText(TRIAL_FAIL)

            # Display success/failure message
            resultPanel.visible(True)

            # Add delay before starting next trial
            yield viztask.waitTime(TRIAL_DELAY)
            resultPanel.visible(False)

            # Disable gray effect
            gray_effect.setEnabled(False)

        viztask.waitDirector(writeScore, score)
        # Display results and ask to quit or play again
        resultPanel.setText(RESULTS.format(score, TRIAL_COUNT))
        resultPanel.visible(True)
        yield viztask.waitKeyDown(" ")
        resultPanel.visible(False)
Ejemplo n.º 6
0
def TrialCountDownTask():
    """Task that count downs to time limit for trial"""
    global revealSelf
    global manChase

    # Action for text fading out
    text_fade = vizact.parallel(
        vizact.fadeTo(0,time=0.8,interpolate=vizact.easeOut)
        ,vizact.sizeTo([1.5,1.5,1.0],time=0.8,interpolate=vizact.easeOut)
    )

    # Reset time text
    time_text.clearActions()
    time_text.alpha(1.0)
    time_text.color(viz.WHITE)
    time_text.setScale([1,1,1])
    time_text.message(str(int(TRIAL_DURATION)))

    # Countdown from time limit
    start_time = viz.getFrameTime()
    last_remain = int(TRIAL_DURATION)
    male2.clearActions()
    male2.setPosition(2.5,0,7.5)

    while (viz.getFrameTime() - start_time) < TRIAL_DURATION:

        if revealSelf:
            pigeon.clearActions()
            pos = viz.MainView.getPosition()
            pigeon.addAction( vizact.walkTo([pos[0], 0, pos[2]]) )

        if manChase:
            male.clearActions()
            male2.state(2)
            pos = pigeon.getPosition()
            male2.addAction( vizact.walkTo([pos[0] - .5, 0, pos[2] - .5]))

        if male2.getPosition()[2] == (pigeon.getPosition()[2] - .5):
            #allow for other actions to take place (chase takes precedence)
            manChase = False
            male2.state(9)

        # Compute remaining whole seconds
        remain = int(math.ceil(TRIAL_DURATION - (viz.getFrameTime() - start_time)))

        # Update text if time remaining changed
        if remain != last_remain:
            if remain <= 5:
                time_text.alpha(1.0)
                time_text.color(viz.RED)
                time_text.setScale([1]*3)
                time_text.runAction(text_fade)
                viz.playSound('sounds/beep.wav')
            time_text.message(str(remain))
            last_remain = remain

        # Wait tenth of second
        yield viztask.waitTime(0.1)
def killActivity():
	global game_timer
	game_timer.setEnabled(0)
	select.disable( viz.RENDERING )
	select.disable( viz.COLLIDE_NOTIFY )
	viz.playSound('Full_Body_Bip001/fire_siren_horn.wav',viz.STOP)
	viz.playSound('Full_Body_Bip001/fire3.wav',viz.STOP)
	global globalSelected
	globalSelected = 0
Ejemplo n.º 8
0
	def playDescription(self):
		"""
		Play the Bone description audio
		"""
		try:
			#print ("play " + boneObj.name + " description")
			viz.playSound(path + "audio_descriptions2\\" + self.name + ".wav")
		except ValueError:
			print ("the name of the audio description file was wrong")
Ejemplo n.º 9
0
	def grabSequence(self):
		"""
		i don't even
		"""
		self.tooltip.enable([viz.RENDERING])
		
		try: #play audio with the same name as the bone
			viz.playSound(".\\dataset\\Skull\\audio_names\\" + self.name + ".wav")
		except ValueError:
			print ("the name of the audio file was wrong")
Ejemplo n.º 10
0
	def snap(self):
		"""
		Moves dog to the pos and euler of its target (dogTarget)
		"""
		movePos = vizact.moveTo(self.outlineCenter.getPosition(), time = self.snapTransitionTime)
		moveAng = vizact.spinTo(euler = self.outlineCenter.getEuler(), time = self.snapTransitionTime)
		transition = vizact.parallel(movePos, moveAng)
		self.dogCenter.addAction(transition)
		viz.playSound(".\\dataset\\snap.wav")
		viztask.schedule(self.mechanics())
Ejemplo n.º 11
0
 def winGame(self):
     viz.MainWindow.setScene(viz.Scene2)
     self.win = True
     self.killtimer(1)
     self.killtimer(2)
     self.killtimer(3)
     self.model.remove()
     self.ambient.stop()
     self.model.remove()
     viz.playSound(self.winSong)
def newActivity():
	viz.playSound('Full_Body_Bip001/fire_siren_horn.wav')
	select.enable( viz.RENDERING )
	select.enable( viz.COLLIDE_NOTIFY )
	global globalSelected
	globalSelected = 0
	RandomSelection()
	viz.playSound('Full_Body_Bip001/fire3.wav',viz.LOOP)
	global game_timer
	game_timer = vizact.ontimer2(30, 0, ShowResults)
Ejemplo n.º 13
0
def snap(dog, dogTarget):
    """
	Moves dog to the pos and euler of its target (dogTarget)
	"""
    movePos = vizact.moveTo(dogTarget.getPosition(), time=snapTransitionTime)
    moveAng = vizact.spinTo(euler=dogTarget.getEuler(), time=snapTransitionTime)
    transition = vizact.parallel(movePos, moveAng)
    dog.addAction(transition)
    viz.playSound(".\\dataset\\snap.wav")
    viztask.schedule(Tutorial.mechanics())
Ejemplo n.º 14
0
	def __init__(self):
		 
		################################################################
		################################################################
		
		## Register sounds.  It makes sense to do it once per experiment.
		
		self.buzzer =  '/Resources/BUZZER.wav'
		
		viz.playSound(self.buzzer,viz.SOUND_PRELOAD)
Ejemplo n.º 15
0
 def endGame(self):
     viz.MainWindow.setScene(viz.Scene3)
     self.lose = True
     self.killtimer(1)
     self.killtimer(2)
     self.killtimer(3)
     self.ambient.stop()
     self.model.remove()
     viz.playSound(self.loseSong)
     print "You Lose!"
Ejemplo n.º 16
0
    def check_allowed_area(self):
        pos = viz.MainView.getPosition()
        if self.glove:
            glove_pos = self.glove.getPosition()
        else:
            glove_pos = [0,0,0]

        if (abs(pos[0]) > self.config['allowed_area_x'] or abs(pos[2]) > self.config[
            'allowed_area_z'] or abs(glove_pos[0]) > self.config['allowed_area_x'] or abs(glove_pos[2]) > self.config[
            'allowed_area_z']) and self.trial_num >= 0:
            viz.playSound('res/sounds/warning.wav')
Ejemplo n.º 17
0
def snap(dog, dogTarget):
    """
	Moves dog to the pos and euler of its target (dogTarget)
	"""
    movePos = vizact.moveTo(dogTarget.getPosition(), time=snapTransitionTime)
    moveAng = vizact.spinTo(euler=dogTarget.getEuler(),
                            time=snapTransitionTime)
    transition = vizact.parallel(movePos, moveAng)
    dog.addAction(transition)
    viz.playSound(".\\dataset\\snap.wav")
    viztask.schedule(Tutorial.mechanics())
Ejemplo n.º 18
0
 def onCollide(self, obj):
     if obj.obj1 == self.deathStar or obj.obj2 == self.deathStar:
         viz.playSound('audio/explosion.wav')
         self.winGame()
         return
     self.numLives -= 1
     if self.numLives == 0:
         self.endGame()
     self.model.visible(viz.OFF)
     viz.playSound('audio/explosion.wav')
     self.starttimer(2, 1, 0)
     print("Collision!")
Ejemplo n.º 19
0
	def onTimer(self,num):
		#print("Timer " + str(num))
		for ball in self.balls:
			if (ball.getY() + ball.radius >= 100 or  ball.getY() - ball.radius <= -100):
				print("X Axis Wall")
				ball.setVXVY(ball.getVX(), -ball.getVY())
				viz.playSound("cartoon053.wav", viz.PLAY)
			if(ball.getX() + ball.radius >= 100) or (ball.getX() - ball.radius <= -100):
				print("Y Axis Wall")
				ball.setVXVY(-ball.getVX(), ball.getVY())
				viz.playSound("cartoon053.wav", viz.PLAY)
			ball.setXY(ball.getVX() + ball.getX(), ball.getVY() + ball.getY())
Ejemplo n.º 20
0
    def onCollideBegin(self, e):
        self.catches += 1
        viz.playSound('ball_sound.wav')

        #Displays on the screen the score that the player scores by catching the snitch
        m = viz.Matrix()
        m.postTrans(-100, -100, 0)
        self.text.setMatrix(m)
        self.text = viz.addText('Score: ' + str(self.catches),
                                viz.SCREEN,
                                pos=[0.01, 0.92, 0])
        self.text.setBackdrop(viz.BACKDROP_RIGHT_BOTTOM)
        self.text.color(0.95, 0.95, 0.95)
        self.text.disable(viz.LIGHTING)
	def collideDetected(self, event):
		
		if (event.obj2 is self.leftFootViz and event.obj1 is not self.avatar): 
			self.flag_leftFootCollision = True
		elif event.obj2 is self.rightFootViz and event.obj1 is not self.avatar:
			self.flag_rightFootCollision = True

		rightFootData = self.rightFoot.getFiltered_InstantaneousFootInfo()
		if event.obj1 is self.avatar:
			if rightFootData is not None and rightFootData.speed_MS <= .5:
				viz.playSound('quack.wav')
				self.avatar.execute(1)
			elif rightFootData is not None and rightFootData.speed_MS > .5:
				viz.playSound('pigeon_fly.wav')
				self.avatar.execute(2)
			return
				
		if event.obj1 is self.crate and (event.obj2 is self.leftFootViz or event.obj2 is self.rightFootViz):
			viz.playSound('crash.wav')
			self.crate.color(1,0,0)
			
		elif event.obj1 is self.cratePole and (event.obj2 is self.leftFootViz or event.obj2 is self.rightFootViz):
			print "Evade registered at: ", event.pos
			self.printLeftFootProperties() if event.obj2 is self.leftFootViz else self.printRightFootProperties()
			viz.playSound('BUZZER.wav')
Ejemplo n.º 22
0
	def onKeyDown(self,key):
		#moving left 
		if(key == viz.KEY_LEFT):
			self.ship.setXY(self.ship.getX() - 10, self.ship.getY())
		
		#moving right 
		if(key == viz.KEY_RIGHT):
			self.ship.setXY(self.ship.getX() + 10, self.ship.getY())
		
		#how it shoots the bullets
		if(key == " "):
			viz.playSound('shoot.wav')
			self.bullet = Bullet()
			self.bullet.setXY(self.ship.getX(), self.bullet.getY() - 190)
			self.bulletList.append(self.bullet)
Ejemplo n.º 23
0
    def onCollide(self, event):
        for bullet in self.bullets:
            if (event.obj1 is bullet
                    or event.obj2 is bullet):  # self.bullet.getVisible() :
                viz.playSound('quack.wav')
                for enemy in self.enemyList:
                    if (event.obj1 is enemy or event.obj2 is enemy):
                        viz.playSound('quack.wav')
                        enemy.remove()
                        self.score += 1

                bullet.remove()

                if self.score == self.enemyCount:
                    self.gameOver(True)
Ejemplo n.º 24
0
	def addBlocks(self):
		if self.blockPositions[9].count(1) > 0:
			self.shootable = False
			return
		numBlocks = random.randint(1, 8)
		for i in range(0, numBlocks):
			row = random.randint(0, 9)
			col = 1
			while(self.blockPositions[col][row] != 0):
				row = random.randint(0, 9)
			
			block = Block(row, col)
			self.blockList.append(block)
			self.blockPositions[col][row] += 1
		self.shootable = True
		viz.playSound(self.pickSound(3))
Ejemplo n.º 25
0
 def onTimer(self, num):
     for i in self.ballList:
         x = i.getX()
         y = i.getY()
         x = i.getVX() + x
         y = i.getVY() + y
         if (x + 10 > 100 or x - 10 < -100):
             # set the vector to bounce off walls
             i.setVXVY(i.getVX() * -1, i.getVY())
             x = i.getVX() + x
             viz.playSound('cartoon053.wav')
         if (y + 10 > 100 or y - 10 < -100):
             i.setVXVY(i.getVX(), i.getVY() * -1)
             y = i.getVY() + y
             viz.playSound('cartoon053.wav')
         i.setXY(x, y)
         print("X is " + str(x) + " and Y is " + str(y))
Ejemplo n.º 26
0
	def onKeyUp(self, key):
		# If the spacebar was pressed and there are no balls on the screen
		if key == ' ' and self.ballsOnScreen == 0:
			# Stop the charging timer
			self.killtimer(3)
			self.chargeCount = 0
			self.charging = False
			
			# Create a Ball, set its center point to the endpoint of the launcher, and set its velocity
			ball = Ball(self.launcher.getAngle())
			ball.setXY(self.launcher.getX(), self.launcher.getY())
			ball.setVXVY(ball.getVX() * self.worldMultiplier, ball.getVY() * self.worldMultiplier)
			viz.playSound(self.pickSound(6))
			
			# Append ball to list
			self.ballList.append(ball)
			self.ballsOnScreen += 1
			
			# Create delay if launching more than a single ball
			if self.clickCount > 1:
				self.starttimer(2, .25, self.clickCount - 2)
Ejemplo n.º 27
0
    def SetNewStimuli(self):
        """Sets the delay and target for the next stimuli, based on the target occurence and current pool"""

        print("SetNewStimuli called")

        t = viz.tick()

        choices = ['T', 'D']
        probabilities = [
            self.Trial_targetoccurence_prob,
            1 - self.Trial_targetoccurence_prob
        ]
        self.currentaudio_type = np.random.choice(
            choices, p=probabilities)  #slow. ~ 1ms.

        if self.currentaudio_type == 'T':
            self.currentaudio = np.random.choice(self.Trial_targets)
        elif self.currentaudio_type == 'D':
            self.currentaudio = np.random.choice(self.Distractor_pool)

        self.Stimuli_PlayedStamp = viz.tick()

        print(self.currentaudio)

        audioindex = self.letters.index(self.currentaudio)

        af = self.AudioList[audioindex]
        viz.playSound(af)

        self.Stimuli_Timer = 0
        self.ppresp = 0

        ##set new delay. Random between 1-1.5
        jitter = np.random.randint(0, 49)
        self.delay = 1.0 + (jitter / 100.0)

        self.Overall_Stimuli_Index += 1
        self.Trial_Stimuli_Index += 1

        print("SetNewStimuli: ", viz.tick() - t)
Ejemplo n.º 28
0
    def onMouseDown(self, button):
        if button == viz.MOUSEBUTTON_LEFT and len(self.bullets) < 9:
            viz.playSound('gunshot.wav')
            bullet = viz.add('bullet.dae')
            self.bullets.append(bullet)

            bullet.collideBox(.25, .25, .25)
            mat = viz.Matrix()
            mat.postScale(0.05, 0.05, 0.05)
            mat.postAxisAngle(1, 0, 0, 90)
            mat.postAxisAngle(self.camAngle)
            self.bulletVector = self.camVector
            mat.postTrans(self.camX + self.bulletVector[0] + 0.025,
                          self.camY + self.bulletVector[1] + 0.05,
                          self.camZ + self.bulletVector[2])
            bullet.setMatrix(mat)
            bullet.enable(viz.COLLIDE_NOTIFY)

            viz.phys.setGravity(0, 0, 0)
            bullet.setVelocity([
                self.bulletVector[0] * 50, self.bulletVector[1] * 50,
                self.bulletVector[2] * 50
            ])
Ejemplo n.º 29
0
def TrialCountDownTask():
    """Task that count downs to time limit for trial"""

    # Action for text fading out
    text_fade = vizact.parallel(
        vizact.fadeTo(0,time=0.8,interpolate=vizact.easeOut)
        ,vizact.sizeTo([1.5,1.5,1.0],time=0.8,interpolate=vizact.easeOut)
    )

    # Reset time text
    time_text.clearActions()
    time_text.alpha(1.0)
    time_text.color(viz.WHITE)
    time_text.setScale([1,1,1])
    time_text.message(str(int(TRIAL_DURATION)))

    # Countdown from time limit
    start_time = viz.getFrameTime()
    last_remain = int(TRIAL_DURATION)
    while (viz.getFrameTime() - start_time) < TRIAL_DURATION:

        # Compute remaining whole seconds
        remain = int(math.ceil(TRIAL_DURATION - (viz.getFrameTime() - start_time)))

        # Update text if time remaining changed
        if remain != last_remain:
            if remain <= 5:
                time_text.alpha(1.0)
                time_text.color(viz.RED)
                time_text.setScale([1]*3)
                time_text.runAction(text_fade)
                viz.playSound('sounds/beep.wav')
            time_text.message(str(remain))
            last_remain = remain

        # Wait tenth of second
        yield viztask.waitTime(0.1)
Ejemplo n.º 30
0
def onCollide(e):
	#Did ball collide with a bumper?
	if e.obj2 in balls:
		#Change color of bumper
		e.obj1.color( random.choice( [viz.RED,viz.GREEN,viz.SKYBLUE,viz.YELLOW,viz.ORANGE,viz.PURPLE] ) )
		#Play sound at a volume appropriate for ball speed
		speed = viz.Vector( e.obj2.getVelocity() ).length()
		if speed > .7:
			viz.playSound( 'crashNew.wav' )
		elif speed > .4:
			viz.playSound( 'crashQuiet.wav' )
		elif speed > .1:
			viz.playSound( 'crashVeryQuiet.wav' )
Ejemplo n.º 31
0
    def onTimer(self, num):
        for i in range(0, len(self.ballList)):
            if self.ballList[i].x + self.ballList[i].radius >= 100:
                self.ballList[i].vx = abs(self.ballList[i].vx) * -1
                if not self.mute:
                    viz.playSound('bounce.wav')
            elif self.ballList[i].x - self.ballList[i].radius <= -100:
                self.ballList[i].vx = abs(self.ballList[i].vx)
                if not self.mute:
                    viz.playSound('bounce.wav')
            elif self.ballList[i].y + self.ballList[i].radius >= 100:
                self.ballList[i].vy = abs(self.ballList[i].vy) * -1
                if not self.mute:
                    viz.playSound('bounce.wav')
            elif self.ballList[i].y - self.ballList[i].radius <= -100:
                self.ballList[i].vy = abs(self.ballList[i].vy)
                if not self.mute:
                    viz.playSound('bounce.wav')

            self.ballList[i].x += self.ballList[i].vx
            self.ballList[i].y += self.ballList[i].vy

            self.ballList[i].setXY(self.ballList[i].x, self.ballList[i].y)
def timer3():
	viz.playSound('boing!.wav')
	a=viz.tick()
	global timer2
	timer2=viz.tick()
Ejemplo n.º 33
0
    def onKeyDown(self, key):
        if (key == viz.KEY_LEFT):
            # turn self.avatar ccw, as viewed from above
            self.ship.yrot -= 2
            self.theta -= 2
        elif (key == viz.KEY_RIGHT):
            # turn self.avatar cw, as viewed from above
            self.ship.yrot += 2
            self.theta += 2
        elif (key == viz.KEY_UP):
            # move avatar forward
            dx = 0.2 * math.sin(math.radians(self.theta))
            dz = 0.2 * math.cos(math.radians(self.theta))
            self.ship.x = self.ship.x + dx
            self.ship.z = self.ship.z + dz
            self.x = self.x + dx
            self.z = self.z + dz
        elif (key == viz.KEY_DOWN):
            # increase the velocity of the ball
            dx = 0.2 * math.sin(math.radians(self.theta))
            dz = 0.2 * math.cos(math.radians(self.theta))
            self.ship.x = self.ship.x - dx
            self.ship.z = self.ship.z - dz
            self.x = self.x - dx
            self.z = self.z - dz

        elif (key == "1"):
            self.start.remove()

            pic = viz.addTexture('snow.jpg')
            # Create surface to wrap the texture on
            self.snow = viz.addTexQuad()
            mat = viz.Matrix()
            mat.postScale(1.995, 1.5, 1.5)
            self.snow.setMatrix(mat)
            self.snow.setPosition([0, 0, 0])  #put quad in view
            # Wrap texture on quad
            self.snow.texture(pic)
            self.mylight.color(.3, .3, .3)
            view = viz.MainView
            mat = viz.Matrix()
            mat.postTrans(0, 0, -1.9)
            view.setMatrix(mat)
            self.t1.remove()
            self.t.remove()
            self.t = viz.addText("Score:" + "" + ` self.score `,
                                 viz.SCREEN,
                                 pos=[0, 0, 0])
            self.t.fontSize(100)
            self.t.font('Chiller')
            self.t1 = viz.addText("Lives:" + "" + ` self.life `,
                                  viz.SCREEN,
                                  pos=[0.8, 0, 0])
            self.t1.fontSize(100)
            self.t1.font('Chiller')

        elif (key == "2"):
            viz.playSound('soundtrack.wav')
            self.mode = "firstperson"

        elif key == 'w':
            if self.deskPressed:
                self.desk.setOrientation(self.desk.getX(), self.desk.getY(),
                                         self.desk.getZ() + 1, 1, 90)
            elif self.shelfPressed:
                self.shelf.setOrientation(self.shelf.getX(), self.shelf.getY(),
                                          self.shelf.getZ() + 1, 1, 0)
        elif key == 'a':
            if self.deskPressed:
                self.desk.setOrientation(self.desk.getX() - 1,
                                         self.desk.getY(), self.desk.getZ(), 1,
                                         90)
            elif self.shelfPressed:
                self.shelf.setOrientation(self.shelf.getX() - 1,
                                          self.shelf.getY(), self.shelf.getZ(),
                                          1, 0)
        elif key == 's':
            if self.deskPressed:
                self.desk.setOrientation(self.desk.getX(), self.desk.getY(),
                                         self.desk.getZ() - 1, 1, 90)
            elif self.shelfPressed:
                self.shelf.setOrientation(self.shelf.getX(), self.shelf.getY(),
                                          self.shelf.getZ() - 1, 1, 0)
        elif key == 'd':
            if self.deskPressed:
                self.desk.setOrientation(self.desk.getX() + 1,
                                         self.desk.getY(), self.desk.getZ(), 1,
                                         90)
            elif self.shelfPressed:
                self.shelf.setOrientation(self.shelf.getX() + 1,
                                          self.shelf.getY(), self.shelf.getZ(),
                                          1, 0)

        elif (key == " "):
            if self.life > 0:
                self.boolean = True
                self.bullet = vizshape.addSphere(radius=.07, color=viz.BLACK)
                mat = viz.Matrix()
                mat.postTrans(self.ship.getX(), self.ship.getY(),
                              self.bZ + 0.05)
                self.bullet.setMatrix(mat)
                self.bullet.collideSphere(bounce=3)
                self.bullet.enable(viz.COLLIDE_NOTIFY)
                self.bullet.setVelocity([0, 0, 5])

        elif (key == viz.KEY_RETURN):
            if self.tower == 1:
                self.snow.remove()
                view = viz.MainView
                mat = viz.Matrix()
                mat.postAxisAngle(1, 0, 0, 30)
                mat.postTrans(4.5, 3.5, .5)
                view.setMatrix(mat)
                viz.playSound('start.wav')
            elif self.tower == 2:
                self.egypt.remove()
                view = viz.MainView
                mat = viz.Matrix()
                mat.postAxisAngle(1, 0, 0, 30)
                mat.postTrans(4.5, 3.5, 7.5)
                view.setMatrix(mat)
                viz.playSound('start.wav')
            elif self.tower == 3:
                self.city.remove()
                view = viz.MainView
                mat = viz.Matrix()
                mat.postAxisAngle(1, 0, 0, 30)
                mat.postTrans(13.5, 3.5, 7.5)
                view.setMatrix(mat)
                viz.playSound('start.wav')
            elif self.tower == 4:
                self.forest7.remove()
                view = viz.MainView
                mat = viz.Matrix()
                mat.postAxisAngle(1, 0, 0, 30)
                mat.postTrans(13.5, 3.5, 0.5)
                view.setMatrix(mat)
                viz.playSound('start.wav')

        if (self.mode == "firstperson"):
            self.start.remove()
            self.mylight.color(.7, .7, .7)
            dx = 0.1 * math.sin(math.radians(self.theta))
            dz = 0.1 * math.cos(math.radians(self.theta))
            view = viz.MainView
            mat = viz.Matrix()
            mat.postAxisAngle(0, 1, 0, self.theta)
            mat.postTrans(self.x, self.y, self.z + 0.15)
            view.setMatrix(mat)
            self.ship.setOrientation(4.5, -17, 4, 0.06, 180)
        self.ship.setTransMatrix()
Ejemplo n.º 34
0
def run(CL, tracks, grounds, backgrounds, cave, driver, autofiles, wheel, save_prefix):
	
	DEBUG = False
	
	trialtime = tracks[list(tracks.keys())[0]].trialtime	
	if DEBUG: trialtime = 6
		
	wait_texture = setStage('dusk.png')	
	wait_col = list(np.mean(np.array([viz.BLACK,viz.SKYBLUE]).T, axis = 1))	
	
		
	#add audio files
	manual_audio = 'C:\\VENLAB data\\shared_modules\\textures\\490_200ms.wav'
	viz.playSound(manual_audio, viz.SOUND_PRELOAD)	
	def SingleBeep():
		"""play single beep"""
		viz.playSound(manual_audio)
	"""
	datacolumns = ('autofile_i','bend','maxyr',
	'onsettime','ppid','trialn','block','timestamp_exp','timestamp_trial',
	'world_x','world_z','world_yaw','swa', 
	'yawrate_seconds','turnangle_frames',
	'distance_frames','dt','wheelcorrection', 
	'steeringbias', 'autoflag', 'autofile')
	"""
	"""
			UpdateValues = []
		UpdateValues.append(yawrate)
		UpdateValues.append(turnangle)
		UpdateValues.append(distance)
		UpdateValues.append(dt)
		UpdateValues.append(SteeringWheelValue)
		UpdateValues.append(self.__Wheel_yawrate_adjustment)
	"""
	
	expid, ppid, block = save_prefix.split('_')
	columns = ('ppid','block','world_x','world_z','world_yaw','timestamp_exp','timestamp_trial','maxyr', 'onsettime', 'bend','dn','autoflag','yr_sec','yr_frames','distance_frames','dt','sw_value','wheelcorrection','sw_angle')	
	
	def update(num):		
		
		
		if UPDATE:
			
			trialtimer = viz.tick() - trialstart	
			if DEBUG: txtmode.message(str(onset) +'\n' + str(yr) + '\n' + str(round(trialtimer,2)))
			
			if AUTOFLAG:
				
				#read the corresponding entry on the playback_data
				if trialtimer <= onset:
					i, auto_row = next(playback_iter)
					#print(i, auto_row)
					dir = auto_row.bend							
					new_swa = auto_row.swa * dir * bend #these columns are named slightly differently to the final experiment data
					new_yr = auto_row.yr * dir * bend
					
					#move the wheel.									
					wheel.set_position(new_swa)	#set steering wheel to 							
				else:
					#driver.setAutomation(False)
					new_yr = 0 #off-tangent failure
			
			else:
				new_yr = None					
			
			#update position
			updatevals = driver.UpdateView(new_yr) 
			#return the values used in position update			
				
				
				#retrieve position and orientation
			pos = cave.getPosition()							
			yaw = vizmat.NormAngle(cave.getEuler()[0])			
						
			#record data	
			#columns = ('ppid', 'block','world_x','world_z','world_yaw','timestamp_exp','timestamp_trial','maxyr', 'onsettime', 'bend','dn','autoflag','yr_sec','yr_frames','distance_frames','dt','sw_value','wheelcorrection','sw_angle')	
			output = (ppid, block, pos[0], pos[2], yaw, viz.tick(), trialtimer, yr, onset, bend, dn, int(AUTOFLAG), updatevals[0], updatevals[1],updatevals[2], updatevals[3],updatevals[4],updatevals[5], updatevals[4]*90) #output array			
				
			#print(output)
		
			#self.OutputWriter.loc[self.Current_RowIndex,:] = output #this dataframe is actually just one line. 		
			OutputWriter.writerow(output)  #output to csv. any quicker?
			
	
	#call update every frame
	UPDATE = False
	
	viz.callback(viz.TIMER_EVENT, update)
	viz.starttimer(0,1.0/60.0,viz.FOREVER)
	
		
	txtmode = viz.addText("Mode",parent=viz.SCREEN)	
	#set above skyline so I can easily filter glances to the letter out of the data
	txtmode.setPosition(.05,.52)
	txtmode.fontSize(36)
	txtmode.color(viz.WHITE)	

	if not DEBUG: txtmode.message('A')
		
	print(CL)	
		
	for trial_i, (idx, trial) in enumerate(CL.iterrows()):
		
		#reset key trial variables 
		trialstart = viz.tick()
		AUTOFLAG = True
		driver.setAutomation(AUTOFLAG)
		
		#set up dataframe and csv writer
		OutputFile = io.BytesIO()
		OutputWriter = csv.writer(OutputFile)
		OutputWriter.writerow(columns) #write headers.
		
		bend = int(trial['Bend'])
		yr = trial['maxYR']
		dn = trial['Day/Night']
		onset = trial['OnsetTime']		
		key = str(bend)+'_'+str(yr)+'_' + dn
		#retrieve playback
		playback = autofiles[str(yr)]
		playback_iter = playback.iterrows()
		
		
		
		#only switch on update loop after retrieving parameters
		
		
		#pick track and make visible
		track = tracks[key]
		track.ToggleVisibility(1)
		
		ground = grounds[dn]
		ground.visible(viz.ON)
		
		viz.clearcolor(backgrounds[dn])
		if trial_i == 0:
			yield viztask.waitTime(2)
		else:
			yield viztask.waitTime(.5)
		
		
		#start the trial proper
		UPDATE = True
		
		#run trial
		def PlaybackReached():
			"""checks for playback limit or whether automation has been disengaged"""
			end = False
			#print(viz.tick() - trialstart)
			if (viz.tick() - trialstart) > trialtime: end = True
			return(end)
		
		def CheckDisengage():
			"""checks automation status of driver class """
			end = False
			auto = driver.getAutomation()
			if auto == False:end = True				
			return (end)

		#create viztask functions.
		waitPlayback = viztask.waitTrue( PlaybackReached )
		waitDisengage = viztask.waitTrue( CheckDisengage )
		
		d = yield viztask.waitAny( [ waitPlayback, waitDisengage ] )		

		if d.condition is waitPlayback:
			print ('end of trial reached')
			
		elif d.condition is waitDisengage:
			print ('Automation Disengaged')
			if not DEBUG: txtmode.message('M')
			
			AUTOFLAG = False				
			wheel.FF_on(.2)				
			SingleBeep()
			yield viztask.waitTime(trialtime - (viz.tick()-trialstart))
			
		#END OF STEERING TASK
		
		#reset trial
		track.ToggleVisibility(0)
		ground.visible(viz.OFF)
		driver.reset()
		wait_texture.visible(1)
		viz.clearcolor(wait_col)
		UPDATE = False
		if not DEBUG: txtmode.message('A')
		
		yield viztask.waitTime(.5)
		wait_texture.visible(0)
		UPDATE = True
		
		savename = save_prefix +'_'+str(trial_i)
		SaveData(OutputFile, savename)
	
	
	CloseConnections(wheel)
Ejemplo n.º 35
0
	def SingleBeep():
		"""play single beep"""
		viz.playSound(manual_audio)
Ejemplo n.º 36
0
#viz_matrix is a module that contains all the arrays for the control arrays we will use. 
import viz_matrix

# Vizconnect
import vizconnect
import vizconnect_config



#General screen setup. 
viz.setMultiSample(4)
viz.fov(60)

#Sometimes, the first "start" sound does not work. The second time, it always works, therefore, I have the start sound
#play when the program starts. This way, there is no chance of the sound not working when the experiment starts. 
viz.playSound('boing!.wav')

"""In viz_matrix, we have many arrays of possible orders of box lengths. Each has a distinct identifiying number, called
 a 'matrix id.' By knowing this in advance, the user inputs the matrix id when the program starts, and the viz_matrix
program will find the respective matrix for the trials.""" 
matrix_id=vizinput.input('Input Matrix ID Number:\n ')
#throughout the program, you may see "prints." This is only seen in the interactive window, and is used only for debugging
#the subject does not see any of the printed messages during experimentation. 
print('matrix_id'+ str(matrix_id))


#our control_array is the array that we have chosen when typing in the matrx_id
control_array=viz_matrix.matrix_controller(matrix_id)
#x is the length of the control array. our program acts differently based on the size of x. in other words,
# there are many conditional trees that are dependant on the size of x. 
x=len(control_array)
Ejemplo n.º 37
0
    def spawnAliens(self):
        # Spawns 3x6 aliens

        print("LEVEL: " + str(self.level))
        if self.level % 6 == 0:  #Spawns a boss at every sixth level
            self.boss = Alien('green',
                              model=self.firstGreen.clone(),
                              hp=self.power * 6)
            self.boss.setPosition(0, 0, 1, scale=.0025 * 3)
            self.speed = 1 / (self.power / 2)
            viz.playSound('bossSpawn.wav')
        elif not self.pause:
            x = -.6
            #Spawns a 3x6 wave of aliens, each alien spawn is random
            for i in range(0, 6):
                num = random.randint(0, 3)
                if num == 0:
                    self.aliens[i] = Alien('blue',
                                           model=self.firstBlue.clone(),
                                           hp=3)
                elif num == 1:
                    self.aliens[i] = Alien('red', model=self.firstRed.clone())
                elif num == 2:
                    self.aliens[i] = Alien('purple',
                                           model=self.firstPurple.clone(),
                                           hp=3)
                elif num == 3:
                    self.aliens[i] = Alien('orange',
                                           model=self.firstOrange.clone(),
                                           hp=2)
                self.aliens[i].setPosition(x, 0, 1)
                x += .25

            x = -.6
            for i in range(6, 12):
                num = random.randint(0, 3)
                if num == 0:
                    self.aliens[i] = Alien('blue',
                                           model=self.firstBlue.clone(),
                                           hp=3)
                elif num == 1:
                    self.aliens[i] = Alien('red', model=self.firstRed.clone())
                elif num == 2:
                    self.aliens[i] = Alien('purple',
                                           model=self.firstPurple.clone(),
                                           hp=3)
                elif num == 3:
                    self.aliens[i] = Alien('orange',
                                           model=self.firstOrange.clone(),
                                           hp=2)
                self.aliens[i].setPosition(x, 0, .75)
                x += .25

            x = -.6
            for i in range(12, 18):
                num = random.randint(0, 3)
                if num == 0:
                    self.aliens[i] = Alien('blue',
                                           model=self.firstBlue.clone(),
                                           hp=3)
                elif num == 1:
                    self.aliens[i] = Alien('red', model=self.firstRed.clone())
                elif num == 2:
                    self.aliens[i] = Alien('purple',
                                           model=self.firstPurple.clone(),
                                           hp=3)
                elif num == 3:
                    self.aliens[i] = Alien('orange',
                                           model=self.firstOrange.clone(),
                                           hp=2)
                self.aliens[i].setPosition(x, 0, .5)
                x += .25
            viz.playSound('newWave.wav')
Ejemplo n.º 38
0
SS_CURRENTLY_FLYING = 2
SS_CURRENTLY_LANDED = 3
SS_CURRENTLY_PAUSED = 4
SS_CURRENTLY_PULLED_TOWARDS_CHILD = 5
SS_CURRENTLY_LANDED_AT_CHILD = 6

#The different helicopter models
HELI_MODEL1 = 'passenger cockpit'
HELI_MODEL2 = 'cockpit2'
HELI_MODEL = HELI_MODEL2

# City Model: see CityModel.py for reference
cityModel = CityModel()

#Sounds to play on building collisions
CRASH_SOUND = viz.playSound('BuildingCrashSound.wav', viz.SOUND_PRELOAD)

BirdEyeWindow = viz.addWindow()
BirdEyeWindow.fov(60)
BirdEyeWindow.visible(0,viz.SCREEN)
BirdEyeView = viz.addView()
BirdEyeWindow.setView(BirdEyeView)
BirdEyeWindow.setPosition([0,25,0])
BirdEyeView.setEuler([0,90,0])

###User tracking with lines###
viz.startLayer(viz.LINE_STRIP)
viz.vertexColor(viz.YELLOW)
lines = viz.endLayer(parent=viz.ORTHO,scene=BirdEyeWindow)

lines.dynamic()
select.disable( viz.DYNAMICS )
select.disable( viz.COLLIDE_NOTIFY )

#Set the position of the selection
def RandomSelection():
	x_factor = random.randint(1, MULTIPLE)
	y_factor = random.randint(1, MULTIPLE)
	z_factor = random.randint(1, MULTIPLE)
	X_DISP = (x_factor/MULTIPLE)*(X_MAX - X_MIN)
	Y_DISP = (y_factor/MULTIPLE)*(Y_MAX - Y_MIN)
	Z_DISP = (z_factor/MULTIPLE)*(Z_MAX - Z_MIN)
	select.setPosition(X_MIN + X_DISP, Y_MIN + Y_DISP, Z_MIN + Z_DISP)
	select.setEuler([0,0,0])

globalSelected = 0
viz.playSound('Full_Body_Bip001\water-splash-2.wav',viz.SOUND_PRELOAD)
#Called when two objects collide in the physics simulator
def onCollide(e):
	if e.obj1 is select:
		viz.playSound('Full_Body_Bip001\water-splash-2.wav')
		global globalSelected
		globalSelected += 1
		RandomSelection()
	
viz.callback( viz.COLLIDE_BEGIN_EVENT, onCollide )

#Set up activity sounds
viz.playSound('Full_Body_Bip001/fire3.wav',viz.SOUND_PRELOAD)
viz.playSound('Full_Body_Bip001/fire_siren_horn.wav',viz.SOUND_PRELOAD)

#Results after completion of activity
Ejemplo n.º 40
0
vizact.onkeydown(' ',dropBall)

#Move ballDropper
vizact.whilekeydown(viz.KEY_UP,ballDropper.setPosition,[0,vizact.elapsed(1),0],viz.REL_PARENT)
vizact.whilekeydown(viz.KEY_DOWN,ballDropper.setPosition,[0,vizact.elapsed(-1),0],viz.REL_PARENT)
vizact.whilekeydown(viz.KEY_RIGHT,ballDropper.setPosition,[vizact.elapsed(1),0,0],viz.REL_PARENT)
vizact.whilekeydown(viz.KEY_LEFT,ballDropper.setPosition,[vizact.elapsed(-1),0,0],viz.REL_PARENT)

#Called when two objects collide in the physics simulator
def onCollide(e):
	#Did ball collide with a bumper?
	if e.obj2 in balls:
		#Change color of bumper
		e.obj1.color( random.choice( [viz.RED,viz.GREEN,viz.SKYBLUE,viz.YELLOW,viz.ORANGE,viz.PURPLE] ) )
		#Play sound at a volume appropriate for ball speed
		speed = viz.Vector( e.obj2.getVelocity() ).length()
		if speed > .7:
			viz.playSound( 'crashNew.wav' )
		elif speed > .4:
			viz.playSound( 'crashQuiet.wav' )
		elif speed > .1:
			viz.playSound( 'crashVeryQuiet.wav' )

viz.callback( viz.COLLIDE_BEGIN_EVENT, onCollide )

# Preload sound files
viz.playSound('crashNew.wav',viz.SOUND_PRELOAD)
viz.playSound('crashQuiet.wav',viz.SOUND_PRELOAD)
viz.playSound('crashVeryQuiet.wav',viz.SOUND_PRELOAD)
Ejemplo n.º 41
0
def playName(boneObj):
	"""Play audio with the same name as the bone"""
	try:
		viz.playSound(path + "audio_names\\" + boneObj.name + ".wav") # should be updated to path
	except ValueError:
		print ("the name of the audio name file was wrong")
Ejemplo n.º 42
0
	def snapCheck(self):
		"""
		Snap checks for any nearby bones, and mates a src bone to a dst bone
		if they are in fact correctly placed.
		"""
		for bb in self._boundingBoxes.values():
			if bb.getAction():
				return
			for m in bb._members:
				if m.getAction():
					return
		
		snapped = False
		
		if not self.getSnapSource():
			print 'nothing to snap'
			return

		
		if isinstance(self.getSnapSource(), bp3d.Mesh):
			SNAP_THRESHOLD		= 0.2; #how far apart the mesh you are snapping is from where it should be
			DISTANCE_THRESHOLD	= 0.75; #distance source mesh is from other meshes
			ANGLE_THRESHOLD		= 45.0; #min euler difference source mesh can be from target mesh
			sourceMesh		= self.getSnapSource()
			searchMeshes	= self.getSnapSearch(source = sourceMesh)
			targetMesh		= self.keyTarget
			
			self.moveCheckers(sourceMesh)
				
			# Search through all of the checkers, and snap to the first one meeting our snap
			# criteria
			
			if sourceMesh.snapAttempts >= 3 and not sourceMesh.group.grounded:
				self.snap(sourceMesh, self.keyTarget, children = True)
				viz.playSound(".\\dataset\\snap.wav")
				print 'Three unsuccessful snap attempts, snapping now!'
				self.score.event(event = 'autosnap', description = 'Three unsuccessful snap attempts, snapping now!', \
					source = sourceMesh.name, destination = targetMesh.name)
#				self._snapAttempts = 0
				if self.modeName == 'testplay':
					self.pickSnapPair()
					
			elif sourceMesh.group.grounded:
				print 'That object is grounded. Returning!'
				
			else:
				for bone in [b for b in searchMeshes if b not in sourceMesh.group.members]:
					targetSnap = bone.checker.getPosition(viz.ABS_GLOBAL)
					targetPosition = bone.getPosition(viz.ABS_GLOBAL)
					targetQuat = bone.getQuat(viz.ABS_GLOBAL)
					
					currentPosition = sourceMesh.getPosition(viz.ABS_GLOBAL)
					currentQuat = sourceMesh.getQuat(viz.ABS_GLOBAL)		
					
					snapDistance = vizmat.Distance(targetSnap, currentPosition)
					proximityDistance = vizmat.Distance(targetPosition, currentPosition)
					angleDifference = vizmat.QuatDiff(bone.getQuat(viz.ABS_GLOBAL), sourceMesh.getQuat(viz.ABS_GLOBAL))
					
					if (snapDistance <= SNAP_THRESHOLD) and (proximityDistance <= DISTANCE_THRESHOLD) \
							and (abs(angleDifference) < ANGLE_THRESHOLD):
						print 'Snap! ', sourceMesh, ' to ', bone
						self.score.event(event = 'snap', description = 'Successful snap', source = sourceMesh.name, destination = bone.name)
						viz.playSound(".\\dataset\\snap.wav")
						self.snap(sourceMesh, bone, children = True)
						snapped = True
						if self.modeName == 'testplay':
							self.pickSnapPair()
						break
				if not snapped:
					print 'Did not meet snap criteria!'
					sourceMesh.snapAttempts += 1
					self.score.event(event = 'snapfail', description = 'did not meet snap criteria', source = sourceMesh.name)
				self.printNoticeable('snap attempts: ' + str(sourceMesh.snapAttempts))
						
			if len(self._lastBoxGrabbed._keystones) == len(self._lastBoxGrabbed._members):
				self.score.event(event = 'Finished Region', description = self._lastMeshGrabbed.region + ' was finished')
				self.printNoticeable('Finished Region!!')
				self._boundingBoxes[sourceMesh.region].finishedRegion = True
				
				# If all regions in a region group are finished than show all members
				self._lastBoxGrabbed.regionGroup.getFinished()
				if self._lastBoxGrabbed.regionGroup.allRegionsFinished:
					for bb in self._lastBoxGrabbed.regionGroup.members:
						bb.showMembers(True)
			if len(self._meshes) == len(sourceMesh.group.members):
				print "Assembly completed!"
				self.end()
				model.menu.endGame()
				
					
		elif isinstance(self.getSnapSource(), BoundingBox):
			SNAP_THRESHOLD		= 1.5; #how far apart the mesh you are snapping is from where it should be
			ANGLE_THRESHOLD		= 45.0; #min euler difference source mesh can be from target mesh
			
			#If lastGrabbed is a bounding box carry out this snap check procedure...
			sourceBB = self.getSnapSource()
			
			# Find closest bounding box
			targetBB, distance = sourceBB.findClosestBB(self._boundingBoxes.values())
			
			# Find Target Position and Euler for the Source BB
			tPos, tEuler = sourceBB.moveChecker(targetBB)
			
			# If the Source is close enough to the target position and euler then snap
			eulerDiff = vizmat.QuatDiff(targetBB.checker.getQuat(viz.ABS_GLOBAL), sourceBB.getQuat(viz.ABS_GLOBAL))
			if distance <= SNAP_THRESHOLD and abs(eulerDiff) <= ANGLE_THRESHOLD:
				sourceBB.snapToBB(targetBB)
			
			self._lastBoxGrabbed.regionGroup.getFinished()
			if self._lastBoxGrabbed.regionGroup.allRegionsFinished:
				for bb in self._lastBoxGrabbed.regionGroup.members:
						bb.showMembers(True)
def ShowResults():
	select.disable( viz.RENDERING )
	select.disable( viz.COLLIDE_NOTIFY )
	viz.playSound('Full_Body_Bip001/fire3.wav',viz.STOP)
	global globalSelected
	viz.message( 'Great Job!\nYou put out {0:d} fires in 30 seconds!'.format(globalSelected) )
def onCollide(e):
	if e.obj1 is select:
		viz.playSound('Full_Body_Bip001\water-splash-2.wav')
		global globalSelected
		globalSelected += 1
		RandomSelection()
Ejemplo n.º 45
0
	def snapCheck(self):
		"""
		Snap checks for any nearby bones, and mates a src bone to a dst bone
		if they are in fact correctly placed.
		"""
		if not self.getSnapSource():
			print 'nothing to snap'
			return

		SNAP_THRESHOLD	= 0.5;
		DISTANCE_THRESHOLD = 1.5;
		ANGLE_THRESHOLD	= 45;
		sourceMesh		= self.getSnapSource()
		targetMesh		= self.getSnapTarget()
		searchMeshes	= self.getSnapSearch()
		
		self.moveCheckers(sourceMesh)
			
		# Search through all of the checkers, and snap to the first one meeting our snap
		# criteria
		
		if self._snapAttempts >= 3 and not sourceMesh.group.grounded:
			self.snap(sourceMesh, targetMesh, children = True)
			viz.playSound(".\\dataset\\snap.wav")
			print 'Three unsuccessful snap attempts, snapping now!'
			self.score.event(event = 'autosnap', description = 'Three unsuccessful snap attempts, snapping now!', \
				source = sourceMesh.name, destination = targetMesh.name)
			self._snapAttempts = 0
			if self.modeName == 'testplay':
				self.pickSnapPair()
		elif sourceMesh.group.grounded:
			print 'That object is grounded. Returning!'
		else:
			for bone in [b for b in searchMeshes if b not in sourceMesh.group.members]:
				targetSnap = bone.checker.getPosition(viz.ABS_GLOBAL)
				targetPosition = bone.getPosition(viz.ABS_GLOBAL)
				targetQuat = bone.getQuat(viz.ABS_GLOBAL)
				
				currentPosition = sourceMesh.getPosition(viz.ABS_GLOBAL)
				currentQuat = sourceMesh.getQuat(viz.ABS_GLOBAL)		
				
				snapDistance = vizmat.Distance(targetSnap, currentPosition)
				proximityDistance = vizmat.Distance(targetPosition, currentPosition)
				angleDifference = vizmat.QuatDiff(bone.getQuat(), sourceMesh.getQuat())
				
				if (snapDistance <= SNAP_THRESHOLD) and (proximityDistance <= DISTANCE_THRESHOLD) \
						and (angleDifference < ANGLE_THRESHOLD):
					print 'Snap! ', sourceMesh, ' to ', bone
					self.score.event(event = 'snap', description = 'Successful snap', source = sourceMesh.name, destination = bone.name)
					viz.playSound(".\\dataset\\snap.wav")
					self.snap(sourceMesh, bone, children = True)
					if self.modeName == 'testplay':
						self.pickSnapPair()
					break
			else:
				print 'Did not meet snap criteria!'
				self._snapAttempts += 1
				self.score.event(event = 'snapfail', description = 'did not meet snap criteria', source = sourceMesh.name)
		if len(self._meshes) == len(sourceMesh.group.members):
			print "Assembly completed!"
			end()
			menu.ingame.endButton()
Ejemplo n.º 46
0
    def onCollideBegin(self, e):
        if (e.obj1 == self.cyl1) and self.cyl1hei >= -7.6 and self.tower == 1:
            self.cyl1hei -= 0.2
            mat = viz.Matrix()
            mat.postTrans(0, self.cyl1hei, 0)
            self.cyl1.setMatrix(mat)
            self.score += 2
            self.t.remove()
            self.t = viz.addText("Score:" + "" + ` self.score `,
                                 viz.SCREEN,
                                 pos=[0, 0, 0])
            self.t.fontSize(100)
            self.t.font('Chiller')
            e.obj2.remove()
            if (self.cyl1hei <= -7.6) and self.tower == 1:
                self.cyl1hei = 0
                self.ship.move(4.5, .7, 11, 5)
                self.ship.setOrientation(4.5, .7, 11, 0.06, 180)
                self.bZ = self.ship.getZ() + 0.05
                self.tower = 2
                viz.playSound('level.wav')
                view = viz.MainView
                mat = viz.Matrix()
                mat.postTrans(0, 0, -1.9)
                view.setMatrix(mat)
                pic = viz.addTexture('egypt.jpg')
                # Create surface to wrap the texture on
                self.egypt = viz.addTexQuad()
                mat = viz.Matrix()
                mat.postScale(1.995, 1.5, 1.5)
                self.egypt.setMatrix(mat)
                self.egypt.setPosition([0, 0, 0])  #put quad in view
                # Wrap texture on quad
                self.egypt.texture(pic)
                mat = viz.Matrix()
                mat.postTrans(0, self.cyl1hei, 0)
                self.cyl1.setMatrix(mat)

        elif (e.obj1
              == self.cyl2) and self.cyl1hei >= -7.6 and self.tower == 2:
            self.cyl1hei -= 0.2
            mat = viz.Matrix()
            mat.postTrans(0, self.cyl1hei, 0)
            self.cyl2.setMatrix(mat)
            self.score += 2
            self.t.remove()
            self.t = viz.addText("Score:" + "" + ` self.score `,
                                 viz.SCREEN,
                                 pos=[0, 0, 0])
            self.t.fontSize(100)
            self.t.font('Chiller')
            e.obj2.remove()
            if (self.cyl1hei <= -7.6) and self.tower == 2:
                self.cyl1hei = 0
                self.ship.move(13.5, .7, 11, 5)
                self.ship.setOrientation(13.5, .7, 11, 0.06, 180)
                self.bZ = self.ship.getZ() + 0.05
                self.tower = 3
                viz.playSound('level.wav')
                view = viz.MainView
                mat = viz.Matrix()
                mat.postTrans(0, 0, -1.9)
                view.setMatrix(mat)
                pic = viz.addTexture('city.jpg')
                # Create surface to wrap the texture on
                self.city = viz.addTexQuad()
                mat = viz.Matrix()
                mat.postScale(1.995, 1.5, 1.5)
                self.city.setMatrix(mat)
                self.city.setPosition([0, 0, 0])  #put quad in view
                # Wrap texture on quad
                self.city.texture(pic)
                mat = viz.Matrix()
                mat.postTrans(0, self.cyl1hei, 0)
                self.cyl2.setMatrix(mat)

        elif (e.obj1
              == self.cyl3) and self.cyl1hei >= -7.6 and self.tower == 3:
            self.cyl1hei -= 0.2
            mat = viz.Matrix()
            mat.postTrans(0, self.cyl1hei, 0)
            self.cyl3.setMatrix(mat)
            self.score += 2
            self.t.remove()
            self.t = viz.addText("Score:" + "" + ` self.score `,
                                 viz.SCREEN,
                                 pos=[0, 0, 0])
            self.t.fontSize(100)
            self.t.font('Chiller')
            e.obj2.remove()
            if (self.cyl1hei <= -7.6) and self.tower == 3:
                self.cyl1hei = 0
                self.ship.move(13.5, .7, 4, 5)
                self.ship.setOrientation(13.5, .7, 4, 0.06, 180)
                self.bZ = self.ship.getZ() + 0.05
                self.tower = 4
                viz.playSound('level.wav')
                view = viz.MainView
                mat = viz.Matrix()
                mat.postTrans(0, 0, -1.9)
                view.setMatrix(mat)
                pic = viz.addTexture('forest.jpg')
                # Create surface to wrap the texture on
                self.forest7 = viz.addTexQuad()
                mat = viz.Matrix()
                mat.postScale(1.995, 1.5, 1.5)
                self.forest7.setMatrix(mat)
                self.forest7.setPosition([0, 0, 0])  #put quad in view
                # Wrap texture on quad
                self.forest7.texture(pic)
                mat = viz.Matrix()
                mat.postTrans(0, self.cyl1hei, 0)
                self.cyl3.setMatrix(mat)

        elif (e.obj1
              == self.cyl4) and self.cyl1hei >= -7.6 and self.tower == 4:
            self.cyl1hei -= 0.2
            mat = viz.Matrix()
            mat.postTrans(0, self.cyl1hei, 0)
            self.cyl4.setMatrix(mat)
            self.score += 2
            self.t.remove()
            self.t = viz.addText("Score:" + "" + ` self.score `,
                                 viz.SCREEN,
                                 pos=[0, 0, 0])
            self.t.fontSize(100)
            self.t.font('Chiller')
            e.obj2.remove()
            if (self.cyl1hei <= -7.6) and self.tower == 4:
                self.cyl1hei = 0
                self.ship.move(4.5, .7, 4, 5)
                self.ship.setOrientation(4.5, .7, 4, 0.06, 180)
                self.bZ = self.ship.getZ() + 0.05
                self.tower = 1
                viz.playSound('level.wav')
                view = viz.MainView
                mat = viz.Matrix()
                mat.postTrans(0, 0, -1.9)
                view.setMatrix(mat)
                pic = viz.addTexture('snow.jpg')
                # Create surface to wrap the texture on
                self.snow = viz.addTexQuad()
                mat = viz.Matrix()
                mat.postScale(1.995, 1.5, 1.5)
                self.snow.setMatrix(mat)
                self.snow.setPosition([0, 0, 0])  #put quad in view
                # Wrap texture on quad
                self.snow.texture(pic)
                mat = viz.Matrix()
                mat.postTrans(0, self.cyl1hei, 0)
                self.cyl4.setMatrix(mat)

        elif self.bullet!= None and ((e.obj1 == self.barricade11 and e.obj2 == self.bullet) \
         or (e.obj1 == self.barricade12 and e.obj2 == self.bullet) \
         or (e.obj1 == self.barricade13 and e.obj2 == self.bullet)\
         or (e.obj1 == self.barricade14 and e.obj2 == self.bullet) \
         or (e.obj1 == self.barricade21 and e.obj2 == self.bullet) \
         or (e.obj1 == self.barricade22 and e.obj2 == self.bullet) \
         or (e.obj1 == self.barricade23 and e.obj2 == self.bullet)\
         or (e.obj1 == self.barricade24 and e.obj2 == self.bullet) \
         or (e.obj1 == self.barricade31 and e.obj2 == self.bullet) \
         or (e.obj1 == self.barricade32 and e.obj2 == self.bullet) \
         or (e.obj1 == self.barricade33 and e.obj2 == self.bullet)\
         or (e.obj1 == self.barricade34 and e.obj2 == self.bullet) \
         or (e.obj1 == self.barricade41 and e.obj2 == self.bullet) \
         or (e.obj1 == self.barricade42 and e.obj2 == self.bullet) \
         or (e.obj1 == self.barricade43 and e.obj2 == self.bullet)\
         or (e.obj1 == self.barricade44 and e.obj2 == self.bullet)):
            self.t1.remove()
            viz.playSound('oof.wav')
            self.life -= 1
            self.t1 = viz.addText("Lives:" + "" + ` self.life `,
                                  viz.SCREEN,
                                  pos=[0.8, 0, 0])
            self.t1.fontSize(100)
            self.t1.font('Chiller')
            if self.life == 0:
                viz.playSound('over.wav')
                pic = viz.addTexture('end.png')
                # Create surface to wrap the texture on
                self.end = viz.addTexQuad()
                mat = viz.Matrix()
                mat.postScale(1.995, 1.5, 1.5)
                self.end.setMatrix(mat)
                self.end.setPosition([0, 0, 0])  #put quad in view
                # Wrap texture on quad
                self.end.texture(pic)
                view = viz.MainView
                mat = viz.Matrix()
                mat.postTrans(0, 0, -1.9)
                view.setMatrix(mat)
                self.t1.remove()
                self.t.remove()
                self.t2 = viz.addText("Final Score:" + ` self.score `,
                                      viz.SCREEN,
                                      pos=[0.18, 0.3, 0])
                self.t2.fontSize(200)
                self.t2.font('Chiller')


        elif self.bullet!= None and ((e.obj1 == self.barricade21 and e.obj2 == self.bullet) \
         or (e.obj1 == self.barricade22 and e.obj2 == self.bullet) \
         or (e.obj1 == self.barricade23 and e.obj2 == self.bullet)\
         or (e.obj1 == self.barricade24 and e.obj2 == self.bullet)):
            self.t1.remove()
            self.life -= 1
            self.t1 = viz.addText("Lives:" + "" + ` self.life `,
                                  viz.SCREEN,
                                  pos=[0.8, 0, 0])
            self.t1.fontSize(100)
            self.t1.font('Chiller')
Ejemplo n.º 47
0
			else:
				viz.playSound('sounds/pigeon_fly.wav')
				viztask.schedule(FadeToGrayTask())
				resultPanel.setText(TRIAL_FAIL)

			#Display success/failure message
			resultPanel.visible(True)

			# Add delay before starting next trial
			yield viztask.waitTime(TRIAL_DELAY)
			resultPanel.visible(False)

			# Disable gray effect
			gray_effect.setEnabled(False)
			viz.quit()


		#Display results and ask to quit or play again
		resultPanel.setText(RESULTS.format(score,TRIAL_COUNT))
		resultPanel.visible(True)
		yield viztask.waitKeyDown(' ')
		resultPanel.visible(False)

viztask.schedule( MainTask() )
vizact.ontimer(1, getData)


# Pre-load sounds
viz.playSound('sounds/beep.wav',viz.SOUND_PRELOAD)
viz.playSound('sounds/pigeon_fly.wav',viz.SOUND_PRELOAD)
viz.playSound('sounds/pigeon_catch.wav',viz.SOUND_PRELOAD)
Ejemplo n.º 48
0
	def onTimer(self, num):
		# Main game loop
		if num == 1:
			# Check for balls colliding with the window borders
			for i in range(0, len(self.ballList)):
				if self.ballList[i].x + self.ballList[i].radius >= 100:
					self.ballList[i].vx = abs(self.ballList[i].vx) * -1
					if not self.mute:
						viz.playSound(self.pickSound(1))
				elif self.ballList[i].x - self.ballList[i].radius <= -100:
					self.ballList[i].vx = abs(self.ballList[i].vx)
					if not self.mute:
						viz.playSound(self.pickSound(1))
				elif self.ballList[i].y + self.ballList[i].radius >= 100:
					self.ballList[i].vy = abs(self.ballList[i].vy) * -1
					if not self.mute:
						viz.playSound(self.pickSound(1))
				elif self.ballList[i].y <= -100 - self.ballList[i].radius:
					self.ballList.pop(i)
					self.ballsOnScreen -= 1
					# Shift all the blocks on screen down
					if self.ballsOnScreen == 0:
						for i in range (0, len(self.blockList)):
							localRow = self.blockList[i].getRow()
							localCol = self.blockList[i].getCol()
							self.blockPositions[localRow][localCol] = 0
							self.blockList[i].shiftDown()
							self.blockPositions[localRow + 1][localCol] = 1
							
							# Check if a block has reached the bottom of the window
							for z in range(0, len(self.blockList)):
								if self.blockList[z].getRow() == 9:
									self.failState = True
									# Prompt for restart or quit
									break
									print("You lost!")
									
						# Give the player another ball if they broke twice the amount of blocks as their number of balls
						if self.contactCount >= self.clickCount * 2:
							self.clickCount += 1
						self.contactCount = 0
						if not self.failState:
							self.addBlocks()
							self.roundCount += 1
					break
				# Check for balls colliding with blocks
				else:
					contact = False
					for j in range(0, len(self.blockList)):
						if self.blockList[j].contains(self.ballList[i].getX() + self.ballList[i].radius, self.ballList[i].getY()):
							self.ballList[i].vx = abs(self.ballList[i].vx) * -1
							contact = True
						elif self.blockList[j].contains(self.ballList[i].getX() - self.ballList[i].radius, self.ballList[i].getY()):
							self.ballList[i].vx = abs(self.ballList[i].vx)
							contact = True
						elif self.blockList[j].contains(self.ballList[i].getX(), self.ballList[i].getY() + self.ballList[i].radius):
							self.ballList[i].vy = abs(self.ballList[i].vy) * -1
							contact = True
						elif self.blockList[j].contains(self.ballList[i].getX(), self.ballList[i].getY() - self.ballList[i].radius):
							self.ballList[i].vy = abs(self.ballList[i].vy)
							contact = True
						
						# Remove block from position and block lists if hit
						if contact:
							self.contactCount += 1
							self.blockPositions[self.blockList[j].getRow()][self.blockList[j].getCol()] = 0
							self.blockList[j].vertices.remove()
							self.blockList.pop(j)
							viz.playSound(self.pickSound(2))
							break
		
				self.ballList[i].x += self.ballList[i].vx
				self.ballList[i].y += self.ballList[i].vy
		
				self.ballList[i].setXY(self.ballList[i].x, self.ballList[i].y)
		# Handle the pause between launching balls
		elif num == 2:
				ball = Ball(self.launcher.getAngle())
				ball.setXY(self.launcher.getX(), self.launcher.getY())
				self.ballList.append(ball)
				ball.setVXVY(ball.getVX() * self.worldMultiplier, ball.getVY() * self.worldMultiplier)
				self.ballsOnScreen += 1
				viz.playSound(self.pickSound(6))
		# Charge launcher
		elif num == 3:
			if self.charging:
				self.worldMultiplier += .25
				self.chargeCount += 1
				if self.chargeCount == 9:
					viz.playSound(self.pickSound(5))
					self.chargeCount = 0
				else:
					viz.playSound(self.pickSound(4))
		# Prompt player if they failed
		if self.failState:
			self.killtimer(1)
			response = vizinput.ask("You survived {} rounds. Play again?".format(self.roundCount))
			if response == 1:
				self.reset()
			else:
				viz.quit()
Ejemplo n.º 49
0
def MainTask():
    """Top level task that controls the game"""
    global won
    global manChase

    # Display instructions and wait for key press to continue
    yield DisplayInstructionsTask()

    yield manKicksBall()

    # Create panel to display trial results
    resultPanel = vizinfo.InfoPanel('',align=viz.ALIGN_CENTER,fontSize=25,icon=False,key=None)
    resultPanel.visible(False)

    resetManChase = False

    if manChase == True:
        resetManChase = True

    while True:

        # Randomly choose hiding spots from list
        locations = random.sample(HIDING_SPOTS,TRIAL_COUNT)

        # Reset score
        score = 0
        UpdateScore(score)

        # Go through each position
        for pos in locations:

            # Perform a trial
            found = yield TrialTask(pos)

            # Update score and display status text
            if found:
                viz.playSound('sounds/pigeon_catch.wav')
                score += 1
                UpdateScore(score)
                tracker.runAction(vizact.spinTo(point=pos,time=0.8,interpolate=vizact.easeOutStrong))
                resultPanel.setText(TRIAL_SUCCESS)
                won = True
                data = yield viztask.waitDirector(writeData)
            else:
                viz.playSound('sounds/pigeon_fly.wav')
                viztask.schedule(FadeToGrayTask())
                resultPanel.setText(TRIAL_FAIL)
                data = yield viztask.waitDirector(writeData)

            #allow for other animations for male2 while also ensuring
            #he chases the pigeon each round
            if resetManChase:
                manChase = True

            #Display success/failure message
            resultPanel.visible(True)

            # Add delay before starting next trial
            yield viztask.waitTime(TRIAL_DELAY)
            resultPanel.visible(False)

            # Disable gray effect
            gray_effect.setEnabled(False)

        #Display results and ask to quit or play again
        resultPanel.setText(RESULTS.format(score,TRIAL_COUNT))
        resultPanel.visible(True)
        yield viztask.waitKeyDown(' ')
        resultPanel.visible(False)
Ejemplo n.º 50
0
def timer3():
	viz.playSound('boing!.wav')
	a=viz.tick()
	global timer2
	timer2=viz.tick()
	sensor_data.write('\nSound goes off at this time'+ str(viz.tick()))
Ejemplo n.º 51
0
import vizact
import vizinfo
import viztask
import vizshape
import vizmat
import zmq, msgpack, time
from msgpack import loads
import numpy as np
import steamvr



# global parameters

gaze_marker_visible = True # True for debugging
beep = viz.playSound('beep500_200.wav', viz.SOUND_PRELOAD)

norm_positions = [
[.30, .70],#LT
[.70, .70],#RT
[.50, .50],#CC
[.30, .30],#LB
[.70, .30],#RB
[.30, .50],#LC
[.50, .30],#CB
[.70, .50],#RC
[.50, .70]]#CT

sphere_size = .015
depth = 2 # m
confidence_level = .2
Ejemplo n.º 52
0
def calibration():
	''' The heart of the calibration routine. Presents points and collects data. '''


	# start calibration routine and sample data
	n = {'subject':'calibration.should_start', 'hmd_video_frame_size':(2160,1200), 'outlier_threshold':35}
	print(send_recv_notification(n))


	ref_data = []
	
	yield showMessage('Zum Starten die Leertaste drücken')
	
	for p in norm_positions:
		
		print('calibration point: ', p)
	
		norm_x = p[0]
		norm_y = p[1]
		
		first_run = True
		
		if first_run:
			
			first_run = False
		
			'''set up a plane 'right in front of user' on which we want to project the dots'''
	
			# target the current center of view
			p_line = viz.MainWindow.screenToWorld(.5, .5)
		
			# let's modify the line and call it line 2. Here we let the line end at the "depth" value
			p_line_2 = viz.Line(begin=p_line.begin, end=p_line.end, dir=p_line.dir, length=depth)
						
			# Add the plane and apply the matrix of our viewpoint to the plane
			plane = vizshape.addBox(size=[3.6, 2, .1])
			mymat = viz.MainView.getMatrix()
			plane.setMatrix(mymat)
			
			# Reposition the plane to the end of line 2
			plane.setPosition(p_line_2.end)
			plane.color([.25,.25,.25])
			plane.alpha(.95)
			
			# Lock it to user
			plane_link = viz.grab(viz.MainView, plane)
		
		
		# interpolate a line from norm values to 3d coordinates
		line = viz.MainWindow.screenToWorld([norm_x, norm_y])
		
		# find the intersection
		intersection = viz.intersect(line.begin, line.end)
		
		# place a dot (at depth level of line) 
		dot = vizshape.addSphere(radius=sphere_size)
		dot.setPosition(intersection.point)
		
		# lock dot to user
		view_link = viz.grab(viz.MainView, dot)
		
		print('ready')
		viz.playSound('beep500_200.wav')
		yield viztask.waitKeyDown(' ')
				
		for s in range(60):
			
			# get the current pupil time (pupil uses CLOCK_MONOTONIC with adjustable timebase).
			# You can set the pupil timebase to another clock and use that.
			t = get_pupil_timestamp()

			# here the left and right screen marker positions are identical.
			datum0 = {'norm_pos':p,'timestamp':t,'id':0}
			datum1 = {'norm_pos':p,'timestamp':t,'id':1}
			ref_data.append(datum0)
			ref_data.append(datum1)
			yield viztask.waitTime(1/60.)
			print(t)
		
		dot.color(viz.RED)
		
		print('waiting for next position...')
		
		yield viztask.waitKeyDown(' ')
		
		yield dot.remove()
		
	

	# send ref data to Pupil Capture/Service:
	# this notification can be sent once at the end or multiple times.
	# during one calibraiton all new data will be appended.
	n = {'subject':'calibration.add_ref_data','ref_data':ref_data}
	print(send_recv_notification(n))

	# stop calibration
	# pupil will correlate pupil and ref data based on timestamps,
	# compute the gaze mapping params, and start a new gaze mapper.
	n = {'subject':'calibration.should_stop'}
	print(send_recv_notification(n))

	time.sleep(2)
		
	showMessage('calibration done! - now validate!')

	plane.remove()
	
	yield viztask.waitTime(2)
Ejemplo n.º 53
0
def validation():
	'''
	Show same calibration points and compare calulated gaze point to ground truth. 
	(Displays both + angular error)
	'''
	
	# ask for the sub port
	req.send_string('SUB_PORT')
	sub_port = req.recv_string()

	# open a sub port to listen to pupil
	sub = ctx.socket(zmq.SUB)
	sub.connect("tcp://{}:{}".format(addr, sub_port))
	sub.setsockopt_string(zmq.SUBSCRIBE, u'gaze')

	# add gaze marker
	m_gaze = vizshape.addSphere(radius=sphere_size, color=viz.GREEN)
	m_gaze.disable(viz.INTERSECTION)
	if not gaze_marker_visible:
		m_gaze.disable(viz.RENDER) # invisible but phyisically present



	def get_gaze(eye_number):
		'''
		checks gaze stream for confident measures of the eye (eye_number) until it finds them
		Args:    eye_number (int): 1=left, 0=right
		Returns: [x, y] (float): normalized x and y values range [0,1]
		'''
		found_confident_val = False
		
		while found_confident_val == False:

			topic = sub.recv_string() # unused
			msg = sub.recv()
			msg = loads(msg, encoding='utf-8')
			
			confidence = msg['confidence']
			
			if msg['id'] == eye_number:
				
				if confidence > confidence_level:
				
					found_confident_val = True
					
					t = msg['timestamp'] # unused
					npx = msg['norm_pos'][0]
					npy = msg['norm_pos'][1]
					
					return [npx, npy]


	def updateGaze():	
		'''
		calls 'get_gaze function' and takes the average of two
		eyes for the normal values - they will be used to project a 
		sphere on where subjects look at
		'''
		
		# get gaze data
		norm_pos_x = np.mean([get_gaze(1)[0], get_gaze(0)[0]])
		norm_pos_y = np.mean([get_gaze(1)[1], get_gaze(0)[1]])
				
		# find the intersection and project sphere
		line = viz.MainWindow.screenToWorld([norm_pos_x, norm_pos_y])
		intersection = viz.intersect(line.begin, line.end)
		m_gaze.setPosition(intersection.point)
		
	# update cursor location on every sample		
	vizact.onupdate(viz.PRIORITY_LINKS+1, updateGaze)


	dot_norm_pos=[]
	gaze_norm_pos=[]
	ang_error = []


	yield showMessage('Zum Starten der Validierung die Leertaste drücken')
	
	for p in norm_positions:
		
		print('calibration point: ', p)
	
		norm_x = p[0]
		norm_y = p[1]
		
		first_run = True
		
		if first_run:
			
			first_run = False
		
			'''set up a plane 'right in front of user' on which we want to project the dots'''
	
			# target the current center of view
			p_line = viz.MainWindow.screenToWorld(.5, .5)
		
			# let's modify the line and call it line 2. Here we let the line end at the "depth" value
			p_line_2 = viz.Line(begin=p_line.begin, end=p_line.end, dir=p_line.dir, length=depth)
						
			# Add the plane and apply the matrix of our viewpoint to the plane
			plane = vizshape.addBox(size=[3.6, 2, .1])
			mymat = viz.MainView.getMatrix()
			plane.setMatrix(mymat)
			
			# Reposition the plane to the end of line 2
			plane.setPosition(p_line_2.end)
			plane.color([.25,.25,.25])
			plane.alpha(.95)
			
			# Lock it to user
			plane_link = viz.grab(viz.MainView, plane)
		
		
		# interpolate a line from norm values to 3d coordinates
		line = viz.MainWindow.screenToWorld([norm_x, norm_y])
		
		# find the intersection
		intersection = viz.intersect(line.begin, line.end)
		
		# place a dot (at depth level of line) 
		dot = vizshape.addSphere(radius=sphere_size)
		dot.setPosition(intersection.point)
		
		# lock dot to user
		view_link = viz.grab(viz.MainView, dot)
		
		print('ready')
		viz.playSound('beep500_200.wav')
		yield viztask.waitKeyDown(' ')
				
		for s in range(60):
			
			# get the current pupil time (pupil uses CLOCK_MONOTONIC with adjustable timebase).
			# You can set the pupil timebase to another clock and use that.
			t = get_pupil_timestamp()

			dot_norm_pos.append(p)
			gaze_norm_pos.append(viz.MainWindow.worldToScreen(m_gaze.getPosition()))

			yield viztask.waitTime(1/60.)
			print(t)
		
		dot.color(viz.RED)
		
		print('waiting for next position...')
		
		yield viztask.waitKeyDown(' ')
		
		yield dot.remove()
				
	time.sleep(2)
		
	showMessage('validation done!')
	
	for p in norm_positions:
		
		i = norm_positions.index(p)
		chunk = range(i*60, (i+1)*60)
		print(i)
		dmx = np.mean([gaze_norm_pos[x][0] for x in chunk])
		dmy = np.mean([gaze_norm_pos[y][1] for y in chunk])
		
		# interpolate a line from norm values to 3d coordinates
		line = viz.MainWindow.screenToWorld([p[0], p[1]])
		line_v = viz.MainWindow.screenToWorld([dmx, dmy])
		
		# find the intersection
		intersection = viz.intersect(line.begin, line.end)
		intersection_v = viz.intersect(line_v.begin, line_v.end)
		
		# place a dots (at depth level of line) for both ground truth and gaze point
		dot = vizshape.addSphere(radius=sphere_size)
		dot.setPosition(intersection.point)
		dot.color(viz.BLUE)
		
		dot_v = vizshape.addSphere(radius=sphere_size*0.75)
		dot_v.setPosition(intersection_v.point)
		dot_v.color(viz.YELLOW_ORANGE)
		
		# lock dots to user
		view_link = viz.grab(viz.MainView, dot)
		viel_link2 = viz.grab(viz.MainView, dot_v)
		
		# calculate angular error
		error = vizmat.AngleBetweenVector(line.dir, line_v.dir)
#		cosangle = np.dot(a,b) / (np.linalg.norm(a) * np.linalg.norm(b))
#		angle = np.arccos(cosangle)
#		error = np.degrees(angle)
		
		ang_error.append(error)
		
		print('angle is: ', error, 'for ', p)

	
	showMessage('mean angular error is: {}'.format(np.mean(ang_error)))
	
	print('mean angular error is: ', np.mean(ang_error), ' deg/ visual angle')
Ejemplo n.º 54
0
    def onTimer(self, num):

        if num == 1 and not self.pause:  # Moves the player left/right and controls the rotation of the ship
            if not self.leftUp and self.playerShip.canGoLeft(-0.25):
                self.playerShip.setPosition(
                    self.playerShip.getX() - self.playerSpeed,
                    self.playerShip.getY(), self.playerShip.getZ())
                if self.playerShip.theta < 45 or self.playerShip.theta >= 315:
                    self.playerShip.rotate(9)
            if not self.rightUp and self.playerShip.canGoRight(0.25):
                self.playerShip.setPosition(
                    self.playerShip.getX() + self.playerSpeed,
                    self.playerShip.getY(), self.playerShip.getZ())
                if self.playerShip.theta > 315 and self.playerShip.theta <= 360 or self.playerShip.theta <= 45:
                    self.playerShip.rotate(351)

        if num == 2 and not self.pause:  #Controls passive rotation for if the player is not actively pressing buttons
            if self.leftUp and self.rightUp:
                if self.playerShip.theta <= 45 and self.playerShip.theta >= 0:
                    self.playerShip.rotate(351)
                if self.playerShip.theta >= 315:
                    self.playerShip.rotate(9)

        if num == 3 and not self.pause:
            #Move bullet
            for bullet in self.bulletlist:
                x = bullet.getX()
                vx = bullet.getVX()
                y = bullet.getY()
                vy = bullet.getVY()
                z = bullet.getZ()
                vz = bullet.getVZ()
                bullet.setPosition(x + vx, y + vy, z + vz)
                #Deallocate bullets
                if (bullet.getZ() > 2):
                    bullet.delete()
                    self.bulletlist.remove(bullet)
                # Check bullet to alien collison
                deadaliens = 0
                for alien in self.aliens:
                    if alien != None:
                        if bullet.getX() > alien.getX() - .1 and bullet.getX(
                        ) < alien.getX() + .1 and bullet.getZ() > alien.getZ(
                        ) - .1 and bullet.getZ() < alien.getZ() + .1:
                            bullet.delete()
                            self.bulletlist.remove(bullet)
                            alien.damage()
                            viz.playSound('alienHit.wav')
                            if alien.getHP() <= 0:
                                alien.delete()
                                deadalien = self.aliens.index(alien)
                                self.aliens[deadalien] = None
                                deadaliens += 1
                                if alien.getColor(
                                ) == 'orange':  #Orange aliens death triggers a powerup
                                    self.playerShip.powerUp()
                                    self.updateHPText()
                                    viz.playSound('powerup.wav')
                                else:
                                    viz.playSound('explosion.wav')
                            self.score += 100
                            self.updateScoreText()

                    else:
                        deadaliens += 1
                if self.boss != None:  #Check if boss alien is hit
                    if bullet.getX() > self.boss.getX() - .3 and bullet.getX(
                    ) < self.boss.getX() + .3 and bullet.getZ(
                    ) > self.boss.getZ() - .3 and bullet.getZ(
                    ) < self.boss.getZ() + .3:
                        bullet.delete()
                        self.bulletlist.remove(bullet)
                        self.boss.damage()
                        viz.playSound('alienHit.wav')
                        if self.boss.getHP() <= 0:
                            self.boss.delete()
                            self.boss = None
                            viz.playSound('explosion.wav')
                        self.score += 100
                        self.updateScoreText()
                #Check to see if current wave is complete
                if len(self.aliens) == deadaliens and self.boss == None:
                    self.power += 1
                    self.level += 1
                    self.updateLevelText()
                    self.speed = 1 / self.power
                    viz.killtimer(4)
                    self.starttimer(4, self.speed, viz.FOREVER)
                    self.spawnAliens()

            # TRANSLATE ALIEN BULLET
            for bullet in self.alienbullets:
                x = bullet.getX()
                vx = bullet.getVX()
                y = bullet.getY()
                vy = bullet.getVY()
                z = bullet.getZ()
                vz = bullet.getVZ()
                bullet.setPosition(x - vx, y - vy, z - vz)

                if (bullet.getZ() < -.8):
                    bullet.delete()
                    self.alienbullets.remove(bullet)
                if bullet.getX() > self.playerShip.getX() - .1 and bullet.getX(
                ) < self.playerShip.getX() + .1 and bullet.getZ(
                ) > self.playerShip.getZ() - .1 and bullet.getZ(
                ) < self.playerShip.getZ() + .1:
                    bullet.delete()
                    self.alienbullets.remove(bullet)
                    self.playerShip.damage(math.floor(self.power / 2))
                    viz.playSound('playerHit.wav')
                    if self.playerShip.getHP() <= 0:
                        #GAME OVER
                        self.gameover = True
                        self.pause = True
                        self.playerShip.delete()
                        viz.playSound('playerDead.wav')
                    self.updateHPText()

        if num == 4 and not self.pause:
            # Move aliens down the Z axis
            for alien in self.aliens:
                if alien != None:
                    alien.setPosition(alien.getX(), alien.getY(),
                                      alien.getZ() - .001, alien.getScale())
                    if self.playerShip.getX() + .04 > alien.getX(
                    ) - .1 and self.playerShip.getX() - .04 < alien.getX(
                    ) + .1 and self.playerShip.getZ() + .06 > alien.getZ(
                    ) - .1 and self.playerShip.getZ() - .06 < alien.getZ() + .1:
                        self.playerShip.damage(1)
                        if self.playerShip.getHP() <= 0:
                            #GAME OVER
                            self.gameover = True
                            self.pause = True
                            self.playerShip.delete()
                            viz.playSound('collision.wav')
                        self.updateHPText()
                    if alien.isOffScreen(
                    ):  #Translate aliens back if off screen
                        alien.setPosition(alien.getX(), alien.getY(), 1,
                                          alien.getScale())

            if self.boss != None:
                #Move the boss around, the boss moves left right on the X axis instead of foward on the Z
                if self.boss.getX() > -1 and self.bossLeft:
                    self.boss.setPosition(self.boss.getX() - .001,
                                          self.boss.getY(), self.boss.getZ(),
                                          self.boss.getScale())
                else:
                    self.bossLeft = False
                if self.boss.getX() < 1 and not self.bossLeft:
                    self.boss.setPosition(self.boss.getX() + .001,
                                          self.boss.getY(), self.boss.getZ(),
                                          self.boss.getScale())
                else:
                    self.bossLeft = True
                if self.playerShip.getX() + .04 > self.boss.getX(
                ) - .1 and self.playerShip.getX() - .04 < self.boss.getX(
                ) + .1 and self.playerShip.getZ() + .06 > self.boss.getZ(
                ) - .1 and self.playerShip.getZ() - .06 < self.boss.getZ() + .1:
                    self.playerShip.damage(1)
                    if self.playerShip.getHP() <= 0:
                        self.playerShip.delete()
                        viz.playSound('explosion.wav')
                    self.updateHPText()
                if self.boss.isOffScreen():
                    self.boss.setPosition(self.boss.getX(), self.boss.getY(),
                                          1, self.boss.getScale())

        if num == 5 and not self.pause:
            for alien in self.aliens:
                if alien != None:
                    if alien.getColor() == 'red' or alien.getColor(
                    ) == 'purple' or alien.getColor(
                    ) == 'green':  #Only red and purple ships can fire
                        index = self.aliens.index(
                            alien
                        )  #Get the index of the current ship in our list
                        #Checks for whether a ship exists in the two spots in front, False = No Ship, True = Ship Exists
                        checkOne = False
                        checkTwo = False
                        if index < 6:
                            if self.aliens[index + 6] != None:
                                checkOne = True
                            if self.aliens[index + 12] != None:
                                checkTwo = True
                        elif index < 12:
                            if self.aliens[index + 6] != None:
                                checkOne = True
                                # FIRES ALIEN BULLETS, THESE CHECKS ARE REQUIRED TO ALLOW A SHIP TO FIRE, alien cannot fire if there is another ship in front of it
                        if not checkOne and not checkTwo and self.playerShip.getX(
                        ) <= alien.getX() + .1 and self.playerShip.getX(
                        ) >= alien.getX() - .1 and not self.pause:
                            b = Bullet(model=self.redbullet.clone())
                            b.setTheta(180)
                            b.setPosition(alien.getX(), alien.getY(),
                                          alien.getZ())
                            self.alienbullets.append(b)
                            viz.playSound('laser.wav')

            if self.boss != None:
                #The boss fires three bullets, one straight ahead and two at an angle
                b = Bullet(model=self.redbullet.clone())
                b.setTheta(180)
                b.setPosition(self.boss.getX(), self.boss.getY(),
                              self.boss.getZ(), 0)
                self.alienbullets.append(b)
                b = Bullet(model=self.redbullet.clone())
                b.setTheta(180)
                b.setVXVY(.02, 0, .02)
                b.setPosition(self.boss.getX(), self.boss.getY(),
                              self.boss.getZ())
                self.alienbullets.append(b)
                b = Bullet(model=self.redbullet.clone())
                b.setTheta(180)
                b.setVXVY(-.02, 0, .02)
                b.setPosition(self.boss.getX(), self.boss.getY(),
                              self.boss.getZ(), 90)
                self.alienbullets.append(b)
                viz.playSound('laser.wav')

        if num == 6:  #Allow player to fire
            self.Fire = True