Exemplo n.º 1
0
 def renameUVSet(self):
     # スキンウェイト書き戻し用、ウェイトを保存しておく。
     if self.uvSetAll[0] != "map1" or len(self.uvSetAll) > 1:
         weight.WeightCopyPaste().main(self.mesh,
                                       mode="copy",
                                       saveName=__name__)
         for self.var in range(1, self.uvNum + 1):
             var = str(self.var)
             renameSet = self.uvSetAll[self.var - 1]
             if renameSet != self.defaultName + var:
                 print("Rename UV Set : " + self.mesh + "." + renameSet +
                       " >>> " + self.defaultName + var)
                 # transfer_weight(self.mesh,skinTemp[0])
                 # デフォーマヒストリも削除しないとリネーム後UVなくなる
                 cmds.bakePartialHistory(self.shapes, preCache=True)
                 cmds.polyUVSet(
                     self.mesh,
                     uvSet=renameSet,
                     newUVSet=self.defaultName + var,
                     e=True,
                     rename=True,
                 )
         # ウェイトを書き戻してくる
         weight.WeightCopyPaste().main(self.mesh,
                                       mode="paste",
                                       saveName=__name__)
Exemplo n.º 2
0
def historyDelete(targetObj, isStart):
    if isStart == True:
        dialogMessage = ""
        lang = mc.about(uiLanguage=True)
        if lang == "ja_JP":
            dialogMessage = "実行前に「デフォーマ以外のヒストリ」削除を行いますがよろしいですか?"
        else:
            dialogMessage = 'Do you delete "Non-Deformer History"\nfor the selected object before execution?'

        # ヒストリを削除してよいかの確認ダイアログ表示
        selDialog = mc.confirmDialog(
            title='kkDisplayVertexColorSeparately_Check',
            message=dialogMessage,
            button=['Yes', 'No'],
            defaultButton='Yes',
            cancelButton='No',
            dismissString='No')

        if selDialog == "No":
            mc.warning("kkDisplayVertexColorSeparately is Canceled."),
            return False

    # デフォーマ以外のヒストリの削除実行
    mc.bakePartialHistory(targetObj, prePostDeformers=True)

    return True
Exemplo n.º 3
0
 def dup_polygon_mesh(self):
     dup_objs = []
     for node in self.copy_mesh:
         #子供のノード退避用ダミーペアレントを用意
         dummy = common.TemporaryReparent().main(mode='create')
         common.TemporaryReparent().main(node,
                                         dummyParent=dummy,
                                         mode='cut')
         #複製
         dup = cmds.duplicate(node, rc=True)[0]
         cmds.bakePartialHistory(dup, pc=True)
         dup_objs.append(dup)
         #ウェイト転送
         weight.WeightCopyPaste().main(node,
                                       mode='copy',
                                       saveName=__name__,
                                       weightFile=node)
         weight.WeightCopyPaste().main(dup,
                                       mode='paste',
                                       saveName=__name__,
                                       weightFile=node)
         cmds.bakePartialHistory(dup, ppt=True)
         #親子付けを戻す
         common.TemporaryReparent().main(node,
                                         dummyParent=dummy,
                                         mode='parent')
         #ダミーペアレントを削除
         common.TemporaryReparent().main(dummyParent=dummy, mode='delete')
     #cmds.select(dup_objs)
     return dup_objs
Exemplo n.º 4
0
    def crenupMultiUV(self):
        self.defaultName = "map"  # デフォルト名
        # print(self.mesh)
        shapes = cmds.listRelatives(self.mesh, s=True, pa=True)
        self.shapes = shapes[0]
        # ヒストリ削除
        cmds.bakePartialHistory(self.shapes, ppt=True)
        # cmds.bakePartialHistory(self.shapes,preCache=True)

        self.uvSetAll = cmds.polyUVSet(self.mesh, q=True, allUVSets=True)
        self.currentSet = cmds.polyUVSet(self.mesh, q=True, currentUVSet=True)

        # 現在のUVが空かどうか調べてスキップフラグがTrueなら関数抜ける
        if not self.checkCurrentUV():
            print("Skip (No UV in Current UVSet) : " + self.mesh)
            return
        self.delUVFlag = True
        self.uvNum = 1  # マルチUVリネーム用
        # マルチUVの指定名があれば削除フラグをFalseに
        if "Multi_UV" in self.mesh or self.delMultiUV is False:
            self.delUVFlag = False
            self.uvNum = len(self.uvSetAll)  # マルチUVリネーム用

        if len(self.uvSetAll) > 0:  # UVセットがあったら
            self.deleteUV()
            # UVセットの名前を変更、マルチUVの場合は繰り返し処理
            self.renameUVSet()
        # UVセットが複数の場合セットに追加する
        if self.groupMultiUV is True and len(self.uvSetAll) > 1:
            cmds.sets(self.mesh, add="Multi_UV_Set")  # setに追加
Exemplo n.º 5
0
def mergeCurves(curves):
    curves = utility.unParentToWorld(curves)

    for curve in curves:
        cmds.makeIdentity(curve, a=1)
        cmds.bakePartialHistory(curve, pc=1)

    # set newTransform as first in selection
    groupTransform = curves[0]

    # get groupTransform
    grp = cmds.group(em=1)
    #cmds.matchTransform(grp, groupTransform)
    groupTransform = grp

    for curve in curves:
        # make sure curveShapes don't move
        cmds.makeIdentity(curve, a=1)

        # merge to groupTransform
        curveShapes = utility.getShapes(curve)
        for curveShape in curveShapes:
            cmds.parent(curveShape, groupTransform, r=1, s=1)

        # delect rest
        cmds.delete(curve)

    # center pivot and clear history
    cmds.xform(groupTransform, cp=1)
    cmds.bakePartialHistory(groupTransform, pc=1)
    cmds.select(groupTransform)
Exemplo n.º 6
0
def TriangulateAllSkinnedMeshes():
    with mayaUtils.DebugTimer('TriangulateAllSkinnedMeshes'):
        cmds.select(clear=True)
        skinList = cmds.ls(type='skinCluster') or []
        for s in skinList:
            mesh = mayaUtils.GetMeshFromSkinCluster(s)
            cmds.polyTriangulate(mesh)
            cmds.bakePartialHistory(mesh, prePostDeformers=True)
        cmds.select(clear=True)
Exemplo n.º 7
0
 def weightCopy(self):
     saveData = {}
     # 保存ディレクトリが無かったら作成
     if not os.path.exists(self.filePath):
         os.makedirs(os.path.dirname(self.filePath + '\\'))  # 末尾\\が必要なので注意
     else:  # ある場合は中身を削除
         files = os.listdir(self.filePath)
         if files is not None:
             for file in files:
                 os.remove(self.filePath + '\\' + file)
     skinFlag = False
     for skinMesh in self.skinMeshes:
         try:
             cmds.bakePartialHistory(skinMesh, ppt=True)
         except:
             pass
         # ノードの中からスキンクラスタを取得してくる#inMesh直上がSkinClusterとは限らないので修正
         srcSkinCluster = cmds.ls(cmds.listHistory(skinMesh),
                                  type='skinCluster')
         if not srcSkinCluster:
             continue  # スキンクラスタがなかったら次に移行
         tempSkinNode = skinMesh  #親を取得するためスキンクラスタのあるノードを保存しておく
         # スキンクラスタのパラメータ色々を取得しておく
         srcSkinCluster = srcSkinCluster[0]
         skinningMethod = cmds.getAttr(srcSkinCluster + ' .skm')
         dropoffRate = cmds.getAttr(srcSkinCluster + ' .dr')
         maintainMaxInfluences = cmds.getAttr(srcSkinCluster + ' .mmi')
         maxInfluences = cmds.getAttr(srcSkinCluster + ' .mi')
         bindMethod = cmds.getAttr(srcSkinCluster + ' .bm')
         normalizeWeights = cmds.getAttr(srcSkinCluster + ' .nw')
         influences = cmds.skinCluster(srcSkinCluster, q=True, inf=True)
         saveData[skinMesh + ';skinningMethod'] = skinningMethod
         saveData[skinMesh + ';dropoffRate'] = dropoffRate
         saveData[skinMesh +
                  ';maintainMaxInfluences'] = maintainMaxInfluences
         saveData[skinMesh + ';maxInfluences'] = maxInfluences
         saveData[skinMesh + ';bindMethod'] = bindMethod
         saveData[skinMesh + ';normalizeWeights'] = normalizeWeights
         saveData[skinMesh + ';influences'] = influences
         skinFlag = True
         if self.engine == 'maya':
             # 読みに行くセーブファイル名を指定、autoならメッシュ名
             if self.weightFile == 'auto':
                 weightFile = skinMesh
             else:
                 weightFile = self.weightFile
             # Pipeはファイル名に出来ないので変換しておく
             meshName = str(weightFile).replace('|', '__pipe__')
             # コロンはファイル名に出来ないので変換しておく
             meshName = str(meshName).replace(':', '__colon__')
             cmds.deformerWeights(meshName + '.xml',
                                  export=True,
                                  deformer=srcSkinCluster,
                                  path=self.filePath + '\\')
     with open(self.fileName, 'w') as f:  # ファイル開く'r'読み込みモード'w'書き込みモード
         json.dump(saveData, f)
Exemplo n.º 8
0
    def runFix(self):

        try:

            # delete non-deformer history
            cmds.bakePartialHistory(allShapes=True, prePostDeformers=True)

            return "Non-deformer history deleted."

        except:

            return "There was a problem deleteing non-deformer history."
