def inRadiusAndFacing():
    cur_pos = viz.get(viz.HEAD_POS)
    cur_rot = viz.get(viz.HEAD_ORI)
    return inRadius(cur_pos, models['homePole'].getPosition(),
                    POLE_TRIGGER_RADIUS) and facing(
                        cur_pos, models['orientPole'].getPosition(),
                        cur_rot[0], THRESHOLD_THETA)
Example #2
0
    def updatePositionLabel():
        global driver, trialtype_signed, trialtype
        ##WHAT DO I NEED TO SAVE?

        # get head position(x, y, z)
        pos = viz.get(viz.HEAD_POS)
        pos[1] = 0.0  # (x, 0, z)
        # get body orientation
        ori = viz.get(viz.BODY_ORI)
        steeringWheel = driver.getPos()

        #what data do we want? RoadVisibility Flag. SWA. Time, TrialType. x,z of that trial These can be reset in processing by subtracting the initial position and reorienting.
        SaveData(pos[0], pos[2], ori, steeringWheel)  ##.
Example #3
0
def masterLoop(num):
	# global variables within masterLoop
	global DATA_COLLECT, DO_PRACTICE, is_practice, is_freewalk, data_collect, trial_stage, trial_num, \
	freewalk_session, time, time_stamp, cur_pos, conditions, practice_conditions, condition, K, B, _alpha, \
	reset_countDown, controlType,instruction, screenshot, data_batch, leaderSpd, leader, avatarID,\
	time_elapsed, HZ, flag

	# Time elapsed since the last run of masterLoop and then added to the global time
	time_elapsed = viz.getFrameElapsed()
	time += time_elapsed
	

	if os.path.isfile(OUTPUT_DIR + 'image'+ str(screenshot) +'.bmp') == True:
		screenshot += 1
		
	vizact.onkeydown('p', viz.window.screenCapture, OUTPUT_DIR + 'image'+ str(screenshot) +'.bmp')
	
	# Current position and roation of the participant
	cur_pos = viz.get(viz.HEAD_POS)
	cur_rot = viz.get(viz.HEAD_ORI)
	#>> Will only work in VENLab <<
	emergencyWalls.popWalls(cur_pos) # Pops up the Emergency Walls when participant is close to physical room edge.

	
	##################
	# Begin Freewalk #
	##################
	
	if is_freewalk == True:
		
		
		# Writes Position and Rotation, but only when DATA_COLLECT set to True
		# and trial_stage has set data_collect to True
		if DATA_COLLECT and data_collect:			

			# Position: Target_x, Target_y, Target_z, Participant_x, Participant_y, Participant_z, Yaw, Pitch, Row, time stamp
			data = [cur_pos[0], cur_pos[1], cur_pos[2], cur_rot[0], cur_rot[1], cur_rot[2]]
			strData = [str(round(t,4)) for t in data+[time]]
			strData = ','.join(strData)+'\n'
			data_batch = data_batch + strData

		
		
		#########
		# 00 01 Freewalk Pretrial: sets up practice trial, establishes pole locations
		if trial_stage == 'pretrial_00_01':
			if flag:
				print '> Start Free Walking Session ' + str(freewalk_session) + ' Trial ' + str(trial_num) + ' ----------------------------------'
				flag = False
		
			# Set position of home pole (where participant stands to start trial)
			if models['homePole'].getVisible() == False:
				models['homePole'].setPosition(HOME_POLE[trial_num%2])
				models['homePole'].alpha(1.0)
				models['homePole'].visible(viz.ON)

			# Set position of orientation pole (where participant faces to start trial)
			if models['orientPole'].getVisible() == False:
				models['orientPole'].setPosition(HOME_POLE[(trial_num+1)%2])
				models['orientPole'].visible(viz.ON)
			
			if trial_num == 1 and freewalk_session == 1 and instruction:
				# placeholder for instructions
				instruction = False
			
			if not(trial_num == 1 and freewalk_session == 1) or countDown(5):
				# Move to next stage
				goToStage('orient_00_02')
				instruction = True
				reset_countDown = True				
				
		#########
		# 00 02 Orienting to Pole: Give time for participant to orient to the pole
		elif trial_stage == 'orient_00_02':
			flag = True
			if inRadiusAndFacing():
				if trial_num == 1 and instruction:					
					if freewalk_session == 2:
						pass # placeholder for instructions
					instruction = False
				if not(trial_num == 1) or (freewalk_session == 1) or (freewalk_session == 2 and countDown(5)):	
					# Move to stage 3
					goToStage('orient_00_02_wait')
					instruction = True
					reset_countDown = True
	
				
		#########
		# wait for orientation
		elif (trial_stage == 'orient_00_02_wait'):			
			if countDown(ORIENT_TIME):
				goToStage('inposition_00_03')
				reset_countDown = True
			if not inRadiusAndFacing():
				reset_countDown = True
		
		#########
		# 00 03 Freewalk In Position: proceeds once participant is standing on home and facing orient for three seconds
		elif (trial_stage == 'inposition_00_03'):
			print 'Free walk start'
			# Turn off home pole
			models['homePole'].visible(viz.OFF)
			models['orientPole'].visible(viz.OFF)
			models['targetPole'].setPosition(HOME_POLE[(trial_num+1)%2])
			models['targetPole'].visible(viz.ON)
			sounds['Begin'].play()
			
	
			# Start to collect data
			data_collect = True
		
			# initialize batch data output
			data_batch = ''
			time = 0
			
			# Move to Stage 4
			goToStage('target_00_04')
			
		#########
		# 00 04 Freewalk: Participants Moves
		elif (trial_stage == 'target_00_04'):
				
			# Detects participant location, moves to Stage 5 (Ends Trial) when participant reache the end line
			if (trial_num%2 == 1) and (cur_pos[2] > endLine(cur_pos[0])) or \
				(trial_num%2 == 0)and (cur_pos[2] < endLine(cur_pos[0])):
					
				goToStage('endtrial_00_05')
		
		#########
		# 00 05 End Freewalk Trial: Close out the trial and reset values for next practice trial or start Experiment
		elif trial_stage == 'endtrial_00_05':
		
			# Clears the target pole
			models['targetPole'].visible(viz.OFF)
			
			# save the data of this trial
			fileName = OUTPUT_DIR + NICKNAME + '_freewalk' + '_subj' + subject + '_s' + str(freewalk_session) + '_trial' + str(trial_num).zfill(3) + '.csv'
			with open(fileName, 'a') as file:
				file.write(data_batch)


			print 'End Freewalk Trial ' + str(trial_num)
			data_collect = False


			# End Check: When trial_num is greater than FREEWALK_TRIALS, end practice and start experiment block
			if trial_num == FREEWALK_TRIALS:
				print '>> End Freewalk Session<<'
				if freewalk_session == 2:
					print '>>> End Experiment <<<'
					goToStage('NULL')
					if instruction:
						sounds['End'].play()
						instruction = False
				elif freewalk_session == 1:
					goToStage('pretrial_01_01')
					is_freewalk = False
					trial_num = 1
					freewalk_session += 1
			# Returns to Stage 1, resets clock
			else:
				trial_num += 1
				goToStage('pretrial_00_01')
				instruction = True
		

	##################
	# Begin practice #
	##################
	
	elif is_practice == True:
		
	
		#########
		# 01 01 Practice Pretrial: sets up practice trial, establishes pole locations
		if trial_stage == 'pretrial_01_01':
			if flag:
				print '> Start Practice Trial ' + str(trial_num) + ' ----------------------------------'
				flag = False
			# load input
			if practice_conditions[trial_num][3] == 'avatar':
				avatarID = random.choice(range(len(avatars)))
				leader = avatars[avatarID]
				leader.state(5)
			else:
				leader = models['leaderPole']
				
			leaderSpd = 0
			# play instruction
			if trial_num == 1 and instruction:
				# placeholder for instructions
				instruction = False
				
			# Move to Stage 2
			if trial_num != 1 or countDown(5):
				goToStage('orient_01_02')
					
			
		#########
		# 01 02 Orienting to Pole: Give time for participant to orient to the pole
		elif (trial_stage == 'orient_01_02'):
			flag = True
			# Set position of home pole (where participant stands to start trial)
			if models['homePole'].getVisible() == False:
				models['homePole'].setPosition(HOME_POLE[trial_num%2])

			if _alpha < 1.0:
				models['homePole'].alpha(_alpha)
				models['homePole'].visible(viz.ON)
				_alpha += 1.0/HZ
	
			# Set position of orientation pole (where participant faces to start trial)
			if models['orientPole'].getVisible() == False:
				models['orientPole'].setPosition(HOME_POLE[(trial_num+1)%2])
				models['orientPole'].visible(viz.ON)
	
				
			if inRadiusAndFacing():					
				reset_countDown = True
				# Move to stage 3
				goToStage('orient_01_02_wait')
				instruction = True
				_alpha = 0.0
				# Current time
				time_stamp = time
				
		#########
		# wait for orientation
		elif (trial_stage == 'orient_01_02_wait'):
			if countDown(ORIENT_TIME):
				goToStage('inposition_01_03')
				reset_countDown = True
			if not inRadiusAndFacing():
				reset_countDown = True
				
				
		#########
		# 01 03 Practice In Position: proceeds once participant is standing on home and facing orient for three seconds
		elif trial_stage == 'inposition_01_03':
			
			print 'Practice Target Appears'
			
			# Turn off home pole and orientation pole
			models['homePole'].visible(viz.OFF)
			models['orientPole'].visible(viz.OFF)
			models['targetPole'].setPosition(HOME_POLE[(trial_num+1)%2])
			models['targetPole'].visible(viz.ON)
			sounds['Begin'].play()
			
			# Move to Stage 4
			goToStage('target_01_04')
			time = 0
			
		#########
		# 01 04 Moving leader: Leader Moves
		elif (trial_stage == 'target_01_04'):
			leaderOnset = float(practice_conditions[trial_num][4])
			d0 = float(practice_conditions[trial_num][1])
			v0 = float(practice_conditions[trial_num][2])
			if time > leaderOnset:
				if not leader.getVisible():
					models['targetPole'].visible(viz.OFF)
					# leader appear d0 meter in front of participant
					leader.setPosition(HOME_POLE[trial_num%2])
					leader.lookAt(HOME_POLE[(trial_num+1)%2], mode=viz.ABS_GLOBAL)
					home = models['homePole'].getPosition()						
					d = d0 + projection([x-y for x, y in zip(cur_pos, home)], [-x for x in home])
					moveTarget(leader, d/time_elapsed, conditions[trial_num][3] == 'avatar') # move the leader by d0 from homepole to leader					
					leader.visible(viz.ON)
				# leader moves
				moveTarget(leader, v0, practice_conditions[trial_num][3] == 'avatar')
			
			# Detects participant location, moves to Stage 6 (Ends Trial) when participant reache the end line
			if (trial_num%2 == 1) and (cur_pos[2] > endLine(cur_pos[0])) or \
				(trial_num%2 == 0)and (cur_pos[2] < endLine(cur_pos[0])):
				goToStage('endtrial_01_05')
		
		#########
		# 01 05 End Practice Trial: Close out the trial and reset values for next practice trial or start Experiment
		elif trial_stage == 'endtrial_01_05':
			
			# Clears the target pole
			leader.visible(viz.OFF)

			print 'End Practice Trial ' + str(trial_num)
			

			# End Check: When trial_num is greater than PRACTICE_TRIALS, end practice and start experiment block
			if trial_num >= PRACTICE_TRIALS:
				print '>> End Practice <<'
				goToStage('pretrial_02_01')
				is_practice = False
				trial_num = 1
			# Returns to Stage 1, resets clock
			else:
				trial_num += 1
				goToStage('pretrial_01_01')
			
	####################
	# Begin Experiment #
	####################
	
	elif is_practice == False:
		

		# Writes Position and Rotation, but only when DATA_COLLECT set to True
		# and trial_stage has set data_collect to True
		if DATA_COLLECT and data_collect:
			
			
			# Location of Target Pole
			leader_loc = leader.getPosition()
			
			leader_loc = leader.getPosition()
			# Position: Target_x, Target_y, Target_z, Participant_x, Participant_y, Participant_z, Yaw, Pitch, Row, time stamp
			data = [leader_loc[0], leader_loc[1], leader_loc[2], cur_pos[0], cur_pos[1], cur_pos[2], cur_rot[0], cur_rot[1], cur_rot[2]]
			strData = [str(round(t,4)) for t in data+[time]] + [str(avatarID)]
			strData = ','.join(strData)+'\n'
			data_batch = data_batch + strData

			# log IPD
			if trial_num == 1:
				file = open(OUTPUT_DIR + NICKNAME + '_subj' + subject + \
				'_IPD_' + str(IPD) + '.txt', 'a')
				file.close()
			
			
		#########
		# 02 01 Experiment Pretrial: sets up trial, establishes pole locations
		if trial_stage == 'pretrial_02_01':
			
			condition = ', '.join(conditions[trial_num][1:4])
			
			# Print start of trial, trial #, and type of trial [pos][speed][turn]
			if flag:
				print '> Start Trial ' + str(trial_num) + ': ' + condition + ' ----------------------------------'
				flag = False
			# load input
			if conditions[trial_num][3] == 'avatar':
				avatarID = random.choice(range(len(avatars)))
				leader = avatars[avatarID]
				leader.state(5)
			elif conditions[trial_num][3] == 'pole':
				leader = models['leaderPole']
						
			leaderSpd = 0
			
			# play instruction
			if trial_num == 1 and instruction:				
				instruction = False
			
			# Move to Stage 2			
			if trial_num != 1 or countDown(5):
				goToStage('orient_02_02')
				
				
		#########
		# 02 02 Orienting to Pole: Give time for participant to orient to the pole
		elif (trial_stage == 'orient_02_02'):
			flag = True
			## Set position of home pole (where participant stands to start trial)
			if models['homePole'].getVisible() == False:
				models['homePole'].setPosition(HOME_POLE[trial_num%2])
				
			if _alpha < 1.0:
				models['homePole'].alpha(_alpha)
				models['homePole'].visible(viz.ON)
				_alpha += 1.0/HZ
	
			# Set position of orient pole (where participant faces to start trial)
			if models['orientPole'].getVisible() == False:
				models['orientPole'].setPosition(HOME_POLE[(trial_num+1)%2])
				models['orientPole'].visible(viz.ON)

			if inRadiusAndFacing():					
				# Move to stage 3
				goToStage('orient_02_02_wait')
				_alpha = 0.0
				instruction = True
				reset_countDown = True				
	
		#########
		# wait for orientation
		elif (trial_stage == 'orient_02_02_wait'):
			if countDown(ORIENT_TIME):
				goToStage('inposition_02_03')
				reset_countDown = True
			if not inRadiusAndFacing():
				reset_countDown = True		
		
		#########
		# 02 03 In Position: proceeds once participant is standing on home and facing orient
		elif trial_stage == 'inposition_02_03':

			# Turn off home and orient poles
			models['homePole'].visible(viz.OFF)
			models['orientPole'].visible(viz.OFF)
			models['targetPole'].setPosition(HOME_POLE[(trial_num+1)%2])
			models['targetPole'].visible(viz.ON)
			sounds['Begin'].play()
			
			# Turn on data collection for this trial
			data_collect = True
				
			# Move to Stage 5
			goToStage('target_02_04')
			# initialize batch data output
			data_batch = ''
			time = 0

			
		#########
		# 02 04 Moving Leader: Leader Moves
		elif (trial_stage == 'target_02_04'):
			# read data
			leaderOnset = float(conditions[trial_num][4])
			d0 = float(conditions[trial_num][1])
			v0 = float(conditions[trial_num][2])
			if time > leaderOnset:
				if not leader.getVisible():
					models['targetPole'].visible(viz.OFF)
					# leader appear d0 meter in front of participant
					leader.setPosition(HOME_POLE[trial_num%2])
					leader.lookAt(HOME_POLE[(trial_num+1)%2], mode=viz.ABS_GLOBAL)
					home = models['homePole'].getPosition()
					d = d0 + projection([x-y for x, y in zip(cur_pos, home)], [-x for x in home])
					moveTarget(leader, d/time_elapsed, conditions[trial_num][3] == 'avatar') # move the leader by d0 from homepole to leader					
					leader.visible(viz.ON)
				# leader moves
				moveTarget(leader, v0, conditions[trial_num][3] == 'avatar')
				
				
			# Detects participant location, moves to Stage 6 (Ends Trial) when participant reache the end line
			if (trial_num%2 == 1) and (cur_pos[2] > endLine(cur_pos[0])) or \
				(trial_num%2 == 0)and (cur_pos[2] < endLine(cur_pos[0])):
				goToStage('endtrial_02_05')
				
			#########
		# 02 05 End Trial: Close out the trial and reset values for next trial
		elif trial_stage == 'endtrial_02_05':
			
			# Clears the target pole
			leader.visible(viz.OFF)

			# End data collection for this trial
			data_collect = False
			
			# save the data of this trial			
			fileName = OUTPUT_DIR + NICKNAME + '_subj' + subject + '_trial' + str(trial_num).zfill(3) + '_' + condition + '.csv'
			with open(fileName, 'a') as file:
				file.write(data_batch)
	
			print 'End Trial ' + str(trial_num)
			
			# When trial_num is greater than TOTAL_TRIALS, end experiment
			if trial_num == TOTAL_TRIALS:
				is_freewalk = True
				goToStage('pretrial_00_01')
				trial_num = 1
			# Returns to Stage 1, resets clock
			else:
				trial_num += 1
				goToStage('pretrial_02_01')
