Archive for the 'Code' Category

new Vector - ActionScript 3’s Typed Array

Flash Player 10 introduces a new core data type to store lists of data called “Vector”. It’s almost identical to the vanilla ActionScript array we use today but with the added benefit of being strictly/strongly typed. Strict typing is very beneficial, it helps create error free code while coding and compiling, allows for understandable APIs and best of all, increases code execution performance.

Vector is a top-level class just as Array is so you will not need to import it.

Below is an example of creating a Vector for the int type.

 var vec:Vector.<int> = new Vector.<int>();

Notice that we define the type of Vector with the use of the less-than/lower-than brackets.

Here is an extended example using a Vector for holding Sprites.

class Foo  {

	private var _displayChildren:Vector.<Sprite>;

	function Foo() {
		_displayChildren = new Vector.<Sprite>;
	}

	public function addChild(child:Sprite):void {
		_displayChildren.push(child);
	}

	public function removeChild(child:Sprite):void {
		var idx:int = _displayChildren.indexOf(child);
		_displayChildren.splice(idx,1);
	}

	public function get numChildren():uint {
		return _displayChildren.length;
	}

}

If you attempt to add data of the wrong type to a vector, you shall receive a “Type Coercion failed: cannot convert” error. There is however some exceptions, for example if you have a int typed Vector and you try to add a String to it using a push or unshift method, it shall perform an int(string) conversion.

intVec.push("00123")
intVec.push("hello")
trace(intVec) // 123, 0

If you try this however .. intVec[0] = “00123″ .. it shall result in a “Implicit coercion of a value of type String to an unrelated type int” error.

The only method Vector didn’t pick up from its Array cousin is sortOn. Apart from that, every method from Array is available to use to manipulate Vector.

Vector does introduce something new though, the ability to force a fixed collection length. Below is an example on how to enable fixed length.

// int Vector with fixed length of 5
var vec:Vector.<int> = new Vector.<int>(5, true);
trace(vec.fixed) // true
trace(vec) // 0, 0, 0, 0, 0

While in fixed mode, the methods push/pop/shift/unshift/splice/..etc shall not work and shall result in a “Cannot change the length of a fixed Vector.” error.

If you go out of the fixed range using the square bracket notation .. vec[15] = 1 .. you shall find this error “The index 15 is out of range 5.”.

removeEventListener causing memory leak?

Update

After inspecting my dispatcher .. i find this awful mistake:

override public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0.0, useWeakReference:Boolean=false):void {
_node.addEventListener(type, listener, useCapture, priority, useWeakReference)
}

override public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void {
_node.addEventListener(type, listener, useCapture)
}

(DOH!!!!!!!!!! LOL)

——

To cut to the chase, in my personal AS3 framework, I’ve implemented deconstructors in all my DisplayObjects objects. The deconstructors mostly feature removeEventListener calls as I try to stay away from using weak refs. Today, while making a regular memory leak check using Flex Builder 3’s profiler, I noticed that I had a few DisplayObjects still latched onto an event dispatcher model object they were supposed to have let go of.

The first thing I did was to put a trace() in my deconstructor to make sure it was being called, yes it was. WTF? After some more digging, I then saw that this particular DisplayObject was flagged to not attach itself to the event dispatcher in the first place. (Wait, you mean that addEventListener hadn’t even been called in the first place? Yes!) So I switched the flag so that the DisplayObject would attach to the event dispatching model and guess what, this time it got GC’d after the deconstructor call.

So why is removeEventListener causing this to happen, the API docs define the method as:

“Removes a listener from the EventDispatcher object. If there is no matching listener registered with the EventDispatcher object, a call to this method has no effect.”

Has no effect, huh? But it seems to be doing something. Has anyone noticed anything similar to this?

Does anybody want ‘Anchor Sprite’ to be Released?

A couple of weeks ago I created a small video demo of a project of mine code named “Anchor Sprite”. It is a small ActionScript 3 library to manage layout and constraints of display objects within a pure AS3 project.

View Original Post

The original post received no comments so I assumed no body is interested or the video wasn’t working or people just didn’t get it. So I want to now implicitly ask if anyone would like me to release this library?

MaterialManager memory leak in Papervision3d: Great White

I’ve just starting using Papervision3d for the first time and I decided to go head first into the Great White build.

After completing a portion of work in my project I usually run the profiler to make sure objects are being collected. So, after finishing my Papervision3d portion of work, I ran the project in the profiler. I immediately noticed that I had a worry number of PV3D objects still hanging out, taking up a lot of memory. They we’re mainly math type objects such as Number3D and Matrix3D. And after exploring some more using the profiler, I was able to see that the culprit was the MaterialManager. And surprise , surprise, it’s a Singleton.

Now, I’m not one of those people who hate Singleton’s in projects, all I ask is that they keep themselves tidy. So that when a singleton is “idle”, it’s memory foot print is minimal. And yes I understand that “Great White” is in a pre-release status so I’m not on a rant and bitch session here. I would merely like to warm others who are using Great White for projects to be carful.

So, how does MaterialManager leak? It would seem that the following Dictionary just keeps growing and growing with complex Material objects.

private var materials:Dictionary;

And in the way I’m using Papervision3d; I end up with hundreds of bitmap BitmapMaterial’s and WireframeMaterial’s by having Cubes covered in the BitmapMaterial’s fly on to stage and then off again. Once I remove the Cube from the Scene3D, I expected the Material to be GC’ed because I saw no hard deconstruct method. But no, I saw this Dictionary becomes quite large, very quickly.

To work around this problem I temporally commented out the body of the registerMaterial method so that my Material would never be added to materials:Dictionary.

public static function registerMaterial(material:MaterialObject3D):void {
//getInstance()._registerMaterial(material);
}

But you may need to build your own work around if you’re using shaders as the MaterialManager seems to be connected to ShadedMaterial’s. Maybe you could call init() on MaterialManager once you’re finished with your papervision3d portion of the project. Or work closely with MaterialManager when removing objects from the Scene3D.

I’m sure this issue shall be corrected for the final release of PV3D 2 but until then this work around will be working for me.

ActionScript 3 Layout & Constraints - Video Demo

Around the middle of December I decided to see if I could improve my ActionScript 3 life a little by creating a very basic layout and constraints framework. I thought it would be the perfect project to help speed up my overall development times.

Starting off, I didn’t plan the framework at all, I just kept coding until I got to the end result which, is usually the way things work for me. And after the couple of tinkering around down days, I ended up with a decorator pattern that I could apply to any existing DisplayObject.

This means that you don’t have to apply this framework to the whole application. The stage can stay as a Sprite; your existing components will still display where you told them to display. This framework can be added to any existing project without the need to upgrading anything and without the fear breaking anything which, I think is the best thing about it.

Unfortunately, I shall not be releasing the framework today. I feel that I can still improve upon it and clean the API a little. But I am attaching a video “walk through” of the API and a link to the code I use in the video.

Disclaimers:

  • This is my first ever video! - be nice
  • It’s unedited and done in a single take .. eeek!
  • I tell a tiny lie close to the end about an offset being a pixel value when it was in-fact it’s a percentage .. doh!
  • The Quicktime movie isn’t hinted for streaming .. sorry

View Code - Click Here

Link to Video (for if you can’t see the embed)

If you have any feedback or questions please feel free to leave a comment.

Also, if you are living in the Bay Area .. please remember that the first San Flashcisco user group meeting is on Thursday (Jan 17th 08). For more information, please visit SanFlashcisco.com

Crazy AS3 Runtime Error

In all the months I’ve been authoring ActionScript 3, I’ve never seen a runtime error as cool as this:http://thebackbutton.com/misc/best_stack_dump_ever.txt(note: some package/class names have been masked)I managed to get this error when I called a temperately disabled function, renderPlotsHandler(e:Event):void. And when I say disabled, I simply mean that I added a ‘return;’ to the first line of the function.So, I have no idea how I managed to get this error if the function did nothing?!Crazy :)

