This repository was archived by the owner on Jul 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1792 lines (1258 loc) · 57.2 KB
/
main.py
File metadata and controls
1792 lines (1258 loc) · 57.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Runs an experiment.
Things required for transition to PandA Lab setup:
- rename performLabVR2.cfg as <machineName>.cfg
- replace all mocap calls with those particular to your system. I tried to mark them with MOCAP
- buy a wiimote, or goto <experiment>.registerWiimoteActions and associate the callbacks with keyboard presses
- d
90
"""
viz.res.addPath('resources')
sys.path.append('utils')
import viz
import viztask
import vizshape
import vizact
from drawNumberFromDist import *
import ode
import datetime
from ctypes import * # eyetrackka
import winsound
import virtualPlane
import vizinput
import time
import numpy as np
#import visEnv12
#import physEnv
import visEnv
import physEnv
#For hardware configuration
viz.res.addPath('resources')
sys.path.append('utils')
from configobj import ConfigObj
from configobj import flatten_errors
from validate import Validator
import platform
import os.path
import vizconnect
expConfigFileName = 'exampleExpConfig.cfg'
useNetwork = True;
############################
if( useNetwork ):
networkClient = 'performLabVR2'.upper()
viz.net.addPort(5000) # Send data over port 5000
def appendTrialToEndOfBlock(e):
experimentObject.appendTrialToEndOfBlock()
import winsound
Freq = 1500 # Set Frequency To 2500 Hertz
Dur = 100 # Set Duration To 1000 ms == 1 second
winsound.Beep(Freq,Dur)
class NumberCount():
def __init__(self):
pass
def startPresentingNumbers(self):
pass
def stopPresentingNumbers(self):
pass
def onNetwork(netPacket):
print 'Received network message'
if netPacket.sender.upper() == networkClient:
experimentObject.eventFlag.setStatus(8)
netPacket.action(netPacket)
viz.callback(viz.NETWORK_EVENT, onNetwork)
#############################
ft = .3048
inch = 0.0254
m = 1
eps = .01
nan = float('NaN')
# Create a globally accessible soundbank.
# To access within a member function,
# import the global variable with 'global soundbank'
class soundBank():
def __init__(self):
################################################################
################################################################
## Register sounds. It makes sense to do it once per experiment.
self.bounce = '/Resources/bounce.wav'
self.buzzer = '/Resources/BUZZER.wav'
self.bubblePop = '/Resources/bubblePop3.wav'
self.highDrip = '/Resources/highdrip.wav'
self.cowbell = '/Resources/cowbell.wav'
self.beep = '/Resources/beep.wav'
self.gong = '/Resources/gong.wav'
self.beep_f = '/Resourcs/beep_Spike.wav'
self.go = '/Resourcs/go.wav'
self.noObstacle = '/Resources/No_Obstacle.wav'
viz.playSound(self.go,viz.SOUND_PRELOAD)
viz.playSound(self.gong,viz.SOUND_PRELOAD)
viz.playSound(self.beep,viz.SOUND_PRELOAD)
viz.playSound(self.bounce,viz.SOUND_PRELOAD)
viz.playSound(self.buzzer,viz.SOUND_PRELOAD)
viz.playSound(self.bubblePop,viz.SOUND_PRELOAD)
viz.playSound(self.highDrip,viz.SOUND_PRELOAD)
viz.playSound(self.cowbell,viz.SOUND_PRELOAD)
viz.playSound(self.beep,viz.SOUND_PRELOAD)
viz.playSound(self.noObstacle,viz.SOUND_PRELOAD)
soundBank = soundBank()
class Configuration():
def __init__(self, expCfgName = ""):
"""
Opens and interprets both the system config (as defined by the <platform>.cfg file) and the experiment config
(as defined by the file in expCfgName). Both configurations MUST conform the specs given in sysCfgSpec.ini and
expCfgSpec.ini respectively. It also initializes the system as specified in the sysCfg.
"""
self.eyeTracker = []
self.writables = list()
if expCfgName:
self.__createExpCfg(expCfgName)
else:
self.expCfg = None
self.__createSysCfg()
for pathName in self.sysCfg['set_path']:
viz.res.addPath(pathName)
self.vizconnect = vizconnect.go( './vizConnect/' + self.sysCfg['vizconfigFileName'])
self.__postVizConnectSetup()
def __postVizConnectSetup(self):
'''
This is where one can run any system-specifiRRRc code that vizconnect can't handle
'''
dispDict = vizconnect.getRawDisplayDict()
if self.sysCfg['use_phasespace']:
from mocapInterface import phasespaceInterface
self.mocap = phasespaceInterface(self.sysCfg);
self.mocap.start_thread()
self.use_phasespace = True
else:
self.use_phasespace = False
if( self.sysCfg['use_wiimote']):
# Create wiimote holder
self.wiimote = 0
self.__connectWiiMote()
if self.sysCfg['use_hmd'] and self.sysCfg['hmd']['type'] == 'DK2':
self.__setupOculusMon()
if self.sysCfg['use_eyetracking']:
self.use_eyetracking = True
self.__connectSMIDK2()
else:
self.use_eyetracking = False
if self.sysCfg['use_DVR'] == 1:
self.use_DVR = True
else:
self.use_DVR = False
if self.sysCfg['use_virtualPlane']:
self.use_VirtualPlane = True
isAFloor = self.sysCfg['virtualPlane']['isAFloor']
planeName = self.sysCfg['virtualPlane']['planeName']
planeCornerFile = self.sysCfg['virtualPlane']['planeCornerFile']
self.virtualPlane = virtualPlane.virtualPlane(self,planeName,isAFloor,planeCornerFile)
if self.sysCfg['use_networking']:
self.use_networking = True
self.netClient = viz.addNetwork( self.sysCfg['networking']['clientName'] )
else:
self.use_networking = False
self.netClient = False
self.writer = None #Will get initialized later when the system starts
self.writables = list()
self.__setWinPriority()
viz.setMultiSample(self.sysCfg['antiAliasPasses'])
viz.MainWindow.clip(0.01 ,200)
viz.vsync(1)
viz.setOption("viz.glfinish", 1)
viz.setOption("viz.dwm_composition", 0)
def __createExpCfg(self, expCfgName):
"""
Parses and validates a config obj
Variables read in are stored in configObj
"""
print "Loading experiment config file: " + expCfgName
# This is where the parser is called.
expCfg = ConfigObj(expCfgName, configspec='expCfgSpec.ini', raise_errors = True, file_error = True)
validator = Validator()
expCfgOK = expCfg.validate(validator)
if expCfgOK == True:
print "Experiment config file parsed correctly"
else:
print 'Experiment config file validation failed!'
res = expCfg.validate(validator, preserve_errors=True)
for entry in flatten_errors(expCfg, res):
# each entry is a tuple
section_list, key, error = entry
if key is not None:
section_list.append(key)
else:
section_list.append('[missing section]')
section_string = ', '.join(section_list)
if error == False:
error = 'Missing value or section.'
print section_string, ' = ', error
sys.exit(1)
if expCfg.has_key('_LOAD_'):
for ld in expCfg['_LOAD_']['loadList']:
print 'Loading: ' + ld + ' as ' + expCfg['_LOAD_'][ld]['cfgFile']
curCfg = ConfigObj(expCfg['_LOAD_'][ld]['cfgFile'], configspec = expCfg['_LOAD_'][ld]['cfgSpec'], raise_errors = True, file_error = True)
validator = Validator()
expCfgOK = curCfg.validate(validator)
if expCfgOK == True:
print "Experiment config file parsed correctly"
else:
print 'Experiment config file validation failed!'
res = curCfg.validate(validator, preserve_errors=True)
for entry in flatten_errors(curCfg, res):
# each entry is a tuple
section_list, key, error = entry
if key is not None:
section_list.append(key)
else:
section_list.append('[missing section]')
section_string = ', '.join(section_list)
if error == False:
error = 'Missing value or section.'
print section_string, ' = ', error
sys.exit(1)
expCfg.merge(curCfg)
self.expCfg = expCfg
def __setWinPriority(self,pid=None,priority=1):
""" Set The Priority of a Windows Process. Priority is a value between 0-5 where
2 is normal priority. Default sets the priority of the current
python process but can take any valid process ID. """
import win32api,win32process,win32con
priorityclasses = [win32process.IDLE_PRIORITY_CLASS,
win32process.BELOW_NORMAL_PRIORITY_CLASS,
win32process.NORMAL_PRIORITY_CLASS,
win32process.ABOVE_NORMAL_PRIORITY_CLASS,
win32process.HIGH_PRIORITY_CLASS,
win32process.REALTIME_PRIORITY_CLASS]
if pid == None:
pid = win32api.GetCurrentProcessId()
handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
win32process.SetPriorityClass(handle, priorityclasses[priority])
def __createSysCfg(self):
"""
Set up the system config section (sysCfg)
"""
# Get machine name
sysCfgName = platform.node()+".cfg"
if not(os.path.isfile(sysCfgName)):
sysCfgName = "defaultSys.cfg"
print "Loading system config file: " + sysCfgName
# Parse system config file
sysCfg = ConfigObj(sysCfgName, configspec='sysCfgSpec.ini', raise_errors = True)
validator = Validator()
sysCfgOK = sysCfg.validate(validator)
if sysCfgOK == True:
print "System config file parsed correctly"
else:
print 'System config file validation failed!'
res = sysCfg.validate(validator, preserve_errors=True)
for entry in flatten_errors(sysCfg, res):
# each entry is a tuple
section_list, key, error = entry
if key is not None:
section_list.append(key)
else:
section_list.append('[missing section]')
section_string = ', '.join(section_list)
if error == False:
error = 'Missing value or section.'
print section_string, ' = ', error
sys.exit(1)
self.sysCfg = sysCfg
def __setupOculusMon(self):
"""
Setup for the oculus rift dk2
Relies upon a cluster enabling a single client on the local machine
THe client enables a mirrored desktop view of what's displays inside the oculus DK2
Note that this does some juggling of monitor numbers for you.
"""
#viz.window.setFullscreenMonitor(self.sysCfg['displays'])
#hmd = oculus.Rift(renderMode=oculus.RENDER_CLIENT)
displayList = self.sysCfg['displays'];
if len(displayList) < 2:
print 'Display list is <1. Need two displays.'
else:
print 'Using display number' + str(displayList[0]) + ' for oculus display.'
print 'Using display number' + str(displayList[1]) + ' for mirrored display.'
### Set the rift and exp displays
riftMon = []
expMon = displayList[1]
with viz.cluster.MaskedContext(viz.MASTER):
# Set monitor to the oculus rift
monList = viz.window.getMonitorList()
for mon in monList:
if mon.name == 'Rift DK2':
riftMon = mon.id
viz.window.setFullscreen(riftMon)
with viz.cluster.MaskedContext(viz.CLIENT1):
count = 1
while( riftMon == expMon ):
expMon = count
viz.window.setFullscreenMonitor(expMon)
viz.window.setFullscreen(1)
def __connectWiiMote(self):
wii = viz.add('wiimote.dle')#Add wiimote extension
# Replace old wiimote
if( self.wiimote ):
print 'Wiimote removed.'
self.wiimote.remove()
self.wiimote = wii.addWiimote()# Connect to first available wiimote
vizact.onexit(self.wiimote.remove) # Make sure it is disconnected on quit
self.wiimote.led = wii.LED_1 | wii.LED_4 #Turn on leds to show connection
def __connectSMIDK2(self):
if self.sysCfg['sim_trackerData']:
self.eyeTracker = smi_beta.iViewHMD(simulate=True)
else:
self.eyeTracker = smi_beta.iViewHMD()
class Experiment(viz.EventClass):
"""
Experiment manages the basic operation of the experiment.
"""
def __init__(self, expConfigFileName):
# Event class
# This makes it possible to register callback functions (e.g. activated by a timer event)
# within the class (that accept the implied self argument)
# eg self.callbackFunction(arg1) would receive args (self,arg1)
# If this were not an eventclass, the self arg would not be passed = badness.
viz.EventClass.__init__(self)
##############################################################
##############################################################
## Use config to setup hardware, motion tracking, frustum, eyeTrackingCal.
## This draws upon the system config to setup the hardware / HMD
config = Configuration(expConfigFileName)
self.config = config
# Update to reflect actual leg length of user
self.inputLegLength()
################################################################
################################################################
## Set states
self.inCalibrateMode = False
self.inHMDGeomCheckMode = False
self.setEnabled(False)
self.test_char = None
################################################################
################################################################
# Create visual and physical objects (the room)
self.room = visEnv.room(config)
viz.phys.enable()
# self.room.physEnv
self.hmdLinkedToView = False
self.directionArrow = vizshape.addArrow(color=viz.BLUE, axis = vizshape.AXIS_X, length=0.2,radiusRatio=0.05 )
self.directionArrow.setEuler([270,0,0])
self.directionArrow.setPosition([-1.1,0,-1.5])
################################################################
################################################################
# Build block and trial list
self.blockNumber = 0;
self.trialNumber = 0; # trial number within block
self.absTrialNumber = 0; # trial number within experiment
self.expInProgress = True;
self.blocks_bl = []
self.room.offsetDistance = float(config.expCfg['room']['minObstacleDistance'])
#print'====> Obstacle Distance = ', self.room.offsetDistance
for bIdx in range(len(config.expCfg['experiment']['blockList'])):
self.blocks_bl.append(block(config,bIdx, self.room));
self.currentTrial = self.blocks_bl[self.blockNumber].trials_tr[self.trialNumber]
################################################################
################################################################
## Misc. Design specific items here.
self.maxTrialDuration = config.expCfg['experiment']['maxTrialDuration']
if( config.wiimote ):
self.registerWiimoteActions()
#self.obstacleViewTimerID = viz.getEventID('obstacleViewTimerID') # Generates a unique ID.
self.numClicksBeforeGo = config.expCfg['experiment']['numClicksBeforeGo']
self.trialEndPosition = config.expCfg['experiment']['trialEndPosition']
self.metronomeTimeMS = config.expCfg['experiment']['metronomeTimeMS']
## Setup virtual plane
if( self.config.use_phasespace == True and self.config.sysCfg['virtualPlane']['attachGlassesToRigid']):
self.setupShutterGlasses()
self.setupFeet()
pass
else:
eyeSphere = visEnv.visObj(self.room,'sphere',size=0.1,alpha=1)
eyeSphere.node3D.setParent(self.room.objects)
eyeSphere = self.room.eyeSphere
eyeSphere.node3D.visible(viz.TOGGLE)
self.config.virtualPlane.attachViewToGlasses(eyeSphere.node3D,viz.MainView)
##############################################################
##############################################################
## Callbacks and timers
vizact.onupdate(viz.PRIORITY_PHYSICS,self._checkForCollisions)
self.callback(viz.KEYDOWN_EVENT, self.onKeyDown)
self.callback(viz.KEYUP_EVENT, self.onKeyUp)
self.callback( viz.TIMER_EVENT,self._timerCallback )
self.callback(viz.NETWORK_EVENT, self._networkCallback)
self.perFrameTimerID = viz.getEventID('perFrameTimerID') # Generates a unique ID.
self.starttimer( self.perFrameTimerID, viz.FASTEST_EXPIRATION, viz.FOREVER)
self.trialTimeoutTimerID = viz.getEventID('trialTimeoutTimerID') # Generates a unique ID.
##############################################################
## Data output
now = datetime.datetime.now()
dateTimeStr = str(now.year) + '-' + str(now.month) + '-' + str(now.day) + '-' + str(now.hour) + '-' + str(now.minute)
import os
dataOutPutDir = config.sysCfg['writer']['outFileDir'] + '//' +str(dateTimeStr) + '//'
#dataOutPutDir = config.sysCfg['writer']['outFileDir'] +str(dateTimeStr)
if not os.path.exists(dataOutPutDir):
os.makedirs(dataOutPutDir)
# Exp data file
self.expDataFile = open(dataOutPutDir + 'exp_data-' + dateTimeStr + '.txt','w+')
# Function to automate exp data writeout
self.writeOutDataFun = vizact.onupdate(viz.PRIORITY_LAST_UPDATE,self.writeDataToText)
# Write experiment metadata out to line 1 of exp data file12
expMetaDataStr = ''
expMetaDataStr = self.getExperimentMetaData()
self.expDataFile.write(expMetaDataStr + '\n')
if( self.config.use_phasespace == True):
# MocapInterface handles writing mocap data in a seperate thread.
#self.config.mocap.startLogging('F:\Data\Stepover')
self.config.mocap.createLog(dataOutPutDir)
from shutil import copyfile
# Copy config files
copyfile('.\\' + expConfigFileName, dataOutPutDir+expConfigFileName ) # exp config
copyfile('.\\expCfgSpec.ini', dataOutPutDir + 'expCfgSpec.ini' )# exp config spec1
copyfile('.\\'+os.environ['COMPUTERNAME'] + '.cfg', dataOutPutDir+os.environ['COMPUTERNAME'] + '.cfg')# system config
copyfile('.\\sysCfgSpec.ini', dataOutPutDir+ 'sysCfgSpec.ini') # system config spec
##############################################################
## Event flag
# Create an event flag object
# This var is set to an int on every frame
# The int saves a record of what was happening on that frame
# It can be configured to signify the start of a trial, the bounce of a ball, or whatever
self.eventFlag = eventFlag()
def _networkCallback(self,netPacket):
print '*** Received network message ***'
print netPacket.message
if( netPacket.message == 'numberTaskError' ):
self.numberTaskError()
def numberTaskError(self):
print '***numberTaskError***'
self.eventFlag.setStatus(8)
def _timerCallback(self,timerID):
mainViewPos_XYZ = viz.MainView.getPosition()
# If the subject is approaching the invisible obstalce
if( self.currentTrial.isBlankTrial is False and
self.currentTrial.approachingObs is True and
self.currentTrial.obsIsVisible is False):
boxPos_XYZ = self.room.standingBox.getPosition()
subPos_XYZ = viz.MainView.getPosition()
subDistFromStartBox = abs(subPos_XYZ[2] - boxPos_XYZ[2])
obsTriggerPosX = self.currentTrial.obsTriggerPosX
# Check if their distance is above threshold
if( subDistFromStartBox > obsTriggerPosX ):
# Present the obstacle
self.currentTrial.obsObj.node3D.enable(viz.RENDERING)
self.currentTrial.obsIsVisible = True
self.eventFlag.setStatus(3)
######################################################################
## Are the feet in the starting position?
if( self.currentTrial.approachingObs == False ):
if( self.isVisObjInBox(self.room.leftFoot) and self.isVisObjInBox(self.room.rightFoot) ):
self.currentTrial.subIsInBox = True
else:
self.currentTrial.subIsInBox = False
######################################################################
## If foot is in box, present obstacle and start metronome
if( self.currentTrial.subIsInBox is True and
self.currentTrial.waitingForGo is False ):
self.subjectHasEnteredBox()
########################################################################
## Subject has just left the box
elif( self.currentTrial.subIsInBox is False and
self.currentTrial.waitingForGo is True):
########################################
### Subject left before go signal was given!
if(self.currentTrial.goSignalGiven is False ):
self.falseStart()
##############################################
### Go signal already given. Starting the trial
elif(self.currentTrial.goSignalGiven is True):
self.startTrial()
def _checkForCollisions(self):
thePhysEnv = self.room.physEnv;
if( self.eventFlag.status == 6 or # A bit of messy schedulign. Trial ending, so collision box does not exist.
self.eventFlag.status == 7 or
thePhysEnv.collisionDetected == False or
self.expInProgress == False ):
# No collisions this time!
return
leftFoot = self.room.leftFoot
rightFoot = self.room.rightFoot
if( self.currentTrial.approachingObs == True and
self.currentTrial.isBlankTrial is False ):
obstacle = self.currentTrial.obsObj
for idx in range(len(thePhysEnv.collisionList_idx_physNodes)):
physNode1 = thePhysEnv.collisionList_idx_physNodes[idx][0]
physNode2 = thePhysEnv.collisionList_idx_physNodes[idx][1]
if( physNode1 == leftFoot.physNode and physNode2 == obstacle.physNode):
self.eventFlag.setStatus(4)
collisionLoc_XYZ,normal,depth,geom1,geom2 = thePhysEnv.contactObjects_idx[0].getContactGeomParams()
self.currentTrial.collisionLocOnObs_XYZ = collisionLoc_XYZ
viz.playSound(soundBank.bounce)
elif( physNode1 == rightFoot.physNode and physNode2 == obstacle.physNode ):
self.eventFlag.setStatus(5)
collisionLoc_XYZ,normal,depth,geom1,geom2 = thePhysEnv.contactObjects_idx[0].getContactGeomParams()
self.currentTrial.collisionLocOnObs_XYZ = collisionLoc_XYZ
viz.playSound(soundBank.bounce)
def subjectHasEnteredBox(self):
# Begin lockout period
#print 'Subject is ready and waiting in the box. Present the obstacle.'
# Yes, the head is inside the standing box
self.currentTrial.waitingForGo = True
# Metronome has been deactivated
#if( type(self.currentTrial.metronomeTimerObj) is list ):
# Start a metronome that continues for the duration of the trial
#self.currentTrial.metronomeTimerObj = vizact.ontimer2(self.metronomeTimeMS/1000, self.numClicksBeforeGo,self.metronomeLowTic)
timeUntilGoSignal = ((self.numClicksBeforeGo)*self.metronomeTimeMS)/1000
# Start the go signal timer
if( type(self.currentTrial.goSignalTimerObj) is list ):
# Start a metronome that continues for the duration of the trial
self.currentTrial.goSignalTimerObj = vizact.ontimer2(timeUntilGoSignal, 0,self.giveGoSignal)
def startTrial(self):
print 'Starting trial ==> Type', self.currentTrial.trialType
self.eventFlag.setStatus(1)
self.currentTrial.approachingObs = True
self.currentTrial.startTime = time.time()
#if( self.blockNumber > 0 ):
# Num trials from previous blocks
#absTrialNum = [absTrialNum + sum(self.blocks_bl[bIdx].numTrials) for block in self.blocks_bl[0:(self.blockNumber-1)]]
# Start logging data
self.config.mocap.writeStringToLog('Start: ' + str(self.absTrialNumber+1) )
self.config.mocap.startLogging()
# Start data collection
viz.playSound(soundBank.beep_f)
if( type(self.currentTrial.goSignalTimerObj) is not list ):
self.currentTrial.goSignalTimerObj.remove()
vizact.ontimer2(self.maxTrialDuration, 0,self.endTrial)
def falseStart(self):
# Head was removed from box after viewing was initiated
print 'Left box prematurely!'
viz.playSound(soundBank.cowbell);
# Remove box
self.currentTrial.waitingForGo = False
self.currentTrial.removeObs();
self.currentTrial.goSignalTimerObj.setEnabled(viz.TOGGLE);
self.currentTrial.goSignalTimerObj = [];
if( self.config.netClient ):
self.config.netClient.send(message="stop")
def startExperiment(self):
##This is called when the experiment should begin.
self.setEnabled(True)
def onKeyDown(self, key):
"""
Interactive commands can be given via the keyboard. Some are provided here. You'll likely want to add more.
"""
mocapSys = self.config.mocap;
if key == 't':
self.toggleWalkingDirection()
###################R#######################################
##########################################################
## Keys used in the defauRRlt mode
## More MocapInterace functions
if key == 'P':
mocapSys.resetRigid('spine')
elif key == 'S':
mocapSys.resetRigid('shutter')
elif key == 'L':
mocapSys.resetRigid('left')
#self.resizeFootBox('left')
elif key == 'R':
mocapSys.resetRigid('right')
#self.resizeFootBox('right')
elif key == 'O':
experimentObject.currentTrial.removeObs()
elif key == 'A':
self.appendTrialToEndOfBlock()
if( viz.key.isDown( viz.KEY_CONTROL_L )):
## More MocapInterace functions
if key == 'p':
mocapSys.saveRigid('spine') # MOCAP
elif key == 's':
mocapSys.saveRigid('shutter') # MOCAP
elif key == 'l':
mocapSys.saveRigid('left') # MOCAP
elif key == 'r':
mocapSys.saveRigid('right') # MOCAP
def onKeyUp(self,key):
if( key == 'v'):
pass
def getExperimentMetaData(self):
'''
Write out experiment specific metadeta
MocapInterace - some parmaeters are specific to the mocap system
'''
config = self.config
outputString = '';
outputString = outputString + 'legLengthCM %f ' % (config.legLengthCM)
outputString = outputString + 'maxTrialDuration %f ' % (self.config.expCfg['experiment']['maxTrialDuration'])
## Numblocks and block list
numBlocks = len(config.expCfg['experiment']['blockList']);
outputString = outputString + 'numBlocks %f ' % (numBlocks)
if( self.config.use_phasespace == True ):
outputString = outputString + 'mocapRefresh %f ' % (config.mocap.owlParamFrequ)
outputString = outputString + 'mocapInterp %f ' % (config.mocap.owlParamInterp)
outputString = outputString + 'mocapPostProcess %f ' % (config.mocap.owlParamPostProcess)
return outputString
def getOutput(self):
"""
Returns a string describing the current state of the experiment, useful for recording.
"""
# Fix Me:
# When the markers are not visible it should not through Error
# Legend:
# ** for 1 var
# () for 2 vars
# [] for 3 vars
# <> for 4 vars
# @@ for 16 vars (view and projection matrices)
#### Eventflag
# 1 ball launched
# 3 ball has hit floor
# 4 ball has hit paddle
# 5 ball has hit back wall
# 6 ball has timed out
## =======================================================================================================
## FrameTime, Event Flag, Trial Type
## =======================================================================================================
outputString = '';
outputString = outputString + 'frameTime %f ' % (viz.getFrameTime())
outputString = outputString + 'sysTime %f ' % (time.time())
outputString = outputString + ' eventFlag %d ' % (self.eventFlag.status)
outputString = outputString + 'isBlankTrial %d ' % (self.currentTrial.isBlankTrial)
if( self.eventFlag.status == 1 ):
outputString = outputString + ' trialType %s ' % (self.currentTrial.trialType)
## =======================================================================================================
## Obstacle Height & Location
## =======================================================================================================
if( self.currentTrial.isBlankTrial is False ):
outputString = outputString + '[ obstacle_XYZ %f %f %f ] ' % (self.currentTrial.obsLoc_XYZ[0],self.currentTrial.obsLoc_XYZ[1],self.currentTrial.obsLoc_XYZ[2])
outputString = outputString + ' obstacleHeight %f ' % (self.currentTrial.obsHeightM)
outputString = outputString + ' obsTriggerPosX %f ' % (self.currentTrial.obsTriggerPosX)
else:
outputString = outputString + '[ obstacle_XYZ %f %f %f ] ' % (np.nan,np.nan,np.nan)
outputString = outputString + ' obstacleHeight %f ' % (np.nan)
outputString = outputString + ' obsTriggerPosX %f ' % (np.nan)
outputString = outputString + ' isWalkingDownAxis %d ' % (self.room.isWalkingDownAxis)
outputString = outputString + ' trialNum %d ' % (self.trialNumber)
outputString = outputString + ' standingBoxOffset_negZ %d ' % (self.room.standingBoxOffset_negZ)
outputString = outputString + ' standingBoxOffset_posZ %d ' % (self.room.standingBoxOffset_posZ)
leftFoot_LWH = self.room.leftFoot.node3D.getBoundingBox().getSize()
outputString = outputString + ' [ leftFoot_LWH %f %f %f ] ' % (leftFoot_LWH[2], leftFoot_LWH[0], leftFoot_LWH[1])
rightFoot_LWH = self.room.rightFoot.node3D.getBoundingBox().getSize()
outputString = outputString + ' [ rightFoot_LWH %f %f %f ] ' % (rightFoot_LWH[2], rightFoot_LWH[0], rightFoot_LWH[1])
if( self.eventFlag.status == 4 or self.eventFlag.status == 5 ):
collisionPosLocal_XYZ = self.currentTrial.collisionLocOnObs_XYZ
outputString = outputString + '[ collisionLocOnObs_XYZ %f %f %f ] ' % (collisionPosLocal_XYZ[0], collisionPosLocal_XYZ[1], collisionPosLocal_XYZ[2])
## =======================================================================================================
## VisNode body positions and quaternions
## =======================================================================================================
##################################################
# Right foot
rightFootPos_XYZ = []
rightFootQUAT_XYZW = []
if( self.room.rightFoot ):
rightFootPos_XYZ = self.room.rightFoot.node3D.getPosition()
rightFootMat = self.room.rightFoot.node3D.getMatrix()
rightFootQUAT_XYZW = rightFootMat.getQuat()
else:
rightFootPos_XYZ = [None, None, None]
rightFootQUAT_XYZW = [None, None, None]
outputString = outputString + '[ rFoot_XYZ %f %f %f ] ' % (rightFootPos_XYZ[0], rightFootPos_XYZ[1], rightFootPos_XYZ[2])
outputString = outputString + '[ rFootQUAT_XYZW %f %f %f %f ] ' % ( rightFootQUAT_XYZW[0], rightFootQUAT_XYZW[1], rightFootQUAT_XYZW[2], rightFootQUAT_XYZW[3] )
##########
# Left foot
leftFootPos_XYZ = []
leftFootQUAT_XYZW = []
if( self.room.leftFoot ):
leftFootPos_XYZ = self.room.leftFoot.node3D.getPosition()
leftFootMat = self.room.leftFoot.node3D.getMatrix()
leftFootQUAT_XYZW = leftFootMat.getQuat()
else:
leftFootPos_XYZ = [None, None, None]
leftFootQUAT_XYZW = [None, None, None]
outputString = outputString + '[ lFoot_XYZ %f %f %f ] ' % (leftFootPos_XYZ[0], leftFootPos_XYZ[1], leftFootPos_XYZ[2])
outputString = outputString + '[ lFootQUAT_XYZW %f %f %f %f ] ' % ( leftFootQUAT_XYZW[0], leftFootQUAT_XYZW[1], leftFootQUAT_XYZW[2], leftFootQUAT_XYZW[3] )
##########
# Glasses
glassesPos_XYZ = []
glassesQUAT_XYZW = []
if( self.room.eyeSphere ):
glassesPos_XYZ = self.room.eyeSphere.node3D.getPosition()
glasses = self.room.eyeSphere.node3D.getMatrix()
glassesQUAT_XYZW = glasses.getQuat()
else:
glassesPos_XYZ = [None, None, None]
glassesQUAT_XYZW = [None, None, None]
outputString = outputString + '[ glasses_XYZ %f %f %f ] ' % (glassesPos_XYZ[0], glassesPos_XYZ[1], glassesPos_XYZ[2])
outputString = outputString + '[ glassesQUAT_XYZW %f %f %f %f ] ' % ( glassesQUAT_XYZW[0], glassesQUAT_XYZW[1], glassesQUAT_XYZW[2], glassesQUAT_XYZW[3] )
##########
# Mainview
headLink = self.config.virtualPlane.head_tracker
viewPos_XYZ = headLink.getPosition()
outputString = outputString + '[ viewPos_XYZ %f %f %f ] ' % (viewPos_XYZ[0],viewPos_XYZ[1],viewPos_XYZ[2])
viewQUAT_XYZW = headLink.getQuat()
outputString = outputString + '[ viewQUAT_XYZW %f %f %f %f ] ' % ( viewQUAT_XYZW[0], viewQUAT_XYZW[1], viewQUAT_XYZW[2], viewQUAT_XYZW[3] )
################################################################################################
## Record rigid body pos / quat, and marker on rigid pos
################################################################################################
if( self.eventFlag.status == 6 or self.eventFlag.status == 7 ):
mocap = self.config.mocap
#trialDuration = time.time() - self.currentTrial.startTime
return outputString #%f %d' % (viz.getFrameTime(), self.inCalibrateMode)
def toggleWalkingDirection(self):
'''
Relocates the standing box / box in which the subject stands to see the obstacle
'''
print 'Changing Direction From ' + str(self.room.isWalkingDownAxis)+' to ' + str(not(self.room.isWalkingDownAxis))
# Flip walking direction indicator
self.room.isWalkingDownAxis = not(self.room.isWalkingDownAxis)
self.standingBoxOffsetX = self.room.standingBoxOffset_X
if( self.room.isWalkingDownAxis ):
self.directionArrow.setEuler([90,0,0])