www.derekrobinette.com

MEL Scripts

Contents

batchTool.meldownload
cgfxToColladafx.meldownload
colladaExport.meldownload
colladaSetup.meldownload


batchTool.mel 1/4

[top][prev][next]
// This script creates a dialog window which can run any of my other scripts with a recursive option
proc createRecursiveFileList (string $currentPath)
{
    int $includeDae = `checkBox -q -v affectedDaeBox`;
    int $includeAnm = `checkBox -q -v affectedAnmBox`;
    int $includeAll = `checkBox -q -v affectedAllBox`;
    
    $currentPath = ($currentPath + "/");
    string $currentFiles[] = `getFileList -folder $currentPath`;
    for ( $i = 0; $i < size( $currentFiles ); $i++ )
    {
        //ignore files or directories starting with "."
        if (`match "^." $currentFiles[$i]` != ".")
        {
            //search for directories
            if (`filetest -d ($currentPath + $currentFiles[$i])`)
            {
                // recall function (go recursive into subdirs)
                createRecursiveFileList ($currentPath + $currentFiles[$i]);
            }
            else
            {
                //is a file...see what to do:
                string $filename = ($currentPath + $currentFiles[$i]);
                string $baseFilename = basename( $filename, ".mb" );
                string $baseFilenameWExt = basename( $filename, "" );
                string $fullPathFilenameSansExt = `substitute $baseFilenameWExt $filename $baseFilename`;
                string $fullPathFilenameDae = ($fullPathFilenameSansExt + ".dae");
                string $fullPathFilenameAnm = ($fullPathFilenameSansExt + ".anm");
                int $includeCurrent = 0;
                
                if (fileExtension ($baseFilenameWExt) == "mb")
                {
                    //test to see if file should be used
                    if ($includeAll)
                    {
                        $includeCurrent = 1;
                    }
                    else if (($includeDae) && (`file -q -exists $fullPathFilenameDae`))
                    {
                        $includeCurrent = 1;
                    }
                    else if (($includeAnm) && (`file -q -exists $fullPathFilenameAnm`))
                    {
                        $includeCurrent = 1;
                    }
                }
                if ($includeCurrent)
                {
                    global int $numFilesToProcess;
                    global string $filesToProcess[];
                    $filesToProcess[$numFilesToProcess] = ($currentPath + $currentFiles[$i]);
                    $numFilesToProcess++;
                }
            }
        }
    }
}


