Pushing the boundaries

…couldn’t be any simpler!

Archive for the ‘AS code tricks’ Category

Programming techniques and best practices

UI reflection

Posted by vijayram on February 8, 2007

distortreflection

package
{
import sandy.util.*;
import flash.display.*;
import flash.display.Sprite;
import flash.display.Shape;
import flash.display.Graphics;
import flash.display.DisplayObject;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display.Bitmap;
import flash.display.Loader;
import flash.events.Event;
import flash.net.URLRequest;
import flash.geom.Point;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.display.BitmapData;

[SWF(width=”1024″, height=”768″, backgroundColor=”#000000″)]

public class App extends Sprite
{
private var _shape:Shape;
private var _refshape:Shape;
private var _loader:Loader = new Loader();
private var _reflectionBitmap:Bitmap;
public function App()
{
init();
}

private function init():void
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align=StageAlign.TOP_LEFT;

_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
_loader.load(new URLRequest(“24012007010.jpg”));

}

private function onComplete(event:Event):void {
var loadedImage:Bitmap = Bitmap(_loader.content);

_shape = new Shape();
_shape.graphics.lineStyle(0,0X0000FF,1);
_shape.graphics.drawRect(0, 0, loadedImage.width, loadedImage.height);
addChild(_shape);
_shape.x=200;
_shape.y=100;

_refshape = new Shape();
_refshape.graphics.lineStyle(0,0X0000FF,1);
_refshape.graphics.drawRect(0, 0, loadedImage.width, loadedImage.height);
addChild(_refshape);
_refshape.x=200;
_refshape.y=100;

var distort:DistortImage = new DistortImage();
distort.container = _shape;
distort.target = loadedImage;
distort.smooth = true;
distort.initialize( 5, 5, null );
distort.setTransform(-76,-80,500,0,500,334,-76,398);
distort.render();

createReflectionBitmap(loadedImage);

}

private function createReflectionBitmap(target:DisplayObject):void {

var Falloff:Number = 0.6;
var rect: Rectangle = new Rectangle(0, 0, target.width, target.height);
var alphaGradientBitmap:BitmapData = new BitmapData(target.width, target.height, true, 0x00000000);

var gradientMatrix: Matrix = new Matrix();
var gradientShape: Shape = new Shape();
gradientMatrix.createGradientBox(target.width, target.height * Falloff, Math.PI/2,
0, target.height * (1.0 – Falloff));
gradientShape.graphics.beginGradientFill(GradientType.LINEAR, [0xFFFFFF, 0xFFFFFF],
[0, 1], [0, 255], gradientMatrix);
gradientShape.graphics.drawRect(0, target.height * (1.0 – Falloff),
target.width, target.height * Falloff);
gradientShape.graphics.endFill();
alphaGradientBitmap.draw(gradientShape, new Matrix());

var targetBitmap:BitmapData = new BitmapData(target.width, target.height, true, 0x00000000);
targetBitmap.fillRect(rect, 0x00000000);
targetBitmap.draw(target, new Matrix());

var reflectionData:BitmapData = new BitmapData(target.width, target.height, true, 0x00000000);
reflectionData.fillRect(rect, 0x00000000);
reflectionData.copyPixels(targetBitmap, rect, new Point(), alphaGradientBitmap);
_reflectionBitmap = new Bitmap(reflectionData);
_reflectionBitmap.alpha = .3;

var m:Matrix = _refshape.transform.matrix;
var position:Point = new Point(m.tx, m.ty);
m.tx = position.x;
m.ty = position.y;
m.d = -1;
m.ty = _refshape.height*3;
_refshape.transform.matrix = m;

var distortn:DistortImage = new DistortImage();
distortn.container = _refshape;
distortn.target = _reflectionBitmap;
distortn.smooth = true;
distortn.initialize( 5, 5, null );
distortn.setTransform(-76,300,500,350,500,695,-76,630);
distortn.render();
}

}
}

[Edit: The above is just a proof of concept and the code is begging for refactorisation;)]

