27
MEL for Beginners By Kedarnath [email protected]

Mel for beginners

Embed Size (px)

Citation preview

Page 1: Mel for beginners

MEL for BeginnersBy [email protected]

Page 2: Mel for beginners

Overview AnintroductiontoMayaEmbeddedLanguage(MEL)asatoolforanimatorstostreamlineworkflow,exercisecontrolovercomplexoperations,andtoexploreideasoriginati8ngfromthegenerationofmotiongraphicsthroughmathematicalprocedures

Prerequisite KnowledgeofMaya

Who should attend this Students/artistswhowanttoautomatetheirworkandgrowintheindustry

Week 1• OverviewofMaya’sDependencyGraphArchitecture• IntrotoMELanditssyntax• Waystocreatescripts• CustomizingMaya• Creating.melfiles• startusingMayacommandsWeek 2• Variables,DataTypes,andOperators• IntegratingvariablesintoMayacommands• ManipulatingattributesWeek3• UsingtheHypergraphandHypershade• ConditionalandloopingStatements• ExpressionsandMELscripts• procedures,functions,recursionWeek 4• Userinteraction• DesigningcustomUI/Creatinginterfaceusingqt• Project‐Createcustomizedtool

Page 3: Mel for beginners

Maya Scripting – MEL or PYTHON

Peoplegenerallyaskwhichscriptinglanguageshouldwelearnfirst.Iprefer“learnMELfirstandonceweareconfidentaboutitandunderstanditthenstartwithPython”.It’snottosayyoucan’tdothesamewithPythonifyou’reafastlearner,butgenerallyspeakingyou’llbeupandrunningwithMELalotquicker.

IfyouhavegoodknowledgeofprogrammingknowledgethenyoucanstartwithPython,whereyoucandevelopscriptsforMayaaswellasforotherpackages.

Advantages of MEL

• MELscriptingisnativetoMaya.• WiththelittleknowledgeofMELwecanstartworkingwithit.• Easytounderstand• ExtensiveMELdocumentationisavailable• Itshowsinthescripteditor

Advantages of Python

• PythoncandoalmosteverythingMELcan+more.• IfyoueverwanttodeveloptoolsoutsideofMaya,orMayatoolsthatinteractwithothersoftware,python

isthewaytogowithhavingexternallibraries.

Page 4: Mel for beginners

Week 1

Overview of Maya’s Dependency Graph Architecture

TheentireMayasceneisasingleDependencyGraph,whichisbuiltfromDependencyNodesconnectedthroughPlugs(thinkitasabrainmadeofinterconnectedneurons).

DependencyGraph DependencyGraphnode.Twomainimportantthingshere,nodesandtheirattributes.Thedependencygraphisawaywhereinyoucanconnectmultiplenodestocomeupwithanoutput(renderedimages,animat‐edgeometry,etc.),infactyoucanactuallydefinealmostanyscenefilebywhatnodesarepresentandwhatconnectionsexistbetweenthesenodes.ADGnodeisanynodethatcanbeconnectedtoothernodes,andtheyarenotnecessarilyvisibleintheSceneHierarchy,butyoucanshowtheDependencyGraphofaparticularobjectbyselectingitandclickingtheInputandOutputConnectionsmode.

EverytimetheMayausermanipulatesthescenehemayaddorremovenodesfromthegraph,connectordisconnectplugs,orfeedsomenewdata.Afterpartsofthedependencygraphhavebeenmanipulated,itisinadirtystateandmustbebroughtuptodatebeforebeingdisplayed.Butinsteadofevaluatingtheentiregraph(whichwouldbeveryslowinacomplexMayascene),onlythedirtypartsofthegraphwhichactuallyneedupdatingwillbeevaluated.

Page 5: Mel for beginners

Directed Acyclic Graph

Any object that can be parented to another object, and can have children parented to it . DAG is mostly for hierarchical distinctions. Any node which has transform attributes is a DAG object. You can see DAG nodes when the Hyper graph is in the Scene Hierarchy mode. There are some simple rules with DAG objects:

• An object can only have one parent at a time. • An object cannot be the child of one of own it’s children. This is what the Acyclic part mainly refers to, in a

hierarchy you can’t have something parented to one of it’s children, otherwise you’d get a cycle if you consid-er how transforms are distributed from child to parent (If you move the parent, the child moves, and if the parent object is under the child as well it receives additional transform...). Maya dosen’t allow this for DAG objects.

Nodes & Attributes

• Everything (for the most part) in Maya is represented by nodes, with attributes, connected to other nodes • There are two kinds of connections between object nodes: Scene hierarchy connections: e.g., grouping, parent-child relationships Input-output connections. For example, the height of one object can be connected to the scale factor of another

Intro to MEL and its syntex

MEL

The Maya Embedded Language (MEL) is a scripting language used to simplify tasks in Autodesk Maya. Most tasks that can be achieved through Maya’s GUI can be achieved with MEL, as well as certain tasks that are not available from the GUI. MEL offers a method of speeding up complicated or repetitive tasks, as well as allowing users to redistribute a specific set of commands to others that may find it useful.

Uses of MEL

• Customization of Maya to create new interfaces and behaviors• Automation of Maya tasks• Creating new tool sets for different work flows like modeling, lighting, rendering etc

MEL Syntax

MEL, follows the programming conventions of many popular languages. Experience with other object oriented programming languages will be very useful.

Few basic syntax rules to follow are:

• End all command lines with a semicolon (;) • All variables should start with $• MEL is a case sensitive ex: polySphere is different than polysphere• Commands usually start with small letter, if commands has 2 or more words then starting letter of the words

would be capital ex: polySphere;

Page 6: Mel for beginners

Ways to write script

you can write scripting using different ways. Choose the way according to your requirement.

• Command line – single command input• Command shell – single command with history• Shelf – icon access to running scripts• Script files – external files to load and run• Script nodes – saved with scene file Runs on demand, scene open/close, render time, time line update.

Customizing Maya UI

You can customize Maya UI using MEL. All MEL scripts are located in maya installation directoryC:/Program Files/Autodesk/Maya2013/scripts Inside Maya if you want to find wchich script to be edited, you can find that using command “whatIs”

Creating .mel files

You can write scripts in notepad or in command panel. Save both and name the files using extension .mel, which can be sourced in Maya afterward.

Start using maya commands

You can find the command list in the Maya documentation. Command for creating polygon sphere is polySphere. Write the below command in command input panel. Select the command and click ctrl+enter or

whatIs “layerEditor”;// Result: Script found in: C:/Program Files/Autodesk/Maya2013/scripts/startup/layerEditor.mel //

Page 7: Mel for beginners

PolySphere;help polySphere;

enter (numpad) to run the command (selecting the whole command/text is usefull if you want to use command again and again).

If you want to know about the command use the help command.

MEL commands have different arguments, below is the syntax for a general MEL command. “Value” of the flag is depending upon the type of the flag.

Flags have long and short names, interchangeable

MEL commands have “command modes” Creation, query, and edit

Default is creation Sphere; Command query – used to get a value from object Sphere –query –radius nurbsSphere1; Command edit – used to change the current value of an object Sphere –edit –radius 4 nurbsSphere1;

Comments // a one line comment /* a multiline comment */

command -flag <value> polySphere -n hi -radius 10; // where flag -n receives string as value and -radius float as value.

polySphere -name hi;polySphere -n hi;

Page 8: Mel for beginners

Lets create a polygon cube with name “wall” having depth 10, height 10 and width 1.

polyCube -n wall -d 10 -h 10 -w 1; // -n name // -d depth // -h height // -w width

Commands to learn: move, rotate, scale, select, print, polySphere, polyCube

move -a 10 0 0; // move object rotate -a 45 0 0; // rotate object scale -r 2 1 1; // scale object //-a is for absolute value //-r is for relative value select wall; // select object with name “wall” select -r wall wall1; // selects objects called wall and wall1 print “test”; // it will print test polySphere -r 1 -sx 20 -sy 20 -ax 0 1 0 -tx 2 -ch 1;//will create poly sphere //with given values move -r -10 0 0 pSphere1.scalePivot pSphere1.rotatePivot ; // set the pivot of sphere to -10 0 0

