Browse the notebook

Tag: actionscript

Overexposed Perlin Texture

var canvas:BitmapData = new BitmapData(1200,1200,false, 0x000000);
addChild(new Bitmap(canvas));

scaleX = scaleY = 0.5;
var w:int = canvas.width 
var hw:int = w / 2;
var hhw:int = hw / 2;
var size:int = canvas.width * canvas.width;

canvas.perlinNoise(hhw,hhw,2,Math.random()*100,false, false, 1, true);

for (var i:int = 0; i<size; i++){
	var xp:int = i % w;
	var yp:int = int(i / w);
	var col:uint =  canvas.getPixel(xp, yp) / (xp+yp-w) >> 8 & 0xFF
	canvas.setPixel(xp, yp, col << 16 | col << 8 | col)
}

var blur:BitmapData = canvas.clone();
blur.applyFilter(blur, blur.rect, new Point(0,0), new BlurFilter(10,10,1));

canvas.draw(blur, null, null, BlendMode.ADD);

I was playing around awhile back and created this snippet, it will draw something that looks like this:

this is one of those snippets that can produce vastly different looking images with minor changes to the code… for instance, try changing the blendMode to darken and line 15 to this:

var col:uint = canvas.getPixel(xp, yp) / (xp|yp-w) >> 5 & 0xFF;

and you’ll end up with this:

…take the original snippet and change the blendMode to subtract:

etc…

Read snippet: Overexposed Perlin Texture

Spring PerspectiveProjection

var pointNum:int = 3000;
x = stage.stageWidth / 2;
y = stage.stageHeight / 2;

var verts:Vector.<Number>  = new Vector.<Number>();
var tVerts:Vector.<Number> = new Vector.<Number>();
var pVerts:Vector.<Number> = new Vector.<Number>();
var uv:Vector.<Number> = new Vector.<Number>();
var cmds:Vector.<int> = new Vector.<int>();

var index:int = 0;
var half:Number = pointNum / 20000;
for (var i:int = 0; i<pointNum; i+=3){
	verts[i] = 0.08 * Math.cos(i * Math.PI / 180);
	verts[i+1] = 0.08 * Math.sin(i * Math.PI / 180);
	verts[i+2] =  i / 10000 - half;
	cmds[index++] = 2;
}
cmds[0] = 1;

var proj:PerspectiveProjection = new PerspectiveProjection();
proj.fieldOfView = 45;
var projMat:Matrix3D = proj.toMatrix3D();
var m:Matrix3D = new Matrix3D();
var dx:Number = 0, dy:Number = 0;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
       m.identity();
	   dx += (mouseX - dx) / 4;
	   dy += (mouseY - dy) / 4;
	   m.appendRotation(dy,Vector3D.X_AXIS);
	   m.appendRotation(dx,Vector3D.Y_AXIS);
	   m.appendTranslation(0,0,0.5);
	   m.transformVectors(verts, tVerts);
	   Utils3D.projectVectors(projMat, tVerts, pVerts, uv);
	   graphics.clear();
	   graphics.lineStyle(3,0x000000);
	   graphics.drawPath(cmds, pVerts);
}

This snippet draws a spring shape in 3D with perspective. This is the first snippet where I’ve made use of the PerspectiveProjection class. So if your wondering how to add perspective to your Utils3D.projectVectors code… this is one way to do it…


Have a look at the swf…

Read snippet: Spring PerspectiveProjection

Quick Pixel Sphere

var pointNum:int = 20000;
var radius:int = 150;

var canvas:BitmapData = new BitmapData(400,400,false, 0x000000);
addChild(new Bitmap(canvas));
var verts:Vector.<Number>  = new Vector.<Number>();
var pVerts:Vector.<Number> = new Vector.<Number>();
var uv:Vector.<Number> = new Vector.<Number>();

for (var i:int = 0; i<pointNum; i+=3){
	var xp:Number = Math.random() * 400 - 200;
	var yp:Number = Math.random() * 400 - 200;
	var zp:Number = Math.random() * 400 - 200;
	var dist:Number = Math.sqrt(xp * xp + yp * yp + zp * zp);
	// normalize and scale x,y,z 
	verts[i] = xp / dist * radius;
	verts[i+1] = yp / dist * radius;
	verts[i+2] = zp / dist * radius;
}

