def load(self, dataset):
		"""
		Load datasets and initialize everything necessary to commence
		the puzzle game.
		"""
		
		# Dataset
		model.ds = bp3d.DatasetInterface()

		# Proximity management
		model.proxManager = vizproximity.Manager()
		target = vizproximity.Target(model.pointer)
		model.proxManager.addTarget(target)

		model.proxManager.onEnter(None, self.EnterProximity)
		model.proxManager.onExit(None, self.ExitProximity)

		#Setup Key Bindings
		self.bindKeys()

		self.score = PuzzleScore(self.modeName)
		
#		viztask.schedule(soundTask(glove))

		self._meshesToLoad = model.ds.getOntologySet(dataset)
		self._filesToPreSnap = model.ds.getPreSnapSet()
		
		yield self.loadControl(self._meshesToLoad)
		yield self.prepareMeshes()
		yield self.preSnap()
		yield self.setKeystone(1)
		
		viztask.schedule(self.updateClosestBone())
    def __init__(self, control_style):
        """
        Every instance of class subject should have at least a code.

        Args:
            id: subject Code determined on BeMoBIL subject questionnaire
            sex: male / female
            age: integer of subjects age
            handedness: left / right
            vision: impaired, corrected, corrected-to-normal
            cap_size: EEG cap size
            neck_size: EEG neck size
            labelscheme: EEG labeling scheme of the cap in use (e.g. MoBI, 10/20 etc.)
            control_style: subject interaction with VR
        """

        self._id = id
        self.hand_tracker_id = None
        # self._sex = sex
        # self._age = age
        # self._handedness = handedness
        # self._vision = vision
        # self._cap_size = cap_size
        # self._neck_size = neck_size
        # self._labelscheme = labelscheme

        # register button press events
        self.BUTTON_A_EVENT = viz.getEventID('A')
        self.BUTTON_B_EVENT = viz.getEventID('B')

        if control_style == 'steamvr without PS':
            self.sphere_radius = 0.01
            self.right_hand_sphere = vizshape.addSphere(
                radius=self.sphere_radius)
            self.right_hand_sphere_target = vizproximity.Target(
                self.right_hand_sphere)
            self.right_hand_sphere.alpha(0)
            self.right_hand_sphere.collideSphere()
            self.right_hand_sphere.disable(viz.DYNAMICS)

            self.head_sphere = vizshape.addSphere(radius=self.sphere_radius)
            self.head_sphere_target = vizproximity.Target(self.head_sphere)
            self.head_sphere.alpha(0)
            self.head_sphere.collideSphere()
            self.head_sphere.disable(viz.DYNAMICS)
Beispiel #3
0
	def load(self, dataset = 'right arm'):
		"""
		Load datasets and initialize everything necessary to commence
		the puzzle game. Customized for test mode.
		"""
		
		# Dataset
		model.ds = model.DatasetInterface()
		
		self._quizPanel = view.TestSnapPanel()
		self._quizPanel.toggle()

		# Proximity management
		model.proxManager = vizproximity.Manager()
		target = vizproximity.Target(model.pointer)
		model.proxManager.addTarget(target)

		model.proxManager.onEnter(None, self.EnterProximity)
		model.proxManager.onExit(None, self.ExitProximity)
	
		#Setup Key Bindings
		self.bindKeys()
		
		# start the clock
		time.clock()

		self.score = PuzzleScore(self.modeName)
		
