示例#1
0
def setUpSound():
	global windAudio, endingAudio, aboveLocation, endingAudioBasic, trumpetAudio
	if USE_HMD_F:
		#Adjusted head location to spatalize towards center of room
		#Next, create 4 subviews to attach sounds to around the room for whooshing
		userView = viz.addView()
		userView.setPosition(0,1.6,0)
		headLocation = viz.addGroup()
		viz.link(userView, headLocation)
		#Good adjustment for reverb and room, might not work as well for the city
		#vizsonic.setReverb (30.0, 0.2, 0.5, 0.9, 0.1)
		vizsonic.setSimulatedRoomRadius(30,30)
		vizsonic.setShaker(1.0)
		viz.setOption('sound3d.useViewRotation', 0)
		#Set auarlizer to play towards center of room
		viz.setListenerSound3D(headLocation)
		#Turn on sound debugging?
		viz.setDebugSound3D(False)
		#Turn on windy city sounds
		vizsonic.setAmbient('windy_edit.wav', 0.75, 0)
		#Configure wind playing based on speed, play at higher location
		aboveView = viz.addView()
		aboveView.setPosition(0,3,0)
		aboveLocation = viz.addGroup()
		viz.link(aboveView, aboveLocation)
		windAudio = aboveLocation.playsound('windMono.wav', viz.STOP, volume=WIND_MIN_VOLUME)
		trumpetAudio = aboveLocation.playsound('audio/hero_trumpet.wav', viz.STOP, volume = 0.75)
	chooseExpStateNLoadSound()
示例#2
0
    def __init__(self, trackers, obj=None):
        """
		Initialize the object which handles the grabs and zooming.
		"""
        viz.EventClass.__init__(self)
        self._obj = obj
        if len(trackers) > 2:
            raise ValueError(
                "Currently only up to 2 trackers are supported. Please use less trackers."
            )

        # variables to save the current state
        self._grabs = {0: None, 1: None}
        self._zooming_object = None

        # Grabber objects which follow the controllers
        self._grabbers = []
        for tracker in trackers:
            tmp = viz.addGroup()
            viz.link(tracker, tmp)
            self._grabbers.append(tmp)

        # Zooming objects which follow the controllers and are needed for the zooming calculation.
        # Different objects than grabbers are needed to use different linking modes.
        self._zoomers = []
        for tracker in trackers:
            tmp = viz.addGroup()
            viz.link(tracker, tmp, mask=viz.LINK_POS)
            self._zoomers.append(tmp)
示例#3
0
def initTrackers(initFlag=vizconnect.INIT_INDEPENDENT, initList=None):
	#VC: place any general initialization code here
	rawTracker = vizconnect.getRawTrackerDict()

	#VC: initialize a new tracker
	_name = 'head_tracker'
	if vizconnect.isPendingInit('tracker', _name, initFlag, initList):
		#VC: init the raw object
		if initFlag&vizconnect.INIT_RAW:
			#VC: set some parameters
			group = None
			
			#VC: create the raw object
			if group is None:
				group = viz.addGroup()
			rawTracker[_name] = group
	
		#VC: init the wrapper (DO NOT EDIT)
		if initFlag&vizconnect.INIT_WRAPPERS:
			vizconnect.addTracker(rawTracker[_name], _name, make='Virtual', model='Group')

	#VC: initialize a new tracker
	_name = 'rift_tracker'
	if vizconnect.isPendingInit('tracker', _name, initFlag, initList):
		#VC: init the raw object
		if initFlag&vizconnect.INIT_RAW:
			#VC: set some parameters
			index = 0
			
			#VC: create the raw object
			import oculus
			sensorList = oculus.getSensors()
			if index < len(sensorList):
				orientationTracker = sensorList[index]
			else:
				viz.logWarn("** WARNING: Oculus VR Rift Orientation Tracker not present.")
				orientationTracker = viz.addGroup()
				orientationTracker.invalidTracker = True
			rawTracker[_name] = orientationTracker
	
		#VC: init the wrapper (DO NOT EDIT)
		if initFlag&vizconnect.INIT_WRAPPERS:
			vizconnect.addTracker(rawTracker[_name], _name, make='Oculus VR', model='DK2')
	
		#VC: init the offsets
		if initFlag&vizconnect.INIT_OFFSETS:
			_link = vizconnect.getTracker(_name).getLink()
			#VC: clear link offsets
			_link.reset(viz.RESET_OPERATORS)
			
			#VC: reset orientation
			_link.preEuler([0, 0, 0], target=viz.LINK_ORI_OP, priority=-20)

	#VC: return values can be modified here
	return None
示例#4
0
def addAppendages(avatar, numberOfArms):
	global chestHorn, leftShoulderHorn, rightShoulderHorn, headHorn

	#adding virtual models of arms
	if some_global_variables.isLeftHanded == 0:
		#right-handed
		some_global_variables.appendage3 = addArm(PATH_TO_STUFF + "skin_tones/thirdArm.png", resources.RIGHT_ARM)
		some_global_variables.appendage4 = addArm(PATH_TO_STUFF + "skin_tones/fourthArm.png", resources.LEFT_ARM)
		some_global_variables.appendage5 = addArm(PATH_TO_STUFF + "skin_tones/fifthArm.png", resources.RIGHT_ARM)
	else:
		#left-handed
		some_global_variables.appendage3 = addArm(PATH_TO_STUFF + "skin_tones/thirdArm.png", resources.LEFT_ARM)
		some_global_variables.appendage4 = addArm(PATH_TO_STUFF + "skin_tones/fourthArm.png", resources.RIGHT_ARM)
		some_global_variables.appendage5 = addArm(PATH_TO_STUFF + "skin_tones/fifthArm.png", resources.LEFT_ARM)
	TouchCube.thirdAppendage = some_global_variables.appendage3

	#adding horns for attaching the arms to
	chestHorn = viz.addGroup()
	chestHornLink = viz.link(avatar.getBone('Bip01 Spine2'), chestHorn)
	chestHornLink.preTrans([0.0, 0.0, 0.0])
	chestHornLink.preEuler([-90.0, 0.0, 0.0])
	
	leftShoulderHorn = viz.addGroup()
	leftShoulderHornLink = viz.link(avatar.getBone('Bip01 L Clavicle'), leftShoulderHorn)
	leftShoulderHornLink.preTrans([-0.2, 0.0, 0.1])
	leftShoulderHornLink.preEuler([-90.0, 0.0, 0.0])

	rightShoulderHorn = viz.addGroup()
	rightShoulderHornLink = viz.link(avatar.getBone('Bip01 R Clavicle'), rightShoulderHorn)
	rightShoulderHornLink.preTrans([0.2, 0.0, 0.1])
	rightShoulderHornLink.preEuler([-90.0, 0.0, 0.0])

	headHorn = viz.addGroup()
	headHornLink = viz.link(avatar.getBone('Bip01 Head'), headHorn)
	headHornLink.preTrans([0.0, 0.2, 0.1])
	headHornLink.preEuler([-90.0, 0.0, 0.0])
	
	#setting the horns for fourth and fifth arms
	if some_global_variables.isLeftHanded == 0:
		#right-handed
		some_global_variables.appendage4.setParent(leftShoulderHorn)
	else:
		#left-handed
		some_global_variables.appendage4.setParent(rightShoulderHorn)
	some_global_variables.appendage5.setParent(headHorn)

	#switching horn attachment to the appendages based on the number of arms to be used
	switchControlSchema(numberOfArms)
示例#5
0
def createCustomComposite(id=0):
    viz.logNotice('MotionNode Head Tracking')

    # Use general VRPN tracker.
    vrpn = viz.add('vrpn7.dle')
    PPT_VRPN = 'Tracker0@localhost'
    head = vrpn.addTracker(PPT_VRPN)
    # Need to change rotation axes from MotionNode
    # to Vizard conventions.
    head.swapQuat([-3, -2, -1, 4])

    # Or, use the built in MotionNode tracker
    # support.
    #MotionNode = viz.add('MotionNode.dle')
    #head = MotionNode.addSensor()

    headfinal = viz.addGroup()
    headlink = viz.link(head, headfinal, enabled=False)
    import vizact
    vizact.onupdate(viz.PRIORITY_PLUGINS + 1, headlink.update)
    headlink.postTrans([0, 0.1, 0])  # Apply 10 cm translate in Y axis

    import vizuniverse as VU
    comp = VU.VUCompositeTrackers()
    comp.storeTracker(comp.HEAD, headfinal)

    comp.createAvatarNone()
    comp.defineViewpoint()
    comp.finishTrackers()
    return comp
示例#6
0
def addAppendage(avatar, skinChoices, skin = 0, appendage = 0):
	global thirdAppendage, usingInvisibleRod
	
	thirdAppendageHorn = viz.addGroup()

	if(appendage == 0):
		#Third Arm
		usingInvisibleRod = False
		thirdAppendage = viz.addChild(resources.ARM)
		if skin == 9:
			texture = viz.addTexture("skin_tones/010.png")
			texture.wrap(viz.WRAP_S,viz.REPEAT)
			texture.wrap(viz.WRAP_T,viz.REPEAT)
		else:
			texture = viz.addTexture("skin_tones/00" + skinChoices[skin] + ".png")
			texture.wrap(viz.WRAP_S,viz.REPEAT)
			texture.wrap(viz.WRAP_T,viz.REPEAT)
		thirdAppendage.texture(texture)
		thirdAppendage.emissive([.75, .75, .75])
		thirdAppendage.setScale(resources.ARM_SCALE)
	elif(appendage == 1):
		#Cylinder
		usingInvisibleRod = False
		thirdAppendage = viz.addChild(resources.CYLINDER)
		thirdAppendage.setScale(resources.ARM_SCALE)
	thirdAppendage.setParent(thirdAppendageHorn)
	global tahLink
	tahLink = viz.link(avatar.getBone('Bip01 Spine'), thirdAppendageHorn)
	global offsetOp
	offsetOp = tahLink.preTrans([0, 0.3, 0.1])
	tahLink.preEuler([-90.0, 0.0, 0.0])

	thirdAppendage.collideBox()
	thirdAppendage.disable(viz.DYNAMICS)
	TouchCube.thirdAppendage = thirdAppendage
def initGroups(initFlag=vizconnect.INIT_INDEPENDENT, initList=None):
    #VC: place any general initialization code here
    rawGroup = vizconnect.getRawGroupDict()

    #VC: initialize a new group
    _name = 'cave_manual_configuration'
    if vizconnect.isPendingInit('group', _name, initFlag, initList):
        #VC: init the raw object
        if initFlag & vizconnect.INIT_RAW:
            #VC: create the raw object
            rawGroup[_name] = viz.addGroup()

        #VC: init the wrapper (DO NOT EDIT)
        if initFlag & vizconnect.INIT_WRAPPERS:
            vizconnect.addGroup(rawGroup[_name],
                                _name,
                                make='Virtual',
                                model='Origin')

        #VC: set the parent of the node
        if initFlag & vizconnect.INIT_PARENTS:
            vizconnect.getGroup(_name).setParent(
                vizconnect.getTransport('wandmagiccarpet'))

    #VC: return values can be modified here
    return None
示例#8
0
	def __init__(self,**kw):
		viz.EventClass.__init__(self)
		node = viz.addGroup()
		viz.VizNode.__init__(self,node.id)
#		viz.EventClass.callback(self,viz.UPDATE_EVENT,self.onUpdate)
		self.sPos = [0,0]
		self.length = 100