Posted in Adobe, AS 3.0, AS code tricks, Flash | 3 Comments »

Matrix Transformation

Posted by vijayram on February 6, 2007

One more addition to the ActionScript code tricks category. It all started with me trying to draw a trapezium (trapezoid) to display an image. Cannot be tough, can it?! Flash gives me all the the tools to draw and this should be easy and using the matrix class, I can move, rotate or skew the shape with ActionScript.
Ah! “skew”, thats what I want to use to give the perception of 3D.
Using matrix transformation, this should be possible….hmmm…nope!!! Lets take a step back and see what is possible using the matrix class.

WWW has a wealth of information about what a matrix is (not the movie). Just think of it as a table of rows and columns represented as m x n matrix. By setting the values in the Matrix object you can perform transformations on the display object which includes translation, rotation, scaling and skewing.
Flash provides a 3 x 3 matrix:
matrix

Note: u,v,w are sort of dummy here though their values remain as 0,0,1. You can manipulate the rest(a,c,c,d,tx and ty) for transformation. Great lets move on.

If I change,
Translation ->tx or ty: It would move either tx pixels to the right or ty pixels down.
Scale ->a or d: It would xScale or yScale.
Skew -> b or c: Skew either parallel to the x or y axis.
Rotation -> a,b,c and d: For an angle q: a is cos(q), b is sin(q), c is -sin(q) and d is cos(q)

Important: Any transformations done,is called affine transformation.
So what is affine transformation?! Wikipediahas this : In geometry, an affine transformation or affine map (from the Latin, affinis, “connected with”) between two vector spaces (strictly speaking, two affine spaces) consists of a linear transformation followed by a translation.
To me and you, it means, it preserves the straightness of lines and so parallel lines stay parallel. WTF?!! I cannot transform my rectangle into a trapezium?? This is crazy.

Me being me, started looking and reading about it and looking for possiblities. I ended up on this website. Ok, am I looking for Projective transformation? This is crazy. Ok, lets just remember Flash is a 2D package and what we want is a 3D look. Any transformation still will work in the 2D space. So left with no choice, we need look into faking 3D.

Ok, what are the alternatives out there for ActionScript 3.0. Papervision3D. Still in beta stage but very much stable. Has anyone work on this before to fake 3D perspective? Well, yes. Couple of them. Look at this by Alex Uhlmann here.

Super cool!!!!! That’s what I am after. He has even made it open-source. He uses Sandy Flash 3D API to do it. He has ported it to ActionScript 3.0 for use in his Flex example.
Now I need to leverage from his work to get the result I want. Thanks to him and the team behind Sandy. What is happening behind the scene is triangular tessellations. To give you an idea, look at Pavils Jurjans example here with a tutorial to give you a start.

3d prespective

package
{

import flash.display.Shape;
import flash.display.Graphics;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display.Bitmap;
import flash.display.Loader;
import flash.events.Event;
import flash.net.URLRequest;
import sandy.util.*;

[SWF(backgroundColor="#000000")]

public class App extends Sprite
{
private var _shape:Shape;
private var _loader:Loader = new Loader();

public function App()
{
init();
}

private function init():void
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align=StageAlign.TOP_LEFT;
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
_loader.load(new URLRequest("24012007010.jpg"));
}

public function onComplete(event:Event):void {
var loadedImage:Bitmap = Bitmap(_loader.content);

_shape = new Shape();
_shape.graphics.lineStyle(0,0X0000FF,1);
_shape.graphics.drawRect(0, 0, loadedImage.width, loadedImage.height);
addChild(_shape);
_shape.x=200;
_shape.y=200;

var distort:DistortImage = new DistortImage();
distort.container = _shape;
distort.target = loadedImage;
distort.smooth = true;
distort.initialize( 5, 5, null );
distort.setTransform(-76,-103,500,0,500,334,-77,398);
distort.render();
}
}
}

Technorati Tags: , , ,

