3D Color Code Calculator in Away3DLite

May 28, 2010

Color Code Calculator

I did this example to demonstrate how to interactively change the materials of a Collada file in Away3DLite. I build the model in Cinema4D and assigned bands and added colors to those bands. I looked up their names in the out putted Collada file and then assigned materials as requested form the Flash Builder ComboBox using change event methods.

Demo

Color Code Calculator

Color Code Calculator

Video

http://www.youtube.com/watch?v=Wgm14JHXyf8

Source

http://code.google.com/p/lv3d/downloads/detail?name=colorCode.zip

Code Discussion

Here’s example code for the first ComboBox

private function changeEvt1(e:Event):void

{

myOne = e.currentTarget.selectedIndex;

modelResistor.materialLibrary.getMaterial(“ID18″).material = myMatArray[myOne];

calcMyOhms();

}

Code for Calculator Ohms as discussed on the video.

private function calcMyOhms():void {

myOhms = (myOne*10 + myTwo)*Math.pow(10, multiplier[myThree]);

if (myOhms >= 1000000) {

myOhms /= 1000000;

myOutput.text = “Resistance = “ + String(myOhms) + ” MOhms, “ + tolerance[myFour];

} else {

if (myOhms >= 1000) {

myOhms /= 1000;

myOutput.text = “Resistance = “ + String(myOhms) + ” KOhms, “ + tolerance[myFour];

} else {

myOutput.text = “Resistance = “ + String(myOhms) + ” Ohms, “ + tolerance[myFour];

}}}

A similar 2D example was done on the web by Danny Goodman at

http://www.dannyg.com/examples/res2/resistor.htm

Enjoy!

private function changeEvt1(e:Event):void {

myOne = e.currentTarget.selectedIndex;

modelResistor.materialLibrary.getMaterial(“ID18″).material = myMatArray[myOne];

calcMyOhms();

}

private function changeEvt2(e:Event):void {

myTwo = e.currentTarget.selectedIndex;

modelResistor.materialLibrary.getMaterial(“ID8″).material = myMatArray[myTwo];

calcMyOhms();

}

private function changeEvt3(e:Event):void {

myThree = e.currentTarget.selectedIndex;

modelResistor.materialLibrary.getMaterial(“ID23″).material = myMatArray[myThree];

calcMyOhms();

}

private function changeEvt4(e:Event):void {

myFour = e.currentTarget.selectedIndex;

modelResistor.materialLibrary.getMaterial(“ID13″).material = myPerArray[myFour];

calcMyOhms();

}


Humvee in Away3DLite (and PV3D) wheels and steering

May 18, 2010

Intro

In chapter 5 of my book, I discuss how to make a car’s wheels move forwards and backwards and steer. It is actually pretty easy to do in PV3D. But in Away3DLite it is not so obvious. So in the video below I discuss the difference and show you how to get wheel movement and steering working for both PV3D and Awa3DLite.

Video

Driving a Humvee in Away3dLite

Try It Out

Driving a Humvee

Driving a Humvee in Away3DLite

Code

To see the code click the link below:

Read the rest of this entry »


Hacking Papervision3D (vidoes 1 – 7)

April 15, 2010

Intro: Hacking Papervision3D

In this seven part video series you learn to hack PV3D using the powerful error checking in Flash Builder. You’ll learn to remove the Number3D and Number2D classes form PV3D and use the native classes in the Flash Player.

Hacking Videos Removing Number3D

Chapter 2: Hacking Papervision3D Part 1

Chapter 2: Hacking Papervision3D Part 2

Chapter 2: Hacking Papervision3D Part 3

Chapter 2: Hacking Papervision3D Part 4

Chapter 2: Hacking Papervision3D Part 5

Chapter 2: Hacking Papervision3D Part 6

Hacking Videos Remove Number3D

Chapter 2: Hacking Papervision3D Part 7

In the class notes, you’ll find many of the Number3D math methods that are explained in the video. Understanding how these functions work will be essential for the rest of the book.

Click the link below to read the class notes:

Read the rest of this entry »


Flash CS4 Planetarium in 49 Lines

April 22, 2009

Intro

