예제 #1
0
	def getTrackValue(self, trackid, time):
		i = self.jointmap[trackid]
		if i != None :
			v = Piavca.Vec(self.vecs[3*i], self.vecs[3*i+1], self.vecs[3*i+2])
			return  self.expmaps[i].expMap(v)
		else:
			return Piavca.Quat()
예제 #2
0
def setUpEventsGUI():
	app = Piavca.getWXApp() #wx.PySimpleApp()
	
	for avatarName in Piavca.Core.getCore().getAvatarNames():
		avatar = Piavca.Core.getCore().getAvatar(avatarName)
		events = Piavca.getEvents(avatar)
		if len(events) > 0:
			frame=wx.Frame(None,-1, title=avatarName+" Events")
			sizer1=wx.BoxSizer(wx.HORIZONTAL)
			sizer2=wx.BoxSizer(wx.VERTICAL)
	
			id_counter = 0
			for event in events:
				button=wx.Button(frame, id_counter, label=event)
				wx.EVT_BUTTON (frame, id_counter, lambda evt, a = avatar, e=event : a.event(e))
				sizer1.Add(button,1 )
				id_counter+=1
				if id_counter % 6 == 0:
					sizer2.Add(sizer1,0)
					sizer1=wx.BoxSizer(wx.HORIZONTAL)
					
			sizer2.Add(sizer1,0)
				
			frame.SetSizer(sizer2)
			frame.SetAutoLayout(1)
			sizer2.Fit(frame)
	
			frame.Show(True)
			frame.Layout()
예제 #3
0
    def expMap(self, p):
        theta = p.mag()

        if (fabs(theta) < 0.00001):
            convFactor = 0.0
        else:
            convFactor = sin(theta) / theta
        p1 = Piavca.Quat()
        p2 = Piavca.Quat()
        p1[0] = cos(theta)
        p1[1] = p[0] * convFactor
        p1[2] = p[1] * convFactor
        p1[3] = p[2] * convFactor

        p2[0] = p1[0] * self.coordAxes[0][0] + p1[1] * self.coordAxes[1][0]
        p2[0] += p1[2] * self.coordAxes[2][0] + p1[3] * self.coordAxes[3][0]

        p2[1] = p1[0] * self.coordAxes[0][1] + p1[1] * self.coordAxes[1][1]
        p2[1] += p1[2] * self.coordAxes[2][1] + p1[3] * self.coordAxes[3][1]

        p2[2] = p1[0] * self.coordAxes[0][2] + p1[1] * self.coordAxes[1][2]
        p2[2] += p1[2] * self.coordAxes[2][2] + p1[3] * self.coordAxes[3][2]

        p2[3] = p1[0] * self.coordAxes[0][3] + p1[1] * self.coordAxes[1][3]
        p2[3] += p1[2] * self.coordAxes[2][3] + p1[3] * self.coordAxes[3][3]

        return p2
예제 #4
0
 def getChildren(self):
     motion = self.motion
     motionlist = []
     if hasattr(motion, "getNumMotions"):
         n = motion.getNumMotions()
         # print "number of children", n
         for i in range(n):
             m = motion.getMotionByIndex(i)
             m = Piavca.getRealMotionType(m)
             motionlist.append(MotionProxy(m, self.backend, self))
     elif hasattr(motion, "getMotion1"):
         m = motion.getMotion1()
         m = Piavca.getRealMotionType(m)
         if m != None:
             motionlist.append(MotionProxy(m, self.backend, self))
         m = motion.getMotion2()
         m = Piavca.getRealMotionType(m)
         if m != None:
             motionlist.append(MotionProxy(m, self.backend, self))
     elif hasattr(motion, "getMotion"):
         m = motion.getMotion()
         m = Piavca.getRealMotionType(m)
         if m != None:
             motionlist.append(MotionProxy(m, self.backend, self))
             # print "got motion list"
     return motionlist
예제 #5
0
	def getChildren(self):
		motion = self.motion
		motionlist = []
		if hasattr(motion, "getNumMotions"):
			n = motion.getNumMotions()
			# print "number of children", n
			for i in range(n):
				m = motion.getMotionByIndex(i)
				m = Piavca.getRealMotionType(m)
				motionlist.append(MotionProxy(m, self.backend, self))
		elif hasattr(motion, "getMotion1"):
			m = motion.getMotion1()
			m = Piavca.getRealMotionType(m)
			if m != None:
				motionlist.append(MotionProxy(m, self.backend, self))
			m = motion.getMotion2()
			m = Piavca.getRealMotionType(m)
			if m != None:
				motionlist.append(MotionProxy(m, self.backend, self))
		elif hasattr(motion, "getMotion"):
			m = motion.getMotion()
			m = Piavca.getRealMotionType(m)
			if m != None:
				motionlist.append(MotionProxy(m, self.backend, self))
		# print "got motion list"
		return motionlist
예제 #6
0
파일: EventsGUI.py 프로젝트: markmze/Piavca
def setUpEventsGUI():
    app = Piavca.getWXApp()  #wx.PySimpleApp()

    for avatarName in Piavca.Core.getCore().getAvatarNames():
        avatar = Piavca.Core.getCore().getAvatar(avatarName)
        events = Piavca.getEvents(avatar)
        if len(events) > 0:
            frame = wx.Frame(None, -1, title=avatarName + " Events")
            sizer1 = wx.BoxSizer(wx.HORIZONTAL)
            sizer2 = wx.BoxSizer(wx.VERTICAL)

            id_counter = 0
            for event in events:
                button = wx.Button(frame, id_counter, label=event)
                wx.EVT_BUTTON(frame,
                              id_counter,
                              lambda evt, a=avatar, e=event: a.event(e))
                sizer1.Add(button, 1)
                id_counter += 1
                if id_counter % 6 == 0:
                    sizer2.Add(sizer1, 0)
                    sizer1 = wx.BoxSizer(wx.HORIZONTAL)

            sizer2.Add(sizer1, 0)

            frame.SetSizer(sizer2)
            frame.SetAutoLayout(1)
            sizer2.Fit(frame)

            frame.Show(True)
            frame.Layout()