Posted in Adobe, AS 3.0, AS code tricks, Flash | 4 Comments »

ActionScript code tricks

Posted by vijayram on January 30, 2007

Continuing with the post, today’s tricks are to do with bitwise operators for manipulation of colours.

After working on the visualizer, it became obvious to me that one needs to know the nitty grittys of assisgning colours and manipulating the same using ActionScript. Working through this reminded me of the days I implemented RSA encryption in FLash 5. Bits, Bytes, hex…..hmm…geek time!

Starting with basics of number theory, we in our day to day life deal with numbers using a base 10. For example, Shilpa Shetty in Celebrity Brother was paid £300,000 for apperance.
300,000 = (3 x 100000)+(0 x 10000)+(0 x 1000)+(0 x 100)+(0 x 10)+(0 x 1)
300,000 = (3 x 10^5)+(0 x 10^4)+(0 x 10^3)+(0 x 10^2)+(0 x 10^1)+(0 x 10^0)

Whilst in computers, everything is represented using base 2 system (ie: 0 and 1).
100010 = (1 x 2^5) + (0 x 2^4) + (0 x 2^3) + (0 x 2^2) + (1 x 2^1) + (0 x 2^0) = 34

Moving on, colours are represented as hexadecimal. This basically means that, it is to the base 16. Simple!. They are represented as: numbers 0 to 9 and the letters A to F. For example, the decimal number 12 is C in hexadecimal.

Colour values in ActionScript is represented using a 32 bit hexadecimal or 4 pairs of hexadecimal digits( one hexadecimal digit = 4 binary digit). I said 4 pairs here, which means each channel makes a hexadecimal pair (Alpha, Red, Green and Blue). Opaque images are 24-bit, with 8 bits for each of its red, green, and blue channels. Transparent images add another 8-bit alpha channel for a total of 32 bits.

So far a 32-bit image, it is AARRGGBB.

Moving on, lets take case of bitwise OR (“|”). Do not confuse this with logical OR. This sets the result bit to 1 if either of the source bits is 1.
0101 OR 0011
= 0111
Several ActionScript gurus use this operator while playing with colours [ eg:graphics.lineStyle(num,0x0033FF|(num << 8)); ]
Lets just put it this way, its a celver way for combining colours. You can use the bitwise OR to combine BitmapDataChannel constants to indicate multiple color channels.
bitmap.perlinNoise(100, 100, 5, 500, false, true, BitmapDataChannel.RED | BitmapDataChannel.GREEN | BitmapDataChannel.BLUE,false, null);

The next operator is shift, Left Shift “<<” and Right Shift “>>”. The left operands value is moved left or right by the number of bits specified by the right operand.
In theory, 00001110 << 2 = 00111000.
Actionscript converts the result to a 32-bit integer, which is good in our case for colours.
Shift operators discard anything after the decimal place, so shifting by zero provides a faster way to floor your numbers:
trace(1234.567>>0); // 1234
Now coming back to our bitmap representation, AARRGGBB we know that it is represented as follows: aaaaaaaarrrrrrrrggggggggbbbbbbbb (8 bits for each channel).

Given an RGB colour, if we want to extract only red, we do as follows:
myRed = myRGB >>16; This would move the bits to the right by 16 place, thereby discarding all the G and B bits and we are left with only R :). But its still padded with those trailing zeros.

The next and the last operator we are going to look at is &. Again this is different from logical and”&&”.
The & operator performs a bitwise AND on two integers. Each bit in the result is 1 only if both corresponding bits in the two input operands are 1. For example:
0 1 0 1 0 1 1 0
& 0 0 1 1 0 0 1 0
—————
0 0 0 1 0 0 1 0
This is a clever operator and used for masking. Masking is nothing but to mask the other bits and extract the ones you want. Interesting!
Lets take the earlier example of extracting the red channel, its easier to do with this operator as follows:
var argb:Number = 0xFFAA341B;
var redChannel:Number = (argb & 0x00FF0000) >> 16;
trace(“redChannel: “+redChannel.toString(16)); //output redChannel: AA