def run_trial(i_trial, s0, d0, angle, recorded):
    global trial_time, alpha, print_flag, ii, timer_on, v0, p_goal, data_buffer, recording
    time_elapsed = viz.getFrameElapsed()
    trial_time += time_elapsed
    # Current position and roation of the participant
    cur_pos = viz.get(viz.HEAD_POS)
    cur_rot = viz.get(viz.HEAD_ORI)
    # Pops up the Emergency Walls when participant is close to physical room edge.
    popWalls(cur_pos)

    # Record data to buffer
    if recorded and recording:
        goal = models['goalPole'].getPosition()
        data = [
            trial_time, cur_pos[0], cur_pos[1], cur_pos[2], cur_rot[0],
            cur_rot[1], cur_rot[2], goal[0], goal[2],
            models['goalPole'].getVisible()
        ]
        data_buffer += ','.join([str(dat) for dat in data]) + '\n'

    if stage == 'ready':
        # Print start of trial, trial # and condition, initialize trial
        if print_flag:
            print_flag = False
            print('>>> Start Trial ' + str(i_trial) + ': ' +
                  ', '.join([str(s0), str(d0), str(angle)]))
            # Compute goal pole position and pacePole velocity for later use
            ang = angle / 360 * 2 * math.pi
            subj_goal_unit = rotate(
                DIAGONAL_UNIT[i_trial % 2],
                ang)  # unit vector pointing from subj to goal
            p_goal = [
                h + d * RAMP_DIST + i * d0
                for i, h, d in zip(subj_goal_unit, HOME_POLE[i_trial % 2],
                                   DIAGONAL_UNIT[i_trial % 2])
            ]
            p_pace = [
                h + d * PACE_DIST
                for h, d in zip(HOME_POLE[i_trial % 2], DIAGONAL_UNIT[i_trial %
                                                                      2])
            ]
            v0 = [i * s0 for i in DIAGONAL_UNIT[i_trial % 2]]
            models['goalPole'].setPosition(p_goal)
            models['pacePole'].setPosition(p_pace)
            models['homePole'].setPosition(HOME_POLE[i_trial % 2])
            models['orientPole'].setPosition(ORI_POLE[i_trial % 2])
            models['pacePole'].setPosition(p_pace)
            models['homePole'].visible(viz.ON)
            models['orientPole'].visible(viz.ON)
            if recorded:
                data_buffer += '\n' + ','.join([
                    'trial',
                    str(i_trial).zfill(3), 's0',
                    str(s0), 'd0',
                    str(d0), 'angle',
                    str(angle)
                ]) + '\n'
                data_buffer += 'timeStamp,subjX,subjY,subjZ,subjYaw,subjPitch,subjRow,' + 'goalX,goalZ,goalVisible\n'
        if alpha < 1.0:
            models['homePole'].alpha(alpha)
            models['orientPole'].alpha(alpha)
            alpha += time_elapsed
        if inRadiusAndFacing():
            if timer(ORIENT_TIME):
                goToStage('pace')
        else:
            timer_on = False
    elif stage == 'pace':
        # Turn off home and orient poles, turn on pacePole
        if models['homePole'].getVisible():
            models['homePole'].visible(viz.OFF)
            models['orientPole'].visible(viz.OFF)
            if s0:
                models['pacePole'].visible(viz.ON)
            else:
                # For freewalk trial
                models['goalPole'].setPosition(ORI_POLE[i_trial % 2])
                models['goalPole'].visible(viz.ON)
            sounds['begin'].play()
            trial_time = 0
            recording = True
        # Move pacePole
        if s0:
            moveTarget(models['pacePole'], v0, time_elapsed)
        # Is stage ended?
        if overTheLine(cur_pos, RAMP_DIST, i_trial):
            goToStage('approach')
        else:
            # Check subject lateral deviation
            if offCourse(cur_pos):
                sounds['startover'].play()
                reset_trial()
    # Obstacle appears
    elif stage == 'approach':
        if s0:
            if not models['goalPole'].getVisible():
                models['goalPole'].visible(viz.ON)
                models['pacePole'].visible(viz.OFF)
        # Trial end
        end_dist = END_DIST
        if not s0:
            p_goal = HOME_POLE[(i_trial + 1) % 2]
            end_dist = 2
        if distance(cur_pos[0], cur_pos[2], p_goal[0], p_goal[2]) < end_dist:
            # Write data to disk
            if recorded:
                filename = os.path.abspath(
                    os.path.join(OUTPUT_DIR,
                                 'Approach_subj' + subject + '.csv'))
                with open(filename, 'a') as file:
                    file.write(data_buffer)
            reset_trial()
            if i_trial == TOTAL_TRIALS:
                stage == 'NULL'
                sounds['end'].play()
            else:
                ii += 1