예제 #7
0
def quatPose(mot, t):
    print[j for j in Piavca.joints(mot)]
    pose = [
        mot.getQuatValueAtTime(j, t) for j in Piavca.joints(mot)
        if mot.getTrackType(j) & Piavca.QUAT_TYPE
    ]
    print pose
    return pose
예제 #8
0
def findMinima(mot, compMotion, compFrame, threshold, fps):
    expmaps = {}

    # create a set of exponential maps
    # what this does is find the average joint
    # rotations of all of start and end poses of the
    # interruptions, and get them in a form where
    # its easy to calculate the distance of a new quaternion to
    # them
    for j in Piavca.joints(mot):
        # don't take the root into account as we reposition the motion
        if j == Piavca.root_orientation_id or j == Piavca.root_position_id:
            continue
        if mot.isNull(j):
            continue
        joint_type = mot.getTrackType(j)
        # the joint orientations of
        # this joint at the start and end
        # frames of the interruptions
        for t in (Piavca.FLOAT_TYPE, Piavca.VEC_TYPE, Piavca.QUAT_TYPE):
            if not (t & joint_type) or not (t & compMotion.getTrackType(j)):
                continue

            frame = Piavca.getValAtTime(compMotion, j, compFrame, t)

            if t == Piavca.QUAT_TYPE:
                expmaps[(j, t)] = Piavca.ExpMap.TangentSpace([frame])
            elif t == Piavca.VEC_TYPE:
                expmaps[(j, t)] = frame
            else:
                expmaps[(j, t)] = frame

    d_minus = None
    d = None
    d_plus = None

    # find local minima of the distance function
    # if its lower than a threshold then we add it to the set of
    # of possible transition points
    minima = []
    values = []
    #print "start time", seq.getStartTime(), "end time", seq.getEndTime()
    for i in range(int(mot.getStartTime() * fps),
                   int(mot.getEndTime() * fps) - 1):
        d_plus = calculateDistance(mot, float(i + 1) / fps, expmaps)
        print d, d_plus, threshold
        if d:
            if d < d_plus:
                if d_minus == None or d < d_minus:
                    print d, d_plus, threshold
                    if d < threshold:
                        #if len(minima) == 0:
                        values.append(d)
                        minima.append(float(i) / fps)
        d_minus = d
        d = d_plus

    return minima
예제 #9
0
 def clear(self):
     self.avatar = None
     self.motion = None
     self.submotion = None
     self.selectedSubMotion = None
     self.playing = False
     Piavca.clear()
     self.update()
     self.frontend.update()
예제 #10
0
def findMinima(mot, compMotion, compFrame, threshold, fps):
	expmaps = {}
		
	# create a set of exponential maps 
	# what this does is find the average joint 
	# rotations of all of start and end poses of the
	# interruptions, and get them in a form where
	# its easy to calculate the distance of a new quaternion to
	# them
	for j in Piavca.joints(mot):
		# don't take the root into account as we reposition the motion
		if j == Piavca.root_orientation_id or j == Piavca.root_position_id :
			continue
		if mot.isNull(j):
			continue
		joint_type = mot.getTrackType(j)
		# the joint orientations of 
		# this joint at the start and end 
		# frames of the interruptions
		for t in (Piavca.FLOAT_TYPE, Piavca.VEC_TYPE, Piavca.QUAT_TYPE):
			if not(t & joint_type) or not(t & compMotion.getTrackType(j)) :
				continue
				
			frame = Piavca.getValAtTime(compMotion, j, compFrame, t)	
			
			if t == Piavca.QUAT_TYPE:
				expmaps[(j,t)] = Piavca.ExpMap.TangentSpace([frame])
			elif t == Piavca.VEC_TYPE:
				expmaps[(j,t)] = frame
			else:
				expmaps[(j,t)] = frame
	
	d_minus = None
	d = None
	d_plus = None
				
	# find local minima of the distance function 
	# if its lower than a threshold then we add it to the set of
	# of possible transition points
	minima = []
	values = []
	#print "start time", seq.getStartTime(), "end time", seq.getEndTime()
	for i in range(int(mot.getStartTime()*fps), int(mot.getEndTime()*fps)-1):
		d_plus = calculateDistance(mot, float(i+1)/fps, expmaps)
		print d, d_plus, threshold
		if d :
			if d < d_plus:
				if d_minus == None or d < d_minus:
					print d, d_plus, threshold
					if d < threshold:
						#if len(minima) == 0:
						values.append(d)
						minima.append(float(i)/fps)
		d_minus = d
		d = d_plus
		
	return minima
예제 #11
0
	def clear(self):
		self.avatar = None
		self.motion = None
		self.submotion = None
		self.selectedSubMotion = None
		self.playing = False
		Piavca.clear()
		self.update()
		self.frontend.update()
예제 #12
0
    def __init__(self,
                 parent,
                 initial_position=Piavca.Vec(),
                 initial_rotation=Piavca.Quat()):
        PiavcaWXCanvas.PiavcaWXCanvasBase.__init__(self, parent)
        self.cameraPos = initial_position
        self.cameraRot = initial_rotation
        self.cameraPitch = 0.0
        self.cameraYaw = 0.0

        self.positionCallbacks = []
예제 #13
0
	def initCameraPosition(self):
		avatar = self.avatar # Piavca.Core.getCore().getAvatar(0)
		if avatar:
			self.initialAvatarBound = avatar.getBoundBox()#avatar.getBaseBoundBox()
			self.initialAvatarRoot = avatar.getRootPosition()
		else:
			self.initialAvatarBound = Piavca.Bound()
			self.initialAvatarRoot = Piavca.Vec()
			
		print "updating camera position, avatar root:", self.initialAvatarRoot
			
		self.updateCameraPosition()
예제 #14
0
	def getPCMotions(self):
		mots = []
		for i in range(self.num_pcs):
			self.setWeight(i, 1.0)
			self.generateMotion()
			mots.append(Piavca.CurrentValueMotion())
			mots[-1].setName("PC_"+str(i))
			for trackId, index in enumerate(self.jointmap):
				if index != None :
					v = Piavca.Vec(self.vecs[3*index], self.vecs[3*index+1], self.vecs[3*index+2])
					mots[-1].setVecValue(trackId, v)
			self.setWeight(i,0.0)
		return mots
예제 #15
0
	def getValue(self):
		try:
			val = [float(self.texts[i].GetValue()) for i in range(self.dim)]
			val = Piavca.Quat(Piavca.degToRad(val[0]), Piavca.Vec(val[1], val[2], val[3]))
			return val
		except ValueError:
			return None
예제 #16
0
 def getCallback(self, callbackname, time, args):
     if callbackname == "motion":
         return motionCallback(time, args, 1)
     if callbackname == "queue_motion":
         return motionCallback(time, args, 0)
     if callbackname == "backgroundmotion":
         return backgroundMotionCallback(time, args)
     if callbackname == "stop":
         return stopMotionCallback(time, args)
     if callbackname == "sound":
         if self.soundEngine != None:
             return soundCallback(time, args, self.soundEngine)
         else:
             print "could not load sounds as audio playback is not supported, please install pyaudio or  pymedia"
             return None
     if callbackname == "say":
         if self.soundEngine != None:
             return sayCallback(time, args, self.soundEngine)
         else:
             print "could not load sounds as audio playback is not supported, please install pyaudio or  pymedia"
             return None
     if callbackname == "event":
         return eventCallback(time, args)
     if callbackname == "expression":
         retVal = None
         if self.faceMotion == None:
             self.faceMotion = Piavca.KeyframeMotion(1)
             retVal = motionCallback(0.0, (self.faceMotion, ))
         trackId = Piavca.Core.getCore().getExpressionId(args[0])
         if self.faceMotion.isNull(trackId):
             self.faceMotion.addFloatTrack(trackId, 0.0)
         self.faceMotion.setFloatKeyframe(trackId, time, float(args[1]))
         return retVal
예제 #17
0
	def getMotionProxy(self, motion):
		if type(motion) == "":
			motion = Piavca.getMotion(str(motion))
		if motion == None:
			return None
		else:
			return MotionProxy(motion, self)
예제 #18
0
 def getMotionProxy(self, motion):
     if type(motion) == "":
         motion = Piavca.getMotion(str(motion))
     if motion == None:
         return None
     else:
         return MotionProxy(motion, self)
예제 #19
0
	def query(self, e):
		mot = self.motion.getValue()
		compMotion = self.comparisonMotion.getValue()
		
		fps = self.fps.getValue()
		threshold = self.threshold.getValue()	
		
		compMotSeq = MotionList(compMotion, fps)
		
		#frameslist = self.backend.getMotionFramesByName(framelist)
		frameslist = findMinima(mot, compMotion, 0.0, threshold, fps)
		print frameslist
		
		framepairs = itertools.chain(zip(frameslist[:-1], frameslist[1:]),zip(frameslist[:-2], frameslist[2:]),zip(frameslist[:-3], frameslist[3:])) 
		submots = ((MotionList(Piavca.SubMotion(mot, f1, f2), fps),f1,f2) for f1, f2 in framepairs)
		
		#submots = [a for a in submots]
		#print submots
		
		#print "about to call dynamic timewarp"
		
		self.results = [(DynamicTimewarpCost(compMotSeq, submot, poseDifference), f1, f2) for submot, f1, f2 in submots]
		self.results.sort()
		
		print "results", self.results
		
		for i, result in enumerate(self.results):
			self.list.InsertStringItem(i, str(result[0]) + " " + str(result[1]) + " " + str(result[2]))
예제 #20
0
def run(path=None, gui_thread=False): 
	app = None
	if path == None:
		try:
			import wx
			from wx.lib.dialogs import *
			
			app = Piavca.getWXApp() #wx.PySimpleApp()
			dialog_return = openFileDialog ()
			path = dialog_return.paths[0]
		except ImportError:
			print "please enter name of .conf file to use"
			path = sys.stdin.readline()

	print path
	pathend = path.rfind("\\")
	print pathend
	if pathend < 0:
		pathend = path.rfind("/")
	print pathend
	if pathend < 0:
		print "no path"
		filename = path
	else:
		print "path"
		filename = path[pathend+1:]
		path = path[:pathend+1]
		os.chdir(path)
	print filename, path
	if filename[-4:] == ".cfg":
		filename = filename[:-4]
	print filename

	script_engine = ScriptEngine("character controller", filename, app)	
	return script_engine
예제 #21
0
    def PCA(self):
        if self.pcs == None:
            print "CANNOT DO PCA, scipy isn't loaded"
        print "doing pca"
        motion = self.tracks[self.selectedTrack].GetMotion()
        splits = self.tracks[self.selectedTrack].GetSplits()
        if len(splits) > 0:
            motions = [
                Piavca.SubMotion(motion, split.GetStart(), split.GetEnd())
                for split in splits
            ]
        else:
            motions = [motion]
        splits = [(0, split.GetStart(), split.GetEnd()) for split in splits]
        length = Track.PositionToTime(
            self.track_length) * Track.frames_per_second
        #self.pcs.do_pca([motion], splits, length, Track.frames_per_second)
        self.pcs.addMotions(motions)
        self.pcs.setFramesPerSecond(Track.frames_per_second)
        self.pcs.create()
        #self.pcs.setMotion(motion)

        # load the PCAs into the avatar to play them
        Piavca.Core.getCore().setCurrentTime(0)
        #self.avatar.playMotionDirect(Piavca.PyMotion(self.pcs))
        self.avatar.playMotionDirect(self.pcs)
        Piavca.Core.getCore().setCurrentTime(self.time)