Technorati Tags: , ,

Posted in Adobe, AS 3.0, AS code tricks, Flash | Leave a Comment »

ActionScript code tricks

Posted by vijayram on January 26, 2007

Continuing this topic, today I shall discuss the benefits of CONSTANTS. I have seen several programmers use it in AS 2.0, but with AS 3.0 to me, it all made sense.

CONSTANTS are all uppercase and spaces converted to underscore. (eg: SERVER_NAME=”god”;)
Values assigned to CONSTANTS do not change as it implies. Declaring a CONSTANT is rather straight forward as declaring a variable with the var keyword.
public static const SERVER_NAME:String =”god”;

In ActionScript 3.0, the one place you will always encounter CONSTANTS are Events. It is best code of practice to use static CONSTANTS property of the Event class.(eg: addEventListener(Event.ENTER_FRAME, onEnterFrame); )

Lets just understand why we require to use the static CONSTANTS, as supposed to using just “enterFrame”. ActionScript 3.0 is a dynamically typed language and also supports compile-time type checking using the “strict mode”. I could type the above Event as follows, which is still valid – addEventListener(“enterFrame”, onEnterFrame);
But what if I were to type it as follows – addEventListener(“enterFame”, onEnterFrame);

I would definitely have “entered Fame” but for all the wrong reasons. The above code would be still compiled by the compiler though no errors will be reported. I would be spending unnecessary time to debug this. To avoid any such mistakes it is better to use the CONSTANT property of the class. How to we create one for our class?

This brings us to another topic of Enumerations. Enumerations are custom data types that you create to encapsulate a small set of value. ActionScript 3.0 does not support a specific enumeration facility like C++ or Java, however you can create this behaviour using classes and static CONSTANTS.

For example, a visitor to a web-page has a choice of language. The LanguagePreference class will use an enumeration PrefLanguage to store a set of language values.
public final class PrefLanguage {
public static const ENGLISH:String = “english”;
public static const FRENCH:String = “french”;
}

Now you can access the enumeration values as follows:
var myLanguage:LanguagePreference = new LanguagePreference();
if ( myLanguage.Language ==PrefLanguage.ENGLISH){
…….
}

The advantage of using the above method is that your code is type-safe, thereby catching errors at compile time. The only disadvantage that I can think of is the need for an additional class to be written to hold your enumeration types.

Posted in Adobe, AS 3.0, AS code tricks, Flash | 4 Comments »

ActionScript code tricks

Posted by vijayram on January 24, 2007

Ok! This post will be ever growing as I come across tricks used by the geek community to write code. I was always baffled by code which didn’t stick to the book. Hoping this post will clear out those myths that if you use this structure whilst coding, you are “god” of the geek land….maybe you are!!!..whatever.

Compound Assignment Operators:
Compound assignment operators provide two benefits. Firstly, they produce more compact code.Saves the trouble of over exercising those fingers. Secondly, the variable being operated upon, or operand, only needs to be evaluated once in the compiled application. This can actually make the code more efficient when executed.In contrast, the statement using the simple operators makes a copy of the variable A, performs the operation on the copy, and then assigns the resulting value back to A, temporarily using extra memory.

Lets take the case of arithmetic operators (+ – * / %).
var += expression; // var = var + expression
var -= expression; // var = var – expression
var *= expression; // var = var * expression
var /= expression; // var = var / expression
var %= expression; // var = var % expression

This statement adds 1 to value :
value ++;
This statement subtracts 1 from value :
value –;

You can use the increment and decrement operators (– and ++) either before or after the variable or property they operate upon. If used before the operand, they are called prefix operators. If used after the operand, they are called postfix operators.
var value :Number = 5;
trace(value ++); // 5
trace(value ); // 6

var value :Number = 5;
trace(++value ); // 6
trace(value ); // 6

Posted in Adobe, AS 3.0, AS code tricks, Flash | 1 Comment »