Requirements     

               
Prerequisite knowledge
To make the most of this tutorial, you need experience with ActionScript programming in Adobe Flash Builder or a similar integrated development envirionment (IDE). You also need previous experience developing Stage3D-based applications using Away3D. A good introduction to Stage3D and Away3D is Richard Olsson’s article Creating 3D games and apps with Away3D and Stage3D – Part 1: Setting up a 3D project in 30 minutes. Previous experience using Autodesk 3ds Max is also required.
Required products
Flash Builder (Download trial)
Sample files
User level
Intermediate
   

Away3D 4 is the latest version of the popular open source 3D engine for Adobe Flash Player and Adobe AIR. Based on the new Stage3D API available with Flash Player 11 and AIR 3, the new engine can be used for highly detailed 3D games, entertainment, simulation, and much more. The open source nature of the engine means you get full access to the source code, so you can even modify it should the need arise.

This tutorial shows how to take a biped-animated model from Autodesk 3ds Max and turn it into an interactive SWF file that can be played in Adobe Flash Player. You can see it running below. Click the man in the window to control the man using the arrow keys, the E key, Shift, and the Space bar.

To complete this tutorial, make sure you have 3ds Max installed and working on your computer. Then download the latest official version of Away3D 4 from the Downloads section on Away3D.com or download the most current version via GitHub. You will also need a tool for creating your SWF file such as Adobe Flash Builder.

Adding the AWD plugin to 3ds Max

The AWD format was created by the Away3D team because existing 3D file formats were not suited for the web. The goal was to create an extensible, compact format that enabled the export of 3D data with or without all assets embedded (such as textures, animation, and more). Support for any number of models is provided, so even complete scenes can be exported. The format is free, defined in an open specification, and has an open-source SDK for C++ and Python to aid in encoding AWD files and to encourage others to adopt the format in their software as well.

The AWD team intends to build AWD exporters for the most popular 3D packages such as Blender, Maya, and 3ds Max. The 3ds Max plugin for 3ds Max 2012 is available now. At the time this tutorial was written, the plugins for Maya and Blender are only available as source code, but will be available in compiled versions soon.

To install the 3ds Max plugin, download the version for your system (32-bit or 64-bit) and follow the instructions in the AWD in 3ds Max wiki. Once you have copied the files to the correct folder, restart 3ds Max and you will see the AWD option when you select Export from the main menu (see Figure 1).

Figure 1. The Away3D plugin is properly installed when you see Away3D (* AWD) as an option in the export menu.
Figure 1. The Away3D plugin is properly installed when you see Away3D (* AWD) as an option in the export menu.

Preparing the model in 3ds Max

The model and code for this tutorial was created by French designer Thillet Laurent. It started as a custom model that was rigged in Character Studio and animated with Biped. The samples files for this tutorial contain the 3ds Max file, textures, Biped .bip files, a src folder containing the ActionScript code, and a file named sequence.txt that I'll discuss later.

Follow these steps to get started:

  1. Open the onkba.max file in 3ds Max. You may see several dialog boxes as you open the file. Just click through these to open the file.
  2. Use the scrub bar at the bottom of the screen to see the three animations showing the model in paused, walking, and running states.
  3. Choose Graph Editors > Motion Mixer to see the three Biped animations and how they are ordered. From this screen (see Figure 2), you can speed up or slow down each animation by extending or compressing it. You can also change the order and position on the timeline.
Figure 2. Motion Mixer in 3ds Max
Figure 2. Motion Mixer in 3ds Max.
  1. To view the Bones driving the animation, open the Manage Layers panel (see Figure 3).
  2. Turn off the bulb in the Hide column on the BONE layer and turn it on for the SKIN layer.

The skeleton will be exported in the AWD file, but you can control the visibility using ActionScript when playing the animation. An option to only include layers set as "renderable" is on the current wish list, and that will eliminate this step in the future.

Figure 3. Viewing the bones
Figure 3. Viewing the bones.

While working with your own files for AWD export, keep in mind that AWD currently supports geometry and meshes (including instancing), scene graphs with containers and parenting, basic color and texture materials, skeletons, and skeletal animation. Any other elements, such as procedural textures and other Max specific features, will be ignored.

Exporting from 3ds Max

Once you have finished your model, you need to indicate which parts of the animation you want to export.

  1. Start by creating a new folder to hold your files.
  2. Open a new text file in the newly created folder and save it as sequences.txt. This file maps the animated frames with names that you can later reference in your code. You can find full instructions on the AWD wiki page on sequence text files.
  3. For this example, insert the following content in the file:
Breathe 0 60 Walk 70 130 Run 140 157

This file is only used when exporting from Max, as the exporter embeds this data into the AWD file. You can change the sequence around. The first one mentioned will be played back by the AWD preview application that is included with the exporter plugin.

  1. Now you are ready to export. Choose File > Export and browse to the folder you want to export to.
  2. Choose AWD in the dropdown and type a file name.
  3. Once you click Save, you'll get to the AWD export settings dialog box.
  4. Click through the various headings to inspect the options available. For most purposes, the defaults are fine.
  5. Under Animation, make sure that the name of the text file you just created is correct and click the Flash Viewer heading.
  6. To export the file, click the OK button.

After it exports the file, the exporter will, by default, create and open a Flash preview file. If you just want to view the file on your computer ensure Export For Local Preview is selected. If you want to export the file for others to view online, select Export For Deployment. If you choose the latter, you will not see anything when opening the exported file locally. This is expected behavior and part of the Flash Player security sandbox model.

  1. In this case, you'll want to view the exported file so select Export For Local Preview.
Figure 4. Away3D AWD options for exporting
Figure 4. Away3D AWD options for exporting.

Note: The plugin will export the whole scene. Exporting only selections is currently not supported.

Figure 5. The exported scene showing the skeleton
Figure 5. The exported scene showing the skeleton.

Don't worry if the Skeleton shows in the exported file (see Figure5). When you use it in your project, it's up to you to make it visible.

Note: If the exported file just shows a blank window and nothing loads, recheck your sequences.txt file. Ensure the file is inside the folder you are exporting to, that the filename is correct, and that the names in the file match the names you used in the Motion Mixer.

Using the model in Flash Builder

This tutorial does not cover the basic setup of an Away3D 4 scene. See the Tutorials section on Away3d.com for tutorials on the basics of cameras, lights, materials, and adding objects to your scene. In this tutorial, I'll be concentrating on the steps that make it possible to load the exported AWD file and then access and control the animations within.

For this part of the tutorial, you'll use Adobe Flash Builder, but you can use other IDEs as well. You can find a detailed description on how to use Away3D with Adobe Flash Professional, Adobe Flash Builder, and the free open source tool FlashDevelop in my article on the topic in Flash Magazine. You may also be interested in Using ActionScript projects in Flex or Flash, which explains how to use ActionScript projects in these same tools.

To start using the model, follow these steps:

  1. In Adobe Flash Builder, choose New > ActionScript Project.
  2. For the project name, type MaxAWDWorkflow. Click Finish (see Figure 6).
Figure 6. Creating the new ActionScript project in Adobe Flash Builder
Figure 6. Creating the new ActionScript project in Adobe Flash Builder.
  1. Copy all of the example files for this tutorial into the newly created project folder. This will replace the empty ActionScript class named MaxAWDWorkflow.as that Flash Builder created for you. You'll use this class very soon, but first you need to tell Flash Builder where to find the Away3D source files.
  2. After you download the Away3D source files to a local folder on your computer, right-click your project root and choose Properties.
  3. Click ActionScript Build Path on the left, and then click the Source Path tab.
  4. Click Add Folder and select the folder containing the Away3D source files (see Figure 7).
  5. Click OK.
Figure 7. Adding the Away3D files to your project
Figure 7. Adding the Away3D files to your project.

Your Package Explorer should now show all the files and folders required for the project, including MaxAWDWorkflow.as (see Figure 8).

Figure 8. The project in Package Explorer with the MaxAWDWorkflow file opened
Figure 8. The project in Package Explorer with the MaxAWDWorkflow file opened.

Stage3D embedding

  1. Choose Run > Run and verify that you can see a round, red sphere.

If you can't see anything in the exported file or you get an Error #2044 message, you may need to add modify your HTML template. This process is explained in the next section. If you see the red sphere, skip ahead to the section Running the example file.

Unfortunately, you can't just export your file when working with Stage3D. The most common problem is that you get a dialog box that says "Error #2044: Unhandled ErrorEvent:. text=Error #3702: Context3D not available." Context3D is one of the core classes for Stage3D in the Flash Player. Using Stage3D requires that you set the wmode parameter in your HTML embed code.

To do this in Flash Builder, follow these steps:

  1. Expand the html-template folder in Package Explorer.
  2. Right-click index.template.html and choose Open With > Text Editor.
  3. Locate the code that sets the various params properties and add the following line (see Figure 9):