示例#9
0
def room_line(high, wide, dep, pixel):
    room = viz.addGroup()

    pos = np.array([[[wide / 2, 0, 0], [wide / 2, high, 0]],
                    [[-wide / 2, 0, 0], [-wide / 2, high, 0]],
                    [[wide / 2, 0, 0], [-wide / 2, 0, 0]],
                    [[wide / 2, high, 0], [-wide / 2, high, 0]],
                    [[wide / 2, 0, -dep], [wide / 2, high, -dep]],
                    [[-wide / 2, 0, -dep], [-wide / 2, high, -dep]],
                    [[wide / 2, 0, -dep], [-wide / 2, 0, -dep]],
                    [[wide / 2, high, -dep], [-wide / 2, high, -dep]],
                    [[wide / 2, 0, 0], [wide / 2, 0, -dep]],
                    [[wide / 2, high, 0], [wide / 2, high, -dep]],
                    [[-wide / 2, 0, 0], [-wide / 2, 0, -dep]],
                    [[-wide / 2, high, 0], [-wide / 2, high, -dep]]])

    for i in range(12):
        viz.startLayer(viz.LINES)
        viz.lineWidth(pixel)
        viz.vertexColor(1, 0, 0)
        viz.vertex(pos[i, 0, :].tolist())
        viz.vertex(pos[i, 1, :].tolist())
        outline = viz.endLayer()
        outline.setParent(room)

    return room
示例#10
0
def doorway(height, width, radius):
    doorway = viz.addGroup()

    cylinder1 = vizshape.addCylinder(height=height + radius * 2 - 0.01,
                                     radius=radius)
    cylinder2 = vizshape.addCylinder(height=height + radius * 2 - 0.01,
                                     radius=radius)
    cylinder3 = vizshape.addCylinder(height=width,
                                     radius=radius,
                                     axis=vizshape.AXIS_X)
    cylinder4 = vizshape.addCylinder(height=width,
                                     radius=radius,
                                     axis=vizshape.AXIS_X)

    cylinder1.setParent(doorway)
    cylinder2.setParent(doorway)
    cylinder3.setParent(doorway)
    cylinder4.setParent(doorway)

    cylinder1.setPosition([-width / 2, height / 2, 0], mode=viz.REL_PARENT)
    cylinder2.setPosition([width / 2, height / 2, 0], mode=viz.REL_PARENT)
    cylinder3.setPosition([0, height, 0], mode=viz.REL_PARENT)
    cylinder4.setPosition([0, 0, 0], mode=viz.REL_PARENT)

    return doorway
def initTrackers(initFlag=vizconnect.INIT_INDEPENDENT, initList=None):
    #VC: place any general initialization code here
    rawTracker = vizconnect.getRawTrackerDict()

    #VC: initialize a new tracker
    _name = 'r_hand_tracker'
    if vizconnect.isPendingInit('tracker', _name, initFlag, initList):
        #VC: init the raw object
        if initFlag & vizconnect.INIT_RAW:
            #VC: set some parameters
            trackerIndex = -1
            speed = 0.5
            debug = False

            #VC: create the raw object
            from vizconnect.util.virtual_trackers import Keyboard
            rawTracker[_name] = Keyboard(trackerIndex=trackerIndex,
                                         speed=speed,
                                         debug=debug)

        #VC: init the wrapper (DO NOT EDIT)
        if initFlag & vizconnect.INIT_WRAPPERS:
            vizconnect.addTracker(rawTracker[_name],
                                  _name,
                                  make='Virtual',
                                  model='Keyboard')

        #VC: set the parent of the node
        if initFlag & vizconnect.INIT_PARENTS:
            vizconnect.getTracker(_name).setParent(vizconnect.getRoot())

    #VC: initialize a new tracker
    _name = 'l_hand_tracker'
    if vizconnect.isPendingInit('tracker', _name, initFlag, initList):
        #VC: init the raw object
        if initFlag & vizconnect.INIT_RAW:
            #VC: set some parameters
            group = None

            #VC: create the raw object
            if group is None:
                group = viz.addGroup()
            rawTracker[_name] = group

        #VC: init the wrapper (DO NOT EDIT)
        if initFlag & vizconnect.INIT_WRAPPERS:
            vizconnect.addTracker(rawTracker[_name],
                                  _name,
                                  make='Virtual',
                                  model='Group')

        #VC: set the parent of the node
        if initFlag & vizconnect.INIT_PARENTS:
            vizconnect.getTracker(_name).setParent(vizconnect.getRoot())

    #VC: set the name of the default
    vizconnect.setDefault('tracker', 'r_hand_tracker')

    #VC: return values can be modified here
    return None
示例#12
0
def initTrackers(initFlag=vizconnect.INIT_INDEPENDENT, initList=None):
	#VC: place any general initialization code here
	rawTracker = vizconnect.getRawTrackerDict()

	#VC: initialize a new tracker
	_name = 'head_tracker'
	if vizconnect.isPendingInit('tracker', _name, initFlag, initList):
		#VC: init the raw object
		if initFlag&vizconnect.INIT_RAW:
			#VC: set some parameters
			index = 0
			
			#VC: create the raw object
			import oculus
			sensorList = oculus.getSensors()
			if index < len(sensorList):
				orientationTracker = sensorList[index]
			else:
				viz.logWarn("** WARNING: Oculus VR Rift Orientation Tracker not present.")
				orientationTracker = viz.addGroup()
				orientationTracker.invalidTracker = True
			rawTracker[_name] = orientationTracker
	
		#VC: init the wrapper (DO NOT EDIT)
		if initFlag&vizconnect.INIT_WRAPPERS:
			vizconnect.addTracker(rawTracker[_name], _name, make='Oculus VR', model='DK2')

	#VC: return values can be modified here
	return None
示例#13
0
def initTrackers(initFlag=vizconnect.INIT_INDEPENDENT, initList=None):
	#VC: place any general initialization code here
	rawTracker = vizconnect.getRawTrackerDict()

	#VC: initialize a new tracker
	_name = 'head_tracker'
	if vizconnect.isPendingInit('tracker', _name, initFlag, initList):
		#VC: init the raw object
		if initFlag&vizconnect.INIT_RAW:
			#VC: set some parameters
			index = 0
			
			#VC: create the raw object
			import steamvr
			try:
				tracker = steamvr.getExtension().getHMDList()[index]
			except IndexError:
				viz.logWarn("** WARNING: Not able to connect to tracker at index {0}. It's likely that not enough trackers are connected.".format(index))
				tracker = viz.addGroup()
				tracker.invalidTracker = True
			rawTracker[_name] = tracker
	
		#VC: init the wrapper (DO NOT EDIT)
		if initFlag&vizconnect.INIT_WRAPPERS:
			vizconnect.addTracker(rawTracker[_name], _name, make='Valve', model='SteamVR HMD Tracker')

	#VC: set the name of the default
	vizconnect.setDefault('tracker', 'head_tracker')

	#VC: return values can be modified here
	return None
def addCaveWall(cave):
	"""Create visualization of cave walls"""

	walls = cave.getWalls()

	group = viz.addGroup()

	for w in walls:

		mat = viz.Matrix()
		mat.setQuat(w.getQuat())
		mat.setPosition(w.getCenter())

		wall_node = vizshape.addQuad([w.getWidth(),w.getHeight()],transform=mat,parent=group)
		wall_node.color(viz.GRAY)
		wall_node.alpha(0.3)

		wire_node = vizshape.addQuad([w.getWidth(),w.getHeight()],transform=mat,parent=group)
		wire_node.color(viz.BLACK)
		wire_node.polyMode(viz.POLY_WIRE)
		wire_node.zoffset()

	group.disable(viz.LIGHTING)

	return group
示例#15
0
    def __init__(self, canvas, controller):
        super(ModeMenu, self).__init__(canvas, 'mode', 'Mode Selection')

        # Store controller instance
        self.controller = controller

        #Store modes from config to populate modemenu with
        self.modes = config.MenuConfig.Modes
        self.getPanel().fontSize(50)

        ##########################
        """creating modes panel"""
        ##########################

        #creating labels for modes
        self.modeLabels = {}

        for l in self.modes.iterkeys():
            self.modeLabels[l] = viz.addText(l, parent=canvas)

        #creating radio buttons for modes
        self.modeGroup = viz.addGroup(parent=canvas)
        self.radioButtons = {}

        for rb in self.modes.iterkeys():
            self.radioButtons[rb] = viz.addRadioButton(self.modeGroup,
                                                       parent=canvas)

        self.radioButtons['Free Play'].set(1)

        #creating grid panel to add mode to
        modeGrid = vizdlg.GridPanel(parent=canvas)

        #adding modes and radio buttons to grid panel
        for i in self.modes.iterkeys():
            modeGrid.addRow([self.modeLabels[i], self.radioButtons[i]])

        ##############################
        """next and back buttons"""
        ##############################

        #creating grid panels to add next and back buttons to
        setGrid = vizdlg.GridPanel(parent=canvas)

        #create back and next buttons and add to grid panel
        backButton = viz.addButtonLabel('Back')
        startButton = viz.addButtonLabel('Next')
        setGrid.addRow([backButton, startButton])

        #add back and state button actions
        self.backward = vizact.onbuttondown(backButton,
                                            self.controller.backMenu)
        self.forward = vizact.onbuttondown(startButton,
                                           self.controller.nextMenu)

        ###############################
        """add items to ModeMenu"""
        ###############################
        self.addItem(modeGrid)
        self.addItem(setGrid)
示例#16
0
    def generate_surface(self, data, color_array_name):
        """
		Render the vtk data as a surface, centered at origin and return the Vizard object.
		color_array_name defines the name of the CellData array (for example: "equivalent_stress" or "material")
		"""
        # Start creating the model
        viz.startLayer(viz.TRIANGLES)
        # Use the range of the complete data set to ensure consitency
        minimum, maximum = self.vtk_data_local.GetCellData().GetArray(
            color_array_name).GetRange()

        # Generate surface model by iterating over every polygon
        polys = data.GetPolys()
        polys.InitTraversal()
        id_list = vtk.vtkIdList()
        cell = polys.GetNextCell(id_list)
        while not cell == 0:
            # Get the value of the cell for color calculation
            value = data.GetCellData().GetArray(color_array_name).GetValue(
                polys.GetTraversalLocation() / 4)
            color = Simulation_Data._get_color(minimum, maximum, value)
            viz.vertexColor(color[0], color[1], color[2])

            # Read the points (po) of the polygon
            po = []
            for j in range(id_list.GetNumberOfIds()):
                po.append(data.GetPoints().GetPoint(id_list.GetId(j)))

            # Calculate the normal vector of the polygon
            # Normal vector is needed for better lighting
            # Calculate the coss product of vectors from point 0 to 1 and 0 to 2
            ab = (po[1][0] - po[0][0], po[1][1] - po[0][1],
                  po[1][2] - po[0][2])
            ac = (po[2][0] - po[0][0], po[2][1] - po[0][1],
                  po[2][2] - po[0][2])
            normal = numpy.cross(ab, ac)
            # Set the magnitude of the normal vector to 1
            normal = normal / numpy.linalg.norm(normal)
            # Create the polygon with the normal vector and the points
            viz.normal(normal[0], normal[1], normal[2])
            for position in po:
                viz.vertex(position[0], position[1], position[2])
            cell = polys.GetNextCell(id_list)

        # Finish the model
        model = viz.endLayer()
        # Enable lighting for the model (Shadows aren't needed)
        model.enable(viz.LIGHTING)
        model.disable(viz.SHADOW_CASTING)
        model.disable(viz.SHADOWS)
        # Set the center of the model to (0, 0, 0)
        model.setPosition(-(self._original_center[0]),
                          -(self._original_center[1]),
                          -(self._original_center[2]))
        # Create group to get a centered model with coordinates (0, 0, 0)
        group = viz.addGroup()
        model.setParent(group)
        return group
