Beruflich Dokumente
Kultur Dokumente
VERSION 3
Alias|Wavefront and the Alias|Wavefront logo are trademarks of Silicon Graphics, Inc. exclusively used by Alias|Wavefront, a division of Silicon Graphics Limited. Maya is a registered trademark of Silicon Graphics, Inc. exclusively used by Alias|Wavefront, a division of Silicon Graphics Limited. Graph Layout Toolkit Copyright 1992-1996 Tom Sawyer Software, Berkeley, California, All Rights Reserved. Fusion is a trademark of eyeon Software. Invigorator is a trademark of Zaxwerks. Linux is a trademark of Linus Torvalds. Red Hat is a registered trademark of Red Hat, Inc. Microsoft, Windows NT, and Windows 2000 are registered trademarks of Microsoft Corporation. SGI is a trademark, and IRIX and Silicon Graphics are registered trademarks of Silicon Graphics, Inc. UNIX is a registered trademark, licensed exclusively through X/Open Company, Ltd. All other product names mentioned are trademarks or registered trademarks of their respective holders. This document contains proprietary and condential information of Alias|Wavefront, Inc. and is protected by Federal copyright law. The contents of this document may not be disclosed to third parties, translated, copied, or duplicated in any form, in whole or in part, without the express written permission of Alias|Wavefront, Inc. The information contained in this document is subject to change without notice. Neither Alias|Wavefront, Inc. nor its employees shall be responsible for incidental or consequential damages resulting from the use of this material or liable for technical or editorial omissions made herein.
CONTENTS
1 INTRODUCING EXPRESSIONS
About expressions 2 3 1 Where you create expressions
2 QUICK START
5 5 7 13 18 29
Controlling attributes in two objects Controlling attributes conditionally Notes on the predefined time variable
3 EXPRESSION SYNTAX
Expressions and MEL
31 32 33
41
CONTENTS
Arithmetic, logic, and relational operators Arithmetic operators Relational operators Logical operators Operator precedence Conditional statements if statements if-else statements else if statements General syntax rules Comments in expressions Programming features Notes for C programmers Flow control statements Flow control errors String usage 79 80 76 63 63 64 65 57 58 59 61 63 55 56 57 50 52
50
Shortcut increment and decrement operators Boolean symbolic constants Common expression errors Error message format Common error messages 84
81
4 EDITING EXPRESSIONS
Finding expressions
CONTENTS
Finding by selected object Finding by item type Using the Selection list 92 93
91
94
Editing an expression with a text editor Choosing a text editor (Maya NT) Choosing a text editor (IRIX) 97 97
96
Using an editor not listed in the Editor menu (IRIX) Changing an editors operation settings (IRIX) Selecting an editor for default startup (IRIX) Creating a new expression Deleting an expression 102 103 103 106 106 102 101
99 100
Using attribute names in expressions Using attribute name abbreviations Omitting an object name in expressions Combining the abbreviation techniques
Reducing redundant expression execution Removing an attribute from an expression Disconnecting an attribute 125
123 124
CONTENTS
Displaying disconnected attributes in expressions Connecting an attribute to a symbolic placeholder Renaming an object 130 130
125 127
Understanding unexpected attribute values Values after rewinding Increment operations Data type conversions 136 137 138 141 142
136
6 PARTICLE EXPRESSIONS
Understanding creation expression execution Setting the dynamics start frame 143 144 Setting attributes for initial state usage Writing creation expressions 145
143
Understanding runtime expression execution Writing runtime expressions Working with particle attributes Adding dynamic attributes 154 147 153
146
Understanding per particle and per object attributes Understanding initial state attributes 156 Example of assigning to a dynamic per particle attribute Example of assigning to a dynamic per object attribute Assigning to a custom attribute 162 Assigning to a particle array attribute of different length Using creation expression values in a runtime expression Working with position, velocity, and acceleration USING MAYA: EXPRESSIONS vi 169
CONTENTS
7 FUNCTIONS
205 208
Understanding function examples in this chapter Limit functions abs ceil floor clamp min max sign trunc 212 213 214 214 215 215 216 216 217 212
212
Exponential functions exp log log10 pow sqrt 217 217 218 218 219
CONTENTS
Trigonometric functions cos cosd sin sind tan tand acos acosd asin asind atan atand atan2 atan2d hypot 219 222 222 227 228 228 229 229 230 230 230 231 231 231 232 233
219
Vector functions angle cross dot mag rot unit 233 233 234 235 236 237
Conversion functions deg_to_rad rad_to_deg hsv_to_rgb rgb_to_hsv Array functions 238 238 239 240 240
238
CONTENTS
Random number functions gauss noise dnoise rand sphrand seed 243 244 246 246 248 250 253 256 258 264
269
CONTENTS
Where do I begin?
The following paragraphs should help you decide where to start reading and learning about Maya. 1 When you install Maya Complete, Maya Unlimited, or Maya Builder, refer to one of the installation guides for guidance. For example, see Installing Maya 3.0 on Windows NT if youre installing Maya Complete or Unlimited on an NT or Windows 2000 system.
Important
In response to customer requests, weve changed the licensing procedure in Maya 3.0, Please read the installation instructions from cover to cover, even if you have installed previous versions of Maya. 2 If youve used Maya before and want an overview of new features, see Whats New in Maya 3. This booklet provides a summary of new features across all modules. Next, you may want to review the Maya 3.0 Release Notes for brief descriptions of limitations in the software and successful ways to work around them. 3 If youre a first-time Maya user, see Learning Maya for a comprehensive, step-by-step tour of the Maya software before you read any other documentation. A CD included at the back of the book contains online documentation of the tutorials as well as all required image and Maya support files. Additional copies of this book are also available from your local technical bookstore. The remaining documentation assumes that you have at least a working familiarity with Maya, so its important to start with Learning Maya.
provides a guide to Mayas user interface and basic tools. Using Maya: Essentials also defines a number of concepts that are common to all of Maya. Using Maya: Essentials was called Using Maya: Basics in previous releases. describes Maya's NURBS modeling and tells how to get the most out of it. describes how to interactively create, modify, and color polygonal models. describes the enhanced subdivision surfaces modeling tools which are available only in Maya Unlimited. tells how to use Mayas deformer, skeleton, skinning, constraint, and character features. describes Maya's basic animation software, which is based on keyframes and motion paths. This book also provides information on motion capture and introduces other Maya animation techniques, such as character setup. describes how to animate using natural forces. You can use dynamics to make effects such as tumbling dice, waving flags, and exploding fireworks. describes how to prepare for rendering, render a scene, and view your rendered images. This book also describes how to create light, shadow, and light effects, shade and texture surfaces. It also tells you how to set up cameras and views and create a background. The information in Using Maya: Rendering is arranged by production task. The online book, Maya Reference: Rendering describes Mayas renderingrelated menu options, attributes, and windows. The information in this book is organized around the user interface
Animation
Dynamics
Rendering
Paint Effects
describes how to use Paint Effects to paint real-time rendered strokes onto or between 3D objects or onto a 2D canvas. describes how to create and animate realistic clothing using Maya Unlimiteds Cloth software. This book includes four tutorials to get you started, as well as a complete users guide. describes how to use Maya Unlimited Fur to create realistic, self-shadowing fur and short hair on multi-surface models. describes how to use Live, Maya Unlimiteds automated match-moving tool. You can use Live to match Maya scenes with live footage by reconstructing 3D locations and camera or object movement from a shot.
Cloth
Fur
Live
Note
The books in the Maya Technical Library are not included in a printed document set. However, html files for these documents are on your product CD for online viewing. PDF files are also provided unless otherwise specified.
MEL
describes how to use the Maya Embedded Language (MEL) to enter commands and write scripts. includes technical descriptions of the individual MEL commands. MEL commands are provided in html format only, no PDF files are supplied.
Expressions
describes how to use expressions to control attributes. Expressions are ideal for controlling attributes that change incrementally, randomly, or rhythmically over time. They are also useful for linking attributes between different objectswhere a change to one attribute affects the other. is for technical users who want more information on the DG node attributes. The DG Node Reference is provided in html format only, no PDF files are supplied. is for technical users with programming experience who want to either edit Maya files or write translators to or from the Maya file formats. describes how to use the Maya API to load, write, and edit plug-ins. This book includes instructions for creating your own plug-ins. The Maya Developers Tool Kit also features on-line links to example plug-ins. is for people who are bringing data into Maya or exporting data to other software packages. describes how to install and use Maya game translators. Information is provided for VRML2 and GE2, as well as the RTG file format. This book also includes information on using the MDt API. describes how to use command-line and stand-alone utilities that are part of Maya, such as fcheck, as well as the options for the command line renderer. Rendering Utilities was called Utilities in previous releases.
Maya Translators
Rendering Utilities
The Glossary For 3.0, weve provided an online glossary so you can look up meanings of words you encounter which are new or confusing. Search tools Due to customer requests, weve provided an enhanced Library search tool in Maya 3.0. You can use the Library Search tool without installing the documentation files on a server. To access the Library Search tool, return to the main Maya Library page and select Library Search. A Book Search tool is also provided in the left frame of most books. Use this tool to look for an item in the book you are viewing currently. Online indexes When you are viewing a specific book, you can access that books index. You can also use the Global Index to view entries throughout the document set (except the MEL Command Reference and the DG Node Reference.)
Printed documentation conventions The printed documentation follows these conventions: MEL commands, program code, expressions, and error messages appear in courier font:
This is computer code
Items in cascading menus are identified by an arrow. For example, select Particles > Make Collide means select the Make Collide option from the Particles menu.
INTRODUCING EXPRESSIONS
Expressions are instructions you type to control attributes 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, theyre ideal for attributes that change incrementally, randomly, or rhythmically over time.
Eric Saindon
INTRODUCING EXPRESSIONS | 1
About expressions
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 backward movement of a car. This chapter has the following topics: About expressions on page 2 Where you create expressions on page 3
ABOUT EXPRESSIONS
Expressions offer an alternative to difficult keyframing tasks. In keyframing, you set the values of attributes at selected keyframes in the animation, and Maya interpolates the action between the keyframes. With expressions, you write a formula, then Maya performs the action as the animation plays. Expressions are often as simple as a few words or lines. In the following example expressions, note the variation in length and detail (rather than their 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, you dont need to be a mathematician or programmer to learn how to use them. If youre fond of programming, expressions offer unlimited animation techniques that would challenge the skill of keyframing experts.
INTRODUCING EXPRESSIONS | 1
Where you create expressions
You can use an expression to animate any keyable, unlocked object attribute for any frame range. You can also use an expression to control per particle or per object attributes. Per particle attributes control each particle of a particle object individually. Per object attributes control all particles of a particle object collectively. You cannot apply an expression to an attribute already animated with any of the following techniques: keys set driven key constraint motion path another expression any other direct connection If you do so, youll see an error message in the Script Editor and the Command Lines response area. Though you cant control a single attribute with two of the preceding techniques, you can control one attribute with keyframes, another with an expression, another with a constraint, and so on. Also, you can use a single expression to assign values to several attributes of one or more objects.
INTRODUCING EXPRESSIONS | 1
Where you create expressions
You cannot start the Expression Editor for some attributes listed in the Channel Box and Attribute Editor. Use Window > Animation Editors > Expression Editor instead, if necessary. The Expression Editor follows:
The expression text field expands as you type text, so you can write expressions of unlimited length. You can also edit expressions with an external text editor by launching it from the Editor pull-down menu above the text field.
QUICK START
The easiest way to learn about expressions is to work through examples. For this reason, we provide the following lessons aimed at beginners. Expressions that control particle attributes are more complex than for other objects. For examples, see Chapter 6, Particle Expressions.
You can use an expression to link attributes in different objectsso a change in one attribute alters the behavior of the other.
In this chapter, youll learn about the following topics: Creating a simple expression on page 7 Controlling attributes in two objects on page 13 Controlling attributes conditionally on page 18 Notes on the predefined time variable on page 29
QUICK START | 2
Preparing for the examples
To prepare for the examples: 1 Select Window > Settings/Preferences > Preferences. In the Categories list of the Preferences window, click Settings to display general application preferences. Set the Time to Film (24 fps) so your animation plays at the default rate of 24 frames per second. In the Categories list, click Timeline to display the animation timeline and playback preferences. Enter 0 and 300 for the Playback Start/End values. Also set the Animation Start/End values to 0 and 300. Specifying a range of 300 frames gives ample time to see the effects youll create in the examples.
Important
For the lessons to work correctly, you must enter 0 for the Playback and Animation Start values. (Press your Enter key as necessary.) Rewind the animation to frame 0. After doing the lessons, read Notes on the predefined time variable on page 29 if you want to know why the lessons require the starting frame to be 0. 3 4 Click the Save button in the Preferences window. At the top edge of the workspace, select Shading > Smooth Shade All to display all objects to be created with smooth shading. This will enhance the look of the objects you create in the examples. 5 6 From the menu bar, choose Window > Animation Editors > Expression Editor. 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 4 gives details on these options.
QUICK START | 2
Creating a simple expression
1 2
Make sure Ball is selected. Display the Expression Editor. The selected objects name, Ball, is highlighted in the Objects list of the Expression Editor.
Enter ScaleBallHeight in the Expression Name box. Entering an expression name lets you find the expression easily in a later if you decide to alter it. USING MAYA: EXPRESSIONS 7
QUICK START | 2
Creating a simple expression
Use alphabetical and numerical characters for expression names. If you use space characters or special characters such as a hyphen (-), Maya deletes them or replaces them with an underscore character (_) after you finish creating the expression. 4 Notice the Attributes list. It displays Balls keyable, unlocked attributesthe attributes youll most likely want to animate with an expression. Use the scroll bar to see the entire list. 5 Enter this expression in the expression text field:
Ball.scaleY = time + 1;
Use the same upper and lowercase spelling shown above. Entries in the expression field are type case sensitive. The semicolon (;) signifies the end of the expression statement. Each statement in an expression must end with a semicolon. The only exception is when the expression has a single statement. An error message appears in the Script Editor and Command Lines response area if the expression has incorrect syntax or typing mistakes. Edit text the same way you edit other text fields in Maya. 6 Click Create to compile the expression. Compiling the expression checks it for syntax errors and converts it to a form Maya can execute when you rewind or play the animation. Clicking this button also executes the expression for the current frame.
QUICK START | 2
Creating a simple expression
The expression sets Balls scaleY attribute to the value of time + 1. Ball.scaleY is the full name of the attribute. A period separates the name of the object and attribute. You must spell them with uppercase and lowercase letters as they appear in the Expression Editors Objects and Attributes lists. See Using attribute names in expressions in Chapter 4 for more details. The word time is a predefined variable in Maya that updates as an animation plays. It contains the elapsed number of seconds from the first frame to the current frame. The value increases with the increasing frame number. At the default animation playback rate of 24 frames per second, time has these values, rounded to four decimal places:
Frame 0 1 2 3 24 240
If you need to change the playback rate, you can do so by choosing Window > Settings/Preferences > Preferences. In the Categories list, click Settings to display general application preferences. Choose a rate from the Time menu. Regardless of which animation playback rate you choose, you can find the time elapsed in the animation at any frame by calculating this formula with a desktop calculator:
QUICK START | 2
Creating a simple expression
For example, if the frame rate is 24 frames/second and the animation is at frame 1, the elapsed time is 1 divided by 24, or 0.0417. At frame 6, the elapsed 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, the elapsed time is 1 divided by 30, which equals 0.0333. At frame 6, elapsed time is 6 divided by 30, which equals 0.2. To see the result of the expression: 1 Rewind and play the animation. Balls scaleY attribute increases as the time increases:
Frame 0 1 2 3 24 240
Maya executes the expression each frame. This causes the object size to scale along its Y-axis, stretching its height during playback.
QUICK START | 2
Creating a simple expression
The scaling is smooth because the geometry stretches in synch with the small time increments of the animation playback. 2 Stop and rewind the animation. Rewinding the animation returns Ball to its original shape. This occurs because the expression executes with time equal to 0. The value of time + 1 is 1, the original scaleY value of Ball. 3 Close the Expression Editor window. This complete the steps to creating an expression. To edit the expression: Suppose you decide that Ball scales too quickly as the animation plays. You can change the expression to see how the animation looks when you scale Ball half as fast. 1 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 the expression examining each expression in the scene thats controlled by an expression
QUICK START | 2
Creating a simple expression
In this example, youll find the expression ScaleBallHeight by its name. See Chapter 4, Editing Expressions for details on the other methods. 2 3 Choose Select Filter > By Expression Name. Click ScaleBallHeight in the Expressions list. The expression appears in the expression text field.
Ball.scaleY = time + 1;
By dividing time by 2, youll make the Y scaling increase half as fast as with the previous version of the expression. 5 Click Edit to compile the modified expression. Clicking the Edit button does the same action as clicking the Create button. The Create button exists only for new expressions. The Edit button replaces the Create button when you display an existing expression. 6 7 Play the animation to see the results of the new expression. Stop and rewind the animation. To control multiple attributes of an object: You can use an expression to control two or more attributes of an object as in this example:
Ball.scaleX = time + 1; Ball.scaleY = time + 2; Ball.scaleZ = time + 5;
Maya scales the Ball at different rates for the X, Y, and Z dimensions. USING MAYA: EXPRESSIONS 12
QUICK START | 2
Controlling attributes in two objects
To link multiple attributes of the same object: You can use an expression to link the value of one attribute to another as in this example:
Ball.scaleX = time + 1; Ball.scaleY = Ball.scaleX; Ball.scaleZ = Ball.scaleX;
The second statement sets Ball.scaleY to the value of Ball.scaleX. Because youve set Ball.scaleX to the value of time + 1, Ball.scaleY also has the value of time + 1. Youre linking one attributes value to another. The third statement also sets Ball.scaleZ to the value of the attribute Ball.scaleX. The advantage of this expression is that if you assign a different value to Ball.scaleX in the first statement, the second and third statements automatically receive the new value. This concludes the first example. Before starting the next example, create a new scene. Summary In this lesson, you learned how to: name an expression and type it in the expression text field compile an expression to a form Maya can execute work with the predefined variable time find an expression you previously created modify an expression control multiple attributes of an object link multiple attributes of the same object with a single expression
QUICK START | 2
Controlling attributes in two objects
Tip
To see an objects local rotation axes, select the object, then choose Display > Component Display > Local Rotation Axes. To prepare the scene: 1 2 3 Create a default NURBS Cone and name it Cone Create a default NURBS Cylinder and name it Can. Move Cone and Can into roughly the positions shown in the preceding figure. The exact translation and scale of Cone and Can is unimportant for this example. 4 5 Display the Expression Editor and make sure youve turned on Select Filter > By Object/Attribute Name. Rewind the animation to frame 0. To create the expression: 1 Select Can. To control attributes in both objects, you can select either object to write the expression. In fact, any object or node in a scene can be selected when you write an expression to control an object other than a particle object. For details on creating expressions to control particles, see Chapter 6, Particle Expressions.
QUICK START | 2
Controlling attributes in two objects
In the Expression Editor, enter RotCanAndCone in the Expression Name box. This names the expression so you can find it easily later, if necessary.
This assigns Cans rotateX attribute and Cones rotateX attribute to the value of 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 from time * 10. After 1 second, for example, the rotateX attribute of each object is one degree times 10, or 10 degrees. After 2 seconds, its 2 degrees times 10, or 20 degrees. Maya works in degree angle units, by default. If you want to change the angular units to radians, select Window > Settings/Preferences > Preferences to display the Preferences window. Click the Settings category, then select radians from the Angular menu. With the animation playing at 24 frames per second, each objects rotateX attribute has these values:
QUICK START | 2
Controlling attributes in two objects
Frame 0 1 2 3 24 240
The values in this chapter are rounded to four significant digits. The actual values 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. The Channel Box updates its values after you stop the animation. To see the degree value of Cone.rotateX at different frames, select Cone instead 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 the expression to this:
Can.rotateX = time * 5; Cone.rotateX = time * 10;
2 3
Click Edit to compile the expression. Play the animation. Can rotates half as fast as Cone as the animation plays.
QUICK START | 2
Controlling attributes in two objects
4 5
Stop and rewind the animation. Close the Expression Editor window. This concludes the example. This example showed how to write a single expression to control attributes of 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 youll have two expression names, each presumably named after the object and attribute youre controlling. Having two expression names makes it easier to find the expression that controls the desired attribute. The advantage of using a single expression to control the attributes is that all statements are in a single expression. You dont need to edit two expressions.
Before starting the next example, 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
QUICK START | 2
Controlling attributes conditionally
To prepare the scene: 1 Select Create > NURBS Primitives > Sphere. By default, this creates a NURBS sphere at the origin with an X scale, Y scale, and Z scale of 1. 2 3 4 In the Channel Box, name the sphere Balloon. Display the Expression Editor and make sure youve turned on Select Filter > By Object/Attribute Name. Rewind the animation to frame 0. To create the expression: 1 2 3 Select Balloon. In the Expression Editor, enter RisingBalloon in the Expression Name box. Enter this expression:
if (time < 2) Balloon.scaleY = time;
This expression is an if statement. The if keyword causes the expression to make 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.
QUICK START | 2
Controlling attributes conditionally
Important
When you compare the value of time to a number in an expression, Maya interprets time as seconds rather than milliseconds, minutes, or any other unit of time. In the example, Maya interprets 2 as 2 seconds. The expression checks whether the value of time is less than two seconds. If so, it does the assignment Balloon.scaleY = time. If time is not less than two seconds, the assignment doesnt occur. Notice the indentation of Balloon.scaleY = time under if (time < 2). Maya ignores all indentation, extra spaces, and blank lines between statements. We used the indentation to make the expression easier to read. You could have also written the expression as follows:
if (time < 2) Balloon.scaleY = time;
This isnt as easy to read. Consistent, organized spacing is a good habit to develop. 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 the animation 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 Balloons scale increases along its Y-axis. It inflates as the animation plays.
QUICK START | 2
Controlling attributes conditionally
At 2 seconds, Balloon stops inflating. An expression executes each frame as an animation plays. The if statement sets the scaleY attribute of Balloon to the 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 statement that follows it, Balloon.scaleY = time, no longer executes. The value of the scaleY attribute stays at the last value it had before time became 2, specifically, 1.9583. At 2 seconds of animation time and every moment thereafter, 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:
Frame 0 1 2 3 24 47 48 49
QUICK START | 2
Controlling attributes conditionally
The if statements condition, (time < 2), is a comparison. The condition must be surrounded by parentheses to isolate it from assignment that follows it. The < in the condition is a relational operator. A relational operator tests how one value relates to another. In the example, the < tested whether time is less than 2. Besides the < operator shown in this example, there are several other relational operators such as >, >=, ==, and so on. See Arithmetic, logic, and relational operators in Chapter 3. 6 Stop and rewind the animation. Balloon flattens again because the scaleY attribute becomes 0 when you rewind the animation. Time is 0, so scaleY is 0. You can make Balloon rise after it inflates by adding a second if statement to the 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 3
Click Edit to compile the expression. Play the animation. Balloon inflates for 2 seconds. After 2 seconds, Balloon stops inflating and its position skips from a Y-axis position of 0 to 2. Youll eliminate the motion skip in a later step. The second if statement increases the translateY position of Balloon after the animation time rises above two seconds. The >= symbols mean greater than or equal to. Whenever time is greater than or equal to 2, the expression assigns Balloons translateY the value of time. The translateY value therefore increases for the rest of your animations playback range. Notice that a semicolon ends each statement. Forgetting a semicolon after each statement causes a syntax error, and the changes youve made to the expression wont take effect.
QUICK START | 2
Controlling attributes conditionally
Important
Always examine the Script Editor for error messages after you edit an expression and click the Create button. If you alter a previously successful expression and a syntax error occurs, Maya executes the previous successful expression when you play the animation. This might make you believe your editing changes took effect. Error messages are preceding by the text // Error:. 4 Stop and rewind the animation. Balloon flattens but doesnt return to the origin. (If Balloon has risen out of view, adjust your camera to see it.)
Balloon doesnt return to the origin because the expression doesnt assign Balloon 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;
QUICK START | 2
Controlling attributes conditionally
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. 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 in the order listed. In this example, the statements work independently, so their order doesnt matter. We put the statements in the order of time execution because its easier to see the logic of the expression. If you ever need to change the expression, youll be able to grasp the expressions actions more quickly. 6 7 Click Edit. Stop and rewind the animation again. The flattened Balloon returns to its correct position at the origin.
Play the animation. Balloon inflates for two seconds, then rises. As mentioned before, Balloon skips from Y-axis position 0 to 2 after two seconds of animation play. You can eliminate the skipping and make Balloon rise smoothly from the origin. To eliminate the motion skip:
1 2
QUICK START | 2
Controlling attributes conditionally
3 4
Click Edit. Play the animation. Balloon inflates for 2 seconds, then rises slowly with time from its position at the origin. When time is greater than or equal to 2, the translateY position of Balloon becomes 2 minus 2, which is 0. As time increases beyond 2 seconds, the translateY position increases in the same increments that time increases.
Stop and rewind the animation. The expression achieved the desired result, but its more complicated than necessary. You can use an if-else statement to make the statement more compact and easier to read. To use an else statement instead of multiple if statements:
2 3
QUICK START | 2
Controlling attributes conditionally
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 time is 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 to time minus two. At any instant in the animations playback, either Balloon.scaleY = time executes or Balloon.translateY = time - 2 executes. Under no circumstances can they both execute. The else statement executes only when the if condition that precedes it is false. Note that we added a blank line between the first if statement and the if-else statement 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 the if-else statements. Using else statements instead of multiple if statements makes an expression simpler to read. If you use an if-else construction instead of a lengthy list of if statements, youll also improve the execution speed of the expression. This improves your animations 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 if statements 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; } else Balloon.translateY = time - 2;
QUICK START | 2
Controlling attributes conditionally
if (time == 0) Balloon.translateY = 0;
In its place, we put the statement Balloon.scaleY = time in a segment enclosed by the braces { and }. Maya evaluates both the statements between the braces if the condition (time < 2) is true. 2 3 Click Edit. 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 set Balloon.scaleY to time, it sets Balloon.translateY to 0. Balloon has a position at 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 makes the expression easier to read and comprehend. As in the previous version of the expression, if time is greater than or equal to 2, Maya executes the else statement. Note that you can put multiple statements between braces for an else statement, just as you do for an if statement. 4 Stop and rewind the animation. You can further refine the animations appearance by expanding Balloon more slowly. To slow Balloons expansion: 1 Change the expression to this:
if (time < 2) { Balloon.translateY = 0; Balloon.scaleY = time * 0.6; } else Balloon.translateY = time - 2;
Only one statement is different, Balloon.scaleY = time * 0.6. The asterisk (*) multiplies time by 0.6. 2 Click Edit.
QUICK START | 2
Controlling attributes conditionally
The scaleY attribute increases at 60% of the value of time, so Balloon expands slower during playback. (The number 0.6 equals 60%.) By the time Balloon 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 dont. 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 Balloons appearance by eliminating the flattened Balloon that appears at the origin when you rewind the animation. You can also scale Balloon at different rates along each of its three axes. To further refine Balloons 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; } else Balloon.translateY = time - 2;
Click Edit. Balloon disappears from view because its scale attributes are 0.
QUICK START | 2
Controlling attributes conditionally
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. As time increases, the value of Balloons scale attributes increase. Because the expression sets scaleX and scaleZ to 50% of the value of time, these dimensions 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 many real balloons.
Stop and rewind the animation. This concludes the example. Summary Using an expression is a combination of logic and experimentation. Problem solving starts with breaking a task into smaller problems you can solve and later 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
QUICK START | 2
Notes on the predefined time variable
use an if-else statement in place of multiple if statements to make an expression easier to read and comprehend refine an expression with a combination of analysis and experimentation In the preceding examples we didnt include comments in expressions because we explained them line by line. When you write your own expressions, include comments with statements to help document how the expression works. This will help you or someone else understand how your expression works later if the need to enhance it arises. See Comments in expressions in Chapter 3.
If you rewind the animation, the expression executes and sets the initial value of Balls scaleY attribute to time + 1, which equals 0.0417 + 1, or 1.0417. Because Balls scaleY attribute was 1 when you created it, rewinding the animation sets scaleY to a value 0.0417 larger than its initial value. This discrepancy means the Ball scaleY is larger than its scaleX and scaleZ attributes in the first frame of the animation. Though the difference is not substantial 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 Balls scaleY value to (0.0417 - 0.0417) + 1. This equals 1, its original scaleY value.
QUICK START | 2
Notes on the predefined time variable
When you use the predefined time variable, be aware of the starting frame number and the associated time value. After doing the lessons in this chapter, remember to change your Time Sliders starting frame, ending frame, and frame rate to the desired values when you start other projects. To do this, use Window > Settings/ Preferences > Preferences.
EXPRESSION SYNTAX
Expressions use the syntax of the Maya Embedded Language (MEL). Though MEL is a scripting language, youll find the syntax easy to learn even if youve never programmed. Mastering the rules of syntax is essential to writing expressions without errors.
You can use an expression to rotate each child joint based on the root joints keyframed rotation.
This chapter describes the following topics: Expressions and MEL on page 32 Elements of an expression on page 33 Attributes on page 35 Variables on page 43 Constants on page 49 Arithmetic, logic, and relational operators on page 50 Operator precedence on page 56 Conditional statements on page 57 USING MAYA: EXPRESSIONS 31
EXPRESSION SYNTAX | 3
Expressions and MEL
General syntax rules on page 60 Comments in expressions on page 62 Programming features on page 63 Common expression errors on page 83
Typical use Does one action Does several actions Animates attribute values as an animation plays
EXPRESSION SYNTAX | 3
Elements of an expression
The following pages describe expression syntax elements such as arithmetic operators you can use to set and compare attributes. If you have trouble understanding the syntax descriptions, refer to a C programming guide for beginners. Except for attribute names, the syntax elements have the same definitions as their counterparts in C. Attribute names do not exist in C. If youre familiar with a programming language such as C, Pascal, or Basic, be sure to see Programming features on page 63.
ELEMENTS OF AN EXPRESSION
An expression is made of one or more statements. Statements follow the rules of algebra, so theyll seem familiar if youve studied math. Each statement has several elements as in the following example:
Assignment operator Arithmetic operator Attribute name Function Constant Terminator
The name of the attribute set by the statement. In the example, Ball.rotateZ is the attribute name of the rotateZ attribute of an object named Ball. 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 the statement sin(time) + 6. (Ignore what this assignment does; its for illustration only.) You can also use = to assign a value to a variable. A special word that you provide with an entry called an argument. In this example, the argument is time. Based on the value of the argument, Maya does a calculation for the function and returns a new value or takes some other action.
Function
EXPRESSION SYNTAX | 3
Elements of an expression
In the example, the function sin(time) returns the sine of the value of time, which evaluates to a number between -1 and 1. Maya has many convenient built-in functions and commands that do math calculations, conversions, and so on. See Chapter 7 for details.
Variable
A variable is a symbolic name that stands for a changing value. You can assign a value to a variable or read a variables value. The variable time is a predefined Maya variable that contains the animation time at the current frame. You can read but not set the value of time.
An operation such as + or < (less than). An unchanging number, for example, 6.1 or 90. A semicolon (;) that marks the end of a statement. An expression 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 Heres an expression with the fewest elements possible: Ball.scaleY = 5;
Value assigned
Ball.scaleY = 5;
EXPRESSION SYNTAX | 3
Attributes
The expression has an attribute, assignment operator (=), value assigned to the attribute, and a statement terminator (;). The expression sets Balls Y scale to 5 grid units. When you play the animation, Balls Y scale stays fixed at 5 regardless of the Y scale value you gave it when you created it.
ATTRIBUTES
An attribute is a characteristic of an object or other item in a scene. There are many ways to set attributes in Mayawith the Attribute Editor, Channel Box, menu selections, and of course, expressions. You can set attributes to control 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 standard attributes Maya provides for objects and items that make up a scene. Custom attributes are attributes you define for an object.
Static attributes
Static attributes are attributes an object has by default. They exist the moment you create the object and throughout its lifetime. For example, the transform node of a NURBS sphere has static attributes scaleX, scaleY, scaleZ, rotateX, and so on. You can set the values of these attributes with the Attribute Editor, Channel Box, expressions, and other techniques after you create the object.
Dynamic attributes
Dynamic attributes have predefined names and purposes, but Maya adds them to an object in response to your user interface selections. For example, suppose you create a particle object and display its particle shape folder in the Attribute Editor. If you click Opacity or Color in the Add Dynamic Attributes section of the Attribute Editor, Maya lets you add a dynamic attribute to the node.
EXPRESSION SYNTAX | 3
Attributes
Clicking the General button lets you add a custom attribute (see the next topic). An object has no dynamic attributes unless your actions cause Maya to add them to the object. By adding only required attributes, Maya runs faster. When you add a dynamic attribute to an object, the attribute appears in the Attribute editor for the selected object or node.
Note
Because soft body geometry is a particle shape node coupled with geometry, a soft body has the same static and dynamic attributes as a particle object.
Custom attributes
Custom attributes are attributes you optionally add from the New folder of the Add Attribute window.
EXPRESSION SYNTAX | 3
Attributes
Such attributes have no direct effect on any characteristic of an object. Theyre often used to control a combination of other attributes. You might also use a custom attribute as a variablea place to store a value temporarily to be read by other attributes. When you add a custom attribute to an object, it appears in the Attribute Editor and Channel Box for the object or node. Though custom attributes are dynamically added to an object, we refer to them as custom to distinguish them from the built-in dynamic attributes. See Assigning to a custom attribute in Chapter 6 for details on how to add and use a custom attribute.
Attribute names
Static, dynamic, and custom attributes follow the same naming conventions and represent the same types of data.
EXPRESSION SYNTAX | 3
Attributes
A full attribute name has this format: object.attribute where object is the name of the object node, and attribute is the name of the attribute. A period (.) separates the name of the object and attribute. You must spell the object and attribute name with uppercase and lowercase letters as they appear in the Expression Editors Objects and Attributes lists. You cannot spell attribute names with the common English spellings shown in the Attribute Editor or by default in the Channel Box. See Using attribute names in expressions in Chapter 4 for more details. Example
Ball.scaleY
The most common attribute data type is floating point. In mathematics, floating point numbers are also called real numbers. Often, such numbers have a decimal point. Booleans are also common data types in attributes. Integer data types are rarely used. Particle shape nodes have these additional attribute data types:
EXPRESSION SYNTAX | 3
Attributes
Example data <<3.2, 7.7, 9.1>> <<4.5, 9.2, 3.1>> <<3.8, 4.4, 2.1>> 1.333 1.666 2.333 1.333
FireShape.lifespan
Note
Scientists often refer to a vector as a quantity that specifies both a magnitude and direction. In Maya, a vector is simply a related group of three floating point numbers that set an attribute or variable. 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 other particle attributes that have a single number value. Attributes having a vector array or float array data type are also called per particle attributes. See Chapter 6 for details on working with particle attributes. If you have programming experience, note that for vector array data types, Maya represents the specified attribute for each particle of the object with a single element of an array. Each element is made of three floating point numbers. In a float array, Maya represents the specified attribute for each particle with a vector array element thats a floating point number.
EXPRESSION SYNTAX | 3
Attributes
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.
A Boolean attribute has a checkbox or other user interface item for turning it on or off. A floating point attribute shows a value that includes a decimal point. Most numerical attributes in Maya are floating point. An integer attribute has no decimal point. Integer attributes are rare in Maya. The data type of an attribute limits what type of value you can enter for the attribute in the Attribute Editor and in expressions. For example, if an attribute is an integer, you cannot enter a decimal point in its text entry box or when you assign it a value in an expression. For a floating point attribute, you can omit the decimal point. The Attribute Editor automatically inserts a decimal point in the attributes text field after you press the Enter key. For example, if you type 3 for a floating point entry, the Attribute Editor replaces 3 with 3.0000.
EXPRESSION SYNTAX | 3
Attributes
An expression also automatically converts an integer to a floating point value when appropriate. See Data type conversions in Chapter 5 for details. Only particle objects, not geometric objects, have vector array and float array attributes. The static vector array attributes for particle objects are position, velocity, and acceleration. These are also called per particle attributes because you can set the attribute for each particle to different values. Maya has other attribute data types that are irrelevant to the use of expressions. For example, Maya has a matrix data type that is useful only in MEL scripting and API programming.
Note
For rigid bodies, you can read but not write the velocity, angularVelocity, and force attributes.
EXPRESSION SYNTAX | 3
Attributes
This assigns the value of time to the floating point translateY attribute of Ball.
Ball.scaleX = Ball.scaleY = Ball.scaleZ = 2;
This assigns 2 to the floating point scaleX, scaleY, and scaleZ attributes of Ball. As the example shows, you can use an assignment operator several times in a statement to set multiple attributes to the same value.
EXPRESSION SYNTAX | 3
Variables
Examples Use:
cone1.tx = 1.5;
Avoid:
setAttr cone1.tx 1.5;
Use:
cone1.tx = sphere1.tx;
Avoid:
cone1.tx = getAttr sphere1.tx;
VARIABLES
A 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 are variables you can create to store data in an expression. Keep in mind that attributes, not variables, set object and component behavior in Maya. You can use variables to as temporary storage for working with the attributes.
EXPRESSION SYNTAX | 3
Variables
Meaning
Examples
floating point numbers signed whole numbers vector made of three floating point numbers one or more characters
392.6, -0.667 10, -5, 0 <<3.2, 7.7, 9.1>> Whats up, chief?
The most common data type of variables is floating point. Integer data types are rarely used. Booleans are commonly used in attributes, but not allowed in variables. Vector variables are useful in expressions for particle shape attributes. Animators with programming experience sometimes use string variables. Quote marks (" ") are required with strings. See String usage on page 77 for details. For a custom variable you create in an expression, you must declare the data type as described in Custom variables on page 46.
Predefined variables
Maya maintains values in two predefined variables as an animation plays:
Contents number of frames the animation has played time in seconds the animation has played
EXPRESSION SYNTAX | 3
Variables
Your expressions can read, but not set, the value of time and frame. These variables are floating point values that are useful for animating an attribute as an animation plays. The time updates as an animation plays. It contains the elapsed number of seconds from the first frame to the current frame. The value increases with the increasing frame number. At the default animation playback rate of 24 frames per second, time has these values, rounded to four decimal places:
Frame 0 1 2 3 24 240
If you need to change the playback rate, you can do so by choosing Window > Settings/Preferences > Preferences. In the Categories list, click Settings to display general application preferences. Choose a rate from the Time menu. Regardless of which animation playback rate you choose, you can find the time elapsed in the animation at any frame with this formula:
EXPRESSION SYNTAX | 3
Variables
If the frame rate is 30 frames/second and the animation is at frame 1, the elapsed time is 1 divided by 30, which equals 0.0333. At frame 6, elapsed time is 6 divided by 30, which equals 0.2. Theres an advantage to writing an expression using the value of time rather than frame: You wont need to modify your expression if you change your animations frame rate. Note that time is always 0 at frame 0. As each frame plays, the time increases in increments resulting from the frame rate. Its impossible to set time to a value other than 0 at frame 0. If you set Mayas frame range to begin at a negative number, time has a negative value. Examples
Ball.translateY = time/2;
This sets the Balls Y translation equal to the value of time divided by 2 as the animation plays. This make the Ball move in a Y direction as the animation time increases.
Ball.scaleY = frame/2;
This sets the Balls Y scale equal to the value of frame divided by 2 as the animation plays. The Ball scales along its Y axis as the animation frame number increases.
Custom variables
You can declare and use variables to store a constant or changing value. These work like their counterparts in programming languages and spreadsheet programs. Though programming languages use such variables abundantly, you might not need to use them at all in many expressions.
Declaring variables
Each custom variable name must begin with a dollar sign character ($). After the $, you can use alphabetical, numerical, and underscore characters. You cannot include spaces in the names. Variable names are type case sensitive. In other words, $temp is a different variable name than $Temp. USING MAYA: EXPRESSIONS 46
EXPRESSION SYNTAX | 3
Variables
Examples
float $object_height;
This declares a floating point variable named $counter and gives it an initial value of 5.3.
$height = 6;
This declares a floating point variable named $height and gives it an initial value of 6. This example shows you can skip declaring the variables data type. When you assign a variable a value, Maya assumes the variable is floating 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 another variable. The first statement assigns 3.1415927 to $pi. The second statement assigns the contents of $pi, 3.1415927, to $twist.
EXPRESSION SYNTAX | 3
Variables
Important
If you misspell an existing declared variable name and assign it a value, a syntax error wont be generated for the undeclared variable. Because Maya automatically provides a data type for an undeclared variable if its on the left side of the assignment operator, the misspelled variable will be interpreted as a newly added variable. Undeclared variables on the right side of the assignment operator do generate error messages. Check spellings of variables if your expression isnt working as expected. In the following example, the misspelling in the final statement generates an error but not the misspelling in the statement before it:
int $start; int $end; int $interrupt; $starrrt = 1; $end = $interrupppt;
You can thereafter set or read the value of this variable in any other expression in the scene.
EXPRESSION SYNTAX | 3
Constants
If you create a variable with the same name in two expressions, the two variables are separate and unrelated. For example, suppose you create a variable named $timer in two expressions. Assigning a value to one of the $timer variables has no effect on the others value. If you declare and initialize a global variable in a single statement, you can initialize it to a numerical constant or string only. Examples
global float $counter = 3;
This causes an error because time is a variable. If you declare and initialize a global variable in a single statement, the statement executes only when Maya compiles the expression. Maya compiles an expression when you click the Create or Edit button in the Expression Editor, or when you open a scene containing a previously created expression. 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.
CONSTANTS
A constant is an unchanging number or variable. Examples
Ball.translateY = 6.1.
EXPRESSION SYNTAX | 3
Arithmetic, logic, and relational operators
This statement sets Balls translateY attribute to the constant number 6.1.
float $pi = 3.1415927; Ball.rotateY = $pi;
These statements set the value of Balls rotateY attribute to the value of the variable $pi. The variable $pi represents the constant 3.1415927.
Arithmetic operators
Symbol + * / % Meaning plus minus or negation for integers and floats: multiply for vectors: dot product divided by remainder of division Used with these data types integer, float, vector, string integer, float, vector integer, float, vector integer, float integer, float
EXPRESSION SYNTAX | 3
Arithmetic, logic, and relational operators
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 time alone.
Car.translateX = 7 % 3;
This assigns Car.translateX the value 1, the remainder of 7 divided by 3. The number 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;
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.
Vectors
For operations between vector attributes and variables, the * operator performs the dot product. The dot product multiplies corresponding components of each vector, then adds the components to create a single floating point number result. For + and - operators, each component of one vector is operated on by its counterpart 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 point number. Examples Suppose youve 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 in sequential order):
$C = $A + $B;
EXPRESSION SYNTAX | 3
Arithmetic, logic, and relational operators
$C = $B - $A;
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 is multiplied by 3 to create a vector result.
Strings
For details on how to use the + operator with strings, see String usage on page 77.
Note
Maya handles integer and Boolean attributes in an expression mathematically 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 and you display the attributes contents in the Script Editor, youll see floating point values. After the expression executes, Maya assigns an appropriate integer or Boolean value to the attributes you set in the expression text field. Maya handles integer and Boolean variables within an expression mathematically as integer and Boolean data types.
Relational operators
Youll often use relational operators to compare the value of variables and attributes in conditional statements. See Conditional statements on page 57.
Symbol <
EXPRESSION SYNTAX | 3
Arithmetic, logic, and relational operators
Meaning greater than equal to not equal to greater than or equal to less than or equal to
Used with these data types integer, float, vector integer, float, vector integer, float, vector integer, float, vector integer, float, vector
When the animation time is greater than 10 seconds of play, the expression sets the Spheres translateX attribute to 3. It stays fixed in this position thereafter. See Conditional statements on page 57 for details on the if condition in this and following examples.
if (Ball.scaleY == 3) Cone.scaleY = 6;
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 to Ball.scaleY. Maya evaluates the assignment statement Ball.scaleY = 3 as a true condition, so it executes Cone.scaleY = 6. This statement doesnt cause an error message, but it gives unintended results.
EXPRESSION SYNTAX | 3
Arithmetic, logic, and relational operators
Vectors
If 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 vectors magnitude:
2 2 2
x +y +z
The x, y, and z numbers in the formula represent the three components of the vector. Examples
vector $A = <<1,2,3>>; vector $B = <<1,2,3>>; if ($A == $B) Sphere.translateX = 3;
This expression sets Spheres translateX attribute to 3, because vector $A is equal to $B. $As left component, 1, is compared to $Bs left component, also 1. $As 2 is compared to $Bs 2, and $As 3 is compared $Bs 3.
vector $A = <<0,4,0>>; vector $B = <<1,0,0>>; if ($A > $B) Sphere.translateX = 3;
This expression sets Spheres translateX attribute to 3, because the magnitude of vector $A is greater than vector $B. The magnitude of $A is:
2 2 2 2
0 +4 +0 =
4 = 4
1 +0 +0 =
1 = 1
EXPRESSION SYNTAX | 3
Arithmetic, logic, and relational operators
Logical operators
You use logical operators with the relational operators described in the previous topic. Logical operators are often part of conditional statements. See Conditional statements on page 57.
Meaning or and
This sets Balls scaleZ attribute to the value of time only when the animation time is greater than 5 and less than 10 seconds. Notice that each condition is grouped in parentheses, and the pair of conditions are enclosed again in parentheses. If you use multiple conditions with logical operators, you must enclose all the conditions in parentheses for the if statement. If you omit the outer pair of parentheses as in the following example, an error message occurs:
if (time > 5) && (time < 10) Ball.scaleZ = time;
Example 2
if ((Ball.translateX < 5) || (Ball.translateY > 10)) Ball.scaleZ = time;
This sets Balls scaleZ attribute to the value of time in either of two conditions: when Balls translateX attribute is less than 5 or greater than 10.
EXPRESSION SYNTAX | 3
Operator precedence
OPERATOR PRECEDENCE
The precedence of operators in expressions follows:
Highest () [] ! ++ - * / % ^
Lowest
This figure includes operators used mainly by individuals experienced in programming. See Programming features on page 63 for details. In the figure, operators on the same row have equal precedence. If a statement has two or more operators from the same row, the operator furthest to the left is evaluated first. The parentheses at the top of the figure are for grouping a condition or elements of a statement. As shown in a following example, parentheses are useful for altering the order of operator evaluation. Examples
Ball.scaleY = 8 + 2 * 4;
This assigns Ball.scaleY the value 10. The + executes first because its further to the left in the statement than the -.
EXPRESSION SYNTAX | 3
Conditional statements
CONDITIONAL STATEMENTS
Conditional statements set one attribute or variable based on the condition of another attribute or variable. For example, you might increase the scale of a balloon after frame 48 plays. The if and if-else statements are the most commonly used conditional statements in expressions. Youll often use relational and logical operators in conditional statements. See page 52 and page 55 for details. If you have programming experience, be aware you can use loop and flow control statements such as while and for. See Programming features on page 63.
if statements
The if conditional statement has this format:
if ( condition ) statement;
This sets the scale of Balls scaleY attribute to 2 after the animation plays three seconds.
if-else statements
The if-else conditional statement has the following format:
if ( condition ) statement1; else statement2;
EXPRESSION SYNTAX | 3
Conditional statements
This sets Balls scaleY attribute to 2 if animation time is greater than 3 seconds. 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; }
If the animation time is less than 2 seconds, the expression sets Balloons translateY attribute to 0, and sets its scaleY attribute to the value of time multiplied by 0.6. If animation time is greater than or equal to 2 seconds, the expression sets Balloons translateY attribute to time minus 2, and sets scaleY to 1.
EXPRESSION SYNTAX | 3
Conditional statements
Important
You cannot set the same attribute in two different expressions. If you try to do so, an error message results and your second expression has no effect.
else if statements
The else if statement works with the if-else conditional statement and has this format:
if (condition1 ) statement1; else if ( condition2 ) statement2;
If condition1 is true, statement1 executes and the else if statement after it is skipped. If condition1 is false, the else if statement executes. If condition2 is true,
statement2 executes. If neither condition is true, neither statement executes.
This sets Balls 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, when time is greater than 6 seconds, scaleY is 3.
EXPRESSION SYNTAX | 3
General syntax rules
Note that you can add multiple else if statements and multiple statements within 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; }
EXPRESSION SYNTAX | 3
General syntax rules
A semicolon marks the end of each statement. 2 3 Enclose each conditional item in an expression within parentheses. In the preceding 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, youll see that there are three opening parentheses, but only 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 opening parentheses. 4 When you use { and } as opening and closing braces, make sure you use them in matching pairs:
if (time > 3) { Ball.rotateZ = deg_to_rad(-6 * (floor(time)); Ball.rotateY = Ball.rotateZ * 3; }
Spaces before and after the numbers and commas are optional. 6 Begin any variable you use with a dollar sign ($), and do not to use spaces or special characters other than underscores in the name. Heres an acceptable example:
float $my_Rotate; $my_Rotate = 3.14;
In conditional statements, be careful to type == rather than = for the equal to operator. The = symbol means assign the value. For example, make sure you type:
if (Ball.scaleY == 3) Cone.scaleY = 6;
instead of this:
EXPRESSION SYNTAX | 3
Comments in expressions
if (Ball.scaleY = 3) Cone.scaleY = 6;
You can use as many spaces, tab characters, and blank lines as you like when separating words, operators, or statements. Maya ignores white space in an expression. For example, suppose youve written this expression:
if (time < 2) { Balloon.translateY = 0; Balloon.scaleY = time * 0.6; } else Balloon.translateY = time - 2;
Though the following expression has different spacing and is unpleasant to read, 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 the else keyword but in no other place in this expression. To simplify spacing considerations, remember to put at least one space before and after a keyword, variable, operator, attribute, assignment operator, and so on. Consistent use of white space makes expressions easier to read. Examples throughout this chapter show examples of good spacing style.
COMMENTS IN EXPRESSIONS
Add comments to your expressions to explain the purpose of each statement within. Youll 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 the comment: USING MAYA: EXPRESSIONS 62
EXPRESSION SYNTAX | 3
Programming features
To write a multi-line comment: Enter two forward slashes (//) before the comment:
// This is an example of a // comment spanning two lines.
PROGRAMMING FEATURES
The following topics describe programming features available in expressions. Discussion is brief and assumes youre familiar with programming. Most of the syntax features described work like their C counterparts.
EXPRESSION SYNTAX | 3
Programming features
int
float
vector
string
matrix
yes
no
on
off
true
false
if break
else continue
for default
while switch
do case
in
Other keywords
global
return
source
catch
alias
proc
The return, proc, and matrix keywords are useful for writing MEL scripts, not for expressions. Other keywords above are described throughout this chapter. Type keywords in lowercase letters exactly as shown. Do not name a custom attribute with any of these keywords.
EXPRESSION SYNTAX | 3
Programming features
Youll often use logical and relational operators in conditional statements. See page 52 and page 55 for details.
Important
Using a while, do, or for loop incorrectly might halt Maya. See Flow control errors on page 75 for details.
while
A while loop has this format:
while ( condition ) { statement; statement; ... }
Use condition to compare variable, attribute, or constant values. If condition is true, Maya executes each statement between braces. Maya then evaluates condition again. If true, it executes each statement again. This cycle continues until condition is false, whereupon execution resumes with the statement after the loop. Example
float $test = 0; while ($test < 5) { print("$test equals: " +$test+"\n"); $test = $test + 1; }
EXPRESSION SYNTAX | 3
Programming features
This message indicates that a MEL command executed when you clicked the Create or Edit button in the Expression Editor. Specifically, an expression command executed. This is unrelated to the exact statements in the expression.
do
A 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 is true, each statement executes again. The loop terminates when condition is false. In contrast to a while loop, a do loop executes the statements in the loop at least once. It tests the termination condition after the loop. A while loop tests the 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);
EXPRESSION SYNTAX | 3
Programming features
for
A for loop has this format:
for (initialization; condition; change of condition) { statement; statement; ... }
A for loop evaluates the termination condition before executing each statement. The condition compares variable, attribute, or constant values. Example
float $i; for ($i = 0; $i < 5; $i = $i + 1) { print("$i equals: " +$i+"\n"); }
break
The break instruction exits a loop from any point within its body, bypassing the normal termination at the loops beginning or end. Expression execution resumes at the next statement after the loop. You can use a break instruction with a while, do, or for loop. Example
float $f = 0; while( $f < 10 ) { print("$f equals: "+$f+"\n"); if ( $f > 5 )
EXPRESSION SYNTAX | 3
Programming features
break; $f = $f + 1; }
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 the expression displays only numbers 0 through 6.
continue
The continue instruction works inside loops. It forces the next iteration of the loop to occur, skipping any statements between itself and the loops test condition. The condition compares variable, attribute, or constant values. 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"); }
EXPRESSION SYNTAX | 3
Programming features
got $f equals: got $f equals: got $f equals: got $f equals: got $f equals: $f equals: $f equals: $f equals:
The loop would display got here after each line of $f equals: n. Maya ignores the continue instruction until $f increases to a value greater than 5. When $f becomes 6 or greater, the continue instruction executes and skips the remaining statement in the loop, so got here isnt printed.
for-in
The for-in loop is a specialized for loop that simplifies manipulation of all elements of an array. A for-in loop with an array element variable lets you omit the initialization, condition, and change of condition components of a for loop. 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)
EXPRESSION SYNTAX | 3
Programming features
The loop executes three times, once for each array element in $carType. The first loop execution copies array element $carType[0] into $car, then prints, I want a new Porsche. Array element $carType[0] is Porsche. The second loop execution copies $carType[1] into $car, then prints the second line shown. The third execution copies $carType[2] into $car, then prints the third line shown. When the for-in statement finishes reading all array elements, the loop terminates.
switch
A switch instruction executes one of several groups of statements based on a control value. The control value can be a variable value or an attribute other than 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;
EXPRESSION SYNTAX | 3
Programming features
The switch executes with a variable control-value. If the variable contents match value1, value2, or another value in the switch, the statements under the associated 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 point arithmetic rounds numerals, a case value might fail to match a control-value as you expect. A break statement within a switch causes execution to skip subsequent case statement groups within the switch instruction. Example 1: Break statement within a switch
int $sway = rand(3); switch ($sway) { case 0: print("Case 0\n"); // Executes if $sway = 0 break; case 1: print("Case 1\n"); // Executes if $sway = 1 break; case 2: while (rand(10) < 7)// These statements print("I say!\n");// execute only print("Case 2\n");// if $sway = 2 break; }
When the expression executes a few times, it might display this random selection of entries in the Script Editor:
Case 0 Case 1 I say! I say!
EXPRESSION SYNTAX | 3
Programming features
The last case instruction in a switch doesnt need a break statement because the switch is finished. Still, its best to add the break statement to avoid future problems that might result from adding other cases to the switch. For details on the purpose of rand(3), see rand on page 246. Example 2: Omitted break statement within a switch The following expression omits a break statement to make the switch continue 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 random selection of entries in the Script Editor:
Fight Fight Fight Food Fight Food
Whenever Food appears, Fight also appears after it. Fight can appear without Food being displayed. Note that you can make more than one case statement execute the same statements:
int $argo = rand(4); switch ($argo) { case 0: case 1:
EXPRESSION SYNTAX | 3
Programming features
// Runs if $argo is 0 or 1
This works like the preceding expression, except that a match of 0 or 1 displays Food and Fight, and a match of 2 or 3 displays Fight. Example You can use the default keyword to make a block of statements execute when none of the case values match the control value label. Generally, you put this label after all the case statements, though you can put it anywhere in the switch statement. If the switch has no default label and none of the case values match the control 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 not break; // <<0,1,1>> or <<1,0,1>> }
The expression executes the default case, which displays the following line in the Script Editor:
Why?
?: operator
The ?: operator lets you write a shorthand if-else statement to set an attribute or variable in one statement. Because of its cryptic appearance, many programming style experts suggest not using it. Heres its format:
EXPRESSION SYNTAX | 3
Programming features
The condition compares variable, attribute, or constant values. If condition is true, Maya evaluates statement1 and assigns its value to attribute. (You can also assign the statements value to a variable.) Maya evaluates either statement1 or statement2, never both. You can optionally enclose statement1 and statement2 in parentheses to make the expression easier to read. Example
Balloon.scaleY = (time < 2) ? time / 2: time * 2;
This statement sets Balloons scaleY attribute to time divided by 2 if time is less than 2, and time multiplied by 2 if time is greater than or equal to 2. This causes the scaleY attribute to increase slower for the first two seconds than after two seconds. This is the same as the following if-else statement:
if (time < 2) Balloon.scaleY = time / 2; else Balloon.scaleY = time * 2;
Important
If you use an integer value as statement1 and a floating point value as statement2, the ?: operator truncates the floating point value of statement2 to an integer. In the expression Balloon.scaleY = (time < 2) ? 0: time;, for example, 0 is an integer, and time is a floating point value. When time is 2 seconds or more, Maya sets Balloons scaleY attribute to the integer value of time. Because Maya sets scaleY to the integer value of time (without the decimal part), 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.
EXPRESSION SYNTAX | 3
Programming features
! operator
You can use the not logical operator (!) with integer, float, and vector data types. For vector values, ! is true only when the vector magnitude is 0. A vectors magnitude is the value resulting from this equation:
x +y +z
The x, y, and z numbers in the formula represent the three components of the vector. Examples
if (!$count) Ball.scaleY = 2;
Because the magnitude of $myvector is 0, the !$myvector condition is true and Ball.scaleY is set to 2.
EXPRESSION SYNTAX | 3
Programming features
Though you might think this expression sets Balloons scaleY attribute to the increasing value of time after the animation time exceeds 3 seconds, it actually halts Maya operation as soon as time exceeds 3. At that moment, the while condition is true, so the while loop statement Balloon.scaleY = time executes repeatedly and endlessly. Even though a statement sets an attribute within an expression, Maya updates the attribute only after the expression finishes executing. Because the expression never finishes executing, Maya halts. Unless you change Balloon.scaleY within the while loop to a value less than or equal to 3, the statement executes infinitely. 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 statement to link the Balls translateY attribute to the Cones translateY attribute:
while (Cone.translateY > 0) Ball.translateY = Cone.translateY;
At first glance, the expression seems to set Balls translateY position to the value of the Cones translateY position whenever Cones translateY is greater than 0. In fact, the expression halts Maya as soon as you translate the Cone to a Y position greater than 0. At that moment, the while condition is true, so the while loop statement Ball.translateY = Cone.translateY executes endlessly. Nothing you do in the user interface can change the Cones translateY position. It stays at translateY value of 0. Unless you change Cone.translateY within the while loop to a value less than 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;
EXPRESSION SYNTAX | 3
Programming features
Though the cosine of 90 degrees is mathematically 0, the cosd(90) function returns the value 6.123e-17, which is extremely close to 0 but not exactly equal. Though the number for practical purposes is the same as 0, its stored in the computer as a fractional quantity above 0 because of the way computers 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 doesnt equal 0.\n");
By checking that $x is between -0.0001 and 0.0001, the appropriate print statement executes. The value returned by cosd(90) is so close to 0 that its within the small range specified in the if statements numerical comparison.
String usage
A string is a sequence of alphabetical, numerical, and special characters. You can display strings in the Script Editor, for example, to check the contents of attributes or variables.
EXPRESSION SYNTAX | 3
Programming features
You can also create strings in the Expression Editor to execute MEL commands in an expression. See Chapter 5 for details. Guidelines for using strings follow: Enclose a literal string with double quotes as in this example:
print("asteroid2");
The following table lists how Maya converts data types if you use arithmetic operators with strings in an expression. Arithmetic operation string operator integer string operator float string operator vector Resulting data type string string string
If youre familiar with C programming, be aware you can assign a string to a vector 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 5.
EXPRESSION SYNTAX | 3
Programming features
The following table shows the shorthand operators and the valid data types for each. The shorthand operators work like their counterparts in C.
Symbol += -= /= *= %=
Data type integer, float, vector, string integer, float, vector integer, float, vector integer, float, vector integer, float
EXPRESSION SYNTAX | 3
Programming features
Expanded syntax variable = variable + 1; variable = variable - 1; variable = variable + 1; variable = variable - 1;
When the increment or decrement operator precedes the variable, the increment or decrement occurs before the statement executes. When the operator follows the variable, the increment or decrement occurs after the statement executes. Examples
float float $crab $crab $crab $eel = 32.3; $crab = $eel++; = $eel--; = --$eel; = ++$eel; // // // // $crab $crab $crab $crab = = = = 32.3; 33.3; 31.3; 32.3; $eel $eel $eel $eel = = = = 33.3; 32.3; 31.3; 32.3;
Important
To avoid unexpected results, do not use more than one shortcut increment or decrement operator on the same variable in the same statement. The evaluation order of the operators is unpredictable.
Arrays
You can create arrays of float, vector, integer, or string values. You can clear an array using a clear function. You can find the size of an array with the size function. See Array functions in Chapter 7 for details. When you assign a value in an array, Maya reserves memory for all elements less than that number. This means you can exceed the capacity of your computer with a single array declaration. For example, do not use a statement like this:
EXPRESSION SYNTAX | 3
Programming features
$newarray[12312323123] = 1;
Note that an array expands its size automatically as you assign values to its elements. You dont need to declare its size. If your array assignment exceeds the size of the array, the array expands to that size. If you reference an 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;
The second statement makes the array contain 1501 elements and assigns element 1500 the value 3. The third statement expands the array to 2001 elements and assigns element 2000 the value 5. Example: Initializing and printing an arrays 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");
EXPRESSION SYNTAX | 3
Programming features
7 8 9 $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 after its definition. The for loop executes the statements between the braces 10 times, once for each 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 of the array after you initialize it. In other words, the Script Editor displays 0 through 9. The for loop stops executing after $i becomes equal to 10. Then the final print statement displays the number of elements of the initialized array, 10. The array increased in size as you assigned values to its elements.
This causes Lances scaleY attribute to increase only if Monsters visibility attribute is on. The on represents 1.
print(3 + on);
EXPRESSION SYNTAX | 3
Common expression errors
EXPRESSION SYNTAX | 3
Common expression errors
Youll often need to scroll or increase the size of the Script Editor to see an entire message. When the Script Editor displays a syntax error, the response area of the Command Line displays the same error with a red background.
If an expression executes a valid statement after the erring statement, the error message with the red background flashes briefly. You wont notice it unless youre looking directly at it and have quick eyes. The best way to know when an error has occurred is to look for a new message prefixed by // Error: in the Script Editor. Before clicking the Create or Edit button to create an expression, you might want to select Edit > Clear History in the Script Editor to remove previous messages in the window. This makes it easier to see when a new error message appears.
You misspelled an attribute name, the attribute doesnt exist in the scene, or you forgot to prefix a variable name with $.
Attribute of a particle object can only be used with dynExpression command: particleShape1.position
EXPRESSION SYNTAX | 3
Common expression errors
You used a particle array attribute in the expression, but a particle shape node is not the Selected Object in the Expression Editor. A particle shape node must be selected to use particle array attributes. A particle array attribute is also called a per particle attribute.
Attribute already controlled by an expression, keyframe, or other connection: Balloon.tx.
You tried to set the value of an attribute that has already been set by one of these techniques: set driven key constraint motion path another expression any other direct connection
More than one attribute name matches. Must use unique path name: 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 different parent objects. For example, a scene might have a child of GroupA named Ball.tx and a different child of GroupB named Ball.tx. If you write a statement such as Ball.tx = time;, Maya wont know which Ball.tx to set. To eliminate the error in this example, you must enter the full pathname of the attribute as GroupA|Ball.tx. The pipe symbol (|) specifies that the object to 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 you cannot 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 matrix type. For instance, you might have tried to use an attribute named translate rather than translateX, translateY, or translateZ attribute. In the error message above, worldMatrix is an attribute that exists for transforms, but you cant use it. Its for Mayas internal use. USING MAYA: EXPRESSIONS 85
EXPRESSION SYNTAX | 3
Common expression errors
You tried to divide by an attribute or variable that equals 0. This typically happens in an expression statement that divides by an objects translateX, translateY, or translateZ attribute when the Snap to grids button is on and you drag the object to past the X-, Y- or Z-axis. When Snap to grids is on, the translateX, translateY, or translateZ attribute becomes exactly equal to 0 at the point where you drag the object across the axis. To prevent this error, turn Snap to grids off. With snapping off, the attribute is 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 same error message once for each particle in the object, its likely that some attribute name, variable, or function is undefined or misspelled.
EDITING EXPRESSIONS
The Expression Editor offers convenient techniques for editing the text of expressions. There are filters that help you search for expressions you previously created, as well as techniques for entering and modifying the text of an expression.
You can edit an expression directly in the text box or with an external text editor.
This chapter describes the following topics: Finding expressions on page 89 Editing text in an expression on page 95 Editing an expression with a text editor on page 96 Creating a new expression on page 102 Deleting an expression on page 102 Using attribute names in expressions on page 103
FINDING EXPRESSIONS
After youve created an expression, you might decide later to alter it to create a different animation result. To edit an expression, you display it in the Expression Editor. The following sections describe how to find and display an expression for editing.
EDITING EXPRESSIONS | 4
Finding expressions
Note
You can find and edit MEL script nodes in the Expression Editor. See Using Maya: MEL for details.
List of expressions
Click the expression in the list. The expression contents appear in the expression text field. If you dont remember the name of the expression, click each name on the list until the desired expression appears in the expression text field.
EDITING EXPRESSIONS | 4
Finding expressions
Note
For a particle shape node, you can create a creation expression, a runtime expression, or both. Both expressions are listed under a single namethe name of the particle shape node. You cant name or rename such expressions. To find such expressions, look for the particle shape nodes name in the Expressions list. Click the appropriate Runtime or Creation checkbox to display the desired expression.
For an object other than a particle shape node, click the name of the attribute controlled by the expression.
EDITING EXPRESSIONS | 4
Finding expressions
If youve forgotten the name of the attribute controlled by the expression, choose Attribute Filter > Connected to Expressions. The Attributes list displays only the attributes controlled by expressions for the selected object. Click each attribute in the Attributes list until you see the desired expression in the expression text field. You cant write a different expression for each attribute of a particle shape as you can for other types of objects. Because you can write only one creation expression and one runtime expression per particle shape, you dont need to select an attribute from the Expression Editors Attributes list. See Understanding particle expressions on page 142 for details on particle expressions.
Note
The Attributes list shows only unlocked, keyable attributes. You can choose whether an attribute is keyable or locked with Window > General 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.
EDITING EXPRESSIONS | 4
Finding expressions
Example Suppose youve written an expression that controls the rotateZ attribute of a spotlight transform node named Searchlight. Do this to find the expression: 1 2 Choose Select Filter > By Object/Attribute name. Select Object Filter > Transforms. Note that you dont select Object Filter > Lights in this example. The rotateZ attribute is an attribute of a lights transform node, not of the light object itself. 3 4 5 Choose Attribute Filter > Connected to Expressions. Select the object Searchlight from the Objects list. Click rotateZ from the Attributes list. The expression appears in the expression text field.
Expressions list
EDITING EXPRESSIONS | 4
Finding expressions
EDITING EXPRESSIONS | 4
Editing text in an expression
To filter attributes from the Attributes list: 1 2 3 4 Select the object containing the attributes. Choose Select Filter > By Object/Attribute Name. Choose Object Filter > Selected Objects. Choose Attribute Filter > Connected to Expressions. Only the objects attributes controlled by expressions appear in the Attributes list. To see all attributes you can control with an expression again, choose Attribute Filter > All.
Important
If you close the Expression Editor window without successfully compiling an expression with the Create or Edit button, Maya discards any editing changes youve made. To use keyboard commands: Command Ctrl+c Ctrl+x Ctrl+v Ctrl+k Ctrl+d Definition Copy Cut Paste Delete to end of line Delete next character Platform Both IRIX and Windows Both IRIX and Windows Both IRIX and Windows IRIX only IRIX only
EDITING EXPRESSIONS | 4
Editing an expression with a text editor
Definition Move cursor to beginning of line Move cursor to end of line Select all the text in the edit box
To clear the entire expression text field: Click the Clear button.
Important
To erase an expression and make sure its previous contents no longer control an attribute, click the Edit button after clicking the Clear button. To reload an expressions previous contents: The Edit button compiles an expression. If youve made an editing change and havent yet clicked the Edit button, you can click the Reload button to retrieve the previous expression. This restores the expression to the contents last present when you clicked the Create or Edit button.
EDITING EXPRESSIONS | 4
Editing an expression with a text editor
There is no file on disk you can edit independently of the Expression Editor. When you use the text editor through the Expression Editor, youre working with a temporary file thats linked to the expression stored in the scene. You can, however, copy text from an independent text file into the temporary file. If you save an expression without specifying a filename, Maya reads the saved expression and stores it with the scene. Youll see it dimmed in the expression text field while youre working with the text editor. When you close the text editor, the expression text field entry no longer is dim. 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 hasnt changed, Mayas copy of the expression doesnt need to change either.
Tip
You can use a text editor to save an expression to a filename in the directory of your choice. This gives you a way to archive an expression you want to use in a different scene.
EDITING EXPRESSIONS | 4
Editing an expression with a text editor
To run a different editor, see Using an editor not listed in the Editor menu (IRIX) on page 99. To start an editor listed in the menu: 1 2 From the Editor pull-down menu in the Expression Editor, select an editor. Double-click an object name, expression name, or attribute name from the Selection list. The editor is displayed. The editors title bar shows a filename thats temporarily created while you work on the expression. When you write or save the file, its contents are copied to the Maya scene containing the expression. The expression text field is inactive while the text editor is open. You can optionally close the Expression Editor window. If you single-click the name of an object, attribute, or expression, the text editor doesnt appear. You can single-click to browse the contents in the expression text field without opening a text editor. If you double-click an attribute thats already been assigned a value in an expression, the expression that controls that attribute appears in the text editor. For non-particle expressions, you can assign to any attribute in the scene, not just to the double-clicked attribute. In fact, you dont even need to work with the double-clicked attribute at all. If you double-click an attribute that has not yet been assigned a value, the text 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 attribute in an expression, you can start the editor only once for the attribute. 3 4 5 6 Create or edit the expression with the editor. Save the file. Confirm that the Expression Editor detected no syntax errors. Quit the editor.
EDITING EXPRESSIONS | 4
Editing an expression with a text editor
Note
If youve created a IRIX command alias for jot, vi, vim, or xemacs, the Expression Editor tries to launch this command. If the arguments provided in the command alias are unusable by the Expression Editor, the editor might operate unexpectedly or fail to launch. Avoid using an alias to customize your editors operation settings. Do the steps in Changing an editors operation settings (IRIX) on page 100.
EDITING EXPRESSIONS | 4
Editing an expression with a text editor
2 3 4 5
Log out and log into your user account. Restart Maya. Choose Other from the Editor pull-down menu. Double-click an object name, expression name, or attribute name from the Selection list. The editor appears.
6 7 8 9
Create or edit the expression with the editor. Save the file. Confirm that the Expression Editor detected no syntax errors. Quit the editor.
EDITING EXPRESSIONS | 4
Editing an expression with a text editor
Important
If youve specified a text editor through Preferences or with the Expression Editors Editor menu, starting the Expression Editor from the Channel Box or Attribute Editor displays the text editor instead of the Expression Editor. The text editor appears when you click the New Expression button.
EDITING EXPRESSIONS | 4
Creating a new expression
DELETING AN EXPRESSION
You can delete an expression to stop it from controlling attributes. To delete an expression: 1 2 Display it in the Expression Editor. Click the Delete button. Note that you can quickly delete all non-particle expressions from a scene. From Mayas main menu bar, select Edit > Delete All by Type > Non-particle Expressions.
EDITING EXPRESSIONS | 4
Using attribute names in expressions
Each attribute has at least one acceptable abbreviation. Here are some commonly used attribute name abbreviations for several types of object transform nodes:
Abbreviation tx ty tz
EDITING EXPRESSIONS | 4
Using attribute names in expressions
Abbreviation rx ry rz sx sy sz v
To see the abbreviations for attributes that can be keyframed: 1 2 Select the object or item containing the desired attributes. Display the Channel Box. Common English equivalents for the long attribute names appear in the Channel Box by default. Do not use these names in the expression text field. Use the names as advised in the following figure.
EDITING EXPRESSIONS | 4
Using attribute names in expressions
From the Channels menu at the top of the Channel Box, select Channel Names > Short. The abbreviated attribute names replace the common English attribute names in the Channel Box. To see abbreviations for attributes that cannot be keyframed: Execute this MEL command in the Script Editor:
listAttr -sn objectname
EDITING EXPRESSIONS | 4
Using attribute names in expressions
Note
After you click Create or Edit to compile an expression, Maya converts all attribute abbreviations in the expression to the full attribute name.
Maya interprets translateY as belonging to Ball, the object listed in the Default Object text box of the Expression Editor. To make an object the Default Object: Enter the objects name in the Default Object text box. By default, the selected object is also the default object. You can omit the object 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 selected object in the Expression Editor. Because a particle shape nodes attributes can be controlled by only one creation expression and one runtime expression, the particle shape node is always the default object when it is the selected object.
EDITING EXPRESSIONS | 4
Using attribute names in expressions
Example Suppose youve selected Ball as the Default Object. In place of this:
Ball.translateY = time;
Maya interprets ty as being the translateY attribute of Ball, the object listed in the Default Object text box of the Expression Editor. Attributes of other objects must be spelled out with the full object and attribute name.
EDITING EXPRESSIONS | 4
Using attribute names in expressions
The falling cube is a soft body with goal and springs. As its points move below the oor, an expression assigns them a goal weight of 0. The cube appears to melt as it passes through the oor. Rob Tesdahl
This chapter describes the following topics: How often an expression executes on page 110 Using custom attributes in expressions on page 111 Displaying attribute and variable contents on page 115 Reproducing randomness on page 115 Speeding expression execution on page 119
Reducing redundant expression execution on page 123 Removing an attribute from an expression on page 124 Disconnecting an attribute on page 125 Renaming an object on page 129 Executing MEL commands in an expression on page 130 Understanding path names on page 134 Understanding unexpected attribute values on page 135
Planet orbits the origin at a radius of 1 unit. In the following steps, youll create a custom attribute named distance to increase the radius of Planets orbit over time.
Note
The small balls in the preceding figure show the circular path of Planet. Theyre in the figure only to help you visualize the motion. They arent part of the animation or expression. To add a custom attribute to alter the orbit: 1 2 Select Planet. Choose Modify > Add Attribute.
3 4
In the Add Attribute window, enter distance in the Attribute Name text box. Make sure Make attribute keyable is on.
5 6
Set Data Type to Float, and Attribute Type to Scalar. Set Minimum to 1, Maximum to 10, and Default to 4. Minimum and Maximum set the lowest and highest values you can enter for the attribute in the Attribute Editor or Channel Box. Default sets the default value displayed for the attribute. An expression isnt bound by the Minimum and Maximum values. The attribute receives whatever value you assign it in the expression. The expression can read the Default value or any other value you set in the Attribute Editor or Channel Box.
Click Add to add the attribute, then close the Add Attribute window. The distance attribute appears in the Attributes list of the Expression Editor for Planet. You can now set or read the value of the attribute in any expression.
Multiplying the sin(time) and the cos(time) by the distance attribute makes Planet circle the origin at a distance specified by the value of the distance attribute. See Chapter 7 for details on the sin and cos functions.
Because you gave the distance attribute a default value of 4 when you added it to Planet, playing the animation makes Planet circle the origin at a distance of 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, Planets orbiting distance increases as playback time increases. Planet moves in a steady outward spiral as the animation plays.
Instead of using an expression to control distance, you can keyframe its value over time. For example, by keyframing a distance value of 1 at frame 1 and a value of 10 at frame 200, Planet moves in a steady outbound spiral as you play the 200 frames. Planets distance increases in a linear interpolation from 1 to 10 as the animation plays. You can animate the distance attribute with keyframes or with an expression, not with both.
Tip
If an expression controls an attribute and you want to control it with keyframes instead, delete all statements that assign values to the attribute, then click the Edit button. Use the Channel Box to reset the attributes value to an initial value, then set keyframes as desired. If keyframes control an attribute and you want to control it with an expression instead, click the attributes text box in the Channel Box, then choose Channels > Delete Selected. Assign values to the attribute name in an expression as desired.
REPRODUCING RANDOMNESS
If you execute the rand, sphrand, and gauss functions repeatedly in an expression, Maya returns a sequence of random numbers. (See Random number functions on page 242 for details on these functions.) Each time you rewind and play your animation, the sequence of random numbers is different. Often, youll want to generate a sequence of random numbers that repeats each time your animation plays. For instance, suppose you use the rand function to assign a random radius to each particle in a stream of emitted particles rendered as Spheres. By default, Maya gives the particles a different sequence of random radius values each time your animation plays.
To create the same radius values each time the animation plays, you can use the seed function in an expression before the rand, sphrand, or gauss functions execute. Theres no need to execute the seed function more than once per animation unless you need to generate several different repeating sequences of random numbers as your animation plays.
Important
When you set a seed value in an expression or MEL script, the seed value affects the rand, sphrand, and gauss functions in other expressions and MEL scripts. Such functions are affected by this seed value in all scenes you open subsequently in the current work session. This seed value is unrelated to the Seed attribute available in the particle shape node. The seed function therefore doesnt affect randomness created with dynamics. Example Suppose you use the rand function to position several marbles at random translateX positions in your scene at frame 1:
if (frame == 1) { marble1.tx marble2.tx marble3.tx marble4.tx }
= = = =
The rand(-10,10) returns a random number between -10 and 10 each time it executes. When you rewind the animation to frame 1, Maya might assign these values to the translateX attributes of the marbles:
Attribute marble4.tx
Value 7.186
The next time you rewind the animation to frame 1, each marbles translateX attribute receives a different random value. Maya might assign these values:
You might prefer the marbles translateX values to stay the same when you rewind, for instance, so you can composite the marbles correctly among a foggy backdrop. You can use the seed function to keep the sequence of random values returned by the rand function consistent when you rewind the animation.
if (frame == 1) { seed(10); marble1.tx marble2.tx marble3.tx marble4.tx }
= = = =
By setting the seed value to an arbitrary number, for instance, 10, the subsequent executions of the rand function return a repeating sequence of random numbers. When you rewind the animation the first time, Maya might assign these values to the translateX attributes of the marbles:
Each time you rewind the animation thereafter, Maya assigns these same values to the translateX attributes of the marbles. The marbles dont move. Each time a statement sets the seed value to 10, the subsequent executions of the rand function return numbers from the sequence starting at the beginning number. In other words, resetting the seed value to 10 restarts the random number generation process to the first value in the sequence. Suppose you alter the expression to this:
if (frame == 1) { seed(10); } marble1.tx marble2.tx marble3.tx marble4.tx
= = = =
When you rewind the animation to frame 1, the expression sets the seed to 10. Maya assigns values to the marbles translateX attributes as in the previous expression. Because the expression doesnt set the seed value in frames other than frame 1, playing the animation causes the rand function to return a new, yet repeating, sequence of random numbers each frame. If you play the animation several times, the translateX values will constantly change during animation, but the sequence of values will be identical each time you play the animation. You can assign the seed a different value to generate a different sequence of returned values. See seed on page 250 for details.
If a measurement unit youve chosen differs from the corresponding internal unit, Maya converts the number to the appropriate internal unit to do the assignment. Example Suppose youve selected degrees from the Angular menu in the Settings part of the Preferences window. 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 the appropriate number of radians to make the assignment to Balls rotateZ attribute. The conversion happens automatically. From your standpoint, Maya is simply rotating Ball 10 degrees. In non-particle expressions, these automatic conversions affect Maya performance. Because the expression executes slower, Maya slows when you play, rewind, or otherwise change the animation time. Saving, opening, and other file operations on the scene containing the expression are also slower. To boost Maya performance, you can turn off conversion to internal units. If you do so, you must convert units in expression statements. To speed expression execution: 1 2 Display the Expression Editor. Choose one of these Convert Units options:
None
Converts no units. You must assign values to attributes as centimeters, radians, or seconds, as appropriate. Execution is fastest with this option. Converts angular units, but no others. You must assign values to attributes as centimeters, seconds, and degrees, as appropriate. (This assumes youre using the default degree setting in the Preferences. If youve selected radians, you must enter radians.) If youre confused by converting degrees to radians, select this option. Execution is fast with this optionunless the expression has many angular values.
Angular Only
To return to default conversions: 1 2 Display the Expression Editor. For the Convert Units option, choose All. This lets you enter all measurement numbers in the same units specified in the Units preference settings. Execution is slowest with this selection, but expression writing is simplest. You can set a different conversion option for each expression. Example Suppose, in the Preferences window, youve set Linear units to millimeters and Angular 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. Examples Suppose, in the Preferences window, youve set Linear units to millimeters and Angular units to degrees. In the Expression Editor you set the Convert Units option to None and enter this expression:
Ball.translateX = 5; Ball.rotateZ = 10;
None causes Maya to read 5 as centimeters and 10 as radians, which is not the result youre seeking. To assign 5 millimeters to Balls translateX attribute, you must convert 5 to the appropriate number of centimeters. To assign 10 degrees to Balls rotateZ attribute, you must convert 10 to the appropriate number of radians.
There are 10 millimeters per centimeter. In other words, a millimeter is a centimeter divided by 10. So 5 millimeters equals 5 centimeters divided by 10. You therefore use the operation 5.0 / 10.0.
Important
When you divide floating point attributes or variables, enter the floating point value 5.0 for an even number such as 5. This ensures that the division works as expected. For more details, see the note in Using mixed data types with arithmetic operators on page 139. There are 57.3 degrees per radian. In other words, a degree is a radian divided by 57.3. So 10 degrees equals 10 radians divided by 57.3. You therefore use the value 10.0 / 57.3. If you need a more precise conversion to radians, divide a degree by 57.29578 instead of 57.3. You can instead use the deg_to_rad function as follows:
Ball.rotateZ = deg_to_rad(10.0);
The deg_to_rad function converts 10.0 degrees to a precise radian equivalent. See deg_to_rad on page 238 for details. Turning off unit conversion affects only expressions. It doesnt affect other Maya commands, options, or displays. For instance, the preceding example expression assigns centimeters to translateX and radians to rotateZ. The Channel Box still displays values for these attributes in millimeters and degrees. It displays values in whatever units you choose in the Settings part of the Preferences window. Note that you cant turn off unit conversion for particle shape node expressions. Maya handles unit conversion differently for such expressions with little impact on performance.
If you use the Move tool in the workspace to drag the sphere in an X-axis direction, Maya executes the expression for each incremental change to the translateX attribute as you drag. Dragging the sphere in the X direction changes the value of the translateX attribute in the expression. As you drag the sphere and Maya updates the workspace display, the value of the translateY attribute changes in the expression. This makes the expression execute. If you turn Always Evaluate off, an expression wont execute if it contains only print function statements, variable assignments, or assignments that do not 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 but assigns no value to an attribute. The next statement assigns an attribute a value, but the value is generated by the random number function rand. This function doesnt read an attribute value. For details on the rand function, see rand on page 246. The last statement reads and prints the value of an attribute, but doesnt assign a value to an attribute. None of these actions causes the expression to execute when Always Evaluate is off. Always Evaluate affects only the expression youre creating or editing. You can turn it on for one expression and off for another. For most animations, expressions execute regardless of whether Always Evaluate is on. If in doubt, leave it on.
DISCONNECTING AN ATTRIBUTE
If you disconnect an attribute from an expression, the expression no longer reads or set its value. You might want to disconnect an attribute, for example, so you can keyframe the attribute rather than control it with an expression. These actions disconnect an attribute from an expression: Delete from the scene an object with an attribute that exists in the expression. Use the Window > General Editors > Connection Editor to disconnect the attribute from the expression. Use the MEL disconnectAttr command. Use the MEL choice command.
Tip
The MEL choice command lets you control an attribute alternately with two or more techniques in different frames. For example, you can keyframe an attribute for frames 1-48, control it with an expression for frames 48-96, and control it with a motion path for subsequent frames.
If you delete Cone from the scene, Cone.translateX, Cone.translateY, and Cone.translateZ attributes no longer exist for the expression to read and assign to Balls translateX, translateY, and translateZ attributes.
The .I[0], .I[1], and .I[2] characters indicate youve disconnected Cones translate attributes from the expression. These symbols represent placeholders for the former use of the attributes in the expression. The .I means the placeholder represents an input to the expression. An input to an expression is an attribute with a value the expression reads for assignment to another attribute or variable. The number in brackets indicates the order in the expression the attribute was read. For example, .I[0] indicates the input is the first attribute read in the expression, .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 particle shape nodes vector attribute placeholder has a value of <<0,0,0>>. In the example, the placeholders .I[0], .I[1], and I[2] have the value 0. When the expression executes, it assigns Ball.translateX, Ball.translateY, and Ball.translateZ the value 0. Note that if you disconnect an attribute from an expression but the attribute still exists in the scene, the attribute keeps its value from the last time the expression executed and set its value. Example Suppose youve 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, and Ball.translateZ attributes no longer exist. The expression can no longer assign Cones translateX, translateY, and translateZ values to the corresponding Ball attributes. Symbolic placeholders replace Ball attributes in the expression. If you display the expression again, the statements appear as follows:
.O[0] = Cone.translateX;
Note
If an expression assigns values to the attributes of only one object, deleting the object deletes the expression also. If your expression assigns values to attributes of several object attributes, deleting all those objects deletes the expression. To avoid deleting the expression in the preceding example, you would need have some statement that sets an attribute of an object other than the deleted Ball. For example, you might include this statement:
Cone.visibility = 1;
The .O[0] characters indicate youve disconnected the attribute Ball.translateY from the expression. The .O indicates that the placeholder represents an output from the expression. An output from an expression is an attribute assigned a value by the expression. The number in brackets, for example, [0], indicates the order in which the attribute was assigned a value in the expression. Because Ball.translateX was the first output from the expression, the expression replaces it with .O[0]. The expression replaces Ball.translateY and Ball.translateZ with .O[1] and .O[2] because they were the second and third outputs from the expression. When the expression executes, it continues to assign values to the placeholder, though the placeholder has no effect on any object or component of scene. The expression assigns the placeholders .O[0], .O[1], and .O[2] the value of Cone.translateX, Cone.translateY, and Cone.translateZ, but these placeholders dont control anything in the scene. The statements have no effect.
The most obvious way to do this is to type the desired attribute name in every occurrence of the symbolic placeholder in the expression. If you have a lengthy expression that has lots of symbolic placeholders, you can use a single MEL connectAttr command to connect the new attribute to all occurrences of the same symbolic placeholder. You can also use Window > General Editors > Connection Editor. Example 1 Suppose you have these statements among others in an expression named HorseController:
WhiteHorse.translateX = Car.translateX; BlackHorse.translateX = Car.translateX; BrownHorse.translateX = Car.translateX;
.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 contents to the translateX attributes of WhiteHorse, BlackHorse, and BrownHorse. Suppose you want to control these attributes with the translateX attribute of an object named Cow. You can enter the following MEL command at the Command Line:
connectAttr Cow.tx HorseController.input[0]
This command connects the attribute Cow.tx to the expressions 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 the Graph > 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;
Example 2 You can also reconnect an expressions output with the connectAttr command. Suppose you have these statements among others in an expression 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.translateX attribute. It received the placeholder .O[2] because its the third output from the 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 to control it with the value in Car.translateX, as shown in the third statement. Suppose you want to control the attribute of a new object named RedHorse.translateX with the Car.translateX value. You can enter the following MEL command in the Command Line:
connectAttr HorseController.output[2] RedHorse.tx
This command connects the HorseController expressions output[2] to the attribute 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 OBJECT
If you rename an object whose attributes were used in an expression, the Expression Editor continues to read or set the attributes. Maya doesnt disconnect the attribute from the expression. The Expression Editor converts to the new name of the object the next time you click the Reload button in the Expression Editor.
When you reload an expression, the Expression Editor converts any short attribute names to their long attribute name equivalents. For example, if you originally type the attribute name Ball.ty, reloading the expression renames it as Ball.translateY. If you rename an object and the name is used in a MEL command within an expression (see the following section), you must change the name manually in the expression. The Expression Editor doesnt convert object names that exist in MEL statements. For example, suppose you use the following statements in an expression successfully:
Cube.translateX = 'getAttr Ball.translateX'; setAttr Ball.translateX 0;
If you later rename Ball as Sphere, the Expression Editor wont change the name Ball to Sphere, and the expression will fail. You must change the name manually in the expression. In the following statements, the Expression Editor will change the name Ball to Sphere and the expression will execute without error. This occurs because the statements use standard expression syntax rather than MEL command syntax.
Cube.translateX = Ball.translateX; Ball.translateX = 0;
When you execute a command from the Command Line, status information appears in the Script Editor and the Command Lines response area. This information 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 MEL script node in an expression The following topics explain the techniques. See Using Maya: MEL for details on MEL.
This example shows the use of a MEL command alone. The statement executes exactly as it would in the Script Editor, except no command output appears in the Script Editor.
The first statement defines an array named $a. The second statement executes the MEL command within quotes, then assigns the commands output to array $a. The third statement displays the contents of $a to the Script Editor as follows: USING MAYA: EXPRESSIONS 131
ambientLightShape1 directionalLightShape1
The first statement assigns the string sphere to the variable $mycommand. The second statement appends -r 5 to sphere and executes the complete command sphere -r 5. This creates a sphere with a radius of 5 grid units. See eval on page 263 for more details.
In an expression statement, use a statement that calls the procedure. You can use 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, youve created a MEL script file named 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; }
When you rewind or play a frame in the animation, the expression executes. The first expression statement executes the randspot procedure in the randspot.mel script file. In the randspot procedure, the rand(2) part of the ifelse 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 on page 246. If the rand(2) function returns a value less than 1, the if statement assigns a MEL 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 floating point components of a randomly generated vector. Though sphrand(10) returns a vector, Maya converts the vector to a string upon assigning it to the string $mycommand. For details on the sphrand function, see sphrand on page 248.
The converted string contains no double angle brackets or commas, but does contain a space character between the floating point components. A space between the floating point components is required syntax for the MEL particle command as used above. If the rand(2) function returns a value greater than 1, $mycommand receives a MEL command string such as sphere -p 4.926 -2.589 1.274. The procedure finishes executing and passes the value of $mycommand back to the expressions calling procedure randspot( ). This assigns the command string to the variable $randcommand. The eval function executes the command string in $randcommand. For example, if the statement executes particle -p -1.356 5.983 8.458, it creates a particle with coordinates <<1.356, 5.983, 8.458>>. The expression executes each frame and creates a new particle or sphere at a random location within a spherical radius of 10 units from the origin.
Ball.tx = time;
Maya generates an error because it doesnt know which Ball.tx to set. To eliminate the error, you must enter the pathname of the attribute as in this example:
GroupA|Ball.tx = time;
The | symbol between GroupA and Ball.tx indicates that the object to the left of the symbol is the parent of the object to its right. Use no spaces before or after the | symbol. Note that the Expression Editor displays pathnames for such objects. For example, the Objects list displays GroupA|Ball.
Important
Always examine the Script Editor for error messages after you edit an expression and click the Create button. If you alter a previously successful expression and a syntax error occurs, Maya executes the previous successful expression when you play the animation. This might lead you to believe your editing changes took effect.
Assume for this example youve set the starting frame of the animation to frame 0.
The first statement sets Ball.tx to the variable $distance. The second statement sets $distance to the value of time. When you play the animation, Ball moves along the X-axis with the increase in time. Balls X-axis position is 4 grid units, for example, when animation time equals 4 seconds. When you rewind the animation, Balls position along the X-axis doesnt return to 0 as you might assume. The previous execution of the expression at time 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, Balls 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 the expression:
$distance = time; Ball.tx = $distance;
After you play and rewind the expression, the first statement executes and assigns 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 the desired translateX position.
Increment operations
If you increment an attribute or variable during animation, you might be confused by its behavior. Example
Ball.ty = 0; Ball.ty = Ball.ty + 1;
Balls translateY position stays at 1 unit along the Y-axis. Balls translateY position doesnt increase by 1 each frame as the animation plays. Example
Ball.ty = Ball.ty + 1;
Balls translateY position increases by 1 each frame as you play the animation. When you rewind the animation, translateY increases by 1 again. When you play the animation again, the translateY position increases by 1 each frame. If you rewind the animation or drag the current time indicator, the translateY position continues to move up the Y-axis. The attribute never returns to its original position. To return Ball to a starting position each time you rewind, you must initialize the attribute to a starting value. For example, you could use the following 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 you drag the current time indicator, though, Ball doesnt return to its Y position of 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. You would need to use a different frame number in the if statement if youve set your animation to start at a different frame.
x +y +z
The x, y, and z numbers in the formula represent the three components in the vector. The resulting value is the magnitude of the vector. Example
Ball.scaleY = <<1,2,0>>;
Maya assigns the floating point scaleY attribute the converted vector:
2 2 2
1 +2 +0 =
5 = 2.236
If you assign an integer to a floating point attribute or variable, Maya makes no conversion. None is necessary. Example
Ball.scaleY = 1;
1 +2 +0 =
5 = 2.236 2
It deletes the decimal component .2360607. The $temp variable receives the truncated value 2.
Operation integer operator float integer operator vector vector operator float Example
Suppose you multiply a vector variable named $velocity by a floating point number 0.5 as follows:
$race = $velocity * 0.5;
If $velocity is <<2,3,0>> when the preceding expression executes, the $race variable is assigned the resulting vector value <<1,1.5,0>>.
Important
When Maya does arithmetic operations on literal constants and variables without a declared data type, it guesses the data type based on the values present. In the statement Ball.scaleY = 1/3;, for example, Maya treats 1 and 3 as integers because they have no decimal points. The expression divides integer 1 by integer 3. The integer result is 0 with a remainder of 1. Maya discards the remainder. Because Ball.scaleY is a floating point attribute, Maya converts the integer 0 result to floating point 0 (which is the same value), then assigns it to Ball.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 have decimal points. The number 1.0 divided by 3.0 results in 0.33333333333.
PARTICLE EXPRESSIONS
Particle expressions are more complex than other types of expressions. For example, you can write an expression to control all particles in an object the same 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 for other expressions, but the resulting effects are worth the effort. This chapter guides you through the intricacies of working with particle expressions.
An expression moves a particle emitter in a corkscrew pattern and changes the color of trailing emitted particles as they age. The particles are displayed as Spheres render type.
Claude Macri
This chapter has the following topics: Understanding particle expressions on page 142 Understanding creation expression execution on page 143 Writing creation expressions on page 145 Understanding runtime expression execution on page 146 Writing runtime expressions on page 147 Working with particle attributes on page 153 USING MAYA: EXPRESSIONS 141
PARTICLE EXPRESSIONS | 6
Understanding particle expressions
Assigning to vectors and vector arrays on page 189 List of particle attributes on page 193
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 generally executes when you rewind an animation or when a particle is emitted. A runtime expression typically executes for each frame other than the rewind frame or the frame in which a particle is emitted. By default, either type of expression executes once for each particle in the object. Creation and runtime expressions dont execute at the same time. The age of each particle in the object determines whether a runtime expression or creation expression executes. Execution details are in Understanding creation expression execution on page 143 and Understanding runtime expression execution on page 146. The Default Object, Always Evaluate, and Convert Units options become dim when you select a particle shape node, and you cant use them. Default Object is dim because a particle shape nodes attributes can be controlled by only one creation expression and one runtime expression. The particle shape node is always the default object when its the selected object.
PARTICLE EXPRESSIONS | 6
Understanding creation expression execution
Always Evaluate is dim for particle shape node expressions because it has no effect on particle shape node expressions. See How often an expression executes in Chapter 5 for details on the checkbox. Convert Units is not selectable because you cant alter how Maya handles unit conversions for particle shape node expressions. See Speeding expression execution on page 119 for details on how Maya converts units for other types of expressions.
Important
You cant write a different expression for each particle shape attribute as you can for other types of objects. Because you can write only one creation expression per particle shape, you dont need to select an attribute from the Expression Editors Attributes list.
PARTICLE EXPRESSIONS | 6
Understanding creation expression execution
The animation time changes when you rewind, play, or otherwise change the current frame displayed. An emitted particles age is 0 in the frame where its emitted. Particles created with the Particle Tool have an age of 0 on and before the Start 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 Sliders start frame higher than the Start Frame, be aware that rewinding the animation might cause the age of particles to be greater than 0. If this occurs, the creation rule for the particles wont execute.
Tip
You can set options in the Attribute Editor to display the age of an objects particles in the workspace. Set the particle shapes Render Type to Numeric. Click Current Render Type next to Add Attributes For, then enter age in the Attribute Name box. The age appears next to each particle. You can also examine the age of an objects particles by entering print(age+\n) in a particle expression. See print on page 265.
PARTICLE EXPRESSIONS | 6
Writing creation expressions
All the particles move in a Y-axis direction at one grid unit per second as the animation plays.
PARTICLE EXPRESSIONS | 6
Understanding runtime expression execution
Important
To use an expression to control particle attributes, make sure the selected object in the Expression Editor is a particle shape node, not the transform node of the particle object. If a particle objects transform node is selected rather than the particle shape node, move the mouse pointer to the workspace and press your keyboards down arrow. This selects the particle shape node.
PARTICLE EXPRESSIONS | 6
Writing runtime expressions
In this context, the predefined variables time and frame are also considered attributes the expression reads.
Important
There are no creation expressions for nodes other than particle shape nodes. Such objects have only one type of expression. (Its similar to a runtime expression.) For a particle shape node, you can write only one runtime expression for all its attributes. You dont need to select an attribute from the Attributes list. You can create only one runtime expression per particle shape.
The expression moves the grid of particles up at 1 grid unit per second as the animation plays.
PARTICLE EXPRESSIONS | 6
Writing runtime expressions
Note
To make the illustrations of particles easier to see in this and other chapters, we show them as small, shaded spheres rather than points.
With the default frame rate of 24 frames/second, the particles move 1/24 of a grid unit each frame. With the default oversampling level of 1, the runtime expression executes once per frame. Maya calculates the runtime expression once for each particle of an object. Because the expression sets the velocity to <<0,1,0>> each frame, the expression executes redundantly. This expression would therefore be more appropriate for a creation expression. However, either type of expression has the same effect in this example.
PARTICLE EXPRESSIONS | 6
Writing runtime expressions
Example Suppose youve created a grid of particles, and your animations starting frame number is 0. You create this runtime expression for its velocity attribute:
particleShape1.velocity = <<0,time,0>>;
The expression increases the Y component of velocity with the increasing value of time as the animation plays. This makes all particles in the grid rise with increasing velocity as the time increases. An increasing velocity is the same as acceleration.
You need to use the statement in a runtime expression rather than a creation expression, because youre increasing a value in the assignment each frame. Using the statement in a creation expression would instead set the velocity to a constant value <<0,0,0>>, because time equals 0 when the creation expression executes for the particle grid. Example The previous examples gave all particles the same value for the velocity attribute. You can instead give each particle a different value for an attribute. Suppose youve created a grid of 121 particles.
PARTICLE EXPRESSIONS | 6
Writing runtime expressions
Suppose further you create this runtime expression for its acceleration attribute:
particleShape1.acceleration = sphrand(2);
The expression executes once for each of the 121 particles each time the runtime expression executes. The sphrand(2) function provides a vector whose randomly selected components reside within an imaginary sphere centered at the origin and with a radius of 2. Each particle receives a different vector value. For details on the sphrand function, see sphrand in Chapter 7. Because each particle receives a different random vector for its acceleration each frame, the particles accelerate individually in a constantly changing direction and rate as the scene plays. This gives the acceleration abrupt changes in direction.
PARTICLE EXPRESSIONS | 6
Writing runtime expressions
Important
To give particles a constant acceleration, assign the acceleration attribute a constant 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 the oversample level is 3, there are 3 timesteps per frame, and so on. Example Suppose youve set your animations starting frame to 0, and youve used the Particle Tool to place a single particle at the origin:
When you play the animation, the runtime expression takes control of the attribute. 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.
PARTICLE EXPRESSIONS | 6
Writing runtime expressions
Each subsequent frame moves the particle upward at a rate set by the incrementing value of time.
When you stop and rewind the animation, the particle moves back to the origin, the particles original position when you created it with the Particle Tool. When you created the particle, Maya stored its original position in an internally maintained initial state attribute named position0. For details, see Understanding initial state attributes on page 156. Because the attribute has no creation expression controlling its value, Maya sets the attribute to its initial state position0 value of <<0,0,0>>. To prevent the particle from jumping back to the origin after rewinding, you can write a creation expression thats the same as the runtime expression:
particleShape1.position = <<3,time,0>>;
PARTICLE EXPRESSIONS | 6
Working with particle attributes
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 following frames, it moves upward synchronized with the increasing value of time. Though this example showed how to initialize the position attribute with a creation expression, you could have gotten almost the same result by saving the objects current attribute values for initial state usage: To save the current attributes for initial state usage: 1 2 Select the particle shape node. Advance the animation to frame 1. Here the position of the particle is <<3, 0.0417, 0>>. 3 From the Dynamics menu set, select Solvers > Initial State > Set for Selected. When you rewind the animation, Maya positions the object at the initial state setting of its position attribute. This setting is <<3, 0.0417, 0>> because you selected Set for Selected while the position was equal to <<3, 0.0417, 0>>.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Note
See List of particle attributes on page 193 for attributes you can use with particle objects.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
For a particle shape node attribute, you can tell whether its a per particle or per object attribute by examining the Attribute Editors particle shape tab. All per particle attributes appear in the Per Particle (Array) Attributes section of the tab. The per object attributes appear elsewhere in the tab. Most appear above the Per Particle (Array) Attributes section, for example, in the Particle Attributes and Render Attributes sections. For many dynamically added attributes, you can also tell whether they are per particle or per object by their names in the Expression Editor. If a name ends with PP, its per particle. Otherwise, its usually per object. Note that position, velocity, and acceleration are per particle attributes, though their names dont end with PP. The most common way to create dynamic per object or per particle attributes for a particle shape is by clicking the Opacity or Color buttons in the Add Dynamic Attributes section of the Attribute Editor. For example, if you click the Opacity button, a window appears and lets you choose whether to add the opacity characteristic as a per object attribute or a per particle attribute. If you choose per particle, the Attributes list of the Expression Editor displays a new attribute for the selected particle shape node: opacityPP. If you choose per object, an opacity attribute is displayed instead. If you add both a per particle attribute and a per object attribute for a characteristic, the per particle attribute takes precedence. For instance, if you add opacity and opacityPP, the opacityPP attribute controls the opacity of the particles of the specified object.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Important
You can use per particle attributes only in particle expressions. You can use per object attributes in particle or nonparticle expressions. If you use a runtime expression to read or write a per object attribute of a particle object with many particles, you can speed up expression execution by reading or writing the attribute in a nonparticle expression. Nonparticle expressions execute only once per object. Particle expressions execute once for each particle in the object. Because reading or writing a per object attribute more than once per frame is redundant, you can save processing time by working with them in nonparticle expressions.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Though an initial state attribute doesnt appear in the Expression Editor, you can read its value, for example with a print statement, to retrieve the initial state. 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 to add it with Add Initial State Attribute on or off. If you choose on, Maya creates a corresponding initial state attribute for the added attribute. If you choose off, Maya doesnt create a corresponding initial state attribute for the added attribute. Without this corresponding attribute, you cant save a particle objects current attribute values for initial state usage. You must write a creation expression if you decide to initialize the custom attributes value upon rewinding the animation.
Note
A per particle attribute is called an array attribute in the Add Attribute window. The two terms have the same meaning. See Assigning to a custom attribute on page 162 for details. You can see whether a custom attribute was added with Add Initial State Attribute on or off by using the MEL listAttributes command. (See the online MEL documentation for details.) You might want to read the value of an initial state attribute in an expression, for instance, to use its original (rewind) value for some calculation. If you assign a value to an initial state attribute. Maya will overwrite 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 name with a 0 character. Youll subvert Mayas naming scheme for the initial state attribute associated with an attribute. For any attribute, if you dont initialize its value with a creation expression or save its value for initial state usage, Maya gives the attribute a default value at the animations first frame. It typically assigns the attribute the value 0 or <<0,0,0>>, as appropriate for the data type. In other cases, for instance, opacityPP and opacity, Maya assigns the attribute a default value of 1.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
If you know youre going to write a creation expression for a custom attribute, you can set Add Initial State Attribute off when you add the attribute. Otherwise, set Add Initial State Attribute on whenever you add a custom attribute. When a creation expression assigns a value to an attribute, the value overrides the attributes initial state value for all particles whose age is 0.
The following steps show how to assign values to opacityPP so that each particle has a different random opacity. To use a per particle opacityPP attribute: 1 2 In the workspace, turn on Shading > Smooth Shade All. Select the particle shape node of Squares in the Outliner or Hypergraph.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
In the Add Dynamic Attributes section of the Attribute Editor, click the Opacity button. A window appears that prompts you to choose whether to add the attribute per object or per particle.
Select Add Per Particle Attribute, then click the Add Attribute button. This adds an opacityPP attribute to the particle shape node of Squares. You can set the value of opacityPP to give each particle a different opacity.
5 6 7
Select the particle shape node of Squares in the Expression Editor. Turn on Creation in the Expression Editor. Create the following expression:
SquaresShape.opacityPP = rand(1); print("Hello\n");
Rewind the animation. Because opacityPP is a per particle attribute and the objects particle shape node is selected in the Expression Editor, the expression does an execution loop of both statements once for each particle in the object. Because the expression is a creation expression, it executes after the expression compiles. It also executes when you rewind the animation after playing it. For each of the particles, the first statement assigns the opacityPP attribute a random floating point number between 0 and 1. The rand function returns a different random number each time it executes, so each particle has a different opacityPP value between 0 and 1. Each particle therefore has a different opacity at birth. For details on the rand function, see chapter 7, Functions. The second statement displays Hello in the Script Editor, once for each particle. When you play the animation, the creation expression does not execute. The particles therefore retain the opacity they received upon rewinding.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Every time you play then rewind the animation, each particle receives a new random opacity. The creation expression executes the random function each time you rewind. If you were to use the preceding expression as a runtime expression rather than creation expression, the opacity of each particle would change each frame as the animation plays. In each frame, the runtime expression would execute, assigning a different random value between 0 and 1 to the opacityPP of each particle.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
In the Add Dynamic Attributes section of the Attribute Editor, click the Opacity button. A window appears that prompts you to choose whether to add the attribute per object or per particle.
Select Add Per Object Attribute, then click the Add Attribute button. This adds the opacity attribute to the particle shape node for Squares.
5 6 7
Play the animation. The runtime expression executes each frame during playback. The statement in the expression executes once for each particle and assigns the opacity attribute an identical value between 0 and 1 according to the linstep function (see linstep on page 253 for details). The values rise gradually from 0 to 1 for the first five seconds of the objects existence.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
or
In the Add Dynamic Attributes section of the Attribute Editor, click the General button. The Add Attribute window appears:
PARTICLE EXPRESSIONS | 6
Working with particle attributes
3 4 5
Enter a name for the attribute in the Attribute Name box. Make sure Make attribute keyable is on. Select one of the following data types:
Vector Float Integer Boolean
Creates a vector attribute consisting of three floating point values. Creates a floating point attribute. Creates an integer attribute. Creates an attribute consisting of an on/off toggle.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Scalar
Creates a per object attribute that you can set to a single value that applies to every particle in the object. A vector scalar is considered a single value with three numbers. Creates a per particle attribute. You can set this type of attribute to different values for each particle.
Array
If you select Scalar, you can specify Minimum, Maximum, and Default values for a Float or Integer attribute. Minimum and Maximum set the lowest and highest values you can enter for the attribute in the Attribute Editor or Channel Box. Default sets the default value displayed for the attribute. Because youre going to control the attributes value with an expression, you might want to skip entering values for these options. An expression isnt bound by the Minimum and Maximum values. The attribute receives whatever value you assign it in the expression. The expression can read the attributes Default value or any other value you give it in the Attribute Editor or Channel Box. When you select Scalar, you cant create a counterpart initial state attribute by turning on Add Initial State Attribute.
If you select Array, you can also create a counterpart initial state attribute by turning on Add Initial State Attribute. See Understanding initial state attributes on page 156 for details. You cant set Minimum, Maximum, or Default values for an Array attribute.
Click Add if you want to add more attributes. Click OK to add the attribute and close the Add Attribute window. The new attribute appears under the Extra Attributes section of the Attribute Editor. Although the attribute name is always spelled with an uppercase first letter in the Attribute Editor, you must use the exact spelling shown in the Expression Editor, whether lowercase or uppercase. To assign values to a custom attribute: You can assign values to a custom attribute with the same techniques you use to assign values to static or dynamic attributes.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Example Suppose youve created a 10-particle object named sunspot, and you add to its particle shape node a float scalar (per object) attribute named glow. You assign the glow attribute a value in a creation expression as follows:
sunspotShape.glow = 11.5; print (sunspotShape.glow + "\n");
When you rewind the animation, the glow attribute of sunspotShape receives the value 11.5. The print statement displays the value in the Script Editor. The value appears 10 times because the expression executes once for each particle in the object. Example Suppose you add a vector array (per particle) attribute named heat to the 10particle sunspot shape node. You can give each particle a different value as in this creation expression:
float $randomNumber = rand(1); sunspotShape.heat = <<$randomNumber,0,0>>; print(sunspotShape.heat + "\n");
When you rewind the animation, the expression loops through 10 executions, once for each particle. The first statement sets the $randomNumber variable to a random number between 0 and 1. The next statement assigns a vector to the heat attribute of a single particle. The left component of the vector assigned to heat is a different random number each time the statement executes. The middle and right 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.
Note
If you add a custom vector attribute to an object, Maya displays the attribute in the Attribute Editor, but you cant enter its value there. You must enter a value for it in an expression or with the Component Editor available from the Attribute Editor.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Suppose you write this runtime expression with TwoPtsShape2 selected in the Object Selection list:
ThreePtsShape.position = TwoPtsShape2.position; print(ThreePtsShape.position+"\n");
In the first frame of runtime expression execution, this assigns the position attribute of TwoPts to the position attribute of ThreePts. In other words, the expression repositions the three particles to the position of the two particles.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Because you selected TwoPtsShape in the Object Selection list, the expression will execute once for each of its two particles. When you play the scene, the runtime expression executes. The first particle of ThreePts now is at the position of the first particle of TwoPts. The second particle of ThreePts is at the position of the second particle of TwoPts. The third particle of ThreePts doesnt change position. The expression executes only twice each frame. In summary, the particles in ThreePts are at these positions:
5 0 0 6 0 0 -3 0 0
Suppose you write the preceding runtime expression instead with ThreePtsShape selected in the Object Selection list. Again, the expression repositions the three particles to the position of the two particles. Because you selected ThreePtsShape in the Object Selection list, the expression executes once for each of its three particles. When you play the scene, the runtime expression executes. The first particle of ThreePts moves to the position of the first particle of TwoPts. The second particle of ThreePts moves to the position of the second particle of TwoPts. Because TwoPts lacks a third particle, the third particle of ThreePts is repositioned at the position of the first particle of TwoPts. You cant see this in the workspace because the particles are in the exact same position. The three particles in ThreePts are at these positions:
5 0 0
PARTICLE EXPRESSIONS | 6
Working with particle attributes
6 0 0 5 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 and assigns 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 with the Particle Tool, and position the particles somewhere in the workspace. Suppose further you select the particle shape node of FivePts in the Expression Editor, then make this assignment in a runtime expression:
FivePtsShape.position = TwoPtsShape2.position;
The five particles move to these positions as soon as the runtime expression executes for the first time:
5 6 5 6 5 0 0 0 0 0 0 0 0 0 0
PARTICLE EXPRESSIONS | 6
Working with particle attributes
The runtime expression for the same particle shape node cant read the contents of the $oldposition variable. To solve this problem, you can create an attribute for the object, assign it a value in the creation expression, then use the attribute value in a runtime expression. For example, suppose you create an attribute named oldpos, and assign it the 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 dont need to create an attribute to hold the objects initial position. The initial position already exists in its initial state attribute named position0. This attribute doesnt appear in the Expression Editors Attributes List.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Note
If dynamics and an expression influence position, velocity, or acceleration the instant at which the expression executes, the resulting object motion is affected. If the expression executes before dynamics, Maya computes the dynamics using the value assigned by the expression. If the expression executes after dynamics, Maya calculates dynamics based on any attribute values left over from the previous frame or values generated by an input ramp. To set whether expressions execute before or after dynamics, select the particle object, display the Attribute Editor, and turn Expressions After Dynamics on or off. Example Suppose a particle drops under the influence of a gravity field with default gravity options. Gravity accelerates the particle at 9.8 units per second per second 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 particles velocity from the expression statement. The velocity increases 1 unit per second in an X-axis direction. Maya then adds the gravitational acceleration to the velocity. Maya uses the combined result to compute the particles position. Of course, you wont see this calculation process. The frame displays the particle in the appropriate position after all computation. Note that the expression adds the constant <<1,0,0>> to the particles velocity each frame as the animation plays. This makes the particle move with increasing velocity in an X direction as the time increases. An increasing velocity is the same as acceleration.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
The ball represents the particles position after several frames. The white squares represent the particles position as time increases.
Gravity alone
The acceleration attribute works differently than the position or velocity attributes in an important way. Maya initializes its value to <<0,0,0>> before each frame. If the oversample level is greater than 1, this initialization occurs before each timestep. Example Suppose you write the following runtime expression for a five-particle object unaffected 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. This happens 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. The acceleration of the particle becomes <<0,1,0>> plus <<0,-9.8,0>>, which equals <<0,-8.8,0>>. The acceleration assigned in the expression slows the downward acceleration of the gravity. Suppose you change the previous expression to this:
acceleration = acceleration + sphrand(3);
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Because Maya sets acceleration to <<0,0,0>> before each frame, the statement has the same result as the following statement:
acceleration = sphrand(3);
As each frame plays, Maya first calculates each particles acceleration from the expression statement. Each particle receives the result of the sphrand(3) function. The sphrand(3) function provides a vector whose randomly selected components reside within a spherical region centered at the origin with radius 3. Each particle receives a different vector value. Finally, Maya adds gravitys acceleration to the expression acceleration resulting from sphrand(3). The frame displays each particle in the resulting position. Because of the random values resulting from the expression, each particle has an acceleration that differs slightly from gravity in direction and magnitude. Because the sphrand(3) function executes for each particle each frame, the acceleration of each particle varies each frame.
Position at rewind Gravity in combination with acceleration = sphrand(3)
This example shows that you can take advantage of the additive effect of fields and the acceleration attribute to create custom field effects.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Tip
You can turn off the effect of all fields on a particle shape node attribute by setting its dynamicsWeight attribute to 0.
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 the attribute that lets you color them. 2 In the Add Dynamic Attributes section of the Attribute Editor, click the Color button.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
A window appears that prompts you to choose whether to add the attribute per 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. Because youre adding this attribute as a per particle attribute, you can give each particle a different color. 4 Choose Shading > Smooth Shade All. This step is necessary to make the correct particle color appear when you assign the rgbPP attribute a value in an expression. 5 6 In the Expression Editor, select Bubbles particle shape node. Turn on Creation in the Expression Editor. Because youll give the particles a color that doesnt change during the animation, you use a creation expression. 7 Enter this expression:
BubblesShape.rgbPP = <<1,0,0>>;
When you click the Create button in the Expression Editor, Maya checks the syntax of the expression. Assuming you made no typing errors, the expression executes once for each of the 100 particles. The expression colors all particles in the object red. The double angle brackets << and >> enclose a vector that sets the red, green, and blue components 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 rewind the animation. The particles remain red for entire animation because the red color is never changed by a runtime expression.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Tip
See the online version of this documentation for colored illustrations. The following steps show how to give the particles a randomly changing color as the animation plays. To give the particles a randomly changing color: 1 2 3 4 With BubblesShape selected in the Expression Editor, turn on Runtime. Enter this runtime expression:
BubblesShape.rgbPP = sphrand(1);
Click the Create button to compile the expression. Rewind the animation. Because the creation expression executes when you rewind, the particles are red.
Play the animation. The runtime expression takes control of the rgbPP attribute. Because rgbPP is a per particle attribute, the runtime expression executes for each particle in the object each frame. For each particle, the expression assigns the rgbPP attribute the output from the execution of the sphrand function with an argument of 1.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
The sphrand function assigns each particles rgbPP color a random vector. The vector represents a random point in a spherical region of radius 1. The left, middle, and right rgbPP color components have a value no less than -1 and no greater than 1. Values less than 0 are treated as 0. The sphrand function returns a different random vector each execution. So each particle has a different random rgbPP value, and therefore, a different color. 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 because the 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 of animation. To slow the change of color: 1 Change the runtime expression to this:
if ((frame % 24) == 0) BubblesShape.rgbPP = sphrand(1);
This expression uses the modulus operator (%) to control when the rgbPP attribute of the particles receives a random color. The modulus operator returns the remainder after division. For example, 24 divided by 24 returns 0, but 25 divided by 24 returns 1. (Dividing 25 by 24 equals 1 with a remainder of 1.)
PARTICLE EXPRESSIONS | 6
Working with particle attributes
If the value of frame divided by 24 is equal to any number with a remainder of 0, the assignment to BubblesShape.rgbPP occurs. In other words, the assignment occurs when frame equals 24, 48, 72, and so on. At an animation rate of 24 frames/second, the assignment happens once each second.
Important
Avoid using the modulus operator with floating point values. Because of number rounding in floating point division, you wont likely get a return value of exactly 0 with the modulus operator. Instead use an integer value when possible. 2 Rewind and play the animation. When you rewind the animation, the particles turn red because the creation expression executes. When the animation plays, the particles receive a random color once each second.
1 second
2 seconds
3 seconds
Note that you can change the red rewind color to random colors by changing the creation expression to this:
BubblesShape.rgbPP = sphrand(1);
PARTICLE EXPRESSIONS | 6
Working with particle attributes
To write an expression for emitted particles: 1 2 3 Create the emitter. Add the desired dynamic attribute to the shape node of the emitted particles. Select the shape node of the emitted particles in the Expression Editor, then write the expression to control the attribute. Example Suppose youve created an emitter and added a per particle opacityPP attribute to the shape node of the emitted particles. The following creation expression gives each of the emitted particles a random opacity between 0 and 1:
particleShape1.opacityPP = rand(1);
Important
Avoid assigning a per particle attribute to another objects per particle attribute if the particles of either object die (because youve used a lifespanPP attribute). As particles die, the order of expression evaluation changes for the objects particles. This causes unexpected results. You can, though, assign from one attribute to another in the same object with dying particles. The array indexes of the different attributes are in synch with each other. For example, if your particles have a lifespanPP of 2, dont write an expression like this: emittedShape.rgbPP = otherParticleShape.rgbPP
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Select Particles > Particle Collision Events from the Dynamics menu bar. The Particle Events window appears.
Click Create Event. This adds an event attribute to the selected particle shape node. The Expression Editor displays the added event attribute in the Attributes list. Close the Particle Events window. To write the expression:
1 2
Select the particle shape node of the colliding particles. Write the runtime or creation expression using the value of any of these attributes of the colliding particles shape node:
Short name
Description Contains the number of times each particle in the object has hit something (on a per particle basis).
eventCount
evc
Total number of events that have occurred for all particles of the object. True if an event has occurred since the last time an expression or MEL getAttr command read the eventTest value.
integer
eventTest
evt
boolean
The eventCount and eventTest are static attributes. A particle shape node has them as soon as you create the particle object. Though they dont appear in the Expression Editor, you can use their values in an expression. You must first create the event attribute as described previously.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Example Suppose youve created a five-particle object named Peas that falls with gravity and collides with a plane.
You can make the particles turn red when the first particle hits the plane. 1 Choose Shading > Smooth Shade All. This step is necessary to make the correct particle color appear when you later use an expression to color particles. 2 3 4 Select PeasShape in the Outliner or Hypergraph. From the Dynamics menu bar, select Particles > Particle Collision Events. In the Particle Events window, click Create Event, then close the window. This adds an event attribute to PeasShape. 5 In the Add Dynamic Attributes section of the Attribute Editor, click Color. The Particle Color window appears. 6 Select Add Per Particle Attribute, then click Add Attribute. This adds a per particle attribute named rgbPP. This attribute controls the red, green, and blue color scheme of each particle.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
The particles turn black after you add the rgbPP attribute. Adding the rgbPP attribute turns off the default coloring of the particles and gives them a value of <<0,0,0>>. 7 With PeasShape selected in the Expression Editor, create this runtime expression:
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>>;
Rewind the animation. Upon rewind, the particles are black. The particles have the default black rgbPP color because no creation expression exists for the object.
Play the animation. The particles fall toward the plane. The runtime expression executes as each frame plays. The event attribute is a per particle attribute. This isnt obvious because its name doesnt have PP as the last two characters. Because event holds a running count of collisions for each particle, event contains 0 for each particle until the first collision with the plane. Until the first collision occurs, the final else statement executes:
else rgbPP = <<1,1,1>>;
This statement executes because event doesnt equal 1, 2, 3, or a number greater than 3. The vector <<1,1,1>> in the RGB color scheme represents the color white. When the first particle of PeaShape hits the plane, Maya sets the event attribute for that particle to 1. This triggers execution of the first assignment, which sets the colliding particles rgbPP value to <<1,0,0>>. In the RGB color scheme, this vector value represents red. (When red equals 1, green equals 0, and blue equals 0, the resulting color is red.)
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Tip
See the online version of this documentation for colored illustrations. Note that the value of the event attribute reflects the collision count in the frame after each collision. For example, if a particle collides with the plane in frame 10, event is updated in frame 11. When the other particles hit the plane for the first time, they also turn red after they collide.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
A particle stays red until it collides with the plane for the second time, when event equals 2. After a second collision, the particle turns green. After a third collision, when event is equal to or greater than 3, a particle turns blue. Each particle stays blue for all subsequent collisions as the animation 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 black for the frame that appears upon rewinding. For example, you can give the particles a white color upon rewinding with two techniques: Write this creation rule for PeasShape:
rgbPP = <<1,1,1>>;
This statement executes for each particle in the object, so they all receive the same white color when you rewind the scene. Select PeasShape, rewind the animation, and play the animation to frame 2. Then select Solvers > Initial State > Set for Selected.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
This saves all PeasShape attribute values from the current frame for the initial state of the attributes. The current value for rgbPP will be used when you rewind the animation. Because you played the second frame of the animation, this saves the white color of the particles at that frame for use upon rewinding the animation. Note that Set for Selected saves all attribute values, including position, velocity, acceleration, and so on. In cases where you have several changing attribute values during playback, Set for Selected might save undesired attribute values in addition to the desired ones. In such cases, use a creation expression.
This works in Maya 3.0, but only if have you have lifespan mode set to lifespanPP only. Now the way to write this expression is:
opacityPP = 1 - age/finalLifespanPP;
This works for all lifespan modes because finalLifespanPP always stores the actual lifespan used for the particles in all modes. Pre-Maya 3.0 expressions that refer to lifespanPP will work correctly now as long as you select lifespanPP only as the lifespan mode. If you select Constant or Random Range mode, you can read the value finalLifespanPP, not lifespanPP. You need to use finalLifespanPP only if you intend to make use of one of the other lifespan modes.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
Each particle has a unique numerical particle identifier. A particles identifier 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 a particleId in sequential order starting at 0. For example, suppose you use the Particle tool to create a five-particle object by clicking positions in the workspace. The first click of the mouse creates a particle 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 in sequential order starting with the first particle emitted. The first emitted particle has particleId 0, the second has particleId 1, the third has particleId 2, and so on. You can assign per particle attribute values to specific particles using the particleId attribute. Example Suppose youve used the Particle tool to create a grid of nine particles named ColorGrid. In the Attribute Editor, youve set the Render Type of the particles to Spheres. Youve chosen Shading > Smooth Shade All to display the particles with shading.
You can give the particles different colors based on their particleId. To color the particles based on particleId: 1 Select the ColorGrid.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
In the Add Dynamic Attributes section of the Attribute Editor, click Color. The Particle Color window appears.
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. When the particles are not selected, they turn black after you add the rgbPP attribute. Adding the rgbPP attribute turns off the default coloring of the particles and gives them a value of <<0,0,0>>.
In the Attribute Editor, choose Numeric from the Render Type menu. The particleId of each particle is displayed instead of spheres:
With ColorGridShape selected in the Expression Editor, enter this creation expression:
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. The particles dont show the color assignments yet. The Numeric particle render type 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:
PARTICLE EXPRESSIONS | 6
Working with particle attributes
The expressions first statement assigns a red color to all particles whose particleId is less than or equal to 2. The value <<1,0,0>> is red in the RGB color scheme. The second statement assigns a white color to all particles whose particleId is greater than 2 and less than 6. The value <<1,1,1>> is white in the RGB color scheme. The third statement assigns a blue color to all particles that dont meet the conditions in the prior two statements. In other words, all particles whose particleId is greater than or equal to 6 become blue. The value <<0,0,1>> is blue in the RGB color scheme. The following steps show another common way to control an attribute based on the particleId attribute. 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>>;
Play the scene. The runtime expression executes each frame as the animation plays. Particles with even-numbered particleIds are red. The odd-numbered particles are blue.
PARTICLE EXPRESSIONS | 6
Working with particle attributes
The first statement uses a modulus operator (%) to calculate the remainder of dividing a particleId by 2. It then compares the remainder to 0. If the remainder 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 the modulus operation doesnt equal 0. The value <<0,0,1>> is blue. For example, dividing particleId 0 by 2 equals 0 with remainder 0. Because the remainder is 0, the particle having particleId 0 receives a red color. Dividing particleId 1 by 2 equals 0 with remainder 1. Because the remainder is 1, the particle having particleId 1 receives a blue color. Dividing particleId 2 by 2 equals 1 with remainder 0. With remainder 0, the particle having particleId 1 receives a blue color. The expression executes for each particle in the object. The result is that even-numbered particleIds become red, odd numbered particles become blue. 3 Rewind the animation. The creation expression executes. The particles become red, white, and blue as described for the previous expression. 4 Play the animation. The runtime expression executes each frame. The particles are red and blue as the animation plays.
PARTICLE EXPRESSIONS | 6
Assigning to vectors and vector arrays
Note to programmers
You cannot assign values to individual particles with the array index notation commonly used in programming languages. For example, suppose youve created an opacityPP attribute for an object made of three particles. You cant assign values as in this example:
opacityPP[0] = 0.3; opacityPP[1] = 0.5; opacityPP[2] = 1;
This assigns the value of vector variable $top_velocity to the vector variable $temp.
PARTICLE EXPRESSIONS | 6
Assigning to vectors and vector arrays
This assigns the right component of $myvector, 3, to the floating point variable $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>>;
An error occurs. A statement can read, but not directly assign, a component of a vector variable.
PARTICLE EXPRESSIONS | 6
Assigning to vectors and vector arrays
Example Suppose you have a 100-particle Cloud of randomly positioned particles. You turn on Shading > Smooth Shade All, add a per particle rgbPP attribute. then enter the following creation expression:
CloudShape.position = sphrand(1); vector $pos = CloudShape.position; CloudShape.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 spherical region of radius 1. The sphrand(1) function gives the X, Y, and Z position components a value no less than -1 and no greater than 1. The second statement assigns a particles position to a vector variable $pos. The third statement assigns an RGB color to a particles rgbPP attribute. The left, middle, and right vector components of CloudShape.rgbPP represent red, green, and blue components of the RGB color scheme. The third statement therefore assigns 0 (no color) to the red and blue components of a particles colorRGB. It gives a particles green component the value of its Y coordinate position. Because a value of 0 or less results in a 0 green value, a particle is black if its below the XZ plane. If a particles Y coordinate position is above the XZ plane, it has a green component varying from nearly 0 to a fully saturated green. This colors the particles from black to green, depending on the position.
PARTICLE EXPRESSIONS | 6
Assigning to vectors and vector arrays
Increasingly green
Example
particleShape1.rgbPP = <<1,0,CloudShape.position.z>>;
This causes an error. Maya interprets CloudShape.position.z as being an attribute named z of an object named CloudShape.position. You can get the intended result with these statements:
vector $temp = CloudShape.position; particleShape1.rgbPP = <<1,0,$temp.z>>;
The first statement reads all three components of vector attribute CloudShape.position and assigns it to the vector variable $temp. The second statement reads the value of the right component of $temp, which contains the right component of CloudShape.position. It then assigns this component to the right component of particleShape1.rgbPP. Example
particleShape1.rgbPP.y = 1;
This also causes an error. You cant assign a value to a vector array attribute component.
PARTICLE EXPRESSIONS | 6
List of particle attributes
Attribute long name (and short name) acceleration (acc) age (ag)
Description Sets the rate of change of velocity on a per particle basis. Contains the number of seconds each particle in the object has existed since the first frame. This is a readonly attribute.
PARTICLE EXPRESSIONS | 6
List of particle attributes
Description Specifies the name of the attribute whose values are to be displayed at particle positions. By default, particle id numbers are displayed. Valid for Numeric render type. Provides smoother lighting and shadowing at the expense of increased processing time. Valid for Cloud render type. Stores the position at which each particle was born in the particles local space. Contains the Current Time value at which each particle in the object was created. This is a read-only attribute. Turns on or off dynamic state caching for the object. Turns on or off the objects ability to cast shadows in software rendered images. Valid for Cloud, Blobby Surface, and Tube render types. Contains the X, Y, and Z elements of the average position of its particles. These are read-only attributes. Sets how much the colliding particles velocity parallel to the surface decreases or increases as it bounces off the collision surface. This attribute is displayed as Friction in the user interface. It works on a per geometry basis. Sets how much rebound occurs when particles collide with a surface. This attribute is listed as Resilience in the user interface. It works on a per geometry basis.
betterIllumination*
boolean
birthPosition birthTime (bt) cacheData (chd) castsShadows (rsh) centroidX, centroidY, centroidZ (ctdx, ctdy, ctdz) collisionFriction (cfr)
float
float (multi)
collisionResilience (crs)
float (multi)
PARTICLE EXPRESSIONS | 6
List of particle attributes
Description U and V positions of the NURBS surface where a particle collided in the current frame. For polygonal surfaces, the values are always 0. The values are reset to -1 at the start of each frame. Values change only in frames where collision occurs. These are read-only attributes. Adds the RGB components of overlapping particles. Also adds opacity values of overlapping particles. Generally, colors become brighter and more opaque as they overlap. To see the effect of Color Accum, you must add an opacity attribute to particles displayed as Points. Valid for MultiPoint, MultiStreak, Points, and Streak render types. Sets blue component of RGB color. Valid for all render types except Numeric and Tube. Sets green component of RGB color. Valid for all render types except Numeric and Tube. Sets red component of RGB color. Valid for all render types except Numeric and Tube. Sets how much of a particle objects velocity attribute value is retained from frame to frame. Contains the total number of particles in the object. This is a read-only attribute. Sets the time value for the particle objects independent clock. Turns on or off depth sorting of particles for rendering. This prevents unexpected colors when you hardware render overlapping colored, transparent particles. Valid for MultiPoint, MultiStreak, Points, Streak, and Sprites render types.
colorAccum*
boolean
colorBlue* colorGreen* colorRed* conserve (con) count (cnt) currentTime (cti) depthSort (ds)
PARTICLE EXPRESSIONS | 6
List of particle attributes
Attribute long name (and short name) dynamicsWeight (dw) emissionInWorld (eiw)
Description Scales the effect of fields, collisions, springs, goals, and emission on particles. When on, emission occurs in the world coordinate system. This is the default setting. When off, emission occurs in the emitted particle objects local space. Sets the per particle emission rate. In a soft body, if you change the original geometrys construction history in a way that alters the number of CVs, vertices, or lattice points, Maya updates the number of particles of the soft body correspondingly. Contains the number of times each particle in the object has hit something. This is a read-only attribute. Sets whether expressions are evaluated before or after other dynamics. Contains the accumulation of all forces acting on the particle object. This is a read-only attribute. If you use this attribute in an expression, first turn on expressionsAfterDynamics. Sets whether forces are applied to the object in world space or in its local space. For a goal object, turns each goal on or off. It has the same effect as setting the corresponding goalWeight to 0, except the animation processing is more efficient. This attribute works on a per object basis.
event*
PARTICLE EXPRESSIONS | 6
List of particle attributes
Attribute long name (and short name) goalOffset* goalPP* goalSmoothness (gsm) goalU, goalV* goalWeight (gw) incandescencePP*
Description Sets an offset to the world space position of the goal object. Sets how much the particles try to follow the goal on a per particle basis. Sets how smoothly goal forces change as the goal weight changes from 0 to 1. The higher the number, the smoother the change. Set the exact locations on a NURBS surface where the particles are attracted. Sets sets how much all particles of the object are attracted to the goal. Sets glow color in conjunction with a software rendering Particle Incand Mapper Node (see Using Maya: Rendering.) Valid for Cloud and Tube render types. Sets the (decimal) fraction of velocity an emitted particle object inherits from an emitter. For a soft body, this sets the coordinate space Maya uses to position point data provided by the input geometry to the particle shape. Turns on or off dynamic animation of the object. Contains 1 if an emitted particle shape is full, or 0 if not full. An emitted particle shape is full when the number of emitted particles equals the maxCount. This is a read-only attribute. Sets when all particles in the object die.
float integer
boolean boolean
lifespan*
float
PARTICLE EXPRESSIONS | 6
List of particle attributes
Attribute long name (and short name) lifespanPP* levelOfDetail (lod) lineWidth * mass (mas) mass0 (mas0) maxCount (mxc) multiCount*
Description Sets when particles die on a per particle basis. Scales the number of particles that can be emitted into the emitted particle object. Sets the width of streaking particles. Valid for MultiStreak and Streak render types. Specifies the physical mass of particles. Mass values affect the results of dynamic calculations. By default, each particle of a particle object has a mass of 1. Initial state counterpart to mass. Sets a limit on the number of particles the emitted particle shape accepts from an emitter. Sets number of points you want displayed for each particle in the object. Valid for MultiPoint and Points render types. Sets radius of spherical region in which particles are randomly distributed. Valid for MultiPoint and MultiStreak render types. Turns on or off the ability to read the parentU and parentV attributes. If you add a surface emitter to a NURBS surface, parentU and parentV contain the UV coordinates where each particle was emitted. You can use these attributes in expressions and MEL scripts. Sets direction of normal for particles. Use with useLighting. Valid for MultiPoint, MultiStreak, Points, and Streak render types.
Data Type float array float float float array float array int float
multiRadius*
float
needParentUV*
boolean
normalDir*
integer (1-3)
PARTICLE EXPRESSIONS | 6
List of particle attributes
Description Sets amount of transparency for all particles in the object. Valid for all render types except Numeric and Tube. Sets amount of transparency on a per particle basis. Valid for all render types except Numeric, Tube, and Blobby Surface. Contains the id number of each particle. Valid for Numeric render type. This is a read-only attribute. If you emit from a particle object, this contains the id of all particles that emit the particles. You can use the id to query the emitting objects attribute values, for example, acceleration, velocity, and lifespanPP. This is a read-only attribute. Note that if you use the MEL emit command to create the particles that emit, the parentId attribute of those emitted particles is always 0.
opacityPP*
parentU, parentV*
If you add a surface emitter to a NURBS surface, these attributes contain the UV coordinates where each particle was emitted. To use these read-only attributes, you must turn on Need Parent UV in the emitter. You can use these attributes in expressions and MEL scripts. Sets render display type of particles, for example, Streak. Sets how large particles are displayed. Valid for MultiPoint, Numeric, and Points render types. Sets the object position in local space coordinates on a per particle basis.
float array
PARTICLE EXPRESSIONS | 6
List of particle attributes
Attribute long name (and short name) position0 (pos0) radius* radius0* radius1* radiusPP* rampAcceleration (rac) rampPosition (rps) rampVelocity (rvl) rgbPP*
Description Initial state counterpart to position. Sets radius size of all particles. Valid for Blobby Surface, Cloud, and Sphere render types. Sets starting point radius for Tube render type. Sets ending point radius for Tube render type. Sets radius size on a per particle basis. Valid for Blobby Surface, Cloud, and Sphere, render types. Controls acceleration with a ramp. Any other animation of acceleration is added to the rampcontrolled acceleration. Controls position with a ramp. Any other animation of position is added to the ramp-controlled position. Controls velocity with a ramp. Any other animation of velocity is added to the ramp-controlled velocity. Sets color on a per particle basis. Valid for MultiPoint, MultiStreak, Points, Spheres, Sprites, and Streak render types. Sets the id of the random number generator of the associated emitter. This attribute works on a per object basis. Contains the value of the time difference between the last displayed frame and current frame. This contains 1 if youre simply playing the animation or clicking the frame forward or backward button. If you click widely separated frames in the Time Slider, the attribute contains the difference in time between the two frames. This is a read-only attribute.
Data Type vector array float float float float array vector array vector array vector array vector array float (multi) time (in current units)
PARTICLE EXPRESSIONS | 6
List of particle attributes
Attribute long name (and short name) selectedOnly* spriteNum* spriteNumPP* spriteScaleX, spriteScaleY* spriteScaleXPP, spriteScaleYPP* spriteTwist* spriteTwistPP* startFrame (stf) surfaceShading*
Description Turns on or off display of id numbers only for selected particles. Valid for Numeric render type. Sets the image number index for a Sprite image sequence. Sets the image number index for a Sprite image sequence on a per particle basis. Sets the Sprite X- and Y-axis image scale. Sets the Sprite X- and Y-axis image scale on a per particle basis. Sets the Sprite images rotation angle. Sets the Sprite images rotation angle on a per particle basis. Sets the animation frame after which dynamics (including emission) are computed for the object. Sets how sharply the spheres of Cloud render type are displayed. Use a value between 0 and 1. A value of 1 displays spheres more distinctly; a value of 0 creates a cloudier effect. Sets the opacity of tail fade. Valid for MultiStreak and Streak render types. Sets the length of the tails for MultiStreak, Streak, and Tube render types. For a soft body, sets the coordinate space Maya uses to position point data provided by the particle shape to the target geometry.
Data Type boolean integer integer array float float array float float array float float
PARTICLE EXPRESSIONS | 6
List of particle attributes
Description Controls surface blending between Cloud or Blobby surface spheres. This is a read-only attribute. Contains the animation frame increment in current units. For example, if your animation is set to Film (24 fps), timeStepSize has a value of 1 (frame). Keying or otherwise setting the Current Time value alters the timeStepSize. For instance, with a frame rate of 24 frames per second, suppose you set the Current Time to 0 at frame 0, and to 100 at frame 50. Because youre compressing twice as much time between frames 0 and 50, the timeStepSize is twice as large, in other words, 2. This is a read-only attribute.
Contains total events that have occurred for all particles of the object. This is a read-only attribute. Sets the maximum number of collisions Maya can detect for the object in each animation time step. Sets the trace depth on a per particle basis. Turns on or off whether scene lighting lights up particles. Valid for MultiPoint, MultiStreak, Points, Sprites, and Streak render types. Predefined outputs for user-defined attributes used in Particle Sampler Info node.
float array
PARTICLE EXPRESSIONS | 6
List of particle attributes
Attribute long name (and short name) userVector1PP userVector2PP userVector3PP userVector4PP userVector5PP velocity (vel) velocity0 (vel0) visibleInReflections (rrl) visibleInRefractions (rrr) worldBirthPosition worldCentroidX, worldCentroidY, worldCentroidZ (wctx, wcty, wctz) worldPosition (wps) worldVelocity (wvl) worldVelocityInObjectSpace (wvo)
Description Predefined outputs for user-defined attributes used in Particle Sampler Info node.
Sets speed and direction on a per particle basis. Initial state counterpart to velocity Turns on or off whether the object is visible in reflections when software rendered. Valid for Cloud, Blobby Surface, and Tube render types. Turns on or off whether the object is visible in refractions when software rendered. Valid for Cloud, Blobby Surface, and Tube render types Stores the position at which each particle was born in world space. Contains the world space X, Y, and Z elements of the average position of its particles. These attributes are a read-only attributes. Contains the world space counterpart to position. This is a read-only attribute. Contains the world space counterpart to velocity. This is a read-only attribute. Contains the local space equivalent to the objects world space velocity. This is a read-only attribute.
boolean
PARTICLE EXPRESSIONS | 6
List of particle attributes
FUNCTIONS
In expressions, you can use built-in operations called functions to create motion, particle positioning, and other effects. This chapter explains the most commonly used functions and a few useful MEL commands.
A hermite function shaped the lightnings soft body geometry, dnoise animated its turbulence, and sphrand enhanced its randomness.
Matt Baer
For easy reference, this chapter groups functions by their purpose. For example, all math functions are grouped in the same section.
FUNCTIONS | 7
To find out about: Understanding functions Function syntax Limit functions abs ceil floor clamp min max sign trunc Exponential functions exp log log10 pow sqrt
See page: 208 209 212 213 213 214 214 215 215 216 216 217 217 217 218 218 219
FUNCTIONS | 7
To find out about: Trigonometric functions cos cosd sin sind tan tand acos acosd asin asind atan atand atan2 atan2d hypot Vector functions angle cross dot mag rot unit Conversion functions hsv_to_rgb rgb_to_hsv deg_to_rad rad_to_deg Array functions clear size sort
See page: 219 219 222 222 227 228 228 229 229 230 230 230 231 231 231 232 233 233 233 234 235 236 237 238 239 240 238 238 240 240 241 241
FUNCTIONS | 7
Understanding functions
To find out about: Random number functions gauss noise dnoise rand sphrand seed Curve functions linstep smoothstep hermite General commands eval print system Other functions and commands
See page: 242 242 244 246 246 248 250 253 253 256 258 263 263 265 267 268
UNDERSTANDING FUNCTIONS
A function generates a value where it occurs in an expression statement. It takes action based on parameters called arguments that you enclose in parentheses next to the function name. Example Suppose you have an object named Star whose translateX attribute is set with this expression statement:
Star.translateX = rand(10);
In this statement, the rand function has the argument 10. With this argument, the function generates a randomly selected floating point number between 0 and 10 each time the statement executes. For example, translateX
FUNCTIONS | 7
Function syntax
might be assigned 6.5409 the first time the statement executes, 3.2974 the second time, 8.7389 the third time, and so on. This causes Star to jump to random 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, they all have at least one argument and generate one value. Note that a function is part of an expression statement. They dont stand alone in an expression. Many functions do mathematical operations. For example, the sin function generates the sine of a specified angle. Though we often provide explanatory figures and details, we assume youre familiar with the mathematical purpose 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 go beyond the basics of expression writing: sin or sind linstep smoothstep hermite noise dnoise rand sphrand print
FUNCTION SYNTAX
To help you quickly reference different functions, this chapter includes a syntax 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.
FUNCTIONS | 7
Function syntax
datatype to the left of the function name indicates the data type returned when the function executes. Note that for either datatype, you dont type a value. The datatype tells you the type of data you must enter or the data type returned by the executed function. The data types are in small type size for easy identification in the syntax definitions. Example 1
int
float
The function name is abs, which returns the absolute value of the number of your choice. The absolute value of a number is the number without its positive or negative sign. This example shows the abs function has three formats. Each version requires an argument with a different data type and returns a value with a different data type. The first version indicates that you can type an integer argument, and the function 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 a vector. 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
This function returns the radian equivalent of to a degree value. It expects a floating point argument and returns a floating point number. Note that Maya ignores spaces between components of functions. For example, the functions in each of these expressions work the same:
FUNCTIONS | 7
Function syntax
Tip
To see the list of functions available in expressions, click the Insert Functions menu in the Expression Editor and peruse the contents. If you select a function from the menu while the cursor is in the Expression text field, Maya inserts the function name in the text.
Data types
In many cases, entering a data type other than the type expected by a function causes an error and prevents the expression from executing. For example, if you enter a vector argument where a floating point number is expected, an error occurs. For a function argument that expects a floating point number, however, you can instead type an integera number without a decimal point. Maya converts an integer to a floating point number in arithmetic operations. If an error occurs when you create an expression, check that youre using the appropriate data types for all arguments.
Notes
In this book, examples of floating point return values show no more than three digits to the right of the decimal point. If you display the contents of an attribute or variable in the Script Editor, youll see as many as 10 digits to the right of the decimal point. For instance, an example might show a return value as 3.539 rather than the precise value 3.538654390. The examples round up such numbers for ease of reading. Note also that converting radians to degrees and vice versa results in rounding errors. For example, converting a radian value might result in 89.99999996 degrees rather than 90.0 degrees.
FUNCTIONS | 7
Limit functions
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 that assigns a value to an attribute or variable. 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 the returned value to an attribute, the statement has no effect.
abs(-1);
Returns 1, but doesnt assign it to an attribute. This has the same result as the following meaningless statement:
1;
In some function examples in this chapter, the functions purpose is easier to understand in the context of an expression. In such cases, we show examples of the function in an expression.
LIMIT FUNCTIONS
The limit functions are math functions that impose limits on numbers.
abs
Returns the absolute value of number. The absolute value of an integer or floating point number is the number without its positive or negative sign. The absolute value of a vector is a vector with components stripped of negative signs.
FUNCTIONS | 7
Limit functions
int
float
vector
number is the number for which you want the absolute value. Examples
abs(-1)
ceil
Returns a number rounded to the smallest integer value greater than or equal to a floating point number.
float
ceil(float number)
Returns 3.
ceil(3.0)
Returns 3.
ceil(Rock.scaleY)
FUNCTIONS | 7
Limit functions
floor
Returns a number rounded to the largest integer less than or equal to a floating point number.
float
floor(float number)
Returns 2.
floor(3.0)
Returns 3.
floor(Head.height)
clamp
Returns a number within a range. You can use the clamp function to confine an increasing, decreasing, or randomly changing number to a range of values.
float
minnumber and maxnumber specify the range of the returned value. parameter is an attribute or variable whose value you want to clamp within the range. If parameter is within the numerical range of minnumber and maxnumber, the function 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)
FUNCTIONS | 7
Limit functions
Returns a value between 0 and 3 each time the expression executes. When you rewind the animation to frame 1, the above expression executes and Balls scaleY attribute receives the value of timea number slightly above 0. The clamp function returns the value of time because time is within the range 0 to 3. When you play the animation, time increments slightly with each frame. The expression executes with each frame and Balls scaleY attribute receives the value of time until time exceeds 3. When time exceeds 3, the clamp function returns the value 3.
min
Returns the lesser of two floating point numbers.
float
Returns -3.2.
Desk.height = -2; Lamp.height = 9; $Mylight = min(Desk.height,Lamp.height);
max
Returns the larger of two floating point numbers.
float
FUNCTIONS | 7
Limit functions
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.
sign
Returns one of three values representing the sign of a number. Returns -1 if the number is negative, 1 if positive, 0 if 0.
float
Returns -1.
sign(0)
Returns 0.
sign(10)
Returns 1.
sign(Ball.translateX)
trunc
Returns the whole number part of a floating point number.
float
trunc(float number)
FUNCTIONS | 7
Exponential functions
Returns 2.
trunc(0.3)
Returns 0.
trunc(-2.82)
Returns -2.
trunc(time)
EXPONENTIAL FUNCTIONS
The following functions work with exponential values.
exp
Returns e raised to the power of a number, enumber. The predefined variable e is the base of the natural logarithm, which is 2.718.
float
exp(float number)
log
Returns the natural logarithm of a number, logenumber. The natural logarithm uses the constant e, which is 2.718.
float
log(float number)
number is the positive number for which you want the natural logarithm.
FUNCTIONS | 7
Exponential functions
Examples
log(10)
Returns 2.303.
log(2.718282845904)
Returns 1.000.
log10
Returns the log base 10 of a number.
float
log10(float number)
number is the positive number for which you want the log base 10. Examples
log10(100)
Returns 2.
log10(10)
Returns 1.
pow
Returns a base number raised to an exponent.
float
base is the base number you want to raise to the exponent. A negative base number 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)
FUNCTIONS | 7
Trigonometric functions
Returns 0.125.
sqrt
Returns 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.
sqrt($side)
TRIGONOMETRIC FUNCTIONS
The following functions return trigonometric values. Each function has two formats that let you choose the type of angular unit you work with: degrees or 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. Note that pi equals 3.1415927, which is also 180 degrees.
cos
Returns 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:
FUNCTIONS | 7
Trigonometric functions
A B X A C
If is less than 1/2 pi radians and more than 3/2 pi radians (from 270 to 90 degrees), cos is a value between 0 and 1.
If is between 1/2 pi radians and 3/ 2 pi radians (90 to 270 degrees), cos is a value between 0 and -1.
The cosine ratio depends only on the size of the angle and not on the size of the triangle. This constant ratio is called the cosine of the measure of the angle. The cosine ratio is a value between -1 and 1. With a steadily increasing or decreasing argument, the cos function returns steadily increasing or decreasing values between 1 and -1. This is useful for creating rhythmic, oscillating changes in attribute values. The cos function works like the sin function except its return values are 90 degrees, or pi/2, out of phase. See page 222 for ideas on how to use the cyclical characteristics of the sin and cos functions. Example 1
cos(1)
FUNCTIONS | 7
Trigonometric functions
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 the incrementing animation time. Its Y translation moves cyclically up and down according to the return values of the cos function. The cos function uses translateX, and therefore indirectly, time, as its argument. As time increases from 0 to 6.283 seconds, the cos function returns values that change in fine increments from 1 to -1 and back to 1. The value 6.283 is 2 times the value of pi. As time increases beyond 6.283 seconds, the same cycle repeats for each span of 6.283 seconds.
Ball.translateY = cos(Ball.translateX);
FUNCTIONS | 7
Trigonometric functions
Ball.translateY = sin(Ball.translateX);
The cosine curve is 1.571 (pi/2) seconds ahead of (or behind) the sine curve, and vice versa.
cosd
Returns 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 preceding topic. The cosd and cos functions do the same operation, but cosd requires its argument in degree measurement units. Example
cosd(45)
sin
Returns 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:
FUNCTIONS | 7
Trigonometric functions
A B X A C
If is from pi to 2 pi radians (180 to 360 degrees), sin is a value between 0 and -1.
The sine ratio depends only on the size of the angle and not on the size of the 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 returns steadily increasing or decreasing values between -1 and 1. This is useful for creating rhythmic, oscillating changes in attribute values. For example, you can use the sin function to manipulate: an objects translate attributes to create snake-like motion a bodys scale attributes to create a breathing cycle a particle objects opacity or color attributes to cycle a color or opacity pattern Example 1
float $pi = 3.1415927; sin($pi/2)
FUNCTIONS | 7
Trigonometric functions
This statement sets Balls translateY attribute equal to the sine of its translateX attribute. If you drag Ball along the X-axis, Balls translateY position 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);
Ball starts at the origin and moves in the X direction at a rate set by the incrementing animation time. Its Y translation moves cyclically up and down according to the return values of the sin function. The sin function uses translateX, and therefore indirectly, time, as its argument. As time increases from 0 to 6.283 seconds, the sin function returns values that change in fine increments from 0 to 1 to -1 to 0. The value 6.283 is 2 times the value of pi. The resulting motion resembles a horizontal S-shape:
FUNCTIONS | 7
Trigonometric functions
As time increases beyond 6.283 seconds, the same S-shaped cycle repeats for each 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 increase the amplitude of the sine wave pattern. The amplitude is half the distance between the minimum and maximum values of the wave.
Amplitude
You can decrease the amplitude of the sine wave by multiplying by a number 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);
FUNCTIONS | 7
Trigonometric functions
By multiplying Ball.translateX by a number greater than 1, you increase the frequency of the sine wave pattern. The frequency is how long it takes the wave to make a complete cycle.
Frequency
You can decrease the frequency of the sine wave by multiplying by a number less than 1, for example, 0.5. This number is known as a frequency multiplier 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 Yaxis. You can, of course, also subtract a number to offset the wave pattern lower on the Y-axis.
Offset of 2
Example 7 The following expression sets a frequency multiplier, amplitude, and offset of a sine pattern in a single statement:
Ball.translateX = time;
FUNCTIONS | 7
Trigonometric functions
Ball.translateY = (sin(Ball.translateX * 2) * 2) + 2;
The following diagram shows which values set the frequency multiplier, amplitude, and offset.
Frequency multiplier Amplitude Offset Ball.translateY = (sin(Ball.translateX * 2) * 2) + 2;
A general equation showing the factors you can use to create a sine wave pattern follows:
attribute = (sin(frequency * frequency multiplier) * amplitude) + offset;
sind
Returns 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 the preceding topic. The sind and sin functions do the same operation, but sind requires its argument in degree measurement units. Example
sind(90)
FUNCTIONS | 7
Trigonometric functions
tan
Returns 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:
A B X A C
The ratio depends only on the size of the angle and not on the size of the triangle. This constant ratio is called the tangent of the measure of the angle. Example
tan(1)
Returns 1.557.
tand
Returns the tangent of an angle specified in degrees.
float
tand(float number)
FUNCTIONS | 7
Trigonometric functions
For more details on the tand function, see the tan function in the preceding topic. The tand and tan functions do the same operation, but tand requires its argument in degree measurement units. Example
tand(45)
acos
Returns the radian value of the arc cosine of a number. The arc cosine is the angle whose cosine is the specified number. The returned value is from 0 to pi.
float
acos(float number)
Returns 0.
acos(-0.5)
acosd
Returns the degree value of the arc cosine of a number. The arc cosine is the angle whose cosine is the specified number. The returned value is from 0 to 180.
float
acosd(float number)
Returns 0 degrees.
acosd(-0.5)
FUNCTIONS | 7
Trigonometric functions
asin
Returns the radian value of the arc sine of a number. The arc sine is the angle whose sine is the specified number. The returned value is from -pi/2 to pi/2.
float
asin(float number)
asind
Returns the degree value of the arc sine of a number. The arc sine is the angle whose sine is the specified number. The returned value is from -90 to 90.
float
asind(float number)
Returns 30 degrees.
atan
Returns the radian value of the arc tangent of a number. The arc tangent is the 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)
FUNCTIONS | 7
Trigonometric functions
Returns 0.785.
atand
Returns the degree value of the arc tangent of a number. The arc tangent is the 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.
atan2
Returns 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 the origin 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 )
atan2d
Returns 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 the origin 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 )
FUNCTIONS | 7
Trigonometric functions
Returns 45 degrees.
hypot
Returns the magnitude of two-dimensional vector from the origin to a point with coordinates X, Y.
Y hypot
(X,Y) X
As shown in the preceding figure, the hypot function returns the radius of a circle whose center is at one end of a right triangles hypotenuse and perimeter is at the other end of the hypotenuse. The following equation gives the magnitude of the vector:
x +y
float
hypot(float x, float y)
FUNCTIONS | 7
Vector functions
Example
hypot(3,4)
Returns 5.
VECTOR FUNCTIONS
The following functions do operations with vectors. The functions take vector arguments and return floating point numbers or vectors.
angle
Returns the radian angle between two vectors.
Vector1
Angle
Vector2
float
vector1 is one of the vectors. vector2 is the other vector. The returned angle is the shortest angle between the two vectors. The measurement is always less than 180 degrees. Example
angle(<<2,-1,1>>,<<1,1,2>>)
cross
Returns the cross product of two vectors.
FUNCTIONS | 7
Vector functions
For two vectors, the cross product returns the vector thats normal to the plane defined by the two vectors.
Vector1
Vector2
Cross product
vector
If the cross product is 0, the two vectors are parallel or colinear. If one or both 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>>)
dot
Returns the floating point dot product of two vectors. The dot product takes two vectors as arguments and returns a scalar value.
float
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>>)
FUNCTIONS | 7
Vector functions
Returns 1. The dot product of this example is (1 * 3) + (2*0) + (-2*1), which equals 1.
mag
Returns the magnitude of a vector. This is the length of the vector.
float
mag(vector vector)
vector is the vector whose magnitude you want. The mag function converts a vector into a floating point number using the following formula.
2 2 2
x +y +z
Example
mag(<<7,8,9>>)
Returns 13.928.
2 2 2
7 + 8 + 9 = 13.928
FUNCTIONS | 7
Vector functions
rot
Returns a vector that represents the position of a point after its rotated a specified number of radians about a specified axis. Rotation is counterclockwise as viewed downward from the axis end position.
Position of point before rotation Angle Position of point after rotation
Axis
vector
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 passes through the origin and the specified axis position. angle is the number of radians the point rotates. Example 1
rot(<<3,3,0>>,<<1,0,0>>,0.5)
Returns <<3, 2.633, 1.438>>. This is a vector representing the position of point <<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);
FUNCTIONS | 7
Vector functions
Suppose your scene has a single-particle object at position <<4,6,0>>, and you wrote the above runtime expression for its particle shape node. When you 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 particles position rotates 0.1 radian, roughly 5.7 degrees.
Motion Particle
unit
Returns the unit vector corresponding to a vector. The unit vector has the same direction as the specified vector, but with a magnitude of 1.
vector
FUNCTIONS | 7
Conversion functions
CONVERSION FUNCTIONS
The following functions convert color scheme values or angle measurements.
deg_to_rad
Returns the radian equivalent of a degree value. One radian equals roughly 57.29578 degrees.
float
rad_to_deg
Returns the degree equivalent of a radian value. One radian equals roughly 57.29578 degrees.
float
rad_to_deg(float radians)
FUNCTIONS | 7
Conversion functions
Examples
rad_to_deg(1)
Returns 57.296.
float $pi = 3.1415927; rad_to_deg($pi)
Returns 180.
hsv_to_rgb
Converts 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>>)
Tip
To see the relationship between HSV and RGB color components, enter the MEL command colorEditor at the Command Line. This displays the Color Chooser window. In the windows hexagonal color wheel, drag the pointer to a color of interest. The edit boxes in the window list the colors values for hue, saturation, and valueand their counterpart red, green, and blue values. Note, however, that the Hue value in the Color Chooser has a range of 0 to 360, while the H component of an HSV vector has a corresponding proportional range of 0 to 1. When you launch the Color Chooser by entering colorEditor, its useful only for learning about color. You cant use it to change the color of objects in your scene.
FUNCTIONS | 7
Array functions
rgb_to_hsv
Converts an RGB vector to an HSV vector.
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>>)
ARRAY FUNCTIONS
The following functions work with integer, floating point, and vector arrays. If you need more information, see a reference book on the C programming language.
clear
Empties the arrays contents, freeing all memory reserved for the array. After you clear an array, its size is 0. When you no longer need to use an array, 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 return value 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 Script Editor:
size of $myInts is: 6
FUNCTIONS | 7
Array functions
size
Returns the number of elements in an array or the number of characters in a string.
int int
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);
sort
Returns an array sorted in alphabetical or ascending numerical order. The returned array has the same number and type of elements as the original array.
array sort(array array)
FUNCTIONS | 7
Random number functions
print($afterSorting[$i]+"\n"); }
The sort function sorts the elements of $myInts in ascending order. The following appears in the Script Editor:
After sorting, the array contains: 1 2 3 4 5 6
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. The following appears in the Script Editor:
After sorting, the array contains: Kennedy Michael Peewee
gauss
Returns a random floating point number or vector. The number returned falls within a Gaussian (bell curve) distribution with mean value 0.
FUNCTIONS | 7
Random number functions
float
vector vector
stdDev specifies the value at which one standard deviation occurs along the distribution. This gives a one-dimensional Gaussian distribution. XstdDev and YstdDev specify the values for one standard deviation. This gives a two-dimensional Gaussian distribution in the XY plane. The right component of the vector returned is 0. stdDevVector specifies the vector component values for one standard deviation. This gives a three-dimensional distribution. To control the random values returned by this function, see seed on page 250. Example
gauss(5)
Returns a random floating point value such as 0.239. If you were to execute gauss(5) repeatedly and chart the values returned, they would occur roughly with this frequency:
Mean One standard deviation
Number of occurrences
-5
Value returned
If you were to execute gauss(2) repeatedly, return values would occur with this frequency:
FUNCTIONS | 7
Random number functions
Number of occurrences
-2
Value returned
noise
Returns a random number from -1 to 1 according to a Perlin noise field generator.
float float float
number specifies a number that generates a random number. This gives a one-dimensional distribution of return values. xnum and ynum specify numbers for generating a random number. This gives a two-dimensional distribution of return values. vector specifies a vector for generating a random number. This gives a threedimensional distribution of return values. If you execute this function with the same argument value repeatedly, the function returns the same random value each time it executes. If you execute this function with an argument value that steadily increases or decreases in fine increments over time, the function returns random values that increase and decrease over time. Example 1
noise(time)
FUNCTIONS | 7
Random number functions
Returns a value between -1 and 1 each time the expression executes as an animation plays. Because time increases in fine increments, the values returned increase and decrease in smooth, yet random, patterns. If you were to chart the values returned over a period of time, they might occur as in this figure:
Example 2
noise(frame)
Returns a value between -1 and 1 each time the expression executes as an animation plays. Because frame increases in larger increments, the values returned increase and decrease in rougher patterns. If you were to chart the values 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 frame contains 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.
FUNCTIONS | 7
Random number functions
dnoise
Returns a vector with each component containing a random number from -1 to 1. It works like the noise function except it expects and returns a vector argument. The returned vector represents the gradient of the noise field in three dimensions.
vector
dnoise(vector argument)
argument specifies a vector for generating a random number. This gives a three-dimensional distribution of return values. See the noise function for more details on dnoise operation. Example
dnoise(<<10,20,-30>>)
rand
Returns a random floating point number or vector within a range of your choice.
float float
rand(float maxnumber) rand(float minnumber, float maxnumber) rand(vector maxvector) rand(vector minvector, vector maxvector)
vector vector
maxnumber specifies the maximum number returned (in the first syntax format 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 numbers returned. maxvector specifies the maximum value for each component of the vector returned. The minimum value is 0. Each component returned is a different random number. minvector and maxvector specify the minimum and maximum value for each component of the vector returned.
FUNCTIONS | 7
Random number functions
To control the random values returned by this function, see seed on page 250. 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. If you were to execute rand(-1,1) repeatedly as an animation plays, its return values 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, for example, <<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 is between 1 and 300. An example is <<81.234, 49.095, 166.048>>.
FUNCTIONS | 7
Random number functions
sphrand
Returns a random vector value that exists within a spherical or ellipsoidal region of your choice. An ellipsoid is a sphere scaled along its X-, Y- or Zaxes.
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 page 250. Example 1
sphrand(1)
Returns a vector whose randomly selected coordinates reside within an imaginary sphere centered at the origin and with a radius of 1. An example returned vector is <<0.444, -0.427, 0.764>>.
radius
Example 2
sphrand(<<2,1,1>>)
Returns a vector whose coordinates reside within an ellipsoid centered at the origin and with a radius of 2 along the X-axis, 1 along the Y-axis, and 1 along the Z-axis.
FUNCTIONS | 7
Random number functions
Radius in Z 1 1
To create a particle ellipsoid: You can use the sphrand function, for example, to create a cluster of 500 particles randomly positioned within an ellipsoid having a radius of 2 in the X-axis, 1 in the Y-axis, and 1 in the Z-axis. 1 2 3 4 5 6 Select Particles > Particle Tool-. Enter 500 for Number of Particles, and 1 for Maximum Radius. Click the mouse somewhere in the workspace to position the particles. Select the particle shape node of the particle object in the Expression Editor. Turn on Creation. Enter this expression:
position = sphrand(<<2,1,1>>);
Maya executes the expression once for each particle. It gives each particle a different random position around the origin within the ellipsoid specified by <<2,1,1>>.
FUNCTIONS | 7
Random number functions
seed
Sets a seed value the gauss, rand, and sphrand functions use to generate random numbers. If you assign a value to the seed then execute the gauss, rand, or sphrand function repeatedly, an identical sequence of random numbers is generated. For clarification, see the example below and Reproducing randomness on page 115.
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);
When you rewind the animation, Balls translateX attribute receives a random value between 0 and 5, for example, 1.392. When you play the animation, the translateX attribute receives a different random value between 0 and 5 each frame. When you rewind the animation again, the translateX attribute receives a value thats 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 value each frame thats different from the values it received the first time you played the animation. In short, every time the rand(5) executes, it gives a different random value. Suppose you change the expression to this:
FUNCTIONS | 7
Random number functions
Rewinding the scene to frame 1 executes the seed(1) function. It then assigns translateX a random value between 0 and 5, for example, 4.501. When you play the animation, the rand(5) function executes each frame and returns a different value. Example returned values follow:
Frame 1 2 3 4 5 6
Each time you rewind and play the animation, translateX receives the same sequence of random values. For different seed values, the sequence of numbers returned will differ. You cant predict the values in the number sequence based on the value of the seed. 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 the animation:
FUNCTIONS | 7
Random number functions
Frame 1 2 3 4 5 6
By changing the seed functions value, you change the sequence of random numbers generated. A common mistake while using the seed function follows:
seed(1); Ball.translateX = rand(5);
When you rewind the animation, Balls translateX attribute receives the value 4.501. When you play the animation, the translateX attribute receives 4.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 therefore returns the first value of the number sequence each time it executes.
Important
When you set a seed value in an expression or MEL script, the seed value affects the rand, sphrand, and gauss functions in other expressions and MEL scripts. Such functions are affected by this seed value in all scenes you open subsequently in the current work session.
FUNCTIONS | 7
Curve functions
CURVE FUNCTIONS
The step functions let you make smooth, incrementing transitions between values.
linstep
Returns a value from 0 to 1 that represents a parameters proportional distance between a minimum and maximum value. This function lets you increase an attribute such as opacity from 0 to 1 linearly over a time range.
float
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 youve used the Particle Tool to create a collection of particles named Cloud:
Suppose further youve added a dynamic per object opacity attribute to Cloud (see Working with particle attributes in Chapter 6). You then write this runtime expression for Clouds particle shape node:
CloudShape.opacity = linstep(0,5,age);
FUNCTIONS | 7
Curve functions
This expression increases the per object opacity attribute of CloudShape in equal steps from 0 to 1 for the first 5 seconds of the objects existence. Because you created the object with the Particle Tool, the particles existence begins in the first frame of the animation. All particles in the object fade in from transparent to opaque for the first 5 seconds of animation. At the first frame that plays, the age of the particles is 0, so the linstep function returns 0 for the opacity. An opacity of 0 is transparent. In each subsequent frame, the linstep function returns a proportionally larger opacity value. When the age of the object reaches 5, the linstep function returns 1 for the opacity. An opacity of 1 is 100% opaque. When the age exceeds 5, the linstep function returns 1. The opacity stays 100% opaque. Here are some values returned for the objects opacity:
Age 0.0417 0.0833 0.125 0.1667 0.2083 2.5 1.0 3.75 5 5.041 5.083 10
FUNCTIONS | 7
Curve functions
As the table shows, the opacity increases in linear increments for the first 5 seconds of the objects age. At the midpoint of the specified 0 to 5 second age range, the opacity is 0.5. At 3/4 of the way between 0 and 5 seconds, the opacity is 0.75. At 5 seconds of the objects age, opacity is 1. After 5 seconds, the opacity stays at 1.
1 opacity
This increases the opacity attribute linearly from 0 to 1 as the objects age increases from 5 to 10 seconds.
1
opacity
10
This decreases the opacity attribute linearly from 1 to 0 for the first 5 seconds of the objects age. Subtracting linstep(0,5,age) from 1 causes the opacity to fade out rather than fade in. USING MAYA: EXPRESSIONS 255
FUNCTIONS | 7
Curve functions
opacity
smoothstep
Returns a value from 0 to 1 that represents a parameters proportional distance between a minimum and maximum value. The smoothstep function lets you increase an attribute such as opacity from 0 to 1 gradually, but nonlinearly, over a time range. The smoothstep function works like the linstep function, except it increases values more quickly near the middle values between the minimum and maximum value. The function uses hermite interpolation between minimum and maximum values.
float
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. The following figure compares values returned by smoothstep and linstep over time:
FUNCTIONS | 7
Curve functions
parameter
smoothstep
linstep
start
end
Example Suppose youve used the Particle Tool to create a collection of particles named Cloud:
Suppose also youve added a dynamic per object opacity attribute to Cloud (see Working with particle attributes in Chapter 6). You then write this runtime expression for Clouds particle shape node:
CloudShape.opacity = smoothstep(0,5,age);
FUNCTIONS | 7
Curve functions
This increases the opacity attribute of CloudShape in steps from 0 to 1 for the first 5 seconds of the objects age. This makes the object fade in from transparent to opaque. The fade in and fade out of the opacity occurs more quickly around 2.5, the midpoint between 0 and 5.
1
opacity
hermite
Returns values along a hermite curve. You can use the hermite function, for instance, to move a particle objects position smoothly along a curve. As the examples in the following pages show, you can create various curve shapes by altering the arguments to the hermite function.
vector float
hermite(vector start, vector end, vector tan1, vector tan2, float parameter)
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 as it leaves the start point of the curve. The vectors position starts at the start point of the curve. tan2 is the tangent vector that guides the direction and shape of the curve as it approaches the end point of the curve. The vectors position starts at the end point of the curve. parameter is an floating point value between 0 and 1, for example, the value returned by a linstep function.
FUNCTIONS | 7
Curve functions
In the second format, the arguments and return values work in a single dimension. 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 four seconds 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 curves direction and shape as it leaves the start point. The tangent vector <0,3,0> sets the curves direction and shape as it approaches the end point. From zero to four seconds of animation play, the particle moves along the curve as defined by the linstep function. (See page 253 for details on linstep.) The function arguments and resulting path of the object follow:
Y tan2 = <<0,3,0>>
end = <<2,2,0>>
Objects path
start = <<0,0,0>>
tan1 = <<3,0,0>>
Example 2 Suppose you change the third argument of the previous example expression to <<6,0,0>>:
FUNCTIONS | 7
Curve functions
The slope of the path curve steepens because of the longer tan1 vector:
Y tan2 = <<0,3,0>>
end = <<2,2,0>>
tan1 = <<0,3,0>>
tan2 = <<0,3,0>>
FUNCTIONS | 7
Curve functions
The tan1 vector <<0,3,0>> sets the direction of the curve from the start point to a positive Y direction. The tan2 vector <<0,3,0>> sets the direction of the curve to a positive Y direction as it approaches the end point. Values between the start and end point curves are interpolated to form an S pattern. Example 4 Suppose you change the fourth argument of the previous example expression to <<0,-3,0>>:
dust.position = hermite(<<0,0,0>>,<<2,0,0>>, <<0,3,0>>, <<0,-3,0>>, linstep(0,4,time));
tan1 = <<0,3,0>>
tan2 = <<0,-3,0>>
The tan1 vector <<0,3,0>> sets the direction of the curve from the start point to a positive Y direction. The tan2 vector <<0,-3,0>> sets the direction of the curve to a negative Y direction as it approaches the end point.
FUNCTIONS | 7
Curve functions
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)); Y tan1 = <<0,10,0>>
tan2 = <<0,-3,0>>
Because of the longer tan1 vector, the slope of the path curve steepens as it rises from the start point. Because the tan2 vector has a smaller Y magnitude than the Y magnitude of the tan1 vector, the slope of the path curve is flatter as it approaches the end point. The curves rise in the Y direction is greater than the previous example because the magnitude of tan1s Y component is larger (10 instead of 3).
FUNCTIONS | 7
General commands
GENERAL COMMANDS
The following functions do various actions in Maya.
eval
Executes a MEL command.
string
eval(string command)
command is either a command string enclosed in quote marks or a string variable containing a command. The returned value contains command output returned by the commands execution. 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 the command 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 the command 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 the complete command sphere -r 5. This creates a sphere with a radius of 5 grid units.
FUNCTIONS | 7
General commands
Example 4
string $a[]; $a = eval("ls -lights"); print($a);
The first statement defines an array of strings named $a. The second statement executes the MEL command ls -lights, then assigns the commands output to array $a. The third statement displays the contents of $a to the Script Editor as follows:
ambientLightShape1 directionalLightShape1
Note that each line of command output appears on a new line. Each command output line is an array element. Maya formats array output with each array element on a new line. Example 5 Suppose youve created a MEL script file named bunk.mel in your Maya scripts directory and it contains this procedure:
global proc string bunk() { string $fog; if (rand(2) < 1) $fog = "particle"; else $fog = "sphere"; return $fog; }
The first expression statement executes the bunk() procedure in the bunk.mel script file. In the bunk procedure, the if-else statement generates a random floating point value between 0 and 2, then compares its value to 1.
FUNCTIONS | 7
General commands
If the value is less than 1, the statement assigns the MEL command string particle to $fog. If the value is greater than 1, $fog receives the command string sphere. The procedure finishes executing and passes the value of $fog back to the calling procedure, bunk() in the expression. This assigns the command string to the variable $name. The eval function executes the command string stored in the $name. For example, the statement might execute particle, which creates a particle at the origin 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.
print
Displays text in the Script Editor. You can use this function to display the contents of attributes and variables. This is helpful for debugging an expression. 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 string variable containing text. number is a number without the quote marks. Numerical arguments display as 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 many digits to the right of the decimal point, for example 0.3333333333.
FUNCTIONS | 7
General commands
Insignificant 0 digits are truncated from floating point numbers. For example, floating point number 2.0 is displayed as 2. A vector appears with a space separating components and no double angle brackets. Each vector component has a floating point value with up to 10 digits to the right of the decimal point. For example, a vector <<1.518876356, 0, -1.290387446>> appears in the Script Editor 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"
You cannot use the + operator with a string array. If you assign a string to a variable thats not a string data type, the following text appears if you display the variable: Variable data type float int vector float String assignment "3.14" "3.14" "3.14" "pi is 3.14" Data displayed 3.14 3 3.14 0 0 0, error message
As shown in the last row of the table, if a variable is assigned a string that starts with a non-numerical character, Maya converts the string to 0.
FUNCTIONS | 7
General commands
For a non-particle expression consisting of only print statements, Always Evaluate must be on in the Expression Editor for the expression to execute. Examples
print(time); print("\n");
The first statement displays the value of time. The second statement displays a new-line character after the value of time, so the time appears on a separate line in the Script Editor.
float $f = 3.14159; print($f);
The print function causes an error message because you cannot use the + operator with a string array.
system
For Maya IRIX, this passes an IRIX command to the shell where Maya was started. For Maya NT, this passes a Windows NT command to a Command Prompt in the directory where Maya was started. This is useful for running a program where you need to use the return value output from its execution.
string
command is either a command string enclosed in quote marks or a string variable containing a command. The returned value is the output resulting from the commands execution.
FUNCTIONS | 7
Other functions and commands
Example (IRIX)
string $cmdout; $cmdout = system("date"); print($cmdout+"\n");
Executes the UNIX date command, which outputs your workstations date and time to the $cmdout variable. The final statement displays the date from the $cmdout variable to the Script Editor. Examples (Windows NT)
system("shell mkdir C:\\junkyard > nul: 2>&1");
Makes a directory named junkyard on the C: drive by executing the mkdir command without displaying a Command Prompt window.
system("start write");
Starts WordPad.
FUNCTIONS | 7
Other functions and commands
Curve
FUNCTIONS | 7
Other functions and commands
INDEX
Symbols
! 76 - 50 -- 81 != 53, 54 $ 46, 62 % 50, 177 %= 80 && 55 * 50 *= 80 + 50 ++ 81 += 80 / 50 // 63 /= 80 < 53 << >> 40, 61, 175, 190 <= 53 -= 80 = 33, 41 == 53, 54, 62 > 53 >= 53 ?: 74 \n 266 { } 26, 58, 60, 61 | 135 || 55 absolute value 212 acceleration attribute 194 assigning constant value to 151 assigning with runtime expression 150 changing value randomly 150 fields effect on 170 initialization to zero 171 working with 169 acos function 229 Add Attribute window 36, 112, 162 Add Dynamic Attributes 35, 155 Add Initial State Attribute checkbox 157, 164 adding custom attributes 112, 162 age attribute 194 age of particles at rewind 144 how to examine 144 runtime expression execution and 146 alias UNIX command avoiding use with text editor 99 Always Evaluate 123 Always Evaluate checkbox 110 amplitude of sin function 225 angle function 233 angular units conversion of 120 degrees 15, 119 radians 15, 119 arc cosine 229 arc sine 230 arc tangent 230, 231 arguments in functions 208 arithmetic operators 50 array (per particle) attributes 157 assigning to array of different length 166 array functions 240 array indexes invalid assigment to 190 Array option for per particle attributes 164 arrays 82 clearing contents of 240 display format 267 element assignment 84 example initialization and usage 82 exceeding memory capacity of 82 expansion of 82 invalid assignment to indexes 190 obtaining size of 241 sorting 241 asin function 230 assigning to attributes 41 to int or float variables 47 to specific particles 186 to vector attributes 42 to vector components 190, 191 to vector variables 48 vector to three scalar attributes 42 with getAttr and setAttr 42 assignment operator 33 atan function 230 atan2 function 231 atan2d function 231 atand function 231 Attribute Name attribute 195
A
abbreviating attribute names 103, 106 abs function 212
ANIMATION
INDEX
attribute names renaming as short names 130 attributes abbreviating names 103, 106 assigning conditionally 18 assigning to 41 assigning to multiple 3, 12 assigning to multiple objects 3, 13 connecting to symbolic placeholders 127 custom 36 data types 38 deleting from expressions 124 disconnecting from expressions 125 displayed in Attributes list 8 displaying contents of 115 displaying disconnected 125 dynamic 35 eliminating expression control of 115 full name 38 initial state 152, 156 linking 1, 5, 13 long names 104 name syntax 33 not selecting for particle shape node 102 particle shape node 153 per object 2, 154 per particle 2, 154 reading in expressions 126 removing from expressions 124 seeing abbreviations of 104, 105 static 35 unexpected values 136 Attributes list 94
B
base number raised to exponent 218 bell curve function 243 Better Illumination 195 birthPosition 195 birthTime 195 blank lines in expressions 62 Booleans 38 handling as floating point 52 symbolic constants 84 braces 60 in statements 26 matching pairs of 61 brackets double angle 40, 61, 175, 190 break instruction 68
C
C language escape characters 266 syntax in expressions 63 Cache Data 195 case sensitivity in variable names 46 Casts Shadows 195 ceil function 213 centimeters 119 Centroid 194 centroidX, Y, Z 195 Channel Box displaying attribute values in 16 choice command 125 circular motion of NURBS sphere 111
clamp function 214 clear function 240 clearing an expression 96 array contents 240 collision example of controlling color resulting from 180 working with particles 179 collisionFriction 195 collisionResilience 195 collisionU, V 196 color Christmas light effect with particles 176 giving object constant color 174 giving particles randomly changing color 175 understanding RGB and HSV 239 working with 173 Color Accum 196 Color Blue 196 Color Green 196 Color Red 196 colorEditor 239 comments converting statements to 124 in expressions 63 compiling an expression 8, 49, 110 conditional assignment to attributes 18 conditional statements 57 else-if 59 if 21, 57 if-else 58 confining numerical range 214 connectAttr command 128
INDEX
connecting an attribute 127 Connection Editor 125, 128 Conserve 196 constants 49 Boolean 84 continue instruction 69 controlling flow in statements 65 conversion of angular units only 120 of data types 138, 139 of user selected units 119 conversion functions 238 converting degrees to radians 122 measurement units 121 statements to comments 124 cos function 219 comparison with sin function 221 cosd function 222 cosine 219, 220, 222 cosine wave pattern animating a ball 221 Count 196 Create button 12 Create Event 179 creating new expressions 102 creation expressions 142 assigning to rgbPP 174 dynamics start frame 143 example assignment to lifespan 159 execution for emitted particles 143 how often execution occurs 142 using values in runtime expressions 169 when to use 145 cross function 233
cross product of two vectors 233 Current Time 196 curve functions 253 custom attributes 36 adding to an object 112 adding to particle shape node 162 assigning to 162 examples of assignment 164 when to use 111 custom variables 46 declaring 46 using globally 48 cyclical pattern with sin function 224
D
data types attribute 40 Boolean 38 conversion during assignment 138, 139 conversion of displayed strings 267 conversion with arithmetic operators 140 data entry limitations 40 float array 39 floating point 38 functions 211 integers 38 matrix 41 vector array 39 debugging expressions with print function 266 decimal deletion in data type conversion 139 decimal precision in display 266 declaring variables 46
default object in Expression Editor 94 making an object the 106 deg_to_rad function 238 degrees 15 converting to radians 122, 238 deleting attribute names 124 expressions 102, 127 text from expressions 95 Depth Sort 196 discarded remainders in data type conversions 140 disconnectAttr command 125 disconnecting an attribute 125 displaying attribute contents 115 disconnected attributes 125 text 266 variable contents 115 dnoise function 246 do loop 67 dollar sign ($) in variable names 46, 62 dot function 234 dot product 234 dot product operator 51 double angle brackets 40, 61, 175, 190 dynamic attributes 35 adding to object 35, 36, 155 dynamic per object attribute example assignment to lifespan 160 dynamic per particle attribute example assignment to lifespanPP 158
INDEX
dynamics changing start frame 143 how often Maya evaluates 143, 146 Dynamics Weight 197 dynamicsWeight attribute 173
E
e raised to power 217 Edit button 12 editing text from keyboard 95 editing expressions in text field 89, 95 else keyword 25 else-if statements 59 Emission In World 197 emitted particles age of 144 creation expression execution and 143 local space 197 working with 178 emitterRatePP 197 emitters obtaining UV coordinates 199, 200 Enforce Count From History 197 English common names for attributes 104 equal to (==) operator 23
errors common expression 84 comparing floats with the == operator 78 from wrong data types in functions 211 in flow control statements 76 logic 84 message format of 84 syntax 22, 61, 84 where they appear 85 eval function 264 event attribute 179, 197 when collision count increases 183 eventCount attribute 180 eventTest attribute 180 examining two or more expressions 96 executing MEL commands in expressions 131 MEL commands with eval function 264 MEL procedures in expressions 133 nonparticle expressions 110 execution slow expression 120 exp function 217 exponential functions 217 Expression Editor starting 3
expressions advantage of separate 17 advantage of single 17 comments in 63 common errors 84 comparison with MEL scripts 32 compiling 8 creating new 102 creation 142 default object 94 deleting 102, 124 displaying connected attributes only 94 editing in text field 89 editing with text editor 96 elements of 32, 33 eliminating control of attributes 115 erasing 96 examining two or more 96 execution for nonparticle shapes 110 fields influence on 170 filtering 89 finding 90, 91, 92 for particles 141 input to 126, 128 keyboard editing 95 keywords 64 names for particle shape node 91 naming conventions 7 output from 127, 129 programming features 63 redundant execution 123, 148 reloading 96 required elements of 34 runtime 142 runtime execution 146 saving to file 97
INDEX
slow execution of 120 speeding execution of 119 text field 4 tutorials 5 type case sensitivity 8 when unusable 3 Expressions After Dynamics 197 Expressions list 90, 94
F
fading opacity 253, 258 fields influence on expression 170 turning off effect in an expression 173 filtering attributes by connected attribute 94 from Expression Editor 94 filtering expressions 89 finding expressions by connected attribute 92 by expression name 90 by item type 92 by script node name 90 by selected object 91 float 38, 44 float arrays data type 39 floating point 38 floor function 214 flow control errors 76 flow control statements 65 for loop 67 force attribute 197 Forces In World 197 for-in loop 70 forward slashes (//) for comments 63
frame 0 reason for using in examples 29 frame playback rate 45 frame variable 44 frequency multiplier of sin function 226 frequency of sin function 226 full attribute name 38 functions 33 arguments in 33, 208, 209 array 240 as expression elements 33 complete list of 205 conversion 238 curve 253 data type of arguments 209 data type of returned values 209 essential for advanced expression writing 209 format of 209 introduction to 205 limit 212 others in online documentation 269 random number 115, 116, 242 spaces in 210 trigonometric 219 understanding book examples 212 vector 233
getAttr command 42 global procedures declaring 133 global variables 48 declaring 49 initializing 49 Goal Active 197 Goal Smoothness 198 Goal Weight 198 goalOffset 198 goalPP 198 goalU, V 198 gravity field accelerations effect on 171
H
half-circle creating motion with hermite function 261 hermite function 258 HSV conversion to RGB 239 hsv_to_rgb function 239 hypot function 232
I
if statements 19, 21, 57 if-else abbreviation 74 if-else statements 24, 25, 58 incandescencePP 198 increment operations and unexpected values 137 Inherit Factor 198
G
gauss function 243 Gaussian distribution 243 General button 36 general commands 264
INDEX
initial state attributes 152, 156, 157 creation expression execution 144 naming convention 157 saving values for 153 Input Geometry Space 198 input to expressions 128 integers 38, 44 handling as floating point 52 internal conversion of units 119 Is Dynamic 198 Is Full 198
linstep function 253 comparison with smoothstep 257 listAttributes MEL command 157 log base 10 218 log function 217, 218 logic errors 84 logical operators 55 && 55 || 55 long attribute names 104 looping errors 76
modulus operator (%) 50, 177, 189 risk of using with floats 177 motion creating jittery 169 creating smooth, random 169 Multi Count 199 Multi Radius 199
N
natural logarithm 217 Need Parent UV 200 needParentUV 199 new line characters in print statement 266 noise function 244 returned values with frame argument 246 returned values with time argument 245 Normal Dir 199 not (!) operator 76 number sequences generating consistently random 118 numeric render type 187
J
joining text in strings 267 jot text editor 97
M
mag function 235 magnitude of a vector 55, 235 mass 199 mass0 199 matrix data type 41 Max Count 199 max function 215 measurement units 119 MEL commands 31, 32 executing with eval function 264 using alone in statements 131 using with eval function 132 using within single quotes 132 MEL procedures using in expressions 132 MEL scripts 32 millimeters 121 min function 215 mixed data types using with arithmetic operators 140
K
keyframes eliminating expression to use 115 keywords in expressions 64
L
Level Of Detail 199 Lifespan in expressions 185 lifespan attribute 198 lifespanPP 199 limit functions 212 Line Width 199 linking attributes 1, 5, 13
O
object names omitting in expressions 106 path of 135 Objects list 94 offset with sin function 226 omitting object names in expressions 106 online function documentation 269
INDEX
opacity particle 200 opacity attribute 155 fading over time 253, 258 Opacity button 155 opacityPP 200 opacityPP attribute 155 operators arithmetic 34, 50 assigning values to 23 dot product 51 equal to 23, 53 greater than 53 greater than or equal to 53 less than 21, 53 less than or equal to 53 logical 34, 55 not equal to 53 precedence 56 relational 34, 52 shortcut assignment 80 shortcut increment and decrement 81 order of statements 23 output from expression 127, 129 oversample level 146, 151
P
parentheses matching pairs of 61 use in conditionals 55, 61 parentId 200 parentU, V 200 particle array attributes assigning to different lengths 166 particle attributes list of 194
Particle Collision Events 179 Particle Render Type 200 particleId 200 particleId attribute 186 particles age of 144 assigning to specific 186 attribute data types 38 expressions for 141 moving position with hermite function 258 selecting shape node 142 shape node attributes 153 transform node attributes 153 using sphrand to create ellipsoid of 249 working with collisions 179 path names of objects 135 per object attributes 2, 154 keyframing 154 naming conventions 155 scalar option 164 per particle attributes 2, 39, 154 Array option 164 assigning to individual particles 185 how to distinguish 154, 155 naming conventions 155 performance of getAttr and setAttr 42 Perlin noise field 244 playback rate 45 Point Size 200 position attribute 200 assigning with creation expression 153 assigning with runtime expression 151 fields effect on 170 working with 169
position0 201 pow function 218 precedence of operators 56 precision of float display 266 predefined variables 44 frame 44 time 44 print function 266 programming features 63
R
radians 15, 119 angle between two vectors 233 converting to degrees 238 Radius 201 Radius0 201 Radius1 201 radiusPP 201 rampAcceleration 201 rampPosition 201 rampVelocity 201 rand function 134, 246 rand functions 115, 116 random number functions 115, 242 random numbers making return values consistent 116 redundant expressions 123 relational operators 52 reloading expressions 96 removing an attribute 124 renaming an object 130 render type numeric 187
INDEX
rewinding effect on creation expressions 143 unexpected values 136 RGB conversion to HSV 240 rgb_to_hsv function 240 rgbPP 201 rgbPP attribute example use of 174 rotate function 236 rotating object around its axis 13 points position 236 rounding errors from converting radians to degrees 211 rounding numbers 214 rules of syntax 61 runtime expressions 142, 147 assigning rgbPP in 176 how often execution occurs 142, 146
S
saving an expression 97 saving attribute values for initial state 153, 185 Scalar option for per object attributes 164 scale multiplying by percentage 27 slowing increase of 11 sceneTimeStepSize 201 Script Editor error display 85 scripting with MEL 31 scripts directory 133
Seed 201 seed function 250 making consistent random values 118 Selected Only 202 Selection list 93, 94 semicolon terminator 8, 34, 61 Set for All Dynamic 156 Set For Selected 144 Set for Selected 153, 156 Set forSelected 184 setAttr command 42 shaded spheres how rendered in examples 148 short attribute names renaming as long names 130 shortcut operators assignment 80 increment and decrement 81 sign function 216 sin function 222 equation for various uses of 227 sind function 227 sine 222, 227 size function 241 Smooth Shade All 148 smooth shading setting all objects to 6 smoothly increasing opacity 254 smoothstep function 256 comparison with linstep 257 soft body attributes in common with particles 36 spaces in expressions 62 in functions 210
specific particles assigning to 186 speeding expression execution 119, 120 spheres how shaded in examples 148 sphrand function 115, 116, 134, 150, 172, 248 use with random color 176 Sprite Num 202 Sprite Scale X, Y 202 Sprite Twist 202 spriteNumPP 202 spriteScaleXPP, YPP 202 spriteTwistPP 202 sqrt function 219 square root 219 S-shaped cycle sin function and 225 S-shaped motion creating with hermite function 261 standard deviation with Gaussian values 243 Start Frame 202 starting the Expression Editor 3 statements between { } 58 order of 23 static attributes 35 strings 44, 79 assigning to a vector 80 concatenating with + 79 data type conversion 79, 267 joining 267 syntax rules 79 Surface Shading 202 switch instruction 71 symbolic placeholders 125, 126
INDEX
T
tab characters in expressions 62 Tail Fade 202 Tail Size 202 tan function 228 tand function 228 tangent 228 Target Geometry Space 202 terminator statement 61 text editor changing operation settings 100 quitting 97 selecting 97 selecting default startup 101 using on expression 96 using unlisted 99 valid options 99 Threshold 203 time changing 146 default use of seconds 19 definition 44 negative value of 46 predefined variable 9 relationship to frame 46 value at different frames 9 timesteps 151 timeStepSize 203 Total Event Count 203 Trace Depth 203 traceDepthPP 203
transform nodes not used for particle expressions 146 trigonometric functions 219 trunc function 216 truncating insignificant numbers 216, 267 tutorials for expressions 5
U
unexpected values after incrementing 137 after rewinding 136 in mixed data type division 140 of attributes 136, 138 unit function 237 unit vector 237 units internal conversion of 119, 121 Use Lighting 203 userScalarPP 203 userVectorPP 204
vectors 44 assigning to component of array attribute 191 assigning to variable 190 component operator 190 data type 39 definition 39 dot product 234 format in print function output 267 formula for magnitude 55, 235 magnitude of 2D 232 random vectors with sphrand 248 velocity attribute 204 velocity attribute assigning with creation expression 145 assigning with runtime expression 147, 149 fields effect on 170 working with 169 velocity0 204 vi text editor 97 vim text editor 97 Visible In Reflections 204 Visible In Refractions 204
V
variables 43 as expression element 34 assigning to vector 48 data type of 44 declaring 46 displaying contents 115 predefined 44 unexpected values 138 vector functions 233
W
while loop 65 white space in expressions 62 WINEDITOR setting 99, 100 World Centroid 194 World Centroid X, Y, Z 204 World Position 204 World Velocity 204
INDEX
X
xemacs text editor 97