siggraph 2003 - combining fluids and particles (with maya)

44
1 Combining Maya Fluids and Particles in Production Presenter: Jason Lazaroff, Meteor Studios This seminar will present the user with different techniques for combining fluid and particle effects through practical examples. The course is aimed at intermediate users who already have a basic understanding of particle dynamics. I. FLUIDS VS PARTICLES When creating an effect, we decide early on weather we’ll use fluid or particle dynamics, or even a combination, therefore it is important to understand the differences. Fluids pros and cons True Volume, can accumulate and fill a space; Fluids can’t live outside their volume; Slow to simulate high-resolution fluids; Excellent presets and preset blending can save research time; Can serve other purposes, such as being 2d or 3d textures; Excellent for simulating liquid in liquid effects; Poor at simulating liquid in air; Particles pros and cons Fast simulation allows for more iterations; No volume means no limit to the area a particle system can cover; Difficulty creating volume (particles tend to escape); Excellent integration of MEL expressions for creation and runtime expressions allows for great flexibility; Excellent for airborne effects, smoke, clouds, fires…; Difficult to create churning liquid effects, requires many fields. Simulation becomes “fragile”; Combining fluids and particles Fluids can be used as fields to influence particles; Fluid can be used as textures on particles, including volume shaders; Particles can float on Ocean shader, or otherwise detect it to trigger other events; Can attach fields to particles and influence Fluids; Particles can emit fluids;

Upload: magalyfx

Post on 14-Apr-2015

206 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Siggraph 2003 - Combining Fluids and Particles (With Maya)

1

Combining Maya Fluids and Particles in ProductionPresenter: Jason Lazaroff, Meteor Studios

This seminar will present the user with different techniques for combining fluid andparticle effects through practical examples. The course is aimed at intermediate userswho already have a basic understanding of particle dynamics.

I. FLUIDS VS PARTICLES

When creating an effect, we decide early on weather we’ll use fluid or particle dynamics,or even a combination, therefore it is important to understand the differences.

Fluids pros and cons

True Volume, can accumulate and fill a space;Fluids can’t live outside their volume;Slow to simulate high-resolution fluids;Excellent presets and preset blending can save research time;Can serve other purposes, such as being 2d or 3d textures;Excellent for simulating liquid in liquid effects;Poor at simulating liquid in air;

Particles pros and cons

Fast simulation allows for more iterations;No volume means no limit to the area a particle system can cover;Difficulty creating volume (particles tend to escape);Excellent integration of MEL expressions for creation and runtime expressions allows forgreat flexibility;Excellent for airborne effects, smoke, clouds, fires…;Difficult to create churning liquid effects, requires many fields. Simulation becomes“fragile”;

Combining fluids and particles

Fluids can be used as fields to influence particles;Fluid can be used as textures on particles, including volume shaders;Particles can float on Ocean shader, or otherwise detect it to trigger other events;Can attach fields to particles and influence Fluids;Particles can emit fluids;

Page 2: Siggraph 2003 - Combining Fluids and Particles (With Maya)

2

II. CREATING BASIC SHIP WAKES

In this section we’ll explore different techniques used in generating ship wakes. We’llfirst begin with an overview of fluids and the Ocean Shader and some of the tools andtechniques associated with its use.

Fluids Overview

Fluids can be used in many techniques to interact with the Ocean Shader and particlesystems. Therefore, a basic understanding of fluids is essential.

Maya Fluids come in different forms, here are the principals:

Height Field – Ocean Shader. A height field uses a fluid simulation to offset a surfacemuch like a displacement map would. The Ocean shader uses a height field, and, unlike2d and 3d Fluids, it has a potentially unlimited resolution. One of the peculiarities ofOcean Shader is that the (texture) UV exists in Worldspace, so that a value of u1 v1would be at Worldspace X 1, Z 1, no relation to the object on which the material isapplied. This brings special considerations when using certain textures mapped intoOcean attributes.

Page 3: Siggraph 2003 - Combining Fluids and Particles (With Maya)

3

2dFluid – Unlike height field, the 2d fluid exists in a limited user defined volume. It hasa certain number of voxels in width and length that define its resolution, and a height thatonly defines the thickness (not the detail). The 2d Fluid’s volume can be transformed, andcan even be applied as a UV or projection texture.

3dFluids – The 3d Fluid also exists in a user defined volume, but unlike the 2d one, thisone has height resolution . 3d Fluids can be transformed and used as volumetric textureon geometry and particles.

Page 4: Siggraph 2003 - Combining Fluids and Particles (With Maya)

4

Ocean Shader Overview

Ocean shader material attributes have usual material attributes affecting color,reflectivity, diffuse, specular… with special consideration for the way light behaves wheninteracting with water. A particularity of the ocean shader is that it has attributesdedicated to the water behavior. This is more akin to a procedural texture.

You can try the following to discover the most basic Ocean shader functions:

In a new scene, create an ocean shader: Fluid Effects > Ocean > Create Ocean (defaultsettings)In order to preview the shader, use the preview plane: Fluid Effects > Ocean > AddPreview PlaneThe preview plane is a non-renderable polygon plane that floats atop the ocean shader. Itcan be transformed, and the resolution can be altered interactively.In the preview plane Attribute Editor, increase the resolution: oceanPreviewPlane1 >Resolution = 80A higher resolution previews finer detail at the cost of performance. Sculpting waveswith at a fixed point in time works best at high resolutions (80), while interactiveplayback is best with mid to low res. (20).Select the preview plane in any viewport and change the scale it up to 25 in X,Z:transform1 > scale X,Z = 25

Scale Y is always locked at 1 in order to accurately preview wave height.The Ocean Shader attributes control the shape and motion of the ocean surface. Thefollowing is a sampling of the most important/commonly used attributes. For moreinformation, consult the Maya 5.0 docs in the Fluids section.

Ocean Attributes > Scale controls the size of the overall ocean and all it’s properties.Making the Ocean larger will make waves seem to move slower because they areproportional to the ocean size. In this case, a lower scale value makes the waves larger, alarge number makes more waves. The scaling effect is the reverse of a typical 3dTextureplacement.

Page 5: Siggraph 2003 - Combining Fluids and Particles (With Maya)

5

Ocean Attributes > Num Frequencies : Changes the wavelet size. Larger values resultin more wavelets on each wave.

Ocean Attributes > Wave Speed : Slows down all Ocean time based properties whenreduced (like a slow motion effect). Increasing this value is a good way to quicklyemulate a much smaller volume of water, like a bathtub (using Fluids > Pond shader iseven better).

Ocean Attributes > Wave Height : This controls the height of the waves. The rampwidget gives a lot of control as to which part of the wave is affected by the Wave HeightValue. Generally speaking, high ramp values to the left result in sharper peaks onsubwaves, while values to the right give more smooth/rounded results. Usually, thevariances are set on the left half of the ramp for a nice choppy look.

Ocean Attributes > Wave Turbulence : Breaks the repetitiveness of waves. Highvalues are good for choppy/stormy effects, and low values can be useful for calmer lakes.

Ocean Attributes > Wave Peaking > Wave Height Offset : This changes the overallheight of the ocean. You can affect a specific are using a connection such as a texture(more on that later). Areas that are raised through this attribute generate more foam.

Page 6: Siggraph 2003 - Combining Fluids and Particles (With Maya)

6

Ocean Attributes > Wave Peaking > Foam… : Increasing foam emission emits moresurface foam. You can map this attribute for effects such as wake foam (more on thatlater). Increasing foam threshold emits onto a wider area (small values limit to the peaks,larger ones spread into the trough).Foam Offset and Bump Blur have no effect on the preview plane, so we’ll get back totheme later.

