Mar 21 2010

AS3 snippet #4: Returning Booleans

When returning a Boolean you can do the validation inside the return statement. Usually I would do something like this:

function doTest():Boolean
{
    var returnValue:Boolean = false;
    if (someValue > otherValue) { returnValue = true; }
    return returnValue;
}

Instead, you could shorten it down to only one line of code like this:

function doTest():Boolean
{
    return (someValue > otherValue);
}

doTest will return true if someValue is greater than otherValue. Pretty neat huh?


Nov 28 2009

Garbage collecting in AIR

At a recent project I had to make a video loop indefinitely and most importanly: seemless. I tried all kinds of different methods, including using FLV, F4V, M4V, FLVplayback component, the Video class, embedded video and a few other. The only solution that worked was (in my opinion) the most outdated one.

I setup a new SWF file in Flash Professional and imported the video to stage. I chose to create keyframes for each frame of the video, set the JPG compression rate to 100 and then exported the video as a SWF. This was the only method I could find that would make the video loop seamlessly. It solved one problem but introduced another.

As the application ran I monitored the memory usage and soon discovered that the application ate up more and more memory for each time the video looped. To solve this problem I forced the garbage collector to run each time the video completed a loop. This kept the memory usage stable and the application has now been running for about a month.

This is how you run the garbage collector:

System.gc()

May 2 2009

AS3 Snippet #3: Remove all childs

I code snippet I tend to use quite often. And one that I tend to forget how I wrote the last time i used it.

while (this.numChildren > 0)
{
    removeChild(this.getChildAt(0));
}

Update:

And when you want to remove a child as a part of an event handler, do this:

event.target.parent.removeChild(event.target);

Let’s say you want to delete the button you just clicked. The button dispatches an event, and this line of code goes in the event handler. event.target is the button (or what ever object you clicked). It does look at bit strange, because you have to tell the button that it’s parent should delete the button. The button can’t delete itself.

Note:

If you’re working with Flex, use this.removeAllChildren(); Thank you Bjørnar :-)


Aug 11 2008

Flash CS3: Adding custom classes to MovieClips in the library

Today I was tearing out my hair in frustration of a problem I just couldn’t seem to figure out. And the solution was just about as stupid as I had hoped it wouldn’t be.

The case was as followed: I’m putting MovieClips in a SWF for use as a library in another SWF (I’ll call it master SWF). The library SWF has a custom document root with a function that helps me return the MovieClips I need. Some of the MovieClips in the library are extended with custom classes.

When I tried to return a MovieClip from the library SWF I would get an error message saying the MovieClip doesn’t exist. Even if the class has been set up correctly, the package names are fine, and everything looks right.

The library SWF resides in the root, together with the master SWF. This way I can keep the same document root in both SWF’s and share classes between. The custom class for the MovieClip I tried to return is in package bb.page, and the name of the class is Frontpage.

In Flash I set the linkage to bb.page.Frontpage, compiled, and expected a positive result. But no. I tried moving everything down to root level, thus flattening the whole directory structure. Removed the package name from the Frontpage class and gave it a try. It actually worked. But it’s not an optimal solution because I don’t want to mess up the root directory with tons of files.

Moving everything back in to the directories they came from, I gave a stupid idea a try; renaming the MovieClip in the library. And guess what? Renaming the MovieClip from ‘Frontpage’ to ‘bb.page.Frontpage’ did the trick. I haven’t bothered trying to figure out why it’s like this, but it seems like it just is.

So, conclusion to this;

Make sure the name of the MovieClip is the same as the linkage class.

Example: class Frontpage resides in bb.page. Linkage class is therefore ‘bb.page.Frontpage’. This will also have to be the name of the MovieClip.

UPDATE August 12 2008

While at work today I spent a few hours figuring out how to deal with this problem and came to a new conclusion; what I’ve written in this article is wrong. I haven’t managed to come to a perfect solution, but good enough for the project I’m working on. I’ll be back later to write more about this.

In the mean time, and if you are looking for a solution to a similar problem, try searching for keywords like as3 asset managemt, resource management, external libraries and such. I found some articles that gave me a better understanding of what I’m dealing with.