Generate Filter ActionScript 3 From DisplayObject’s

Filters in Flash are great, but I do have one big problem when working with them. As I’ve stated many times in my blog, I’m quite the ActionScript purist and I hardly touch the Flash IDE or FLA files. Thus visualizing a filter purely in code can be quite a pain. So sometimes, I’ll open up the Flash IDE and work on creating the filter settings with the help of the nice GUI controls. The problem is then converting all of my filter settings back into reusable ActionScript code.

To make this process a little easier, I took two minutes out to create an ActionScript class that accepts a display object as an argument, and then traces the ActionScript code needed in order to recreate the filter to the output console.

Check it out …

Zip File | Source

See the example below

Read more »

Recruiting: San Francisco Flash Platform User Group

Disclaimer: If there is already a San Francisco Flash Platform user group in existence, please let me know and ignore this post.

From my observations, I’ve heard of many Flash user groups from all around the world. The first few that spring to mind are based in Boston, LA, London and Belgium. They all seem to attract a good following and these people seem to want to share what they know and love with other like minded individuals.

So, what’s the motivation behind this post. Well, for the past few years, I’ve been a bit of a Flash lone wolf, as I’ve always ended up working as the only ActionScripter in my workplaces. Even now at Sony, I’m working in an office full of C engineers and one IA person. I have no one to talk ActionScript with!

At lunch times, I’ll sometimes take the short walk down Townsend St to get a burger from the Holy Grill, passing the SF Adobe building on the way. And I feel that I can’t be alone in my ActionScript world with the Flash mother-ship right next to me. haha.

For these reasons, I feel compelled to start a San Francisco based Flash Platform user group (see Disclaimer). To start recruiting people, I’ve setup a group hosted on Facebook (yes, I know it’s not the best solution and it’s only temporary) so, if your based in the Bay Area, with a love for anything Flash / Flex / AIR / ActionScript / MXML related, I would encourage you to join in!

When and if the group gets a big enough following, I’ll make another posting, both on here and on Facebook, outlining plans for a first meet to discuss how the group shall be organized.

I feel that any kind of group should be as democratic as possible, so please, if you have any suggestions or feedback on what I can do to make this group a success, please don’t hesitate in leaving me a comment or email.

Let’s make it happen! :)

Speed up Flash with Stage Quality

Ever since the release of Flash 8, I’ve rarely published a Flash project with a HIGH stage quality. If you know why, then you can skim this post and leave me a high-five in the comments, if not then read on …

So what’s stage quality I hear some of you asking? Well, you may of seen it feature within the default context menu of the Flash Player. And this small setting defines how certain elements are anti-aliased/smoothed within your Flash application.

Here are the four available quality settings:

  • StageQuality.LOW - Graphics are not anti-aliased, and bitmaps are not smoothed.
  • StageQuality.MEDIUM - Graphics are anti-aliased using a 2 x 2 pixel grid, but bitmaps are not smoothed.
  • StageQuality.HIGH - Graphics are anti-aliased using a 4 x 4 pixel grid, and bitmaps are smoothed if the movie is static.
  • StageQuality.BEST - Graphics are anti-aliased using a 4 x 4 pixel grid and bitmaps are always smoothed.

So, HIGH and BEST sounds really awesome right? Think again! Let’s take a brief look at (vector) graphics:

Vector graphics (also called geometric modeling or object-oriented graphics) is the use of geometrical primitives such as points, lines, curves, and polygons, which are all based upon mathematical equations to represent images in computer graphics. It is used in contrast to the term raster graphics (also know as a Bitmap), which is the representation of images as a collection of pixels, and used as the sole graphic type for actual photographic images.

