예제 #1
0
    def __init__(self):

        self.Dialog = QtGui.QDialog()
        self.animset = sfm.GetCurrentAnimationSet()
        self.setupUi(self.Dialog)

        self.ExpandToolBox()
        self.audiofilepath = None
        self.audioAnalyze = None

        if len(sfmClipEditor.GetSelectedClips("CDmeSoundClip")) == 0:
            self.ErrorBox("One Wav file needs to be selected!")
            return

        self.sfmCDmeSoundClip = sfmClipEditor.GetSelectedClips()[0]
        ClipName = self.sfmCDmeSoundClip.GetName().replace('\\', '/')

        if "wav" not in ClipName[-4:]:
            self.ErrorBox("Sound file Needs to be .wav")
            return

#we need to search though sfm mod paths cache because CDmeSoundClip does not contain a full file path

        search_paths = filesystem.valve.GameInfoFile(
            filesystem.valve.mod() + "/gameinfo.txt").getSearchMods()

        for index in range(len(search_paths)):
            if os.path.isfile(search_paths[index] + "/sound/" + ClipName):
                self.audiofilepath = search_paths[index] + "/sound/" + ClipName

        self.Dialog.closeEvent = self.closeEvent
        #allows user to somewhat interact with sfm while script is active. any changes to scene will happen once script is closed
        self.Dialog.show()
        #important!!, any gui that needs to alter animset values for animation needs to be .exec_() else sfm will crash
        self.Dialog.exec_()
예제 #2
0
def main():
    # Типы скриптов:
    #scripts\sfm\..
    # global - mainmenu
    # animation set context menu - animset
    # dag context menu - dag
    # during sfm initialization - sfm_init.py

    # shot = sfm.GetCurrentShot()
    # camera = shot.camera
    # animset = shot.animationSets[0]
    # controls = кости

    animSet = sfm.GetCurrentAnimationSet()
    gameModel = animSet.gameModel
    rootGroup = animSet.GetRootControlGroup()
    # ControlGroupName = 'newControlName'
    # controlGroup = animSet.FindOrAddControlGroup(animSet.GetRootControlGroup(), 'newControlName')
    # print(controlGroup)

    materials_dict = dict()

    # for material in gameModel.materials:
    #   materials_dict =

    for material in gameModel.materials:
        value = 'xxxxx'
        if not material.HasAttribute('$cloakcolortint'):
            continue

        print material.name
        print material.GetValue('$cloakcolortint')
        print type(material.GetValue('$cloakcolortint'))
예제 #3
0
def getMaterialByName(name, animset=None):
    if not animset:
        animset = sfm.GetCurrentAnimationSet()

    for material in animset.gameModel.materials:
        if material.GetValue('name') == name:
            return SFMMaterial
예제 #4
0
    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)
예제 #5
0
    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 main():
    aset = sfm.GetCurrentAnimationSet()
    rc = aset.GetRootControlGroup()

    if not rc.HasChildGroup('Rigidbodies', False):
        PySide.QtGui.QMessageBox.critical(
            None, 'ERROR - sfmphys_make_object_kinematic.py',
            'Error! Could\'nt find Rigidbodies control group.\n\n'
            'Try to reapply rig with rig_physics.py again or report error to developer.'
        )
        return

    # Remove constraints for all groups excep Rigidbodies and PhysConstraints
    other_control_groups = []
    for control_group in rc.GetValue('children'):
        control_group_name = control_group.GetName()
        if control_group_name not in ('Rigidbodies', 'PhysConstraints') and \
                control_group.GetValue('controls'):
            other_control_groups.append(control_group_name)
    sfm.ClearSelection()
    sfm.Select(*other_control_groups)
    sfm.RemoveConstraints()

    rigid_bodies = rc.FindChildByName('Rigidbodies', False)
    for child in rigid_bodies.GetValue('children'):
        # child is DmeControlGroup
        name = child.GetName()
        controls = child.GetValue('controls')
        for control in controls:
            if control.GetName().startswith('Handle'):
                handle = control
            elif control.GetName().startswith('Kinematic'):
                kinematic = control

        # set kinematic = 1 all the way
        kinematic = python_sfm.SFMControl(kinematic)
        ch = kinematic.channels[0]
        ch.values = [1 for i in ch.values]

        # create parent constraint: original control -> physical handle
        handle_name = handle.GetName()
        original_control_name = re.findall(r'Handle \((.+)\)$', handle_name)[0]
        sfm.ParentConstraint(original_control_name, handle.GetName(), mo=True)
예제 #7
0
def PresetGroupsToJSON():
    
    animSet = sfm.GetCurrentAnimationSet()
    presetGroups = animSet.presetGroups

    data = {}
    data["Model"] = str(animSet.gameModel.modelName)
    data["PresetGroups"] = []

    for presetGroup in presetGroups:

        pgdata = {}
        pgdata["Name"] = str(presetGroup.name)

        presets = []
        for preset in presetGroup.presets:
            pdata = {}
            pdata["Name"] = str(preset.name)
            controlValues = []
            for cv in preset.controlValues:
                cvdata = {}
                cvdata["Name"] = str(cv.name)
                if hasattr(cv, "value"):
                    cvdata["Value"] = str(cv.value)
                if hasattr(cv, "leftValue"):
                    cvdata["LeftValue"] = str(cv.leftValue)
                if hasattr(cv, "rightValue"):
                    cvdata["RightValue"] = str(cv.rightValue)
                controlValues.append(cvdata)
            pdata["ControlValues"] = controlValues
            presets.append(pdata)
        pgdata["Presets"] = presets

        data["PresetGroups"].append(pgdata)

    jdata = json.dumps(data)
    filename, _ = QtGui.QFileDialog.getSaveFileName(None, "Export preset groups", "C:\\" + str(animSet.name) + ".json")
    f = open(filename, "w")
    f.write(jdata)
    f.close()

    QtGui.QMessageBox.information(None, "Export successful", "Export succeeded! Export file: " + filename)
예제 #8
0
    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, 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
예제 #10
0
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
예제 #11
0
def getActiveControlsList():
    animset = sfm.GetCurrentAnimationSet()
    c = sfmApp.GetDocumentRoot().settings.graphEditorState.activeControlList
    return c