示例#17
0
	def __init__(self, canvas, controller):
		super(ModeMenu, self).__init__(canvas, 'mode', 'Mode Selection')
		
		# Store controller instance
		self.controller = controller
		
		#Store modes from config to populate modemenu with
		self.modes = config.MenuConfig.Modes
		self.getPanel().fontSize(50)
		
		##########################
		"""creating modes panel"""
		##########################
		
		#creating labels for modes
		self.modeLabels = {}
		
		for l in self.modes.iterkeys():
			self.modeLabels[l] = viz.addText(l, parent = canvas)
		
		#creating radio buttons for modes
		self.modeGroup = viz.addGroup(parent = canvas)
		self.radioButtons = {}
		
		for rb in self.modes.iterkeys():
			self.radioButtons[rb] = viz.addRadioButton(self.modeGroup, parent = canvas)
		
		self.radioButtons['Free Play'].set(1)
		
		#creating grid panel to add mode to
		modeGrid = vizdlg.GridPanel(parent = canvas)
		
		#adding modes and radio buttons to grid panel
		for i in self.modes.iterkeys():
			modeGrid.addRow([self.modeLabels[i], self.radioButtons[i]])
		
		##############################
		"""next and back buttons"""
		##############################
		
		#creating grid panels to add next and back buttons to
		setGrid = vizdlg.GridPanel(parent = canvas)
		
		#create back and next buttons and add to grid panel
		backButton = viz.addButtonLabel('Back')
		startButton = viz.addButtonLabel('Next')
		setGrid.addRow([backButton, startButton])
		
		#add back and state button actions
		self.backward = vizact.onbuttondown(backButton, self.controller.backMenu)
		self.forward = vizact.onbuttondown(startButton, self.controller.nextMenu)
		
		###############################
		"""add items to ModeMenu"""
		###############################
		self.addItem(modeGrid)
		self.addItem(setGrid)
示例#18
0
def toggleMenu(node=viz.addGroup(),view=viz.MainView,menu=viz.addGUICanvas(),val=viz.TOGGLE):
	menu.visible(val)
	menuLink = None
	if menu.getVisible() is True:
		pos = view.getPosition()
		menu.setPosition(pos[0],pos[1]-1,pos[2]+5)
#		menuLink.remove()
	else:
		menuLink = viz.grab(node,menu)
示例#19
0
def BridgeRoot(pos=([0,0,0]),euler=([0,0,0])):
	bridge_root = viz.addGroup()
#	axes = vizshape.addAxes(parent=bridge_root)
#	X = viz.addText3D('X',pos=[1.1,0,0],color=viz.RED,scale=[0.3,0.3,0.3],parent=axes)
#	Y = viz.addText3D('Y',pos=[0,1.1,0],color=viz.GREEN,scale=[0.3,0.3,0.3],align=viz.ALIGN_CENTER_BASE,parent=axes)
#	Z = viz.addText3D('Z',pos=[0,0,1.1],color=viz.BLUE,scale=[0.3,0.3,0.3],align=viz.ALIGN_CENTER_BASE,parent=axes)
	bridge_root.setPosition(pos)
	bridge_root.setEuler(euler)
	return bridge_root
示例#20
0
	def getHUD(self):
		"""Returns the root HUD node"""
		if not self._hud_root:
			root = viz.addGroup()
			root.setReferenceFrame(viz.RF_VIEW)
			root.drawOrder(100000)
			root.disable(viz.DEPTH_TEST)
			root.disable(viz.LIGHTING)
			self._hud_root = root
		return self._hud_root
示例#21
0
    def makeRail(self):
        rail = viz.addGroup()

        # Cylinders to act as the wheel tracks
        leftCyl = vizshape.addCylinder(height=20,
                                       radius=5,
                                       axis=vizshape.AXIS_Y,
                                       slices=20,
                                       bottom=True,
                                       top=True)
        m = viz.Matrix()
        m.postTrans(-10)
        leftCyl.setMatrix(m)

        rightCyl = vizshape.addCylinder(height=20,
                                        radius=5,
                                        axis=vizshape.AXIS_Y,
                                        slices=20,
                                        bottom=True,
                                        top=True)
        m = viz.Matrix()
        m.postTrans(10)
        rightCyl.setMatrix(m)

        # Slats
        slat1 = vizshape.addBox(size=(40, 5, 5),
                                right=True,
                                left=True,
                                top=True,
                                bottom=True,
                                front=True,
                                back=True,
                                splitFaces=False)
        m = viz.Matrix()
        m.postTrans(0, 5, 0)
        slat1.setMatrix(m)

        slat2 = vizshape.addBox(size=(40, 5, 5),
                                right=True,
                                left=True,
                                top=True,
                                bottom=True,
                                front=True,
                                back=True,
                                splitFaces=False)
        m = viz.Matrix()
        m.postTrans(0, -5, 0)
        slat2.setMatrix(m)

        leftCyl.setParent(rail)
        rightCyl.setParent(rail)
        slat1.setParent(rail)
        slat2.setParent(rail)

        return rail
示例#22
0
def initTrackers(initFlag=vizconnect.INIT_INDEPENDENT, initList=None):
    #VC: place any general initialization code here
    rawTracker = vizconnect.getRawTrackerDict()

    #VC: initialize a new tracker
    _name = 'dk2'
    if vizconnect.isPendingInit('tracker', _name, initFlag, initList):
        #VC: init the raw object
        if initFlag & vizconnect.INIT_RAW:
            #VC: set some parameters
            index = 0

            #VC: create the raw object
            import oculus
            sensorList = oculus.getSensors()
            if index < len(sensorList):
                orientationTracker = sensorList[index]
            else:
                viz.logWarn(
                    "** WARNING: Oculus VR Rift Orientation Tracker not present."
                )
                orientationTracker = viz.addGroup()
                orientationTracker.invalidTracker = True
            rawTracker[_name] = orientationTracker

        #VC: init the wrapper (DO NOT EDIT)
        if initFlag & vizconnect.INIT_WRAPPERS:
            vizconnect.addTracker(rawTracker[_name],
                                  _name,
                                  make='Oculus VR',
                                  model='DK2')

        #VC: init the offsets
        if initFlag & vizconnect.INIT_OFFSETS:
            _link = vizconnect.getTracker(_name).getLink()
            #VC: clear link offsets
            _link.reset(viz.RESET_OPERATORS)

            #VC: apply offsets
            _link.postTrans([0, 1.405, 0])

        #VC: init the mappings for the wrapper
        if initFlag & vizconnect.INIT_WRAPPER_MAPPINGS:
            #VC: on-state mappings
            if initFlag & vizconnect.INIT_MAPPINGS_ON_STATE:
                vizconnect.getTracker(_name).setOnStateEventList([
                    vizconnect.onstate(
                        lambda rawInput: rawInput['keyboard'].isButtonDown(19),
                        vizconnect.getTracker(_name).resetHeading
                    ),  # make=Generic, model=Keyboard, name=keyboard, signal=Key R
                ])

    #VC: return values can be modified here
    return None
示例#23
0
	def __init__(self):
		super(self.__class__, self).__init__()
		
		self._day = viz.add('resources/sky_day.osgb',parent=self._root)
		self._day.renderToBackground(order=8)
		self._environment = vizfx.addChild('resources/environment.osgb',parent=self._root)
#		self._environment.renderToBackground()
		self._waveGroup = viz.addGroup(parent=self._root)
#		self._wave_M = viz.addChild('resources/wave.osgb',cache=viz.CACHE_CLONE,pos=([0,1.5,0]),parent=self._waveGroup)
#		self._wave_B = viz.addChild('resources/wave.osgb',cache=viz.CACHE_CLONE,pos=([0,1.5,-50]),parent=self._waveGroup)
		self._newWalkway = vizfx.addChild('resources/walkway.osgb',pos=[0,0.25,0], parent=self._root)	
	def show(self):
		"""Turns on the grid, destroys any prior grid, and writes the current grid to file."""
		if not self.previousMatrix:
			self.previousMatrix = viz.MainView.getMatrix()
		
		self.state = viz.ON
		viz.MainView.reset(viz.HEAD_POS | viz.HEAD_ORI)
		
		if (self.grid):
			self.grid.remove()
		
		self.grid = viz.addGroup()
		
		m =  viz.MainWindow.getMatrix()

		horizOffset = math.tan(self.centerHorizAngle)*self.distance + self.offset[0]
		vertOffset = math.tan(self.centerVertAngle)*self.distance + self.offset[1]
		
		horizDelta = math.tan(self.horizAngle) * self.distance + self.dx
		vertDelta = math.tan(self.vertAngle) * self.distance + self.dy
		
		topLeftPos = [horizOffset - horizDelta * (self.numCols -1) / 2, vertOffset - vertDelta * (self.numRows - 1) / 2, self.distance]
		
		self.pos =  [[[0, 0, 0]] * self.numRows for k in range(self.numCols)]
		
		self.pos_screen_left = [[[0, 0, 0]] * self.numRows for k in range(self.numCols)]
		self.pos_screen_right = [[[0, 0, 0]] * self.numRows for k in range(self.numCols)]
		
		for i in range(0, self.numCols):
			for j in range(0, self.numRows):
				#print i,j
				self.pos[i][j] = [topLeftPos[0] + i * horizDelta, topLeftPos[1] + j * vertDelta, self.distance]
								
				pt = viz.MainWindow.worldToScreen(self.pos[i][j], eye=viz.LEFT_EYE)
				pt[2] = 0
				self.pos_screen_left[i][j] = pt
				#print pt

				
				pt = viz.MainWindow.worldToScreen(self.pos[i][j], eye=viz.RIGHT_EYE)
				pt[2] = 0
				self.pos_screen_right[i][j] = pt
				
				q = viz.addTexQuad(parent=self.grid)
				q.texture(self.cross_tex)
				q.setScale(self.stimScale, self.stimScale, 1)
				q.setPosition(self.pos[i][j])
				q.billboard() #Makes always visible to viewer
				
		#print self.pos
				
		self.writeoutSettings()
		self.writeCustomCalPoints()
	def __init__(self,tracker):

		# Initialize using group node
		group = viz.addGroup()
		viz.VizNode.__init__(self,group.id)

		self._offset = viz.Vector()
		self._tracker = tracker
		self._velocity = 0.0

		# Update tracker every frame
		self._updater = vizact.onupdate(0,self.update)
示例#26
0
    def __init__(self, tracker):

        # Initialize using group node
        group = viz.addGroup()
        viz.VizNode.__init__(self, group.id)

        self._offset = viz.Vector()
        self._tracker = tracker
        self._velocity = 0.0

        # Update tracker every frame
        self._updater = vizact.onupdate(0, self.update)
def initTrackers(initFlag=vizconnect.INIT_INDEPENDENT, initList=None):
	#VC: place any general initialization code here
	rawTracker = vizconnect.getRawTrackerDict()

	#VC: initialize a new tracker
	_name = 'head_tracker'
	if vizconnect.isPendingInit('tracker', _name, initFlag, initList):
		#VC: init the raw object
		if initFlag&vizconnect.INIT_RAW:
			#VC: set some parameters
			addMouseOrientation = True
			positionSensitivity = 2.5
			heightOffset = 1.82
			sensorIndex = 0
			
			#VC: create the raw object
			import oculus
			sensorList = oculus.getSensors()
			if sensorIndex < len(sensorList):
				dk2Tracker = sensorList[sensorIndex]
				from vizconnect.util import virtual_trackers
				tracker = virtual_trackers.TrackerAndKeyboardWalking(dk2Tracker, addMouseOrientation=addMouseOrientation, positionSensitivity=positionSensitivity, heightOffset=heightOffset)
			else:
				viz.logWarn("** WARNING: Oculus Tracker not present.")
				tracker = viz.addGroup()
				tracker.invalidTracker = True
			rawTracker[_name] = tracker
	
		#VC: init the wrapper (DO NOT EDIT)
		if initFlag&vizconnect.INIT_WRAPPERS:
			vizconnect.addTracker(rawTracker[_name], _name, make='Oculus VR', model='Rift With Mouse And Keyboard')
	
		#VC: init the offsets
		if initFlag&vizconnect.INIT_OFFSETS:
			_link = vizconnect.getTracker(_name).getLink()
			#VC: clear link offsets
			_link.reset(viz.RESET_OPERATORS)
			
			#VC: reset orientation
			_link.preEuler([0, 0, 0], target=viz.LINK_ORI_OP, priority=-20)
	
		#VC: init the mappings for the wrapper
		if initFlag&vizconnect.INIT_WRAPPER_MAPPINGS:
			#VC: on-state mappings
			if initFlag&vizconnect.INIT_MAPPINGS_ON_STATE:
				vizconnect.getTracker(_name).setOnStateEventList([
						vizconnect.onstate(lambda rawInput: rawInput['keyboard'].isButtonDown(19), vizconnect.getTracker(_name).resetHeading),# make=Generic, model=Keyboard, name=keyboard, signal=Key R
				])

	#VC: return values can be modified here
	return None