When Flash renders a vector graphic, the bitmap result of the vector data is calculated on the fly. This can be awfully taxing on the users machine depending on how complex the vector graphic drawing is. A large part of this calculation goes on smoothening-out all of the lines and edges so that you end up with something that doesn’t look jaggy, and this is where the quality setting comes into play. You can think of the quality setting as accuracy level of anti-aliasing. So, the higher the accuracy, the more work has to be done when rendering.

So what changed in Flash 8?. Well, Bitmaps staged a military coup and took the crown away from vector graphics of course (err). First off, we got the cacheAsBitmap flag, this took a lot of stress of rendering complex vectors away such as UI components. Then we got the awesome BitmapData class (its like a freaking Swiss army knife!), and finally we got Advanced embedded text rendering. The new text rendering is the most important reason for not using HIGH anymore as it does not suffer from jaggies in lower modes.

Back in 2005, I created my first Flash 8 website while working at Sparkart for Mike Shinoda’s side project, Fort Minor (http://fortminor.com/site.php). I really wanted to dip my toes into as many Flash 8 features as possible. So, in the site you’ll see blend modes, blurs, vp6, BitmapData (used for image flattening) and advanced text. But the best thing about all of this is that the site stage quality is set to LOW! Now, this site wont win any awards for usability and the code is rushed (~2.5 week project) but you’ll see how I was able to push the speed of the animation by setting the quality to LOW without really loosing anything visually. An important thing to note from this is that the site has no vector graphics, its all bitmap based.

This brings me briefly onto Papervision 3D developers who actually inspired me to write this post. Today, I came across the papervision based game “Downtown Maze Master” from Nissan. I noticed that the game was running in HIGH mode through the games context menu as my MacBooks core was running at 77% and my laptops fan soon fired up. Thanks again to the context menu, I took the setting down to LOW and immediately watched my core usage go down to 54% without any anything visually bad happening in the game. I’d usually expect papervision3d developers to be close on the bleeding edge of Flash, so I wonder why the quality setting was forgotten. And this site is only once of many papervision3d sites guilty of this sin. End of rant, spread the word :).

Bitmaps rock your sock in Flash, but what about if you need to resize bitmap elements? Well in my world today, I work mainly on creating application UIs vs website experiences, and my best friend is 9 slice bitmap scaling. To read more about 9 slice resizing, check here. But what about if you still need to utilize vector graphics and run with a LOW setting? Well, you may still need to use the HIGH setting if your vector is quite dynamic and/or shape tweened. But if your only planing to pan your vector around the stage, then you might be able to use LOW successfully if you “flatten” the vector to a Bitmap in HIGH mode, then switch back to LOW.

// ActionScript 3

stage.quality = StageQuality.HIGH;
var shape:Shape = new Shape();
shape.graphics.lineStyle(2,0xcc00cc);
shape.graphics.drawCircle(100,100,100);
var bitmapCanvas:BitmapData = new BitmapData(200,200,true,0xffffff);
bitmapCanvas.draw(shape)
stage.quality = StageQuality.LOW;
var circleImg:Bitmap = new Bitmap(bitmapCanvas);
addChild(circleImg)

The result will be a wonderfully anti-aliased circle shown in LOW mode. This method also works well for cutting down the number of elements on stage in general, just think of it as an uneditable cacheAsBitmap.

The lesson I want you to take from this post is to always play with your default quality mode before pushing your site live. You just might get a pleasant surprise :).

I Need To Contribute ActionScript 3

I want to start an open source AS3 project(s) here on The Back Button. Woo! One problem though, I don’t know what it is I want to create! :(

This is where I need you, the community, to pitch in ideas. So, what are you missing in your day to day ActionScript life’s? What do you find yourself doing over and over again? What do you hate most about ActionScript 3?

I just love creating reusable, flexible, purist code and would love to solve as many problems as I can.

So, please leave comments here or email me directly at bustin:at:gmail:com

Let’s do it! :)

p.s. I’d rather stay AS3 only right now, so please, no Flex Framework/MXML request.