var m:Matrix3D = new Matrix3D();
var dx:Number = 0, dy:Number = 0;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
       m.identity();
	   dx += (mouseX - dx) / 4;
	   dy += (mouseY - dy) / 4;
	   m.appendRotation(dx, Vector3D.X_AXIS);
	   m.appendRotation(dy, Vector3D.Y_AXIS);
	   m.appendTranslation(200,200,0);
	   Utils3D.projectVectors(m, verts, pVerts, uv);
	   canvas.fillRect(canvas.rect, 0x000000);
	   for (var i:int = 0; i<pVerts.length; i+=2){
	     canvas.setPixel(pVerts[i], pVerts[i + 1], 0xFFFFFF);
	   }
}

This snippet shows a quick way to randomly place a bunch of xyz coordinates on the surface of a sphere. I saw this trick in an OpenGL book a few years back – dug around my books but couldn’t find it… If I find it I’ll update this post.

The trick is achieved by normalizing the vector defined by each 3D coordinate…


Have a look at the swf…

Read snippet: Quick Pixel Sphere

Wave Trick

[SWF(width=800, height=600)]
var dupes:int = 5
var pntNum:int = 180;

var hh:Number = stage.stageHeight / 2;
var points:Vector.<Number> = new Vector.<Number>();
var vel:Vector.<Number> = new Vector.<Number>();
var cmds:Vector.<int> = new Vector.<int>();
var vectors:Vector.<Shape> = new Vector.<Shape>();

for (var i:int = 0; i<dupes; i++){
	vectors[i] = Shape(addChildAt(new Shape(),0));
	vectors[i].x = 10 * i;
	vectors[i].y = -10 * i;
}
var index:int = 0;
for (i = 0; i<pntNum; i++){
	points[index++] = 10 + i * 4;
	points[index++] = hh;
	cmds[i] = 2;
	vel[i] = 0;
}
cmds[0] = 1;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {	
   index = 1;
   points[index] += (mouseY - points[index]) / 12;
   for (var i:int = 3; i<points.length; i+=2){
         points[i] += vel[index];
		 vel[index] += ((points[i] - points[i - 2]) * -0.16 - vel[index]) / 4;
		 index++;
   }
   for (i = 0; i<dupes; i++){
	   var c:uint =  255 - 255 / i;
	   with (vectors[i].graphics){
		   clear();
		   lineStyle(0,c << 16 | c << 8 | c);
		   drawPath(cmds, points);
	   }
   }
}

This snippet uses elasticity to create an interesting wave effect. I first stumbled upon this technique back in my director days…


Have a look at the swf here…

Read snippet: Wave Trick

Summarize Contents of Array

var a:Array = [true, true, true, false, false, true, true, true, false];

var counter:int = 0;
var prev:Boolean;
var summary:Array = [];
for (var i:int = 1; i<a.length; i++){
	prev = a[i - 1]
	counter++;
	if (prev != a[i]){
		if (prev){
			summary.push("true: "+ counter);
		}else{
			summary.push("false: "+ counter);
		}
		counter = 0;
	}
}
summary.push(a[i-1].toString()+": "+ (counter+1));

trace(summary);

/** outputs:
true: 3,false: 2,true: 3,false: 1
*/

This is a handy way to summarize the contents of an array of boolean values.

Read snippet: Summarize Contents of Array

Sphere of Squares

[SWF(width = 600, height = 600, backgroundColor=0x000000)]
var squareNum:int  = 1000;
var hw:Number = stage.stageWidth / 2;
var hh:Number = stage.stageHeight / 2;
// verts defines a single square
var verts:Vector.<Number> = Vector.<Number>([-20, 0, 0, 20, 0, 0, 20, 0, 40, -20, 0, 40, -20, 0, 0]);
var cmds:Vector.<int> = Vector.<int>([1,2,2,2,2]);
var tempVerts:Vector.<Number> = new Vector.<Number>();
var newVerts:Vector.<Number> = new Vector.<Number>();
var pVerts:Vector.<Number> = new Vector.<Number>(10 * squareNum);
var uv:Vector.<Number> = new Vector.<Number>(15 * squareNum);
var vectors:Shape = new Shape();
var canvas:BitmapData = new BitmapData(stage.stageWidth,stage.stageHeight,false, 0x000000);
addChild(new Bitmap(canvas));
var blurred:BitmapData = new BitmapData(stage.stageWidth,stage.stageHeight,false, 0x000000);
var blur:BlurFilter = new BlurFilter(20,20,1);