示例#28
0
	def __init__(self):		
		# --Key commands
		self.KEYS = { 'forward'	: 'w'
					,'back' 	: 's'
					,'left' 	: 'a'
					,'right'	: 'd'
					,'down'		: 'z'
					,'up'		: 'x'
					,'reset'	: 'r'
					,'camera'	: 'c'
					,'restart'	: viz.KEY_END
					,'home'		: viz.KEY_HOME
					,'builder'	: 'b'
					,'viewer'	: 'v'
					,'env'		: 't'
					,'grid'		: 'g'
					,'hand'		: 'h'
					,'showMenu' : ' '
					,'snapMenu'	: viz.KEY_CONTROL_L
					,'interact' : viz.MOUSEBUTTON_LEFT
					,'utility'	: viz.MOUSEBUTTON_MIDDLE
					,'rotate'	: viz.MOUSEBUTTON_RIGHT
					,'orient'	: viz.KEY_TAB
					,'mode'		: viz.KEY_SHIFT_L
					,'proxi'	: 'p'
					,'collide'	: 'c'
					,'walk'		: ','
					,'angles'	: '.'
					,'road'		: 'n'
					,'esc'		: viz.KEY_ESCAPE
					,'stereo' 	: '='
					,'capslock'	: viz.KEY_CAPS_LOCK
					,'slideFar'	: '2'
					,'slideNear': '1'
		}
		self.MOVE_SPEED = 1.4
		self.MIN_SPEED = 0.7
		self.MAX_SPEED = 2.8
		self.STRAFE_SPEED = 2.0
		self.TURN_SPEED = 90
		self.ORIGIN_POS = [0,0,0]
		self.ORIGIN_ROT = [0,0,0]
		self.EYE_HEIGHT = 1.8
		self.FOV = 100
		self.CAN_ELEVATE = True
		self.CAN_STRAFE = True
		
		self.NODE = viz.addGroup()
		self.VIEW = viz.MainView

		self.VIEW_LINK = viz.link(self.NODE,self.VIEW)	
示例#29
0
def configureSound():
	global subview
	subview = viz.addView()
	subview.setPosition(0,1.6,-1)
	headLocation = viz.addGroup()
	viz.link(subview, headLocation)
	vizsonic.setReverb (6.0, 0.2, 0.5, 0.9, 0.1)
	vizsonic.setSimulatedRoomRadius(3,1.5)
	vizsonic.setShaker(1.0)
	viz.setOption('sound3d.useViewRotation', 0)
	#Set auarlizer to play towards center of room
	viz.setListenerSound3D(subview)
	#Turn on sound debugging?
	viz.setDebugSound3D(False)
示例#30
0
    def __init__(self, filename):
        """
		Load the file and display it with default properties.
		"""
        # Load the file
        self.vtk_data = pv.OpenDataFile(filename)
        # Save applied filters to remove them when not needed anymore to release memory
        self._filters = [self.vtk_data]
        # Save a unaltered version of the data
        self.vtk_data_local = pv.servermanager.Fetch(self.vtk_data)
        # Init variables
        # ... for clipping function
        self.clip_origin = None
        self.clip_normal = None
        # ... for point cloud model
        self.cloud_point_size = 2
        # ... for switching between point cloud and surface model
        self._cycle_view_mode_buffer = False

        # ... for positioning the models
        self.origin_node = viz.addGroup()
        self.surface_node = viz.addGroup(parent=self.origin_node)
        self.cloud_node = viz.addGroup(parent=self.origin_node)
        # ... for registering the model parts
        self.surface_materials = {}
        self.cloud_materials = {}

        # Calculate the center of the data to move the model later to origin
        # bounding_box indices are found out by reading test data and compare it to ParaView standalone
        bounding_box = self.vtk_data_local.GetBounds()
        self._original_center = ((bounding_box[0] + bounding_box[1]) / 2,
                                 (bounding_box[2] + bounding_box[3]) / 2,
                                 (bounding_box[4] + bounding_box[5]) / 2)

        # Generate the models form the vtk data
        self.reload_models()
示例#31
0
def door_line(high, wide, pixel):
    door = viz.addGroup()

    pos = np.array([[-wide / 2, 0, 0], [wide / 2, 0, 0], [wide / 2, high, 0],
                    [-wide / 2, high, 0]])

    viz.startLayer(viz.LINE_LOOP)
    viz.lineWidth(pixel)
    for i in range(4):
        viz.vertex(pos[i, :].tolist())

    line = viz.endLayer()
    line.setParent(door)

    return door
def initTrackers():
	rawTracker = vizconnect.getRawTrackerDict()
	default = ''

	# initialization code for ppt which is a WorldVizPPT
	pptHostname="localhost"
	vrpn7 = viz.add('vrpn7.dle')
	# initialization for sub object ppt_Rhead
	markerId=1
	rawTracker['ppt_Rhead'] = vrpn7.addTracker('PPT0@'+pptHostname, markerId-1)
	# initialization for sub object ppt_Lhead
	markerId=2
	rawTracker['ppt_Lhead'] = vrpn7.addTracker('PPT0@'+pptHostname, markerId-1)
	# initialization for sub object ppt_hand
	markerId=4
	rawTracker['ppt_hand'] = vrpn7.addTracker('PPT0@'+pptHostname, markerId-1)

	# initialization code for osv3_sensor_bus which is a InertialLabsOSv3SensorBus
	port=11
	sensorIndex=0
	InertialLabs = viz.add('InertialLabs.dle')
	sensors = InertialLabs.addSensorBus(port=port)
	try:
		sensor = sensors[sensorIndex]
	except:
		viz.logWarn("** WARNING: can't connect to InertialLabs OSv3 (Sensor Bus) on port {0} with index {1}. It's likely that not enough sensors are connected.".format(port, sensorIndex))
		sensor = viz.addGroup()
		sensor.invalidTracker = True
	rawTracker['osv3_sensor_bus'] = sensor

	# transformation offset code for osv3_sensor_bus
	link = viz.link(rawTracker['osv3_sensor_bus'], viz.NullLinkable)
	link.setSrcMaskOverride(viz.LINK_ORI|viz.LINK_POS)
	link.preEuler([90, 0, 180])
	rawTracker['osv3_sensor_bus'] = link

	# initialization code for optical_heading which is a VirtualOpticalHeading
	leftPosTracker=vizconnect.getRawTracker('ppt_Lhead')
	rightPosTracker=vizconnect.getRawTracker('ppt_Rhead')
	oriTracker=vizconnect.getRawTracker('osv3_sensor_bus')
	distance=0.37
	from vizconnect.virtual_trackers import OpticalHeading
	rawTracker['optical_heading'] = OpticalHeading(leftPosTracker, rightPosTracker, oriTracker, distance=distance)

	# setting default
	default = 'ppt_Rhead'

	return rawTracker, default
示例#33
0
    def generate_cloud(self, data, color_array_name):
        """
		Render the vtk data as a cloud, centered at origin and return the Vizard object.
		color_array_name defines the name of the CellData array (for example: "equivalent_stress" or "material")
		"""
        # Start creating the model
        viz.startLayer(viz.POINTS)
        viz.pointSize(self.cloud_point_size)
        # Use the range of the complete data set to ensure consitency
        minimum, maximum = self.vtk_data_local.GetCellData().GetArray(
            color_array_name).GetRange()

        # Generate cloud model by iterating over every cell
        num_of_cells = data.GetNumberOfCells()
        for i in range(num_of_cells):
            cell = data.GetCell(i)

            # Calculate the center of the cell
            x = 0.0
            y = 0.0
            z = 0.0
            num_of_points = cell.GetNumberOfPoints()
            for j in range(num_of_points):
                point = cell.GetPoints().GetPoint(j)
                x += point[0]
                y += point[1]
                z += point[2]
            x /= num_of_points
            y /= num_of_points
            z /= num_of_points

            # Get the value of the cell for color calculation
            value = data.GetCellData().GetArray(color_array_name).GetValue(i)
            color = Simulation_Data._get_color(minimum, maximum, value)
            viz.vertexColor(color[0], color[1], color[2])
            # Draw the point
            viz.vertex(x, y, z)

        # Finish the model
        model = viz.endLayer()
        # Set the center of the model to (0, 0, 0)
        model.setPosition(-(self._original_center[0]),
                          -(self._original_center[1]),
                          -(self._original_center[2]))
        # Create group to get a centered model with coordinates (0, 0, 0)
        group = viz.addGroup()
        model.setParent(group)
        return group
示例#34
0
def initTrackers(initFlag=vizconnect.INIT_INDEPENDENT, initList=None):
	#VC: place any general initialization code here
	rawTracker = vizconnect.getRawTrackerDict()

	#VC: initialize a new tracker
	_name = 'rift_orientation_tracker'
	if vizconnect.isPendingInit('tracker', _name, initFlag, initList):
		#VC: init the raw object
		if initFlag&vizconnect.INIT_RAW:
			#VC: create the raw object
			import oculus
			index=0
			sensorList = oculus.getSensors()
			if index < len(sensorList):
				orientationTracker = sensorList[index]
			else:
				viz.logWarn("** WARNING: Oculus VR Rift Orientation Tracker not present.")
				orientationTracker = viz.addGroup()
				orientationTracker.invalidTracker = True
			rawTracker[_name] = orientationTracker
	
		#VC: init the wrapper (DO NOT EDIT)
		if initFlag&vizconnect.INIT_WRAPPERS:
			vizconnect.addTracker(rawTracker[_name], _name, make='Oculus VR', model='Rift Orientation Tracker')
	
		#VC: init the offsets
		if initFlag&vizconnect.INIT_OFFSETS:
			_link = vizconnect.getTracker(_name).getLink()
			#VC: clear link offsets
			_link.reset(viz.RESET_OPERATORS)
			
			#VC: reset orientation
			_link.preEuler([0, 0, 0], target=viz.LINK_ORI_OP, priority=-20)
			
			#VC: apply offsets
			_link.postTrans([0, 1.68, 0])			
	
		#VC: init the mappings for the wrapper
		if initFlag&vizconnect.INIT_WRAPPER_MAPPINGS:
			#VC: on-state mappings
			if initFlag&vizconnect.INIT_MAPPINGS_ON_STATE:
				vizconnect.getTracker(_name).setOnStateEventList([
						vizconnect.onstate(lambda rawInput: rawInput['joystick'].isButtonDown(2), vizconnect.getTracker(_name).resetHeading),# make=Generic, model=Joystick, name=joystick, signal=Button 2
				])

	#VC: return values can be modified here
	return None
