Sunday, December 9, 2007

Modeling Basics

What Is Modeling?

Let's begin with a working definition of what modeling is in computer animation: 3D modeling is the process of creating three-dimensional surfaces using a computer, for the purpose of rendering them into a picture or a sequence of pictures. In fields such as the automobile industry or engineering, digital models are actually built with specific products in mind—their purpose is to create a physical model or prototype that will ultimately become a working automobile or a building. Rendering is only a stage they go through in order to get to their ultimate destination. For 3D artists working in computer animation, however, the ultimate destination is pictures that exist in TV, videos, or celluloid—all 2D environments.

Creating an Illusion

Digital space is a world of facades. If only the back and right walls of a room will be seen, it makes no sense to build the front or the left side. For the computer animator, modeling is all about creating illusions for the eye to feast on—build only what the eye (the camera) will see. This is why careful preproduction planning is so crucial and why well-organized production teams create detailed storyboards before they commit to building anything.

Good Models and Bad Models

Good models look good when rendered, and bad models look bad. It's that simple. The catch, of course, is that producing models that look good takes a lot of time and care, and producing great-looking models always takes a lot of sweat and effort. Tight schedules and deadlines often make this a difficult—if not an impossible—task.

Other less-obvious factors in the production environment also determine whether a model is good or bad, and these are just as important as the model's appearance. The two criteria for good modeling most frequently used in animation are how computationally heavy or light a model is and how well it can be set up for animation.

Improperly built models often end up being heavy, meaning they are built with too much geometry and can cause numerous problems for the animators or a loss of precious production time in rendering. A heavy model makes the computer's CPU work harder than it would otherwise need to. A light model, in contrast, does not have a lot of geometry for the computer to calculate and thus allows the animator to act more interactively with it, producing better animation in shorter time. It generally renders faster too.

Modeling Tools

Let's now look at some of Maya's modeling features. Maya has a vast array of tools that can aid in modeling. Here are some of the more basic and useful functions we will cover in this chapter:

  • Templates

  • Layers

  • Isolated selection

  • Pick-masking

  • Snapping

  • Freezing transformations

  • Construction history

Templates

In Maya, templates are mainly used as guides for modeling. Objects that become templates remain visible but cannot be selected like other objects. The standard way to turn an object into a template is to select the object and then choose Display ® Object Display ® Template. You can also open the Attribute Editor (press Ctrl+A), choose Display, and toggle on Template.

Because you cannot select the templated object in the usual way by dragging, in order to untemplate it, you must either select it in the Outliner or the Hypergraph Editor, or use a selection mask and then toggle it back by choosing Display ® Object Display ® Untemplate.

You can also template objects by using the Layer Editor. A layer also has templating capability, and it is generally the more efficient way to template objects because it can handle groups. You access layers through the buttons above the Channel Box. You have three options for viewing them—layer only, Channel Box only, or both together.

The Layer Editor

"Techniques for Speeding Up Workflow," introduced the Layer Editor, an extremely useful tool for modeling. Originally created for Alias Power Animator, it came back in its original form in Maya 2 and has become even better with each new version of Maya. A layer creates an exclusive collection of objects that can be selected, hidden, or templated together. Essentially, a layer acts as a directory or a folder for objects to aid in organization and work efficiency.

Be sure you are familiar with the basic techniques presented for working with the Layer Editor:

  • To display the Layer Editor if it has been turned off, choose Display ® UI Elements ® Channel Box/Layer Editor. If the Channel Box is showing but not the Layer Editor, click the second or the third button in the top-left corner of the Channel Box to display it.

  • To create a new layer, choose Layers ® Create Layer from the Layer Editor's menu, or click the New Layer button—it's to the right and just below the menu.

Rendering Basics

Rendering an Object

As we've done in previous chapters, we will explore the rendering process by working through an example from beginning to end. To demonstrate rendering, we'll use a beveled text letter. We will light it, texture it, and animate it appearing and disappearing against a textured background. Then we will render the animation as a video-quality picture sequence.

Setting the Camera and the Resolution

First, you need to set the camera. As you learned in earlier chapters, cameras are windows through which you look at objects in Maya's world space. The four default views that you see when you start a new scene are actually four cameras that cannot be deleted: one camera with a perspective view and three cameras with orthographic views, which you know as the front, side, and top views. Generally, you use the orthographic views for modeling, texturing, and animation purposes, and rendering is done only through the perspective views.