global proc batchButtonAction ()
{
    string $baseDir = `textFieldButtonGrp -q -text baseDirTextGroup`;
    string $animBaseFile = `textFieldButtonGrp -q -text animBaseFileGroup`;
    string $animRootNode = `textFieldButtonGrp -q -text animRootNodeGroup`;
    string $animNamespace = `textFieldGrp -q -text animNamespaceGroup`;
    int $doCgfxToColladafx = `checkBox -q -v cgfxToColladafxBox`;
    int $doCloseWindows = `checkBox -q -v closeWindowsBox`;
    int $doExportModified = `checkBox -q -v exportModifiedBox`;
    int $doExportAll = `checkBox -q -v exportAllBox`;
    string$customScript = `textFieldGrp -q -text customScriptGroup`;
    string$customCommand = `textFieldGrp -q -text customCommandGroup`;
    
    createRecursiveFileList $baseDir;
    global string $filesToProcess[];
    
    //TODO:  prompt number or list of files to process if > X or if basedir == default
    //("You are about to process " + $TEMPnum + " files in the following directory:\n" + $baseDir + "\nIs that OK?");
    
    deleteUI batchToolWindow;
    
    //TODO:  Log window with errors/progress
    
    for ($i = 0; $i < size($filesToProcess); $i++)
    {
        int $modifiedFile = 0;
        global string $filesToProcess[];
        //open file
        pv_performAction $filesToProcess[$i] "Best Guess";
        file -f -options "v=0"  -typ "mayaBinary" -o $filesToProcess[$i];
        
        //run through list of things that need to be done
        if ($customScript != "")
        {
            eval "source $customScript";
            $modifiedFile = 1;
        }
        if ($customCommand != "")
        {
            eval $customCommand;
            $modifiedFile = 1;
        }
        if ($doCgfxToColladafx)
        {
            string $CgfxToColladafxResult = `cgfxToColladafx`;
            if ($CgfxToColladafxResult == "modifiedFile") {$modifiedFile = 1;}
            else if ($CgfxToColladafxResult == "cgfxPluginLoaded")
            {
                global string $filesWithCgfx[];
                global int $numFilesWithCgfx;
                $filesWithCgfx[$numFilesWithCgfx] = $filesToProcess[$i];
                $numFilesWithCgfx++;
            }
        }
        if ($doCloseWindows)
        {
            //TODO:  Create close windows proc/.mel
            //$didCloseAllWindows = `closeAllWindows`;
            //if ($didCloseAllWindows) {$modifiedFile = 1;}
        }
        if (($doExportAll) || (($doExportModified) && ($modifiedFile)))
        {
            source colladaExport.mel;
            $didColladaExport = `doColladaExport`;
            if ($didColladaExport)
            {
                global string $filesExported[];
                global int $numFilesExported;
                $filesExported[$numFilesExported] = $filesToProcess[$i];
                $numFilesExported++;
            }
        }
        //save if modified
        if ($modifiedFile)
        {
            file -save;
            global string $filesModified[];
            global int $numModified;
            $filesModified[$numModified] = $filesToProcess[$i];
            $numModified++;
        }
    }
    //Summary
    global string $filesToProcess[];
    global int $numFilesToProcess;
    global string $filesModified[];
    global int $numModified;
    global string $filesExported[];
    global int $numFilesExported;
    global string $filesWithCgfx[];
    global int $numFilesWithCgfx;
    
    print "\n\nModified the following files:\n";
    print $filesModified;
    print "\nExported the following files:\n";
    print $filesExported;
    string $message = ("Modified " + $numModified + " .mb files\nExported " + $numFilesExported + " .dae files");
    if ($numFilesWithCgfx > 0)
    {
        print "\nFiles using the CgFx plugin:\n";
        print $filesWithCgfx;
        $message = ($message + "\n" + $numFilesWithCgfx + " files are still using the CgFx plugin");
    }
    print ("\n" + $message + "\n");
    print "Export complete\n";
    confirmDialog
        -title "Export complete"
        -message $message
        -button "OK"
        -defaultButton "OK";
}


global proc setBatchBaseDir (string $baseDir, string $fileType)
{
    textFieldButtonGrp -edit -text $baseDir baseDirTextGroup;
}


global proc setBatchAnimBaseFile (string $animBaseFile, string $fileType)
{
    textFieldButtonGrp -edit -text $animBaseFile animBaseFileGroup;
}


global proc getSelectedBaseNode (string $animBaseFile, string $fileType)
{
    //TODO: actually create this proc
    textFieldButtonGrp -edit -text $animRootNode animRootNodeGroup;
}