예제 #22
0
파일: Split.py 프로젝트: markmze/Piavca
	def __init__(self, mot, start = 0, end = -1):
		self.start = start # start time
		self.end = end # end time (if -1 it's the end of the motion)

		# the motion you are taking a range of
		self.originalMotion = mot 
		# a Piavca.rangeMotion that represents the split
		self.rangeMotion = Piavca.TimeRangeMotion(mot, start, end) 
예제 #23
0
	def getParameterVal(self, name):
		if hasattr(self.motion, "get" + name):
			# print name, "set" + name
			if hasattr(self.motion, "set" + name):
				# print name
				if name[:len("Motion")] == "Motion":
					# print "found Motion in paramname"
					return None
				if name[:len("Weight")] == "Weight":
					weights = [0 for i in range(self.motion.getNumMotions())]
					for i in range(self.motion.getNumMotions()):
						motName = self.motion.getMotion(i).getName()
						weights[i] = (i, motName, self.motion.getWeight(i))
					return weights
				else:
					method = getattr(self.motion, "get" + name)
					# print "got method"
					value = method()
					# print "got value"
					# print name, value
					return value
		if name == "FloatValue" or name == "QuatValue" or name == "VecValue":
			core = Piavca.Core.getCore()
			indices = [i for i in range(core.getMinTrackId(), core.getMaxTrackId()+1)]
			names = [core.getTrackName(i) for i in indices]
			if name == "FloatValue":
				vals = [0.0 for i in indices]
				for i, track in enumerate(indices):
					if (not self.motion.isNull(track)) and self.motion.getTrackType(track) & Piavca.FLOAT_TYPE:
						vals[i] = self.motion.getFloatValueAtTime(track,0)
			if name == "VecValue":
				vals = [Piavca.Vec() for i in indices]
				for i, track in enumerate(indices):
					if (not self.motion.isNull(track)) and self.motion.getTrackType(track) & Piavca.VEC_TYPE:
						vals[i] = self.motion.getVecValueAtTime(track,0)
			if name == "QuatValue":
				vals = [Piavca.Quat() for i in indices]
				for i, track in enumerate(indices):
					if (not self.motion.isNull(track)) and self.motion.getTrackType(track) & Piavca.QUAT_TYPE:
						vals[i] = self.motion.getQuattValueAtTime(track,0)
		
			return zip(indices, names, vals)
		
		else:
			return None
예제 #24
0
	def getMotion(self):
		motion = self.motion.getValue()
		
		i = self.list.GetNextSelected(-1)
		print i
		if i >= 0:
			return Piavca.SubMotion(motion, self.results[i][1], self.results[i][2])
		else:
			return None
예제 #25
0
    def logMap(self, q):
        p1 = q
        if (p1[0] < 0.0):
            p1 = Piavca.Quat(-p1[0], -p1[1], -p1[2], -p1[3])

        p2 = Piavca.Quat(self._dot(p1, self.coordAxes[0]),
                         self._dot(p1, self.coordAxes[1]),
                         self._dot(p1, self.coordAxes[2]),
                         self._dot(p1, self.coordAxes[3]))
        p2.normalise()

        theta = acos(p2[0])
        if (fabs(theta) < 0.0001):
            convFactor = 0.0
        else:
            convFactor = theta / sin(theta)
        return Piavca.Vec(p2[1] * convFactor, p2[2] * convFactor,
                          p2[3] * convFactor)
예제 #26
0
 def middleMove(self, x, y):
     #print "right butting dragging", x, y, self.prevX, self.prevY
     if hasattr(self, "prevX"):
         trans = Piavca.Vec((x - self.prevX), -(y - self.prevY), 0.0)
         trans = trans * self.trans_sensitivity
         trans = self.cameraRot.inverse().transform(trans)
         self.cameraPos = self.cameraPos + trans
         self.updatePositionCallback()
         print self.cameraPos
     self.prevX, self.prevY = x, y
예제 #27
0
	def setPosition(self, p):
		#print "setting position ", p
		#oldPos = Piavca.Vec()#self.cvm.getVecValueAtTime(self.jointId, 0)
		if not hasattr(self, "lastShiftTime"):
			self.lastShiftTime = 0.0
		if hasattr(self, "oldPos"):
			diff = p - self.oldPos
			#print diff.mag()
			if abs(diff.mag()) > 0.01:
				#if not self.alreadyShifted:
				if (Piavca.getTime() - self.lastShiftTime) > self.interShiftTime:
					#self.alreadyShifted = True
					self.getMotion().reset()
					#self.shiftedlast == False
					self.lastShiftTime = Piavca.getTime()
			#else:
			#	self.alreadyShifted = False
		self.oldPos = p
		
		
예제 #28
0
    def loadToCanvas(self):
        app = Piavca.getWXApp()
        canvas = app.getCanvas()
        if canvas:
            canvas.addPlugin(self)

            self.quad = gluNewQuadric()

            return True
        else:
            return False
예제 #29
0
	def __call__(self, avatar):
		if self.motion == None:
			#print "script engine core", Piavca.Core.getCore()
			self.motion = Piavca.getMotion(self.motionName)
			if self.motion == None:
				print "Could not find motion", self.motionName
				return
			self.motion.Reference()
		if self.interrupt:
			avatar.interrupt_motion()
		avatar.play_motion(self.motion)
예제 #30
0
 def readfile(self, filename):
     if filename[-4:] == ".cfg":
         self.avatar = Piavca.Avatar(filename[:-4])
     else:
         Piavca.XMLMotionFile.parse(filename)
     if self.avatar == None:
         print self.getAvatarNames()
         print self.getMotionNames()
         if len(self.getAvatarNames()) > 0:
             self.setAvatar(self.getAvatarNames()[0])
     self.frontend.update()
