def initEvents(initFlag=vizconnect.INIT_INDEPENDENT, initList=None): #VC: place any general initialization code here rawEvent = vizconnect.getRawEventDict() #VC: initialize a new event _name = 'TOGGLE_MODEL_EVENT' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag&vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag&vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag&vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['keyboard'].isButtonDown(47):# make=Generic, model=Keyboard, name=keyboard, signal=Key V event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag&vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'RESTORE_MODEL_EVENT' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag&vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag&vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag&vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['keyboard'].isButtonDown(19):# make=Generic, model=Keyboard, name=keyboard, signal=Key R event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag&vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: return values can be modified here return None
def initEvents(initFlag=vizconnect.INIT_INDEPENDENT, initList=None): #VC: place any general initialization code here rawEvent = vizconnect.getRawEventDict() #VC: initialize a new event _name = 'CHANGE_SCENES' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag&vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag&vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag&vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['keyboard'].isButtonDown(46):# make=Generic, model=Keyboard, name=keyboard, signal=Key C event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag&vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: return values can be modified here return None
class Block(Task): '''A block represents a group of trials during an experiment. Blocks are grouped into an experiment. You should subclass this class and then, at a minimum, provide an implementation of the `generate_trials()` method to create the sequence of trials in this block. ''' PRE_RUN_EVENT = viz.getEventID('BLOCK_PRE_RUN_EVENT') POST_RUN_EVENT = viz.getEventID('BLOCK_POST_RUN_EVENT') def run(self): for trial in self.generate_trials(): yield trial.workflow() def generate_trials(self): raise NotImplementedError
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)
def __init__(self, id, sex, age, handedness, vision, cap_size, neck_size, labelscheme, 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._sex = sex self._age = age self._handedness = handedness self._vision = vision self._cap_size = cap_size self._neck_size = neck_size self._labelscheme = labelscheme # manifest and define control_style self.control_style = control_style self.use_control(control_style) # register button press events self.BUTTON_A_EVENT = viz.getEventID('A') self.BUTTON_B_EVENT = viz.getEventID('B') # instatiate some class objects that may only be used in certain control_style settings to facilitate handling if control_style == 'dk2 head hands': self.tracker = None #self.left_hand_tracker = None self.right_hand_tracker = None elif self.control_style == 'joystick': self.joy = None
def checkTaskStatus(): while animationTask.alive(): # had to do this otherwise it doesn't work because vizard libraries don't allow checking for stuff finishing # dummy event ANIMATION_TASK_ALIVE = viz.getEventID('ANIMATION_TASK_ALIVE') else: # when the animationTask finishes carry on from here because vizards libraries are bad # and the execution doesnt carry on from the place where the function was called like it should - animationTask # queuing the animation of clapping that link.setOffset([0, 0, 0]) link.setEuler([0, 0, 0])
class Experiment(Task): '''An experiment represents a group of blocks. You should subclass this class and then, at a minimum, provide an implementation of the `generate_blocks()` method to create the sequence of blocks in this experiment. ''' PRE_RUN_EVENT = viz.getEventID('EXPERIMENT_PRE_RUN_EVENT') POST_RUN_EVENT = viz.getEventID('EXPERIMENT_POST_RUN_EVENT') def run(self): for block in self.generate_blocks(): yield block.workflow() def generate_blocks(self): raise NotImplementedError def main(self, fullscreen=True): logging.info('running experiment') viz.go(viz.FULLSCREEN if fullscreen else 0) viztask.schedule(self.workflow)
class Trial(Task): '''A trial represents a single "measurement" during an experiment. Trials are grouped into blocks. You should subclass this class and then, at a minimum, provide an implementation of the `run()` method to run a single trial. class MyTrial(Trial): def run(self): print 'press the space key' start = viz.tick() yield viztask.waitKeyDown(' ') ms = 1000 * (viz.tick() - start) print 'reaction time: {:.1f}ms'.format(ms) You can set up the environment for a trial by implementing the `setup()` method, and clean up or otherwise handle the end of a trial by implementing the `teardown()` method. ''' PRE_RUN_EVENT = viz.getEventID('TRIAL_PRE_RUN_EVENT') POST_RUN_EVENT = viz.getEventID('TRIAL_POST_RUN_EVENT')
def initEvents(initFlag=vizconnect.INIT_INDEPENDENT, initList=None): #VC: place any general initialization code here rawEvent = vizconnect.getRawEventDict() #VC: initialize a new event _name = 'SHOW_MENU_EVENT' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'MOVE_MENU_EVENT' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: return values can be modified here return None
def init(): """Code for one time initialization routine.""" # add grabber tools based on proxy tools for proxyWrapper in vizconnect.getToolsWithMode('Proxy'): grabberTool = tools.grabber.HandGrabber( usingPhysics=False, usingSprings=False, placementMode=tools.placer.MODE_DROP_DOWN) name = 'grabber_tool_based_on_' + proxyWrapper.getName() grabberWrapper = vizconnect.addTool(raw=grabberTool, name=name, make='Virtual', model='Grabber') # parent the grabber wrapper to the proxy's parent grabberWrapper.setParent(proxyWrapper) grabberTool.setItems(grabbableItems) viz.callback(viz.getEventID('RESET_THE_LOFT_LAYOUT'), lambda e: resetMovedObjects())
class Task(viz.EventClass): '''Abstract base class for the workflow during an experiment. Instances of class are intended to be used as part of the viztask module, by calling `viztask.schedule()` using our `workflow()` method: >>> viztask.schedule(MyTaskSubclass().workflow) But since this base class is abstract, it is not to be used directly---instead, use the Trial, Block, or Experiment classes, or implement your own subclass. ''' PRE_RUN_EVENT = viz.getEventID('TASK_PRE_RUN_EVENT') POST_RUN_EVENT = viz.getEventID('TASK_POST_RUN_EVENT') def __init__(self, periodic=()): super(Task, self).__init__() self._timers = [0] for period, callback in periodic: self.add_periodic(period, callback) def workflow(self): '''Run the workflow associated with this task. Each task is separated into three phases: startup, running, and teardown. (These are inspired by the commonly implemented phases of a unit test.) Instances of this task also emit events just before and just after running the task. These events can be used to attach callbacks that do things like start and stop a timer, or other similar things you might want to do during an experiment. ''' yield self.setup() viz.sendEvent(self.PRE_RUN_EVENT, self) yield self.run() viz.sendEvent(self.POST_RUN_EVENT, self) yield self.teardown() def setup(self): '''Set up some environment necessary for running this task. This can be used, for example, to: - set up storage for variables that might need to be recorded while running a task - draw or show objects that will be needed for the task - etc. Example implementations: def setup(self): os.makedirs(self.trial_output_dir()) yield viztask.waitTime(3) # wait 3 seconds def setup(self): yield viztask.waitKeyDown(' ') # wait until space is pressed def setup(self): yield self.signal.wait() # wait until some signal fires ''' pass def run(self): '''Run this task. Subclasses of this base must implement this method. ''' raise NotImplementedError def teardown(self): '''Tear down the environment after having run a task.''' pass def add_periodic(self, period, callback): '''Call some code periodically while running a task. The given `callback` will be called every `period` seconds between the firings of the PRE_RUN and POST_RUN events for this task. Parameters ---------- period : float Number of seconds between successive calls to the `callback`. callback : callable (no arguments) Call this function every `period` seconds. Returns ------- timer_id : The Vizard timer ID. Can be used to kill this periodic event. ''' timer_id = 1 + max(self._timers) self._timers.append(timer_id) viz.callback(self.POST_RUN_EVENT, lambda me: viz.killtimer(timer_id)) def start(me): def clock(t): if t == timer_id: callback() viz.callback(viz.TIMER_EVENT, clock) viz.starttimer(timer_id, period, viz.FOREVER) viz.callback(self.PRE_RUN_EVENT, start) return timer_id def stop_periodic(self, timer_id): '''Stop a periodic event from occurring. Parameters ---------- timer_id : int The Vizard ID of the timer to stop. ''' viz.killtimer(timer_id)
def initializeBoatGrabberAndPhysics(): global grabberTool, boatObjectsToGrab, ALL_GRABBED_EVENT #physics stuff # viz.phys.disable() # Enable physics # viz.phys.enable() # Enable physics globals_oa.boat.collideMesh() # globals_oa.boat.disable( viz.DYNAMICS ) usingPhysics=False from tools import grabber from tools import highlighter global rhGrabber, lhGrabber if rhGrabber is None: rhGrabber = grabber.Grabber(usingPhysics=False, usingSprings=False, highlightMode=highlighter.MODE_BOX) if lhGrabber is None: lhGrabber = grabber.Grabber(usingPhysics=False, usingSprings=False, highlightMode=highlighter.MODE_BOX) rhGrabber.setUpdateFunction(rUpdateGrabberOnBoat) if globals_oa.rhModel is not None: rhGrabber.setParent(globals_oa.rhModel) lhGrabber.setUpdateFunction(lUpdateGrabberOnBoat) if globals_oa.lhModel is not None: lhGrabber.setParent(globals_oa.lhModel) boatObjectsToGrab = [] #read object list from txt file filePointerToBoatGrabbableList = open(globals_oa.filePathToBoatItemsToGrab, 'r') for line in filePointerToBoatGrabbableList: s = line.strip('\n').split(' ') print s if globals_oa.boat is not None: if s[0] != "combine": item = globals_oa.boat.getChild(s[0]) if item: boatObjectsToGrab.append(item) item.collideBox() else: item1 = globals_oa.boat.getChild(s[1]) if item1: boatObjectsToGrab.append(item1) item2 = globals_oa.boat.getChild(s[2]) if item2: linkBetweenTwoSeparateModelsWhichNeedToBeTogether = viz.link(item1, item2) rhGrabber.setItems(boatObjectsToGrab) lhGrabber.setItems(boatObjectsToGrab) viz.callback(grabber.GRAB_EVENT,grabObject) viz.callback(grabber.RELEASE_EVENT, releaseObject) #proximity stuff basketOnBoat = globals_oa.boat.getChild('diveBasket.OSGB') global basketManager basketManager = vizproximity.Manager() basketSensor = vizproximity.addBoundingBoxSensor(basketOnBoat, scale = (1.5, 4.5, 1.5)) basketManager.addSensor(basketSensor) # basketManager.onEnter(None, objectBasketed) global rhandtar, lhandtar rhsphere = vizshape.addSphere(radius = 0.05) rhsphere.setParent(globals_oa.rhModel) rhsphere.setPosition([0,0,.55]) rhsphere.disable(viz.RENDERING) lhsphere = vizshape.addSphere(radius = 0.05) lhsphere.setParent(globals_oa.lhModel) lhsphere.setPosition([0,0,.55]) lhsphere.disable(viz.RENDERING) if globals_oa.rhModel is not None:rhandtar = vizproximity.Target(rhsphere)#globals_oa.rhModel) if globals_oa.lhModel is not None:lhandtar = vizproximity.Target(lhsphere)#globals_oa.lhModel) basketManager.addTarget(rhandtar) basketManager.addTarget(lhandtar) ALL_GRABBED_EVENT = viz.getEventID("all items grabbed on the boat")
startAngle = angle * accumulation else: startAngle = 0 prevLeft = globals_oa.lhViveTracker.getTrigger() prevRight = globals_oa.rhViveTracker.getTrigger() def enterWheel(e): global wheelEntered wheelEntered = True def exitWheel(e): global wheelEntered wheelEntered = False timesLookedOpening = 0 lookingOpeningTimer = None LOOKED_OPENING_EVENT = viz.getEventID('Looked at Opening') def lookingAtOpening(): global timesLookedOpening, lookingOpeningTimer, LOOKED_OPENING_EVENT renderStats = viz.getRenderStats() if renderStats.drawableCount > 300: timesLookedOpening += 1 if timesLookedOpening >= 20: viz.sendEvent(LOOKED_OPENING_EVENT) lookingOpeningTimer.setEnabled(0) def startBoatIntro(): global boatScene, ALL_GRABBED_EVENT, wheel, radius, wheelTimer, skipKey # hideOceanScene() # FADE_IN_TIME = 4 globals_oa.user.setPosition([0,0,0])
"""Utility to fade out an audio track""" import viz import vizact import viztask # Global, externally accessible mixer instance mixer = viz.addSoundMixer() FADE_COMPLETE = viz.getEventID('fade_complete') class FadeableAudio(object): """Wrapper class for an audio file providing a fade feature. Note: mp3 file type not supported, recommended to use wav instead """ def __init__(self, filepath, volume=1.0): # Set up a sound mixer with underlying audio file self._mixer = viz.addSoundMixer() self._mixer.setPaused(True) self._filepath = filepath self._mixer.play(self._filepath) # Store volume parameter self._volume = volume # Define a time step for fade self._timeStep = 0.1 # seconds
packaging of this file. Please review the following information to ensure the GNU Lesser General Public License version 3 requirements will be met: https://www.gnu.org/licenses/lgpl-3.0.html. """ """ This file takes care of the controls. The events of vizconnect couldn't be used here, because it always sends an event object as first parameter. Altering the subscribed function to recieve that object results in bad function signatures. """ import viz import vizconnect import math # Define the Events, which can be subscribed to CONTROL_NEW_FILE = viz.getEventID("CONTROL_NEW_FILE_INTERNAL") CONTROL_CLIP = viz.getEventID("CONTROL_CLIP_INTERNAL") CONTROL_TOGGLE_ENVIRONMENT = viz.getEventID( "CONTROL_TOGGLE_ENVIRONMENT_INTERNAL") CONTROL_CLOUD_INCREASE = viz.getEventID("CONTROL_CLOUD_INCREASE_INTERNAL") CONTROL_CLOUD_DECREASE = viz.getEventID("CONTROL_CLOUD_DECREASE_INTERNAL") CONTROL_CYCLE_VIEW_MODE = viz.getEventID("CONTROL_CYCLE_VIEW_MODE_INTERNAL") CONTROL_MATERIAL = viz.getEventID("CONTROL_MATERIAL_INTERNAL") CONTROL_TOGGLE_STRESSINDICATOR = viz.getEventID( "CONTROL_TOGGLE_STRESSINDICATOR_INTERNAL") CONTROL_HAND_GRAB = viz.getEventID("CONTROL_HAND_GRAB_INTERNAL") CONTROL_HAND_RELEASE = viz.getEventID("CONTROL_HAND_RELEASE_INTERNAL") class _Controls(viz.EventClass): """
import viz import vizact import SerialPort_win import viztask # ------ Configuration for the lumina box ------------ DEVICE = "COM3" TIMEOUT = 0 SPEED = 19200 TRIGGER_DOWN = "5" RIGHT_BUTTON_DOWN = "4" #4--scanner #3 RIGHT_BUTTON_UP = "4" LEFT_BUTTON_DOWN = "1" #--scanner LEFT_BUTTON_UP = "1" #2 TRIGGER_EVENT = viz.getEventID("PULSE_EVENT") RIGHT_BUTTON_EVENT = viz.getEventID("RIGHT_B_EVENT") LEFT_BUTTON_EVENT = viz.getEventID("LEFT_B_EVENT") FIRST_TRIGGER_EVENT = viz.getEventID("FIRST_PULSE_EVENT") # ---------------------------------------------------- # ----- Configuration for fake scanner triggers ------ LEFT_KEY = "a" RIGHT_KEY = "'" # ---------------------------------------------------- """ Classes for interacting with the Lumina system in the UCSB Brain Imaging Center in vizard. If you're testing this without the scanner, use FakeFmriTrigger """
def initEvents(initFlag=vizconnect.INIT_INDEPENDENT, initList=None): #VC: place any general initialization code here rawEvent = vizconnect.getRawEventDict() #VC: initialize a new event _name = 'CONTROL_NEW_FILE' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['keyboard'].isButtonDown( 49 ): # make=Generic, model=Keyboard, name=keyboard, signal=Key N event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_CYCLE_VIEW_MODE' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['l_hand_input'].isButtonDown( 0 ): # make=HTC, model=Vive Controller, name=l_hand_input, signal=Button Menu event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_MATERIAL_TRIGGER' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['r_hand_input'].isButtonDown( 3 ): # make=HTC, model=Vive Controller, name=r_hand_input, signal=Button Trackpad event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_CLIP' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['r_hand_input'].isButtonDown( 1 ): # make=HTC, model=Vive Controller, name=r_hand_input, signal=Button Grip event.sendOnce(e=viz.Event(mag=1)) if rawInput['l_hand_input'].isButtonDown( 1 ): # make=HTC, model=Vive Controller, name=l_hand_input, signal=Button Grip event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_CLOUD_INCREASE' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['l_hand_input'].getTrackpad()[1] > 0.01 and\ rawInput['l_hand_input'].isButtonDown(3):# make=HTC, model=Vive Controller, name=l_hand_input, signal=Trackpad Top (along with) make=HTC, model=Vive Controller, name=l_hand_input, signal=Button Trackpad event.sendOnce(e=viz.Event(mag=abs( rawInput['l_hand_input'].getTrackpad()[1]) * 1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_CLOUD_DECREASE' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['l_hand_input'].getTrackpad()[1] < -0.01 and\ rawInput['l_hand_input'].isButtonDown(3):# make=HTC, model=Vive Controller, name=l_hand_input, signal=Trackpad Bottom (along with) make=HTC, model=Vive Controller, name=l_hand_input, signal=Button Trackpad event.sendOnce(e=viz.Event(mag=abs( rawInput['l_hand_input'].getTrackpad()[1]) * 1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_TOGGLE_STRESSINDICATOR' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['r_hand_input'].isButtonDown( 0 ): # make=HTC, model=Vive Controller, name=r_hand_input, signal=Button Menu event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_TOGGLE_ENVIRONMENT' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['keyboard'].isButtonDown( 19 ): # make=Generic, model=Keyboard, name=keyboard, signal=Key R event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_LEFT_HAND_GRAB' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['l_hand_input'].isButtonDown( 2 ): # make=HTC, model=Vive Controller, name=l_hand_input, signal=Button Trigger event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_LEFT_HAND_RELEASE' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if not rawInput['l_hand_input'].isButtonDown( 2 ): # make=HTC, model=Vive Controller, name=l_hand_input, signal=Button Trigger event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_RIGHT_HAND_GRAB' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['r_hand_input'].isInMode( 'super' ) and rawInput['r_hand_input'].isButtonDown( 2 ): # make=HTC, model=Vive Controller, name=r_hand_input, signal=Button Trigger event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_RIGHT_HAND_RELEASE' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['r_hand_input'].isInMode( 'super' ) and not rawInput['r_hand_input'].isButtonDown( 2 ): # make=HTC, model=Vive Controller, name=r_hand_input, signal=Button Trigger event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: return values can be modified here return None
import viz import vizact import viztask import vizfx import vizshape import vizcam import NodeSelectionWithFeedbackOptions from vhil_devkit import * INTRO_OVER_EVENT = viz.getEventID('INTRO_OVER_EVENT') def playPhoneAndRadio(): global main_screen, radio, selector, phoneEvent yield screen.playsound('resources/audio/vibrate.wav', viz.STOP) yield selector.disable() yield selector.disable() yield screen.endAction( pool = 0) yield vizact.removeEvent(phoneEvent) voicemail = screen.playsound('resources/audio/voicemail_mono.wav', viz.PLAY) yield viztask.waitTime(voicemail.getDuration()) newsReport = radio.playsound('resources/audio/RadioShowScene_louder.wav') yield viztask.waitTime(newsReport.getDuration()) viz.sendEvent(INTRO_OVER_EVENT) def selectPhone(): global screen, phoneEvent, fadeInAndOut, selector if screenFound: viztask.schedule(playPhoneAndRadio) #vizact.removeEvent(phoneEvent)
import os import sys import csv import random import colorsys import viz import vizfx import vizact import vizinfo import viztask import vizshape import steamvr DEBUGGER_SHOW_EVENT = viz.getEventID('SteamVRDebugOverlayShowEvent') DEBUGGER_HIDE_EVENT = viz.getEventID('SteamVRDebugOverlayHideEvent') def showVRText(msg, color=[1.0, 1.0, 1.0], distance=2.0, scale=0.05, duration=2.0): """ Display head-locked message in VR, e.g. for instructions. Args: msg (str): Message text color: RBG 3-tuple of color values distance (float): Z rendering distance from MainView scale (float): Text node scaling factor duration (float): Message display duration (seconds) """ # Create 3D text object text = viz.addText3D(msg, scale=[scale, scale, scale], color=color)
#Joe Snider #7/14 # #Run the treadmill from Vizard (wraps treadmill.py) import viz import treadmill import FLMOCommands import vizact import viztask import math #this is sent whenever a new value is read from the treadmill # It should mainly come from subscribed values (things the treadmill is sending as fast as it can) TREADMILL_STATE_UPDATED = viz.getEventID('TREADMILL_STATE_UPDATED') #register a quit call back to shutdown the treadmill properly STOP_TREADMILL = viz.getEventID('STOP_TREADMILL') TREADMILL_STOPPED = viz.getEventID('TREADMILL_STOPPED') def doShutdownTreadmill(): yield viztask.waitKeyDown('q') viz.sendEvent(STOP_TREADMILL) yield viztask.waitEvent(TREADMILL_STOPPED) print "pause ...", yield viztask.waitTime(1) print "done" viz.quit()
#needs to move the flash drive as well, only if one is there def onDrawerRelease(e): threshold2 = 5.00 if e.released == drawer: xDisplacement = abs(drawer.getPosition()[0]) yDisplacement = abs(drawer.getPosition()[1]) if xDisplacement < threshold2 or yDisplacement < threshold2: drawer.setPosition(.57, 0, 0) drawer.setEuler(0, 0, 0) if choice == 0 or 1: movable_Drive.setPosition(.57, 0, 0) # Setup callback to enable guitar sounds vizact.onevent(viz.getEventID('GRABBER_GRAB_EVENT'), lambda e: (True, e), onGuitarGrab) vizact.onevent(viz.getEventID('GRABBER_RELEASE_EVENT'), lambda e: (True, e), onGuitarRelease) vizact.onevent(viz.getEventID('GRABBER_RELEASE_EVENT'), lambda e: (True, e), onDrawerRelease) # Manually add a few additional items to the grabbable list, which were not added above by the description parser extraGrabbables = [ 'DEC_Vaso Ovo', # Cellular-egg decorative vase 'arch49_055_obj_00', # Orange ball cap on child's bed 'DEC_Fruteira B01', # Basket of lemons on kitchen counter 'DEC_fruteiras_A_01_maca_08', # Basket of apples on kitchen counter 'DEC_vaso', # Toilet in master bedroom 'DEC_vaso02', # Toilet in common area 'Pot',
def __init__(self, config): # Event classes can register their own callback functions # 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 self.config = config # Eventually, self.config.writables is passed to DVRwriter # self.config.writables is a list # dvrwriter will attempt to run .getOutput on every member of the list # One could then add experiment, theBall, theRacquet, eyeTrackingCal to the list, assuming # they include the member function .getOutput(). # I prefer to do all my data collection in one place: experiment.getOutput() self.config.writables = [self] ################################################################ ################################################################ ## 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) # self.room.physEnv self.hmdLinkedToView = False ################################################################ ################################################################ # Build block and trial list self.blockNumber = 0; self.trialNumber = 0; self.inProgress = True; self.blocks_bl = [] for bIdx in range(len(config.expCfg['experiment']['blockList'])): self.blocks_bl.append(block(config,bIdx)); self.currentTrial = self.blocks_bl[self.blockNumber].trials_tr[self.trialNumber] # ################################################################ # ################################################################ # ## Misc. Design specific items here. if( config.wiimote ): self.registerWiimoteActions() # Setup launch trigger #self.launchKeyIsCurrentlyDown = False #self.minLaunchTriggerDuration = config.expCfg['experiment']['minLaunchTriggerDuration'] # maxFlightDurTimerID times out balls a fixed dur after launch #self.maxFlightDurTimerID = viz.getEventID('maxFlightDurTimerID') # Generates a unique ID. ################################################################ ## LInk up the hmd to the mainview if( self.config.use_phasespace == True ): ################################################################ ## Link up the hmd to the mainview if( self.config.use_HMD and config.mocap.returnPointerToRigid('hmd') ): self.config.mocap.enableHMDTracking() # If there is a paddle visObj and a paddle rigid... #self.setupPaddle() ############################################################## ############################################################## ## Callbacks and timers vizact.onupdate(viz.PRIORITY_PHYSICS,self._checkForCollisions) #self.callback(viz.TIMER_EVENT, self.timer_event) self.callback(viz.KEYDOWN_EVENT, self.onKeyDown) self.callback(viz.KEYUP_EVENT, self.onKeyUp) self.callback( viz.TIMER_EVENT,self._timerCallback ) self.perFrameTimerID = viz.getEventID('perFrameTimerID') # Generates a unique ID. self.starttimer( self.perFrameTimerID, viz.FASTEST_EXPIRATION, viz.FOREVER) # DVR snaps a shot of the frame, records eye data, and contents of self.writables is written out to the movie self.callback(viz.POST_SWAP_EVENT, self.config.__record_data__, viz.PRIORITY_LAST_UPDATE) # Use text output! if( config.sysCfg['use_DVR'] >0): vizact.ontimer(3,self.checkDVRStatus) now = datetime.datetime.now() dateTimeStr = str(now.year) + '-' + str(now.month) + '-' + str(now.day) + '-' + str(now.hour) + '-' + str(now.minute) dataOutPutDir = config.sysCfg['writer']['outFileDir'] self.expDataFile = open(dataOutPutDir + 'exp_data-' + dateTimeStr + '.txt','a') if( self.config.sysCfg['use_eyetracking']): self.eyeDataFile = open(dataOutPutDir + 'eye_data-' + dateTimeStr + '.txt','a') vizact.onupdate(viz.PRIORITY_LAST_UPDATE,self.writeDataToText) # 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()
#acceleration and deceleration values (should be pretty fast) #range is 0 to 18000, 900 is initial DECELERATION = 1200 ACCELERATION = 1200 #decelleration for going off the back is larger (so the foot doesn't hit the light switch and cause a suspend) BACK_DECELERATION = 2000 #correct the left plate position by this much CORRECT_LEFT = 0.01776 #m #at least for testing, just turn it on MIN_DIST_TO_DESIRED = 0.2#m FIXED_SPEED = 0.4#m/s REQUEST_FEET_ALIGNMENT_TREADMILL = viz.getEventID('REQUEST_FEET_ALIGNMENT_TREADMILL') DONE_FEET_ALIGNMENT_TREADMILL = viz.getEventID('DONE_FEET_ALIGNMENT_TREADMILL') class StabilizeTreadmill: def __init__(self, tmill, forceplates): #use enable to prevent the belts from moving/view updating self.enable = False self.tmill = tmill self.forceplates = forceplates self.leftStrideLength = 0.#m, this is only an initial estimate, it will be measured self.rightStrideLength = 0.#m self.leftDistToDesired = 0.0#m self.rightDistToDesired = 0.0#m
import viz import vizact import vizshape import vizproximity import random import vizfx import vizconnect import viztask WATER_RISE_EVENT = viz.getEventID('WATER_RISE_EVENT') HEIGHT = 0 obj_vis = [] waterSound = viz.addAudio('fountain.wav') waterSound.volume(0.2) choirLocation = viz.addGroup(pos=[0.2, 1.8, -53]) choir_sound = choirLocation.playsound('art/scene1 choir.wav') #scene1 = viz.addChild('art/scene1.osgb') scene1 = vizfx.addChild('art/scene1.osgb') viz.MainView.getHeadLight().disable() # Disable ambient light vizfx.setAmbientColor(viz.BLACK) #scene1.disable(viz.LIGHTING) scene1.hint(viz.ALLOW_NPOT_TEXTURE_HINT) scene1.disable(0x3000) #Disable clip plane on model waterPlane = vizshape.addPlane(size=[400, 400], pos=[0, 0.2, 0]) obj_vis.append(scene1)
import vector3 import dataCollection from vector3 import * from tools import highlighter from worldvizcode import EnterProximityZone1 from worldvizcode import EnterProximityZone2 from worldvizcode import EnterProximityZone3 #from schooling import createSchoolWithNode3D import schooling import vizfx import nodeselectionwithfeedbackoptions from questionnaire import * TIME_BETWEEN_TASKS = 3 ALL_FOUND_EVENT = viz.getEventID('ALL_FOUND_EVENT') TIME_OUT_EVENT = viz.getEventID('TIME_OUT_EVENT') ZONE1_OVER_EVENT = viz.getEventID('ZONE1_OVER_EVENT') ZONE3_OVER_EVENT = viz.getEventID('ZONE3_OVER_EVENT') #numObjectsToFind = [2, 1] numObjectsToFind = [] speciesIndex = 0 speciesRegex = {} numSnailsFound1 = 0 numEelsFound = 0 numOctFound = 0 numGrassFound = 0 numSnailsFound2 = 0
filePathForBubbles3Dpositions = 'data/bubblesPos.txt' initBoatCalled = False initIschiaCalled = False #boatSceneUserStartPos = [0.712917149066925, 0.6620826721191406, -6.251225233078003] boatSceneUserStartPos = [0.5578010082244873, 0.6620826721191406, 6.547428607940674] footprintPos = [0.0, 1.3] co2HoveringMoleculePath = MODEL_DIRECTORY + 'CO2animated.OSGB' boatWithMoleculesPath = MODEL_DIRECTORY + 'boatWithMoleculeArray1.osgb' #boatWithMoleculesPath = MODEL_DIRECTORY + 'boatWithMolecules.osgb' specialCO2 = MODEL_DIRECTORY + 'singleCO2_noAnimation_WithBubble.osgb' CRYSTAL_EVENT = viz.getEventID("crystal ball scene ending") CITY_SCENE_END_EVENT = viz.getEventID("city scene ending") BOAT_SCENE_END_EVENT = viz.getEventID("boat scene ending") FOOTPRINT_EVENT = viz.getEventID("standing on footprint") H2CO3_COMPLETION_EVENT = viz.getEventID("H2CO3 formation complete") VIDEO_END_EVENT = viz.getEventID("video scene ending") ZONE1_EVENT = viz.getEventID("zone 1 scene ending") ZONE2_EVENT = viz.getEventID("zone 2 scene ending") CG_END_EVENT = viz.getEventID("CG scene ending") co2Path = MODEL_DIRECTORY + '2D-CO2.osgb' h2OLocationUntilWeChangeAgain = [-0.61,0.14,5] h2CO3LocationUntilWeChangeAgain = [0, -0.5, 5.0] pathToH2CO3molecule = MODEL_DIRECTORY + 'Molecule Animation_h2co3.OSGB'
#Joe Snider #7/14 # #read in the treadmill foreplate data import viz import u6 import math import viztask import numpy as np MIN_WEIGHT_NEWTONS = -100# ~20 lbs, negetive for downward gravity LEFT_OFF_TREADMILL = viz.getEventID('LEFT_OFF_TREADMILL') LEFT_ON_TREADMILL = viz.getEventID('LEFT_ON_TREADMILL') RIGHT_OFF_TREADMILL = viz.getEventID('RIGHT_OFF_TREADMILL') RIGHT_ON_TREADMILL = viz.getEventID('RIGHT_ON_TREADMILL') class CTreadmillForcePlate(): def __init__(self): self.device = u6.U6() print self.device.configU6() #for the labjack self.numChannels = 12 self.firstChannel = 2 self.resolutionIndex = 4 self.gainIndex = 0 self.settlingFactor = 0 self.differential = False
import viz import vizact W_KEY_PRESSED_EVENT = viz.getEventID('W_KEY_PRESSED_EVENT') A_KEY_PRESSED_EVENT = viz.getEventID('A_KEY_PRESSED_EVENT') S_KEY_PRESSED_EVENT = viz.getEventID('S_KEY_PRESSED_EVENT') D_KEY_PRESSED_EVENT = viz.getEventID('D_KEY_PRESSED_EVENT') def CheckKey(): if viz.key.isDown('w',immediate=False): viz.sendEvent(W_KEY_PRESSED_EVENT) elif viz.key.isDown('a',immediate=False): viz.sendEvent(A_KEY_PRESSED_EVENT) elif viz.key.isDown('s',immediate=False): viz.sendEvent(S_KEY_PRESSED_EVENT) elif viz.key.isDown('d',immediate=False): viz.sendEvent(D_KEY_PRESSED_EVENT) def CheckMouse(): global _mouseState pos = viz.mouse.getPosition(viz.WINDOW_NORMALIZED,True) state = (0 <= pos[0] <= 1.0) and (0 <= pos[1] <= 1.0) if state != _mouseState: _mouseState = state if state: viz.sendEvent(MOUSE_ENTER_EVENT,pos) else: viz.sendEvent(MOUSE_LEAVE_EVENT,pos)
if totalAngleChange>180: totalAngleChange = 180 - (totalAngleChange-180) newEuler = self.initialEuler newEuler[0] += totalAngleChange * self.data[0] newEuler[1] += totalAngleChange * self.data[1] newEuler[2] += totalAngleChange * self.data[2] object.setEuler(newEuler) def excite(x,y,z,speed,dur=viz.FOREVER): bla = viz.ActionData() bla.data =[x,y,z,speed,dur] bla.actionclass=VizExciteAction return bla COLOR_EVENT = viz.getEventID('COLOR_EVENT') class ColorEventClass(viz.EventClass) : def __init__(self): viz.EventClass.__init__(self) self.callback(COLOR_EVENT,self.onKeyDown) def onKeyDown(self): global status_bar status_bar.color(random.choice([viz.BLUE, viz.YELLOW, viz.GREEN])) ColorEventClass() def ChangeColor() : viz.sendEvent(COLOR_EVENT)
def initEvents(initFlag=vizconnect.INIT_INDEPENDENT, initList=None): #VC: place any general initialization code here rawEvent = vizconnect.getRawEventDict() #VC: initialize a new event _name = 'CONTROL_NEW_FILE' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['keyboard'].isButtonDown( 49 ): # make=Generic, model=Keyboard, name=keyboard, signal=Key N event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_CLIP' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['keyboard'].isButtonDown( 48 ): # make=Generic, model=Keyboard, name=keyboard, signal=Key B event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_CLOUD_INCREASE' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['keyboard'].isButtonDown( 23 ): # make=Generic, model=Keyboard, name=keyboard, signal=Key I event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_CLOUD_DECREASE' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['keyboard'].isButtonDown( 37 ): # make=Generic, model=Keyboard, name=keyboard, signal=Key K event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_TOGGLE_ENVIRONMENT' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['keyboard'].isButtonDown( 19 ): # make=Generic, model=Keyboard, name=keyboard, signal=Key R event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_CYCLE_VIEW_MODE' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['keyboard'].isButtonDown( 47 ): # make=Generic, model=Keyboard, name=keyboard, signal=Key V event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_LEFT_HAND_GRAB' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['joystick'].isButtonDown( 5 ): # make=Generic, model=Joystick, name=joystick, signal=Button 5 event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_LEFT_HAND_RELEASE' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if not rawInput['joystick'].isButtonDown( 5 ): # make=Generic, model=Joystick, name=joystick, signal=Button 5 event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_RIGHT_HAND_GRAB' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if rawInput['joystick'].isButtonDown( 6 ): # make=Generic, model=Joystick, name=joystick, signal=Button 6 event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: initialize a new event _name = 'CONTROL_RIGHT_HAND_RELEASE' if vizconnect.isPendingInit('event', _name, initFlag, initList): #VC: init the raw object if initFlag & vizconnect.INIT_RAW: #VC: create the raw object from vizconnect.util import events rawEvent[_name] = events.CustomEvent(viz.getEventID(_name)) #VC: init the mappings for the raw object if initFlag & vizconnect.INIT_MAPPINGS: #VC: per frame mappings if initFlag & vizconnect.INIT_MAPPINGS_PER_FRAME: #VC: get the raw input dict so we have access to signals import vizact rawInput = vizconnect.getConfiguration().getRawDict('input') #VC: set the update function which checks for input signals def update(event): if not rawInput['joystick'].isButtonDown( 6 ): # make=Generic, model=Joystick, name=joystick, signal=Button 6 event.sendOnce(e=viz.Event(mag=1)) rawEvent[_name].setUpdateFunction(update) #VC: init the wrapper (DO NOT EDIT) if initFlag & vizconnect.INIT_WRAPPERS: vizconnect.addEvent(rawEvent[_name], _name, make='Vizconnect', model='Custom') #VC: return values can be modified here return None
import viz import vizact MOUSE_ENTER_EVENT = viz.getEventID('MOUSE_ENTER_EVENT') MOUSE_LEAVE_EVENT = viz.getEventID('MOUSE_LEAVE_EVENT') _mouseState = None def CheckMouse(): global _mouseState pos = viz.mouse.getPosition(viz.WINDOW_NORMALIZED,True) state = (0 <= pos[0] <= 1.0) and (0 <= pos[1] <= 1.0) if state != _mouseState: _mouseState = state if state: viz.sendEvent(MOUSE_ENTER_EVENT,pos) else: viz.sendEvent(MOUSE_LEAVE_EVENT,pos) vizact.onupdate(0,CheckMouse)
import vizconnect import vizproximity import scene1 import scene2 import scene3 viz.setMultiSample(8) vizconnect.go('vizconnect_config_desktop.py') #vizconnect.go('vizconnect_config_vive.py') grabTool = vizconnect.getRawTool('grabber') grabTool.setItems(scene1.getGrabObjects()) vizact.onkeydown(' ', viz.setDebugSound3D, viz.TOGGLE) CHANGE_SCENES_EVENT = viz.getEventID('CHANGE_SCENES') oriMode = vizconnect.VIEWPOINT_MATCH_DISPLAY posMode = vizconnect.VIEWPOINT_MATCH_FEET scene1_pos = [[0, 0, -21.87243], [0, 0, -46.27398], [0.4, 0, -73], [-0.2, 2.6, -90]] scene2_pos = [[0, 0.1, 0], [3, -3.2, 2.4], [10, -3, -4.73], [15, 0.1, -1.73]] scene2_ori = [[90, 0, 0], [110, 0, 0], [70, 0, 0], [90, 0, 0]] scene3_pos = [[0, 0, 0], [0, 0, 30], [0, 0, 70], [0, 0, 180]] vp1 = [] for pos in scene1_pos: vp = vizconnect.addViewpoint(pos=pos, euler=[180, 0, 0], oriMode=oriMode,
import viz import vizact import math APPROACH_MAN_EVENT = viz.getEventID('APPROACH_MAN_EVENT') LEAVE_MAN_EVENT = viz.getEventID('LEAVE_MAN_EVENT') MAN_POSITION = [-6.5,0,13.5] state = None def CheckNearMan(): global state pos = viz.MainView.getPosition() dx = pos[0] - MAN_POSITION[0] dz = pos[2] - MAN_POSITION[2] distance = math.sqrt(dx * dx + dz * dz) closeToMan = distance < 3 # Whether we are close to the man or not if (state != closeToMan): state = closeToMan if (closeToMan): viz.sendEvent(APPROACH_MAN_EVENT) else: viz.sendEvent(LEAVE_MAN_EVENT) vizact.onupdate(0, CheckNearMan)
import viz import vizact #check when mouse leaves and enters region in lower left MOUSE_ENTER_SPECIAL_EVENT = viz.getEventID('MOUSE_ENTER_SPECIAL_EVENT') MOUSE_LEAVE_SPECIAL_EVENT = viz.getEventID('MOUSE_LEAVE_SPECIAL_EVENT') _mouseState = None def CheckMouse(): global _mouseState pos = viz.mouse.getPosition(viz.WINDOW_NORMALIZED,True) state = (0 <= pos[0] <= .1) and (0 <= pos[1] <= .1) if state != _mouseState: _mouseState = state if state: viz.sendEvent(MOUSE_ENTER_SPECIAL_EVENT,pos) else: viz.sendEvent(MOUSE_LEAVE_SPECIAL_EVENT,pos) vizact.onupdate(0,CheckMouse)
def getEventID(self, eventName): return self.dictOfEvents.setdefault(eventName,viz.getEventID(eventName))
import viz import vizact import viztask import vizfx import vizshape import vizcam import keyboardcontrol as control import NodeSelectionWithFeedbackOptions from vhil_devkit import * CAR_SCALE = 0.05 OBJECT_SCALE = .00131 TIME_BETWEEN_TASKS = 1 FINDING_TASK_OVER_EVENT = viz.getEventID('FINDING_TASK_OVER_EVENT') selectedNode = -1 cupMoved = False blanketLifted = False toothPasteFound = False objectsToSelect = [] #animations to move objects to dash #hardcoded with care, please be careful with the numbers if you are going to modify def moveToDash(node): if (node == cup1):#cup1 move = vizact.sequence(vizact.moveTo([-.70,1.4,-2.4],speed=.5),vizact.moveTo([.69,1.4,-2.4],speed=.5), vizact.moveTo([.69,1.23,-2.76],speed=.5)) node.addAction(move) yield viztask.waitActionEnd(node,move) viz.sendEvent(FINDING_TASK_OVER_EVENT, SCENE)
resultPanel.visible(False) # Disable gray effect gray_effect.setEnabled(False) dataFile.write('[{}/{}]'.format(score, TRIAL_COUNT)) dataFile.flush() #Display results and ask to quit or play again resultPanel.setText(RESULTS.format(score,TRIAL_COUNT)) resultPanel.visible(True) yield viztask.waitKeyDown(' ') resultPanel.visible(False) _viewState = None VIEW_LOOKUP_ENTER_EVENT = viz.getEventID('VIEW_LOOKUP_ENTER_EVENT') VIEW_LOOKUP_EXIT_EVENT = viz.getEventID('VIEW_LOOKUP_EXIT_EVENT') def CheckView(): global _viewState state = viz.MainView.getEuler()[1] < -45 if state != _viewState: _viewState = state if state: print 'LOOK UP' viz.sendEvent(VIEW_LOOKUP_ENTER_EVENT) else: print 'LOOK DOWN' viz.sendEvent(VIEW_LOOKUP_EXIT_EVENT) def PlaySound():