My Playground

Ha you have reached my playground, for all those moments at work when you think this would be cool but then I need more time. Or the client simply just does not like it for some reason. And ofcourse to show prototypes that did got used in projects, hopefully in different versions to show the work in progress flow, which in my opinion is always nice to see.

Some of my experiments use classes from wismanas3lib repository, so please get a copy from the repository so you can retrieve possible updates aswell. Or download them here (!! the classes will get updated so it’s better to use the googlecode repository !!).

Cheers JW

FLARToolkit Single & MultipleMarker Detection

Last modified on 2013-01-09 22:08:29 GMT. 15 comments. Top.

What you will need:
1. Photoshop (any will do)
2. Papervision3D rev. 817 or later
3. FlarToolkit
4. ArToolkit Marker Generator (flash player 10)
5. webcam
6. Fash CS3 or Higher

There are allready some great sites experimenting and writing tutorials about Augmented reality in flash. This is nothing new, just my experience in writing the code to create a simple version so I can learn from the others who started it. So before I start credits go out to squidder.com for some amazing tutorials and examples and saqoosha.net for starting the FlarToolkit.

For creating the best markers go and see the tutorial at squidder.com
For the starters kit you can get flartoolkit via libspark repository or download the starterskit at saqoosha.net.

Example of a Single Marker Detection:

Code Single Marker detection:

  1. package nl.wisman.codexperiments.augmented
  2. {
  3.  // papervision
  4.  import org.papervision3d.materials.utils.MaterialsList;
  5.  import org.papervision3d.objects.primitives.Cube;
  6.  import org.papervision3d.lights.PointLight3D;
  7.  import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
  8.  import org.papervision3d.render.LazyRenderEngine;
  9.  import org.papervision3d.scenes.Scene3D;
  10.  import org.papervision3d.view.Viewport3D;
  11.  
  12.  // flash
  13.  import flash.display.PixelSnapping;
  14.  import flash.display.Bitmap;
  15.  import flash.net.URLRequest;
  16.  import flash.events.Event;
  17.  import flash.net.URLLoaderDataFormat;
  18.  import flash.net.URLLoader;
  19.  import flash.display.BitmapData;
  20.  import flash.media.Video;
  21.  import flash.media.Camera;
  22.  import flash.display.Sprite;
  23.  import org.papervision3d.objects.DisplayObject3D;
  24.  
  25.  // libspark
  26.  import org.libspark.flartoolkit.core.FLARCode;
  27.  import org.libspark.flartoolkit.core.param.FLARParam;
  28.  import org.libspark.flartoolkit.core.raster.rgb.FLARRgbRaster_BitmapData;
  29.  import org.libspark.flartoolkit.core.transmat.FLARTransMatResult;
  30.  import org.libspark.flartoolkit.detector.FLARSingleMarkerDetector;
  31.  import org.libspark.flartoolkit.pv3d.FLARBaseNode;
  32.  import org.libspark.flartoolkit.pv3d.FLARCamera3D;
  33.  
  34.  public class FlarSingleMarkerDemo extends Sprite
  35.  {
  36.   // flar properties
  37.   private var _camParameters:FLARParam;
  38.   private var _marker4Pattern:FLARCode;
  39.   private var _raster:FLARRgbRaster_BitmapData;
  40.   private var _detector:FLARSingleMarkerDetector;
  41.   private var _flarCam3D:FLARCamera3D;
  42.   private var _resultMat:FLARTransMatResult;
  43.   private var _baseNode:FLARBaseNode;
  44.  
  45.   // flash properties
  46.   private var _cam:Camera;
  47.   private var _vid:Video;
  48.   private var _capture:Bitmap;
  49.   private var _loader:URLLoader;
  50.  
  51.   // papervision3d
  52.   private var _vp:Viewport3D;
  53.   private var _scene:Scene3D;
  54.   private var _renderer:LazyRenderEngine;
  55.   private var _light:PointLight3D;
  56.   private var _cube:Cube;
  57.  
  58.   public function FlarSingleMarkerDemo()
  59.   {
  60.    loadCamera();
  61.   }
  62.  
  63.   private function loadCamera():void
  64.   {
  65.    _loader = new URLLoader();
  66.    _loader.dataFormat = URLLoaderDataFormat.BINARY;
  67.    _loader.addEventListener(Event.COMPLETE, onLoadCamParam);
  68.    _loader.load(new URLRequest("camera_para.dat"));
  69.   }
  70.  
  71.   // camera parameters are loaded, load the marker you want to use
  72.   private function onLoadCamParam(event:Event):void
  73.   {
  74.    _loader.removeEventListener(Event.COMPLETE, onLoadCamParam);
  75.    _camParameters = new FLARParam();
  76.    _camParameters.loadARParam(_loader.data);
  77.    _camParameters.changeScreenSize(500, 500);
  78.  
  79.    _loader.dataFormat = URLLoaderDataFormat.TEXT;
  80.    _loader.addEventListener(Event.COMPLETE, onLoadCode);
  81.    _loader.load(new URLRequest("yourmarker.pat"));
  82.   }
  83.  
  84.   // marker now also loaded, so remove _loader and create a FlarCode
  85.   private function onLoadCode(event:Event):void
  86.   {
  87.    initWebcam();
  88.  
  89.    _marker4Pattern = new FLARCode(4, 4, 65, 65);
  90.    _marker4Pattern.loadARPatt(_loader.data);
  91.  
  92.    _loader.removeEventListener(Event.COMPLETE, onLoadCode);
  93.    _loader = null;
  94.  
  95.    // create bitmap and bitmapdata where we can draw the webcam into
  96.    var bmd:BitmapData = new BitmapData(500, 500, false, 0);
  97.    _capture = new Bitmap(bmd, PixelSnapping.AUTO,false);
  98.    _capture.width = 500;
  99.    _capture.height = 500;
  100.    addChild(_capture);
  101.  
  102.    _raster = new FLARRgbRaster_BitmapData(_capture.bitmapData);
  103.    _detector = new FLARSingleMarkerDetector(_camParameters, _marker4Pattern, 65);
  104.  
  105.    initFlar();
  106.    initPV3D();
  107.    initListeners();
  108.   }
  109.  
  110.   private function initWebcam():void
  111.   {
  112.    _cam = Camera.getCamera();
  113.    _cam.setMode(500, 500, 60);
  114.    _vid = new Video(500, 500);
  115.    _vid.attachCamera(_cam);
  116.   }
  117.  
  118.   private function initFlar():void
  119.   {
  120.    _flarCam3D = new FLARCamera3D(_camParameters);
  121.    _resultMat = new FLARTransMatResult();
  122.    _baseNode = new FLARBaseNode();
  123.   }
  124.  
  125.   private function initPV3D():void
  126.   {
  127.    _vp = new Viewport3D(500, 500);
  128.    addChild(_vp);
  129.  
  130.    _scene = new Scene3D();
  131.    _scene.addChild(_baseNode);
  132.  
  133.    _light = new PointLight3D();
  134.  
  135.    // add a cube or whatever we want to show when pattern is recognised
  136.    // in the basenode (FLARBaseNode, which extends from a DisplayObject3D)
  137.    var fmat:FlatShadeMaterial = new FlatShadeMaterial(_light, 0x7DC202, 0xCCCCCC);
  138.    _cube = new Cube(new MaterialsList({all: fmat}), 40, 40, 80);
  139.    _cube.z = 20;
  140.    _cube.name = "cube";
  141.    _baseNode.addChild(_cube);
  142.  
  143.    _renderer = new LazyRenderEngine(_scene, _flarCam3D, _vp);
  144.   }
  145.  
  146.   private function initListeners():void
  147.   {
  148.    addEventListener(Event.ENTER_FRAME, render);
  149.   }
  150.  
  151.   private function render(event:Event):void
  152.   {
  153.    _capture.bitmapData.draw(_vid);
  154.  
  155.    if (_detector.detectMarkerLite(_raster, 65) && _detector.getConfidence() > 0.5)
  156.    {
  157.     // when deteactmarker finds the marker you created show the baseNode
  158.     _detector.getTransformMatrix(_resultMat);
  159.     _baseNode.setTransformMatrix(_resultMat);
  160.     _baseNode.visible = true;
  161.    }
  162.    else
  163.    {
  164.     _baseNode.visible = false;
  165.    }
  166.  
  167.    if(_baseNode.visible)
  168.    {
  169.     Cube(_baseNode.getChildByName("cube")).roll(1);
  170.    }
  171.  
  172.    _renderer.render();
  173.   }
  174.  }
  175. }

Example of a Multiple Marker Detection: (its still a work in progress, still shifts cube from one pattern to another but he…)