Page 7: Siggraph 2003 - Combining Fluids and Particles (With Maya)

7

Understanding colorAtPoint MEL Command

One of the most visible and difficult aspects of water interaction is floating objects, suchas particle foam and certain types of objects. Maya has a number of built-in tools to floatboats and boat-like objects, tools such as addBuoy, addBoat, and addMotorBoat . Allthese tools have one very important thing in common, they’re all based on thecolorAtPoint MEL command. By mastering this function, we can expand Maya’scapabilities and use it to create custom tools and effects such as floating curves orparticles on the ocean shader.

colorAtPoint can sample any combination of colors (RGBA) on an Ocean shader (orother texture) at a given UV address. While this can be put to many uses, we areprimarily concerned with retrieving the height of the waves and applying it to the Yposition of objects and particles. Like most displacement maps in Maya, Ocean outAlphais used to calculate the displacement height. Since the Ocean shader’s UVs are based onWorldspace (X 3, Z 4 in Maya Worldspace = U 3, V 4 in Ocean shader UV) we candirectly convert any point’s Worldspace to ocean UV space and sample the Alpha to getthe appropriate Y height of the waves.

colorAtPoint use: -convert point (object) Worldspace to Ocean UV;-sample Alpha at given UV address;-use returned Alpha value as Y height of point (object);

The following example will make this principle clear:

1- Open: fluid_colorAtPoint_start.ma

In the persp window change to textured view (keyboard shortcut “6”) . When youplayback or scroll through the timeline, the checkered sphere should float above highwaves. If the playback is too slow, lower the previewPlane resolution;

3- With the floatSphere selected, select the translateY channel and right click. SelectExpressions in the dropdown menue ;

In the Expression Editor, type the following (or copy/paste from the CDrom text filemyFloat_expression.txt);

//myFloat_expression//float an object on the ocean surface//translate XZ are free, Y is constrained to ocean

float $posu = floatSphere.translateX;float $posv = floatSphere.translateZ;float $posy[] = `colorAtPoint -o A -u $posu -v $posv oceanShader1`;floatSphere.translateY = $posy[0];

Page 8: Siggraph 2003 - Combining Fluids and Particles (With Maya)

8

