def InitalizeAnimSet(animSet,makeVisibleChannel = True): shot = sfm.GetCurrentShot() channelsClip = sfmUtils.GetChannelsClipForAnimSet(animSet, shot) visibleChannel = None if makeVisibleChannel: # Ensure additional channels: visibleChannel = FindChannel(channelsClip.channels,'visible_channel') if visibleChannel is None: visibleChannel = sfmUtils.CreateControlAndChannel('visible', vs.AT_BOOL, False, animSet, shot).channel visibleChannel.mode = 3 visibleChannel.fromElement = animSet.gameModel visibleChannel.fromAttribute = 'visible' visibleChannel.toElement = animSet.gameModel visibleChannel.toAttribute = 'visible' # clear channel logs: for chan in channelsClip.channels: chan.ClearLog() if visibleChannel: # Not visible initially: visibleChannel.log.SetKey(-channelsClip.timeFrame.start.GetValue(), False)
def GetChannel(self,animSet,channelName): key = animSet.GetName() + channelName value = self.dict.get(key, False) if False == value: channelsClip = sfmUtils.GetChannelsClipForAnimSet(animSet, sfm.GetCurrentShot()) value = FindChannel(channelsClip.channels, channelName) self.dict[key] = value return value
def writeToGroup(self, group): animset = sfm.GetCurrentAnimationSet() shot = sfm.GetCurrentShot() rootDag = sfmUtils.FindFirstDag([ "RootTransform", "rootTransform", "roottransform", "Roottransform" ]) suffix = self.createSuffix(self.target) groupAddStringAttribute(group, name_targetname, self.target) group.SetValue(name_boxsize, self.boxsize) group.SetValue(name_boxcenter, self.boxcenter) group.SetValue(name_margin, float(self.margin)) group.SetValue(name_mass, float(self.mass)) self.handle = sfm.CreateRigHandle(name_handle + suffix, group=group.GetName()) #position the handle at the box center bonedag = sfm.FindDag(self.target) CenterTransform = PosQuatToTransform(self.boxcenter, vs.Quaternion(0, 0, 0, 1)) ResultTransform = vs.matrix3x4_t() vs.ConcatTransforms(bonedag.GetAbsTransform(), CenterTransform, ResultTransform) self.handle.SetAbsTransform(ResultTransform) sfmUtils.Parent(self.handle, rootDag) sfm.ParentConstraint(name_handle + suffix, self.target, mo=True) self.force = sfm.CreateRigHandle(name_force + suffix, group=group.GetName()) self.force.SetAbsTransform(self.handle.GetAbsTransform()) sfmUtils.Parent(self.force, self.handle) shapeval = 0 if self.shape == "sphere": shapeval = 1 groupCreateControlledValue(group, name_shape + suffix, shapeval, animset, shot) kineval = 0 if self.mass == 0: kineval = 1 groupCreateControlledValue(group, name_kinematic + suffix, kineval, animset, shot) groupCreateControlledValue(group, name_bounce + suffix, self.bounce, animset, shot) groupCreateControlledValue(group, name_friction + suffix, self.friction, animset, shot) groupCreateControlledValue(group, name_lindamp + suffix, self.lindamp, animset, shot) groupCreateControlledValue(group, name_rotdamp + suffix, self.rotdamp, animset, shot)
def writeToGroup(self, group): animset = sfm.GetCurrentAnimationSet() shot = sfm.GetCurrentShot() suffix = self.createSuffix(animset.GetName(), self.boneprefix) attrNodelist = group.AddAttribute(name_nodelist, vs.AT_ELEMENT_ARRAY) attrLinklist = group.AddAttribute(name_linklist, vs.AT_ELEMENT_ARRAY) attrFacelist = group.AddAttribute(name_facelist, vs.AT_ELEMENT_ARRAY) counter = 0 for bone in self.nodelist: temp = vs.CreateElement("Bone " + str(counter), group.GetFileId()) temp.AddAttribute(name_nodename, vs.AT_STRING).SetValue(bone[0]) temp.SetValue(name_nodemass, bone[1]) attrNodelist.append(temp) counter += 1 #end counter = 0 for link in self.linklist: temp = vs.CreateElement("Link " + str(counter), group.GetFileId()) temp.SetValue("a", link[0]) temp.SetValue("b", link[1]) attrLinklist.append(temp) counter += 1 #end counter = 0 for face in self.facelist: temp = vs.CreateElement("Link " + str(counter), group.GetFileId()) temp.SetValue("a", face[0]) temp.SetValue("b", face[1]) temp.SetValue("c", face[2]) temp.SetValue("d", face[3]) attrFacelist.append(temp) counter += 1 #end groupAddStringAttribute(group, name_boneprefix, self.boneprefix) group.SetValue(name_margin, float(self.margin)) group.SetValue(name_mass, float(self.mass)) groupCreateControlledValue(group, name_stretch + suffix, self.stretch, animset, shot) groupCreateControlledValue(group, name_shear + suffix, self.shear, animset, shot) groupCreateControlledValue(group, name_bend + suffix, self.bend, animset, shot) groupCreateControlledValue(group, name_lindamp + suffix, self.damp, animset, shot) groupCreateControlledValue(group, name_friction + suffix, self.friction, animset, shot)
def readFromGroup(self, group, time): animset = group.FindAnimationSet(True) shot = sfm.GetCurrentShot() self.boneprefix = group.GetValue(name_boneprefix) suffix = self.createSuffix(animset.GetName(), self.boneprefix) self.daglist = list() for bone in group.GetValue(name_nodelist): dag = sfm.FindDag(animset.GetName() + ":" + bone.GetValue(name_nodename)) pos, quat = TransformToPosQuat(GetAbsTransformAtTime(dag, time)) self.nodelist.append((bone.GetValue(name_nodename), bone.GetValue(name_nodemass), pos)) self.daglist.append(dag) #end for link in group.GetValue(name_linklist): self.linklist.append((link.GetValue("a"), link.GetValue("b"))) #end for face in group.GetValue(name_facelist): self.facelist.append((face.GetValue("a"), face.GetValue("b"), face.GetValue("c"), face.GetValue("d"))) #end self.margin = group.GetValue(name_margin) self.mass = group.GetValue(name_mass) self.stretch = groupGetControlledValueAtTime(group, name_stretch + suffix, time) self.shear = groupGetControlledValueAtTime(group, name_shear + suffix, time) self.bend = groupGetControlledValueAtTime(group, name_bend + suffix, time) self.damp = groupGetControlledValueAtTime(group, name_lindamp + suffix, time) self.friction = groupGetControlledValueAtTime(group, name_friction + suffix, time) #end #end
def welcome(self): shot = sfm.GetCurrentShot() print(shot) self.setupUi(self) if (shot == None): shotError = QtGui.QMessageBox() shotError.setText( "Couldn't get current shot. Make sure you run this script from the \"Rig\" menu of an animation set." ) shotError.setIcon(QtGui.QMessageBox.Critical) shotError.setWindowTitle('Uh...') shotError.exec_() self.close() return for shotAttribute in shot.iterAttrs(): if shotAttribute.GetName() == "animationSets": for animSet in shotAttribute: AnimSets.append(animSet) break if AnimSets is None: setAnimSet = QtGui.QMessageBox() setAnimSet.setText("There is not any Animation Set in the scene!") setAnimSet.setIcon(QtGui.QMessageBox.Critical) setAnimSet.setWindowTitle('Uh...') setAnimSet.exec_() self.close() return sfm.SetCurrentFrame(0) print(shot) print(AnimSets) for AnimSet in AnimSets: self.animSetComboBox.addItem(str(AnimSet.name)) self.pushButton.clicked.connect(self.Close) self.pushButton_2.clicked.connect(self.ControlSelection) self.show()
def writeToGroup(self, group): animset = sfm.GetCurrentAnimationSet() shot = sfm.GetCurrentShot() rootDag = sfmUtils.FindFirstDag([ "RootTransform", "rootTransform", "roottransform", "Roottransform" ]) suffix = self.createSuffix(self.constype, self.bodya, self.bodyb) groupAddStringAttribute(group, name_typename, self.constype) groupAddStringAttribute(group, name_bodya, self.bodya) groupAddStringAttribute(group, name_bodyb, self.bodyb) self.handle = sfm.CreateRigHandle(name_handle + suffix, group=group.GetName()) #position the handle at bodya plus some offset daga = sfm.FindDag(self.bodya) dagb = sfm.FindDag(self.bodyb) ResultTransform = vs.matrix3x4_t() if (self.pos is None): #placing pos at the same spot as bodyb is usually a good guess ResultTransform = PosQuatToTransform(dagb.GetAbsPosition(), daga.GetAbsOrientation()) else: OffsetTransform = PosQuatToTransform(self.pos, vs.Quaternion(0, 0, 0, 1)) vs.ConcatTransforms(daga.GetAbsTransform(), OffsetTransform, ResultTransform) #end self.handle.SetAbsTransform(ResultTransform) sfmUtils.Parent(self.handle, daga) if (self.constype == "cone"): groupCreateControlledValue(group, name_rotx + suffix, self.rotx / 180.0, animset, shot) groupCreateControlledValue(group, name_roty + suffix, self.roty / 180.0, animset, shot) groupCreateControlledValue(group, name_twist + suffix, self.twist / 180.0, animset, shot)
def ReadFile(fileName): file = None try: file = open(fileName, 'rb') if file is None: self.error('Could not open file.') return False version = ReadAgrVersion(file) if version is None: SetError('Invalid file format.') return False if 5 != version: SetError('Version '+str(version)+' is not supported!') return False shot = sfm.GetCurrentShot() timeConverter = AgrTimeConverter() dict = AgrDictionary() handleToLastModelHandle = {} unusedModelHandles = [] channelCache = ChannelCache() afxCam = None stupidCount = 0 objNr = 0 while True: stupidCount = stupidCount +1 if 4096 <= stupidCount: stupidCount = 0 gc.collect() #break #reply = QtGui.QMessageBox.question(None, 'Message', 'Imported another 4096 packets - Continue?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) #if reply == QtGui.QMessageBox.No: # break node0 = dict.Read(file) if node0 is None: break elif 'afxFrame' == node0: time = ReadFloat(file) timeConverter.Frame(time) afxHiddenOffset = ReadInt(file) if afxHiddenOffset: curOffset = file.tell() file.seek(afxHiddenOffset -4, 1) numHidden = ReadInt(file) for i in range(numHidden): handle = ReadInt(file) modelHandle = handleToLastModelHandle.pop(handle, None) if modelHandle is not None: dagAnimSet = modelHandle.modelData if dagAnimSet: # Make ent invisible: MakeKeyFrameValue(channelCache, dagAnimSet, 'visible_channel', timeConverter.GetTime(sfmUtils.GetChannelsClipForAnimSet(dagAnimSet, shot)), False) unusedModelHandles.append(modelHandle) #print("Marking %i (%s) as hidden/reusable." % (modelHandle.objNr,modelHandle.modelName)) file.seek(curOffset,0) elif 'afxFrameEnd' == node0: timeConverter.FrameEnd() elif 'afxHidden' == node0: # skipped, because will be handled earlier by afxHiddenOffset numHidden = ReadInt(file) for i in range(numHidden): handle = ReadInt(file) elif 'deleted' == node0: handle = ReadInt(file) modelHandle = handleToLastModelHandle.pop(handle, None) if modelHandle is not None: dagAnimSet = modelHandle.modelData if dagAnimSet: # Make removed ent invisible: MakeKeyFrameValue(channelCache, dagAnimSet, 'visible_channel', timeConverter.GetTime(sfmUtils.GetChannelsClipForAnimSet(dagAnimSet, shot)), False) unusedModelHandles.append(modelHandle) print("Marking %i (%s) as hidden/reusable." % (modelHandle.objNr,modelHandle.modelName)) elif 'entity_state' == node0: visible = None dagAnimSet = None handle = ReadInt(file) if dict.Peekaboo(file,'baseentity'): modelName = dict.Read(file) visible = ReadBool(file) renderOrigin = ReadVector(file) renderAngles = ReadQAngle(file) modelHandle = handleToLastModelHandle.get(handle, None) if (modelHandle is not None) and (modelHandle.modelName != modelName): # Switched model, make old model invisible: dagAnimSet = modelHandle.modelData if dagAnimSet: MakeKeyFrameValue(channelCache, dagAnimSet, 'visible_channel', timeConverter.GetTime(sfmUtils.GetChannelsClipForAnimSet(dagAnimSet, shot)), False) modelHandle = None if modelHandle is None: # Check if we can reuse s.th. and if not create new one: bestIndex = 0 bestLength = 0 for idx,val in enumerate(unusedModelHandles): if (val.modelName == modelName) and ((modelHandle is None) or (modelHandle.modelData and (modelHandle.lastRenderOrigin is not None) and ((modelHandle.lastRenderOrigin -renderOrigin).Length() < bestLength))): modelHandle = val bestLength = (modelHandle.lastRenderOrigin -renderOrigin).Length() bestIndex = idx if modelHandle is not None: # Use the one we found: del unusedModelHandles[bestIndex] print("Reusing %i (%s)." % (modelHandle.objNr,modelHandle.modelName)) else: # If not then create a new one: objNr = objNr + 1 modelHandle = ModelHandle(objNr, modelName) print("Creating %i (%s)." % (modelHandle.objNr,modelHandle.modelName)) handleToLastModelHandle[handle] = modelHandle dagAnimSet = modelHandle.modelData if dagAnimSet is False: # We have not tried to import the model for this (new) handle yet, so try to import it: dagName = modelName.rsplit('/',1) dagName = dagName[len(dagName) -1] dagName = (dagName[:60] + '..') if len(dagName) > 60 else dagName dagName = "afx." +str(modelHandle.objNr)+ " " + dagName dagAnimSet = sfmUtils.CreateModelAnimationSet(dagName,modelName) if(hasattr(dagAnimSet,'gameModel')): dagAnimSet.gameModel.evaluateProceduralBones = False # This will look awkwardly and crash SFM otherwise print "Initalizing animSet " + dagName InitalizeAnimSet(dagAnimSet) modelHandle.modelData = dagAnimSet modelHandle.lastRenderOrigin = renderOrigin MakeKeyFrameValue(channelCache, dagAnimSet, 'visible_channel', timeConverter.GetTime(sfmUtils.GetChannelsClipForAnimSet(dagAnimSet, shot)), visible) MakeKeyFrameTransform(channelCache, dagAnimSet, "rootTransform", timeConverter.GetTime(sfmUtils.GetChannelsClipForAnimSet(dagAnimSet, shot)), renderOrigin, QuaternionFromQAngle(renderAngles), True) if dict.Peekaboo(file,'baseanimating'): #skin = ReadInt(file) #body = ReadInt(file) #sequence = ReadInt(file) hasBoneList = ReadBool(file) if hasBoneList: dagModel = None if dagAnimSet is not None and hasattr(dagAnimSet,'gameModel'): dagModel = dagAnimSet.gameModel numBones = ReadInt(file) for i in xrange(numBones): vec = ReadVector(file) quat = ReadQuaternion(file) if dagModel is None: continue if(i < len(dagModel.bones)): name = dagModel.bones[i].GetName() #print name name = name[name.find('(')+1:] name = name[:name.find(')')] #print name MakeKeyFrameTransform(channelCache, dagAnimSet, name, timeConverter.GetTime(sfmUtils.GetChannelsClipForAnimSet(dagAnimSet, shot)), vec, quat) if dict.Peekaboo(file,'camera'): thidPerson = ReadBool(file) renderOrigin = ReadVector(file) renderAngles = ReadQAngle(file) fov = ReadFloat(file) fov = fov / 180.0 modelCamera = modelHandle.camera if modelCamera is None: camName = "camera."+str(modelHandle.objNr) dmeAfxCam = vs.CreateElement( "DmeCamera", camName, shot.GetFileId()) modelCamera = sfm.CreateAnimationSet( camName, target=dmeAfxCam) InitalizeAnimSet(modelCamera,makeVisibleChannel=False) channelsClip = sfmUtils.GetChannelsClipForAnimSet(modelCamera, sfm.GetCurrentShot()) scaled_fieldOfView_channel = FindChannel(channelsClip.channels, "scaled_fieldOfView_channel") scaled_fieldOfView_channel.fromElement.lo = 0 scaled_fieldOfView_channel.fromElement.hi = 180 shot.scene.GetChild(shot.scene.FindChild("Cameras")).AddChild(dmeAfxCam) modelHandle.camera = modelCamera MakeKeyFrameValue(channelCache, modelCamera, 'fieldOfView', timeConverter.GetTime(sfmUtils.GetChannelsClipForAnimSet(modelCamera, shot)), fov) MakeKeyFrameTransform(channelCache, modelCamera, 'transform', timeConverter.GetTime(sfmUtils.GetChannelsClipForAnimSet(modelCamera, shot)), renderOrigin, QuaternionFromQAngle(renderAngles), True, '_pos', '_rot') dict.Peekaboo(file,'/') viewModel = ReadBool(file) elif 'afxCam' == node0: if afxCam is None: dmeAfxCam = vs.CreateElement( "DmeCamera", "afxCam", shot.GetFileId()) afxCam = sfm.CreateAnimationSet( "afxCam", target=dmeAfxCam) InitalizeAnimSet(afxCam,makeVisibleChannel=False) channelsClip = sfmUtils.GetChannelsClipForAnimSet(afxCam, sfm.GetCurrentShot()) scaled_fieldOfView_channel = FindChannel(channelsClip.channels, "scaled_fieldOfView_channel") scaled_fieldOfView_channel.fromElement.lo = 0 scaled_fieldOfView_channel.fromElement.hi = 180 shot.scene.GetChild(shot.scene.FindChild("Cameras")).AddChild(dmeAfxCam) renderOrigin = ReadVector(file) renderAngles = ReadQAngle(file) fov = ReadFloat(file) fov = fov / 180.0 MakeKeyFrameValue(channelCache, afxCam, 'fieldOfView', timeConverter.GetTime(sfmUtils.GetChannelsClipForAnimSet(afxCam, shot)), fov) MakeKeyFrameTransform(channelCache, afxCam, 'transform', timeConverter.GetTime(sfmUtils.GetChannelsClipForAnimSet(afxCam, shot)), renderOrigin, QuaternionFromQAngle(renderAngles), True, '_pos', '_rot') else: SetError('Unknown packet: ') return False finally: if file is not None: file.close() return True
def ReadFile(fileName, scale, camFov): shot = sfm.GetCurrentShot() animSet = sfm.GetCurrentAnimationSet() channelsClip = sfmUtils.GetChannelsClipForAnimSet(animSet, shot) if channelsClip == None: SetError("Selected animation set does not have channels clip.") return False rootControlGroup = animSet.GetRootControlGroup() if None == rootControlGroup: SetError("Selected animation set does not have rootControlGroup.") return False transformCtrl = rootControlGroup.FindControlByName("transform", True) if None == transformCtrl: SetError("Selected animation set does not have transform control.") return False positionChan = transformCtrl.GetPositionChannel() orientationChan = transformCtrl.GetOrientationChannel() file = open(fileName, 'rU') rootName = ReadRootName(file) if not rootName: SetError('Failed parsing ROOT.') return False print 'ROOT:', rootName channels = ReadChannels(file) if not channels: SetError('Failed parsing CHANNELS.') return False frames = ReadFrames(file); if frames < 0: SetError('Failed parsing Frames.') return False if 0 == frames: frames = 1 frames = float(frames) frameTime = ReadFrameTime(file) if not frameTime: SetError('Failed parsing Frame Time.') return False timeOffset = (shot.ToChildMediaTime(vs.DmeTime_t(sfmApp.GetHeadTimeInSeconds()),False) -channelsClip.timeFrame.start.GetValue()) # Prepare curves: timeStart = timeOffset timeEnd = vs.DmeTime_t(float(frameTime) * float(frames)) +timeOffset ClearKeys(positionChan.log,timeStart,timeEnd) ClearBookmarks(positionChan.log,0,timeStart,timeEnd) ClearBookmarks(positionChan.log,1,timeStart,timeEnd) ClearBookmarks(positionChan.log,2,timeStart,timeEnd) ClearKeys(orientationChan.log,timeStart,timeEnd) ClearBookmarks(orientationChan.log,0,timeStart,timeEnd) ClearBookmarks(orientationChan.log,1,timeStart,timeEnd) ClearBookmarks(orientationChan.log,2,timeStart,timeEnd) frameCount = float(0) lastQuat = None while True: frame = ReadFrame(file, channels) if not frame: break frameCount += 1 BTT = vs.DmeTime_t(float(frameTime) * float(frameCount-1)) +timeOffset BYP = -frame[0] *scale BZP = frame[1] *scale BXP = -frame[2] *scale BZR = -frame[3] BXR = -frame[4] BYR = frame[5] positionChan.log.SetKey(BTT, vs.Vector(BXP, BYP, BZP)) # positionChan.log.AddBookmark(BTT, 0) # We cannot afford bookmarks (waste of memory) # positionChan.log.AddBookmark(BTT, 1) # We cannot afford bookmarks (waste of memory) # positionChan.log.AddBookmark(BTT, 2) # We cannot afford bookmarks (waste of memory) quat = vs.Quaternion() vs.AngleQuaternion(vs.QAngle(BXR,BYR,BZR), quat) # Make sure we travel the short way: if lastQuat: dp = vs.QuaternionDotProduct(lastQuat,quat) if dp < 0: quat = vs.Quaternion(-quat.x,-quat.y,-quat.z,-quat.w) lastQuat = quat orientationChan.log.SetKey(BTT, quat) # orientationChan.log.AddBookmark(BTT, 0) # We cannot afford bookmarks (waste of memory) # orientationChan.log.AddBookmark(BTT, 1) # We cannot afford bookmarks (waste of memory) # orientationChan.log.AddBookmark(BTT, 2) # We cannot afford bookmarks (waste of memory) if not frameCount == frames: SetError("Frames are missing in BVH file.") return False return True
def WriteFile(fileName, scale): shot = sfm.GetCurrentShot() animSet = sfm.GetCurrentAnimationSet() dag = sfm.FindDag("transform") if dag == None: SetError("Selected animation set does not have transform DAG node.") return False curFrame = 0 fps = sfmApp.GetFramesPerSecond() frameTime = fps if not 0 == frameTime: frameTime = 1.0 / float(frameTime) frameCount = shot.GetDuration().CurrentFrame(vs.DmeFramerate_t(fps)) file = open(fileName, 'wb') if not file: SetError('Could not open file ' + fileName + ' for writing') return False oldFrame = sfm.GetCurrentFrame() try: WriteHeader(file, frameCount, frameTime) while curFrame < frameCount: sfm.SetCurrentFrame(curFrame) loc = sfm.GetPosition("transform", space="World") rot = sfm.GetRotation("transform", space="World") X = -loc[1] * scale Y = loc[2] * scale Z = -loc[0] * scale ZR = -rot[0] #*RAD2DEG XR = -rot[1] #*RAD2DEG YR = rot[2] #*RAD2DEG ZR = LimDeg(ZR) XR = LimDeg(XR) YR = LimDeg(YR) S = "" + FloatToBvhString(X) + " " + FloatToBvhString( Y) + " " + FloatToBvhString(Z) + " " + FloatToBvhString( ZR) + " " + FloatToBvhString(XR) + " " + FloatToBvhString( YR) + "\n" file.write(S) curFrame += 1 finally: file.close() sfm.SetCurrentFrame(oldFrame) if not curFrame == frameCount: SetError("Could not write all frames.") return False return True
def __init__(self): self._original = sfm.GetCurrentShot() self.animsets = [ SFMAnimationSet(animset) for animset in self._original.animationSets ]
def getAnimationSetByName(name): shot = sfm.GetCurrentShot() for animset in shot.animationSets: if animset.name.GetValue() == name: return SFMAnimationSet(animset)