#		viztask.schedule(soundTask(glove))
		self._meshesToLoad = model.ds.getOntologySet(dataset)
		self.loadMeshes(self._meshesToLoad)

		# Hide all of the meshes
		for m in self._meshes:
			m.disable()
		
		# Randomly select keystone(s)
		rand = random.sample(self._meshes, 3)
		print rand
		self._keystones += rand
		rand[0].enable()
		rand[0].setPosition([0.0,1.5,0.0])
		rand[0].setEuler([0.0,90.0,180.0])
		rand[0].group.grounded = True
		for m in rand[1:]:
			m.enable()
			self.snap(m, rand[0], add = False)
			print 'snapping ', m.name
		
		# Randomly enable some adjacent meshes
		keystone = random.sample(self._keystones, 1)[0]
		self._keystoneAdjacent.update({keystone:[]})
		for m in self.getAdjacent(keystone, self.getDisabled())[:4]:
			print m
			m.enable(animate = False)
		self.pickSnapPair()
    def proximity_target(proximity_manager, target):
        """
        Creates and adds a target to the proximity manager.

        Args:
            proximity_manager:
            target:

        Returns:

        """

        target = vizproximity.Target(target)
        proximity_manager.addTarget(target)

        return target
	def load(self, dataset = 'right arm'):
		"""
		Load datasets and initialize everything necessary to commence
		the puzzle game. Customized for test mode.
		"""
		
		# Dataset
		model.ds = bp3d.DatasetInterface()
		

		# Proximity management
		model.proxManager = vizproximity.Manager()
		target = vizproximity.Target(model.pointer)
		model.proxManager.addTarget(target)

		model.proxManager.onEnter(None, self.EnterProximity)
		model.proxManager.onExit(None, self.ExitProximity)
		
		#create list of meshes to load
		self._meshesToLoad = model.ds.getOntologySet(dataset)
		self._filesToPreSnap = model.ds.getPreSnapSet()
		
		#create and add quiz panel
		self._quizPanel = puzzleView.TestSnapPanel()
		self._quizPanel.toggle()
		
		#load and prep meshes
		viz.MainWindow.setScene(viz.Scene2) #change to loading screen scene
		yield self.loadControl(self._meshesToLoad)
		yield self.prepareMeshes()
		yield self.preSnap()
		yield self.addToBoundingBox(self._meshes)
		yield self.disperseRandom(self._boundingBoxes.values())
		yield self.setKeystone(3)
		yield self.testPrep()
		yield self.hideMeshes()
		yield rotateAbout(self._boundingBoxes.values(), [0,0,0], [0,90,0])
		viz.MainWindow.setScene(viz.Scene1) #change back to game scene
		
		# Setup Key Bindings
		self.bindKeys()
		
		#Schedule closest bone calculation
		viztask.schedule(self.updateClosestBone)
	def load(self, dataset):
		"""
		Load datasets and initialize everything necessary to commence
		the puzzle game.
		"""
		
		# Dataset
		model.ds = bp3d.DatasetInterface()

		# Proximity management
		model.proxManager = vizproximity.Manager()
		target = vizproximity.Target(model.pointer)
		model.proxManager.addTarget(target)

		model.proxManager.onEnter(None, self.EnterProximity)
		model.proxManager.onExit(None, self.ExitProximity)

		#Setup Key Bindings
		self.bindKeys()
		

		self.score = PuzzleScore(self.modeName)
		
#		viztask.schedule(soundTask(glove))

		self._meshesToLoad = model.ds.getOntologySet(dataset)
		self._filesToPreSnap = model.ds.getPreSnapSet()
		
		viz.MainWindow.setScene(viz.Scene2) #change to loading screen scene
		yield self.loadControl(self._meshesToLoad)
		yield self.addToBoundingBox(self._meshes)
		yield self.prepareMeshes()
		yield self.disperseRandom(self._boundingBoxes.values())
		yield self.preSnap()
		yield self.setKeystone(3)
		yield rotateAbout(self._boundingBoxes.values() + self._meshes, [0,0,0], [0,90,0])
		viz.MainWindow.setScene(viz.Scene1) #change back to game scene
#		yield self.enableSlice()

		viztask.schedule(self.updateClosestBone())
Beispiel #7
0
	def load(self, dataset = 'right arm'):
		"""
		Load datasets and initialize everything necessary to commence
		the puzzle game.
		"""
		
		# Dataset
		model.ds = model.DatasetInterface()

		# Proximity management
		model.proxManager = vizproximity.Manager()
		target = vizproximity.Target(model.pointer)
		model.proxManager.addTarget(target)

		model.proxManager.onEnter(None, self.EnterProximity)
		model.proxManager.onExit(None, self.ExitProximity)
	
		#Setup Key Bindings
		self.bindKeys()
		
		# start the clock
		time.clock()

		self.score = PuzzleScore(self.modeName)
		
#		viztask.schedule(soundTask(glove))

		self._meshesToLoad = model.ds.getOntologySet(dataset)
		self.loadMeshes(self._meshesToLoad)

		# Set Keystone
		for m in [self._meshes[i] for i in range(0,1)]:
			m.setPosition([0.0,1.5,0.0])
			m.setEuler([0.0,90.0,180.0])
			m.group.grounded = True
			self._keystones.append(m)
Beispiel #8
0
        tmp_color = [0, 1, 2]
        tmp_color.remove(lastColor)
        lastColor = random.choice(tmp_color)
        yield viztask.waitTime(0.75)


def reactTime():
    clicktime = viz.tick()
    sub_rt.write(',' + str(clicktime))