global proc batchTool () 
{
    //reset global variables
    global string $filesToProcess[];
    global int $numFilesToProcess;
    global string $filesModified[];
    global int $numModified;
    global string $filesExported[];
    global int $numFilesExported;
    global string $filesWithCgfx[];
    global int $numFilesWithCgfx;
    clear ($filesToProcess);
    $numFilesToProcess = 0;
    clear ($filesModified);
    $numModified = 0;
    clear ($filesExported);
    $numFilesExported = 0;
    clear ($filesWithCgfx);
    $numFilesWithCgfx = 0;
    
    //set defaults
    string $baseDir = `workspace -fn`;
    int $includeDae = 1;
    int $includeAnm = 0;
    int $includeAll = 0;
    string $animBaseFile;
    string $animRootNode;
    string $animNamespace;
    int $doCgfxToColladafx = 0;
    int $doCloseWindows = 0;
    int $doExportModified = 1;
    int $doExportAll = 0;
    string $customScript;
    string $customCommand;
    
    window
        -title "Batch Tool"
        -menuBar true
        -resizeToFitChildren true
        batchToolWindow;
        columnLayout -columnWidth 500 -adjustableColumn 1;
            textFieldButtonGrp
                -label "Base Directory"
                -cw 1 80
                -cw 2 390
                -cw 3 30
                -text $baseDir
                -buttonLabel "..."
                -buttonCommand "fileBrowserDialog -m 4 -fc setBatchBaseDir -an \"Choose a starting directory:\""
                baseDirTextGroup;
        setParent ..;
        
        frameLayout
            -collapsable false
            -label "Files to Process"
            -width 500;
            columnLayout -columnWidth 500;
             checkBox
                 -label "Files with .dae"
                 -value $includeDae
                affectedDaeBox;
             checkBox
                 -label "Files with .anm"
                 -value $includeAnm
                affectedAnmBox;
             checkBox
                 -label "All .mb Files"
                 -value $includeAll
                affectedAllBox;
            setParent ..;
        setParent ..;
        
        frameLayout
            -collapsable true
            -collapse 1
            -label "Transfer Animation (not functional)"
            -width 500;
            columnLayout -columnWidth 500;
                textFieldButtonGrp
                    -label "Base File"
                    -cw 1 80
                    -cw 2 390
                    -cw 3 30
                    -text $animBaseFile
                    -buttonLabel "..."
                    -buttonCommand "fileBrowserDialog -m 0 -fc setBatchAnimBaseFile -an \"Choose a base file:\" -ft mayaBinary"
                    animBaseFileGroup;
                textFieldButtonGrp
                    -label "Root Node"
                    -cw 1 80
                    -cw 2 150
                    -cw 3 100
                    -text $animRootNode
                    -buttonLabel "Use Selected"
                    -buttonCommand getSelectedBaseNode
                    animRootNodeGroup;
                textFieldGrp
                    -label "Namespace"
                    -cw 1 80
                    -cw 2 150
                    -text $animNamespace
                    animNamespaceGroup;
            setParent ..;
        setParent ..;
        
        frameLayout
            -collapsable true
            -collapse true
            -label "Custom .mel Script or Command"
            -width 500;
            columnLayout -columnWidth 500;
            textFieldGrp
                -label "Script"
                -cw 1 60
                -cw 2 150
                -text $customScript
                customScriptGroup;
            textFieldGrp
                -label "Command"
                -cw 1 60
                -cw 2 150
                -text $customCommand
                customCommandGroup;
            setParent ..;
        setParent ..;  
         
        frameLayout
            -collapsable false
            -label "Commands"
            -width 500;
            columnLayout -columnWidth 500;
             checkBox
                 -label "Convert Materials (cgfx to colladafx)"
                 -value $doCgfxToColladafx
                cgfxToColladafxBox;
             checkBox
                 -label "Close All UI Windows (not functional)"
                 -value $doCloseWindows
                closeWindowsBox;
             checkBox
                 -label "Export .dae (Modified Files)"
                 -value $doExportModified
                exportModifiedBox;
             checkBox
                 -label "Export .dae (All Files)"
                 -value $doExportAll
                exportAllBox;
            setParent ..;
        setParent ..;
        
        rowColumnLayout
            -nc 2
            -columnWidth 1 250
            -columnWidth 2 250;                
            button
                -label "Go!"
                -width 250
                -command "batchButtonAction";
            button
                -label "Close"
                -width 250
                -command "deleteUI -window batchToolWindow";
    showWindow batchToolWindow;
}


cgfxToColladafx.mel 2/4