To set the camera and the resolution, follow these steps:

  1. Create a beveled text letter M (choose Surfaces ® Bevel), as we did in Chapter 5, "NURBS Modeling."

  2. Create another perspective view by choosing Panels ® Perspective ® New. Persp1 camera is created.

  3. In the Outliner, rename the view to Camera. Open its Attribute Editor, shown in Figure 16.1, and in the Film Back section, set Overscan to 1.1. In the Display Options section, check Display Resolution. (You can also turn on Display Resolution by choosing View ® Camera Settings ® Resolution Gate.) In the camera view, you will see a box that shows the exact area that will be rendered. The Overscan setting of 1.1 also shows a bit of the area just outside the box. In the Display Options section, also check the Display Film Gate setting. This displays another box, representing the Film Gate, the camera setting for the medium in which you want to display the images. The default resolution size in Maya is 320 × 240 pixels, which gives a width × height (aspect) ratio of 1.33333. If you see the Film Gate box overlapping the resolution box imperfectly, there is an imperfect match between the aspect ratio of the pictures being rendered and the ratio used in the final display medium.

  4. In the Film Back section, select different media in the Film Gate drop-down list, such as 70mm projection, to see how the aspect ratio changes. Change the preset to 35mm TV Projection, as shown in Figure 16.1. This setting has the 1.33333 ratio for television. The Film Gate and Resolution boxes should now match perfectly. (See the "Broadcast Standards" sidebar later in this section for more information on resolutions and ratios.)

  5. The default resolution setting is at 320 × 240, which you can see at the top of the resolution gate in the camera view, but you will probably want to render the pictures at a higher resolution. Choose Window ® Rendering Editors ® Render Globals (or click the Render Globals button in the Status line) and open the Resolution section. For our example, set the Render Resolution to 640×480.

  6. Adjust the camera view, dragging and rotating the camera until you have the proper composition for the letter M. Then keyframe the Camera attributes. (First, make sure you are at frame 1 on the Time Slider. Then, with the camera selected, RM click any of the attributes in the Channel Box and select Key All.) Now you can switch back to the regular perspective window and test-render the camera view as you make changes to the lighting and textures.


Layer Rendering, Compositing, and Editing

What we've done with the letter M rendering is actually rather … dumb. Because the letter wasn't moving, the 60 frames of rendering were not necessary; only the first 10 frames need to be rendered. In studio environments, where meeting deadlines and work efficiency are always paramount, this kind of rendering redundancy would have been frowned upon.

With any editing software or with some renaming and renumbering script commands, you can extend frame 1 forward to frame 5, reverse the animation from frames 5 to 15 to make them frames 50 to 60, and hold frame 15 until frame 49.

Alternatively, we could have rendered the letter M separately from the fractal textured background. Since the background remains constant, only a single frame is necessary. Using compositing software, we could have composited the letter M onto the background.

Adding Depth of Field

Maya cameras can also imitate the depth-of-field functionality of real-world cameras. To use this capacity in any practical way, however, requires some setup.

Open the letter_M file, select Camera, and open its Attribute Editor. Go to the Depth Of Field section and check Depth Of Field. Its attributes become active. The Focus Distance attribute does what it says—it sets the distance for the camera focus.

It would be useful to have a way of interactively controlling that distance in the modeling window, instead of punching in numbers. An easy way to do this is to open the Connection Editor with the Camera Shape loaded on both windows and connect the Center Of Interest output to the Focus Distance input. This constrains the focus distance to the camera's center of interest, which shows up as part of the Show Manipulator handle.



Rendering Basics

Rendering an Object

As we've done in previous chapters, we will explore the rendering process by working through an example from beginning to end. To demonstrate rendering, we'll use a beveled text letter. We will light it, texture it, and animate it appearing and disappearing against a textured background. Then we will render the animation as a video-quality picture sequence.

Setting the Camera and the Resolution

First, you need to set the camera. As you learned in earlier chapters, cameras are windows through which you look at objects in Maya's world space. The four default views that you see when you start a new scene are actually four cameras that cannot be deleted: one camera with a perspective view and three cameras with orthographic views, which you know as the front, side, and top views. Generally, you use the orthographic views for modeling, texturing, and animation purposes, and rendering is done only through the perspective views.

