expressions-- maya expression editor from basic to professional

274
Expressions

Upload: emin-urundas

Post on 22-Feb-2015

483 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Expressions-- Maya Expression Editor From Basic to Professional

Expressions

Page 2: Expressions-- Maya Expression Editor From Basic to Professional
Page 3: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 3

Expressions

3 Introducing Expressions 11About expressions 12

Where you create expressions 13

4 Quick Start 15Preparing for the examples 15

Creating a simple expression 17

Controlling multiple attributes of an object 23

Controlling attributes in two objects 28

Controlling attributes conditionally 32

Notes on the predefined time variable 43

5 Expression Syntax 45Expressions and MEL 46

Elements of an expression 47

Attributes 49

Static attributes 49

Dynamic attributes 49

Custom attributes 50

Attribute names 51

Data types of attributes 51

Assigning a value to an attribute 55

Variables 56

Data types of variables 57

Predefined variables 57

Custom variables 59

Page 4: Expressions-- Maya Expression Editor From Basic to Professional

4 Using Maya: Hypergraph, Sets & Expressions

ExpressionsContents

Constants 62

Arithmetic, logic, and relational operators 63

Arithmetic operators 63

Relational operators 65

Logical operators 67

Operator precedence 68

Conditional statements 69

if statements 69

if-else statements 70

else if statements 71

General syntax rules 73

Comments in expressions 75

Programming features 75

Notes for C programmers 75

Expression language keywords 76

Flow control statements 77

Flow control errors 88

String usage 90

Shortcut assignment operators 91

Shortcut increment and decrement operators 92

Arrays 93

Boolean symbolic constants 95

Common expression errors 95

Error message format 95

Common error messages 97

6 Editing Expressions 99Finding expressions 99

Finding by expression name 100

Finding by selected object 101

Page 5: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 5

ExpressionsContents

Finding by item type 102

Using the Selection list 103

Filtering attributes from the Selection list 104

Editing an expression in the text field 105

Deleting and copying text 105

Clearing the expression text field 106

Reloading an expression’s previous contents 106

Editing an expression with a text editor 106

Using an editor listed in the Editor menu 107

Using an editor not listed in the Editor menu 109

Changing an editor’s operation settings 110

Selecting an editor for default startup 110

Creating a new expression 111

Deleting an expression 112

Using attribute names in expressions 112

Using attribute name abbreviations 113

Omitting an object name in expressions 115

Combining the abbreviation techniques 116

7 Beyond the Basics 117How often an expression executes 118

Using custom attributes in expressions 118

Displaying attribute and variable contents 123

Reproducing randomness 123

Speeding expression execution 127

Reducing redundant expression execution 130

Removing an attribute from an expression 131

Disconnecting an attribute 132

Displaying disconnected attributes in expressions 132

Connecting an attribute to a symbolic placeholder 135

Page 6: Expressions-- Maya Expression Editor From Basic to Professional

6 Using Maya: Hypergraph, Sets & Expressions

ExpressionsContents

Renaming an object 136

Executing MEL commands in an expression 137

Understanding path names 140

Understanding unexpected attribute values 141

Values after rewinding 141

Increment operations 142

Data type conversions 143

8 Particle Expressions 147Understanding particle expressions 148

Understanding creation expression execution 149

Setting the dynamics start frame 149

Setting attributes for initial state usage 150

Writing creation expressions 150

Understanding runtime expression execution 152

Writing runtime expressions 153

Working with particle attributes 159

Adding dynamic attributes 159

Understanding per particle and per object attributes 160

Understanding initial state attributes 162

Example of assigning to a dynamic per particle attribute 164

Example of assigning to a dynamic per object attribute 167

Assigning to a custom attribute 169

Assigning to a particle array attribute of different length 172

Using creation expression values in a runtime expression 174

Working with position, velocity, and acceleration 175

Working with color 178

Working with emitted particles 183

Working with collisions 183

Working with specific particles 189

Page 7: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 7

ExpressionsContents

Assigning to vectors and vector arrays 193

List of particle shape attributes 196

9 Functions 203Understanding functions 205

Function syntax 206

Data types 208

Understanding function examples in this chapter 208

Limit functions 209

abs 209

ceil 210

floor 210

clamp 211

min 212

max 212

sign 212

trunc 213

Exponential functions 214

exp 214

log 214

log10 214

pow 215

sqrt 215

Trigonometric functions 216

cos 216

cosd 218

sin 219

sind 224

tan 224

tand 225

Page 8: Expressions-- Maya Expression Editor From Basic to Professional

8 Using Maya: Hypergraph, Sets & Expressions

ExpressionsContents

acos 225

acosd 226

asin 226

asind 226

atan 227

atand 227

atan2 227

atan2d 228

hypot 228

Vector functions 229

angle 229

cross 230

dot 231

mag 231

rot 232

unit 233

Conversion functions 234

deg_to_rad 234

rad_to_deg 234

hsv_to_rgb 235

rgb_to_hsv 235

Array functions 236

clear 236

size 237

sort 237

Random number functions 239

gauss 239

noise 241

dnoise 242

rand 243

sphrand 244

Page 9: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 9

ExpressionsContents

seed 246

Curve functions 249

linstep 249

smoothstep 252

hermite 254

General commands 259

eval 259

print 261

system 263

Other functions and commands 264

Page 10: Expressions-- Maya Expression Editor From Basic to Professional

10 Using Maya: Hypergraph, Sets & Expressions

ExpressionsContents

Page 11: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 11

Ex

pre

ss

ion

s

3 Introducing Expressions

Expressions are instructions you type to control an object attribute over time.An attribute is a characteristic of an object, for instance, X scale, Y translate,visibility, and so on.

Though you can create an expression to animate attributes for any purpose,they’re ideal for attributes that change incrementally, randomly, orrhythmically over time.

Expressions are also useful for linking attributes between different objects—where a change in one attribute alters the behavior of the other. For instance,you can make the rotation of a tire dependent on the forward or backwardmovement of a car.

This chapter has the following topics:

• “About expressions” on page 12

• “Where you create expressions” on page 13

An expression gives themanta ray’s wings a fluid,rhythmic motion.

Eric Saindon

Page 12: Expressions-- Maya Expression Editor From Basic to Professional

12 Using Maya: Hypergraph, Sets & Expressions

Introducing ExpressionsAbout expressions

About expressionsExpressions offer an alternative to difficult keyframing tasks. In keyframing,you set the values of attributes at selected keyframes in the animation, andMaya interpolates the action between the keyframes. With expressions, youwrite a formula, then Maya performs the action as the animation plays.

Expressions are often as simple as a few words or lines. In the followingexample expressions, note the variation in length and detail (rather thantheir purpose).

Example

Ball.translateX = Cube.translateX + 4;

Example

if (frame == 1)Cone.scaleY = 1;

else{Cone.scaleY = (0.25 + sin(time)) * 3;print(Cone.scaleY + "\n");}

Though many expressions look like math or a programming language, youdon’t need to be a mathematician or programmer to learn how to use them.If you’re fond of programming, expressions offer unlimited animationtechniques that would challenge the skill of keyframing experts.

You can use an expression to animate any keyable, unlocked object attributefor any frame range. You can also use an expression to control per particle orper object attributes. Per particle attributes control each particle of an objectindividually. Per object attributes control all particles of an objectcollectively.

You cannot apply an expression to an attribute already animated with any ofthese techniques:

• keys

• set driven key

• constraint

• motion path

Page 13: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 13

Introducing ExpressionsWhere you create expressions

Ex

pre

ss

ion

s

• another expression

• any other direct connection

If you do so, you’ll see an error message in the Script Editor and theCommand Line’s response area.

Though you can’t control a single attribute with two of the precedingtechniques, you can control one attribute with keyframes, another with anexpression, another with a constraint, and so on.

Also, you can use a single expression to assign values to several attributes ofone or more objects.

Where you create expressionsYou create and edit an expression in the Expression Editor. There are severalways to start the Expression Editor:

• From the main menu bar or Hotbox, choose Window→Expression Editor.

• From the Channel Box, click the right mouse button in an attribute text fieldand select Expressions.

• From the Attribute Editor, click the right mouse button in an attribute textfield and select Create New Expression, Edit Expression, or ExpressionEditor.

You cannot start the Expression Editor from every attribute text field in theChannel Box and Attribute Editor. Use Window→Expression Editor ifnecessary.

Page 14: Expressions-- Maya Expression Editor From Basic to Professional

14 Using Maya: Hypergraph, Sets & Expressions

Introducing ExpressionsWhere you create expressions

The Expression Editor follows:

The expression text field expands as you type text, so you can writeexpressions of unlimited length. You can also edit expressions with a texteditor such as jot by selecting it from the Editor pull-down menu above thetext field.

Expression text field

Page 15: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 15

Ex

pre

ss

ion

s

4 Quick Start

The easiest way to learn about expressions is to work through examples. Forthis reason, we provide the following introductory lessons. Expressions thatcontrol particle attributes are more complex than for other objects. Forexamples, see Chapter 8, “Particle Expressions.”

In this chapter, you’ll learn about the following topics:

• “Creating a simple expression” on page 17

• “Controlling multiple attributes of an object” on page 23

• “Controlling attributes in two objects” on page 28

• “Controlling attributes conditionally” on page 32

• “Notes on the predefined time variable” on page 43

Preparing for the examplesA few preparatory steps will simplify your understanding of the examples inthis chapter. Before starting the examples, do these steps:

To prepare for the examples:

1 Select Options→General Preferences.

You can use an expression to linkattributes in different objects—soa change in one attribute altersthe behavior of the other.

Page 16: Expressions-- Maya Expression Editor From Basic to Professional

16 Using Maya: Hypergraph, Sets & Expressions

Quick StartPreparing for the examples

The General Preferences window appears.

Drag either side of the General Preferences window to expand its width. Youmust do this to display the Units tab in the window.

2 Click the Units tab.

3 In the Units tab, make sure Time is set to Film (24 fps).

This makes your animation play at the default rate of 24 frames per second.

4 In the General Preferences window, choose the Animation tab.

5 Enter 0 for the starting frame of the Time Slider and the Range Slider, andenter 300 for the ending frame of the Time Slider and Range Slider.

Specifying a range of 300 frames gives ample time to see the effects you’llcreate in the examples.

6 In the General Preferences window, click Save and Close.

7 At the top edge of the workspace, select Shading→Smooth Shade All todisplay all objects you create in the scene with smooth shading.

This will enhance the look of the objects you create in the examples.

8 From the menu bar, choose Window→Expression Editor to display theExpression Editor.

Important

For the lessons to work correctly, you must enter 0 for the starting frame ofthe Time Slider and Range Slider. Press your keyboard’s Enter key aftereach entry. Rewind the animation to frame 0. After doing the lessons, read“Notes on the predefined time variable” on page 43 for details on why thelessons require the starting frame to be 0.

Page 17: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 17

Quick StartCreating a simple expression

Ex

pre

ss

ion

s

9 Make sure these default Expression Editor menu options are selected:

Select Filter→By Object/Attribute Name

Object Filter→Selected Objects

Attribute Filter→All

“Finding expressions” in Chapter 6 gives details on these options.

Creating a simple expressionThe following steps show how to control an attribute of a single object. Anattribute is a characteristic of an object, for example, X scale, Y scale,X rotation, and so on.

In this example, you’ll learn how to stretch a sphere along its Y-axis bycontrolling its scaleY attribute as the animation plays.

To prepare the scene:

1 From the Modeling menu, choose Primitives→Create NURBS→Sphere.

This creates a NURBS sphere with an X scale, Y scale, and Z scale of 1.

2 In the Channel Box or elsewhere, name the sphere Ball.

3 Select Display→NURBS Smoothness→Fine to set Ball’s display smoothnessto fine resolution.

Maya displays the object with extra polygons to make it look smoother inthe workspace. This doesn’t affect the underlying model’s geometry. It altersonly its display.

4 Rewind the animation to frame 0.

Page 18: Expressions-- Maya Expression Editor From Basic to Professional

18 Using Maya: Hypergraph, Sets & Expressions

Quick StartCreating a simple expression

To create the expression:

1 Make sure Ball is selected.

2 Choose Window→Expression Editor to display the Expression Editor.

The selected object’s name, Ball, is highlighted in the Objects list of theExpression Editor.

3 Enter ScaleBallHeight in the Expression Name box.

Entering an expression name lets you find the expression easily in a laterwork session if you decide to alter it.

Use alphabetical and numerical characters for expression names. If you usespace characters or special characters such as a hyphen (-), Maya deletesthem or replaces them with an underscore character (_) after you finishcreating the expression.

4 Notice the Attributes list.

It displays Ball’s keyable, unlocked attributes—the attributes you’ll mostlikely want to animate with an expression. Use the scroll bar to see the entirelist.

5 Enter this expression in the expression text field:

Enter the expression with the same upper and lowercase spelling shown.Entries in the expression field are type case sensitive.

The semicolon (;) signifies the end of the expression statement. Eachstatement in an expression must end with a semicolon. The only exception iswhen the expression has a single statement.

An error message appears in the Script Editor and Command Line’sresponse area if the expression has incorrect syntax or typing mistakes.

Edit text the same way you edit other text fields in Maya.

Ball.scaleY = time + 1;

Page 19: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 19

Quick StartCreating a simple expression

Ex

pre

ss

ion

s

6 Click Create to compile the expression.

Compiling the expression checks it for syntax errors and converts it to aform Maya can execute when you rewind or play the animation. Clickingthis button also executes the expression for the current frame.

The expression sets Ball’s scaleY attribute to the value of time + 1. Ball.scaleYis the full name of the attribute. A period separates the name of the objectand attribute. You must spell them with uppercase and lowercase letters asthey appear in the Expression Editor’s Objects and Attributes lists. See“Using attribute names in expressions” in Chapter 6 for more details.

The word time is a predefined variable in Maya that updates as an animationplays. It contains the elapsed number of seconds from the first frame to thecurrent frame. The value increases with the increasing frame number.

At the default animation playback rate of 24 frames per second, time hasthese values, rounded to four decimal places:

If you ever need to change the playback rate, you can do so by choosingOptions→General Preferences. Expand the General Preferences window,display the Units folder, and choose the desired rate from the Time menu.

Regardless of what animation playback rate you choose, you can find thetime elapsed in the animation at any frame with this formula:

For example, if the frame rate is 24 frames/second and the animation is atframe 1, the elapsed time is 1 divided by 24, or 0.0417. At frame 6, theelapsed time is 6 divided by 24, which equals 0.25.

Frame Time (seconds)

0 0

1 0.0417

2 0.0833

3 0.125

24 1.0

240 10.0

timeframerate

---------------=

Page 20: Expressions-- Maya Expression Editor From Basic to Professional

20 Using Maya: Hypergraph, Sets & Expressions

Quick StartCreating a simple expression

If the frame rate is 30 frames/second and the animation is at frame 1, theelapsed time is 1 divided by 30, which equals 0.0333. At frame 6, elapsedtime is 6 divided by 30, which equals 0.2.

To see the result of the expression:

1 Rewind and play the animation.

Ball’s scaleY attribute increases as the time increases:

Maya executes the expression each frame. This causes the object size to scalealong its Y-axis, stretching its height during playback.

The scaling is smooth because the geometry stretches in synch with the smalltime increments of the animation playback.

Frame Time (seconds) Ball.scaleY (time + 1)

0 0 1

1 0.0417 1.0417

2 0.0833 1.0833

3 0.125 1.125

24 1.0 2.0

240 10.0 11.0

Page 21: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 21

Quick StartCreating a simple expression

Ex

pre

ss

ion

s

2 Stop and rewind the animation.

Rewinding the animation returns Ball to its original shape. This occursbecause the expression executes with time equal to 0. The value of time + 1 is1, the original scaleY value of Ball.

3 Play the animation.

This repeats the increasing scale.

4 Stop and rewind the animation.

5 Close the Expression Editor window.

This complete the steps to creating an expression.

To further your understanding of expressions, we’ve included the followingsteps to show how to edit the expression you just completed.

To edit the expression:

Suppose you decide that Ball scales too quickly as the animation plays. Youcan change the expression to see how the animation looks when you scaleBall half as fast.

1 Choose Window→Expression Editor to display the Expression Editor again.

You can find the expression you created earlier by:

• remembering the name of the expression

• remembering the name of the object and attribute you controlled with theexpression

• examining each expression in the scene that’s controlled by an expression

In this example, you’ll find the expression ScaleBallHeight by its name. SeeChapter 6, “Editing Expressions” for details on the other methods.

2 Choose Select Filter→By Expression Name.

3 Click ScaleBallHeight in the Expressions list.

The expression appears in the expression text field.

Page 22: Expressions-- Maya Expression Editor From Basic to Professional

22 Using Maya: Hypergraph, Sets & Expressions

Quick StartCreating a simple expression

4 Change the previous expression to this:

Ball.scaleY = time/2 + 1;

Use the same editing techniques you use with other text fields in Maya.

By dividing time by 2, you’ll make the Y scaling increase half as fast as withthe previous version of the expression.

5 Click Edit to compile the modified expression.

Compiling the expression checks it for syntax errors and converts it to aform Maya can execute when you rewind or play the animation. After beingcompiled, the expression executes for the current frame.

Clicking the Edit button does the same action as clicking the Create button.The Create button exists only for new expressions. The Edit button replacesthe Create button when you display an existing expression.

To see the result of the edited expression:

1 Play the animation.

Ball scales its Y dimension half as fast as with the previous expressioncontents.

2 Stop and rewind the animation.

Feel free to experiment with other values in the expression.

This concludes the first example. Before starting the next example, delete thescene and create a new scene.

Summary

In this lesson, you learned how to:

• name an expression and type it in the expression text field

Ball.scaleY = time + 1;

Page 23: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 23

Quick StartControlling multiple attributes of an object

Ex

pre

ss

ion

s

• compile an expression to a form Maya can execute

• work with the predefined variable time

• find an expression you previously created

• modify an expression

Controlling multiple attributes of an objectYou can use a single expression to control two or more attributes of anobject. In the following steps, you’ll use an expression to increase the X, Y,and Z scale attributes of a sphere as the animation plays.

To prepare the scene:

1 From the Modeling menu, choose Primitives→Create NURBS→Sphere.

This creates a NURBS sphere with an X scale, Y scale, and Z scale of 1.

2 In the Channel Box or elsewhere, name the sphere Planet.

3 Select Display→NURBS Smoothness→Fine to set the Planet’s displaysmoothness to fine resolution.

4 Display the Expression Editor and select Select Filter→By Object/AttributeName.

5 Rewind the animation to frame 0.

To create the expression:

1 Select the Planet object.

Planet becomes the selected object in the Expression Editor.

2 In the Expression Editor, enter ScalePlanet in the Expression Name box.

Page 24: Expressions-- Maya Expression Editor From Basic to Professional

24 Using Maya: Hypergraph, Sets & Expressions

Quick StartControlling multiple attributes of an object

This names the expression so you can find it more easily later.

3 Enter these statements in the expression text field:

The expression has three statements. Each statement sets an attribute to thevalue of the predefined variable time.

4 Click Create to compile the expression.

An error message appears in the Script Editor and Command Line’sresponse area if the expression has incorrect syntax.

Planet disappears because clicking Create also executes the expression at thecurrent frame after compiling. At frame 0, time is 0, so the value of thescaleX, scaleY, and scaleZ attributes becomes 0. Planet has no size, so itdisappears.

To see the result of the expression:

1 Play the animation.

The expression executes each frame, so Planet grows quickly as theanimation plays.

Page 25: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 25

Quick StartControlling multiple attributes of an object

Ex

pre

ss

ion

s

Because animation playback increases time, the value of Planet’s scaleX,scaleY, and scaleZ attributes increase at the rate of the increasing time.

The object increases its scale until the last frame of the Time Slider plays.

2 Stop and rewind the animation.

The following two series of steps show how to see the same result with othermethods.

To see the result by linking attribute values:

1 Change the expression to this:

Planet.scaleX = time;Planet.scaleY = Planet.scaleX;Planet.scaleZ = Planet.scaleX;

2 Click Edit to compile the expression.

3 Play the animation.

The expression works the same as the previous one. The first statement setsPlanet.scaleX to the value of time.

The second statement sets Planet.scaleY to the value of Planet.scaleX.Because you’ve set Planet.scaleX to the value of time, Planet.scaleY also hasthe value of time. You’re simply transferring one attribute’s value to another.

The third statement also sets Planet.scaleZ to the value of the attributePlanet.scaleX.

Page 26: Expressions-- Maya Expression Editor From Basic to Professional

26 Using Maya: Hypergraph, Sets & Expressions

Quick StartControlling multiple attributes of an object

The advantage of this expression is that if you assign a different value toPlanet.scaleX in the first statement, the second and third statementsautomatically receive the new value. In other words, you’ve linkedPlanet.scaleY and Planet.scaleZ to the value of Planet.scaleX—whatever itsvalue is.

4 Stop and rewind the animation.

5 In the first statement of the expression, divide time by 5 as follows:

Planet.scaleX = time/5;Planet.scaleY = Planet.scaleX;Planet.scaleZ = Planet.scaleX;

6 Click Edit to compile the expression.

7 Play the animation.

Planet increases its scale attributes one-fifth as fast of the previousexpression.

By assigning the value of Planet.scaleX to Planet.scaleY and Planet.scaleZ,Planet.scaleY and Planet.scaleZ were automatically assigned the value time/5 in the second and third statements.

8 Stop and rewind the animation.

You can get the same result using a variable in an expression.

To see the results using a variable:

1 Change the expression to this:

float $increment;$increment = time/5;Planet.scaleX = $increment;Planet.scaleY = $increment;Planet.scaleZ = $increment;

The expression has the same result as the previous one. The first statementdefines a variable named $increment to be used as storage for the value of atime increment. You define it as a floating point number—a number that canhave a decimal point.

The second statement assigns $increment the value of time divided by 5. Asthe animation plays and the time increases each frame, the value of$increment increases by the value of time divided by 5. The $incrementtherefore increases in smaller units than time increases.

Page 27: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 27

Quick StartControlling multiple attributes of an object

Ex

pre

ss

ion

s

The next three statements assign the contents of $increment to the three scaleattributes of Planet. The scale attributes therefore receive the value of timedivided by 5 each frame. This makes the object increase uniformly in scaleslowly as the animation plays.

2 Click Edit.

3 Play the animation.

The result is the same as with the previous expression

4 Stop and rewind the animation.

You can make a change to the variable assignment in the second statementwithout altering the other statements.

To modify the variable:

1 Change the expression to this:

float $increment;$increment = time * 2;Planet.scaleX = $increment;Planet.scaleY = $increment;Planet.scaleZ = $increment;

2 Click Edit.

3 Play the animation.

Because you assigned time * 2 to the variable $increment, the expression setsall three attributes to the value of time * 2 as the animation plays. This makesthe three scale attributes increase at a rate twice as fast as would occur if youassigned them the value of time alone.

4 Stop and rewind the animation.

This concludes the example. Before starting the next example, delete thescene and create a new scene.

Summary

In this lesson, you learned how to:

• link multiple attributes of the same object with a single expression

• use a variable you defined in an expression

• modify a single assignment to an attribute without changing otherstatements

Page 28: Expressions-- Maya Expression Editor From Basic to Professional

28 Using Maya: Hypergraph, Sets & Expressions

Quick StartControlling attributes in two objects

Controlling attributes in two objectsYou can write an expression to control attributes in two or more objects. Inthe following steps, you’ll create a cylinder and cone, then rotate eacharound its local X-axis as the animation plays. In other words, each objectwill spin around in place.

To see an object’s local rotation axes, select the object, then chooseDisplay→Object Components→Local Rotation Axes.

To prepare the scene:

1 From the Modeling menu, choose Primitives→Create NURBS→Cone.

2 In the Channel Box or elsewhere, name it Cone.

3 Choose Primitives→Create NURBS→Cylinder from the Modeling menu.

4 In the Channel Box or elsewhere, name the cylinder Can.

The exact translation and scale of Cone and Can is unimportant in thisexample. Give them roughly the same translation and scale as in the abovefigure.

5 Select both objects, then choose Display→NURBS Smoothness→Fine.

This sets the display smoothness of both objects to fine resolution.

6 Display the Expression Editor and select Select Filter→By Object/AttributeName.

7 Rewind the animation to frame 0.

Page 29: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 29

Quick StartControlling attributes in two objects

Ex

pre

ss

ion

s

To create the expression:

1 Select Can.

To control attributes in both objects, you can select either object to write theexpression. In fact, any object or node in a scene can be selected when youwrite an expression to control an object other than a particle object. Fordetails on creating expressions to control particles, see Chapter 8, “ParticleExpressions.”

2 In the Expression Editor, enter RotCanAndCone in the Expression Namebox.

This names the expression so you can find it more easily later.

3 Enter this expression:

Can.rotateX = time * 10;Cone.rotateX = time * 10;

This assigns Can’s rotateX attribute and Cone’s rotateX attribute to the valueof time multiplied by 10.

4 Click Create to compile the expression.

To see the results:

1 Play the animation.

Each object rotates around its local X-axis by the degree value resulting fromtime * 10. After 1 second, for example, the rotateX attribute of each object isone degree times 10, or 10 degrees. After 2 seconds, it’s 2 degrees times 10,or 20 degrees.

Maya works in degree angle units, by default. You can change the angularunits to radians by choosing Options→General Preferences and displayingthe Units folder.

Page 30: Expressions-- Maya Expression Editor From Basic to Professional

30 Using Maya: Hypergraph, Sets & Expressions

Quick StartControlling attributes in two objects

With the animation playing at 24 frames per second, each object’s rotateXattribute has these values:

The values in this chapter are rounded to four significant digits. The actualvalues might have many more digits.

To see the degree value of Can.rotateX at different frames, select Can,display the Channel Box, and stop the animation at selected frames. TheChannel Box updates its values after you stop the animation.

To see the degree value of Cone.rotateX at different frames, select Coneinstead of Can. The Channel Box displays values for the selected object.

2 Stop and rewind the animation.

You can edit the expression to make Can rotate slower than Cone.

To get different results:

1 Change to the expression to this:

Can.rotateX = time * 5;Cone.rotateX = time * 10;

2 Click Edit to compile the expression.

3 Play the animation.

Can rotates half as fast as Cone as the animation plays.

Frame Time Can.rotateX(degrees)

0 0 0

1 0.0417 0.417

2 0.0833 0.833

3 0.125 1.25

24 1.0 10

240 10.0 100

Page 31: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 31

Quick StartControlling attributes in two objects

Ex

pre

ss

ion

s

4 Stop and rewind the animation.

5 Close the Expression Editor window.

This concludes the example.

This example showed how to write a single expression to control attributesof two different objects. However, you could have written two expressions,one that rotates Can and one that rotates Cone.

The advantage of creating separate expressions is that you’ll have twoexpression names, each presumably named after the object and attributeyou’re controlling. Having two expression names makes it easier to find theexpression that controls the desired attribute.

The advantage of using a single expression to control the attributes is that allstatements are in a single expression. You don’t need to edit twoexpressions.

Before starting the next example, delete the scene and create a new scene.

Summary

In this lesson, you learned how to:

• control rotateX attributes in two objects using the same expression

• increase the rotation of each object in synch with animation time

• rotate one object at half the speed of the other object

Page 32: Expressions-- Maya Expression Editor From Basic to Professional

32 Using Maya: Hypergraph, Sets & Expressions

Quick StartControlling attributes conditionally

Controlling attributes conditionallyYou can write an expression that takes different actions depending on thevalue of attributes or variables it examines as an animation plays.

In the following steps, you’ll increase the scale of a sphere for the first twoseconds of animation, then stop scaling and move it in a global Y-axisdirection for the remainder of the animation.

To prepare the scene:

1 From the Modeling menu, choose Primitives→Create NURBS→Sphere.

By default, this creates a NURBS sphere at the origin with an X scale, Y scale,and Z scale of 1.

2 From the Channel Box or elsewhere, name the sphere Balloon.

3 Select Display→NURBS Smoothness→Fine to set Balloon’s displaysmoothness to fine resolution.

4 Display the Expression Editor and select Select Filter→By Object/AttributeName.

5 Rewind the animation to frame 0.

To create the expression:

1 Select Balloon.

2 In the Expression Editor, enter RisingBalloon in the Expression Name box.

3 Enter this expression:

if (time < 2)Balloon.scaleY = time;

This expression is an if statement. The if keyword causes the expression tomake a decision based on a comparison of two or more items. In this case,the expression compares the value of time to the value 2.

Page 33: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 33

Quick StartControlling attributes conditionally

Ex

pre

ss

ion

s

The expression checks whether the value of time is less than two seconds. Ifso, it does the assignment Balloon.scaleY = time. If time is not less than twoseconds, the assignment doesn’t occur.

Notice the indentation of Balloon.scaleY = time under if (time < 2). Mayaignores all indentation, extra spaces, and blank lines between statements. Weused the indentation to make the expression easier to read. You could havealso written the expression as follows:

if (time < 2) Balloon.scaleY = time;

This isn’t as easy to read. Consistent, organized spacing is a good habit todevelop. This book shows examples of good spacing style.

4 Click Create to compile the expression.

Balloon flattens.

The expression executes when you click the Create button. Because theanimation is at frame 0, animation time is 0. Because time is less than 2,Maya sets Balloon.scaleY equal to the value of time, which equals 0.

A scaleY value of 0 flattens the object in the Y dimension.

5 Play the animation.

The flattened Balloon’s scale increases along its Y-axis. It inflates as theanimation plays.

Important

When you compare the value of time to a number in an expression, Mayainterprets time as seconds rather than milliseconds, minutes, or any otherunit of time. In the example, Maya interprets 2 as 2 seconds.

Page 34: Expressions-- Maya Expression Editor From Basic to Professional

34 Using Maya: Hypergraph, Sets & Expressions

Quick StartControlling attributes conditionally

At 2 seconds, Balloon stops inflating. An expression executes each frame asan animation plays. The if statement sets the scaleY attribute of Balloon tothe value of time each frame when the time is less than 2.

When time equals 2 or more, the if condition is no longer true. The statementthat follows it, Balloon.scaleY = time, no longer executes. The value of thescaleY attribute stays at the last value it had before time became 2,specifically, 1.9583. At 2 seconds of animation time and every momentthereafter, scaleY continues to be 1.9583.

Recall that this example uses a frame rate of 24 frames/second.

The time and Balloon.scaleY have these values at various frames:

The if statement’s condition, (time < 2), is a comparison. The condition mustbe surrounded by parentheses to isolate it from assignment that follows it.

Frame Time (seconds) Balloon.scaleY (time)

0 0 0

1 0.0417 0.0417

2 0.0833 0.0833

3 0.125 0.125

24 1.0 1.0

47 1.96 1.9583

48 2.0 1.9583

49 2.04 1.9583

Page 35: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 35

Quick StartControlling attributes conditionally

Ex

pre

ss

ion

s

The < in the condition is a relational operator. A relational operator testshow one value relates to another. In the example, the < tested whether timeis less than 2.

Besides the < operator shown in this example, there are several otherrelational operators such as >, >=, ==, and so on. See “Arithmetic, logic, andrelational operators” in Chapter 5.

6 Stop and rewind the animation.

Balloon flattens again because the scaleY attribute becomes 0 when yourewind the animation. Time is 0, so scaleY is 0.

You can make Balloon rise after it inflates by adding a second if statement tothe expression.

To add another if statement to the expression:

1 Change the expression to this:

if (time < 2)Balloon.scaleY = time;

if (time >= 2)Balloon.translateY = time;

2 Click Edit to compile the expression.

3 Play the animation.

Balloon inflates for 2 seconds. After 2 seconds, Balloon stops inflating and itsposition skips from a Y-axis position of 0 to 2. You’ll eliminate the motionskip in a later step.

The second if statement increases the translateY position of Balloon after theanimation time rises above two seconds. The >= symbols mean greater thanor equal to. Whenever time is greater than or equal to 2, the expressionassigns Balloon’s translateY the value of time. The translateY value thereforeincreases for the rest of your animation’s playback range.

Notice that a semicolon ends each statement. Forgetting a semicolon aftereach statement causes a syntax error, and the changes you’ve made to theexpression won’t take effect.

Page 36: Expressions-- Maya Expression Editor From Basic to Professional

36 Using Maya: Hypergraph, Sets & Expressions

Quick StartControlling attributes conditionally

4 Stop and rewind the animation.

Balloon flattens but doesn’t return to the origin. (If Balloon has risen out ofview, adjust your camera to see it.)

Balloon doesn’t return to the origin because the expression doesn’t assignBalloon a starting point for the beginning of the animation.

5 To make Balloon return to the origin, change the expression to this:

if (time == 0)Balloon.translateY = 0;

if (time < 2)Balloon.scaleY = time;

if (time >= 2)Balloon.translateY = time;

The new first statement sets Balloon.translateY to 0 whenever time equals 0.The == symbols mean is equal to. In conditional statements, be careful to type== rather than =. The = symbol means assign the value to.

Important

Always examine the Script Editor for error messages after you edit anexpression and click the Create button. If you alter a previously successfulexpression and a syntax error occurs, Maya executes the previoussuccessful expression when you play the animation. This might make youbelieve your editing changes took effect.

Page 37: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 37

Quick StartControlling attributes conditionally

Ex

pre

ss

ion

s

Note that you can put the three statements in any order in this example.When Maya plays each frame, it executes each statement in the expression inthe order listed. In this example, the statements work independently, so theirorder doesn’t matter.

We put the statements in the order of time execution because it’s easier tosee the logic of the expression. If you ever need to change the expression,you’ll be able to grasp the expression’s actions more quickly.

6 Click Edit.

7 Stop and rewind the animation again.

The flattened Balloon returns to its correct position at the origin.

8 Play the animation.

Balloon inflates for two seconds, then rises.

As mentioned before, Balloon skips from Y-axis position 0 to 2 after twoseconds of animation play. You can eliminate the skipping and makeBalloon rise smoothly from the origin.

To eliminate the motion skip:

1 Stop and rewind the animation.

2 Change the expression to this:

if (time == 0)Balloon.translateY = 0;

if (time < 2)Balloon.scaleY = time;

if (time >= 2)Balloon.translateY = time - 2;

3 Click Edit.

4 Play the animation.

Page 38: Expressions-- Maya Expression Editor From Basic to Professional

38 Using Maya: Hypergraph, Sets & Expressions

Quick StartControlling attributes conditionally

Balloon inflates for 2 seconds, then rises slowly with time from its position atthe origin.

When time is greater than or equal to 2, the translateY position of Balloonbecomes 2 minus 2, which is 0. As time increases beyond 2 seconds, thetranslateY position increases in the same increments that time increases.

5 Stop and rewind the animation.

The expression achieved the desired result, but it’s more complicated thannecessary. You can use an if-else statement to make the statement morecompact and easier to read.

To use an else statement instead of multiple if statements:

1 Change the expression to this:

if (time == 0)Balloon.translateY = 0;

if (time < 2)Balloon.scaleY = time;

elseBalloon.translateY = time - 2;

2 Click Edit.

3 Play the animation.

The else keyword sets Balloon.translateY to time - 2 when (time < 2) is false.In English terms, the combination of the if and else statements says, “If timeis less than two seconds, set Balloon.scaleY to the value of time. Otherwise(when time is greater than or equal to two seconds), set Balloon.translateY totime minus two.”

Page 39: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 39

Quick StartControlling attributes conditionally

Ex

pre

ss

ion

s

At any instant in the animation’s playback, either Balloon.scaleY = timeexecutes or Balloon.translateY = time - 2 executes. Under no circumstancescan they both execute. The else statement executes only when the ifcondition that precedes it is false.

Note that we added a blank line between the first if statement and the if-elsestatement combination. This has no effect on the execution of the statements.We put it there to emphasize that the two if statements are unrelated.

The first if statement executes whenever time equals 0. It is unrelated to theif-else statements.

Using else statements instead of multiple if statements makes an expressionsimpler to read. If you use an if-else construction instead of a lengthy list ofif statements, you’ll also improve the execution speed of the expression. Thisimproves your animation’s playback and rendering speed.

Either expression is valid. If using the if-else construction seems confusing,stick with multiple if statements.

You can accomplish most expression animation tasks with several ifstatements strung after one another.

4 Stop and rewind the animation.

You can refine the expression to make it even easier to read.

To make the expression easier to read:

1 Change the expression to this:

if (time < 2){Balloon.translateY = 0;Balloon.scaleY = time;}

elseBalloon.translateY = time - 2;

We removed this statement from the previous version of the expression:

if (time == 0)Balloon.translateY = 0;

In its place, we put the statement Balloon.scaleY = time in a segmentenclosed by the braces { and }. Maya evaluates both the statements betweenthe braces if the condition (time < 2) is true.

2 Click Edit.

Page 40: Expressions-- Maya Expression Editor From Basic to Professional

40 Using Maya: Hypergraph, Sets & Expressions

Quick StartControlling attributes conditionally

3 Play the animation.

The animation plays exactly as before with the new expression.