Aug 5 2008

Actionscript: Accessing MovieClips from an externally loaded SWF

For the time I’m working on a website and so far I’ve only spent some time doing research around all the ideas I have. One of them was to put all MovieClips in one externally loaded SWF. Loading the SWF is easy, but how do you access the individual MovieClips? Easy as 1-2-3!

For loading the assets I use BulkLoader; so far it seems like a pretty good alternative to writing a bunch of code myself. I like.

In the assets.swf I have only stuffed the library with MovieClips, and the ones I’d like to access from the outside are set to linked. Nothing is placed on stage. The document root to the SWF is set to a custom class. It is within this class the trick lays. And the trick is to set up a public function that returns any MovieClip to the parent SWF.

The parent SWF loads assets.swf and puts it in a variable. The public function in the assets document class is now accessible by dot syntax. By calling this function we can easily add MovieClips from the assets library to any MovieClip in the parent SWF.

Here’s the document class for assets.swf:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package
{
	import flash.display.MovieClip;
	import flash.utils.getDefinitionByName;
 
	public class Assets extends MovieClip
	{
		public function Assets()
		{
		}
 
		public function getAsset(s:String):*
		{
			var a:Class = getDefinitionByName(s) as Class;
			return new a();
		}
	}
}

What this does is first of all import getDefinitionByName from the flash.utils package. This is a function that will return any object based on the string you give it. Second, and last, is setting up a generic public function that will look for and return an object with the name you provide it with.

In the parent SWF you would set up an eventHandler that puts the loaded SWF in a variable, and then call getAsset(). Like this (note that I’m using BulkLoader):

1
2
3
4
5
6
private function mclibLoaded(e:Event):void
{
	var lib:MovieClip = loader.getContent("mclib");
	var p1:MovieClip = lib.getAsset("Page2");
	keeper.addChild(p1);
}

loader is the name of the BulkLoader object, and keeper is a MovieClip on stage.

Rather easy, right?

If you’re interested in knowing more about BulkLoader, take a look at the documentation.
The generic function I’ve written here was taken from Big Spaceship Labs. They did it in a more elegant way than I initially did. Don’t thank me, thank them.


Jun 11 2008

Papervision3D: workaround for onReleaseOutside

I just stumbled across a very simple way of achieving an onReleaseOutside event when working with Papervision3D.

Now, why would I bring up Papervision3D in such a setting? If you, like me, have included a Papervision3D scene on a stage where other 2D objects (like MovieClips and other Flash components) are scattered about, you have probably seen a few unexplainable events happening.

I’ve only done a few tests with PV3D and Flex, but it seems to be easy to limit the size of the 3D scene to the boundaries of a component. But when adding a PV3D scene in a Flash project (creating an instance of a PV3D class and adding it to stage using addChild()) other rules seems to apply.

Once I tried to limit the size of the Papervision3D (PV3D) scene to just a portion of the stage, and center it. But the bloody scene kept taking over the entire stage of the parent class. The result was that coordinate 0,0 i the PV3D class was aligned with 0,0 in the parent class. Way out of the area where it was supposed to be displayed. I managed to solve it somehow…

Today, working on a different project, I was facing a different challenge. I have a PV3D class added to stage. This class has a few public functions which I intend to access from the parent class using buttons and whatnot. These buttons and whatnot are added on a level (z-index) above the PV3D class, making them visible at all time. You could say the buttons are the GUI, and the PV3D class shows the content.

Listening for MouseEvent.MOUSE_DOWN on the button is easy, but adding a function for when releasing the mouse button outside of the button wasn’t that easy. I did a bit of googling and found some answers here and there. Derrick Grigg wrote a post about the issue. Some people dicussed it at ActionScript.org, where Tink gave a simple solution. And Senocular wrote about it over at Kirupa, confirming what everyone else has written; add an eventListener to stage which listens for MOUSE_UP events.