To set the camera and the resolution, follow these steps:

  1. Create a beveled text letter M (choose Surfaces ® Bevel), "NURBS Modeling."

  2. Create another perspective view by choosing Panels ® Perspective ® New. Persp1 camera is created.

  3. In the Outliner, rename the view to Camera. Open its Attribute Editorand in the Film Back section, set Overscan to 1.1. In the Display Options section, check Display Resolution. (You can also turn on Display Resolution by choosing View ® Camera Settings ® Resolution Gate.) In the camera view, you will see a box that shows the exact area that will be rendered. The Overscan setting of 1.1 also shows a bit of the area just outside the box. In the Display Options section, also check the Display Film Gate setting. This displays another box, representing the Film Gate, the camera setting for the medium in which you want to display the images. The default resolution size in Maya is 320 × 240 pixels, which gives a width × height (aspect) ratio of 1.33333. If you see the Film Gate box overlapping the resolution box imperfectly, there is an imperfect match between the aspect ratio of the pictures being rendered and the ratio used in the final display medium.

  4. In the Film Back section, select different media in the Film Gate drop-down list, such as 70mm projection, to see how the aspect ratio changes. Change the preset to 35mm TV Projection.This setting has the 1.33333 ratio for television. The Film Gate and Resolution boxes should now match perfectly.

  5. The default resolution setting is at 320 × 240, which you can see at the top of the resolution gate in the camera view, but you will probably want to render the pictures at a higher resolution. Choose Window ® Rendering Editors ® Render Globals (or click the Render Globals button in the Status line) and open the Resolution section. For our example, set the Render Resolution to 640×480.

  6. Adjust the camera view, dragging and rotating the camera until you have the proper composition for the letter M. Then keyframe the Camera attributes. (First, make sure you are at frame 1 on the Time Slider. Then, with the camera selected, RM click any of the attributes in the Channel Box and select Key All.) Now you can switch back to the regular perspective window and test-render the camera view as you make changes to the lighting and textures.


Layer Rendering, Compositing, and Editing

What we've done with the letter M rendering is actually rather … dumb. Because the letter wasn't moving, the 60 frames of rendering were not necessary; only the first 10 frames need to be rendered. In studio environments, where meeting deadlines and work efficiency are always paramount, this kind of rendering redundancy would have been frowned upon.

With any editing software or with some renaming and renumbering script commands, you can extend frame 1 forward to frame 5, reverse the animation from frames 5 to 15 to make them frames 50 to 60, and hold frame 15 until frame 49.

Alternatively, we could have rendered the letter M separately from the fractal textured background. Since the background remains constant, only a single frame is necessary. Using compositing software, we could have composited the letter M onto the background.

Adding Depth of Field

Maya cameras can also imitate the depth-of-field functionality of real-world cameras. To use this capacity in any practical way, however, requires some setup.

Open the letter_M file, select Camera, and open its Attribute Editor. Go to the Depth Of Field section and check Depth Of Field. Its attributes become active. The Focus Distance attribute does what it says—it sets the distance for the camera focus.

It would be useful to have a way of interactively controlling that distance in the modeling window, instead of punching in numbers. An easy way to do this is to open the Connection Editor with the Camera Shape loaded on both windows and connect the Center Of Interest output to the Focus Distance input. This constrains the focus distance to the camera's center of interest, which shows up as part of the Show Manipulator handle.


MEL

MEL Is Fundamental

Maya Embedded Language (MEL) is the ground from which you interact with Maya. When you open Maya, the program first runs several MEL scripts that actually build all the windows you see—that's right: Maya itself has no interface whatsoever. You can even run Maya from your operating system command prompt by typing Maya –prompt! Behind nearly everything you see in Maya is a MEL script.

What does this mean to the average Maya user? Simple: whatever the original programmers did, you also can do. You can write windows that have sliders, tabs, text fields, and buttons in them; you can create attributes in the Channel Box; you can even add menu items to the main menu bar. The fact that Maya is built on MEL is one of the program's most powerful features.

What Is a Scripting Language?

