SlideShare a Scribd company logo
1 of 27
Download to read offline
MEL for Beginners
By Kedarnath
m_kedar_nath@yahoo.com
Overview
	 An introduction to Maya Embedded Language (MEL) as a tool for animators to streamline work flow,
exercise control over complex operations, and to explore ideas originati8ng from the generation of motion
graphics through mathematical procedures
Prerequisite
	 Knowledge of Maya
Who should attend this
	 Students/artists who want to automate their work and grow in the industry
Week 1
•	 Overview of Maya’s Dependency Graph Architecture
•	 Intro to MEL and its syntax
•	 Ways to create scripts
•	 Customizing Maya
•	 Creating .mel files
•	 start using Maya commands
Week 2
•	 Variables, Data Types, and Operators
•	 Integrating variables into Maya commands
•	 Manipulating attributes
Week3
•	 Using the Hypergraph and Hypershade
•	 Conditional and looping Statements
•	 Expressions and MEL scripts
•	 procedures, functions, recursion
Week 4
•	 User interaction
•	 Designing custom UI/ Creating interface using qt
•	 Project‐ Create customized tool
Maya Scripting – MEL or PYTHON
	 People generally ask which scripting language should we learn first. I prefer “learn MEL first and once
we are confident about it and understand it then start with Python”. It’s not to say you can’t do the same with
Python if you’re a fast learner, but generally speaking you’ll be up and running with MEL a lot quicker.
	 If you have good knowledge of programming knowledge then you can start with Python, where you can
develop scripts for Maya as well as for other packages.
Advantages of MEL
•	 MEL scripting is native to Maya.
•	 With the little knowledge of MEL we can start working with it.
•	 Easy to understand
•	 Extensive MEL documentation is available
•	 It shows in the script editor
Advantages of Python
•	 Python can do almost everything MEL can + more.
•	 If you ever want to develop tools outside of Maya, or Maya tools that interact with other software, python
is the way to go with having external libraries.
Week 1
Overview of Maya’s Dependency Graph Architecture
	 The entire Maya scene is a single Dependency Graph, which is built from Dependency Nodes connected
through Plugs (think it as a brain made of interconnected neurons).
Dependency Graph
	 Dependency Graph node. Two main important things here, nodes and their attributes. The dependency
graph is a way wherein you can connect multiple nodes to come up with an output (rendered images, animat‐
ed geometry, etc.), in fact you can actually define almost any scene file by what nodes are present and what
connections exist between these nodes. A DG node is any node that can be connected to other nodes, and
they are not necessarily visible in the Scene Hierarchy, but you can show the Dependency Graph of a particular
object by selecting it and clicking the Input and Output Connections mode.
	
	 Every time the Maya user manipulates the scene he may add or remove nodes from the graph, connect
or disconnect plugs, or feed some new data. After parts of the dependency graph have been manipulated, it
is in a dirty state and must be brought up to date before being displayed. But instead of evaluating the entire
graph (which would be very slow in a complex Maya scene), only the dirty parts of the graph which actually
need updating will be evaluated.
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;
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 directory
C:/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 //
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;
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 scripting
Assignment2: Create a basic computer table using scripting and save the script as .mel file which can be used
directly
Assignment3: Create a room with spiral stair case
Week 2
Variables, 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
$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
==
equal to
	 A == B
< !=
	 not equal to
	 A != B
Logical Operators
Use 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 //
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
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;
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”);
	}
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
	}
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));
switch
The 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 .
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 gray
Assignment11: 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 editor
Windows -> 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
Limit Functions: abs, ceil, floor, clamp etc
abs
	 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 Maya
Assignment12B: Create animation of universe using expressions and functions
Assignment 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
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.
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 renderglobals
Assignment14: create a procedure for your final project
Week 4
User 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 windows
This is the core of writing a window. Every window must start with this command
	 window windowName;
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
{
	 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.
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]);
	}
-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;
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:
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 FilesAutodeskMaya2013bindesigner.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;
	}
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 documentation
3. http://nccastaff.bournemouth.ac.uk/jmacey/RobTheBloke/www/mel/index.html
4. http://www.fundza.com/index.html
	 Thanks for reading this book, clarifications/suggestions are welcome.
	 Please write me to m_kedar_nath@yahoo.com

More Related Content

What's hot

코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011Esun Kim
 
[NDC 2014] 던전앤파이터 클라이언트 로딩 최적화
[NDC 2014] 던전앤파이터 클라이언트 로딩 최적화[NDC 2014] 던전앤파이터 클라이언트 로딩 최적화
[NDC 2014] 던전앤파이터 클라이언트 로딩 최적화Jaeseung Ha
 
Maven tutorial
Maven tutorialMaven tutorial
Maven tutorialDragos Balan
 
게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013
게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013
게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013영욱 오
 
멀티스레드 렌더링 (Multithreaded rendering)
멀티스레드 렌더링 (Multithreaded rendering)멀티스레드 렌더링 (Multithreaded rendering)
멀티스레드 렌더링 (Multithreaded rendering)Bongseok Cho
 
문석진, 프로젝트DH의 절차적 애니메이션 시스템 Ⅱ, NDC2018
문석진, 프로젝트DH의 절차적 애니메이션 시스템 Ⅱ, NDC2018문석진, 프로젝트DH의 절차적 애니메이션 시스템 Ⅱ, NDC2018
문석진, 프로젝트DH의 절차적 애니메이션 시스템 Ⅱ, NDC2018devCAT Studio, NEXON
 
[IGC 2017] 아마존 구승모 - 게임 엔진으로 서버 제작 및 운영까지
[IGC 2017] 아마존 구승모 - 게임 엔진으로 서버 제작 및 운영까지[IGC 2017] 아마존 구승모 - 게임 엔진으로 서버 제작 및 운영까지
[IGC 2017] 아마존 구승모 - 게임 엔진으로 서버 제작 및 운영까지강 민우
 
GPGPU(CUDA)를 이용한 MMOG 캐릭터 충돌처리
GPGPU(CUDA)를 이용한 MMOG 캐릭터 충돌처리GPGPU(CUDA)를 이용한 MMOG 캐릭터 충돌처리
GPGPU(CUDA)를 이용한 MMOG 캐릭터 충돌처리YEONG-CHEON YOU
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
UE4 Garbage Collection
UE4 Garbage CollectionUE4 Garbage Collection
UE4 Garbage CollectionQooJuice
 
KGC 2014 프로파일러를 이용한 게임 클라이언트 최적화
KGC 2014 프로파일러를 이용한 게임 클라이언트 최적화KGC 2014 프로파일러를 이용한 게임 클라이언트 최적화
KGC 2014 프로파일러를 이용한 게임 클라이언트 최적화Jongwon Kim
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.jsPagepro
 
R2서버정진욱
R2서버정진욱R2서버정진욱
R2서버정진욱jungjinwouk
 
중앙 서버 없는 게임 로직
중앙 서버 없는 게임 로직중앙 서버 없는 게임 로직
중앙 서버 없는 게임 로직Hoyoung Choi
 
OpenGL 3.2 and More
OpenGL 3.2 and MoreOpenGL 3.2 and More
OpenGL 3.2 and MoreMark Kilgard
 

What's hot (20)

코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011
 
[NDC 2014] 던전앤파이터 클라이언트 로딩 최적화
[NDC 2014] 던전앤파이터 클라이언트 로딩 최적화[NDC 2014] 던전앤파이터 클라이언트 로딩 최적화
[NDC 2014] 던전앤파이터 클라이언트 로딩 최적화
 
Maven tutorial
Maven tutorialMaven tutorial
Maven tutorial
 
Vue 2 vs Vue 3.pptx
Vue 2 vs Vue 3.pptxVue 2 vs Vue 3.pptx
Vue 2 vs Vue 3.pptx
 
게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013
게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013
게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013
 
멀티스레드 렌더링 (Multithreaded rendering)
멀티스레드 렌더링 (Multithreaded rendering)멀티스레드 렌더링 (Multithreaded rendering)
멀티스레드 렌더링 (Multithreaded rendering)
 
Basics of VueJS
Basics of VueJSBasics of VueJS
Basics of VueJS
 
Express node js
Express node jsExpress node js
Express node js
 
문석진, 프로젝트DH의 절차적 애니메이션 시스템 Ⅱ, NDC2018
문석진, 프로젝트DH의 절차적 애니메이션 시스템 Ⅱ, NDC2018문석진, 프로젝트DH의 절차적 애니메이션 시스템 Ⅱ, NDC2018
문석진, 프로젝트DH의 절차적 애니메이션 시스템 Ⅱ, NDC2018
 
[IGC 2017] 아마존 구승모 - 게임 엔진으로 서버 제작 및 운영까지
[IGC 2017] 아마존 구승모 - 게임 엔진으로 서버 제작 및 운영까지[IGC 2017] 아마존 구승모 - 게임 엔진으로 서버 제작 및 운영까지
[IGC 2017] 아마존 구승모 - 게임 엔진으로 서버 제작 및 운영까지
 
GPGPU(CUDA)를 이용한 MMOG 캐릭터 충돌처리
GPGPU(CUDA)를 이용한 MMOG 캐릭터 충돌처리GPGPU(CUDA)를 이용한 MMOG 캐릭터 충돌처리
GPGPU(CUDA)를 이용한 MMOG 캐릭터 충돌처리
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
UE4 Garbage Collection
UE4 Garbage CollectionUE4 Garbage Collection
UE4 Garbage Collection
 
KGC 2014 프로파일러를 이용한 게임 클라이언트 최적화
KGC 2014 프로파일러를 이용한 게임 클라이언트 최적화KGC 2014 프로파일러를 이용한 게임 클라이언트 최적화
KGC 2014 프로파일러를 이용한 게임 클라이언트 최적화
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Multithread & shared_ptr
Multithread & shared_ptrMultithread & shared_ptr
Multithread & shared_ptr
 
R2서버정진욱
R2서버정진욱R2서버정진욱
R2서버정진욱
 
중앙 서버 없는 게임 로직
중앙 서버 없는 게임 로직중앙 서버 없는 게임 로직
중앙 서버 없는 게임 로직
 
OpenGL 3.2 and More
OpenGL 3.2 and MoreOpenGL 3.2 and More
OpenGL 3.2 and More
 
Motion blur
Motion blurMotion blur
Motion blur
 

Similar to Mel for beginners

advancedzplmacroprogramming_081820.pptx
advancedzplmacroprogramming_081820.pptxadvancedzplmacroprogramming_081820.pptx
advancedzplmacroprogramming_081820.pptxssuser6a1dbf
 
Object Oriented Programming with COBOL
Object Oriented Programming with COBOLObject Oriented Programming with COBOL
Object Oriented Programming with COBOLMicro Focus
 
Session 05 – mel and expression
Session 05 – mel and expressionSession 05 – mel and expression
Session 05 – mel and expressionTrí Bằng
 
Scalaマクロ入門 bizr20170217
Scalaマクロ入門 bizr20170217 Scalaマクロ入門 bizr20170217
Scalaマクロ入門 bizr20170217 dcubeio
 
Cs2305 programming paradigms lecturer notes
Cs2305   programming paradigms lecturer notesCs2305   programming paradigms lecturer notes
Cs2305 programming paradigms lecturer notesSaravanakumar viswanathan
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On RailsBalint Erdi
 
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...Jose Quesada (hiring)
 
About Functional Programming
About Functional ProgrammingAbout Functional Programming
About Functional ProgrammingAapo KyrÜlä
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryPray Desai
 
Introduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallIntroduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallJohn Mulhall
 