Assignment1: Create a staircase using scriptingAssignment2: Create a basic computer table using scripting and save the script as .mel file which can be used directlyAssignment3: Create a room with spiral stair case

Page 9: Mel for beginners

Week 2Variables, Data types and Operators

General guidelines

• Always preceded with a “$” symbol ( “$name” ) • You cannot have white spaces or special characters• Can not start with a number ( “$2” ) • A variable’s type cannot be redefined once it is created, until the Maya session is ended.• To debug script insert print commands in your expression at points were you would like to know the value of

a variable or object attribute. Mel has a few basic data types. For MEL beginners it is important to learn the Integer, float, string, vector and matrix data types. Like any other programming language Maya provides the user with the ability to tempo-rarily store information through variables. Declaring Variables and Data types

When declaring a variable there is a specific format you need to use. first declare what sort of variable you are using. Next use a $ sign followed by the name.

int $myInt;

int $myInt = 1; float $myfloat1 = 1.123; string $myString = “Hello”;

vector $myvector = <<1.3, 1.2, 1.1>>;

string $myArray[] = {“one”,”two”,”three”,”four”}; int $myArray2[] = {1,2,3,4};

matrix $m[3][5]= <<1,3,5,7,9; 2,4,6,8,1; 4,7,0,3,6>>;

If you are unsure what a variable type is use the whatIs command to find out. int $myInt = 1; whatIs “$myInt”; // Result: int variable //

Operators

Assignment Operator =the equals sign sets a variable equal to a value. float $a = 2.135;

Arithmetic Operators+ Add two elements

Page 10: Mel for beginners

$C = $A + $B;- Subtract two elements $C = $A - $B;* Multiply two elements $C = $A * $B;/ Divide two elements together $C = $A / $B;% Find the fractional remainder of the division $C = $A % $B;^ Find the cross product of two vectors vector $a = <<2,2,2>>; vector $b =<<2,4,6>>; vector $c =$a^$b; print $c; //returns 4 -8 4

The cross product can be used to find a vector that is perpendicular to the two input vector . Cross product can be broken down as. (a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x)

Boolean Operators Boolean are used for making comparison and have one of two states... true or false. Boolean can also be called using the following:

true, yes, on, 1 false, no, off, 0

Comparisson Operators< less than A < B > greater than A > B <= less than or equal A <= B >= greater than or equal A >= B ==

Page 11: Mel for beginners

equal to A == B < != not equal to A != B Logical OperatorsUse logical operators when you want to compair two or more values. || or a || b && and a && b ! not !a Precedence precedence is the hierarchy in which operators are evaluated. they are as follows:

( ),[ ] !,++,-- *,/,%,^ +,- <,<=,>,>= ==,!= && || ?: =,+=,-=,*=,/=

Manipulating Attributes

Manipulating attributes using setAttr and getAttr. In one node there can be several attributes, which can be changed using “setAttr” command and one can get the data of the attributes using “getAttr”. As discussed above you should keep data type of attributes in mind.

polyCube -n wall; getAttr wall.translateX; setAttr wall.translateX 10;

The above set of commands create a cube called wall and set its translation of X to 10. What if we use wall.trans-late instead of translateX. Translate has 3 values (x, y,z) where as translateX has only x value.

getAttr wall.translateX; // Result: 10 // getAttr wall.translate; // Result: 10 0 0 //

Page 12: Mel for beginners

setAttr wall.translate 10 1 1; //similarly we can set all values of translate

setAttr “lambert2.color” -type double3 1 0 0 ; // similarly we can set attributes of different shaders also. Where data type of color is double with 3 values of R G B.

To get and store the value of an attribute in a variable we can use getAttr command in single quotes(` `). Which means return the value of getAttr command.

int $transx =`getAttr wall.translateX`; // it will store the value in variable called transx print $transx; // to print the value of translation of x-axis.

Assignment4: create 10 lambert shaders and set the color red, incand green, diffuse 1, switch on the refraction and set the refraction limit to 2.