[top][prev][next]
//This script converts all CgFx materials in the active scene to ColladaFX
//For ColladaMaya_301
global proc string cgfxToColladafx()
{
    if (`pluginInfo -query -loaded cgfxShader.mll` == 0)
    {
        print "The CgFx PlugIn is not Loaded\n";
        return "uneventful";
    }
    else
    {
        //TODO: split out and generalize functions to be shared by other scripts
        //TODO: make proc getNodesFromSelected (name/type, string)
        //delete cgfx camera nodes
        int $numBadCameraNodes = 0;
        select persp;
        string $perspNodes[] = `listConnections -connections 1`;
        for ($i = 0; $i < size($perspNodes); $i++)
        {
            if ((`match pos $perspNodes[$i]` != "") || (`match dir $perspNodes[$i]` != ""))
            {
                delete $perspNodes[$i];
                $numBadCameraNodes++;
            }
        }
        string $oldMaterials[] = `ls -type cgfxShader`;
        if (`size($oldMaterials)` == 0)
        {
            print "There are no CgFx materials in this scene\n";
            //test to see if cgfx plugin is loaded
            if (`pluginInfo -query -loaded cgfxShader.mll`)
            {
                if ($numBadCameraNodes > 0)
                {
                    return "modifiedFile";
                }
                else
                {
                    return "cgfxPluginLoaded";
                }
            }
            else
            {
                return "uneventful";
            }
        }
        else
        {
            string $sharedFileNodes[] ={"ambient_sampler",
                                        "diffuse_sampler",
                                        "emissive_sampler",
                                        "env_sampler",
                                        "normal_sampler",
                                        "specular_sampler"};
                                        
            string $sharedParams[] =   {"shininess",
                                        "reflection",
                                        "hidden",
                                        "collidable"};
                                        
                                            
            for ($i = 0; $i < size($oldMaterials); $i++)
            {
                //get .cgfx file
                //TODO: skip if no cgfx file is assigned
                string $cgfxFile = `getAttr ($oldMaterials[$i] + ".shader")`;
                //add full path if needed
                string $projPath = `workspace -fn`;
                //string $cgfxMatch = `match $projPath $cgfxFile`;
                if  (`match $projPath $cgfxFile` == "")
                {
                    $cgfxFile = ($projPath + $cgfxFile);
                }
                //make sure collada plugin is loaded
                if (`pluginInfo -query -loaded COLLADA.mll` == 0)
                {
                    string $oldpath = `pwd`;
                    chdir "/";
                    chdir "/Program Files/AliasWavefront/Maya7.0";
                    chdir "/Program Files/Alias/Maya7.0";
                    chdir "%MAYA_PATH70%";
                    string $mayapath = `pwd`;
                    chdir "/";
                    chdir $oldpath;
                    string $colladapath = $mayapath + "/bin/plug-ins/COLLADA.mll";
                    waitCursor -state on;
                    $ignoreUpdateCallback = true;
                    catch( `loadPlugin $colladapath`);
                    $ignoreUpdateCallback = false;
                    waitCursor -state off;
                }
                //create new shader name (changing cgfx to colladafx if applicable)
                string $newMaterial = `substitute "cgfx" $oldMaterials[$i] "colladafx"`;
                //rename old shader
                rename ($oldMaterials[$i]) ($oldMaterials[$i]+ "_old");
                $oldMaterials[$i] = ($oldMaterials[$i]+ "_old");
                //create new shader
                shadingNode -asShader colladafxShader -name $newMaterial;
                
                //assign .cgfx file
                setAttr -type "string" ($newMaterial + ".vertexProgram") $cgfxFile;
                setAttr -type "string" ($newMaterial + ".fragmentProgram") $cgfxFile;
                //reload collada shader
                eval ("colladafxShaderCmd -lfe \"" + $cgfxFile + "\" \"main\" \"main\" -shader " + $newMaterial);
                //refreshColladafxShader $newMaterial;
                
                //get technique
                string $currentTechnique = `getAttr ($oldMaterials[$i] + ".technique")`;
                //set technique (cgfx technique = string - collada usetech = int)
                switch ($currentTechnique)
                {
                    case "opaque":      setAttr ($newMaterial + ".useTech") 0; break;
                    case "alpha_blend": setAttr ($newMaterial + ".useTech") 1; break;
                    case "alpha_test":  setAttr ($newMaterial + ".useTech") 2; break;
                    case "sky_opaque":  setAttr ($newMaterial + ".useTech") 3; break;
                    case "sky_blend":   setAttr ($newMaterial + ".useTech") 4; break;
                }
        
                //copy $sharedParams between $oldMaterials[$i] and $newMaterial
                for ($j = 0; $j < size($sharedParams); $j++)
                {
                    //get and assign attr
                    setAttr ($newMaterial + "." + $sharedParams[$j]) `getAttr ($oldMaterials[$i] + "." + $sharedParams[$j])`;
                }
                //set .light_dir to persp
                string $lightDir = ($newMaterial + ".light_dir");
                defaultNavigation -ce -d $lightDir -source persp;
                //connectNodeToAttrOverride("persp", $lightDir);        
                
                //get channelFilePairs
                select $oldMaterials[$i];
                string $channelFilePairs[] = `listConnections -connections 1`;
                
                //check existing cgfx connections and create connections to file nodes on new colladafx material
                for ($j = 0; $j < size($channelFilePairs); $j+=2)
                {
                    string $channel  = $channelFilePairs[$j];
                    string $fileNode = $channelFilePairs[$j+1];
                    //check against $sharedFileNodes
                    for ($k = 0; $k < size($sharedFileNodes); $k++)
                    {
                        if ($channel == ($oldMaterials[$i] + "." + $sharedFileNodes[$k]))
                        {
                            //assign file node to new shader
                            connectAttr -force ($fileNode + ".outColor") ($newMaterial + "." + $sharedFileNodes[$k]);
                        }
                    }
                }
                //select objects with old material, assign new material
                hyperShade -objects $oldMaterials[$i];
                hyperShade -assign $newMaterial;
                
                //delete old material
                delete $oldMaterials[$i];
            }    
            //the end
            select -cl;
            print "\nc'est finis";
        }
        return "modifiedFile";
    }
}


