Papervision2.0 – dynamically loading MovieMaterial in Flex

I’ve been working with Flex Builder a lot more lately in case you haven’t noticed. I’ve noticed that a lot Papervision2.0 examples I run into that use MovieMaterial embed the source .swf a little like this:
[as]
[Embed(source=”img01.jpg”)]
[/as]
But, what about loading the .swf in dynamically for more flexibility? It’s a whole lot easier than you think:

[as]
package {
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.geom.Rectangle;
import flash.net.URLRequest;

import org.papervision3d.materials.MovieMaterial;
import org.papervision3d.objects.primitives.Plane;
import org.papervision3d.view.BasicView;

public class FlexLoader extends BasicView
{
private var request:URLRequest;
private var loader:Loader;

public function FlexLoader()
{
super(200,200,false, true);
loadSWF();
startRendering();

}

private function loadSWF():void {
request = new URLRequest(“assets/matTest.swf”);
loader = new Loader();

loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadError);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress);
loader.contentLoaderInfo.addEventListener(Event.INIT, loadInit);

loader.load(request);

}

private function makePlane(e:Event):void {

//create material
var loadedVidSWF:MovieClip = e.target.content as MovieClip;
var loadedMat:MovieMaterial = new MovieMaterial(loadedVidSWF, false, true, false, new Rectangle(0,0,400,400));
loadedMat.doubleSided = true;
loadedMat.animated = true;

//create plane
var vidPlane:Plane = new Plane(loadedMat,400,400,5,5);
scene.addChild(vidPlane);
}

private function loadComplete(e:Event):void {
trace(e);
}

private function loadError(e:IOErrorEvent):void {
trace(e);
}

private function loadProgress(e:ProgressEvent):void {
trace(e);
}

private function loadInit(e:Event):void {
trace(e);
makePlane(e);
//to call a function on your SWFs timeline
//e.target.content.yourFunction(args);

}

override protected function onRenderTick(event:Event = null):void
{
super.onRenderTick(event);
}

}

}
[/as]

Here’s the source for even easier reading. It uses rev.691 of Papervision2.0 GreatWhite, but the Papervision classes are not included in this zip file.

Have a comment or question? Find me on twitter or email me.