Exemplo n.º 9
0
def create_joint_controllers():
    # Makes a square NURBS controller and parent constraints the joints to the controllers
    import maya.cmds as cmds

    # Makes an array of the selected joints
    TempSel_JointArray = cmds.ls(type=('joint'), sl=True, flatten=True)

    for i in TempSel_JointArray:

        # Selects current joint and sets it as variable TempSel_Parent
        cmds.select(i)
        TempSel_Parent = cmds.ls(sl=True)

        # Selects child joint and sets it as variable tempSel_AimAt
        TempSel_AimAt = cmds.listRelatives(type='joint')

        # Creates square NURBS curve and deletes it's history
        cmds.select(d=True)
        cmds.curve(d=1,
                   p=[(-0.5, 0, .5), (-0.5, 0, -.5), (.5, 0, -.5), (.5, 0, .5),
                      (-0.5, 0, .5)],
                   name='CTRL_' + i)
        cmds.rotate(0, 0, 90)
        cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
        cmds.bakePartialHistory()

        # Makes a group and makes the controller a child of the PIVOT group
        cmds.group(em=True, name='PIVOT_' + (i))
        cmds.parent('CTRL_' + (i), 'PIVOT_' + (i))

        # Makes parent constraint for controller location
        cmds.parentConstraint(TempSel_Parent,
                              'PIVOT_' + i,
                              mo=False,
                              name='TempParentConstraint' + i)
        cmds.delete('TempParentConstraint' + (i))
        if not TempSel_AimAt:
            print "no child joint of {}, skipping rotation".format(i)
        elif len(TempSel_AimAt) == 1:
            # Makes aim constraint for controller orientation
            cmds.aimConstraint(TempSel_AimAt,
                               'PIVOT_' + i,
                               name='TempAimConstraint' + i)
            cmds.delete('TempAimConstraint' + (i))

        # Parent constrains the joint to the controller
        cmds.select('CTRL_' + i)
        cmds.select((i), add=True)
        cmds.parentConstraint(name='parentConstraint_' + (i) + '_CTRL_' + i)
        cmds.select(d=True)
 def pre_transfer_for_noskin_comp(self):
     reselection_flag = False
     for node in self.hl_nodes:
         skin_cluster = cmds.ls(cmds.listHistory(node), type='skinCluster')
         if not skin_cluster:
             #print('pre transfer :', node, self.copy_mesh[0])
             weight.transfer_weight(self.copy_mesh[0], node, transferWeight=False)
             cmds.bakePartialHistory(node, ppt=True)
             reselection_flag = True
     if reselection_flag:
         #print('reselect for undo :')
         #アンドゥ、リドゥのためにエディタ側のスキン情報を更新しておく
         cmds.select(self.transfer_comp, r=True)
         siweighteditor.WINDOW.get_set_skin_weight()
Exemplo n.º 11
0
def freezeModeling(node, engine='maya'):
    #子供のノード退避用ダミーペアレントを用意
    dummy = common.TemporaryReparent().main(mode='create')
    common.TemporaryReparent().main(node,dummyParent=dummy, mode='cut')
    #ヒストリを全削除
    cmds.bakePartialHistory(node,pc=True)
    #ウェイトを書き戻してくる
    weight.WeightCopyPaste().main(node, mode='paste', saveName=__name__, engine=engine)
    #いらないシェイプを消す
    deleteZeroShape(node)
    #親子付けを戻す
    common.TemporaryReparent().main(node, dummyParent=dummy, mode='parent')
    #ダミーペアレントを削除
    common.TemporaryReparent().main(dummyParent=dummy, mode='delete')
Exemplo n.º 12
0
def OptimizeBodyMaterials():
    with mayaUtils.DebugTimer('OptimizeBodyMaterials'):
        shape = mayaUtils.FindMeshByWildcard('Genesis8Female*',
                                             checkForMatWithName='Torso')

        if shape is None:
            print 'Error! Can`t find body(Torso) shape'
            return

        mayaUtils.AppendShadingGroupByMat(shape, 'Face', 'Lips')
        mayaUtils.AppendShadingGroupByMat(shape, 'Face', 'Ears')
        mayaUtils.AppendShadingGroupByMat(shape, 'Face', 'EyeSocket')

        mayaUtils.AppendShadingGroupByMat(shape, 'Legs', 'Toenails')
        mayaUtils.AppendShadingGroupByMat(shape, 'Arms', 'Fingernails')

        mayaUtils.AppendShadingGroupByMat(shape, 'Torso', 'Legs')
        mayaUtils.AppendShadingGroupByMat(shape, 'Torso', 'Arms')
        mayaUtils.AppendShadingGroupByMat(shape, 'Torso', 'Face')

        mayaUtils.AppendShadingGroupByMat(shape, 'Mouth', 'Teeth')

        mayaUtils.AppendShadingGroupByMat(shape, 'EyeMoisture',
                                          'Cornea')  # useful eyes
        mayaUtils.AppendShadingGroupByMat(shape, 'Pupils',
                                          'Irises')  # not used
        mayaUtils.AppendShadingGroupByMat(shape, 'Pupils',
                                          'Sclera')  # not used

        eyesShape = mayaUtils.DetachSkinnedMeshByMat(shape,
                                                     ['EyeMoisture', 'Pupils'],
                                                     '_Eyes')

        mayaUtils.DeleteFacesByMat(eyesShape, ['Pupils'])
        unusedEyesFaces = selUtils.GetFacesOutsideCenterUVRange(eyesShape)
        cmds.delete(unusedEyesFaces)

        mayaUtils.RenameMaterial('Torso', 'Body')
        mayaUtils.RenameMaterial('EyeMoisture', 'Eyes')

        mayaUtils.RenameMaterial('EyeLashes*', 'FemaleEyeLashes')

        SafeBakePartialHistoryKeepBlendShapes(shape)

        if eyesShape:
            cmds.bakePartialHistory(eyesShape, prePostDeformers=True)

        mayaUtils.CleanUnusedInfluensesOnAllSkinClusters()
Exemplo n.º 13
0
 def deleteUV(self):
     # print(self.uvSetAll)
     # print(self.uvSetAll)
     if len(self.uvSetAll) > 1 and self.delUVFlag:  # UVセットが複数あったら削除処理
         cmds.polyUVSet(self.mesh,
                        uvSet=self.uvSetAll[0],
                        e=True,
                        currentUVSet=True)  # カレントを1に
         dummy = common.TemporaryReparent().main(mode="create")
         for var in range(1, len(self.uvSetAll)):
             # print(self.uvSetAll[var])
             # tempUV = cmds.polyUVSet(self.mesh, q=True, allUVSets=True)
             # for uv in tempUV:
             # print(u'UV名確認用 : '+str(uv))
             if self.uvSetAll[var] == self.currentSet[0]:
                 # 親子付けしたまま親のノードを処理するとなぜかUVSet名で処理できないので退避しておく
                 common.TemporaryReparent().main(self.mesh,
                                                 dummyParent=dummy,
                                                 mode="cut")
                 # カレントUVを1番目にコピー
                 cmds.polyCopyUV(self.mesh,
                                 uvi=self.uvSetAll[var],
                                 uvs=self.uvSetAll[0])
                 # 親子付けを戻す
                 common.TemporaryReparent().main(self.mesh,
                                                 dummyParent=dummy,
                                                 mode="parent")
             if self.uvSetAll[var].split(".")[-1] in self.exclusion:
                 print("Skip UV in Exclusion List :", self.uvSetAll[var])
                 continue
             # 最初のUVセット以外は削除
             try:
                 print("Delete UV Set : " + self.mesh + "." +
                       self.uvSetAll[var])
                 cmds.polyUVSet(self.mesh,
                                uvSet=self.uvSetAll[var],
                                delete=True)
             except:
                 print("Delete UV Set Error : " + self.mesh + "." +
                       self.uvSetAll[var] + " is not exsist\n" +
                       "Skip this mesh object")
         # ダミー削除
         common.TemporaryReparent().main(dummyParent=dummy, mode="delete")
         # ヒストリ削除
         cmds.bakePartialHistory(self.shapes, ppt=True)
Exemplo n.º 14
0
def freeze():
    cmds.selectMode(o=True)
    selection = cmds.ls(sl=True, type = 'transform')
    dummy = common.TemporaryReparent().main(mode='create')#モジュールでダミーの親作成
    clusterCopy = modeling.ClusterCopy()
    for sel in selection:
        allChildren = [sel] + cmds.listRelatives(sel, ad=True)#子供を取得して1つのリストにする
        polyMesh = common.search_polygon_mesh(allChildren)
        if polyMesh:
            for mesh in polyMesh:
                common.TemporaryReparent().main(mesh, dummyParent=dummy, mode='cut')
                defCls = clusterCopy.copy(mesh)
                cmds.bakePartialHistory(mesh,pc=True)
                if defCls:
                    clusterCopy.paste(mesh)
                common.TemporaryReparent().main(mesh, dummyParent=dummy, mode='parent')#コピーのおわったメッシュの子供を元に戻す
    common.TemporaryReparent().main(dummyParent=dummy, mode='delete')#ダミー親削除
    cmds.select(selection, r=True)
