Tuesday, June 12, 2007

Drawing Optimization

The flash drawing API is very simple to use, but problems arise when drawing lots of things on the same plane. What happens, as far as i know, is the Flash Player tries to render the line that's been drawn continuously, whether the line is actually contiguous or not.

Since the lines that are drawn are actually vectors the player has to calculate each and every vector in the line, every single time a new vector is drawn.

Naturally, if you have to calculate and recalculate the entire line before you can make the line any longer its going to take quite a bit of processing power. This results in a VERY VERY slow drawing API as the drawing grows and becomes more and more complex.

=========

My Workaround

Actionscript 3 has 3 different container objects, 2 more than AS2 had. Movieclips (same as before), Sprites, and Shapes. Now, Movieclips are the same old usual movieclips, they're objects with a timeline that can be animated.

Sprites become plain old flat static images when they're rendered, so they use very little power to be rendered. Movieclips try to loop through the timeline when they're rendered, adding a little to the processing time. Shapes are the same as Sprites but for speeds sake they have disabled most interaction with shapes.

The way i get around the slowing down of the drawing api is to split up the drawing as its being drawn. For example, when the mouse is pressed down it automatically creates a new container object, when the mouse is moved the drawing api starts drawing inside of the new container object.

When the mouse is released it stops drawing and caches the container as a flat image. Once the mouse is pressed down again, it creates a new container and because of this, a new drawing. This relieves the API of having to recalculate the entire drawing each time a new line is created.

There are a few advantages from doing it this way. The biggest advantage being it speeds everything up. It also opens new doors for extra interaction. Drawing things then scaling, moving, rotating, and deleting segments of that drawing.


Right now im not entirely sure which container I'm going to use, but of the 3 types that I can choose from I will definitely not use MovieClip and will probably use Shape if the interactive limitations don't get in the way.

Here's Keith Peters Input on the Shape vs Sprite debate: http://www.bit-101.com/blog/?p=899

No comments: