Adding Video to a Papervision3D Curved Plane

March 9, 2009


Note: This post lays the foundation for my next post which shows how to put video on a CS4 Primitive at

Putting Video on a CS4 Primitive

(here we do it for Papervision3D).

The real power of Papervision3D is its strong OOP (object oriented) structure. It lets you to do some very robust things, such as put video on any primitive. And in this post, you place a simple video on a curved Plane (developed in Chapter 3 of the book).

Video on a Curved Primitive

Video on a Curved Primitive




Here the basics on how it’s created.

At the heart of the program is the NetStream class that allows you to bring a video into Flash. This class will be discussed in greater detail in Chapter 11, which is on the Flash Media Server. The two important import classes are media and net classes, which contain Sound, Video, and net Connection methods. Armed with these you can instantiate your video net Connection and net Stream.

//net stream assets
private var myConnection : NetConnection;
private var myStream : NetStream;
private var myVideo : Video;

In addition to setting up Papervision3D and bringing in your curved video prim (which was covered in Chapter 3), you must load your video into your net Stream and then attach that net Stream to your instantiated video (myVideo) so you can play it on your curved prim.

private function loadMyVideo():void
//Set up Net Connection
myConnection = new NetConnection();
//Not on the media server
myStream = new NetStream(myConnection);
//Set buffer time
myStream.bufferTime = 2;
//Set up My Stream for client
myStream.client = new Object();
//Instantiate the video
myVideo = new Video(320, 240);“assets/eternity.flv”);
//Attach to local client side video

One of the important tricks, shown in the code above, it to set your net Connection “connect” to null.


This lets you stream from a local server (as opposed to a Flash Media Server). And as usual you run into the Flash security sandbox issue for streams coming from a server without a cross-domain policy. If you’ve been developing in Flash for a while you are familiar with this issue. And later in the book, you’ll learn how to use a little PHP to get around such problems.

After attaching your net Stream to your instantiated video object you can now place it on your curved prim.

videoMaterial = new VideoStreamMaterial(myVideo, myStream);
//videoMaterial.interactive = true;
videoMaterial.doubleSided = true;

//plane = new Plane(material applied to object, width, height, wSegments, hSegments);
planeCurve = new CurvedPlane(videoMaterial,32,24,8,8,10);

You’ll finally ready to use your Video Stream Material.

Place your video and stream in the Video Stream Material. Declare it double sided so when you spin your curved plane you see the video on the other side. Place that videoMaterial on your curved plane. And add that plane to your scene. Ta-da, video on a prim!

Papervision3D Pendulums – NKU Seminar #3

February 17, 2009

Papervision3D Pendulums NKU Seminar #3

This is the 3rd in a series of free public seminars held at NKU on Papervision3D and CS4. In this seminar, we take advantage of a number of open source references (given at the end of this post): MIT Open Courseware, Wikipedia, and Wolfram.

(Also in this seminar, Cocomo is tested.)

Please download Flash Player 10 to View all Examples


This seminar treats four pendulum types in Papervision3D: Simple , Double , Torsion, and Foucault. In addition, numerical techniques such as Runge-Kutta are discussed and source code demonstrated.

4 Pendulums

4 Pendulums

Source Files


Part 1: Simple & Double

Part 2: Torsion & Foucault


In each topic, we introduce an important coding concept. By the end of this seminar you should have a knowledge of basic pendulum types, open source resources, encapsulation, pinning, Runge-Kutta, sliders, and environment maps.

A. Simple Pendulum: Encapsulation

Encapsulation is what really separates men from mice when it come to programming in 3D Flash. Dehash on his Blog post a series of Papervision3D examples:

The example double plane demonstrates how to properly encapsulate elements in Papervision3D. I’ve extended his example to make the planes oscillated: Check it out here (and included in the source code).

Simple Pendulum

Simple Pendulum


Basically, the overall code is separated into two classes. The main class runs BasicView and is in charge of providing length, pinning, and animation information. The second class holds the elements to be animated.

Two Classes

Two Classes

It’s brilliant (wish I could take credit) and provides the foundations for all types of coolness to be published in future blog posts.

Once the secondary class is imported using

import objects.*;

then you can access all the public classes which let you manipulate the instantiated objects from the sub class, as described in my book.

Of course, the super huge advantage here is that my pendulum elements can be substantiated and pinned as often as needed and used by any number of programs.

B. Double Pendulum: Pinning

The example below demonstrates the importance of pinning. Pinning lets you attach one segment to another.

Double Pendulum

Double Pendulum


The two elements above were pinned together using:

myPendulum1.rotationZ = Osc;
myPendulum2.rotationZ = Osc*1.721;
myPendulum2.x = myPendulum1.getPin(Osc).x;
myPendulum2.y = myPendulum1.getPin(Osc).y;

where the getPin(Osc) function gives the end point of the first segment and starting point of the second. Its code for the 2D and 3D cases are:

2D Case

public function getPin(myRot:Number):Point
var angle:Number = myRot* Math.PI / 180;
var xPos:Number = this.x + Math.sin(angle) * myLength;
var yPos:Number = this.y – Math.cos(angle) * myLength;
return new Point(xPos, yPos);

3D pseudo Code (still needs work)

public function getPin(myTheta:Number, myPhi:Number):Vertex3D
var angle1:Number = myTheta* Math.PI / 180;
var angle2:Number = myPhi* Math.PI / 180;

var xPos:Number = this.x + Math.cos(angle1) * Math.sin(angle2)*myLength;
var yPos:Number = this.y + Math.cos(angle2) * myLength;
var zPos:Number = this.z + Math.sin(angle1) * Math.sin(angle2)*myLength;

return new Vertex3D(xPos, yPos, zPos);

In both cases, pinning is just a trig-calculation of segment ending points.

This example demonstrates one of the normal modes of the double pendulum: with the second pendulum overextending to demonstrate the second degree of freedom. To properly handle this problem one needs to use numerical analysis (such as Runge-Kutta).

C. Numerical Calculations: Runge-Kutta

Though beyond the scope of this seminar, we have include the Flash code of Runge-Kutta 2 (midpoint), and 4 in your source files. This code was developed by Keith Peters in his book Advanced ActionScript 3.0 Animation. It’s a good starting point and will be used in seminars to come. The code is included in the objects folder of your download and is labelled RK2, and RK4.

Keith Peter’s Demo (bouncing ball RK4)

D. Torsion: Sliders

Here we describe the use of sliders. Sliders let you interact with your animations: they add the thrill of interaction. But there is a fundamental decision to be made when using such elements. Should you use Flash components, Flex components, or make your own?

Torsion Pendulum

Torsion Pendulum


In this seminar, we use Flex components. And since Flex is free for educators, it’s the logical choice (for this seminar). And in addition, by creating a MXML applications your can just drag those components onto the screen where they are supposed to go.

Here’s the steps:

  • Drag your Flex component to the stage and position it
  • Use the Flex Properties Panel to assign min, max, tick, etc…
  • Incorporate your slider using the following code
  • In the HSlider mx tag (which was automatically generated when you dragged the slider to the stage) place a change event: change=”sliderChangeLive2(event);”

<mx:HSlider change=”sliderChangeLive2(event);” x=”10″ y=”67″ value=”6″ maximum=”40″ minimum=”1″ liveDragging=”false” id=”length” enabled=”true” snapInterval=”1″/

  • Create the sliderChangeLive2 function

private function sliderChangeLive2(event:SliderEvent):void {
var currentSlider2:Slider=Slider(event.currentTarget);

  • Place the mySpConst which is generated by your slider into your equations of motion which are located in your animation loop

var Osc1:Number=80*Math.sin(incre*(Math.sqrt(mySpConst)/20));

E. Foucault: Environment Map

Placing an Environment Map on your primitive adds realism to your object as can be shown below. An Environment Map is a Papervision3D shader material, and a great blog to learn more about shader is Jim Foley’s blog MAD VERTICES. He does a super job with primitives, shaders, and more…and has code, video, and demos.

Foucault Pendulum

Foucault Pendulum


As mentioned earlier an EnvMapMaterial is a shader material. A shader material is a material that uses a light object to determine how it displays. The EnvMapMaterial accepts 4 parameters, the light object, light map bitmapdata, back environment bitmapdata and the ambient light. The EnvMapMaterial displays as though your object is a mirror that is reflecting its environment.

environment = new EnvMapMaterial(light, envMap, envMap, 0×555555)

F. Application: Butterflies

Seb Lee-Delise on his blog gives an example of a butterfly whose wings oscillate like a simple pendulum

Essentially, two planes are created and positioned with a sine oscillation. The code required to do this is given below:

var leftWing:DisplayObject3D;
var rightWing:DisplayObject3D;
var butterfly:* = new DisplayObject3D();
leftWing = new DisplayObject3D();
rightWing = new DisplayObject3D();
var mat:* = new BitmapFileMaterial(“butterfly_wind.png”);
mat.doubleSided = true;
var leftWingPlane:* = new Plane(mat, 200, 200, 1, 1);
var rightWingPlane:* = new Plane(mat, 200, 200, 1, 1);
leftWingPlane.scaleX = -1;
leftWingPlane.x = -100;
rightWingPlane.x = 100;

function (EffectEvent:Event) : void
leftWing.rotationY = Math.sin(getTimer() / 200) * 60;
rightWing.rotationY = Math.sin(getTimer() / 200) * -60;

To improve the code one would need to use encapsulation and pinning. This is treated in the book.

G. Speeding Things Up

In the book, we show you how to build these pendulums in CS4, which speeds things up by reducing the overhead of Papervision3D.


The availability of knowledge provided by the internet is changing the face of education. No longer do we need to leave home to gain excess to the reservoirs of knowledge once cloistered in ivory towers. But now at our finger tips, with a simple click ,we gain excess to more than we could ever retain in a lifetime of study.

It’s changing the way we view education and interact with knowledge. From the “small to large” to the “large to small”, knowledge is in an overwhelming abundance and we must now pare it down and interact with what’s pertinent to our assigned task; which really makes the case for 3D data visualization

Simple Pendulum

Double Pendulum

Torsional Pendulum

Foucault Pendulum

Free Papervision3D Workshops

January 7, 2009

Last Semester I taught a series of Papervision training courses at NKU and we have expanded that endeavor this semester by offering two free national workshops and 11 courses (free for all Kentucky Educators). Dates are subject to change, and as we approach the workshops I will supply additional information.

If you can’t make the workshops, don’t worry, everything will be recorded and placed on YouTube. And all source files will be posted on Google Code for download.

The workshops and courses are specifically geared for educators.

Training Schedule NKU (Courses and Dates)

1. (Feb 3) Virtual Tours & Google Maps
2. (Feb 10) Human Organ Modeling in Blender
3. (Feb 17) Virtual Physics Labs in Papervision
4. (Feb 24) Building Molecules in 3D
5. (Mar 3) 3D Plotter and Equation Parser
6. (Mar 11, 12, 13) Spring Break Free National Workshop Flex/Papervision
7. (Mar 17) Open Workshop
8. (Mar 24) Creating a Data-Driven Website
9. (Mar 31) 3D Virtual Learning Games
10. (Apr 7) Building a Cell Phone Course Part 1
11. (Apr 14) Building a Cell Phone Course Part 2
12. (Apr 21) Open Workshop
13. (May 19, 20, 21) Summer Break Free National Workshop Flex/CS4


Note: All sessions will be recorded live and placed on YouTube.

(Feb 3) Virtual Tours & Google Maps: In this course, you’ll learn how to create a Google Map and place a Blender (or 3DSMax) model on its longitude latitude positions. You’ll learn how to make those models interactive. And how to load content into your project for display on the web. The Walton County Ghost tour will be used as a demonstration. The class is free and participants are required to bring their own laptop.

(Feb 10) Human Organ Modeling in Blender: In this course, you’ll make organs in Blender (such as the heart, liver, stomach). You’ll learn how to create textures for those organs, and how to place your models on the web so your students can interact with them. The heart will be used as a demonstration. The class is free and participants are required to bring their own laptop.

(Feb 17) Virtual Physics Labs in Papervision: In this course, you’ll create virtual physics labs based upon MIT OpenCourseware. Basic Newtonian mechanics will be discussed, and ActionScripting gravity, friction, vibration, and collision will be demonstrated. Finally, a 3D physics engine will be used to create interactive physics labs. The oscillating pendulum will be used as an example. The class is free and participants are required to bring their own laptop.

(Feb 24) Building Molecules in 3D: In this class, you’ll use Papervision to create molecules from standard mol files. You’ll learn how to load different molecules and how to make them springy. Billboarding for large molecules will be discussed. You’ll place your models on the web so students can interact with them. Benzene and other basic molecules will be used as examples. The class is free and participants are required to bring their own laptop.

(Mar 3) 3D Plotter and Equation Parser: In this course, you’ll learn how to integrate an equation parser (created by Barbara Kaskosz of Flash & Math) with a Papervision plotting program. The program allows you to input an equation and have it plotted in 3D. Equation parsers, 3D plotting, and 3D engine development will be discussed. The Sinc and other functions will be used as an example. The class is free and participants are required to bring their own laptop.

(Mar 11, 12, 13) Spring Break National Workshop Flex/Papervision
This 3 day workshop will include:
Day 1: Getting Started in Flex, and Papervision
Day 2: Building Models and 3D Wii Games
Day 3: Creating a 3D Learning Management System
The workshop is free and participants are required to bring their own laptop.

(Mar 17) Open Workshop: This is a feedback session allowing participants to ask questions about previous sessions, bring in design ideas for discussion, and learn about requested topics that were not addressed in previous courses. The class is free and participants are required to bring their own laptop.

(Mar 24) Creating a Data-Driven Website: In this class, you’ll learn the basics of creating a data-driven website. You’ll build a searchable Flex interface. You’ll learn how to get PHP talking to your Flex interface and a MYSQL database. You’ll learn about CRUD, and how to store and change data in your database. Roxanne Kent-Drury’s English site will be used as an example. The class is free and participants are required to bring their own laptop.

(Mar 31) 3D Virtual Learning Games: In this class, you’ll learn how to tear apart 2D games and turn them into 3D games. You’ll learn how to turn killing games into learning games. You’ll learn how to work with models, textures, and sounds. You’ll learn how to upload your games to the web. Both board games and virtual environment games will be discussed. A simple memory game, and Stuart Crickmer’s business game will be used as an example. The class is free and participants are required to bring their own laptop.

(Apr 7) Building a Cell Phone Course Part 1: In this class, you’ll receive an overview of cell phone technologies and a discussion of why they are important in education. You’ll learn how to program a cell phone and how to use it to disseminate information. The class is free and participants are required to bring their own laptop and encouraged to bring a specified cell phone (the cell phone type will be provided upon request).

(Apr 14) Building a Cell Phone Course Part 2: This class is a continuation of Building a Cell Phone Course Part 1. In this class, you’ll learn more advanced techniques in cell phone programming and optimization. You’ll learn how to work with media and data sources. You’ll learn how to put together a cell phone course for the web. The class is free and participants are required to bring their own laptop and encouraged to bring a specified cell phone (the cell phone type will be provided upon request).

(Apr 21) Open Workshop: This is a feedback session allowing participants to ask questions about previous sessions, bring in design ideas for discussion, and learn about requested topics that were not addressed in previous courses (such as working with Adobe Air). The class is free and participants are required to bring their own laptop.

(May 19, 20, 21) Summer Break National Workshop Flex/CS4
This 3 day workshop will include:
Day 1: Getting Started in Flex, and CS4
Day 2: Building Models and 3D Websites
Day 3: Creating 3D Data Visualization Templates
The workshop is free and participants are required to bring their own laptop.

34 Papervision Legacy Examples

December 10, 2008

A while ago 34 Papervision examples were moved from the AS3  examples folder of Papervision (they were moved to as3 > tags > 1_7 > examples – see villmer’s comment below). I’m assuming this was done to  remove legacy code. Some of the examples are dated and need to be streamlined, but many are still somewhat instructive. So I’ve zipped them and put them on my book’s site for you to download. The image below names the available examples.

34 Papervision Legacy Examples

34 Papervision Legacy Examples

To download the 34 Papervision Legacy Examples click here or try the direct link below;

Direct Link

The swfs in the individual folders are functional. So if you click on them they should run (given that you have flash installed). Also, I have included the src folder which contains the legacy version of Papervision used to create these examples. It amazing how much Papervision has changed over the past year. But more change is on the way.

The Papervision team is in the process of writing PapervisionX (the Flash 10 compatible version of Papervision). Once that is completed the examples above will be totally obsolete, but for now you might find them useful.

Getting Started with Gumbo (Flash 10)

November 28, 2008


We knew from the start in writing Professional Papervision that the technology would change mid-stream. Mid-stream is here and we are delighted with the changes. And we are incorporating them into your book. Yes, expect the book to cover Gumbo (Flex 4) – and much more.

I just couldn’t resist this graphic below. Is it a bird (gumby)? Is it a plane (dumbo)? No it’s Gumbo!

Flex 4 Gumbo

Open Source Flex 4 Gumbo

In addition to the power of the Flash 10 player, having the open source gumbo code opens up a whole new world of development possibilities.

In this tutorial, you’ill learn how to get started with Gumbo by doing the following;

  • Installing and configuring Gumbo
  • Creating your first program
  • Examining the Gumbo classes

I’m thrilled that Gumbo is here and have already started using it to extend the possibilities of Papervision. You’ll hear much about integrating Gumbo with Papervision in future blog post.

Gumbo Rotating Video Example

A great place to go for Gumbo examples is Peter deHaan’s blog on Flex Examples. I’ve been reading his blog since it first came out and he does really good work in Flex – almost an example everyday. I modified his rotating image Gumbo Code and extended it to play video, and have added a discussion on how to discover what is available in Gumbo. And how to work with Gumbo’s class structure. My extended example can be accessed by clicking on the link below – remember you need the Flash 10 player to run it!

Rotating Gumbo Video

Rotating Gumbo Video

You can watch the demo or download the source from the links below;



The Big Deal!!!

So what’s the big deal? Why should you even care about Gumbo? Besides the performance enhancement and ease of use, Flex’s components are now native 3D – no more bitmapdata hacks to get them into Papervision – and if you are interested in building a Flash version of Second Life you just got a major boost. Second Life doesn’t handle data well – Flex 4 is a 3D data animal.

Installing and configuring Gumbo

YouTube (Part 1 Installing Gumbo – Part 2 below):

Getting Started Steps (Covered in YouTube Video)

All these steps are covered in the YouTube video, and they are included here so you can follow along.

1. To download Gumbo, navigate to the following URL:

2. Download the latest stable build or latest milestone – newest date. Download Adobe Flex SDK.

3. Save latest stable build to your hard drive and extract the files from the .ZIP file

4. In Flex Builder 3, select Window > Preferences from the main menu to open the Flex Builder Preferences dialog box. To add, edit, or remove a Flex SDK, select Flex > Installed Flex SDKs.

5. Click the Add button to launch the Add Flex SDK dialog box and click the Browse button to navigate to the directory where you extracted the nightly SDK build in a previous step.

6. Click OK to apply your changes and add the new Flex SDK. If you want to set the newly downloaded SDK as your default SDK, click the check box to the left of the SDK name. Click OK to dismiss this dialog.

If you want to compile your code against this new SDK you can select Project > Properties from the main menu, select Flex Compiler from the menu on the left, and select your new SDK from the dropdown menu in the Flex SDK version section. Note:Make sure Flash Player 10 is selected.

Also worth mentioning is that you can manage your installed SDKs via the Project Properties dialog menu by clicking the Configure Flex SDKs link, which takes you to the Installed Flex SDKs preferences.

Difference Between Builds

Latest Milestone Release Builds – Releases are builds that have been declared major releases by the development team – Releases are the right builds for people who want to be on a stable, tested release, and don’t need the latest greatest features and improvements

Stable Builds – Stable builds have been found to be stable enough for most people to use. They are promoted from nightly build by the architecture team after they have been used for a few days and deemed reasonable. The latest stable build is the right build for people who want to stay up to date with what is going on in the latest development stream, and don’t mind putting up with a few problems in order to get the latest and greatest features and bug fixes.

Nightly Builds – Nightly builds are produced every night from whatever has been released into the HEAD of the SVN repository. They are untested and may have problems. Some possibly will not work at all.

Different types of Flex SDKs available:

  • Free Adobe Flex SDK – An official Adobe product, with released versions found at The Adobe Flex SDK contains everything you will need to build and deploy Flex RIAs
  • Open Source Flex SDK – For users who want a package that contains only open source code, we offer the Open Source Flex SDK, which is available from this site.
  • Adobe Add-ons for Open Source Flex SDK – This package contains all of the items that are in the Adobe Flex SDK and not in the Open Source Flex SDK.

Code Creation and Working with Classes (Covered in YouTube Video)

YouTube Video (Part 2 Code Creation)

After downloading deHaan’s example of the rotating image load it into Flex and get it working. You’ll modify his code to get a button-controlled video (play, stop, pause) instead of an image rotating. Here are the steps below;

  • Add the Video Display import statement

import mx.controls.VideoDisplay;

  • Add a video1 private variable for your video

private var video1:VideoDisplay

  • Add video play, stop, and pause buttons and include their event listeners in the initiation function

fxVideoPlay =new FxButton();
fxVideoPlay.label = “Play Video”;
fxVideoPlay.addEventListener(MouseEvent.CLICK, playVideo);

fxVideoPause =new FxButton();
fxVideoPause.label = “Pause Video”;
fxVideoPause.addEventListener(MouseEvent.CLICK, pauseVideo);

fxVideoStop =new FxButton();
fxVideoStop.label = “Stop Video”;
fxVideoStop.addEventListener(MouseEvent.CLICK, stopVideo);

  • Add the buttons to the VGroup


  • Instantiate the Video Display, add its source, position, style, and add to the stage

video1 = new VideoDisplay();


video1.setStyle(“horizontalCenter”, 0);
video1.setStyle(“verticalCenter”, 0);


  • Finally add the play, pause, and stop button function for your listeners

private function playVideo(evt:MouseEvent):void {;

private function pauseVideo(evt:MouseEvent):void {


private function stopVideo(evt:MouseEvent):void {


  • And that’s it! To see the code click the more button below.

Read the rest of this entry »

Guts of a Papervision Application

November 18, 2008

All Papervision applications have the following elements in common. They can be thought of as the guts of Papervision.

Scene The scene is where objects are placed. It contains the 3D environment and manages all objects rendered in Papervision3D. It extends the DisplayObjectContainer3D class to arrange the display objects.

Viewport The viewport displays the rendered scene. It’s a sprite that is painted with a snapshot of all the stuff contained in the view frustum. The viewport sprite inherits all the sprite methods and can be moved, positioned, and have effects added just like any normal sprite in flash.

Camera The camera is your eye inside of the 3D scene and defines the view from which a scene will be rendered. Different camera settings will present a scene from different points of view. When rendering, the scene is drawn as if you were looking through the camera lens.

Object An object is a combination of vertices, edges, and faces which provide a meaningful form for display, such as a car, avatar, or box. Objects are created in Papervision using primitives, or embedded or imported into Papervision from a modeling application such as Blender, Swift3D, or 3DSMax.

Material The material is the texture which is applied to an object. Textures can consist of various formats such as bitmaps, swfs, or video, and interact with light sources creating bump map effects and shaders.

Renderer The renderer draws a sequence of faces onto the viewport so that they make visual sense. Typically the renderer is set into a loop using onEnterFrame or Timer methods native to the flash player.

Running a Papervision application is like simultaneously recording and projecting your 3D scene as shown in the image below. The scene is the middle man. It’s what the camera films and what the projector projects.

Papervision Films and Projects at the Same Time

Papervision Films and Projects at the Same Time

You can think of the whole process as a combination of a movie camera and projector which both films and projects your 3D scene simultaneously. The scene is what the camera is pointed at and the objects are the items that the camera films. The materials are what your objects are dressed in and determine how the light interacts with the scene elements. The reels on your projector are your renderer and as your reels turn (using onEnterFrame or Timer methods) they cast the recorded scene onto your screen which is your viewport.

The base code distributed with Chapter 1 of the book provides a great example of these six quantities in action. Click on the links below to see a demo, or download the code.


Download: (

YouTube Video:

Click more below to see the code example.

Read the rest of this entry »

Getting Your Head Around Papervision3D

November 14, 2008

I recently got a question on “how to get your head around papervision3D”. This was a really good question since going to the next level in Papervison does require some digging. Since there isn’t much out there yet!

Here is what I did;

1. I read all the blog links of course – many of which you can find under mylinks on by book site at

2. I read every 3D book I could get off of Amazon – many of them are less than a dollar if you buy used.

3. I used the video tutorial service which actually does two tutorial series on particles (one by Seb) and extensive Flex, 3DSmax, AS3, and Flash. I’ve used lynda for years.

4. I dug really hard on Blender – not much out there – but some tutorials on Youtube, a book on Amazon, and a tutorials series on Wikipedia at

5. I started digging into the Papervision code and modifying the classes and comparing that to what I was reading in the books I bought off of Amazon. This really helped a bunch. Flex is the best environment to do this in. You can ctrl link to other classes which helps tremendously in tracking things down.

6. I took John Grden’s Papervision Optimization class which was relatively cheap from the rich media institute.

7. I used Sothink to look at what others were doing. If you want to write good code you need to look at good code. But use the old rule – look but don’t touch. No reason to take other people’s code. (This sounds a little pedantic – decompiling is a very sensitive area and I answer a reader’s concern in the comments) You can write your own more rapidly, but it does no harm to look at good ideas. SWF is an open format.

8. I dug through the code of other open source projects such as Sandy, Away3D, WOW, vectorvision , panosalado , Flint Particle System , and Mr. Doobs Previewer.

9. Finally, I prayed a lot.

Hope this helps!

Creating an Adjustable Carousel Primitive

November 12, 2008


Typically carousels are created by assembling single planes in a cylindrical configuration stacking rows as needed. But there is another way to do this. You can create a single primitive which constructs all the planes internally. Handling a single primitive requires fewer calculations to manipulate it than handling multiple planes. And you can do more with it.

To see a demo click on the image below. Try clicking on the images they are interactive.

Single Primitive Carousel

Single Primitive Carousel

Just as in the case of the cube primitive, the carousel primitive can be manipulated as a single primitive. And the number row and column numbers are adjustable.

Web Stuff


Download (CarouselPrimitive)

YouTube How to Video:

How it works

The carousel constructor function shown below gives you the ability to control the horizontal and vertical gap size, number of rows and columns, height and width, segments, and material list.

public function Carousel( materials:MaterialsList, myGap:Number=0, myHGap:Number=0 ,horizNum:int=1, vertiNum:int=1, width:Number=0, height:Number=0, segmentsW:Number=0, segmentsH:Number=0, initObject:Object=null )

Primitive Code

The carousel primitive was created by duplicating the Clickable Button Panel Primitive found in this blog and renaming the class and constructor function to Carousel. Then after adding the appropriate variables, the simple equation for a cylinder was used to place the primitives according to the angle and number created by the horizNum (number of images in a circular row).

var x :Number = myX*Math.cos(myThetaIs)+myZ*Math.sin(myThetaIs);

var z :Number = -myX*Math.sin(myThetaIs)+myZ*Math.cos(myThetaIs);

var y :Number = iy * iH -(textureY+myHGap/2)*(vertiNum/2-n);

var vertex:Vertex3D = new Vertex3D();

vertex[ "x" ] = x;
vertex[ "y" ] = y;
vertex[ "z" ] = z*10;

As the different x, y, and z values are created they are put into the vertex array just as was done in creating the clickable button panel. But notice the term vertex[ "z" ] = z*10; which has a multiplier of 10. This is an issue that must be investigated in the future.

The next issue was changing how the material was named. For the clickable button panel we used a matrix numbering scheme for the material name. We change this scheme when dealing with the carousel primitive to produce a sequential numbering system. This made the images easier to work with and the code is shown below.

var myNumber:Number= horizNum*n+m;
var myMaterial:String = “myMat”+myNumber;

Main Code

Since the carousel contains many images, we do not want to have to list them individually for the material list as we did in the Button Panel case. So we put the image address in a myBitmaps array and iterate through them as shown below to create the materials list.

var materialsList:MaterialsList = new MaterialsList();

for (var i:int = 0; i<myBitmaps.length; i++)

var myBitmapFileMaterial:BitmapFileMaterial = new BitmapFileMaterial(myBitmaps[i]);
myBitmapFileMaterial.doubleSided = true;

myBitmapFileMaterial.interactive = true;”myMat”+i;



for (var ik:int = 0; ik<myBitmaps.length; ik++)

materialsList.addMaterial(myBitmapFileMaterials[ik], “myMat” + ik);


This is a real time/code saver and can be used to bring in items from an external data base or xml page using HTTP Services.

The Big Problem

In Papervision, pixel measurements lose their meaning due to the 1/z parameter of perspective and as result you end up doing some adjusting. The is true for the carousel. If you change the gap or height components of the Carousel function you must readjust the following parameters to get the carousel to go to the correct image when clicking on it.

var myAdjustLift:Number=35;
var myAdjustHeight:Number=70;
var myLift:Number=myAdjustLift*(plane.vertiNum-1);
var myHeight:Number=myAdjustHeight*(plane.vertiNum);

The myLift parameter adjust the place where you enter the image close up and the myHeight parameter adjusts the individual column spacings entry point. Once you set the parameters above you can change row and column numbers without further adjustments. But if you change vertical gap or image height you need to readjust the parameters above.

There is a nonlinear equation that governs this behavior, but that is the subject of another post…

To see the full Carousel class click the more button below.

Read the rest of this entry »

Papervision Planetarium (Flex Code – NOMAD constellations)

November 6, 2008


I was having so much fun writing chapter 4 (on particles) that I could not resist creating a Planetarium. There are so many things you can do with particles like make fire, smoke, a flock of birds, or even the planetarium shown below.

Click on the image below to view the demo and then we’ll discuss how it was made. And get ready for some major hacking.

Papervision Planetarium

Papervision Planetarium

These are real constellations above found on sites like NOMAD and they use standard astro-celestial coordinates.

Web Stuff


Download: (Choose Planetarium)

How to Video:

How it was Made

If you’re a Papervision purist, stop reading, close this post, and go for a cup of coffee. We are going to hack the heck out of Papervision, and it’s going to get ugly! On the other hand, if you’re ready to rock let’s get started.

The good news is that the entire code is only about 200 lines (counting spaces). Coming from the 2D Flash 8 world that’s pretty amazing. There are two parts to this hack. Creating a SkyMap class and creating the main Flex application which uses the SkyMap class.

Steps for creating the SkyMap class

  1. Create a Flex Project – call it Planetarium.
  2. Put Cairngorm in your Flex libs folder. To learn more about Cairngorm check out the video tutorials tab at the top of the blog (choose installing Cairngorm). I go over MVC architecture there. The purpose of Cairngorm is to hold the stellar data. Now you could have used just an array and an XML import, but since I build Learning Management systems I just couldn’t help myself. And yes, I just swatted a fly with an elephant – I confess!
  3. Place the Papervision classes in the src folder and open up the ParticleField class found in org/papervision3d/objects/special folder. Make a duplicate of it and name it SkyMap and then change its public class name and constructor name to SkyMap. In order to get stars you’ll need to use the ParticleField ParticleMaterial class that I expanded added to in a previous post on

    Putting Stars and More into a Skybox (Source)

    Otherwise, you’ll only get circles and squares. I like stars better!

  4. Place your sky map data into an xml file using CSV. Check this out on the how to video to see an example.
  5. Now change the public class by eliminating length, width, and depth variables and add a radius variable in their place.
  6. Finally eliminate the random particle equations (for x, y, and z) and substitute in the celestial equations which use the xml data brought into the Cairngorm array using HTTP services. This code is shown below;

private function createParticles(size:Number):void
var c:int;
var r:int;

//Lively Modifications Add Particle Stuff
var myPartNum:Number = modelLocator.myStarData.length/4;
for( var i:Number = 0; i < myPartNum; i++ )
var myX:Number=skyRadius*(Math.cos(2*Math.PI*modelLocator.myStarData[4*i]/24)*Math.sin((90-modelLocator.myStarData[4*i+1])*Math.PI/180));
var myZ:Number=-skyRadius*(Math.sin(2*Math.PI*modelLocator.myStarData[4*i]/24)*Math.sin((90-modelLocator.myStarData[4*i+1])*Math.PI/180));
var myY:Number=skyRadius*Math.cos((90-modelLocator.myStarData[4*i+1])*Math.PI/180)
var mySize:Number=size*(3-modelLocator.myStarData[(4*i+3)]);
addParticle(new Particle(material as ParticleMaterial, mySize, myX, myY, myZ));

Steps for creating the main Flex Application

This main application is just a hack of the panorama application created in the post on

Creating a Spherical Panorama in Papervision

Here are the steps;

  1. Grab the Spherical Panorama class and rip off the package tags and remove the public class and add void to the constructor function.
  2. Create the appropriate Cairngorm folders including a singleton file in the model folder named ViewModelLocator and place an array myStarData in the singleton.
  3. Make sure that both your main Flex application and the SkyMap class have the appropriate import and variables strings to bring in Cairngorm and the myStarData model locator array.
  4. Put a HTTP services command in Flex that brings in your star data and make sure your application tag contains a call to start up your HTTP services.
  5. Parse that data in an Array Collection and comma split it and place that data into your model Locator array.
  6. You’re done! The array is now available for your SkyMap. Run your program.

To see the code for both the SkyMap class and the main Flex Application click on the more button below. Or better yet, just download it from the link provided above.

Read the rest of this entry »

Clickable Button Panel Primitive

October 27, 2008


Custom primitives are unexplored territory in Papervision. And they pack a big punch. To illustrate the point, consider the following custom clickable button panel primitive. From the image below you see 8 planes in two rows. Typically you rez planes on the stage one at a time and keep track of them individually as they rotate.

But with a custom primitive it’s all one primitive, which reduces the number of primitives you have to keep track of to one.

Click the image below to see a demo.

Clickable Custom Button Panel

Clickable Custom Button Panel

In the demo above, when you click on a plane a URL is brought up in the browser. Each plane calls a different URL.

Even cooler – you have total control over the number of rows, columns and spacing. The custom primitive is called


You place it in the primitives folder and rez it to the state the same way you would any other primitive and adjust its properties in the same way as well.

The primitive function look like this

MultMatPlane( materials:MaterialsList, myGap:Number=0,horizNum:int=1, vertiNum:int=1, width:Number=0, height:Number=0, segmentsW:Number=0, segmentsH:Number=0, initObject:Object=null )

The adjustable parameters are

  • materials
  • gap
  • column number
  • row number
  • image width
  • image height
  • width segments
  • height segments

Of course the important part in changing row and column parameter is to have the materials labeled correctly in the materials list. If the materials aren’t in the materials list – you won’t see them. That makes sense, but I’ve already made the mistake 100 times. And you should probably know about it. More on how this works below.

Note of Caution

One more thing – late last night this primitive didn’t like my Firefox pop up blocker (well at least not at 2 o’clock in the morning) – so keep an eye on that!

Any primitive as new as this one has to go through a few cycles of work to make sure it is fully functional for web use; this one has not been through those cycles yet!!! But it is being used successfully on a website – which is encouraging. The purpose of this tutorial is to demystify how such primitives are built – not beat all the bugs out. That comes with time and use.

Web Stuff



(Download from the list)


How it was made

Building this primitive was really easy. Here are the steps and stuff to look out for:

  1. Make a copy of the plane primitive and rename its class and constructor function to MultMatPlane (or whatever you want to call it)
  2. In the public class MultMatPlane, add the new properties that you need such as row number, column number, materials, … whatever you want.
  3. Then make sure those variables are carried over in your constructor function.
  4. Open up the cube primitive and see how the different sides were made. You will need to follow the same pattern, but generalize it for multisides and different geometries.
  5. After porting the cube code that you need, create and call the buildMultiPlane function – this is the heart of your class. It iterates through your column and row sizes placing them on the screen, shown below:

private function buildMultiPlane(myGap:Number, horizNum:Number, vertiNum:Number, width:Number, height:Number ):void

for(var n:int=0; n <vertiNum; n++){

for(var m:int=0; m <horizNum; m++){

var myMaterial:String = “myMat”+””+n+””+m;


buildPlane( myMaterial, myGap, m, n, horizNum, vertiNum, width, height) ;

5. Keep the code very similar to the cube code port, only replace all u variables with x variables and v variables with y variables.

6. And here is the big trick. Replace the plane vertices.push( new Vertex3D( x, y, 0 ) ) with the cube primitive technique for dealing with vertices as shown below. Make sure you put x in for u and y in for v.

var vertex:Vertex3D = new Vertex3D();

vertex[ "x" ] = x;
vertex[ "y" ] = y;
vertex[ "z" ] = 0;

vertices.push( vertex );
planeVerts.push( vertex );

And that is pretty much it! A little bit of work here, but now you are set up to do so much more. Like make single primitive carousels, images balls, and terrains. An all-in-one primitive. How cool is that?

Material List

So how do your get different images on the different planes in your custom primitive?

Use a materials list!

Here is an example of such a list from your main code:

var materialsList:MaterialsList = new MaterialsList();
materialsList.addMaterial(myBitmapFileMaterial00, “myMat00″);
materialsList.addMaterial(myBitmapFileMaterial01, “myMat01″);
materialsList.addMaterial(myBitmapFileMaterial02, “myMat02″);
materialsList.addMaterial(myBitmapFileMaterial03, “myMat03″);
materialsList.addMaterial(myBitmapFileMaterial10, “myMat10″);
materialsList.addMaterial(myBitmapFileMaterial11, “myMat11″);
materialsList.addMaterial(myBitmapFileMaterial12, “myMat12″);
materialsList.addMaterial(myBitmapFileMaterial13, “myMat13″);

The big thing was coming up with a naming conventions. For the cube it is top, right, left, top,…

But in this case I just numbered them by row and column, where myMatt00 is the lower left most button.


Making the plane interactive is not difficult. Give each of your materials a name and use a switch case to call that name when a plane is clicked on:

Name it like this! = “myMat00″;

Call it like this!

case “myMat00″:
navigateToURL(new URLRequest(“;), “_blank”);
}// end case …

That’s pretty much it! To check out the rest of the code by downloading it from the link above. And the MultMatPlane code is given below.

MultMatPlane Code

Get the MultMatPlane code under the more tab below. Note: The code is not fully documented. I’ll take care of that before the book comes out.

Read the rest of this entry »


Get every new post delivered to your Inbox.