Exemplo n.º 1
0
def read(amcFile, simData=None):
	'''Load animation data from a .amc file and adds it to an SimData.Agent.
	   The name of the SimData.Agent is gotten from the .amc file name.
	   If a simData is provided, it will be queried to get SimData.Agent.
	   If the specified SimData.Agent does not exist, the read will exit
	   early. If no simData is provided a new SimData.Agent is created.
	   In both cases the target SimData.Agent is returned (although if
	   a SimData was provided it will also store the target SimData.Agent).
	   For now amcFile must be a path to a .amc file (as opposed to an open
	   file handle).'''
 
 	# AMC sim files are named: agentType.#.amc where agentType.# is
	# the name of that particular agent instance
	#
	tokens = os.path.basename(amcFile).split(".")
	agentName = Agent.formatAgentName(tokens[0], tokens[1])
	
 	# Python 2.4 limitation: try... except: finally: doesn't work,
 	# have to nest try... except: in try... finally:
	try:
		if simData:
			agentSim = simData.agent(agentName)
			if not agentSim:
				# Agent is not in one of the chosen "selections"
				#
				return None
		else:
			agentSim = SimData.Agent(agentName)
		
		path = os.path.dirname(amcFile)
		
		fileHandle = open(amcFile, "r")
		try:
			frame = 0
			for line in fileHandle:
				tokens = line.strip().split()
				if tokens:
					if tokens[0][0] == ":":
						# file options
						continue
					elif len(tokens) == 1:
						# sample number
						frame = int(tokens[0])
					else:
						jointName = tokens[0]
 					
	 					data = []
	 					for i in range(1, len(tokens)):
	 						data.append(float(tokens[i]))
	 					
	 					agentSim.addSample(jointName, frame, data) 
	 	finally:
			fileHandle.close()				
	except:
		print >> sys.stderr, "Error reading AMC file: %s" % amcFile
		raise
	
	return agentSim
Exemplo n.º 2
0
def read(amcFile, simData=None):
    '''Load animation data from a .amc file and adds it to an SimData.Agent.
	   The name of the SimData.Agent is gotten from the .amc file name.
	   If a simData is provided, it will be queried to get SimData.Agent.
	   If the specified SimData.Agent does not exist, the read will exit
	   early. If no simData is provided a new SimData.Agent is created.
	   In both cases the target SimData.Agent is returned (although if
	   a SimData was provided it will also store the target SimData.Agent).
	   For now amcFile must be a path to a .amc file (as opposed to an open
	   file handle).'''

    # AMC sim files are named: agentType.#.amc where agentType.# is
    # the name of that particular agent instance
    #
    tokens = os.path.basename(amcFile).split(".")
    agentName = Agent.formatAgentName(tokens[0], tokens[1])

    # Python 2.4 limitation: try... except: finally: doesn't work,
    # have to nest try... except: in try... finally:
    try:
        if simData:
            agentSim = simData.agent(agentName)
            if not agentSim:
                # Agent is not in one of the chosen "selections"
                #
                return None
        else:
            agentSim = SimData.Agent(agentName)

        path = os.path.dirname(amcFile)

        fileHandle = open(amcFile, "r")
        try:
            frame = 0
            for line in fileHandle:
                tokens = line.strip().split()
                if tokens:
                    if tokens[0][0] == ":":
                        # file options
                        continue
                    elif len(tokens) == 1:
                        # sample number
                        frame = int(tokens[0])
                    else:
                        jointName = tokens[0]

                        data = []
                        for i in range(1, len(tokens)):
                            data.append(float(tokens[i]))

                        agentSim.addSample(jointName, frame, data)
        finally:
            fileHandle.close()
    except:
        print >> sys.stderr, "Error reading AMC file: %s" % amcFile
        raise

    return agentSim
Exemplo n.º 3
0
def read(callsheet, sim):
    """Load the simmed values of agent variables"""

    if isinstance(callsheet, basestring):
        fileHandle = open(callsheet, "r")
    else:
        fileHandle = callsheet

    try:
        try:
            for line in fileHandle:
                tokens = line.strip().split()
                if tokens:
                    # 0   :	id
                    # 1   :	name
                    # 2-17:	placement matrix
                    # 18  : keyword "cdl"
                    # 19  : cdl file path
                    # 20-?: variable names and values
                    id = int(tokens[0])
                    agentName = Agent.formatAgentName(tokens[1])
                    agentSpec = sim.scene.agentSpec(sim.scene.resolvePath(tokens[19]))

                    agent = sim.agent(agentName, id, agentSpec)

                    if not agent:
                        # Agent is not in one of the chosen "selections"
                        #
                        continue

                    agent.placement = [float(token) for token in tokens[2:18]]
                    for i in range(20, len(tokens), 2):
                        agent.variableValues[tokens[i]] = float(tokens[i + 1])
        finally:
            if fileHandle != callsheet:
                fileHandle.close()
    except:
        print >>sys.stderr, "Error reading callsheet."
        raise
Exemplo n.º 4
0
def read(callsheet, sim):
	'''Load the simmed values of agent variables'''
 
 	if isinstance(callsheet, basestring):
		fileHandle = open(callsheet, "r")
	else:
		fileHandle = callsheet
 	
 	try:
 		try:
			for line in fileHandle:
				tokens = line.strip().split()
		 		if tokens:
		 			# 0   :	id
		 			# 1   :	name
		 			# 2-17:	placement matrix
		 			# 18  : keyword "cdl"
		 			# 19  : cdl file path
		 			# 20-?: variable names and values
		 			id = int(tokens[0])
		 			agentName = Agent.formatAgentName(tokens[1])
		 			agentSpec = sim.scene.agentSpec(sim.scene.resolvePath(tokens[19]))
		 					 			
			 		agent = sim.agent(agentName, id, agentSpec)
			 		
					if not agent:
						# Agent is not in one of the chosen "selections"
						#
						continue
					 			
		 			agent.placement = [ float(token) for token in tokens[2:18] ]
		 			for i in range(20, len(tokens), 2 ):
		 				agent.variableValues[tokens[i]] = float(tokens[i+1])
		finally:
			if fileHandle != callsheet:
		 		fileHandle.close()
	except:
 		print >> sys.stderr, "Error reading callsheet."
 		raise