params.wmode="direct";
Figure 9. Setting wmode in the index.template.html file
Figure 9. Setting wmode in the index.template.html file.
  1. If you are using Adobe AIR, you may need to add the following line to your application.xml file:
<renderMode>direct</renderMode>
  1. Attempt to run the application again.
  2. If you still have problems and you are using Flash Builder, IntelliJ, FlashDevelop, or any IDE based on an older version of the Flex SDK, you will need to add the following compiler argument:
-swf-version=13

This command will force compilation for Flash Player 11.x.

Running the example file

Once you know your setup works, you are ready to test the exported AWD file. To do this, you must set the AWDViewerLoth.as file to be the default file to run.

  1. In Adobe Flash Builder, right-click AWDViewerLoth.as and select Set As Default Application.

Keep AWDViewerLoth.as open for the rest of this tutorial as you will be referencing bits of it later.

  1. Choose Run > Run again and, if all goes well, you'll soon see your animated friend.
  2. You can use the arrow keys, the E key, and the Space bar to rotate and walk around. Hold down the Shift key to run.
  3. If the file fails to run and you get the message SecurityError: Error #2148, you'll need to add the compiler argument -use-network=false to your setup. See the Stack Overflow entry on Security Sandbox for more details.

To understand what makes this model work, I encourage you to explore the code.

Looking at the AWDViewerLoth class in the sample files, you will see the constructor calls the methods initEngine() , initText() and initLights() . These methods set up the scene, the view, and the camera—all the basics that you need to view your 3D content. The last method called in the constructor is initLoading(), which loads your assets using the AssetLibrary class.

The AssetLibrary class

AssetLibrary is a new class in Away3D 4 that simplifies working with loaded assets. Assets are any item that can be used in the engine: a Mesh, a Geometry, a BitmapTexture, and so on. You tell AssetLibrary to load what you need (models, textures, animations) and then request the results when loaded.

To use it, you must first enable the file format parsers that you want to use in your project. Away3D4 can import files in OBJ, AC3D, DAE, 3DS, MD2, and MD5 formats as well as the native AWD1 and AWD2 formats. You can add all these parsers at once by calling the Parsers.enableAllBundled() method. However, the more parsers you enable, the larger your SWF file. In this project, you can save 82Kb by enabling the AWD2 parser only:

AssetLibrary.enableParser( AWD2Parser );

AssetLibrary will keep you updated on the loading progress using the event system built into Flash Player. The three important events you should listen for are AssetEvent.ASSET_COMPLETE , LoaderEvent.LOAD_ERROR , and LoaderEvent.RESOURCE_COMPLETE .

AssetEvent.ASSET_COMPLETE

A 3D model may require more than just the mesh. For this example, the model contains animations that are controlled by a skeleton. The skeleton has different poses and it may also embed materials (basic color materials and textures are supported). The model itself is built from many different submeshes and these contain geometry. Using the onAssetComplete() method, which is the handler for the AssetEvent.ASSET_COMPLETE event, you can inspect each of these as they load and apply actions to them.

In this tutorial, this event is only used for debugging as the loading itself is handled by AssetLibrary. Using a trace command, you can see the name and type of each asset as it is loaded.

AssetLibrary.addEventListener(AssetEvent.ASSET_COMPLETE, onAssetComplete); private function onAssetComplete(event:AssetEvent):void { trace("Loaded " + event.asset.name + " Name: " + event.asset.name); }

If you run this application in debug mode and look at the trace output, you'll see that the loaded assets all have the same names as used when authoring in 3ds Max and the animations map to the names you added to the sequences.txt file. Take care when naming your models to avoid problems caused by naming conflicts. If there is a naming conflict, AssetLibrary has ways of handling some. Those methods are beyond the scope of this article.

You can also listen for even more detailed events that tell when each of these assets has been loaded. You can learn which events exist by looking at the top of the away3d.library.AssetLibraryBundle class included in the Away3D source.

LoaderEvent.LOAD_ERROR

This event occurs when an asset does not load as it should. Make sure you handle this event by adding an event listener to your loader and at a minimum, displaying an error message the user can see. If you do not handle this event or display and error message for the user to see, your project will not display anything and the user will see a blank screen when such an error occurs.

In the sample code for this tutorial the onLoadError() method simply traces the error out to the console. When running your project in debug mode, you should see "Error #2032: Stream Error" in your IDE when this error occurs.

