Pushing the boundaries

…couldn’t be any simpler!

Archive for the ‘Adobe’ Category

Adobe Flash Actionscript, Adobe Flex MXML, etc.

Cairngorm 2 and PopUpManager woes!

Posted by vijayram on May 24, 2007

Read through this blog post by darron schall in which he explains the reason why….gosh! I wish I read this few hours back.

http://www.darronschall.com/weblog/archives/000224.cfm

Just wanted to highlight this issue once again.

Posted in AS 3.0 | 1 Comment »

Apollo – Window Transparent

Posted by vijayram on March 19, 2007

Just downloaded the alpha version of Apollo from the labs section on the Adobe website.
http://labs.adobe.com/technologies/apollo/

While reading through the documentation on “Create your first Flex-based Apollo application in Flex Builder” , I came across a typo error which stated as follows:
——–

Next, set the application’s window transparency:

  1. Open the HelloWorld-app.xml file from the Project Navigator. The file is opened in the Flex Builder text editor.
  2. In the rootContent node of the application, set the systemChrome and transparent attributes to the following:
    systemChrome="standard" transparent="false"
  3. Save your changes and then close the HelloWorld-app.xml file.

——–While point 2 should read as “systemChrome="none" transparent="true"” to achieve the end result.

Posted in Apollo, MXML | Leave a Comment »

Distort class(DisplayShelf Component)

Posted by vijayram on February 21, 2007

Ok, my approach is no comparison to this slick component by Ely Greenfield.
His approach is also to try and mimic a trapezoid and have the bitmap drawn into it.

http://www.quietlyscheming.com/blog/components/tutorial-displayshelf-component/

One can learn a lot from his component and now he has even made an interactive tutorial to explain, saving us from pulling out our hairs. Great stuff.

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

Rick at Stanford

Posted by vijayram on February 12, 2007

Rick Reitmaier ( Adobe, Tamarin JIT developer)  had given a presentation at Stanford University about the Flash Player ActionScript Virutal Machine.

This is the video link for his presentation here. I found it whilst googling.

The is one of the better presentation I have seen on AVMplus engine. He does a great job explaining the roadmap of the present VirutalMachine and what it took to get to this stage. I can say, I am pretty much clear now on what makes this present release of the VirutalMachine so important and how it makes this step, a revolutionay one for FlashPlayer as we know it.

The presentation runs for little more than an hour but is packed with valuable information and the QA brought out some interesting quirks. Personally I think its a must view for any ActionScript programmer. He talks about the JIT, Verifiers and GC during the later half of the presentation, which raised few valid questions.

One of the quirk which I thought interested me was the fact on an empty for-loop performance increase. He quickly spotted this to be a bug as it should have compiled to no code at all. I thought the same as well as I noticed this to be the case when I was testing the speed for int vs Number in my previous post.  I would have assumed empty loops would have been bypassed by the compiler. So I am not the only one who think this to be a bug!!

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

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 »

integer overflow

Posted by vijayram on February 4, 2007

Santosh Kumar over on the iGeeks brought to my attention about this interesting topic. I never have dug in deep to learn about this subject, since I know it could cause more harm 😉

He mentioned: ” While type casting from Number (64-bit double-precision) to int (32-bit integer) if Number value range cannot fit into integer than integer value is converted to default value ie 0.”

Interesting, but why should it default to zero?! That begged the question. Let me retrospect from my earlier post. I mentioned, anything over the range of Integer values, shall be internally operated as a “Number” data-type in Flash.

var i:int = 2147483648;
trace(describeType(i));
//-output
<type name=”Number” base=”Object” isDynamic=”false” isFinal=”true” isStatic=”false”>
<extendsClass type=”Object”/>
<constructor>
<parameter index=”1″ type=”*” optional=”true”/>
</constructor>
</type>

Wait a minute, we just came across an example of “integer overflow“! When an attempt is made to store a value greater than this maximum value it is known as an integer overflow. Why didn’t the compiler warn me? Apparently where is no compile-time warnings or run-time exceptions to let you this.
Integer overflows cannot be detected after they have happened, so there is not way for an application to tell if a result it has calculated previously is in fact correct. This can get dangerous if the calculation has to do with the size of a buffer or how far into an array to index.

Ok, time to understand what is happening here. Lets take the case of both the unsigned integer and signed integer overflows (there are overflows and underflows).
When an unsigned integer reaches its maximum value, it wraps around and starts over, much as a car odometer. Unsigned short integers can’t hold a number larger than 4294967295, so the value is wrapped around to 0.

var i:uint = 4294967296; //overflow
trace(i);
// output – 0

A signed integer is different from an unsigned integer, in that half of the values you can represent are negative. Instead of picturing a traditional car odometer, you might picture one that rotates up for positive numbers and down for negative numbers. One mile from 0 is either 1 or -1. When you run out of positive numbers, you run right into the largest negative numbers and then count back down to 0.

var i:int = 2147483648; // overflow
trace(i);
//output – -2147483648 (this is largest negative int value)

Why is this important to know??Supposing you are working with unsigned data-type, the memory would be allocated for it accordingly. If that value has wrapped around then there would be far little memory for it now available. Disaster. Or if you are comparing values with a signed integer and it has overflown to be a negative, it would it pass througn. Disaster again!! If an attempt is made to store a value in an integer which is greater than the maximum value the integer can hold, the value will be truncated. If the stored value is the result of an arithmetic operation, any part of the program which later uses the result will run incorrectly as the result of the arithmetic being incorrect.

Now, think of what impact this could have. One could exploit this if it has not been taken care for in the Flash Plugin. One cannot directly overwrite the memory but the exploitation can be subtle. This topic is out of the subject for this current post but you can read about it here on Wikipedia. Flash plugin was prone to heap buffer read overflow in the recent past.
Microsoft have there version of SafeInt class to help safeguard from this issue. All arithmetic is performed on unsigned values, which is very interesting.