That’s a clever solution, and an easy one too. At MOUSE_DOWN you add an eventListener to stage which listens for MOUSE_UP events. When that event fires, it calls a handler which removes the eventListener from stage. Simple, and it works. Except for when you have a PV3D object covering the stage.

Even if the PV3D object is empty and therefore seems quite transparent, one would think that the stage is clickable. But it isn’t. The eventListener on stage will never fire because of the PV3D object. The solution must be to add an object above the PV3D object and make that one listen for MOUSE_UP events. But wait a second! That would make the PV3D object unclickable. We must make the listener object appear temporary.

We could use addChildAt and removeChildAt to dynamically place the object above the PV3D object, but underneath the button, and then remove it when not needed. But that would require us to keep track of where we place various objects and making sure we remove the right ones and so on. Sounds like hassle.

I decided to place a permanent MovieClip on a layer between the PV3D object and the button. Yes, the exact opposite of what I’ve just wrtten. It’s permanently stuck to stage, but appears temporary. This object is empty for most of the time but filled when needed. Filling the MovieClip is easily done by accessing the graphics property of the MovieClip. When I click the button I run a Fill() command to fill the object with a white color. When the button releases I simply run a clear() command to remove the fill. This way I can turn the object on or off.

The object also has the eventListener permanently attached making it unnecessary to add and remove the eventListener for each click and release.

The object has no alpha property set to 0, but yet it is transparent. I read somewhere that someone had found out that using blendMode was faster and less CPU intensive that using alpha = 0. I know from experience that semitransparent objects can reduce performance (and in this project, performance is an issue), so I chose to stick with blendMode. When I attach the object to stage, I set blendMode to multiply. Multiplying the color white to any other color makes it invisible. Wikipedia hasn’t the best explanation of multiply, but you’ll see that the formula is result color = top color * bottom color / 255. Since the bottom color remains unchanged when multiplying with white, white would represent the value 0. And multiplying anything with 0 results in 0.

So there you have it. Filling and clearing a MovieClip to turn it on and off.

As a final note I’d like to add one thing. If one would like to do something with the button (like changing it’s state) one would probably fall for the temptation of using the event object returned by the MouseEvent to refer to the button (event.currentTarget.something). Keep in mind that there are 2 separate objects calling this handler, making the event object refer to 2 different objects. So, as in my case, where I wanted to do things with the button, I had to directly refer to the button’s instance, and not use the event object.

Here are a few lines of code from my project:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class someclass extends MovieClip
{
	private var _square:Sprite = new Sprite();
	private var _btn:ButtonClass = new ButtonClass();
 
	public function someclass()
	{
		addChild(PV3D); // Add the PV3D object
 
		_square.blendMode = "multiply";
		_square.addEventListener(MouseEvent.MOUSE_UP, scrollRelease); // Listen for button release
		addChild(_square);
 
		addChild(_btn);
	}
 
	// This function has been added to the _btn object
	private function scrollPress(e:MouseEvent):void
	{
		_square.graphics.beginFill(0xFFFFFF);
		_square.graphics.drawRect(0, 0, 500, 250);
		_square.graphics.endFill();
	}
 
	private function scrollRelease(e:MouseEvent):void
	{
		_square.graphics.clear();
	}
}

Jun 2 2008

Actionscript: Outputting a grid using only one for-loop

Sometime this winter a friend of mine (Knut Urdalen) introduced me to a part of mathematics called modular arithmetic. Now that is a nifty little thing.

In modular arithmetic, or modulus if you like, numbers reset themselves when reaching a given limit. Modulus is also known as “clock arithmetic”, and the clock is a very good example for explaining modulus.

A 12 hour clock has a limit of 12, making the hours reset at 12 o’clock. So instead of becoming 13, it simply jumps back to 1. The same thing happens with a 24 hour clock, but at 24 hours instead of 12. This is as simple as I would’ve explained it, but Wolfram has a more in-depth article with links to further reading. I’m sure Google has even more.

In ActionScript you can use modulus like this: x = y % z. Which reads like “x is y modulus to z”.

Following the example of the clock we would have to do a modulus of 12 on the total numbers of hours since the beginning of time to get the current time. Why? Ever since we started keeping track of time the numbers of hours have kept increasing. Time never stops. So instead of saying “oh, the time is 87654826253745 hours”, we do a modulus of 12 on 87654826253745 and get 7. And by looking out of the window we can tell if it is morning or evening.

Modulus can however not be used to count the number of turns the hour hand has turned at 87654826253745 o’clock. It only knows when it has reached the limit, not how many times it has turned.

So, as you probably have guessed already modulus is a drop dead simple way of outputting grids. And this is how I would’ve made a grid of images:

private _max:Number = 20; // Total number of items
private _rows:Number = 5; // Items per row
private _width:Number = 100;
private _height:Number = 100;
 
private function createGrid():void
{
       var ix:Number = 0;
        for(var i:int=0; i<_max; i++) // Iterate through all items
        {
                var col:Number = i % _rows;
                col==0 ? ++ix : void;
                x = ix * _width;
                y = col * _height;
    }
}

Let’s look at each of the lines;
01 : define max number of items in the grid
02 : define max number of items in each row
03 & 04 : width and height of each of the items
08 : x position of row <em>n</em> (increases for each new row)
09 : loop through all items
11 : col is ‘current item’ modulus to ‘items per row’
12 : if col has reset, increase ix by one. Here we jump to the next column
13 : place item at x position ‘ix * _width’
14 : place item at y position ‘col * _height’

And that’s about it. Simple, right?

If anyone of a more mathematical kind of person discovers something wrong, or would’ve explained modulus in a better way, do arrest me. I’m still learning.


Apr 13 2008

Making a YouTube-esque video player in Flex

Earlier this week I finished a project for one of our clients. The client produces quite lot of video content, and wanted a video player that could be embedded in other websites. This was a rather straight forward project where I got to use a lot of things I already knew. But still I learned a few new things.

One of the requirements was the file size of the finished SWF. I’d like to keep it to a minimum with no preloading before the buffering starts. It has to look good, so some graphics will have to be included, but the video is what people wants to see. One of the tricks to reduce filesize and loading time is avoiding using container classes like the canvas, hbox, vbox and the likes. The container classes are handy and useful for laying out your components. But they contain a lot of functionality I didn’t need, and whenever you add a component to a container class, it will redraw itself. So the initialization process will be slower. (Note to self; put all components inn the container before you add it to stage. That will reduce number of redraws)

As a general rule; if all you need to do is place the component at a particular coordinate; try avoiding using container classes and rather use the x, y properties of the component itself. It is very tempting to let the container do the positioning for you, but with a few extra lines of code, you can most likely avoid using them.

So I discarded the thought of using any containers at all. So how do I approach the placement of the components? Well, first of all I need to find the dimensions of the FLV, and then place the control bar accordingly.

When I first started making Flex apps, I read a lot of articles about developing with Flex. One of them was about the application startup order. I realized that was a subject worth paying attention to, but never did. And all of my Flex apps so far have worked fine. But this time I started to understand the importance of knowing how your Flex app builds itself up.

The video player reads a few FlashVars at startup, one of them being the URL to the FLV. Now, the dimensions of the FLV can vary from file to file, so sending the width and height will only cause more work to be done server side. Flex (and Flash) have a very easy to use event for retrieving the meta data of a FLV. So I decided to keep the number of FlashVars down to a minimum, and rather rely on the MetadataReceived event.

The MetadataReceived event doesn’t fire until the first part of the FLV has been read. So, since the layout of the video player is waiting for the dimensions of the FLV, I have would have to put this function at the earliest possible stage of the creation process. Sounds easy, but there was one thing that I didn’t think would matter but did; buffer time.

I was thinking about implementing some kind of dynamic buffering routine to take in account of the various bandwith’s people have. But the video’s are rarely longer than 30 seconds and on an average of about 6-7MB. So I figured it would be sufficient to just set the buffering to about 25-30% of the total playtime. And so I did.