예제 #31
0
def saveAll(filename):
    core = Piavca.Core.getCore()
    motions = core.getMotionNames()
    #print motions
    motions = [Piavca.getMotion(motion) for motion in motions]

    avatars = core.getAvatarNames()
    #print avatars
    avatars = [core.getAvatar(avatar) for avatar in avatars]

    saveMotions(filename, motions=motions, avatars=avatars)
예제 #32
0
	def load(self, avatar):
		print "about to load position handler"
		Piavca.MotionFilter.load(self, avatar)
		print "getting app"
		app = Piavca.getWXApp()
		print "getting canvas"
		canvas = app.getCanvas()
		print "canvas"
		if hasattr(canvas, "loadPositionCallback"):
			print "has position callback"
			canvas.loadPositionCallback(lambda pos, rot : self.setPosition(pos))
		print "print finished loading position handler"
예제 #33
0
def saveAll(filename):
	core = Piavca.Core.getCore()
	motions = core.getMotionNames()
	#print motions
	motions = [Piavca.getMotion(motion) for motion in motions]
	
	avatars = core.getAvatarNames()
	#print avatars
	avatars = [core.getAvatar(avatar) for avatar in avatars]
	
	
	saveMotions(filename, motions=motions, avatars=avatars)
예제 #34
0
	def setMotion(self, motionname):
		self.setTime(0.0)
		#print "motion name", motionname, type(motionname)
		motion = self.getMotionByName(motionname)
		#print "motion", motion
		if motion == None:
			raise ValueError("no motion named" + str(motionname))
		else:
			#print "motion", motion, "ownership", motion.thisown
			if motion.getName() == "":
				dialog_return = textEntryDialog (message="Please enter a name for this motion")
				motion_name = dialog_return.text.encode("latin-1")
				Piavca.loadMotion(motion_name, motion)
			motion.reset(True)
			self.motion = MotionProxy(motion, self)#motion
			self.submotion = self.motion
			#print "avatar", self.avatar
			if self.avatar:
				print "playing", self.avatar, self.motion.getMotion()
				self.avatar.playMotionDirect(self.motion.getMotion())
			self.resetRange()
			self.update()
예제 #35
0
	def ShowDistances(self, e):
		weights = []
		file = open("TrackWeights.txt", "r")
		for line in file.readlines():
			for joint in line.split():
				joint = joint.split("=")
				weight = float(joint[1])
				joint = joint[0]
				jointid = Piavca.Core.getCore().getJointId(joint)
				print joint, jointid, weight
				if( not self.motion.isNull(jointid)):
					weights.append((jointid, float(1.0)))
		self.distancemeasure = Piavca.DistanceMeasure(10, weights)
		self.framearray = Piavca.makeFrameArray(self.motion, 25.0)
		self.reference_time = self.time
예제 #36
0
def calculateDistance(mot, t, expmaps):
	sum = 0.0
	for j in Piavca.joints(mot):
		# don't take the root into account as we reposition the motion
		if j == Piavca.root_orientation_id or j == Piavca.root_position_id :
			continue
		if mot.isNull(j):
			continue
		joint_type = mot.getTrackType(j)
		if joint_type & Piavca.FLOAT_TYPE and expmaps[(j,Piavca.FLOAT_TYPE)]:
			sum += abs(mot.getFloatValueAtTime(j, t) - expmaps[(j,Piavca.FLOAT_TYPE)])
		if joint_type & Piavca.VEC_TYPE and expmaps[(j,Piavca.VEC_TYPE)]:
			sum +=(mot.getVecValueAtTime(j, t) - expmaps[(j,Piavca.VEC_TYPE)]).mag()
		if joint_type & Piavca.QUAT_TYPE and expmaps[(j,Piavca.QUAT_TYPE)]:
			sum +=expmaps[(j,Piavca.QUAT_TYPE)].logMap(mot.getQuatValueAtTime(j, t)).mag()
	return sum
예제 #37
0
	def getMotionByName(self, name):
		if name[:10] == "__Type__::":
			typename = name[10:]
			cl = getattr(Piavca, typename)
			if type(cl) == types.TypeType and issubclass(cl, Piavca.Motion):
				motion =  cl()
				motion.thisown = False
				motion.Reference()
				return motion
			else:
				ValueError(typename+" is not a motion class")
		else:
			print "motion name", name, type(name)
			motion = Piavca.getMotion(str(name.encode("latin-1")))
			if motion == None:
				raise ValueError("no motion named" + str(name))
			else:
				return motion
예제 #38
0
def redirect(filename="python_output.txt", app = None):
	import Piavca
	if wxpresent and app == None:
		print "creating app"
		app = Piavca.getWXApp() #wx.PySimpleApp()
	outputer = outputRedirection(filename)
	outputer.Show()

	outputer.write("Piavca\n")

		
	#outputer.setOutputFunc(Piavca.PiavcaGlut.outputMessage)

	outputer.write("output redirection\n")

	sys.stderr = outputer
	sys.stdout = outputer

	#print "hello"

	print "output redirection successful"
	
	if wxpresent:
		thread.start_new_thread(app.MainLoop, ())
예제 #39
0
	def GUI(self, avatarName):
		print "GUI", avatarName
		if not wxAvailable:
			print "can't instantiate GUI, wx python not present"

		print "app", self.app
		if self.app == None:
			print "getting app"
			self.app = Piavca.getWXApp() #wx.PySimpleApp()

		self.frame=wx.Frame(None,-1)
		sizer1=wx.BoxSizer(wx.HORIZONTAL)
		sizer2=wx.BoxSizer(wx.VERTICAL)

		id_counter = 0
		for scriptname in self.scripts.keys():
			button=wx.Button(self.frame, id_counter, label=scriptname)
			wx.EVT_BUTTON (self.frame, id_counter, lambda e, s = self, n=scriptname : s.playScript(avatarName, n))
			sizer1.Add(button,1 )
			id_counter+=1
			if id_counter % 6 == 0:
				sizer2.Add(sizer1,0)
				sizer1=wx.BoxSizer(wx.HORIZONTAL)
				
		sizer2.Add(sizer1,0)
			
		self.frame.SetSizer(sizer2)
		self.frame.SetAutoLayout(1)
		sizer2.Fit(self.frame)

		self.frame.Show(True)
		self.frame.Layout()

		#print "starting gui"
		if self.gui_thread:
			thread.start_new_thread(self.app.MainLoop, ())