vizact.onkeydown('.', reactTime)

manager = vizproximity.Manager()

target = vizproximity.Target(view)
manager.addTarget(target)


# Experiment Set up
def trials(block_no, vis_dist, isDisks=False):
    info.setText("Hurrah!! Please wait for the experimenter.")
    for m in range(4):
        vis_pos = [0, real_tg - vis_dist, vis_dist]
        sensor_Target = vizproximity.Sensor(
            vizproximity.RectangleArea([6, 0.1],
                                       center=[0,
                                               real_tg_dist[(-1)**(m + 1)]]),
            None)
        manager.addSensor(sensor_Target)
Beispiel #9
0
def pointerInput(mode, pointer, arena):
	viz.phys.enable()
	"""
	Initialize the pointer tool
	
	Mode selection:
		0 - Keyboard driven
		1 - Spacemouse (WARNING: potential conflict with camera mode 1)
	"""
	
	proxy = vizproximity.Manager()
	proxy.setDebug(viz.TOGGLE)
	
#	theSensor = vizproximity.addBoundingBoxSensor(arena, scale = [0.95, 0.95, 0.95])
	theTarget = vizproximity.Target(pointer)
	
#	proxy.addSensor(theSensor)
	proxy.addTarget(theTarget)
		
	vizact.onkeydown('l',pointer.setPosition,[0,1,0])
	vizact.onkeydown('l',pointer.setVelocity,[0,0,0])	
	vizact.onkeydown('l',pointer.setAngularVelocity,[0,0,0])
	
	if mode == 0:
		# Keyboard driven pointer, in case you don't have a space mouse
		# wx/da/ez control
		
		#For keyboard controls the glove is only linked via orientation
		#linking via position was causing issues with the camera focusing feature
		#fixedRotation = viz.link(viz.MainView,pointer)
		#fixedRotation.setMask(viz.LINK_ORI)
		
		speed = 3.0
		vizact.whilekeydown('w',pointer.setPosition,[0,vizact.elapsed(speed),0],viz.REL_LOCAL)
		vizact.whilekeydown('x',pointer.setPosition,[0,vizact.elapsed(-speed),0],viz.REL_LOCAL)
		vizact.whilekeydown('d',pointer.setPosition,[vizact.elapsed(speed),0,0],viz.REL_LOCAL)
		vizact.whilekeydown('a',pointer.setPosition,[vizact.elapsed(-speed),0,0],viz.REL_LOCAL)
		vizact.whilekeydown('e',pointer.setPosition,[0,0,vizact.elapsed(speed)],viz.REL_LOCAL)
		vizact.whilekeydown('z',pointer.setPosition,[0,0,vizact.elapsed(-speed)],viz.REL_LOCAL)
		
	elif mode == 1:
		# Set up pointer control with the Spacemouse
		connexion = viz.add('3dconnexion.dle')
		device = connexion.addDevice()		

		def buttonPress(e):
			pointer.setPosition([0,1,0])
			pointer.setVelocity([0,0,0])
			pointer.setAngularVelocity([0,0,0])
			
		viz.callback(viz.SENSOR_DOWN_EVENT,buttonPress)
		
		#call this every loop
		#all of this should likely go in controls, we need to fix controls!! -ADE
		def getCoords(source, destination, log = False):
			"""
			source should be a 3D connection device, and 
			the destination should be a 3d node type
			"""
			while True:
				yield viztask.waitTime( .01 ) 
				position	= source.getRawTranslation()
				orientation	= source.getRawRotation()
				
				#sets the velocity of the glove (destination) to zero 
				destination.setVelocity([0,0,0], viz.ABS_GLOBAL)
				destination.setAngularVelocity([0,0,0] ,viz.ABS_GLOBAL)
				
				#if selected do log scale on orientation
				if log:
					config.SMEulerScale= [0.5, 0.5 , 0.5]
					orientation = logScale(orientation)

				#rescale position
				position	= list(numpy.multiply(position,config.SMPositionScale))
				orientation	= list(numpy.multiply(orientation,config.SMEulerScale))
				
				#invert signs of x and z 
				x,y,z = position
				
				#invert signs of x and z rotations, and exchange b and a
				a,b,g		= orientation
				orientation	= [b,a,g]
				
				destination.setPosition(position, viz.REL_PARENT)
				destination.setEuler(orientation, viz.REL_PARENT)

		#schedule controller loop with viztask scheduler
		viztask.schedule(getCoords(device, pointer))
		
		return device
		
	else:
		raise ValueError('Invaid control mode selection')	
