Tag Archives: AS3

Chinese Handwriting Recognition App

Unlike the iPad, the BlackBerry PlayBook has rather poor international keyboard support, with no method for entering chinese characters. I like the way iOS achieves this, so went about building my own version in ActionScript.

This was mainly an academic exercise and to help me to learn to write chinese. My approach was to sample the strokes drawn into the app as a series of up to 8 directions, including the relative position of a given stroke to the previous stroke, again as one of 8 directions. This pattern, represented as a string of numbers is then put through a smoothing algorithm, to remove some unnecessary noise and then compared with a dictionary of pattern keys, which may contain one or more suggested characters. If there are no hits, an advanced search occurs, by mutating the given pattern in specific ways, in order to find alternative suggestions. I can also find characters based on the next most likely character to the one you’ve just entered, using frequency analysis on given sample text.

The app will eventually be a PlayBook App, but is still unfinished and currently in ‘training mode’, so that character patterns can be trained into the database. It’s currently primed with some simplified sample data, from which it picks the most popular few characters to learn. If you write chinese, give it a go.

SmoothBitmap – How to enforce pixel smoothing on a Bitmap

A common oversight when using Bitmaps with loaded content is that Flash will revert a Bitmap’s smoothing parameter to false when you replace its bitmapData. It’s simple enough to fix, but since you may not know if someone is going to replace the bitmapData of a Bitmap you have created – then it’s often better to code defensively around it.

This little SmoothBitmap class is for just such an occassion. Instantiate it like a regular Bitmap and, no matter what another developer does with it, smooth pixels when scaling/rotating will be ensured.

CODING WRONGS – Where do I start with the bad?

It gets scary out there sometimes. During my freelance career I’ve worked at a lot of different companies and have seen such coding horrors as you cannot imagine. So I thought I’d start immortalising some of them – so that we can all learn better coding practices, by looking at the bad.

Starter for 10 – What’s wrong with this picture?

Did you spot the fubar? It’s not an obvious one.

This code potentially replaces a Bitmap’s BitmapData, without first explicitly disposing any existing BitmapData.

I see this kind of thing quite often and it’s the source of many a memory leak. AVM2 isn’t that great at dealing with this kind of situation and there’s a crucial difference between GC cleaning up out-of-scope objects for you and things like BitmapData: GC will reclaim the memory associated with objects ‘when it feels like it’, whereas explicitly calling the ‘dispose’ method of a BitmapData will immediately give you back that memory.

In the case of platforms with hardware accelerated graphics (such as mobile or set top box), the memory associated with the pixel data itself (video memory) will be reclaimed immediately.

The lesson?

Don’t make more work for the Garbage Collector when you can avoid it.

TextField.getRawText() what it does

I was recently creating an API that required extending TextField and happened across the getRawText() method. I assumed this returned the text from the field without formatting or something – so I looked up the AS3 docs for flash.text.TextField.

Nothing there – gee thanks Adobe. A quick search turned up this which, it turns out, isn’t quite accurate.

So, with a tad of testing, it appears that getRawText() returns the text, stripped of any HTML tags (if you had set htmlText). I now wonder if this is faster than using a RegEx to strip the tags and why Adobe didn’t document it?

Loan Shark – fast object pooling utility

LoanShark AS3 Object Pooling UtilityA couple of years ago, I created an object pooling utility for a games project I was building in AS3. Since then, I’ve used it quite a few times, in order to speed up apps and improve resource management, easing the load on the garbage collector by reusing objects instead of recreating them.

While object pooling isn’t a magic bullet to speed up every use case, it works especially well on things that are heavy to continually construct and destroy. A good example is my History of the World project, which uses an object pool for item renderers, instead of creating and destroying them as you navigate around – press ALT+CTRL to bring up the resource debugger, which shows a little information on its usage.

I recently updated the utility, improving its performance, adding features and putting loads of unit tests around it. It’s now hosted it over at GitHub. Using it is a simple as:

Fastest way to add multiple elements to an Array / Vector