C++ & VISUAL C++
C++ & VISUAL C++ C++ & VISUAL C++
C++ & VISUAL C++ Makaha Rutendo
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptxVijalJain3
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updatesVinay H G
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 
Data abstraction and object orientation
Data abstraction and object orientationData abstraction and object orientation
Data abstraction and object orientationHoang Nguyen
 
Introduction to MLflow
Introduction to MLflowIntroduction to MLflow
Introduction to MLflowDatabricks
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016Martin Odersky
 

Similar to Mel for beginners (20)

advancedzplmacroprogramming_081820.pptx
advancedzplmacroprogramming_081820.pptxadvancedzplmacroprogramming_081820.pptx
advancedzplmacroprogramming_081820.pptx
 
Object Oriented Programming with COBOL
Object Oriented Programming with COBOLObject Oriented Programming with COBOL
Object Oriented Programming with COBOL
 
Session 05 – mel and expression
Session 05 – mel and expressionSession 05 – mel and expression
Session 05 – mel and expression
 
Scalaマクロ入門 bizr20170217
Scalaマクロ入門 bizr20170217 Scalaマクロ入門 bizr20170217
Scalaマクロ入門 bizr20170217
 
Cs2305 programming paradigms lecturer notes
Cs2305   programming paradigms lecturer notesCs2305   programming paradigms lecturer notes
Cs2305 programming paradigms lecturer notes
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
 
About Functional Programming
About Functional ProgrammingAbout Functional Programming
About Functional Programming
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 
Introduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallIntroduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John Mulhall
 
C++ & VISUAL C++
C++ & VISUAL C++ C++ & VISUAL C++
C++ & VISUAL C++
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Java unit 7
Java unit 7Java unit 7
Java unit 7
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updates
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
CoreML
CoreMLCoreML
CoreML
 
Data abstraction and object orientation
Data abstraction and object orientationData abstraction and object orientation
Data abstraction and object orientation
 
Introduction to MLflow
Introduction to MLflowIntroduction to MLflow
Introduction to MLflow
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 

More from kedar nath

Myraytracer
MyraytracerMyraytracer
Myraytracerkedar nath
 
Maths&programming forartists wip
Maths&programming forartists wipMaths&programming forartists wip
Maths&programming forartists wipkedar nath
 
Understnading HDRI for VFX Lighting
Understnading HDRI for VFX LightingUnderstnading HDRI for VFX Lighting
Understnading HDRI for VFX Lightingkedar nath
 
LightingTD_course_ katanaRenderman
LightingTD_course_ katanaRendermanLightingTD_course_ katanaRenderman
LightingTD_course_ katanaRendermankedar nath
 
LPEs in KATANA and Maya
LPEs in KATANA and MayaLPEs in KATANA and Maya
LPEs in KATANA and Mayakedar nath
 
Python for katana
Python for katanaPython for katana
Python for katanakedar nath
 

More from kedar nath (6)

Myraytracer
MyraytracerMyraytracer
Myraytracer
 
Maths&programming forartists wip
Maths&programming forartists wipMaths&programming forartists wip
Maths&programming forartists wip
 
Understnading HDRI for VFX Lighting
Understnading HDRI for VFX LightingUnderstnading HDRI for VFX Lighting
Understnading HDRI for VFX Lighting
 
LightingTD_course_ katanaRenderman
LightingTD_course_ katanaRendermanLightingTD_course_ katanaRenderman
LightingTD_course_ katanaRenderman
 
LPEs in KATANA and Maya
LPEs in KATANA and MayaLPEs in KATANA and Maya
LPEs in KATANA and Maya
 
Python for katana
Python for katanaPython for katana
Python for katana
 

Recently uploaded

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 

Recently uploaded (20)

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 