示例#35
0
def finalDemo():
    sky.remove()
    Panel.remove()
    piazza = viz.add('gallery.osgb')
    Panel2 = vizinfo.InfoPanel(
        "You may now take off the headset, Thank you for your participation",
        parent=canvas,
        align=viz.ALIGN_CENTER,
        fontSize=22,
        icon=False,
        title="Finished")
    Panel2.alpha(.8)
    navigationNode = viz.addGroup()
    viewLink = viz.link(navigationNode, viz.MainView)
    viewLink.preMultLinkable(hmd.getSensor())
    viewLink.setOffset([0, 1.8, 0])
    viz.link(viz.CenterBottom, Panel2, offset=(400, 230, 0))
示例#36
0
def InitVive():
    viz.setMultiSample(8)
    # Setup SteamVR HMD
    hmd = steamvr.HMD()
    if not hmd.getSensor():
        sys.exit('SteamVR HMD not detected')

    navigationNode = viz.addGroup()
    viewLink = viz.link(navigationNode, viz.MainView)
    viewLink.preMultLinkable(hmd.getSensor())

    # setting starting camera position and rotation of the view
    navigationNode.setEuler(180, 0, 0)
    navigationNode.setPosition(-0, 0.3, 3.0)

    # setting starting camera position and rotation
    viz.MainView.setEuler([180, 0, 0])
    viz.MainView.setPosition([0, 1.3, 4])
示例#37
0
    def update_stressindicator(self, e=None):
        """
		Update the meassured data.
		"""
        # Read indicator position
        indicator_position = self._stressindicator.getPosition(viz.ABS_GLOBAL)

        # Convert the indicator position to the position in the ParaView coordinate system.
        # Create a node3d object for the get_local_position() method
        tmp = viz.addGroup()
        tmp.setPosition(indicator_position)
        position = HelpFunctions.get_local_position(
            self._simulation_data.cloud_materials[1].getChildren()[0], tmp)
        tmp.remove()

        # Read the equivalent_stress from ParaView
        stress = self._simulation_data.get_probe_value(position)

        # Update the displayed text
        self._stressindicator_text.message(str(stress))
示例#38
0
	def __setDesktopMode(self):
		self.__cave_mode = False
		
		self.__cave_origin = viz.addGroup()
		
		viz.MainWindow.fov (90) # Reset frustum because the vizcave module plays around with all of this
		viz.MainWindow.setViewOffset (viz.Matrix.euler (0,0,0))
		
		#Set cave tracker to viewtracker, (faulty automatic stereo computation)	
		#self.__cave.setTracker(pos = self.__head_tracker, ori = self.__head_tracker)
						
		self.__cave.addWall(self.__front_wall, mask=viz.CLIENT1) 
		self.__cave.addWall(self.__left_wall, mask=viz.CLIENT2) 
		self.__cave.addWall(self.__right_wall, mask=viz.CLIENT3) 
		self.__cave.addWall(self.__bottom_wall, mask=viz.CLIENT4)
				
		self.drawWalls(True)
		self.drawEyes(True)
		
		self.__cave_origin_auto_update = True
示例#39
0
    def __init__(self,
                 frame_weight=0.5,
                 aperture_scale=0.5,
                 node=None,
                 **kwargs):
        # node to reference this instance in the scenegraph
        self._node = node
        if self._node == None:
            self._node = viz.addGroup()

        viz.VizNode.__init__(self, id=self._node.id, **kwargs)

        # init intensity capture for each face
        self._capture_faces = {
            viz.POSITIVE_X: ViewAccumulator(frame_weight=0.5,
                                            aperture_scale=0.5),
            viz.NEGATIVE_X: ViewAccumulator(frame_weight=0.5,
                                            aperture_scale=0.5),
            viz.POSITIVE_Y: ViewAccumulator(frame_weight=0.5,
                                            aperture_scale=0.5),
            viz.NEGATIVE_Y: ViewAccumulator(frame_weight=0.5,
                                            aperture_scale=0.5),
            viz.POSITIVE_Z: ViewAccumulator(frame_weight=0.5,
                                            aperture_scale=0.5),
            viz.NEGATIVE_Z: ViewAccumulator(frame_weight=0.5,
                                            aperture_scale=0.5)
        }

        cube_euler = {
            viz.POSITIVE_X: [90, 0, 0],
            viz.NEGATIVE_X: [-90, 0, 0],
            viz.POSITIVE_Y: [0, -90, 0],
            viz.NEGATIVE_Y: [0, 90, 0],
            viz.POSITIVE_Z: [0, 0, 0],
            viz.NEGATIVE_Z: [-180, 0, 0]
        }

        # transform face captures according to face orientation
        for face in self._capture_faces:
            self._capture_faces[face].setEuler(cube_euler[face])
            viz.grab(self, self._capture_faces[face])
示例#40
0
	def AddPanel(self, langu):
		self._hud = viz.addGroup(viz.ORTHO, scene=self._window)
		panel = viz.addTexQuad(parent=viz.ORTHO, scene=self._window, size=200)
		panel.texture(viz.addTexture('textures/panel.png', useCache = True))
		panel.setParent(self._hud)
		self.tag = viz.addTexQuad(parent=viz.ORTHO, scene=self._window, size=200)
		self.tag.texture(viz.addTexture('textures/p'+str(self._player)+'_tag.png', useCache = True))
		self.tag.setParent(self._hud)
		#add the player name as a child of the panel
		self._name = viz.addText(self._name, panel)
		self._name.alignment(viz.ALIGN_CENTER_TOP)
		self._name.font("Segoe UI")
		self._name.color(viz.BLACK)
		self._name.fontSize(14)
		self._name.resolution(.5)
		self._name.setScale(1.5,.75,1)
		self._name.setPosition(3,92,0)
		self._name.setParent(self._hud)
		#add the user feedback message
		self._message = viz.addText('', viz.ORTHO, self._window)
		self._message.alignment(viz.ALIGN_LEFT_TOP)
		self._message.font("Segoe UI")
		self._message.color(viz.BLACK)
		self._message.fontSize(13)
		self._message.resolution(.5)
		self._message.setScale(1.5,.75,1)
		self._message.setPosition(-80,32,0)
		self._message.setParent(self._hud)
		#add the collab icon
		self._collabTextures = [viz.add('textures/signs'+langu+'/collab0.png'), viz.add('textures/signs'+langu+'/collab1.png')]
		self._collabIcon = viz.addTexQuad(parent=viz.ORTHO, scene=self._window, size=150)
		self._collabIcon.texture(self._collabTextures[0])
		self._collabIcon.setParent(self._hud)
		self._collabIcon.drawOrder(20)
		self._collabIcon.setPosition(0, -65, 10)
		self._collabIcon.setScale(1,.4,1)
		self._collabIcon.alpha(0)
		self.ResizePanel()
		#add the info panels
		self.CreateInfoPanels()
def initGroups(initFlag=vizconnect.INIT_INDEPENDENT, initList=None):
	#VC: place any general initialization code here
	rawGroup = vizconnect.getRawGroupDict()

	#VC: initialize a new group
	_name = 'cave_manual_configuration'
	if vizconnect.isPendingInit('group', _name, initFlag, initList):
		#VC: init the raw object
		if initFlag&vizconnect.INIT_RAW:
			#VC: create the raw object
			rawGroup[_name] = viz.addGroup()
	
		#VC: init the wrapper (DO NOT EDIT)
		if initFlag&vizconnect.INIT_WRAPPERS:
			vizconnect.addGroup(rawGroup[_name], _name, make='Virtual', model='Origin')
	
		#VC: set the parent of the node
		if initFlag&vizconnect.INIT_PARENTS:
			vizconnect.getGroup(_name).setParent(vizconnect.getDisplay('cave_manual_configuration'))

	#VC: return values can be modified here
	return None
示例#42
0
    def __init__(self,
                 frame_weight=0.5,
                 aperture_scale=0.5,
                 node=None,
                 **kwargs):
        # node to reference this instance in the scenegraph
        self._node = node
        if self._node == None:
            self._node = viz.addGroup()

        viz.VizNode.__init__(self, id=self._node.id, **kwargs)

        # Create two render textures which we will swap between when updating
        self._output_texture = viz.addRenderTexture()
        self._last_frame_texture = viz.addRenderTexture()

        ### INIT CAMERA
        # Create render node for camera
        self._cam = viz.addRenderNode(size=(1024, 1024))
        self._cam.renderOnlyToWindows([viz.MainWindow])
        self._cam.setInheritView(False)
        self._cam.drawOrder(1000)
        self._cam.setFov(90.0, 1.0, 0.1, 1000.0)
        # Only render once per frame, in case stereo is enabled
        self._cam.setRenderLimit(viz.RENDER_LIMIT_FRAME)
        # set the starting render textures for output and input
        self._cam.setRenderTexture(self._output_texture)
        self._cam.texture(self._last_frame_texture, unit=4)
        # link camera to capture
        viz.link(self._node, self._cam)

        # affect camera so its render texture will be computed using the defined shading pipeline
        self._projector = ViewProjector()
        self._projector.setFrameWeight(frame_weight)
        self._projector.setApertureScale(aperture_scale)
        self._projector.affect(self._cam)

        self._update_event = vizact.onupdate(100, self.update)
    def __init__(self, start=True, node=None, **kwargs):

        # node to reference this instance in the scenegraph
        self._node = node
        if self._node == None:
            self._node = viz.addGroup()

        viz.VizNode.__init__(self, id=self._node.id, **kwargs)

        # container to save recorded data
        self._data = []

        # flag that states if animation path capture is currently stopped
        self._stop = not start

        # start time
        self._start_time = -1

        # average fps of the recording
        self._avg_fps = -1.0

        # reference to event function called each frame
        self._onUpdate = vizact.onupdate(0, self._onUpdate)
示例#44
0
    def _setup_stressindicator(self):
        """
		Setup all objects for the stessindicator.
		"""
        # Create a 3D text to display the measured stress
        self._stressindicator_text = viz.addText3D('3D Text', pos=[0, -1, 0])
        self._stressindicator_text.alignment(viz.ALIGN_LEFT_BOTTOM)
        self._stressindicator_text.color(viz.GREEN)
        self._stressindicator_text.setScale([.05, .05, .05])
        # Create a green sphere where the measurement takes place
        self._stressindicator = vizshape.addSphere(radius=0.01,
                                                   color=viz.GREEN)
        self._stressindicator_text.setParent(self._stressindicator)
        self._stressindicator_text.setPosition([0, .1, 0], viz.ABS_PARENT)
        # Create a group to add an offset to the measurement sphere
        tmp = viz.addGroup()
        self._stressindicator.setParent(tmp)
        self._stressindicator.setPosition([0, -.01, .05], viz.ABS_PARENT)
        self._stressindicator.setEuler([0, 90, 0], viz.ABS_PARENT)
        # Connect the stressindicator to the right controller
        viz.link(vizconnect.getRawTracker('r_hand_tracker'), tmp)
        # Hide the objects until the stressindicator gets used
        self._stressindicator.visible(False)
	def __init__(self,**kw):
		group = viz.addGroup(**kw)
		viz.VizNode.__init__(self,group.id)

		self._quad = vizshape.addQuad([1,1],parent=self)
		self._quad.color(viz.RED)
		self._quad.polyMode(viz.POLY_WIRE)

		viz.startLayer(viz.LINES)
		viz.vertexColor(viz.RED)
		for x in range(8):
			viz.vertex([0,0,0])
		self._lines = viz.endLayer(parent=self)
		self._lines.dynamic()

		self.zoffset(-2)
		self.lineWidth(2)
		self.disable(viz.LIGHTING)

		self._wall = None
		self._tracker = None

		vizact.onupdate(viz.PRIORITY_LAST_UPDATE,self.updateFrustum)