Integrating variables into Maya commands

Using variables to manipulate attribute values

If you want to set same value to several objects and there is a possibility of modifying the value several times, then you can store the value in a variable and use the variable in different objects. With this if you change the value once on the top, automatically other values will be changed.

Create a integer variable called “transx” with value of 5 and set the translate x-axis value of polygon cube called “wall” to the “transx”.

polyCube -n wall; int $transx =5; setAttr wall.translateX $transx; // sets the value of translatex to variable $transx setAttr wall.translateY $transx; // sets the value of translatey to variable $transx setAttr wall.translateZ $transx; // sets the value of translatez to variable $transx

Create a integer variable called “trans” with value of 2, create string variable called “name” with value of lambert3, and set the diffuse of lambert3 shader to trans.

int $trans =2; string $name = “lambert3”; setAttr ($name+”.diffuse”) $trans;

Similarly you can set the value of diffuse of the selected shaders to 2. int $diff =2; string $names[] = `ls -sl`; // list the selected objects and put in array called $names[] setAttr ($names[0]+”.diffuse”) $diff;// set the value for first object in the array called $names[]

Assignment5: Create 10 lambert shaders and set the color red, incand green, diffuse 1, switch on the refraction and set the refraction limit to 2 with a smaller script than in assignment3

Assignment6: Create renderlayers called key,fill,rim.bounce,occ

Page 13: Mel for beginners

Assignment7: Create display layer called “lights” with all lights in the scene file and another layer called “geom” with all geometryshapes in the scene file

Assignment8: Switch on all lights

Commands to learn: ls, select.

select -all; ls -type light; ls -type geometryShape;

Page 14: Mel for beginners

Week 3

Using the Hypergraph and Hypershade

Hyper shade and Hypergraph are used to create, check and modify the connections and attributes of shaders and other nodes. It is also used to create different nodes. Hierarchy of the scene and other nodes can be viewed here.

Commands to learn: sahdingNode, hyperShade,createNode,listNodeTypes,listrelatives

The below script is used to create a new shading node blinn and attach it to selected object.

polySphere; polyCone; string $myBlinn = `shadingNode -asShader blinn`; // create a shader blinn select nurbsSphere1; hyperShade -assign $myBlinn; // assign $myBlinn to selected object select -cl; hyperShade -objects $myBlinn; string $blinn = `createNode blinn`; print $blinn; print $myBlinn; select lambert1 $blinn; hyperShade -objects “”;

Assignment9 : create a new shader with particular values and assign to selected objects.

Conditional and looping Statements

If else If else is mainly used to check the condition, whether the condition is true or false.

If mainly consists of syntax if(condition) { operation} else {operation} int $marks = 10; if($marks>30) { print (“you are pass”); } else { print (“you are fail”); }

Page 15: Mel for beginners

Loops

For The “for” loop is mainly used to run commands on the values of an array. It is used to do one task several times in a loop. A for loop mainly consists of: syntax: for(initial execution; test condition; execute after each loop) {operation;} string $myArray [] = {“one”,”two”,”three”,”four”}; int $myArraySize = size($myArray); for ($i =0; $i<$myArraySize; $i++) { if ($myArray[$i] == “one”) print (“\n”+$myArray[$i] + “ apple”); else print (“\n”+$myArray[$i] + “ apples”); } for in This is an alternate statement for “for” loop, you can use.

int $Vals[5] = {1, 2, 3, 4, 5}; int $elements; for($elements in $Vals) { print (“\n current value is “+ $elements+” in Vals.”); }

While The while loop runs a command while the test condition holds true A while loop mainly consists of: syntax while (test condition;) {operation;}