In Chapter 7 of the book I change the  Planetarium example (shown in a previous post) so that it only uses XML (threw out Cairngorm). And in the process I thought, hey this should be easy to do in CS4. And it was! Check it out below…a planetarium (with real star data) in 49 lines of code…including comments.

Flash CS4 Planetarium in 49 Lines

Flash CS4 Planetarium in 49 Lines

Demo

Source

Disucssion

There are two main steps in getting this to go:

Step 1: Get a star object into your library so you can instantiate it onto the stage like you would your particles class – this step saves you tons of code: var myStar = new Star();

Star in the Library for Instantiation

Star in the Library for Instantiation

Step 2: Treat your stars like a particle system. This lets your stuff then into an updatable array so you can rotate them:

The rest of this stuff you’ve seen before, and I go through the discussion in the book and in the YouTube video above so I just show the code below: myParticles[j]

Sample Star Data (CSV)

AND, 2.065, 42.316, 0,
AND, 1.161, 35.616, 1,
AND, 0.655, 30.85, 1,
AND, 0.139, 29.083, 1,

CS4 Planetarium in 49 lines

import flash.events.*;
import flash.display.*;

//Create star parameters
var myStar:Star;
var skyRadius:Number = 240;
var myOsc:int=0;
var starHolder:MovieClip= new MovieClip();

//Create a star array to hold CSVdata and particle array
var starArray:Array=new Array();
var myParticles = new Array();

//XML Statements used to bring in XML data
var urlRequest:URLRequest = new URLRequest(“data/starData.xml”);
var xmlLoader:URLLoader = new URLLoader(urlRequest);
xmlLoader.addEventListener(“complete”, readXml);

//XML parser and CSV splitter
function readXml(event:Event):void{
var markersXML:XML = new XML(event.target.data);
starArray=markersXML.myStars.split(“,”);

//Set the initial star system in place and add to a Movie holder
for(var i:uint = 0; i < starArray.length/4; i++){

//Instantiate stars and place them in a particle array
var myStar = new Star();
myParticles.push(myStar);
starHolder.addChild(myStar);

//Position stars (x, y, z) on stage
myStar.x=skyRadius*(Math.cos(2*Math.PI*starArray[4*i+1]/24)*Math.sin((90-starArray[4*i+2])*Math.PI/180));
myStar.z=-skyRadius*(Math.sin(2*Math.PI*starArray[4*i+1]/24)*Math.sin((90-starArray[4*i+2])*Math.PI/180));
myStar.y=skyRadius*Math.cos((90-starArray[4*i+2])*Math.PI/180);

//Scale stars according to magnitude and give a rand rotation
myStar.scaleX=myStar.scaleY=(1/9)*(3-starArray[(4*i+3)]);
myStar.rotation=180*Math.random();
}

//Add stars to star holder and position the holder
addChild(starHolder);
starHolder.x=400;
starHolder.y=300;

//Create your animation loop using an Enter Frame Listener
this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
}

function onEnterFrame(event:Event):void{
//Increment oscillation parameter and iterate over stars
myOsc++;
for(var j:uint = 0; j < starArray.length/4; j++){

//Set new x, y, z for your stars as they rotate
myParticles[j].x=skyRadius*(Math.cos(2*Math.PI*starArray[4*j+1]/24+myOsc/180)*Math.sin((90-starArray[4*j+2])*Math.PI/180));
myParticles[j].z=-skyRadius*(Math.sin(2*Math.PI*starArray[4*j+1]/24+myOsc/180)*Math.sin((90-starArray[4*j+2])*Math.PI/180));
myParticles[j].y=skyRadius*Math.cos((90-starArray[4*j+2])*Math.PI/180);
}}


Putting 3D Google Maps on the Web (using Flash 10)

April 18, 2009

Intro

To this point, I’ve been putting Google Maps into Air applications due to the Flash Sandbox issue encountered in PV3D (discussed in a previous post). But in CS4, guess what, it’s not an issue. They go right on the web as you can see from the demo below:

Google Map in 3D on the Web

Google Map in 3D on the Web

Demo

Source

Discussion

Now here is how you do it, and it’s so simple you will not believe it. Use the code below to put your map into a movie where it’s free to move freely in 3D.

movie.addChild(map);

Placing a Google Map on a CS4 Plane is easier in Flex 4 (Gumbo) than it is in PV3D. All you do is throw your map into a movie clip using the code below, and then center it to get your map pivot right. The code snippet below sets your map in a movie clip, centers its pivot, sets map controls, places your movie in a Flex canvas, and centers your movie on the stage.

//Place your map in a movie so you can position its pivot
movie.addChild(map);

//Set your map pivot
map.x=-map.width/2;
map.y=-map.height/2;

//Add Map Controls
map.addControl(new ZoomControl());
map.addControl(new PositionControl());
map.addControl(new MapTypeControl());

//Put your movie in a Flex Canvas
mapHolder.rawChildren.addChild(movie);

//Center your Movie
movie.z=0;
movie.x=450;
movie.y=300;

The map also has two additional Flex components; a button, which stops it from spinning and a slider, which adjusts its speed and direction of rotation.

This is the great power of CS4 over PV3D. You can now bring native Flex components into your 3D environment in conjunction with your 3D objects. Bringing Flex components into PV3D is a difficult task and requires the use of the draw BitmapData feature. But with CS4 it occurs natively, and those components can be manipulated in 3D as well.

Hey that’s it, how crazy can that be! And all the controls and buttons are fully functional and in the right place.

Note: You could have just rotated the map directly, but you put it in a movie to control positioning and its pivot point.

The rest of the code is shown in the link below and discussed in greater detail in Chapter 7 of the book.

Read the rest of this entry »


Flash CS4 Exploding House of Cards (3D Particle Class)

April 15, 2009

Intro

Exploding an object is serious gaming fun. There’s just something about the human psyche that loves to see things blow up. In this post, we show you how to create a card house in Flash CS4 and then how to blow it up by treating the cards as particles.

Exploding House of Cards

Exploding House of Cards

Demo

Source: http://flex3cookbook3.googlecode.com/files/blowitUp3D.zip


YouTube Video 1: Building a House of Cards in CS4 (Part 1)

YouTube Video 2: Building a House of Cards in CS4 (Part 2)

YouTube Video 3: Making Your CS4 Card House Explode (Part 3)

Discussion

The first step in making things explode is to add a spin (x, y, z) property to your Particle3D class (developed in the book).

You can accomplish this in the following three steps:

Exploding an object is serious gaming fun. There’s just something about the human psyche that loves to see things blow up. The first step in making things explode is to add a spin (x, y, z) property to your Particle3D class. You can accomplish this in the following three steps:

Step 1: To keep things straight rename your Particle3D (developed in the book) class to ParticleBlowUp and add a spin (x, y, z) property

public var spinX:Number;
public var spinY:Number;
public var spinZ:Number;

Step 2: In the constructor function, set the spin (x, y, z) equal to zero.

spinX = 0;
spinY = 0;
spinZ = 0;

Step 3: And in your animation method “myLoop” update the rotation of the particle by iterating the spin (x, y, z) amount.

this.rotationX += spinX;
this.rotationY += spinY;
this.rotationZ += spinZ;

And that’s all you have to do to your Particle3D (now named ParticleBlowUp) class. See the book for more details…

You’re Only Half Way

But to get your particle system to explode you want to transfer a multi-part movie clip into your Particle class (using polymorphism). Then iterate over the elements of that movie clip, so you can spin those elements off into space in different directions, simulating an explosion.

To do this, make the following changes to your Particle3D class shown below:

1. Remove the “extends Sprite” statement from your ParticleBlowUp class; this allows you to bring in an object into your ParticleBlowUp class.

2. Create a public property “obj” and data type it as a Display Object:

public var obj:DisplayObject

3. Add “obj” to your constructor method, declare “obj” as an object in your constructor method.
4. Finally, change all the “this” keywords to object so that the transformations are applied to the object passed in through the constructor.

To see the rest of the discussion click the link below:

Read the rest of this entry »


Slicing Images in 3D and Adding Interactivity

April 5, 2009

Intro

One of the things I really hate about slicing up images … is slicing them. It’s just so time intensive in Photoshop, Illustrator, or Gimp and then I never get it right or the site specs change and I have to re-slice (and God forbid re-program). So I’ve developed a method for slicing them programmatically – no more hand made clothes, all made by machine! Let me show you how it works.

Click the image below to see the demo (click on the slices to rotate them, or you can drag them as well):

Split Image and Interactivity

Split Image and Interactivity

Demo

Note: You must use the Flash 10 player. I built this in Gumbo as an ActionScript project.

Source

YouTube Demo


Discussion

In this post we actually handle three important concepts

  1. Slicing an Image
  2. Polymorphism & Encapsulation
  3. Static Properties/Methods & Interactivity

These concepts are key OOP principles briefly discussed below, but are given much more detail in the book. And are essential in understanding PV3D.

Slicing an Image

Slicing an image is pretty easy using copyPixels. You just bring in your image and copy the portion of the image that is your split as shown below:

// loop through all pieces
for(var x:uint=0;x<6;x++) {
for (var y:uint=0;y<4;y++) {

// create new map piece bitmap
var newmapPieceBitmap:Bitmap = new Bitmap(new BitmapData(pieceWidth,pieceHeight));
newmapPieceBitmap.bitmapData.copyPixels(image.bitmapData,new Rectangle(x*pieceWidth,y*pieceHeight,pieceWidth,pieceHeight),new Point(0,0));

// create new sprite and add bitmap data to it
var newmapPiece:Sprite = new Sprite();
newmapPiece.addChild(newmapPieceBitmap);
mapPiece=new MapPiece(newmapPiece,x,y);
DragDropStatic.DragDrop(mapPiece);

// set location
mapPiece.x = x*(pieceWidth+5)+20;
mapPiece.y = y*(pieceHeight+5)+20;
mapPiece.addEventListener(MouseEvent.CLICK,clickmapPiece);

// add to stage
movie.addChild(mapPiece);

}
}

You’ve got to loop twice to get both column and row as you use copyPixels to grab your slice. If you check out Gary Rosenzweig’s book ActionScript 3.0 Game Programming University you’ll find that he uses a similar slicing technique. But in addition to Gary’s approach, we use Polymorphism & Encapsulation typically found in PV3D. Their use is briefly discussed below, but is treated in greater detail in the book.

Polymorphism & Encapsulation

The heart of PV3D is encapsulation and by using polymorphism we can create a MapPiece class that enables us to easily work with the map pieces. Polymorphism is used to grab the map pieces and treat them as instantiated objects as shown in the MapPiece class below:

package objects.primitives
{
import flash.display.Sprite;

public class MapPiece extends Sprite
{
private var mapPiece:Sprite;
private var locX:uint;
private var locY:uint;
private var myXPos:Number;
private var myYPos:Number;

public function MapPiece(mapPiece:Sprite,locX:uint,locY:uint)
{
this.mapPiece=mapPiece;
this.locX=locX;
this.locY=locY;
addChild(mapPiece);
}

Interactivity

Interactivity is accomplished in two ways: (1) by adding a listener, and (2) using Static Properties and Methods.

Listener

The instantiated map piece has a mouse click listener added to each map piece using the code below:

mapPiece.addEventListener(MouseEvent.CLICK,clickmapPiece);

Static Properties and Methods

By creating a static properties and methods class you can create reusable code. This is done for the drag and drop class shown below.

package utils
{
import flash.display.Sprite;
import flash.events.MouseEvent;

public class DragDropStatic
{
public function DragDropStatic()
{

}

public static function DragDrop(mySprite:Sprite):void
{
mySprite.addEventListener(MouseEvent.MOUSE_DOWN, dragMe);
mySprite.addEventListener(MouseEvent.MOUSE_UP, dropMe);
function dragMe(event:MouseEvent):void
{
mySprite.startDrag();
}
function dropMe(event:MouseEvent):void
{
mySprite.stopDrag();

}}}}

Once the class is created then it’s easily executed using

DragDropStatic.DragDrop(mapPiece);

All of this is handled in greater detail in Chapter 6 of the book.

Check out the source code by downloading it from the link above or clicking below.

Read the rest of this entry »


Animating Multiple Pixel Bender Lights

March 21, 2009

Intro
Having multiple lights in PV3D is a desired effect. But after going through the lightmap classes, let me say that it’s impossible without an major rewrite. But with Pixel Bender all you do is add another term to your pbk filter…let’s do it!

Animating Pixel Bender Lights

Animating Pixel Bender Lights

Demo

Source

Discussion

It’s an amazingly simple process. Just add another term to your pixel bender light equation as shown below:

Adding Multiple Images to PV3D

Adding Multiple Images to PV3D

The example above only shows two lights, but you can have as many lights as you want just by adding additional light terms:

The pixel bender code looks like this

float2 outcoord = outCoord();
float attn = (brightness1/((distance(outcoord, center1)+radius1)))+(brightness2/((distance(outcoord, center2)+radius2)));

dst = attn* sampleNearest(src, outcoord);
dst.a=1.0;

Wow, only five lines of code to have multiple light sources – get out of here!

Animating Your Sources

Once you’ve set your shader up then animating it is pretty easy. If you aren’t sure how to set up your shader for animation, check out Lee Brimlow’s video on animating shaders. I do it a little differently than Lee, but not by much. Here are the steps for animating the lights:

  1. Increment your oscillation parameter osc++
  2. Calculate sine and cosine based upon your incremented osc
  3. Update your light positions
  4. Apply the update to your image

The fully documented code is shown below:

private function loop(e:Event):void{

//Increment your oscillation parameter
osc++;
//Calculate sine and cosine
var cos:Number=150*Math.cos(osc/10);
var sin:Number=150*Math.sin(osc/10);
//Update your light positions
shader.data.center1.value = [sin+400, cos+180];
shader.data.center2.value = [cos+200, sin+180];
//Apply the update to your image
image.filters = [filter];
//Rotating your image holder
holder.rotationY+=.25;
}

If you are aware of how hard this is to do in PV3D, you’re going wow…tell me more…and we will…

For the entire source code download the source above, or check out the link below:

Read the rest of this entry »


Adding Pixel Bender to Papervision3D

March 20, 2009

Intro

One of the things which I abhor about modeling in Papervision3D is texture baking. And if you’ve been in the business as long as I have you know why…it’s a labor intensive nightmare…and you can’t ever get it right. But with pixel bender you don’t have to bake your textures anymore and you can adjust your parameters dynamically using ActionScript.

Dynamic Shading using Pixel Bender

Dynamic Shading using Pixel Bender

Demo

Source

YouTube http://www.youtube.com/watch?v=i8BnSqf0Z_g

Discussion

Adding Pixel Bender to Papervision3D was a three step process:

  • Creation of a Pixel Bender Filter
  • Creation of a Pixel Bender Bitmap File Material Class
  • Creation of a Pixel Bender Bitmap Material Class
Adding Pixel Bender to PV3D

Adding Pixel Bender to PV3D

Before you start coding. Make sure you’ve switched to the Flash 10 player!!!

Step 1: In the previous post several pixel builder filters were presented.

Pixel Bender Filters and Algorithms

To create a dynamic light baker filter the simple light filter was modified by throwing out all the pow and exponent methods. The big trick is that exponential behavior can be mimicked by using inverse of distance –now that’s a processor saver. The final algorithm use is shown below:

lively3d Light Source for Texture Baking

lively3d Light Source for Texture Baking

The pixel bender algorithm is easily implemented using the code below:

float2 outcoord = outCoord();
float attn = (brightness/((distance(outcoord, center)+radius)));

dst = attn* sampleNearest(src, outcoord);
dst.a=1.0

In addition to the modification mentioned above the alpha component is split off and set to one. This keeps the images from losing its alpha as you reduce brightness.

Step 2: Next you must create a Pixel Bender Bitmap File Material Class. This is simply done by making a copy of PV3D’s BitmapFileMaterial class and renaming it BitmapBendMaterial class and after changing the constructor and class names extend this class by the BitmapPixelMaterial class.

BitmapBendMaterial extends BitmapPixelMaterial

You’ll now create the BitmapPixelMaterial class.

Step 3: Make a copy of the PV3D BitmapMaterial class and name it BitmapPixelMaterial. Add the appropriate import statements and the pbj and image embed methods and create a shader as shown below:

[Embed (source="filters/livelyLight.pbj",
mimeType="application/octet-stream")]
private var ShaderClass:Class;

[Embed (source="assets/images/gainesHouse512.jpg")]
private var myImage:Class;

private var shader:Shader

Next incorporate the code to get your shader and image working together:

shader = new Shader(new ShaderClass());
shader.data.center.value = [400, 306];
shader.data.brightness.value = [150];
shader.data.radius.value = [100];

var image:Bitmap = new myImage();
image.filters = [new ShaderFilter(shader)];
shader.data.src.input = image.bitmapData

Finally you must change your fill method to a shader fill method with a matrix method

graphics.beginShaderFill(shader,_localMatrix)

That’s it! To check out the wrapper code download the source or click the more button below:

Read the rest of this entry »


Flex 4 (Gumbo) Fire Video on the Supper Club

March 13, 2009

Intro

Our group just finished the first part of the Beverly Hills Supper Club project. I realize that this is a sensitive area and lives were lost. The completed site will be a memorial to those loved ones that were lost in this tragic fire.

Here I demonstrated playing the Supper Club fire video on the Blender building skin. To see the demo just click the image below (drag the building with the mouse to rotate it and click the play video button to get the video to play):

Supper Club Video on a Blender Model

Supper Club Video on a Blender Model

Demo

Code (Only MXML File – Video too large for Google Code)

UTube

Discussion

It’s pretty easy. Just follow the posts below which explain everything in detail:

1. Learn about netStream and netConnection

Adding Video to a Papervision3D Curved Plan

2. Learn about using video in CS4

Putting Video on a CS4 (Flash 10) Primitive

3. Learn how to build a CS4 shaded model using drawTriangles

CS4 Flat Shaded Tie Fighter with drawTriangles

4. Learn about Light in Papervision3D

Adding Brightness to PV3D Light Source

5. Learn how to model in Blender

3D Modeling

6. Learn how to export your Blender models to Papervision3D and CS4

New Blender XML Exporter/PV3D XML Primitive

The big trick to this is to create a simple parameter that allows you to switch between the shaded model and video within the triangle creation loop.

playMyVideo = false or true;

Run Shade Code if false

….

Run Video Code if true

}else{

var vertices2:Vector.<Number>=new Vector.<Number>();
vertices2.push(dispVec[facesVec[curFace][0]].x, dispVec[facesVec[curFace][0]].y);
vertices2.push(dispVec[facesVec[curFace][1]].x, dispVec[facesVec[curFace][1]].y);
vertices2.push(dispVec[facesVec[curFace][2]].x, dispVec[facesVec[curFace][2]].y);

//Draw Video into Bitmap
bitmapData.draw( this.myVideo);
this.myVideo.attachNetStream ( this.myStream );

spObjImage.graphics.beginBitmapFill(bitmapData,null, false, false);
spObjImage.graphics.drawTriangles(vertices2);
spObjImage.graphics.drawTriangles(vertices2)

}

Another trick is handling rotations correctly. To do this you need to use subtraction of your previous position from you present position (since you are appending rotation in this example). So if you are rotating forward the difference is positive and if backwards the difference is negative.

private function boardMove(e:MouseEvent):void {

var locX:Number=prevX;
var locY:Number=prevY;
if(doRotate){
prevX=spBoard.mouseX;
prevY=spBoard.mouseY;
rotateObj(prevY-locY,-(prevX-locX),0);
e.updateAfterEvent();

}

Once you “get this in your head” you’ll undertstand “append” rotation in CS4 – otherwise it’s uncontrollably wild.

Now there’s on more “Super trick”. This application was originally created for an Adobe Air and was run on the desktop. So when you put it on the web the video will not work since it uses

spObjImage.graphics.drawTriangles(vertices2)

looks like a terrible sandbox issue, but wait a second didn’t we get video on a prim in the previous post on Putting Video on a CS4 (Flash 10) Primitive…

Yes we did???

But this time we don’t have indices and uv data … shouldn’t we just give up or get some expert to tell us what to do…nah, just replace indices and uv data with null and it works…please don’t ask me why. Remember, I said this was a trick.

spObjImage.graphics.drawTriangles(vertices2, null, null,TriangleCulling.NEGATIVE);

And Tada, video on the Supper Club.

Remarks

The full project will allow site visitors to leave messages in supper club rooms…building a flexpress flat-file data base to handle these messages is part of the TEI project… The advantage of the flat-file data base is that you can drop the program onto any server – hassle free and it works – no fancy install!

To see the entire code click the more button below:

Read the rest of this entry »


Follow

Get every new post delivered to your Inbox.