Now, what happends when you set the bufferTime property of the videoDisplay component to e.g. 5 seconds, is that videoDisplay will wait until the buffer is full before triggering the MetadataReceived event. I don’t see any logical reason for this, but that’s the way it is. The solution to this is simply setting the bufferTime to 0 at initialization. The MetadataReceived will then trigger immediately, giving me all of the details on the FLV I needed. In the event handler for the Metadata-event I simply adjust the bufferTime up to the desired level. It is important to set the autoplay attribute of the VideoDisplay to false, or else the video will try to play immediately since the buffertime is 0.

At this time I have all of the information I need for placing the control bar. In the event handler for MetadataReceived I simply set the control bar’s y parameter to the height of the video. And voila! The layout is finished, and it all happend withing a fraction of a second.

To give the viewer an indication of the buffertime, I simply used a ProgressBar component. And on top of that I put an HSlider for scrubbing. In retrospect I now see that the ProgressBar is overkill for this purpose. It features a lot of functionality I don’t use, and I could have managed to achieve the same result using a Sprite which I scale in width (just like with the good old preloaders we made when AS1 and 2 was the big thing).

I mentioned earlier that I didn’t want any preloading of the application. But Flex throws in a preloader no matter what. In many cases this is a blessing, because you don’t have to make it yourself. But in this case, it’s a fair bit annoying. I guess it has to be there because of the creation process, which can take a few seconds -even on tiny applications. So my only option was to make it not look like the standard Flex preloader. I found a few articles on customizing the Flex preloader which helped me. Luckily, this doesn’t take more than a second in this application, so I simply used the client’s logo as a preloader. No indication of any progress at all.

These are the few things I learned while working on this project, which will most likely help me attack my next project in a better and more efficient way. Now, there’s one more thing I’d like to make a note of. And that’s something I didn’t learn.

It seems to me the VideoDisplay component doesn’t have any events for when the file is not found. I use the debugger version of the Flash Player, and that throws me a large error message saying the file was not found. It would’ve been better (in terms of usability) for me to trace this error using events instead, and then outputting a message onscreen saying “file not found”, or even showing a video where someone says “Sorry, file not found. But you might want to look at these videos…”. I could probably have used NetConnection. If there are anyone out there with an idea, or even better; an answer to this, please leave a comment. I’d love to hear about it.

Resources
Flex 3 – startup order
David Colettas slideshow on Flex optimization. It’s only a slideshow, but there are a few good tips to pick up.
Powered By Hamsters has a few good tips on optimizing a Flex app.

Alagad – Skinning with Flex 3 CSS Explorer
Adobe Devnet – Using CS3 to design styles and skins for Flex 3
Flex 3 Help – Applying skins. Some code examples of how to add skins to your components

Ted Parick – Flex custom preloaders
FLEXibleMySelf – Custom Preloader (Flex 3)

Always helpful:
Flex 3 Language Reference
Flex 3 Style Explorer


Apr 7 2008

totalTime and MetadataReceived from VideoDisplay object in Flex

Interesting (and more than a bit annoying) observation; neither the property totalTime or the event MetadataEvent.METADATA_RECEIVED will trigger unless the buffer is full.

I just discovered this as I tried to dynamically set the bufferTime to be 30% of the total playtime (I calculate the bufferTime using totalBytes and bytesLoaded). But as I traced values like totalTime, I noticed it would stay at -1 until the video started playing (in other words; the buffer was full). Just for the sake of curiosity I set up an eventlistener listening for the duration property of the MetadataReceived event object. Interesting enough it wouldn’t trigger until the buffer was full.

It has been filed as a bug at Adobe’s Flex Bug and Issues Management System.

Possible workaround:

  1. set bufferTime to 0 at initialization (this would hopefully trigger the READY event (or MetadataReceived if you prefer)
  2. catch the totalTime value
  3. pause/stop the video
  4. increase bufferTime (or skip number 3 and go directly to number 4. It might work?)

Technorati Tags: , , , , ,


Apr 7 2008

AS3 Snippet #1: Copy text to clipboard

A useful little snippet of code for when you want to copy text to the clipboard:

System.setClipboard(source.text);

Where ‘source’ is the id of e.g. a text field.