選択したMeshグループAからBへスキンウェイトを全部コピーMEL

Meshグループに無数にMeshがはいっててスキンウェイトをコピーするのがめんどくさくなったから書いたよ

Aのメッシュグループから
Bのメッシュグループにコピーしていく

動作はちょっと逆で
Bのグループのメッシュ名をループして
Aのグループのメッシュ名にあるか探す
あったらスキンウェイトコピー
なかったらrejectedリストに入れてます。
最後にrejectedListを表示するのでスキンウェイトしなかったメッシュのリストが出ます。

// SkinWeightCopy First Select MeshGroup to Second Select MeshGroup 
string $selectedArrFUllPath[] = `ls -long -sl`;
print($selectedArrFUllPath);

string $FirstSelect=$selectedArrFUllPath[0];

string $SecondSelect=$selectedArrFUllPath[1];

string $rejectArr[];

string $inputNodes[] = `ls -type transform -long -dag $FirstSelect`;
string $destNodes[] = `ls -type transform -long -dag $SecondSelect`;

$inputNodeslong=size($inputNodes);
$destNodeslong=size($destNodes);

string $buffer[];
string $buffer_i[];
$finded = 0;
for($d = 0; $d <$destNodeslong;$d++){
    string $destNode_name=$destNodes[$d];
    
    if($destNode_name==$SecondSelect){
            
    }else{
        print("$destNode_name= "+$destNode_name+"\n");
        
        $numTokens = `tokenize $destNode_name "|" $buffer`;
        $bufferlong=size($buffer);
        string $destNode_name_Short = $buffer[$bufferlong-1]+"";
        print("$destNode_name_Short= "+$destNode_name_Short+"\n");
        $finded = 0;
        for($i = 0; $i <$inputNodeslong;$i++){
            string $inputNode_name=$inputNodes[$i];
            $numTokens_i = `tokenize $inputNode_name "|" $buffer_i`;
            $bufferlong_i=size($buffer_i);
            string $inputNode_name_Short = $buffer_i[$bufferlong_i-1]+"";
            print("$inputNode_name_Short= "+$inputNode_name_Short+"\n");
                
            //$index=`gmatch $inputNode_name $destNode_name_Short`;
            //if($index > 0){
            if($inputNode_name_Short==$destNode_name_Short){
                //$blendShapeName = $blendshapeRet_name;
                print("$destNode_name= "+$destNode_name+" isHit!! "+"\n");
                select -r $inputNode_name;
                select -add $destNode_name;
                copySkinWeights  -noMirror -surfaceAssociation closestPoint -influenceAssociation closestJoint;
                //copySkinWeights -noMirror -surfaceAssociation closestPoint -influenceAssociation closestJoint -sourceSkin $inputNode_name -destinationSkin $destNode_name;
                $finded = 1;
            }
        }
        if($finded==0){
            $rejectArr[size($rejectArr)] = $destNode_name;
        }
    }
}
print("----rejected_list---start"+"\n");
print($rejectArr);
print("----rejected_list---end"+"\n");
select -r $FirstSelect ;
select -add $SecondSelect ;

メッシュグループ内のグループを無視できるように、MeshのTransformだけをフィルターした。

// SkinWeightCopy First Select MeshGroup to Second Select MeshGroup 
string $selectedArrFUllPath[] = `ls -long -sl`;
print($selectedArrFUllPath);

string $FirstSelect=$selectedArrFUllPath[0];

string $SecondSelect=$selectedArrFUllPath[1];

string $rejectArr[];

//string $inputNodes[] = `ls -type transform -long -dag $FirstSelect`;
//string $destNodes[] = `ls -type transform -long -dag $SecondSelect`;

string $inputNodes_mesh[] = `ls -type mesh -long -dag $FirstSelect`;
string $destNodes_mesh[] = `ls -type mesh -long -dag $SecondSelect`;

$inputNodes_meshlong=size($inputNodes_mesh);
$destNodes_meshlong=size($destNodes_mesh);

string $inputNodes[];
string $destNodes[];
clear $inputNodes;
clear $destNodes;
string $mesh;
string $parent;
for($d0 = 0; $d0 <$inputNodes_meshlong;$d0++){
    $mesh=$inputNodes_mesh[$d0];
    string $parentS[] = `listRelatives -parent -path -type transform $mesh`;
    $parent=$parentS[0];
    $inputNodes[size($inputNodes)] = $parent;
}
for($d0 = 0; $d0 <$destNodes_meshlong;$d0++){
    $mesh=$destNodes_mesh[$d0];
    string $parentS[] = `listRelatives -parent -path -type transform $mesh`;
    $parent=$parentS[0];
    $destNodes[size($destNodes)] = $parent;
}

print("$inputNodes= ------------------------------------------------ \n");
print($inputNodes);

print("$destNodes= ------------------------------------------------ \n");
print($destNodes);



