-->

Discover Clap Your Hands Say Yeah!

Having obtained an interactive, texture mapped scene I’d now like to a bit more realism into it by adding a light source and shading the objects. The price of course for having a more realistic scene is at the cost of reduced performance as you’ll find many more calculations are necessary to render the scene. You can find the equivalent article for Papervision3D in my post on First steps in Papervision3D : Part 4 - lighting and shading, however I find that there is quite a difference for Away3D, at least compared to the other tutorials in this series.

Previous articles summary :

Lighting in Away3D can be split into three basic components:

  • the light source(s) defining the properties of the light(s)
  • shaders providing algorithms that determine how a light source interacts with a material
  • a material type combining different shaders along with base colours or bitmaps

The first difference I notice compared to Papervision3D is that we can specify more than one light source. This of course increases the cpu load but in certain cases may produce a more realistic rendering of a scene.

There are three main types of light sources:

  • AmbientLight3D which has no position and provides a uniform ambient light to all objects
  • DirectionalLight3D which provides light from a specified position but with a strength that does not diminish with distance
  • PointLight3D providing light from a specified position that weakens in intensity with distance

In terms of shaders we have the following posibilities:

  • AmbientShader which provides ambient shading to a triangle face
  • DiffusePhongShader which, depending on the angle between the light source and a triangle face, produces a diffuse shading pattern
  • SpecularPhongShader which produces specular shading on triangles to imitate a surface that is reflecting light, depending on the observer’s position and the light position
  • EnviroShader allowing for environment mapping, producing a reflection from a surrounding environment on an object, independent of a light source. Requires bitmap data for the environment
  • DiffuseDot3Shader to increase scene reality by adding more small scale structure through the use of normal mapping to an object. Requires bitmap data for the normal map

The above shaders, with the exception of the EnviroShader assume that the light source is a DirectionalLight3D.

We then have a choice of CompositeMaterials that uses a combination of different shaders and base materials as shown in the following list:

  • PhongBitmapMaterial used to create ambient, diffuse and specular lighting on a texture-mapped material
    Base material : BitmapMaterial
    Shaders : AmbientShader, DiffusePhongShader and SpecularPhongShader
  • PhongMovieMaterial used to create ambient, diffuse and specular lighting on a material based on another Flash movie
    Base material : MovieMaterial
    Shaders : AmbientShader, DiffusePhongShader and SpecularPhongShader
  • PhongColorMaterial used to create ambient, diffuse and specular lighting on a simple coloured material
    Base material : ColorMaterial
    Shaders : AmbientShader, DiffusePhongShader and SpecularPhongShader
  • EnviroBitmapMaterial used to create environmental lighting on a texture-mapped material
    Base material : BitmapMaterial
    Shaders : EnviroShader
  • Dot3BitmapMaterial used to create ambient and normal-mapped lighting on a texture-mapped material
    Base material : BitmapMaterial
    Shaders : AmbientShader and DiffuseDot3Shader,
  • Dot3MovieMaterial used to create ambient and normal-mapped lighting on a material based on another Flash movie
    Base material : MovieMaterial
    Shaders : AmbientShader and DiffuseDot3Shader

The above materials all produce smoothly shaded objects which naturally has a price in terms of performance. If we want to have objects that are more simply shaded then we can use a CenterLightingMaterial. This type of material produces the equivalent of flat-shaded materials in Papervision3D. We have in this category two choices:

  • ShadingColorMaterial for simple flat shading of a ColorMaterial
  • WhiteShadingBitmapMaterial for simple flat shading of a BitmapMaterial, but assuming that the light source is always white (independent of colour given to light source).

In the example code for this article I’m going to look at two of these materials: the PhongBitmapMaterial and the WhiteShadingBitmapMaterial. These two materials are very simple to use and provide a lot of control over the lighting effects on the material. One advantage here, personally speaking, over Papervision3D is the ability to mix ambient, diffuse and specular lighting all together which is necessary to produce real Phong reflection. Papervision3D provides materials for ambient plus diffuse and ambient plus specular but not all three together. This obviously is quicker to render but is less realistic when drawing shiny materials for example. Mixing all three is still possible but requires more effort as I showed in my post on phong reflection with Papervision3D.

For the light source I’m simply going to use a DirectionalLight3D which, as I mentioned before, correctly renders these materials. Another aspect that I like with Away3D is that the light source itself can be given a number of characteristics. Specifically we can give it a colour and define relative strengths of ambient, diffuse and specular shading, none of which are possible with Papervision3D. Being able to specify a light colour allows us to create new effects with materials of different colours. Specifying the ambient level directly with the light source, for example, also eliminates the need to specify the ambient light with every material created, as is the case with Papervision3D.

Away3D also allows us to create more than one light source and have a material rendered appropriately, which is not possible in Papervision3D. This, again, is obviously a drain on computational resources, but, in certain cases, this can open up new possibilities for rendering a more realistic scene.

I guess what I like most is that, conceptually, Away3D allows us to disassociate the light source from the material meaning that we can create a specific material without thinking about the environment and lighting in which it will be placed.

Anyway, enough of the theory and personal opinions, lets move onto the code. I’m using exactly the same scene as for the previous example only this time adding a DirectionalLight3D and replacing the BitmapMaterial with PhongBitmapMaterial and WhiteShadingBitmapMaterial.

package {   import away3d.cameras.Camera3D;   import away3d.containers.ObjectContainer3D;   import away3d.containers.Scene3D;   import away3d.containers.View3D;   import away3d.core.base.Object3D;   import away3d.core.math.Number3D;   import away3d.core.render.Renderer;   import away3d.core.utils.Cast;   import away3d.events.MouseEvent3D;   import away3d.lights.DirectionalLight3D;   import away3d.materials.PhongBitmapMaterial;   import away3d.materials.WhiteShadingBitmapMaterial;   import away3d.primitives.Cube;   import away3d.primitives.Cylinder;   import away3d.primitives.Sphere;   import away3d.primitives.Torus;     import caurina.transitions.Tweener;     import flash.display.Bitmap;   import flash.display.Sprite;   import flash.display.StageAlign;   import flash.display.StageScaleMode;   import flash.events.Event;   import flash.events.MouseEvent;     [SWF(backgroundColor="#000000")]     public class Example005 extends Sprite {     [Embed(source="/../assets/earth.jpg")] private var EarthImage:Class;     private var earthBitmap:Bitmap = new EarthImage();     [Embed(source="/../assets/away3D.png")] private var Away3DImage:Class;     private var away3DBitmap:Bitmap = new Away3DImage();     [Embed(source="/../assets/checker.jpg")] private var CheckerImage:Class;     private var checkerBitmap:Bitmap = new CheckerImage();     private static const ORBITAL_RADIUS:Number = 150;     private static const CAMERA_ORBIT:Number = 600;     private var scene:Scene3D;     private var camera:Camera3D;     private var view:View3D;       private var group:ObjectContainer3D;     private var sphere:Sphere;     private var cube:Cube;     private var centerCube:Cube;     private var cylinder:Cylinder;     private var torus:Torus;       private var doRotation:Boolean = false;     private var lastMouseX:int;     private var lastMouseY:int;     private var cameraPitch:Number = 60;     private var cameraYaw:Number = -60;         public function Example005() {             // set up the stage       stage.align = StageAlign.TOP_LEFT;       stage.scaleMode = StageScaleMode.NO_SCALE;       // Add resize event listener       stage.addEventListener(Event.RESIZE, onResize);             // Listen to mouse up and down events on the stage       stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);       stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);       // Initialise Papervision3D       init3D();             // Create the 3D objects       createScene();             // Initialise frame-enter loop       this.addEventListener(Event.ENTER_FRAME, loop);     }     private function init3D():void {       // Create a new scene where all the 3D object will be rendered       scene = new Scene3D();             // Create a new camera, passing some initialisation parameters       camera = new Camera3D({zoom:25, focus:30});       setCameraPosition();             // Create a new view that encapsulates the scene and the camera       view = new View3D({scene:scene, camera:camera, renderer:Renderer.CORRECT_Z_ORDER});       // center the viewport to the middle of the stage       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;             //view.renderer = Renderer.CORRECT_Z_ORDER;             addChild(view);     }     private function createScene():void {       // create a new directional white light source with specific ambient, diffuse and specular parameters       var light:DirectionalLight3D = new DirectionalLight3D({color:0xFFFFFF, ambient:0.25, diffuse:0.75, specular:0.9});       light.x = 100;       light.z = 500;       light.y = 500;       scene.addChild(light);       // Create an object container to group the objects on the scene       group = new ObjectContainer3D();       scene.addChild(group);           // Create a new sphere object using a very shiny phong-shaded bitmap material representing the earth       var earthMaterial:PhongBitmapMaterial = new PhongBitmapMaterial(Cast.bitmap(earthBitmap));       earthMaterial.shininess = 100;       sphere = new Sphere({material:earthMaterial, radius:50, segmentsW:10, segmentsH:10});       sphere.x = ORBITAL_RADIUS;       sphere.ownCanvas = true;       group.addChild(sphere);       // Create a new cube object using a tiled, phong-shaded bitmap material       var tiledAway3DMaterial:PhongBitmapMaterial = new PhongBitmapMaterial(Cast.bitmap(away3DBitmap), {repeat:true, scaleX:.5, scaleY:.5});       cube = new Cube({material:tiledAway3DMaterial, width:75, height:75, depth:75});       cube.z = -ORBITAL_RADIUS;       cube.ownCanvas = true;       group.addChild(cube);         // Create a cylinder mapping the earth data again       cylinder = new Cylinder({material:earthMaterial, radius:25, height:100, segmentsW:16});       cylinder.x = -ORBITAL_RADIUS;       cylinder.ownCanvas = true;       group.addChild(cylinder);         // Create a torus object and use a checkered, flat-shaded (from white light) bitmap material       var checkerBitmapMaterial:WhiteShadingBitmapMaterial = new WhiteShadingBitmapMaterial(Cast.bitmap(checkerBitmap));       torus = new Torus({material:checkerBitmapMaterial, radius:40, tube:10, segmentsT:8, segmentsR:16});       torus.z = ORBITAL_RADIUS;       torus.ownCanvas = true;       group.addChild(torus);         // Create a new cube object using a smoothed, precise, phong-shaded, mat (not shiny) bitmap material       var away3DMaterial:PhongBitmapMaterial = new PhongBitmapMaterial(Cast.bitmap(away3DBitmap), {smooth:true, precision:2});       away3DMaterial.shininess = 0;       centerCube = new Cube({material:away3DMaterial, width:75, height:75, depth:75});       centerCube.ownCanvas = true;       group.addChild(centerCube);       // add mouse listeners to all the 3D objects       sphere.addOnMouseDown(onMouseDownOnObject);       cube.addOnMouseDown(onMouseDownOnObject);       cylinder.addOnMouseDown(onMouseDownOnObject);       torus.addOnMouseDown(onMouseDownOnObject);       centerCube.addOnMouseDown(onMouseDownOnObject);     }         private function loop(event:Event):void {             // rotate the group of objects       group.yaw(2);           // rotate the objects       sphere.yaw(-4);       cube.yaw(-4);       cylinder.yaw(-4);       torus.yaw(-4);       // update the camera position       updateCamera();       // Render the 3D scene       view.render();     }     // updates the camera position     private function updateCamera():void {             // If the mouse button has been clicked then update the camera position            if (doRotation) {                 // convert the change in mouse position into a change in camera angle         var dPitch:Number = (mouseY - lastMouseY) / 2;         var dYaw:Number = (mouseX - lastMouseX) / 2;                 // update the camera angles         cameraPitch -= dPitch;         cameraYaw -= dYaw;         // limit the pitch of the camera         if (cameraPitch <= 0) {           cameraPitch = 0.1;         } else if (cameraPitch >= 180) {           cameraPitch = 179.9;         }               // reset the last mouse position         lastMouseX = mouseX;         lastMouseY = mouseY;                 // reposition the camera         setCameraPosition();       }           }     // sets the camera position given pitch and yaw angles     private function setCameraPosition():void {       camera.y = CAMERA_ORBIT * Math.cos(cameraPitch * Math.PI / 180);       camera.x = CAMERA_ORBIT * Math.sin(cameraPitch * Math.PI / 180) * Math.cos(cameraYaw * Math.PI / 180);       camera.z = CAMERA_ORBIT * Math.sin(cameraPitch * Math.PI / 180) * Math.sin(cameraYaw * Math.PI / 180);             // keep the camera looking at the origin       camera.lookAt(new Number3D(0, 0, 0));     }     // called when mouse down on stage     private function onMouseDown(event:MouseEvent):void {       doRotation = true;       lastMouseX = event.stageX;       lastMouseY = event.stageY;     }     // called when mouse up on stage     private function onMouseUp(event:MouseEvent):void {       doRotation = false;     }       // called when mouse down on a 3D object     private function onMouseDownOnObject(event:MouseEvent3D):void {       var object:Object3D = event.object;       Tweener.addTween(object, {y:200, time:1, transition:"easeOutSine", onComplete:function():void {goBack(object);} });     }         // called when a tween created in onMouseDownOnObject has terminated     private function goBack(object:Object3D):void {       Tweener.addTween(object, {y:0, time:2, transition:"easeOutBounce"});     }         // called when the window is resized     private function onResize(event:Event):void {       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;     }   }     }

When compiled you should get the same result as below (click on the image). As before, the scene is interactive so you can click on the background and move the mouse to move the camera and click on an object to make it bounce.

Since the code is so similar to the previous example I’m going to concentrate solely on the function createScene - this is the only function that has been modified.

In this example we use a simple white light source and see four different types of materials rendered: one that is very shiny, another that has a mat texture, one that takes default lighting parameters (being quite shiny) and another that is flat shaded.

Starting with the light source, we use a DirectionLight3D for which we specify its position and lighting properties.

      // create a new directional white light source with specific ambient, diffuse and specular parameters       var light:DirectionalLight3D = new DirectionalLight3D({color:0xFFFFFF, ambient:0.25, diffuse:0.75, specular:0.9});       light.x = 100;       light.z = 500;       light.y = 500;       scene.addChild(light);

As you can see the constructor takes an array of initialisation parameters in which we set the colour to white and give it ambient, diffuse and specular factors (being between 0 and 1).

The first object that we create is the rotating globe. Here I wanted the object to appear to be very shiny so modify its shininess.

      // Create a new sphere object using a very shiny phong-shaded bitmap material representing the earth       var earthMaterial:PhongBitmapMaterial = new PhongBitmapMaterial(Cast.bitmap(earthBitmap));       earthMaterial.shininess = 100;       sphere = new Sphere({material:earthMaterial, radius:50, segmentsW:10, segmentsH:10});       sphere.x = ORBITAL_RADIUS;       sphere.ownCanvas = true;       group.addChild(sphere);

First of all, the PhongBitmapMaterial takes bitmap data for the texture mapping, as is the case for an ordinary, unshaded BitmapMaterial. Next we modify the shininess property (by default this is set at 20). This property, on the rendered scene, in effect modifies the extent of the specular lighting. The bright white dot that we see on the globe is reduced by increasing this property as if the light source is reflected off a more concentrated region of the material.

An important point to note is the line

      sphere.ownCanvas = true;

Without this line the scene is not correctly rendered as objects remain partially visible when they pass behind others.

Moving on to the tiled material object, I wanted to show that the initialisation parameters that we send to a material are still taken into account for the base material. The PhongBitmapMaterial is composed of a TransformBitmapMaterial (as well as the shaders) as we discussed in the previous example. The initialisation parameters {repeat:true, scaleX:.5, scaleY:.5} are passed directly to this element when it is constructed and therefore the texture map is still tiled. This object uses the default shading parameters of the PhongBitmapMaterial and is therefore appears less shiny than the globe.

The cylinder uses the same material as the globe just to illustrate that we can use the same material more than once.

Next, for the torus, we implement flat shading by using a WhiteShadingBitmapMaterial. As its name indicates this assumes a white light source. You can test this by experimenting with the light source colour. You’ll notice that all the other objects correctly reflect the change in light colour but this object remains white and red. This material is obviously less complex in terms of necessary calculations and therefore provides better rendering performance. However, we see that smoothly shaded materials, as with the other objects, allow us to reduce the number of rendered triangles to produce more rounded objects.

Finally, the cube in the center is rendered with shininess set to zero. Only diffuse and ambient lighting remain in this case. This is useful for rendering mat materials but unfortunately has no performance benefits. We can see however that there is a difference in the visible result for the two cubes.

So thats it for this tutorial! I hope this has given a useful overview of lighting and shading in Away3D. Of course I’ve not gone into detail for all the different types of lights and shaders - you’ll discover a lot by experimenting with this example, for example by changing the materials, the type of lighting, its properties and its position. I’ve purposely ignored the Dot3BitmapMaterial and EnviroBitmapMaterial for this post because I felt that it was important to look at simple lighting and shading first - they should appear in the next article. But for now, at least, I hope this provides a useful starting point - comments and suggestions, as always, are very welcome!

Next article:

-->
Monday, November 17th, 2008

First steps in Away3D : Part 4 - Scene interaction

Having created a scene last time with texture mapped objects, I’d now like to add some interaction so that we can rotate the camera around the scene and make the 3D objects react to mouse events. As you’ll see this is very straightforward with Away3D as each triangle drawn on the screen individually detects mouse events. For an equivalent tutorial in Papervision3D, check out First steps in Papervision3D : Part 5.

Previous articles summary :

For the scene interaction we’ll be looking at two different types of events. Firstly, the standard flash MouseEvent that we’ll use to rotate the camera when the user clicks on the stage and moves the mouse. Secondly we’ll look at the Away3D-specific event: the MouseEvent3D. This event is created for similar mouse actions on 3D objects but more importantly it contains the associated 3D object. To add MouseEvent3D listeners, all Object3D objects have the following functions for different mouse interactions:

Another new feature for this tutorial is to add object animation using an external library: Tweener.

Without having to calculate and specify the change in positions (for example) of objects within the code, a tween does all the hard work for us. A tween works on a particular property of an object and at each frame of an animation modifies this property in a particular manner. You’ll find more information on tweens on the web, for example at wikipedia.

Tweener is an opensource library, compatible with Actionscript2 and Actionscript3 as well as JavaScript and HaXE. To install it in your Eclipse/Flex Builder 3 environment simply create a new Flex Library Project, download the sources from the Tweener homepage and extract them into the src directory. The source should be automatically compiled and you can either link your own ActionScript projects to this project or directly used the compiled library. If you need help on compiling new flex library projects in eclipse then you should find useful information on my post for installing and compiling Away3D in eclipse.

Lets take a look at the code. I’m following directly from the example in the last post but am simply adding the new mouse listeners.

package {   import away3d.cameras.Camera3D;   import away3d.containers.ObjectContainer3D;   import away3d.containers.Scene3D;   import away3d.containers.View3D;   import away3d.core.base.Object3D;   import away3d.core.math.Number3D;   import away3d.core.utils.Cast;   import away3d.events.MouseEvent3D;   import away3d.materials.BitmapMaterial;   import away3d.materials.TransformBitmapMaterial;   import away3d.primitives.Cube;   import away3d.primitives.Cylinder;   import away3d.primitives.Sphere;   import away3d.primitives.Torus;     import caurina.transitions.Tweener;     import flash.display.Bitmap;   import flash.display.Sprite;   import flash.display.StageAlign;   import flash.display.StageScaleMode;   import flash.events.Event;   import flash.events.MouseEvent;     [SWF(backgroundColor="#000000")]     public class Example004 extends Sprite {     [Embed(source="/../assets/earth.jpg")] private var EarthImage:Class;     private var earthBitmap:Bitmap = new EarthImage();     [Embed(source="/../assets/away3D.png")] private var Away3DImage:Class;     private var away3DBitmap:Bitmap = new Away3DImage();     [Embed(source="/../assets/checker.jpg")] private var CheckerImage:Class;     private var checkerBitmap:Bitmap = new CheckerImage();     private static const ORBITAL_RADIUS:Number = 150;     private static const CAMERA_ORBIT:Number = 600;     private var scene:Scene3D;     private var camera:Camera3D;     private var view:View3D;       private var group:ObjectContainer3D;     private var sphere:Sphere;     private var cube:Cube;     private var centerCube:Cube;     private var cylinder:Cylinder;     private var torus:Torus;       private var doRotation:Boolean = false;     private var lastMouseX:int;     private var lastMouseY:int;     private var cameraPitch:Number = 60;     private var cameraYaw:Number = -60;         public function Example004() {             // set up the stage       stage.align = StageAlign.TOP_LEFT;       stage.scaleMode = StageScaleMode.NO_SCALE;       // Add resize event listener       stage.addEventListener(Event.RESIZE, onResize);             // Listen to mouse up and down events on the stage       stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);       stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);       // Initialise Papervision3D       init3D();             // Create the 3D objects       createScene();             // Initialise frame-enter loop       this.addEventListener(Event.ENTER_FRAME, loop);     }     private function init3D():void {       // Create a new scene where all the 3D object will be rendered       scene = new Scene3D();             // Create a new camera, passing some initialisation parameters       camera = new Camera3D({zoom:25, focus:30});       setCameraPosition();             // Create a new view that encapsulates the scene and the camera       view = new View3D({scene:scene, camera:camera});       // center the viewport to the middle of the stage       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;       addChild(view);     }     private function createScene():void {       // Create an object container to group the objects on the scene       group = new ObjectContainer3D();       scene.addChild(group);           // Create a new sphere object using a bitmap material representing the earth       var earthMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(earthBitmap));       sphere = new Sphere({material:earthMaterial, radius:50, segmentsW:10, segmentsH:10});       sphere.x = ORBITAL_RADIUS;       group.addChild(sphere);       // Create a new cube object using a tiled bitmap material       var tiledAway3DMaterial:TransformBitmapMaterial = new TransformBitmapMaterial(Cast.bitmap(away3DBitmap), {repeat:true, scaleX:.5, scaleY:.5});       cube = new Cube({material:tiledAway3DMaterial, width:75, height:75, depth:75});       cube.z = -ORBITAL_RADIUS;       group.addChild(cube);         // Create a cylinder mapping the earth data again       cylinder = new Cylinder({material:earthMaterial, radius:25, height:100, segmentsW:16});       cylinder.x = -ORBITAL_RADIUS;       group.addChild(cylinder);         // Create a torus object and use a checkered bitmap material       var checkerBitmapMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(checkerBitmap));       torus = new Torus({material:checkerBitmapMaterial, radius:40, tube:10, segmentsT:8, segmentsR:16});       torus.z = ORBITAL_RADIUS;       group.addChild(torus);         // Create a new cube object using a smoothed, precise bitmap material       var away3DMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(away3DBitmap), {smooth:true, precision:2});       centerCube = new Cube({material:away3DMaterial, width:75, height:75, depth:75});       group.addChild(centerCube);       // add mouse listeners to all the 3D objects       sphere.addOnMouseDown(onMouseDownOnObject);       cube.addOnMouseDown(onMouseDownOnObject);       cylinder.addOnMouseDown(onMouseDownOnObject);       torus.addOnMouseDown(onMouseDownOnObject);       centerCube.addOnMouseDown(onMouseDownOnObject);     }         private function loop(event:Event):void {             // rotate the group of objects       group.yaw(2);           // rotate the objects       sphere.yaw(-4);       cube.yaw(-4);       cylinder.yaw(-4);       torus.yaw(-4);       // update the camera position       updateCamera();       // Render the 3D scene       view.render();     }     // updates the camera position     private function updateCamera():void {             // If the mouse button has been clicked then update the camera position            if (doRotation) {                 // convert the change in mouse position into a change in camera angle         var dPitch:Number = (mouseY - lastMouseY) / 2;         var dYaw:Number = (mouseX - lastMouseX) / 2;                 // update the camera angles         cameraPitch -= dPitch;         cameraYaw -= dYaw;         // limit the pitch of the camera         if (cameraPitch <= 0) {           cameraPitch = 0.1;         } else if (cameraPitch >= 180) {           cameraPitch = 179.9;         }               // reset the last mouse position         lastMouseX = mouseX;         lastMouseY = mouseY;                 // reposition the camera         setCameraPosition();       }           }     // sets the camera position given pitch and yaw angles     private function setCameraPosition():void {       camera.y = CAMERA_ORBIT * Math.cos(cameraPitch * Math.PI / 180);       camera.x = CAMERA_ORBIT * Math.sin(cameraPitch * Math.PI / 180) * Math.cos(cameraYaw * Math.PI / 180);       camera.z = CAMERA_ORBIT * Math.sin(cameraPitch * Math.PI / 180) * Math.sin(cameraYaw * Math.PI / 180);             // keep the camera looking at the origin       camera.lookAt(new Number3D(0, 0, 0));     }     // called when mouse down on stage     private function onMouseDown(event:MouseEvent):void {       doRotation = true;       lastMouseX = event.stageX;       lastMouseY = event.stageY;     }     // called when mouse up on stage     private function onMouseUp(event:MouseEvent):void {       doRotation = false;     }       // called when mouse down on a 3D object     private function onMouseDownOnObject(event:MouseEvent3D):void {       var object:Object3D = event.object;       Tweener.addTween(object, {y:200, time:1, transition:"easeOutSine", onComplete:function():void {goBack(object);} });     }         // called when a tween created in onMouseDownOnObject has terminated     private function goBack(object:Object3D):void {       Tweener.addTween(object, {y:0, time:2, transition:"easeOutBounce"});     }         // called when the window is resized     private function onResize(event:Event):void {       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;     }   }     }

The example embeds the same images as the last time so if you need them you can find them in my last post. Don’t forget that you’ll need to link to the Tweener library for this to compile correctly. The resulting Flash movie should be as below - click on the image below to load it. Now when you click on the background and move the mouse you should be able to rotate the scene (effectively moving the camera) and clicking on each object should make them bounce.

First of all, lets have a look how the we add the standard Flash MouseEvent to rotate the camera.

Starting with the constructor we add two listeners.

      // Listen to mouse up and down events on the stage       stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);       stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);

When a mouse click is detected on the stage the function onMouseDown is called. When the button is released onMouseUp is called. These functions indicate when the camera movement should start and stop.

    // called when mouse down on stage     private function onMouseDown(event:MouseEvent):void {       doRotation = true;       lastMouseX = event.stageX;       lastMouseY = event.stageY;     }     // called when mouse up on stage     private function onMouseUp(event:MouseEvent):void {       doRotation = false;     }

To start the camera movement we set the boolean doRotation to true and to stop it we set it to false. The amount of rotation depends on how far the mouse moves during a single frame so we store the position of the mouse at every frame as well. The camera is then updated during the loop function

    private function loop(event:Event):void {             // rotate the group of objects       group.yaw(2);           // rotate the objects       sphere.yaw(-4);       cube.yaw(-4);       cylinder.yaw(-4);       torus.yaw(-4);       // update the camera position       updateCamera();       // Render the 3D scene       view.render();     }

Other than the call to updateCamera the rendering remains identical to the last example. The camera position is then calculated as follows.

    // updates the camera position     private function updateCamera():void {             // If the mouse button has been clicked then update the camera position            if (doRotation) {                 // convert the change in mouse position into a change in camera angle         var dPitch:Number = (mouseY - lastMouseY) / 2;         var dYaw:Number = (mouseX - lastMouseX) / 2;                 // update the camera angles         cameraPitch -= dPitch;         cameraYaw -= dYaw;         // limit the pitch of the camera         if (cameraPitch <= 0) {           cameraPitch = 0.1;         } else if (cameraPitch >= 180) {           cameraPitch = 179.9;         }               // reset the last mouse position         lastMouseX = mouseX;         lastMouseY = mouseY;                 // reposition the camera         setCameraPosition();       }           }

From the change in mouse position we calculate (arbitrarily) a change in angle from the y axis (pitch) and similarly around the y axis (yaw). The pitch is kept within limits to avoid the camera from going over the poles and hence changing the up direction of the camera. Once we’ve calculated the new values of pitch and yaw for the camera position we can convert these angles into x, y and z positions. This is done in setCameraPosition.

    // sets the camera position given pitch and yaw angles     private function setCameraPosition():void {       camera.y = CAMERA_ORBIT * Math.cos(cameraPitch * Math.PI / 180);       camera.x = CAMERA_ORBIT * Math.sin(cameraPitch * Math.PI / 180) * Math.cos(cameraYaw * Math.PI / 180);       camera.z = CAMERA_ORBIT * Math.sin(cameraPitch * Math.PI / 180) * Math.sin(cameraYaw * Math.PI / 180);             // keep the camera looking at the origin       camera.lookAt(new Number3D(0, 0, 0));     }

Note that we keep the camera at all times looking at the origin.

Moving on to the interaction with the 3D objects using the MouseEvent3D event, for this example I’m just going to look at the events when the mouse is clicked over an object. You’ll see that adding the listeners is very simple: at the end of the createScene a listener is added to each object.

      // add mouse listeners to all the 3D objects       sphere.addOnMouseDown(onMouseDownOnObject);       cube.addOnMouseDown(onMouseDownOnObject);       cylinder.addOnMouseDown(onMouseDownOnObject);       torus.addOnMouseDown(onMouseDownOnObject);       centerCube.addOnMouseDown(onMouseDownOnObject);

The rest of createScene is identical to the previous example. Now, whenever a user clicks on these objects, the function onMouseDownOnObject is called.

    // called when mouse down on a 3D object     private function onMouseDownOnObject(event:MouseEvent3D):void {       var object:Object3D = event.object;       Tweener.addTween(object, {y:200, time:1, transition:"easeOutSine", onComplete:function():void {goBack(object);} });     }

The listener is called with the MouseEvent3D passed as an argument. From this we can easily obtain the Object3D for which the event occurred. We then invoke Tweener to perform an animation on the object.

Tweener contains static methods that allow us to modify object properties. In this case we simply modify the y position of the object so that it goes to a value of 200 in 1 second using the easeOutSine transition function. I’d recommend looking at the Tweener documentation on the different transition functions. The onComplete argument allows us to put the sphere back to its original position when the tween has completed.

    // called when a tween created in onMouseDownOnObject has terminated     private function goBack(object:Object3D):void {       Tweener.addTween(object, {y:0, time:2, transition:"easeOutBounce"});     }

This then uses another tween with an easeOutBounce transition to move the sphere back to the x-z plane.

And that’s all there is to it! With Tweener you can modify a number of different properties in parallel. For example you can change y and scale the object at the same time. The interface provided by Away3D is in any case very easy to use. Making a comparison to Papervision3D I find it a bit easier: with Papervision3D we need to say that the say that each individual material is interactive, as well as the View itself. This is surely to produce some performance optimisation. Other than this the interaction with objects is very similar for both engines and, I hope you’ll find, is straightforward to implement!

Next article:

Sunday, November 16th, 2008

Musical Interlude - Editors


Discover Editors!
-->
Sunday, November 16th, 2008

First steps in Away3D : Part 3 - Texture mapping

In this post I’d like to show how to add textures to 3D objects rather than using plain colours which provides much more realistic (or at least interesting) rendering. You’ll find that with Away3D the concepts are very similar to those used in other 3D engines - for a comparison and some texture mapping references check out my equivalent tutorial for texture mapping in Papervision3D. I’m going to discuss texture mapping rather early on in this series of articles (earlier than for the Papervision3D series) simply because you’ll find that when come on to adding lighting and shading it opens up a much richer set of possibilities. But, I’m sure you’ll find that adding textures is a very simple process - at least, I hope so!

Previous articles summary :

Adding textures to objects in Away3D (as with most, if not all, 3D engines) is done by mapping coordinates on bitmap data to triangle vertices, known as texture mapping. More specifically, a technique known as uv mapping is used where u and v are the coordinates of the bitmap data which are then passed to the renderer for every triangle vertex. The following diagram tries to explain this for a pyramid. The uv coordinates are totally invented but you can see that for a single triangle the uv coordinates for every vertex are mapped onto the bitmap data (having a maximum u being equal to 1, and similarly for the maximum v) and the resulting triangle from the bitmap used to render the pyramid face.

In this example you’ll see that a number of different primitives are used (a cube, sphere, torus and cylinder). Each triangle used to produce these 3D objects has the uv coordinates for each vertex calculated. You can see in the link above for uv mapping the calculation necessary for a sphere. As you’ll see below, the image used to give texture to the sphere has been pre-calculated so that once mapped it produces a realistic image of the earth.

Ok, so on with the example code. As usual this is built on the previous example and there are not too many differences. We’ll go into more detail on what’s changed later. The code produces five primitives, all rotating about the origin and each one rotating about its individual y-axis.

package {   import away3d.cameras.Camera3D;   import away3d.containers.ObjectContainer3D;   import away3d.containers.Scene3D;   import away3d.containers.View3D;   import away3d.core.math.Number3D;   import away3d.core.utils.Cast;   import away3d.materials.BitmapMaterial;   import away3d.materials.TransformBitmapMaterial;   import away3d.primitives.Cube;   import away3d.primitives.Cylinder;   import away3d.primitives.Sphere;   import away3d.primitives.Torus;     import flash.display.Bitmap;   import flash.display.Sprite;   import flash.display.StageAlign;   import flash.display.StageScaleMode;   import flash.events.Event;     [SWF(backgroundColor="#000000")]     public class Example003 extends Sprite {     [Embed(source="/../assets/earth.jpg")] private var EarthImage:Class;     private var earthBitmap:Bitmap = new EarthImage();     [Embed(source="/../assets/away3D.png")] private var Away3DImage:Class;     private var away3DBitmap:Bitmap = new Away3DImage();     [Embed(source="/../assets/checker.jpg")] private var CheckerImage:Class;     private var checkerBitmap:Bitmap = new CheckerImage();     private static const ORBITAL_RADIUS:Number = 150;     private var scene:Scene3D;     private var camera:Camera3D;     private var view:View3D;       private var group:ObjectContainer3D;     private var sphere:Sphere;     private var cube:Cube;     private var centerCube:Cube;     private var cylinder:Cylinder;     private var torus:Torus;         public function Example003() {             // set up the stage       stage.align = StageAlign.TOP_LEFT;       stage.scaleMode = StageScaleMode.NO_SCALE;       // Add resize event listener       stage.addEventListener(Event.RESIZE, onResize);             // Initialise Papervision3D       init3D();             // Create the 3D objects       createScene();             // Initialise frame-enter loop       this.addEventListener(Event.ENTER_FRAME, loop);     }     private function init3D():void {       // Create a new scene where all the 3D object will be rendered       scene = new Scene3D();             // Create a new camera, passing some initialisation parameters       camera = new Camera3D({zoom:25, focus:30, x:-200, y:400, z:-400});       camera.lookAt(new Number3D(0, 0, 0));             // Create a new view that encapsulates the scene and the camera       view = new View3D({scene:scene, camera:camera});       // center the viewport to the middle of the stage       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;       addChild(view);     }     private function createScene():void {       // Create an object container to group the objects on the scene       group = new ObjectContainer3D();       scene.addChild(group);           // Create a new sphere object using a bitmap material representing the earth       var earthMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(earthBitmap));       sphere = new Sphere({material:earthMaterial, radius:50, segmentsW:10, segmentsH:10});       sphere.x = ORBITAL_RADIUS;       group.addChild(sphere);       // Create a new cube object using a tiled bitmap material       var tiledAway3DMaterial:TransformBitmapMaterial = new TransformBitmapMaterial(Cast.bitmap(away3DBitmap), {repeat:true, scaleX:.5, scaleY:.5});       cube = new Cube({material:tiledAway3DMaterial, width:75, height:75, depth:75});       cube.z = -ORBITAL_RADIUS;       group.addChild(cube);         // Create a cylinder mapping the earth data again       cylinder = new Cylinder({material:earthMaterial, radius:25, height:100, segmentsW:16});       cylinder.x = -ORBITAL_RADIUS;       group.addChild(cylinder);         // Create a torus object and use a checkered bitmap material       var checkerBitmapMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(checkerBitmap));       torus = new Torus({material:checkerBitmapMaterial, radius:40, tube:10, segmentsT:8, segmentsR:16});       torus.z = ORBITAL_RADIUS;       group.addChild(torus);         // Create a new cube object using a smoothed, precise bitmap material       var away3DMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(away3DBitmap), {smooth:true, precision:2});       centerCube = new Cube({material:away3DMaterial, width:75, height:75, depth:75});       group.addChild(centerCube);     }         private function loop(event:Event):void {             // rotate the group of objects       group.yaw(2);           // rotate the objects       sphere.yaw(-4);       cube.yaw(-4);       cylinder.yaw(-4);       torus.yaw(-4);       // Render the 3D scene       view.render();     }     private function onResize(event:Event):void {       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;     }   } }

Copy the code above and compile it within Flex Builder 3 or Eclipse. The images I used are shown below - click on them and save them if you want to use the same ones.

Click on the image below to see the resulting flash movie. The images are embedded in the movie making it larger than the previous examples so it could take a couple of seconds to load.

The code follows the same style as the previous examples: initialisation of 3D elements, creation of scene and rendering loop. As usual I’ll just concentrate on what’s new.

Not really related to Away3D but important for projects (in Flex) using images is the ability to embed images in the compiled movie. As you can see the images are embedded in the class definition.

    [Embed(source="/../assets/earth.jpg")] private var EarthImage:Class;     private var earthBitmap:Bitmap = new EarthImage();     [Embed(source="/../assets/away3D.png")] private var Away3DImage:Class;     private var away3DBitmap:Bitmap = new Away3DImage();     [Embed(source="/../assets/checker.jpg")] private var CheckerImage:Class;     private var checkerBitmap:Bitmap = new CheckerImage();

Using the Embed meta-tag we can add binary object to the compiled movie. These can then be converted into usable graphic elements, as shown above for a Bitmap. As with the same example in Papervision3D, I’m not going to go into detail of embedding objects here, rather I’ll leave you with these couple of references that are very useful. The first one is at at assertTrue and the second is from the Flex livedocs.

You’ll note that the source is “../assets”. This is because I have my assets folder at the same level as the src folder - when the Actionscript is compiled, the root folder is the src folder. If you want to compile the above source then simply create an assets folder and put the image files in it.

Now that we have embedded the images and obtained bitmap data we can start to create texture mapped materials. This is done in createScene where some different methods of creating different textures is examined.

    private function createScene():void {       // Create an object container to group the objects on the scene       group = new ObjectContainer3D();       scene.addChild(group);           // Create a new sphere object using a bitmap material representing the earth       var earthMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(earthBitmap));       sphere = new Sphere({material:earthMaterial, radius:50, segmentsW:10, segmentsH:10});       sphere.x = ORBITAL_RADIUS;       group.addChild(sphere);       // Create a new cube object using a tiled bitmap material       var tiledAway3DMaterial:TransformBitmapMaterial = new TransformBitmapMaterial(Cast.bitmap(away3DBitmap), {repeat:true, scaleX:.5, scaleY:.5});       cube = new Cube({material:tiledAway3DMaterial, width:75, height:75, depth:75});       cube.z = -ORBITAL_RADIUS;       group.addChild(cube);         // Create a cylinder mapping the earth data again       cylinder = new Cylinder({material:earthMaterial, radius:25, height:100, segmentsW:16});       cylinder.x = -ORBITAL_RADIUS;       group.addChild(cylinder);         // Create a torus object and use a checkered bitmap material       var checkerBitmapMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(checkerBitmap));       torus = new Torus({material:checkerBitmapMaterial, radius:40, tube:10, segmentsT:8, segmentsR:16});       torus.z = ORBITAL_RADIUS;       group.addChild(torus);         // Create a new cube object using a smoothed, precise bitmap material       var away3DMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(away3DBitmap), {smooth:true, precision:2});       centerCube = new Cube({material:away3DMaterial, width:75, height:75, depth:75});       group.addChild(centerCube);     }

As you can see, the creation of the 3D objects is very simple: just create a new primitive, pass it some initialisation arguments and create a new material for it. Of course, compared the previous example, the materials are now texture mapped. Two different materials are used in this example: the BitmapMaterial for simple texture mapping and TransformBitmapMaterial which gives us more options.

Starting with the Sphere, we use a simple BitmapMaterial and pass it bitmap data. The class Cast in Away3D provides useful transformation routines - in this case to return the BitmapData of the Bitmap object.

      var earthMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(earthBitmap));

The Sphere is then created using this material. All uv mapping is handled by the Sphere itself to render the image over the sphere triangles.

The next object is a Cube. Here I want to illustrate how to tile images over an object. Tiling allows us to repeat an image over a surface, for example imagine a scene with a grassy plain with the same grass image repeated a number of times. This allows us to keep the image size reasonable and have a texture mapped object that isn’t too pixelated.

      var tiledAway3DMaterial:TransformBitmapMaterial = new TransformBitmapMaterial(Cast.bitmap(away3DBitmap), {repeat:true, scaleX:.5, scaleY:.5});

To tile bitmap we need to use the TransformBitmapMaterial class. With this we can manipulate the image data, for example, here we scale it to half its size and indicate that it should be repeated. Scaling here implies that the maximum u and v coordinates of the texture become 0.5 rather than 1 hence we should see a two-by-two image drawn on each face of the cube. If the repeat:true initialisation parameter is skipped then the image is drawn only once… try recompiling without this to see the result.

The Cylinder and Torus objects use simple BitmapMaterials again just to show how the bitmaps are mapped to these primitives.

Finally the cube in the center shows an example of a texture map using a smoothed image and uses more precise perspective calculations when rendered. This link for texture mapping shows what happens for affine texture mapping: Away3D (as for Papervision3D) tries to optimise the calculation for rendering textures and this can result in a distorted image. You can see this in the above example for the tiled cube where the black lines appear to be wavy. The distortion can, however, be corrected but of course this produces a more cpu-intensive calculation.

      var away3DMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(away3DBitmap), {smooth:true, precision:2});

For the central cube we set smooth:true to have a less pixelated texture and we set precision:2 to indicate that the texture should be correctly rendered to within 2 pixels. A value of 0 turns off the precision calculation.

As an alternative to using more precise rendering of a texture we can also increase the number of triangles used so that the distortion becomes less evident. You can check out this example for Papervision3D that illustrates the result. Of course, increasing the number of triangles increases the render time but within limits it can produce a visually acceptable rendering quicker than a single precise texture mapping.

So that’s it for texture mapping at its simplest! As you can see there’s nothing too complicated in adding bitmaps to 3D objects but bear in mind that it is obviously more cpu-intensive that simple coloured objects. As with the previous articles I’d recommend having a look at the Away3D source - you’ll see that there are a lot of different types of materials in the away3D.materials package including the BitmapFileMaterial which loads an image from a URL, rather than embedding it in the movie. Anyway, hope this has been of use. As always, questions and comments are welcome!

Next article:

Saturday, November 15th, 2008

First steps in Away3D : Part 2 - Animation

Following from my previous post, I’d like to make the scene a bit more interesting by adding some animation. As you’ll see, not many modifications to the code are necessary. As with Part 1, I’m basing this example on a previous Papervision3D example that you can find in First steps in Papervision3D : Part 3.

Previous articles summary :

Using the same objects as before (a Sphere and LineSegments displaying the x, y and z axes), my objective is to rotate all of them about the origin and individually rotate the sphere. Rotation in Away3D is very easy to achieve. These objects inherit from a base class called Object3D as do all 3D object displayed in a Scene in Away3D. This class provides a number of useful functions to rotate, translate and scale an object. The simplest way to rotate an object is to use the pitch, yaw and roll functions which rotate an object about its local x, y and z axes respectively.

So, lets dive right in and take a look at the code. As I mentioned before, this is based on the previous example and very little modifications have been made. As before I’m using eclipse with the Flex Builder 3 plugin to compile the examples: take a look at my previous post if you’re new to eclipse and want to see how to set up the projects. Otherwise, create a new ActionScript class, call it Example002 and cut and paste the following code.

package {   import away3d.cameras.Camera3D;   import away3d.containers.ObjectContainer3D;   import away3d.containers.Scene3D;   import away3d.containers.View3D;   import away3d.core.base.Vertex;   import away3d.core.math.Number3D;   import away3d.materials.WireColorMaterial;   import away3d.materials.WireframeMaterial;   import away3d.primitives.LineSegment;   import away3d.primitives.Sphere;     import flash.display.Sprite;   import flash.display.StageAlign;   import flash.display.StageScaleMode;   import flash.events.Event;     [SWF(backgroundColor="#000000")]     public class Example002 extends Sprite {     private var scene:Scene3D;     private var camera:Camera3D;     private var view:View3D;       private var group:ObjectContainer3D;     private var sphere:Sphere;         public function Example002() {             // set up the stage       stage.align = StageAlign.TOP_LEFT;       stage.scaleMode = StageScaleMode.NO_SCALE;       // Add resize event listener       stage.addEventListener(Event.RESIZE, onResize);             // Initialise Papervision3D       init3D();             // Create the 3D objects       createScene();             // Initialise frame-enter loop       this.addEventListener(Event.ENTER_FRAME, loop);     }     private function init3D():void {       // Create a new scene where all the 3D object will be rendered       scene = new Scene3D();             // Create a new camera, passing some initialisation parameters       camera = new Camera3D({zoom:15, focus:30, x:100, y:300, z:-200});       camera.lookAt(new Number3D(0, 0, 0));             // Create a new view that encapsulates the scene and the camera       view = new View3D({scene:scene, camera:camera});       // center the viewport to the middle of the stage       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;       addChild(view);     }     private function createScene():void {       // Create an object container to group the objects on the scene       group = new ObjectContainer3D();       scene.addChild(group);             // Create a new sphere object using a wirecolor material       var sphereMaterial:WireColorMaterial = new WireColorMaterial(0x5500FF, {wirecolor:0xFF9900});       sphere = new Sphere({material:sphereMaterial, radius:50, segmentsW:10, segmentsH:10});       // Position the sphere and add it to the group       sphere.x = -100;       group.addChild(sphere);         // Create a origin vertex       var origin:Vertex = new Vertex(0, 0, 0);       // Create the red-coloured x-axis with a width of 2 and add it to the group       var xAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0xFF0000, {width:2})});       xAxis.start = origin;       xAxis.end = new Vertex(100, 0, 0);       group.addChild(xAxis);           // Create the green-coloured y-axis with a width of 2 and add it to the group       var yAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0x00FF00, {width:2})});       yAxis.start = origin;       yAxis.end = new Vertex(0, 100, 0);       group.addChild(yAxis);           // Create the blue-coloured z-axis with a width of 2 and add it to the group       var zAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0x0000FF, {width:2})});       zAxis.start = origin;       zAxis.end = new Vertex(0, 0, 100);       group.addChild(zAxis);       }         private function loop(event:Event):void {             // rotate the group of objects       group.yaw(5);           // rotate the sphere       sphere.yaw(-10);           // Render the 3D scene       view.render();     }     private function onResize(event:Event):void {       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;     }   } }

This should produce a scene that is rotated about the y-axis with a sphere that rotates in the opposite direction, also about its y-axis. Click on the image below to see the final result.

As always, lets take a look at the code in more detail. Since there are so many similarities with the previous example I won’t go into detail for everything, just what is new.

Starting with the constructor, you’ll notice that I’ve added a resize listener that calls the method onResize.

    private function onResize(event:Event):void {       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;     }   } }

This is used to ensure that if a user resizes the browser or flash player that the View is automatically resized to take up the full stage area. Its not really much of a 3D element of the scene but its important not to forget it!

The rest of the code takes the same form as before: initialise the 3D elements, create the scene and re-render the scene at every new frame. As you’ll see in init3D I’ve modified the camera slightly.

      // Create a new camera, passing some initialisation parameters       camera = new Camera3D({zoom:15, focus:30, x:100, y:300, z:-200});       camera.lookAt(new Number3D(0, 0, 0));

The camera is now in a different position, but more importantly I’ve added a call to camera.lookAt. Previously the camera was looking directly along the z-axis: now I’ve told it to look at the origin. You can similarly call the functions tilt and pan which (as it says in the code comments for the Camera3D class) is like someone nodding and shaking their head.

Moving on to the scene creation in createScene, I’ve introduced a new element used to group the objects: an ObjectContainer3D.

      // Create an object container to group the objects on the scene       group = new ObjectContainer3D();       scene.addChild(group);

This object is not itself visible on the scene but allows us to add children to it and translate, rotate and scale these children all together. So, rather than adding each individual object to the scene, they are now added to the group as is, for example, the sphere.

      // Create a new sphere object using a wirecolor material       var sphereMaterial:WireColorMaterial = new WireColorMaterial(0x5500FF, {wirecolor:0xFF9900});       sphere = new Sphere({material:sphereMaterial, radius:50, segmentsW:10, segmentsH:10});       // Position the sphere and add it to the group       sphere.x = -100;       group.addChild(sphere);  

The lines are similarly added to the group. So that’s the only difference to the scene creation itself (other than the sphere now being a different colour). Now we come to adding the animation.

To add animation we simply need to modify object parameters at each frame and then re-render the scene. As I mentioned before I simple rotate the ObjectContainer3D and the Sphere itself and this is done in the loop function that is called at the start of every new frame.

    private function loop(event:Event):void {             // rotate the group of objects       group.yaw(5);           // rotate the sphere       sphere.yaw(-10);           // Render the 3D scene       view.render();     }

As you can see there’s really not much to it: simple rotate the group about its y axis, and the same for the sphere itself. The call the view.render then updates what we see on the screen.

And that’s it! To get a feel for the animation, try changing the yaw method to roll or pitch, or try adding some translation. I’d recommend having a look at the Away3D code to see what else is available - you’ll find that there are a lot of possibilities! Anyway, I hope this has been a useful step in making more interesting 3D scenes in Away3D!

Next article:

Wednesday, November 12th, 2008

Musical Interlude - dEUS


Discover dEUS!
Wednesday, November 12th, 2008

First steps in Away3D : Part 1 - Getting started

In the same spirit as the First steps in Papervision3D series of articles, I’m documenting my own progress in learning about this 3D engine for Flash. I hope as well that this provides a useful tutorial for others getting started with Away3D. I guess what I’m trying to say is that this is by no means a definitive guide to Away3D! This is my first day as well so if you find mistakes or have suggestions then please let me know!

Before starting I’d like to post a couple of links to a series of articles that I found very interesting and useful for beginners learning the basics of 3D programming. The first one one, Flash 3D Basics, provides a very good overview of the important elements for any 3D development. The second one is aimed directly at Away3D, but is relevant also to Papervision3D, and discusses the two main classes for any Away3D flash movie: The View and The Scene. You’ll see both of these being used below. Anyway, I’d really recommend taking a look at them.

For this post I’m really starting at the very beginning. My aim is simply to draw 3D shapes on the screen, exactly as I did for First steps in Papervision3D : Part 1. For this I’m assuming that you are using Flex Builder 3, or the Flex Builder 3 plugin for eclipse, as I am. I’m also assuming that you have Away3D built and ready to link to. My previous article on downloading and installing Away3D in eclipse might help if this isn’t the case.

For those of you who are new to using Flex Builder 3, we need to first of all create a new project and then set it’s build path to that of the Away3D source.

In eclipse (or Flex Builder 3), from the File menu, select New and then ActionScript project. You’ll see a New ActionScript Project window appear.

Type in a project name (for example I named it Tartiflop) and click on Finish. We then need to configure the project to use either the Away3D.swf library that I showed how to create before, or we link directly to the Away3D source. I prefer the second method simply because it gives me a more convenient access to the library source by navigating within eclipse. To do this, select the new project and right-click. Select Properties from the drop-down menu. Select the ActionScript Build Path on the left.

Select the Library path tab and click on Add Project….

Select the Away3D Flex Library project and click on OK. You’ll see that the library has now been added into the list of build path libraries.

We’re now ready to start creating our first Away3D flash movie! You’ll notice that the new project wizard of eclipse has automatically created an ActionScript class called Tartiflop.as. We don’t need this so you can delete it. For this post the class is called Example001.as so you’ll need to create a new ActionScript. Right-click on src in the Tartiflop project in the Flex Navigator tree. Select New and then ActionScript Class. Name the new class Example001 and click Finish.

The following code draws a sphere and three lines showing the x, y and z axes. Cut and paste the code below (we’ll go into the details of how it works later), save and it should hopefully compile without any errors!

package {   import away3d.cameras.Camera3D;   import away3d.containers.Scene3D;   import away3d.containers.View3D;   import away3d.core.base.Vertex;   import away3d.materials.WireColorMaterial;   import away3d.materials.WireframeMaterial;   import away3d.primitives.LineSegment;   import away3d.primitives.Sphere;     import flash.display.Sprite;   import flash.display.StageAlign;   import flash.display.StageScaleMode;   import flash.events.Event;     [SWF(backgroundColor="#000000")]     public class Example001 extends Sprite {     private var scene:Scene3D;     private var camera:Camera3D;     private var view:View3D;         public function Example001() {             // set up the stage       stage.align = StageAlign.TOP_LEFT;       stage.scaleMode = StageScaleMode.NO_SCALE;             // Initialise Papervision3D       init3D();             // Create the 3D objects       createScene();             // Initialise Event loop       this.addEventListener(Event.ENTER_FRAME, loop);        }     private function init3D():void {       // Create a new scene where all the 3D object will be rendered       scene = new Scene3D();             // Create a new camera, passing some initialisation parameters       camera = new Camera3D({zoom:20, focus:30, x:-100, y:-100, z:-500});             // Create a new view that encapsulates the scene and the camera       view = new View3D({scene:scene, camera:camera});       // center the viewport to the middle of the stage       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;       addChild(view);     }     private function createScene():void {       // First object : a sphere             // Create a new material for the sphere : simple white wireframe       var sphereMaterial:WireColorMaterial = new WireColorMaterial(0x000000, {wirecolor:0xFFFFFF});       // Create a new sphere object using wireframe material, radius 50 with       // 10 horizontal and vertical segments       var sphere:Sphere = new Sphere({material:sphereMaterial, radius:50, segmentsW:10, segmentsH:10});       // Position the sphere (default = [0, 0, 0])       sphere.x = -100;       scene.addChild(sphere);         // Second object : x-, y- and z-axis         // Create a origin vertex       var origin:Vertex = new Vertex(0, 0, 0);       // Create the red-coloured x-axis with a width of 2       var xAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0xFF0000, {width:2})});       xAxis.start = origin;       xAxis.end = new Vertex(100, 0, 0);       scene.addChild(xAxis);           // Create the green-coloured y-axis with a width of 2       var yAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0x00FF00, {width:2})});       yAxis.start = origin;       yAxis.end = new Vertex(0, 100, 0);       scene.addChild(yAxis);           // Create the blue-coloured z-axis with a width of 2       var zAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0x0000FF, {width:2})});       zAxis.start = origin;       zAxis.end = new Vertex(0, 0, 100);       scene.addChild(zAxis);       }         private function loop(event:Event):void {       // Render the 3D scene       view.render();     }   } }

To see the final result, right-click again on the Tartiflop project and select Run As and Flex Application. What you should see is the following: click on the image below to see the real flash movie (its not much more interesting than the image though!).

Let’s go into more detail with the code. I’m taking a look at this with the point of view of someone who has been using Papervision3D and its interesting to look at the similarities and differences between the two libraries. If you compare the code to the equivalent in Papervision3D, you can see that the codes resemble a lot.

The constructor of Example001 is identical to that of the equivalent example in Paperivision3D: the stage parameters are set so that the scene is scaled correctly, the 3D elements are initialised, the scene is created and then we add a frame-enter event listener.

Example001 inherits from the Sprite class as is indeed possible with Papervision3D. Papervision3D however provides a BasicView class where the scene, camera, view and renderer are all encapsulated (see part 2 of the Papervision3D series for example). Also the stage scaling is automatically encapsulated in the BasicView class.

    public function Example001() {             // set up the stage       stage.align = StageAlign.TOP_LEFT;       stage.scaleMode = StageScaleMode.NO_SCALE;             // Initialise Papervision3D       init3D();             // Create the 3D objects       createScene();             // Initialise Event loop       this.addEventListener(Event.ENTER_FRAME, loop);        }

However, as we can see, its not very complicated to initialise all the 3D elements individually - as we do in the init3D() function.

    private function init3D():void {       // Create a new scene where all the 3D object will be rendered       scene = new Scene3D();             // Create a new camera, passing some initialisation parameters       camera = new Camera3D({zoom:20, focus:30, x:-100, y:-100, z:-500});             // Create a new view that encapsulates the scene and the camera       view = new View3D({scene:scene, camera:camera});       // center the viewport to the middle of the stage       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;       addChild(view);     }

We first of all create a Scene3D object which is used later to contain all of our rendered 3D elements. Secondly we create a Camera3D which sets up all our viewing parameters and finally we create a View3D object which provides us with our window through which we observe the scene.

Interesting to note is the way we can create Away3D objects. Unlike Papervsion3D which has well defined constructors taking specific arguments, Away3D allows us to pass an array of initialisation parameters. One good point is that this makes the code more concise, however, personally, I feel that it is less intuitive: with Papervision3D I felt I could determine relatively quickly what was needed to construct an object but here you need to search more within a class to obtain useful information. Having said that I have to admit that I haven’t yet looked at the Away3D documentation! I’m someone who is too excited to get his hands dirty before reading the manual!

With respect to the camera, unlike Papervision3D it is not possible to modify the field of view (or fov) directly and instead we need to manipulate the zoom and focus of the camera (see my post on the relationship between all three and also this really good article explaining the Away3D camera). Having an OpenGL background I find the field of view more intuitive however this is just a personal opinion.

After the 3D base elements have been created we can move on to creating the scene. This, as is fairly obvious, is done in the createScene() function.

    private function createScene():void {       // First object : a sphere             // Create a new material for the sphere : simple white wireframe       var sphereMaterial:WireColorMaterial = new WireColorMaterial(0x000000, {wirecolor:0xFFFFFF});       // Create a new sphere object using wireframe material, radius 50 with       // 10 horizontal and vertical segments       var sphere:Sphere = new Sphere({material:sphereMaterial, radius:50, segmentsW:10, segmentsH:10});       // Position the sphere (default = [0, 0, 0])       sphere.x = -100;       scene.addChild(sphere);         // Second object : x-, y- and z-axis         // Create a origin vertex       var origin:Vertex = new Vertex(0, 0, 0);       // Create the red-coloured x-axis with a width of 2       var xAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0xFF0000, {width:2})});       xAxis.start = origin;       xAxis.end = new Vertex(100, 0, 0);       scene.addChild(xAxis);           // Create the green-coloured y-axis with a width of 2       var yAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0x00FF00, {width:2})});       yAxis.start = origin;       yAxis.end = new Vertex(0, 100, 0);       scene.addChild(yAxis);           // Create the blue-coloured z-axis with a width of 2       var zAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0x0000FF, {width:2})});       zAxis.start = origin;       zAxis.end = new Vertex(0, 0, 100);       scene.addChild(zAxis);       }

The scene is very simple: no lighting and just two stationary types of objects. As with Papervision3D, most objects provide only the vertices of a given shape: the rendering (what we see on the screen) is done through the material.

In this example we use two types of materials for two different types of shapes. This is different to Papervision3D where any material seems to be usable with any object. Here, the two shapes belong to two different families: an AbstractPrimitive and an AbstractWirePrimitive. Each one uses a material also belonging to a different family: an ITriangleMaterial and an ISegmentMaterial respectively. If we give the wrong type of material to a particular primitive then it is not rendered.

The two shapes used are a Sphere (an AbstractPrimitive) and a LineSegment (an AbstractWirePrimitive). We therefore give them two different types of materials. In this example I’ve used a WireColorMaterial and a WireframeMaterial respectively. The WireColorMaterial is created with a face color (black in this case) and a wire color is passed in the list of initialisation arguments (being white). The wireframe material is simply white but I’ve passed a width of 2 in the initialisation parameters.

The sphere is created first, taking a list of initialisation parameters including the sphere material. It should be noted that these parameters can be set afterwards, not necessarily in the constructor. I then create 3 lines for each axis, each one with a different color wireframe material. The lines are then given two vertices to define their start and end positions. Each 3D object is added to the scene so that they are rendered.

As a first impression of Away3D, I actually find that the construction of these primitive objects is more concise than for Papervision3D. Looking through the source directory of Away3D I also get the impression that there is more choice of primitives compared to Papervision3D.

Finally for this example, a small function is used to render the scene. We added in the constructor a frame-enter event listener called loop.

    private function loop(event:Event):void {       // Render the 3D scene       view.render();     }

Very simply, we call the function render of view to redraw the scene. This is another difference to Papervision3D: Papervision3D has a specific Renderer class used to draw the scene.

And that’s it! A very simple example of rendering a 3D scene in Away3D. Compared to Papervision3D, for something this simple, there really isn’t a huge difference. Overall I feel that Away3D is more concise but maybe loses degree of simplicity using the parameters array rather than having explicit constructor arguments… but that’s just a personal point of view though.

One surprise is the difference in file sizes between Papervision3D and Away3D. In Away3D the flash animation come to 136KB whereas in Papervision3D its at only 82KB. Okay, so neither are huge and maybe Away3D is a bigger library… but I’m interested to see how this compares for more complex examples.

Anyway, that’s it for this example. For me too its a first step - I just wanted to see what the Away3D library was like and how easy it was to convert from a Papervision3D source to an Away3D one. I hope to continue along the same theme to produce more complex examples over the coming weeks. As always, comments and suggestions as are always welcome so please don’t hesitate!

Next article:

Tuesday, November 11th, 2008

Downloading and compiling Away3D sources with SVN in Eclipse

Away3D can be installed either from the latest releases on the Away3D downloads page or from the SVN repository located on the googlecode site.

I’ve chosen the second method so that I can easily and regularly update the source to be up to date with the latest fixes and enhancements. I’m using the same technique that I showed downloading and compiling Papervision3D using SVN in eclipse. Since I use eclipse as my development environment (with the Flex Builder 3 plugin), I like to keep all my sources together in the same environment and the SVN plugin for eclipse works very well.

In eclipse select Import… from the File menu. You’ll see the following window appear.

Under the SVN item, select Projects from SVN and click Next. You’ll then be requested to enter details for the SVN repository.

For the URL enter http://away3d.googlecode.com/svn. Leave the user details empty - we’ll use anonymous access to obtain the source. Click Next to continue. Eclipse will examine the SVN repository and show the repository structure.

We’ll download everything from the trunk (which includes the source, docs and examples), so select trunk and click on Finish. You’ll then be asked how you want to check out the source.

We want to create a Flex Library project so select Check out as a project configured using the New Project Wizard.

Under Flex Builder, choose Flex Library Project and click Next.

Enter Away3D as the Project name (or any other name you’d like…) then select Next to configure the source directory.

Click next to src under Classes to include in the library. The Main source folder should show src, and the Output folder should show bin. Sometimes selecting the source folder here doesn’t always work and we’ll have to explicitly give the source folder again after the project has been created, as shown below.

You should now see in the Flex Navigator in eclipse a new project called Away3D with the latest revision number next to it. If you have the error nothing was specified to be included in the library shown in the Problems view, then you need to re-specify the source directory as I mentioned above. Simply right-click on the Away3D project and select Properties.

Under Flex Library Build Path, once again click next to src in the Classes to include in library box. After clicking OK you should see that eclipse is compiling the sources.

The final result is the Away3D.swc Flex library, located in the bin directory, that can be used with other Away3D projects that you create afterwards. Similarly, with eclipse, you can compile Away3D projects by linking directly to this project. Personally I prefer the second method simply because it makes developing and debugging easier as you can directly look at the source for a particular Away3D class.

Hope this is of some use. I’ll be taking a look, as I did with Papervision3D, at producing a few simple examples just to get a feel of the library… more soon I hope!

Tuesday, November 11th, 2008

Musical Interlude - Foals


Discover Foals!