var m:Matrix3D = new Matrix3D();

var radius:Number = 200;
// duplicate the verts array a bunch of times
// each time moving the square to a random place on the
// circumference of a sphere
for (var i:int = 0; i<squareNum; i++){
	m.identity();
	var s:Number = Math.random()*.5 + .5;
	m.appendScale(s, s, s);
	m.appendRotation(90,Vector3D.X_AXIS);
	m.appendTranslation(0, 0, radius);
	m.appendRotation(Math.random()*360,Vector3D.X_AXIS);
	m.appendRotation(Math.random()*360,Vector3D.Y_AXIS);
	m.appendRotation(Math.random()*360,Vector3D.Z_AXIS);
	m.transformVectors(verts,tempVerts);
	newVerts = newVerts.concat(tempVerts);
	cmds = cmds.concat(Vector.<int>([1,2,2,2,2]));
}
newVerts.fixed = pVerts.fixed = uv.fixed = true;
var dx:Number = 0, dy:Number = 0;
var pnt:Point = new Point();
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	   dx += (mouseX - dx) / 4;
	   dy += (mouseY - dy) / 4;
	   m.identity();
	   m.appendRotation(dx,Vector3D.Z_AXIS);
	   m.appendRotation(dy,Vector3D.X_AXIS);
	   m.appendTranslation(hw,hh, 0);
	   Utils3D.projectVectors(m, newVerts, pVerts, uv);
	   with(vectors.graphics){
		   clear();
		   beginFill(0xFFFFFF);
		   drawCircle(hw, hh, radius+10);
		   beginFill(0x000000);
		   drawPath(cmds, pVerts, GraphicsPathWinding.NON_ZERO);
	   }
	   canvas.fillRect(canvas.rect, 0x000000);
	   canvas.draw(vectors);
	   blurred.copyPixels(canvas, canvas.rect, pnt);
	   blurred.applyFilter(blurred,blurred.rect, pnt, blur);
	   canvas.draw(blurred, null, null, BlendMode.SCREEN);
}

This snippet is similar to yesterdays post but the visual result is rather different. This one does a little more Matrix3D stuff resulting in a sphere made up entirely of squares. This is obscured by the size of the squares and the fact that they overlap and cut each other up. BitmapData a BlurFilter and a BlendMode give the entire thing a slight glow…


Have a look at the swf here…

Read snippet: Sphere of Squares

Recursive 2D Structure

[SWF(width = 600, height = 700, frameRate=24)]
var canvas:BitmapData = new BitmapData(stage.stageWidth,stage.stageHeight,false, 0xFFFFFF);
addChild(new Bitmap(canvas));

var maxBranches:int = 600;
var branches:int = 0;
var startX:Number = 300
makeBranch(startX,690,30,-60, 60);

function makeBranch(xp:Number, yp:Number, step:Number, min:Number, max:Number):void {
	var vectors:Shape = Shape(addChild(new Shape()));
	var cX:Number, cY:Number, eX:Number, eY:Number
	var dcX:Number=xp, dcY:Number=yp, deX:Number=xp, deY:Number=yp;
	var theta:Number = (min + Math.random()*(max-min) - 90) * Math.PI / 180;
	cX = xp + step * Math.cos(theta);
	cY = yp + step * Math.sin(theta);
	theta = (min + Math.random()*(max-min)-90) * Math.PI / 180;
	eX = cX + step * Math.cos(theta);
	eY = cY + step * Math.sin(theta);
	var run:Function = function():void{
	     dcX +=  (cX - dcX) / 2;
		 dcY +=  (cY - dcY) / 2;
		 deX +=  (eX - deX) / 8;
		 deY +=  (eY - deY) / 8;
		 with(vectors.graphics){
			  clear();
			  beginFill(0xFFFFFF,0.8);
			  lineStyle(0,0x000000,0.8);
			  moveTo(startX, yp);
			  lineTo(xp, yp);
			  curveTo(dcX, dcY, deX, deY);
			  lineTo(startX, deY);
		 }
		 if (Math.abs(dcX - cX) < 1 && Math.abs(deX - eX) < 1 && Math.abs(dcY - cY) < 1 && Math.abs(deY - eY) < 1){
			 canvas.draw(vectors);
			 removeChild(vectors);
			 if (branches < maxBranches){
				 setTimeout(makeBranch, 10, deX, deY, step - Math.random(), -90, 90);
				 branches++;
				 if (int(Math.random()*2) == 1){
				    setTimeout(makeBranch, 10, deX, deY, step - Math.random()*3, -90, 90);
					branches++;
				 }
			 }
		 }else{
		     setTimeout(arguments.callee,  1000 / 24);
		 }
	}();
}

