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
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()
def getValue(self): try: val = [float(self.texts[i].GetValue()) for i in range(self.dim)] val = Piavca.Vec(val[0], val[1], val[2]) return val except ValueError: return None self.texts[i].SetValue(str(val[i]))
def __init__(self, mot=None, footplants=None): if mot != None: Piavca.MotionFilter.__init__(self, mot) else: Piavca.MotionFilter.__init__(self) self.__disown__() self.noChanges = False self.setFootPlants(footplants) self.rootPos = Piavca.Vec()
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
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 = []
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()
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
def __init__(self, currentValMot=None): if currentValMot != None: Piavca.CurrentValueMotion.__init__(self, currentValMot) else: Piavca.CurrentValueMotion.__init__(self) self.setVecValue(Piavca.root_position_id, Piavca.Vec()) self.loadToCanvas() self.radius = 10.0 self.sensetivity = 1.0 self.prevX = None self.prevY = None self.__disown__()
def __init__(self, p): self.coordAxes = 4 * [Piavca.Quat()] if type(p) == type(Piavca.Quat()): self._calcCoordAxes(p) return q = Piavca.Quat(0.0, 0.0, 0.0, 0.0) for val in p: if (val[0] < 0.0): val = Piavca.Quat(-val[0], -val[1], -val[2], -val[3]) q[0] += val[0] / len(p) q[1] += val[1] / len(p) q[2] += val[2] / len(p) q[3] += val[3] / len(p) q.normalise() u = Piavca.Vec(0.0, 0.0, 0.0) count = 0 while 1: if count > 500: print "error", u, u.mag() if u.mag() < 0.001: break raise "exceeded maximum iterations" count += 1 self._calcCoordAxes(q) u = Piavca.Vec() for val in p: val = self.logMap(val) u += val / len(p) q = self.expMap(u) #print "curent iter", u, q if u.mag() < 0.0005: break self._calcCoordAxes(q)
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
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)
def updateCameraPosition(self): avatar = self.avatar # Piavca.Core.getCore().getAvatar(0) if avatar: #self.initialAvatarBound = avatar.getBaseBoundBox() #self.initialAvatarRoot = avatar.getRootPosition() self.focusRoot = avatar.getRootPosition() self.focusBound = avatar.getBaseBoundBox(); else: #self.initialAvatarBound = Piavca.Bound() #self.initialAvatarRoot = Piavca.Vec() self.focusRoot = Piavca.Vec() self.focusBound = Piavca.Bound() # print "initialAvatarRoot", self.initialAvatarRoot # print "initialAvatarBound", self.initialAvatarBound # print "focusRoot", self.focusRoot # print "focusBound", self.focusBound self.focusBound.min = self.initialAvatarBound.min+self.focusRoot-self.initialAvatarRoot; self.focusBound.max = self.initialAvatarBound.max+self.focusRoot-self.initialAvatarRoot;
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)
import time import Piavca #Piavca.PiavcaGlut.init(Piavca.Core.getCorePointerAsLong()) import Piavca.JointNames Piavca.JointNames.loadDefaults() import Piavca.FreeCameraCanvas import wx from wx.lib.dialogs import * from wx import glcanvas app = Piavca.getWXApp() canvas = app.showWindows(canvastype=Piavca.FreeCameraCanvas.FreeCameraCanvas) canvas.setPosition(Piavca.Vec(0.0, 100, 33)) canvas.setPitch(Piavca.degToRad(-90.0)) app.getCanvas().setClearColour(1.0, 1.0, 1.0) if len(sys.argv) > 1: path = sys.argv[1] else: dialog_return = openFileDialog() path = dialog_return.paths[0] dirname = os.path.dirname(path) os.chdir(dirname) try: Piavca.JointNames.importJointNames("Joints.txt")
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
def ValueListToVec(valuelist): vec = [float(x) for x in valuelist] vec = Piavca.Vec(vec[0], vec[1], vec[2]) return vec
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))
def setFilename(self, filename): print "#########################################################" print "set filename", filename self.filename = filename if self.filename == "": return dom = minidom.parse(filename) #mot = Piavca.KeyframeMotion() print "reading", filename for topLevel in dom.childNodes: for mainelement in topLevel.childNodes: if mainelement.nodeName == "SceneInfo": startTick = mainelement.getAttribute("startTick") try: self.startTick = float(startTick) except ValueError: pass fps = 30.0 try: fps = float(mainelement.getAttribute("frameRate")) except ValueError: pass ticksPerFrame = 160.0 try: ticksPerFrame = float( mainelement.getAttribute("ticksPerFrame")) except ValueError: pass self.tickrate = fps * ticksPerFrame if mainelement.nodeName == "Node": for nodechild in mainelement.childNodes: print nodechild.nodeName if nodechild.nodeName == "Controller": nm = nodechild.getAttribute("name") print nm nm_elements = nm.split() track = Piavca.Core.getCore().nullId for el in nm_elements: print el, Piavca.Core.getCore().getTrackId(el) track = Piavca.Core.getCore().getTrackId(el) if track != Piavca.Core.getCore().nullId: break if track != Piavca.Core.getCore().nullId: print "found track", el, track keyframes = [] for keyset in nodechild.childNodes: print keyset.nodeName if keyset.nodeName == "Keys" or keyset.nodeName == "Samples": for key in keyset.childNodes: if key.nodeName == "Key": t = key.getAttribute("t") try: t = float(t) except ValueError: continue v = key.getAttribute("v") #try: # v = float(t) #except ValueError: # continue keyframes.append((t, v)) print keyframes v = keyframes[0][1] v = str(v) v = v.strip() v = v.split() print v if len(v) == 1: print "scalar", v try: v = float(v[0]) print "float", v self.addFloatTrack(track, v) for t, v in keyframes: print t, v v = str(v) v = v.strip() v = float(v) v = v / 100.0 t = t / self.tickrate print track, t, v self.setFloatKeyframe( track, t, v) except ValueError: continue elif len(v) == 3: try: print "vector", v v = Piavca.Vec( float(v[0]), float(v[1]), float(v[2])) self.addVecTrack(track, v) for t, v in keyframes: t = t / self.tickrate v = Piavca.Vec( float(v[0]), float(v[1]), float(v[2])) self.setVecKeyframe( track, t, v) except: continue elif len(v) == 4: try: print "quat", v v = Piavca.Quat( float(v[0]), float(v[1]), float(v[2])) self.addQuatTrack(track, v) for t, v in keyframes: t = t / self.tickrate v = Piavca.Quat( float(v[3]), float(v[0]), float(v[1]), float(v[2])) self.setQuattKeyframe( track, t, v) except: continue #Piavca.loadMotion(name, mot) #impl = minidom.getDOMImplementation() #doc = impl.createDocument("", "PiavcaMotions", None) #f = open(filename, "w") #dom.writexml(f, "", "\t", "\n") dom.unlink
def InterruptableSequence(seq, interruptions, fps=20, threshold=6.5, window=0.5): 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(seq): # 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 seq.isNull(j): continue joint_type = seq.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): continue extremeFrames = [] for m in interruptions: if m.isNull(j): continue if not (m.getTrackType(j) & t): continue start_time = m.getStartTime() extremeFrames.append(Piavca.getValAtTime(m, j, start_time, t)) end_time = m.getEndTime() extremeFrames.append(Piavca.getValAtTime(m, j, end_time, t)) if len(extremeFrames) == 0: expmaps[(j, t)] = None elif t == Piavca.QUAT_TYPE: expmaps[(j, t)] = Piavca.ExpMap.TangentSpace(extremeFrames) elif t == Piavca.VEC_TYPE: expmaps[(j, t)] = sum(extremeFrames, Piavca.Vec()) / float( len(extremeFrames)) else: print len(extremeFrames), extremeFrames expmaps[(j, t)] = sum(extremeFrames) / float(len(extremeFrames)) 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 = [seq.getStartTime()] values = [] #print "start time", seq.getStartTime(), "end time", seq.getEndTime() for i in range(int(seq.getStartTime() * fps), int(seq.getEndTime() * fps) - 1): d_plus = calculateDistance(seq, float(i + 1) / fps, expmaps) print d, d_plus, threshold if d: if d < d_plus: if d_minus != None and d < d_minus: print float(i) / fps, d, d_plus, threshold, 4.0 * window if d < threshold: if len(minima) == 0 or (float(i) / fps - minima[-1]) > 4.0 * window: values.append(d) minima.append(float(i) / fps) d_minus = d d = d_plus minima.append(seq.getEndTime()) values.sort(reverse=False) print "values", values print "minima", minima numMinima = len(minima) # create the motions # a submotion for each transition point # a sequential choice motion that plays the original motion # a choice motion with default that allows us to interrupt # and finally loop in all # we add "window" to the end time so that it works with # the smooth transitioning function submots = [ Piavca.SubMotion(seq, start, end) for start, end in zip(minima[:-1], minima[1:]) ] print submots choice1 = Piavca.SequentialChoiceMotion() choice1.setSmooth(False) choice1.setAccumulateRoot(False) choice1.setWindowLength(window) for mot in submots: print mot choice1.addMotion(mot) loop1 = Piavca.LoopMotion(choice1) choice2 = Piavca.ChoiceMotionWithDefault() choice2.setWindowLength(window) choice2.addMotion(loop1) for mot in interruptions: print mot choice2.addMotion(mot) loop2 = Piavca.LoopMotion(choice2) return loop2, numMinima