def main():
    # Initialize window
    viz.setMultiSample(8)
    viz.go()

    # Setup SteamVR HMD
    hmd = steamvr.HMD()
    if not hmd.getSensor():
        sys.exit('SteamVR HMD not detected')

    # Setup navigation node and link to main view
    navigationNode = viz.addGroup()
    viewLink = viz.link(navigationNode, viz.MainView)
    viewLink.preMultLinkable(hmd.getSensor())

    # Load environment
    gallery = vizfx.addChild('gallery.osgb')
    gallery.hint(viz.OPTIMIZE_INTERSECT_HINT)
    gallery.disable(viz.SHADOW_CASTING)

    #Create skylight
    viz.MainView.getHeadLight().disable()
    sky_light = viz.addDirectionalLight(euler=(0,90,0), color=viz.WHITE)
    sky_light.setShadowMode(viz.SHADOW_DEPTH_MAP)
    
    #Start the Leap Motion!
    handGenerator = LeapListener()
    handGenerator.startLeap(hmd.getSensor())
    
    # Add controllers
    for controller in steamvr.getControllerList():

        # Create model for controller
        controller.model = controller.addModel(parent=navigationNode)
        controller.model.disable(viz.INTERSECTION)
        viz.link(controller, controller.model)
示例#47
0
def setUpHMD():
	global lhTracker, rhTracker, flyingLink, headTracker
	viz.window.setSize(1520,1205)
	viz.go(viz.TRACKER)

	
	view = viz.MainView
#	isense = viz.add('intersense.dle')
#	headTracker = isense.addTracker(port=1)
#	vizact.onkeydown('r',headTracker.resetHeading)
	#vrpn = viz.add('vrpn7.dle')
	#Tracker_HOSTNAME = '171.64.33.43'
	
	from vizconnect.util.virtual_trackers import OpticalHeading
	
	import steamvr
	# vive view will take the Main View (viz.MainView)
	hmd = steamvr.HMD()


		
### Trackers ###

	ORI_TRACKER = hmd.getSensor()
	offsetMarkerNode = viz.addGroup()
	headTracker = viz.link(ORI_TRACKER, offsetMarkerNode)

	lhTracker = steamvr.getControllerList()[0]
	rhTracker = steamvr.getControllerList()[1]
	
	viveViewLink = viz.link(headTracker, viz.MainView)

	
	if FLYING_F:
		flyingLink = viveViewLink
		flyingLink.postTrans(START_POSITION_BASE)
示例#48
0
def playThreeTouch():
	global hfScoreTimes, threeTouchNeedsSimulTouch, gameOn, numberOfHitsCompleted
	# Sort cubes by associated limb
	#BL:start
	#not ignoring the cubes at the center of each block of cubes anymore!
	leftCubes= [touchCubes[i] for i in range(0, 3)]
	leftCubes.extend([touchCubes[i] for i in range(9, 12)])
#	leftCubes.extend([touchCubes[i] for i in [9, 11]])
	leftCubes.extend([touchCubes[i] for i in range(18, 21)])
	rightCubes = [touchCubes[i] for i in range(3, 6)]
	rightCubes.extend([touchCubes[i] for i in range(12, 15)])
#	rightCubes.extend([touchCubes[i] for i in [12, 14]])
	rightCubes.extend([touchCubes[i] for i in range(21, 24)])
	hornCubes = [touchCubes[i] for i in range(6, 9)]
	hornCubes.extend([touchCubes[i] for i in range(15, 18)])
#	hornCubes.extend([touchCubes[i] for i in [15, 17]])
	hornCubes.extend([touchCubes[i] for i in range(24, 27)])
	#BL:end
	# Load sounds
#	scoreSound = touchCubes[0].playsound("./Resources/Misc/bing2.wav", viz.STOP, volume=0.1)
	if USING_VIZSONIC:
		scoreSound = touchCubes[0].playsound("./Resources/Misc/bing2.wav", viz.STOP, volume=0.1)
	else:
		scoreSound = touchCubes[0].playsound("./Resources/Misc/bingCropped_mono.wav", viz.STOP)
	print "game started at time = " + str(time.clock())
	global startTime#, pausedTime
	startTime = time.clock()
	while True:
#	for i in range(NUMBER_OF_CUBE_HIT_ROUNDS):
		scoreCubes = []
		scDimColors = []
		scoreCubes.append(random.choice(leftCubes))
		scDimColors.append(scoreCubes[0]._dimColor)
		scoreCubes.append(random.choice(rightCubes))
		scDimColors.append(scoreCubes[1]._dimColor)
		scoreCubes.append(random.choice(hornCubes))
		scDimColors.append(scoreCubes[2]._dimColor)
		for cube in scoreCubes:
			cube.color(CUBE_HIGHLIGHT_COLOR)
			cube.touchCallback = TouchCube.lightUp if threeTouchNeedsSimulTouch else TouchCube.lightUpAndStayLitPlusRecord
		playerScored = False
		#Stops recording after 5 minutes (5mins * 60s/min = 300)
		#print 'numberOfHitsCompleted = ' + str(numberOfHitsCompleted)
		if (time.clock() < startTime + DURATION_OF_GAME):
			while not playerScored:
				yield viztask.waitTime(1)
				playerScored = allAreLit(scoreCubes)
			global firstHitComplete
			if not threeTouchNeedsSimulTouch: 
				for i in range(len(scoreCubes)):
					if firstHitComplete:
						hfScoreTimes.append(TouchCube.recordedScoreTimeEntries[2 - i].cube.id)
						hfScoreTimes.append(TouchCube.recordedScoreTimeEntries[2 - i].timeStamp)
						appendLRMforHandIDs(hfScoreTimes, TouchCube.recordedScoreTimeEntries[2 - i].triggerObject.id)
#						hfScoreTimes.append(TouchCube.recordedScoreTimeEntries[2 - i].triggerObject.id)
			for i in range(len(scoreCubes)):
				scoreCubes[i]._dimColor = scDimColors[i]
				scoreCubes[i].touchCallback = None
				scoreCubes[i].dim()
			scoreSound.play()
			currentTime = time.clock()
			#Reducing by the pausedTime, captured in controlAppendages.py
			currentTime = currentTime - some_global_variables.pausedTime
			if firstHitComplete:
				hfScoreTimes.append(currentTime)
				dataRecording_controlSchema.enterScoreAndFlush(filePointerForRuntimeScoring, hfScoreTimes, numberOfHitsCompleted * 10)
				dataRecording_controlSchema.recordTimeEveryThreeHits(filePointerForTimeRecording, (currentTime - startTime))
				numberOfHitsCompleted += 1
			else:
				firstHitComplete = True
				startTime = currentTime
#			print "hit completed at time = " + str(time.clock())
#			print "Round: " + str(i)
#			print "Hits completed: " + str(numberOfHitsCompleted)
		else:
			recSound = viz.addGroup().playsound(REC_SOUND, viz.STOP, volume=1.0)
			recSound.play()
			removeCubes(touchCubes)
			gameOn = False
			break
示例#49
0



# initialize window
viz.setMultiSample(8)
viz.fov(60)
viz.go()

# setup SteamVR HMD
hmd = steamvr.HMD()
if not hmd.getSensor():
	sys.exit('SteamVR HMD not detected')
	
# setup navigation node and link to main view
navigationNode = viz.addGroup()
viewLink = viz.link(navigationNode, viz.MainView)
viewLink.preMultLinkable(hmd.getSensor())



# create a zmq REQ socket to talk to Pupil Service
ctx = zmq.Context()
req = ctx.socket(zmq.REQ)
addr = '134.176.175.219'
sub_port = '50020'
req.connect("tcp://{}:{}".format(addr, sub_port))

# convenience functions
def send_recv_notification(n):
	# REQ REP requirese lock step communication with multipart msg (topic,msgpack_encoded dict)
示例#50
0
leftWalls = []
rightWalls = []

def lowerWalls():
	for i in range(1,10):
		leftWallName = 'Left' + str(i) +'-GEODE'
		rightWallName = 'Right' + str(i) + '-GEODE'
		leftWall = scene3.getChild(leftWallName)
		rightWall = scene3.getChild(rightWallName)
		height = wallHeights[i-1]
		leftWall.setPosition([0,-height,0],viz.REL_LOCAL)
		rightWall.setPosition([0,-height,0],viz.REL_LOCAL)
		leftWalls.append(leftWall)
		rightWalls.append(rightWall)
	
walls = viz.addGroup(pos=[0,0,50])
walls.audio_running = viz.addAudio('sounds/pit_running.wav',loop=True)
walls.audio_stop = viz.addAudio('sounds/pit_stop.wav')
walls.audio_running.volume(0.5)
walls.audio_stop.volume(0.5)

def raiseWalls():
	for i, height in enumerate(wallHeights):
		leftWalls[i].runAction(vizact.move(0,2,0,time=(height/2)))
		rightWalls[i].runAction(vizact.move(0,2,0,time=(height/2)))
		if i == len(wallHeights) - 1:
			walls.audio_running.play()
			walls.runAction(vizact.move(0,2,0,time=(height/2)))
			walls.addAction(vizact.call(walls.audio_stop.play))
			walls.addAction(vizact.call(walls.audio_running.pause))