$inputNodeslong=size($inputNodes);
$destNodeslong=size($destNodes);

string $buffer[];
string $buffer_i[];
$finded = 0;
for($d = 0; $d <$destNodeslong;$d++){
    string $destNode_name=$destNodes[$d];
    
    if($destNode_name==$SecondSelect){
            
    }else{
        print("$destNode_name= "+$destNode_name+"\n");
        
        $numTokens = `tokenize $destNode_name "|" $buffer`;
        $bufferlong=size($buffer);
        string $destNode_name_Short = $buffer[$bufferlong-1]+"";
        print("$destNode_name_Short= "+$destNode_name_Short+"\n");
        $finded = 0;
        for($i = 0; $i <$inputNodeslong;$i++){
            string $inputNode_name=$inputNodes[$i];
            $numTokens_i = `tokenize $inputNode_name "|" $buffer_i`;
            $bufferlong_i=size($buffer_i);
            string $inputNode_name_Short = $buffer_i[$bufferlong_i-1]+"";
            print("$inputNode_name_Short= "+$inputNode_name_Short+"\n");
                
            //$index=`gmatch $inputNode_name $destNode_name_Short`;
            //if($index > 0){
            if($inputNode_name_Short==$destNode_name_Short){
                //$blendShapeName = $blendshapeRet_name;
                print("$destNode_name= "+$destNode_name+" isHit!! "+"\n");
                select -r $inputNode_name;
                select -add $destNode_name;
                copySkinWeights  -noMirror -surfaceAssociation closestPoint -influenceAssociation closestJoint;
                //copySkinWeights -noMirror -surfaceAssociation closestPoint -influenceAssociation closestJoint -sourceSkin $inputNode_name -destinationSkin $destNode_name;
                $finded = 1;
            }//if
        }//for
        if($finded==0){
            $rejectArr[size($rejectArr)] = $destNode_name;
        }//if
    }//if
}//for
print("----rejected_list---start"+"\n");
print($rejectArr);
print("----rejected_list---end"+"\n");
select -r $FirstSelect ;
select -add $SecondSelect ;

maya mel python 環境変数 一覧 path MAYA_SCRIPT_PATH

maya mel python environment variables list path MAYA_SCRIPT_PATH

MEL

//getenv "MAYA_SCRIPT_PATH";//パスを確認

$sPath=`getenv "PATH"`;
print("$sPath= "+$sPath+"\n");
$sMAYA_SCRIPT_PATH=`getenv "MAYA_SCRIPT_PATH"`;
print("$sMAYA_SCRIPT_PATH= "+$sMAYA_SCRIPT_PATH+"\n");

$array = stringToStringArray($sMAYA_SCRIPT_PATH, ";");

for ($MSP in $array) {
    print($MSP+"\n");
}

Python

import os
print("------------------------PATH---------------------------")
ePath = os.environ["PATH"]
ePath_List=ePath.split(";")
for ePath_line in ePath_List:
    #for ev in environ:
    print(ePath_line)

print("------------------------MAYA_SCRIPT_PATH-----------------------------")

mayaScriptPath = os.environ["MAYA_SCRIPT_PATH"]
mayaScriptPath_List=mayaScriptPath.split(";")
for mayaScriptPath_line in mayaScriptPath_List:
    #for ev in environ:
    print(mayaScriptPath_line)

[Daz3D][Maya][Marvelous Designer] Das3D 4.22 Genesis9をMaya2022に持ってきてMarvelous Designerの服をスキニングしてコピースキンウェイトしたVol.02(まとめ)

このノード状態がキレイなので「bindPose1が一つだけ」キープしながらモデリング編集すること。

Genesis9 やったこと

—————————————-ここからはモデリングとする。——————————————–
Das3D 4.22 のGenesis9を
Maya2022に持ってきて

duplicateでスキンバインド外し=複製して
meshGroupのグループに
・genesis9のまつ毛や口のレイヤーも入れる(skinCluster初めから無いので)
・Marvelous Designerの服レイヤーも入れる
・highheelレイヤーも入れる
highheelの高さにhipとmeshGroupをmoveする。(オプション)
↑高さはBluePrintで変更可能

—————————————-ここまではモデリングとする。——————————————–

新しい方の骨とmeshGroupでバインド
↑ちゃんとしたバインドオプションが重要
cmds.skinBind()引数なしじゃclusterがダメ
genesis9からcopySkinWeightした

モデル編集後ファイル (自分用リンク)」

jennie9_6_v12z_v00122_dupGen9_Kihon.zip

#jennie9_6_v12z_v00122_dupGen9_Kihon__ModelEnd_SkinBindSkinWeight.py

def startSelectionToNewSkinCluster():
    selectList=cmds.ls(sl=1,long=1)
    print("selectList= "+str(selectList))
    # 全部必要だから引数にした
    Genesis9 = selectList[0]
    Genesis9_Mesh = selectList[1]
    Genesis9s = selectList[2]
    MeshGroup = selectList[3]
    #------------------------------------------------------------------------
    ModelEnd_SkinBind(Genesis9s,MeshGroup)
    ModelEnd_SkinWeight(Genesis9,Genesis9_Mesh,Genesis9s,MeshGroup)
    #------------------------------------------------------------------------
    
def ModelEnd_SkinBind(Genesis9s,MeshGroup):
    
    cmds.select(Genesis9s,MeshGroup)
    #MEL  (Script found in: C:/Program Files/Autodesk/Maya2022/scripts/others/newSkinCluster.mel)
    #newSkinCluster " -bindMethod 0  -normalizeWeights 1 -weightDistribution 0 -mi 3  -dr 4 -rui false -ihs , multipleBindPose, 0";
    
    #Python でMEL実行
    import maya.mel
    maya.mel.eval('newSkinCluster " -bindMethod 0  -normalizeWeights 1 -weightDistribution 0 -mi 3  -dr 4 -rui false -ihs , multipleBindPose, 0";')
    
    #Python  NG  'maya.cmds' has no attribute 'newSkinCluster' # 
    #cmds.newSkinCluster(" -bindMethod 0  -normalizeWeights 1 -weightDistribution 0 -mi 3  -dr 4 -rui false -ihs , multipleBindPose, 0")

    #import pymel.core as pm #OK
    #pm.mel.newSkinCluster(" -bindMethod 0  -normalizeWeights 1 -weightDistribution 0 -mi 3  -dr 4 -rui false -ihs , multipleBindPose, 0")
def ModelEnd_SkinWeight(Genesis9,Genesis9_Mesh,Genesis9s,MeshGroup):
    
    Genesis9_Low_skincluster = Get_SkinCluster(Genesis9_Mesh)
    print("Genesis9_Low_skincluster= "+str(Genesis9_Low_skincluster))
    
    MeshList = cmds.listRelatives(MeshGroup,shapes=0,fullPath=1)
    print("MeshList= "+str(MeshList))
    
    for closet_mesh in MeshList:
        closet_skinCluster = Get_SkinCluster(closet_mesh)
        print("closet_skinCluster= "+str(closet_skinCluster))
        
        # 元のスキンクラスターを服のスキンクラスターへコピースキンウェイト
        cmds.copySkinWeights(
            sourceSkin = Genesis9_Low_skincluster,
            destinationSkin = closet_skinCluster,
            noMirror=True,
            influenceAssociation="oneToOne",
            surfaceAssociation="closestPoint"
        )
    
def Get_SkinCluster(LowMeshTransformLong):
    # トランスフォームのシェイプノードを取得
    shapeList = cmds.listRelatives(LowMeshTransformLong, shapes=True, noIntermediate=True,fullPath=True)
    #print("shapeList= "+str(shapeList))
    # lowのヒストリーを取得し、スキンクラスターのみ取得
    historyList = cmds.listHistory(shapeList[0], pruneDagObjects=True, interestLevel=2)
    #print("historyList= "+str(historyList))
    skinclusterList = cmds.ls(historyList, type="skinCluster")
    #print("skinclusterList= "+str(skinclusterList))
    skincluster = skinclusterList[0]
    #print("skincluster= "+str(skincluster))
    return skincluster
    
startSelectionToNewSkinCluster()

完成ファイル (自分用リンク)

jennie9_6_v12z_v00127_Mouse_SW_Take2OK_Kihon_UE532ExportEnd.zip

[maya][mel] scriptedPanel のサンプルを動作させてみた。想像と違った。

I tried running the scriptedPanel sample.

// define callbacks for this type and make it a unique type
// as we don't want two panels sharing the same global data.

scriptedPanelType
    -ccb sampleCreateCallback
    -icb sampleInitCallback
    -acb sampleAddCallback
    -rcb sampleRemoveCallback
    -dcb sampleDeleteCallback
    -scb sampleSaveStateCallback
    -unique true
    "sampleScriptedPanelType6";


global proc sampleCreateCallback(string $panelName) {
//
//  Description:
//      Create any editors unparented here and do
//      any other initialization required.
//
//      In this example we will only declare a global array to
//        maintain some state information.
//
    global float $gSampleState[5];

}


global proc sampleInitCallback(string $panelName) {
//
//  Description:
//      Re-initialize the panel on file -new or file -open.
//
//      In this example we will only re-init the global array.
//
    global float $gSampleState[];

       $gSampleState[0] = 20.2;
       $gSampleState[1] = 50.5;
       $gSampleState[2] = 34.7;
       $gSampleState[3] = 2.0;
       $gSampleState[4] = 1.0;

}

global proc sampleAddCallback(string $panelName) {
//
//  Description:  Create UI and parent any editors.
//
    global float $gSampleState[];

    columnLayout -adj true topCol;
    separator -style "none" -h 10;
        frameLayout -l "Sliders" -mw 10;
            columnLayout -adj true sampleCol;
                separator -style "none" -h 10;

                floatSliderGrp -l "Property A" -f true
                    -v $gSampleState[0]
                    fsg1;
                floatSliderGrp -l "Property B" -f true
                    -v $gSampleState[1]
                    fsg2;
                floatSliderGrp -l "Property C" -f true
                    -v $gSampleState[2]
                    fsg3;
                separator -style "none" -h 10;
            setParent ..;
        setParent ..;

        separator -style "none" -h 10;
        frameLayout -l "Radio Buttons" -mw 10;
            columnLayout sampleCol2;
                separator -style "none" -h 10;
                radioButtonGrp -nrb 3
                    -l "Big Options"
                    -la3 "Option 1" "Option 2" "Option 3"
                    -select $gSampleState[3]
                    rbg;
                radioButtonGrp -nrb 3
                    -l "Little Options"
                    -la3 "Option 4" "Option 5" "Option 6"
                    -select $gSampleState[4]
                    rbg2;
                separator -style "none" -h 10;

}

global proc sampleRemoveCallback(string $panelName) {
//
//  Description:
//        Unparent any editors and save state if required.
//
        global float $gSampleState[];
       //  Scope the control names to this panel.
       //
       string $control = `scriptedPanel -q -control $panelName`;
       setParent $control;

       $gSampleState[0] = `floatSliderGrp -q -v fsg1`;
       $gSampleState[1] = `floatSliderGrp -q -v fsg2`;
       $gSampleState[2] = `floatSliderGrp -q -v fsg3`;
       $gSampleState[3] = `radioButtonGrp -q -sl rbg`;
       $gSampleState[4] = `radioButtonGrp -q -sl rbg2`;
}

global proc sampleDeleteCallback(string $panelName) {
//
//  Description:
//        Delete any editors and do any other cleanup required.

}

global proc string sampleSaveStateCallback(string $panelName) {
//
//  Description:
//        Return a string that will restore the current state
//        when it is executed.

        global float $gSampleState[];
       $indent = "\n\t\t\t";

       return ($indent+"$gSampleState[0]="+$gSampleState[0]+";" +
               $indent+"$gSampleState[1]="+$gSampleState[1]+";" +
               $indent+"$gSampleState[2]="+$gSampleState[2]+";" +
               $indent+"$gSampleState[3]="+$gSampleState[3]+";" +
               $indent+"$gSampleState[4]="+$gSampleState[4]+";" +
               $indent+"setSamplePanelState $panelName;\n" );
}

global proc setSamplePanelState( string $whichPanel ) {
//
//  Description:
//        This is a convenience proc to set the panel state from the
//        global array

        global float $gSampleState[];

       //  Scope the control names to this panel.
       //
       string $control = `scriptedPanel -q -control $whichPanel`;
       if ("" != $control) {
              setParent $control;

              floatSliderGrp -e -v $gSampleState[0] fsg1;
              floatSliderGrp -e -v $gSampleState[1] fsg2;
              floatSliderGrp -e -v $gSampleState[2] fsg3;
              if (0 != $gSampleState[3]) {
               radioButtonGrp -e -sl $gSampleState[3] rbg;
              };
           if (0 != $gSampleState[4]) {
               radioButtonGrp -e -sl $gSampleState[4] rbg2;
           }
       }
}


//  This script will create an unparented scripted panel, place it
//  in one window, remove it, and place it in another window then
//  return it to the first window.
//

//    Create unparented scripted panel
//
scriptedPanel -unParent -type "sampleScriptedPanelType6" -label "Sample" "sampleScriptedPanel6";

//    Create a couple of windows and parent the scripted panel to the first.
//
window "sampleWin6";
frameLayout -lv false -bv false frm;
scriptedPanel -e -parent "sampleWin6|frm" "sampleScriptedPanel6";
showWindow;
/*
window -w `window -q -w sampleWin` -h `window -q -h "sampleWin"` "sampleWin2";
frameLayout -lv false -bv false frm;
showWindow;
*/

[maya] よくあるtextFieldの入力をchangeCommandで受ける場合に必要なwindow object path のpythonの話

なんか引っかかってしまいがちな

どこにも書いてないウィンドウパスの話
MY_Export_window|MY_layout|pathTxtFld

    
def createWindow():
    MY_window = cmds.window("MY_Export_window", widthHeight=(400, 200))
    MY_layout = cmds.columnLayout("MY_layout",adjustableColumn=True, parent=MY_window)

    cmds.text (label="テキストを変更したら呼ばれるよ", align='left', parent=MY_layout)

    text_Field_id = cmds.textField("pathTxtFld",text=get_lastExportDirPath(),changeCommand=changeTextFld)
    print("text_Field_id= "+text_Field_id)

    cmds.showWindow(MY_window)
    
    return None

def changeTextFld(*arg):
    text_Field_id="MY_Export_window|MY_layout|pathTxtFld"
    print("text_Field_id= "+text_Field_id)
    pathTxtFld_value = cmds.textField(text_Field_id, q=True, text=True)
    print("pathTxtFld_value= "+pathTxtFld_value)
    set_lastExportDirPath(pathTxtFld_value)


createWindow()   

この時出力が

#columnLayoutに名前つけないとパスがこんな不安な感じになる。
text_Field_id= MY_Export_window|columnLayout118|pathTxtFld

#columnLayoutに名前つければとパスがこんな確実な感じになる。
text_Field_id= MY_Export_window|MY_layout|pathTxtFld

text_Field_id= MY_Export_window|MY_layout|pathTxtFld

[maya] MEL To Python2 From pymel For Maya 2016

MEL To Python2

これがシンプルな状態
import pymel.tools.mel2py as mel2py

pyCmd = mel2py.mel2pyStr(melCmd,pymelNamespace=’pm‘)

pyCmd = mel2py.mel2pyStr(melCmd,pymelNamespace=’cmds‘)でいいのかも

# -*- coding: cp932 -*-
import pymel.core as pm
import pymel.tools.mel2py as mel2py
import re
import math
import random
melCmd = """
$value1 = `floatFieldGrp -q -label "Frame range" -v1`;
	"""
pyCmd =  mel2py.mel2pyStr(melCmd,pymelNamespace='pm')

melで改行をしてる「+”¥n”」と「¥n」を けしてから

あと、出力結果がPyMelにならないようにしてみたり。

# -*- coding: cp932 -*-
import pymel.core as pm
import pymel.tools.mel2py as mel2py
import re
import math
import random
melCmd = """
global proc Generic_modelFileOpen()
{
  string $workspaceRoot = `workspace -q -rootDirectory`;
    string $motionFileDir= $workspaceRoot+"scenes/Generic_model_wep.mb";
    file -f -options "v=0;"  -ignoreVersion  -typ "mayaBinary" -o $motionFileDir;
        if(`file -q -writable`==1){
            select `ls -type joint`;
    
    string $joints[] =`ls -type joint`;
   int $jointsLength=size($joints);
    if($jointsLength==0)
    {
      print ("-------------------------joint nothing-----------------------------");
    }else{
        for	($joint in $joints)
        {
            //setKeyframe 0 ,1
            currentTime 0 ;
            setKeyframe -breakdown 0 -hierarchy none -controlPoints 0 -shape 0 -time 0 $joint;
           currentTime 1 ;
            setKeyframe -breakdown 0 -hierarchy none -controlPoints 0 -shape 0 -time 0 $joint;
        }
    }
    print("-------------------------joint-----------------------------");
    print($joint);
    print ("\n-------------------------joint-----------------------------");
    if($joint=="")
    {
    print ("-------------------------joint nothing-----------------------------");
    }
    ////////////////////////////////////////////////////////joint select
            print("TstanceFBXExport()");
           TstanceFBXExport();
    }
}
$value1 = `floatFieldGrp -q -label "Frame range" -v1`;
	"""
		
print "----------------mel code replace----------------------------"
#melCmd = melCmd.replace('$writable_bool','`file -q -writable`')
melCmd = melCmd.replace('"\n--', '"--')
melCmd = melCmd.replace('+"\n"', '')
melCmd = melCmd.replace('\n"', '"')
print("melCmd="+melCmd)
print "------------------------------------------------"
# mel2py.mel2pyStr  
pyCmd =  mel2py.mel2pyStr(melCmd,pymelNamespace='pm')
pyFixed_Dest = ""
#pyFixed_Dest = pyFixed_Dest + "# -*- coding: cp932 -*- \n"
pyFixed_Dest = pyFixed_Dest + "# -*- coding: utf-8 -*- \n"
#pyFixed_Dest = pyFixed_Dest + "# -*- coding: shift-jis -*- \n"
pyFixed_Dest = pyFixed_Dest + "from maya import cmds \n"
pyFixed_Dest = pyFixed_Dest + "from python import Debug \n"
pyFixed = pyCmd.replace("pymel.all","pymel.core")
pyFixed = pyFixed.replace("pm.pm.cmds","cmds")
pyFixed_Dest = pyFixed_Dest + pyFixed+"\n"
print "----------------------python sorce replace----------------------"