string $myArray [] = {“one”,”two”,”three”,”four”}; int $i =0; while ( $i < size($myArray)) { if ($myArray[$i] == “one”) print (“\n”+$myArray[$i] + “ apple”); else print (“\n”+$myArray[$i] + “ apples”); $i++;//IF you forget this Maya will get stuck in an infinite loop }

Page 16: Mel for beginners

do while The do-while loop runs a command while the test condition holds true. While loop does the operation if the test condition is true, where in do while loop, first it does the operation then checks for the test condition and it repeatedly does the operation until the test condition will fail or false. A do-while loop mainly consists of: syntax do {operation;} while (test condition);

string $myArray [] = {“one”,”two”,”three”,”four”}; int $i =0; do { if ($myArray[$i] == “one”) print (“\n”+$myArray[$i] + “ apple”); else print (“\n”+$myArray[$i] + “ apples”); $i++; //IF you forget this Maya will get stuck in an infinite loop } while ( $i < size($myArray)); switchThe switch statement can be used to shorten a would be long list of if statements. The same work can be done using if elseif statements also.

int $random= rand(0,10); switch($random) { case 0: print “\n case is 0”; break; case 1: print “\n case is 1”; break; case 2: print “\n case is 2”; break; case 3: print “\n case is 3”; break; case 4: print “\n case is 4”; break; default: print (“\n Case is “ + $random); }

If you want more than one case to execute if a given case is true then omit its break. This will not stop the case from executing the cases which follow. The switch will not exit until it reaches the end of the cases or en-counters another break .

Page 17: Mel for beginners

Commands to learn: conncetAttr, disconnectAttr

Using connectAttr and disconnectAttr commands we can connect or disconnect the connections be-tweeen the two different nodes. We can connect only similar data type of output and input.

disconnectAttr file1.outColor blinn3.color; shadingNode -asTexture checker; shadingNode -asUtility place2dTexture; connectAttr place2dTexture1.outUV checker1.uv; connectAttr place2dTexture1.outUvFilterSize checker1.uvFilterSize; connectAttr -force checker1.outColor blinn3.color;

Assignment10: disconnect all the diffuse textures and make them grayAssignment11: select hidden lights/non hidden lights

Expressions and MEL scripts

Expressions Expressions are simply run time MEL commands that animate pretty much any given attribute in Maya. This can be looked at as procedural animation. Animation with little to no user intervention and no . To activate an expression open the expression editorWindows -> Animation Editors -> Expression Editor I find it useful to name your expressions when creating them. Maya by default will give them the name expression1, expression2, etc... If you are using a vast amount of expressions this could confuse you when trying to edit a specific expression.

You can also select Select Filter switch this to by expression name.

This will show you all of the expression your Maya project currently hold.

General guidelines

• Expressions are executed on every frame.• Expressions can only access attributes of type float, int, or boolean. • Avoid using setAttr and getAttr. instead directly set the objects attribute. $float $myScale = box.scale; box.scale = $myScale; • Attributes with incoming connections already existing will not take an expression. Break connections on the

object before attempting to connect an expression to it. • Time = frame/rate• If you are writing an expression under the by object/attribute name window view. You can omit the objects

name and simply call the attribute which you are setting. Maya understands that tx = 10; would be the same as ball.translateX = 10

Procedures, Functions, Recursion

Functions A function is a group of statements that is given a name, and which can be called from some point of the program. There are several types of functions available in Maya. Lets see few of them. Types of functions: Limit, Exponential, Trigonometric, Array, Random

Page 18: Mel for beginners

Limit Functions: abs, ceil, floor, clamp etcabs Operation: absolute value Supported Data types: int float vector abs(-5); // Result: 5 // Exponential Functions: exp,log, log10, pow, sqrt etc.

pow Operation: Returns a base number raised to an exponent supported Data types: float float pow(float base, float exponent )

pow(2,3); // Result: 8 //

Assignment12A: Find out other types of functions available in MayaAssignment12B: Create animation of universe using expressions and functionsAssignment 13: Create a plane and make terrain using vertices of it

Procedures Procedures can be looked at as a custom set of structured MEL commands that perform a specific action. If you have programmed before you could make the connection that a MEL procedure is much like a function in another languages. A nice aspect of a procedure is that you can feed it a variable and have it return data. There is one stipulation when using procedures in Maya, you can not use a procedure within a procedure.

Simple procedure

proc hello() { print (“\nHello World”); }

Hit enter and then type hello();

Simple procedure with user input

proc hello(string $name) { print (“\nHello “+$name); }

Hit enter and type in hello(“John”);

This procedure takes user input. When specifying a string value you need to place the string in quotes.

Passing Values through a procedure

Page 19: Mel for beginners

proc int myVal(int $a, int $b) { int $c = $a + $b; return $c; } int $returned = myVal(10,20); print $returned;

When using a procedure that returns a value specify what data type the return value is the declaration of the pro-cedure.

Global Vs Local variables

Now that we understand the basics of a procedure, it is important understand the scope of variables. Variables are only seen within the braces that they reside { }, and their children. Braces are also known as blocks. Take the following code as an example.

{ int $a = 5; { int $b =6; print $a; } print $b; } Variable $a will print a value of 5 because the print command is in the scope of variable $a. When print $b is reached we receive an error because variable $b was initialized in a different block. Variable $a was able to print because the print command resided in a child block. What if we, the user, want a variable or procedure that can be seen by any given Mel script after its init-ilization? This is where global and local variables come into play. Prior to this point we have been using local variables and procedures. If we want a variable or procedure to be global we must specify this at creation time.

Global Variables

To initialize a global variable you must declare it at the top most block structure of your code. You will need to re-initialize it in any blocks that you want to use it in after initialization. If you fail to do this, the block structure will assume the variable is a new local variable and not associate it with the global variable.

{ global string $myGlobalString; { global string $myGlobalString = “yes”; print $myGlobalString; } }

An important complication of global variables is to realize that they are only initialized once. This could be a good thing or a bad thing depending on how you look at it. If you are dependent on the global variable to have a constant start value, you may want to have a procedure that reassigns the global variables value after it is use.

Page 20: Mel for beginners

Global Procedures

Global Procedures are not much different than global variables. Once declared they are visible throughout Maya.

{ global proc float myGlobalProc(float $myInput) { float $myNewValue = $myInput * 3.25; return $myNewValue; } }

Type this in and hit enter. This will initialize our global procedure. This is a global proc that returns a value. To make it a global procedure that does not return a value simply write the procedure as follows.

{ global proc myGlobalProc2(float $myInput) { float $myNewValue = $myInput * 3.25; print $myNewValue; } }

Lastly when saving a global procedure you want to say your script into your scripts directory.Run this command to find out where your user script dirctory resides. string $dir = `internalVar -userScriptDir`;

Assignment13: Create a procedure to set renderglobalsAssignment14: create a procedure for your final project

Week 4User interaction

Windows are a nice way to package your MEL scripts. Using windows allows the user to input / change data used by your MEL scripts on the fly. They can also be useful for making list of commonly used commands. If we did not use a window to process our procedures the user would have to either type in the variables value when calling the procedure or they would have to edit the variables value in the MEL script before using it.

-windows

-creating windowsThis is the core of writing a window. Every window must start with this command window windowName;

Page 21: Mel for beginners

In order to have the window show you must call this command. Call this command after you have writing every-thing you want to go into your window. showWindow windowName; -deleting old windows.In order to open a window again. you need to delete the window. Place this code before the window command. if (`window -exists windowName`) deleteUI windowName; -positioning windows. All elements in your interface must be placed within a Layout. There are a number of layouts for the con-tents of windows. Some examples:

• ColumnLayout • RowLayout • RowColumnLayout • ScrollLayout • FrameLayout • FormLayout Use the following formats to position and size your windows

if (`window -exists $window`) deleteUI $window; string $window = `window -title “MyWindow” -iconName “Render” -widthHeight 200 55`; columnLayout -adjustableColumn true; button -label “Deleteme” -command (“delete”); button -label “Close” -command (“deleteUI -window “ + $window); setParent ..; showWindow $window;

-popup windows promptDialog confirmDialog

Another example to create a window and set the values of the objects

Page 22: Mel for beginners

{ string $my[] = `ls -sl`; int $mysize = size($my); if ($mysize > 1) error (“please select only one obj”); if ($mysize < 1) error (“please select an obj”); string $myattX = $my[0] + “.sx”; string $myattY = $my[0] + “.sy”; string $myattZ = $my[0] + “.sz”; window myWin1; columnLayout; attrFieldSliderGrp -min 0 -max 10 -at $myattX; attrFieldSliderGrp -min 0 -max 10 -at $myattY; attrFieldSliderGrp -min 0 -max 10 -at $myattZ; showWindow myWin1; }

Buttons are pretty easy to understand. You click the button, something happens. To see a full list of options asso-ciated with buttons consult the maya help menu.

-buttons

//create a list of buttons.

Page 23: Mel for beginners

if (`window -exists myButtons`) { deleteUI myButtons; windowPref -remove myButtons; }

window -widthHeight 155 175 myButtons; columnLayout -columnWidth 250 -rowSpacing 10 -columnOffset “left” 25; button -label “Default” -width 100; button -label “Left” -align “left” -width 100; button -label “Centre” -align “center” -width 100; button -label “Right” -align “right” -width 100; showWindow myButtons;

-radioButtonGrp //radio button groups that arelinked together. //click the button to print out its color

string $window = `window`; columnLayout; string $group1 = `radioButtonGrp -numberOfRadioButtons 3 -label “Colors” -labelArray3 “Red” “Blue” “Green” -on1 “doWrite(0)” -on2 “doWrite(1)” -on3 “doWrite(2)”`; radioButtonGrp -numberOfRadioButtons 3 -shareCollection $group1 -label “” -labelArray3 “Yellow” “Orange” “Purple” -on1 “doWrite(3)” -on2 “doWrite(4)” -on3 “doWrite(5)”; showWindow $window; proc doWrite(int $color) { //the value you put into the doWrite() corrilates to this array string $mycolor[] ={“Red”,”Blue”,”Green”,”Yellow”,”Orange”,”Purple”}; print (“\nyou clicked the color “+$mycolor[$color]); }

Page 24: Mel for beginners

-iconTextButton//Make an image a button.

string $window = `window -t “Mywindow”`; columnLayout -adjustableColumn true; iconTextButton -style “textOnly” -image1 “sphere.xpm” -label “sphere”; iconTextButton -style “iconOnly” -image1 “spotlight.xpm” -label “spotlight”; iconTextButton -style “iconAndTextHorizontal” -image1 “cone.xpm” -label “cone”; iconTextButton -style “iconAndTextVertical” -image1 “cube.xpm” -label “cube” ; showWindow $window;

Page 25: Mel for beginners

Controls

The Controls are the elements in your interface where the real work takes place: buttons, input fields, sliders and text areas. An overview of the most common controls:

Page 26: Mel for beginners

You can find a complete overview of the available controls in the MEL Command Reference. Most controls have various options (flags). Some controls can show multiple input fields at once (e.g: to input X, Y and Z values), have a text label or allow widths to be set for a field or other element of the control. All these options are documented in the MEL Command Reference.

Designing custom UI/ Creating UI using Qt

QT is a software in which we can develop programmes. Qt designer will automatically get installed while installing Maya. Through qt desiger we can design the layout of our script and we can assign commands to it.

You will find in the below path

C:\Program Files\Autodesk\Maya2013\bin\designer.exe

You can create ui (buttons,sliders etc) using designer, and using property editor in qt add dynamic property. You can write the procedure name there. While loading it create the procedure with same name which is connected to the button. Below is the example for a small script.

string $dialog = `loadUI -uiFile (“d:/test.ui”)`; //test.ui is created using designer and there is a button to which a procedure attached having name “try” showWindow $dialog; proc try() { delete; }

Page 27: Mel for beginners

Project‐ Create your own customized tool Create a final project : Procedural modeling/Automate of work

Recommended Readings

1. Complete Maya Programming: An Extensive Guide to MEL and C++ API by David Gould 2. Maya documentation3. http://nccastaff.bournemouth.ac.uk/jmacey/RobTheBloke/www/mel/index.html4. http://www.fundza.com/index.html

Thanks for reading this book, clarifications/suggestions are welcome. Please write me to [email protected]