def initDisplays(initFlag=vizconnect.INIT_INDEPENDENT, initList=None):
    #VC: place any general initialization code here
    rawDisplay = vizconnect.getRawDisplayDict()

    #VC: initialize a new display
    CAVE_CONFIG_NAME = 'cave_manual_configuration'

    if vizconnect.isPendingInit('display', CAVE_CONFIG_NAME, initFlag,
                                initList):
        #VC: init which needs to happen before viz.go
        if initFlag & vizconnect.INIT_PREVIZGO:
            viz.setOption('viz.stereo', viz.QUAD_BUFFER)

        #VC: init the raw object
        if initFlag & vizconnect.INIT_RAW:
            #VC: set the window for the display
            _window = viz.MainWindow

            #APG: constants, 5 total instances running...
            FRONT_WALL_CLUSTER_CLIENT = viz.CLIENT1
            LEFT_WALL_CLUSTER_CLIENT = viz.CLIENT2
            RIGHT_WALL_CLUSTER_CLIENT = viz.CLIENT3
            FLOOR_LEFT_CLUSTER_CLIENT = viz.CLIENT4
            FLOOR_RIGHT_CLUSTER_CLIENT = viz.CLIENT5

            #These are determined by testing the monitors
            FRONT_WALL_MONITOR_ID = 1
            LEFT_WALL_MONITOR_ID = 4
            RIGHT_WALL_MONITOR_ID = 5
            FLOOR_LEFT_MONITOR_ID = 3
            FLOOR_RIGHT_MONITOR_ID = 2

            #==============================================
            #Cave calculations

            #VC: create the raw object
            # Create a cave object
            import vizcave
            cave = vizcave.Cave(stereo=viz.QUAD_BUFFER)

            # get an origin node
            originName = CAVE_CONFIG_NAME
            initGroups(vizconnect.INIT_INDEPENDENT,
                       [originName])  # ensure it's been created
            originNode = vizconnect.getGroup(originName).getNode3d()

            frontImageWidth = 5.5372
            imageHeight = 2.2225
            imageRise = 0.0
            originLeft = 3.5503
            originRight = 3.5503
            sideImageWidth = 2.9591
            shiftRight = 0
            shiftUp = 0
            shiftForward = 0

            # get the originLeft angle from the origin measurements
            import math
            aOR = math.pi / 4.0
            aAOR = (originRight**2 - originLeft**2 -
                    frontImageWidth**2) / (-2 * originLeft * frontImageWidth)
            if abs(aAOR) <= 1:
                aOR = math.acos(aAOR)

            # convert the angle to front and right shifts
            Sr = -(math.cos(aOR) * originLeft - frontImageWidth / 2.0)
            Sf = (math.sin(aOR) * originLeft - sideImageWidth / 2.0)

            # find left/right, up/down, front/back (x,y,z) extent of caves
            R = frontImageWidth / 2.0 + Sr + shiftRight  # right
            L = -frontImageWidth / 2.0 + Sr + shiftRight  # left
            U = imageRise + imageHeight + shiftUp  # up/top
            D = imageRise + shiftUp  # bottom/down
            F = sideImageWidth / 2.0 + Sf + shiftForward  # front
            B = -sideImageWidth / 2.0 + Sf + shiftForward  # back

            # find corners
            # e.g.
            # Front Wall: C1,C2,C5,C6
            # Left  Wall: C0,C1,C4,C5
            # Right Wall: C2,C3,C6,C7
            C0 = L, U, B
            C1 = L, U, F
            C2 = R, U, F
            C3 = R, U, B
            C4 = L, D, B
            C5 = L, D, F
            C6 = R, D, F
            C7 = R, D, B
            C8 = L, D, 0
            C9 = R, D, 0
            C10 = -0.19939, D, F
            C11 = 0.19939, D, F
            C12 = -0.19939, D, 0
            C13 = 0.19939, D, 0

            #			wall_list = [C0, C1, C2, C3, C4,
            #						C5, C6, C7, C8,
            #						C9, C10, C11, C12, C13]
            #
            #			for item in wall_list:
            #				print(item)

            #==============================================

            WALL_CORNERS = "corners"
            WALL_NAME = "name"
            WALL_CLUSTER_ID = "cluster_id"
            WALL_MONITOR_ID = "monitor_id"

            #Creates wall, then adds it to the vizcave obj
            def config_wall(wall_config, window):
                points = wall_config[WALL_CORNERS]
                cluster_client_id = wall_config[WALL_CLUSTER_ID]
                monitor_id = wall_config[WALL_MONITOR_ID]

                new_wall = vizcave.Wall(upperLeft=points[0],
                                        upperRight=points[1],
                                        lowerLeft=points[2],
                                        lowerRight=points[3],
                                        name=wall_config[WALL_NAME])

                cave.addWall(new_wall, mask=cluster_client_id, window=window)

                with viz.cluster.MaskedContext(cluster_client_id):
                    viz.window.setFullscreenMonitor(monitor_id)
                    _window.setStereoSwap(False)
                    viz.window.setFullscreen(True)

            #Create front wall
            #==================================
            wall_config = {}
            wall_config[WALL_CORNERS] = [C1, C2, C5, C6]
            wall_config[WALL_NAME] = "Front Wall"
            wall_config[WALL_CLUSTER_ID] = FRONT_WALL_CLUSTER_CLIENT
            wall_config[WALL_MONITOR_ID] = FRONT_WALL_MONITOR_ID

            config_wall(wall_config, _window)

            #Create right wall
            #==================================
            wall_config = {}
            wall_config[WALL_CORNERS] = [C2, C3, C6, C7]
            wall_config[WALL_NAME] = "Right Wall"
            wall_config[WALL_CLUSTER_ID] = RIGHT_WALL_CLUSTER_CLIENT
            wall_config[WALL_MONITOR_ID] = RIGHT_WALL_MONITOR_ID

            config_wall(wall_config, _window)

            # #Create left wall
            # #=================================
            wall_config = {}
            wall_config[WALL_CORNERS] = [C0, C1, C4, C5]
            wall_config[WALL_NAME] = "Left Wall"
            wall_config[WALL_CLUSTER_ID] = LEFT_WALL_CLUSTER_CLIENT
            wall_config[WALL_MONITOR_ID] = LEFT_WALL_MONITOR_ID

            config_wall(wall_config, _window)

            #Create floor_left
            #==================================
            wall_config = {}
            wall_config[WALL_CORNERS] = [C5, C11, C8, C13]
            wall_config[WALL_NAME] = "Floor Left"
            wall_config[WALL_CLUSTER_ID] = FLOOR_LEFT_CLUSTER_CLIENT
            wall_config[WALL_MONITOR_ID] = FLOOR_LEFT_MONITOR_ID

            config_wall(wall_config, _window)

            #Create floor_right
            #==================================
            wall_config = {}
            wall_config[WALL_CORNERS] = [C10, C6, C12, C9]
            wall_config[WALL_NAME] = "Floor Right"
            wall_config[WALL_CLUSTER_ID] = FLOOR_RIGHT_CLUSTER_CLIENT
            wall_config[WALL_MONITOR_ID] = FLOOR_RIGHT_MONITOR_ID

            config_wall(wall_config, _window)

            #==================================

            # We need to pass an object which will be used to update the projection
            # or the display to the view's position, typically this would be the
            # node attached to an avatar's head tracker.
            viewpoint = viz.addGroup()
            cave.setTracker(viewpoint)

            # Create a CaveView object for manipulating the entire cave environment.
            # The caveView is a node that can be adjusted to move the entire
            # cave around the virtual environment.
            caveView = vizcave.CaveView(viewpoint)

            _window.originLink = viz.link(originNode,
                                          caveView,
                                          dstFlag=viz.ABS_GLOBAL,
                                          srcFlag=viz.ABS_GLOBAL)
            _window.caveView = caveView
            _window.originNode = originNode
            _window.displayNode = cave
            _window.viewpointNode = viewpoint

            rawDisplay[CAVE_CONFIG_NAME] = _window

        #VC: init the wrapper (DO NOT EDIT)
        if initFlag & vizconnect.INIT_WRAPPERS:
            vizconnect.addDisplay(rawDisplay[CAVE_CONFIG_NAME],
                                  CAVE_CONFIG_NAME,
                                  make='Generic',
                                  model='Cave Manual Configuration')

        #VC: set the parent of the node
        if initFlag & vizconnect.INIT_PARENTS:
            vizconnect.getDisplay(CAVE_CONFIG_NAME).setParent(
                vizconnect.getAvatar('head_and_hand').getAttachmentPoint(
                    'head'))

    #VC: set the name of the default
    vizconnect.setDefault('display', 'cave_manual_configuration')

    #VC: return values can be modified here
    return None
def initAvatars(initFlag=vizconnect.INIT_INDEPENDENT, initList=None):
    #VC: place any general initialization code here
    rawAvatar = vizconnect.getRawAvatarDict()

    #VC: initialize a new avatar
    _name = 'head_and_hand'
    if vizconnect.isPendingInit('avatar', _name, initFlag, initList):
        #VC: init the raw object
        if initFlag & vizconnect.INIT_RAW:
            #VC: set some parameters
            # rightHandFilename = 'glove.cfg'
            rightHandFilename = ''
            leftHandFilename = ''

            #VC: create the raw object
            # base avatar
            avatar = viz.addGroup()
            avatar._bodyPartDict = {}
            avatar._handModelDict = {}
            # head
            head = viz.addGroup()
            head.setParent(avatar)
            avatar._bodyPartDict[vizconnect.AVATAR_HEAD] = head
            # left hand
            if leftHandFilename:
                leftHand = avatar.add(leftHandFilename)
                avatar.leftHandFilename = leftHandFilename
            else:
                leftHand = viz.addGroup()
                avatar.leftHandFilename = None
            leftHand.setParent(avatar)
            avatar._bodyPartDict[vizconnect.AVATAR_L_HAND] = leftHand
            # right hand
            if rightHandFilename:
                rightHand = avatar.add(rightHandFilename)
                avatar.rightHandFilename = rightHandFilename
            else:
                rightHand = viz.addGroup()
                avatar.rightHandFilename = None
            rightHand.setParent(avatar)
            avatar._bodyPartDict[vizconnect.AVATAR_R_HAND] = rightHand
            # done
            rawAvatar[_name] = avatar

        #VC: init the wrapper (DO NOT EDIT)
        if initFlag & vizconnect.INIT_WRAPPERS:
            vizconnect.addAvatar(rawAvatar[_name],
                                 _name,
                                 make='Generic',
                                 model='Head and Hand')

        #VC: init the gestures
        if initFlag & vizconnect.INIT_GESTURES:
            #VC: need to get the raw input dict so we have access to signals
            import vizact
            rawInput = vizconnect.getConfiguration().getRawDict('input')

            #VC: gestures for the avatar's r_hand
            import hand
            # remove the old hand
            rightHand = rawAvatar[_name]._bodyPartDict[
                vizconnect.AVATAR_R_HAND]
            if rightHand:
                rightHand.remove()
            # add a new hand
            def initHand():
                sensor = hand.InputSensor()
                rawAvatar[_name].handSensor = sensor
                sensor.createHandRenderer = lambda *args, **kw: hand._InputDeviceRenderer(
                    *args, **kw)

                def appliedGetData():
                    #VC: set the mappings for the gestures
                    if rawInput['flystick'].isButtonDown(
                            0
                    ):  # make=ART, model=Flystick, name=flystick, signal=Button 0
                        return (hand.GESTURE_FIST, False, False
                                )  # GESTURE_FIST
                    #VC: end gesture mappings
                    return (hand.GESTURE_FLAT_HAND, False, False)

                sensor.getData = appliedGetData
                file = None
                if hasattr(rawAvatar[_name], "rightHandFilename"):
                    file = rawAvatar[_name].rightHandFilename
                return hand.HandModel(left=False,
                                      type=hand.GLOVE_5DT,
                                      file=file,
                                      sensor=sensor)

            rightHand = initHand()
            rightHand.setParent(rawAvatar[_name])
            rawAvatar[_name]._bodyPartDict[
                vizconnect.AVATAR_R_HAND] = rightHand
            rawAvatar[_name]._handModelDict[
                vizconnect.AVATAR_R_HAND] = rightHand

            #VC: gestures may change the raw avatar, so refresh the raw in the wrapper
            vizconnect.getAvatar(_name).setRaw(rawAvatar[_name])

        #VC: init the animator
        if initFlag & vizconnect.INIT_ANIMATOR:
            # need to get the raw tracker dict for animating the avatars
            from vizconnect.util.avatar import animator
            from vizconnect.util.avatar import skeleton

            # get the skeleton from the avatar
            _skeleton = skeleton.Disembodied(rawAvatar[_name])

            #VC: set which trackers animate which body part
            # format is: bone: (tracker, parent, degrees of freedom used)
            _trackerAssignmentDict = {
                vizconnect.AVATAR_HEAD:
                (vizconnect.getTracker('dtrack_head').getNode3d(), None,
                 vizconnect.DOF_6DOF),
                vizconnect.AVATAR_R_HAND:
                (vizconnect.getTracker('dtrack_flystick').getNode3d(), None,
                 vizconnect.DOF_6DOF),
            }

            #VC: create the raw object
            _rawAnimator = animator.Disembodied(rawAvatar[_name], _skeleton,
                                                _trackerAssignmentDict)

            #VC: set animator in wrapper (DO NOT EDIT)
            vizconnect.getAvatar(_name).setAnimator(_rawAnimator,
                                                    make='Virtual',
                                                    model='Disembodied')

        #VC: set the parent of the node
        if initFlag & vizconnect.INIT_PARENTS:
            vizconnect.getAvatar(_name).setParent(
                vizconnect.getGroup('cave_manual_configuration'))

    #VC: set the name of the default
    vizconnect.setDefault('avatar', 'head_and_hand')

    #VC: return values can be modified here
    return None
示例#53
0
#viz.add('piazza_animations.osgb')
#######################################################

# Setup Oculus Rift HMD
headTracker = None
hmd = oculus.Rift()
headTracker = hmd.getSensor()

if not headTracker:
	hmd = steamvr.HMD()
	headTracker = hmd.getSensor()
else:
	globals_oa.hmdType = "RIFT"

# Setup navigation node and link to main view
navigationNode = viz.addGroup()
viewLink = viz.link(navigationNode, viz.MainView)

if headTracker is None:
	print "Rift is not connected!"
else:
	globals_oa.headTrackingActive = True
	# Setup heading reset key
	vizact.onkeydown(KEYS['reset'], hmd.getSensor().reset)
	viewLink.preMultLinkable(headTracker)