Code Multiple Marker detection:

  1. package
  2. {
  3.  // bulkloader
  4.  import br.com.stimuli.loading.BulkLoader;
  5.  
  6.  // papervision
  7.  import org.papervision3d.materials.utils.MaterialsList;
  8.  import org.papervision3d.objects.primitives.Cube;
  9.  import org.papervision3d.lights.PointLight3D;
  10.  import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
  11.  import org.papervision3d.render.LazyRenderEngine;
  12.  import org.papervision3d.scenes.Scene3D;
  13.  import org.papervision3d.view.Viewport3D;
  14.  
  15.  // flash
  16.  import flash.display.PixelSnapping;
  17.  import flash.display.Bitmap;
  18.  import flash.net.URLRequest;
  19.  import flash.events.Event;
  20.  import flash.net.URLLoaderDataFormat;
  21.  import flash.net.URLLoader;
  22.  import flash.display.BitmapData;
  23.  import flash.media.Video;
  24.  import flash.media.Camera;
  25.  import flash.display.Sprite;
  26.  import org.papervision3d.objects.DisplayObject3D;
  27.  
  28.  // libspark
  29.  import org.libspark.flartoolkit.core.FLARCode;
  30.  import org.libspark.flartoolkit.core.param.FLARParam;
  31.  import org.libspark.flartoolkit.core.raster.rgb.FLARRgbRaster_BitmapData;
  32.  import org.libspark.flartoolkit.core.transmat.FLARTransMatResult;
  33.  import org.libspark.flartoolkit.detector.FLARMultiMarkerDetector;
  34.  import org.libspark.flartoolkit.pv3d.FLARBaseNode;
  35.  import org.libspark.flartoolkit.pv3d.FLARCamera3D;
  36.  
  37.  public class FlarMultiMarkerDemo extends Sprite
  38.  {
  39.   // flar properties
  40.   private var _camParameters:FLARParam;
  41.   private var _raster:FLARRgbRaster_BitmapData;
  42.   private var _detector:FLARMultiMarkerDetector;
  43.   private var _flarCam3D:FLARCamera3D;
  44.   private var _resultMat:FLARTransMatResult;
  45.  
  46.   // flash properties
  47.   private var _cam:Camera;
  48.   private var _vid:Video;
  49.   private var _capture:Bitmap;
  50.   private var _loader:URLLoader;
  51.   private var _allMarkers:Array;
  52.  
  53.   // papervision3d
  54.   private var _vp:Viewport3D;
  55.   private var _scene:Scene3D;
  56.   private var _renderer:LazyRenderEngine;
  57.   private var _light:PointLight3D;
  58.   private var _bLoader:BulkLoader;
  59.  
  60.   public function FlarMultiMarkerDemo()
  61.   {
  62.    _allMarkers = [
  63.          {markerSource: "path/your_first_marker.pat", segments: 4, size: 65},
  64.          {markerSource: "path/your_second_marker.pat", segments: 4, size: 65},
  65.          {markerSource: "path/your_third_marker.pat", segments: 4, size: 65},
  66.         ];
  67.  
  68.    loadCamera();
  69.   }
  70.  
  71.   private function loadCamera():void
  72.   {
  73.    _loader = new URLLoader();
  74.    _loader.dataFormat = URLLoaderDataFormat.BINARY;
  75.    _loader.addEventListener(Event.COMPLETE, onLoadCamParam);
  76.    _loader.load(new URLRequest("camera_para.dat"));
  77.   }
  78.  
  79.   // camera parameters are loaded, load the marker you want to use
  80.   // camera parameters are loaded, load the marker you want to use
  81.   private function onLoadCamParam(event:Event):void
  82.   {
  83.    _loader.removeEventListener(Event.COMPLETE, onLoadCamParam);
  84.  
  85.    // setup camera parameters
  86.    _camParameters = new FLARParam();
  87.    _camParameters.loadARParam(_loader.data);
  88.    _camParameters.changeScreenSize(500, 500);
  89.  
  90.    // reset loader
  91.    _loader = null;
  92.  
  93.    _bLoader = new BulkLoader("markerLoader");
  94.    _bLoader.addEventListener(Event.COMPLETE, markersLoadedHandler);
  95.    // now load multiple markers (for now its 3)
  96.    for (var i:int = 0; i < _allMarkers.length; i++)
  97.    {
  98.     _bLoader.add(_allMarkers[i].markerSource, {id: "marker_" + i.toString() });
  99.    }
  100.    _bLoader.start();
  101.   }
  102.  
  103.   private function markersLoadedHandler(event:Event):void
  104.   {
  105.    var codes:Array = new Array();
  106.    var sizes:Array = new Array();
  107.    for (var i:int = 0; i < _allMarkers.length; i++)
  108.    {
  109.     var code:FLARCode = new FLARCode(_allMarkers[i].segments, _allMarkers[i].segments, _allMarkers[i].size, _allMarkers[i].size);
  110.     code.loadARPatt(_bLoader.getContent( "marker_" + i.toString()));
  111.     codes.push(code);
  112.     sizes.push(_allMarkers[i].size);
  113.    }
  114.  
  115.    initWebcam();
  116.  
  117.    // create bitmap and bitmapdata where we can draw the webcam into
  118.    var bmd:BitmapData = new BitmapData(500, 500, false, 0);
  119.    _capture = new Bitmap(bmd, PixelSnapping.AUTO,false);
  120.    _capture.width = 500;
  121.    _capture.height = 500;
  122.    addChild(_capture);
  123.  
  124.    _raster = new FLARRgbRaster_BitmapData(_capture.bitmapData);
  125.    _detector = new FLARMultiMarkerDetector(_camParameters, codes, sizes, codes.length);
  126.  
  127.    initFlar();
  128.    initPV3D();
  129.    initListeners();
  130.   }
  131.  
  132.   private function initWebcam():void
  133.   {
  134.    _cam = Camera.getCamera();
  135.    _cam.setMode(500, 500, 60);
  136.    _vid = new Video(500, 500);
  137.    _vid.attachCamera(_cam);
  138.   }
  139.  
  140.   private function initFlar():void
  141.   {
  142.    _flarCam3D = new FLARCamera3D(_camParameters);
  143.    _resultMat = new FLARTransMatResult();
  144.   }
  145.  
  146.   private function initPV3D():void
  147.   {
  148.    _vp = new Viewport3D(500, 500);
  149.    addChild(_vp);
  150.  
  151.    _scene = new Scene3D();
  152.  
  153.    _light = new PointLight3D();
  154.  
  155.    // add a cube or whatever we want to show when pattern is recognised
  156.    // in the basenode (FLARBaseNode, which extends from a DisplayObject3D)
  157.    for (var i:int = 0; i < _allMarkers.length; i++)
  158.    {
  159.     var fmat:FlatShadeMaterial = new FlatShadeMaterial(_light, 0x7DC202 * Math.random(), 0xCCCCCC);
  160.     var cube:Cube = new Cube(new MaterialsList({all: fmat}), 40, 40, 80);
  161.     cube.z = 20;
  162.     cube.name = "cube_" + i.toString();
  163.     var baseNode:FLARBaseNode = new FLARBaseNode();
  164.     baseNode.name = "baseNode_" + i;
  165.     baseNode.addChild(cube);
  166.     _scene.addChild(baseNode);
  167.    }
  168.  
  169.    _renderer = new LazyRenderEngine(_scene, _flarCam3D, _vp);
  170.   }
  171.  
  172.   private function initListeners():void
  173.   {
  174.    addEventListener(Event.ENTER_FRAME, render);
  175.   }
  176.  
  177.   private function render(event:Event):void
  178.   {
  179.    _capture.bitmapData.draw(_vid);
  180.  
  181.    for (var i:int = 0; i< _allMarkers.length; i++)
  182.    {
  183.     if(_detector.detectMarkerLite(_raster, 65) &#038;&#038; _detector.getConfidence(i) > .5)
  184.     {
  185.      _detector.getTransmationMatrix(i, _resultMat);
  186.      FLARBaseNode(_scene.getChildByName("baseNode_" + i)).setTransformMatrix(_resultMat);
  187.      _scene.getChildByName("baseNode_" + i).visible = true;
  188.     }
  189.     else
  190.     {
  191.      _scene.getChildByName("baseNode_" + i).visible = false;
  192.     }
  193.    }
  194.  
  195.    _renderer.render();
  196.   }
  197.  }
  198. }

And last but not least a flash version to play with:

Try it yourself, but don’t forget to download the patterns first.

Brownian Motion + CollisionGrid

Last modified on 2013-01-09 22:08:30 GMT. 3 comments. Top.

brownianmotionwithgridcollisionView experiment.

Started reading Advanced Actionscript 3 Animation written by Keith Peters & Seb Lee-DeLisle (technical reviewer) so here’s a little experiment with grid collision using the FP10 Vector class. Let it run for a while and it creates a nice weird image.

Brownian CollisionDemo:

  1. package
  2. {
  3.  import flash.display.BlendMode;
  4.  import flash.filters.BlurFilter;
  5.  import flash.display.Bitmap;
  6.  import flash.display.BitmapData;
  7.  import flash.events.Event;
  8.  import flash.display.StageScaleMode;
  9.  import flash.display.StageAlign;
  10.  import flash.display.DisplayObject;
  11.  import flash.display.Sprite;
  12.  
  13.  public class CollisionDemo extends Sprite
  14.  {
  15.   private const GRID_SIZE:Number = 30;
  16.   private const RADIUS:Number = 15;
  17.  
  18.   private var _screen:BitmapData = new BitmapData(800, 600, false, 0);
  19.   private var _balls:Vector.<DisplayObject>;
  20.   private var _grid:CollisionGrid;
  21.   private var _numBalls:int = 100;
  22.   private var _ballContainer:Sprite = new Sprite();
  23.  
  24.   public function CollisionDemo()
  25.   {
  26.    stage.align = StageAlign.TOP_LEFT;
  27.    stage.scaleMode = StageScaleMode.NO_SCALE;
  28.  
  29.    addChild(new Bitmap(_screen));
  30.    addChild(_ballContainer);
  31.  
  32.    _grid = new CollisionGrid(stage.stageWidth, stage.stageHeight, GRID_SIZE);
  33.    _grid.drawGrid(graphics, 0, .1);
  34.  
  35.    makeBalls();
  36.  
  37.    addEventListener(Event.ENTER_FRAME, onEnterFrame);
  38.   }
  39.  
  40.   function onEnterFrame(event:Event):void
  41.   {
  42.    updateBalls();
  43.    _grid.check(_balls);
  44.  
  45.    var numChecks:int = _grid.checks.length;
  46.    for(var j:int = 0; j < numChecks; j += 2)
  47.    {
  48.     checkCollision(_grid.checks[j] as Circle, _grid.checks[j + 1] as Circle);
  49.    }
  50.  
  51.    _screen.draw(_ballContainer);
  52.   }
  53.  
  54.   private function makeBalls():void
  55.   {
  56.    _balls = new Vector.<DisplayObject>(_numBalls);
  57.    for(var i:int = 0; i < _numBalls; i++)
  58.    {
  59.     var circle:Circle = new Circle(RADIUS);
  60.     circle.x = Math.random() * stage.stageWidth;
  61.     circle.y = Math.random() * stage.stageHeight;
  62.     circle.vx = Math.random() * 105;
  63.     circle.vy = Math.random() * 105;
  64.     _ballContainer.addChild(circle);
  65.     _balls[i] = circle;
  66.    }
  67.  
  68.    _ballContainer.visible = false;
  69.   }
  70.  
  71.   private function updateBalls():void
  72.   {
  73.    for(var i:int = 0; i < _numBalls; i++)
  74.    {
  75.     var circle:Circle = _balls[i] as Circle;
  76.     circle.update();
  77.  
  78.     circle.vx = Math.random() * 105;
  79.     circle.vy = Math.random() * 105;
  80.  
  81.     if(circle.x < RADIUS)
  82.     {
  83.      circle.x = RADIUS;
  84.      circle.vx *= -1;
  85.     }
  86.     else if(circle.x > stage.stageWidth – RADIUS)
  87.     {
  88.      circle.x = stage.stageWidth – RADIUS;
  89.      circle.vx *= -1;
  90.     }
  91.     if(circle.y < RADIUS)
  92.     {
  93.      circle.y = RADIUS;
  94.      circle.vy *= -1;
  95.     }
  96.     else if(circle.y > stage.stageHeight – RADIUS)
  97.     {
  98.      circle.y = stage.stageHeight – RADIUS;
  99.      circle.vy *= -1;
  100.     }
  101.     circle.color = 0xffffff;
  102.    }
  103.   }
  104.  
  105.   private function checkCollision(circleA:Circle, circleB:Circle):void
  106.   {
  107.    var dx:Number = circleB.x – circleA.x;
  108.    var dy:Number = circleB.y – circleA.y;
  109.    var dist:Number = Math.sqrt(dx * dx + dy * dy);
  110.    if(dist < circleA.radius + circleB.radius)
  111.    {
  112.     circleA.color = 0x7DC202;
  113.     circleB.color = 0x7DC202;
  114.    }
  115.   }
  116.  }
  117. }

CollisionGrid Class:

  1. package
  2. {
  3.  import flash.display.DisplayObject;
  4.  import flash.display.Graphics;
  5.  import flash.events.EventDispatcher;
  6.  
  7.  public class CollisionGrid extends EventDispatcher
  8.  {
  9.   private var _checks:Vector.<DisplayObject>;
  10.   private var _grid:Vector.<Vector.<DisplayObject>>;
  11.   private var _gridSize:Number;
  12.   private var _height:Number;
  13.   private var _width:Number;
  14.   private var _numCells:int;
  15.   private var _numCols:int;
  16.   private var _numRows:int;
  17.  
  18.   public function CollisionGrid(width:Number, height:Number, gridSize:Number)
  19.   {
  20.    _width = width;
  21.    _height = height;
  22.    _gridSize = gridSize;
  23.    _numCols = Math.ceil(_width / _gridSize);
  24.    _numRows = Math.ceil(_height / _gridSize);
  25.    _numCells = _numCols * _numRows;
  26.   }
  27.  
  28.   public function drawGrid(graphics:Graphics, color:int = 0×333333, alpha:Number = 1):void
  29.   {
  30.    graphics.lineStyle(0, color, alpha);
  31.    for (var i:int = 0; i < _width; i += _gridSize)
  32.    {
  33.     graphics.moveTo(i, 0);
  34.     graphics.lineTo(i, _height);
  35.    }
  36.  
  37.    for (var j:int = 0; j < _height; j += _gridSize)
  38.    {
  39.     graphics.moveTo(0, j);
  40.     graphics.lineTo(_width, j);
  41.    }
  42.   }
  43.  
  44.   public function check(objects:Vector.<DisplayObject>):void
  45.   {
  46.    var numObjects:int = objects.length;
  47.    _grid = new Vector.<Vector.<DisplayObject>>(_numCells);
  48.    _checks = new Vector.<DisplayObject>();
  49.    for(var i:int = 0; i < numObjects; i++)
  50.    {
  51.     var obj:DisplayObject = objects[i];
  52.     var index:int = Math.floor(obj.y / _gridSize) * _numCols + Math.floor(obj.x / _gridSize);
  53.     if(_grid[index] == null) _grid[index] = new Vector.<DisplayObject>;
  54.     _grid[index].push(obj);
  55.    }
  56.  
  57.    checkGrid();
  58.   }
  59.  
  60.   private function checkGrid():void
  61.   {
  62.    for (var i:int = 0; i <_numCols; i++)
  63.    {
  64.     for (var j:int = 0; j < _numRows; j++)
  65.     {
  66.      checkOneCell(i,j);
  67.      checkTwoCells(i, j, i + 1, j);  // right
  68.      checkTwoCells(i, j, i – 1, j + 1); // lower left
  69.      checkTwoCells(i, j, i    , j + 1); // lower
  70.      checkTwoCells(i, j, i + 1, j + 1);  // lower right
  71.     }
  72.    }
  73.   }
  74.  
  75.   private function checkOneCell(x:int, y:int):void
  76.   {
  77.    var cell:Vector.<DisplayObject> = _grid[y * _numCols + x];
  78.    if (cell == null) return;
  79.  
  80.    var cellLength:int = cell.length;
  81.    for (var i:int = 0; i < cellLength – 1; i++)
  82.    {
  83.     var objA:DisplayObject = cell[i];
  84.  
  85.     for (var j:int = i + 1; j < cellLength; j++)
  86.     {
  87.      var objB:DisplayObject = cell[j];
  88.      _checks.push(objA, objB);
  89.     }
  90.    }
  91.   }
  92.  
  93.   private function checkTwoCells(x1:int, y1:int, x2:int, y2:int):void
  94.   {
  95.    // make sure cell exists
  96.    if (x2 >= _numCols || x2 < 0 || y2 >= _numRows) return;
  97.  
  98.    var cellA:Vector.<DisplayObject> = _grid[y1 * _numCols + x1];
  99.    var cellB:Vector.<DisplayObject> = _grid[y2 * _numCols + x2];
  100.    if (cellA == null || cellB == null) return;
  101.  
  102.    var cellALength:int = cellA.length;
  103.    var cellBLength:int = cellB.length;
  104.  
  105.    for (var i:int = 0; i < cellALength; i++)
  106.    {
  107.     var objA:DisplayObject = cellA[i];
  108.  
  109.     for(var j:int = 0; j < cellBLength; j++)
  110.     {
  111.      var objB:DisplayObject = cellB[j];
  112.      _checks.push(objA, objB);
  113.     }
  114.    }
  115.   }
  116.  
  117.   public function get checks():Vector.<DisplayObject>
  118.   {
  119.    return _checks;
  120.   }
  121.  }
  122. }

PV3D – Playing with light and cubes

Last modified on 2013-01-09 22:08:30 GMT. 8 comments. Top.

Little thingy in between, playing with light in the most simplest way there is. It has no purpose…, but thought he why not. Click and drag the cube. On click the light will tween out of the center outside the cubes, onrelease move back to the center. At this point i’m still looking around to play with multiple lights so if anyone has suggestions of ideas…leave a message

And here is the code:

  1. package
  2. {
  3.  // tweener
  4.  import gs.easing.Back;
  5.  import caurina.transitions.Tweener;
  6.  
  7.  // flash
  8.  import flash.events.MouseEvent;
  9.  import flash.filters.BlurFilter;
  10.  import flash.events.Event;
  11.  import flash.display.Sprite;
  12.  
  13.  // papervision
  14.  import org.papervision3d.view.BasicView;
  15.  import org.papervision3d.objects.DisplayObject3D;
  16.  import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
  17.  import org.papervision3d.objects.primitives.Cube;
  18.  import org.papervision3d.lights.PointLight3D;
  19.  import org.papervision3d.materials.utils.MaterialsList;
  20.  import org.papervision3d.view.AbstractView;
  21.  import org.papervision3d.core.proto.CameraObject3D;
  22.  import org.papervision3d.core.proto.MaterialObject3D;
  23.  
  24.  [SWF(width="500", height="500", backgroundColor="#000000", frameRate="60")]
  25.  public class LightDemo3D extends Sprite
  26.  {
  27.   //
  28.   // private constants
  29.   //
  30.   private static const GRID_SPACE:int = 50;
  31.   private static const CUBE_SIZE:int = 150;
  32.  
  33.   //
  34.   // private properties
  35.   //
  36.   private var _viewBasic:BasicView;
  37.   private var _mList:MaterialsList;
  38.   private var _pl:PointLight3D;
  39.   private var _flatMat:FlatShadeMaterial;
  40.   private var _mainCube:DisplayObject3D;
  41.   private var _isDown:Boolean;
  42.   private var _prevMouseX:Number;
  43.   private var _prevMouseY:Number;
  44.   private var _cameraPitch:Number = 90;
  45.   private var _cameraYaw:Number = 270;
  46.   private var _cameraTarget:DisplayObject3D;
  47.  
  48.   //////////////////////////////////////////////////////////////////////////////////////
  49.   //
  50.   // Constructor
  51.   //
  52.   //////////////////////////////////////////////////////////////////////////////////////
  53.  
  54.   // ———————————————————————————–
  55.   public function LightDemo3D()
  56.   {
  57.    addEventListener(Event.ADDED_TO_STAGE, initialize);
  58.   }
  59.  
  60.   //////////////////////////////////////////////////////////////////////////////////////
  61.   //
  62.   // Public methods
  63.   //
  64.   //////////////////////////////////////////////////////////////////////////////////////
  65.  
  66.   // ———————————————————————————–
  67.   // none
  68.  
  69.   //////////////////////////////////////////////////////////////////////////////////////
  70.   //
  71.   // Private methods
  72.   //
  73.   //////////////////////////////////////////////////////////////////////////////////////
  74.  
  75.   // ———————————————————————————–
  76.   private function initialize(event:Event):void
  77.   {
  78.    removeEventListener(Event.ADDED_TO_STAGE, initialize);
  79.  
  80.    // setup view
  81.    initView();
  82.  
  83.    // materials
  84.    initMaterials();
  85.  
  86.    // objects
  87.    initObjects();
  88.  
  89.    // listeners
  90.    addEventListener(Event.ENTER_FRAME, render);
  91.  
  92.    stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
  93.    stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
  94.    stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
  95.    stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
  96.   }
  97.  
  98.   private function initView():void
  99.   {
  100.    _viewBasic = new BasicView(800, 600, true, true);
  101.    addChild(_viewBasic);
  102.  
  103.    _viewBasic.viewport.filters = [new BlurFilter(2,2,1)];
  104.  
  105.    // Camera
  106.    _cameraTarget = _viewBasic.scene.addChild(new DisplayObject3D());
  107.    _viewBasic.camera.lookAt(_cameraTarget);
  108.    _viewBasic.camera.z = -1200;
  109.  
  110.    // PointLight
  111.    _pl = new PointLight3D(true);
  112.  
  113.   }
  114.  
  115.   private function initMaterials():void
  116.   {
  117.    _flatMat = new FlatShadeMaterial(_pl, 0x7DC202, 0×000000);
  118.    _flatMat.doubleSided = false;
  119.    _flatMat.fillAlpha = .85;
  120.  
  121.    _mList = new MaterialsList();
  122.    _mList.addMaterial(_flatMat, "all");
  123.   }
  124.  
  125.   private function initObjects():void
  126.   {
  127.    /*
  128.     * create grid of 4x4x4 cubes with a
  129.     * space of 10px between all objects
  130.     */
  131.    var rows:int = 0;
  132.    var cols:int = 0;
  133.    var depth:int = 0;
  134.  
  135.    _mainCube = new DisplayObject3D();
  136.     _viewBasic.scene.addChild(_mainCube);
  137.  
  138.    for (var i:int = 0; i < 64; i++)
  139.    {
  140.     var cube:Cube = new Cube(_mList, CUBE_SIZE, CUBE_SIZE, CUBE_SIZE, 2, 2, 2);
  141.     cube.name = "cube_" + i;
  142.     cube.x = -320 + rows * (CUBE_SIZE + GRID_SPACE);
  143.     cube.y = -320 + cols * (CUBE_SIZE + GRID_SPACE);
  144.     cube.z = -320 + depth * (CUBE_SIZE + GRID_SPACE);
  145.  
  146.     if (++rows > 3)
  147.     {
  148.      rows = 0;
  149.      if (++depth > 3)
  150.      {
  151.       depth = 0;
  152.       cols++;
  153.      }
  154.     }
  155.  
  156.     _mainCube.addChild(cube);
  157.    }
  158.  
  159.    // place light in the center
  160.    _pl.x = _mainCube.x;
  161.    _pl.y = _mainCube.y;
  162.    _pl.z = _mainCube.z;
  163.   }
  164.  
  165.   private function mouseDownHandler(event:MouseEvent):void
  166.   {
  167.    _isDown = true;
  168.    _prevMouseX = event.stageX;
  169.    _prevMouseY = event.stageY;
  170.  
  171.    Tweener.addTween(_pl, {time: 2, z: 1500, transition: Back.easeInOut});
  172.   }
  173.  
  174.   private function mouseUpHandler(event:MouseEvent = null):void
  175.   {
  176.    _isDown = false;
  177.  
  178.    Tweener.addTween(_pl, {time: 2, z: -320, transition: Back.easeInOut});
  179.   }
  180.  
  181.   private function mouseMoveHandler(event:MouseEvent):void
  182.   {
  183.    var differenceX:Number = event.stageX – _prevMouseX;
  184.    var differenceY:Number = event.stageY – _prevMouseY;
  185.  
  186.    if(_isDown)
  187.    {
  188.     // with many thanx to Lee Brimelow
  189.     // blog post: http://pv3d.org/tag/orbit/
  190.     _cameraPitch += differenceY;
  191.     _cameraYaw += differenceX;
  192.  
  193.     _cameraPitch %= 360;
  194.     _cameraYaw %= 360;
  195.  
  196.     _cameraPitch = _cameraPitch > 0 ? _cameraPitch : 0.0001;
  197.     _cameraPitch = _cameraPitch < 90 ? _cameraPitch : 89.9999;
  198.  
  199.     _prevMouseX = event.stageX;
  200.     _prevMouseY = event.stageY;
  201.  
  202.     _viewBasic.camera.orbit(_cameraPitch, _cameraYaw, true, _mainCube);
  203.    }
  204.  
  205.   }
  206.  
  207.   private function mouseLeaveHandler(event:Event):void
  208.   {
  209.    mouseUpHandler();
  210.   }
  211.  
  212.   private function render(event:Event):void
  213.   {
  214.    _viewBasic.singleRender();
  215.   }
  216.  }
  217. }

PV3D – Changing Cube Materials at runtime

Last modified on 2013-01-09 22:08:30 GMT. 3 comments. Top.

A little demo illustrating how to change cube materials at runtime. In this demo you can click to go to the next side of the cube. Or just use your left and right arrow keys,

  1. _sidesLeftToRight = ["back", "right", "front", "left"];
  2. _currpageID = 0;
  3.  
  4. private function updateSkin():void
  5. {
  6.  var faceName:String = _sidesLeftToRight[(_currpageID % _sidesLeftToRight.length)];
  7.  var material:MovieAssetMaterial = new MovieAssetMaterial(_list[_currpageID], true, true, true, true);
  8.  material.animated = true;
  9.  material.doubleSided = true;
  10.  _cube.replaceMaterialByName(material, faceName);
  11. }

Where _list is an array with all the linkId’s to library assets. And _currPageID is updated by using the arrow keys (left & right) or mouse.

Will commit it to codexperience at googlecode soon

Just fun with dragging 3D Object

Last modified on 2013-01-09 22:08:30 GMT. 6 comments. Top.

With many thanx to Andy Zupko. Next step adding more objects to it and apply some physics (JigLibFlash) to it.

[UPDATE] Had to remove ground texture, file became way to big.

  1. /**
  2.  * with many thanx to: Andy Zupko
  3.  */
  4. package
  5. {
  6.  // FLASH
  7.  import flash.filters.BlurFilter;
  8.  import flash.display.Sprite;
  9.  import flash.ui.Mouse;
  10.  import flash.display.Bitmap;
  11.  import flash.events.Event;
  12.  
  13.  // PAPERVISION
  14.  import org.papervision3d.materials.MovieMaterial;
  15.  import org.papervision3d.core.proto.LightObject3D;
  16.  import org.papervision3d.materials.BitmapMaterial;
  17.  import org.papervision3d.materials.special.CompositeMaterial;
  18.  import org.papervision3d.view.layer.util.ViewportLayerSortMode;
  19.  import org.papervision3d.lights.PointLight3D;
  20.  import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
  21.  import org.papervision3d.core.math.Quaternion;
  22.  import org.papervision3d.objects.primitives.Sphere;
  23.  import org.papervision3d.core.math.Plane3D;
  24.  import org.papervision3d.core.math.Number3D;
  25.  import org.papervision3d.objects.DisplayObject3D;
  26.  import org.papervision3d.materials.ColorMaterial;
  27.  import org.papervision3d.objects.primitives.Plane;
  28.  import org.papervision3d.view.BasicView;
  29.  import org.papervision3d.view.layer.ViewportLayer;
  30.  import org.papervision3d.core.proto.MaterialObject3D;
  31.  
  32.  [SWF(width="640", height="480", backgroundColor="#000000", frameRate="60")]
  33.  public class MouseDepth extends BasicView
  34.  {
  35.   private var _plane:Plane;
  36.   private var _lookAt:DisplayObject3D;
  37.   private var _vz:Number = 0;
  38.   private var _vy:Number = 0;
  39.   private var _vx:Number = 0;
  40.   private var _plane3d:Plane3D;
  41.   private var _sphere:Sphere;
  42.   private var _radius:Number = 50;
  43.   private var _light:PointLight3D;
  44.   private var _ground:Plane;
  45.   private var _globalLight:LightObject3D;
  46.   private var _shadowPlane:Plane;
  47.  
  48.   [Embed(source="tennisball.jpg")]
  49.   public var ball:Class;
  50.  
  51.   public function MouseDepth()
  52.   {
  53.    initPapervision();
  54.   }
  55.  
  56.   private function initPapervision():void
  57.   {
  58.    Mouse.hide();
  59.  
  60.    // set sortmode
  61.    viewport.containerSprite.sortMode = ViewportLayerSortMode.INDEX_SORT;
  62.  
  63.    // create light for ball
  64.    _light = new PointLight3D(false);
  65.    _light.y = 300;
  66.  
  67.    // create general light
  68.    _globalLight = new PointLight3D(true);
  69.    _globalLight.y = 400;
  70.    _globalLight.x = 300;
  71.  
  72.    // create plane3d
  73.    _plane3d = new Plane3D();
  74.    _plane3d.setNormalAndPoint(new Number3D(0, 1, 0), new Number3D(0, 0, 0));
  75.  
  76.    // ground
  77.    // add some effect to it
  78.    var gravelFM:FlatShadeMaterial = new FlatShadeMaterial(_globalLight, 0xFFFFFF, 0×333333);
  79.    gravelFM.fillAlpha = .2;
  80.    _ground = new Plane(gravelFM, 2000,2000);
  81.    _ground.rotationX = 90;
  82.    scene.addChild(_ground);
  83.    viewport.getChildLayer(_ground).layerIndex = 0;
  84.  
  85.    // create mouse object
  86.    var cm:ColorMaterial = new ColorMaterial(0×333333);
  87.    cm.fillAlpha = .5;
  88.  
  89.    _plane = new Plane(cm, 50, 50, 2, 2);
  90.    _plane.rotationX = 90;
  91.  
  92.    // -radius, to place the sphere right on top of our plane
  93.    _plane.y = -_radius;
  94.    scene.addChild(_plane);
  95.    viewport.getChildLayer(_plane).layerIndex = 1;
  96.  
  97.    // create materials for sphere
  98.    var bmat:BitmapMaterial = new BitmapMaterial(Bitmap(new ball()).bitmapData, true);
  99.    bmat.tiled = true;
  100.    bmat.smooth = true;
  101.  
  102.    var fm:FlatShadeMaterial = new FlatShadeMaterial(_light, 0xFFFFFF, 0×333333);
  103.    fm.fillAlpha = .5;
  104.  
  105.    var sm:CompositeMaterial = new CompositeMaterial();
  106.    sm.addMaterial(bmat);
  107.    sm.addMaterial(fm);
  108.  
  109.    // create sphere
  110.    _sphere = new Sphere(sm, _radius, 20, 18);
  111.    scene.addChild(_sphere);
  112.    viewport.getChildLayer(_sphere).layerIndex = 3;
  113.  
  114.    // object to look at
  115.    _lookAt = new DisplayObject3D();
  116.    camera.focus = 100;
  117.    camera.zoom = 11;
  118.    camera.lookAt(_lookAt);
  119.  
  120.    // place camera higher up
  121.    camera.y = 800;
  122.  
  123.    createShadow();
  124.  
  125.    // render
  126.    startRendering();
  127.   }
  128.  
  129.   public function createShadow():void
  130.   {
  131.    var floorSprite:Sprite = new Sprite();
  132.    floorSprite.graphics.beginFill(0xdddddd, 0);
  133.    floorSprite.graphics.drawRect(0, 0, 400, 400);
  134.    floorSprite.graphics.endFill();
  135.  
  136.    var shadow:Sprite = new Sprite();
  137.    shadow.graphics.beginFill(0×101010, 1);
  138.    shadow.graphics.drawCircle(0, 0, 100);
  139.    shadow.graphics.endFill();
  140.    floorSprite.addChild(shadow);
  141.  
  142.    shadow.filters = [new BlurFilter(30, 30, 8)];
  143.    shadow.x = 200;
  144.    shadow.y = 200;
  145.  
  146.    _shadowPlane = new Plane(new MovieMaterial(floorSprite, true, false, true), 200, 200, 1, 1);
  147.    _shadowPlane.pitch(90);
  148.    scene.addChild(_shadowPlane);
  149.    _shadowPlane.y = -_radius;
  150.    viewport.getChildLayer(_shadowPlane).layerIndex = 2;
  151.   }
  152.  
  153.   override protected function onRenderTick(event:Event = null):void
  154.   {
  155.    // move plane
  156.    var cameraPosition:Number3D = new Number3D(camera.x, camera.y, camera.z);
  157.  
  158.    //get the direction vector of the mouse position
  159.    var ray:Number3D = camera.unproject(viewport.containerSprite.mouseX, viewport.containerSprite.mouseY);
  160.  
  161.    //convert ray to a 3d point in the ray direction from the camera
  162.    ray = Number3D.add(ray, cameraPosition);
  163.  
  164.    //find the intersection of the line defined by the camera and the ray position with the plane3D
  165.    var intersect:Number3D = _plane3d.getIntersectionLineNumbers(cameraPosition, ray);
  166.  
  167.    //find distance to object and add to velocity
  168.    _vx += (_sphere.x-intersect.x)/1200;
  169.    _vy += (_sphere.y-intersect.y)/100;
  170.    _vz += (_sphere.z-intersect.z)/1200;
  171.  
  172.    // update vel
  173.    _vx *= .98;
  174.    _vy *= .94;
  175.    _vz *= .98;
  176.  
  177.    // move out plane to mouse coordinates
  178.    _plane.x -= (_plane.x – intersect.x)/4;
  179.    _plane.z -= (_plane.z – intersect.z)/4;
  180.  
  181.    // apply vel
  182.    _sphere.x -= _vx;
  183.    _sphere.y -= _vy;
  184.    _sphere.z -= _vz;
  185.  
  186.    // move shadow allong with sphere
  187.    _shadowPlane.x = _sphere.x;
  188.    _shadowPlane.z = _sphere.z;
  189.  
  190.    // move light with ball
  191.    _light.x = _sphere.x;
  192.    _light.z = _sphere.z;
  193.  
  194.    // the function written by Andy Zupko (blog.zupko.info), so usefull!
  195.    rollMe(_vx, _vy, _vz);
  196.  
  197.    super.onRenderTick(event);
  198.   }
  199.  
  200.   private function rollMe(vx:Number, vy:Number, vz:Number):void
  201.   {
  202. //   var pos:Number3D = new Number3D(_sphere.x, _sphere.y, _sphere.z);
  203.    var dif:Number3D = new Number3D(-vx, -vy, -vz);
  204.    var dist:Number = Math.sqrt(dif.x*dif.x+dif.z*dif.z);
  205.  
  206.    //find the cross of the up axis with the direction vector
  207.    var rotAxis:Number3D = Number3D.cross(dif, new Number3D(0, 1, 0));
  208.    rotAxis.normalize();
  209.  
  210.    //rotate around that axis by how long the direction vector is relative to the radius
  211.    var rotation:Quaternion = Quaternion.createFromAxisAngle(rotAxis.x, rotAxis.y, rotAxis.z, dist/_radius);
  212.    rotation.normalize();
  213.  
  214.    _sphere.transform.calculateMultiply3x3(rotation.matrix, _sphere.transform);
  215.   }
  216.  }
  217. }

JigLib Flash + Papervision3D Demo

Last modified on 2013-01-09 22:08:54 GMT. 2 comments. Top.

I had to play immediately with the JigLibFlash library. Like always there is a learning curve, but the syntax is at least better written/understandable than Box2DFlash, which doesn’t mean that I don’t like Box2DFlash, cause I do!

In this example you use the mouse to move the magenta ball, when you keep your mouse at the center of the stage you don’t apply any speed to the magenta ball. All the balls can drop of the floor on the front side. Have FUN!

  1. /**
  2.  * @author janwillemwisman
  3.  *
  4.  * positioning 3d papervision objects, only via the jBox.moveTo,
  5.  * otherwise object will be centered when added to the PhysicsSystem.
  6.  *
  7.  * when you dont use physicsStep, jBoxes will not be place correctly. nothing will happen basically
  8.  */
  9. package
  10. {
  11.  // flash
  12.  import flash.utils.getTimer;
  13.  import flash.events.Event;
  14.  import flash.display.Sprite;
  15.  
  16.  // wismanas3lib
  17.  import nl.wisman.utils.MathExt;
  18.  
  19.  // papervision
  20.  import org.papervision3d.cameras.Camera3D;
  21.  import org.papervision3d.lights.PointLight3D;
  22.  import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
  23.  import org.papervision3d.materials.utils.MaterialsList;
  24.  import org.papervision3d.objects.DisplayObject3D;
  25.  import org.papervision3d.objects.primitives.Cube;
  26.  import org.papervision3d.objects.primitives.Sphere;
  27.  import org.papervision3d.render.BasicRenderEngine;
  28.  import org.papervision3d.scenes.Scene3D;
  29.  import org.papervision3d.view.Viewport3D;
  30.  import org.papervision3d.view.layer.ViewportLayer;
  31.  import org.papervision3d.view.layer.util.ViewportLayerSortMode;
  32.  
  33.  // jiglibflash
  34.  import jiglib.physics.PhysicsSystem;
  35.  import jiglib.math.JMatrix3D;
  36.  import jiglib.math.JNumber3D;
  37.  import jiglib.geometry.JSphere;
  38.  import jiglib.geometry.JBox;
  39.  
  40.  public class JigLibDemo extends Sprite
  41.  {
  42.   //
  43.   // private  properties
  44.   //
  45.   private var _scene:Scene3D;
  46.   private var _viewport:Viewport3D;
  47.   private var _renderer:BasicRenderEngine;
  48.   private var _sceneLight:PointLight3D;
  49.   private var _camera:Camera3D;
  50.   private var _cameraTarget:DisplayObject3D;
  51.   private var _newTime:int;
  52.   private var _deltaTime:Number;
  53.   private var _currentTime:Number;
  54.   private var _physicsSpeed:Number = 10;
  55.   private var _speedBall:int = 10;
  56.   private var _maxBall:Number = 10;
  57.   private var _jBalls:Array;
  58.  
  59.   //////////////////////////////////////////////////////////////////////////////////////
  60.   //
  61.   // Constructor
  62.   //
  63.   //////////////////////////////////////////////////////////////////////////////////////
  64.  
  65.   // ———————————————————————————–
  66.   public function JigLibDemo()
  67.   {
  68.    addEventListener(Event.ADDED_TO_STAGE, initialize);
  69.   }
  70.  
  71.   //////////////////////////////////////////////////////////////////////////////////////
  72.   //
  73.   // Public methods
  74.   //
  75.   //////////////////////////////////////////////////////////////////////////////////////
  76.  
  77.   // ———————————————————————————–
  78.   // none
  79.  
  80.   //////////////////////////////////////////////////////////////////////////////////////
  81.   //
  82.   // Private methods
  83.   //
  84.   //////////////////////////////////////////////////////////////////////////////////////
  85.  
  86.   // ———————————————————————————–
  87.   private function initialize(event:Event):void
  88.   {
  89.    removeEventListener(Event.ADDED_TO_STAGE, initialize);
  90.  
  91.    // setup
  92.    _currentTime = getTimer();
  93.  
  94.    initPapervision3D();
  95.    initArea();
  96.    init3DObjects();
  97.    setupEventListeners();
  98.   }
  99.  
  100.   // ———————————————————————————–
  101.   private function initPapervision3D():void
  102.   {
  103.    _scene = new Scene3D();
  104.    _viewport = new Viewport3D(0,0,true);
  105.    addChild(_viewport);
  106.  
  107.    // set _viewport sortmode to index
  108.    _viewport.containerSprite.sortMode = ViewportLayerSortMode.INDEX_SORT;
  109.  
  110.    _renderer = new BasicRenderEngine();
  111.  
  112.    // light settings
  113.    _sceneLight = new PointLight3D(true, true);
  114.    _sceneLight.x = 0;
  115.    _sceneLight.y = 400;
  116.    _sceneLight.z = -300;
  117.  
  118.    // _camera settings
  119.    _camera = new Camera3D();
  120.    _camera.x = 0;
  121.    _camera.y = 450;
  122.    _camera.z = -1000;
  123.    _camera.zoom = 5;
  124.    _camera.focus = 100;
  125.  
  126.    // _camera target, helper object to make the _camera a target type
  127.    _cameraTarget=new DisplayObject3D();
  128.    _cameraTarget.x=0;
  129.    _cameraTarget.y=250;
  130.    _cameraTarget.z=0;
  131.    // set the _camera target
  132.    _camera.target = _cameraTarget;
  133.   }
  134.  
  135.   // ———————————————————————————–
  136.   private function initArea():void
  137.   {
  138.    // general material
  139.    var materialGround:MaterialsList = new MaterialsList();
  140.    materialGround.addMaterial(new FlatShadeMaterial(_sceneLight, 0×999999), "all");
  141.  
  142.    // create back wall
  143.    var backWall3D:Cube = new Cube(materialGround, 1000, 50, 1000, 2, 2, 2);
  144.    _scene.addChild(backWall3D);
  145.  
  146.    var vplBackWall3D:ViewportLayer = _viewport.getChildLayer(backWall3D);
  147.    vplBackWall3D.layerIndex = 1;
  148.  
  149.    var jBackWall:JBox = new JBox(backWall3D, false, 1000, 50, 1000);
  150.    jBackWall.MoveTo( new JNumber3D(0, 0, 500), JMatrix3D.IDENTITY);
  151.    PhysicsSystem.getInstance().AddBody(jBackWall);
  152.  
  153.    // create left wall
  154.    var leftWall3D:Cube = new Cube(materialGround, 50, 1000, 1000, 2, 2, 2);
  155.    _scene.addChild(leftWall3D);
  156.  
  157.    var vplLeftWall3D:ViewportLayer = _viewport.getChildLayer(leftWall3D);
  158.    vplLeftWall3D.layerIndex = 2;
  159.  
  160.    var jLeftWall:JBox = new JBox(leftWall3D, false, 50, 1000, 1000);
  161.    jLeftWall.MoveTo( new JNumber3D(500, 0, 0), JMatrix3D.IDENTITY);
  162.    PhysicsSystem.getInstance().AddBody(jLeftWall);
  163.  
  164.    // create right wall
  165.    var rightWall3D:Cube = new Cube(materialGround, 50, 1000, 1000, 2, 2, 2);
  166.    _scene.addChild(rightWall3D);
  167.  
  168.    var vplRightWall3D:ViewportLayer = _viewport.getChildLayer(rightWall3D);
  169.    vplRightWall3D.layerIndex = 3;
  170.  
  171.    var jRightWall:JBox = new JBox(rightWall3D, false, 50, 1000, 1000);
  172.    jRightWall.MoveTo( new JNumber3D(-500, 0, 0), JMatrix3D.IDENTITY);
  173.    PhysicsSystem.getInstance().AddBody(jRightWall);
  174.  
  175.    // Ground pv3d
  176.    var pv3dGround:Cube = new Cube(materialGround,1000,1000,50,2,2,2);
  177.    _scene.addChild(pv3dGround);
  178.  
  179.    // Viewport layer ground
  180.    var vplGround:ViewportLayer = _viewport.getChildLayer(pv3dGround);
  181.    vplGround.layerIndex = 4;
  182.  
  183.    // Ground physics
  184.    var jGround:JBox = new JBox(pv3dGround,false,1000,1000,50);
  185.    PhysicsSystem.getInstance().AddBody(jGround);
  186.   }
  187.  
  188.   // ———————————————————————————–
  189.   private function init3DObjects():void
  190.   {
  191.    // VIEWPORT LAYER OBJECTS
  192.    // balls boxes chain sphere will be placed on it
  193.    var vplObjects:ViewportLayer = new ViewportLayer(_viewport,null);
  194.    vplObjects.layerIndex = 4;
  195.    vplObjects.sortMode = ViewportLayerSortMode.Z_SORT; // sort mode for this viewportlayer based on z
  196.    _viewport.containerSprite.addLayer(vplObjects);
  197.  
  198.    _jBalls = new Array();
  199.    for (var i:int = 0; i < _maxBall; i++)
  200.    {
  201.     // create sphere
  202.     var colorSphere:uint = (i == 0)?0xe20074:0xeeee00;
  203.     var pv3dBall:Sphere = new Sphere( new FlatShadeMaterial(_sceneLight, colorSphere) ,50,20,16);
  204.  
  205.     // add sphere to viewportlayer for objects
  206.     vplObjects.addDisplayObject3D(pv3dBall);
  207.  
  208.     // add to _scene
  209.     _scene.addChild(pv3dBall);
  210.  
  211.     // add papervision sphere to jSphere
  212.     _jBalls[i] = new JSphere(pv3dBall,true,50);
  213.     _jBalls[i].MoveTo(new JNumber3D(MathExt.random(-100, 250), MathExt.random(400, 650), MathExt.random(100, 350)), JMatrix3D.IDENTITY); // start position x,y,z
  214.  
  215.     // add to physicsSystem
  216.     PhysicsSystem.getInstance().AddBody(_jBalls[i]);
  217.    }
  218.   }
  219.  
  220.   // ———————————————————————————–
  221.   private function setupEventListeners():void
  222.   {
  223.    addEventListener(Event.ENTER_FRAME, update);
  224.   }
  225.  
  226.   // ———————————————————————————–
  227.   private function update(event:Event):void
  228.   {
  229.    moveBall();
  230.    physicsStep();
  231.    checkFallenObjects();
  232.    _renderer.renderScene( _scene, _camera, _viewport );
  233.   }
  234.  
  235.   // Calculate the deltaTime
  236.   // ————————————————————————
  237.   private function physicsStep():void
  238.   {
  239.             _newTime = getTimer();
  240.             _deltaTime = ((_newTime – _currentTime) / 1000) * _physicsSpeed;
  241.             _currentTime = _newTime;
  242.           PhysicsSystem.getInstance().Integrate(_deltaTime); // phyisc step 5 is the speed
  243.   }
  244.  
  245.   // ———————————————————————————–
  246.   private function checkFallenObjects():void
  247.   {
  248.    for (var i:String in _jBalls)
  249.    {
  250.     if (_jBalls[i].CurrentState.Position.y < -50)
  251.     {
  252.      _jBalls[i].MoveTo(new JNumber3D(MathExt.random(-100, 250), MathExt.random(400, 650), MathExt.random(100, 350)), JMatrix3D.IDENTITY); // reposition balls
  253.     }
  254.    }
  255.   }
  256.  
  257.   // ———————————————————————————–
  258.   private function moveBall():void
  259.   {
  260.    // area left
  261.    if (mouseX < 350)
  262.    {
  263.     _jBalls[0].AddWorldForce(new JNumber3D(-_speedBall,0,0), _jBalls[0].CurrentState.Position);
  264.    }
  265.    // area right
  266.    if (mouseX > 450)
  267.    {
  268.     _jBalls[0].AddWorldForce(new JNumber3D(_speedBall,0,0), _jBalls[0].CurrentState.Position);
  269.    }
  270.    // top area
  271.    if (mouseY < 250)
  272.    {
  273.     _jBalls[0].AddWorldForce(new JNumber3D(0,0,_speedBall), _jBalls[0].CurrentState.Position);
  274.    }
  275.    // bottom area
  276.    if (mouseY > 350)
  277.    {
  278.     _jBalls[0].AddWorldForce(new JNumber3D(0,0,-_speedBall), _jBalls[0].CurrentState.Position);
  279.    }
  280.   }
  281.  }
  282. }

Papervision3D + Loading Collada

Last modified on 2013-01-09 22:08:55 GMT. 2 comments. Top.

Playing around with collada (dae) files which use textures. You can get lots of models at google’s 3D warehouse, check it and start playing around with it. Its really easy!

package
{
	// import flash
	import flash.filters.BlurFilter;
	import flash.display.StageScaleMode;
	import flash.display.StageAlign;
	import flash.display.Sprite;
	import flash.events.Event;	

	//import main papervision assets
	import org.papervision3d.cameras.Camera3D;
	import org.papervision3d.lights.PointLight3D;
	import org.papervision3d.render.QuadrantRenderEngine;
	import org.papervision3d.scenes.Scene3D;
	import org.papervision3d.view.Viewport3D;

	//import objects
	import org.papervision3d.objects.DisplayObject3D;
	import org.papervision3d.objects.parsers.DAE;

	//import event listener
	import org.papervision3d.events.FileLoadEvent;

	public class EifelTowerCollada extends Sprite
	{
		//papervision main assets
		private var scene:Scene3D;
		private var viewport:Viewport3D;
		private var camera:Camera3D;
		private var light:PointLight3D;
		private var quadRenderer:QuadrantRenderEngine;

		//other things needed for dae
		public var universe:DisplayObject3D;
		private var daeFile:DAE;
		private var bl:Number;
		private var bt:Number;
		private var per:Number;

		//////////////////////////////////////////////////////////////////////////////////////
		//
		// Constructor
		//
		//////////////////////////////////////////////////////////////////////////////////////

		// -----------------------------------------------------------------------------------
		public function EifelTowerCollada()
		{
			addEventListener(Event.ADDED_TO_STAGE, initialize);
		}

		// -----------------------------------------------------------------------------------
		// constructor listener
		private function initialize(event:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, initialize);

			// blur for more realness
			filters = [new BlurFilter(1.5,1.5,3)];

			//Setup stage.
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.quality = "BEST";

			//Setup viewport, add to stage
			viewport = new Viewport3D(0,0,true);
			addChild(viewport);

			//Setup renderer
			quadRenderer = new QuadrantRenderEngine(1);

			//Setup camera
			camera = new Camera3D();
			camera.y = 100;
			camera.z = -200;

			//Setup light
			light = new PointLight3D(true);
			light.x = 0;
			light.y = 500;//camera.y;
			light.z = -200;//camera.z;

			//Setup scene
			scene = new Scene3D();

			//add dae object
			daeFile = new DAE();
			daeFile.load("daefiles/eifelTower.dae");

			// scale
			daeFile.y = -100;

			//add loading listeners to your dae
			daeFile.addEventListener(FileLoadEvent.LOAD_COMPLETE, handleLoadComplete);
			daeFile.addEventListener(FileLoadEvent.LOAD_ERROR, handleLoadError);
			daeFile.addEventListener(FileLoadEvent.LOAD_PROGRESS, handleProgress);
			daeFile.addEventListener(FileLoadEvent.SECURITY_LOAD_ERROR, handleSecurity);
			daeFile.addEventListener(FileLoadEvent.COLLADA_MATERIALS_DONE, handleMaterialsDone);

			//Setup container, add dae to container, add container to scene.
			universe = new DisplayObject3D();
			universe.addChild(daeFile);
			scene.addChild(universe);

			//Listen to enter frame
			addEventListener(Event.ENTER_FRAME, handleRender);
		}

		private function handleLoadComplete(e:Event):void
		{
			trace("IN EVENT LISTENER, LOAD COMPLETE");
		};

		private function handleLoadError(e:Event):void
		{
			trace("THERE HAS BEEN A LOADING ERROR");
		};

		private function handleProgress(e:Event):void
		{
			bl = e.target.bytesLoaded;
			bt = e.target.bytesTotal;
			per = Math.round(bl/bt*100);
			trace("COLLADA "+per+"% LOADED, PLEASE WAIT");
		};

		private function handleSecurity(e:Event):void
		{
			trace("THERE HAS BEEN A SECURITY ERROR");
		};

		private function handleMaterialsDone(e:Event):void
		{
			trace("COLLADA MATERIALS LOAD COMPLETE");
		};

		// _______________________________________________________________________
		// render on enterframe

		private function handleRender(e:Event):void
		{
			camera.lookAt(universe);
			quadRenderer.renderScene(scene, camera, viewport);
		}
	}
}

