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
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 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 __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 __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 _cross(self, q1, q2, q3): q = Piavca.Quat() q[0] = q1[1] * (q2[2] * q3[3] - q2[3] * q3[2]) q[0] -= q1[2] * (q2[1] * q3[3] - q2[3] * q3[1]) q[0] += q1[3] * (q2[1] * q3[2] - q2[2] * q3[1]) q[1] = -q1[0] * (q2[2] * q3[3] - q2[3] * q3[2]) q[1] += q1[2] * (q2[0] * q3[3] - q2[3] * q3[0]) q[1] -= q1[3] * (q2[0] * q3[2] - q2[2] * q3[0]) q[2] = q1[0] * (q2[1] * q3[3] - q2[3] * q3[1]) q[2] -= q1[1] * (q2[0] * q3[3] - q2[3] * q3[0]) q[2] += q1[3] * (q2[1] * q3[0] - q2[0] * q3[1]) q[3] = -q1[0] * (q2[1] * q3[2] - q2[2] * q3[1]) q[3] += q1[1] * (q2[0] * q3[2] - q2[2] * q3[0]) q[3] -= q1[2] * (q2[0] * q3[1] - q2[1] * q3[0]) return q
def _calcCoordAxes(self, q): self.coordAxes[0] = q if (fabs(q[0]) < 0.0001 and fabs(q[1]) < 0.0001): self.coordAxes[1] = Piavca.Quat(1.0, 0.0, 0.0, 0.0) self.coordAxes[2] = Piavca.Quat(0.0, 1.0, 0.0, 0.0) self.coordAxes[3] = Piavca.Quat(0.0, 0.0, q[3], -q[2]) self.coordAxes[3].normalise() return if (fabs(q[2]) < 0.0001 and fabs(q[3]) < 0.0001): self.coordAxes[1] = Piavca.Quat(q[1], -q[0], 0.0, 0.0) self.coordAxes[1].normalise() self.coordAxes[2] = Piavca.Quat(0.0, 0.0, 1.0, 0.0) self.coordAxes[3] = Piavca.Quat(0.0, 0.0, 0.0, 1.0) return self.coordAxes[1] = Piavca.Quat(q[1], -q[0], 0.0, 0.0) self.coordAxes[1].normalise() self.coordAxes[2] = Piavca.Quat(0.0, 0.0, q[3], -q[2]) self.coordAxes[2].normalise() self.coordAxes[3] = self._cross(self.coordAxes[0], self.coordAxes[1], self.coordAxes[2]) self.coordAxes[3].normalise()
def preFrame(self, time): if self.noChanges: return #print "Footplants, preFrame" Piavca.MotionFilter.preFrame(self, time) #print "Footplants, preFrame" if self.plantedFoot == None: #print "no planted foot" return av = self.getAvatar() ori = av.getRootOrientation() pos = av.getRootPosition() #print "old ori", ori, "old pos", pos pos = av.getJointBasePosition(self.plantedFoot, Piavca.WORLD_COORD) #print time, "old foot pos", pos, self.plantPos, self self.noChanges = True #print "no changes", self.noChanges #print "self", self av.showMotionAtTime(time, None, 0) #av.showMotionAtTime(time, self.getMotion(),0) ori = av.getJointOrientation(self.plantedFoot, Piavca.WORLD_COORD) pos = av.getJointBasePosition(self.plantedFoot, Piavca.WORLD_COORD) self.noChanges = False #print "rootpos", av.getRootPosition() #print "current pos, ori", pos, ori #print "jointlocal", av.getJointOrientation(self.plantedFoot, Piavca.JOINTLOCAL_COORD), av.getJointOrientation(self.plantedFoot, Piavca.JOINTLOCAL_COORD) #print "world", av.getJointOrientation(self.plantedFoot, Piavca.WORLD_COORD), av.getJointOrientation(self.plantedFoot, Piavca.WORLD_COORD) #if abs(ori[0]+ori[1]+ori[2]+ori[3]) < 0.0001: # asdf #self.rootOri = self.plantOri * ori.inverse() self.rootOri = Piavca.Quat() #self.plantOri * ori.inverse() #print "plant ori", self.plantOri, "current ori", ori #print "plant pos", self.plantPos, " current pos ", self.rootOri.transform(pos) #self.rootPos = self.plantPos - self.rootOri.transform(pos) self.rootPos = self.plantPos - pos
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 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 load_FileObject(self, f): lines = f.readlines() data_portion = 0 i = 0 pcs = None for line in lines : if not data_portion : contents = string.split(line, ":") #print contents if contents[0] == "Num Pcs": self.num_pcs = int(contents[1]) #print self.num_pcs if contents[0] == "Use Vels": self.use_vels = bool(contents[1]) #print self.use_vels #if contents[0] == "Using Splits": # self.using_splits = int(contents[1]) # print self.using_splits if contents[0] == "Exp Maps": #print "expmaps" self.expmaps = [] #print "expmaps" number_pattern = re.compile("-?((([0-9]+)|([0-9]*\.[0-9]+))([eE][-+]?[0-9]+)?)") #print "expmaps" quat_pattern = re.compile("\[[^\]]*\]") #print "created regexp" matches = quat_pattern.findall(contents[1]) #print "got matches" for match in matches : #print "match" numbers = string.split(match[1:-1]) #print numbers q = Piavca.Quat(float(numbers[0]), float(numbers[1]), float(numbers[2]), float(numbers[3])) #print q self.expmaps.append(Piavca.ExpMap.TangentSpace(q)) #print matches if contents[0] == "Joint Types": self.joint_types = [] numbers = string.split(contents[1]) for number in numbers: self.joint_types.append(int(number)) if contents[0] == "Joint Map": self.jointmap = [] numbers = string.split(contents[1]) for number in numbers: if number == "None": self.jointmap.append(None) else: self.jointmap.append(int(number)) if contents[0] == "Quants": self.quants = [] quants = string.split(contents[1], ";") for quant in quants: if quant == "": continue if quant == "\n": continue q = [] numbers = string.split(quant) for number in numbers: if number == "": continue q.append(float(number)) if q != []: self.quants.append(q) #print self.quants self.quants = scipy.array(self.quants) if contents[0] == "length": pcs = scipy.zeros((int(contents[1]), self.num_pcs),'d') if(contents[0] == "data"): data_portion = 1 else: numbers = string.split(line) if numbers == [] : continue #print len(numbers) for j in range(len(numbers)): pcs[j][i] = float(numbers[j]) i += 1 #print self.pcs if pcs == None: return else: self.pcs = pcs self.weights = scipy.zeros((self.num_pcs,),'d') self.generateMotion()
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 __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)
def calcRotation(self): self.cameraRot = Piavca.Quat(self.cameraPitch, Piavca.Vec_XAxis()) self.cameraRot = Piavca.Quat(self.cameraYaw, Piavca.Vec_YAxis()) * self.cameraRot