def Hide():
	viz.get(viz.HEAD_LIGHT).enable()
	key_spot.disable()
	def updatePositionLabel():
		global driver, trialtype_signed, fixation, fixation_counter, rdsize, outside_edge, inside_edge, trialtype, groundplane
		
		# get head position(x, y, z)
		pos = viz.get(viz.HEAD_POS)
		pos[1] = 0.0 # (x, 0, z)
		# get body orientation
		ori = viz.get(viz.BODY_ORI)
		steeringWheel = driver.getPos()

		
		######Fixation. This section makes sure the fixation is moved with the observer. 
		fpheight = .12  
		fixation.setEuler((ori, 0.0, 0.0),viz.ABS_GLOBAL) ##fixation point always faces observer
		
		
		if trialtype_signed > 0: ##fixations for right bends
			while fixation_counter < 3142:
				fix_dist = mt.sqrt( ( ( pos[0] - x_right_mid[fixation_counter] )**2 ) + ( ( pos[2] - z_right_mid[fixation_counter] )**2 ) )
				if ( (fix_dist < 16.0) | (fix_dist > 16.3) ):
					fixation_counter += 1
					continue
				elif ( (fix_dist > 16.0) and (fix_dist < 16.3) ):
					fpx = x_right_mid[fixation_counter]
					fpz = z_right_mid[fixation_counter]
					centre_x = x_right_mid[fixation_counter]
					centre_z = z_right_mid[fixation_counter]
					break
			else: ##if you move more than 16m away from any possible fixation, fixation goes back to 0,0,0
				fixation_counter = 0  ##if you end up finding your path again, there is a brand new fixation for you! 
				fpx = 0
				fpz = 0
				centre_x = 0
				centre_z = 0
		else: ##fixations for left bends
			while fixation_counter < 3142:
				fix_dist = mt.sqrt( ( ( pos[0] - x_left_mid[fixation_counter] )**2 ) + ( ( pos[2] - z_left_mid[fixation_counter] )**2 ) )
				if ( (fix_dist < 16.0) | (fix_dist > 16.3) ):
					fixation_counter += 1
					#compCount += 1
					continue
				elif ( (fix_dist > 16.0) and (fix_dist < 16.3) ):
					fpx = x_left_mid[fixation_counter]
					fpz = z_left_mid[fixation_counter]
					centre_x = x_left_mid[fixation_counter]
					centre_z = z_left_mid[fixation_counter]
					#print fix_dist
					break
			else:
				fixation_counter = 0
				fpx = 0
				fpz = 0
				centre_x = 0	
				centre_z = 0
		
		############################
		## added by Yuki
		# insert variables in driver class
		driver.function_insert(centre_x, centre_z, pos[0], pos[2], fix_dist)
		############################
		
		# fixation coordinate(X, eye height, Z)
		fixation.translate(fpx, fpheight, fpz)
		
		eyedata = 9999