Mel for beginners

  • 1. MEL for Beginners By Kedarnath m_kedar_nath@yahoo.com
  • 2. Overview An introduction to Maya Embedded Language (MEL) as a tool for animators to streamline work flow, exercise control over complex operations, and to explore ideas originati8ng from the generation of motion graphics through mathematical procedures Prerequisite Knowledge of Maya Who should attend this Students/artists who want to automate their work and grow in the industry Week 1 • Overview of Maya’s Dependency Graph Architecture • Intro to MEL and its syntax • Ways to create scripts • Customizing Maya • Creating .mel files • start using Maya commands Week 2 • Variables, Data Types, and Operators • Integrating variables into Maya commands • Manipulating attributes Week3 • Using the Hypergraph and Hypershade • Conditional and looping Statements • Expressions and MEL scripts • procedures, functions, recursion Week 4 • User interaction • Designing custom UI/ Creating interface using qt • Project‐ Create customized tool
  • 3. Maya Scripting – MEL or PYTHON People generally ask which scripting language should we learn first. I prefer “learn MEL first and once we are confident about it and understand it then start with Python”. It’s not to say you can’t do the same with Python if you’re a fast learner, but generally speaking you’ll be up and running with MEL a lot quicker. If you have good knowledge of programming knowledge then you can start with Python, where you can develop scripts for Maya as well as for other packages. Advantages of MEL • MEL scripting is native to Maya. • With the little knowledge of MEL we can start working with it. • Easy to understand • Extensive MEL documentation is available • It shows in the script editor Advantages of Python • Python can do almost everything MEL can + more. • If you ever want to develop tools outside of Maya, or Maya tools that interact with other software, python is the way to go with having external libraries.
  • 4. Week 1 Overview of Maya’s Dependency Graph Architecture The entire Maya scene is a single Dependency Graph, which is built from Dependency Nodes connected through Plugs (think it as a brain made of interconnected neurons). Dependency Graph Dependency Graph node. Two main important things here, nodes and their attributes. The dependency graph is a way wherein you can connect multiple nodes to come up with an output (rendered images, animat‐ ed geometry, etc.), in fact you can actually define almost any scene file by what nodes are present and what connections exist between these nodes. A DG node is any node that can be connected to other nodes, and they are not necessarily visible in the Scene Hierarchy, but you can show the Dependency Graph of a particular object by selecting it and clicking the Input and Output Connections mode. Every time the Maya user manipulates the scene he may add or remove nodes from the graph, connect or disconnect plugs, or feed some new data. After parts of the dependency graph have been manipulated, it is in a dirty state and must be brought up to date before being displayed. But instead of evaluating the entire graph (which would be very slow in a complex Maya scene), only the dirty parts of the graph which actually need updating will be evaluated.
  • 5. 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;
  • 6. 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 directory C:/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 //
  • 7. 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;
  • 8. 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 scripting Assignment2: Create a basic computer table using scripting and save the script as .mel file which can be used directly Assignment3: Create a room with spiral stair case
  • 9. Week 2 Variables, 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
  • 10. $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 ==
  • 11. equal to A == B < != not equal to A != B Logical Operators Use 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 //
  • 12. 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
  • 13. 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;
  • 14. 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”); }
  • 15. 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 }
  • 16. 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)); switch The 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 .
  • 17. 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 gray Assignment11: 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 editor Windows -> 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
  • 18. Limit Functions: abs, ceil, floor, clamp etc abs 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 Maya Assignment12B: Create animation of universe using expressions and functions Assignment 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
  • 19. 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.
  • 20. 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 renderglobals Assignment14: create a procedure for your final project Week 4 User 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 windows This is the core of writing a window. Every window must start with this command window windowName;
  • 21. 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
  • 22. { 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.
  • 23. 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]); }
  • 24. -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;
  • 25. 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:
  • 26. 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 FilesAutodeskMaya2013bindesigner.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; }
  • 27. 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 documentation 3. http://nccastaff.bournemouth.ac.uk/jmacey/RobTheBloke/www/mel/index.html 4. http://www.fundza.com/index.html Thanks for reading this book, clarifications/suggestions are welcome. Please write me to m_kedar_nath@yahoo.com