Expression explained:-o A : “A” samples the Alpha only. Other options are “RGB” and “RGBA”;-u and –v : place input variable for the Worldspace point you wish to sample (object’sposition XZ you wish to float). IMPORTANT: since colorAtPoint is a MEL command,you have to use “`” (not single quote, the other one above TAB on your keyboard) oneither end when in an expression. Also, you should use $variables for –u and –v sinceMEL can’t convert expression syntax such as “locator1.translateX” (MEL sees this as astring only).$locY[] : Since colorAtPoint returns a float Array, you can’t use it directly in translateY(requires a single float).NOTE : When a MEL commands such as colorAtPoint is embedded in an expression, itdoes not update when names it refers to are changed. E.g. If “oceanShader1” werechanged to “myOcean”, the expression would return an error. Since many Maya floatingtools (createBoat…) generate expressions with embedded MEL, it is very dangerous torename the floating object/locator’s transform, or the oceanShader after the tool isinvoked. You would have to manually edit the MEL lines in the expression after such aname change.

Now you can key the floatSphere at frame 1: translationX = -10 and frame 100:translationX = 10 . When you playback or scroll through the timeline, the sphere willstick to the ocean surface. Alternatively, you can just freely move the floatSphere in theperspective view, and it will stay on the ocean surface;IMPORTANT: If you key the translation with Shift-W, Maya will override theexpression with an animation curve. A new feature in Maya 5.0 makes it possible formultiple inputs into a single channel (like TranslationY). The operation creates apairBlend node. You can find it in the INPUTS (Channel Box), and switch from anychannel with options for blend, channel1, or channel2. So selecting floatSphere >INPUTS > pairBlend1 > TranslateY > Input2Only would give us the desired result.

Note: When using Maya’s built-in boat tools, they have many custom controls, some ofwhich depend on an objects velocity. In these cases (like with dynamics), you cannot getreliable results when skipping or scrolling through the timeline.

colorAtPoint can be easily used to float surfaces or curves by applying expression to thecomponents (CVs or vertices). Even particles can be made to float, as we’ll see later.

Finished scene: fluid_colorAtPoint_final.ma

Page 9: Siggraph 2003 - Combining Fluids and Particles (With Maya)

9

Creating and Previewing Ship Wakes – Fluid Texture

We finally get to the goal of this section, demonstrating techniques for boat wakes. Theprincipal way of generating wakes on an ocean shader involves adding to thedisplacement map. We can do this by connecting textures to the waveHeightOffsetattribute of the ocean shader. We’ll start with Maya’s built-in solution: the use of Fluidstextures as wakes (the addWake tool). This solution offers the closest match betweenscene preview and rendering.

1- Open: fluid_wake_fluid_start.ma . Notice this scene already has an ocean and apreviewPlane. Also, our boat (the futuristic myBoat) has no animation;

2- Hide oceanPlane1 so that it doesn’t interfere with our previewPlane interaction. We’llonly need the oceanPlane1 when we render later;

3- With my boat selected: Fluid Effects > Ocean > Add Motor Boats . This parentsmyBoat to a locator driven by expressions based on colorAtPoint ;NOTE: Do not change the name of the newly created locator1, as this will break theexpressions that make it float. If you need to change the name either locator1 oroceanShader1, you’ll have to manually replace the same names in the new expression1 .

4- Select the locator1 shape node (locatorShape1). In the Extra Attributes section of

Page 10: Siggraph 2003 - Combining Fluids and Particles (With Maya)

10

the Attribute Editor you’ll find all the boat controls, with basic instructions in the Noteswindow.Don’t’ change any settings yet. If you playback the scene, the boat will bob up, bouncingup and down until it eventually settles into a convincing floating motion. We’ll have togive it a better starting motion;

NOTE: Boat Length, Width and Height are automatically derived from the bounding boxsize of the selected boat when any Maya “boat” tool is used. These tools always consideraxis with the longest length to be front, so if you use an odd shape (wider than long) thesteering and throttle may be wrong. You can simply change the scale temporarily beforeapplying the boat tool, then revert after.

5- Change the Start Time of your timeline to –50 , and the Start Frame of the boat to –50 also. Playback until frame 1, then change your timeline and boat Start to 1. You havejust set the equivalent of an Initial State for the boat. This initial state is saved in anexpression variable, so it does not save with the scene. We want a more robust solutionwe’ll bake boat animation later;NOTE: The motorBoat expression (expression1) uses velocity in its calculations, so,like dynamic simulations, you need playback with Play Every Frame option. Scrollingthrough the timeline, or playing backwards will also be inaccurate.

6- Key the Throttle to 0 at frame 0 and 0.8 at frame 1;

7- Reset Start Time for the time slider and Start Time for the boat locator1 to –50.Now when you start playback the boat will settle down before the positive frames, thenmove forwards under it’s own power. Now we’re ready to bake the boat movement;

8- Select locator1 and highlight all the translation and rotation channels. In the mainMenu Bar, open Edit > Keys > Bake Simulation option box. Edit > Reset Settings,then check Channels > From Channel Box. Press Bake. When the bake is finished, youcan delete expression1 (Windows > Animation Editors > Expression Editor).

Page 11: Siggraph 2003 - Combining Fluids and Particles (With Maya)

11

We baked the boat for two reasons:-We don’t want to runup the boat animation every time we playback or reopen the scene;-We don’t want the boat to ride on top of the wake it will emit;

9- Fluid Effects > Ocean > Create Wake option box > Edit > Reset Settings. Nowclick Create Ocean Wake . This creates a fluid texture (notice the volume bounding boxthat just appeared) and a fluid emitter. They are automatically attached to the oceanshader in the waveHeightOffset, so that the fluid density will add wake displacement.This rig can also generate foam, but we’ll look at that later.

10 Translate the OceanWakeEmitter1 to the back of myBoat and Parent it. We wantthe wake to follow the boat;

11- If you playback now, the wake is much too strong. Set OceanWakeEmitter1 >Fluid Attributes > Density/Voxels/Sec to 1.0 . The density controls wake height. Now ifyou playback again, the wake and froth displacement at the back of the boat are aboutright, but a circular shockwave radiates at the start of playback. We can fix that;

12- Shift select myBoat and the fluid (fluidTexture3D1 represented by a volumebounding box in the viewport). Click Fluid Effects > Make Collide . Now the fluid willcollide with the boat. Since the boat animation is baked, the fluid collision won’t push theboat, instead it will simply be blocked. This is an easy way to go from the default circularwake shape to a more appropriate one;

Page 12: Siggraph 2003 - Combining Fluids and Particles (With Maya)

12

Page 13: Siggraph 2003 - Combining Fluids and Particles (With Maya)

13

Creating and Previewing Ship Wakes – Projected Texture

Another way of adding wakes to the ocean shader, is the use of projected texture files.This is very convenient when using external image files or sequences, but has itslimitations when previewing.

1- Open the scene: fluid_wake_projection_start.ma ;

2- Before making any heavy modifications to the ocean shader, it’s best to save oursetting so we can reapply them latter. Select oceanShader1 and in the Attribute Editor,click and hold on Presets (next to the upstream/downstream buttons top right) and SaveOcean Shader Presets . Call it ocean_projection1 .

4- In the Hypershade , create > 2d textures > As Projection > File . Rename the newfile node wake_file , and the projection node to wake_projection ;

5- Set the wake_file > File Attributes > Image name to fluid_wake_image1.sgi . Usethe browse button to find it in the sourceimages directory.

Page 14: Siggraph 2003 - Combining Fluids and Particles (With Maya)

14

6- Connect the wake_projection.outAlpha to the oceanShader1.waveHeightOffset .You can use the connection editor or the output/input plugs in the Hypershade workAreafor this connection;

7- Parent the place3dTexture1 to myBoat so that it will follow the animation;

8- Ocean shader can sometimes take a lot of time to render, and since we can’t see theresults a projected texture on the previewPlane, placement of the 3dTexture can be atedious guessing game with many test renders or lengthy IPR. One way around thisproblem is to attach a geometry surface to the projection box, and use texture view tointeractively place the 3dTexture.Create > NURBS > NURBS Plane . Rename it preview_nurbsPlane. Set scaleXYZ to 10 . In the preview_nurbsPlaneShape, turn off all renderStats so it

won’t show up at render time. We only need to see it in texture view.

9- Create > material > Lambert . Rename it preview_lambert. Assign the newpreview_lambert shader to the NURBS plane we just made (preview_nurbsPlane).

10- Connect the wake_projection.outColor to the preview_lambert.color .

11- In the preview_lambert , set hardwareTexturing > textureResolution to High .This will give us enough detail in texture view to accurately place the 3dprojection;

12- Now we have to place the projection in the correct position relative to the boat. Selectthe wake_projection’s place3dTexture1 and transform it until you it fits the boat to yourliking, or apply the following transforms:

translateX –5.3 rotateX –90.0 scaleX 4.0translateY 0 rotateY 0 scaleY 2translateZ -1 rotateZ 0 scaleZ 1

Page 15: Siggraph 2003 - Combining Fluids and Particles (With Maya)

15

13- At frame 1 , do a preview render of with the ocean_cam . Notice how the wake lacksdetail (a bit chunky). This is due to the lack of tessellation in the oceanPlane. The Oceanshader gets its detail and sharpness from bump mapping, but anything mapped towaveHeightOffset relies on displacement alone for detail.

14- in OceanPlaneShape1 , change Tessellation > Advanced tessellation > PrimaryTessellation Attributes to U 40 and V 40 . This will help show the wake’s detail atrender time.Note: The oceanShader preset scenes in Maya all use Advanced Tessellation combinedwith a circular NURBS plane that concentrates detail towards the center. This optimizestessellation at the ocean’s center, but nothing prevents you from using other geometryshapes for custom effects. Ocean shader does not support feature displacement.

15- Scale down oceanPlane1 surface from 375 to 100. This will help increase thetessellation relative to the wave/wake size, while keeping the total poly count to aminimum. Since the Ocean shader is based on Worldspace UV, the wave size and othershader derived characteristics will be unaffected by the scale change.

16- Now if you do a preview render, notice how the detail is very good, but the wake istoo high. To change the height, simply reduce the alphaGain of wake_projection in thecolorBalance section. A value of 0.33 to 0.5 is good in this case ;

Page 16: Siggraph 2003 - Combining Fluids and Particles (With Maya)

16

Creating and Previewing Ship Wakes – UV Texture

The use of UV texture files with the ocean shader is very limited. It requires someworkaround to follow animated objects (boats) and to render with the properdisplacement, but this combination has interesting possibilities for other types of effects.

1- Open scene: fluid_UVfollow_start.ma, notice that the scene already has anocean preview plane with a UV mapped texture (in waveHeightOffset) creating a bulge;

2- Do a preview render of ocean_cam . The render doesn’t show the effects of our UVmapped texture, despite the fact that we can see the effect of the texture map on thepreview plane. This is a limitation in Maya 5.0, we have to use a workaround. Beforefixing the preview/render problem, we need to make our UV texture follow the boat;

3- To move the wake, you need to change the settings for place2dTexture connected toour texture file, in this case UVfollow_place2dTexture. In the Utilities tab of theHypershade, you will find the place2dTexture. Move the wake with 2d TexturePlacement Attributes:Coverage (acts like a scale)Translate Frame (1 for 1 in Maya units for Translate XZ)Rotate Frame (rotation in degrees)

Page 17: Siggraph 2003 - Combining Fluids and Particles (With Maya)

17

As you can already see, the controls are not very intuitive compared to a regulartransform node, this is due to the rotate frame acting before the translate frame. We’llcreate a rig that allows us to move the 2dTexture placement with a projection box. Thiswill give us better interaction in the scene.NOTE: Like with the previous projection texture example, you can change thedisplacement height by modifying the alphaGain in the wake_file;

4- Create > Utilities > General > 3dPlacemet . Rename the place3dTexture toUVfollow_place3dTexture . Set the UVfollow_place3dTexture.rotateX to –90 so wehave the correct orientation relative to out ocean.

5- We’ll use expressions to connect the UVfollow_place3dTexture andUVfollow_place2dTexture. In the Expression Editor, create a new expression and typethe following:

//UVfollow_expression//This expression make a place2dTexture follow a place3dTexture node

//UV offset to center textureUVfollow_place2dTexture.coverageU = UVfollow_place3dTexture.sx*2;UVfollow_place2dTexture.coverageV = UVfollow_place3dTexture.sy*2;float $offu = UVfollow_place2dTexture.coverageU/ -2;float $offv = UVfollow_place2dTexture.coverageV/ -2;

//local rotation for UV and standin geoUVfollow_place2dTexture.rotateFrame = UVfollow_place3dTexture.ry;

//distance offset from world zerofloat $mag1 = mag(<<0, 0, 0>> - <<UVfollow_place3dTexture.tx, 0, UVfollow_place3dTexture.tz>>);

//angle for UV frame translationfloat $ang1;if(UVfollow_place3dTexture.translateZ <= 0)$ang1 = angle(<<UVfollow_place3dTexture.tx, 0, UVfollow_place3dTexture.tz>>, <<$mag1, 0, 0>>);else$ang1 = -1 *angle(<<UVfollow_place3dTexture.tx, 0, UVfollow_place3dTexture.tz>>, <<$mag1, 0, 0>>);float $ang2 = $ang1-deg_to_rad(UVfollow_place3dTexture.ry);

//position UV frame using angle and distancevector $rot1 = rot(<<$mag1, 0, 0>>,<<0,1,0>>, $ang2);

//add centering offset for final UV posUVfollow_place2dTexture.translateFrameU = $offu+$rot1.x;UVfollow_place2dTexture.translateFrameV = $offv+$rot1.z;

Alternatively, you can just copy/paste the expressions from the CDrom text fileUVfollow_expression.txt . When you’re done, press Create . The wake preview willinteractively follow your 3dTexturePlacement node as you move it.

UVfollow_expression explained:// all line starting with a “//” are comments which do not evaluate with the expression;

Page 18: Siggraph 2003 - Combining Fluids and Particles (With Maya)

18

For an in depth look at the math functions used in this expression, please consult theMaya MEL expression math functions guide. Here is a breakdown of the basic principleat work:

-match the place2dTexture to place3dTexture scale;-find the correct offset that will center our place2dTexture;-match the place2dTexture to place3dTexture rotation;-find the distance between place3d and world position “0”;-find the local translation angle for the place2dTexture by doing: position angle -

place3dTexture – local rotation place3dTexture;-find the new place2dTexture position by rotating a point around the world Yaxis using

our place3d distance from step 4 and our local translation angle from step 5;-calculate the final place2dTexture transform by adding up the result of the world Yaxis

rotation position in step 6 and the centering offset in step 2;

6- Now that the interactive placement is resolved, we need to tackle the rendering issue.We still can’t see the displacement effect when rendering. Since UV textures can’tdisplace the ocean shader, we’ll have to displace the ocean NURBS surface. This requiressome tricky workarounds.First we need a much smaller NURBS surface to limit the poly count as we will bedisplacing the CVs just like a preview plane.

Delete the previewPlane . We’ll need a NURBS version for our purposes. We’ll use a“hidden” MEL script that is provided in you in one of the Maya Fluid demo scenes andcopied in a convenient .mel in this courseware;

7- Make certain that oceanNurbsPreviewPlane.mel is sourced. Use the scriptEditor >file > sourceScript and brows for oceanNurbsPreviewPlane.mel in the files provided toyou with this course CD. Then run the following in the scriptEditor or command line:“oceanNurbsPreviewPlane 40 40 oceanShader1” . Notice how the new NURBSpreview plane is displaced just like the ocean previewPlane.The syntax is: oceanNurbsPreviewPlane Uresolution Vresolution oceanShaderName .This is a script supplied by AliasWavefront to create a NURBS version of the previewplane with a few important differences:

-it can be rendered;-it can be used as a collision object in dynamics;-it is only a one degree/linear surface;-it does not preview ocean color information (like the regular previewPlane);

you cannot change the resolution once the plane is created becauseoceanNurbsPreviewPlane.mel generates a control expression with hardcodedresolution. Rerun the script to create a new plane if you need a different resolution;NOTE: Scenes containing a large resolution oceanNurbsPreviewPlane will take a longtime to open in Maya. Also, you may need to force a refresh (change current frame) tosee the proper displacement on the NURBS surface.

8- Set oceanShader1 > waveHeight to 0 , and set oceanNurbsPlane > visibility OFF .Our oceanShader1 will only be used as a tool to displace the NURBS preview plane.

Page 19: Siggraph 2003 - Combining Fluids and Particles (With Maya)

19

We’ll assign another ocean shader to the NURBS plane for actual rendering with thewake;

9- create > materials > oceanShader . Apply the new ocean shader to the previewNURBS plane. IMPORTANT: Make certain the Feature Displacement is OFF on thenew NURBS preview plane, and use Advanced Tessellation (U 10, V 10 is a goodsetting). If you do a test render now, the ocean will look faceted;

10- With construction history ON, go to modeling in the option box for Edit NURBS >Rebuild Surface . In the options, reset to default settings (Edit > Reset Settings), andcheck Keep > UVs . Click Rebuild. Now our surface is smooth (3 degrees) and has thecorrect displacement through construction history. The interaction and playback will bevery slow because Maya has to displace the original 1-degree preview plane, then rebuildit every frame. If you need to do a lot of transforms, it’s best to do them all (finishanimating) before proceeding with the rebuild.

11- Preview render the ocean_cam . Now we have a decent displacement with our oceanrender. Since the preview plane can only covers a small area of screen real-estate, it maybe necessary to render two passes for the ocean. One pass for the displacement area andanother for the overall ocean using a typical setup. Both would use the same oceanshader.

Page 20: Siggraph 2003 - Combining Fluids and Particles (With Maya)

20

For the final image, wake_file textureGain was set to 0.1 , and thenormalSeas_oceanShader preset was used.

Finished scene: fluid_UVfollow_final.ma

Page 21: Siggraph 2003 - Combining Fluids and Particles (With Maya)

21

Rendering With Ocean Shader

Here a few common issues related to rendering with the Ocean Shader:

Displacement: Ocean Shader does support Feature Displacement. Also, you cannot mapthe displacement and bump (normalCamera) to other shaders, say to try sending thedisplacement info to a useBackground shader and generate shadow or reflection passes.

Reflection Pass: Ocean Shader is different than other materials concerning therelationship between specularity and reflection. In most materials, turning specularityOFF results in no reflection, a useBackground shader would be used to extract reflection.In the case of Ocean Shader, useBackground doesn’t work, since the displacement andmaterial are intimately linked, but turning specularity OFF doesn’t affect Reflectivity.Therefore, a clean reflection pass is possible when turning color and specularity OFF.The resulting image has to be lumaKeyed since it won’t have a reflection specific alphalike a useBackground would.Alternatively, you can bake a portion of the ocean into a NURBS or Poly surface, andapply a useBackground on it.

Shadow Pass: Since Ocean can’t be combined with useBackground, you can removerough shadowing, reflection and specular to get a mat surface. Then, with color set towhite, you can any number of texture Utilities to Clamp the shadow color in order toeliminate the self shadowing on the waves, and just keep the projected ones.Alternatively, you can bake a portion of the ocean into a NURBS or Poly surface, andapply a useBackground on it.

Repetition: Repetitiveness with the Ocean Shader can be a problem at certain angles. Trychanging the Wave Turbulence attribute.

Bump Noise: Objects with bump at low angle, are notorious for noising/crawling atrender time. Like most displacement in Maya, the Ocean shader uses a bump map togenerate the fine details. You can create a shading network that reduces bump intensityaccording to camera distance. Here’s how you can build this simple network:

1- Open scene: fluid_ocean_start.ma;

2- Make certain Render Globals are at highest, with Min Max shading samples at 2 and 5respectively. This will give you a good compromise between speed and quality;

3- Preview render the “ocean_cam” view. Notice how the ocean’s waves seem to mergeinto an irregular “noisy” pattern on the horizon. This is mainly due to the bump patternbeing smaller than one pixel in at that distance and angle. This will cause crawling ifrendered in a sequence;

Page 22: Siggraph 2003 - Combining Fluids and Particles (With Maya)

22

4- In the Hypershade, create a Sampler Info node (Create > General Utilities > SamplerInfo ) and a Set Range (Create > General Utilities > Set Range ). These nodes willhelp us control the Ocean’s bump mapping according to the camera distance.The Sampler Info node is one of the most useful utility nodes in Maya. As the nameimplies, it samples each pixel at render time to return useful information such as distanceto camera, world position, and normals to camera… that can be used in any number ofways in a shading network.

5- In the Hypershade, use the middle mouse button to drag the sampler info onto the setrange, and select “other” in the drop-down connection menu. This will open theconnection editor. Alternatively, in the Hypershade you can open the connection editorwith Window > Connection Editor , or in the main menu bar, use Window > GeneralEditors > Connection Editor. If you open the Connection Editor through the menus,you will have to load the nodes you wish to connect manually. Use the right/left loadbuttons at the top of the Connection Editor;

Connect samplerInfo1.pointCameraZ to setRange1.valueX .

The Sampler Info’s pointCamera measures each pixel’s position relative to the camera at

Page 23: Siggraph 2003 - Combining Fluids and Particles (With Maya)

23

render time. Since we want to regulate our bump mapping according to camera distance,we only need the Z information.The Set Range utility allows us to convert numeric data from one range to another. In thiscase we will convert distance in Maya units (large) to a bump value range (small). Sincewe’re only using one channel from the samplerInfo (pointCameraZ), we only need oneinput for Value in the setRange. X, Y, or Z, any one will do.

In the Hypershade, connect the setRange1.outValueX to oceanShader1.bumpBlur .You’ll have to use the connection editor again.

The bumpBlur attribute is found in the ocean shader Ocean Attributes under WavePeaking. This function controls the amount of blur applied to the ocean’s bump mapping.Very low values result in crisp details, while large values can so completely blur outdetails that they disappear. We will basically blur out all the details that are in theproblem areas (horizon);

Page 24: Siggraph 2003 - Combining Fluids and Particles (With Maya)

24

Adjust the set range values as follows:

The setRange node converts Old Min/Max range into (new) Min/Max.Old Min/Max is the distance from camera at which we want to ramp up our blur. Bellowthe Min will be our crisp detail, above the Max will be the smoothed out. IMPORTANT:Since Maya cameras are created facing negative Z, the pointCamera returns negativenumbers also. So use negative numbers for distance to camera. The closer to zero a valueis , the closer to the camera it is. Large negative values are further.Min/Max is the output of the setRange utility, in this case our bumpBlur. They directlycorrespond to the Old values. Since the Old Max is close to camera, Max will be thebump close to camera, and Min will be bumpBlur far away.

Use IPR preview render to test different settings of distance to camera and blur. Thesevalues will change with the scale of the scene.

Page 25: Siggraph 2003 - Combining Fluids and Particles (With Maya)

25

This rendered image shows the default bumpBlur (0.05), fully blurred (33), and setRangeresult.

Finished scene: fluid_ocean_final.ma

Page 26: Siggraph 2003 - Combining Fluids and Particles (With Maya)

26

III. FOAM AND SPLASH INTERACTION

Now that we have some basic wakes, we can tackle the finer details of water interaction.

Creating Foam With Fluid Textures

Although any texture can be used to influence the foamOffset, none offer as muchflexibility as the 3dFluid texture. The same addWake tool we used in a previous wakescene can be used to generate foam.

1- Open scene: fluid_foam_fluid_start.ma . Notice that the boat already has a fluidemitter and 3dFluide texture connected to the ocean. Rather than using addWake togenerate foam, we will do it manually using the emitter already present;

2- Duplicate waveHeight_fluidTexture3D, and rename it: foamEmit_fluidTexture3D.IMPORTANT: This will also duplicate the fluid texture, but without renaming it. So withtwo OceanWakeTexture1 in the, Maya may have difficulty running certain commands(like connections) due to name clashing. To avoid connection problems later on, youshould rename this texture OceanFoamTexture1 . To find out which of the two is theduplicate:-Go to the Hypershade Textures tab;-Select both OceanWakeTexture1;-Click on the view upstream/downstream graph button;-In the Work Area, you’ll see that the duplicate texture is only connected to time;NOTE: To find the duplicate, you can also select foamOffset_fluidTexture3D and lookdownstream in the Attribute Editor (tabs at the top);

Page 27: Siggraph 2003 - Combining Fluids and Particles (With Maya)

27

3- Apply the following settings to the duplicate fluidtexture(foamOffset_fluidTexture3D):Container Properties > Resolution: 50 * 50 . We need very little resolution, since afractal texture inside the fluid will take care of the foam detail;

Container Properties > Size: 200 * 200 * 40. Same size as our wake fluid;

Contents Method> Temperature: Dynamic Grid . We turn ON Temperature since ouremitter is already emitting density (for the wake displacement). We’ll map Temperatureto the Ocean Shader foamOffset;

Contents Detail > Density Scale: 1. We don’t need as much density as with wakedisplacement. Too much turns the foam into a solid white mass;

Shading > Incandescence > Incandescence Input Temperature;

Shading > Opacity > Opacity Input: Temperature. IMPORTANT – Because we’reemitting temperature (not density) and only using opacity for our foam texturing;

Shading > Opacity > Input Bias: 0.3 . Higher values are softer in this instance;

Textures > Texture Opacity: ON . We’ll use variations in the opacity to give us thedetail and pattern we need for a foamy look;

Textures > Texture Type: Space Time ;

Textures > Opacity Texture Gain: 0.3 . Higher values look crisper, while lower onesare blurry/soft;

Texture > Depth Max: 4 . Ads fine details to the noise texture. Higher values look likethey have more depth, but take longer to render;

Texture > Invert texture: ON ;

Texture > Inflection: ON ;

Texture > Texture Time: Expression. Right click and Create New Expression. Typein the following: OceanFoamTexture1.textureTime = time;An animated texture time gives the texture a churning motion. Much like time does inother fractal and noise textures;

Texture > Frequency: 1 . In this case it’s already at 1, but it’s important to note that thisessentially scales the noise pattern. The default Maya setting when generating foamthrough the addWake tool is 10 (much too fine/small for this scene);

Page 28: Siggraph 2003 - Combining Fluids and Particles (With Maya)

28

Connect the foamOffset_fluidTexture3D fluid to OceanWakeEmitter1 fluid emitter .You can use the Windows > Relationship Editors > Dynamic Relationship Editor forthis. Just select the fluid (left menu), and left click on the emitter (right menu);

5- Connect the OceanFoamTexture1.outAlpha to the oceanShader1.foamOffset;

6- Now we need to emit some Temperature into the new foam fluid.Select OceanWakeEmitter1 . Copy the animation curve from Fluid Attributes >Density/Voxel/Sec into Heat/Voxel/Sec. Make certain that they start at frame 15 (that’swhen the boat starts foreword).Alternatively, you can simply connect the two attributes through the Connection Editor;

7- When you playback, the foam should be visible on the previewPlane in shaded view;So the back of the boat is emitting foam (engine froth). Now we can add a little from thehull contact (hull-line);

8- Shift Select the left half of the nubs hull (hull_port) andfoamOffset_fluidTexture3D. From the Main Menu Bar, activate Fluid Effects >

Page 29: Siggraph 2003 - Combining Fluids and Particles (With Maya)

29

Add/Edit Contents > Emit From Object (reset the Settings if you have to). Thisconnects a fluid emitter to the hull. Rename it hull_fluidEmitter;

9- If you playback, nothing emits from the hull. That’s because it isn’t emittingTemperature.Key hull_fluidEmitter > Heat/Voxel/Sec at frame 18 = “0” and frame 30 = “50”. Nowthe boat emits foam from all points of contact with the ocean;

Final scene: fluid_foam_fluid_final.ma

Page 30: Siggraph 2003 - Combining Fluids and Particles (With Maya)

30

Creating Particle Foam (and Splash)

Here we take a look at using colorAtPoint to float particle foam on the ocean surface.

1- Open scene: fluid_foam_particle_start.ma . Notice that there is already a particleemitter called motor_emitter on the small sphere section (motorSphere). If youplayback, the particles go flying everywhere because they aren’t connected to fields yet;

2- Select the particle’s shape node (foam_particleShape), and set the Conserve to 0.9.This will slow down the particles each frame, like air friction, so they won’t travel as far;

3- With the particles selected, go to the Main Menu Bar (Dynamics section): Fields >Gravity. Make certain it’s at 9.8. Since the particles were selected when the gravity fieldwas created, it is automatically connected. Else you could have used the ConnectionEditor or Fields > Use Selected As Source Of Field.

4- With the particle selected: Fields > Turbulence. Apply the following settings:Magnitude: 33 We need a large number because the conserve is low.Attenuation: 0 We don’t want the turbulence effect to fall-off with distance.Frequency: 0.5 This small number makes for a larger pattern appropriates for our scale;

If you playback the timeline, the particles are going straight through the oceanpreviewPlane.

We’ll add the expressions to float our particle foam. In the foam_particleShapeAttribute Editor, go to Per Particle (Array) Attributes, and right click the field next toposition. Select Runtime Expression from the dropdown menu.

Page 31: Siggraph 2003 - Combining Fluids and Particles (With Maya)

31

In the expression editor, type the following (or copy/paste from the CDrom data filefloatParticles_expression.txt):

//float particles on ocean surface (runtime)

//get ocean height at current particle positionvector $ppos = foam_particleShape.position;float $pu = $ppos.x;float $pv = $ppos.z;float $cpoint[] = `colorAtPoint -u $pu -v $pv oceanShader1`;

//when particle position lower than ocean, stick to oceanif($ppos.y <= $py)

foam_particleShape.position = <<$pu, $cpoint[0], $pv>>;

Playback the animation. It’s slower than before because of the colorAtPoint MELcommand. Using MEL in expressions is slower than regular math functions.

Also, when you playback you might notice that some particles tend to float above thewater too long. This is because the turbulence is so strong. Since we don’t want to loosesome of the particle pattern accumulation on the water surface, we’ll figure a way ofmaking the particles fall faster.Last, but not least, because the particles are sitting exactly on the ocean previewPlane,we’re loosing sight of about half of them. This is because particle position is calculatedfrom the center of the multiPoint radius. We can compensate with an offset;

7- Select OceanWakeEmitter1 , and add a new float attribute called foamOffset . Youcan use the Main Menu Bar > Modify > Add Attribute . We’ll use foamOffset in ourparticle expression to raise the particle on the ocean surface.

Set foamOffset to 0.3 ;

8- Make the following modifications to the foam_particleShape runtime expression (orcopy/paste from the CDrom text file floatParticlesDone_expression.txt):

//float particles on ocean surface (runtime)

Page 32: Siggraph 2003 - Combining Fluids and Particles (With Maya)

32

//get ocean height at current particle positionvector $ppos = foam_particleShape.position;float $pu = $ppos.x;float $pv = $ppos.z;float $cpoint[] = `colorAtPoint -u $pu -v $pv oceanShader1`;

//add user offset to foam heightfloat $py = $cpoint[0]+OceanWakeEmitter1.foamOffset;

//when particle position lower than ocean, stick to oceanif($ppos.y <= $py)

foam_particleShape.position = <<$pu, $py, $pv>>;//gradually increase gravity(faked) to counter turbulence//and make particles stick fasterelse if(foam_particleShape.ageNormalized >= 0.1) {

vector $pvel = foam_particleShape.velocity;

foam_particleShape.velocity = <<$pvel.x, $pvel.y-1, $pvel.z>>;}

Expression changes explained:$py : Contains our new height offset;ageNormalized : ageNormalized is the current age in percentage, relative to 1 (where 0is birth, and 1 is death). ageNormalized is normally only available if you connected anarrayMapper to the particle at some point (usually by adding a ramp to a Per Particleattribute. In this case we already had one in rgbPP);.velocity: We’re just subtracting 1 from the velocityY each frame starting at 10% of theparticle lifespan, so it will start coming down faster after a good initial push (from theemitter and turbulence field);

9- When you playback, the particles should behave correctly. We’re still missing anyinteraction at the waterline around the hull. This is more difficult to accomplish than withfluids. We don’t want our particles to emit from the hull too far above the waterline, andemitting too many particles below would be a waste. Ideally, we want to emit from thepoint of intersection between the boat hull and the water surface.We’ll generate a curve that follows the point of intersection. It’ll be usable for particle oreven fluid emission. First, we need a NURBS ocean surface, because we’ll by using theintersectSurfaces tool that require two NURBS surfaces;

Page 33: Siggraph 2003 - Combining Fluids and Particles (With Maya)

33

10- We’ll use the same script we used in the UVwake scene to create our NURBSpreviewPlane. Delete the current previewPlane, and make certainoceanNurbsPreviewPlane.mel is sourced. Type the following in the command line:

oceanNurbsPreviewPlane 25 50 oceanShader1;

This will take a while to calculate. When it’s done, you’ll have a rectangular NURBSpreviewPlane;

11- The preview plane and the boat hull have to intersect at all times without breaking forthe whole length of the animation (150 frames). The following transforms will correctlyplace the new Plane:

TranslationX: 11 ScaleX: 56TranslationZ: 37 ScaleZ: 113

12- With construction history ON, shift select the left hull (port_hull) and then theNURBS previewPlane. Main Menu Bar > Modeling > Edit NURBS > IntersectSurfaces with the following options:

Create Curves for: First SurfaceCurve Type: Curve ON SurfaceUse Tolerance: Local (0.0100)

You can scroll through the timeline and watch the curve intersection update, but it’s aslow process because the intersection has to be recalculated every frame. We’ll greatlyimprove performance by baking the curve (which also allows us to get rid of the veryheavy NURBS previewPlane);

13- Two problems with this new intersect curve prevent it from being baked:It’s a curve on surface;It has a different number of CVs every time it’s rebuilt (every frame);

Select the intersection curve, then Modeling > Edit Curves > Duplicate SurfaceCurves. Now we’ve generated a regular curve;

Select the new duplicate curve (should be outside the hierarchy), then Modeling > EditCurves > Rebuild Curve . Starting from the default settings, just change Number OFSpans to 24;

IMPORTANT: Throughout this whole process construction history should be ON (untilwe finish baking the curve).

14- Maya doesn’t have any good tools to bake geometry, for tasks like that we need someexternal scripts. An updated version of the popular bakeSoft.mel script is included withthe course data (bakeSoftPro.mel).

Page 34: Siggraph 2003 - Combining Fluids and Particles (With Maya)

34

With bakeSoftPro.mel sourced, select the rebuilt intersect curve’s shape node, then typein the command prompt:

bakeSoftPro 1 150 2;

Usage is: bakeSoftPro startFrame endFrame byFrame;

This will take a while.

15- Verify that the new baked curve follows correctly, then delete the other curves (thesource curve is now Visibility OFF) and the NURBS previewPlane.

Playback should be much faster;

16- Rename the new baked curve curvePort, and add a particle emitter to it: Dynamics >Particles > Emit From Object . Rename the new emitter curvePort_emitter, and deletethe new particle object. Change the emitter settings to:

Emitter Type: Curve;Rate: 3000;Speed: 9;Speed Random: 0;

The rest should be default;

17- Connect foamParticle to the curvePort_emitter using the Dynamic relationshipEditor.Now both emitters are emitting into the same floating particle system. Our only problemis that the hull emits too early. We’ll add one last element, a top-level control that willallow us to set the foam emission of both emitters;

18- Select OceanWakeEmitter1 and add a float attribute called foamParticle (Modify >Add Attribute). Set it to between 3 and 6 . This is our emission multiplier;

19- Last step. Create a new expression (Windows > Animation Editors) and type:

//emitterLink_expression

motor_emitter.rate = OceanWakeEmitter1.fluidHeatEmission *100 *OceanWakeEmitter1.foamParticle;

portCurve_emitter.rate = OceanWakeEmitter1.fluidHeatEmission *100 *OceanWakeEmitter1.foamParticle;

Expression explained:This will link the fluid emission rate (which is keyframed to the boat movement) to theparticle emission, and multiply them by our new override attribute;

The new playback shows particle foam emitting from the waterline and motor with

Page 35: Siggraph 2003 - Combining Fluids and Particles (With Maya)

35

correct timing;

Final scene: fluid_foam_particle_final.ma

Page 36: Siggraph 2003 - Combining Fluids and Particles (With Maya)

36

Creating Particle Crest Mist

The last step in our exploration of the Ocean shader and particles is the proceduralcreation of crest mist on a stormy sea. We’ll create top-level controls to tweak the spray’semission and behavior.

1- Open scene: fluid_spray_start.ma

2- Create a NURBS plane and scale it to 100. Rename the plane ocean_emitterPlane .The new plane will be used to emit the particle spray. W could emit from the OceanNURBS plane, but it would probably be too large and processor intensive. Also,having an independent plane allows us to render the larger base plane, and use thesmaller emitter plane to control the spray emission location.

3- Change the following settings in the ocean_emitterPlaneShape node:Render Stats: All OFFObject Display > Drawing Overrides: EnabledObject Display > Drawing Overrides > Shading: OFFObject Display > Drawing Overrides > Texturing: OFF

These settings are similar to those of the ocean previewPlane. They allow us toview ocean_emitterPlane in wireframe, but not display any shading, texturing, or

Page 37: Siggraph 2003 - Combining Fluids and Particles (With Maya)

37

rendering. This allows us to view and manipulate the plane at all times withoutinterfering with other elements, or continually toggling Visibility.

3- Add a particle emitter to ocean_emitterPlane. Dynamics > Particles > EmitFrom Object ;

4- Rename the emitter spray_emitter and the particles spray_particle. Apply thefollowing settings:

Emitter Type: SurfaceRate: 3000Speed: 5Speed Random: 2

The other emitter attributes should be default;NOTE: Increase the emission rate to whatever your workstation can handle. The

screenshots were taken with a rate of 100 000;

5- If you playback the timeline now, the particles are just accumulating above theemitter plane. We have to emit our particles from the ocean surface. Selectspray_particleShape , and add the following Creation Expression in Per Particle(Array) Attributes :

//creation expression floats particlesvector $ppos = pos;float $pu = $ppos.x;float $pv = $ppos.z;float $samp[] = `colorAtPoint -o A -u $pu -v $pv oceanShader1`;float $py = $samp[0];

//set initial particle position on ocean surfacepos = <<$pu, $py, $pv>>;

//default lifespanlifespanPP = rand(0.2, 1.5);

Expression Explained:Again, we’re using colorAtPoint to place our particles on the ocean surface (Yposition only). This time in Creation only, so the particles appear to generate fromthe waves, but are free to move afterwards in all axis.The lifespan per particle will allow us to cull particles at birth later on.

5- Set spray_particleShape > Lifespan Attributes > Lifespan Mode to lifespanPP .In the Attribute Editor, change spray_particleShape > Render Attributes >Particle Render Type to Multi Streak. Click Add Attributes For Current RenderType (same menu), and change the following settings:

Multi Radius: 1.8

Page 38: Siggraph 2003 - Combining Fluids and Particles (With Maya)

38

Tail Size: 2.0NOTE: If the attributes for Multi Streak Particles do not appear in Render Attributeswhen you click Add Attributes, just refresh the Attribute Editor by selecting/deselectingthe particles.

When you do a playback. The particles are appearing on the ocean surface;

6- Our spray isn’t supposed to come off the entire ocean surface, we want it to appearonly from the wave crests. To achieve this, we’ll generate particles only from thefoamy areas, and we’ll give the spray a minimum emission elevation.We need to do a few of thing in order to get ready for the crest spray.Select ocean_emitterPlane and add a float attribute (Modify > Add Attributes)called sprayThreshold with default settings. Set the sprayStart to 1.0 . This will beour minimum height for spray emission;

7- Add another float attribute to ocean_emitterPlane (Modify > Add Attributes) calledsprayThreshold with a minimum value of 0 a default of 85 and 100. This will be ouremission color tolerance. Only particles emitting from a wave point with a brightnesspercentage higher than sprayThreshold will appear. This enables us to emit onlyfrom the light foam areas of our ocean ;

8- Select spray_particleShape . In the Attribute Editor, Add Dynamic Attributes >Color > Add Per Particle Attribute . We’ll match the spray color to the Ocean foamat the point of emission. This will help to help blend the particles at render time;

9- Modify the spray_particleShape Creation expression as follows:

//creation expression floats particlesvector $ppos = spray_particleShape.position;float $pu = $ppos.x;float $pv = $ppos.z;float $samp[] = `colorAtPoint -o RGBA -u $pu -v $pv oceanShader1`;float $py = $samp[3];

Page 39: Siggraph 2003 - Combining Fluids and Particles (With Maya)

39

//set initial particle position on ocean surfacespray_particleShape.position = <<$pu, $py, $pv>>;

//match particle color to oceanspray_particleShape.rgbPP = <<$samp[0], $samp[1], $samp[2]>>;

//default lifespanspray_particleShape.lifespanPP = rand(0.15, 1.3);if($py < ocean_emitterPlane.sprayStart)

spray_particleShape.lifespanPP = 0;else if(spray_particleShape.rgbPP <(ocean_emitterPlane.sprayThreshold/100))

spray_particleShape.lifespanPP = 0;

Expression Explained:-We’ve changed the colorAtPoint to read all channels (RGBA). IMPORTANT: Theheight field array[] value for Alpha changes to [3] (from the previous [0]).-We’re now setting the color per particle from the Ocean Shader with the newcolorAtPoint sampling. The array values for color are: Red[0], Green[1], Blue[3].-Finally, we’re culling the particles at birth based on their altitude(ocean_emitterPlane.sprayStart) and their initial color(ocean_emitterPlane.sprayStart), so that only particles born in upper foamy areas willappear at creation. We cull particles by setting lifespan to 0;

10- Connect spray_particle to the three field already in the scene:spray_turbulenceField : It’s a stormy ocean;spray_gravityField : All things must fall (on Earth, anyway);spray_airField : Strong directional wind;

You can Window > Relationship Editors > Dynamic Relations to do your connections;

11- The particles are emitting at the correct position during playback, but sometimestravel through the waves. We’ll create an air pressure zone above the waves that will pullthe particles down if they travel too high. We’ll also prevent them from traversing thewaves. All this with handy top-level controls to “tweak” our settings interactively.

Page 40: Siggraph 2003 - Combining Fluids and Particles (With Maya)

40

Add a new float attribute to ocean_emitterPlane (Modify > Add Attributes) calledsprayHeigh with default settings. Set the sprayHeight to 10.0 . Any spray particlesabove this height (relative to the water surface) will be pulled down;

12- Add one last float attribute to ocean_emitterPlane (Modify > Add Attributes)called sprayPull with default settings. This is the force we’ll apply to particles above thesprayHeigh to pull the spray down towards the ocean surface;

13- Add the following Runtime Expression to spray_particleShape:

//runtime expression for ocean spray

//check wave surface heightvector $ppos = spray_particleShape.position;float $pu = $ppos.x;float $pv = $ppos.z;float $samp[] = `colorAtPoint -o A -u $pu -v $pv oceanShader1`;float $py = $samp[0];

//clamp lower particle altitude to wave heightif($ppos.y <= $py) {spray_particleShape.position = <<$pu, $py, $pv>>;}//drive particle down when it's too highelse if($ppos.y > $py + ocean_emitterPlane.sprayHeight) {

vector $pvel = spray_particleShape.velocity;spray_particleShape.velocity = <<$pvel.x, $pvel.y -

ocean_emitterPlane.sprayPull, $pvel.z>>;};

//gradually lighten particle color after emissionspray_particleShape.rgbPP += 0.005;

Expression Explained:-We’re calculation wave height with colorAtPoint again, but this time only enforcing itwhen particles travel too low, effectively faking particle collisions with the water surface.-We’re also driving particles down when they’re too high(ocean_emitterPlane.sprayHeight) relative to the waves. The downward force isachieved by subtracting Y velocity based on used input (spray_particleShape.velocity).We’re creating a kind of custom pulling/sucking force that hugs the irregular oceansurface.-Finally, we’re incrementally adding brightness to the particle color so they willgradually turn white. Since we’re using hardware particles, the color will automaticallyclamp to <<1, 1, 1>>;

14- We’ll finish off the look of our particles by adding fading off the particles before theydie, thus avoiding the “popping”. Select spray_particleShape . In the Attribute Editor,perform Add Dynamic Attributes > Opacity > Add Dynamic Attribute . If the newopacityPP attribute does not appear in your Per Particle Attributes, just refresh theAttribute Editor by deselecting/reselecting the particles;

Page 41: Siggraph 2003 - Combining Fluids and Particles (With Maya)

41

15- Right click opacityPP , and open the Create Ramp option box. In the Map Todropdown menu, select SprayOpacity_Ramp (a ramp that was provided with thisscene);

Final scene: fluid_spray_final.ma

Page 42: Siggraph 2003 - Combining Fluids and Particles (With Maya)

42

IV. MANAGING FLUID AND PARTICLE CACHES

Caching can be a frustrating, yet necessary experience at the end of a long production.Disk caching with particles has been available for years, how does the new Fluid diskcaching measure up? We’ll finish with an overview of the basic caching state of affairs;

Basic Fluid Cache Management

Fluids is the new kid on the bloc in Maya dynamics, but it brings a few tricks andimprovement for disk cache management.

Seeding: None of the Fluids have repeatability when being dynamicallysimulated. Only the Ocean Shader insures repetion without caching(unless you add a fluid texture simulation in one of the channels…);

Disk Cache: There are numerous advatageous features to Fluid Caching.Dynamics > Fluid Effects > Create Cache

Pros:-Can pick which elements to cache (Density, Velocity, Temperature,Texture…);-Can pick which cache element to read, simulate, or turn off;-One cache node/Fluid. Can be connected, scripted, switched, andotherwise manipulated. You can find the cache node by selecting yourcached fluid and viewing the connections in the Hypergraph orHypershade;-Multi-session caching. So we can Cache Density/Velocity one day, andColor/Texture the next by adding to the first cache file. Also allowscaches larger than a computer’s physical memory by building itincrementally;-Fluid cache files can be trimmed (truncated) from within Maya;-Simulations can easily be retimed/warped when they’re cached (bydisconnecting the Time attribute);-Faster rendering for large Fluid simulations;

Cons:-Can be very time consuming. Usually artist time;-A Fluid cache consists of a single file, this can be a curse when you runout of physical memory and the cache is ruined. Backups are mandatory;-Cache files have the scene name attached to them, so they follow theirscene. When performing save as, Maya copies the cache file (with thescene name in it). Disk hog;

Page 43: Siggraph 2003 - Combining Fluids and Particles (With Maya)

43

Basic Particle Cache Management

To cache, or not to cache, that is indeed the question with particles and distributedrendering. Generally speaking, particle disk caching is not required unless a simulation isvery heavy, mainly because particles are so easy to seed.

Global Seeding: Maya has a MEL command called seed which can seed all mathfunctions related randomizing (rand, sphereRand, gauss) in the entirescene. Seeding is only desirable when using randomize functions, sinceMaya’s own internal seeds take care of insuring repeatability with otherrandom-like functions (min/max distance, speed randomize, and liferandomize in emitters…);

Here are a couple of seeding expressions. Apply them in a NewExpression (not inside a dynamic expression):

//resetting seed on a single frame//looks very random//user must be very careful to insure that triggering//frame will be evaluated at render timeif (frame <= 1)seed 1;

//resetting seed every frame//can reveal pattern if seed changes by small increments//patterns can be interesting//this particular large increment (1001) is safe//very safe for distributed renderingint $seeder = frame*1001;seed $seeder;

Disk Cache: Here are a few pros and cons for disk caching:Dynamics > Slolvers > Create Particle Disk Cache

Pros:-Faster rendering than calculating dynamics (faster than seeding);-A physical file means they can be backed up;-Can be exported to another 3dpackage or renderer;-Cached particles can operate independently of emitter, fields, andcollisions. None are needed for rendering;-Very easy to change dynamic timings with Time attribute once particlesare cached;

Page 44: Siggraph 2003 - Combining Fluids and Particles (With Maya)

44

-Ramp driven attributes are not cached, so a well planed particle systemcan be cached and used for many render variation/passes with a singlecache;

Cons:-Very time consuming to generate large caches. Usually artist time;-The Create Particle Disk Cache tool caches all particle systems in ascene, even those with dynamics turned off;-Maya can only read cache files from one location at any given time;-Can be very IO intensive on a network;-Cane take huge amounts of storage space;

dynExport: One of the tools that can help reduce most of the particle disk cachelimitations, is the dynExport MEL command. DynExport allows a userto pick which particle system will be cached (one, a list, all), to whichdirectory, and what Per Particle attributes to cache. A judicious use ofthis command can drastically reduce cache time and disk spacerequirement, as well as IO time.NOTE: With dynExport, you must export all the PPattributes that haveinput/output connections, else they may not read the cache. This almostnever happens during the cache session, it usually breaks when trying toread the cache in a new session;

Others: Some cache management can be accomplished through you file browser.Since all particles disk cache filenames contain the particleShape name,it’s very easy to split, sort, and rearrange cache files and directories. Soparticle caches from different scenes can easily be brought together intoa new one without resimulating (just copy/paste the desired files into anew directory in your particles folder);

Mooooooo J