Exemplo n.º 15
0
def SafeBakePartialHistoryKeepBlendShapes(pShape):
    print 'SafeBakePartialHistoryKeepBlendShapes(pShape=\'{}\')'.format(pShape)
    bs = mayaUtils.GetBlendShape(pShape)
    if not bs:
        print 'No blendshape detected. Performing standart baking partial history'
        #cmds.bakePartialHistory(shape, prePostDeformers=True)
    else:
        print 'Detected blendshape \'{}\'. Performing ajustments'.format(bs)
        weightCount = cmds.blendShape(bs, q=True, weightCount=True)
        names = cmds.listAttr(bs + '.w', m=True)

        tempTargetObjects = []

        # Extract every blendshape to separate mesh
        for i in range(weightCount):
            # Set current index weight to 1.0, all others to 0.0
            for x in range(weightCount):
                weight = 0.0
                if i == x:
                    weight = 1.0
                cmds.blendShape(bs, edit=True, weight=[x, weight])
            newShape = cmds.duplicate(pShape, name=names[i])[0]
            cmds.setAttr(newShape + '.tz', lock=0)
            cmds.bakePartialHistory(newShape)
            cmds.xform(newShape,
                       absolute=True,
                       translation=[0, 0, 50.0 * (i + 1)])
            tempTargetObjects.append(newShape)

        # Reset all weights to zero
        for i in range(weightCount):
            cmds.blendShape(bs, edit=True, weight=[i, 0.0])

        cmds.delete(bs)
        cmds.bakePartialHistory(pShape, prePostDeformers=True)

        argsList = []
        argsList.extend(tempTargetObjects)
        argsList.append(pShape)  # LAST add initial object to list
        cmds.blendShape(argsList)

        cmds.delete(tempTargetObjects)  # delete temporary objects
Exemplo n.º 16
0
def PostprocessGenitaliaObject(genitaliaMeshWildcard):
    with mayaUtils.DebugTimer(
            'PostprocessGenitaliaObject(genitaliaMeshWildcard={0})'.format(
                genitaliaMeshWildcard)):
        genitaliaMesh = mayaUtils.FindMeshByWildcard(genitaliaMeshWildcard)
        if not genitaliaMesh:
            print 'Genitalia mesh not found. Aborted'
            return

        print 'Processing {0}'.format(genitaliaMesh)

        genitaliaMesh = cmds.rename(genitaliaMesh,
                                    'FemaleGenitalia')  #rename to proper name

        #replace material with original torso mat
        facesWithTorsoMat = mayaUtils.GetFacesByMatsWildcard(
            genitaliaMesh, 'Torso*')
        mayaUtils.AssignObjectListToShader(facesWithTorsoMat,
                                           'Body')  #use new material name
        # mayaUtils.ArrangeUVByMat(genitaliaMesh, 'Body', su=0.5, sv=0.5, u=0.5, v=0.5)
        mayaUtils.AppendShadingGroupByMat(genitaliaMesh, 'Anus', 'V****a')
        mayaUtils.RenameMaterial('Anus', 'BodyGenitalia')
        cmds.bakePartialHistory(genitaliaMesh, prePostDeformers=True)

        bodyMesh = mayaUtils.FindMeshByWildcard('FemaleBody' + '*',
                                                checkForMatWithName='Body')

        if not bodyMesh:
            print '{0} mesh not found. Aborted'
            return

        cmds.select(clear=True)
        borderVertsList = mayaUtils.GetBorderVertices(genitaliaMesh)
        borderVertsList = cmds.filterExpand(borderVertsList,
                                            sm=31,
                                            expand=True)

        bodySkinCluster = mayaUtils.GetSkinCluster(bodyMesh)
        genitaliaSkinCluster = mayaUtils.GetSkinCluster(genitaliaMesh)

        #transfer attributes manually
        for v in borderVertsList:
            pos = cmds.pointPosition(v, world=True)
            #print pos
            closestVert = mayaUtils.GetClosestVertex(bodyMesh, pos)
            closestVertPos = cmds.xform(closestVert, t=True, ws=True, q=True)
            closestVertNormal = cmds.polyNormalPerVertex(closestVert,
                                                         query=True,
                                                         xyz=True)

            # set position
            cmds.move(closestVertPos[0],
                      closestVertPos[1],
                      closestVertPos[2],
                      v,
                      absolute=True,
                      worldSpace=True)
            # set normal
            cmds.polyNormalPerVertex(v,
                                     xyz=(closestVertNormal[0],
                                          closestVertNormal[1],
                                          closestVertNormal[2]))

            referenceVertInfluences = cmds.skinPercent(bodySkinCluster,
                                                       closestVert,
                                                       query=True,
                                                       transform=None,
                                                       ignoreBelow=0.00001)

            targetInfluences = cmds.skinCluster(genitaliaSkinCluster,
                                                query=True,
                                                influence=True)

            targetTransformValues = []

            for i in referenceVertInfluences:
                if i not in targetInfluences:
                    cmds.skinCluster(genitaliaSkinCluster,
                                     e=True,
                                     addInfluence=i,
                                     weight=0.0)
                    #print i
                referenceInfluenceValuePerVertex = cmds.skinPercent(
                    bodySkinCluster,
                    closestVert,
                    query=True,
                    transform=i,
                    transformValue=True)
                targetTransformValues.append(
                    (i, referenceInfluenceValuePerVertex))

            #print targetTransformValues

            # set weight
            cmds.skinPercent(genitaliaSkinCluster,
                             v,
                             transformValue=targetTransformValues)

        cmds.bakePartialHistory(genitaliaMesh, prePostDeformers=True)