# Apply user profile eye height to view
profile = None
if globals_oa.hmdType == "RIFT":
	profile = hmd.getProfile()
	if profile:
示例#54
0
文件: D2C3.py 项目: vhilab/VRITS-2015
piazza = viz.addChild('piazza.osgb')
viz.addChild('piazza_animations.osgb')

# Loop fountain sound
piazza.playsound('fountain.wav',viz.LOOP,node='fountain-sound')

# Swap out sky with animated sky dome
piazza.getChild('pz_skydome').remove()
day = viz.add('sky_day.osgb')

# Add avatar sitting on a bench
male = viz.addAvatar('vcc_male2.cfg',pos=(-6.5,0,13.5),euler=(90,0,0))
male.state(6)

# Create pigeon
pigeon_root = viz.addGroup()
pigeon_root.visible(False)
pigeon = viz.addAvatar('pigeon.cfg',parent=pigeon_root)

# Add idle animation
random_walk = vizact.walkTo(pos=[vizact.randfloat(-0.5,0.5),0,vizact.randfloat(-0.5,0.5)])
random_animation = vizact.method.state(vizact.choice([1,3],vizact.RANDOM))
random_wait = vizact.waittime(vizact.randfloat(4.0,8.0))
pigeon_idle = vizact.sequence( random_walk, random_animation, random_wait, viz.FOREVER)
pigeon.runAction(pigeon_idle)

# Adding sound to pigeon
hooting = pigeon.playsound('birds.wav',viz.LOOP)
hooting.pause()

# Create flash screen quad
示例#55
0
from touchcube import TouchCube
from touchcube import setupTouchCubes
from touchcube import startThreeTouch
import touchcube
import dataRecording_controlSchema
import time
import some_global_variables

############################################################################################################################

viz.window.setFullscreenMonitor([2, 1])
clock = 0
GRAVITY = 9.81
num = 0
NUM_AVATARS = 2
headLocation = viz.addGroup()

##########################
#### Scene Creation   ####
##########################

light = viz.MainView.getHeadLight().ambient(1, 1, 1)
light2 = viz.addLight()

roomGroup = None
viz.clearcolor(0.1, 0.1, 0.3)
link = None

# list of limbs to check for collision body
COLLISION_LIMBS = [
    "Bip01 Head",
示例#56
0
    def __init__(self):

        viz.EventClass.__init__(self)

        self.callback(viz.TIMER_EVENT, self.onTimer)
        self.callback(viz.KEYDOWN_EVENT, self.onKeyDown)
        self.callback(viz.MOUSEDOWN_EVENT, self.onClick)
        self.callback(viz.COLLIDE_BEGIN_EVENT, self.onCollide)

        self.x = 0
        self.y = 0
        self.z = 0

        self.scaleValue = 2

        self.roll = 0
        self.pitch = 0
        self.yaw = 0

        self.rotateValue = 3

        self.numLives = 5

        self.t = viz.addText("Lives: " + str(self.numLives),
                             viz.SCREEN,
                             pos=[0, 0.9, 0])
        self.t.font('Times New Roman')
        self.t.fontSize(20)

        self.winText = viz.addText3D(
            "You survived the trench!\n   Press any key to quit",
            viz.SCREEN,
            pos=[0.1, 0.9, 0],
            scene=viz.Scene2)
        self.winText.font('Times New Roman')
        self.winText.color(viz.YELLOW)

        self.loseText = viz.addText3D(
            "   You died horribly!\n Press any key to quit",
            viz.SCREEN,
            pos=[0.15, 0.9, 0],
            scene=viz.Scene3)
        self.loseText.font('Times New Roman')
        self.loseText.color(viz.YELLOW)

        self.sounds = [
            'audio/XWING/XWing-Fly1.wav', 'audio/XWING/XWing-Fly2.wav',
            'audio/XWING/XWing-Fly3.wav', 'audio/XWING/YWing-Fly1.wav',
            'audio/XWING/YWing-Fly2.wav', 'audio/TIE/TIE-Fly1.wav',
            'audio/TIE/TIE-Fly2.wav', 'audio/TIE/TIE-Fly3.wav',
            'audio/TIE/TIE-Fly4.wav', 'audio/TIE/TIE-Fly5.wav',
            'audio/TIE/TIE-Fly6.wav', 'audio/TIE/TIE-Fly7.wav'
        ]

        self.rotmatrix = viz.Matrix()

        self.trench = viz.addGroup()

        space = viz.add(viz.ENVIRONMENT_MAP, 'Skybox/stars.jpg')
        skybox = viz.add('skydome.dlc')
        skybox.texture(space)
        m = viz.Matrix()
        m.postScale(100, 100, 100)
        skybox.setMatrix(m)

        self.model = None

        self.xWing = viz.add('x-wing/x-wing.dae')
        self.tie = viz.add('tie/tie.dae')

        self.destroyer = viz.add('StarDestroyer.dae')
        self.destroyer.setAxisAngle(0, 1, 0, -45)
        self.destroyer.setPosition(-1000, 250, 15000)

        self.destroyer2 = viz.add('StarDestroyer.dae')
        self.destroyer2.setAxisAngle(0, 1, 0, -45)
        self.destroyer2.setPosition(-1000, 500, 17500)

        self.deathStar = viz.add('DeathStar.dae')

        m = viz.Matrix()
        m.postScale(10, 10, 10)
        m.postAxisAngle(0, 1, 0, 100)
        m.postTrans(1000, 3000, 20000)
        self.deathStar.setMatrix(m)
        self.deathStar.collideMesh()
        #self.deathStar.enable(viz.COLLIDE_NOTIFY)

        self.monCal = viz.add('MC80a.dae')
        self.monCal.setAxisAngle(0, 1, 0, 45)
        self.monCal.setPosition(300, 500, 15000)

        self.picking = True
        self.win = False
        self.lose = False

        self.winSong = ''
        self.loseSong = ''
        self.ambient = ''

        self.pickShip()
示例#57
0
def add(avatar, appendage, skinChoices, skin, controlSchema):
	global isCube1, isCube2, thirdAppendage, usingInvisibleRod
	
	thirdAppendageHorn = viz.addGroup()

	if(appendage == 0):
		#Third Arm
		usingInvisibleRod = False
		thirdAppendage = viz.addChild(resources.ARM)
		if skin == 9:
			texture = viz.addTexture("skin_tones/010.png")
			texture.wrap(viz.WRAP_S,viz.REPEAT)
			texture.wrap(viz.WRAP_T,viz.REPEAT)
		else:
			texture = viz.addTexture("skin_tones/00" + skinChoices[skin] + ".png")
			texture.wrap(viz.WRAP_S,viz.REPEAT)
			texture.wrap(viz.WRAP_T,viz.REPEAT)
		thirdAppendage.texture(texture)
		thirdAppendage.emissive([.75, .75, .75])
		thirdAppendage.setScale(resources.ARM_SCALE)
	elif(appendage == 1):
		#Cylinder
		usingInvisibleRod = False
		thirdAppendage = viz.addChild(resources.CYLINDER)
		thirdAppendage.setScale(resources.ARM_SCALE)
#	elif(appendage == 2):
#		#Floating hand
#		usingInvisibleRod = True
#		thirdAppendage = viz.addChild(resources.FLOATING_HAND)
#		thirdAppendage.setScale(resources.ARM_SCALE)
#		if skin == 9:
#			texture = viz.addTexture("skin_tones/010.png")
#			texture.wrap(viz.WRAP_S,viz.REPEAT)
#			texture.wrap(viz.WRAP_T,viz.REPEAT)
#		else:
#			texture = viz.addTexture("skin_tones/00" + skinChoices[skin] + ".png")
#			texture.wrap(viz.WRAP_S,viz.REPEAT)
#			texture.wrap(viz.WRAP_T,viz.REPEAT)
#		thirdAppendage.texture(texture)
#		thirdAppendage.emissive([.75, .75, .75])
#	elif(appendage ==3):
#		#Floating Chunk
#		usingInvisibleRod = True
#		thirdAppendage = viz.addChild(resources.FLOATING_CHUNK)
#		thirdAppendage.setScale(resources.ARM_SCALE)
	thirdAppendage.setParent(thirdAppendageHorn)
	global tahLink
	tahLink = viz.link(avatar.getBone('Bip01 Spine'), thirdAppendageHorn)
	global offsetOp
	offsetOp = tahLink.preTrans([0, 0.3, 0.1])
	tahLink.preEuler([-90.0, 0.0, 0.0])

	thirdAppendage.collideBox()
	thirdAppendage.disable(viz.DYNAMICS)
	TouchCube.thirdAppendage = thirdAppendage
	
	# EXTENSION: Add third appendage movement via intersense cube
	isense = viz.add('intersense.dle')
	isCube1 = isense.addTracker(port=6)
	isCube2 = isense.addTracker(port=7)
	
	# Link cubes
	pptextensionDK2.isCube1 = isCube1
	pptextensionDK2.isCube2 = isCube2

	
	# Setup thirdarm updating.
	#vizact.onupdate(0, updateThirdArm)
	
	#Control schema switch
	if (controlSchema == 0):
		vizact.onupdate(0, controlWithWristRotation)
	elif (controlSchema == 1):
		setupBimanualAsymmetricControl()
示例#58
0
piazza = viz.addChild('piazza.osgb')

male = viz.addAvatar('vcc_male.cfg',pos=[8, 0, 7])
female = viz.addAvatar('vcc_female.cfg',pos=[8,0,9],euler=[180,0,0])
male.state(14)
female.state(14)

bird1 = viz.addAvatar('pigeon.cfg',pos=[-6.5, 0.43, -1.56],euler=[120,0,0])
bird1.state(1)

bird2 = viz.addAvatar('pigeon.cfg',pos=[5.61, 4.5, -9.88],euler=[-90,0,0])
bird2.state(1)

piazza.playsound('fountain.wav',viz.LOOP,node='fountain-sound')

conversation_node = viz.addGroup(pos=[8,1.8,8])
conversation_node.playsound('conversation.wav',viz.LOOP)

bell_sound = piazza.playsound('bells.wav',node='bell-sound')
bell_sound.minmax(0,3)

vizact.onkeydown('1',bell_sound.play)

def startBird1():
    bird1_sound = bird1.playsound('birds.wav')
    vizact.ontimer(14,bird1_sound.play)

vizact.ontimer2(7,0,startBird1)

bird2_sound = bird2.playsound('birds.wav')
vizact.ontimer(14,bird2_sound.play)
示例#59
0
SCALE = 5
NUM_DOTS = 50
RADIUS = 30
MOVE_SPEED = .005
ROTATION_SPEED = 5
SUB_GROUP_SPACING = 20
for i in range(0, NUM_DOTS):
	x = random.random() - 0.5
	y = random.random() / 2
	z = random.random() - 0.5
	length = math.sqrt(x*x + y*y + z*z)
	x = x / length * RADIUS
	y = y / length * RADIUS
	z = z / length * RADIUS
	particleGroup = viz.addGroup()
	particleGroup.setPosition([x, y, z])
	particleGroup.setEuler([random.random()*360, random.random()*360, random.random()*360])
	particleGroup.addAction(vizact.spin(random.random(),random.random(),random.random(), random.random()*ROTATION_SPEED,viz.FOREVER))
	particleGroup.addAction(vizact.move(random.random()*MOVE_SPEED,random.random()*MOVE_SPEED,random.random()*MOVE_SPEED,viz.FOREVER), 1)
	
	for i in range(10):
		clone = particle.clone()
		clone.parent(particleGroup)
		clone.setScale([SCALE]*3)
		clone.setEuler([random.random()*360, random.random()*360, random.random()*360])
		clone.setPosition([random.random()*SUB_GROUP_SPACING, random.random()*SUB_GROUP_SPACING, random.random()*SUB_GROUP_SPACING])
	
	

if __name__ == '__main__':