예제 #40
0
	def getEvents(self):
		if self.avatar:
			return Piavca.getEvents(self.avatar)
		else:
			return []
예제 #41
0
def readMotions(motions):
	mots = []
	element_list = []
	child_motion_list = []
	for motion in motions:
		if motion.nodeType == minidom.Node.ELEMENT_NODE:
			#print "current node", motion.nodeName
			if motion.nodeName == "Avatar":
				name = str(motion.getAttribute("name"))
				if name == "":
					name = str(motion.getAttribute("Name"))
				if name == "":
					print "Avatar statement without a name"
					
				position = str(motion.getAttribute("position"))
				if position == "":
					position = str(motion.getAttribute("Position"))
				if position != "":
					position = str(position).strip()
					position = stringToValueList(position)
					position = ValueListToVec(position)
				else:
					position = Piavca.Vec()
					
				rotation = str(motion.getAttribute("rotation"))
				if rotation == "":
					rotation = str(motion.getAttribute("Rotation"))
				if rotation != "":
					rotation = str(rotation).strip()
					rotation = stringToValueList(rotation)
					rotation = ValueListToQuat(rotation)
				else:
					rotation = Piavca.Quat()
					
				avatar = Piavca.Avatar(name)
				#print "loaded avatar", name, position, rotation
				avatar.setRootPosition(position)
				avatar.setRootOrientation(rotation)
				for child in motion.childNodes:
					if child.nodeType != minidom.Node.ELEMENT_NODE:
						continue
					if child.nodeName != "Event":
						#print "expected a Event statement as a child of an avatar but got", child.nodeName
						continue
					name = str(child.getAttribute("name"))
					if name == "":
						name = str(child.getAttribute("Name"))
					if name == "":
						print "Event statement without a name"
					Piavca.addEvent(avatar, name)
					
			elif motion.nodeName == "Motion":
				#print "found a motion statement", motion
				for i in range(motion.attributes.length):
					#print motion.attributes.item(i).name, motion.attributes.item(i).nodeValue
					unknownAttrs=[]
					if motion.attributes.item(i).name != "name":
						unknownAttrs.append((motion.attributes.item(i).name, motion.attributes.item(i).nodeValue))
				name = str(motion.getAttribute("name"))
				if name == "":
					name = str(motion.getAttribute("Name"))
				if name == "":
					print "Motion statement without a name"
				else:
					#print "*"+name+"*"
					mot = Piavca.getMotion(name)
					#print mot
					if mot == None:
						print "could not find motion", name
					else:
						mots.append((mot, str(motion.nodeName), unknownAttrs))
						#print "mots", mots
						
			elif motion.nodeName == "File":
				name = str(motion.getAttribute("name"))
				filename = str(motion.getAttribute("filename"))
				Paivca.loadMotion(name, filename)
						
			elif motion.nodeName == "Keyframes":
				for i in range(motion.attributes.length):
					#print motion.attributes.item(i).name, motion.attributes.item(i).nodeValue
					unknownAttrs=[]
					if motion.attributes.item(i).name != "name":
						unknownAttrs.append((motion.attributes.item(i).name, motion.attributes.item(i).nodeValue))
				name = str(motion.getAttribute("name"))
				mot = Piavca.KeyframeMotion()
				mot.thisown = False
				for child in motion.childNodes:
					if child.nodeType != minidom.Node.ELEMENT_NODE:
						continue
					if child.nodeName != "Key":
						print "expected a key statement as a child of a keyframe motion but got", child.nodeName
						continue
					key_type = str(child.getAttribute("type"))
					key_value = str(child.getAttribute("value"))
					key_time = float(child.getAttribute("time"))
					key_joint = str(child.getAttribute("joint"))
					if key_type == "FLOAT" or key_type == "Float" or key_type == "float":
						key_joint = Piavca.Core.getCore().getExpressionId(key_joint)
					else:
						key_joint = Piavca.Core.getCore().getJointId(key_joint)
					if key_joint == Piavca.Core.getCore().nullId :
						raise ValueError("Unknown Joint Id " + str(child.getAttribute("joint")))
						Piavca.Core.getCore().addJointNameSet([key_joint])
					if key_type == "FLOAT" or key_type == "Float" or key_type == "float":
						if mot.isNull(key_joint):
							mot.addFloatTrack(key_joint, 0.0)
						key_value = float(key_value)
						mot.setFloatKeyframe(key_joint, float(key_time), key_value)
					if key_type== "VEC" or key_type == "Vec" or key_type == "vec":
						if mot.isNull(key_joint):
							mot.addVecTrack(key_joint, Piavca.Vec())
						valuelist = stringToValueList(key_value)
						key_value = ValueListToVec(valuelist)
						mot.setVecKeyframe(key_joint, float(key_time), key_value)
					if key_type == "QUAT" or key_type == "Quat" or key_type == "quat":
						if mot.isNull(key_joint):
							mot.addQuatTrack(key_joint, Piavca.Quat())
						valuelist = stringToValueList(key_value)
						key_value = ValueListToQuat(valuelist)
						mot.setQuatKeyframe(key_joint, float(key_time), key_value)
				if name != "":
					Piavca.loadMotion(name, mot)
							
			else:
				try:
					#print "other motion types", motion.nodeName
					cl = getattr(Piavca, motion.nodeName)
					if type(cl) == types.TypeType and issubclass(cl, Piavca.Motion):
						#print "found motion type", motion.nodeName
						mot = cl()
						
						storedMotName = mot.getName()
						storedMotStr = str(mot)
						if mot == None:
							raise "could not create motion " + motion.nodeName
							continue
						mot.thisown = False
						unknownAttrs=[]
						for i in range(motion.attributes.length):
							if str(motion.attributes.item(i).name) == "name" or str(motion.attributes.item(i).name) == "Name":
								name = str(motion.attributes.item(i).nodeValue)
								#print "========================motion name", name
								if name != "":
									Piavca.loadMotion(name, mot)
								continue
							attrName = motion.attributes.item(i).name
							attrValue = motion.attributes.item(i).nodeValue
							#print attrName, attrValue
							if not setAttribute(mot, attrName, attrValue):
								unknownAttrs.append((attrName, attrValue))
						child_motion_list.append((mot, motion.childNodes))
												
						mot.create()
						mots.append((mot, str(motion.nodeName), unknownAttrs))
					else:
						raise str(motion.nodeName) + " is not a motion type, its type is: " + str(type(cl))
						# add to a "add list" instead, parse attributes into a dictionary
				except AttributeError, e:
					print "Attribute Error:", e
					
					elementName = motion.nodeName
					attrList = []	
					for i in range(motion.attributes.length):
						
						attrName = motion.attributes.item(i).name
						attrValue = motion.attributes.item(i).nodeValue
						attrList.append((attrName, attrValue))
					element_list.append((elementName, attrList))