Exemplo n.º 17
0
def autoFKIK(jnt_start, jnt_end, panel):
    # -------------------------------------------------------------------------------
    # create ik joint match render joint
    # -------------------------------------------------------------------------------
    ik_jnt_list = []

    jnt_i = jnt_end
    render_jnt_list = []

    while True:
        print("start: " + jnt_i)
        render_jnt_list.append(jnt_i)
        name = jnt_i.split("|")[-1]

        ik_jnt_i = cmds.duplicate(jnt_i, n=name + "_ik", parentOnly=1)[0]
        ik_jnt_list.append(ik_jnt_i)

        if jnt_i == jnt_start:
            print("end loop")
            break
        else:
            prt = utility.getPrt(jnt_i)
            if prt:
                jnt_i = prt
                print("end: " + jnt_i)
            else:
                break

    # reparent
    for inx in range(len(ik_jnt_list)):
        if inx < len(ik_jnt_list) - 1:
            ik_jnt_list[inx] = cmds.parent(ik_jnt_list[inx],
                                           ik_jnt_list[inx + 1])[0]
        else:
            if utility.getPrt(ik_jnt_list[inx]):
                ik_jnt_list[inx] = cmds.parent(ik_jnt_list[inx], w=1)[0]

    name = jnt_start.split("|")[-1]
    ikHandle = cmds.ikHandle(name=name + "_ikHandle",
                             sj=ik_jnt_list[-1],
                             ee=ik_jnt_list[0])[0]

    # -------------------------------------------------------------------------------
    # create ik ctls
    # -------------------------------------------------------------------------------

    radius1 = cmds.joint(jnt_end, q=1, radius=1)[0]

    ik_ctl = functions.createCurves(curvesInfo[2]['shape'], (0.26, 0.84, 1.0),
                                    name=name + "_ik_ctl")

    cmds.bakePartialHistory(ik_ctl, pc=1)
    cmds.matchTransform(ik_ctl, ikHandle)

    cmds.xform(ik_ctl, s=[radius1 * 3, radius1 * 3, radius1 * 3])
    functions.groupIt([ik_ctl])

    # Constraint
    cmds.select(ik_ctl)
    cmds.select(ikHandle, add=1)

    ik_constraint = cmds.parentConstraint(mo=1)[0]

    cmds.select(ik_ctl)
    cmds.select(ik_jnt_list[0], add=1)
    cmds.orientConstraint(mo=1)

    # -------------------------------------------------------------------------------
    # create pole ctls
    # -------------------------------------------------------------------------------
    ik_pole = functions.createCurves(curvesInfo[1]['shape'], (1.0, 0.1, 0.21),
                                     name=name + "_ik_pole")
    #cmds.bakePartialHistory(ik_pole, pc=1)

    middle_jnt = render_jnt_list[len(render_jnt_list) // 2]
    radius2 = cmds.joint(middle_jnt, q=1, radius=1)[0]

    cmds.matchTransform(ik_pole, middle_jnt, pos=1)

    pole_vector = cmds.getAttr(ikHandle + '.poleVector')[0]
    pole_vector = utility.vectorMult(pole_vector, radius2 * 4)

    cmds.xform(ik_pole, r=1, ws=1, t=pole_vector)
    cmds.xform(ik_pole, s=[radius2, radius2, radius2])

    functions.groupIt([ik_pole])

    cmds.select(ik_pole)
    cmds.select(ikHandle, add=1)

    pole_constraint = cmds.poleVectorConstraint()[0]

    pole_help = functions.createCurves(curvesInfo[3]['shape'], (0.3, 0.3, 0.3),
                                       name=name + "_pole_help")
    shapes = utility.getShapes(pole_help)
    for shape in shapes:
        cmds.setAttr(shape + '.overrideDisplayType', 1)

    cmds.select(pole_help + '.cv[0]')
    pole_c1 = cmds.cluster(name=name + "_pole_c1")[1]

    cmds.select(pole_help + '.cv[1]')
    pole_c2 = cmds.cluster(name=name + "_pole_c2")[1]

    cmds.select(middle_jnt)
    cmds.select(pole_c1, add=1)
    cmds.pointConstraint(mo=0)

    cmds.select(ik_pole)
    cmds.select(pole_c2, add=1)
    cmds.pointConstraint(mo=0)
    # -------------------------------------------------------------------------------
    # create fk ctls
    # -------------------------------------------------------------------------------
    fk_ctl_list = []

    for inx in range(len(render_jnt_list)):
        name = render_jnt_list[inx].split("|")[-1]
        radius = cmds.joint(render_jnt_list[inx], q=1, radius=1)[0]

        fk_ctl = functions.createCurves(curvesInfo[0]['shape'], (1, 0.8, 0.0),
                                        name=name + "_fk_ctl")

        cmds.bakePartialHistory(fk_ctl, pc=1)
        fk_ctl_list.append(fk_ctl)
        cmds.matchTransform(fk_ctl, render_jnt_list[inx])
        print(radius)
        cmds.xform(fk_ctl, s=[radius * 4, radius * 4, radius * 4])
        cmds.xform(fk_ctl, p=1, rotateOrder='xzy')

    for inx in range(len(fk_ctl_list) - 1):
        fk_ctl_list[inx] = cmds.parent(fk_ctl_list[inx],
                                       fk_ctl_list[inx + 1])[0]
    print(fk_ctl_list)
    functions.groupIt(fk_ctl_list)

    constraint_list = []

    for inx in range(len(render_jnt_list)):

        cmds.select(ik_jnt_list[inx])
        cmds.select(fk_ctl_list[inx], add=1)
        cmds.select(render_jnt_list[inx], add=1)

        constraint = cmds.parentConstraint(mo=1)[0]
        constraint_list.append(constraint)

    print("render jnt: ")
    print(render_jnt_list)
    print("ik jnt: ")
    print(ik_jnt_list)
    print("fk ctl: ")
    print(fk_ctl_list)
    print("constraints: ")
    print(constraint_list)

    # -------------------------------------------------------------------------------
    # connecting node
    # -------------------------------------------------------------------------------
    attr_name = name + '_FKIK'
    attr_full_name = panel + '.' + attr_name

    # check if it already has 'fkik'
    if cmds.attributeQuery(attr_name, node=panel, ex=1):
        cmds.addAttr(attr_full_name,
                     k=1,
                     e=1,
                     ln=attr_name,
                     at="float",
                     max=1.0,
                     min=0.0)
    else:
        cmds.addAttr(panel, k=1, ln=attr_name, at="float", max=1.0, min=0.0)

    # set to 0
    cmds.setAttr(attr_full_name, 0)

    # clear old one
    range_node = cmds.listConnections(attr_full_name, d=1, s=0)

    if not range_node:
        range_node = cmds.shadingNode("setRange", au=1)
        cmds.connectAttr(attr_full_name, "%s.valueX" % range_node, f=1)
        cmds.connectAttr(attr_full_name, "%s.valueY" % range_node, f=1)
        cmds.setAttr("%s.oldMaxX" % range_node, 1.0)
        cmds.setAttr("%s.oldMaxY" % range_node, 1.0)
        cmds.setAttr("%s.maxX" % range_node, 1.0)
        cmds.setAttr("%s.minY" % range_node, 1.0)
    else:
        range_node = range_node[0]

    print(range_node)

    # connect node
    for inx, constraint in enumerate(constraint_list):

        ik_weight_name = constraint + "." + ik_jnt_list[inx] + "W0"
        fk_weight_name = constraint + "." + fk_ctl_list[inx] + "W1"
        fk_ctl_vis_name = fk_ctl_list[inx] + ".visibility"

        cmds.connectAttr("%s.outValueX" % range_node, ik_weight_name, f=1)
        cmds.connectAttr("%s.outValueY" % range_node, fk_weight_name, f=1)
        cmds.connectAttr("%s.outValueY" % range_node, fk_ctl_vis_name, f=1)

    cmds.connectAttr("%s.outValueX" % range_node, ik_ctl + ".visibility", f=1)
    cmds.connectAttr("%s.outValueX" % range_node, ik_pole + ".visibility", f=1)
    cmds.connectAttr("%s.outValueX" % range_node,
                     pole_help + ".visibility",
                     f=1)

    divide_node = cmds.shadingNode("multiplyDivide", au=1)
    clamp_node = cmds.shadingNode("clamp", au=1)

    distanceD = cmds.distanceDimension(sp=(0, 2, 2), ep=(1, 5, 6))
    [loc1, loc2] = cmds.listConnections(distanceD, d=0, s=1)

    #cmds.matchTransform(loc1,ik_ctl)
    #loc1 = cmds.parent(loc1,ik_ctl)[0]
    #cmds.matchTransform(loc2,render_jnt_list[-1])
    #loc2 = cmds.parent(loc2,render_jnt_list[-1])[0]

    cmds.select(ik_ctl)
    cmds.select(loc1, add=1)
    cmds.pointConstraint(mo=0)

    cmds.select(ik_jnt_list[-1])
    cmds.select(loc2, add=1)
    cmds.pointConstraint(mo=0)

    originL = 0
    for inx in range(len(ik_jnt_list) - 1):
        originL += cmds.getAttr("%s.translateX" % ik_jnt_list[inx])
    print(originL)

    cmds.setAttr("%s.operation" % divide_node, 2)
    cmds.setAttr("%s.input2X" % divide_node, originL)
    cmds.setAttr("%s.minR" % clamp_node, 1.0)
    cmds.setAttr("%s.maxR" % clamp_node, 10.0)
    cmds.connectAttr("%s.distance" % distanceD,
                     "%s.input1X" % divide_node,
                     f=1)
    cmds.connectAttr("%s.outputX" % divide_node, "%s.inputR" % clamp_node, f=1)

    for inx in range(len(ik_jnt_list)):
        cmds.connectAttr("%s.outputR" % clamp_node,
                         "%s.scaleX" % ik_jnt_list[inx],
                         f=1)

    misc_grp = cmds.ls("DoNotTouch")
    if not misc_grp:
        misc_grp = cmds.group(name="DoNotTouch", em=1)

    hide_list = [
        ikHandle, pole_c1, pole_c2, ik_jnt_list[-1], loc1, loc2,
        utility.getPrt(distanceD)
    ]
    misc_list = [
        ikHandle, pole_help, pole_c1, ik_jnt_list[-1], pole_c2, loc1, loc2,
        utility.getPrt(distanceD)
    ]

    for obj in hide_list:
        cmds.hide(obj)

    for obj in misc_list:
        cmds.parent(obj, misc_grp)

    utility.lockHideObj(fk_ctl_list, ['tx', 'ty', 'tz', 'sx', 'sy', 'sz', 'v'])
    utility.lockHideObj([ik_pole], ['rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'])
    utility.lockHideObj([ik_ctl], ['sx', 'sy', 'sz', 'v'])

    prt = utility.getPrt(jnt_start)
    if prt:
        cmds.select(prt)
        cmds.select(ik_jnt_list[-1], add=1)
        cmds.parentConstraint(mo=1)
def extract_faces(face_list=None,
                  new_name=None,
                  keep_original=False,
                  copy_skinning=False):
    """Extract faces from mesh and create a copy

    :param face_list: List of faces to extract
    :param new_name: New mesh name
    :param keep_original: Make a copy of mesh before extraction
    :param copy_skinning: Copy skin weights over to extracted mesh
    :return: Extracted mesh
    """

    if not face_list:
        selected_faces = cmds.ls(sl=True)
    else:
        selected_faces = face_list

    if not bool(cmds.filterExpand(selected_faces, ex=True, sm=34)) or []:
        raise RuntimeError("Must select one or more faces")

    shape = cmds.listRelatives(p=1)
    cur_mesh = cmds.listRelatives(shape, p=1)[0]

    cmds.select(cur_mesh + '.f[:]', tgl=1)
    faces_to_extract = cmds.ls(sl=1)

    # Save current pose
    influence_list = cmds.skinCluster(cur_mesh, q=True, wi=True)
    cur_pose = cmds.dagPose(influence_list, save=True, name='extractInPose')

    # Go to bind pose before copying weights
    bind_pose = cmds.dagPose(influence_list, q=True, bindPose=True)
    cmds.dagPose(bind_pose, restore=True)

    new_mesh = cmds.duplicate(cur_mesh)[0]

    # Rename mesh
    if new_name:
        new_mesh = cmds.rename(new_mesh, new_name)

    # Copy skin weights over to new mesh
    if copy_skinning:
        copy_proxy_to_skin(cur_mesh, new_mesh)

    if not keep_original:
        cmds.delete(selected_faces)

    # Swap current mesh to new mesh
    for i in range(len(faces_to_extract)):
        faces_to_extract[i] = faces_to_extract[i].replace(cur_mesh, new_mesh)

    cmds.delete(faces_to_extract)

    # Clean new mesh
    if copy_skinning:
        cmds.bakePartialHistory(cur_mesh, prePostDeformers=True)
        cmds.bakePartialHistory(new_mesh, prePostDeformers=True)
    else:
        cmds.delete(new_mesh, ch=1)

    cmds.dagPose(cur_pose, restore=True)
    cmds.delete(cur_pose)
    cmds.select(new_mesh, r=1)

    return new_mesh
Exemplo n.º 19
0
def create_nurbs_circle():
    curve = cmds.circle(name='Circle_CTRL')[0]
    cmds.bakePartialHistory(curve)
    nurbs_surf_setup(curve_name=curve)
Exemplo n.º 20
0
def AurTDSafeDelHistory(self):
    tempSel_SafeDelHistory = cmds.ls(sl=True)
    cmds.bakePartialHistory(tempSel_SafeDelHistory, prePostDeformers=True)
Exemplo n.º 21
0
def move_center2selection():
    if not cmds.ls(sl=True):
        return
    if cmds.selectMode(q=True, co=True):
        selection = cmds.ls(sl=True)
        selMode = 'component'
        #カーブもとっておく
        cv_selection = cmds.ls(sl=True, type='double3', fl=True)
        verticies = cmds.polyListComponentConversion(selection, tv=True)
        if verticies:
            verticies = cmds.filterExpand(verticies, sm=31) + cv_selection
        else:
            verticies = cv_selection
        #print verticies
        center = [0, 0, 0]
        for i in range(3):
            center[i] = sum(
                [cmds.pointPosition(vtx, w=True)[i]
                 for vtx in verticies]) / len(verticies)
        #print center
    elif cmds.selectMode(q=True, o=True):
        selMode = 'object'
    #スムース直後だとうまくオブジェクト選択にならないときがあるのでいったんコンポーネントを経由
    cmds.selectMode(co=True)
    cmds.selectMode(o=True)
    selection = cmds.ls(sl=True, l=True, tr=True)

    childeNodes = common.search_polygon_mesh(selection,
                                             serchChildeNode=True,
                                             fullPath=True,
                                             nurbs=True)
    #print childeNodes

    selection = list(set(selection + childeNodes))
    preLock = {}
    for sel in selection:
        preLock[sel] = cmds.getAttr(sel + '.translateX', lock=True)
        for ax in ['X', 'Y', 'Z']:
            cmds.setAttr(sel + '.translate' + ax, lock=False)

    if selMode == 'object':
        #正しいバウンディングボックスを得るために複製、ベイク、取得、削除する
        duplicate_mesh = cmds.duplicate(selection,
                                        rc=True)  #子の名前を固有にしてエラー回避rc=True
        cmds.bakePartialHistory(duplicate_mesh, ppt=True)
        bBox = cmds.exactWorldBoundingBox(duplicate_mesh,
                                          ignoreInvisible=False)
        center = [(bBox[i] + bBox[i + 3]) / 2 for i in range(3)]
        cmds.delete(duplicate_mesh)

    for sel in selection:
        if np_flag:
            sel_pos = np.array(cmds.xform(sel, q=True, t=True, ws=True))
            offset = sel_pos - np.array(center)
        # offset *= 2
        else:
            sel_pos = cmds.xform(sel, q=True, t=True, ws=True)
            offset = [p - c for p, c in zip(sel_pos, center)]

        dummy = common.TemporaryReparent().main(mode='create')  #モジュールでダミーの親作成
        common.TemporaryReparent().main(sel, dummyParent=dummy, mode='cut')

        cmds.xform(sel, t=center, ws=True)

        #カーブもとっておく
        cv_selection = cmds.ls(sel + '.cv[*]', fl=True)
        #print cv_selection
        verticies = cmds.polyListComponentConversion(sel, tv=True)
        if verticies:
            verticies = cmds.filterExpand(verticies, sm=31) + cv_selection
        else:
            verticies = cv_selection
        #print verticies
        #print offset
        cmds.xform(verticies, t=offset, r=True, ws=True)

        cmds.xform(sel + '.scalePivot', t=center, ws=True)
        cmds.xform(sel + '.rotatePivot', t=center, ws=True)

        if preLock[sel]:
            for ax in ['X', 'Y', 'Z']:
                cmds.setAttr(sel + '.translate' + ax, lock=True)

        #cmds.xform(sel+'.scalePivot', t=[0, 0, 0], os=True)
        #cmds.xform(sel+'.rotatePivot', t=[0, 0, 0], os=True)

        common.TemporaryReparent().main(sel, dummyParent=dummy, mode='parent')
        common.TemporaryReparent().main(sel, dummyParent=dummy, mode='delete')

    freeze.main(mesh=selection)
    cmds.select(selection, r=True)
Exemplo n.º 22
0
 def _fix(self, mesh):
     """
     :param str mesh:
     """
     cmds.bakePartialHistory(mesh, prePostDeformers=True)
Exemplo n.º 23
0
def polyToCurveS(*args):
    cmds.polyToCurve(form=2, degree=3, conformToSmoothMeshPreview=1)
    cmds.bakePartialHistory(pc=1)
Exemplo n.º 24
0
def duplycateSymmetry(object):
    meshNode = cmds.listRelatives(object,
                                  s=True,
                                  pa=True,
                                  type='mesh',
                                  fullPath=True)
    if meshNode is not None:
        #エラー吐くことがあるのでノンデフォーマヒストリを削除
        cmds.bakePartialHistory(object, ppt=True)
    #ネームスペースから分割
    nemeSplit = object.split('|')
    newName = nemeSplit[-1]
    #左右リネーム関数呼び出し
    newName = renameLR(newName)
    #複製して反転
    duplicated = pm.duplicate(object, name=newName)
    try:
        parentNode = duplicated[0].firstParent(
        )  #Pymelの機能で親の階層を取得しておく。listRelativesと同じような。
        parentNode = str(parentNode)  #cmdsで使えるように文字列に変換
        #左右リネーム関数呼び出し
        newParent = renameLR(parentNode)
    except:
        parentNode = None
        newParent = None
    duplicated = str(duplicated[0])  #cmdsで使えるように文字列に変換
    #子供のオブジェクト取得関数呼び出し
    children = pm.listRelatives(duplicated, ad=True, type='transform', f=True)
    #子供のオブジェクトがある場合は重複を避けるため削除
    if len(children) != 0:
        cmds.delete(children)
    #アトリビュートのロック解除
    #全部のロック解除しないと親が変わったときのロカール値が変わらず、ズレることがある。
    attr = ['.translate', '.rotate', '.scale']
    axis = ['X', 'Y', 'Z']
    for varA in range(0, 3):
        for varB in range(0, 3):
            cmds.setAttr(duplicated + attr[varA] + axis[varB], lock=False)
    #ワールドスケール用ダミーロケータ作成
    dummy = common.TemporaryReparent().main(mode='create')
    cmds.parent(duplicated, dummy)
    #X方向に-1スケーリングしてからスケールフリーズ
    cmds.scale(-1, 1, 1, dummy, relative=True, pivot=(0, 0, 0))
    #杏仁生成を防ぐためにダミーロケータのスケールをフリーズ、負の値が親に入ってると杏仁が生成されるような。
    if cmds.nodeType(duplicated) == 'joint':
        #ジョイントを正しい回転、位置に修正するため、スケールフリーズ前のグローバル値を取得しておく
        pos = cmds.xform(duplicated, q=True, t=True, ws=True)
        rot = cmds.xform(duplicated, q=True, ro=True, ws=True)
        cmds.makeIdentity(dummy,
                          apply=True,
                          translate=False,
                          rotate=False,
                          scale=True,
                          preserveNormals=True)
    #元の親名と違い、かつ新しい親名のオブジェクトが存在する場合は付け替え
    if parentNode is None:
        cmds.parent(duplicated, w=True)
    else:
        if parentNode != newParent and cmds.ls(newParent):
            cmds.parent(duplicated, newParent)
        else:
            cmds.parent(duplicated, parentNode)
    #ダミーペアレントを削除
    common.TemporaryReparent().main(dummyParent=dummy, mode='delete')
    cmds.makeIdentity(duplicated,
                      apply=True,
                      translate=False,
                      rotate=False,
                      scale=True,
                      preserveNormals=True)
    if cmds.nodeType(duplicated) == 'joint':
        cmds.xform(duplicated, t=pos, ro=rot, ws=True)
    return duplicated
Exemplo n.º 25
0
def OptimizeBodyMeshForBaking():
    start = time.clock()
    shape = cmds.ls(selection=True)

    if not shape:
        print 'Mesh not selected'
        return
    shape = shape[0]
    print shape
    print 'bakePartialHistory'
    cmds.bakePartialHistory(shape, preCache=True)

    allSets = cmds.listSets(object=shape, extendToShape=True)
    renderingSets = cmds.listSets(object=shape, extendToShape=True, type=1)
    print allSets
    if allSets:
        for s in allSets:
            if s not in renderingSets:
                cmds.delete(s)

    unusedMatsList = [
        '*Mouth*', '*Teeth*', '*Pupils*', '*EyeMoisture*', '*Cornea*',
        '*Irises*', '*Sclera*'
    ]
    for mat in unusedMatsList:
        unusedFaces = mayaUtils.GetFacesByMatsWildcard(shape, mat)
        if unusedFaces:
            cmds.delete(unusedFaces)

    mayaUtils.CleanUnusedMaterials()

    mayaUtils.AppendShadingGroupByMatWildcard(shape, '*Face*', '*Lips*')
    mayaUtils.AppendShadingGroupByMatWildcard(shape, '*Face*', '*Ears*')
    mayaUtils.AppendShadingGroupByMatWildcard(shape, '*Face*', '*EyeSocket*')

    mayaUtils.AppendShadingGroupByMatWildcard(shape, '*Legs*', '*Toenails*')
    mayaUtils.AppendShadingGroupByMatWildcard(shape, '*Arms*', '*Fingernails*')

    mayaUtils.ArrangeUVByMatWildcard(shape,
                                     '*Torso*',
                                     su=0.5,
                                     sv=0.5,
                                     u=0.5,
                                     v=0.5)
    mayaUtils.ArrangeUVByMatWildcard(shape,
                                     '*Face*',
                                     su=0.5,
                                     sv=0.5,
                                     u=0.0,
                                     v=0.5)
    mayaUtils.ArrangeUVByMatWildcard(shape,
                                     '*Legs*',
                                     su=0.5,
                                     sv=0.5,
                                     u=0.5,
                                     v=0.0)
    mayaUtils.ArrangeUVByMatWildcard(shape,
                                     '*Arms*',
                                     su=0.5,
                                     sv=0.5,
                                     u=0.0,
                                     v=0.0)

    mayaUtils.AppendShadingGroupByMatWildcard(shape, '*Torso*', '*Legs*')
    mayaUtils.AppendShadingGroupByMatWildcard(shape, '*Torso*', '*Arms*')
    mayaUtils.AppendShadingGroupByMatWildcard(shape, '*Torso*', '*Face*')

    mayaUtils.RenameMaterial('*Torso*', 'Body')
    mayaUtils.CleanUnusedMaterials()
    print 'FINISHED OptimizeBodyMeshForBaking(): time taken %.02f seconds' % (
        time.clock() - start)
    mayaUtils.NotifyWithSound()
Exemplo n.º 26
0
    #selects current joint and sets it as variable tempSel_Parent
    cmds.select(i)
    tempSel_Parent = cmds.ls(sl=True)

    #selects child joint and sets it as variable tempSel_AimAt
    tempSel_AimAt = cmds.listRelatives(type='joint')

    #creates square NURBS curve and deletes it's history
    cmds.select(d=True)
    cmds.curve(d=1,
               p=[(-0.5, 0, .5), (-0.5, 0, -.5), (.5, 0, -.5), (.5, 0, .5),
                  (-0.5, 0, .5)],
               name='CTRL_' + (i))
    cmds.rotate(0, 0, 90)
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
    cmds.bakePartialHistory()

    #makes a group and makes the controller a child of the PIVOT group
    cmds.group(em=True, name='PIVOT_' + (i))
    cmds.parent('CTRL_' + (i), 'PIVOT_' + (i))

    #makes parent constraint for controller location
    cmds.parentConstraint(tempSel_Parent,
                          'PIVOT_' + (i),
                          mo=False,
                          name='tempParentConstraint' + (i))
    cmds.delete('tempParentConstraint' + (i))

    #makes aim constraint for controller orientation
    cmds.aimConstraint(tempSel_AimAt,
                       'PIVOT_' + (i),
Exemplo n.º 27
0
def updateMesh(path, backup=True):
    '''
    Function that interates through all the .txt files in the path.This function creates a reference, then connects the outMesh to the inMesh and 
    removes the reference.
    '''
    print '___ '
    if len(path)>0:
        #list the files in the "path"
        update_files = os.listdir(path)
        base_mesh = ''
        out_dict  = ''
        #Build the full path
        outPath   =os.path.join(path,'outmesh.txt')
        print outPath
         
        #test that outmesh.txt exists, this file is key and needs to be in the path directory
        if os.path.exists(outPath) == True:
            out_dict = makeFileDict(outPath)
            print out_dict
            #read each file in the mesh_update_info path
            for i in update_files:
                #skip and files that start with '.' and skip the "outmesh.txt" file
                if i[0] != '.' and i != 'outmesh.txt':
                    #make sure that the outmesh.txt has been read in, in case that file doesn't exists
                    if len(out_dict) != 0:
                        #read in the data from the current update file 
                        in_dict  =  makeFileDict(os.path.join(path,i))
                        #open the file specified in "path"
                        print 'file:  ', in_dict['path'] 
                        cmds.file(in_dict['path'], o=True, f=True)
                        print in_dict['path']
                        if backup == True:
                            #make sure 'mesh_update_scene_backup' folder exists in the path
                            backupCMD(in_dict['path'])
                            #This call to path will return unexpected results if there are more than one '.' in the name
                            name        = os.path.basename(in_dict['path'].split('.')[0])
                            #build the save path
                            savepath    = os.path.join(os.path.dirname(in_dict['path']), 'mesh_update_scene_backup')
                            # get the current name of the file
                            currentName = cmds.file(query=True,exn=True)
                            #get the file type
                            fileType    = cmds.file(query=True, type=True)[0]
                            #name this file, save it into the backup folder then rename it back to its original name
                            cmds.file(rename = os.path.join(savepath, name + '_backup'))
                            cmds.file(save=True, type=fileType)
                            cmds.file(rename=currentName)
                        
                        #reference in the outmesh file
                        ref_file = cmds.file(out_dict['path'],r=True ,namespace = out_dict['ref'], type='mayaBinary')
                        #interate through all the enteries in the update file
                        for geo in in_dict:
                            #skip path and ref entries
                            if geo != 'path' and geo != 'ref':
                                #None is specified when geo doesn't exist in the scene
                                if in_dict[geo] != 'None':
                                    #find the skinCluster on the specified geo
                                    skin = mm.eval('findRelatedSkinCluster("'+ in_dict[geo] +'")')
                                    #get the shapeNode 
                                    inShape  = cmds.listRelatives(in_dict[geo], shapes=True)[0]
                                    #if the object is skinned, the shapeOrig is required for connection
                                    if len(skin) != 0:
                                        inShape  = cmds.listRelatives(in_dict[geo], shapes=True)[1]
                                    #get the shapeNode for the .outMesh connection
                                    outShape = cmds.listRelatives(out_dict['ref'] +':'+out_dict[geo], type ='shape')[0]
                                    
                                    #connect the "outShape.outMesh" to the "inShape.inMesh" 
                                    cmds.connectAttr(outShape + '.outMesh',inShape + '.inMesh')
                                    print inShape
                                    #bake the history into the inShape, if this isn't done everything reverts back to it's state post connection
                                    cmds.bakePartialHistory(inShape)
                        #remove the reference
                        cmds.file(ref_file , rr=True)
                        cmds.file(save=True, type=fileType)
                    else:
                        print '!!!!! outmesh.txt file not found, update halted !!!!!'
                else:
                    print '3'
        else:
            print '1'
    else:
        print 'No valid path exists!'
Exemplo n.º 28
0
def deleteHist(objLs, partial=False):
    for obj in objLs:
        if partial:
            mc.bakePartialHistory(ppt=True)
        else:
            mc.delete(ch=True, c=True, e=True, cn=True)
Exemplo n.º 29
0
    def __init__(self, parent=None):
        # すでにウィンドウ開いていた場合閉じておく
        self.deleteInstances()

        selList = om2.MGlobal.getActiveSelectionList()

        mDagPath, _ = selList.getComponent(0)

        self.targetObj = om2.MFnTransform(mDagPath)
        self.targetObjMesh = om2.MFnMesh(mDagPath)

        self.targetObjVtxCount = self.targetObjMesh.numVertices
        self.targetObjVtxIdxList = xrange(self.targetObjVtxCount)

        mObj = mDagPath.node()

        # ターゲットのオブジェクト名が変更されたcallbackを受けて実行する関数を登録
        self.callbackID_nameChanged = om2.MNodeMessage.addNameChangedCallback(
            mObj, self.targetObjNameChangedCallback)

        super(kkDisplayVertexColorSeparatelyWindow, self).__init__(parent)
        self.setupUI()

        # displayColorsを取得して残しておきつつ、確認できるようにカラー表示をONにしておく
        self.attrDispColor = mc.getAttr("%s.displayColors" %
                                        self.targetObjMesh.fullPathName())
        mc.setAttr("%s.displayColors" % self.targetObjMesh.fullPathName(), 1)

        # colorMaterialChannelとmaterialBlendを取得して残しておきつつ変更する
        self.pOption_matChl = mc.polyOptions(q=True,
                                             colorMaterialChannel=True,
                                             gl=False)[0]
        self.pOption_matBld = mc.polyOptions(q=True,
                                             materialBlend=True,
                                             gl=False)[0]
        mc.polyOptions(colorMaterialChannel="ambientDiffuse", gl=False)
        mc.polyOptions(materialBlend="overwrite", gl=False)

        # 中間オブジェクトがあるか確認
        historyList = mc.bakePartialHistory(self.targetObjMesh.fullPathName(),
                                            q=True,
                                            prePostDeformers=True) or []
        if len(historyList) > 0:
            self.hasIntermediateObject = True

        # 実行前にアクティブになっていたベースのcolorSetを保存しておく
        curColorSetList = mc.polyColorSet(q=True, currentColorSet=True)

        # colorSerがない場合生成する
        if curColorSetList == None:
            curColorSet = mc.polyColorSet(create=True,
                                          colorSet="colorSet",
                                          clamped=True,
                                          representation="RGBA")[0]
        else:
            curColorSet = curColorSetList[0]

        self.baseColorSet = curColorSet
        self.baseColorSerRep = mc.polyColorSet(q=True,
                                               currentColorSet=True,
                                               representation=True)
        self.baseColorBeforeEdit = self.targetObjMesh.getVertexColors(
            self.baseColorSet)

        # self.baseColorSerRepで得たベースのcolorSetの種類を元に各色を表現するためのtempのcolorSetを追加
        self.checkColorSet()

        # 現在のcolorSetの色を取得して、各色のcolorSetを編集
        # 中間オブジェクトある場合、そのcolorSet編集時にpolyColorPerVertexノードが作られる
        self.getBaseVertexColorData()

        # 中間オブジェクトある場合、念のため途中でヒストリ削除されてノードが消えた時に復活させるjobを設定
        if self.hasIntermediateObject == True:
            self.setDeleteNodeJobs()

        # 別シーンが開かれたらウィンドウを閉じるscriptJobを登録する
        self.otherSceneOpenedJob()

        if self.hasIntermediateObject == True:
            self.jobNum_attributeChange_Base = mc.scriptJob(
                attributeChange=[
                    "tmpColorSet_Base_Node.vertexColor", self.vtxColBase
                ],
                allChildren=True,
                parent="kkDisplayVertexColorSeparatelyWindow",
                compressUndo=True,
                runOnce=True)

        else:
            self.jobNum_attributeChange_Base = mc.scriptJob(
                attributeChange=[
                    "%s.colorSet" % self.targetObjMesh.fullPathName(),
                    self.vtxColBase
                ],
                allChildren=True,
                parent="kkDisplayVertexColorSeparatelyWindow",
                compressUndo=True,
                runOnce=True)
Exemplo n.º 30
0
def ManualTransferAttributesForBorderVerts(targetMesh, srcMesh):
    cmds.select(clear=True)
    borderVertsList = GetBorderVertices(targetMesh)
    borderVertsList = cmds.filterExpand(borderVertsList, sm=31, expand=True)

    bodySkinCluster = GetSkinCluster(srcMesh)
    genitaliaSkinCluster = GetSkinCluster(targetMesh)

    #transfer attributes manually
    for v in borderVertsList:
        pos = cmds.pointPosition(v, world=True)
        #print pos
        closestVert = GetClosestVertex(srcMesh, pos)
        closestVertPos = cmds.xform(closestVert, t=True, ws=True, q=True)
        closestVertNormal = cmds.polyNormalPerVertex(closestVert,
                                                     query=True,
                                                     xyz=True)

        # set position
        cmds.move(closestVertPos[0],
                  closestVertPos[1],
                  closestVertPos[2],
                  v,
                  absolute=True,
                  worldSpace=True)
        # set normal
        cmds.polyNormalPerVertex(v,
                                 xyz=(closestVertNormal[0],
                                      closestVertNormal[1],
                                      closestVertNormal[2]))

        referenceVertInfluences = cmds.skinPercent(bodySkinCluster,
                                                   closestVert,
                                                   query=True,
                                                   transform=None,
                                                   ignoreBelow=0.00001)

        targetInfluences = cmds.skinCluster(genitaliaSkinCluster,
                                            query=True,
                                            influence=True)

        targetTransformValues = []

        for i in referenceVertInfluences:
            if i not in targetInfluences:
                cmds.skinCluster(genitaliaSkinCluster,
                                 e=True,
                                 addInfluence=i,
                                 weight=0.0)
                #print i
            referenceInfluenceValuePerVertex = cmds.skinPercent(
                bodySkinCluster,
                closestVert,
                query=True,
                transform=i,
                transformValue=True)
            targetTransformValues.append((i, referenceInfluenceValuePerVertex))

        #print targetTransformValues

        # set weight
        cmds.skinPercent(genitaliaSkinCluster,
                         v,
                         transformValue=targetTransformValues)

    cmds.bakePartialHistory(targetMesh, prePostDeformers=True)
Exemplo n.º 31
0
def createBlocks(*args):
    ''' -Query GUI Values- '''
    horizontalCount = cmds.intField('horizontalCount', q=True, value=True)
    verticalCount = cmds.intField('verticalCount', q=True, value=True)
    blockScaling = cmds.floatField('blockScaling', q=True, value=True)
    blockSpacing = cmds.floatField('blockSpacing', q=True, value=True)
    blockBevel = cmds.intField('blockBevel', q=True, value=True)
    addCollision = cmds.checkBox('addCollision', q=True, value=True)
    ''' -Create Geo Grp- '''
    if cmds.objExists('blockMainGeo_grp'):
        blockMainGeoGrp = 'blockMainGeo_grp'

    else:
        blockMainGeoGrp = cmds.group(n='blockMainGeo_grp', em=True)
    ''' -Create Rig Grp- '''
    if cmds.objExists('blockMainRig_grp'):
        blockMainRigGrp = 'blockMainRig_grp'

    else:
        blockMainRigGrp = cmds.group(n='blockMainRig_grp', em=True)
    ''' -Create Controller Grp- '''
    if cmds.objExists('blockController_grp'):
        blockControllerGrp = 'blockController_grp'

    else:
        blockControllerGrp = cmds.group(n='blockController_grp', em=True)
    ''' -Create Geo Layer- '''
    if cmds.objExists('blockGeo_layer'):
        blockGeoLayer = 'blockGeo_layer'

    else:
        blockGeoLayer = cmds.createDisplayLayer(n='blockGeo_layer')
    ''' -Create Controller Layer- '''
    if cmds.objExists('blockController_layer'):
        blockControllerLayer = 'blockController_layer'

    else:
        blockControllerLayer = cmds.createDisplayLayer(
            n='blockController_layer')

    cmds.editDisplayLayerMembers(blockControllerLayer, blockControllerGrp)
    ''' -Build Controller- '''
    if cmds.objExists('blockTop*_controller'):
        cmds.select('blockTop*_controller')
        versionCount = cmds.ls(sl=True)
        versionCount = len(versionCount) + 1
        versionCount = str(versionCount)

    else:
        versionCount = '1'

    blockTopScaleX = (blockScaling * horizontalCount * 0.5) + (
        (horizontalCount - 1) * blockSpacing * 0.5) + blockScaling
    blockTopScaleZ = (blockScaling * verticalCount * 0.5) + (
        (verticalCount - 1) * blockSpacing * 0.5) + blockScaling

    blockTopController = cmds.curve(n='blockTop' + versionCount +
                                    '_controller',
                                    p=[(-blockTopScaleX, 0, -blockTopScaleZ),
                                       (blockTopScaleX, 0, -blockTopScaleZ),
                                       (blockTopScaleX, 0, blockTopScaleZ),
                                       (-blockTopScaleX, 0, blockTopScaleZ),
                                       (-blockTopScaleX, 0, -blockTopScaleZ)],
                                    d=1)

    blockController = cmds.circle(n='block' + versionCount + '_controller',
                                  nr=[0, 1, 0],
                                  r=blockScaling,
                                  ch=False)[0]
    radiusScaleAttr = createAttr(blockController, 'radiusScale', [0, 1])

    cmds.setAttr(blockController + '.translateY', blockScaling * 10)
    cmds.makeIdentity(blockController, apply=True, t=True, r=True, s=True, n=0)

    cmds.parent(blockController, blockTopController)
    cmds.parent(blockTopController, blockControllerGrp)

    blockRigTop = cmds.group(n='blockRigTop' + versionCount + '_grp',
                             p=blockMainRigGrp,
                             em=True)
    cmds.parentConstraint(blockTopController, blockRigTop, mo=True)
    cmds.scaleConstraint(blockTopController, blockRigTop, mo=True)

    blockCount = horizontalCount * verticalCount
    ''' -Progress Bar- '''
    progressName = progressBar('Building Blocks', blockCount)

    for block in range(blockCount):
        ''' -Block Count- '''
        if cmds.objExists('block*_geo'):
            cmds.select('block*_geo')
            blockVersion = cmds.ls(sl=True)
            blockVersion = len(blockVersion) + 1
            blockVersion = str(blockVersion)

        else:
            blockVersion = '1'

        blockGeoGrp = cmds.group(n='blockGeo' + blockVersion + '_grp',
                                 p=blockMainGeoGrp,
                                 em=True)
        blockRigGrp = cmds.group(n='blockRig' + blockVersion + '_grp',
                                 p=blockRigTop,
                                 em=True)
        ''' -Create Block- '''
        blockGeo = cmds.polyCube(n='block' + blockVersion + '_geo',
                                 w=blockScaling,
                                 h=blockScaling,
                                 d=blockScaling,
                                 ch=False)[0]

        cmds.parent(blockGeo, blockGeoGrp)
        cmds.editDisplayLayerMembers(blockGeoLayer, blockGeo)
        ''' -Extrude the Top poly- '''
        extrudeTop = cmds.polyExtrudeFacet(blockGeo + '.f[1]')[0]
        cmds.setAttr(extrudeTop + ".localScale", 0.7, 0.7, 0.7, type='double3')
        cmds.setAttr(extrudeTop + ".localTranslate",
                     0,
                     0,
                     blockScaling * 0.05,
                     type='double3')
        ''' -Translate Block to Ground Level- '''
        blockTop = cmds.xform(blockGeo + '.f[9]', ws=True, q=True, t=True)
        cmds.setAttr(blockGeo + '.translateY', -blockTop[1])
        ''' -Setup Distance- '''
        blockBaseLoc = cmds.spaceLocator(n='blockBase' + blockVersion +
                                         '_loc')[0]
        blockEndLoc = cmds.spaceLocator(n='blockEnd' + blockVersion +
                                        '_loc')[0]
        blockTopLoc = cmds.spaceLocator(n='blockTop' + blockVersion +
                                        '_loc')[0]
        blockLoc = cmds.spaceLocator(n='block' + blockVersion + '_loc')[0]

        cmds.parent(blockBaseLoc, blockEndLoc, blockLoc, blockTopLoc,
                    blockRigGrp)

        cmds.parentConstraint(blockController, blockTopLoc, blockEndLoc)
        cmds.setAttr(blockTopLoc + '.translateY', blockScaling * 10)
        ''' -Create Top Collision- '''
        if addCollision == True:

            collisionBlockGeo = cmds.duplicate(blockGeo,
                                               n='collisionBlock' +
                                               blockVersion + '_geo')[0]
            cmds.delete(collisionBlockGeo + '.f[0]',
                        collisionBlockGeo + '.f[2:5]')

            cmds.makeIdentity(collisionBlockGeo,
                              apply=True,
                              t=True,
                              r=True,
                              s=True,
                              n=0)
            cmds.makeIdentity(collisionBlockGeo)

            cmds.delete(collisionBlockGeo, ch=True)
            ''' -Collision Dynamics- '''
            collisionDyn = cmds.rigidBody(collisionBlockGeo,
                                          n='collisionBlock' + blockVersion +
                                          '_dyn',
                                          active=False)
            cmds.hide(collisionBlockGeo)

            cmds.pointConstraint(blockLoc, collisionBlockGeo)
        ''' -Zero Out Block Values- '''
        cmds.makeIdentity(blockGeo, apply=True, t=True, r=True, s=True, n=0)
        cmds.makeIdentity(blockGeo)

        cmds.delete(blockGeo, ch=True)
        ''' -Create and Place Joints- '''
        cmds.select(cl=True)
        blockBaseJnt = cmds.joint(n='blockBase' + blockVersion + '_jnt')
        blockBottom = cmds.xform(blockGeo + '.f[0]', ws=True, q=True, t=True)
        cmds.setAttr(blockBaseJnt + '.translateY', blockBottom[1])

        blockEndJnt = cmds.joint(n='blockEnd' + blockVersion + '_jnt')
        cmds.setAttr(blockEndJnt + '.translateY', -blockBottom[1])

        cmds.setAttr(blockBaseJnt + '.radius', blockScaling * 0.1)
        cmds.setAttr(blockEndJnt + '.radius', blockScaling * 0.1)

        cmds.parentConstraint(blockLoc, blockEndJnt)
        cmds.parent(blockBaseJnt, blockRigGrp)
        ''' -Skin Block to Joints- '''
        blockSkin = cmds.skinCluster(blockGeo,
                                     blockBaseJnt,
                                     blockEndJnt,
                                     n='block' + blockVersion + '_skin')[0]

        cmds.skinPercent(blockSkin,
                         blockGeo + '.vtx[0:1]',
                         blockGeo + '.vtx[6:7]',
                         transformValue=[(blockBaseJnt, 1), (blockEndJnt, 0)])

        cmds.skinPercent(blockSkin,
                         blockGeo + '.vtx[2:5]',
                         blockGeo + '.vtx[8:11]',
                         transformValue=[(blockBaseJnt, 0), (blockEndJnt, 1)])
        ''' -Bevel the Block- '''
        if blockBevel >= 1:
            cmds.polyBevel(blockGeo + '.e[0:19]',
                           offset=0.08,
                           offsetAsFraction=1,
                           autoFit=1,
                           segments=blockBevel,
                           worldSpace=1,
                           uvAssignment=0,
                           fillNgons=1,
                           mergeVertices=1,
                           mergeVertexTolerance=0.0001,
                           smoothingAngle=30,
                           miteringAngle=180,
                           angleTolerance=180,
                           ch=1)

            cmds.bakePartialHistory(blockGeo, prePostDeformers=True)
        ''' -Radius Scale- '''
        try:
            blockScaleCurve1 = blockScaleCurve1

            blockEndConstraint = cmds.parentConstraint(blockEndLoc,
                                                       name=True,
                                                       q=True)
            blockEndAlias = con = cmds.parentConstraint(blockEndLoc,
                                                        weightAliasList=True,
                                                        q=True)

            blockEndConstraint1 = blockEndConstraint + '.' + blockEndAlias[0]
            blockEndConstraint2 = blockEndConstraint + '.' + blockEndAlias[1]

            cmds.connectAttr(blockScaleCurve1 + '.output', blockEndConstraint1)
            cmds.connectAttr(blockScaleCurve2 + '.output', blockEndConstraint2)

        except:
            blockEndConstraint = cmds.parentConstraint(blockEndLoc,
                                                       name=True,
                                                       q=True)
            blockEndAlias = con = cmds.parentConstraint(blockEndLoc,
                                                        weightAliasList=True,
                                                        q=True)

            blockEndConstraint1 = blockEndConstraint + '.' + blockEndAlias[0]
            blockEndConstraint2 = blockEndConstraint + '.' + blockEndAlias[1]

            cmds.setDrivenKeyframe(blockEndConstraint1,
                                   cd=radiusScaleAttr,
                                   dv=0,
                                   v=1)
            cmds.setDrivenKeyframe(blockEndConstraint1,
                                   cd=radiusScaleAttr,
                                   dv=1,
                                   v=0)

            cmds.setDrivenKeyframe(blockEndConstraint2,
                                   cd=radiusScaleAttr,
                                   dv=0,
                                   v=0)
            cmds.setDrivenKeyframe(blockEndConstraint2,
                                   cd=radiusScaleAttr,
                                   dv=1,
                                   v=1)

            blockScaleCurve1 = cmds.listConnections(blockEndConstraint1,
                                                    source=True,
                                                    type="animCurve")[0]
            blockScaleCurve2 = cmds.listConnections(blockEndConstraint2,
                                                    source=True,
                                                    type="animCurve")[0]
        ''' -Find Distance- '''
        blockDistance = cmds.shadingNode('distanceBetween',
                                         asUtility=True,
                                         name='block' + blockVersion +
                                         '_distance')

        blockBaseLocShape = cmds.listRelatives(blockBaseLoc, shapes=True)[0]
        blockEndLocShape = cmds.listRelatives(blockEndLoc, shapes=True)[0]

        cmds.connectAttr(blockBaseLocShape + '.worldPosition [0]',
                         blockDistance + '.point1')
        cmds.connectAttr(blockEndLocShape + '.worldPosition [0]',
                         blockDistance + '.point2')
        ''' -Translate Box Anim- '''
        cmds.setDrivenKeyframe(blockLoc + '.translateY',
                               cd=blockDistance + '.distance',
                               dv=blockScaling * 10,
                               v=blockScaling * 0)
        cmds.setDrivenKeyframe(blockLoc + '.translateY',
                               cd=blockDistance + '.distance',
                               dv=blockScaling * 9.8,
                               v=-blockScaling * 0.2)

        cmds.setDrivenKeyframe(blockLoc + '.translateY',
                               cd=blockDistance + '.distance',
                               dv=blockScaling * 5.2,
                               v=blockScaling * 5.2)
        cmds.setDrivenKeyframe(blockLoc + '.translateY',
                               cd=blockDistance + '.distance',
                               dv=blockScaling * 5,
                               v=blockScaling * 5)

        cmds.setDrivenKeyframe(blockLoc + '.translateY',
                               cd=blockDistance + '.distance',
                               dv=blockScaling * 0.2,
                               v=-blockScaling * 0.2)
        cmds.setDrivenKeyframe(blockLoc + '.translateY',
                               cd=blockDistance + '.distance',
                               dv=blockScaling * 0,
                               v=blockScaling * 0)
        ''' -Block Layout- '''
        blockScaling2 = blockScaling + blockSpacing

        if block == 0:
            traX = ((horizontalCount - 1) * -0.5 * blockScaling2)
            traZ = ((verticalCount - 1) * -0.5 * blockScaling2)

            cmds.setAttr(blockRigGrp + '.translate', traX, 0, traZ)
            horizontalCountDown1 = horizontalCount - 1
            horizontalCountDown2 = horizontalCount
            verticalCountDown = 0

        else:
            if horizontalCountDown1 == 0:
                horizontalCountDown1 = horizontalCount
                horizontalCountDown2 = horizontalCount
                verticalCountDown = verticalCountDown - 1

            horizontalCountDown1 = horizontalCountDown1 - 1
            horizontalCountDown2 = horizontalCountDown2 - 1

            traX = (((horizontalCount - 1) * -0.5 + horizontalCountDown2) *
                    blockScaling2)
            traZ = (((verticalCount - 1) * -0.5 - verticalCountDown) *
                    blockScaling2)

            cmds.setAttr(blockRigGrp + '.translate', traX, 0, traZ)

        cmds.parentConstraint(blockController, blockTopLoc, mo=True)

        cmds.hide(blockRigGrp)
        cmds.progressBar(progressName, e=True, step=1)
    ''' -Close Progress Bar- '''
    progressBar('', 0)
mc.color("c_ForegroundMatte", rgb=(1, 0.5, 0.5))
mc.color("c_MidgroundMatte",  rgb=(1, 0.5, 1))
mc.color("c_BackgroundMatte", rgb=(0, 1, 2))

#create a square control
mc.circle(n="POS", nr = (0,1,0,), d = 1, s=4, r = 1)
mc.scale(7876, 7876, 7876, "POS")
mc.rotate(0, "45deg", 0,  "POS")

# select backgrounds and the controls
mc.select(matteNames, ctrlNames, "POS", r=True )
#freeze transformations
mc.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
#delete history
mc.bakePartialHistory(matteNames, ctrlNames, "POS", prePostDeformers=True)
# clear selection
mc.select(clear=True)

#parent cylinders to controls

inc = 0

for item in range(3):
    
    connection = mc.parentConstraint(ctrlNames[inc], matteNames[inc], mo=True, weight=1)
    mc.scaleConstraint(ctrlNames[inc], matteNames[inc], mo=True, weight=1)
    inc = inc + 1
         
#group the geo
mc.group(matteNames, n="GEO_fixed")