colladaExport.mel 3/4

[top][prev][next]
//This script exports the active scene as a Collada .dae file
//For ColladaMaya_301
global proc int doColladaExport () 
{
    string $fullPathFilename = `file -q -sn`;
    if ($fullPathFilename == "")
    {
        confirmDialog
            -title "Export Failed"
            -message "Error:  You must save the file before exporting it"
            -button "OK"
            -defaultButton "OK";
        error  "You must save the file before exporting it";
        return 0;
    }
    else
    {
        string $baseFilename = basename( $fullPathFilename, ".mb" );
        string $baseFilenameWExt = basename( $fullPathFilename, "" );
        string $fullPathFilenameSansExt = `substitute $baseFilenameWExt $fullPathFilename $baseFilename`;
        string $fullPathFilenameDae = ($fullPathFilenameSansExt + ".dae");
        pv_performAction $fullPathFilenameDae "COLLADA exporter";
        if (`file -f -op 
	        "bakeTransforms=1;
	        relativePaths=1;
	        bakeLighting=0;
	        exportCameraAsLookat=0;
	        exportTriangles=1;
	        isSampling=1;
	        curveConstrainSampling=0;
	        samplingFunction=30;
	        exportPolygonMeshes=1;
	        exportLights=1;
	        exportCameras=1;
	        exportJointsAndSkin=1;
	        exportAnimations=1;
	        exportInvisibleNodes=1;
	        exportNormals=1;
	        exportTexCoords=1;
	        exportVertexColors=1;
	        exportTangents=0;
	        exportTexTangents=1;
	        exportMaterialsOnly=0;
	        exportConstraints=1;
	        exportPhysics=1;
	        exclusionSetMode=0;
	        exclusionSets=;
	        exportXRefs=1;
	        dereferenceXRefs=1;
	        cameraXFov=0;
	        cameraYFov=1;"
	        -typ "COLLADA exporter" -pr -ea $fullPathFilenameDae` == $fullPathFilenameDae)
        {
            return 1;
        }
        else
        {
            confirmDialog
                -title "Export Failed"
                -message "The file was not sucessfully exported"
                -button "OK"
                -defaultButton "OK";
            error  "The file was not sucessfully exported";
            return 0;
        }
    }
}


global proc colladaExport () 
{
    if (`doColladaExport`)
    {
        print "File Exported";
        confirmDialog
            -message "File Exported"
            -button "OK"
            -defaultButton "OK";
    }
}