예제 #42
0
import sys
import os
import time


import Piavca
#Piavca.PiavcaGlut.init()
#Piavca.PiavcaGlut.init(Piavca.Core.getCorePointerAsLong())
import Piavca.JointNames
Piavca.JointNames.loadDefaults()
import wx
from wx.lib.dialogs import *

import thread

app = Piavca.getWXApp()
#app = wx.PySimpleApp()

import Piavca.FreeCameraCanvas
canvas = app.showWindows(canvastype = Piavca.FreeCameraCanvas.FreeCameraCanvas)	
app.getCanvas().setClearColour(1, 1, 1)
	
if len(sys.argv) > 1:
	path = sys.argv[1]
else:
	dialog_return = openFileDialog (wildcard="*.cfg")
	path = dialog_return.paths[0].encode("latin-1")

print path
pathend = path.rfind("\\")
if pathend < 0:
예제 #43
0
def saveMotions(filename, motions, element = None, doc = None, avatars=[]):
	writeout = 0
	if element == None:
		impl = minidom.getDOMImplementation()
		doc = impl.createDocument("", "PiavcaMotions", None)
		element = doc.documentElement
		writeout = 1
	
	allPiavca = Piavca.__dict__
	#print allPiavca
	
	members_to_ignore = ["getQuatValueAtTime", "getVecValueAtTime", "getFloatValueAtTime", "getQuatValueAtTimeInternal", 
						"getVecValueAtTimeInternal", "getFloatValueAtTimeInternal", "getMotionLength"]
	
	for avatar in avatars:
		avatar_el = doc.createElement("Avatar")
		avatar_el.setAttribute("name", avatar.getName())
		avatar_el.setAttribute("position", str(avatar.getRootPosition()))
		q = avatar.getRootOrientation()
		angle = q.getAngle()
		axis = q.getAxis()
		avatar_el.setAttribute("rotation", str(angle) + " " + str(axis))
		
		events = Piavca.getEvents(avatar)
		for event in events:
			el = doc.createElement("Event")
			el.setAttribute("name", event)
			avatar_el.appendChild(el)
			
		element.appendChild(avatar_el)
	
	for motion in motions:
		motiontype = None
		motiontypes = []
		motiontypename = "unknown"
		for key in allPiavca.keys():
			if type(allPiavca[key]) == types.TypeType and isinstance(motion, allPiavca[key]):
				motiontypes.append(allPiavca[key])
				if motiontype == None or issubclass(allPiavca[key], motiontype):
					motiontype = allPiavca[key]
					motiontypename = key
		#print name, "is a", motiontypename
		if motiontype == None:
			print "Motion is of unknown type"
			continue
		if motiontype == Piavca.KeyframeMotion:
			print "don't save keyframe motions"
			continue
		#print motion.getName(), motiontypename
		el = doc.createElement(motiontypename)
		#el.setAttribute("name", name)
		#print motion.__dict__
		ignorelist = set(["getStartTime", "getMotion", "getMotion1", "getMotion2"])
		for mtype in motiontypes:
			for key in mtype.__dict__.keys():
				if key[:3] == "get":
					#print key
					if key in ignorelist:
						continue
					if hasattr(motion, "set" + key[3:]):
						#print key
						method = getattr(motion, key)
						value = method()
						if type(value) == Piavca.Quat:
							value = str(Piavca.radToDeg(value.getAngle())) + " " + str(value.getAxis())
						else:
							value = str(value)
						if key[-len("JointId"):] == "JointId" or key[-len("ExpressionId"):] == "ExpressionId" or key[-len("TrackId"):] == "TrackId":
							value = Piavca.Core.getCore().getTrackName(method())
							
						# don't save empty names, it screws things up
						if key[3:] != "Name" or value != "":
							# check if its  a quaternion
							
							el.setAttribute(key[3:], value)
		motionlist = []
		if hasattr(motion, "getNumMotions"):
			n = motion.getNumMotions()
			for i in range(n):
				m = motion.getMotionByIndex(i)
				if m == None:
					continue
				m = Piavca.getRealMotionType(m)
				motionlist.append(m)
		elif hasattr(motion, "getMotion1"):
			m = motion.getMotion1()
			if m != None:
				m = Piavca.getRealMotionType(m)
				motionlist.append(m)
			m = motion.getMotion2()
			if m != None:
				m = Piavca.getRealMotionType(m)
				motionlist.append(m)
		elif hasattr(motion, "getMotion"):
			m = motion.getMotion()
			if m != None:
				m = Piavca.getRealMotionType(m)
				motionlist.append(m)
				
		for m in motionlist:
			if m.getName() != "":
				sub_el = doc.createElement("Motion")
				sub_el.setAttribute("name", m.getName())
				el.appendChild(sub_el)
			else:
				saveMotions(filename, [m], el, doc)
				
		element.appendChild(el)
		
	file = open(filename, "w")
	doc.writexml(file, "", "\t", "\n")
	file.close()