MEL is a scripting language, not a complete programming language (like Java or C++). A program written in a programming language is compiled and becomes an independent program (like the core program, Maya, which just runs off your computer's operating system). A scripting language, on the other hand, resides on top of another program (in this case, Maya) and is interpreted at every line rather than compiled. Because scripting languages are interpreted by the "mother" program, they are a bit slower than compiled programs—however, they require much less programming overhead than do compiled programs.

If you are a real "propeller head" and like to get into the guts of a program, you can create plug-ins for the program itself using the C or C++ programming languages. Maya has its own API (application programming interface)—appropriately enough named Maya API. MEL does just fine for 95 percent of the things most people want to do, however, and it isn't too difficult to learn.

The Script Editor

One of the best ways to get to know MEL is to use the Script Editor. MEL is a huge language (with more than 600 commands and about 75 functions), but the Script Editor will clue you in on how commands are used and allow you to "cut and paste" whole scripts together without the need to program a thing yourself. You don't even need to use the command line to enter the MEL commands. Operations you perform in the Maya interface are recorded as MEL commands in the Script Editor. With no knowledge of programming, you can actually copy-paste together a fairly complex script.

What Is an Attribute?

As you likely understand from reading earlier chapters, an attribute (MEL uses the term Attr to refer to attributes) is any item that lives on a Maya node. (A Maya node is anything you can see in the Hypergraph, or the tabs at the top of the Attribute Editor.) This sounds a bit obscure, but it's really fairly straightforward: anything in the Channel Box, such as rotateX, transformY, or scaleZ, is an attribute of an object (more specifically, an object's transform node).

When you build, alter, or animate an object, you're changing one or more attributes on one or more nodes in the object—and, of course, all of these changes are just MEL commands, so you can make Maya do the work for you. In this section, we'll take a quick look at how MEL works with attributes; in a later section, we'll get into more detail about how to build complex scripts using attributes.

