[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");
    }

[maya]「スムーズ スキン サーフェスから未使用のインフルエンスを除去する」だけで、すごくいろんな動作が軽くなる。

Maya の処理スピードを向上させスキン ウェイト ペイント ツール(Paint Skin Weights Tool)を使いやすくするために、全てのスキン ウェイトが 0 であるスムーズ スキンから、ジョイントとインフルエンス オブジェクトを接続解除することができます。これにより未使用のインフルエンスがスキンのインフルエンス(Influence)リストに表示されなくなり、スキン ウェイト ペイント ツール(Paint Skin Weights Tool)が使いやすくなります。

たとえば、既定のオプションを使って、人間のスケルトンにストッキングをはいた左足をスムーズ スキニングするとします。スケルトン内のすべてのジョイントがポテンシャル インフルエンスとしてストッキングに接続されますが、ウェイトが 0 以外の値になるのは左足のストッキングに最も近いジョイントだけです。

肘を選択して回転させると、Maya はストッキングのスキンを計算して 0 以外の値をもつウェイトがないかどうかを調べます。ストッキングを未使用のインフルエンスから接続解除すると、肘とウェイトが 0 のその他のジョイントの回転を処理する必要がなくなり、パフォーマンスが向上します。

未使用のインフルエンスを除去するには

  1. スキンを選択します。
  2. スキン > 影響を編集 > 使われていないインフルエンスの除去(Skin > Edit Influences > Remove Unused Influences)を選択します。

[maya] python prefixHierarchy remove suffix

Python

    def delete_suffixHierarchy_remove_suffix(self,suffix):
        print("-----------prefixHierarchy_remove_suffix-----------start")
        #suffix="fat:"
        # Get the prefix the user entered
        #
        # Get a list of all descendents (The nodes are ordered from
        # leaf to root
        #    
        currentNodes=pm.mel.eval("listRelatives -pa -ad `ls -sl -l`")
        print("currentNodes 1= "+str(currentNodes))
        # add the prefix to each descendent node
        #
        if len(currentNodes)>0:
            for i in range(0,len(currentNodes)):
                #pm.mel.prefixNode(prefix, currentNodes[i])
                newName=currentNodes[i].replace(suffix,"")
                print("newName= "+newName)
                cmds.rename(currentNodes[i], newName)

            
        currentNodes=cmds.ls(l=1, sl=1)
        print("currentNodes 2= "+str(currentNodes))
        # get a list of nodes on the list
        # add the prefix to each node on the active list
        #
        if len(currentNodes)>0:
            for i in range(0,len(currentNodes)):
                #pm.mel.prefixNode(prefix, currentNodes[i])
                newName=currentNodes[i].replace(suffix,"")
                print("newName= "+newName)
                cmds.rename(currentNodes[i], newName)
        print("-----------prefixHierarchy_remove_suffix-----------end")

mel

global proc prefixHierarchy( )
{
	string $ok		= (uiRes("m_prefixHierarchy.kOK"));
	string $cancel	= (uiRes("m_prefixHierarchy.kCancel"));
	string $result = `promptDialog
		-title (uiRes("m_prefixHierarchy.kPrefixHierarchy")) 
		-message (uiRes("m_prefixHierarchy.kEnterPrefix")) 
		-text "prefix_"
		-button $ok  
		-button $cancel 
		-defaultButton $ok  
		-cancelButton $cancel 
		-dismissString $cancel `;

	// If the result was "OK", then proceed
	//
	if ( $result == $ok ) {

		// Get the prefix the user entered
		//
		string $prefix = `promptDialog -q`;

		// Get a list of all descendents (The nodes are ordered from
		// leaf to root
		//	
		string $currentNodes[] = eval("listRelatives -pa -ad `ls -sl -l`");
	
		// add the prefix to each descendent node
		//
		if ( size( $currentNodes ) > 0 ) {
			for( $i=0; $i < size( $currentNodes ); $i++ ) {
				prefixNode( $prefix, $currentNodes[$i] );
			}
		}

		// get a list of nodes on the list
		$currentNodes = `ls -sl -l`;
	
		// add the prefix to each node on the active list
		//
		if ( size( $currentNodes ) > 0 ) {
			for( $i=0; $i < size( $currentNodes ); $i++ ) {
				prefixNode( $prefix, $currentNodes[$i] );
			}
		}
	}
}

[MEL] 戻り値を配列で返す (関数 引数 戻り値 配列 追加)

mel 関数 引数 戻り値 配列 追加

proc string[] sample(string $param[])
{
    string $return[];
    for ($i = 0 ; $i < size($param) ; $i++)
    {
        $return[$i] = "Re_"+$param[$i];
    }
    return $return;
}

sample({"aaa","bbb","ccc"});
// Result: Re_aaa Re_bbb Re_ccc //


{
    string $array[] = {"000","001","002"};
    string $item = "003";
    stringArrayInsertAtIndex(size($array) , $array , $item);
    print $array;
}