In a simple situation, where you wish to add many elements to an Array or Vector, you might just do:

However, the sizes of both Arrays are manipulated for each loop, which will have an adverse impact on speed and memory usage. So, we could cache the length of the input Array and not manipulate it:

But we’re still growing the size of the output Array incrementally, which is very bad. Since we know input.length in advance, we could grow the output Array to its new size just once, before the loop:

This is OK, but still involves a loop. If only we could push multiple elements into the push method in one go. Well, we can – enter the apply method. Since Array.push accepts multiple arguments (something rarely used) and apply allows us to pass an Array of arguments to any Function, one line and we’re done:

This works out faster and more memory efficient than the other methods. It works nicely for Vectors, too. If anyone has a faster method of doing this, do let me know.

SWFIdle – simple flash idling utility

If you’re still churning out Flash banners, please use this!

swfidleI created this simple utility, called SWFIdle, to enable the Flash Player to lower its CPU usage while the user is not interacting with it. Since it’s possible to have multiple Flash instances embedded in one page (for example, a game and a couple of banners), I recommend that everyone uses this in their projects, so that players needn’t fight for CPU and give a worse name than it has already.

I know there’s the hasPriority embed attribute now. But:

  • That assumes you have access to the HTML that embeds your SWF
  • If no other players are present, it has no effect
  • There’s still usually little reason to be running your SWF at a high framerate if the user isn’t interacting with it
  • Flash banners with wastefully unoptimised drawing routines are probably one of the key reasons that Flash got poo-pooed off of mobile platforms and disabled on everyone’s laptops – CPU usage = battery usage!

Dependency Injection by Extension pattern

Since I’m not sure whether I have indeed invented a new design pattern here. So, alternative titles for this post include:

  • Dependency Injection without a Dependency Injection framework
  • Why misuse of the default namespace for tests is pure evil
  • How to make your code more testable without completely messing it up

The problem:
You need to use some kind of Dependency Injection (DI for short) to provision some System Under Test (SUT for short) in tests you’re writing, but can’t or don’t want to use a DI framework to do so.

Of course, the simplest form of DI is simply passing things to a constructor. But you probably don’t want to code every class to be handed every dependency at construction. And you definitely don’t want to expose the private parts of your implementation through some unnecessary interface. No, you really don’t!

I’ve seen scary examples of what I call ‘keyhole surgery’ on classes, either by abuse of the internal namespace to allow poking into otherwise private implementation, or just by making too many things public. Although the internal namespace (AKA the default namespace) is perceived to retain a sufficient level of encapsulation, it really doesn’t. Anything in the same package can jump all over it, so it’s somewhat of a loose interface. As such, you should never leave methods unscoped, letting them default to the internal namespace. You should also reserve the internal namespace only for when you are in control of all classes that will exist in the same package, such as when creating utility classes.

Loose interfaces are bad practice for a few reasons:

  • Clarity – anyone using the class will be confused as to the intentions of its interface
  • Stability – a class with such a loose interface is open to misuse and a recipe for failure
  • Cleanliness – code for tests does not belong in your production code
  • Testability – you should test a class through its interface, not its implementation
  • Flexibility – it is hard to refactor classes that leak implementation detail in such a way

The solution:
Well, this is one possible solution and ultimately just my suggestion. It’s especially useful when needing to refactor classes with overuse of the internal namespace, since you won’t need to change much test or production code. I call it the Dependency Injection by Extension pattern.

How it works:
You provide DI helpers as protected methods in your SUT and subclass it from within your test case, as a script-level class, to expose the DI helpers as public and/or use the constructor to do some of the DI work – allowing you to inject mocked dependencies for your tests. This has the advantage of not allowing anything else to meddle with your SUT, other than through its interface, of course. And, if anything in your production code wishes to extend your SUT, potentially overriding and messing up the interface, then that class should have its own tests anyway.

Example:
The following example shows a very basic class (SystemUnderTest) being extended from within its testcase (SomeTest) to allow injection and access to its dependencies, for the purpose of verifying its behaviour under given conditions.