You might have noticed when you adjusted certain attributes of myCube in the previous section that the Script Editor was filled with statements that started with setAttr. The setAttr statement tells MEL to set a certain attribute to a certain value. Likewise, the getAttr statement gets (reads) the value of an attribute on a certain object, so you can use that value in another MEL statement. The addAttr statement tells MEL to add a custom attribute to a certain item. Essentially, using the setAttr statement is the same as opening the Attribute Editor window and changing a value in one of its fields. (Try changing a value in the Attribute Editor, and you'll notice that the Script Editor history pane shows that a setAttr statement has been executed.)

The syntax (the rules of what goes where) for an Attr statement is as follows:

setAttr [flags] objectName value;

Flags, as you've seen, are any special requests for MEL to complete; the object name is the name of the item's attribute to set (such as myCube.translateX); and the value is the value to set the attribute to. The getAttr and addAttr commands have similar syntax. For example, we can move a cube called "box" to 10 on the X axis by typing the following in the Script Editor:

setAttr box.translateX 10;

Once you execute this command, your box moves from where it is to 10 on the X axis. (Of course, if you have no object called "box," you will get an error message.)

The way MEL (and Maya) references an attribute is similar to the way C++ and other object-oriented programs work. You reference the node, then a period, then the attribute: Object.Attribute. If you don't specify the node on which the attribute is located , you'll get an error message. For example, typing setAttr translateX 10; generates an error message, because Maya doesn't know what to translate.

Setting the translateX attribute is much like giving the move command: move 10 0 0. Unlike giving the move command, however, setting the attribute of translateX does not affect the other two attributes (the Y and Z translate attributes). Also, the setAttr statement is far more flexible than the move command, which can translate only an object.

As a quick example of how setAttr can work, let's make a box and manually set several of its attributes. Type the following in the Script Editor's input pane:

polyCube –n box;
setAttr polyCube1.sw 3;
setAttr polyCube1.w 5;
setAttr box.rotateY 45;
setAttr box.translateX –2.5;
setAttr box.translateY .25;

setAttr box.scaleY 0.5;

Can you figure out what each command does on your own? Try highlighting each line and pressing the numeric Enter key to execute it. Highlighting one line at a time is a useful way to figure out what's happening in a script—and to see where things go wrong!

To change the way your cube is constructed, you reference the shape node (polyCube1), not the transform node, which you have renamed box.

How to Get Help with MEL

Before we delve any further into the world of MEL, let's examine the powerful Maya help tools—and how easy they are to use.

First, you have Maya's internal Help function. Because there are so many MEL commands and functions (about 700), the Help function is a quick and useful feature. (You can even type help help to get a look at how the Help command works.)

Here's an example of the type of information available in Help. Open the Script Editor and type the name of the command you want help with into the input pane (or just type it in the command line below the main window). For example, to get help with the setAttr command, type:

help setAttr;

Execute the command (press Enter on the numeric keypad, or press Ctrl+Enter on the keyboard), and in the Script Editor's history pane, you'll see the following result lines:

// Result:
Synopsis: setAttr [flags] Name[...]
Flags:
-e -edit
-q -query
-av -alteredValue
-k -keyable on|off
-l -lock on|off
-s -size Index
-typ -type String
//

These result lines give you a quick look at the setAttr command: a synopsis of its syntax (or how to use it) and a list of flags that you can use with the command.

If you're an experienced programmer, this information might be all you need to use the command. If you're just starting out, however, you'll probably want more guidance. In that case, try typing the following in the input pane:

help –doc setAttr;

When you execute this command, Maya automatically opens your browser of choice (usually Netscape Communicator or Microsoft Internet Explorer) and finds the correct HTML page in your online documents (contained on your hard drive) that contains the command you want help with. In the case of the setAttr statement, the following is displayed (this is merely an excerpt—the actual page contains much more information):

Name
setAttr
Synopsis
SetAttr
[flags] object.attribute value [value..]
ReturnValue
None.
Description
Sets the value of a dependency node attribute. No value for the
attribute is needed when the -l/-k/-s flags are used. The -type flag
is only required when setting a non-numeric attribute.
The following chart outlines the syntax of setAttr for non-numeric
data types:
{TYPE} below means any number of values of type TYPE, separated by a space
[TYPE] means that the value of type TYPE is optional
A|B means that either of A or B may appear

Examples
sphere -n sphere;
// Set a simple numeric value
setAttr sphere.translateX 5;
// Lock an attribute to prevent further modification
setAttr -lock on sphere.translateX;
// Make an attribute unkeyable
setAttr -keyable off sphere.translateZ;
// Set an entire list of multi-attribute values in one command
setAttr -size 7 "sphereShape.weights[0:6]" 1 1 2 1 1 1 2
// Set an attribute with a compound numeric type
setAttr "sphere.rotate" -type "double3" 0 45 90;
// Set a multi-attribute with a compound numeric type
setAttr "sphereShape.controlPoints[0:2]" -type "double3"

0 0 0 1 1 1 2 2 2;

As you can see, a few examples can do a lot to clarify how a command is used.

You can also access an entire MEL manual online, for a more in-depth look at the structure of the scripting language itself. In Maya, choose Help ® Library to open the main reference page in your web browser. Choose the Using Maya/MEL link to display a menu of introductory material, frequently asked questions, and other resources for learning MEL. Between the internal Help files and the online help on your hard drive, you can access excellent reference material rapidly.

A Comment on Commenting

Comments are a way for you, as a programmer, to document your code. Comments can be useful when you revisit old code, when you're writing code that may be confusing, or when others are reading your code.

Comments are identified by two forward slashes (//). When the script executes, the interpreter ignores anything that follows the two slashes. Here are some examples of legal comments:

//Script written by: John Doe
polyCube –n myCube; //create a cube named myCube

As you can see, a comment can be on a line by itself or at the end of a line of code.

Always include comments at the top of a script about what the script does, which arguments (inputs) it needs (you'll learn about arguments later in the section on procedures), who wrote (and modified) it, and when it was last modified. It's also not a bad idea to put in a "use at your own risk" line to indicate that some unforeseen problem could arise while using the script and that the author is not responsible for any mishaps because of the script's usage (ah, the joys of a litigious society!).

You might think that these comments are of use only to others and not to yourself, and you'd rather not bother with them if you don't plan to distribute the script. But remember that two months after you create the script, you might need to modify it, and if you can't figure out what you did or why, you'll waste a great deal of time hunting through the script instead of getting right to your modifications.

Always comment your scripts well (even the simplest ones). It's a habit (and for once, a good one), so get into it! Commenting well doesn't necessarily mean commenting everything though. In this chapter, the scripts are a little over-commented for instructional purposes, but in most cases, if you have more comments than code, you have overdone it. Good code is self-documenting with comments included where you or someone else might need a little extra information about what is happening. Here is an example of poor, or overdone, commenting technique:

// z equals x plus y
$z = $x + $y;

Hands On: Building a Room Automatically

Let's put all this information to some use now. We're going to record several actions we perform to create a default room setup, copy those actions into a macro, and place that macro on a shelf. Once we've done that, we can automatically set up a room for any scene we want, at the click of a mouse.

  1. Open Maya or begin a new scene.

  2. Open the Script Editor and clear the history pane.

  3. Build a room with three walls, a floor, and a ceiling (polygon cubes or planes). Leave one side of the room open to see inside. Place a cube and a sphere inside the room. Create a point light and place it in the center of the room, and shine a spotlight into the room. Then create a camera to see inside the room.

  4. Once you're happy with the room, simply select everything in the history pane and MM drag the highlighted text up to the shelf of your choosing. If you're not happy with your room, you can use a sample room script, room.mel, on the accompanying CD-ROM. Simply load it into the input pane of the Script Editor by choosing File ® Open Script. Once the script is loaded, highlight it and then MM drag it up to a shelf. A new button appears .

  5. Let's see if it worked. Select everything in your scene and press Delete. (Or you can type select –all; delete; in the Script Editor to do the same thing.)

  6. Once your scene is empty, go up to the shelf and click your newly made button. After a couple of seconds, you should see your room magically appear in the scene, just as you had it set up.


Variables, Loops, and Branching

If you've done any programming at all, you've probably been waiting for this point: the main reasons to program are (1) to create flexibility and (2) to take care of repetitive tasks. Flexibility comes through variables and branching; repetition is made possible through looping.

Variables

It's actually much easier to see what a variable is than to talk about it. Type the following in the Script Editor:

string $myVariable;
$myVariable = "hi there";

print $myVariable;

When you execute these commands, you'll see that "hi there" is displayed in the last line of the history pane, indicating that when you told Maya to print $myVariable, it displayed "hi there." The first line of this script is called a declaration of the variable: string is the variable's type (a string is just text contained in quotes), and $myVariable is its name. The second line of the script assigns the string "hi there" to the variable $myVariable, and the third line tells the print command to output the contents of the variable $myVariable, which as you can see is "hi there".

Looping

Next, let's examine looping. Say you want to create five cubes in your scene using MEL commands. You can either type polyCube –n box five times or have MEL do it for you using the for loop. To build our five cubes, type the following:

int $i; for ($i = 1; $i<= 5; $i++){ polyCube –n box; }

VoilĂ , five cubes named box1 through box5. (However, you'll need to move them away from each other to see them as separate objects. We'll do that in a moment.)

MEL supports implicit variable declaration, so the int $i line is not strictly necessary. However, in most cases, it is preferable to declare all variables explicitly to avoid possible complications in the script.

Notice that there is no semicolon after the for statement: MEL expects one or more commands (contained within the { } brackets) after the for statement, so a semicolon is unnecessary. Additionally, the closing bracket (}) functions as a semicolon, so a semicolon is also unnecessary on the last line. The syntax for the for loop is as follows:

for (initial value; test value; increment)

Branching

The last basic program structure we'll look at is branching. Branching provides a way to ask a question and decide whether to take some further action given the answer. (The for statement actually contains a branch in its test value statement.) Let's use the same script as previously, only this time let's put a conditional statement inside it:

for ($i = 1; $i<= 5; $i++){
polyCube –n box;
if ($i<=3){
move –r 0 (2 * $i) 0;
}
else{
move –r (2 * $i) 0 0;
}
}

What happens when you execute these commands? The first three cubes are stacked up on the Y axis (when $i is less than or equal to 3), and the last two are stacked along the X axis (when $i is 4 and 5, and therefore greater than 3). In abstract, the syntax for the if statement is as follows:

if (test){
commands;
}
else if (test){
commands;
}
else{
commands;
}

The else if and else statements do not have to exist for the if statement to work. The else if statement, listed here, allows you to make as many tests as you like (your conditional statement can have as many else if statements as you wish), allowing you to test for multiple possibilities within one large conditional statement. The else statement must always be last in such examples, and it is the "default" answer if no other conditions are met. All the commands for an if, else if, or else statement must be enclosed in brackets ({ }). If we want, we can increase the complexity of our create-and-move-box code with an else if statement: