Login | Register
Flash 3D Basics

Flash 3D Basics

This article is for those new to 3D computer graphics. It will introduce you to the lingo used and will explain what is required to make 3D in Flash. If you don't know what a mesh, texture or shader is, this tutorial will prepare you for working with Flash 3D engines such as Papervision3D, Away3D and Sandy. This tutorial does not require programming knowledge as it only covers the basics of 3D on computers in general.

The tutorial is for the very beginners, but it also hold something for others. All the examples are done in Away3D and the source code for each example is available for download. Exploring source code is often the best way to learn, so if you wonder how any of the examples are created, download the code and have a look at it.

 Note that the example files were created in Away3D 3.6. They will not work directly in Away3D 4.x though you could probably adapt them.

Read more about using the example files at the end of this article. One more thing - all the examples require that you move your mouse over them. If all the Flash files on this page started playing at once, your browser would just crash. You'll soon learn why.

Let's get started. 3D is simple. It's something you're very used to as you see it all the time with your own eyes. Because of that, your brain know a lot about how 3D works. 3D in computers are very much like 3D in real life. The difference is that on the computer, everything you see is created by someone and that it is displayed in only 2 dimensions.

The third dimension

You probably remember graphing in Math classes at school? You plotted lines along the X and Y axis with seemingly no other purpose than to satisfy the teacher. In 2D graphics we use sets of X and y coordinates and plot lines between these to create lines. In 3D graphics we use sets of X, Y and Z coordinates.

This content requires Flash Player 9 (or a more recent version). You need to upgrade your Flash Player

movie: Triaxe.as

Click and drag on the example above. Here we've added a trident and three spheres. The spheres make it easier to understand how you are moving the trident. Without them, you would have no real sense of the rotation. Remember that unless you move a 3D object around (or animate it) it might just as well be a 2D drawing.

Vertices

A point in 3D space is called a vertex. To define a vertex you need to define a position for each of the three axes. Coordinates in 3D space are always in the order X, Y, Z. Just like a 2D point, the values are made in reference to a "point of origin". When you draw graphics in Flash, the position of the graphic is given as X and Y, relative to the upper left corner of the stage. A 3D world has a similar point of origin, so the X, Y and Z values can relate to this common reference.

Triangles

A triangle is the smallest possible 3D object you can draw. To create a triangle, you need three vertices. By changing the position of these three vertices, we can make the triangle face any direction along the three axes. This makes triangles very flexible and that is why they are the basic building block in most 3D software.

3D software often refer to these triangles as a "Face" (short for surface). There is another good reason for the name - these triangles usually face only a single direction, meaning that they are only visible from one side. Only the faces that face the virtual camera are displayed to the user.

Most 3D engines offer the possibility to flip what side is visible or to make the faces double-sided so they can be seen from both sides. If a face is set to be visible from both sides, it requires a little extra processing power. This may not seem as a problem, but to make something look good you will need a lot of these triangles.

This content requires Flash Player 9 (or a more recent version). You need to upgrade your Flash Player

movie: Triangles.as

Hover to play the sample above. Here we have 500 random triangles that you can toggle as single or double sided. Notice how making them double sided introduces a severe drop in framerate (framerate is measured as fps = frames per second). To make matters worse - the processing power for every computer varies, so Real-time 3D in Flash may require a lot of testing on different hardware to make it right.

3D models

By drawing a lot of triangles in 3D space and placing them next to each other, you can construct pretty much any kind of model. The resulting model is usually referred to as a Mesh or a wireframe. Drawing a curved surface is impossible with triangles, but by adding many triangles, a seemingly pointed surface will appear round.

This content requires Flash Player 9 (or a more recent version). You need to upgrade your Flash Player

movie: SphereTri.as

Click the plus and minus buttons to increase/decrease the triangle density of the Sphere above. The more you increase the resolution the Sphere, the less you can see that it's based on triangles. You'll also notice that as you add triangles, the animation slows down. The more triangles there is to render, the slower your animation will run.

This Sphere is one of the many Primitives you usually find in 3D engines. Other common primitives are Planes, Boxes, Cylinders and Cones. The primitives can take you far and you can also create your 3D models from scratch by drawing triangles. However, it's much easier to use a specialized software for creating models.

3D Modeling software

3D is a big industry and various programs suit different tasks. There's Swift3D, Blender, Strata, Maya, 3DS Max, Lightwave 3D, Softimage, Electric Image, Cinema4D, FormZ, Rhino, SketchUp and many more. These all vary immensely in terms of capabilities and price. Some are used to create simple effects and other are used in Hollywood.

Personally, I've used 3DS Max (expensive) and SketchUp (free), but I know that many in the Flash community use the Open Source tool Blender. The price point is hard to beat (free) and Blender exports to a variety of formats that works with Actionscript based 3D engines (thanks to Dennis Ippel). No matter what tool you choose, expect to spend some time to learn the tool. Creating 3D models can be a tedious task and the various software packages can be complex. Use tutorials you find online or get a good book to ease the process. As you get proficient at modeling, keep in mind what you just learned about the complexity of models as well. Something that looks good in the modeling software may easily be too complex to display in Real-time using Flash.

Views and Cameras

3D on a screen really isn't 3D at all. Real 3D requires that your two eyes see different things and that just isn't possible without specialized hardware. To solve this, we have to "translate" the 3D space into 2D. We do this by using a virtual camera connected to a View. The view is a rectangle that we make a projection of the 3D space onto.  By setting the width and height of the view, you decide the aspect of the resulting image. Classic television has an aspect ratio of 4:3 (width:height). New High Definition TVs use the 16:9 aspect ratio.

How the 3D model is drawn is decided by the properties of the Camera. Experiment with the example below.

This content requires Flash Player 9 (or a more recent version). You need to upgrade your Flash Player

movie: Camera.as

In this example, the camera position is fixed but you can vary the Zoom by moving up/down and the Focus width (often referred to as Field Of View or FOV) by moving sideways. Just as on an ordinary camera lens, a lower Focus value will see a wider area and a lower will see a more narrow area as illustrated in the "As seen from above" box. This sample is not 100% technically correct, but you should get the general idea. By moving the mouse cursor to the upper left corner, you'll get the "hyperdrive"-effect as seen in movies like Star Wars. If you move to the upper right corner, the 3D model will appear more "flat". Move down and you'll zoom in on the big red sphere.

The process of converting a virtual 3D scene to 2D is called 3D Projection. You view the triangles through a virtual Camera and project the onto a plane. The two main kinds of projection for 3D graphics called Perspective Projection and Orthographic Projection. Briefly said, the first considers the camera "optics" and the other does not. How the triangles position are translated are decided by the settings of the camera.

 

image

 

This is done using Matrix math and it's beyond the scope of this tutorial. If you know your math and want to learn more, click here. The average Flash user does not need to know anything about this unless you want to create your own 3D engine.

Textures

A wireframe model is kind of informative, but add a texture to the surface of the model and you'll get something that looks much more real. The process of adding textures is fairly complex since every triangle will need to show a small part of a larger image. Every one of these triangles may have rotation along the X, Y or Z axis so the texture must be skewed to compensate for this perspective.

If there is too few triangles, you will see distortions in the texture. By refining the underlying geometry by adding more triangles, we can make the texture look much better. Click the buttons to test this yourself.

This content requires Flash Player 9 (or a more recent version). You need to upgrade your Flash Player

movie: Textures.as

The textures are applied to the triangles according to a set of rules referred to as UV coordinates. These coordinates tell what part of the image goes on what triangle. Since the UV coordinates just point to various parts of a bitmap, you can easily skin an entire airplane with just one bitmap.

 

image

 

Different parts of the image are mapped onto the wings, body, wheels, interior and all other parts of the plane. The standard primitives contain UV coordinate presets. To create the UV coordinates for a complex model like an airplane, you would use a 3D modeling software.

There are several kinds of textures you can map onto the 3D model:

  • color mapping - single or multi colored surfaces
  • bitmap mapping - wraps a bitmap around your model
  • bump mapping - like bitmap maps, but uses an extra greyscale image to add "bumps" in the texture surface. Can greatly enhance a model without making the geometry more complex. (example)
  • environment mapping - like bitmap maps, but creates a "reflection" based on another bitmap that changes depending on object rotation (example)
  • normal mapping - smoothes the surface of the model making it appear to be much higher resolution. can be used to create bump map effects. (example)

The current 3D engines have differing capabilities in this area, so you'll need to do some research if you have special needs. Briefly said, Papervision3D supports color, bitmap, bump, environment and Away3D supports color, bitmap, environment, normal.

Remember that using the right texture will make your model stand out. There's a lot of high quality textures on the web, and you can get really far if you are willing to search around. However, if you have a budget there's much more available from commercial vendors. These are typically of better quality and higher resolution than what you can find online and by buying commercially, you'll also get a license for the use. This can save you from headaches later.

image

 

Image from our Heaven and Earth tutorial based on freely available textures

Light and shadow

For realism, nothing beats light and shadows. We are so used to this in the real world that we instantly notice if it's missing. It is common to have different kinds of lights like omni lights, directional lights and ambient lights. None of the current 3D engines in Flash offer very solid support for lighting and shadows and the reason is simple - this requires a lot of processing. Small demos have been done with the various engines, but these are more or less experiments.

Flash Player 10 and it's new Pixel Bender shader engine is what could bring about light and shadow to Flash, but for now these features are more or less novelty.

Shaders

While a plain textures sphere looks good and obviously can be used for a lot of purposes, it looks kind of flat. Shaders are what adds depth and richness to a 3D model. There are many kinds of shaders: Flat, Goraud, Phong, Bump, Cel/Cartoon and more. These add shadow, detail, highlights, reflections and refraction to the basic texture of a model. To see how lights combine with shaders affect 3D objects in Away3D, check this fine example by Ralph Brooker.

Ralph Hauwert, one of the Papervision3D contributors has done some experimental work on shaders that might make it into a future release. For now, most of the shaders available for use with Flash are simple Phong shaders. Expect that to change as Flash Player 10's 3D and Pixel Bender features are implemented.

Rendering

Rendering is the process of combining all of the above and outputting the projected image. We usually divide 3D into two kinds: Real-time and Pre Rendered. For use in Flash, Real-time is usually what we are after though Pre Rendered is fully possible. The current breed of 3D engines are all Real-time.

Most 3D software offers different kinds of renderers. Some offer advanced rendering of glass and refraction of light, but that's not possible in Real-time. In Real-time rendering, everything is about tradeoffs and tricks to make the playback smoother.A common trick is to not render the triangles that are not visible to the virtual camera. This process is called Culling. Another trick is that you may not need everything to be technically perfect at all times, so you can "cheat" by not sorting every triangle perfectly.

The various engines offer different renderers targeted at different scenarios. If you need precision and use less complex geometry, you can get some pretty good looking results. If you have complex geometry, you'll want to build your models so you can use the fastest renderer. Away3D offers 3 renderers: Basic (fast), Correct Z order (forces sorting of triangles) and Intersecting Objects (automatically subdivides objects into more triangles to display correctly). The GreatWhite branch of Papervision3D offers a Basic renderer as well as a Lazy renderer. The Sandy 3D engine has a different approach and offers four different sort methods. Future versions of each engine will add more renderers.

To illustrate how different renderers impacts the framerate, lets return to our Triangles example earlier in this article. Click the "renderer" button to change rendering method.

This content requires Flash Player 9 (or a more recent version). You need to upgrade your Flash Player

movie: Renderers.as

As you can see from this example, the Intersection Objects renderer is quite CPU intensive. The more objects that intersect, the lower fps. If you want to learn more about 3D rendering check this Wikipedia article.

Running the sample files

To learn how to use the downloaded files, check this tutorial on setting up Away3D. The examples require that you download and install the source code for Away3D and set the class files up for use with your IDE.  Note that the example files were created in Away3D 3.6. They will not work directly in Away3D 4.x though you could probably adapt them.

A final word of warning

Keep in mind when you start creating 3D content that you should have a good reason as to why you are using that third dimension. 3D is cool, but 3D for 3D's sake really isn't interesting. Make sure you utilize the extra possibilities 3D gives you and don't use it for something you could do better with plain 2D or even HTML / images. Your users and clients will thank you.

Notes

If this article is too "untechnical for you", check this great tutorial series by Caleb Johnston. It's based on Papervision3D, but most of it applies to any 3D engine. The tutorials explain some of the same things as this article, but in a more technical manner. The Wikipedia image on Perspective Projection is used under the GNU Free Documentation license. The 3D models used in this article were found on the web and are believed to be in the "public domain" due to their simplistic nature.

 

About Jens C Brynildsen

Jens has been working with Flash since version 3 came out. Since then, he's been an active member of the Flash community. He's created more than a hundred Flash games (thus the name of his blog) but he also creates web/standalone applications, does workshops and other consulting. He loves playing with new technology and he is convinced that the moment you stop learning you die (creatively speaking). Jens is also the Editor of this website.

Get new stories first

Click to follow us on Twitter!

 

Comments


Posted by xanxac on 07/22 at 03:21 AM

Hi, I am really interested in learning about away3d but find it very difficult to get the tutoriols running. For instance, I downloaded the sphereTri source code and saved it into a folder named “sphereTri” together with “away3d” folder,“nochump”, “com”(wich includes “bit101”), “MinimalComps”, “gs” and “awaybuilder”. then, created a new project in Flex named “sphereTri” and selected my sphereTri folder as the folder location.
Finally, tried to run the project and all I got was an empty internet explorer window with a grayish background.
I already went through the tutorial about setting up away3d. WHat didnīt I get right?
ANy help would be greatly appreciated.
Thanks in advance
Alex


Posted by Jens C Brynildsen on 08/08 at 08:48 PM

Hi Alex,
Sounds like your setup is correct. Can’t think of a good reason for this. Are there any errors output’ed?

It’s generally easier to start with the series of Away3D tutorials than these samples. The tutorials explain each new method carefully so you can troubleshoot these things yourself as you learn about them: http://www.flashmagazine.com/Tutorials/category/away3d/

J


Posted by FunkyDude on 08/24 at 10:10 AM

This was an interesting article, thanks for sharing. At first the demos for 3D in flash seem kind of crappy, but the environment mapping or normal mapping really gives you an idea of what’s capable.


Posted by PowerSparks on 10/09 at 05:59 PM

Great articles. really helpful and well written. I have started with the Triaxes.as and it seems there is a Class called Cover. I have re written TriAxes.as for flex as
public class TriAxes extends UIComponent

I am using the latest version of Away3d.
my question is how is “Cover” defined?
if this is a flash based class, then what might be an option for flex 3?


Posted by PowerSparks on 10/09 at 06:04 PM

oops, I see. I need the Cover.as


Posted by jimif on 01/18 at 03:41 PM

Hi,

I’m a full beginner with away3D. I tried the first example, triaxe.as and got an error about the cover object :
        cover = new Cover(this);
        addChild(cover);
error : undefined method (translated from french, sorry)
I tried to remove all stuff related to cover (3 lines), it compiles, but nothing appears in the window…

Another question : is it possible to load .x files from 3DSMax into away3D ?
Someone could help ?

Thx for answers…


Posted by Jens C Brynildsen on 01/29 at 09:51 AM

@jimif Did you also remove the if-statement surrounding the View.render() command?

private function onEnterFrame(e:Event):void
{
  // rerender viewport
  var cameraSpeed:Number = 0.3; // Approximately same speed as mouse movement.
  if (move) {
      camera.targetpanangle = cameraSpeed*(stage.mouseX - lastMouseX) + lastPanAngle;
      camera.targettiltangle = cameraSpeed*(stage.mouseY - lastMouseY) + lastTiltAngle;
  }
  camera.hover();
  View.render();
}

About 3DSMAX - Away3D can only load 3DS files, but I’m pretty sure that you can also export to Collada, OBJ, MD2 or one of the other supported formats.

J


Posted by jimif on 01/29 at 06:54 PM

Thx for your answer, I’ve advanced a lot since my post and all is ok now. I did not notice that cover.as was necessary to compile (I thought it was part of some library…).
I succeeded also to load .3DS files after using a tool to translate .x to .3ds (3DConverter).

Although, I got a new problem with away3D : objects (such as a simple plane) (with alpha=1) are not fully opaque, some parts of objects behind can sometimes be seen, is it a bug in away3D or there is a trick ? I never got this pb with direct3D.


Posted by Jens C Brynildsen on 01/29 at 10:50 PM

Yeah I know. The Cover.as file distracts. I should never have included that in the samples, only in the code for the SWFs that I ad to the tutorials. Will have to go through that before writing new tutorials.

About the alpha - I’ve not seen this in Away but I’ve seen it in many other apps. I would guess it’s a bug, but it may also be the compositing in the Flash Player.

I’ll usually set an object to visible = false to save CPU when alpha is zero as this removes the object from the rendering. If you use a tweening engine like TweenLite / TweenMax you’ll have options for stuff like that.

J


Posted by jimif on 01/30 at 07:25 AM

It seems that it is a rendering pb, some triangles appear or not, depending on the camera position although it should not be (the camera is far enough from these objects). Precision pb ?
This pb is less important as one increases the number of vertices, but is still here.
It’s a pity to see this result, my scene is so simple compared with some demo examples.

But it seems to be the same pb in your triangle.as demo, some triangles appear suddenly on the scene… and not smoothly as they should, they turn regularly and appear suddenly… I use Flash 10.


Posted by Jens C Brynildsen on 01/31 at 09:41 PM

@jimif This is expected behavior of most 3D engines. If you check out the Renderers.as example and toggle to the “Intersecting” renderer, you’ll see it working.

3D engines cheat a lot but it’s rarely visible. In this case, it is very visible since the triangles are intersecting and the renderer tries to toggle them on/off. To get around this issue, either change the model so no triangles are intersecting or use the “intersecting” rendering method. It’s super slow, but does the required splitting of the triangles.

J


Posted by jimif on 02/01 at 09:21 AM

Thx for your precision, i did not imagine that one could design renderers that are not not perfect for Z order. Anyway, my application is already too slow with the default renderer, I’ll have to wait for webgl (and opengl to be available for most of the processors) for a speedy real time application in a web wrapper…
Thx again for your answers and tutorials, it helps a lot.


Posted by Jens C Brynildsen on 02/01 at 12:12 PM

@jimif Yeah. I thought so as well, but think about it. The fast renderer uses a single Z value for each triangle. The more precise version will use all three vertices so it’ll take three times as long for this part of the rendering loop. The “intersecting” renderer will even go in and spilt triangles into more triangles to be sure it can be displayed correctly. So much more to do = slower.

No matter the technology (be it WebGL or Unity), it really makes sense to cheat as much as possible. If you drop by the Away3D forum (http://groups.google.com/group/away3d-dev) you’ll find all sorts of tips and tricks to solve performance problems and still make things run realtime in the Flash Player. The tricks often involve reducing the polygon count as much as possible and using Normal Maps. Reducing your ambitions and accepting a simpler looking final result will also help ;-)

J


Posted by Jovan.74 on 02/05 at 07:23 PM

hi… i’am a beginner in Away3d… and i have a question:
when i will add the ActionScript to the first layer, there is an error: “Packages cannot be nested”... can you help me ????


Posted by Jens C Brynildsen on 02/06 at 10:01 PM

@Jovan.74 Sure. Briefly said - code on the Flash timeline can only be simple actionscript statements, not a complete Class.

Read this tutorial on how to use Classes in Flash http://www.flashmagazine.com/Tutorials/detail/using_actionscript_projects_in_flex_or_flash/ That should explain what you need :)

J


Posted by Jovan.74 on 02/06 at 10:59 PM

@Jens C Brynildsen Thank you… now i understand it thanks again ;)


Posted by BobbyBerberyan on 08/02 at 07:32 PM

great article, even for seasoned flashers.

Submit a comment

Only registered members can comment. Click here to login or here to register