def Show():
	vizact.ontimer (0, ontimer)
	viz.get(viz.HEAD_LIGHT).disable()
	key_spot.enable()
 def updateCues(self):
     (x, y, z) = viz.get(viz.HEAD_POS)
     t = viz.get(viz.HEAD_ORI)[0]
     for cue in self.CueList:
         cue.setCurtain(x, z, t)
def run_trial(i_trial, angle, speed, dsize, ipd, recorded):
    global trial_time, alpha, print_flag, ii, timer_on, obst_v, data_buffer, recording, \
        IPD, eye_height
    time_elapsed = viz.getFrameElapsed()
    trial_time += time_elapsed
    # Current position and roation of the participant
    cur_pos = viz.get(viz.HEAD_POS)
    cur_rot = viz.get(viz.HEAD_ORI)
    # Pops up the Emergency Walls when participant is close to physical room edge.
    popWalls(cur_pos)

    #    print(viz.MainWindow.getIPD())
    #    print(eye_height, models['obstPole'].getPosition()[1] + models['obstPole'].getScale()[1] * 3)
    # Record data to buffer
    if recorded and recording:
        obst = models['obstPole'].getPosition()
        goal = models['goalPole'].getPosition()
        obstScale = models['obstPole'].getScale()
        data = [
            trial_time, cur_pos[0], cur_pos[1], cur_pos[2], cur_rot[0],
            cur_rot[1], cur_rot[2], obst[0], obst[1], obst[2], obstScale[0],
            obstScale[1], obstScale[2], goal[0], goal[1], goal[2]
        ]
        data_buffer += ','.join([str(round(dat, 4)) for dat in data]) + '\n'

    if stage == 'ready':
        # Print start of trial, trial # and condition, initialize trial
        if print_flag:
            print_flag = False
            print('>>> Start Trial ' + str(i_trial) + ': ' + str(angle) +
                  ', ' + str(speed) + ', ' + str(dsize) + ', ' + str(ipd))
            # Update IPD for this the trial
            IPD = ipd
            # Compute obstacle position and velocity for later use
            ang, dist = angle / 360 * 2 * math.pi, (DIAGONAL - 4) / 2
            obst_vi = rotate(DIAGONAL_UNIT[i_trial % 2], ang)  # unit vector
            obst_p = [-i * dist for i in obst_vi]
            obst_v = [vi * speed for vi in obst_vi]
            models['obstPole'].setPosition(obst_p)
            models['obstPole'].setScale([0.5, 0.6, 0.5])
            models['homePole'].setPosition(HOME_POLE[i_trial % 2])
            models['orientPole'].setPosition(ORI_POLE[i_trial % 2])
            models['homePole'].visible(viz.ON)
            models['orientPole'].visible(viz.ON)
            if recorded:
                data_buffer += '\n' + 'trial,' + str(i_trial).zfill(3) + ',angle,' + str(angle) + ',speed,' + str(speed) +\
                ',dsize,' + str(dsize) + ',ipd,' + str(ipd) + '\n'
                data_buffer += 'timeStamp,subjX,subjY,subjZ,subjYaw,subjPitch,subjRow,obstX,obstY,obstZ,obstScaleX,obstScaleY,obstScaleZ,goalX,goalY,goalZ\n'
        if alpha < 1.0:
            models['homePole'].alpha(alpha)
            models['orientPole'].alpha(alpha)
            alpha += time_elapsed
        if inRadiusAndFacing():
            if timer(ORIENT_TIME):
                goToStage('go')
        else:
            timer_on = False
    elif stage == 'go':
        # Turn off home and orient poles, turn on goal pole
        if models['homePole'].getVisible():
            # Read eye height
            eye_height = cur_pos[1]
            models['homePole'].visible(viz.OFF)
            models['orientPole'].visible(viz.OFF)
            models['goalPole'].setPosition(ORI_POLE[i_trial % 2])
            models['goalPole'].visible(viz.ON)
            sounds['begin'].play()
            trial_time = 0
            recording = True
        # Is stage ended?
        if overTheLine(cur_pos, RAMP_DIST, i_trial):
            goToStage('avoid')
        else:
            # Check subject lateral deviation
            if offCourse(cur_pos):
                sounds['startover'].play()
                reset_trial()
    # Obstacle appears
    elif stage == 'avoid':
        if speed > 0:
            if not models['obstPole'].getVisible():
                models['obstPole'].visible(viz.ON)
            # Move obstPole
            moveTarget(models['obstPole'], obst_v, time_elapsed)
            # Change the size of obstPole when it's on the opposite side of homePole
            #            if models['obstPole'].getPosition()[0] * models['homePole'].getPosition()[0] < 0:
            changeSize(models['obstPole'], eye_height, cur_pos, dsize,
                       time_elapsed)
        # Trial end
        if overTheLine(cur_pos, -END_DIST, i_trial):
            # Write data to disk
            if recorded:
                filename = os.path.abspath(
                    os.path.join(OUTPUT_DIR, 'exp_a_Subj' + subject + '.csv'))
                with open(filename, 'a') as file:
                    file.write(data_buffer)
            reset_trial()
            if i_trial == TOTAL_TRIALS:
                stage == 'NULL'
                models['homePole'].setPosition(HOME_POLE[(i_trial + 1) % 2])
                models['homePole'].visible(viz.ON)
                models['orientPole'].visible(viz.OFF)
                models['goalPole'].visible(viz.OFF)
                sounds['end'].play()
            else:
                ii += 1