This snippet uses a technique similar to what you might use to create a recursive tree. A bit of additional logic is added for bezier branches, filled shapes and animation.

WARNING: may run slow on older machines

Have a look at the swf…

Read snippet: Recursive 2D Structure

Smudge Tool #1

[SWF(backgroundColor = 0xCCCCCC)]
var canvas:BitmapData = new BitmapData(stage.stageWidth,stage.stageHeight,true, 0xFFFFFFFF);
addChild(new Bitmap(canvas));

var loader:Loader = new Loader();
loader.load(new URLRequest("https://actionsnippet.com/wp-content/chair.jpg"));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
function onComplete(evt:Event):void{
	canvas.draw(loader);
}

var brush:Shape = new Shape();
var diameter:Number = 120;
var radius:Number = diameter / 2;
var matrix:Matrix = new Matrix();

var brushAlpha:BitmapData = new BitmapData(diameter, diameter, true, 0x00000000);
drawRadial();
brushAlpha.draw(brush);

var xp:Number = 0, yp:Number = 0, px:Number = 0, py:Number = 0;
var dx:Number, dy:Number;

stage.addEventListener(MouseEvent.MOUSE_MOVE, onLoop);
function onLoop(evt:Event):void {
	xp = mouseX - radius;
	yp = mouseY - radius;
	dx = xp - px;
	dy = yp - py;
	canvas.copyPixels(canvas,
					new Rectangle(px, py, diameter, diameter),
					new Point(xp, yp), brushAlpha, new Point(0,0), true);
	px = xp;
	py = yp
}

function drawRadial():void{
	matrix.createGradientBox(diameter, diameter, 0, 0, 0);
	with (brush.graphics){
		beginGradientFill(GradientType.RADIAL, [0xFFFFFF, 0xFFFFFF], [1,0], [0, 255], matrix, SpreadMethod.PAD);
		drawCircle(radius, radius, radius);
	}
}

This is a quick snippet I wrote while thinking about how to create a smudge tool using BitmapData… it isn’t perfect, but it’s a good first step. It still needs some linear interpolation and I may need to do some pixel pushing to prevent a strange alpha anomaly that causes the brush to get darker than expected….


Here is the swf…

Read snippet: Smudge Tool #1

Isometric Cones (spikes)

[SWF(width = 600, height = 500, backgroundColor=0xFFFFFF)]

var canvas:BitmapData = new BitmapData(stage.stageWidth,stage.stageHeight,false, 0xFFFFFF);
addChild(new Bitmap(canvas));

var matrix:Matrix = new Matrix();
var grid:Sprite =   new Sprite();
grid.filters = [new DropShadowFilter(4, 0, 0, 0.05, 20, 10)];
matrix.rotate(Math.PI / 4);
matrix.scale(1, 0.6);
matrix.translate(stage.stageWidth / 2, stage.stageHeight / 2 + 50);
grid.transform.matrix = matrix;

