






















Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!























I remember when I was but a small lad and my parents took me to the movies to see the latest attempt at 3D film. It was absolutely awful in retrospect, but to my adolescent mind it was an extraordinary experience. I walked out of that cinema in awe and said to my parents, entirely in earnest, “I wish the real world was 3D, too!”
My point (other than to suggest I was a slow-minded youth) is that 3D work can easily inspire wonder and amazement, but if its only purpose is to attempt to inspire this wonder and amazement, chances are you’ll end up with something like Jaws 3D. Like any effect or technique used in site design and animation, 3D should be included to support the content, not simply for eye candy. Keep this fact in mind as you work through these next two chapters, and think about how you might use Flash 3D elements to support and enhance your own designs.
Before we get into utilizing the drawing API to create 3D shapes through code, let’s quickly take an important look at the alternative methods of incorporating 3D content in your Flash work.
This is the easiest method of the lot, if you have the resources. A program like Electric Rain’s Swift 3D is dedicated to producing vector images for your Flash movies. Electric Rain also produces plug-ins to export Flash movies from Discreet’s 3ds max, NewTek’s LightWave, and Softimage. Electric Image’s Amorphium Pro also produces Flash output that can be brought directly into your movies. Using these programs and others, you can quickly render stills or multiple frames of animation, and then use ActionScript to manipulate the images inside Flash. Drawbacks of these programs include the cost, of course, but also the file size of the exported
Flash MX Studio
movies can be very large at times. Still, these programs enable you to produce images that are simply not possible within the limitations Flash, as we’ll discuss shortly.
Believe me, artists were producing 3D imagery long before the invention of the microprocessor. If all you are looking to produce is a static 3D image, then there’s no reason why you couldn’t make this yourself without the aid of any expensive 3D software. With an image-editing program like Adobe Photoshop you can create faux-3D images that are startlingly real (check out Bert Monroy’s web site at www.bertmonroy.com to see some fantastic evidence of this). Even within Flash, you can still produce some terrific 3D effects and images using only the drawing tools and knowledge of perspective and lighting.
And here’s the reason you’re reading this chapter in the first place. With a little math (um, or a lot of math), you can create 3D objects at run-time just using code. The drawing API is a big help here since the creation and filling of polygons at run-time is now possible. Though you could work around this in Flash 5 by skewing triangles, it was an imperfect solution as gaps often appeared in objects and the skewing calculations bogged down the processor.
The processing load is still a concern with 3D in Macromedia Flash MX, but there are ways to ease the strain to a certain extent. One way is to avoid attempting to create complete, animated, 3D environments using ActionScript alone. You’re not going to make Halo , sorry. If you wish to explore fully interactive 3D worlds then look into Flash’s big brother, Macromedia Director. Despite debates in the online Flash forums over the relevancy of Director and the equality between the two programs, Director is simply more powerful and the 3D capabilities of its latest version can perform astonishing things that are impossible in Flash.
But wait! Before you head off grumbling that you bought the wrong program (we both know that’s not true), the benefits of Flash 3D can outweigh those of Shockwave 3D (produced in Director). For one, the Flash Player is simply more ubiquitous than the Shockwave Player. This means that more people will be able to view your Flash 3D content immediately, while they would have to download the relatively larger player to view your Shockwave 3D content. Also, because of the complexity of some of the Shockwave 3D environments, the file sizes are much larger, and sometimes too great for users on slower connections. Until broadband connections are the norm, Flash has the upper hand.
3D concepts reviewed
It’s important to review the basic concepts of 3D before we start on the code that will produce our Flash 3D. Now, don’t start flipping back through the pages to find where these 3D concepts were discussed initially; they weren’t. But, if we’re to get to the practical applications of coded, run-time 3D, we have to get started quickly. Because of this, and because friends of ED have
Flash MX Studio
center, and depth simulation is achieved. The formula we will use to find out how we move a vertex from world center is:
scale = focalLength/(focalLength-z); _x = xscale; _y = yscale;
focalLength represents the distance between the viewer and the screen. Imagine in the above scenario that we set the focalLength to 100. For vertex 2, the scale variable will evaluate to approximately 1.33, which will set its Flash _x and _y properties to -66.5 and 133, respectively. This is the screen distance of the vertex from world center measured in pixels. Vertex 1, with its scale variable evaluating to 2, will have its Flash _x and _y properties set to –100 and 200, respectively. This sets the vertex’s screen coordinates (again, separate from its 3D coordinates) further away from world center. By adjusting focalLength, we can increase or decrease this perspective distortion.
We’ll discuss these further when we get into lighting, but you should at least be aware that a vector is a quantity in our 3D world consisting of a direction and a magnitude. Imagine a theater spotlight shining down from the ceiling on to a soloist on stage. This is a vector as it has a direction that it’s pointing in and also has a specific length to its beam.
Remember these from the last chapter? Yes, they’re back, and this time it’s personal (sorry, Jaws 3D is still on my mind). Matrices, as you’ll recall, are rectangular arrays of numbers. We’ll use matrices to help us in transforming our 3D world in much the same way they helped us transform our gradients in the last chapter.
Those are the basic ideas and terms you need to have a firm grasp on, but hey, enough of my yakking! Let’s move on and apply these ideas in Flash.
Coding the cube
In this exercise we’re going to create the ultimate Flash 3D exercise to demonstrate the concepts we’ve looked at so far and to give us a base to build on: it’s the well- worn but underrated spinning cube.
3D with the drawing API
1. Create a new movie and save it as spinning_cube_0.fla. Create a new movie clip symbol with a central registration point called vertex and make it a small circle (mine’s 12.5 in diameter). In the Linkage Properties , check Export for ActionScript and give it the identifier name vertex.
So now we have the vertex symbol in the Library. Eventually, the vertices will only be objects in memory and no longer actual movie clip symbols, but for this exercise we’ll utilize them as symbols. Now on to the code.
2. Go back into the main timeline and rename the default layer actions. In frame 1 type the following code:
this.createEmptyMovieClip(“center”, 0); center._x = Stage.width/2; center._y = Stage.height/2; focalLength = 400;
We’ve initially created a new movie clip that will hold our 3D world and place it at stage center. We’ve set our focalLength variable (to be used for our depth simulation) to 400.
3. We next create our cube model by defining the vertices. Add this beneath the previous code:
cube = {}; cube.vertexList = []; cube.vertexList.push({x:-50, y:-50, z:50}); cube.vertexList.push({x:50, y:-50, z:50}); cube.vertexList.push({x:50, y:-50, z:-50}); cube.vertexList.push({x:-50, y:-50, z:-50}); cube.vertexList.push({x:-50, y:50, z:50}); cube.vertexList.push({x:50, y:50, z:50}); cube.vertexList.push({x:50, y:50, z:-50}); cube.vertexList.push({x:-50, y:50, z:-50}); vertices = []; for (i=0; i<cube.vertexList.length; i++) { center.attachMovie(“vertex”, “v”+i, i); vertices.push(center[“v”+i]); }
cube is a new object that we give a single property to: vertexList. This will be an array to hold each individual vertex. Over the following eight lines, we push the vertices into the array. Note that each vertex is an individual object made up of three properties: x, y, and
Setting the vertices
3D with the drawing API
Not too impressive yet: the cube isn’t spinning so it’s difficult to view the vertices’ location. We’ll change this, at least briefly, with the following function:
5. Type this directly after the render function:
rotateY = function (model, degree) { var sin = Math.sin(degreeMath.PI/180); var cos = Math.cos(degreeMath.PI/180); for (var i = 0; i<model.vertexList.length; i++) { var x = cosmodel.vertexList[i].x-sinmodel.vertexList[i].z; var z = cosmodel.vertexList[i].z+sinmodel.vertexList[i].x; model.vertexList[i].z = z; model.vertexList[i].x = x; } };
This will rotate the vertices of our model about the world’s y-axis. We first find the sin and cos of the angle sent (in degrees, so we must convert the number to radians) and then we go through each vertex in our model and move the vertex based on the angle. The formulas for rotation about the axes are established formulas, and to save pages I’ll work with the assumption that you accept that they are true.
6. Finally, replace the last line render(cube); with the following code:
center.onEnterFrame = function() { rotateY(cube, 3); render(cube); };
This final code rotates our cube by 3 degrees about the y-axis and then re-renders it to the screen. Test your movie to view the rotating cube. (If you get some unexpected results here you can check your file against our spinning_cube_0.fla on the CD).
The first thing we need to do to more accurately simulate a 3D cube is to join up the vertices of the model with meshlines to create a wireframe. This could be accomplished in Flash 5, but is now far easier in Flash MX as we can use the drawing API.
1. Save your existing movie as spinning_cube_1.fla. What we’ll do now is add some code to our render function in order to draw some lines between our vertices. To do this, we’ll need to know which vertices need to be attached to each other. We’ll accomplish this by assigning sides to our model made up of selected vertices. Add this code right after the
Adding meshlines
Flash MX Studio
previous lines that defined the vertices of cube (beneath the last line which began cube.vertexList.push):
cube.side = []; cube.side.push([0, 1, 2, 3]); cube.side.push([2, 1, 5, 6]); cube.side.push([1, 0, 4, 5]); cube.side.push([5, 4, 7, 6]); cube.side.push([0, 3, 7, 4]); cube.side.push([3, 2, 6, 7]);
side is another array property of our model. Each index consists of four vertices that make up a cube side (try sketching it out from the vertex coordinates to see how these relate). The order that the vertices are placed in each side index is very important as you’ll see when we come to backface culling , which is the process of making invisible any side that isn’t facing the viewer (thus saving us from excess processing). We will discuss why in a few pages time. For the time being, just make sure you keep the same order of vertices for each side (the order of sides, however, is of no importance).
2. We now need to edit our render function to actually draw the lines between the vertices. With the sides already defined, this is a fairly straightforward process. The added code is in bold:
render = function (model) { center.clear(); center.lineStyle(2, 0, 100); for (var i = 0; i<model.vertexList.length; i++) { var scale = focalLength/(focalLength-model.vertexList[i].z); vertices[i]._x = model.vertexList[i].xscale; vertices[i]._y = model.vertexList[i].yscale; } for (var i = 0; i<model.side.length; i++) { center.moveTo(vertices[model.side[i][0]]._x, ➥ vertices[model.side[i][0]]._y); for (var j = 1; j<model.side[i].length; j++) { center.lineTo(vertices[model.side[i][j]]._x, ➥ vertices[model.side[i][j]]._y); } center.lineTo(vertices[model.side[i][0]]._x, ➥ vertices[model.side[i][0]]._y); } };
Flash MX Studio
for (var i = 0; i<model.side.length; i++) { center.moveTo( verts2D [model.side[i][0]] .x , ➥ verts2D [model.side[i][0]] .y ); for (var j = 1; j<model.side[i].length; j++) { center.lineTo( verts2D [model.side[i][j]] .x , ➥ verts2D [model.side[i][j]] .y ); } center.lineTo( verts2D [model.side[i][0]] .x , ➥ verts2D [model.side[i][0]] .y ); } };
There isn’t too much difference. We create a new array called verts2D that stores objects made up of our adjusted screen coordinates. When we loop through our sides and vertices, we look into verts2D for these values. With only a few extra lines (really, we deleted more than we added), we’ve made our 3D spinning cube exist solely using ActionScript:
5. With the movie clip vertices removed, we have a 3D wireframe model spinning about its y- axis completely created using the drawing API. 6. Save your movie and leave it open, as we’ll be modifying it again once we’ve looked at some more theory.
I’d like to discuss another concept here and it concerns how we’re handling our transformations. As it is, for each rotation about an axis (even though we only presently have rotation about the y-axis, you can probably surmise the code for the other two axes) we are looping through each vertex and adjusting its coordinates accordingly. Wouldn’t it be nice to only have to do this once, after we have calculated all the necessary transformations? Well, we can, and the way to do it is by using matrices.
3D with the drawing API
Although you might not have thought it at the time, each vertex can be described as a matrix too, without requiring us to adjust any code. A vertex with the coordinates (50,30,15) can be written just as easily as:
You don’t have to change a thing in your code (it’s not as if you can format it this way in the ActionScript panel!), just as long as you understand what this matrix means. Um, so what does it mean? Well, you saw how easily we could perform transformations on our gradients using our transforms stored in matrices? Well, we can do the same thing for our 3D transforms.
In our last exercise, for example, in the rotateY function the transformation is handled by:
x = cos(?)x - sin(?)z; //y = y; z = cos(?)z + sin(?)x;
The commented out line was not in our previous code, but I’ve put it there as a placeholder so you can see where we’re going with this.
Now what if I told you that this transform formula could be stored in a transform matrix that we could multiply with our 3D coordinates? What if I told you that these transform matrices could actually be multiplied together, creating a cumulative transform matrix that we would only have to multiply with our coordinates once at the end of our transformations? What if I told you that doing so could save us some processing and aid us in future transformations? What if I keep asking rhetorical questions and never get to show you how this is done? Nah, that’ll never happen. The transform matrix for the above code looks like this:
3D with the drawing API
Scaling of the object:
Let’s incorporate some of these into our code so that we might easily perform these transformations.
1. Still using your movie from the last exercise, save it as spinning_cube_2.fla. Then enter this code immediately after our render function:
rotateX = function (model, degree) { var rad = degreeMath.PI/180; var sin = Math.sin(rad); var cos = Math.cos(rad); var matrix = {a:1, b:0, c:0, d:0, e:cos, f:sin, g:0, h:-sin, ➥i:cos}; transform(matrix, model); }; rotateY = function (model, degree) { var rad = degreeMath.PI/180; var sin = Math.sin(rad); var cos = Math.cos(rad); var matrix = {a:cos, b:0, c:-sin, d:0, e:1, f:0, g:sin, h:0, ➥i:cos}; transform(matrix, model); }; rotateZ = function (model, degree) { var rad = degree*Math.PI/180; var sin = Math.sin(rad); var cos = Math.cos(rad); var matrix = {a:cos, b:sin, c:0, d:-sin, e:cos, f:0, g:0, h:0, ➥i:1}; transform(matrix, model);
Transforming with matrices
continues overleaf
Flash MX Studio
scale = function (model, percent) { var rad = degree*Math.PI/180; var matrix = {a:percent, b:0, c:0, d:0, e:percent, f:0, g:0, h:0, ➥i:percent}; transform(matrix, model); };
You could easily set these matrices up as linear arrays, but I’ve chosen to make them objects similar to our gradient transformation matrices from the last chapter so that you can see the relation. After we’ve made our matrix, we call our transform function to add this matrix to our full transform. Let’s write this function next.
2. Under the matrix definitions we added in the last step, add the following code:
transform = function (matrix, model) { if (transformMatrix) { var a = matrix.atransformMatrix.a+matrix.btransformMatrix.d ➥+matrix.ctransformMatrix.g; var b = matrix.atransformMatrix.b+matrix.btransformMatrix.e ➥+matrix.ctransformMatrix.h; var c = matrix.atransformMatrix.c+matrix.btransformMatrix.f ➥+matrix.ctransformMatrix.i; var d = matrix.dtransformMatrix.a+matrix.etransformMatrix.d ➥+matrix.ftransformMatrix.g; var e = matrix.dtransformMatrix.b+matrix.etransformMatrix.e ➥+matrix.ftransformMatrix.h; var f = matrix.dtransformMatrix.c+matrix.etransformMatrix.f ➥+matrix.ftransformMatrix.i; var g = matrix.gtransformMatrix.a+matrix.htransformMatrix.d ➥+matrix.itransformMatrix.g; var h = matrix.gtransformMatrix.b+matrix.htransformMatrix.e ➥+matrix.itransformMatrix.h; var i = matrix.gtransformMatrix.c+matrix.htransformMatrix.f ➥+matrix.i*transformMatrix.i; transformMatrix = {a:a, b:b, c:c, d:d, e:e, f:f, g:g, ➥h:h,i:i}; } else { transformMatrix = matrix; } };
Though this might look a bit daunting, this is simply the formula for multiplying a 3x3 matrix by another 3x3 matrix. What we’re doing in this function is first checking to see if a transform matrix already exists. If it does, we multiply the two matrices together, thus
Flash MX Studio
Finally, before we render the model to the screen, we need to apply our transformations (which are conveniently stored in a single matrix) to our vertices. The extra code is the basic formula for multiplying a 3x3 matrix (our transform) with a 3x1 matrix (each vertex’s coordinates). We then delete our transform to ready ourselves for further transformations.
4. To call our new rotation functions, alter the onEnterFrame function at the end of our code to read:
center.onEnterFrame = function() { rotateX(cube, 3); rotateY(cube, 6); rotateZ(cube, 10); render(cube); };
Notice that although we perform three separate transformations, they will not be applied to the model until the render function is called, once each frame. Go ahead and test the movie to see the results.
Using 3x3 transformation matrices, the rotation of our wireframe model about all three of its axes is made more efficient.
If you get any unexpected results then you can check your code against mine in spinning_cube_2.fla on the CD.
Now we’re getting somewhere! Even though all we have is the same old spinning wireframe cube, we’re building something that will provide a solid foundation for us to improve on.
Depth sorting
One improvement that will be necessary once we begin filling the models with color is a depth sorting or z-sorting method. This is a method of placing models or the sides of the cube that are nearer to the viewer in front of objects and sides that are further away. Basically, you don’t
3D with the drawing API
want an object with a z=–200 coordinate to be in front of an object that has a z=50 coordinate. In Flash 5, you needed to swap the depths of your vertex movie clips in order to accomplish this. Now in MX, we can simply create an order to draw in, starting with the sides that are furthest away and working towards the viewer, effectively drawing over the sides that should be behind. This will all be accomplished in our render function, as we’ll see in the following exercise.
1. Save your movie as spinning_cube_3.fla. Update your render function with the following new code:
render = function (model) { if (transformMatrix) { for (var i = 0; i<model.vertexList.length; i++) { var vert = model.vertexList[i]; var x = transformMatrix.avert.x+transformMatrix.bvert.y ➥+transformMatrix.cvert.z; var y = transformMatrix.dvert.x+transformMatrix.evert.y ➥+transformMatrix.fvert.z; var z = transformMatrix.gvert.x+transformMatrix.hvert.y ➥+transformMatrix.i*vert.z; vert.x = x; vert.y = y; vert.z = z; } delete transformMatrix; } center.clear(); center.lineStyle(2, 0, 100); verts2D = []; depthArray = []; for (var i = 0; i<model.side.length; i++) { var zDepth = 0; for (var j = 0; j<model.side[i].length; j++) { var whichVert = model.side[i][j]; if (verts2D[whichVert] == undefined) { verts2D[whichVert] = {}; var scale = focalLength/(focalLength ➥ -model.vertexList[whichVert].z); verts2D[whichVert].x = model.vertexList[whichVert].x ➥ *scale; verts2D[whichVert].y = model.vertexList[whichVert].y ➥ *scale;
Filling the sides
continues overleaf
3D with the drawing API
other hand, will hold that full array of vertex numbers. Remember that each index of depthArray holds a reference to one of the model’s sides and its zDepth. By looking at the first index position in a particular index of depthArray, we can find that side’s list of vertices, which we then place in sideVerts.
2. Test your movie. We now have filled sides! Thanks, drawing API!
spinning_cube_3.swf demonstrates a cube model with solid-filled polygons and visible edges, all created with the drawing API. Depth sorting of each polygon allows for nearer polygon sides to appear in front of further sides. The cube is spun about all three of its axes each frame using 3x3 transformation matrices.
3. Save your movie and leave it open for the next exercise.
Backface culling
Backface culling, as stated earlier, is simply preventing the rendering of polygons that are turned away from the viewer, saving the computer excess processing work (in fact, it’s the polygon’s normal directed away from the viewer, but unfortunately there’s not much time to get into this here). This is desirable most of the time, though you can certainly make this option a toggled state for your models if you so choose. The way to determine if a polygon is facing the viewer or turned away is by examining the screen coordinates of its vertices, not the 3D coordinates, since it’s the model’s relation to the screen and the viewer that is the important determining factor on whether the polygons can be seen or not. We also need to note if the vertices are in a clockwise or counter-clockwise order. With our method, it is imperative that the vertices are defined for the side in a counter-clockwise order in relation to the object center, in order for them to be seen at the correct angles.
This all sounds a bit confusing, doesn’t it? Well, once you get the hang of it, it’s pretty easy. Trust me. In fact, explaining it is the most difficult part. The process I use to help me determine the correct order of vertices is to imagine the polygon (or side) to be directly facing me on the near side of center before I determine the vertex order. For our cube model, this would mean mentally spinning the cube until each side faced me so that I might see the order for the vertices better.
Flash MX Studio
If I then place the vertices into the side array in a counter-clockwise order at the current view, the side will be fully visible to the viewer while on the near side of center. To visualize this better, we'll look at our cube model with three of its sides defined so that the outside of the cube may be seen:
Now although it might appear that we simply have to define all sides in a counter-clockwise order in relation to our view, take a look at the order for our remaining three sides:
Ah-hah! Clockwise! This is because in this view we don’t want these sides to be rendered, since they are inside the box. It’s for this reason that I use the procedure described above, that of mentally spinning the model so that each side faces me before I record the vertex order. If I spin side[5] around to face me on the near side of center, then the order of its vertices would indeed be counter-clockwise.
OK, now that we know that whenever a side’s vertices are in a clockwise order on the screen it should not be rendered, we need a way to determine the order in which the vertices’ 2D coordinates are currently seen. (Full credit must go to Pavils Jurjans at www.jurjans.lv/flash for his open source code and this fun section).