''' ************************* Initializations *************************** '''
#tracker = viz.add('intersense.dls')
#viz.translate(viz.HEAD_POS,0,-1.8,0)
#viz.eyeheight(1.8);
initialKnee = 0
LKvert = 0
RKvert = 0
#data = 0
#timeElapsed = 0
stepCounter = 0
threshold = .1
text1 = viz.addText("Stand still")
#stepTimeDif = 0
view = viz.get(viz.MAIN_VIEWPOINT)

view.setPosition(0,1.8,-3)
prevStep = "DOWN"
initialStep = 0
checkYaw = 0
yaw = 0
yaws = []
aveYaw = 0
YAW_SIZE = 10

now = datetime.datetime.now()
counter = 0
filename = 'Output files/output {}-{} {}h{}m{}s.csv'.format(now.month,now.day,now.hour,now.minute,now.second)
''' ********************* End of Initializations ************************ '''
        if string.find(file, name) >= 0:
            dirFiles.append(file)
            #print "Found matches for ",name,": ",file
    return dirFiles


if __name__ == '__main__':
    prefix = "MTM"
    dirPrefix = ""
    env = "Demo"
    InitMsg = None
    prompt = True
    if prompt:
        print __doc__
        viz.go(viz.PROMPT | viz.FULLSCREEN)
        InitMsg = viz.get(viz.INITMESG)
        giveDirs = viz.get(viz.OPTION1)
        skipTraining = viz.get(viz.OPTION2)
        movie = viz.get(viz.TRACKER)
        if viz.get(viz.HMD): group = 1
        else: group = 0
    else:
        viz.go(viz.FULLSCREEN)
        InitMsg = "MTM Grid D 1 1"
        giveDirs = 0
        skipTraining = 0
        movie = 0
        movement = 0
        group = 0
    viz.mouse(viz.OFF)
    viz.cursor(viz.OFF)
import viz
import vizact
import vizinput

viz.setMultiSample(4)
viz.fov(60)

# Start Vizard with a prompt dialog box
viz.go(viz.PROMPT)

import vizinfo
vizinfo.add('This script demonstrates how to gather input from the user at startup.')

#Retrieve text from the prompt
speed = viz.get(viz.INITMESG)

#Ask user for name
name = vizinput.input('What is your name?')

choices = ['Blue','Green','Orange']
colors = [[0,0,1],[0,1,0],[1,0.5,0]]
#Ask user for favorite color
favColor = vizinput.choose('Which of the following colors is your most favorite?',choices)

#Create text object of user name
text = viz.addText(name)
text.setPosition([0,3,7])
text.color(colors[favColor])

# Try to convert the text into a number.
# If the text is invalid, then set the rotation speed to 90.