When the animation time is less than two seconds, not only does Maya setBalloon.scaleY to time, it sets Balloon.translateY to 0. Balloon has a positionat the origin until the animation time is greater than or equal to 2 seconds.

Setting Ball.translateY to 0 here instead of in a separate if statement makesthe expression easier to read and comprehend.

As in the previous version of the expression, if time is greater than or equalto 2, Maya executes the else statement.

Note that you can put multiple statements between braces for an elsestatement, just as you do for an if statement.

4 Stop and rewind the animation.

You can further refine the animation’s appearance by expanding Balloonmore slowly.

To slow Balloon’s expansion:

1 Change the expression to this:

if (time < 2){Balloon.translateY = 0;Balloon.scaleY = time * 0.6;}

elseBalloon.translateY = time - 2;

Only one statement is different, Balloon.scaleY = time * 0.6. The asterisk (*)multiplies time by 0.6.

2 Click Edit.

3 Play the animation.

Page 41: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 41

Quick StartControlling attributes conditionally

Ex

pre

ss

ion

s

The scaleY attribute increases at 60% of the value of time, so Balloonexpands slower during playback. (The number 0.6 equals 60%.) By the timeBalloon starts to rise, it has expanded to the size of a typical balloon.

How do you know whether to multiply time by 0.6 or some other number?You don’t. In cases like this, you need to experiment.

For example, you might multiply by various percentages such as 0.2, 0.5,0.75, and finally 0.6. The 0.6 creates a life-like balloon shape at two seconds.

4 Stop and rewind the animation.

You can further refine Balloon’s appearance by eliminating the flattenedBalloon that appears at the origin when you rewind the animation. You canalso scale Balloon at different rates along each of its three axes.

To further refine Balloon’s appearance:

1 Change the expression to this:

if (time < 2){Balloon.translateY = 0;Balloon.scaleY = time * 0.6;Balloon.scaleX = time * 0.5;Balloon.scaleZ = time * 0.5;}

elseBalloon.translateY = time - 2;

2 Click Edit.

Balloon disappears from view because its scale attributes are 0.

The scaleX, scaleY, and scaleZ attributes are 0 at frame 0 because time is 0.Any number multiplied by 0 is 0.

3 Play the animation.

Page 42: Expressions-- Maya Expression Editor From Basic to Professional

42 Using Maya: Hypergraph, Sets & Expressions

Quick StartControlling attributes conditionally

As time increases, the value of Balloon’s scale attributes increase. Becausethe expression sets scaleX and scaleZ to 50% of the value of time, thesedimensions scale slower than scaleY, which is set to 60% of the value of time.

Balloon scales faster in height than in width or depth. This is true for manyreal balloons.

4 Stop and rewind the animation.

This concludes the example.

Summary

Using an expression is a combination of logic and experimentation. Problemsolving starts with breaking a task into smaller problems you can solve andlater refine.

In this lesson, you learned how to:

• control an attribute conditionally with an if statement

• use good spacing and indentation for expressions

• use relational operators such as <, <=, and ==

• use multiple if statements to control different conditions

• use an if-else statement in place of multiple if statements to make anexpression easier to read and comprehend

• refine an expression with a combination of analysis and experimentation

Page 43: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 43

Quick StartNotes on the predefined time variable

Ex

pre

ss

ion

s

In the preceding examples we didn’t include comments in expressionsbecause we explained them line by line. When you write your ownexpressions, include comments with statements to help document how theexpression works.

This will help you or someone else understand how your expression workslater if the need to enhance it arises. See “Comments in expressions” inChapter 5.

Notes on the predefined time variableThe lessons in this chapter use a starting frame number of 0. In your work,you’ll typically create an animation with a starting frame number of 1.

Because the examples use Maya’s default frame rate of 24 frames per second,time is 0.0417 at frame 1. Because of this small offset from 0, the exampleswould have required more steps and instructions to work with frame 1 asthe starting frame.

For instance, in the first example of the chapter, suppose you set the startingframe of the animation to 1. The expression in the example follows:

Ball.scaleY = time + 1;

If you rewind the animation, the expression executes and sets the initialvalue of Ball’s scaleY attribute to time + 1, which equals 0.0417 + 1, or 1.0417.Because Ball’s scaleY attribute was 1 when you created it, rewinding theanimation sets scaleY to a value 0.0417 larger than its initial value.

This discrepancy means the Ball scaleY is larger than its scaleX and scaleZattributes in the first frame of the animation. Though the difference is notsubstantial in this example, other cases might be more significant.

To start your animation at frame 1 and get the same result as the example,you can subtract 0.0417 from the attribute:

Ball.scaleY = (time - 0.0417) + 1;

When you rewind the animation, the expression sets Ball’s scaleY value to(0.0417 - 0.0417) + 1. This equals 1, its original scaleY value.

When you use the predefined time variable, be aware of the starting framenumber and the associated time value.

Page 44: Expressions-- Maya Expression Editor From Basic to Professional

44 Using Maya: Hypergraph, Sets & Expressions

Quick StartNotes on the predefined time variable

After doing the lessons in this chapter, remember to change your TimeSlider’s starting frame, ending frame, and frame rate to the desired valueswhen you start other projects. To do this, select Options→GeneralPreferences and display the appropriate tabs in the General Preferenceswindow.

Page 45: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 45

Ex

pre

ss

ion

s

5 Expression Syntax

Expressions use the syntax of the Maya Embedded Language (MEL).Though MEL is a scripting language, you’ll find the syntax easy to learneven if you’ve never programmed. Mastering the rules of syntax is essentialto writing expressions without errors.

This chapter describes the following topics:

• “Expressions and MEL” on page 46

• “Elements of an expression” on page 47

• “Attributes” on page 49

• “Variables” on page 56

• “Constants” on page 62

• “Arithmetic, logic, and relational operators” on page 63

• “Operator precedence” on page 68

• “Conditional statements” on page 69

• “General syntax rules” on page 73

• “Comments in expressions” on page 75

You can use an expression torotate each child joint basedon the root joint’s keyframedrotation.

Tristan Ikuta

Page 46: Expressions-- Maya Expression Editor From Basic to Professional

46 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxExpressions and MEL

• “Programming features” on page 75

• “Common expression errors” on page 95

Expressions and MELExpressions have a different purpose from MEL commands and MELscripts. You enter a MEL command to do a single action, for example, tocreate a sphere.

A MEL script is a list of commands you create to do a sequence of actions,for instance, create a wall-shaped object and apply a brick texture to it.

Because you store a MEL script in a file on disk, you can run a script indifferent scenes and different work sessions, whether today or next year.

An expression animates one or more attributes over time in a single scene.By default, an expression executes each frame as an animation plays. Afteryou create an expression, it executes whenever you play the animation—including when you play the animation after saving, closing, and reopeningthe scene.

A MEL command or script is not part of a scene after you execute it. Youmust execute it again to repeat the action.

Sometimes it’s useful to exectute MEL commands and scripts in expressions.See “Executing MEL commands in an expression” on page 137 for details.

The following pages describe expression syntax elements such as arithmeticoperators you can use to set and compare attributes. If you have troubleunderstanding the syntax descriptions, refer to a C programming guide forbeginners. Except for attribute names, the syntax elements have the samedefinitions as their counterparts in C. Attribute names do not exist in C.

If you’re familiar with a programming language such as C, Pascal, or Basic,be sure to see “Programming features” on page 75.

Action Typical use

MEL command Does one action

MEL script Does several actions

Expression Animates attribute values as an animation plays

Page 47: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 47

Expression SyntaxElements of an expression

Ex

pre

ss

ion

s

Elements of an expressionAn expression is made of one or more statements. Statements follow therules of algebra, so they’ll seem familiar if you’ve studied math. Eachstatement has several elements as in the following example:

Detailed explanations follow the summary definitions:

Attribute name The name of the attribute set by the statement. In theexample, Ball.rotateZ is the attribute name of the rotateZattribute of an object named Ball.

Assignmentoperator The = to the right of an attribute name. This symbol assigns

the attribute the result of the statement on the right side of=. In the example, Ball.rotateZ receives the value of thestatement sin(time) + 6. (Ignore what this assignment does;it’s for illustration only.) You can also use = to assign a valueto a variable.

Function A special word that you provide with an entry called anargument. In this example, the argument is time. Based onthe value of the argument, Maya does a calculation for thefunction and returns a new value or takes some other action.

In the example, the function sin(time) returns the sine of thevalue of time, which evaluates to a number between -1 and1.

Maya has many convenient built-in functions andcommands that do math calculations, conversions, and soon. See Chapter 9 for details.

Attribute name ConstantFunction

Assignment operator Arithmetic operator

Ball.rotateZ = sin(time) + 6;

VariableStatement

Terminator

Page 48: Expressions-- Maya Expression Editor From Basic to Professional

48 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxElements of an expression

Variable A variable is a symbolic name that stands for a changingvalue. You can assign a value to a variable or read avariable’s value. The variable time is a predefined Mayavariable that contains the animation time at the currentframe. You can read but not set the value of time.

Arithmetic, logic,or relationaloperator An operation such as + or < (less than).

Constant An unchanging number, for example, 6.1 or 90.

Terminator A semicolon (;) that marks the end of a statement. Anexpression can have an unlimited number of statements.You must end each statement with a semicolon.

Each expression usually has an attribute name, assignment operator (=),expression value assigned to the attribute, and a statement terminator (;).Other elements are optional.

Example

Here’s an expression with the fewest elements possible:

The expression has an attribute, assignment operator (=), value assigned tothe attribute, and a statement terminator (;). The expression sets Ball’s Yscale to 5 grid units. When you play the animation, Ball’s Y scale stays fixedat 5 regardless of the Y scale value you gave it when you created it.

Ball.scaleY = 5;

Value assigned

Page 49: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 49

Expression SyntaxAttributes

Ex

pre

ss

ion

s

AttributesAn attribute is a characteristic of an object or other item in a scene. There aremany ways to set attributes in Maya—with the Attribute Editor, ChannelBox, menu selections, and of course, expressions. You can set attributes tocontrol virtually anything in your animation.

There are three types of attributes you work with in Maya:

• static

• dynamic

• custom

Static and dynamic attributes have a predefined purpose. They are standardattributes Maya provides for objects and items that make up a scene. Customattributes are attributes you define for an object.

Static attributesStatic attributes are attributes an object has by default. They exist themoment you create the object and throughout its lifetime.

For example, the transform node of a NURBS sphere has static attributesscaleX, scaleY, scaleZ, rotateX, and so on. You can set the values of theseattributes with the Attribute Editor, Channel Box, expressions, and othertechniques after you create the object.

Dynamic attributesDynamic attributes have predefined names and purposes, but Maya addsthem to an object in response to your user interface selections.

For example, suppose you create a particle object and display its particleshape folder in the Attribute Editor. If you click one of the following buttonsin the Add Dynamic Attributes section of the Attribute Editor, Maya adds adynamic attribute to the node:

Clicking the General button lets you add a custom attribute (see the nexttopic). Clicking any of the other buttons lets you add one or more dynamicattributes with names that are the same or similar to the button name.

Page 50: Expressions-- Maya Expression Editor From Basic to Professional

50 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxAttributes

An object has no dynamic attributes unless your actions cause Maya to addthem to the object. By adding only required attributes, Maya runs faster.

When you add a dynamic attribute to an object, the attribute appears in theAttribute editor for the selected object or node.

Custom attributesCustom attributes are attributes you optionally add from the New folder ofthe Add Attribute window.

Note

Because soft body geometry is a particle shape node coupled withgeometry, a soft body has the same static and dynamic attributes as aparticle object.

Page 51: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 51

Expression SyntaxAttributes

Ex

pre

ss

ion

s

Such attributes have no direct effect on any characteristic of an object.They’re often used to control a combination of other attributes. You mightalso use a custom attribute as a variable—a place to store a valuetemporarily to be read by other attributes.

When you add a custom attribute to an object, it appears in the AttributeEditor and Channel Box for the object or node. Though custom attributes aredynamically added to an object, we refer to them as custom to distinguishthem from the built-in dynamic attributes.

See “Assigning to a custom attribute” in Chapter 8 for details on how to addand use a custom attribute.

Attribute namesStatic, dynamic, and custom attributes follow the same naming conventionsand represent the same types of data.

A full attribute name has this format:

object.attribute

where object is the name of the object node, and attribute is the name of theattribute. A period (.) separates the name of the object and attribute.

You must spell the object and attribute name with uppercase and lowercaseletters as they appear in the Expression Editor’s Objects and Attributes lists.You cannot spell attribute names with the common English spellings shownin the Attribute Editor or by default in the Channel Box.

See “Using attribute names in expressions” in Chapter 6 for more details.

Example

Ball.scaleY

Data types of attributesEach attribute has a data type that specifies the type of values you can use tocontrol it in an expression. This is true for static, dynamic, and customattributes.

Page 52: Expressions-- Maya Expression Editor From Basic to Professional

52 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxAttributes

Attributes you’ll work with in expressions have these data types:

The most common attribute data type is floating point. In mathematics,floating point numbers are also called real numbers. Often, such numbershave a decimal point.

Booleans are also common data types in attributes. Integer data types arerarely used.

Particle shape nodes have these additional attribute data types:

Data type Meaning Example attribute Example data

float floating point numbers Balloon.scaleY -2.3333333333

integer signed whole numbers Ball.sections 16

Boolean on or off selection Ball.visibility on

Data type Meaning Example attribute Example data

vectorarray

array of vectors FireShape.position <<3.2, 7.7, 9.1>><<4.5, 9.2, 3.1>><<3.8, 4.4, 2.1>>

floatarray

array of floatingpoint numbers

FireShape.lifespan 1.3331.6662.3331.333

Note

Scientists often refer to a vector as a quantity that specifies both amagnitude and direction. In Maya, a vector is simply a related group ofthree floating point numbers that set an attribute or variable.

Page 53: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 53

Expression SyntaxAttributes

Ex

pre

ss

ion

s

Vector array data types are useful for animating position, velocity,acceleration, color, and other particle attributes made of three components.

Float array attributes are useful for setting lifespan, opacity, and otherparticle attributes that have a single number value.

Attributes having a vector array or float array data type are also called perparticle attributes. See Chapter 8 for details on working with particleattributes.

If you have programming experience, note that for vector array data types,Maya represents the specified attribute for each particle of the object with asingle element of an array. Each element is made of three floating pointnumbers. In a float array, Maya represents the specified attribute for eachparticle with a vector array element that’s a floating point number.

Data types of static and dynamic attributesStatic and dynamic attributes have predefined data types. To learn theattribute’s data type, select the node containing it. In the Attribute Editor,find the attribute name and examine its data format.

Note

In expressions, you must type a vector in double angle brackets (<< >>).For example, type <<3,0,5>> for a vector having 3, 0, and 5 as its left,middle, and right component.

Page 54: Expressions-- Maya Expression Editor From Basic to Professional

54 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxAttributes

Here’s an example display of attributes with floating point, Boolean, andinteger data types:

A floating point attribute shows a value that includes a decimal point. Mostnumerical attributes in Maya are floating point.

A Boolean attribute has a checkbox or other user interface item for turning iton or off.

An integer attribute has no decimal point. Integer attributes are rare inMaya.

The data type of an attribute limits what type of value you can enter for theattribute in the Attribute Editor and in expressions. For example, because adirectional light’s Depth Map Filter Size attribute is an integer, you cannotenter a decimal point in its text entry box or assign it a decimal quantity inan expression.

For a floating point attribute, you can omit the decimal point. The AttributeEditor automatically inserts a decimal point in the attribute’s text field afteryou press the Enter key. For example, if you type 3 for a floating point entry,the Attribute Editor replaces 3 with 3.0000.

Floating point

Boolean

Integer

Page 55: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 55

Expression SyntaxAttributes

Ex

pre

ss

ion

s

An expression also automatically converts an integer to a floating pointvalue when appropriate. See “Data type conversions” in Chapter 7 fordetails.

Only particle objects, not geometric objects, have vector array and float arrayattributes. The static vector array attributes for particle objects are position,velocity, and acceleration. These are also called per particle attributesbecause you can set the attribute for each particle to different values.

Maya has other attribute data types that are irrelevant to the use ofexpressions. For example, Maya has a matrix data type that is useful only inMEL scripting and API programming.

Data types of custom attributesWhen you add a custom attribute to an object with Modify→Add Attribute,you choose whether its data type is floating point, integer, Boolean, orvector. Vector attributes are commonly used with particle shape nodes.

Assigning a value to an attributeYou assign a value to an attribute using the = assignment operator. Staticand dynamic attributes have data types established by Maya. You do notdefine their data type.

Because you choose the data type of custom attributes when you add themwith Modify→Add Attribute, you do not define their data type either.

You can assign a value to any attribute. If the attribute is dynamic or custom,though, you must add the attribute to the object before you can assign it avalue in an expression.

Become familiar with the purpose of an attribute by working with it in theAttribute Editor, Channel Box, or other parts of Maya before assigning it avalue in an expression. It’s best to know the behavior you can expect fromthe attribute in case you write your expression incorrectly.

Note

For rigid bodies, you can read but not write the velocity, angularVelocity,and force attributes.

Page 56: Expressions-- Maya Expression Editor From Basic to Professional

56 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxVariables

Assigning to a float or integer attributeAn assignment operation is a statement, so you must terminate it with asemicolon (;).

Examples

Cone.scaleY = 5.3;

This assigns 5.3 to the floating point scaleY attribute of Cone.

Ball.translateY = time;

This assigns the value of time to the floating point translateY attribute ofBall.

Ball.scaleX = Ball.scaleY = Ball.scaleZ = 2;

This assigns 2 to the floating point scaleX, scaleY, and scaleZ attributes ofBall. As the example shows, you can use an assignment operator severaltimes in a statement to set multiple attributes to the same value.

Assigning to a vector attributeYou can assign values to all three components of a vector attribute, or just toa single component.

See “Assigning to vectors and vector arrays” in Chapter 8 for details onassigning values to vector attributes. Only particle shape nodes have vectorattributes.

Note that you cannot assign a vector to three related scalar attributes such asscaleX, scaleY, and scaleZ. For example, you can’t do this:

Ball.scale = <<1,2,0>>;

You must assign to each attribute separately:

Ball.scaleX = 1;Ball.scaleY = 2;Ball.scaleZ = 0;

VariablesA variable is a symbolic name that stands for a constant or changing value.There are two types of variables, predefined and custom.

Maya creates and maintains predefined variables. Custom variables arevariables you can create to store data in an expression.

Page 57: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 57

Expression SyntaxVariables

Ex

pre

ss

ion

s

Keep in mind that attributes, not variables, set object and componentbehavior in Maya. You can use variables to as temporary storage forworking with the attributes.

Data types of variablesVariables can be one of these types of data:

The most common data type of variables is floating point. Integer data typesare rarely used. Booleans are commonly used in attributes, but not allowedin variables. Vector variables are useful in expressions for particle shapeattributes.

Animators with programming experience sometimes use string variables.Quote marks (" ") are required with strings. See “String usage” on page 90for details.

For a custom variable you create in an expression, you must declare the datatype as described in “Custom variables” on page 59.

Predefined variablesMaya maintains values in two predefined variables as an animation plays:

Data type Meaning Examples Definingkeyword

float floating point numbers 392.6, -0.667 float

integer signed whole numbers 10, -5, 0 int

vector vector made of threefloating point numbers

<<3.2, 7.7, 9.1>> vector

string one or more characters “What’s up, chief?” string

Variable Contents Data type

frame number of frames the animation has played float

time time in seconds the animation has played float

Page 58: Expressions-- Maya Expression Editor From Basic to Professional

58 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxVariables

Your expressions can read, but not set, the value of time and frame. Thesevariables are floating point values that are useful for animating an attributeas an animation plays.

The time updates as an animation plays. It contains the elapsed number ofseconds from the first frame to the current frame. The value increases withthe increasing frame number.

At the default animation playback rate of 24 frames per second, time hasthese values, rounded to four decimal places:

If you need to change the playback rate, choose Options→GeneralPreferences. Expand the General Preferences window, display the Unitsfolder, and choose the desired rate from the Time menu.

Regardless of what animation playback rate you choose, you can find thetime elapsed in the animation at any frame with this formula:

For example, if the frame rate is 24 frames/second, and the animation is atframe 1, the elapsed time is 1 divided by 24, or 0.0417. At frame 6, theelapsed time is 6 divided by 24, which equals 0.25.

If the frame rate is 30 frames/second and the animation is at frame 1, theelapsed time is 1 divided by 30, which equals 0.0333. At frame 6, elapsedtime is 6 divided by 30, which equals 0.2.

Frame Time (seconds)

0 0

1 0.0417

2 0.0833

3 0.125

24 1.0

240 10.0

timeframerate

---------------=

Page 59: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 59

Expression SyntaxVariables

Ex

pre

ss

ion

s

There’s an advantage to writing an expression using the value of time ratherthan frame: You won’t need to modify your expression if you change youranimation’s frame rate.

Note that time is always 0 at frame 0. As each frame plays, the time increasesin increments resulting from the frame rate.

It’s impossible to set time to a value other than 0 at frame 0. If you setMaya’s frame range to begin at a negative number, time has a negativevalue.

Examples

Ball.translateY = time/2;

This sets the Ball’s Y translation equal to the value of time divided by 2 asthe animation plays. This make the Ball move in a Y direction as theanimation time increases.

Ball.scaleY = frame/2;

This sets the Ball’s Y scale equal to the value of frame divided by 2 as theanimation plays. The Ball scales along its Y axis as the animation framenumber increases.

Custom variablesYou can declare and use variables to store a constant or changing value.These work like their counterparts in programming languages andspreadsheet programs.

Though programming languages use such variables abundantly, you mightnot need to use them at all in many expressions.

Declaring variablesEach custom variable name must begin with a dollar sign character ($). Afterthe $, you can use alphabetical, numerical, and underscore characters. Youcannot include spaces in the names.

Variable names are type case sensitive. In other words, $temp is a differentvariable name than $Temp.

Page 60: Expressions-- Maya Expression Editor From Basic to Professional

60 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxVariables

Examples

float $object_height;

This declares $object_height as a floating point variable.

int $counter;

This declares $counter as an integer.

vector $top_velocity;

This declares $top_position as a vector variable.

Assigning a value to an integer or float variableTo assign a value to a variable, you use = as an assignment operator. Anassignment operation is a statement, so you must end it with a semicolon (;).

Examples

float $counter = 5.3;

This declares a floating point variable named $counter and gives it an initialvalue of 5.3.

$height = 6;

This declares a floating point variable named $height and gives it an initialvalue of 6. This example shows you can skip declaring the variable’s datatype. When you assign a variable a value, Maya assumes the variable isfloating point unless you specify a different data type.

$pi = 3.1415927;$twist = $pi;

These statements show you can assign the value of one variable to anothervariable. The first statement assigns 3.1415927 to $pi. The second statementassigns the contents of $pi, 3.1415927, to $twist.

Page 61: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 61

Expression SyntaxVariables

Ex

pre

ss

ion

s

Assigning a value to a vector variableYou can assign values to all three components of a vector variable, or just toa single component.

See “Assigning to vectors and vector arrays” in Chapter 8 for details onassigning values to vector variables. Such variables are useful for workingwith particle shape node attributes.

Using custom variables globallyTypically, you’ll use variables within a single expression. If you want tocreate and maintain a custom variable in one expression, but use it inanother expression, you must declare it as a global variable.

Example

global float $counter;

You can thereafter set or read the value of this variable in any otherexpression in the scene.

If you create a variable with the same name in two expressions, the twovariables are separate and unrelated. For example, suppose you create avariable named $timer in two expressions. Assigning a value to one of the$timer variables has no effect on the other’s value.

Important

If you misspell an existing declared variable name and assign it a value, asyntax error won’t be generated for the undeclared variable. Because Mayaautomatically provides a data type for an undeclared variable if it’s on theleft side of the assignment operator, the misspelled variable will beinterpreted as a newly added variable. Undeclared variables on the rightside of the assignment operator do generate error messages.

Check spellings of variables if your expression isn’t working as expected.

In the following example, the misspelling in the final statement generatesan error but not the misspelling in the statement before it:

int $start;int $end;int $interrupt;

$starrrt = 1;$end = $interrupppt;

Page 62: Expressions-- Maya Expression Editor From Basic to Professional

62 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxConstants

If you declare and initialize a global variable in a single statement, you caninitialize it to a numerical constant or string only.

Examples

global float $counter = 3;

This initializes $counter to 3.

global float $counter = time;

This causes an error because time is a variable.

If you declare and initialize a global variable in a single statement, thestatement executes only when Maya compiles the expression. Maya compilesan expression when you click the Create or Edit button in the ExpressionEditor, or when you open a scene containing a previously createdexpression.

Example

global float $counter = 3;print($counter+"\n");$counter = 1000;print($counter+"\n");

When Maya compiles the expression, it sets $counter to 3, prints 3, sets$counter to 1000, then prints 1000.

During playback, each execution of the expression skips the first statement,so $counter never receives the value 3. The expression prints 1000, sets$counter to 1000 again, and prints 1000 again.

ConstantsA constant is an unchanging number or variable.

Examples

Ball.translateY = 6.1.

This statement sets Ball’s translateY attribute to the constant number 6.1.

float $pi = 3.1415927;Ball.rotateY = $pi;

These statements set the value of Ball’s rotateY attribute to the value of thevariable $pi. The variable $pi represents the constant 3.1415927.

Page 63: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 63

Expression SyntaxArithmetic, logic, and relational operators

Ex

pre

ss

ion

s

Arithmetic, logic, and relational operatorsYou can use the following operator symbols to add, subtract, multiply,compare, and do other actions to variables and attributes.

Arithmetic operators

Integers and floatsFor integer and floating point attributes and variables, the above arithmeticoperators work according to the rules of basic math. Note that the modulusoperator (%) calculates the remainder of division.

Examples

Car.translateX = time / 2.0;

This moves the Car in an X direction as the time increases in the animation.By dividing time by 2.0, you move the object half as fast as if you used timealone.

Car.translateX = 7 % 3;

This assigns Car.translateX the value 1, the remainder of 7 divided by 3. Thenumber 7 divided by 3 equals 2 with a remainder of 1.

Car.translateX = 8.8 % 4.2;

This assigns Car.translateX the value 0.4, the remainder of 8.8 divided by 4.2.The number 8.8 divided by 4.2 equals 2 with a remainder of 0.4.

Car.translateX = 0.5 % 3;

Symbol Meaning Used with these data types

+ plus integer, float, vector, string

- minus or negation integer, float, vector

* for integers and floats: multiplyfor vectors: dot product

integer, float, vector

/ divided by integer, float

% remainder of division integer, float

Page 64: Expressions-- Maya Expression Editor From Basic to Professional

64 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxArithmetic, logic, and relational operators

This assigns Car.translateX the value 0.5, the remainder of 0.5 divided by 3.The number 0.5 divided by 3 equals 0, with a remainder of 0.5.

VectorsFor operations between vector attributes and variables, the * operatorperforms the dot product. The dot product multiplies correspondingcomponents of each vector, then adds the components to create a singlefloating point number result.

For + and - operators, each component of one vector is operated on by itscounterpart component in the other vector.

For operations between a vector and an integer or floating point number,each component of the vector is operated on by the integer or floating pointnumber.

Examples

Suppose you’ve initialized these vectors:

vector $A = <<1,2,3>>;vector $B = <<2,3,4>>;vector $C;float $myfloat;

You then use the following statements (in different expressions, not insequential order):

$C = $A + $B;

This assigns $C the value << 3, 5, 7>>.

$C = $B - $A;

This assigns $C the value <<1, 1, 1>>.

$myfloat = $A * $B;

This assigns $myfloat the value (1*2) + (2*3) + (3*4), which equals 20.Multiplying two vectors gives the dot product of the vectors.

$C = 3 * $A;

This assigns $C the value <<3, 6, 9>>. Each component of the vector ismultiplied by 3 to create a vector result.

Page 65: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 65

Expression SyntaxArithmetic, logic, and relational operators

Ex

pre

ss

ion

s

StringsFor details on how to use the + operator with strings, see “String usage” onpage 90.

Relational operatorsYou’ll often use relational operators to compare the value of variables andattributes in conditional statements. See “Conditional statements” on page69.

Integers and floatsFor integer and floating point attributes and variables, the above relationaloperators work according to the rules of algebra.

Note

Maya handles integer and Boolean attributes in an expressionmathematically as floating point numbers. After the expression executes,Maya converts the floating point number to the proper data type.

If your expression does arithmetic on an integer or Boolean attribute andyou display the attribute’s contents in the Script Editor, you’ll see floatingpoint values. After the expression executes, Maya assigns an appropriateinteger or Boolean value to the attributes you set in the expression textfield.

Maya handles integer and Boolean variables within an expressionmathematically as integer and Boolean data types.

Symbol Meaning Used with these data types

< less than integer, float, vector

> greater than integer, float, vector

== equal to integer, float, vector

!= not equal to integer, float, vector

>= greater than or equal to integer, float, vector

<= less than or equal to integer, float, vector

Page 66: Expressions-- Maya Expression Editor From Basic to Professional

66 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxArithmetic, logic, and relational operators

Examples

if (time > 10)Sphere.translateX = 3;

When the animation time is greater than 10 seconds of play, the expressionsets the Sphere’s translateX attribute to 3. It stays fixed in this positionthereafter. See “Conditional statements” on page 69 for details on the ifcondition in this and following examples.

if (Ball.scaleY == 3)Cone.scaleY = 6;

If Ball’s scaleY attribute is equal to 3, Maya sets Cone’s scaleY attribute to 6.

VectorsIf you use the == or != operators between two vector attributes or variables,Maya compares the corresponding components of each vector. In contrast,the >, >=, <, and <= operators compare the magnitude of two vectors.

Use this formula to calculate a vector’s magnitude:

The x, y, and z numbers in the formula represent the three components ofthe vector.

Examples

vector $A = <<1,2,3>>;vector $B = <<1,2,3>>;if ($A == $B)

Sphere.translateX = 3;

Important

Be careful to type == rather than = for the equal to operator.

For example, suppose you type if (Ball.scaleY = 3) in the previous example.Rather than test whether Ball.scaleY is equal to 3, the statement assigns 3 toBall.scaleY.

Maya evaluates the assignment statement Ball.scaleY = 3 as a truecondition, so it executes Cone.scaleY = 6. This statement doesn’t cause anerror message, but it gives unintended results.

x2

y2

z2

+ +

Page 67: Expressions-- Maya Expression Editor From Basic to Professional
Page 68: Expressions-- Maya Expression Editor From Basic to Professional

68 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxOperator precedence

Notice that each condition is grouped in parentheses, and the pair ofconditions are enclosed again in parentheses. If you use multiple conditionswith logical operators, you must enclose all the conditions in parentheses forthe if statement.

If you omit the outer pair of parentheses as in the following example, anerror message occurs:

if (time > 5) && (time < 10)Ball.scaleZ = time;

Example 2

if ((Ball.translateX < 5) || (Ball.translateY > 10))Ball.scaleZ = time;

This sets Ball’s scaleZ attribute to the value of time in either of twoconditions: when Ball’s translateX attribute is less than 5 or greater than 10.

Operator precedenceThe precedence of operators in expressions follows:

This figure includes operators used mainly by individuals experienced inprogramming. See “Programming features” on page 75 for details.

In the figure, operators on the same row have equal precedence. If astatement has two or more operators from the same row, the operatorfurthest to the left is evaluated first.

The parentheses at the top of the figure are for grouping a condition orelements of a statement. As shown in a following example, parentheses areuseful for altering the order of operator evaluation.

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

Highest

Lowest

Page 69: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 69

Expression SyntaxConditional statements

Ex

pre

ss

ion

s

Examples

Ball.scaleY = 8 + 2 * 4;

This assigns Ball.scaleY the value 16.

Ball.scaleY = (8 + 2) * 4;

This assigns Ball.scaleY the value 40.

Ball.scaleY = 8 + 6 - 4;

This assigns Ball.scaleY the value 10. The + executes first because it’s furtherto the left in the statement than the - .

Conditional statementsConditional statements set one attribute or variable based on the conditionof another attribute or variable. For example, you might increase the scale ofa balloon after frame 48 plays.

The if and if-else statements are the most commonly used conditionalstatements in expressions.

You’ll often use relational and logical operators in conditional statements.See page 65 and page 67 for details.

If you have programming experience, be aware you can use loop and flowcontrol statements such as while and for. See “Programming features” onpage 75.

if statementsThe if conditional statement has this format:

if ( condition )statement ;

If condition is true, statement executes.

Example

if (time > 3)Ball.scaleY = 2;

This sets the scale of Ball’s scaleY attribute to 2 after the animation playsthree seconds.

Page 70: Expressions-- Maya Expression Editor From Basic to Professional

70 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxConditional statements

if-else statementsThe if-else conditional statement has the following format:

if ( condition )statement1 ;

elsestatement2 ;

If condition is true, statement1 executes. Otherwise statement2 executes.

Example 1: Simple if-else statement

if (time > 3)Ball.scaleY = 2;

elseBall.scaleY = 1;

This sets Ball’s scaleY attribute to 2 if animation time is greater than 3seconds. If animation time is less than 3, scaleY is set to 1.

You can use more than one statement after a condition with this format:

if ( condition ){statement ;statement ;}

else{statement;statement;}

Notice you must enclose the multiple statements between braces ({ }).

Example 2: Braces in if-else statement

if (time < 2){Balloon.translateY = 0;Balloon.scaleY = time * 0.6;}

else{Balloon.translateY = time - 2;Balloon.scaleY = 1;}

Page 71: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 71

Expression SyntaxConditional statements

Ex

pre

ss

ion

s

If the animation time is less than 2 seconds, the expression sets Balloon’stranslateY attribute to 0, and sets its scaleY attribute to the value of timemultiplied by 0.6.

If animation time is greater than or equal to 2 seconds, the expression setsBalloon’s translateY attribute to time minus 2, and sets its scaleY attribute to1.

else if statementsThe else if statement works with the if-else conditional statement and hasthis format:

if ( condition1 )statement1 ;

else if ( condition2 )statement2 ;

If condition1 is true, statement1 executes and the else if statement after it isskipped.

If condition1 is false, the else if statement executes. If condition2 is true,statement 2 executes. If neither condition is true, neither statement executes.

You can add an else condition to the previous format as follows:

if ( condition1 )statement1 ;

else if ( condition2 )statement2 ;

elsestatement3 ;

If neither condition is true, statement3 executes.

Important

You cannot set the same attribute in two different expressions. If you try todo so, an error message results and your second expression has no effect.

Page 72: Expressions-- Maya Expression Editor From Basic to Professional

72 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxConditional statements

Example

if (time < 3)Ball.scaleY = 1;

else if ((time >= 3) && (time =< 6))Ball.scaleY = 2;

elseBall.scaleY = 3;

This sets Ball’s scaleY attribute to 1 if animation time is less than 3 seconds.If animation time is between 3 and 6 seconds, scaleY is 2. Otherwise, whentime is greater than 6 seconds, scaleY is 3.

Note that you can add multiple else if statements and multiple statementswithin braces ({ }) using this format:

if ( condition1 ){statement ;statement ;}

else if ( condition2 ){statement ;statement ;}

else if ( condition3 ){statement ;statement ;}

else if ( condition4 ){statement ;statement ;}

else{statement ;statement ;}

Page 73: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 73

Expression SyntaxGeneral syntax rules

Ex

pre

ss

ion

s

General syntax rulesUse these guidelines to avoid syntax errors while writing expressions:

• Terminate each statement in an expression with a semicolon (;). Here’s anexample expression with two statements:

if (time < 3)nurbsSphere1.translateX = time/2;

elsenurbsSphere1.translateX = time*3;

A semicolon marks the end of each statement.

• Enclose each conditional item in an expression within parentheses. In thepreceding example, (time < 3) is a conditional item enclosed in parentheses.

• Match each opening parenthesis with a closing parenthesis.

For example, this statement causes an error:

Ball.rotateZ = deg_to_rad(-6 * (floor(time));

If you look closely, you’ll see that there are three opening parentheses, butonly two closing parentheses. The next statement causes no error:

Ball.rotateZ = deg_to_rad(-6 * (floor(time)));

There are three matching closing parentheses for the three openingparentheses.

• When you use { and } as opening and closing braces, make sure you usethem in matching pairs:

if (time > 3){Ball.rotateZ = deg_to_rad(-6 * (floor(time));Ball.rotateY = Ball.rotateZ * 3;}

• Enclose a vector in double angle brackets as in this example:

<<3,4,8>>

Spaces before and after the numbers and commas are optional.

• Begin any variable you use with a dollar sign ($), and do not to use spaces orspecial characters other than underscores in the name. Here’s an acceptableexample:

float $my_Rotate;$my_Rotate = 3.14;

Page 74: Expressions-- Maya Expression Editor From Basic to Professional

74 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxGeneral syntax rules

• In conditional statements, be careful to type == rather than = for the equal tooperator. The = symbol means assign the value. For example, make sure youtype:

if (Ball.scaleY == 3)Cone.scaleY = 6;

instead of this:

if (Ball.scaleY = 3)Cone.scaleY = 6;

• You can use as many spaces, tab characters, and blank lines as you like whenseparating words, operators, or statements. Maya ignores white space in anexpression.

For example, suppose you’ve written this expression:

if (time < 2){Balloon.translateY = 0;Balloon.scaleY = time * 0.6;}

elseBalloon.translateY = time - 2;

Though the following expression has different spacing and is unpleasant toread, Maya interprets the expression the same as the previous one.

if(time<2){Balloon.translateY=0;Balloon.scaleY=time*0.6;}

else Balloon.translateY=time-2;

You must include at least one space between any two keywords, variables,or attribute names (or combination of these). So a space is required after theelse keyword but in no other place in this expression.

To simplify spacing considerations, remember to put at least one spacebefore and after a keyword, variable, operator, attribute, assignmentoperator, and so on.

Consistent use of white space makes expressions easier to read. Examplesthroughout this chapter show examples of good spacing style.

Page 75: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 75

Expression SyntaxComments in expressions

Ex

pre

ss

ion

s

Comments in expressionsAdd comments to your expressions to explain the purpose of each statementwithin. You’ll appreciate this later if you need to modify the expression.Maya ignores comments.

To add a comment to the right of a one-line statement:

Enter two forward slashes (//) at the end of the statement, then enter thecomment:

Ball.translateX = time; // Moves ball in X dir. with time

To write a multi-line comment:

Enter two forward slashes (//) before the comment:

// This is an example of a// comment spanning two lines.

Programming featuresThe following topics describe programming features available inexpressions. Discussion is brief and assumes you’re familiar withprogramming. Most of the syntax features described work like their Ccounterparts.

Notes for C programmersSome important differences between expression and C syntax follow:

• A C program consists of one or more functions, each containing multiplestatements. An expression is simply a single block of statements. You don’tdeclare main( ) or your own functions in an expression. You also don’tinclude the C standard library of functions.

You will, though, sometimes include a built-in Maya function such as sin( )to accomplish time-saving tasks. See Chapter 9, “Functions,” for details.

• After you type an expression in the Expression Editor, clicking the Create orEdit button compiles the expression.

• The first character of variables must be a dollar sign ($).

• ANSI C has 32 keywords. The expression language has less, as listed in thefollowing topic.

Page 76: Expressions-- Maya Expression Editor From Basic to Professional

76 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxProgramming features

• Maya’s integer data type has the same numerical range as ANSI C’s integerdata type, -2,147,483,648 to 2,147,483,648.

• Maya’s float data type has the same numerical range as ANSI C’s doubledata type.

Expression language keywordsThe expression language keywords follow:

Data type keywords

Boolean constant keywords

Flow control keywords

Other keywords

The return, proc, and matrix keywords are useful for writing MEL scripts,not for expressions. Other keywords above are described throughout thischapter.

Type keywords in lowercase letters exactly as shown. Do not name a customattribute with any of these keywords.

int float vector string matrix

yes no on off true false

if else for while do in

break continue default switch case

global return source catch alias proc

Page 77: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 77

Expression SyntaxProgramming features

Ex

pre

ss

ion

s

Flow control statementsBesides the if and if-else statements described previously, you can controlthe flow of statement execution with while, do, for, break, continue, and ?:instructions. These work like their C language counterparts.

You’ll often use logical and relational operators in conditional statements.See page 65 and page 67 for details.

whileA while loop has this format:

while ( condition ){statement ;statement ; ...}

Use condition to compare variable, attribute, or constant values. If condition istrue, Maya executes each statement between braces. Maya then evaluatescondition again. If true, it executes each statement again. This cycle continuesuntil condition is false, whereupon execution resumes with the statementafter the loop.

Example

float $test = 0;

while ($test < 5){print("$test equals: " +$test+"\n");$test = $test + 1;}

Important

Using a while, do, or for loop incorrectly might halt Maya. See “Flowcontrol errors” on page 88 for details.

Page 78: Expressions-- Maya Expression Editor From Basic to Professional

78 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxProgramming features

This expression displays the following lines in the Script Editor:

$test equals: 0$test equals: 1$test equals: 2$test equals: 3$test equals: 4

These lines are followed by a status message similar to this:

expression -e -s "<expression string>" -o Ball -an 1 Expr

This message indicates that a MEL command executed when you clicked theCreate or Edit button in the Expression Editor. Specifically, an expressioncommand executed. This is unrelated to the exact statements in theexpression.

doA do loop has this format:

do {statement ;statement ; ...}

while (condition);

Here Maya executes each statement between braces, then evaluates condition.The condition compares variable, attribute, or constant values. If condition istrue, each statement executes again. The loop terminates when condition isfalse.

In contrast to a while loop, a do loop executes the statements in the loop atleast once. It tests the termination condition after the loop. A while loop teststhe termination condition before executing the statements in the loop.

Example

float $test = 0;

do {print("$test equals: " +$test+"\n");$test = $test + 1;}

while ($test < 5);

Page 79: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 79

Expression SyntaxProgramming features

Ex

pre

ss

ion

s

This expression displays the following lines in the Script Editor:

$test equals: 0$test equals: 1$test equals: 2$test equals: 3$test equals: 4

forA for loop has this format:

for ( initialization ; condition ; change of condition ){statement ;statement; ...}

A for loop evaluates the termination condition before executing eachstatement. The condition compares variable, attribute, or constant values.

Example

float $i;

for ($i = 0; $i < 5; $i = $i + 1){print("$i equals: " +$i+"\n");}

This expression displays the following lines in the Script Editor:

$i equals: 0$i equals: 1$i equals: 2$i equals: 3$i equals: 4

breakThe break instruction exits a loop from any point within its body, bypassingthe normal termination at the loop’s beginning or end. Expression executionresumes at the next statement after the loop. You can use a break instructionwith a while, do, or for loop.

Page 80: Expressions-- Maya Expression Editor From Basic to Professional

80 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxProgramming features

Example

float $f = 0;

while( $f < 10 ){print("$f equals: "+$f+"\n");if ( $f > 5 )

break;$f = $f + 1;}

This expression displays the following lines in the Script Editor:

$f equals: 0$f equals: 1$f equals: 2$f equals: 3$f equals: 4$f equals: 5$f equals: 6

Suppose the example didn’t have this statement:

if ($f > 5)break;

The loop would execute ten times and display the numbers 0 through 9.

The break statement terminates the loop after $f is greater than 5. So theexpression displays only numbers 0 through 6.

continueThe continue instruction works inside loops. It forces the next iteration of theloop to occur, skipping any statements between itself and the loop’s testcondition. The condition compares variable, attribute, or constant values.

Page 81: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 81

Expression SyntaxProgramming features

Ex

pre

ss

ion

s

Example

float $f = 0;

for( $f = 0; $f < 10; $f = $f + 1){print("$f equals: "+$f+"\n");if( $f > 5 )

continue;print(" got here.\n");}

This expression displays the following lines in the Script Editor:

$f equals: 0got here.

$f equals: 1got here.

$f equals: 2got here.

$f equals: 3got here.

$f equals: 4got here.

$f equals: 5got here.

$f equals: 6$f equals: 7$f equals: 8$f equals: 9

Suppose the example didn’t have this statement:

if( $f > 5 )continue;

The loop would display got here after each line of $f equals: n. Maya ignoresthe continue instruction until $f increases to a value greater than 5.

When $f becomes 6 or greater, the continue instruction executes and skipsthe remaining statement in the loop, so got here isn’t printed.

for-inThe for-in loop is a specialized for loop that simplifies manipulation of allelements of an array. A for-in loop with an array element variable lets youomit the initialization, condition, and change of condition components of a forloop.

Page 82: Expressions-- Maya Expression Editor From Basic to Professional

82 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxProgramming features

The for-in loop has this format:

for ( array-element in array ){statement ;statement ;...}

Example

string $carType[3] = {"Porsche", "Ferrari", "Fiesta"};string $car;for ($car in $carType)

{print("I want a new ");print($car + ".\n");}

The expression displays this in the Script Editor:

I want a new Porsche.I want a new Ferrari.I want a new Fiesta.

The loop executes three times, once for each array element in $carType.

The first loop execution copies array element $carType[0] into $car, thenprints, “I want a new Porsche.” Array element $carType[0] is Porsche.

The second loop execution copies $carType[1] into $car, then prints thesecond line shown. The third execution copies $carType[2] into $car, thenprints the third line shown.

When the for-in statement finishes reading all array elements, the loopterminates.

Page 83: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 83

Expression SyntaxProgramming features

Ex

pre

ss

ion

s

switchA switch instruction executes one of several groups of statements based on acontrol value. The control value can be a variable value or an attribute otherthan an array (per particle) attribute. The format follows:

switch ( control-value ){case value1 :

statement;statement ; ...break;

case value2 :statement;statement ; ...break;

case value3 :statement;statement ; ...break;...

default:statement;statement ;...break;

}

The switch executes with a variable control-value. If the variable contentsmatch value1, value2, or another value in the switch, the statements under theassociated case statement execute. The control-value can be an int, float,string, or vector.

Be careful if you use a float control-value. Because of the way floating pointarithmetic rounds numerals, a case value might fail to match a control-valueas you expect.

A break statement within a switch causes execution to skip subsequent casestatement groups within the switch instruction.

Page 84: Expressions-- Maya Expression Editor From Basic to Professional

84 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxProgramming features

Example 1: Break statement within a switch

int $sway = rand(3);switch ($sway)

{case 0:

print("Case 0\n"); // Executes if $sway = 0break;

case 1:print("Case 1\n"); // Executes if $sway = 1break;

case 2:while (rand(10) < 7)// These statementsprint("I say!\n");// execute onlyprint("Case 2\n");// if $sway = 2break;

}

When the expression executes a few times, it might display this randomselection of entries in the Script Editor:

Case 0Case 1I say!I say!I say!Case 2Case 0Case 1

The last case instruction in a switch doesn’t need a break statement becausethe switch is finished. Still, it’s best to add the break statement to avoidfuture problems that might result from adding other cases to the switch.

For details on the purpose of rand(3), see “rand” on page 243.

Page 85: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 85

Expression SyntaxProgramming features

Ex

pre

ss

ion

s

Example 2: Omitted break statement within a switch

The following expression omits a break statement to make the switchcontinue execution after the first case:

int $argo = rand(2);switch ($argo)

{case 0:

print("Food\n"); // Runs if $argo is 0.case 1:

print("Fight\n");// Runs if $argo is 0 or 1.break;

}

When the expression executes a few times, it might display this randomselection of entries in the Script Editor:

FightFightFightFoodFightFood

Whenever Food appears, Fight also appears after it. Fight can appearwithout Food being displayed.

Note that you can make more than one case statement execute the samestatements:

int $argo = rand(4);switch ($argo)

{case 0:case 1:

print("Food\n"); // Runs if $argo is 0 or 1case 2:case 3:

print("Fight\n");// Runs if $argo is 2 or 3break;

}

This works like the preceding expression, except that a match of 0 or 1displays Food and Fight, and a match of 2 or 3 displays Fight.

Page 86: Expressions-- Maya Expression Editor From Basic to Professional

86 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxProgramming features

Example

You can use the default keyword to make a block of statements execute whennone of the case values match the control value label. Generally, you put thislabel after all the case statements, though you can put it anywhere in theswitch statement.

If the switch has no default label and none of the case values match thecontrol value, the switch does nothing.

vector $mgb = <<1,1,0>>;switch ($mgb)

{case <<0,1,1>>:

print("Who?\n");// Runs if $mgb is <<0,1,1>>break;

case <<1,0,1>>:print("What?\n");//Runs if $mgb is <<1,0,1>>break;

default:print("Why?\n"); // Executes if $mgb is notbreak; // <<0,1,1>> or <<1,0,1>>

}

The expression executes the default case, which displays the following linein the Script Editor:

Why?

?: operatorThe ?: operator lets you write a shorthand if-else statement to set an attributeor variable in one statement. Because of its cryptic appearance, manyprogramming style experts suggest not using it.

Here’s its format:

attribute = condition ? statement1 : statement2 ;

The condition compares variable, attribute, or constant values. If condition istrue, Maya evaluates statement1 and assigns its value to attribute. (You canalso assign the statement’s value to a variable.)

Maya evaluates either statement1 or statement2, never both.

You can optionally enclose statement1 and statement2 in parentheses to makethe expression easier to read.

Page 87: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 87

Expression SyntaxProgramming features

Ex

pre

ss

ion

s

Example

Balloon.scaleY = (time < 2) ? time / 2: time * 2;

This statement sets Balloon’s scaleY attribute to time divided by 2 if time isless than 2, and time multiplied by 2 if time is greater than or equal to 2. Thiscauses the scaleY attribute to increase slower for the first two seconds thanafter two seconds.

This is the same as the following if-else statement:

if (time < 2)Balloon.scaleY = time / 2;

elseBalloon.scaleY = time * 2;

Use this format because it’s easier to read.

! operatorYou can use the not logical operator (!) with integer, float, and vector datatypes.

For vector values, ! is true only when the vector magnitude is 0. A vector’smagnitude is the value resulting from this equation:

The x, y, and z numbers in the formula represent the three components ofthe vector.

Important

If you use an integer value as statement1 and a floating point value asstatement2, the ?: operator truncates the floating point value of statement2 toan integer.

In the expression Balloon.scaleY = (time < 2) ? 0: time;, for example, 0 is aninteger, and time is a floating point value. When time is 2 seconds or more,Maya sets Balloon’s scaleY attribute to the integer value of time.

Because Maya sets scaleY to the integer value of time (without the decimalpart), scaleY jumps in one-second increments at time 2, 3, 4, and so on.

If you have problems using the ?: operator, use an if-else statement instead.

x2

y2

z2

+ +

Page 88: Expressions-- Maya Expression Editor From Basic to Professional

88 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxProgramming features

Examples

if (!$count)Ball.scaleY = 2;

The !$count condition is true only if $count is 0. If true, Ball.scaleY is set to 2.

vector $myvector = <<0,0,0>>;if (!$myvector)

Ball.scaleY = 2;

Because the magnitude of $myvector is 0, the !$myvector condition is trueand Ball.scaleY is set to 2.

Flow control errorsThe following topics describe solutions to common mistakes in expressionflow control statements.

Modifying variable values in test conditionsIf you use a while, do, or for loop in an expression, remember to change thevariable or attribute being tested in the test condition of the loop. Failing todo so can halt Maya operation.

Example 1

Suppose you create an object named Balloon and decide to use a while loopto increase its Y scaling after three seconds of animation play.

while (time > 3)Balloon.scaleY = time;

Though you might think this expression sets Balloon’s scaleY attribute to theincreasing value of time after the animation time exceeds 3 seconds, itactually halts Maya operation as soon as time exceeds 3. At that moment, thewhile condition is true, so the while loop statement Balloon.scaleY = timeexecutes repeatedly and endlessly.

Even though a statement sets an attribute within an expression, Mayaupdates the attribute only after the expression finishes executing. Becausethe expression never finishes executing, Maya halts.

Unless you change Balloon.scaleY within the while loop to a value less thanor equal to 3, the statement executes infinitely.

Page 89: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 89

Expression SyntaxProgramming features

Ex

pre

ss

ion

s

To get the desired result without halting Maya, use this expression:

if (time > 3)Balloon.scaleY = time;

Example 2

Suppose you create objects named Cone and Ball, then use a while statementto link the Ball’s translateY attribute to the Cone’s translateY attribute:

while (Cone.translateY > 0)Ball.translateY = Cone.translateY;

At first glance, the expression seems to set Ball’s translateY position to thevalue of the Cone’s translateY position whenever Cone’s translateY is greaterthan 0.

In fact, the expression halts Maya as soon as you translate the Cone to a Yposition greater than 0. At that moment, the while condition is true, so thewhile loop statement Ball.translateY = Cone.translateY executes endlessly.

Nothing you do in the user interface can change the Cone’s translateYposition. It stays at translateY value of 0.

Unless you change Cone.translateY within the while loop to a value lessthan or equal to 0, the statement executes infinitely.

To get the desired result without halting Maya, use this expression:

if (Cone.translateY > 0)Ball.translateY = Cone.translateY;

Comparing floating point values to 0 with ==If you use the == operator to compare a floating point variable or attribute to0, your expression might not work correctly. This typically occurs when youassume the value returned by a built-in function such as cosd will be exactly0.

Example

float $x = cosd(90);if ($x == 0)

print("This equals 0.\n");else

print("This doesn’t equal 0.\n");

Page 90: Expressions-- Maya Expression Editor From Basic to Professional

90 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxProgramming features

The expression displays the following text:

This doesn’t equal 0.

Though the cosine of 90 degrees is mathematically 0, the cosd(90) functionreturns the value 6.123e-17, which is extremely close to 0 but not exactlyequal. Though the number for practical purposes is the same as 0, it’s storedin the computer as a fractional quantity above 0 because of the waycomputers handle floating point numbers.

To fix the problem, compare the values as in this expression:

float $x = cosd(90);if (($x > -0.0001) && ($x < 0.0001))

print("This equals 0.\n");else

print("This doesn’t equal 0.\n");

The expression displays the following text:

This equals 0.

By checking that $x is between -0.0001 and 0.0001, the appropriate printstatement executes. The value returned by cosd(90) is so close to 0 that it’swithin the small range specified in the if statement’s numerical comparison.

String usageA string is a sequence of alphabetical, numerical, and special characters. Youcan display strings in the Script Editor, for example, to check the contents ofattributes or variables.

You can also create strings in the Expression Editor to execute MELcommands in an expression. See Chapter 7 for details.

Guidelines for using strings follow:

• Enclose a literal string with double quotes as in this example:

print("asteroid2");

This displays the following text:

asteroid2

• You can use the + operator to concatenate strings as in this example:

print("Ball’s scaleY attribute equals: " + Ball.scaleY);

Page 91: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 91

Expression SyntaxProgramming features

Ex

pre

ss

ion

s

This displays the following text:

Ball’s scaleY attribute equals: 0.3333333333

• The following table lists how Maya converts data types if you use arithmeticoperators with strings in an expression.

For example, suppose you type the following statement:

print("Hi there, "+007);

This displays the following text:

Hi there, 007

• If you’re familiar with C programming, be aware you can assign a string to avector as in these examples:

vector $i = (vector) "<<1,2,3>>";

vector $i = vector ("<<1,2,3>>");

• You can execute a MEL command in an expression statement. See“Executing MEL commands in an expression” in Chapter 7.

Shortcut assignment operatorsYou can use shorthand assignment operators to save typing time comparedto their longhand counterparts.

In place of a statement like this:

$height = $height + 3;

You can use this statement:

$height += 3;

Arithmetic operation Resulting data type

string operator integer string

string operator float string

string operator vector string

Page 92: Expressions-- Maya Expression Editor From Basic to Professional

92 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxProgramming features

The following table shows the shorthand operators and the valid data typesfor each. The shorthand operators work like their counterparts in C.

Do not insert a space between the operator and =.

Example

$counter += 1;

This adds 1 to $counter each time the statement executes.

Shortcut increment and decrement operatorsYou can use the ++ and -- shortcut increment and decrement operators toincrease or decrease floating point and integer variables by 1. The followingtable shows the shortcut syntax and its equivalent expanded syntax:

When the increment or decrement operator precedes the variable, theincrement or decrement occurs before the statement executes. When theoperator follows the variable, the increment or decrement occurs after thestatement executes.

Symbol Data type

+= integer, float, vector, string

-= integer, float, vector

/= integer, float, vector

*= integer, float, vector

%= integer, float

Shortcut syntax Expanded syntax

++variable; variable = variable + 1;

--variable; variable = variable - 1;

variable++; variable = variable + 1;

variable--; variable = variable - 1;

Page 93: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 93

Expression SyntaxProgramming features

Ex

pre

ss

ion

s

Examples

float $eel = 32.3;float $crab = $eel++; // $crab = 32.3; $eel = 33.3;$crab = $eel--; // $crab = 33.3; $eel = 32.3;$crab = --$eel; // $crab = 31.3; $eel = 31.3;$crab = ++$eel; // $crab = 32.3; $eel = 32.3;

ArraysYou can create arrays of float, vector, integer, or string values. You can clearan array using a clear function. You can find the size of an array with thesize function. See “Array functions” in Chapter 9 for details.

When you assign a value in an array, Maya reserves memory for allelements less than that number. This means you can exceed the capacity ofyour computer with a single array declaration. For example, do not use astatement like this:

$newarray[12312323123] = 1;

Examples: Defining an array

float $myarray[];

vector $myposition[];

int $p[];

Note that an array expands its size automatically as you assign values to itselements. You don’t need to declare its size. If your array assignmentexceeds the size of the array, the array expands to that size. If you referencean element of the array beyond the array size, a 0 is returned.

Suppose you include these statements in an expression:

int $p [];$p[1500] = 3;$p[2000] = 5;

Important

To avoid unexpected results, do not use more than one shortcut incrementor decrement operator on the same variable in the same statement. Theevaluation order of the operators is unpredictable.

Page 94: Expressions-- Maya Expression Editor From Basic to Professional

94 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxProgramming features

The second statement makes the array contain 1501 elements and assignselement 1500 the value 3. The third statement expands the array to 2001elements and assigns element 2000 the value 5.

Example: Initializing and printing an array’s contents

float $fa[];print("$fa size: "+size($fa)+"\n");

for( $i = 0; $i < 10; $i = $i + 1){

$fa[$i] = $i;print($fa[$i]+"\n");

}print("fa size: "+size($fa)+"\n");

This expression displays the following:

$fa size: 00123456789$fa size: 10

The first statement creates an array of floating point variables named $fa[ ].The next statement displays the size of the array, which has 0 elements afterits definition.

The for loop executes the statements between the braces 10 times, once foreach increment of $i from 0 to 9. The first statement between the braces ({ })initializes and sets the value of one element of the array. Array element$fa[0] is set to floating point value 0, element $fa[1] is set to 1, element $fa[2]is set to 2, and so on.

The print statement between the braces displays the value of each element ofthe array after you initialize it. In other words, the Script Editor displays 0through 9.

Page 95: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 95

Expression SyntaxCommon expression errors

Ex

pre

ss

ion

s

The for loop stops executing after $i becomes equal to 10. Then the finalprint statement displays the number of elements of the initialized array, 10.The array increased in size as you assigned values to its elements.

Boolean symbolic constantsYou can use the symbolic constants on, true, or yes for the Boolean numericvalue 1. You can use off, false, or no to represent 0. Be aware that on, true,and yes are equal only to 1. They aren’t equal to nonzero values.

Example

if (Monster.visibility == on)Lance.scaleY = time / 3;

This causes Lance’s scaleY attribute to increase only if Monster’s visibilityattribute is on. The on represents 1.

print(3 + on);

This displays 4 in the Script Editor. Again, on represents the value 1.

Common expression errorsThere are two types of errors you can make when writing expressions:syntax errors and logic errors. Syntax errors include mistakes in spelling,incomplete attribute names, omitted semicolons, and other oversights thatprevent the expression from compiling and executing. For syntax errors,Maya explains the error in a message to the Script Editor.

Logic errors are mistakes in your reasoning that cause unexpected animationresults. The syntax of your expression is valid, but errors in your logicprevent Maya from doing what you intended. In the worst cases, Mayamight halt operation because your statements lock it into a permanent loop.

Because Maya can’t detect logic errors, it can’t display error messages. Assuch, these errors are harder to find and require more analysis to solve. Toresolve logic errors, it’s often helpful to display the contents of relevantattributes and variables. See “Displaying attribute and variable contents” inChapter 7.

Error message formatA syntax error displays one or more messages in the Script Editor.

Page 96: Expressions-- Maya Expression Editor From Basic to Professional

96 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxCommon expression errors

You’ll often need to scroll or increase the size of the Script Editor to see anentire message.

When the Script Editor displays a syntax error, the response area of theCommand Line displays the same error with a red background.

If an expression executes a valid statement after the erring statement, theerror message with the red background flashes briefly. You won’t notice itunless you’re looking directly at it and have quick eyes.

The best way to know when an error has occurred is to look for a newmessage prefixed by // Error: in the Script Editor.

Command line’s response area turns red if error occurs

Page 97: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 97

Expression SyntaxCommon expression errors

Ex

pre

ss

ion

s

Before clicking the Create or Edit button to create an expression, you mightwant to select Edit→Clear History in the Script Editor to remove previousmessages in the window. This makes it easier to see when a new errormessage appears.

Common error messagesHere are some common syntax errors and their explanations:

Attribute not found or variable missing '$': Ball.goof.

You misspelled an attribute name, the attribute doesn’t exist in the scene, oryou forgot to prefix a variable name with $.

Attribute of a particle object can only be used withdynExpression command: particleShape1.position

You used a particle array attribute in the expression, but a particle shapenode is not the Selected Object in the Expression Editor. A particle shapenode must be selected to use particle array attributes. A particle arrayattribute is also called a per particle attribute.

Attribute already controlled by an expression, keyframe, orother connection: Balloon.tx.

You tried to set the value of an attribute that has already been set by one ofthese techniques:

• set driven key

• constraint

• motion path

• another expression

• any other direct connection

More than one attribute name matches. Must use unique pathname: Ball.tx.

You used an object.attribute name that exists in two or more parent objects.Two objects in a scene can have the same object name if they have differentparent objects.

For example, a scene might have a child of GroupA named Ball.tx and adifferent child of GroupB named Ball.tx. If you write a statement such as“Ball.tx = time;”, Maya won’t know which Ball.tx to set.

Page 98: Expressions-- Maya Expression Editor From Basic to Professional

98 Using Maya: Hypergraph, Sets & Expressions

Expression SyntaxCommon expression errors

To eliminate the error in this example, you must enter the full pathname ofthe attribute as GroupA|Ball.tx. The pipe symbol (|) specifies that the objectto its left is the parent of the object on the right.

Cannot set 'time' or 'frame'

You can read the value of the predefined time and frame variables, but youcannot set them.

Attributes must be of float, integer, or boolean types:Ball.worldMatrix

You tried to set or read the value of an attribute that was a string or matrixtype. For instance, you might have tried to use an attribute named translaterather than translateX, translateY, or translateZ attribute.

In the error message above, worldMatrix is an attribute that exists fortransforms, but you can’t use it. It’s for Maya’s internal use.

Cannot divide by zero

You tried to divide by an attribute or variable that equals 0. This typicallyhappens in an expression statement that divides by an object’s translateX,translateY, or translateZ attribute when the Snap to grids button is on andyou drag the object to past the X-, Y- or Z-axis. When Snap to grids is on, thetranslateX, translateY, or translateZ attribute becomes exactly equal to 0 atthe point where you drag the object across the axis.

To prevent this error, turn Snap to grids off. With snapping off, the attributeis unlikely to become exactly 0 as you drag across the axis.

Note

If you compile an expression for a particle shape node and see the sameerror message once for each particle in the object, it’s likely that someattribute name, variable, or function is undefined or misspelled.

Page 99: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 99

Ex

pre

ss

ion

s

6 Editing Expressions

The Expression Editor offers convenient techniques for editing the text ofexpressions. There are filters that help you search for expressions youpreviously created, as well as techniques for entering and modifying the textof an expression.

This chapter describes the following topics:

• “Finding expressions” on page 99

• “Editing an expression in the text field” on page 105

• “Editing an expression with a text editor” on page 106

• “Creating a new expression” on page 111

• “Deleting an expression” on page 112

• “Using attribute names in expressions” on page 112

Finding expressionsAfter you’ve created an expression, you might decide later to alter it tocreate a different animation result. To edit an expression, you display it inthe Expression Editor. The following sections describe how to find anddisplay an expression for editing.

You can edit an expressiondirectly in the text box or witha text editor such as vi.

Page 100: Expressions-- Maya Expression Editor From Basic to Professional

100 Using Maya: Hypergraph, Sets & Expressions

Editing ExpressionsFinding expressions

Finding by expression nameTo find an expression, you can choose from a list of all expressions in thescene.

To search for an expression by name:

1 From the Expression Editor, choose Select Filter→By Expression Name.

An Expressions list appears in the Expression Editor. This list shows allexpressions created for the scene.

2 Click the expression in the list.

The expression contents appear in the expression text field.

If you don’t remember the name of the expression, click each name on thelist until the desired expression appears in the expression text field.

Note

For a particle shape node, you can create a creation expression, a runtimeexpression, or both. Both expressions are listed under a single name—thename of the particle shape node. You can’t name or rename suchexpressions.

To find such expressions, look for the particle shape node’s name in theExpressions list.

Click the appropriate Runtime or Creation checkbox to display the desiredexpression.

List of expressions

Page 101: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 101

Editing ExpressionsFinding expressions

Ex

pre

ss

ion

s

Finding by selected objectIf you can’t remember the name you gave an expression, you can find it byselecting the affected object. For a nonparticle shape node, you can alsoselect an affected attribute from the Attributes list to narrow the search forthe expression.

To search for an expression by object and attribute name:

1 Select the object or other node in the Outliner, Hypergraph, or workspace.

2 Choose Select Filter→By Object/Attribute Name in the Expression Editor.

This is the default search setting for the Expression Editor.

3 Choose Object Filter→Selected Objects.

The selected object’s name and appropriate attributes appear in the window.

4 For an object other than a particle shape node, click the name of the attributecontrolled by the expression.

If you’ve forgotten the name of the attribute controlled by the expression,choose Attribute Filter→Connected to Expressions. The Attributes listdisplays only the attributes controlled by expressions for the selected object.Click each attribute in the Attributes list until you see the desired expressionin the expression text field.

You can’t write a different expression for each attribute of a particle shape asyou can for other types of objects. Because you can write only one creationexpression and one runtime expression per particle shape, you don’t need toselect an attribute from the Expression Editor’s Attributes list. See“Understanding particle expressions” on page 148 for details on particleexpressions.

Object name

Object’s attributes

Page 102: Expressions-- Maya Expression Editor From Basic to Professional

102 Using Maya: Hypergraph, Sets & Expressions

Editing ExpressionsFinding expressions

Finding by item typeYou can find an expression based on the type of object or item theexpression affects. For example, if you can’t remember an expression’s namebut remember you applied it to a shader node, you can narrow your searchto expressions that control shader nodes in the scene.

To search for an expression by item type:

1 In the Expression Editor, choose Select Filter→By Object/Attribute Name.

2 From the Object Filter menu, select the type of object or item the expressionaffects.

3 Choose Attribute Filter→Connected to Expressions.

4 Select the affected object or item from the Objects list.

5 Select the affected attribute from the Attributes list.

The expression that controls the attribute appears in the expression text field.

Example

Suppose you’ve written an expression that controls the rotateZ attribute of aspotlight transform node named Searchlight. Do this to find the expression:

1 Choose Select Filter→By Object/Attribute name.

2 Select Object Filter→Transforms.

Note that you don’t select Object Filter→Lights in this example. The rotateZattribute is an attribute of a light’s transform node, not of the light objectitself.

3 Choose Attribute Filter→Connected to Expressions.

4 Select the object Searchlight from the Objects list.

Note

The Attributes list shows only unlocked, keyable attributes. You canchoose whether an attribute is keyable or locked with View→Object→Editors→Channel Control.

To write an expression for any nonkeyable attribute not shown in the list,enter object.attribute name in the Selected Obj & Attr text box.

Page 103: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 103

Editing ExpressionsFinding expressions

Ex

pre

ss

ion

s

5 Click rotateZ from the Attributes list.

The expression appears in the expression text field.

Using the Selection listThe Expression Editor displays a Selection list by default. This list displayseither a list of objects and attributes, or a list of expressions you’ve created.

To display the list of objects and attributes, choose Select Filter→By Object/Attribute Name. This is the default display.

To display the list of expressions you’ve created in the scene, chooseSelect Filter→By Expression Name.

Using the Objects and Attributes listThe objects listed in the Objects list depend on which entry you’ve selectedfrom the Object Filter menu. If you select Object Filter→Lights, forinstance, all lights in the scene appear in the list.

The appropriate attributes of the object selected in the Objects list appear inthe Attributes list. For example, if spotLightShape1 is selected in the Objectslist, the attributes of spotLightShape1 appear in the list.

When searching for an expression to edit, you can click an object andattribute from this list to find and display an expression that affects thechosen attribute. You can edit the displayed expression in the expression textfield.

Expressions list

Selection list triangle

Page 104: Expressions-- Maya Expression Editor From Basic to Professional

104 Using Maya: Hypergraph, Sets & Expressions

Editing ExpressionsFinding expressions

For a particle shape node, you don’t need to select an attribute from theAttributes list. You can create only one creation expression and one runtimeexpression per particle shape node. The same expression appears for eachattribute.

When you create a new expression, you can click an object from this list tochoose the default object to which the expression applies.

When you select the default object in the Expression Editor, you can skipomit the object name and period that’s part of a full attribute name (see“Omitting an object name in expressions” on page 115.)

Using the Expressions listThe Expressions list shows all expressions you’ve created in the scene. Whensearching for an expression to edit, click an expression from this list todisplay and edit its contents.

Hiding the Selection listYou can hide the Selection list to lessen clutter in the window. To do so, clickthe triangle next to Selection (see previous figure). This triangle collapsesand expands the list.

Filtering attributes from the Selection listIf a selected object has several attributes controlled by expressions but you’renot sure which attributes, you can select a filter to list only attributescontrolled by an expression.

To filter attributes from the Attributes list:

1 Select the object containing the attributes.

2 Choose Select Filter→By Object/Attribute Name.

3 Choose Object Filter→Selected Objects.

4 Choose Attribute Filter→Connected to Expressions.

Only the object’s attributes controlled by expressions appear in theAttributes list.

To see all attributes you can control with an expression again, chooseAttribute Filter→All.

Page 105: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 105

Editing ExpressionsEditing an expression in the text field

Ex

pre

ss

ion

s

Editing an expression in the text fieldThe Expression Editor provides techniques for deleting and copying text inthe expression text field. There are also techniques for clearing and restoringthe text of an expression.

Deleting and copying text

To delete text:

1 Drag the mouse to select the text.

2 Press your keyboard’s Backspace key to delete it.

To copy and paste text:

1 Drag the mouse to select the text to be copied.

2 At the point in the text where you want to copy the text, click with themiddle mouse button.

This technique takes a little practice. If you find this frustrating, you mightprefer using a text editor native to your operating system, for example, vi orjot. See “Editing an expression with a text editor” on page 106.

Important

If you close the Expression Editor window without successfully compilingan expression with the Create or Edit button, Maya discards any editingchanges you’ve made to the expression.

Expression text field

Page 106: Expressions-- Maya Expression Editor From Basic to Professional

106 Using Maya: Hypergraph, Sets & Expressions

Editing ExpressionsEditing an expression with a text editor

Clearing the expression text fieldYou can erase the entire expression text field by clicking a button rather thandragging and deleting text.

To clear the expression text field:

Click the Clear button.

Reloading an expression’s previous contentsClicking the Create or Edit button compiles an expression. If you’ve madean editing change and haven’t yet clicked the Edit button, you can reload theprevious expression if you don’t like the results.

To reload the expression:

Click the Reload button.

This restores the expression to the contents last present when you clicked theCreate or Edit button.

Editing an expression with a text editorFrom the Expression Editor, you can start a text editor such as vi to createand edit an expression. Text editors have features useful for editing bigexpressions.

When you start the text editor for an expression, you can edit only thatexpression with that instance of the text editor. However, you can start thetext editor once for each of several expressions if you want to examine oredit several expressions at the same time.

Once you start a text editor for an expression, the Expression Editor’s textfield dims to indicate you can’t work there while the text editor runs. Youcan, though, work in the expression text field for another expression.

Important

To erase an expression and make sure its previous contents no longercontrol an attribute, click the Edit button after clicking the Clear button.

Page 107: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 107

Editing ExpressionsEditing an expression with a text editor

Ex

pre

ss

ion

s

There is no file on disk you can edit independently of the Expression Editor.When you use the text editor through the Expression Editor, you’re workingwith a temporary file that’s linked to the expression stored in the scene. Youcan, however, read an independent text file containing expression text intothe temporary file.

If you save an expression without specifying a filename, Maya reads thesaved expression and stores it with the scene. You’ll see it dimmed in theexpression text field while you’re working with the text editor.

When you close the text editor, the expression text field entry no longer isdim. The text expression field becomes active after you close the text editor.

If you quit the text editor without saving the expression, Maya does nothing.Because the expression hasn’t changed, Maya’s copy of the expressiondoesn’t need to change either.

Using an editor listed in the Editor menuBy default, you can start one of these editors from the Editor menu in theExpressions Editor:

• jot

• vi

• vim

• xemacs

To run a different editor, see “Using an editor not listed in the Editor menu”on page 109.

To start an editor listed in the menu:

1 From the Editor pull-down menu in the Expression Editor, select an editor.

2 Double-click an object name, expression name, or attribute name from theSelection list.

Tip

You can use a text editor to save an expression to a filename in thedirectory of your choice. This gives you a way to archive an expression youwant to use in a different scene.

Page 108: Expressions-- Maya Expression Editor From Basic to Professional

108 Using Maya: Hypergraph, Sets & Expressions

Editing ExpressionsEditing an expression with a text editor

The editor appears. An example display of vi follows:

The editor’s title bar shows a filename that’s temporarily created while youwork on the expression. When you write or save the file, its contents arecopied to the Maya scene containing the expression.

The expression text field is inactive while the text editor is open. You canoptionally close the Expression Editor window.

If you single-click the name of an object, attribute, or expression, the texteditor doesn’t appear. You can single-click to browse the contents in theexpression text field without opening a text editor.

If you double-click an attribute that’s already been assigned a value in anexpression, the expression that controls that attribute appears in the texteditor. For nonparticle expressions, you can assign to any attribute in thescene, not just to the double-clicked attribute. In fact, you don’t even need towork with the double-clicked attribute at all.

If you double-click an attribute that has not yet been assigned a value, thetext editor appears with no contents. If you double-click that attribute again,a new instance of the editor appears. After you assign a value to an attributein an expression, you can start the editor only once for the attribute.

3 Create or edit the expression with the editor.

4 Save the file.

5 Confirm that the Expression Editor detected no syntax errors.

6 Quit the editor.

Page 109: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 109

Editing ExpressionsEditing an expression with a text editor

Ex

pre

ss

ion

s

Using an editor not listed in the Editor menuIf your workstation has a text editor that’s not listed in the Editor menu, youcan use it after doing a few preliminary UNIX system administration tasks.

To start an unlisted editor:

1 In your UNIX .cshrc file, set the WINEDITOR environment variable tospecify the desired editor and options.

See “Changing an editor’s operation settings” on page 110 for examples.

You can choose any valid options for the editor, but you must specify thatthe editor runs in the foreground (if this option is relevant to the editor).

If the editor normally appears in the shell where you launched it, you mustmake the WINEDITOR setting display the editor in a shell.

2 Log out and log into your user account.

3 Restart Maya.

4 Choose Other from the Editor pull-down menu.

5 Double-click an object name, expression name, or attribute name from theSelection list.

The editor appears.

6 Create or edit the expression with the editor.

7 Save the file.

8 Confirm that the Expression Editor detected no syntax errors.

9 Quit the editor.

Note

If you’ve created a UNIX command alias for jot, vi, vim, or xemacs, theExpression Editor tries to launch this command. If the arguments providedin the command alias are unusable by the Expression Editor, the editormight operate unexpectedly or fail to launch.

Avoid using an alias to customize your editor’s operation settings. Do thesteps in “Changing an editor’s operation settings” on page 110.

Page 110: Expressions-- Maya Expression Editor From Basic to Professional

110 Using Maya: Hypergraph, Sets & Expressions

Editing ExpressionsEditing an expression with a text editor

Changing an editor’s operation settingsMaya launches the editors listed in the Editor menu with default operationsettings. You can change the operation settings with a few preliminarysystem administration tasks.

To change an editor’s operation settings:

1 Set the WINEDITOR environment variable to specify the desired editoroptions.

You can choose any valid options for the editor, but you must specify thatthe editor runs in the foreground (if this option is relevant to the editor). Forexample, jot requires the option -f, vim requires -g -f, and xemacs requiresthe option -nw.

An example of setting WINEDITOR for vi follows:

setenv WINEDITOR “xwsh -name mayaEditor -e vi”

An example for vim follows:

setenv WINEDITOR “xwsh -geometry 80x57+350+130 -bg 97 -evim”

2 Log out and log into your user account.

3 Restart Maya.

4 Choose Other from the Editor pull-down menu.

5 Double-click an object name, expression name, or attribute name from theSelection list.

The editor appears.

6 Create or edit the expression with the editor.

7 Save the file.

8 Confirm that the Expression Editor detected no syntax errors.

9 Quit the editor.

Selecting an editor for default startupYou can make an external text editor start by default each time you start atext editor.

Page 111: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 111

Editing ExpressionsCreating a new expression

Ex

pre

ss

ion

s

To start an editor by default:

1 Choose Options→UI Preferences.

2 In the UI Preferences window, click the Misc folder.

3 Choose the editor in the Expression Editor menu.

To choose an editor specified with the WINEDITOR environment variable,select Other.

4 Click Save Changes to close the window.

5 In the Expression Editor, double-click an object name, expression name, orattribute name from the Selection list.

The editor appears. The next time you start the Expression Editor, theeditor’s name appears in the Editor pull-down menu by default.

If you’ve chosen different text editors in UI Preferences and the Editormenu, the one chosen in UI Preferences appears.

Creating a new expressionYou can create a new expression after you’ve been editing an existing one.

To create a new expression:

1 Make sure you click the Create or Edit button to compile the existingexpression.

2 Choose Select Filter→By Expression Name.

3 Click the New Expression button.

This clears the Expression Name box and expression text field so you cancreate a new expression.

Important

If you’ve specified a text editor through Options→UI Preferences or withthe Expression Editor’s Editor menu, starting the Expression Editor fromthe Channel Box or Attribute Editor displays the text editor instead of theExpression Editor.

Note the text editor appears when you click the New Expression button.

Page 112: Expressions-- Maya Expression Editor From Basic to Professional

112 Using Maya: Hypergraph, Sets & Expressions

Editing ExpressionsDeleting an expression

When you create the expression, the Expression Editor associates the objectname with the expression. This means you can narrow your search for theexpression using the object’s name in addition to the expression name.

You do not need to select an attribute in the Attributes list. You can associatethe expression with an object only.

For a particle shape node, you don’t need to select an attribute, as you cancreate only one creation expression and one runtime expression per particleshape. For nonparticle shape objects, you can create one expression perattribute.

Deleting an expressionIf you want to stop an expression from controlling attributes, you can deletethe expression.

To delete an expression:

1 Display it in the Expression Editor.

2 Click the Delete button.

Using attribute names in expressionsA full attribute name has this format:

object.attribute

where object is the name of the object node and attribute is the name of theattribute. A period separates the name of the object and attribute.

Object and attribute names are case-sensitive. You must spell them withuppercase and lowercase letters as they appear in the Expression Editor’sObjects and Attributes lists. You cannot spell attribute names with thecommon English spellings shown in the Attribute Editor or by default in theChannel Box.

The following topics show how you can abbreviate attribute names to savetyping time.

Page 113: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 113

Editing ExpressionsUsing attribute names in expressions

Ex

pre

ss

ion

s

Using attribute name abbreviationsYou can use an abbreviation in place of any full attribute name in theexpression text field.

Example

In place of this:

Ball.translateY = time;

you can type this:

Ball.ty = time;

Each attribute has at least one acceptable abbreviation. Here are somecommonly used attribute name abbreviations for several types of objecttransform nodes:

To see the abbreviations for attributes that can be keyframed:

1 Select the object or item containing the desired attributes.

2 Turn on Options→Channel Box to display the Channel Box.

Long name Abbreviation

translateX tx

translateY ty

translateZ tz

rotateX rx

rotateY ry

rotateZ rz

scaleX sx

scaleY sy

scaleZ sz

visibility v

Page 114: Expressions-- Maya Expression Editor From Basic to Professional

114 Using Maya: Hypergraph, Sets & Expressions

Editing ExpressionsUsing attribute names in expressions

Common English equivalents for the long attribute names appear in theChannel Box by default. These names are different than the names you mustuse in the expression text field.

If you use the long attribute name, use the name that appears in theAttributes list of the Expression Editor. Do not use the common Englishlanguage equivalents displayed in the Channel Box.

3 From the Channels menu at the top of the Channel Box, selectChannel Names→Short.

The abbreviated attribute names replace the common English attributenames in the Channel Box.

Do not use thesecommon Englishnames

Use either attribute longnames or abbreviatednames in expressions

Page 115: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 115

Editing ExpressionsUsing attribute names in expressions

Ex

pre

ss

ion

s

To see abbreviations for other attributes:

Execute this MEL command in the Script Editor:

listAttr -sn objectname

where objectname is the name of the object or other node.

Omitting an object name in expressionsIf you select an object as the Default Object in the Expression Editor, you canomit the object name and period that’s part of a full attribute name.

Example

Suppose you’ve selected Ball as the Default Object.

In place of this:

Ball.translateY = time;

you can type this:

translateY = time;

Maya interprets translateY as belonging to Ball, the object listed in theDefault Object text box of the Expression Editor.

To make an object the Default Object:

Enter the object’s name in the Default Object text box.

By default, the selected object is also the default object. You can omit theobject name only for attributes of the object in the Default Object text box.

The Default Object text box is dim when a particle shape node is the selectedobject in the Expression Editor. Because a particle shape node’s attributescan be controlled by only one creation expression and one runtimeexpression, the particle shape node is always the default object when it is theselected object.

Note

After you click Create or Edit to compile an expression, Maya converts allattribute abbreviations in the expression to the full attribute name.

Page 116: Expressions-- Maya Expression Editor From Basic to Professional

116 Using Maya: Hypergraph, Sets & Expressions

Editing ExpressionsUsing attribute names in expressions

Combining the abbreviation techniquesYou can combine the abbreviation techniques mentioned in the two previoustopics to minimize typing.

Example

Suppose you’ve selected Ball as the Default Object.

In place of this:

Ball.translateY = time;

you can type this:

ty = time;

Maya interprets ty as being the translateY attribute of Ball, the object listedin the Default Object text box of the Expression Editor.

Attributes of other objects must be spelled out with the full object andattribute name.

Page 117: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 117

Ex

pre

ss

ion

s

7 Beyond the Basics

This chapter describes advanced concepts for writing expressions. Unlessotherwise noted, the topics within apply to expressions for attributes of allobjects, including particles. For additional details on working with particles,see Chapter 8, “Particle Expressions.”

This chapter describes the following topics:

• “How often an expression executes” on page 118

• “Using custom attributes in expressions” on page 118

• “Displaying attribute and variable contents” on page 123

• “Reproducing randomness” on page 123

• “Speeding expression execution” on page 127

• “Reducing redundant expression execution” on page 130

• “Removing an attribute from an expression” on page 131

• “Disconnecting an attribute” on page 132

The falling cube is a soft body withgoal and springs. As its points movebelow the floor, an expressionassigns them a goal weight of 0.The cube appears to melt as itpasses through the floor.

Rob Tesdahl

Page 118: Expressions-- Maya Expression Editor From Basic to Professional

118 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsHow often an expression executes

• “Renaming an object” on page 136

• “Executing MEL commands in an expression” on page 137

• “Understanding path names” on page 140

• “Understanding unexpected attribute values” on page 141

How often an expression executesAfter you’ve typed an expression in the Expression Editor, you click theCreate or Edit button to compile the expression. Compiling the expressionchecks it for syntax errors and converts it to a form Maya can execute whenyou rewind or play the animation. After being compiled, the expressionexecutes for the current frame.

When you select an object other than a particle shape node, the ExpressionEditor displays an Always Evaluate checkbox that affects when anexpression executes. If you select a particle shape node, the ExpressionEditor dims this checkbox. For details on particle shape node expressions,see Chapter 8, “Particle Expressions”).

Generally an expression executes whenever the current animation time orframe changes. For example, an expression executes when you rewind orplay the animation. The expression executes once for each time theanimation frame or time changes.

An expression also generally executes when your interaction with Mayamakes use of an attribute in the expression. For example, if your expressionassigns a sphere’s translateX attribute to another attribute and you move thesphere in an X-axis direction, the expression executes upon each incrementof the sphere’s movement.

Occasionally, it’s useful to turn off Always Evaluate to diminish redundantexpression execution and speed Maya operation. Before doing this, it’s bestto understand the subtle details of expression execution. See “Reducingredundant expression execution” on page 130 for details.

Using custom attributes in expressionsIt’s often helpful to add a custom attribute to an object and use it in anexpression. You can use a custom attribute to control a combination of otherattributes. You can also use a custom attribute as a variable—a place to storea value temporarily to be read by other attributes.

Page 119: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 119

Beyond the BasicsUsing custom attributes in expressions

Ex

pre

ss

ion

s

Custom attributes have no direct effect on any characteristic of an object.

See “Assigning to a custom attribute” in Chapter 8 for details on how to addand use a custom attribute with particles.

Example

Suppose you’ve given a NURBS sphere named Planet a circular, orbitingmotion in the XY plane with this expression:

Planet.tx = sin(time);Planet.ty = cos(time);

Planet orbits the origin at a radius of 1 unit.

In the following steps, you’ll create a custom attribute named distance toincrease the radius of Planet’s orbit over time.

To add a custom attribute to alter the orbit:

1 Select Planet.

2 Choose Modify→Add Attribute.

Note

The small balls in the preceding figure show the circular path of Planet.They’re in the figure only to help you visualize the motion. They aren’tpart of the animation or expression.

Page 120: Expressions-- Maya Expression Editor From Basic to Professional

120 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsUsing custom attributes in expressions

3 In the Add Attribute window, enter distance in the Attribute Name text box.

4 Make sure Make attribute keyable is on.

5 Set Data Type to Float, and Attribute Type to Scalar.

6 Set Minimum to 1, Maximum to 10, and Default to 4.

Minimum and Maximum set the lowest and highest values you can enterfor the attribute in the Attribute Editor or Channel Box.

Default sets the default value displayed for the attribute.

An expression isn’t bound by the Minimum and Maximum values. Theattribute receives whatever value you assign it in the expression.

The expression can read the Default value or any other value you set in theAttribute Editor or Channel Box.

7 Click Add to add the attribute, then close the Add Attribute window.

Page 121: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 121

Beyond the BasicsUsing custom attributes in expressions

Ex

pre

ss

ion

s

The distance attribute appears in the Attributes list of the Expression Editorfor Planet. You can now set or read the value of the attribute in anyexpression.

8 Edit the expression to this:

Planet.tx = distance * sin(time);Planet.ty = distance * cos(time);

Multiplying the sin(time) and the cos(time) by the distance attribute makesPlanet circle the origin at a distance specified by the value of the distanceattribute. See Chapter 9 for details on the sin and cos functions.

Because you gave the distance attribute a default value of 4 when you addedit to Planet, playing the animation makes Planet circle the origin at a distanceof 4 grid units from the origin.

You can make the expression control the distance attribute over time.

9 Edit the expression to this:

distance = time;Planet.tx = distance * sin(time);Planet.ty = distance * cos(time);

By setting distance to the value of time, Planet’s orbiting distance increasesas playback time increases. Planet moves in a steady outward spiral as theanimation plays.

Page 122: Expressions-- Maya Expression Editor From Basic to Professional

122 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsUsing custom attributes in expressions

Instead of using an expression to control distance, you can keyframe itsvalue over time.

For example, by keyframing a distance value of 1 at frame 1 and a value of10 at frame 200, Planet moves in a steady outbound spiral as you play the200 frames. Planet’s distance increases in a linear interpolation from 1 to 10as the animation plays.

You can animate the distance attribute with keyframes or with anexpression, not with both.

Tip

If an expression controls an attribute and you want to control it withkeyframes instead, delete all statements that assign values to the attribute,then click the Edit button. Use the Channel Box to reset the attribute’svalue to an initial value, then set keyframes as desired.

If keyframes control an attribute and you want to control it with anexpression instead, click the attribute’s text box in the Channel Box, thenchoose Channels→Delete Selected. Assign values to the attribute name inan expression as desired.

Page 123: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 123

Beyond the BasicsDisplaying attribute and variable contents

Ex

pre

ss

ion

s

Displaying attribute and variable contentsThe predefined print( ) function displays attribute contents, variablecontents, and other strings in the Script Editor. This is often helpful fordebugging an expression. See “print” on page 261 for more details.

Note that for a nonparticle expression consisting of only print statements,Always Evaluate must be on in the Expression Editor for the expression toexecute.

Reproducing randomnessIf you execute the rand, sphrand, and gauss functions repeatedly in anexpression, Maya returns a sequence of random numbers. (See “Randomnumber functions” on page 239 for details on these functions.) Each time yourewind and play your animation, the sequence of random numbers isdifferent. Often, you’ll want to generate a sequence of random numbers thatrepeats each time your animation plays.

For instance, suppose you use the rand function to assign a random radiusto each particle in a stream of emitted particles rendered as Spheres. Bydefault, Maya gives the particles a different sequence of random radiusvalues each time your animation plays.

To create the same radius values each time the animation plays, you can usethe seed function in an expression before the rand, sphrand, or gaussfunctions execute. There’s no need to execute the seed function more thanonce per animation unless you need to generate several different repeatingsequences of random numbers as your animation plays.

Important

When you set a seed value in an expression or MEL script, the seed valueaffects the rand, sphrand, and gauss functions in other expressions andMEL scripts. Such functions are affected by this seed value in all scenesyou open subsequently in the current work session.

This seed value is unrelated to the Seed option available throughSettings→Dynamics Controller in the Dynamics menus. The seed functiontherefore doesn’t affect randomness created with dynamics.

Page 124: Expressions-- Maya Expression Editor From Basic to Professional

124 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsReproducing randomness

Example

Suppose you use the rand function to position several marbles at randomtranslateX positions in your scene at frame 1:

if (frame == 1){

marble1.tx = rand(-10,10);marble2.tx = rand(-10,10);marble3.tx = rand(-10,10);marble4.tx = rand(-10,10);

}

The rand(-10,10) returns a random number between -10 and 10 each time itexecutes. When you rewind the animation to frame 1, Maya might assignthese values to the translateX attributes of the marbles:

Attribute Value

marble1.tx 2.922

marble2.tx 5.963

marble3.tx -4.819

marble4.tx 7.186

Page 125: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 125

Beyond the BasicsReproducing randomness

Ex

pre

ss

ion

s

The next time you rewind the animation to frame 1, each marble’s translateXattribute receives a different random value. Maya might assign these values:

You might prefer the marbles’ translateX values to stay the same when yourewind, for instance, so you can composite the marbles correctly among afoggy backdrop.

You can use the seed function to keep the sequence of random valuesreturned by the rand function consistent when you rewind the animation.

if (frame == 1){

seed(10);marble1.tx = rand(-10,10);marble2.tx = rand(-10,10);marble3.tx = rand(-10,10);marble4.tx = rand(-10,10);

}

By setting the seed value to an arbitrary number, for instance, 10, thesubsequent executions of the rand function return a repeating sequence ofrandom numbers.

Attribute Value

marble1.tx -3.972

marble2.tx 9.108

marble3.tx -7.244

marble4.tx -3.065

Page 126: Expressions-- Maya Expression Editor From Basic to Professional

126 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsReproducing randomness

When you rewind the animation the first time, Maya might assign thesevalues to the translateX attributes of the marbles:

Each time you rewind the animation thereafter, Maya assigns these samevalues to the translateX attributes of the marbles. The marbles don’t move.

Each time a statement sets the seed value to 10, the subsequent executions ofthe rand function return numbers from the sequence starting at thebeginning number. In other words, resetting the seed value to 10 restarts therandom number generation process to the first value in the sequence.

Suppose you alter the expression to this:

if (frame == 1){

seed(10);}

marble1.tx = rand(-10,10);marble2.tx = rand(-10,10);marble3.tx = rand(-10,10);marble4.tx = rand(-10,10);

When you rewind the animation to frame 1, the expression sets the seed to10. Maya assigns values to the marbles’ translateX attributes as in theprevious expression.

Attribute Value

marble1.tx 8.020

marble2.tx -2.973

marble3.tx -7.709

marble4.tx 0.741

Page 127: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 127

Beyond the BasicsSpeeding expression execution

Ex

pre

ss

ion

s

Because the expression doesn’t set the seed value in frames other than frame1, playing the animation causes the rand function to return a new, yetrepeating, sequence of random numbers each frame. If you play theanimation several times, the translateX values will constantly change duringanimation, but the sequence of values will be identical each time you playthe animation.

You can assign the seed a different value to generate a different sequence ofreturned values. See “seed” on page 246 for details.

Speeding expression executionMaya does calculations internally in centimeters, radians, and seconds. Aradian is an angular unit commonly used in mathematics. It equals 180degrees divided by pi, or roughly 57.3 degrees.

When you assign a number to an attribute whose value is a measurementunit, the expression interprets the number, by default, as the appropriateunit selected in the Units folder of the General Preferences window. Bydefault, the Units folder selections are centimeters, degrees, and seconds.

If a measurement unit you’ve chosen in the Units folder differs from thecorresponding internal unit, Maya converts the number to the appropriateinternal unit to do the assignment.

Example

Suppose you’ve selected degrees from the Angular menu in the Unitsfolder. You then write this expression for an object named Ball:

Ball.rotateZ = 10;

Maya reads the 10 as being 10 degrees, then converts the value to theappropriate number of radians to make the assignment to Ball’s rotateZattribute. The conversion happens automatically. From your standpoint,Maya is simply rotating Ball 10 degrees.

In nonparticle expressions, these automatic conversions affect Mayaperformance. Because the expression executes slower, Maya slows when youplay, rewind, or otherwise change the animation time. Saving, opening, andother file operations on the scene containing the expression are also slower.

To boost Maya performance, you can turn off conversion to internal units. Ifyou do so, you must convert units in expression statements.

Page 128: Expressions-- Maya Expression Editor From Basic to Professional

128 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsSpeeding expression execution

To speed expression execution:

1 Display the Expression Editor.

2 Choose one of these Convert Units options:

None Converts no units. You must assign values to attributes ascentimeters, radians, or seconds, as appropriate. Execution isfastest with this option.

Angular Only Converts angular units, but no others. You must assignvalues to attributes as centimeters, seconds, and degrees, asappropriate. (This assumes you’re using the default degreesetting in the Units folder. If you’ve selected radians, youmust enter radians.)

If you’re confused by converting degrees to radians, selectthis option. Execution is fast with this option—unless theexpression has many angular values.

To return to default conversions:

1 Display the Expression Editor.

2 For the Convert Units option, choose All.

This lets you enter all measurement numbers in the same units specified inthe Units preference settings. Execution is slowest with this selection, butexpression writing is simplest.

You can set a different conversion option for each expression.

Example

Suppose, in the Units folder, you’ve set Linear units to millimeters andAngular units to degrees. You then write the following expression:

Ball.translateX = 5;Ball.rotateZ = 10;

All causes Maya to read 5 as millimeters and 10 as degrees.

None causes Maya to read 5 as centimeters and 10 as radians.

Angular causes Maya to read 5 as centimeters and 10 as degrees.

To convert units in an expression statement:

You must convert the units mathematically in a statement.

Page 129: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 129

Beyond the BasicsSpeeding expression execution

Ex

pre

ss

ion

s

Examples

Suppose, in the Units folder, you’ve set Linear units to millimeters andAngular units to degrees.

In the Expression Editor you set the Convert Units option to None and enterthis expression:

Ball.translateX = 5;Ball.rotateZ = 10;

None causes Maya to read 5 as centimeters and 10 as radians, which is notthe result you’re seeking.

To assign 5 millimeters to Ball’s translateX attribute, you must convert 5 tothe appropriate number of centimeters. To assign 10 degrees to Ball’s rotateZattribute, you must convert 10 to the appropriate number of radians.

The following statements do this:

Ball.translateX = 5.0 / 10.0;Ball.rotateZ = 10.0 / 57.3;

There are 10 millimeters per centimeter. In other words, a millimeter is acentimeter divided by 10. So 5 millimeters equals 5 centimeters divided by10. You therefore use the operation 5.0 / 10.0.

There are 57.3 degrees per radian. In other words, a degree is a radiandivided by 57.3. So 10 degrees equals 10 radians divided by 57.3. Youtherefore use the value 10.0 / 57.3.

If you need a more precise conversion to radians, divide a degree by57.29578 instead of 57.3. You can instead use the deg_to_rad function asfollows:

Ball.rotateZ = deg_to_rad(10.0);

The deg_to_rad function converts 10.0 degrees to a precise radianequivalent. See “deg_to_rad” on page 234 for details.

Important

When you divide floating point attributes or variables, enter the floatingpoint value 5.0 for an even number such as 5. This ensures that the divisionworks as expected. For more details, see the note in “Using mixed datatypes with arithmetic operators” on page 145.

Page 130: Expressions-- Maya Expression Editor From Basic to Professional

130 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsReducing redundant expression execution

Turning off unit conversion affects only expressions. It doesn’t affect otherMaya commands, options, or displays. For instance, the preceding exampleexpression assigns centimeters to translateX and radians to rotateZ. TheChannel Box still displays values for these attributes in millimeters anddegrees. It displays values in whatever units you choose in the Units folderof the General Preferences window.

Note that you can’t turn off unit conversion for particle shape nodeexpressions. Maya handles unit conversion differently for such expressionswith little impact on performance.

Reducing redundant expression executionIf your expression has redundant statement calculations, you can turn offAlways Evaluate to speed up scrubbing and playback of your animation. Tounderstand when this feature is useful, you must understand the subtledetails of expression execution.

An expression generally executes whenever the animation time changes. Anexpression also executes whenever an attribute that’s read by the expressionchanges value, and either of the following two actions occurs:

• Some other node in Maya uses the value of an attribute the expression writesto. For example, a deformer or shader uses its value.

• Maya needs the value of an attribute to which it writes in order to redrawthe workspace contents.

In this context, the predefined variables time and frame are also consideredattributes the expression reads.

Suppose you write an expression that moves a NURBS sphere along the Y-axis at twice the current value of its X-axis translation:

nurbsSphere1.translateY = 2 * nurbsSphere1.translateX;

If you use the Move tool in the workspace to drag the sphere in an X-axisdirection, Maya executes the expression for each incremental change to thetranslateX attribute as you drag.

Dragging the sphere in the X direction changes the value of the translateXattribute in the expression. As you drag the sphere and Maya updates theworkspace display, the value of the translateY attribute changes in theexpression. This makes the expression execute.

Page 131: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 131

Beyond the BasicsRemoving an attribute from an expression

Ex

pre

ss

ion

s

If you turn Always Evaluate off, an expression won’t execute if it containsonly print function statements, variable assignments, or assignments that donot read attribute values.

Example

global float $BallHeight = 5;print($BallHeight+"\n");nurbsSphere1.tx = rand(1);print(nurbsSphere1.tx+"\n");

The first statement declares and assigns a value to the variable $BallHeight,which is not an attribute. The next statement prints the $BallHeight butassigns no value to an attribute.

The next statement assigns an attribute a value, but the value is generated bythe random number function rand. This function doesn’t read an attributevalue. For details on the rand function, see “rand” on page 243.

The last statement reads and prints the value of an attribute, but doesn’tassign a value to an attribute.

None of these actions causes the expression to execute when AlwaysEvaluate is off.

Always Evaluate affects only the expression you’re creating or editing. Youcan turn it on for one expression and off for another.

For most animations, expressions execute regardless of whether AlwaysEvaluate is on. If in doubt, leave it on.

Removing an attribute from an expressionIf you do any of the following actions, an expression no longer sets or readsan attribute:

• Delete all occurrences of the attribute name in the expression.

• Convert to comments all statements that use the attribute name in theexpression.

• Delete the expression that contains the attribute.

Following these actions, the attribute keeps its value from the last time theexpression executed and set its value.

Page 132: Expressions-- Maya Expression Editor From Basic to Professional

132 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsDisconnecting an attribute

The attribute doesn’t return to the value it had before the expression set it.To return the attribute to its original value, use the Channel Box or AttributeEditor to set the attribute.

Disconnecting an attributeIf you disconnect an attribute from an expression, the expression no longerreads or set its value. You might want to disconnect an attribute, forexample, so you can keyframe the attribute rather than control it with anexpression.

These actions disconnect an attribute from an expression:

• Delete from the scene an object with an attribute that exists in theexpression.

• Use the Window→General Editors→Connection Editor to disconnect theattribute from the expression.

• Use the MEL disconnectAttr command.

• Use the MEL choice command.

Displaying disconnected attributes in expressionsThe Expression Editor displays a disconnected attribute with a symbolicplaceholder representing the attribute’s former existence in the expression.

Example

Suppose your scene has two objects, Ball and Cone, and you’ve written thisexpression:

Ball.translateX = Cone.translateX;Ball.translateY = Cone.translateY;Ball.translateZ = Cone.translateZ;

Tip

The MEL choice command lets you control an attribute alternately with twoor more techniques in different frames. For example, you can keyframe anattribute for frames 1-48, control it with an expression for frames 48-96, andcontrol it with a motion path for subsequent frames.

Page 133: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 133

Beyond the BasicsDisconnecting an attribute

Ex

pre

ss

ion

s

If you delete Cone from the scene, Cone.translateX, Cone.translateY, andCone.translateZ attributes no longer exist for the expression to read andassign to Ball’s translateX, translateY, and translateZ attributes.

If you display the expression again, it appears as follows:

Ball.translateX = .I[0];Ball.translateY = .I[1];Ball.translateZ = .I[2];

The .I[0], .I[1], and .I[2] characters indicate you’ve disconnected Cone’stranslate attributes from the expression. These symbols representplaceholders for the former use of the attributes in the expression.

The .I means the placeholder represents an input to the expression. An inputto an expression is an attribute with a value the expression reads forassignment to another attribute or variable. The number in brackets indicatesthe order in the expression the attribute was read.

For example, .I[0] indicates the input is the first attribute read in theexpression, .I[1] indicates the input is the second attribute read, and .I[2]indicates the input is the third attribute read.

A floating point or integer attribute placeholder has a value of 0. A particleshape node’s vector attribute placeholder has a value of <<0,0,0>>. In theexample, the placeholders .I[0], .I[1], and I[2] have the value 0. When theexpression executes, it assigns Ball.translateX, Ball.translateY, andBall.translateZ the value 0.

Note that if you disconnect an attribute from an expression but the attributestill exists in the scene, the attribute keeps its value from the last time theexpression executed and set its value.

Example

Suppose you’ve written these statements among others:

Ball.translateX = Cone.translateX;Ball.translateY = Cone.translateY;Ball.translateZ = Cone.translateZ;

If you delete Ball from the scene, Ball.translateX, Ball.translateY, andBall.translateZ attributes no longer exist. The expression can no longerassign Cone’s translateX, translateY, and translateZ values to thecorresponding Ball attributes.

Page 134: Expressions-- Maya Expression Editor From Basic to Professional

134 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsDisconnecting an attribute

Symbolic placeholders replace Ball attributes in the expression. If youdisplay the expression again, the statements appear as follows:

.O[0] = Cone.translateX;

.O[1] = Cone.translateY;

.O[2] = Cone.translateZ;

The .O[0] characters indicate you’ve disconnected the attributeBall.translateY from the expression. The .O indicates that the placeholderrepresents an output from the expression.

An output from an expression is an attribute assigned a value by theexpression. The number in brackets, for example, [0], indicates the order inwhich the attribute was assigned a value in the expression.

Because Ball.translateX was the first output from the expression, theexpression replaces it with .O[0]. The expression replaces Ball.translateY andBall.translateZ with .O[1] and .O[2] because they were the second and thirdoutputs from the expression.

When the expression executes, it continues to assign values to theplaceholder, though the placeholder has no effect on any object orcomponent of scene.

The expression assigns the placeholders .O[0], .O[1], and .O[2] the value ofCone.translateX, Cone.translateY, and Cone.translateZ, but theseplaceholders don’t control anything in the scene. The statements have noeffect.

Note

If an expression assigns values to the attributes of only one object, deletingthe object deletes the expression also. If your expression assigns values toattributes of several object attributes, deleting all those objects deletes theexpression.

To avoid deleting the expression in the preceding example, you wouldneed have some statement that sets an attribute of an object other than thedeleted Ball. For example, you might include this statement:

Cone.visibility = 1;

Page 135: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 135

Beyond the BasicsDisconnecting an attribute

Ex

pre

ss

ion

s

Connecting an attribute to a symbolic placeholderAfter you’ve disconnected an attribute from an expression, a symbolicplaceholder replaces it in the expression as described in the preceding topic.You can replace the placeholder with the attribute of your choice.

The most obvious way to do this is to type the desired attribute name inevery occurrence of the symbolic placeholder in the expression.

If you have a lengthy expression that has lots of symbolic placeholders, youcan use a single MEL connectAttr command to connect the new attribute toall occurrences of the same symbolic placeholder. You can also useWindow→General Editors→Connection Editor.

Example 1

Suppose you have these statements among others in an expression namedHorseController:

WhiteHorse.translateX = Car.translateX;BlackHorse.translateX = Car.translateX;BrownHorse.translateX = Car.translateX;

Deleting the Car and reloading the expression shows this:

WhiteHorse.translateX = .I[0];BlackHorse.translateX = .I[0];BrownHorse.translateX = .I[0];

.I[0] is the symbolic placeholder for what was the Car.translateX attribute.You can connect a different attribute to this placeholder to assign its contentsto the translateX attributes of WhiteHorse, BlackHorse, and BrownHorse.

Suppose you want to control these attributes with the translateX attribute ofan object named Cow. You can enter the following MEL command at theCommand Line:

connectAttr Cow.tx HorseController.input[0]

This command connects the attribute Cow.tx to the expression’s input[0].The expression is named HorseController. The input[0] is abbreviated as .I[0]in the expression. You can see the spelled-out input name input[0] in theGraph→Up and Downstream Connections display of the Hypergraph.

Reloading the expression shows the new attribute connection:

WhiteHorse.translateX = Cow.translateX;BlackHorse.translateX = Cow.translateX;BrownHorse.translateX = Cow.translateX;

Page 136: Expressions-- Maya Expression Editor From Basic to Professional

136 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsRenaming an object

Example 2

You can also reconnect an expression’s output with the connectAttrcommand. Suppose you have these statements among others in anexpression named HorseController:

WhiteHorse.translateX = Car.translateX;BlackHorse.translateX = Car.translateX;BrownHorse.translateX = Car.translateX;

Deleting the BrownHorse object and reloading the expression displays this:

WhiteHorse.translateX = Car.translateX;BlackHorse.translateX = Car.translateX;.O[2] = Car.translateX;

.O[2] is the symbolic placeholder for what was the BrownHorse.translateXattribute. It received the placeholder .O[2] because it’s the third output fromthe expression. (The first and second outputs from the expression are .O[0]and .O[1] .) You can connect a different object attribute to this placeholder tocontrol it with the value in Car.translateX, as shown in the third statement.

Suppose you want to control the attribute of a new object namedRedHorse.translateX with the Car.translateX value. You can enter thefollowing MEL command in the Command Line:

connectAttr HorseController.output[2] RedHorse.tx

This command connects the HorseController expression’s output[2] to theattribute RedHorse.tx. The output[2] is abbreviated .O[2] in the expression.

Reloading the expression shows the new attribute connection:

WhiteHorse.translateX = Cow.translateX;BlackHorse.translateX = Cow.translateX;RedHorse.translateX = Cow.translateX;

Renaming an objectIf you rename an object whose attributes were used in an expression, theExpression Editor continues to read or set the attributes. Maya doesn’tdisconnect the attribute from the expression. The Expression Editor convertsto the new name of the object the next time you click the Reload button inthe Expression Editor.

Page 137: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 137

Beyond the BasicsExecuting MEL commands in an expression

Ex

pre

ss

ion

s

Executing MEL commands in an expressionYou can execute MEL commands and procedures in an expression.However, if you make or break connections or add or delete nodes, yourscene might malfunction.

Rewinding your animation does not undo MEL command execution in anexpression. For instance, if your expression executes MEL commands tocreate a pair of spheres, rewinding doesn’t delete the spheres. Moreover,playing the scene again creates another pair of spheres.

Though you can usually undo executed MEL commands by selectingEdit→Undo repeatedly, this might not work if your scene is malfunctioning.

When you execute a command from the Command Line, status informationappears in the Script Editor and the Command Line’s response area. Thisinformation is not displayed when a command executes in an expression.

You can execute MEL commands in an expression with several techniques:

• MEL command alone in a statement

• MEL command within left-hand single quote marks

• MEL command used as an argument to an eval function

• MEL procedure call to a procedure in a MEL script

The following topics explain the techniques. See Using MEL for details onMEL.

Using a MEL command alone in a statementThe simplest way to use a MEL command in an expression is to type it in astatement exactly as you would in the Script Editor or in a MEL script.

Example

select -cl;

Note

When you reload an expression, the Expression Editor converts any shortattribute names to their long attribute name equivalents. For example, ifyou originally type the attribute name Ball.ty, reloading the expressionrenames it as Ball.translateY.

Page 138: Expressions-- Maya Expression Editor From Basic to Professional

138 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsExecuting MEL commands in an expression

This example shows the use of a MEL command alone. The statementexecutes exactly as it would in the Script Editor, except no command outputappears in the Script Editor.

Using a MEL command within single quote marksIf you enclose a command within left-hand single quote marks (‘ ), Mayareturns command output where the command is in the statement. You canassign this output to a variable to, for example, display it in the Script Editor.

Example

string $a[];$a = ‘ls -lights‘;print($a);

The first statement defines an array named $a. The second statementexecutes the MEL command within quotes, then assigns the command’soutput to array $a. The third statement displays the contents of $a to theScript Editor as follows:

ambientLightShape1directionalLightShape1

Using a MEL command with the eval functionUsing a MEL command with the eval function has an advantage over theprevious two techniques: you can build a command from a string.

Example

string $mycommand = "sphere";eval($mycommand+" -r 5");

The first statement assigns the string sphere to the variable $mycommand.The second statement appends -r 5 to sphere and executes the completecommand sphere -r 5. This creates a sphere with a radius of 5 grid units.

See “eval” on page 259 for more details.

Using a MEL procedure in an expressionYou can execute a MEL procedure in an expression by entering theprocedure name in a statement.

Page 139: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 139

Beyond the BasicsExecuting MEL commands in an expression

Ex

pre

ss

ion

s

To execute a MEL procedure:

1 Give the script the same filename as the procedure it contains, but with theextension .mel.

For example, if your procedure name is randspot( ), name your script filerandspot.mel.

2 Put the script file in your Maya scripts directory.

3 Declare the procedure as global in the script file as in this example:

global proc string randspot()

4 In an expression statement, use a statement that calls the procedure. You canuse the statement within left-hand single quote marks with an eval function,or alone as in this example:

randspot();

A complete example of calling a MEL procedure from an expression follow:

Example

Suppose, in your Maya scripts directory, you’ve created a MEL script filenamed randspot.mel with the following contents:

global proc string randspot(){string $mycommand;

if (rand(2) < 1)$mycommand = "particle -p "+ sphrand(10);

else$mycommand = "sphere -p "+ sphrand(10);

return $mycommand;}

Further suppose you’ve created this expression:

string $randcommand = randspot();eval($randcommand);

When you rewind or play a frame in the animation, the expression executes.The first expression statement executes the randspot procedure in therandspot.mel script file. In the randspot procedure, the rand(2) part of the if-else statement generates a random floating point value between 0 and 2,then compares its value to 1. For details on the rand function, see “rand” onpage 243.

Page 140: Expressions-- Maya Expression Editor From Basic to Professional

140 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsUnderstanding path names

If the rand(2) function returns a value less than 1, the if statement assigns aMEL command string such as particle -p -1.356 5.983 8.458 to $mycommand.The + sphrand(10) part of the statement appends to sphere -p the three floatingpoint components of a randomly generated vector.

Though sphrand(10) returns a vector, Maya converts the vector to a stringupon assigning it to the string $mycommand. For details on the sphrandfunction, see “sphrand” on page 244.

The converted string contains no double angle brackets or commas, but doescontain a space character between the floating point components. A spacebetween the floating point components is required syntax for the MELparticle command as used above.

If the rand(2) function returns a value greater than 1, $mycommand receivesa MEL command string such as sphere -p 4.926 -2.589 1.274.

The procedure finishes executing and passes the value of $mycommandback to the expression’s calling procedure randspot( ). This assigns thecommand string to the variable $randcommand.

The eval function executes the command string in $randcommand. Forexample, if the statement executes particle -p -1.356 5.983 8.458, it creates aparticle with coordinates <<1.356, 5.983, 8.458>>.

The expression executes each frame and creates a new particle or sphere at arandom location within a spherical radius of 10 units from the origin.

Understanding path namesIf two objects in a scene have different parents, they can have the same objectname. If you refer to an attribute of such an object in an expression, youmust use a more complete name that includes the object’s path name.

An object’s path name has this format:

pathname|objectname.attributename

where pathname is the parent node’s name, objectname is the object’s name,and attributename is the attribute’s name of the attribute.

A pipe symbol (|) symbol divides the pathname from the object name. Don’ttype spaces before or after the | symbol.

Page 141: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 141

Beyond the BasicsUnderstanding unexpected attribute values

Ex

pre

ss

ion

s

For example, a scene might have a child of GroupA named Ball.tx and adifferent child of GroupB named Ball.tx. If you write this statement:

Ball.tx = time;

Maya generates an error because it doesn’t know which Ball.tx to set.

To eliminate the error, you must enter the pathname of the attribute as inthis example:

GroupA|Ball.tx = time;

The | symbol between GroupA and Ball.tx indicates that the object to the leftof the symbol is the parent of the object to its right. Use no spaces before orafter the | symbol.

Understanding unexpected attribute valuesAs you work with expressions, you’ll sometimes see attribute values youdidn’t expect. The following topics describe a few common causes ofconfusion.

Values after rewindingWhen you rewind a scene, an expression executes with the last settingsmade for attribute values. This sometimes gives unexpected results.

Example

Ball.tx = $distance;$distance = time;

Assume for this example you’ve set the starting frame of the animation toframe 0.

The first statement sets Ball.tx to the variable $distance. The secondstatement sets $distance to the value of time.

Important

Always examine the Script Editor for error messages after you edit anexpression and click the Create button. If you alter a previously successfulexpression and a syntax error occurs, Maya executes the previoussuccessful expression when you play the animation. This might lead you tobelieve your editing changes took effect.

Page 142: Expressions-- Maya Expression Editor From Basic to Professional

142 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsUnderstanding unexpected attribute values

When you play the animation, Ball moves along the X-axis with the increasein time. Ball’s X-axis position is 4 grid units, for example, when animationtime equals 4 seconds.

When you rewind the animation, Ball’s position along the X-axis doesn’treturn to 0 as you might assume. The previous execution of the expression attime equals 4 set the $distance variable to 4. So rewinding sets Ball.tx to 4,then sets the value of $distance to 0, the value of time upon rewinding.

If you rewind again, Ball’s position along the X-axis returns to 0 as desired.Because the previous execution of the expression upon rewinding set the$distance to 0, the expression now correctly sets Ball.tx to 0.

To fix this problem, reverse the order of the statements and compile theexpression:

$distance = time;Ball.tx = $distance;

After you play and rewind the expression, the first statement executes andassigns the time to $distance. The next statement assigns Ball.tx the value of$distance, which the first statement set to the value of time. Because$distance is set to 0 as the first statement after rewinding, Ball returns to thedesired translateX position.

Increment operationsIf you increment an attribute or variable during animation, you might beconfused by its behavior.

Example

Ball.ty = 0;Ball.ty = Ball.ty + 1;

Ball’s translateY position stays at 1 unit along the Y-axis. Ball’s translateYposition doesn’t increase by 1 each frame as the animation plays.

Example

Ball.ty = Ball.ty + 1;

Ball’s translateY position increases by 1 each frame as you play theanimation. When you rewind the animation, translateY increases by 1 again.

Page 143: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 143

Beyond the BasicsUnderstanding unexpected attribute values

Ex

pre

ss

ion

s

When you play the animation again, the translateY position increases by 1each frame. If you rewind the animation or drag the current time indicator,the translateY position continues to move up the Y-axis. The attribute neverreturns to its original position.

To return Ball to a starting position each time you rewind, you mustinitialize the attribute to a starting value. For example, you could use thefollowing expression:

Ball.ty = Ball.ty + 1;if (frame == 1)

Ball.translateY = 0;

This returns Ball to a Y position of 0 when you rewind to frame 1. When youdrag the current time indicator, though, Ball doesn’t return to its Y positionof 0.

The if statement resets the value of translateY to 0 only when frame 1 plays.Frame 1 is the default frame that plays when you rewind an animation. Youwould need to use a different frame number in the if statement if you’ve setyour animation to start at a different frame.

Data type conversionsMaya is flexible in its handling of data types. If you do assignment orarithmetic operations between two different data types, Maya converts datatype as necessary and doesn’t report a syntax error.

The following topics describe the conversions that occur in such instances.Understanding these details might help you troubleshoot unexpectedattribute and variable values.

Unless you have programming experience, don’t intentionally convert datatypes. You might be confused by unexpected attribute and variable values.

Assigning to a floating point attribute or variableIf you assign a vector to a floating point attribute or variable, Maya convertsthe vector to a floating point value according to this equation:

The x, y, and z numbers in the formula represent the three components inthe vector. The resulting value is the magnitude of the vector.

x2

y2

z2

+ +

Page 144: Expressions-- Maya Expression Editor From Basic to Professional

144 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsUnderstanding unexpected attribute values

Example

Ball.scaleY = <<1,2,0>>;

Maya assigns the floating point scaleY attribute the converted vector:

If you assign an integer to a floating point attribute or variable, Maya makesno conversion. None is necessary.

Example

Ball.scaleY = 1;

Maya assigns the value 1 to Ball.scaleY.

Assigning to an integer attribute or variableIf you assign a floating point value to an integer attribute or variable, Mayadeletes the decimal part of the number.

If you assign a vector to an integer attribute or variable, Maya converts thevector to an integer using the square root equation in the previous topic.However, it deletes the decimal component of the result.

Example

int $pi = 3.14;

Maya assigns the integer variable $pi the value 3.

int $temp = <<1,2,0>>;

Maya assigns the integer variable $temp this vector value:

It deletes the decimal component .2360607. The $temp variable receives thetruncated value 2.

12

22

02

+ + 5 2.236= =

12

22

02

+ + 5 2.236 2≈= =

Page 145: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 145

Beyond the BasicsUnderstanding unexpected attribute values

Ex

pre

ss

ion

s

Assigning to a vector attribute or variableIf you assign an integer or floating point value to a vector attribute orvariable, Maya puts the integer or floating point value into each componentof the vector.

Example

vector $speed = 1.34;

Because $speed is a vector, Maya assigns it <<1.34,1.34,1.34>>.

Using mixed data types with arithmetic operatorsThe following table lists how Maya converts data types when you usearithmetic operators between different types in an expression.

Example

Suppose you multiply a vector variable named $velocity by a floating pointnumber 0.5 as follows:

$race = $velocity * 0.5;

If $velocity is <<2,3,0>> when the preceding expression executes, the $racevariable is assigned the resulting vector value <<1,1.5,0>>.

Operation Resulting data type

integer operator float float

integer operator vector vector

vector operator float vector

Page 146: Expressions-- Maya Expression Editor From Basic to Professional

146 Using Maya: Hypergraph, Sets & Expressions

Beyond the BasicsUnderstanding unexpected attribute values

Important

When Maya does arithmetic operations on literal constants and variableswithout a declared data type, it guesses the data type based on the valuespresent.

In the statement Ball.scaleY = 1/3;, for example, Maya treats 1 and 3 asintegers because they have no decimal points. The expression dividesinteger 1 by integer 3. The integer result is 0 with a remainder of 1. Mayadiscards the remainder.

Because Ball.scaleY is a floating point attribute, Maya converts the integer 0result to floating point 0 (which is the same value), then assigns it toBall.scaleY.

To get the intended result of 1/3, you must type Ball.scaleY = 1.0/3.0;

Maya treats 1.0 and 3.0 as floating point numbers because they havedecimal points. The number 1.0 divided by 3.0 results in 0.33333333333.

Page 147: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 147

Ex

pre

ss

ion

s

8 Particle Expressions

Particle expressions are more complex than other types of expressions. Forexample, you can write an expression to control all particles in an object thesame way, or you can control each particle differently.

Execution of expressions differs for particles than for other types of objects.To become proficient with particle expressions takes more study than forother expressions, but the resulting effects are worth the effort. This chapterguides you through the intricacies of working with particle expressions.

This chapter has the following topics:

• “Understanding particle expressions” on page 148

• “Understanding creation expression execution” on page 149

• “Writing creation expressions” on page 150

• “Understanding runtime expression execution” on page 152

• “Writing runtime expressions” on page 153

• “Working with particle attributes” on page 159

• “Assigning to vectors and vector arrays” on page 193

• “List of particle shape attributes” on page 196

Claude Macri

An expression moves a particleemitter in a corkscrew patternand changes the color of trailingemitted particles as they age.The particles are displayed asSpheres render type.

Page 148: Expressions-- Maya Expression Editor From Basic to Professional

148 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsUnderstanding particle expressions

Understanding particle expressionsIf you select a particle shape node, the Creation and Runtime buttons in theExpression Editor are no longer dim and you can select them.

These buttons let you write two types of expressions: creation and runtime.You can use both types for any attribute of a particle shape node.

Though the details of execution are subtle, a creation expression generallyexecutes when you rewind an animation or when a particle is emitted. Aruntime expression typically executes for each frame other than the rewindframe or the frame in which a particle is emitted. By default, either type ofexpression executes once for each particle in the object.

Creation and runtime expressions don’t execute at the same time. The age ofeach particle in the object determines whether a runtime expression orcreation expression executes. Execution details are in “Understandingcreation expression execution” on page 149 and “Understanding runtimeexpression execution” on page 152.

The Default Object, Always Evaluate, and Convert Units options becomedim when you select a particle shape node, and you can’t use them.

Default Object is dim because a particle shape node’s attributes can becontrolled by only one creation expression and one runtime expression. Theparticle shape node is always the default object when it’s the selected object.

Always Evaluate is dim for particle shape node expressions because it hasno effect on particle shape node expressions. See “How often an expressionexecutes” in Chapter 7 for details on the checkbox.

Buttons lit for particle shapes

Page 149: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 149

Particle ExpressionsUnderstanding creation expression execution

Ex

pre

ss

ion

s

Convert Units is not selectable because you can’t alter how Maya handlesunit conversions for particle shape node expressions. See “Speedingexpression execution” on page 127 for details on how Maya converts unitsfor other types of expressions.

Understanding creation expression executionFor a particle you create with the Particle Tool, a creation expressionexecutes when you rewind the animation. For an emitted particle, a creationexpression executes in the frame where the particle is emitted. However,there are exceptions to these rules as described in the following topics.

Note that rewinding an animation two or more times in succession withoutplaying the animation doesn’t execute a creation expression. Because noattribute value changes when you rewind several times in succession, theexpression doesn’t execute.

You might also notice that all expressions in your scene are compiled andexecuted each time you open the scene. This occurs for architectural reasonsand is unimportant to your work with expressions.

Setting the dynamics start frameA creation expression executes once for each particle whose age is 0 whenMaya evaluates dynamics. Maya evaluates dynamics whenever theanimation time changes and it’s greater than or equal to the dynamics StartFrame setting—frame 1 by default.

The Start Frame specifies when dynamic calculations begin for youranimation. This option is available through Settings→Dynamics Controller,in the Extra Attributes section of the Attribute Editor.

The animation time changes when you rewind, play, or otherwise changethe current frame displayed.

An emitted particle’s age is 0 in the frame where it’s emitted.

Important

You can’t write a different expression for each particle shape attribute asyou can for other types of objects. Because you can write only one creationexpression per particle shape, you don’t need to select an attribute from theExpression Editor’s Attributes list.

Page 150: Expressions-- Maya Expression Editor From Basic to Professional

150 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWriting creation expressions

Particles created with the Particle Tool have an age of 0 on and before theStart Frame. With the default animation frame range and Start Frame,rewinding an animation to frame 1 returns such particles to age 0.

If you set the Time Slider’s start frame higher than the dynamics StartFrame, be aware that rewinding the animation might cause the age ofparticles to be greater than 0. If this occurs, the creation rule for the particleswon’t execute.

Setting attributes for initial state usageIf, at some frame, you’ve saved a particle shape’s attributes for its initialstate, rewinding an animation does not return the age of the particles to 0.

Suppose you’ve created a particle grid having an opacity attribute that fadesgradually as the animation plays. You stop the animation at some framewhere you decide the grid’s opacity looks good as a starting point for theanimation. You then choose Settings→Initial State→Set For Current tocause the current value of the object’s attributes—including age—to becomethe initial state values.

If you rewind the animation, the age of the particles in the grid is equal toage at the time you chose Set For Current. The age of the particles thereforeis not equal to 0 when you rewind the scene.

See “Understanding initial state attributes” on page 162 for more details oninitial state attributes.

Writing creation expressionsA creation expression is useful for attributes that don’t need to changeduring animation. For example, you might want all particles in an object tohave a single velocity for the duration of an animation.

Tip

You can set options in the Attribute Editor to display the age of an object’sparticles in the workspace. Set the particle shape’s Render Type toNumeric, click Add Attributes For Current Render Type, and enter age inthe Attribute Name box. The age appears next to each particle.

You can also examine the age of an object’s particles by enteringprint(age+“\n”) in a particle expression. See “print” on page 261.

Page 151: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 151

Particle ExpressionsWriting creation expressions

Ex

pre

ss

ion

s

A creation expression is also useful for initializing an attribute’s value for thefirst frame before a runtime expression takes control of the attribute value insubsequent frames. See “Writing runtime expressions” on page 153 for anexample of the interaction between a runtime and creation expression.

Example

Suppose you’ve used the Particle Tool to place a collection of particles in theworkspace. You then create the following creation expression to control theirvelocity:

particleShape1.velocity = <<0,1,0>>;

All the particles move in a Y-axis direction at one grid unit per second as theanimation plays.

Important

To use an expression to control particle attributes, make sure the selectedobject in the Expression Editor is a particle shape node, not the transformnode of the particle object.

If a particle object’s transform node is selected rather than the particleshape node, move the mouse pointer to the workspace and press yourkeyboard’s down arrow. This selects the particle shape node.

Page 152: Expressions-- Maya Expression Editor From Basic to Professional

152 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsUnderstanding runtime expression execution

Understanding runtime expression executionFor a particle you’ve created with the Particle Tool, a runtime expressiontypically executes in each frame after the frame that appears uponrewinding.

For an emitted particle, a runtime expression typically executes in eachframe after the first one where the particle was emitted. More specifically, aruntime expression executes once for each particle whose age is greater than0, each time Maya evaluates dynamics.

Maya evaluates dynamics whenever the Time Slider time changes and thetime is greater than or equal to the dynamics Start Frame. To set thedynamics Start Frame, select Settings→Dynamics Controller from theDynamics menu bar. Time changes when you rewind, play, or otherwisechange the current frame displayed.

A runtime expression executes once per oversample level per frame as youplay or otherwise change the animation time. For example, if the oversamplelevel is 4, Maya executes a particle shape expression four times per frame foreach particle in the object.

Use Settings→Dynamics Controller from the Dynamics menu to set theOversample Level. Maya’s default setting is 1.

In addition to executing when animation time changes, a runtime expressionexecutes when the value of an attribute it reads changes, and when either ofthese actions occurs for an attribute the expression writes to:

• Some other node in Maya uses its value.

• Maya needs the value to redraw the workspace contents.

In this context, the predefined variables time and frame are also consideredattributes the expression reads.

Important

There are no creation expressions for nodes other than particle shapenodes. Such objects have only one type of expression. (It’s similar to aruntime expression.)

For a particle shape node, you can write only one runtime expression forall its attributes. You don’t need to select an attribute from the Attributeslist. You can create only one runtime expression per particle shape.

Page 153: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 153

Particle ExpressionsWriting runtime expressions

Ex

pre

ss

ion

s

Writing runtime expressionsA runtime expression controls an attribute as an animation plays. Mayaupdates any attribute that’s assigned a value in a runtime expression eachtime the expression executes. This typically occurs once per frame.

If an attribute is not set by a runtime expression, the attribute uses thecreation expression value for subsequent frames of the animation.

Example

Suppose you’ve created a grid of particles, then create this runtimeexpression for its velocity attribute:

particleShape1.velocity = <<0,1,0>>;

The expression moves the grid of particles up at 1 grid unit per second as theanimation plays.

Constant upward velocity

Page 154: Expressions-- Maya Expression Editor From Basic to Professional

154 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWriting runtime expressions

With the default frame rate of 24 frames/second, the particles move 1/24 ofa grid unit each frame. With the default oversampling level of 1, the runtimeexpression executes once per frame. Maya calculates the runtime expressiononce for each particle of an object.

Because the expression sets the velocity to <<0,1,0>> each frame, theexpression executes redundantly. This expression would therefore be moreappropriate for a creation expression. However, either type of expression hasthe same effect in this example.

Example

Suppose you’ve created a grid of particles, and your animation’s startingframe number is 0. You create this runtime expression for its velocityattribute:

particleShape1.velocity = <<0,time,0>>;

The expression increases the Y component of velocity with the increasingvalue of time as the animation plays. This makes all particles in the grid risewith increasing velocity as the time increases. An increasing velocity is thesame as acceleration.

Note

To make the illustrations of particles easier to see in this and otherchapters, we show them as small, shaded spheres rather than points.

To display particles as spheres:

1 Select the particle shape node.

2 In the Attribute Editor’s Render Attributes section, choose Spheres forthe Render Type.

3 Click the Current Render Type button next to Add Attributes For.

A Radius slider appears below the button.

4 Adjust the Radius to set the size of the spheres.

5 Turn on Shading→Smooth Shade All (at the upper left of theworkspace).

Page 155: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 155

Particle ExpressionsWriting runtime expressions

Ex

pre

ss

ion

s

You need to use the statement in a runtime expression rather than a creationexpression, because you’re increasing a value in the assignment each frame.

Using the statement in a creation expression would instead set the velocityto a constant value <<0,0,0>>, because time equals 0 when the creationexpression executes for the particle grid.

Example

The previous examples gave all particles the same value for the velocityattribute. You can instead give each particle a different value for an attribute.

Suppose you’ve created a grid of 121 particles.

Suppose further you create this runtime expression for its accelerationattribute:

particleShape1.acceleration = sphrand(2);

Increasing upward velocity

Page 156: Expressions-- Maya Expression Editor From Basic to Professional

156 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWriting runtime expressions

The expression executes once for each of the 121 particles each time theruntime expression executes.

The sphrand(2) function provides a vector whose randomly selectedcomponents reside within an imaginary sphere centered at the origin andwith a radius of 2. Each particle receives a different vector value. For detailson the sphrand function, see “sphrand” in Chapter 9.

Because each particle receives a different random vector for its accelerationeach frame, the particles accelerate individually in a constantly changingdirection and rate as the scene plays. This gives the acceleration abruptchanges in direction.

Important

To give particles a constant acceleration, assign the acceleration attribute aconstant value in a runtime expression rather than in a creation expression.

Maya simulates the physics of acceleration. It initializes acceleration to<<0,0,0>> before each frame, or if the oversample level is greater than 1,before each timestep.

If the oversample level is 2, there are 2 timesteps per frame. If theoversample level is 3, there are 3 timesteps per frame, and so on.

Page 157: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 157

Particle ExpressionsWriting runtime expressions

Ex

pre

ss

ion

s

Example

Suppose you’ve set your animation’s starting frame to 0, and you’ve usedthe Particle Tool to place a single particle at the origin:

You then create a runtime expression to control its position:

particleShape1.position = <<3,time,0>>;

When you play the animation, the runtime expression takes control of theattribute. In the first frame that plays, the particle jumps to <<3, time, 0>>.At the default frame rate of 24 frames/second, the position is <<3, 0.0417,0>>, because the value of time is 0.0417.

Page 158: Expressions-- Maya Expression Editor From Basic to Professional

158 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWriting runtime expressions

Each subsequent frame moves the particle upward at a rate set by theincrementing value of time.

When you stop and rewind the animation, the particle moves back to theorigin, the particle’s original position when you created it with the ParticleTool. When you created the particle, Maya stored its original position in aninternally maintained initial state attribute named position0. For details, see“Understanding initial state attributes” on page 162.

Because the attribute has no creation expression controlling its value, Mayasets the attribute to its initial state position0 value of <<0,0,0>>.

To prevent the particle from jumping back to the origin after rewinding, youcan write a creation expression that’s the same as the runtime expression:

particleShape1.position = <<3,time,0>>;

When you rewind the animation, the particle moves to position<<3,time,0>>. Because time is 0 at frame 0, the particle starts at position<<3,0,0>> when you rewind the animation. In the second and followingframes, it moves upward synchronized with the increasing value of time.

Though this example showed how to initialize the position attribute with acreation expression, you could have gotten almost the same result by savingthe object’s current attribute values for initial state usage:

To save the current attributes for initial state usage:

1 Select the particle shape node.

2 Advance the animation to frame 1.

Here the position of the particle is <<3, 0.0417, 0>>.

3 Select Settings→Initial State→Set for Current.

Page 159: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 159

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

When you rewind the animation, Maya positions the object at the initial statesetting of its position attribute. This setting is <<3, 0.0417, 0>> because youselected Set for Current while the position was equal to <<3, 0.0417, 0>>.

Working with particle attributesWhen you create a particle object, it has two types of static attributes:

• attributes for its transform node

• attributes for its particle shape node

These attribute are permanently part of a particle object. You typically won’twork with the static attributes that are part of its transform node, forexample, scaleX, translateX, and so on. These attributes control the positionand orientation of the transform node of the entire particle object, not theposition and orientation of the individual particles.

You’ll instead work with the static attributes of the particle shape node, forexample, position, velocity, acceleration, and age. These attributes appear inthe Attributes list of the Expression Editor’s when you chooseObject Filter→Dynamics→Particles for the selected particle object.

Adding dynamic attributesYou also use expressions to control dynamic and custom attributes you addto a particle shape node. See “Attributes” in Chapter 5 for details on thedifferences between static, dynamic, and custom attributes. See “Assigningto a custom attribute” on page 169 for details on working with customattributes.

When you add a dynamic attribute to an object, the attribute names appearin the Expression Editor’s Attributes list.

Note

See “List of particle shape attributes” on page 196 for attributes you canuse with particle objects.

Page 160: Expressions-- Maya Expression Editor From Basic to Professional

160 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

Understanding per particle and per object attributesYou can dynamically add two types of attributes to a particle shape node:

• per particle

• per object

A per particle attribute lets you set the value of the attribute individually foreach particle of the object. A per object attribute lets you set the attributevalue for all particles of the object collectively with a single value.

For example, a per particle opacityPP attribute lets you set a unique opacityvalue for each particle of an object. With a per object opacity attribute, youmust give all particles of the object the same opacity.

A per particle attribute holds the attribute values for each particle in theobject. For example, though there is only one opacityPP attribute in aparticle object, the attribute holds the value for each particle’s opacity value.The attribute holds the values in an array. In simple terms, an array is a list.

Though per particle attributes are best for creating complex effects, you can’tkeyframe them. You can keyframe per object attributes.

You can add per particle or per object attributes for opacity, color, lifespan,and other effects.

For a particle shape node attribute, you can tell whether it’s a per particle orper object attribute by examining the Attribute Editor’s particle shape folder.All per particle attributes appear in the Per Particle (Array) Attributessection of the folder.

The per object attributes appear elsewhere in the folder. Most appear abovethe Per Particle (Array) Attributes section, for example, in the ParticleAttributes and Render Attributes sections.

For many dynamically added attributes, you can also tell whether they areper particle or per object by their names in the Expression Editor. If a nameends with PP, it’s per particle. Otherwise, it’s usually per object.

Note that position, velocity, and acceleration are per particle attributes,though their names don’t end with PP.

Page 161: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 161

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

The most common way to create dynamic per object or per particle attributesfor a particle shape is by clicking one of the following buttons in the AddDynamic Attributes section of the Attribute Editor:

For example, if you click the Opacity button, a window appears and lets youchoose whether to add the opacity characteristic as a per object attribute or aper particle attribute.

If you choose per particle, the Attributes list of the Expression Editordisplays a new attribute for the selected particle shape node: opacityPP. Ifyou choose per object, an opacity attribute is displayed instead.

For attributes other than lifespan, if you add both a per particle attribute anda per object attribute for a characteristic, the per particle attribute takesprecedence. For instance, if you add opacity and opacityPP, the opacityPPattribute controls the opacity of the particles of the specified object.

When you click Lifespan and add both a per particle and per objectattribute, Maya adds an additional attribute named useLifspanPP that letsyou choose whether lifespanPP or lifespan controls the characteristic.

By default, the Attribute Editor setting of useLifespanPP is on, so thelifespanPP attribute control the characteristic. If you turn useLifespanPP offin the Attribute Editor, lifespan controls the characteristic.

If you click the Goal button in the Add Dynamic Attributes section of theAttribute Editor, Maya adds a per object attribute and a per particleattribute. The attributes are named goal and goalPP. Neither attribute hasprecedence. Maya multiplies the value of the per object goal attribute by theper particle goalPP attribute to create the final goal effect for each particle.

Page 162: Expressions-- Maya Expression Editor From Basic to Professional

162 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

Understanding initial state attributesFor all static per particle attributes, Maya keeps a corresponding attributewith a name ending in 0. For example, the static attributes position, velocity,and acceleration have counterparts position0, velocity0, and acceleration0.

An attribute name that ends in 0 holds the initial state value of the attribute.When you save a particle object’s current attribute values for initial stateusage, Maya assigns those values to the initial state attributes.

To save a particle object’s attribute values for initial state usage, use either ofthese commands:

• Settings→Initial State→Set for Current

This saves all per particle attribute values for the selected particle shapenode or rigid body.

• Settings→Initial State→Set for All Dynamic

This saves all per particle attribute values for all dynamic objects in thescene—in other words, all particle shape nodes and rigid bodies.

When you dynamically add a per particle attribute by clicking one of thebuttons in the Add Dynamic Attributes section of the Attribute Editor, Mayaalso adds a corresponding initial state attribute with name ending in 0. Forexample, when you click the Lifespan button in the Attribute Editor, Mayaadds lifespanPP0.

Though an initial state attribute doesn’t appear in the Expression Editor, youcan read its value to retrieve the initial state.

Important

You can use per particle attributes only in particle expressions. You can useper object attributes in particle or nonparticle expressions.

If you use a runtime expression to read or write a per object attribute of aparticle object with many particles, you can speed up expression executionby reading or writing the attribute in a nonparticle expression.

Nonparticle expressions execute only once per object. Particle expressionsexecute once for each particle in the object. Because reading or writing aper object attribute more than once per frame is redundant, you can saveprocessing time by working with them in nonparticle expressions.

Page 163: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 163

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

When you use the Add Attribute window to add a custom per particle(array) attribute to a particle shape, you must choose whether you want toadd it with Add Initial State Attribute on or off. If you choose on, Mayacreates a corresponding initial state attribute for the added attribute.

If you choose off, Maya doesn’t create a corresponding initial state attributefor the added attribute. Without this corresponding attribute, you can’t savea particle object’s current attribute values for initial state usage. You mustwrite a creation expression if you decide to initialize the custom attribute’svalue upon rewinding the animation.

You can see whether a custom attribute was added with Add Initial StateAttribute on or off by using the MEL listAttributes command. (See the onlineMEL documentation for details.)

You might want to read the value of an initial state attribute in anexpression, for instance, to use its original (rewind) value for somecalculation. If you assign a value to an initial state attribute. Maya willoverwrite the value if you save the attribute value for initial state usage.

When you add a custom attribute to a particle shape, do not end the namewith a 0 character. You’ll subvert Maya’s naming scheme for the initial stateattribute associated with an attribute.

For any attribute, if you don’t initialize its value with a creation expressionor save its value for initial state usage, Maya gives the attribute a defaultvalue at the animation’s first frame. It typically assigns the attribute thevalue 0 or <<0,0,0>>, as appropriate for the data type. In other cases, forinstance, opacityPP and opacity, Maya assigns the attribute a default valueof 1.

If you know you’re going to write a creation expression for a customattribute, you can set Add Initial State Attribute off when you add theattribute. Otherwise, set Add Initial State Attribute on whenever you add acustom attribute.

When a creation expression assigns a value to an attribute, the valueoverrides the attribute’s initial state value for all particles whose age is 0.

Note

A per particle attribute is called an array attribute in the Add Attributewindow. The two terms have the same meaning. See “Assigning to acustom attribute” on page 169 for details.

Page 164: Expressions-- Maya Expression Editor From Basic to Professional

164 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

Example of assigning to a dynamic per particle attributeSuppose you’ve used the Particle tool to create a small number of particlesnamed Bubbles:

The following steps show how to assign a different lifespanPP value for eachof the particles to make them disappear as the scene plays.

To use a per particle lifespanPP attribute:

1 Select the particle shape node for Bubbles in the Outliner or Hypergraph.

2 In the Add Dynamic Attributes section of the Attribute Editor, click theLifespan button.

A window appears that prompts you to choose whether to add the attributeper object or per particle.

3 Select Add Per Particle Attribute, then click the Add Attribute button.

This adds a lifespanPP attribute to the particle shape node for Bubbles. Youcan set this attribute to give each particle a different value for how long itlives.

4 Select Bubble’s particle shape node in the Expression Editor.

5 Turn on Creation in the Expression Editor.

6 Create the following expression:

BubblesShape1.lifespanPP = rand(5);print("Hello\n");

7 Play the animation.

Page 165: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 165

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

Because lifespanPP is a per particle attribute and the object’s particle shapenode is selected in the Expression Editor, the expression does an executionloop of both statements once for each particle in the object.

Because the expression is a creation expression, it executes after theexpression compiles. It also executes when you rewind the animation afterplaying it.

For each of the particles, the first statement assigns the lifespanPP attribute arandom floating point number between 0 and 5. The rand function returns adifferent random number each time it executes, so each particle has adifferent lifespanPP value between 0 and 5. For details on the rand function,see chapter 9, “Functions.”

The second statement displays Hello in the Script Editor, once for eachparticle.

The creation expression gives each particle a random lifespanPP of less than5 seconds. The particles disappear from the scene at random times between 0and 5 seconds of scene play. (Maya gives particles created with the Particletool an age of 0 in the first frame of the animation.)

When you rewind the animation, the particles reappear in the scene. Playingthe scene again makes them disappear at random times within 5 seconds.

Particles remaining afterthree seconds, with creationexpression for lifespanPP.

Page 166: Expressions-- Maya Expression Editor From Basic to Professional

166 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

It’s important that you use a creation expression for this effect. If you wereto use a runtime expression, the particles would disappear more quickly asthe animation plays, and Hello would appear 100 times each frame. Thereason for this is subtle:

In each frame, a runtime expression would assign a different random valuebetween 0 and 5 seconds to the lifespanPP of each particle. The expressionwould likely assign one or more of the particles a lifespanPP near 0.Meanwhile, the age of each particle increases from 0 at the first frame ofplay.

Maya checks the age of each particle every frame. If the age is greater thanthe lifespanPP value, Maya removes the particle.

Because the expression would reassign new random lifespanPP values toeach remaining particle in each frame, the new assignments would likelygive a few particles a lifespanPP that’s less than their current age value.Maya deletes such particles. This causes the object’s particles to disappearquickly from the scene.

Particles remaining afterone second, withruntime expression forlifespanPP.

Page 167: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 167

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

Example of assigning to a dynamic per object attributeSuppose you’ve used the Particle tool to create the same Bubbles particleobject described in the previous topic.

The following steps show how to give the particles a single lifespan. Allparticles disappear at the same time when you play the scene.

To use a per object lifespan attribute:

1 Select the particle shape node for Bubbles in the Outliner or Hypergraph.

2 In the Add Dynamic Attributes section of the Attribute Editor, click theLifespan button.

A window appears that prompts you to choose whether to add the attributeper object or per particle.

3 Select Add Per Object Attribute, then click the Add Attribute button.

This adds the lifespan attribute to the particle shape node for Bubbles.

4 In the Expression Editor, turn on Creation.

5 Create this creation expression:

BubblesShape1.lifespan = 1.33;print("Hello\n");

Because this is a creation expression, it executes after the expressioncompiles. It also executes when you rewind the animation after playing it.

Page 168: Expressions-- Maya Expression Editor From Basic to Professional

168 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

For each of the 100 particles, the first statement assigns the lifespan attributethe value 1.33. The second statement displays Hello in the Script Editor oncefor each particle.

6 Play the animation.

Because all particles have a lifespan of 1.33, they disappear from the sceneafter 1.33 seconds of animation play.

When you rewind the animation, the particles reappear in the scene. Playingthe scene again makes them disappear again after 1.33 seconds.

If you had put the preceding statements in a runtime expression, theparticles would still disappear in 1.33 seconds. The expression would assigna lifespan of 1.33 seconds to all 100 particles redundantly each frame.

The age of the particles is 0 in the first frame of their creation. (Maya givesparticles created with the Particle tool an age of 0 in the first frame of theanimation.)

Reassigning lifespan 1.33 each frame has no effect on the age of the particles.Their age increases from the first frame regardless of the lifespan value.

Note that, unlike particles created with the Particle Tool, the age of emittedparticles starts in the frame where they’re emitted.

1.32 seconds of animation 1.33 seconds of animation

Page 169: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 169

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

Assigning to a custom attributeYou can add a custom attribute to a particle shape node and control its valuein an expression.

To add a custom attribute:

1 Select the object’s particle shape node rather than its transform node.

Use the Hypergraph or Outliner to select the shape node.

2 Choose Modify→Add Attribute.

or

In the Add Dynamic Attributes section of the Attribute Editor, click theGeneral button.

The Add Attribute window appears:

3 Enter a name for the attribute in the Attribute Name box.

Page 170: Expressions-- Maya Expression Editor From Basic to Professional

170 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

4 Make sure Make attribute keyable is on.

5 Select one of the following data types:

Vector Creates a vector attribute consisting of three floating pointvalues.

Float Creates a floating point attribute.

Integer Creates an integer attribute.

Boolean Creates an attribute consisting of an on/off toggle.

6 Select one of the following attribute types:

Scalar Creates a per object attribute that you can set to a singlevalue that applies to every particle in the object. A vectorscalar is considered a single value with three numbers.

Array Creates a per particle attribute. You can set this type ofattribute to different values for each particle.

• If you select Scalar, you can specify Minimum, Maximum, and Defaultvalues for a Float or Integer attribute.

Minimum and Maximum set the lowest and highest values you can enterfor the attribute in the Attribute Editor or Channel Box. Default sets thedefault value displayed for the attribute. Because you’re going to control theattribute’s value with an expression, you might want to skip entering valuesfor these options.

An expression isn’t bound by the Minimum and Maximum values. Theattribute receives whatever value you assign it in the expression. Theexpression can read the attribute’s Default value or any other value you giveit in the Attribute Editor or Channel Box.

When you select Scalar, you can’t create a counterpart initial state attributeby turning on Add Initial State Attribute.

• If you select Array, you can also create a counterpart initial state attribute byturning on Add Initial State Attribute. See “Understanding initial stateattributes” on page 162 for details.

You can’t set Minimum, Maximum, or Default values for an Arrayattribute.

7 Click Add if you want to add more attributes. Click OK to add the attributeand close the Add Attribute window.

Page 171: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 171

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

The new attribute appears under the Dynamic Attributes section of theAttribute Editor.

To assign values to a custom attribute:

You can assign values to a custom attribute with the same techniques youuse to assign values to static or dynamic attributes.

Example

Suppose you’ve created a 100-particle object named sunspot, and you add toits particle shape node a vector per object attribute named glow. You assignthe glow attribute a vector value in a creation expression as follows:

sunspotShape1.glow = <<3,0,0>>;print(sunspotShape1.glow + "\n");

When you rewind the animation, the glow attribute of sunspotShape1receives the value <<3,0,0>>. The print statement displays the values in theScript Editor.

Example

Suppose you add a vector per particle attribute named heat to the 100-particle sunspot shape node. You can give each particle a different value asin this creation expression:

float $randomNumber = rand(1);sunspotShape1.heat = <<$randomNumber,0,0>>;print(sunspotShape1.heat + "\n");

When you rewind the animation, the expression loops through 100executions, once for each particle.

The first statement sets the $randomNumber variable to a random numberbetween 0 and 1. The next statement assigns a vector to the heat attribute ofa single particle. The left component of the vector assigned to heat is adifferent random number each time the statement executes. The middle andright components are always 0.

One particle might have the value <<0.57, 0, 0>>, another <<0.32, 0, 0>>,another <<0.98, 0, 0>>, and so on.

The print statement displays the values in the Script Editor.

Page 172: Expressions-- Maya Expression Editor From Basic to Professional

172 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

Assigning to a particle array attribute of different lengthYou can assign the array attribute of one particle shape node to another nodehaving a different number of particles. The assignment is affected by whichnode you select in the Object Selection list in the Expression Editor. Thenumber of particles in the selected particle shape node sets the number ofstatement executions, and, therefore, affects the assignment.

Example

Suppose your scene contains an object named ThreePts made of threeparticles and an object named TwoPts made of two particles.

The three particles in ThreePts are at these positions:

-5 0 0-4 0 0-3 0 0

The two particles in TwoPts are at these positions:

5 0 06 0 0

Note

If you add a custom vector attribute to an object, Maya displays theattribute in the Attribute Editor, but you can’t enter its value there. Youmust enter a value for it in an expression or with the Component Editoravailable from the Attribute Editor.

Page 173: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 173

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

Suppose you write this runtime expression with TwoPtsShape2 selected inthe Object Selection list:

ThreePtsShape1.position = TwoPtsShape2.position;print(ThreePtsShape1.position+"\n");

In the first frame of runtime expression execution, this assigns the positionattribute of TwoPts to the position attribute of ThreePts. In other words, theexpression repositions the three particles to the position of the two particles.

Because you selected TwoPtsShape1 in the Object Selection list, theexpression will execute once for each of its two particles.

When you play the scene, the runtime expression executes. The first particleof ThreePts now is at the position of the first particle of TwoPts. The secondparticle of ThreePts is at the position of the second particle of TwoPts. Thethird particle of ThreePts doesn’t change position. The expression executesonly twice each frame.

In summary, the particles in ThreePts are at these positions:

5 0 06 0 0-3 0 0

Suppose you write the preceding runtime expression instead withThreePtsShape1 selected in the Object Selection list.

Again, the expression repositions the three particles to the position of thetwo particles. Because you selected ThreePtsShape1 in the Object Selectionlist, the expression executes once for each of its three particles.

When you play the scene, the runtime expression executes. The first particleof ThreePts moves to the position of the first particle of TwoPts. The secondparticle of ThreePts moves to the position of the second particle of TwoPts.

Page 174: Expressions-- Maya Expression Editor From Basic to Professional

174 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

Because TwoPts lacks a third particle, the third particle of ThreePts isrepositioned at the position of the first particle of TwoPts. You can’t see thisin the workspace because the particles are in the exact same position.

The three particles in ThreePts are at these positions:

5 0 06 0 05 0 0

As this example shows, the assignment statement executes three times.When it runs out of counterpart particles to assign to, it loops around andassigns to the previous particles. It starts with the first particle in the object,and continues through the other particles.

For example, suppose you create a five-particle object named FivePts withthe Particle Tool, and position the particles somewhere in the workspace.Suppose further you select the particle shape node of FivePts in theExpression Editor, then make this assignment in a runtime expression:

FivePtsShape1.position = TwoPtsShape2.position;

The five particles move to these positions as soon as the runtime expressionexecutes for the first time:

5 0 06 0 05 0 06 0 05 0 0

Using creation expression values in a runtime expressionA runtime expression can’t read a variable you’ve defined in a creationexpression unless you define the variable as global. However, you can createa custom attribute, assign it a value in a creation expression, then read orwrite its value in a runtime expression.

Page 175: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 175

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

For example, suppose you assign a particle object’s position to a variablenamed $oldposition in a creation expression:

vector $oldposition = particleShape1.position;

The runtime expression for the same particle shape node can’t read thecontents of the $oldposition variable. To solve this problem, you can createan attribute for the object, assign it a value in the creation expression, thenuse the attribute value in a runtime expression.

For example, suppose you create an attribute named oldpos, and assign itthe following position in a creation expression:

particleShape1.oldpos = particleShape1.position;

You can read the value of particleShape1.oldpos in a runtime expression.

Note that you don’t need to create an attribute to hold the object’s initialposition. The initial position already exists in its initial state attribute namedposition0. This attribute doesn’t appear in the Expression Editor’s AttributesList.

Working with position, velocity, and accelerationTo create various types of particle motion, you can assign vector values tothe position, velocity, or acceleration attribute. See “Writing runtimeexpressions” on page 153 for examples of working with these attributes.

Unless you have a solid grasp of physics, avoid setting a combination of theposition, velocity, and acceleration attributes.

To give a smooth, random motion to particles with a runtime expression, usea random number function such as sphrand to assign random numbers tothe particle shape’s acceleration attribute. A change in acceleration alwaysgives smooth motion no matter how abruptly its value changes.

To give a jittery random motion to particles with a runtime expression, use arandom number function such as sphrand to assign random numbers to theparticle shape’s velocity or position attributes.

See “Random number functions” on page 239 for details on how to userandom number functions.

If an expression and a dynamic field control an object’s position, velocity, oracceleration, Maya calculates the expression’s effect first, then adds thefield’s effect.

Page 176: Expressions-- Maya Expression Editor From Basic to Professional

176 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

Example

Suppose a particle drops under the influence of a gravity field with defaultgravity options. Gravity accelerates the particle at 9.8 units per second persecond down the Y-axis. In other words, the default acceleration of gravity is<<0,-9.8,0>>.

Suppose further you write the following runtime expression for the particle:

velocity = velocity + <<1,0,0>>;

As each frame plays, Maya first calculates the particle’s velocity from theexpression statement. The velocity increases 1 unit per second in an X-axisdirection. Maya then adds the gravitational acceleration to the velocity.Maya uses the combined result to compute the particle’s position.

Of course, you won’t see this calculation process. The frame displays theparticle in the appropriate position after all computation.

Note that the expression adds the constant <<1,0,0>> to the particle’svelocity each frame as the animation plays. This makes the particle movewith increasing velocity in an X direction as the time increases. Anincreasing velocity is the same as acceleration.

Gravity alone Gravity in combination withvelocity = velocity + <<1,0,0>>

The ball represents the particle’s position afterseveral frames. The white squares representthe particle’s position as time increases.

Page 177: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 177

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

The acceleration attribute works differently than the position or velocityattributes in an important way. Maya initializes its value to <<0,0,0>> beforeeach frame. If the oversample level is greater than 1, this initialization occursbefore each timestep.

Example

Suppose you write the following runtime expression for a five-particle objectunaffected by gravity:

acceleration = acceleration + <<0,1,0>>;

Rather than adding <<0,1,0>> to the acceleration value each frame,acceleration remains a constant <<0,1,0>> for each of the particles. Thishappens because Maya initializes the value of acceleration to <<0,0,0>>before each frame.

Suppose you connect the particle object to gravity with default settings. Theacceleration of the particle becomes <<0,1,0>> plus <<0,-9.8,0>>, whichequals <<0,-8.8,0>>. The acceleration assigned in the expression slows thedownward acceleration of the gravity.

Suppose you change the previous expression to this:

acceleration = acceleration + sphrand(3);

Because Maya sets acceleration to <<0,0,0>> before each frame, thestatement has the same result as the following statement:

acceleration = sphrand(3);

As each frame plays, Maya first calculates each particle’s acceleration fromthe expression statement. Each particle receives the result of the sphrand(3)function.

The sphrand(3) function provides a vector whose randomly selectedcomponents reside within a spherical region centered at the origin withradius 3. Each particle receives a different vector value.

Finally, Maya adds gravity’s acceleration to the expression accelerationresulting from sphrand(3). The frame displays each particle in the resultingposition.

Because of the random values resulting from the expression, each particlehas an acceleration that differs slightly from gravity in direction andmagnitude. Because the sphrand(3) function executes for each particle eachframe, the acceleration of each particle varies each frame.

Page 178: Expressions-- Maya Expression Editor From Basic to Professional

178 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

This example shows that you can take advantage of the additive effect offields and the acceleration attribute to create custom field effects.

Working with colorColoring particles is a fundamental task for expression writers. As thetechniques for coloring particles are easiest to learn by example, we providethe following lesson.

Example

Suppose you’ve used the Particle tool to create a randomly positionedcollection of particles named Bubbles. You can use a creation expression togive the particles a constant color during animation play.

Tip

You can turn off the effect of all fields on a particle shape node attribute bysetting its dynamicsWeight attribute to 0.

Gravity in combination withacceleration = sphrand(3)

Position at rewind

Position after one second

Gravity alone (shown for comparison)

Page 179: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 179

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

To give the particles a constant color:

1 Select the particle shape node for Bubbles in the Hypergraph or Outliner.

To write an expression to color particles, you must dynamically add theattribute that lets you color them.

2 In the Add Dynamic Attributes section of the Attribute Editor, click theColor button.

A window appears that prompts you to choose whether to add the attributeper object, per particle, or connected to a shader.

3 Select Add Per Particle Attribute, then click the Add Attribute button.

This adds an rgbPP attribute to the particle shape node for Bubbles. Becauseyou’re adding this attribute as a per particle attribute, you can give eachparticle a different color.

4 Choose Shading→Smooth Shade All.

This step is necessary to make the correct particle color appear when youassign the rgbPP attribute a value in an expression.

5 In the Expression Editor, select Bubble’s particle shape node.

6 Turn on Creation in the Expression Editor.

Because you’ll give the particles a color that doesn’t change during theanimation, you use a creation expression.

7 Enter this expression:

BubblesShape1.rgbPP = <<1,0,0>>;

Page 180: Expressions-- Maya Expression Editor From Basic to Professional

180 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

When you click the Create button in the Expression Editor, Maya checks thesyntax of the expression. Assuming you made no typing errors, theexpression executes once for each of the 100 particles.

The expression colors all particles in the object red. The double anglebrackets << and >> enclose a vector that sets the red, green, and bluecomponents of the rgbPP attribute to 1, 0, and 0. In the RGB color scheme,this gives the object a red color.

8 Play the animation.

Because the expression is a creation expression, it executes when you rewindthe animation. The particles remain red for entire animation because the redcolor is never changed by a runtime expression.

The following steps show how to give the particles a randomly changingcolor as the animation plays.

To give the particles a randomly changing color:

1 With BubblesShape1 selected in the Expression Editor, turn on Runtime.

2 Enter this runtime expression:

BubblesShape1.rgbPP = sphrand(1);

3 Click the Create button to compile the expression.

4 Rewind the animation.

Tip

See the online version of this documentation for colored illustrations.

Page 181: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 181

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

Because the creation expression executes when you rewind, the particles arered.

5 Play the animation.

The runtime expression takes control of the rgbPP attribute. Because rgbPPis a per particle attribute, the runtime expression executes for each particle inthe object each frame. For each particle, the expression assigns the rgbPPattribute the output from the execution of the sphrand function with anargument of 1.

The sphrand function assigns each particle’s rgbPP color a random vector.The vector represents a random point in a spherical region of radius 1. Theleft, middle, and right rgbPP color components have a value no less than -1and no greater than 1. Values less than 0 are treated as 0.

The sphrand function returns a different random vector each execution. Soeach particle has a different random rgbPP value, and therefore, a differentcolor. The color of each particle changes each frame.

If you rendered the animation and played it back at 24 frames per second,you would have trouble seeing the color of a particle in any instant becausethe color changes so quickly.

You can slow the change of colors to create a flashing Christmas light effect.The following steps make the particles change colors every second ofanimation.

To slow the change of color:

1 Change the runtime expression to this:

if ((frame % 24) == 0)BubblesShape1.rgbPP = sphrand(1);

Page 182: Expressions-- Maya Expression Editor From Basic to Professional

182 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

This expression uses the modulus operator (%) to control when the rgbPPattribute of the particles receives a random color. The modulus operatorreturns the remainder after division. For example, 24 divided by 24 returns0, but 25 divided by 24 returns 1. (Dividing 25 by 24 equals 1 with aremainder of 1.)

If the value of frame divided by 24 is equal to any number with a remainderof 0, the assignment to BubblesShape1.rgbPP occurs. In other words, theassignment occurs when frame equals 24, 48, 72, and so on. At an animationrate of 24 frames/second, the assignment happens once each second.

2 Rewind and play the animation.

When you rewind the animation, the particles turn red because the creationexpression executes. When the animation plays, the particles receive arandom color once each second.

Note that you can change the red rewind color to random colors bychanging the creation expression to this:

BubblesShape1.rgbPP = sphrand(1);

This is the same expression as the runtime expression.

Important

Avoid using the modulus operator with floating point values. Because ofnumber rounding in floating point division, you won’t likely get a returnvalue of exactly 0 with the modulus operator. Instead use an integer valuewhen possible.

1 second 3 seconds2 seconds

Page 183: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 183

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

Working with emitted particlesIf you make an object emit particles, you can write a creation or runtimeexpression for attributes of the emitted particles. For example, you canassign the emitted particles a value for lifespan, opacity, and color.

To write an expression for emitted particles:

1 Create the emitter.

2 Add the desired dynamic attribute to the emitter shape node.

3 Select the shape node of the emitted particles in the Expression Editor, thenwrite the expression to control the attribute.

Example

Suppose you’ve created an emitter and added a per particle lifespanPPattribute to it. The following creation expression gives the emitted particles alifespan of 2 seconds:

particleShape1.lifespanPP = 2;

Each particle disappears two seconds after it’s emitted.

Working with collisionsIf you make a particle object collide with an object, you can write anexpression to trigger expression statements after the collision. For example,you can change the color, opacity, or lifespan of the colliding particles.

Important

Avoid assigning a per particle attribute to another object’s per particleattribute if the particles of either object die. As particles die, the order ofexpression evaluation changes for the object’s particles. This causesunexpected results.

You can, though, assign from one attribute to another in the same objectwith dying particles. The array indexes of the different attributes are insynch with each other.

For example, don’t write an expression like this:

emittedShape1.lifespanPP = 2;emittedShape1.rgbPP = otherParticleShape2.rgbPP

Page 184: Expressions-- Maya Expression Editor From Basic to Professional

184 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

To prepare for writing the expression:

1 Select the particle shape node of the particles in the Outliner or Hypergraph.

2 Select Settings→Particle Collision Events from the Dynamics menu bar.

The Particle Events window appears.

3 Click Create Event.

This adds an event attribute to the selected particle shape node. TheExpression Editor displays the added event attribute in the Attributes list.

Close the Particle Events window.

To write the expression:

1 Select the particle shape node of the emitted particles.

2 Write the runtime or creation expression using the value of any of theseattributes of the emitted particle’s shape node:

The eventCount and eventTest are static attributes. A particle shape nodehas them as soon as you create the particle object. Though they don’t appearin the Expression Editor, you can use their values in an expression. Youmust first create the event attribute as described previously.

Long name Short name Description Data Type

event Contains the number oftimes each particle in theobject has hit something(on a per particle basis).

float array

eventCount evc Total number of eventsthat have occurred for allparticles of the object.

integer

eventTest evt True if an event hasoccurred since the lasttime an expression or MELgetAttr command read theeventTest value.

boolean

Page 185: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 185

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

Example

Suppose you’ve created a five-particle object named Peas that falls withgravity and collides with a plane.

You can make the particles turn red when the first particle hits the plane.

1 Select PeasShape1 in the Outliner or Hypergraph.

2 From the Dynamics menu bar, select Settings→Particle Collision Events.

3 In the Particle Events window, click Create Event, then close the window.

This adds an event attribute to PeasShape1.

4 In the Add Dynamic Attributes section of the Attribute Editor, click Color.

The Particle Color window appears.

5 Select Add Per Particle Attribute, then click Add Attribute.

This adds a per particle attribute named rgbPP. This attribute controls thered, green, and blue color scheme of each particle.

The particles turn black after you add the rgbPP attribute. Adding the rgbPPattribute turns off the default coloring of the particles and gives them a valueof <<0,0,0>>.

6 Choose Shading→Smooth Shade All.

This step is necessary to make the correct particle color appear when youassign the rgbPP attribute a value in an expression.

Page 186: Expressions-- Maya Expression Editor From Basic to Professional

186 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

7 With PeasShape1 selected in the Expression Editor, create this runtimeexpression:

if (event == 1)rgbPP = <<1,0,0>>;

else if (event == 2)rgbPP = <<0,1,0>>;

else if (event >= 3)rgbPP = <<0,0,1>>;

else rgbPP = <<1,1,1>>;

8 Rewind the animation.

Upon rewind, the particles are black. The particles have the default blackrgbPP color because no creation expression exists for the object.

9 Play the animation.

The particles fall toward the plane. The runtime expression executes as eachframe plays. The event attribute is a per particle attribute. This isn’t obviousbecause its name doesn’t have PP as the last two characters.

Because event holds a running count of collisions for each particle, eventcontains 0 for each particle until the first collision with the plane. Until thefirst collision occurs, the final else statement executes:

else rgbPP = <<1,1,1>>;

This statement executes because event doesn’t equal 1, 2, 3, or a numbergreater than 3. The vector <<1,1,1>> in the RGB color scheme represents thecolor white.

When the first particle of PeaShape1 hits the plane, Maya sets the eventattribute for that particle to 1. This triggers execution of the first assignment,which sets the colliding particle’s rgbPP value to <<1,0,0>>. In the RGB colorscheme, this vector value represents red. (When red equals 1, green equals 0,and blue equals 0, the resulting color is red.)

Page 187: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 187

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

Note that the value of the event attribute reflects the collision count in theframe after each collision. For example, if a particle collides with the plane inframe 10, event is updated in frame 11.

When the other particles hit the plane for the first time, they also turn redafter they collide.

A particle stays red until it collides with the plane for the second time, whenevent equals 2. After a second collision, the particle turns green.

Tip

See the online version of this documentation for colored illustrations.

Red particle after collision

Page 188: Expressions-- Maya Expression Editor From Basic to Professional

188 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

After a third collision, when event is equal to or greater than 3, a particleturns blue. Each particle stays blue for all subsequent collisions as theanimation plays.

10 Rewind the animation.

The particles turn black again because they receive the default rgbPP value<<0,0,0>>. When you play the animation again, the particles turn white, red,green, and blue in the same sequence as before.

You can refine the animation by giving the particles a color other than blackfor the frame that appears upon rewinding. For example, you can give theparticles a white color upon rewinding with two techniques:

• Write this creation rule for PeasShape1:

rgbPP = <<1,1,1>>;

This statement executes for each particle in the object, so they all receive thesame white color when you rewind the scene.

• Select PeasShape1, rewind the animation, and play one frame.

11 Choose Settings→Initial State→Set for Current.

This saves all PeasShape1 attribute values from the current frame for theinitial state of the attributes. The current value for rgbPP will be used whenyou rewind the animation. Because you played the second frame of theanimation, this saves the white color of the particles at that frame for useupon rewinding the animation.

Page 189: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 189

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

Note that Set for Current saves all attribute values, including position,velocity, acceleration, and so on. In cases where you have several changingattribute values during playback, Set for Current might save undesiredattribute values in addition to the desired ones. In such cases, use a creationexpression.

Working with specific particlesA per particle attribute holds the attribute values for each of an object’sparticles. For example, the rgbPP attribute holds the value for each particle’srgbPP value.

Each particle has a unique numerical particle identifier. A particle’sidentifier is stored in a per particle particleId attribute for the particle object.As you create the particles of a particle object, Maya assigns each particle aparticleId in sequential order starting at 0.

For example, suppose you use the Particle tool to create a five-particle objectby clicking positions in the workspace. The first click of the mouse creates aparticle with particleId 0, the second click creates a particle with particleId 1,the third click creates a particle with particleId 2, and so on.

When an emitter emits particles, Maya assigns particleId numbers insequential order starting with the first particle emitted. The first emittedparticle has particleId 0, the second has particleId 1, the third has particleId2, and so on.

You can assign per particle attribute values to specific particles using theparticleId attribute.

Example

Suppose you’ve used the Particle tool to create a grid of eight particlesnamed ColorGrid. In the Attribute Editor, you’ve set the Render Type of theparticles to Spheres. You’ve chosen Shading→Smooth Shade All to displaythe particles with shading.

Page 190: Expressions-- Maya Expression Editor From Basic to Professional

190 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

You can give the particles different colors based on their particleId.

To color the particles based on particleId:

1 Select the ColorGrid.

2 In the Add Dynamic Attributes section of the Attribute Editor, click Color.

The Particle Color window appears.

3 Select Add Per Particle Attribute, then click Add Attribute.

This adds a per particle attribute named rgbPP, which controls the red,green, and blue color scheme of each particle.

The particles turn black after you add the rgbPP attribute. Adding the rgbPPattribute turns off the default coloring of the particles and gives them a valueof <<0,0,0>>.

4 In the Attribute Editor, choose Numeric from the Render Type menu.

The particleId of each particle is displayed instead of spheres:

Page 191: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 191

Particle ExpressionsWorking with particle attributes

Ex

pre

ss

ion

s

5 With ColorGridShape1 selected in the Expression Editor, enter this creationexpression:

if (particleId <= 2)rgbPP = <<1,0,0>>;

else if ((particleId > 2) && (particleId < 6))rgbPP = <<1,1,1>>;

else rgbPP = <<0,0,1>>;

The creation expression executes whenever you rewind the animation. Theparticles don’t show the color assignments yet. The Numeric particle rendertype ignores color assignments to rgbPP.

6 In the Attribute Editor, set Render Type of the particles to Spheres again.

The left, middle, and right columns of particles are red, white, and blue:

The expression’s first statement assigns a red color to all particles whoseparticleId is less than or equal to 2. The value <<1,0,0>> is red in the RGBcolor scheme.

The second statement assigns a white color to all particles whose particleIdis greater than 2 and less than 6. The value <<1,1,1>> is white in the RGBcolor scheme.

The third statement assigns a blue color to all particles that don’t meet theconditions in the prior two statements. In other words, all particles whoseparticleId is greater than or equal to 6 become blue. The value <<0,0,1>> isblue in the RGB color scheme.

The following steps show another common way to control an attribute basedon the particleId attribute.

Page 192: Expressions-- Maya Expression Editor From Basic to Professional

192 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsWorking with particle attributes

To color half the particles red, and half the particles blue:

1 Enter the following runtime expression:

if ((particleId % 2) == 0)rgbPP = <<1,0,0>>;

else rgbPP = <<0,0,1>>;

2 Play the scene.

The runtime expression executes each frame as the animation plays. Half theparticles are blue, half are red.

The first statement uses a modulus operator (%) to calculate the remainderof dividing a particleId by 2. It then compares the remainder to 0. If theremainder equals 0, the statement assigns the particle a red color. The value<<1,0,0>> is red.

The second statement assigns a particle a blue color if the remainder of themodulus operation doesn’t equal 0. The value <<0,0,1>> is blue. Forexample, dividing particleId 0 by 2 equals 0 with remainder 0. Because theremainder is 0, the particle having particleId 0 receives a red color.

Dividing particleId 1 by 2 equals 0 with remainder 1. Because the remainderis 1, the particle having particleId 1 receives a blue color.

Dividing particleId 2 by 2 equals 1 with remainder 0. With remainder 0, theparticle having particleId 1 receives a blue color. The expression executes foreach particle in the object.

The result is that even-numbered particleIds become red, odd numberedparticles become blue.

3 Rewind the animation.

Page 193: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 193

Particle ExpressionsAssigning to vectors and vector arrays

Ex

pre

ss

ion

s

The creation expression executes. The particles become red, white, and blueas described for the previous expression.

4 Play the animation.

The runtime expression executes each frame. The particles are red and blueas the animation plays.

Assigning to vectors and vector arraysPrevious topics in this chapter show general techniques for working withvector array attributes. Vector array attributes are also called per particleattributes. Subtle details of assigning to vector and vector array attributesand variables follow.

Assigning to a vector variableYou can assign a literal vector value or another vector variable to a vectorvariable. Enclose a literal vector value in double angle brackets.

Examples

vector $top_velocity = <<2,2,5>>;

This assigns the vector $top_velocity the value <<2,2,5>>.

vector $temp;vector $temp = $top_velocity;

This assigns the value of vector variable $top_velocity to the vector variable$temp.

Note to programmers

You cannot assign values to individual particles with the array indexnotation commonly used in programming languages.

For example, suppose you’ve created an opacityPP attribute for an objectmade of three particles. You can’t assign values as in this example:

opacityPP[0] = 0.3;opacityPP[1] = 0.5;opacityPP[2] = 1;

Page 194: Expressions-- Maya Expression Editor From Basic to Professional

194 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsAssigning to vectors and vector arrays

Using the vector component operator with variablesYou can use a vector component operator (.) to read a component of a vectorvariable or vector array variable.

Examples

float $temp;vector $myvector = <<1,2,3>>;float $temp = $myvector.z;

This assigns the right component of $myvector, 3, to the floating pointvariable $temp.

Suppose you have a vector initialized as follows:

vector $myvector = <<1,2,3>>;

To replace the right component of $myvector, 3, with a new value such as 7,use this technique to preserve the other two components:

$myvector = <<$myvector.x,$myvector.y,7>>;

This statement is incorrect:

$myvector.z = 3;

An error occurs. A statement can read, but not directly assign, a componentof a vector variable.

Assigning to a vector array attribute componentAn expression can neither read nor assign a component of a vector or vectorarray attribute. The following example shows a technique for workingaround this limitation. For details on working with color attributes, see“Working with color” on page 178.

Format Meaning

$variable.x left component

$variable.y middle component

$variable.z right component

Page 195: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 195

Particle ExpressionsAssigning to vectors and vector arrays

Ex

pre

ss

ion

s

Example

Suppose you have 100-particle Cloud of randomly positioned particles.

CloudShape1.position = sphrand(1);vector $pos = CloudShape1.position;CloudShape1.rgbPP = <<0,$pos.y,0>>;

The three statements execute once for each particle in Cloud.

The first statement gives a particle a random position within a sphericalregion of radius 1. The sphrand(1) function gives the X, Y, and Z positioncomponents a value no less than -1 and no greater than 1.

The second statement assigns a particle’s position to a vector variable $pos.

The third statement assigns an RGB color to a particle’s rgbPP attribute.

The left, middle, and right vector components of CloudShape1.rgbPPrepresent red, green, and blue components of the RGB color scheme. Thethird statement therefore assigns 0 (no color) to the red and blue componentsof a particle’s colorRGB. It gives a particle’s green component the value of itsY coordinate position.

Because a value of 0 or less results in a 0 green value, a particle is black if it’sbelow the XZ plane. If a particle’s Y coordinate position is above the XZplane, it has a green component varying from nearly 0 to a fully saturatedgreen.

This colors the particles from black to green, depending on the position.

Increasingly green

Page 196: Expressions-- Maya Expression Editor From Basic to Professional

196 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsList of particle shape attributes

Example

particleShape1.rgbPP = <<1,0,CloudShape1.position.z>>;

This causes an error. Maya interprets CloudShape1.position.z as being anattribute named z of an object named CloudShape1.position.

You can get the intended result with these statements:

vector $temp = CloudShape1.position;particleShape1.rgbPP = <<1,0,$temp.z>>;

The first statement reads all three components of vector attributeCloudShape1.position and assigns it to the vector variable $temp. Thesecond statement reads the value of the right component of $temp, whichcontains the right component of CloudShape1.position. It then assigns thiscomponent to the right component of particleShape1.rgbPP.

Example

particleShape1.rgbPP.y = 1;

This also causes an error. You can’t assign a value to a vector array attributecomponent.

List of particle shape attributesThe following table describes the static and dynamic attributes that affectparticle shape nodes on a per object or per particle basis. Note the following:

• Attributes you can read but not write are marked with an asterisk (*).

• Empty boxes in the Render Type column indicate the render type isirrelevant to the attribute’s usage.

• You can read and write per particle attributes only in particle expressions.

See Using Maya: Dynamics for more details on the attributes.

Page 197: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 197

Particle ExpressionsList of particle shape attributes

Ex

pre

ss

ion

s

Attribute long name(and short name)

Description Perparticle

Render Type Data Type

acceleration(acc)

Sets acceleration. yes vector array

age*(ag)

Contains number ofseconds each particle hasexisted in scene.

yes float array

attributeName Specifies name of attributewhose value is displayedat particle positions.

Numeric string

betterIllumination Toggles increased selfshadowing.

Cloud boolean

colorAccum Toggles additive displayeffect for RGB and opacityof overlapping particlesfor this object.

MultiPointMultiStreakPointsStreak

boolean

colorBlue Sets blue component ofRGB color.

Blobby SurfaceCloudMultiPointMultiStreakPointsSphereSpriteStreak

float

colorGreen Sets green component ofRGB color.

float

colorRed Sets red component ofRGB color.

float

conserve(con)

Sets amount ofmomentum conservation.

float

count*(cnt)

Contains number ofparticles in object.

integer

depthSort(ds)

Toggles depth sorting ofparticles for rendering.

MultiPointMultiStreakPointsStreakSprite

boolean

Page 198: Expressions-- Maya Expression Editor From Basic to Professional

198 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsList of particle shape attributes

dynamicsWeight(dw)

Scales effect of dynamicfields and collisions onparticle object.

float

event* Contains number of timeseach particle in the objecthas hit something.

yes float array

eventCount*(evc)

Contains total number ofevents that have occurredfor all particles of theobject.

integer

eventTest*(evt)

Contains 1 if an event hasoccurred on the objectsince last time anexpression or MELgetAttr command read theeventTest value.

boolean

goalPP Sets how much theparticles try to follow goalon a per particle basis.

yes float array

goalWeight(gw)

Sets how much theparticles try to followgoal.

float

incandescence Sets glow color. Cloud vector

incandescencePP Sets glow color. yes Cloud vector array

inheritFactor(inh)

Sets fraction of velocityinherited from the emitterof this particle object.

float

isDynamic(isd)

Toggles dynamics forobject.

boolean

lifespan Sets when all particles die. float

Attribute long name(and short name)

Description Perparticle

Render Type Data Type

Page 199: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 199

Particle ExpressionsList of particle shape attributes

Ex

pre

ss

ion

s

lifespanPP Sets when particles die ona per particle basis.

yes float array

levelOfDetail(lod)

Scales number of particlesthat can be emitted intothe object.

float

lineWidth Sets width of particle. MultiStreakStreak

float

mass Specifies physical mass ofparticles. As massincreases, the effect ofdynamic forces change.

yes float array

maxCount(mxc)

Sets maximum number ofparticles that can beemitted into this object.

integer

multiCount Sets number of pointsyou want displayed foreach particle. This numberapplies to each particle inthe object.

MultiPointPoint

float

multiRadius Sets radius of sphericalregion in which particlesare randomly distributed.

MultiPointMultiStreak

float

normalDir Sets direction of normalfor particles. Used withuseLighting.

MultiPointMultiStreakPointsStreak

integer (1-3)

Attribute long name(and short name)

Description Perparticle

Render Type Data Type

Page 200: Expressions-- Maya Expression Editor From Basic to Professional

200 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsList of particle shape attributes

opacity Sets amount oftransparency.

MultiPointMultiStreakPointsStreakSphereBlobby SurfaceCloudSprite

float

opacityPP Sets amount oftransparency.

yes MultiPointMultiStreakPointsStreakSphereCloudSprite

float array

particleId*(id)

Contains id number ofeach particle.

yes Numeric float array

pointSize Sets size of particle points. MultiPoint,NumericPoints

float

position(pos)

Sets position. yes vector array

radius Sets radius size of allparticles.

Blobby SurfaceCloudSphere

float

radius0 Sets starting point radiusfor tube render type.

Tube float

radius1 Sets ending point radiusfor tube render type.

Tube float

radiusPP Sets radius size on a perparticle basis.

yes Blobby SurfaceCloudSphere

float array

Attribute long name(and short name)

Description Perparticle

Render Type Data Type

Page 201: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 201

Particle ExpressionsList of particle shape attributes

Ex

pre

ss

ion

s

primaryVisibility(rea)

Toggles whether surfacewill be rendered bysoftware renderer.

CloudBlobby SurfaceTube

boolean

visibleInReflections(rrl)

Toggles whether object isvisible in reflections.

CloudBlobby SurfaceTube

boolean

visibleInRefractions(rrr)

Toggles whether object isvisible in refractions.

CloudBlobby SurfaceTube

boolean

castsShadows(rsh)

Toggles whether objectcasts shadows.

CloudBlobby SurfaceTube

boolean

rgbPP Sets color. yes MultiPointMultiStreakPointsSphereSpriteStreak

vector array

selectedOnly Toggles display of idnumbers for selectedparticles.

Numeric boolean

spriteNum Sets image number indexfor image sequence.

Sprite integer

spriteNumPP Sets image number indexfor image sequence.

yes Sprite integer array

spriteScaleX Sets X-axis image scale. Sprite float

spriteScaleXPP Sets X-axis image scale. yes Sprite float array

spriteScaleY Sets Y-axis image scale. Sprite float

spriteScaleYPP Sets Y-axis image scale. yes Sprite float array

spriteTwist Sets image’s rotationangle.

Sprite float

Attribute long name(and short name)

Description Perparticle

Render Type Data Type

Page 202: Expressions-- Maya Expression Editor From Basic to Professional

202 Using Maya: Hypergraph, Sets & Expressions

Particle ExpressionsList of particle shape attributes

spriteTwistPP Sets image’s rotationangle.

yes Sprite float array

surfaceShading Sets level of shading. Cloud float

tailFade Sets opacity of tail fade. MultiStreakStreak

float

tailSize Sets length of tail. MultiStreakStreakTube

float

threshold Sets distance betweenparticles at which loftingoccurs.

Blobby SurfaceCloud

float

useLighting Toggles whether scenelighting lights upparticles.

MultiPointMultiStreakPointsSpriteStreak

boolean

velocity(vel)

Sets velocity. yes vector array

Attribute long name(and short name)

Description Perparticle

Render Type Data Type

Page 203: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 203

Ex

pre

ss

ion

s

9 Functions

In expressions, you can use built-in operations called functions to createmotion, particle positioning, and other effects. This chapter explains themost commonly used functions and a few useful MEL commands.

For easy reference, this chapter groups functions by their purpose. Forexample, all math functions are grouped in the same section.

To find out about: See page:

Understanding functions 205

Function syntax 206

Limit functionsabsceilfloorclampminmaxsigntrunc

209210210210211212212212213

A hermite function shapedthe lightning’s soft bodygeometry, dnoise animatedits turbulence, and sphrandenhanced its randomness.

Matt Baer

Page 204: Expressions-- Maya Expression Editor From Basic to Professional

204 Using Maya: Hypergraph, Sets & Expressions

Functions

Exponential functionsexploglog10powsqrt

214214214214215215

Trigonometric functionscoscosdsinsindtantandacosacosdasinasindatanatandatan2atan2dhypot

216216218219224224225225226226226227227227228228

Vector functionsanglecrossdotmagrotunit

229230230231231232233

Conversion functionshsv_to_rgbrgb_to_hsvdeg_to_radrad_to_deg

234235235234234

To find out about: See page:

Page 205: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 205

FunctionsUnderstanding functions

Ex

pre

ss

ion

sUnderstanding functionsA function generates a value where it occurs in an expression statement. Ittakes action based on parameters called arguments that you enclose inparentheses next to the function name.

Example

Suppose you have an object named Star whose translateX attribute is setwith this expression statement:

Star.translateX = rand(10);

In this statement, the rand function has the argument 10. With thisargument, the function generates a randomly selected floating point numberbetween 0 and 10 each time the statement executes. For example, translateX

Array functionsclearsizesort

236236237237

Random number functionsgaussnoisednoiserandsphrandseed

239239241242243244246

Curve functionslinstepsmoothstephermite

249249252254

General commandsevalprintsystem

259259261263

Other functions andcommands

264

To find out about: See page:

Page 206: Expressions-- Maya Expression Editor From Basic to Professional

206 Using Maya: Hypergraph, Sets & Expressions

FunctionsFunction syntax

might be assigned 6.5409 the first time the statement executes, 3.2974 thesecond time, 8.7389 the third time, and so on. This causes Star to jump torandom points from 0 to 10 units away from the X-axis as the scene plays.

Though functions can be more or less complicated than this example, theyall have at least one argument and generate one value. Note that a functionis part of an expression statement. They don’t stand alone in an expression.

Many functions do mathematical operations. For example, the sin functiongenerates the sine of a specified angle. Though we often provide explanatoryfigures and details, we assume you’re familiar with the mathematicalpurpose of such functions. For details on the math behind such functions,see a more elementary reference.

Note that the following functions are important to learn if you want to gobeyond the basics of expression writing:

• sin or sind

• linstep

• smoothstep

• hermite

• noise

• dnoise

• rand

• sphrand

• print

Function syntaxTo help you quickly reference different functions, this chapter includes asyntax format statement for each function. The format follows:

datatype function( datatype argument )

function is the name of the function.

datatype to the left of an argument indicates the data type of the argument.

argument is a parameter you type with the function.

datatype to the left of the function name indicates the data type returnedwhen the function executes.

Page 207: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 207

FunctionsFunction syntax

Ex

pre

ss

ion

s

Note that for either datatype, you don’t type a value. The datatype tells youthe type of data you must enter or the data type returned by the executedfunction.

The data types are in small type size for easy identification in the syntaxdefinitions.

Example 1

int abs( int number )

float abs( float number )

vector abs( vector number )

The function name is abs, which returns the absolute value of the number ofyour choice. The absolute value of a number is the number without itspositive or negative sign.

This example shows the abs function has three formats. Each versionrequires an argument with a different data type and returns a value with adifferent data type.

The first version indicates that you can type an integer argument, and thefunction returns an integer result. For example, abs(-3) returns 3.

The second version indicates that you can type a floating point argument,and the function returns a floating point result. For instance, abs(-7.54)returns 7.54.

The third version indicates you can type a vector, and the function returns avector. For example abs(<<3, -6.3, -2>>) returns <<3, 6.3, 2>>.

Example 2

Many functions have only one format, for example, the deg_to_rad function:

float deg_to_rad( float degrees )

This function returns the radian equivalent of to a degree value. It expects afloating point argument and returns a floating point number.

Note that Maya ignores spaces between components of functions. Forexample, the functions in each of these expressions work the same:

rotateY = deg_to_rad (45);

rotateY = deg_to_rad(45);

rotateY = deg_to_rad( 45 );

Page 208: Expressions-- Maya Expression Editor From Basic to Professional

208 Using Maya: Hypergraph, Sets & Expressions

FunctionsFunction syntax

Data typesIn many cases, entering a data type other than the type expected by afunction causes an error and prevents the expression from executing. Forexample, if you enter a vector argument where a floating point number isexpected, an error occurs.

For a function argument that expects a floating point number, however, youcan instead type an integer—a number without a decimal point. Mayaconverts an integer to a floating point number in arithmetic operations.

If an error occurs when you create an expression, check that you’re using theappropriate data types for all arguments.

Understanding function examples in this chapterMost function examples in this chapter show the use of the function outsideof an expression statement. This makes the examples less cluttered andeasier to read. For instance, the first example for the abs function on page209 is:

abs(-1)

This returns the value 1 where it occurs in an expression statement.

For a function to have effect, you must use it within an expression thatassigns a value to an attribute or variable.

Notes

In this book, examples of floating point return values show no more thanthree digits to the right of the decimal point. If you display the contents ofan attribute or variable in the Script Editor, you’ll see as many as 10 digitsto the right of the decimal point.

For instance, an example might show a return value as 3.539 rather thanthe precise value 3.538654390. The examples round up such numbers forease of reading.

Note also that converting radians to degrees and vice versa results inrounding errors. For example, converting a radian value might result in89.99999996 degrees rather than 90.0 degrees.

Page 209: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 209

FunctionsLimit functions

Ex

pre

ss

ion

s

Examples

Ball.scaleY = abs(-1);

This statement assigns Ball.scaleY the value returned by the abs(-1) function.

If you use a function in an expression statement and do not assign thereturned value to an attribute, the statement has no effect.

abs(-1);

Returns 1, but doesn’t assign it to an attribute. This has the same result asthe following meaningless statement:

1;

In some function examples in this chapter, the function’s purpose is easier tounderstand in the context of an expression. In such cases, we show examplesof the function in an expression.

Limit functionsThe limit functions are math functions that impose limits on numbers.

absReturns the absolute value of number. The absolute value of an integer orfloating point number is the number without its positive or negative sign.The absolute value of a vector is a vector with components stripped ofnegative signs.

int abs( int number )

float abs( float number )

vector abs( vector number )

number is the number for which you want the absolute value.

Examples

abs(-1)

Returns the value 1.

abs(1)

Returns the value 1.

Page 210: Expressions-- Maya Expression Editor From Basic to Professional

210 Using Maya: Hypergraph, Sets & Expressions

FunctionsLimit functions

abs(<<-1,-2.43,555>>)

Returns <<1, 2.43, 555>>.

abs(Ball.translateY)

If Ball.translateY contains -20, this returns 20.

ceilReturns a number rounded to the smallest integer value greater than orequal to a floating point number.

float ceil( float number )

number is the number you want to round.

Examples

ceil(2.344)

Returns 3.

ceil(3.0)

Returns 3.

ceil(Rock.scaleY)

If Rock.scaleY contains -2.82, this returns -2.

floorReturns a number rounded to the largest integer less than or equal to afloating point number.

float floor( float number )

number is the number you want to round.

Examples

floor(2.344)

Returns 2.

floor(3.0)

Returns 3.

Page 211: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 211

FunctionsLimit functions

Ex

pre

ss

ion

s

floor(Head.height)

If Head.height is -2.8, this returns -3.

clampReturns a number within a range. You can use the clamp function to confinean increasing, decreasing, or randomly changing number to a range ofvalues.

float clamp( float minnumber , float maxnumber , float parameter )

minnumber and maxnumber specify the range of the returned value.

parameter is an attribute or variable whose value you want to clamp withinthe range.

If parameter is within the numerical range of minnumber and maxnumber, thefunction returns the value of parameter.

If parameter is greater than the range, the function returns the maxnumber.

If parameter is less than the range, the function returns the minnumber.

Examples

clamp(4,6,22)

Returns 6, because 22 is greater than 6, the maximum number of the range.

clamp(4,6,2)

Returns 4, because 2 is less than 4, the minimum number of the range.

clamp(4,6,5)

Returns 5, because it’s within the range.

Ball.scaleY = clamp(0,3,time);

Returns a value between 0 and 3 each time the expression executes.

When you rewind the animation to frame 1, the above expression executesand Ball’s scaleY attribute receives the value of time—a number slightlyabove 0. The clamp function returns the value of time because time is withinthe range 0 to 3.

When you play the animation, time increments slightly with each frame. Theexpression executes with each frame and Ball’s scaleY attribute receives thevalue of time until time exceeds 3. When time exceeds 3, the clamp functionreturns the value 3.

Page 212: Expressions-- Maya Expression Editor From Basic to Professional

212 Using Maya: Hypergraph, Sets & Expressions

FunctionsLimit functions

minReturns the lesser of two floating point numbers.

float min( float number , float number )

number is a number you want to compare.

Examples

min(7.2,-3.2)

Returns -3.2.

Desk.height = -2;Lamp.height = 9;$Mylight = min(Desk.height,Lamp.height);

Sets $Mylight to -2.

maxReturns the larger of two floating point numbers.

float max( float number , float number )

number is a number you want to compare.

Examples

max(7.2,-3.2)

Returns 7.2.

Desk.height = -2;Lamp.height = 9;$Mylight = max(Desk.height,Lamp.height);

Sets $Mylight to 9.

signReturns one of three values representing the sign of a number. Returns -1 ifthe number is negative, 1 if positive, 0 if 0.

float sign( float number )

number is the number whose sign you want to determine.

Page 213: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 213

FunctionsLimit functions

Ex

pre

ss

ion

s

Examples

sign(-9.63)

Returns -1.

sign(0)

Returns 0.

sign(10)

Returns 1.

sign(Ball.translateX)

If Ball.translateX is 5, this returns 1.

truncReturns the whole number part of a floating point number.

float trunc( float number )

number is the number you want to truncate.

Examples

trunc(2.344)

Returns 2.

trunc(0.3)

Returns 0.

trunc(-2.82)

Returns -2.

trunc(time)

If time equals 3.1234, this returns 3.

Page 214: Expressions-- Maya Expression Editor From Basic to Professional

214 Using Maya: Hypergraph, Sets & Expressions

FunctionsExponential functions

Exponential functionsThe following functions work with exponential values.

expReturns e raised to the power of a number, enumber. The predefined variable eis the base of the natural logarithm, which is 2.718.

float exp( float number )

number is the exponent to which you want to raise e.

Examples

exp(1)

Returns 2.718, the value of e.

exp(2)

Returns 7.389, the value of e2.

logReturns the natural logarithm of a number, logenumber. The naturallogarithm uses the constant e, which is 2.718.

float log( float number )

number is the positive number for which you want the natural logarithm.

Examples

log(10)

Returns 2.303.

log(2.718282845904)

Returns 1.000.

log10Returns the log base 10 of a number.

float log10( float number )

number is the positive number for which you want the log base 10.

Page 215: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 215

FunctionsExponential functions

Ex

pre

ss

ion

s

Examples

log10(100)

Returns 2.

log10(10)

Returns 1.

powReturns a base number raised to an exponent.

float pow( float base, float exponent )

base is the base number you want to raise to the exponent. A negative basenumber with a decimal component causes an error message.

exponent is the exponent.

Examples

pow(2,3)

Returns 8.

pow(-2,3)

Returns -8.

pow(2,-3)

Returns 0.125.

sqrtReturns the square root of a positive number.

float sqrt( float number )

number is the positive number of which you want the square root.

A negative number displays an error message.

Examples

sqrt(16)

Returns 4.

Page 216: Expressions-- Maya Expression Editor From Basic to Professional

216 Using Maya: Hypergraph, Sets & Expressions

FunctionsTrigonometric functions

sqrt($side)

If $side is 25, this returns 5.

Trigonometric functionsThe following functions return trigonometric values. Each function has twoformats that let you choose the type of angular unit you work with: degreesor radians. For example, the cos function expects an argument in radians,while cosd expects an argument in degrees.

A radian equals 180 degrees divided by pi, or roughly 57.3 degrees. Notethat pi equals 3.1415927, which is also 180 degrees.

cosReturns the cosine of an angle specified in radians.

float cos( float number )

number is the angle, in radians, whose cosine you want.

For any right triangle, the cosine of an angle is the following ratio:

If θ is between 1/2 pi radians and3/2 pi radians (90 to 270 degrees),cos θ is a value between 0 and -1.

If θ is less than 1/2 pi radians andmore than 3/2 pi radians (from 270to 90 degrees), cos θ is a valuebetween 0 and 1.

θ

CA

B X

Y

θ

CA

BX

Y

C

θcos adjacenthypotenuse------------------------------ B

C----= =

Page 217: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 217

FunctionsTrigonometric functions

Ex

pre

ss

ion

s

The cosine ratio depends only on the size of the angle and not on the size ofthe triangle. This constant ratio is called the cosine of the measure of theangle.

The cosine ratio is a value between -1 and 1.

With a steadily increasing or decreasing argument, the cos function returnssteadily increasing or decreasing values between 1 and -1. This is useful forcreating rhythmic, oscillating changes in attribute values.

The cos function works like the sin function except its return values are 90degrees, or pi/2, out of phase.

See page 219 for ideas on how to use the cyclical characteristics of the sinand cos functions.

Example 1

cos(1)

Returns 0.5403, the cosine of 1 radian.

Example 2

To animate the motion of Ball in a cosine wave pattern, use this expression:

Ball.translateX = time;Ball.translateY = cos(Ball.translateX);

Ball starts at the origin and moves in the X direction at a rate set by theincrementing animation time. Its Y translation moves cyclically up anddown according to the return values of the cos function. The cos functionuses translateX, and therefore indirectly, time, as its argument.

As time increases from 0 to 6.283 seconds, the cos function returns valuesthat change in fine increments from 1 to -1 and back to 1. The value 6.283 is 2times the value of pi.

As time increases beyond 6.283 seconds, the same cycle repeats for each spanof 6.283 seconds.

Page 218: Expressions-- Maya Expression Editor From Basic to Professional

218 Using Maya: Hypergraph, Sets & Expressions

FunctionsTrigonometric functions

Compare the same expression using the sin function:

The cosine curve is 1.571 (pi/2) seconds ahead of (or behind) the sine curve,and vice versa.

cosdReturns the cosine of an angle specified in degrees.

float cosd( float number )

number is the angle, in degrees, whose cosine you want.

For more details on the cosd function, see the cos function in the precedingtopic. The cosd and cos functions do the same operation, but cosd requiresits argument in degree measurement units.

time = 6.283(2 * pi seconds)

Ball.translateY = cos(Ball.translateX);

time = 6.283(2 * pi seconds)

Ball.translateY = sin(Ball.translateX);

Page 219: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 219

FunctionsTrigonometric functions

Ex

pre

ss

ion

s

Example

cosd(45)

Returns 0.707, the cosine of 45 degrees.

sinReturns the sine of an angle specified in radians.

float sin( float number )

number is the angle, in radians, whose sine you want.

For any right triangle, the sine of an angle is the following ratio:

The sine ratio depends only on the size of the angle and not on the size ofthe triangle. This constant ratio is called the sine of the measure of the angle.

The sine ratio is a value between -1 and 1.

With a steadily increasing or decreasing argument, the sin function returnssteadily increasing or decreasing values between -1 and 1. This is useful forcreating rhythmic, oscillating changes in attribute values.

θ

CA

B X

Y

θ

CA

BX

Y

C

If θ is from 0 to pi radians (0 to180 degrees), sin θ is a valuebetween 0 and 1.

If θ is from pi to 2 pi radians (180to 360 degrees), sin θ is a valuebetween 0 and -1.

θsin oppositehypotenuse------------------------------ A

C----= =

Page 220: Expressions-- Maya Expression Editor From Basic to Professional

220 Using Maya: Hypergraph, Sets & Expressions

FunctionsTrigonometric functions

For example, you can use the sin function to manipulate:

• an object’s translate attributes to create snake-like motion

• a body’s scale attributes to create a breathing cycle

• a particle object’s opacity or color attributes to cycle a color or opacitypattern

Example 1

float $pi = 3.1415927;sin($pi/2)

Returns 1, the sine of pi/2 radians.

Example 2

Ball.translateY = sin(Ball.translateX);

This statement sets Ball’s translateY attribute equal to the sine of itstranslateX attribute. If you drag Ball along the X-axis, Ball’s translateYposition moves up and down in a cyclical pattern:

Example 3

To animate Ball to the path of the preceding example, use this expression:

Ball.translateX = time;Ball.translateY = sin(Ball.translateX);

Page 221: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 221

FunctionsTrigonometric functions

Ex

pre

ss

ion

s

Ball starts at the origin and moves in the X direction at a rate set by theincrementing animation time. Its Y translation moves cyclically up anddown according to the return values of the sin function. The sin functionuses translateX, and therefore indirectly, time, as its argument.

As time increases from 0 to 6.283 seconds, the sin function returns valuesthat change in fine increments from 0 to 1 to -1 to 0. The value 6.283 is 2times the value of pi. The resulting motion resembles a horizontal S-shape:

As time increases beyond 6.283 seconds, the same S-shaped cycle repeats foreach span of 6.283 seconds.

Example 4

This expression animates Ball with larger up and down swings:

Ball.translateX = time;Ball.translateY = sin(Ball.translateX) * 2;

By multiplying sin(Ball.translateX) by a number greater than 1, you increasethe amplitude of the sine wave pattern. The amplitude is half the distancebetween the minium and maximum values of the wave.

time = 6.283(2 * pi seconds)

Amplitude

Page 222: Expressions-- Maya Expression Editor From Basic to Professional

222 Using Maya: Hypergraph, Sets & Expressions

FunctionsTrigonometric functions

You can decrease the amplitude of the sine wave by multiplying by anumber less than 1, for example, 0.5.

Example 5

This expression increases how often the sine wave completes a cycle:

Ball.translateX = time;Ball.translateY = sin(Ball.translateX * 2);

By multiplying Ball.translateX by a number greater than 1, you increase thefrequency of the sine wave pattern. The frequency is how long it takes thewave to make a complete cycle.

You can decrease the frequency of the sine wave by multiplying by anumber less than 1, for example, 0.5. This number is known as a frequencymultiplier because it multiplies (or divides) the frequency of the sine pattern.

Example 6

This expression offsets the wave pattern higher up the Y-axis:

Ball.translateX = time;Ball.translateY = sin(Ball.translateX) + 2;

By adding 2 to sin(Ball.translateX), the wave pattern starts further up the Y-axis. You can, of course, also subtract a number to offset the wave patternlower on the Y-axis.

Frequency

Page 223: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 223

FunctionsTrigonometric functions

Ex

pre

ss

ion

s

Example 7

The following expression sets a frequency multiplier, amplitude, and offsetof a sine pattern in a single statement:

Ball.translateX = time;Ball.translateY = (sin(Ball.translateX * 2) * 2) + 2;

The following diagram shows which values set the frequency multiplier,amplitude, and offset.

A general equation showing the factors you can use to create a sine wavepattern follows:

Offset of 2

Frequency multiplier

AmplitudeOffset

Ball.translateY = (sin(Ball.translateX * 2) * 2) + 2;

attribute = (sin(frequency * frequency multiplier) * amplitude) + offset ;

Page 224: Expressions-- Maya Expression Editor From Basic to Professional

224 Using Maya: Hypergraph, Sets & Expressions

FunctionsTrigonometric functions

sindReturns the sine of an angle specified in degrees.

float sind( float number )

number is the angle, in degrees, whose sine you want.

For more details on how to use the sind function, see the sin function in thepreceding topic. The sind and sin functions do the same operation, but sindrequires its argument in degree measurement units.

Example

sind(90)

Returns 1, the sine of 90 degrees.

tanReturns the tangent of an angle specified in radians.

float tan( float number )

number is the angle, in radians, whose tangent you want.

For any right triangle, the tangent of an acute angle is the following ratio:

θ

CA

B X

Y

θ

CA

BX

Y

C

θtan oppositeadjacent----------------------- A

B---= =

Page 225: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 225

FunctionsTrigonometric functions

Ex

pre

ss

ion

s

The ratio depends only on the size of the angle and not on the size of thetriangle. This constant ratio is called the tangent of the measure of the angle.

Example

tan(1)

Returns 1.557.

tandReturns the tangent of an angle specified in degrees.

float tand( float number )

number is the angle, in degrees, whose tangent you want.

For more details on the tand function, see the tan function in the precedingtopic. The tand and tan functions do the same operation, but tand requiresits argument in degree measurement units.

Example

tand(45)

Returns roughly 1, the tangent of 45 degrees.

acosReturns the radian value of the arc cosine of a number. The arc cosine is theangle whose cosine is the specified number. The returned value is from 0 topi.

float acos( float number )

number is the cosine of the angle, and must be from -1 to 1.

Example

acos(1)

Returns 0.

acos(-0.5)

Returns 2.0944 radians.

Page 226: Expressions-- Maya Expression Editor From Basic to Professional

226 Using Maya: Hypergraph, Sets & Expressions

FunctionsTrigonometric functions

acosdReturns the degree value of the arc cosine of a number. The arc cosine is theangle whose cosine is the specified number. The returned value is from 0 to180.

float acosd( float number )

number is the cosine of the angle, and must be from -1 to 1.

Example

acosd(1)

Returns 0 degrees.

acosd(-0.5)

Returns 120 degrees.

asinReturns the radian value of the arc sine of a number. The arc sine is the anglewhose sine is the specified number. The returned value is from -pi/2 to pi/2.

float asin( float number )

number is the sine of the angle, and must be from -1 to 1.

Example

asin(0.5)

Returns 0.525 radians.

asindReturns the degree value of the arc sine of a number. The arc sine is theangle whose sine is the specified number. The returned value is from -90 to90.

float asind( float number )

number is the sine of the angle, and must be from -1 to 1.

Page 227: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 227

FunctionsTrigonometric functions

Ex

pre

ss

ion

s

Example

asind(0.5))

Returns 30 degrees.

atanReturns the radian value of the arc tangent of a number. The arc tangent isthe angle whose tangent is the specified number. The returned value is from-pi/2 to pi/2.

float atan( float number )

number is the tangent of the angle and can be any value.

Example

atan(1)

Returns 0.785.

atandReturns the degree value of the arc tangent of a number. The arc tangent isthe angle whose tangent is the specified number. The returned value is from-90 to 90.

float atand( float number )

number is the tangent of the angle and can be any value.

Example

atand(1)

Returns 45 degrees.

atan2Returns the radian value of the arc tangent of specified X and Y coordinates.The arc tangent is the angle from the X-axis to a line passing through theorigin and a point with coordinates X,Y. The returned angle is in radians,from -pi to pi, excluding -pi.

float atan2( float Y, float X)

X is the X coordinate of the point.

Page 228: Expressions-- Maya Expression Editor From Basic to Professional

228 Using Maya: Hypergraph, Sets & Expressions

FunctionsTrigonometric functions

Y is the Y coordinate of the point.

Example

atan2(1,1)

Returns 0.785 radians.

atan2dReturns the degree value of the arc tangent of specified X and Y coordinates.The arc tangent is the angle from the X-axis to a line passing through theorigin and a point with coordinates X,Y. The returned angle is in degrees,from -180 to 180, excluding -180.

float atan2d( float Y, float X)

X is the X coordinate of the point.

Y is the Y coordinate of the point.

Example

atan2d(1,1)

Returns 45 degrees.

hypotReturns the magnitude of two-dimensional vector from the origin to a pointwith coordinates X, Y.

(X,Y)

hypot

X

Y

Page 229: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 229

FunctionsVector functions

Ex

pre

ss

ion

s

As shown in the preceding figure, the hypot function returns the radius of acircle whose center is at one end of a right triangle’s hypotenuse andperimeter is at the other end of the hypotenuse.

The following equation gives the magnitude of the vector:

float hypot( float x, float y)

X is the X coordinate of the point.

Y is the Y coordinate of the point.

Example

hypot(3,4)

Returns 5.

Vector functionsThe following functions do operations with vectors. The functions takevector arguments and return floating point numbers or vectors.

angleReturns the radian angle between two vectors.

float angle( vector vector1 , vector vector2 )

vector1 is one of the vectors.

x2

y2

+

Angle

Vector1

Vector2

Page 230: Expressions-- Maya Expression Editor From Basic to Professional

230 Using Maya: Hypergraph, Sets & Expressions

FunctionsVector functions

vector2 is the other vector.

The returned angle is the shortest angle between the two vectors. Themeasurement is always less than 180 degrees.

Example

angle(<<2,-1,1>>,<<1,1,2>>)

Returns 1.0472 radians, which equals 60 degrees.

crossReturns the cross product of two vectors.

For two vectors, the cross product returns the vector that’s normal to theplane defined by the two vectors.

vector cross( vector vector1 , vector vector2 )

If the cross product is 0, the two vectors are parallel or colinear. If one orboth vectors are <<0,0,0>>, the cross product returns <<0,0,0>>.

vector1 is one of the vectors.

vector2 is the other vector.

Example

cross(<<1,2,-2>>,<<3,0,1>>)

Returns <<2, -7, -6>>.

Vector1

Vector2

Cross product

Page 231: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 231

FunctionsVector functions

Ex

pre

ss

ion

s

dotReturns the floating point dot product of two vectors. The dot product takestwo vectors as arguments and returns a scalar value.

float dot( vector vector1 , vector vector2 )

If the dot product returns 0, the two vectors are perpendicular.

vector1 is one of the vectors.

vector2 is the other vector.

Example

dot(<<1,2,-2>>,<<3,0,1>>)

Returns 1. The dot product of this example is (1 * 3) + (2*0) + (-2*1), whichequals 1.

magReturns the magnitude of a vector. This is the length of the vector.

float mag( vector vector )

vector is the vector whose magnitude you want.

X-axis

Y-axis

Z-axis

Y

XZ

<<X, Y, Z>>

Magnitude

Page 232: Expressions-- Maya Expression Editor From Basic to Professional

232 Using Maya: Hypergraph, Sets & Expressions

FunctionsVector functions

The mag function converts a vector into a floating point number using thefollowing formula.

Example

mag(<<7,8,9>>)

Returns 13.928.

rotReturns a vector that represents the position of a point after it’s rotated aspecified number of radians about a specified axis. Rotation is counter-clockwise as viewed downward from the axis end position.

vector rot( vector point , vector axis , float angle )

point is the position of a point in the world coordinate system.

axis is the axis around which the point rotates. The axis is a line that passesthrough the origin and the specified axis position.

angle is the number of radians the point rotates.

x2

y2

z2

+ +

72

82

92

+ + 13.928=

Angle

Position of pointafter rotation

Position of pointbefore rotation

Axis

Page 233: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 233

FunctionsVector functions

Ex

pre

ss

ion

s

Example 1

rot(<<3,3,0>>,<<1,0,0>>,0.5)

Returns <<3, 2.633, 1.438>>. This is a vector representing the position ofpoint <<3,3,0>> after rotating it 0.5 radians around the axis represented by<<1,0,0>>.

Example 2

particleShape1.position = rot(position,<<0,1,0>>,0.1);

Suppose your scene has a single-particle object at position <<4,6,0>>, andyou wrote the above runtime expression for its particle shape node. Whenyou play the scene, the particle rotates in a circular pattern around the Y-axis(the axis represented by <<0,1,0>>).

In each frame, the particle’s position rotates 0.1 radian, roughly 5.7 degrees.

unitReturns the unit vector corresponding to a vector.

The unit vector has the same direction as the specified vector, but with amagnitude of 1.

vector unit( vector vector )

vector is the vector whose unit vector you want.

Example

unit(<<1,1,1>>)

Returns <<0.577, 0.577, 0.577>>.

Motion

Particle

Page 234: Expressions-- Maya Expression Editor From Basic to Professional

234 Using Maya: Hypergraph, Sets & Expressions

FunctionsConversion functions

Conversion functionsThe following functions convert color scheme values or anglemeasurements.

deg_to_radReturns the radian equivalent of a degree value. One radian equals roughly57.29578 degrees.

float deg_to_rad( float degrees )

degrees is the degree angle you want to convert to radians.

Example

deg_to_rad(90)

Returns 1.571, which is the same as pi/2.

rad_to_degReturns the degree equivalent of a radian value. One radian equals roughly57.29578 degrees.

float rad_to_deg( float radians )

radians is the radian angle you want to convert to degrees.

X

Y

Z

<<1, 1, 1>>

Unit vector (magnitude = 1)

<<0.577, 0.577, 0.577>>

Page 235: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 235

FunctionsConversion functions

Ex

pre

ss

ion

s

Examples

rad_to_deg(1)

Returns 57.296.

float $pi = 3.1415927;rad_to_deg($pi)

Returns 180.

hsv_to_rgbConverts an HSV vector to an RGB vector.

vector hsv_to_rgb( vector hsv )

hsv is a vector representing the hue, saturation, and value components.

Example

hsv_to_rgb(<<1,0.5,0.6>>)

Returns <<0.6, 0.3, 0.3>>.

rgb_to_hsvConverts an RGB vector to an HSV vector.

Tip

To see the relationship between HSV and RGB color components, enter theMEL command colorEditor at the Command Line. This displays the ColorChooser window.

In the window’s hexagonal color wheel, drag the pointer to a color ofinterest. The edit boxes in the window list the color’s values for hue,saturation, and value—and their counterpart red, green, and blue values.

Note, however, that the Hue value in the Color Chooser has a range of 0 to360, while the H component of an HSV vector has a correspondingproportional range of 0 to 1.

When you launch the Color Chooser by entering colorEditor, it’s useful onlyfor learning about color. You can’t use it to change the color of objects inyour scene.

Page 236: Expressions-- Maya Expression Editor From Basic to Professional

236 Using Maya: Hypergraph, Sets & Expressions

FunctionsArray functions

vector rgb_to_hsv( vector rgb )

rgb is a vector representing the red, green, and blue components.

Example

rgb_to_hsv(<<0.6,0.6, 0.6>>)

Returns <<0, 0, 0.6>>.

Array functionsThe following functions work with integer, floating point, and vector arrays.If you need more information, see a reference book on the C programminglanguage.

clearEmpties the array’s contents, freeing all memory reserved for the array.After you clear an array, its size is 0. When you no longer need to use anarray, use the clear function to free memory.

int clear( array array )

array is the name of the array you want to clear.

The clear function returns 1 if the function succeeds, 0 if it fails. The returnvalue is not typically used in expressions.

Example

int $myInts[] = {1,2,3,4,5,6};print("size of $myInts is: "+size($myInts)+"\n");clear($myInts);print("size of $myInts is: "+size($myInts)+"\n");

The third statement above clears the array $myInts.

The second and fourth statements display the following text in the ScriptEditor:

size of $myInts is: 6size of $myInts is: 0

Page 237: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 237

FunctionsArray functions

Ex

pre

ss

ion

s

sizeReturns the number of elements in an array or the number of characters in astring.

int size( array array )

int size( string string )

array is the name of the array whose size you want.

string is the string whose number of characters you want.

Example 1

string $s = "Hello";$stringlen = size($s);

The size($s) function returns 5, then the statement assigns 5 to $stringlen.

Example 2

int $myInts[] = {1,2,3,4,5,6};$numInts = size($myInts);

The size($myInts) function returns 6, then the statement assigns 6 to$numInts.

sortReturns an array sorted in alphabetical or ascending numerical order. Thereturned array has the same number and type of elements as the originalarray.

array sort( array array )

array is the name of the array to be sorted.

Example 1

int $myInts[] = {3,6,1,4,2,5};int $afterSorting[] = sort($myInts);print("After sorting, the array contains:\n");for ($i = 0; $i < 6; $i = $i + 1)

{print($afterSorting[$i]+"\n");}

Page 238: Expressions-- Maya Expression Editor From Basic to Professional

238 Using Maya: Hypergraph, Sets & Expressions

FunctionsArray functions

The sort function sorts the elements of $myInts in ascending order. Thefollowing appears in the Script Editor:

After sorting, the array contains:123456

Example 2

string $myName[] = {"Peewee","Michael","Kennedy"};string $afterSorting[] = sort($myName);print("After sorting, the array contains:\n");for ($i = 0; $i < 3; $i = $i + 1)

{print($afterSorting[$i]+"\n");}

The sort function sorts the elements of $myName in alphabetical order. Thefollowing appears in the Script Editor:

After sorting, the array contains:KennedyMichaelPeewee

Page 239: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 239

FunctionsRandom number functions

Ex

pre

ss

ion

s

Random number functionsThe following functions generate random numbers. Random numbers areuseful when you want the position, motion, or color of an object’s particlesor vertices to have a random appearance.

gaussReturns a random floating point number or vector. The number returnedfalls within a Gaussian (bell curve) distribution with mean value 0.

float gauss( float stdDev )

vector gauss( float XstdDev , float YstdDev )

vector gauss( vector stdDevVector )

stdDev specifies the value at which one standard deviation occurs along thedistribution. This gives a one-dimensional Gaussian distribution.

XstdDev and YstdDev specify the values for one standard deviation. Thisgives a two-dimensional Gaussian distribution in the XY plane. The rightcomponent of the vector returned is 0.

stdDevVector specifies the vector component values for one standarddeviation. This gives a three-dimensional distribution.

To control the random values returned by this function, see “seed” on page246.

Example

gauss(5)

Returns a random floating point value such as 0.239.

Page 240: Expressions-- Maya Expression Editor From Basic to Professional

240 Using Maya: Hypergraph, Sets & Expressions

FunctionsRandom number functions

If you were to execute gauss(5) repeatedly and chart the values returned,they would occur roughly with this frequency:

If you were to execute gauss(2) repeatedly, return values would occur withthis frequency:

Number ofoccurrences

-5 50

Value returned

One standard deviation

About 2/3 of returned values willbe within one standard deviation.

Mean

Number ofoccurrences

-2 20

Value returned

About 2/3 of returned values willbe within one standard deviation.

One standard deviation

Mean

Page 241: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 241

FunctionsRandom number functions

Ex

pre

ss

ion

s

noiseReturns a random number from -1 to 1 according to a Perlin noise fieldgenerator.

float noise( float number )

float noise( float xnum , float ynum )

float noise( vector vector )

number specifies a number that generates a random number. This gives aone-dimensional distribution of return values.

xnum and ynum specify numbers for generating a random number. Thisgives a two-dimensional distribution of return values.

vector specifies a vector for generating a random number. This gives a three-dimensional distribution of return values.

If you execute this function with the same argument value repeatedly, thefunction returns the same random value each time it executes.

If you execute this function with an argument value that steadily increasesor decreases in fine increments over time, the function returns randomvalues that increase and decrease over time.

Example 1

noise(time)

Returns a value between -1 and 1 each time the expression executes as ananimation plays. Because time increases in fine increments, the valuesreturned increase and decrease in smooth, yet random, patterns. If you wereto chart the values returned over a period of time, they might occur as in thisfigure:

noise(time) as animation plays-1

0

1Returnvalue

Page 242: Expressions-- Maya Expression Editor From Basic to Professional

242 Using Maya: Hypergraph, Sets & Expressions

FunctionsRandom number functions

Example 2

noise(frame)

Returns a value between -1 and 1 each time the expression executes as ananimation plays. Because frame increases in larger increments, the valuesreturned increase and decrease in rougher patterns. If you were to chart thevalues returned over a period of time, they might occur as in this figure:

The value returned by noise(frame) and noise(time) is the same when framecontains the same number as time. For example, when frame equals 10,noise(frame) returns the same value that noise(time) returns when time is 10.

dnoiseReturns a vector with each component containing a random number from -1to 1. It works like the noise function except it expects and returns a vectorargument. The returned vector represents the gradient of the noise field inthree dimensions.

vector dnoise( vector argument )

argument specifies a vector for generating a random number. This gives athree-dimensional distribution of return values.

See the noise function for more details on dnoise operation.

Example

dnoise(<<10,20,-30>>)

Returns <<-0.185, 0.441, 0.686>>.

noise(frame) as animation plays-1

0

1Returnvalue

Page 243: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 243

FunctionsRandom number functions

Ex

pre

ss

ion

s

randReturns a random floating point number or vector within a range of yourchoice.

float rand( float maxnumber )

float rand( float minnumber , float maxnumber )

vector rand( vector maxvector )

vector rand( vector minvector , vector maxvector )

maxnumber specifies the maximum number returned (in the first syntaxformat listed above). The minimum number returned is 0. In other words,the returned value will be a random number between 0 and maxnumber.

minnumber and maxnumber specify the minimum and maximum numbersreturned.

maxvector specifies the maximum value for each component of the vectorreturned. The minimum value is 0. Each component returned is a differentrandom number.

minvector and maxvector specify the minimum and maximum value for eachcomponent of the vector returned.

To control the random values returned by this function, see “seed” on page246.

Example 1

rand(5)

Returns a random floating point number between 0 and 5, for example,3.539.

Example 2

rand(-1,1)

Returns a random floating point number between -1 and 1, for example,0.452.

Page 244: Expressions-- Maya Expression Editor From Basic to Professional

244 Using Maya: Hypergraph, Sets & Expressions

FunctionsRandom number functions

If you were to execute rand(-1,1) repeatedly as an animation plays, its returnvalues might occur as in this figure:

Example 3

rand(<<1,1,1>>)

Returns a random vector in which each component is between 0 and 1, forexample, <<0.532, 0.984, 0.399>>.

Example 4

rand(<<1,1,1>>,<<100,200,300>>)

Returns a random vector in which the left component is between 1 and 100,the middle component is between 1 and 200, and the right component isbetween 1 and 300. An example is <<81.234, 49.095, 166.048>>.

sphrandReturns a random vector value that exists within a spherical or ellipsoidalregion of your choice. An ellipsoid is a sphere scaled along its X-, Y- or Z-axes.

vector sphrand( float radius )

vector sphrand( vector vector )

radius is the radius of a sphere in which the returned vector exists.

vector is the radius of an ellipsoid along the X-, Y-, and Z-axis.

To control the random values returned by this function, see “seed” on page246.

rand(1,-1) as animation plays-1

0

1

Returnvalue

Page 245: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 245

FunctionsRandom number functions

Ex

pre

ss

ion

s

Example 1

sphrand(1)

Returns a vector whose randomly selected coordinates reside within animaginary sphere centered at the origin and with a radius of 1. An examplereturned vector is <<0.444, -0.427, 0.764>>.

Example 2

sphrand(<<2,1,1>>)

Returns a vector whose coordinates reside within an ellipsoid centered at theorigin and with a radius of 2 along the X-axis, 1 along the Y-axis, and 1 alongthe Z-axis.

To create a particle ellipsoid:

You can use the sphrand function, for example, to create a cluster of 500particles randomly positioned within an ellipsoid having a radius of 2 in theX-axis, 1 in the Y-axis, and 1 in the Z-axis.

radius

OriginOuter boundary of returned value

1

Radius in X

Outer bound ofreturned value

2

Radius in Y

1

1

Radius in Z

Page 246: Expressions-- Maya Expression Editor From Basic to Professional

246 Using Maya: Hypergraph, Sets & Expressions

FunctionsRandom number functions

1 Select Particles→Particle Tool-❒.

2 Enter 500 for Number of Particles, and 1 for Maximum Radius.

3 Click the mouse somewhere in the workspace to position the particles.

4 Select the particle shape node of the particle object in the Expression Editor.

5 Turn on Creation.

6 Enter this expression:

position = sphrand(<<2,1,1>>);

Maya executes the expression once for each particle. It gives each particle adifferent random position around the origin within the ellipsoid specified by<<2,1,1>>.

seedSets a seed value the gauss, rand, and sphrand functions use to generaterandom numbers. If you assign a value to the seed then execute the gauss,rand, or sphrand function repeatedly, an identical sequence of randomnumbers is generated. For clarification, see the example below and“Reproducing randomness” on page 123.

int seed( int number )

number sets an arbitrary number to be used as the seed value.

Example

Suppose you create a NURBS sphere named Ball then enter this expression:

Ball.translateX = rand(5);

Page 247: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 247

FunctionsRandom number functions

Ex

pre

ss

ion

s

When you rewind the animation, Ball’s translateX attribute receives arandom value between 0 and 5, for example, 1.392. When you play theanimation, the translateX attribute receives a different random valuebetween 0 and 5 each frame.

When you rewind the animation again, the translateX attribute receives avalue that’s different from the value it received the first time you rewound,for example, 3.223.

When you play the animation again, the translateX attribute receives a valueeach frame that’s different from the values it received the first time youplayed the animation. In short, every time the rand(5) executes, it gives adifferent random value.

Suppose you change the expression to this:

if (frame == 1)seed(1);

Ball.translateX = rand(5);

Rewinding the scene to frame 1 executes the seed(1) function. It then assignstranslateX a random value between 0 and 5, for example, 4.501.

When you play the animation, the rand(5) function executes each frame andreturns a different value. Example returned values follow:

Each time you rewind and play the animation, translateX receives the samesequence of random values.

For different seed values, the sequence of numbers returned will differ. Youcan’t predict the values in the number sequence based on the value of theseed.

Frame Value

1 4.501

2 3.863

3 3.202

4 3.735

5 2.726

6 0.101

Page 248: Expressions-- Maya Expression Editor From Basic to Professional

248 Using Maya: Hypergraph, Sets & Expressions

FunctionsRandom number functions

Suppose you change the expression to this:

if (frame == 1)seed(500);

Ball.translateX = rand(5);

The rand(5) function returns these values as you rewind and play theanimation:

By changing the seed function’s value, you change the sequence of randomnumbers generated.

A common mistake while using the seed function follows:

seed(1);Ball.translateX = rand(5);

When you rewind the animation, Ball’s translateX attribute receives thevalue 4.501. When you play the animation, the translateX attribute receives4.501 each time the expression executes.

Because you assign a value (1) to the seed before each execution of rand(5),you initialize the random number sequence. The rand(5) function thereforereturns the first value of the number sequence each time it executes.

Frame Value

1 4.725

2 2.628

3 0.189

4 0.004

5 4.834

6 0.775

Important

When you set a seed value in an expression or MEL script, the seed valueaffects the rand, sphrand, and gauss functions in other expressions andMEL scripts. Such functions are affected by this seed value in all scenesyou open subsequently in the current work session.

Page 249: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 249

FunctionsCurve functions

Ex

pre

ss

ion

s

Curve functionsThe step functions let you make smooth, incrementing transitions betweenvalues.

linstepReturns a value from 0 to 1 that represents a parameter’s proportionaldistance between a minimum and maximum value. This function lets youincrease an attribute such as opacity from 0 to 1 linearly over a time range.

float linstep( float start , float end, float parameter )

start and end specifies the minimum and maximum values.

parameter is the value you want to use to generate the proportional number.

If parameter is less than start, linstep returns 0.

If parameter is greater than end, linstep returns 1.

Example

Suppose you’ve used the Particle Tool to create a collection of particlesnamed Cloud:

Suppose further you’ve added a dyamic per object opacity attribute to Cloud(see “Working with particle attributes” in Chapter 8). You then write thisruntime expression for Cloud’s particle shape node:

CloudShape1.opacity = linstep(0,5,age);

Page 250: Expressions-- Maya Expression Editor From Basic to Professional

250 Using Maya: Hypergraph, Sets & Expressions

FunctionsCurve functions

This expression increases the per object opacity attribute of CloudShape1 inequal steps from 0 to 1 for the first 5 seconds of the object’s existence.Because you created the object with the Particle Tool, the particles existencebegins in the first frame of the animation.

All particles in the object fade in from transparent to opaque for the first 5seconds of animation.

At the first frame that plays, the age of the particles is 0, so the linstepfunction returns 0 for the opacity. An opacity of 0 is transparent.

In each subsequent frame, the linstep function returns a proportionallylarger opacity value. When the age of the object reaches 5, the linstepfunction returns 1 for the opacity. An opacity of 1 is 100% opaque.

When the age exceeds 5, the linstep function returns 1. The opacity stays100% opaque. Here are some values returned for the object’s opacity:

Age Opacity

0.0417 0.0083

0.0833 0.0166

0.125 0.025

0.1667 0.0333

0.2083 0.0417

2.5 0.5

1.0 0.2

3.75 0.75

5 1

5.041 1

5.083 1

10 1

Page 251: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 251

FunctionsCurve functions

Ex

pre

ss

ion

s

As the table shows, the opacity increases in linear increments for the first 5seconds of the object’s age. At the midpoint of the specified 0 to 5 second agerange, the opacity is 0.5. At 3/4 of the way between 0 and 5 seconds, theopacity is 0.75. At 5 seconds of the object’s age, opacity is 1. After 5 seconds,the opacity stays at 1.

Suppose you edit the runtime expression as follows:

CloudShape1.opacity = linstep(5,10,age);

This increases the opacity attribute linearly from 0 to 1 as the object’s ageincreases from 5 to 10 seconds.

Suppose you edit the runtime expression as follows:

particleShape1.opacity = 1-linstep(0,5,age);

This decreases the opacity attribute linearly from 1 to 0 for the first 5 secondsof the object’s age. Subtracting linstep(0,5,age) from 1 causes the opacity tofade out rather than fade in.

0

opacity

age (in seconds)5

1

0

opacity

age (in seconds)5

1

10

Page 252: Expressions-- Maya Expression Editor From Basic to Professional

252 Using Maya: Hypergraph, Sets & Expressions

FunctionsCurve functions

smoothstepReturns a value from 0 to 1 that represents a parameter’s proportionaldistance between a minimum and maximum value. The smoothstep functionlets you increase an attribute such as opacity from 0 to 1 gradually, butnonlinearly, over a time range.

The smoothstep function works like the linstep function, except it increasesvalues more quickly near the middle values between the minimum andmaximum value. The function uses hermite interpolation between minimumand maximum values.

float smoothstep( float start , float end, float parameter )

start and end specifies the minimum and maximum values.

parameter is the value you want to use to generate the smoothstep number.

If parameter is less than start, linstep returns 0.

If parameter is greater than end, linstep returns 1.

0

opacity

age (in seconds)5

1

Page 253: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 253

FunctionsCurve functions

Ex

pre

ss

ion

s

The following figure compares values returned by smoothstep and linstepover time:

Example

Suppose you’ve used the Particle Tool to create a collection of particlesnamed Cloud:

Suppose also you’ve added a dynamic per object opacity attribute to Cloud(see “Working with particle attributes” in Chapter 8). You then write thisruntime expression for Cloud’s particle shape node:

CloudShape1.opacity = smoothstep(0,5,age);

start end

parameter

smoothstep linstep

Page 254: Expressions-- Maya Expression Editor From Basic to Professional

254 Using Maya: Hypergraph, Sets & Expressions

FunctionsCurve functions

This increases the opacity attribute of CloudShape1 in steps from 0 to 1 forthe first 5 seconds of the object’s age. This makes the object fade in fromtransparent to opaque. The fade in and fade out of the opacity occurs morequickly around 2.5, the midpoint between 0 and 5.

See the linstep function for details on similar examples.

hermiteReturns values along a hermite curve. You can use the hermite function, forinstance, to move a particle object’s position smoothly along a curve. As theexamples in the following pages show, you can create various curve shapesby altering the arguments to the hermite function.

vector hermite( vector start , vector end, vector tan1, vector tan2, float parameter )

float hermite( float start , float end, float tan1, float tan2, float parameter )

start is the start point of the curve.

end is the end point of the curve.

tan1 is the tangent vector that guides the direction and shape of the curve asit leaves the start point of the curve. The vector’s position starts at the startpoint of the curve.

tan2 is the tangent vector that guides the direction and shape of the curve asit approaches the end point of the curve. The vector’s position starts at theend point of the curve.

parameter is an floating point value between 0 and 1, for example, the valuereturned by a linstep function.

In the second format, the arguments and return values work in a singledimension.

0

opacity

age (in seconds)5

1

Page 255: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 255

FunctionsCurve functions

Ex

pre

ss

ion

s

Example 1

Suppose you create an object named dust made of one particle at the origin.To guide its motion along a short upward-bound curve for the first fourseconds of animation, you can write the following runtime expression:

dust.position = hermite(<<0,0,0>>,<<2,2,0>>,<<3,0,0>>, <<0,3,0>>, linstep(0,4,time));

When you play the animation, the particle moves from the start point<0,0,0> along a curve to the end point <2,2,0>. The tangent vector <3,0,0>sets the curve’s direction and shape as it leaves the start point. The tangentvector <0,3,0> sets the curve’s direction and shape as it approaches the endpoint.

From zero to four seconds of animation play, the particle moves along thecurve as defined by the linstep function. (See page 249 for details on linstep.)

The function arguments and resulting path of the object follow:

Example 2

Suppose you change the third argument of the previous example expressionto <<6,0,0>>:

dust.position = hermite(<<0,0,0>>,<<2,2,0>>,<<6,0,0>>, <<0,3,0>>, linstep(0,4,time));

end = <<2,2,0>>

start = <<0,0,0>> tan1 = <<3,0,0>>

tan2 = <<0,3,0>>

X

Y

Object’s path

Page 256: Expressions-- Maya Expression Editor From Basic to Professional

256 Using Maya: Hypergraph, Sets & Expressions

FunctionsCurve functions

The slope of the path curve steepens because of the longer tan1 vector:

Example 3

The following expression moves dust in an S pattern:

dust.position = hermite(<<0,0,0>>,<<2,0,0>>,<<0,3,0>>, <<0,3,0>>, linstep(0,4,time));

The tan1 vector <<0,3,0>> sets the direction of the curve from the start pointto a positive Y direction. The tan2 vector <<0,3,0>> sets the direction of thecurve to a positive Y direction as it approaches the end point.

Values between the start and end point curves are interpolated to form an Spattern.

end = <<2,2,0>>

start = <<0,0,0>> tan1 = <<6,0,0>>

tan2 = <<0,3,0>>

X

Y

Object’s path

end = <<2,0,0>>start = <<0,0,0>>

tan1 = <<0,3,0>> tan2 = <<0,3,0>>

X

Y

Page 257: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 257

FunctionsCurve functions

Ex

pre

ss

ion

s

Example 4

Suppose you change the fourth argument of the previous exampleexpression to <<0,-3,0>>:

dust.position = hermite(<<0,0,0>>,<<2,0,0>>,<<0,3,0>>, <<0,-3,0>>, linstep(0,4,time));

The dust particle moves in a pattern resembling a half-circle:

The tan1 vector <<0,3,0>> sets the direction of the curve from the start pointto a positive Y direction. The tan2 vector <<0,-3,0>> sets the direction of thecurve to a negative Y direction as it approaches the end point.

Example 5

Suppose you change the third argument of the preceding example to<<0,10,0>>:

dust.position = hermite(<<0,0,0>>,<<2,0,0>>,<<0,10,0>>, <<0,-3,0>>, linstep(0,4,time));

end = <<2,0,0>>start = <<0,0,0>>

tan1 = <<0,3,0>>

tan2 = <<0,-3,0>>

X

Y

Page 258: Expressions-- Maya Expression Editor From Basic to Professional

258 Using Maya: Hypergraph, Sets & Expressions

FunctionsCurve functions

Because of the longer tan1 vector, the slope of the path curve steepens as itrises from the start point. Because the tan2 vector has a smaller Y magnitudethan the Y magnitude of the tan1 vector, the slope of the path curve is flatteras it approaches the end point. The curve’s rise in the Y direction is greaterthan the previous example because the magnitude of tan1’s Y component islarger (10 instead of 3).

end = <<2,0,0>>start = <<0,0,0>>

tan1 = <<0,10,0>>

tan2 = <<0,-3,0>>

X

Y

Page 259: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 259

FunctionsGeneral commands

Ex

pre

ss

ion

s

General commandsThe following functions do various actions in Maya.

evalExecutes a MEL command.

string eval( string command )

command is either a command string enclosed in quote marks or a stringvariable containing a command.

The returned value contains command output returned by the command’sexecution.

Example 1

eval("select -cl")

Executes the command select -cl, which deselects all objects in the scene.Though the return value is not used in this example, it contains thecommand output.

Example 2

string $cmd = "select -cl";eval($cmd);

The first statement assigns the command string select -cl to the string variable$cmd. The second statement executes the contents of $cmd, which is thecommand select -cl.

Example 3

string $mycommand = "sphere";eval($mycommand+"-r 5");

The first statement assigns the string sphere to the variable $mycommand.The second statement appends -r 5 to the string sphere and executes thecomplete command sphere -r 5. This creates a sphere with a radius of 5 gridunits.

Page 260: Expressions-- Maya Expression Editor From Basic to Professional

260 Using Maya: Hypergraph, Sets & Expressions

FunctionsGeneral commands

Example 4

string $a[];$a = eval("ls -lights");print($a);

The first statement defines an array of strings named $a. The secondstatement executes the MEL command ls -lights, then assigns the command’soutput to array $a. The third statement displays the contents of $a to theScript Editor as follows:

ambientLightShape1directionalLightShape1

Note that each line of command output appears on a new line. Eachcommand output line is an array element. Maya formats array output witheach array element on a new line.

Example 5

Suppose you’ve created a MEL script file named bunk.mel in your Mayascripts directory and it contains this procedure:

global proc string bunk(){string $fog;

if (rand(2) < 1)$fog = "particle";

else$fog = "sphere";

return $fog;}

Further suppose you create this expression:

string $name = bunk();eval($name);print($name);

The first expression statement executes the bunk() procedure in thebunk.mel script file. In the bunk procedure, the if-else statement generates arandom floating point value between 0 and 2, then compares its value to 1.

If the value is less than 1, the statement assigns the MEL command stringparticle to $fog. If the value is greater than 1, $fog receives the commandstring sphere.

Page 261: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 261

FunctionsGeneral commands

Ex

pre

ss

ion

s

The procedure finishes executing and passes the value of $fog back to thecalling procedure, bunk() in the expression. This assigns the command stringto the variable $name.

The eval function executes the command string stored in the $name. Forexample, the statement might execute particle, which creates a particle at theorigin of the workspace.

The fourth statement displays the contents of $name, for example, particle.

The expression executes each frame and creates a new particle or sphere.

printDisplays text in the Script Editor. You can use this function to display thecontents of attributes and variables. This is helpful for debugging anexpression.

print( string text )

print( vector number )

print( float number )

print( int number )

print( array number )

text is either a string enclosed in quote marks or an attribute name or stringvariable containing text.

number is a number without the quote marks. Numerical arguments displayas strings.

There is no returned value for this function.

Note the following display considerations.

• You can format displayed text with standard C language escape characters.For example, you can create a new line with “\n” or a tab character with“\t” in the argument.

• Displaying a floating point value shows the number with up to 10 digits tothe right of the decimal point, for example 0.3333333333.

• Insignificant 0 digits are truncated from floating point numbers. Forexample, floating point number 2.0 is displayed as 2.

Page 262: Expressions-- Maya Expression Editor From Basic to Professional

262 Using Maya: Hypergraph, Sets & Expressions

FunctionsGeneral commands

• A vector appears with a space separating components and no double anglebrackets. Each vector component has a floating point value with up to 10digits to the right of the decimal point.

For example, a vector <<1.518876356, 0, -1.290387446>> appears in the ScriptEditor as this:

1.518876356 0 -1.290387446

• Arrays are formatted with each array element on a new line.

• You can use the + operator to join two strings in an argument:

"text1" + "text2"

This is displayed as:

text1text2

• You can also append a number to a string:

"text" + 1

This is displayed as:

text1

• You cannot use the + operator with a string array.

• If you assign a string to a variable that’s not a string data type, the followingtext appears if you display the variable:

As shown in the last row of the table, if a variable is assigned a string thatstarts with a nonnumerical character, Maya converts the string to 0.

• For a nonparticle expression consisting of only print statements, AlwaysEvaluate must be on in the Expression Editor for the expression to execute.

Variable data type String assignment Data displayed

float "3.14" 3.14

int "3.14" 3

vector "3.14" 3.14 0 0

float "pi is 3.14" 0, error message

Page 263: Expressions-- Maya Expression Editor From Basic to Professional

Using Maya: Hypergraph, Sets & Expressions 263

FunctionsGeneral commands

Ex

pre

ss

ion

s

Examples

print(time);print("\n");

The first statement displays the value of time. The second statement displaysa new-line character after the value of time, so the time appears on aseparate line in the Script Editor.

float $f = 3.14159;print($f);

Displays the floating point number 3.14159.

string $s = "Hello There";print($s);

Displays the string Hello There.

vector $v;$v = <<1.2,2.3,3.4>>;print($v);

Displays the vector as 1.2 2.3 3.4.

string $a[];$a = eval("ls -lights");print($a+" are the lights in my scene.\n");

The print function causes an error message because you cannot use the +operator with a string array.

systemPasses a UNIX command to the shell where you launched Maya.

int system( string command )

command is either a command string enclosed in quote marks or a stringvariable containing a command.

The returned value is the output resulting from the command’s execution.

Example

string $cmdout;$cmdout = system("date");print($cmdout+"\n");

Page 264: Expressions-- Maya Expression Editor From Basic to Professional

264 Using Maya: Hypergraph, Sets & Expressions

FunctionsOther functions and commands

Executes the UNIX date command, which outputs your workstation’s dateand time to the $cmdout variable. The final statement displays the date inthe Script Editor.

Other functions and commandsIn addition to the functions described in this chapter, you might find thefollowing less commonly used functions and administration commandshelpful. For details on usage, see the MEL online documentation.

General Math Curve String File

alias acosh besselj0 gmatch fopen

catch asinh besselj1 match fclose

chdir atanh besseljn size fflush

env constrainValue besselyn strcmp popen

error erf substitute pclose

exists erfc substring fprint

getenv expm1 tokenize frewind

getpid fmod tolower feof

gmatch gamma toupper fgetline

putenv log1p fgetword

pwd fwrite

source fread

trace filetest

warning

whatIs

Page 265: Expressions-- Maya Expression Editor From Basic to Professional

Index

Using Maya: Hypergraph, Sets & Expressions 265

Index

Symbols! 87- 63-- 92!= 65, 66$ 59, 73% 63, 182%= 92&& 67* 63*= 92+ 63++ 92+= 92/ 63// 75/= 92< 65<< >> 53, 73, 180, 193<= 65-= 92= 47, 55== 65, 66, 74> 65>= 65?: 86\n 261{ } 39, 70, 72, 73| 140|| 67

Aabbreviating attribute

names 112, 116abs function 209absolute value 209acceleration 197acceleration attribute

assigning constant valueto 156

assigning with runtimeexpression 155

changing value randomly 156field’s effect on 175initialization to zero 177working with 175

acos function 225, 226Add Attribute window 50, 120,

169Add Dynamic Attributes 49, 161Add Initial State Attribute

checkbox 163, 170adding custom attributes 119,

169age 197age of particles

at rewind 150how to examine 150runtime expression executionand 152

when created with Particletool 168

alias UNIX commandavoiding use with texteditor 109

Always Evaluate 130Always Evaluate checkbox 118amplitude of sin function 221angle function 229

angular unitsconversion of 128degrees 29, 127radians 29, 127

arc cosine 225, 226arc sine 226arc tangent 227, 228arguments in functions 205arithmetic operators 63array (per particle) attributes 163

assigning to array of differentlength 172

array functions 236array indexes

invalid assigment to 193Array option for per particle

attributes 170arrays 93

clearing contents of 236display format 262element assignment 95example initialization andusage 93

exceeding memory capacityof 93

expansion of 93invalid assignment toindexes 193

obtaining size of 237sorting 237

asin function 226assigning

to attributes 55to int or float variables 60to specific particles 189to vector attributes 56to vector components 193,194

to vector variables 61vector to three scalarattributes 56

assignment operator 47

Page 266: Expressions-- Maya Expression Editor From Basic to Professional

Index

266 Using Maya: Hypergraph, Sets & Expressions

atan function 227atan2 function 227atan2d function 228atand function 227attribute names

renaming as short names 137attributeName 197

attributesabbreviating names 112, 116assigning conditionally 32assigning to 55assigning to multiple 13, 23assigning to multipleobjects 13, 28

connecting to symbolicplaceholders 135

custom 50data types 51deleting fromexpressions 131

disconnecting fromexpressions 132

displayed in Attributes list 18displaying contents of 123displaying disconnected 132dynamic 49eliminating expression controlof 122

full name 51initial state 158, 162linking 11, 15, 26long names 114name syntax 47not selecting for particle shapenode 112

particle shape node 159per object 12, 160per particle 12, 160reading in expressions 133removing fromexpressions 131

seeing abbreviations of 113,115

static 49unexpected values 141

Attributes list 103

Bbase number raised to

exponent 215bell curve function 239betterIllumination 197blank lines in expressions 74Booleans 52

handling as floating point 65symbolic constants 95

braces 72in statements 39, 40matching pairs of 73

bracketsdouble angle 53, 73, 180, 193

break instruction 79

CC language

escape characters 261syntax in expressions 75

case sensitivity in variablenames 59

castsShadows 201ceil function 210centimeters 127Channel Box

displaying attribute valuesin 30

choice command 132circular motion of NURBS

sphere 119clamp function 211clear function 236clearing

an expression 106array contents 236

Page 267: Expressions-- Maya Expression Editor From Basic to Professional

Index

Using Maya: Hypergraph, Sets & Expressions 267

Index

collisionexample of controlling colorresulting from 185

working with particles 183color

Christmas light effect withparticles 181

giving object constantcolor 179

giving particles randomlychanging color 180

understanding RGB andHSV 235

working with 178colorAccum 197colorBlue 197colorEditor 235colorGreen 197colorRed 197comments

converting statements to 131in expressions 75

compiling an expression 19, 62,118

conditional assignment toattributes 32

conditional statements 69else-if 71if 34, 69if-else 70

confining numerical range 211connectAttr command 135connecting an attribute 135Connection Editor 132, 135conserve 197constants 62

Boolean 95continue instruction 80controlling flow in statements 77

conversionof angular units only 128of data types 143, 144of user selected units 127

conversion functions 234converting

degrees to radians 129measurement units 128statements to comments 131

copying text in expressions 105cos function 216

comparison with sinfunction 218

cosd function 218cosine 216, 217, 218cosine wave pattern

animating a ball 217count 197Create button 22Create Event 184creating new expressions 111creation expressions 148

assigning to rgbPP 179dynamics start frame 149example assignment tolifespan 165, 167

example assignment tolifespanPP 164

execution for emittedparticles 149

how often executionoccurs 148

using values in runtimeexpressions 174

when to use 150cross function 230cross product of two vectors 230curve functions 249

custom attributes 50adding to an object 119adding to particle shapenode 169

assigning to 169examples of assignment 171when to use 118

custom variables 59declaring 59using globally 61

cyclical pattern with sinfunction 220

Ddata types

attribute 53Boolean 52conversion duringassignment 143, 144

conversion of displayedstrings 262

conversion with arithmeticoperators 145

data entry limitations 54float array 52floating point 52functions 208integers 52matrix 55vector array 52

debugging expressions with printfunction 261

decimal deletion in data typeconversion 144

decimal precision in display 261declaring variables 59default object

in Expression Editor 104making an object the 115

defining variables 26deg_to_rad function 234

Page 268: Expressions-- Maya Expression Editor From Basic to Professional

Index

268 Using Maya: Hypergraph, Sets & Expressions

degrees 29converting to radians 129,234

deletingattribute names 131expressions 112, 134text from expressions 105

depthSort 197discarded remainders in data type

conversions 146disconnectAttr command 132disconnecting an attribute 132displaying

attribute contents 123disconnected attributes 132text 261variable contents 123

dnoise function 242do loop 78dollar sign ($) in variable

names 59, 73dot function 231dot product 231dot product operator 64double angle brackets 53, 73,

180, 193dynamic attributes 49

adding to object 49, 50, 161dynamic per object attribute

example assignment tolifespan 167

dynamic per particle attributeexample assignment tolifespanPP 164

dynamicschanging start frame 149how often Mayaevaluates 149, 152

Dynamics Controller 149, 152dynamicsWeight 198dynamicsWeight attribute 178

Ee raised to power 214Edit button 22editing expressions

in text field 99, 105else keyword 38else-if statements 71emitted particles

age of 149assigning lifespanPP for 183creation expression executionand 149

working with 183English common names for

attributes 114equal to (==) operator 36errors

common expression 95comparing floats with the ==operator 89

from wrong data types infunctions 208

in flow control statements 88logic 95message format of 95syntax 36, 73, 95where they appear 96

eval function 259event 198event attribute 184

when collision countincreases 187

eventCount 198eventCount attribute 184eventTest 198eventTest attribute 184examining two or more

expressions 106

executingMEL commands inexpressions 137

MEL commands with evalfunction 259

MEL procedures inexpressions 139

nonparticle expressions 118UNIX commands inexpressions 263

executionslow expression 127

exp function 214exponential functions 214Expression Editor

starting 13

Page 269: Expressions-- Maya Expression Editor From Basic to Professional

Index

Using Maya: Hypergraph, Sets & Expressions 269

Index

expressionsadvantage of separate 31advantage of single 31comments in 75common errors 95comparison with MELscripts 46

compiling 19copying text 105creating 13creating new 111creation 148default object 104deleting 112, 131deleting text in 105displaying connectedattributes only 104

editing in text field 99editing with text editor 106elements of 46, 47eliminating control ofattributes 122

erasing 106examining two or more 106execution for nonparticleshapes 118

field’s influence on 175filtering 99finding 100, 101, 102for particles 147input to 133, 135keywords 76names for particle shapenode 100

naming conventions 18output from 134, 136programming features 75redundant execution 130,154

reloading 106required elements of 48runtime 148runtime execution 152saving to file 107

slow execution of 127speeding execution of 127text field 14tutorials 15type case sensitivity 18when unusable 12

Expressions list 100, 104

Ffading opacity 249, 253fields

influence on expression 175turning off effect in anexpression 178

filtering attributesby connected attribute 104from Expression Editor 104

filtering expressions 99finding expressions

by connected attribute 101by expression name 100by item type 102by selected object 101

float 52, 57float arrays data type 52floating point 52floor function 210flow control errors 88flow control statements 77for loop 79for-in loop 81forward slashes (//) for

comments 75frame 0

reason for using inexamples 43

frame playback rate 16, 58frame variable 57frequency multiplier of sin

function 222

frequency of sin function 222full attribute name 51functions 47

arguments in 47, 205, 206array 236as expression elements 47complete list of 203conversion 234curve 249data type of arguments 206data type of returnedvalues 206

essential for advancedexpression writing 206

format of 206introduction to 203limit 209others in onlinedocumentation 264

random number 123, 239spaces in 207trigonometric 216understanding bookexamples 208

vector 229

Ggauss function 239Gaussian distribution 239General button 49general commands 259global procedures

declaring 139global variables 61

declaring 62initializing 62

goal attribute 161Goal button 161goalPP 198goalPP attribute 161

Page 270: Expressions-- Maya Expression Editor From Basic to Professional

Index

270 Using Maya: Hypergraph, Sets & Expressions

goalWeight 198gravity field

acceleration’s effect on 177

Hhalf-circle

creating motion with hermitefunction 257

hermite function 254HSV conversion to RGB 235hsv_to_rgb function 235hypot function 229

Iif statements 32, 34, 69if-else abbreviation 86if-else statements 38, 39, 70incandescence 198incandescencePP 198increment operations and

unexpected values 142inheritFactor 198initial state attributes 158, 162,

163creation expressionexecution 150

naming convention 163saving values for 158

input to expressions 135integers 52, 57

handling as floating point 65internal conversion of units 127isDynamic 198

Jjoining text in strings 262

jot text editor 107

Kkeyframes

eliminating expression touse 122

keywords in expressions 76

LlevelOfDetail 199lifespan 198lifespan attribute 161

example assignment increation expression 167

Lifespan button 161lifespanPP 199lifespanPP attribute 161, 164

assigning for emittedparticles 183

limit functions 209lineWidth 199linking attributes 11, 15, 26linstep function 249

comparison withsmoothstep 253

listAttributes MEL command 163log base 10 214log function 214logic errors 95logical operators 67

&& 67|| 67

long attribute names 114looping errors 88

Mmag function 231magnitude of a vector 67, 231mass 199matrix data type 55max function 212maxCount 199measurement units 127MEL commands 45, 46

executing with evalfunction 259

using alone instatements 137

using with eval function 138using within singlequotes 138

MEL proceduresusing in expressions 138

MEL scripts 46millimeters 128min function 212mixed data types

using with arithmeticoperators 145

modulus operator (%) 63, 182,192

risk of using with floats 182motion

creating jittery 175creating smooth, random 175

multiCount 199multiRadius 199

Nnatural logarithm 214new line characters in print

statement 261

Page 271: Expressions-- Maya Expression Editor From Basic to Professional

Index

Using Maya: Hypergraph, Sets & Expressions 271

Index

noise function 241returned values with frameargument 242

returned values with timeargument 241

normalDir 199not (!) operator 87number sequences

generating consistentlyrandom 125

numeric render type 190

Oobject names

omitting in expressions 115path of 140

Objects list 103offset with sin function 222omitting object names in

expressions 115online function

documentation 264opacity 200opacity attribute 161

fading over time 249, 253Opacity button 161opacityPP 200opacityPP attribute 161

operatorsarithmetic 48, 63assigning values to 36dot product 64equal to 36, 65greater than 65greater than or equal to 65less than 35, 65less than or equal to 65logical 48, 67not equal to 65precedence 68relational 48, 65shortcut assignment 91shortcut increment anddecrement 92

order of statements 37output from expression 134, 136oversample level 152, 156

Pparentheses

matching pairs of 73use in conditionals 68, 73

particle array attributesassigning to differentlengths 172

particle attributeslist of 196

Particle Collision Events 184particleId 200particleId attribute 189

particlesage of 150assigning to specific 189attribute data types 52expressions for 147moving position with hermitefunction 254

selecting shape node 148shape node attributes 159transform node attributes 159using sphrand to createellipsoid of 245

working with collisions 183path names of objects 140per object attributes 12, 160

keyframing 160naming conventions 160scalar option 170

per particle attributes 12, 53, 160Array option 170assigning to individualparticles 189

how to distinguish 160naming conventions 160

Perlin noise field 241playback rate 58pointSize 200position 200position attribute

assigning with creationexpression 158

assigning with runtimeexpression 157

field’s effect on 175working with 175

pow function 215precedence of operators 68precision of float display 261predefined variables 57

frame 57time 57

primaryVisibility 201

Page 272: Expressions-- Maya Expression Editor From Basic to Professional

Index

272 Using Maya: Hypergraph, Sets & Expressions

print function 261programming features 75

Rradians 29, 127

angle between twovectors 229

converting to degrees 234radius 200radius0 200radius1 200radiusPP 200rand function 140, 243rand functions 123random lifespan of particles 165random number functions 123,

239random numbers

making return valuesconsistent 124

redundant expressions 130relational operators 65reloading expressions 106removing an attribute 131renaming an object 136render type

numeric 190rewinding

effect on creationexpressions 149

unexpected values 141RGB conversion to HSV 235rgb_to_hsv function 235rgbPP 201rgbPP attribute

example use of 179rotate function 232

rotatingobject around its axis 28point’s position 232

rounding errorsfrom converting radians todegrees 208

rounding numbers 210rules of syntax 73runtime expressions 148, 153

assigning rgbPP in 181how often executionoccurs 148, 152

Ssaving an expression 107saving attribute values for initial

state 158, 188Scalar option for per object

attributes 170scale

multiplying by percentage 41slowing increase of 21, 26

Script Editorerror display 96

scripting with MEL 45scripts directory 139seed function 246

making consistent randomvalues 125

selectedOnly 201Selection list 103, 104semicolon terminator 18, 48, 73Set for All Dynamic 162Set For Current 150Set for Current 158, 162, 188shaded spheres

how rendered inexamples 154

short attribute namesrenaming as long names 137

shortcut operatorsassignment 91increment and decrement 92

sign function 212sin function 219

equation for various usesof 223

sind function 224sine 219, 224size function 237Smooth Shade All 154smooth shading

setting all objects to 16smoothly increasing opacity 250smoothstep function 252

comparison with linstep 253soft body

attributes in common withparticles 50

spacesin expressions 74in functions 207

specific particlesassigning to 189

speeding expressionexecution 127, 128

sphereshow shaded in examples 154

sphrand function 123, 140, 156,177, 244

use with random color 181spriteNum 201spriteNumPP 201spriteScaleX 201spriteScaleXPP 201spriteScaleY 201spriteScaleYPP 201spriteTwist 201spriteTwistPP 202

Page 273: Expressions-- Maya Expression Editor From Basic to Professional

Index

Using Maya: Hypergraph, Sets & Expressions 273

Index

sqrt function 215square root 215S-shaped cycle

sin function and 221S-shaped motion

creating with hermitefunction 256

standard deviationwith Gaussian values 239

starting the Expression Editor 13statements

between { } 70order of 37

static attributes 49strings 57, 90

assigning to a vector 91concatenating with + 90data type conversion 91, 262joining 262syntax rules 90

surfaceShading 202switch instruction 83symbolic placeholders 132, 134syntax

errors 36, 73, 95rules 73

system function 263

Ttab characters in expressions 74tailFade 202tailSize 202tan function 224tand function 225tangent 224, 225terminator

statement 73

text editorchanging operationsettings 110

quitting 107selecting 107selecting default startup 110using on expression 106using unlisted 109valid options 109

threshold 202time

changing 152default use of seconds 33definition 57dividing by 27multiplying by 27negative value of 59predefined variable 19relationship to frame 59value at different frames 19

Time Slidersetting start and end range 16

timesteps 156transform nodes

not used for particleexpressions 151

trigonometric functions 216trunc function 213truncating

insignificant numbers 213,261

tutorialsfor expressions 15

Uunexpected values

after incrementing 142after rewinding 141in mixed data typedivision 146

of attributes 141, 143

unit function 233unit vector 233units

internal conversion of 127,128

UNIX commandsexecuting fromexpressions 263

useLifspanPP attribute 161useLighting 202

Vvariables 56

as expression element 48assigning to vector 61data type of 57declaring 59defining 26displaying contents 123predefined 57unexpected values 143

vector functions 229vectors 57

assigning to component ofarray attribute 194

assigning to variable 193component operator 194data type 52definition 52dot product 231format in print functionoutput 262

formula for magnitude 67,231

magnitude of 2D 228random vectors withsphrand 244

velocity 202

Page 274: Expressions-- Maya Expression Editor From Basic to Professional

Index

274 Using Maya: Hypergraph, Sets & Expressions

velocity attributeassigning with creationexpression 150

assigning with runtimeexpression 153, 154

field’s effect on 175working with 175

vi text editor 107vim text editor 107visibleInReflections 201visibleInRefractions 201

Wwhile loop 77white space in expressions 74WINEDITOR setting 109, 110

Xxemacs text editor 107