예제 #44
0
	def __call__(self, avatar):
		mot = Piavca.getMotion(self.motionName)
		if mot == None:
			raise "could not find motion " + self.motionName
		avatar.add_background_motion(mot)
예제 #45
0
	def getTime(self):
		return Piavca.getTime()
예제 #46
0
def ValueListToQuat(valuelist):
	quat = [float(x) for x in valuelist]
	quat = Piavca.Quat(Piavca.degToRad(quat[0]), Piavca.Vec(quat[1], quat[2], quat[3]))
	return quat
예제 #47
0
	def setValue(self, val):
		angle = Piavca.radToDeg(val.getAngle())
		axis = val.getAxis()
		MultiParamEntry.setValue(self, [angle, axis[0], axis[1], axis[2]])
예제 #48
0
def quatPose(mot, t):
	print [j for j in Piavca.joints(mot)]
예제 #49
0
#
#  MotionIterators.py
#  piavca
#
#  Created by Marco Gillies on 03/02/2010.
#  Copyright (c) 2010 __MyCompanyName__. All rights reserved.
#

import Piavca

def quatPose(mot, t):
	print [j for j in Piavca.joints(mot)]
	pose = [mot.getQuatValueAtTime(j,t) for j in  Piavca.joints(mot) if mot.getTrackType(j) & Piavca.QUAT_TYPE]
	print pose
	return pose

def MotionIterator(mot, fps = 20, posefunc = quatPose):
	return (posefunc(mot, float(t)/fps) for t in range(0, int(mot.getMotionLength()*fps)))
	
	#increment = 1.0/fps
	#currentTime = 0.0
	#while(currentTime < mot.getMotionLength())
	#	yield posefunc(mot, currentTime)
	#	currentTime += increment
		
def MotionList(mot, fps = 20, posefunc = quatPose):
	return [p for p in MotionIterator(mot, fps, posefunc)]
예제 #50
0
	def __init__(self, name, filename, app = None, gui_thread=False):
		Piavca.TimeCallback.__init__(self, name)
		self.app = app
		self.gui_thread = gui_thread
		self.frame = None
	
		self.camera_pos = Piavca.Vec()
		self.camera_pitch = 0.0
		self.camera_yaw = 0.0
	
		loadDefaults()
		
		self.scripts = {}
		self.currentscript = {}
		self.starttimes = {}
		
		if pymediapresent or pyaudiopresent:
			self.soundEngine = SoundEngine()
		else:
			self.soundEngine = None
			
		inputfile = open(filename, "r")
		lines = inputfile.readlines()
		inputfile.close()
		gui_list = []
		for line in lines:
			line = line.strip()
			commentpos = line.find("#")
			if commentpos >= 0:
				line = line[:commentpos]
			line = line.split()
			print line
			if len(line) <= 0:
				continue
			if line[0] == "soundpack":
				if len(line) == 2:
					spackname = line[1]
				else:
					spackname = line[2]
				if self.soundEngine != None:
					self.soundEngine.loadSounds(spackname)
				else:
					print "could not load sound packs as audio playback is not supported, please install pyaudio or pymedia"
			elif line[0] == "expressions":
				importExpressionNames(line[1])
			elif line[0] == "joints":
				importJointNames(line[1])
			elif line[0] == "avatar":
				print "avatar", line[1]
				print "start loading avatar"
				avatar = Piavca.Avatar(line[1])
				print "finished loading avatar"
				i = 2
				while i < len(line):
					if line[i] == "position" or line[i] == "pos":
						pos = Piavca.Vec(float(line[i+1]), float(line[i+2]), float(line[i+3]))
						avatar.setRootPosition(pos)
						i = i+3
					elif line[i] == "rotation" or line[i] == "rot":
						angle = Piavca.degToRad(float(line[i+1]))
						axis = Piavca.Vec(float(line[i+2]), float(line[i+3]), float(line[i+4]))
						avatar.setRootOrientation(Piavca.Quat(angle, axis))
						i = i+4
					i += 1
			elif line[0] == "motionpack":
				if len(line) == 2:
					mpackname = line[1]
				else:
					mpackname = line[2]
				print "motionpack", mpackname
				MotionFile.readMotionFile(mpackname)
			elif line[0] == "script":
				if len(line) == 2:
					spackname = line[1]
				else:
					spackname = line[2]
				print "script pack", spackname
				self.loadScripts(spackname)
			elif line[0] == "camera":
				if line[1] == "position":
					self.camera_pos = Piavca.Vec(float(line[2]), float(line[3]), float(line[4]))
				elif line[1] == "vert_angle":
					self.camera_pitch = Piavca.degToRad(float(line[2]))
				elif line[1] == "horiz_angle":
					self.camera_yaw = Piavca.degToRad(float(line[2]))
				#elif line[1] == "rotation":
				#       s            	self.camera_ori = Piavca.Quat(float(line[2]), Piavca.Vec(float(line[3], float(line[4], lfloat(ine[5]))
			elif line[0] == "GUI":
				print "gui"
				gui_list.append(line[1])
			elif line[0] == "gui":
				print "gui"
				gui_list.append(line[1])
				
		for gui_name in gui_list:
			self.GUI(gui_name)
				
		self.thisown = 0
		Piavca.Core.getCore().registerCallback(self)
예제 #51
0
	def addEvent(self, eventName):
		Piavca.addEvents(self.getAvatar(), [eventName])