pyFixed_Dest = pyFixed_Dest.replace('import pymel.core as pm', 'import pymel.core as pm \nDebug=Debug.Debug')
pyFixed_Dest = pyFixed_Dest.replace('pm.file', 'cmds.file')
pyFixed_Dest = pyFixed_Dest.replace('pm.ls', 'cmds.ls')
pyFixed_Dest = pyFixed_Dest.replace('pm.select', 'cmds.select')
pyFixed_Dest = pyFixed_Dest.replace('pm.internalVar', 'cmds.internalVar')
pyFixed_Dest = pyFixed_Dest.replace('pm.keyframe', 'cmds.keyframe')
pyFixed_Dest = pyFixed_Dest.replace('pm.workspace', 'cmds.workspace')
pyFixed_Dest = pyFixed_Dest.replace('pm.getFileList', 'cmds.getFileList')
pyFixed_Dest = pyFixed_Dest.replace('=="1"', '==1')
pyFixed_Dest = pyFixed_Dest.replace('== "1"', '== 1')
pyFixed_Dest = pyFixed_Dest.replace('print("', 'print(u"')
pyFixed_Dest = pyFixed_Dest.replace('print "', 'print u"')
pyFixed_Dest = pyFixed_Dest.replace('pm.flushUndo()', 'cmds.flushUndo()')
pyFixed_Dest = pyFixed_Dest.replace('pm.parent', 'cmds.parent')
pyFixed_Dest = pyFixed_Dest.replace('pm.objExists', 'cmds.objExists')
pyFixed_Dest = pyFixed_Dest.replace('pm.rename', 'cmds.rename')
pyFixed_Dest = pyFixed_Dest.replace('pm.playbackOptions', 'cmds.playbackOptions')
pyFixed_Dest = pyFixed_Dest.replace('pm.mel.DebugLog', 'self.DebugLog')
pyFixed_Dest = pyFixed_Dest.replace('pm.currentTime', 'cmds.currentTime')
pyFixed_Dest = pyFixed_Dest.replace('pm.setKeyframe', 'cmds.setKeyframe')
#pyFixed_Dest = pyFixed_Dest.replace('maya.mel.eval("listRelatives -pa -ad `ls -sl -l`"', 'cmds.listRelatives(path=True, allDescendents =True,cmds.ls(selection=True, long=True))'))
#for Class
pyFixed_Dest = pyFixed_Dest.replace('():', '(self):')
pyFixed_Dest = pyFixed_Dest.replace('():', '(self):')
regex = r'print+'
#pattern = re.compile(regex)
#matchObj = pattern.match(pyFixed_Dest)
#matchObj = re.search(r'[a-z]+', pyFixed_Dest)

def repl(m):
    inner_word1 = list(m.group(1))  #prin(\w\W)    "prin" "t" " "    real ['t', ' ']
    #print("inner_word1= "+str(inner_word1))   
    inner_word2 = list(m.group(2))    #(.*)     something strings "----1-----" real ['u', '"', '-', '-', '-', '-', '1', '-', '-', '-', '-']
    #print("inner_word2= "+str(inner_word2))
    inner_word3 = list(m.group(3))
    #inner_word4 = list(m.group(4))    #(\")  double cout   real  ['"']
    print("inner_word123= "+str(inner_word1)+str(inner_word2)+str(inner_word3)+""+str(list(m.group(4)))+str(list(m.group(5)))+"")
    #print("inner_word2= "+str(inner_word1)+str(inner_word2)+str(inner_word3))
    #random.shuffle(inner_word)
    #back= m.group(1) + "".join(inner_word) + m.group(3)
    back="00000"+ str(m.end())
    back=m.group(1) +m.group(2)+"("+m.group(3)+m.group(4)+m.group(5)+")" #for print
    back=m.group(1) +"Debug.Log"+"("+m.group(3)+m.group(4)+m.group(5)+")"  #for Debug.Log  Debug Class is https://gist.github.com/whaison/fc625381dce126ca5d88d1f914ce89f0
    
    return back
#text = "Professor Abdolmalek, please report your absences promptly."
text = """
print "----1----"
print "----2----"
print "----3----"
print "----4----"
print "----5----"
print "----6----"
print "----7----"
	"""
#resub=re.sub(r"(\w)(\w+)(\w)", repl, text)
#resub=re.sub(r'(prin\w)', repl, text)
resub=re.sub(r'(.*)(prin\w\W)(.*)(\")(.*)', repl, text)

print("resub    --------------------output  start")
print resub 
#print resub[:m.start()]
#print resub[m.end():]
print("resub    --------------------output  end")
pyFixed_Dest=re.sub(r'(.*)(prin\w\W)(.*)(\")(.*)', repl, pyFixed_Dest)
print("resub  pyFixed_Dest  --------------------output  start")
print pyFixed_Dest 
#print resub[:m.start()]
#print resub[m.end():]
print("resub pyFixed_Dest   --------------------output  end")
print("search    --------------------output  start")
email = "tony@tiremove_thisger.net"
m = re.search(r'print*', text)
print text[:m.start()] +"print("+ text[m.end():]
print("search    --------------------output  end")
print "------------------------------------------------"
print pyFixed_Dest

出力結果

------------------------------------------------
# -*- coding: utf-8 -*- 
from maya import cmds 
from python import Debug 
import pymel.core as pm 
Debug=Debug.Debug