Exemplo n.º 5
0
	def compute(self, plug, dataBlock):
		'''Calculate the output translate and rotate values. If any value is
		   queried, all of them are updated and cleaned.'''
		try:
			if ( plug == MsvSimLoader.aOutput or
				 plug == MsvSimLoader.aTranslate or
				 plug == MsvSimLoader.aRotate ):
				
				#==============================================================
				# Query Input Attributes
				#==============================================================
				simDir = self._asString( dataBlock.inputValue( MsvSimLoader.aSimDir ) )
				if not simDir or not os.path.isdir(simDir):
					raise npy.Errors.BadArgumentError("Please set the simDir attribute to a valid directory path.")
				
				agentType = self._asString( dataBlock.inputValue( MsvSimLoader.aAgentType ) )
				if not agentType:
					raise npy.Errors.BadArgumentError("Please set the agentType attribute.")

				instance = dataBlock.inputValue( MsvSimLoader.aInstance ).asInt()
	
				frame = int(dataBlock.inputValue( MsvSimLoader.aTime ).asTime().value())

				simType = self._asString( dataBlock.inputValue( MsvSimLoader.aSimType ) )
				simType = ".%s" % simType

				#==============================================================
				# Query the cached sim data, or read it from disk if no cache
				# exists
				#==============================================================				
				try:
					sim = MsvSimLoader.sims[simDir]
				except:
					sim = SimData.SimData()
					SimReader.read( simDir, simType, sim )
					MsvSimLoader.sims[simDir] = sim
				
				#==============================================================
				# Get the sim data for the target agent
				#==============================================================
				agentName = Agent.formatAgentName( agentType, instance )
				agentSim = sim.agent(agentName)
				if agentSim: 
					#==========================================================
					# Iterate over the input joints and query their translate
					# and rotate values from the sim data. Add the
					# corresponding offset and stuff the result in 'output'.
					#==========================================================
					haJoints = dataBlock.inputArrayValue( MsvSimLoader.aJoints )
					haOffsets = dataBlock.inputArrayValue( MsvSimLoader.aOffsets )
					haOutput = dataBlock.outputArrayValue( MsvSimLoader.aOutput )
					for i in range(haJoints.elementCount()):
						# Assume that both the 'joints' and 'output' multis
						# have the same number of elements and are not sparse
						haJoints.jumpToArrayElement(i)
						jointName = self._asString( haJoints.inputValue() )
						jointSim = agentSim.joint(jointName)

						# 'output' is a multi-compound with one entry for every
						# entry in the 'joints' input multi. The compound
						# children are also multis, with one element for every
						# channel in the corresponding joint's sim data. By
						# iterating over the elements in the 'translate' and
						# 'rotate' compound children we know how many samples
						# to query from the joint sim.
						#
						# 'offsets' is structured the same as 'output' and
						# stores the translate and rotate offsets for a given
						# channel.
						sampleIndex = 0
						haOffsets.jumpToArrayElement(i)
						haOutput.jumpToArrayElement(i)
						# The joint sim stores sample data as an array and
						# without distinguishing between translate and rotate
						# samples. 'sampleIndex' will keep track of where we
						# are in that array.
						haTranslateOffset = MArrayDataHandle( haOffsets.inputValue().child( MsvSimLoader.aTranslateOffset ) )
						haTranslate = MArrayDataHandle( haOutput.outputValue().child( MsvSimLoader.aTranslate ) )
						for j in range(haTranslate.elementCount()):
							# Get the sample data
							sample = jointSim.sampleByIndex( sampleIndex, frame )
							# Add the offset
							haTranslateOffset.jumpToArrayElement(j)
							sample += haTranslateOffset.inputValue().asDistance().value()
							# Stuff it in the output
							distance = MDistance( sample )
							haTranslate.jumpToArrayElement(j)
							haTranslate.outputValue().setMDistance( distance )
							# Increment sampleIndex so we know what sample to
							# query from the jointSim
							sampleIndex += 1
						haTranslate.setAllClean()
						
						haRotateOffset = MArrayDataHandle( haOffsets.inputValue().child( MsvSimLoader.aRotateOffset ) )
						haRotate = MArrayDataHandle( haOutput.outputValue().child( MsvSimLoader.aRotate ) )
						for j in range(haRotate.elementCount()):
							# Get the sample data
							sample = jointSim.sampleByIndex( sampleIndex, frame )
							# Add the offset
							haRotateOffset.jumpToArrayElement(j)
							sample += haRotateOffset.inputValue().asAngle().value()
							# Stuff it in the output
							angle = MAngle( sample, MAngle.kDegrees )
							haRotate.jumpToArrayElement(j)
							haRotate.outputValue().setMAngle( angle )
							# Increment sampleIndex so we know what sample to
							# query from the jointSim
							sampleIndex += 1
						haRotate.setAllClean()
					haOutput.setAllClean()
				return MStatus.kSuccess
		except ns.py.Errors.Error, e:
			MGlobal.displayError("Error: %s" % e)
			return MStatus.kFailure