Beispiel #10
0
INSTRUCTIONS = """
{} bombs are to be defused in the city. You have {} seconds to get to each of them.
Use the mouse to move around. The locations of the bombs include
a the school, school bus, trash can, by the bench etc be very observant while looking
for the bomb so you do not run out of time and blow up the city.
Press spacebar to begin the bomb defusal game!""".format(
    TRIAL_COUNT, TRIAL_DURATION)

RESULTS = """You found {} of {} bombs."""

TRIAL_SUCCESS = 'Bomb found!'
TRIAL_FAIL = 'Failed, Please evacuate !!'

# Add main viewpoint as proximity target
manager = vizproximity.Manager(viz.MainView)
manager.addTarget(vizproximity.Target(viz.MainView))

# Create sensors attached to static matrix
#Bomb in car
sensor = vizproximity.Sensor(vizproximity.Sphere(15.0),
                             source=viz.Matrix.translate(-85, 0.3, 30))

#Bomb in small building
sensor2 = vizproximity.Sensor(vizproximity.Sphere(15.0),
                              source=viz.Matrix.translate(-15, 0, -25))

#Bomb in school
sensor3 = vizproximity.Sensor(vizproximity.Sphere(15.0),
                              source=viz.Matrix.translate(70, 0, -20))

#Bomb under bench
Beispiel #11
0
monitor_record_Network = viz.addNetwork('SimonR-PC')
VRPNhost = 'SimonR-PC'

# Setup VRPN
vrpn = viz.add('vrpn7.dle')
head = vrpn.addTracker('Tracker0@' + VRPNhost, 9)
body = vrpn.addTracker('Tracker0@' + VRPNhost, 10)
tracker = vrpn.addTracker('Tracker0@' + VRPNhost, 4)
head.swapPos([1, 2, -3])
head.swapQuat([-1, -2, 3, 4])
body.swapPos([1, 2, -3])
body.swapQuat([-1, -2, 3, 4])

# Set up proximity sensor
manager = vizproximity.Manager()
target = vizproximity.Target(head)
manager.addTarget(target)


# LED flashing for single trial
class LEDs(object):
    def __init__(self, colors, highTime, lowTime):
        self.taskHandle = Task()
        self.taskHandle.CreateDOChan('Dev1/port0/line0:7', '',
                                     DAQmx_Val_ChanForAllLines)
        self.colors = colors
        self.on = numpy.array([0, 1, 1, 1, 1, 1, 1, 0], dtype=uInt8)
        self.red1 = numpy.array([0, 0, 0, 0, 1, 0, 0, 0], dtype=uInt8)
        self.red2 = numpy.array([0, 1, 0, 0, 0, 0, 0, 0], dtype=uInt8)
        self.yellow1 = numpy.array([0, 0, 0, 0, 0, 0, 1, 0], dtype=uInt8)
        self.yellow2 = numpy.array([0, 0, 0, 1, 0, 0, 0, 0], dtype=uInt8)