def Generic_modelFileOpen(self):
	
	workspaceRoot=str(cmds.workspace(q=1, rootDirectory=1))
	motionFileDir=workspaceRoot + "scenes/Generic_model_wep.mb"
	cmds.file(motionFileDir, ignoreVersion=1, typ="mayaBinary", options="v=0;", o=1, f=1)
	if cmds.file(q=1, writable=1) == 1:
		cmds.select(cmds.ls(type='joint'))
		joints=cmds.ls(type='joint')
		jointsLength=len(joints)
		if jointsLength == 0:
			Debug.Log(u"-------------------------joint nothing-----------------------------")
			
		
		else:
			for joint in joints:
				cmds.currentTime(0)
				#setKeyframe 0 ,1
				cmds.setKeyframe(joint, breakdown=0, hierarchy='none', shape=0, time=0, controlPoints=0)
				cmds.currentTime(1)
				cmds.setKeyframe(joint, breakdown=0, hierarchy='none', shape=0, time=0, controlPoints=0)
				
			
		Debug.Log(u"-------------------------joint-----------------------------")
		print joint
		Debug.Log(u"-------------------------joint-----------------------------")
		if joint == "":
			Debug.Log(u"-------------------------joint nothing-----------------------------")
			
		Debug.Log(u"TstanceFBXExport()")
		#//////////////////////////////////////////////////////joint select
		pm.mel.TstanceFBXExport()
		
	

value1=pm.floatFieldGrp("Frame range", q=1, v1=1, label=1)

[mel] 全リファレンスからオブジェクトを読み込み

[mel] 全リファレンスからオブジェクトを読み込み

[mel] import object from all references


