package { import flash.display.Sprite; import flash.display.BitmapData; import flash.display.GraphicsPathCommand; public class PerlinWaves extends Sprite { public var n:int =32; // dimensions width public var m:int =8; // dimensions 'distance' public var depthLevel:Number = 360.0; // dimensions: y-level of the bottom floor // two bitmaps: bitmapData (set,get - zdata) holds the info for the height, // textureMap is the texture that is drawn ... private var zData:BitmapData; public var textureMap:BitmapData = new BitmapData(1,1,true,0xFFFFFFFF); private var vertices:Vector.; private var indices:Vector.; private var uvtData:Vector.; private var i:int; private var j:int; public function PerlinWaves(bmp:BitmapData) { zData = bmp; n = zData.width; init(); upDate(); } public function set bitmapData(bmp:BitmapData):void { this.zData=bmp; upDate(); } public function get bitmapData():BitmapData { return this.zData; } private function init():void { vertices = new Vector.(); indices = new Vector.(); uvtData = new Vector.(); for (j=0; j!=m; j++) { for (i=0 ; i!=n; i++) { // x,y coordinates, initialize vector size vertices.push(0.0, 0.0); // texture mapping coordinates between 0,0 and 1,1 uvtData.push(i/(n-1.0),j/(m-1.0)); } } // // indices for two triangles, CCW // // ii-----ii+1 // |\ | // | \ | // | \ | // | \| // ii+n---ii+n+1 var ii:int =0; for (j=0 ; j!=m-1; j++) { for (i=0 ; i!=n-1; i++) { indices.push(ii,ii+n+1,ii+1); indices.push(ii+n,ii+n+1,ii++); } ii++; } } private function upDate():void { // when the maps updated, the mesh info, e.g uvtData and indices // remain the same, only vertices will be updated var ii:int =0; for (j=0; j!=m;j++) { for (i=0 ; i!=n; i++) { // x-coordinate vertices[ii++]= i/(n-1); // *100.0; if (j==m-1) { // y-coordinate, bottom level vertices[ii++]= depthLevel; } else { // y-coordinate, sampled from image's blue channel vertices[ii++]= Number(zData.getPixel(i,j) & 0xFF); } } } // draw the new graphics with (this.graphics) { clear(); beginBitmapFill(this.textureMap); drawTriangles(vertices,indices,uvtData); endFill(); } } } }