Beispiel #12
0
    def __init__(self, canvas):

        sf = 0.5
        model.pointer.setEuler(0, 0, 0)
        model.pointer.setPosition(0, 0, 0)
        self.gloveStart = model.pointer.getPosition()
        self.iterations = 0
        self.canvas = canvas
        self.origPosVec = config.positionVector
        self.origOrienVec = config.orientationVector

        #creating directions panel
        #		viz.mouse.setVisible(False)
        #		directions = vizinfo.InfoPanel('', fontSize = 10, parent = canvas, align = viz.ALIGN_LEFT_TOP, title = 'Tutorial', icon = False)
        #		if config.pointerMode ==0:
        #			directions.addItem(viz.addText('Keyboard Controls:'))
        #			directions.addLabelItem(viz.addText('W'))
        #
        #		if config.pointerMode ==1:
        #			directions.addItem(viz.addText('Spacemouse Controls:'))
        #			directions.addItem(viz.addTexQuad(size = 300, parent = canvas, texture = viz.addTexture('.\\mouse key.png')))

        #creating tutorial objects
        self.dog = viz.addChild('.\\dataset\\dog\\dog.obj')
        self.dogOutline = viz.addChild('.\\dataset\\dog\\dog.obj')
        self.dogStart = self.dog.getPosition()
        self.dog.setScale([sf, sf, sf])
        self.dogOutline.setScale([sf, sf, sf])
        self.startColor = model.pointer.getColor()

        #creating dog outline
        self.dogOutline.alpha(0.8)
        self.dogOutline.color(0, 5, 0)
        self.dogOutline.texture(None)

        #creating proximity manager
        self.manager = vizproximity.Manager()
        '''creating dog grab and snap sensors around sphere palced in the center of the dog'''
        self.dogCenter = vizshape.addSphere(0.1, pos=(self.dogStart))
        self.dogSnapSensor = vizproximity.Sensor(vizproximity.Sphere(
            0.35, center=[0, 1, 0]),
                                                 source=self.dogCenter)
        self.outlineCenter = vizshape.addSphere(0.1, pos=(self.dogStart))

        self.dogCenter.setPosition([0, -.35, 0])
        self.outlineCenter.setPosition([0, -.35, 0])

        self.centerStart = self.dogCenter.getPosition()
        self.dogGrab = viz.grab(self.dogCenter, self.dog)
        self.outlineGrab = viz.grab(self.outlineCenter, self.dogOutline)

        self.dogCenter.color(5, 0, 0)
        self.outlineCenter.color(0, 5, 0)
        self.dogCenter.visible(viz.OFF)
        self.outlineCenter.visible(viz.OFF)

        self.dogSnapSensor = vizproximity.Sensor(vizproximity.Sphere(
            0.35, center=[0, 1, 0]),
                                                 source=self.dogCenter)
        self.manager.addSensor(self.dogSnapSensor)
        self.dogGrabSensor = vizproximity.Sensor(vizproximity.Sphere(
            0.85, center=[0, 1, 0]),
                                                 source=self.dogCenter)
        self.manager.addSensor(self.dogGrabSensor)
        '''creating glove target and a dog target. the dog target is a sphere placed at the center of the dog outline'''
        self.gloveTarget = vizproximity.Target(model.pointer)
        self.manager.addTarget(self.gloveTarget)
        self.dogTargetMold = vizshape.addSphere(0.2,
                                                parent=self.dogOutline,
                                                pos=(self.dogStart))
        self.dogTargetMold.setPosition([0, 1.2, 0])
        self.dogTargetMold.visible(viz.OFF)
        self.dogTarget = vizproximity.Target(self.dogTargetMold)
        self.manager.addTarget(self.dogTarget)

        #manager proximity events
        self.manager.onEnter(self.dogGrabSensor, EnterProximity,
                             self.gloveTarget, model.pointer)
        self.manager.onExit(self.dogGrabSensor, ExitProximity, model.pointer,
                            self.startColor)
        self.manager.onEnter(self.dogSnapSensor, snapCheckEnter,
                             self.dogTarget)
        self.manager.onExit(self.dogSnapSensor, snapCheckExit,
                            self.dogTargetMold)

        #reset command
        self.keybindings = []
        self.keybindings.append(
            vizact.onkeydown('l', resetGlove, self.manager, self.gloveStart,
                             self.dogCenter, self.outlineCenter))
        self.keybindings.append(vizact.onkeydown('p', self.debugger))

        #task schedule
        self.interface = viztask.schedule(self.interfaceTasks())
        self.gameMechanics = viztask.schedule(self.mechanics())
Beispiel #13
0
sphere3 = vizshape.addSphere(radius=.1)
sphere3.setPosition(8.62, .3, 12)
sphere3.color(0, 0, 1)  #blue
sphere3physics = sphere3.collideSphere(bounce=1.5)

shapes = [sphere1, sphere2, sphere3]
grabber = vizconnect.getRawTool('grabber')
grabber.setItems(shapes)

#rgb boxes
p1 = vizshape.addCube(size=1)
p1.color(1, 0, 0)
p1.setPosition(9, 0, 10)
p1p = p1.collideBox()
sensor1 = vizproximity.addBoundingBoxSensor(p1)
target1 = vizproximity.Target(sphere1)

p2 = vizshape.addCube(size=1)
p2.color(0, 1, 0)
p2.setPosition(9, 0, 8)
p2p = p2.collideBox()
sensor2 = vizproximity.addBoundingBoxSensor(p2)
target2 = vizproximity.Target(sphere2)

p3 = vizshape.addCube(size=1)
p3.color(0, 0, 1)
p3.setPosition(9, 0, 6)
p3p = p3.collideBox()
sensor3 = vizproximity.addBoundingBoxSensor(p3)
target3 = vizproximity.Target(sphere3)
texto = viz.addText('',parent=viz.SCREEN, pos=[0.005,0.927,0], scale=[0.5,0.5,1], color = viz.PURPLE)