Now add the object to your stage

_eifelTower = new EifelTowerCollada();
addChild(_eifelTower);

Fun with Ribbons3D

Last modified on 2013-01-09 22:08:55 GMT. 0 comments. Top.

experiment_3d_line

Old experiment I found with the ribbon3D class thought might as well post it. With many thanx to Soulwire for writing this class. Based on where your mouse positions it tweens to that location via bezier points.

  1. package
  2. {
  3.  // papervision
  4.  import org.papervision3d.core.effects.view.ReflectionView;
  5.  import org.papervision3d.lights.PointLight3D;
  6.  import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
  7.  import org.papervision3d.objects.DisplayObject3D;
  8.  
  9.  // tweenmax
  10.  import gs.TweenMax;
  11.  import gs.easing.Linear;
  12.  
  13.  // flash
  14.  import flash.display.DisplayObjectContainer;
  15.  import flash.events.Event;
  16.  import flash.filters.BlurFilter;
  17.  
  18.  
  19.  public class CirclingRibbon extends ReflectionView
  20.  {
  21.   private var _light:PointLight3D;
  22.   private var _ribbon:Ribbon3D;
  23.   private var _universe:DisplayObject3D;
  24.   private var _centerX:Number = 0;
  25.   private var _centerY:Number = 0;
  26.   private static const UNIVERSE:Number = 500;
  27.  
  28.   public function CirclingRibbon()
  29.   {
  30.    initialize();
  31.   }
  32.  
  33.   private function initialize():void
  34.   {
  35.    // setup reflection
  36.    viewportReflection.filters = [new BlurFilter(6,6,1)];
  37.    setReflectionColor(.25, .25, .25);
  38.    surfaceHeight = -400;
  39.    
  40.    camera.z = -1500;
  41.    
  42.    // light
  43.    _light = new PointLight3D();
  44.    _light.x = camera.x;
  45.    _light.y = camera.y500;
  46.    _light.z = -camera.z;
  47.    
  48.    viewport.filters = [new BlurFilter(2,2,1)];
  49.    
  50.    // universe
  51.    _universe = new DisplayObject3D();
  52.    scene.addChild(_universe);
  53.    
  54.    // setup line material
  55.    var fMat:FlatShadeMaterial = new FlatShadeMaterial(_light, 0XE20074, 0xF7F7F7);
  56.    fMat.doubleSided = true;
  57.    
  58.    // setup line
  59.    _ribbon = new Ribbon3D(fMat, 40, 40);
  60.    _universe.addChild(_ribbon);
  61.    
  62.    addEventListener(Event.ENTER_FRAME, update);
  63.    
  64.    tween(_ribbon);
  65.   }
  66.  
  67.   public function setStage(inClip:DisplayObjectContainer)
  68.   {
  69.    _centerX = inClip.stage.stageWidth * .5;
  70.    _centerY = inClip.stage.stageHeight * .5;
  71.   }
  72.  
  73.   private function tween(object:Ribbon3D):void
  74.   {
  75.    if(object is Ribbon3D)
  76.    {
  77.     var b:Array = new Array();
  78.     var d:int = random( 3, 6 );
  79.     for (var i:int = 0; i < d * .6 << 0; i++)
  80.     {
  81.      b.push( {
  82.        x:random( -UNIVERSE, UNIVERSE ),
  83.        y:400, // we don't want this to be lower than the reflectionViews surface
  84.        z:random( -UNIVERSE, UNIVERSE )
  85.        } );
  86.     }
  87.    
  88.     var posX:Number = -_centerX + mouseX;
  89.     var posY:Number = _centerY + -mouseY;
  90.     var posZ:Number = (_ribbon.x – _ribbon.y) * 2;
  91.     TweenMax.to(_ribbon, 1, {x:posX, y:posY, z:posZ, ease:Linear.easeNone, bezierThrough:b, onComplete: tween, onCompleteParams: [object] });
  92.    }
  93.   }
  94.  
  95.   private function update(event:Event):void
  96.   {
  97.    _ribbon.draw();
  98.    _universe.yaw(1);
  99.    camera.lookAt(_universe);
  100.    singleRender();
  101.   }
  102.  
  103. // ———————————————————————————–
  104.   public static function random( min:Number, max:Number = NaN ):Number
  105.   {
  106.    if (isNaN(max)) { max = min; min = 0; }
  107.    return Math.random() * (maxmin) + min;
  108.   }
  109.  }
  110. }

Now add it to your stage and set the stage:

  1. var cRibbon:CirclingRibbon = new CirclingRibbon();
  2. cRibbon.setStage(this);
  3. addChild(cRibbon);

3D World – SimpleDemo

Last modified on 2013-01-09 22:08:55 GMT. 4 comments. Top.

experiment_se

Simple demo showing the world in 3D, using a bitmap as texture combined with a phongshader and a shadedmaterial which combines the bitmap and the phongshader. For sure its not new, but its still fun.

Here’s the code:

  1. package
  2. {
  3.  // tweenmax
  4. import gs.easing.Back;
  5.  import gs.TweenMax;
  6.  
  7.  // papervision
  8.  import org.papervision3d.materials.shaders.ShadedMaterial;
  9.  import org.papervision3d.materials.shaders.PhongShader;
  10.  import org.papervision3d.core.effects.view.ReflectionView;
  11.  import org.papervision3d.lights.PointLight3D;
  12.  import org.papervision3d.materials.BitmapMaterial;
  13.  import org.papervision3d.objects.primitives.Sphere;
  14.  
  15.  // flash
  16.  import flash.filters.BlurFilter;
  17.  import flash.display.BitmapData;
  18.  import flash.events.Event;
  19.  
  20.  public class BitmapEarth extends ReflectionView
  21.  {
  22.   private var _light:PointLight3D;
  23.   private var _sphere:Sphere;
  24.  
  25.   public function BitmapEarth()
  26.   {
  27.    initialize();
  28.   }
  29.  
  30.   private function initialize():void
  31.   {
  32.    // setup reflection
  33.    viewportReflection.filters = [new BlurFilter(6,6,1)];
  34.    setReflectionColor(.5, .5, .5);
  35.    surfaceHeight = -200;
  36.  
  37.    // camera
  38.    camera.z = -300;
  39.  
  40.    // create light
  41.    _light = new PointLight3D();
  42.  
  43.    // create bitmap material from library asset
  44.    var bmClass:Class = getDefinitionByName("EarthTexture") as Class;
  45.    var bmd:BitmapData = new bmClass(0,0);
  46.    var bMaterial:BitmapMaterial = new BitmapMaterial(bmd, true);
  47.  
  48.    // create shader
  49.    var pShader:PhongShader = new PhongShader(_light, 0xFFFFFF, 0×666666, 20);
  50.  
  51.    //create shaded material from my bitmap from library and the phongshader
  52.    var shadedMaterial:ShadedMaterial = new ShadedMaterial(bMaterial, pShader);
  53.  
  54.    // create sphere and apply shaded material
  55.    _sphere = new Sphere(shadedMaterial, 100, 24, 18);
  56.    _sphere.x = 700;
  57.    _sphere.z = -1200;
  58.    scene.addChild(_sphere);
  59.  
  60.    // render
  61.    addEventListener(Event.ENTER_FRAME, update);
  62.  
  63.    // move sphere to center
  64.    TweenMax.to(_sphere, 5, {x: 0, y: 0, z: 0, ease: Back.easeOut});
  65.   }
  66.  
  67.   private function update(event:Event):void
  68.   {
  69.    camera.lookAt(_sphere);
  70.  
  71.    _sphere.yaw(1.5); // y-axis
  72. //   _sphere.pitch(1.25); // x-axis
  73. //   _sphere.roll(1);// z-axis
  74.  
  75.    singleRender();
  76.   }
  77.  }
  78. }

The only thing you have to do now is add it to your stage:

  1. var earth:BitmapEarth = new BitmapEarth();
  2. addChild(earth);

GoogleMaps API – SimpleDemo

Last modified on 2013-01-09 22:08:55 GMT. 0 comments. Top.

experiment_gm_v001

Simple demo showing google maps in flash, add a marker as an overlay with a listener to open its information window. (Up at codexperiments.googlecode.com).

  1. package
  2. {
  3.  // flash
  4.  import flash.geom.Point;
  5.  import flash.events.Event;
  6.  import flash.display.MovieClip;
  7.  
  8.  // google maps
  9.  import com.google.maps.Map;
  10.  import com.google.maps.MapEvent;
  11.  import com.google.maps.MapType;
  12.  import com.google.maps.LatLng;
  13.  import com.google.maps.InfoWindowOptions;
  14.  import com.google.maps.MapOptions;
  15.  import com.google.maps.overlays.Marker;
  16.  import com.google.maps.MapMouseEvent;
  17.  import com.google.maps.controls.NavigationControl;
  18. import com.google.maps.controls.MapTypeControl;
  19.  
  20.  public class ShowMapsDemo extends MovieClip
  21.  {
  22.   private var _map:Map;
  23.   private var _marker:Marker;
  24.  
  25.   public function ShowMapsDemo()
  26.   {
  27.    addEventListener(Event.ADDED_TO_STAGE, initialize);
  28.   }
  29.  
  30.   private function initialize(event:Event):void
  31.   {
  32.    removeEventListener(Event.ADDED_TO_STAGE, initialize);
  33.  
  34.    // setup google map
  35.    _map = new Map();
  36.  
  37.    // place your own googlemaps api key at:http://code.google.com/apis/maps/signup.html
  38.    _map.key = "your googlemaps api key goes here";
  39.    _map.setSize(new Point(550, 400));
  40.    _map.addEventListener(MapEvent.MAP_PREINITIALIZE, mapPreInitializeHandler);
  41.    _map.addEventListener(MapEvent.MAP_READY, mapReadyHandler);
  42.    _map.addControl(new NavigationControl());
  43.    _map.addControl(new MapTypeControl());
  44.  
  45.    // add to stage
  46.    addChild(_map);
  47.   }
  48.  
  49.   private function mapReadyHandler(event:MapEvent):void
  50.   {
  51.    _marker = new Marker(new LatLng(52.365983,4.80757));
  52.    _marker.addEventListener(MapMouseEvent.CLICK, onMarkerClicked);
  53.    _map.addOverlay(_marker);
  54.  
  55.    onMarkerClicked();
  56.   }
  57.  
  58.   private function mapPreInitializeHandler(event:MapEvent):void
  59.   {
  60.    _map.removeEventListener(MapEvent.MAP_PREINITIALIZE, mapPreInitializeHandler);  
  61.  
  62.    var mapOptions:MapOptions = new MapOptions();
  63.    mapOptions.center = new LatLng(52.365983,4.80757);
  64.    mapOptions.zoom = 17;
  65.    mapOptions.mapType = MapType.SATELLITE_MAP_TYPE;
  66.    _map.setInitOptions(mapOptions);
  67.   }
  68.  
  69.   private function onMarkerClicked(event:MapMouseEvent = null):void
  70.   {
  71.    _marker.openInfoWindow(new InfoWindowOptions({title: "Home sweet home", content: "Ooh no, my house isn't available!!"}));
  72.   }
  73.  }
  74. }

Papervision3D Multiple Objects hitTest

Last modified on 2013-01-09 22:08:55 GMT. 1 comment. Top.

experiment_3D_v004

A little research on hitTest with multiple objects. You could imagine what you could do with it, for instance create a game like Guitar Hero (with a setup like this that is).

Code is now committed at codexperiments.googlecode.com, hope you enjoy it

If you want to add more hitArea’s (planes) on the stage to do hitTests with use for instance the following line of code:_world.addHitArea(0x0000FF, 500, -25, 600);.

experiment_3D_v006
1. Click here to see it in action with multiple hitarea’s

experiment_3D_v005
2. And add some nice reflections, and it will look like this

Code of the reflection version:

Main Class

  1. /**
  2.  * @author janwillemwisman
  3.  * We have 3 lanes, in this case: -500, 0 and 500
  4.  */
  5. package
  6. {
  7.  // wismanas3lib
  8.  import nl.wisman.utils.MathExt;
  9.  import nl.wisman.components.Slider;
  10.  
  11.  // flash
  12.  import flash.events.TimerEvent;
  13.  import flash.utils.Timer;
  14.  import flash.events.Event;
  15.  import flash.display.MovieClip;
  16.  
  17.  public class DemoHitTestReflection extends MovieClip
  18.  {
  19.   //
  20.   // on stage
  21.   //
  22.   public var thumb:MovieClip;
  23.   public var track:MovieClip;
  24.  
  25.   //
  26.   // private  properties
  27.   //
  28.   private var _world:GuitarHeroSetupReflection;
  29.   private var _leftLaneTimer:Timer;
  30.   private var _centerLaneTimer:Timer;
  31.   private var _rightLaneTimer:Timer;
  32.  
  33.   // wismanas3lib
  34.   private var _slider:Slider;
  35.  
  36.   //////////////////////////////////////////////////////////////////////////////////////
  37.   //
  38.   // Constructor
  39.   //
  40.   //////////////////////////////////////////////////////////////////////////////////////
  41.      
  42.   // ———————————————————————————–
  43.   public function DemoHitTestReflection()
  44.   {
  45.    addEventListener(Event.ADDED_TO_STAGE, initialize);
  46.   }
  47.  
  48.   //////////////////////////////////////////////////////////////////////////////////////
  49.   //
  50.   // Public methods
  51.   //
  52.   //////////////////////////////////////////////////////////////////////////////////////
  53.  
  54.   // ———————————————————————————–
  55.   // none
  56.  
  57.   //////////////////////////////////////////////////////////////////////////////////////
  58.   //
  59.   // Private methods
  60.   //
  61.   //////////////////////////////////////////////////////////////////////////////////////
  62.  
  63.   // ———————————————————————————–
  64.   private function initialize(event:Event):void
  65.   {
  66.    removeEventListener(Event.ADDED_TO_STAGE, initialize);
  67.    
  68.    // create world
  69.    _world = new GuitarHeroSetupReflection();
  70.    
  71.    // set start and end points
  72.    _world.startPointZ = 2000;
  73.    _world.endPointZ = -1000;
  74.    
  75.    // set hitarea positions
  76.    // (back) 1000 -> 0 -> -1000 (front) on z-axis
  77.    // left
  78.    _world.addHitArea(0xFF0000, -500, -25, 1200);
  79.    _world.addHitArea(0xFF0000, -500, -25, 0);
  80.    // center
  81.    _world.addHitArea(0xFFFFFF, 0, -25, 900);
  82.    _world.addHitArea(0xFFFFFF, 0, -25, 0);
  83.    // right
  84.    _world.addHitArea(0x0000FF, 500, -25, 1600);
  85.    _world.addHitArea(0x0000FF, 500, -25, 600);
  86.    _world.addHitArea(0x0000FF, 500, -25, 0);
  87.    
  88.    // initialize timers
  89.    _leftLaneTimer = new Timer(1000);
  90.    _leftLaneTimer.addEventListener(TimerEvent.TIMER, leftLaneTimerHandler);
  91.    _leftLaneTimer.start();
  92.    
  93.    _centerLaneTimer = new Timer(2000);
  94.    _centerLaneTimer.addEventListener(TimerEvent.TIMER, centerLaneTimerHandler);
  95.    _centerLaneTimer.start();
  96.    
  97.    _rightLaneTimer = new Timer(3000);
  98.    _rightLaneTimer.addEventListener(TimerEvent.TIMER, rightLaneTimerHandler);
  99.    _rightLaneTimer.start();
  100.  
  101.    // add to stage
  102.    addChild(_world);
  103.    
  104.    // Slider
  105.    _slider = new Slider(stage, thumb, track);
  106.    _slider.restricted = true;
  107.    _slider.friction = .90;
  108.    _slider.addEventListener(Event.CHANGE, sliderUpdate);
  109.   }
  110.  
  111.   // ———————————————————————————–
  112.   private function sliderUpdate(event:Event):void
  113.   {
  114.    var rot:Number = _slider.percentage;
  115.    
  116.    // only from front to back (1.8 instead of 3.6)
  117.    _world.universe.rotationY = rot * 1.8;
  118.   }
  119.  
  120.   // ———————————————————————————–
  121.   private function leftLaneTimerHandler(event:TimerEvent):void
  122.   {
  123.    _world.addNote(0xFF0000, -500, 0, MathExt.random(1, 4));
  124.   }
  125.  
  126.   // ———————————————————————————–
  127.   private function centerLaneTimerHandler(event:TimerEvent):void
  128.   {
  129.    _world.addNote(0xFFFFFF, 0, 0, MathExt.random(2, 5));
  130.   }
  131.  
  132.   // ———————————————————————————–
  133.   private function rightLaneTimerHandler(event:TimerEvent):void
  134.   {
  135.    _world.addNote(0x0000FF, 500, 0, MathExt.random(3, 6));
  136.   }
  137.  }
  138. }

3D World/setup Class

  1. package
  2. {
  3.  // flash
  4.  import flash.filters.BlurFilter;
  5.  import flash.events.Event;
  6.  
  7.  // tweenmax
  8.  import gs.TweenMax;
  9.  
  10.  // papervision3d
  11.  import org.papervision3d.objects.primitives.Plane;
  12.  import org.papervision3d.objects.DisplayObject3D;
  13.  import org.papervision3d.core.proto.MaterialObject3D;
  14.  import org.papervision3d.lights.PointLight3D;
  15.  import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
  16.  import org.papervision3d.materials.utils.MaterialsList;
  17.  import org.papervision3d.objects.primitives.Cube;
  18.  import org.papervision3d.core.effects.view.ReflectionView;
  19.  import org.papervision3d.materials.WireframeMaterial;
  20.  
  21.  
  22.  public class GuitarHeroSetupReflection extends ReflectionView
  23.  {
  24.   //
  25.   // public properties
  26.   //
  27.   // the higher it is, the further away
  28.   public var startPointZ:Number = 500;
  29.   // the lower the closer it will come
  30.   public var endPointZ:Number = -500;
  31.  
  32.   //
  33.   // private properties
  34.   //
  35.   private var _light:PointLight3D;
  36.   private var _matList:MaterialsList = new MaterialsList();
  37.   private var _hitAreaList:Array = new Array();
  38.   private var _noteList:Array = new Array();
  39.   private var _universe:DisplayObject3D;
  40.  
  41.   //////////////////////////////////////////////////////////////////////////////////////
  42.   //
  43.   // Constructor
  44.   //
  45.   //////////////////////////////////////////////////////////////////////////////////////
  46.      
  47.   // ———————————————————————————–
  48.   public function GuitarHeroSetupReflection()
  49.   {
  50.    // use reflection
  51.    viewportReflection.filters = [new BlurFilter(6,6,1)];
  52.    setReflectionColor(.5, .5, .5);
  53.    surfaceHeight = -100;
  54.    
  55.    _universe = new DisplayObject3D();
  56.    scene.addChild(_universe);
  57.    
  58.    initialize();
  59.   }
  60.  
  61.   //////////////////////////////////////////////////////////////////////////////////////
  62.   //
  63.   // Public methods
  64.   //
  65.   //////////////////////////////////////////////////////////////////////////////////////
  66.  
  67.   // ———————————————————————————–
  68.   public function addHitArea(hitColor:Number = 0×000000, xPos:Number = 0, yPos:Number = 0, zPos:Number = 0):void
  69.   {
  70.    var material:MaterialObject3D = new WireframeMaterial(hitColor, .5, 1);
  71.    material.doubleSided = true;
  72.    var plane:Plane = new Plane(material, 200, 200, 2, 2);
  73.    plane.x = xPos;
  74.    plane.y = yPos;
  75.    plane.z = zPos;
  76.    plane.rotationX = 90;
  77.    universe.addChild(plane);
  78.    
  79.    _hitAreaList.push(plane);
  80.   }
  81.  
  82.   // ———————————————————————————–
  83.   public function addNote(noteColor:Number = 0xFF0000, xPosition:Number = 0, yPosition:Number = 0, speed:Number = 1):void
  84.   {
  85.    // create material
  86.    var material:MaterialObject3D = new FlatShadeMaterial(_light, noteColor ,0X333333);
  87.    _matList.addMaterial(material, "all");
  88.    
  89.    // create box
  90.    var box:Cube = new Cube(_matList, 200, 200,50, 2, 2, 2);
  91.    box.x = xPosition;
  92.    box.y = yPosition;
  93.    box.z = startPointZ;
  94.    box.extra = {hitted: false};
  95.    
  96.    // add box
  97.    universe.addChild(box);
  98.    
  99.    // store all 3d objecs
  100.    _noteList.push(box);
  101.    
  102.    // start tween
  103.    startTween(box, speed);
  104.   }
  105.  
  106.   //////////////////////////////////////////////////////////////////////////////////////
  107.   //
  108.   // Getters & Setters
  109.   //
  110.   //////////////////////////////////////////////////////////////////////////////////////
  111.  
  112.   // ———————————————————————————–
  113.   public function get universe():DisplayObject3D
  114.   {
  115.    return _universe;
  116.   }
  117.  
  118.   //////////////////////////////////////////////////////////////////////////////////////
  119.   //
  120.   // Private methods
  121.   //
  122.   //////////////////////////////////////////////////////////////////////////////////////
  123.  
  124.   // ———————————————————————————–
  125.   private function initialize():void
  126.   {
  127.    // place camera higher-up and look down
  128.    camera.y = 400;
  129.    
  130.    // light
  131.    _light = new PointLight3D();
  132.    _light.x = camera.x + 500;
  133.    _light.y = camera.y;
  134.  
  135.    var do3d:DisplayObject3D = new DisplayObject3D();
  136.    scene.addChild(do3d);
  137.    camera.lookAt(do3d);
  138.    _light.lookAt(do3d);
  139.    
  140.    // render
  141.    addEventListener(Event.ENTER_FRAME, update);
  142.   }
  143.  
  144.   // ———————————————————————————–
  145.   private function startTween(box:Cube, speed:Number):void
  146.   {
  147.    TweenMax.to(box, speed, {z: endPointZ});
  148.   }
  149.  
  150.   // ———————————————————————————–
  151.   private function update(event:Event):void
  152.   {
  153.    for (var i:int = 0; i < _noteList.length; ++i)
  154.    {
  155.     for (var j:int = 0; j < _hitAreaList.length; ++j)
  156.     {
  157.      var note:Cube = _noteList[i] as Cube;
  158.      var hitArea:Plane = _hitAreaList[j] as Plane;
  159.      
  160.      // reset when needed
  161.      if (!note.hitTestObject(hitArea) && note.extra.hitted)
  162.      {
  163.       note.y = 0;
  164.       note.extra.hitted = false;
  165.      }
  166.      
  167.      // set note when hits a plane
  168.      if (note.hitTestObject(hitArea))
  169.      {
  170.       note.extra.hitted = true;
  171.       note.y = 100;
  172.       break;
  173.      }
  174.     }
  175.    
  176.     // remove when needed
  177.     if (note.z <= endPointZ)
  178.     {
  179.      _universe.removeChild(note);
  180.      _noteList.slice(i,0);
  181.     }
  182.    }
  183.    
  184.    // render reflection
  185.    singleRender();
  186.   }
  187.  }
  188. }

Papervision3D 2.0 + Google Sketchup – v2

Last modified on 2013-01-09 22:08:55 GMT. 3 comments. Top.

experiment_3D_v003

After loading the collada file and apply a texture on the whole object (see previous post), we now give each seperate object from the collada file its own texture and make them interactive.

get main node:
var holder:DisplayObject3D = daeFile.getChildByName("COLLADA_Scene").getChildByName("Model");

Within the “Model” we find all our 6 mesh shapes.

loop through all meshes:
for (var i:int = 0; i < holder.numChildren; i++) { var object3D:DisplayObject3D = holder.getChildByName("mesh" + (i+1).toString()); object3D.extra = {x: object3D.x, y: object3D.y, z: object3D.z}; // do not use materialslist but set it directly, get the colors from a class variable called _colors (Array) var mat:FlatShadeMaterial = new FlatShadeMaterial(light, _colors[i].diffuse, _colors[i].ambient); mat.interactive = true; object3D.material = mat; object3D.addEventListener(InteractiveScene3DEvent.OBJECT_CLICK, object3dClick); }

Papervision3D 2.0 and Google Sketchup

Last modified on 2013-01-09 22:08:55 GMT. 4 comments. Top.

experiment_3D_v001

Its a first tryout, so any feedback/help/examples it's all welcome, just drop a line/comment. Thanx in advance!

UPDATE: instead of using the BasicRenderEngine I implemented the QuadrantRenderEngine with the type number set to 1, so now there are no face 'issues' anymore.

Go check it out

And here are the source files: download

Particles v3

Last modified on 2013-01-09 22:08:55 GMT. 0 comments. Top.

experiment_particles_v3

Particles with random velocity on x-axis aswell on the y-axis and gravitation.

Using the same Particle class as in Particles v1 (post), is this another demo:

  1. package
  2. {
  3.  // FLASH
  4.  import flash.filters.BlurFilter;
  5.  import flash.utils.getDefinitionByName;
  6.  import flash.events.Event;
  7.  import flash.display.MovieClip;
  8.  
  9.  public class Particles003 extends MovieClip
  10.  {
  11.   //
  12.   // Private properties
  13.   //
  14.   private var _particles:Array;
  15.  
  16.   //////////////////////////////////////////////////////////////////////////////////////
  17.   //
  18.   // Constructor
  19.   //
  20.   //////////////////////////////////////////////////////////////////////////////////////
  21.  
  22.   // -----------------------------------------------------------------------------------
  23.   public function Particles003()
  24.   {
  25.    _particles = new Array();
  26.    filters = [new BlurFilter(6,6,1)];
  27.    addEventListener(Event.ENTER_FRAME, enterframeHandler);
  28.   }
  29.  
  30.   private function enterframeHandler(event : Event) : void
  31.   {
  32.    var particle:Particle;
  33.  
  34.    // loop through particles
  35.    for (var i:int = 0; i < _particles.length; i++)
  36.    {
  37.     particle = Particle(_particles[i]);
  38.     particle.update();
  39.    }
  40.  
  41.    // create particles
  42.    particle = new Particle(getDefinitionByName("Circle") as Class, this, mouseX, mouseY);
  43.    particle.xVel = random(-2, 2);
  44.    particle.yVel = random(-6, -10);
  45.  
  46.    particle.drag = .99;
  47.    particle.shrink = 1.05;
  48.    particle.gravity = .3;
  49.    particle.fade = .02;
  50.    _particles.push(particle);
  51.  
  52.    // add particles
  53.    while (_particles.length > 60)
  54.    {
  55.     // remove particle from array _particles
  56.     particle = _particles.shift();
  57.  
  58.     // remove from displaylist
  59.     particle.destroy();
  60.    }
  61.   }
  62.   // -----------------------------------------------------------------------------------
  63.   public static function random( min:Number, max:Number = NaN ):Number
  64.   {
  65.    if (isNaN(max)) { max = min; min = 0; }
  66.    return Math.random() * (max - min) + min;
  67.   }
  68.  }
  69. }

Particles v2

Last modified on 2013-01-09 22:08:55 GMT. 0 comments. Top.

experiment_particles_v2

Particles with no velocity on the axis's, but instead we use negative gravitation.

Using the same Particle class as in Particles v1 (post), is this demo 2:

  1. package
  2. {
  3. // FLASH
  4.  import flash.filters.BlurFilter;
  5.  import flash.utils.getDefinitionByName;
  6.  import flash.events.Event;
  7.  import flash.display.MovieClip;
  8.  
  9.  public class Particles002 extends MovieClip
  10.  {
  11.   //
  12.   // Private properties
  13.   //
  14.   private var _particles:Array;
  15.  
  16.   //////////////////////////////////////////////////////////////////////////////////////
  17.   //
  18.   // Constructor
  19.   //
  20.   //////////////////////////////////////////////////////////////////////////////////////
  21.  
  22.   // -----------------------------------------------------------------------------------
  23.   public function Particles002()
  24.   {
  25.    _particles = new Array();
  26.    filters = [new BlurFilter(6,6,1)];
  27.  
  28.    addEventListener(Event.ENTER_FRAME, enterframeHandler);
  29.   }
  30.  
  31.   private function enterframeHandler(event : Event) : void
  32.   {
  33.    var particle:Particle;
  34.  
  35.    // loop through particles
  36.    for (var i:int = 0; i < _particles.length; i++)
  37.    {
  38.     particle = Particle(_particles[i]);
  39.     particle.update();
  40.    }
  41.  
  42.    // create particles
  43.    particle = new Particle(getDefinitionByName("Circle") as Class, this, mouseX, mouseY);
  44.  
  45.    particle.drag = .98;
  46.    particle.shrink = .95;
  47.    particle.gravity = -.3;
  48.    particle.fade = .02;
  49.    _particles.push(particle);
  50.  
  51.    // add particles
  52.    while (_particles.length > 60)
  53.    {
  54.     // remove particle from array _particles
  55.     particle = _particles.shift();
  56.  
  57.     // remove from displaylist
  58.     particle.destroy();
  59.    }
  60.   }
  61.  }
  62. }

Particles v1

Last modified on 2013-01-09 22:08:55 GMT. 0 comments. Top.

experiment_particles_v1

Particles with random velocity on x-axis aswell on the y-axis.

The Particle Class

  1. package
  2. {
  3.  import flash.display.DisplayObjectContainer;
  4.  import flash.display.DisplayObject;
  5.  
  6.  public class Particle
  7.  {
  8.   //
  9.   // public properties
  10.   //
  11.   public var clip:DisplayObject;
  12.   public var xVel:Number = 0;
  13.   public var yVel:Number = 0;
  14.   public var drag:Number = 1;
  15.   public var gravity:Number = 0;
  16.   public var shrink:Number = 1;
  17.   public var fade:Number = 0;
  18.  
  19.   //////////////////////////////////////////////////////////////////////////////////////
  20.   //
  21.   // Constructor
  22.   //
  23.   //////////////////////////////////////////////////////////////////////////////////////
  24.  
  25.   // -----------------------------------------------------------------------------------
  26.   public function Particle(symbolClass:Class, target:DisplayObjectContainer, xpos:Number, ypos:Number)
  27.   {
  28.    // make particle clip
  29.    clip = new symbolClass();
  30.  
  31.    // add particle to target
  32.    target.addChild(clip);
  33.  
  34.    // set position
  35.    clip.x = xpos;
  36.    clip.y = ypos;
  37.   }
  38.  
  39.   //////////////////////////////////////////////////////////////////////////////////////
  40.   //
  41.   // Public methods
  42.   //
  43.   //////////////////////////////////////////////////////////////////////////////////////
  44.  
  45.   // -----------------------------------------------------------------------------------
  46.   public function update():void
  47.   {
  48.    clip.x += xVel;
  49.    clip.y += yVel;
  50.  
  51.    // apply drag
  52.    xVel *= drag;
  53.    yVel *= drag;
  54.  
  55.    yVel += gravity;
  56.  
  57.    clip.scaleX *= shrink;
  58.    clip.scaleY *= shrink;
  59.  
  60.    clip.alpha -=fade;
  61.   }
  62.  
  63.   // -----------------------------------------------------------------------------------
  64.   public function destroy():void
  65.   {
  66.    clip.parent.removeChild(clip);
  67.   }
  68.  
  69.   //////////////////////////////////////////////////////////////////////////////////////
  70.   //
  71.   // Private methods
  72.   //
  73.   //////////////////////////////////////////////////////////////////////////////////////
  74.  
  75.   // -----------------------------------------------------------------------------------
  76.   // none
  77.  }
  78. }

Class Demo 1:

  1. package
  2. {
  3.  // FLASH
  4.  import flash.filters.BlurFilter;
  5.  import flash.utils.getDefinitionByName;
  6.  import flash.events.Event;
  7.  import flash.display.MovieClip;
  8.  
  9.  public class Particles001 extends MovieClip
  10.  {
  11.   //
  12.   // Private properties
  13.   //
  14.   private var _particles:Array;
  15.  
  16.   //////////////////////////////////////////////////////////////////////////////////////
  17.   //
  18.   // Constructor
  19.   //
  20.   //////////////////////////////////////////////////////////////////////////////////////
  21.      
  22.   // -----------------------------------------------------------------------------------
  23.   public function Particles001()
  24.   {
  25.    _particles = new Array();
  26.    filters = [new BlurFilter()];
  27.    addEventListener(Event.ENTER_FRAME, enterframeHandler);
  28.   }
  29.  
  30.   private function enterframeHandler(event : Event) : void
  31.   {
  32.    var particle:Particle;
  33.    
  34.    // loop through particles
  35.    for (var i:int = 0; i < _particles.length; i++)
  36.    {
  37.     particle = Particle(_particles[i]);
  38.     particle.update();
  39.    }
  40.    
  41.    // create particles
  42.    particle = new Particle(getDefinitionByName("Circle") as Class, this, 250, 150);
  43.    particle.xVel = random(-5, 5);
  44.    particle.yVel = random(-5, 5);
  45.    particle.clip.alpha = random(.25, 1);
  46.    
  47.    _particles.push(particle);
  48.    
  49.    // add particles
  50.    while (_particles.length > 100)
  51.    {
  52.     // remove particle from array _particles
  53.     particle = _particles.shift();
  54.    
  55.     // remove from displaylist
  56.     particle.destroy();
  57.    }
  58.   }
  59.  
  60.  // -----------------------------------------------------------------------------------
  61.   public static function random( min:Number, max:Number = NaN ):Number
  62.   {
  63.    if (isNaN(max)) { max = min; min = 0; }
  64.    return Math.random() * (max - min) + min;
  65.   }
  66.  }
  67.  }
  68. }

PerlinNoise

Last modified on 2013-01-09 22:08:55 GMT. 0 comments. Top.

experiment_perlinnoise

Started (finally) experimenting with Perlin Noise....its a first but anyways...
Finally figured out that the number of Octaves and offset points are connected to eachother, which helps a lot!

Droppin' Boxes

Last modified on 2013-01-09 22:09:12 GMT. 2 comments. Top.

A Little experiment with Box2DFlash and papervision3D

Christmas Ribbons

Last modified on 2013-01-09 22:09:13 GMT. 0 comments. Top.

Merry Christmas to you all!! (click on the image)
With many thanx to soulwire for the code!

-->