AssetLibrary.addEventListener(LoaderEvent.LOAD_ERROR, onLoadError); protected function onLoadError(event:LoaderEvent):void{ showError("Error loading: " + event.url); }

LoaderEvent.RESOURCE_COMPLETE

This event will fire for every element you ask AssetLibrary to load. In this case, the texture is separate from the AWD model so you have two load calls:

AssetLibrary.load(new URLRequest(TEXTURE_URL)); AssetLibrary.load(new URLRequest(MESH_URL));

Note: AWD2 may also embed the textures into the model. This simplifies asset management at the price of larger files.

On the web, there is no guarantee that assets will complete loading in the same order as you request them. To manage this, the onResourceComplete() method maintains a counter to check that you have loaded all the resources you need before moving on.

AssetLibrary.addEventListener(LoaderEvent.RESOURCE_COMPLETE, onResourceComplete); private function onResourceComplete(ev:LoaderEvent):void { assetsThatAreloaded++; // check to see if we have all we need if (assetsThatAreloaded == assetsToLoad) { setupScene(); } }

Once both the model and the texture have loaded, it is safe to display your 3D model. This is done in the setupScene() method.

Rendering the output

Any material that is to be rendered in Away3D must be added to the scene. In the setupScene() method you prepare the material for your "hero" and then apply it to the model. Since most 3D programs work in arbitrary units, scaling your model will often be required. After the material is prepared and applied to the model, the model is scaled with the following code:

hero.scale( 8 );

You can avoid scaling the model if you know how the camera setup will work. Rather than scaling the model, you can tweak the camera setup to compensate for model size. It's all relative, so you decide. For larger 3D projects it is important to avoid any such issues by agreeing on a world scale and then making sure all models follow that.

When the model is set up as you want it, you add it to your scene:

scene.addChild( hero );

This makes the model renderable and thus visible. It will be standing in the default pose, so next you'll set up the animation set. This acts as a container for animation data and uses the values traced in the ASSET_COMPLETE handler earlier:

animationSet = new SkeletonAnimationSet(3); animationSet.addState(breatheState.name, breatheState); animationSet.addState(walkState.name, walkState); animationSet.addState(runState.name, runState);

Now that you have your animation set, you can set up your animator. It will connect the animation data to the model and provide a control mechanism. You do this with an animator object that ties together the skeleton information you retrieved from ASSET_COMPLETE with the newly created animation set, and applies it to your hero model. To stop the character from walking away from the camera, you can disable the position update that usually applies to bones animation when any motion is expected:

animator = new SkeletonAnimator(animationSet, skeleton); animator.updateRootPosition = false; hero.animator = animator;

Finally, you define a state transition for your animation states. This is used when transitioning active states in the animator, and can be custom created for whatever behavior is required. For now, you can use the default crossfade transition object:

crossfadeTransition = new CrossfadeStateTransition(XFade_TIME);

The XFADE_TIME constant (defined at the top of the ActionScript file) tells how many seconds Away3D should blend between the current and the new animation state. Setting this to zero would cause the change to happen instantly. This looks bad, so you usually want to blend the vertex positions as shown here.

To be sure that all the animations were successfully loaded and created, you invoke the animationSet.hasState() method for each animation that should exist. This isn't required, but it's a good idea to do this to avoid strange errors. If all is good, you point the camera at your hero and start rendering and listening for user input.

if (animationSet.hasState("Breathe") && animationSet.hasState("Walk") && animationSet.hasState("Run")) { hoverController.lookAtObject = hero; // point the camera at the hero goToPauseState(); // starts the "breathe" animation initListeners(); // get ready for user input } else { showError("Animation error"); }

Depending on which key the user presses, the movement of the character is performed in the updateMovement() method. If the user is not pressing any key, the goToPauseState() method is executed. In both of these methods, you set the name of the animation state and then activate it using:

animator.play(currentAnim, crossfadeTransition);

Where to go from here

Thanks to the AWD format and the AWD plugins, it is easy to import animated and textured models straight from Autodesk 3ds Max into Away3D. The new AssetLibrary class in Away3D 4 simplifies the loading procedure for basic scenes like this as well as for large and complex games. The ActionScript language makes it easy to build large scale interactive applications for the web and mobile, and the compactness of the AWD files improves the end user experience by ensuring less loading time.

Check out the Tutorials section on Away3D.com to learn more about using Away3D. You can also find more Away3D 4 tutorials at Flashmagazine.com and GotoAndLearn.