#INICIALIZACIÓN DE LOS PROXIMITY SENSORS    
# Create proximity manager
manager = vizproximity.Manager()
manager.setDebug(True)

# Add the tracker (hand) as proximity target
#target =  vizproximity.Target(viz.MainView)
#Add the object that will do the grabbing   PARA CONTROL EN LA COMPU
hand = viz.addChild('marker.wrl')
mouseTracker = viztracker.MouseTracker()
mouseTracker.scroll(-8)
item = viz.link(mouseTracker,hand)

target = vizproximity.Target(item)#PARA CONTROL EN LA COMPU
#target = vizproximity.Target(rightHand) #DESCOMENTAR ESTO PARA LA SALA DE RV
manager.addTarget(target)


#-------------------------------ABRIR Y CERRAR PUERTAS-------------------------------------------------------

#ABRIR Y CERRAR PUERTA SALA DE CONTROL

DoorSC_GEODE = lab.getChild('Door sala control').getChild ('Box010')
Chapa = lab.getChild ('Chapa')
Cilindro = lab.getChild('Cylinder001')
link_DoorSC = viz.link(DoorSC_GEODE, Chapa)
link2_DoorSC = viz.link(DoorSC_GEODE, Cilindro)

sensor_DoorSC = vizproximity.addBoundingSphereSensor(DoorSC_GEODE, scale = .8)
    stacks=20)  #Adding a sphere to represent user's fingertip
#left_main_sphere=vizshape.addSphere(radius=.01,slices=20,stacks=20) #Adding a sphere to represent user's fingertip
#viz.link(handTracker, main_sphere) #Linking sphere to vizconnect tracking of the hand
viz.link(leftHand, main_sphere)
viz.MainView.setPosition([0, 15, -15
                          ])  #~Made it slightly lower for mouse and keyboard

#Create proximity manager to manage sensors____________________________________

manager = vizproximity.Manager()
manager.setDebug(
    viz.OFF)  #Turn on to add wireframe, done below with keypress 'l'
vizact.onkeydown('l', manager.setDebug, viz.TOGGLE)

# Setting hand tracked position as target
right_hand = vizproximity.Target(handTracker)
left_hand = vizproximity.Target(leftHand)
manager.addTarget(left_hand)
manager.addTarget(right_hand)

# Visual grid that appears on floor
grid = vizshape.addGrid(color=[0.2] * 3)
viz.clearcolor(viz.GRAY)
#~ can be removed, kept for reference of spacial dimensions
#table= vizshape.addBox([1.05,.000000001,.495],right=True,left=True,top=True,bottom=True, front=True,back=True, splitFaces=False, color= viz.PURPLE)
#table.setPosition(0,.76-.001,.23)