var rowCol:int = 9;
var spikeNum:Number = rowCol * rowCol;
var diameter:Number = 30;
var space:Number  = diameter + 10;
var halfGridSize:Number  = rowCol * space / 2;
var radius:Number;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	radius  = diameter / 2;
	grid.y -= 0.9;
	grid.graphics.clear();
	for (var i:Number = 0; i<spikeNum; i++){
	   var xp:Number = i % rowCol;
	   var yp:Number = int(i / rowCol);
	   drawSpike(xp * space - halfGridSize, yp * space - halfGridSize, (xp + yp) / 4, 0, -yp);
	}
	canvas.draw(grid, grid.transform.matrix);
	diameter -= 0.5;
	if (diameter < 3){
		removeEventListener(Event.ENTER_FRAME, onLoop);
	}
}
function drawSpike(xp:Number, yp:Number, rot:Number = 0, xOff:Number=0, yOff:Number = 0):void{
	matrix.createGradientBox(diameter, diameter, rot, xp - radius + yOff, yp - radius + xOff);
	with (grid.graphics){
		beginGradientFill(GradientType.LINEAR, [0xFFFFFF, 0x999999], [1,1], [0, 255], matrix, SpreadMethod.PAD);
		drawCircle(xp, yp, radius);
	}
}

This snippet draws some isometric cones. Here are some images created by tweaking a few of the values:

Read snippet: Isometric Cones (spikes)

Cut Image into Squares (copyPixels)

[SWF(width=650, height=650)]
var loader:Loader = new Loader();
loader.load(new URLRequest("https://actionsnippet.com/wp-content/chair.jpg"));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);

var w:Number;
var h:Number;
var rows:Number = 20;
var cols:Number = 20;
var tiles:Vector.<BitmapData> = new Vector.<BitmapData>();
var locX:Vector.<Number> = new Vector.<Number>();
var locY:Vector.<Number> = new Vector.<Number>();
var rX:Vector.<Number> = new Vector.<Number>();
var rY:Vector.<Number> = new Vector.<Number>();
var sX:Vector.<Number> = new Vector.<Number>();
var sY:Vector.<Number> = new Vector.<Number>();
function onLoaded(evt:Event):void{
	w = evt.target.width;
	h = evt.target.height;
	var image:BitmapData = Bitmap(evt.target.content).bitmapData;
	var tileWidth:Number = w / cols;
	var tileHeight:Number = h / rows;
	var inc:int = 0;
	var pnt:Point = new Point();
	var rect:Rectangle = new Rectangle(0,0,tileWidth,tileHeight);
	for (var i:int = 0; i<rows; i++){
		for (var j:int = 0; j<cols; j ++){
			 var currTile:BitmapData= new BitmapData(tileWidth, tileHeight, true, 0x00000000);
			 rect.x = j * tileWidth;
			 rect.y = i * tileHeight;
			 currTile.copyPixels(image, rect, pnt, null, null, true);
			 tiles[inc] = currTile;
			 rect.x += 25;
			 rect.y += 25;
			 sX[inc] = rect.x;
			 sY[inc] = rect.y;
			 locX[inc] = rX[inc] = -rect.width * 2
			 locY[inc] = rY[inc] =  Math.random() * stage.stageHeight;
			 setTimeout(startAnimation, inc *4 + 100, inc, rect.x, rect.y);
			 inc++;
		}
	}
}

function startAnimation(index:int, dx:Number, dy:Number):void{
	var interval:Number;
	var animate:Function = function(index:int):void{
		locX[index] += (dx - locX[index]) / 4;
		locY[index] += (dy - locY[index]) / 4;
		if (Math.abs(locX[index] - dx) < 1 && Math.abs(locY[index] - dy)<1){
			locX[index] = dx;
			locY[index] = dy;
		    clearInterval(interval);
		}
	}
   interval = setInterval(animate, 32, index);
}

var canvas:BitmapData = new BitmapData(stage.stageWidth,stage.stageHeight,false, 0xFFFFFF);
addChild(new Bitmap(canvas));

var loc:Point = new Point();
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	  canvas.fillRect(canvas.rect, 0xFFFFFF);
      for (var i:int = 0; i<tiles.length; i++){
		    var tile:BitmapData= tiles[i];
			loc.x = locX[i];
			loc.y = locY[i];
		    canvas.copyPixels(tile, tile.rect, loc, null, null, true);
	  }
}

This snippet cuts a dynamically loaded image into a series of smaller BitmapData instances. These BitmapData instances are then drawn to a canvas BitmapData using copyPixels. The BitmapData.copyPixels() method is extremely fast – so this has some advantages over yesterdays post (which did basically the same thing with Sprites). I used setInterval and setTimeout to do a simple demo animation, but I recommend using TweenLite on a real project.

Read snippet: Cut Image into Squares (copyPixels)