Now back to Flash. Any number too big is just returned back as “infinity”. Clever!!! But why?
Lets just remember that Flash uses another data-type for arithmetic operations called “Number”. The Number data-type interoperates as “double” data-type which means it has a larger range of numbers it can store and display.

Through some debugging process, I came to know that Flash uses “int” data-type to represent any values between the range 2^29 (-268435456 to +268435455). I am not sure what happens to those extra 3 bits, though one bit would be used for the sign (+ or-). Anything over this range is held internally as a Number data-type to represent. What this implies is that, we do not have our flash player crashing if we have an overflow or underflow as this implicit casting happens internally. Anything over the range of Number will be called as “infinity”.

Posted in Adobe, AS 3.0, Flash, Programming | 3 Comments »

int vs Number

Posted by vijayram on February 1, 2007

This issue was highlighted by Sho Kuwamoto sometime back who recommends to use Number where ever possible. Grant Skinner made some additional test and has posted his results here.

While looking through the code on tamarin on the class construct for Number, it is defined as a 64-bit double-precision floating-point number while, int and uint are 32-bit each. So technically both int and uint use 4bytes in the memory whilst Number uses 8 bytes of memory.

From, the Flex doc it says: “When you store integer values with the Number data type, only the 52 bits of the significand are used. The Number data type uses these 52 bits and a special hidden bit to represent integers from -9,007,199,254,740,992 (-253) to 9,007,199,254,740,992 (253)”. Explains the 64-bit range.

By looking through tamarin, it is evident what the maximum and minimum value you can store for each of these data types.
For Number:
public static const MIN_VALUE :Number = 4.9e-324
public static const MAX_VALUE :Number = 1.7976931348623158e+308
For int:
public static const MIN_VALUE:int = -0x80000000;
public static const MAX_VALUE:int = 0x7fffffff;
For uint:
public static const MIN_VALUE:uint = 0;
public static const MAX_VALUE:uint = 0xffffffff;

I was actually digging through the notes on tamarin just to see how things work and why we have this variations in speed.
It so happens that, almost all the numbers ranges that we use to code falls between the max and min values of an integer (-2,147,483,648 to 2,147,483,647). Flash does an implicit conversion at runtime for any values we pass between this range to an integer. Even if you pass a floating point to a variable data-typed as int.How did I know this?

The flash.utils package contains a method called describeType. Equipped with this function, call this on your variable which contains the value and you shall the result as follows:
<type name=”int” base=”Object” isDynamic=”false” isFinal=”true” isStatic=”false”>
<extendsClass type=”Object”/>
<constructor>
<parameter index=”1″ type=”*” optional=”true”/>
</constructor>
</type>

Even if your variable is data-typed to be a Number it still is converted to “int”. Now what happens if we exceeds the rage for Integer? It is automatically converted into a Number as it has a larger range than integer. Clever! What about uint? It is again converted to int.

Now go back to Grant Skinner’s test results and you shall see why int outperforms in most cases. As you are aware, Number data-type can accepts decimal values and hence floating-point operator(multiplication and division) is quicker when data-typed to Number.
So to avoid this performance overhead of implicit conversion, its better to data-type your variable to “int” during addition and subraction and whilst division and multiplication is involved use “Number” data-type.

Technorati Tags: , , ,

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

native function

Posted by vijayram on January 31, 2007

Ok, this is a cool modifier. While I was looking through the notes on ActionScript 3.0, I did notice a reserved keyword called “native”. I had worked with native implementation in JAVA(JNI), so this really got me excited.Why?!

The reason being, the use of native functions indicates that the method is implemented externally. In a DLL maybe? ;). So, there maybe possiblities to call native windowsAPI from the swf…hmmm. Using this abstract modifier means that the method implementation is not provided in the class.Because an external method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature.

native function functionName();
class className {
native function methodName();
}

So I started rummaging through the Flash Player code, and voila they use native functions as a part of implementation. What this means is that the native functions available to the Virtual Machine is called for through this function call using ActionScript.

package
{
//pseudo-final – no user class can extend Class
public dynamic class Class
{
// {DontEnum,DontDelete,ReadOnly}
public native final function get prototype()

// Class.length = 1 per ES3
// E262 {ReadOnly, DontDelete, DontEnum }
public static const length:int = 1;
}
}

The above is the actual code for a top level Class construct in the Virtual Machine which is available on tamarin.
Ok, the next obvious step, can I call for it from my code and override it if possible?!

Sadly not!!!! It turns out that Flash Player uses this internally and I cannot use it in my code as explained here.

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

Garbage Collector

Posted by vijayram on January 31, 2007

Adding to the post on Stacks and Heaps, I had to link to this blog about the internal workings of Garbage Collector in ActionScript 3.0.

Grant Skinner on Resource Management . If that’s not enough, he has published his talks on Garbage Collector using visual simulators here.

*Some side notes:
– You cannot delete class members in ActionScript 3, if you want to cause a variable to no longer reference an object or value in memory, you should set your variable’s value to null instead of deleting it. [ myVar = null; ]
If all variable references to an object are null, the Garbage Collector will mark it for deletion and it will eventually be cleared from memory.
There is a post hereby Gordon Smith explaning the same.
– Ted Patrick has an interesting post on “flash.system.System.totalMemory” saying it just represents the memory allocated to the FlashPlayer. So it might not be the best util to check for memory leaks when you remove objects by setting it to null. You can learn about System.totalMemory here.
– FlashLite has this profiling for sometime now showing the heap memory usage. Pretty cool using the emulator tool. Any questions on that can be directed to IndiMad which is managed by Mariam.

Technorati Tags: , , ,

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