colladaSetup.mel 4/4

[top][prev][next]
//This script runs from a batch to set up Maya for the current project, and adds appropriate shelf buttons
global proc doColladaSetup () 
{
    string $gShelfTopLevel;
    string $oldpath = `pwd`;
    chdir "/";
    chdir "/Program Files/AliasWavefront/Maya7.0";
    chdir "/Program Files/Alias/Maya7.0";
    chdir "%MAYA_PATH70%";
    string $mayapath = `pwd`;
    string $bitmap = $mayapath + "/extras/icons/colladaExport.bmp";    
    string $colladapath = $mayapath + "/bin/plug-ins/COLLADA.mll";
    string $cgfxpath = $mayapath + "/bin/plug-ins/cgfxShader.mll";
    string $animexportpath = $mayapath + "/bin/plug-ins/animImportExport.mll";
    
    //////////////////PLUGINS/////////////////////

    //auto load collada        
    pluginInfo -edit -autoload true $colladapath;
    
    //load collada
    waitCursor -state on;
    $ignoreUpdateCallback = true;
    catch( `loadPlugin $colladapath`);
    $ignoreUpdateCallback = false;
    waitCursor -state off;

    //auto load anim import/export
    pluginInfo -edit -autoload true $animexportpath;
    
    //load anim import/export
    waitCursor -state on;
    $ignoreUpdateCallback = true;
    catch( `loadPlugin $animexportpath`);
    $ignoreUpdateCallback = false;
    waitCursor -state off;

    //////////////////SHELVES/////////////////////

    //TODO: add and populate XL tools shelf 
    
    //polygon shelf export button
    string $polyshelf[] = `shelfLayout -q -childArray "Polygons"`;
    int $a = 0;
    int $polyexists = 0;
    while ($a < size($polyshelf))
    {
        if (`shelfButton -query -label $polyshelf[$a]` == "Export Collada (.dae)")
        {
            $polyexists = 1;
        }
        $a = ($a + 1);
    }
    
    if ($polyexists == 0)
    {        
        shelfButton
            -parent Polygons
            -enableCommandRepeat 1
            -enable 1
            -width 34
            -height 34
            -manage 1
            -visible 1
            -preventOverride 0
            -align "center" 
            -label "Export Collada (.dae)" 
            -labelOffset 0
            -font "tinyBoldLabelFont" 
            -imageOverlayLabel "" 
            -image $bitmap
            -image1 $bitmap
            -style "iconOnly" 
            -marginWidth 1
            -marginHeight 1
            -command "colladaExport" 
            -actionIsSubstitute 0
            colladapoly;
        }

    //animation shelf export button    
    string $animshelf[] = `shelfLayout -q -childArray "Animation"`;
    int $a = 0;
    int $animexists = 0;
    while ($a < size($animshelf))
    {
        if (`shelfButton -query -label $animshelf[$a]` == "Export Collada (.dae)")
        {
            $animexists = 1;
        }
        $a = ($a + 1);
    }
    
    if ($animexists == 0)
    {        shelfButton
        -parent Animation
        -enableCommandRepeat 1
        -enable 1
        -width 34
        -height 34
        -manage 1
        -visible 1
        -preventOverride 0
        -align "center" 
        -label "Export Collada (.dae)" 
        -labelOffset 0
        -font "tinyBoldLabelFont" 
        -imageOverlayLabel "" 
        -image $bitmap
        -image1 $bitmap 
        -style "iconOnly" 
        -marginWidth 1
        -marginHeight 1
        -command "colladaExport" 
        -actionIsSubstitute 0
        colladaanim;
    }
    
    chdir "/";
    chdir $oldpath;
    confirmDialog
        -message "Collada setup complete.\nMaya will now close."
        -button "OK" -defaultButton "OK";
    eval `quit -force`;
}

global proc colladaSetup () 
{
    scriptJob -runOnce 1 -conditionFalse busy "doColladaSetup";
}

Generated by GNU enscript 1.6.4.