#Timer Functions___________________________________________________________________________________
"""
Used to check if participant left the start sensor early.
Beispiel #16
0
#	def playXylo2(self):
#		self.play('xylo32.wav')
#	def playXylo2(self):
#		self.play('xylo33.wav')
#	def playXylo2(self):
#		self.play('xylo34.wav')
#	def playXylo2(self):
#		self.play('xylo35.wav')

sp = SoundPlayer()

enteredDir = None

rHand = vizconnect.getAvatar().getAttachmentPoint('r_hand').getNode3d()
lHand = vizconnect.getAvatar().getAttachmentPoint('l_hand').getNode3d()
rHandTar = vizproximity.Target(rHand)
lHandTar = vizproximity.Target(lHand)


class DirectionUpdater:
    def __init__(self):
        self.rHandPre = rHand.getPosition()
        self.rHandPost = rHand.getPosition()
        self.lHandPre = lHand.getPosition()
        self.lHandPost = lHand.getPosition()
        self.fist = True

    def upadate(self):
        #if self.fist:
        if abs(self.rHandPost[1] - vizconnect.getAvatar().getAttachmentPoint(
                'r_hand').getNode3d().getPosition()[1]) > 0.01 or abs(
Beispiel #17
0
        record.write(data)
        yield viztask.waitTime(1 / 75)


# Set up a calibration at the beginning of each trial
manager_cali = vizproximity.Manager()
# First create a transparent ball
eyepatch = viz.addTexQuad(parent=viz.HEAD, color=viz.CYAN, size=1)
eyepatch.setPosition([0, 0, 5], viz.ABS_PARENT)
eyepatch.alpha(0.5)
eyepatch.visible(viz.OFF)
# Set up sensor
sensor = vizproximity.Sensor(vizproximity.Box(size=[0.4, 0.4, 2]),
                             source=Cross)
# Set up target
target_cali = vizproximity.Target(eyepatch)
# Add sensor and target
manager_cali.addSensor(sensor)
manager_cali.addTarget(target_cali)

# Set up the information panel
info = hmd.addMessagePanel('', pos=(0, 0, 3))
info.visible(viz.OFF)

# Set up the staircase
# Multiple staircases
exp_conditions = [
    {
        'label': 'Very Close',
        'name': 'Close',
        'startVal': 5
Beispiel #18
0
viz.link(tracker, viz.MainView)
viz.mouse.setVisible(False)
viz.collision(viz.ON)

viz.MainView.setPosition([4, 0, 2])
gallery = viz.addChild('gallery.osgb')

#-----------Info panel set up--------------------
import vizinfo
#Add info panel to display messages to participant
instructions = vizinfo.InfoPanel(icon=False, key=None)
#------------------------------------------------

#-----------Sensor creation----------------------
import vizproximity
target = vizproximity.Target(viz.MainView)

viewPath = []
inTime = 0

MainViewApproaches = 0
sensor1 = vizproximity.Sensor(
    vizproximity.RectangleArea([3, 1], center=[-4, 0.375]), None)
sensor2 = vizproximity.Sensor(
    vizproximity.RectangleArea([2.25, 2.25], center=[-4, 2.5]), None)
sensor3 = vizproximity.Sensor(
    vizproximity.RectangleArea([3, 1], center=[-4, 4.75]), None)
sensor4 = vizproximity.Sensor(
    vizproximity.RectangleArea([2.25, 1.5], center=[-4, 6.75]), None)
sensor5 = vizproximity.Sensor(vizproximity.CircleArea(0.75, center=[2, 7.5]),
                              None)
Beispiel #19
0
def pointerInput(mode, pointer, arena):
    viz.phys.enable()
    """
	Initialize the pointer tool
	
	Mode selection:
		0 - Keyboard driven
		1 - Spacemouse (WARNING: potential conflict with camera mode 1)
	"""

    proxy = vizproximity.Manager()
    proxy.setDebug(viz.TOGGLE)
    theSensor = vizproximity.addBoundingBoxSensor(arena, scale=[.95, .95, .95])
    theTarget = vizproximity.Target(pointer)

    proxy.addSensor(theSensor)
    proxy.addTarget(theTarget)

    def EnterProximity(e):
        #print('Hit the wall')
        pointer.setVelocity([0, 0, 0])
        pointer.setAngularVelocity([0, 0, 0])
        print(e.target.getPosition())
        temp = e.target.getPosition()
        #pointer.setPosition([1,1,1])

    def ExitProximity(e):
        #print('Hit the wall')
        x, y, z = pointer.getPosition()

        if (y < .4):
            y = .5
        elif (y > 4.5):
            y = 4.4
        if (abs(x) > abs(z) and abs(x) > 5):
            if (x < 0):
                x = -4.9
            else:
                x = 4.9
        elif (abs(z) > 4):
            if (z < 0):
                z = -3.9
            elif (z > 0):
                z = 3.9
        pointer.setPosition(x, y, z)
        pointer.setVelocity([0, 0, 0])
        pointer.setAngularVelocity([0, 0, 0])

    proxy.onEnter(None, EnterProximity)
    proxy.onExit(None, ExitProximity)

    vizact.onkeydown('l', pointer.setPosition, [0, 1, 0])
    vizact.onkeydown('l', pointer.setVelocity, [0, 0, 0])
    vizact.onkeydown('l', pointer.setAngularVelocity, [0, 0, 0])

    if mode == 0:
        # Keyboard driven pointer, in case you don't have a space mouse
        # wx/da/ez control

        #For keyboard controls the glove is only linked via orientation
        #linking via position was causing issues with the camera focusing feature
        #fixedRotation = viz.link(viz.MainView,pointer)
        #fixedRotation.setMask(viz.LINK_ORI)

        speed = 3.0
        vizact.whilekeydown('w', pointer.setPosition,
                            [0, vizact.elapsed(speed), 0], viz.REL_LOCAL)
        vizact.whilekeydown('x', pointer.setPosition,
                            [0, vizact.elapsed(-speed), 0], viz.REL_LOCAL)
        vizact.whilekeydown('d', pointer.setPosition,
                            [vizact.elapsed(speed), 0, 0], viz.REL_LOCAL)
        vizact.whilekeydown('a', pointer.setPosition,
                            [vizact.elapsed(-speed), 0, 0], viz.REL_LOCAL)
        vizact.whilekeydown('e', pointer.setPosition,
                            [0, 0, vizact.elapsed(speed)], viz.REL_LOCAL)
        vizact.whilekeydown('z', pointer.setPosition,
                            [0, 0, vizact.elapsed(-speed)], viz.REL_LOCAL)

    elif mode == 1:
        # Set up pointer control with the Spacemouse
        connexion = viz.add('3dconnexion.dle')
        device = connexion.addDevice()

        def buttonPress(e):
            pointer.setPosition([0, 1, 0])
            pointer.setVelocity([0, 0, 0])
            pointer.setAngularVelocity([0, 0, 0])

        viz.callback(viz.SENSOR_DOWN_EVENT, buttonPress)

        #device.setTranslateScale([1,1,1])
        #device.setRotateScale([0,0,0]) # i don't think we need this

        #add 3Dnode object that follows mainview exactly, called MainViewShadow
        #		MainViewShadow = vizshape.addSphere(radius = .5)
        #		MainViewShadow.disable(viz.RENDERING)
        #		viz.link(viz.MainView, MainViewShadow)

        #make glove () child of MainViewShadow

        #fixedRotation = viz.link(MainViewShadow,pointer)
        #fixedRotation.setMask(viz.LINK_ORI)
        #pointer.setParent(MainViewShadow)

        #call this every loop
        #all of this should likely go in controls, we need to fix controls!! -ADE
        def getCoords(source, destination):
            """
			source should be a 3D connection device, and 
			the destination should be a 3d node type
			"""
            def logScale(orientation):
                """ 
				list or len() = 3 -> list of len 3 
				takes the orintation list and returns the log of
				the magnitude of each element , and then keeps the 
				original sign
				
				ex) [ 10 , -10 ,1000] -> [1 , -1, 3]
				
				"""
                import math
                base = 2
                mag_orientation = []
                sign = []  #list of signs

                #make all elements positive, store original signs
                for element in orientation:
                    if math.fabs(element) == element:
                        #element is positive
                        mag_orientation.append(element)
                        sign.append(1)
                    else:
                        #element is negative
                        mag_orientation.append(-1 * element)
                        sign.append(-1)
                #handle case where number is zero, and set to 1
                n = 0
                for element in mag_orientation:
                    if element == 0:
                        mag_orientation[n] = 1
                    n += 1

                #take log of each element
                log_orientation = []
                for element in mag_orientation:
                    log = math.log(element, base)
                    log_orientation.append(log)

                #restablish original signs
                orientation = scalarMult(sign, log_orientation)
                return orientation

            #set source scale


#			scale1 = [.0001,.0001,.0001]
#			scale2 =[.01,.01,.01]

#log
            log = False

            while True:
                yield viztask.waitTime(.01)
                position = source.getRawTranslation()
                orientation = source.getRawRotation()

                #sets the velocity of the glove (destination) to zero
                destination.setVelocity([0, 0, 0], viz.ABS_GLOBAL)
                destination.setAngularVelocity([0, 0, 0], viz.ABS_GLOBAL)

                #if selected do log scale on orientation
                if log == True:
                    config.orientationVector = [.5, .5, .5]
                    orientation = logScale(orientation)

                #rescale position
                position = scalarMult(position, config.positionVector)
                orientation = scalarMult(orientation, config.orientationVector)

                #invert signs of x and z
                x, y, z = position

                #invert signs of x and z rotations, and exchange b and a
                a, b, g = orientation
                orientation = [b, a, g]

                #print(orientation)
                destination.setPosition(position, viz.REL_PARENT)
                destination.setEuler(orientation, viz.REL_PARENT)

        def scalarMult(lst1, lst2):
            """ 
			takes 2 lists, and returns the scalar 
			multiplication of the lists
			*lists must be the same length
			"""
            new_lst = []
            for i in range(len(lst1)):
                n_val = lst1[i] * lst2[i]
                new_lst.append(n_val)

            return new_lst

        #schedule controller loop with viztask scheduler
        viztask.schedule(getCoords(device, pointer))

        #vizact.ontimer2(.01,1, delayedSet )

        #viz.link(device, pointer, viz.REL_PARENT)
        #link.preEuler([0,90,0])

        return device

    else:
        raise ValueError('Invaid control mode selection')

    #question guys. if keyboard is selected, should  the init script call code
    #in the control module to set the functions? - Alex