global proc reference_to_object(){
    print("reference_to_object \n");
    
    string $refArr[] = `file -q -list`;
    //-list(-l)		query
    //すべてのファイルをリスト表示します。 すべてのセグメント/リファレンス ファイルの名前を文字配列で返し、複製は削除します。つまり、ファイルが複数回参照され、-withoutCopyNumber フラグを設定している場合は、シーン内で 1 度リスト表示されます。
    
    string $mayaAsciiArr[] = {};
    for ($ref in $refArr) {
        print($ref+" \n");
        string $fileNameExt[];
        $numTokens = `tokenize $ref "." $fileNameExt`;

        //_Motion.ma{1} の対応
        string $ExtArr[];
        $numTokens2 = `tokenize $fileNameExt[1] "{" $ExtArr`;
        //print("$fileNameExt[1]="+$fileNameExt[1]+" \n");
        /*
        if($fileNameExt[1]=="ma"){
            print("HIT!! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+ $ref+" \n");
            //Array Append Add
            $mayaAsciiArr[size($mayaAsciiArr)] = $ref;
        }else
        //_Motion.ma{1}  の対応
        */ 
        if($ExtArr[0]=="ma"){
            print("HIT!! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+ $ref+" \n");
            //Array Append Add
            $refFileName=$fileNameExt[0]+"."+$ExtArr[0];
            $mayaAsciiArr[size($mayaAsciiArr)] = $refFileName;
        }
    }
    string $Ref_MayaAsciiArr[] = {};
    for ($ref_mayaAscii in $mayaAsciiArr) {
        print("$ref_mayaAscii= "+ $ref_mayaAscii+" \n");
        string $sceneName=`file -q -sceneName`;
        print("$sceneName= "+$sceneName+" \n");
        
        if($ref_mayaAscii==$sceneName){
            print("-----------------------HIT $sceneName ------------------------------ \n");
        }else{
            $Ref_MayaAsciiArr[size($Ref_MayaAsciiArr)] = $ref_mayaAscii;
        }
    }
    //string $refArrStr = stringArrayToString($refArr,", \n");
    //print("$refArrStr= "+$refArrStr+ " \n");
    print("----------------------------------- $Ref_MayaAsciiArr ------------------------------------------ \n");
    for ($ref_mayaAscii_path in $Ref_MayaAsciiArr) {
        print("$ref_mayaAscii_path= "+$ref_mayaAscii_path+" \n");
        //=====================================================================
        file -importReference $ref_mayaAscii_path;
        //-importReference(-ir)		create
        //指定したファイル内でデータの周りのリファレンスのカプセル化を削除します。これにより指定したファイルの内容がカレント シーンの一部となり、オリジナル ファイルのすべてのリファレンスが失われます。 インポートされたリファレンスの名前が返されます。
        //====================================================================
    }
    print("----------------------------------- $Ref_MayaAsciiArr ------------------------------------------ \n");

    
}

//reference_to_object();

[Maya] .offsetParentMatrixをmel/Pythonスクリプトで取り扱う場合の研究

解決策から、、画像のような状態でよかった。関数はこんな感じ

global proc _Input_Lines(){
    print("_Input_Lines \n");
    
    _offsetParentMatrix_Value_Input("Dummy_calf_l",-15.216,0);
    _offsetParentMatrix_Value_Input("Dummy_calf_r",15.216,0);
    _offsetParentMatrix_Value_Input("Dummy_foot_l",-7.821,-0.047);
    _offsetParentMatrix_Value_Input("Dummy_foot_r",7.821,0.047);
}

global proc _offsetParentMatrix_Value_Input(string $NodeName,float $X,float $Y){
    print("_offsetParentMatrix_Value_Input \n");
    string $LocatorName="OffsetParentMatrix_locator_"+$NodeName;
    print("$LocatorName= "+$LocatorName+" \n");
    spaceLocator -position 0.0 0.0 0.0 -name $LocatorName;
    $LocatorNameTransX = $LocatorName+".translateX";
    print("$LocatorNameTransX= "+$LocatorNameTransX+" \n");
    setAttr $LocatorNameTransX $X;
    $LocatorNameTransY = $LocatorName+".translateY";
    print("$LocatorNameTransY= "+$LocatorNameTransY+" \n");
    setAttr $LocatorNameTransY $Y;
    $LocatorName_worldMatrix0 = $LocatorName+".worldMatrix[0]";
    print("$LocatorName_worldMatrix0= "+$LocatorName_worldMatrix0+" \n");
    $NodeName_offsetParentMatrix = $NodeName+".offsetParentMatrix";
    print("$NodeName_offsetParentMatrix= "+$NodeName_offsetParentMatrix+" \n");
    connectAttr -f $LocatorName_worldMatrix0 $NodeName_offsetParentMatrix;
}

で大丈夫そう

————————————————–下は参考サイトの例————————————————-

この関数を

import os
import stat
import maya.cmds as cmds
#import maya.OpenMaya as OpenMaya
import maya.api.OpenMaya as OpenMaya
def func_offsetParentMatrix(node,driver):
    mult = cmds.createNode("multMatrix")

    offset = matrix_to_list(
        OpenMaya.MMatrix(cmds.getAttr("{}.worldMatrix[0]".format(node)))
        * OpenMaya.MMatrix(cmds.getAttr("{}.matrix".format(node))).inverse()
        * OpenMaya.MMatrix(cmds.getAttr("{}.worldInverseMatrix[0]".format(driver)))
    )
    cmds.setAttr("{}.matrixIn[0]".format(mult), offset, type="matrix")

    cmds.connectAttr("{}.worldMatrix[0]".format(driver), "{}.matrixIn[1]".format(mult))

    parent = cmds.listRelatives(node, parent=True, path=True)
    if parent:
        cmds.connectAttr("{}.worldInverseMatrix[0]".format(parent[0]), "{}.matrixIn[2]".format(mult))

    cmds.connectAttr(
        "{}.matrixSum".format(mult), "{}.offsetParentMatrix".format(node)
    )
    
def matrix_to_list(mtx):
    lst=[]
    for row in range(0,4):
        for col in range(0,4):
            lst.append(mtx.getElement(row,col))
    return lst
    
def list_to_matrix(lst):
    mtx=OpenMaya.MMatrix(lst)
    # OpenMaya.MScriptUtil.createMatrixFromList(lst, mtx)
    return mtx

こう使った。

global proc Func_TEST_offsetParentMatrix_Proc(){    
    print("Func_TEST_offsetParentMatrix_Proc");
    spaceLocator -position -15.216 0.0 0.0 -name "calf_l_OffsetMatrix_locator_l" -absolute;
    func_offsetParentMatrix_Python_Proc("Dummy_calf_telescopic_l","calf_l_OffsetMatrix_locator_l");
}
    
global proc func_offsetParentMatrix_Python_Proc(string $node,string $driver){
    print("func_offsetParentMatrix");
    python("import func_offsetParentMatrix");
	python("import importlib");
	python("importlib.reload(func_offsetParentMatrix)");
    python("func_offsetParentMatrix.func_offsetParentMatrix('"+$node+"','"+$driver+"')");
}

参考

offsetParentMatrixの記事
https://www.chadvernon.com/blog/space-switching-offset-parent-matrix/

matrix_to_list
https://gist.github.com/rjmoggach/4ea80af3104a3517d3a2a46293acf043

[maya] mel get all material

全然検索してもでてこないのに簡単だった。

NO MEAN    
  string $shadingEngines[]=`ls -type "shadingEngine"`;
    //string $materials[]=`ls -type "material"`;
    string $ShaderS[];
    string $lambertS[]=`ls -type "lambert"`;
    string $phongS[]=`ls -type "phong"`;
    string $materials[]=`ls -sl`;

shadingEnginesとか関係なかった。

//ANSWER
string $allMaterials[] = `ls -materials`;

    for($mtl in $allMaterials)
    {
      string $materialsType=`objectType $mtl`;
      print("$mtl= "+$mtl+" $materialsType="+$materialsType+"\n");
    }