PixelBlitz Engine Logonews icondownload icon

Archive for the ‘ActionScript3’ Category

651:Announce Demo by GYW

Tuesday, October 21st, 2008

squize and ngfx of Gaming Your Way infamy have released a lovely little Flash demo called 651: Announce. It’s a typically old-school demo but with a lovely modern feel to it. squize pumps out the polys with some smooth PV3D sections (you ought to try Away3D mate!) and while the different parts feel slightly disjointed (few transitions from one to the other) they each stand up well in their own right. From pretty rotating plasma, to gunmetal spheres and the neat voxel landscape trip right at the end, this is well worth watching.

Oh and squize: Thanks for the greets :) and I was glad to see you got this released! Surprised you managed it so quickly given how you admitted you like to procrastinate about these things rather than do them :)

You’ll need Flash Player 10 to view it: http://blog.gamingyourway.com/content/binary/index651.html

99er by evoflash (the best Flash demo yet)

Friday, October 3rd, 2008

I’m ashamed I didn’t pick this up since now as it happened back in August, but evoflash released their 99er demo at Assembly 2008 into the browser contest there and won. When you watch it, you’ll understand why! A truly amazing example of what can be done with Flash (and the Away3D engine). Click the picture to watch the demo.

Or go here: http://evo.bombsquad.org/99er/away3d/99er-evof.html

It’s stuff like this that makes me want to use Away3D instead of PV3D! But the new BSP enhancements I saw at FOTB08 in PV3D were very impressive.

Damn it’s great to have so much choice :)

PixelBlitz - Optimised RenderLayer part 1

Friday, September 19th, 2008

Tonight I updated the PixelBlitz Engine with a small but significant feature. I attacked the issue of redundant redrawing of elements, and updated both the PixelSprite and RenderLayer classes so they no longer refresh all of their content if nothing has actually changed since the last render call.

Sounds simple and it is, but it makes a world of difference to the speed of things.

I’ve been researching how beneficial adding a dirty rect system in the engine would be. The problem I have is that it’s all dependant on the type of game. For example a vertical shooter, with a scrolling background and bullets flying everywhere, would have no benefit at all - if anything the extra calculations may even slow it down. But in a sedate game, especially one with large (overlapping) objects, it could be a dream.

So, still in two minds really - perhaps it’s something we allow the user to disable at will.

For now I’m going to optimise the 2DRenderer further by making it only copyPixels() from the area of the RenderLayer that has changed. At the moment it grabs a full sized layer even if the layer only contains say a 64×64 sprite somewhere.

Anyway until then the new code is available in svn.

Is “Pixel Blitting” in AS3 really worth the effort?

Friday, September 19th, 2008

While planning some new routines for the PixelBlitz engine tonight one thing struck me - is it actually worth it?

There are a number of articles across the web about pixel blitting in AS3 (most of them at 8-bit Rocket :) but I did wonder if anyone had actually done some tests to see just what difference it makes in real-world terms.

After all, why mess around “blitting” things about if using a Sprite or MovieClip is just as fast anyway? Infact you could easily argue that using a native Flash display object gives you far more control (as you get to play with scaling, alpha, rotation, animation, sound events and more, easily).

Another thing also struck me - when building up the display for render the AVM will automatically use a dirty rectangles system. If you’ve got two overlapping movieclips then it won’t waste time drawing pixels that would otherwise be obscured by the one in front. Traditional blitting on the other hand doesn’t care about this, it’ll gleefully copyPixel() until the cows come home, pasting image after image on-top of each other (PixelBlitz suffers from this issue too).

[ Side note: It's true we could add a similar dirty rectangles system to Pixel Blitz, to avoid copying data when it's guaranteed to be overwritten further up the chain - but this is not something we've found a fast way to do yet (the potential alpha channel of a bitmap causing the most problems), the overhead of sorting and checking for overlaps is always taking longer than just brute-force copying everything each time (if you can help, email me!) ]

Tonight I decided to write two simple tests. They would measure the speed of the AVMs dirty rectangle system vs. raw bitmapdata copypixel power. I was interested in 3 things - the overall time it took to run the test, the amount of memory it used and the average fps rate.

The Tests

I took a 550 x 400 sized stage published at 30 fps. All tests were run using the Debug version of the Player (9.0 r 124). The test consisted of creating an array of X number of sprites (to test the AVM) and PixelSprites (to test blitting). Each sprite was 50×50 in size and contained an alpha channel. I then drew all of the sprites onto the stage and moved them along by 4 pixels per frame, if they hit the left of the stage they wrapped around to the right again. The Sprites had cacheAsBitmap set to true (see note below)

Then I ran the tests multiple times, with varying numbers of fish, for varying durations, recording the data at each step and averaging it out.

I agree that this is in no way a truly “scientific” test, but I wanted a general “feeling” as a result, to see if this was an avenue still worth walking down or not.

The Results

With 500 sprites both the standard Sprite and the blit method kept a solid 30 fps frame rate. Using Sprites consumed 15MB of RAM, using blits 11MB.

At 1000 sprites we’re still at a consistent 30 fps, but there is noticeable “tearing” in the visuals as the sprites move across the stage. It’s not terrible, but you can easily see it. The standard method is now using 20MB while the blit is using 14MB.

2500 sprites and we see both techniques struggle to keep-up with the 30 fps rate. The traditional Sprites actually outpace the blitting at 23 fps vs 21 fps, but the memory consumption is more than doubled, 35MB vs. 15MB.

At 5000 sprites they are both starting to feel the strain, each level pegging at 12 fps. But the standard Sprites technique is using a staggering 58MB, while the blit is only up to 20MB.

7,500 sprites all moving at once and both techiques are virtually bought to their knees managing just 8 fps each. Given the amount of data moving this isn’t totally surprising. The blit technique at this point is literally copying 18.7 million pixels around in memory. The AVMs internal dirty rectangle is feeling the full force of what’s going on however, and is now consuming 237MB of RAM vs. the blit techniques 25MB.

10,000 sprites crashes the Debug player for both versions, it literally runs out of memory :)

cacheAsBitmap

As I mentioned at the start, the Sprite version had cacheAsBitmap set to true. This is the main cause of the huge amount of RAM being used. As our Sprite only contained a single Bitmap this wasn’t needed. By removing this setting the amount of RAM used dropped, ending up only a few MB higher than the straight blit method.

Our Findings

So what can we pull from this?

First of all, the AVM dirty rectangles implementation is pretty damn sweet! But brute-force blitting is equally as fast in this test case. Logic tells us that adding redraw aware optimisation to our blit engine should increase this gap in our favour significantly.

NEVER enable cacheAsBitmap on a Sprite or MovieClip if all it contains is bitmap data.

The blit engine uses less memory. If you need to cache vector Sprites in your game, then it uses considerably less memory!

No-one really needs a game with 7,500 fish swimming around in it ;)

Maybe the test wasn’t “real world” enough - even at the 1000 sprite level (at which both methods kept a 30 fps frame rate) we were still moving 2.5 million pixels around a 550 x 400 stage. That’s enough to fill the stage 11 times over (and still have some spare). Is this likely in a real game? Well no, I don’t believe so - but it isn’t that far off either. Games are getting bigger (we published one at 800×600 today for example), and if you had a game featuring multiple layers going on (foreground, player, background, distance, etc) with alpha showing through them all, then it doesn’t take long to start using pixels in the millions range.

There are instances when I believe it’s just easier to deal with things on a blit level - for example building up a large n-way scrolling tilemap, where you constantly need to redraw the scroll buffers. Doing the same by placing (and updating) hundreds of Sprites would be an exercise in pain I wouldn’t wish on anyone.

Is a combination of both worlds the way to go? Quite possibly. While I loathe using the timeline (or Movieclips in general) for anything, they do offer Flash animators a rich featured tool-set that let’s them create vibrant moving games. Whereas the blit method requires graphic artists trained in the way of the pixel, and I believe those are a dying (and expensive) breed indeed. Creating quality animations at that level is time-consuming and costly. But as we’ve seen, animating on a vector level introduces both resource and speed issues into your game.

What about collision detection? Well we all know this pretty much sucks in Flash. So we have to roll our own methods anyway. For pixel perfect collision detection we need to inspect the elements on a pixel level (surprise surprise), at least with the blit technique we’re already operating on that level, so there’s no extra draw() overhead involved.

Conclusion

Are AS3 Sprites “evil” for those of you trying to create arcade style games? No, I don’t believe so. They can hold their own in the speed stakes thanks to the power of the AVM, but you do have to watch yourself and be very careful re: memory consumption.

Is “blitting” really that much faster the using normal Sprites? No, it isn’t. It does have less memory overhead and a “cleaner” feel to it, but it’s no speed demon in comparison.

Would a hybrid solution work? (i.e. a fully blitted tilemap with Movieclips characters on-top) - yes, absolutely!

Don’t feel that because you have travelled down the “blit” route you need to have the whole game living there. If you can mix and match your game logic and most importantly your collision systems, then there’s no harm in splitting these elements up, using both at once.

P.S. If you’ve got some ideas or concepts on optimising blit level drawing, please get in touch. I’ve been reading a lot about this recently (what I can find at least) but it’s always good to pick someone’s brain.

BlitzMouse right-click capture example

Tuesday, September 16th, 2008

sergej wrote a comment to my BlitzMouse post saying that if you right-clicked the custom pointer gets lost until the page is refreshed. Here is some simple code to work around this.

In your main SWF make sure you import ContextMenu and ContextMenuEvent. Then add 2 new global vars:

Actionscript:
  1. private var rightClickContext:ContextMenu;
  2. private var contextOpen:Boolean;

and within your init (or constructor) add this:

Actionscript:
  1. rightClickContext = new ContextMenu();
  2. this.contextMenu = rightClickContext;
  3. rightClickContext.addEventListener(ContextMenuEvent.MENU_SELECT, contextMenuOpen, false, 0, true);

"this" is a Sprite in this case, but any valid display object (that has access to the contextMenu) will do. The "contextMenuOpen" function is literally just the following:

Actionscript:
  1. private function contextMenuOpen(event:ContextMenuEvent):void
  2. {
  3. contextOpen = true;
  4. }

and finally, in your main game loop, just check the state of this var and reset accordingly:

Actionscript:
  1. if (contextOpen && mouse.isDown)
  2. {
  3. mouse.hide();
  4. }

When the context menu is opened (by a right-click on Windows) it fires the ContextMenuEvent.MENU_SELECT event, which we capture and set a boolean for accordingly. While the menu is open we can do nothing about the standard mouse pointer, but in our main loop we can listen out for a mouse click (mouse.isDown) and then hide the pointer again accordingly.

I've not tested this on a Mac (where you can command-click to get the context menu up) so if anyone reading can do so, please let me know if it works.

The SWF below should allow you access to the context menu, but upon clicking the SWF again the custom pointer should return (assuming you click within the limit zone!)

BlitzMouse Released + Demo

Monday, September 15th, 2008

After working my butt-off on my latest game I decided it was time to redirect some love and attention to PixelBlitz. So this weekend I finished off a new class I had planned out a while ago. Introducing... BlitzMouse! This pairs up with BlitzKeyboard to complete the input set, and is a feature rich (and very fast) mouse handling system.

Here's a very simple demo of it in action:

Press the cursor keys to limit custom mouse pointer movement.

So what can this bad boy do? The aim (as with all things PixelBlitz) is to make working with the mouse in your games easier. Here's a quick overview of the core features:

Accurate mouse tracking

Keep an eye on that rodent! Easily check if it has left the stage, or re-entered again. Doesn't use any CPU time processing events that require the mouse if it's not over the stage!

Button / Click handling

Detect when the mouse button is down, or up.. or being held down. Find out how long it took the user to make that last mouse click (the speed from down to up again). Find out how many clicks the user has made since you last checked. Writing those god-awful "Ninja Finger" style games has never been so simple ;)

Mouse stats

Want to know if the mouse is moving up? Just check isMovingUp! You can poll all 4 directions easily and quickly. Want to know how far in pixels the mouse has travelled on the X axis? Call distanceX() - want to know how fast it moved? Call speedX!

Rotation

To know which angle the mouse is at call angle(), and you can have the result back in degrees or radians. Use the optional "lowerAccuracy" parameter and it uses a much faster calculation, but sacrifice a little accuracy in the process (great for a quick arcade game, not-so for a physics simulation).

You can set the point of the angle calculation (it defaults to the centre of your stage), which allows you to track the angle from anywhere to the mouse. You can even get the angle from any display object to the mouse using angleToObject() (with all the same parameters that angle() supports). This means if you want 3 things all pointing right at the mouse then it's no problem! (see the demo above) Want to know the distance from any display object to the mouse? Call distanceToObject() and it'll tell you.

Custom Mouse Pointers

Use changePointer() and you can set the mouse pointer to any display object - with custom X/Y offset support incase the pointer needs aligning differently to the standard top left. As the mouse moves, the display object is updated. If the mouse leaves the stage the display object is made invisible, so you don't get that "cursor stuck on the edge" problem :)

Movement Limits

Want to limit the movement of the custom pointer? No problem! You can limit it in all four directions (up/down/left/right) with optional snapBack support on both axis. For example if you were making a Pong game (please... don't) by just calling limitMovement(true, true, false, false) you will lock the bat into only moving up and down with left/right movements ignored.

Want to limit the mouse to a specific area of the stage? Call limit(new Rectangle(x,y,w,h)) - if the mouse goes outside of this zone it will be hidden from view. You can see this in the example above as it hides when it leaves the light grey box. This limit also effects custom pointers. Of course when the mouse leaves the stage there is nothing you can do about that - but we have to work within the limits of Flash here :)

So there we have it - BlitzMouse! Hopefully more useful than you thought when you first read the title, aye? :) I plan to add more features, such as custom events/function calls on mouse actions, the ability to attach as many display objects as you like to it (so they all update at once) and custom zones, so you can have as many "mouse zones" as you want. The code is uploaded to Google, so enjoy :)

PixelBlitz: BlitzFont is live :)

Thursday, September 4th, 2008

Tonight I created and finished BlitzFont. BlitzFont is a bitmap font handling class. Most Flash games use True Type fonts for their text, or "bitmap True Type fonts", where the font was specially designed to be used at a small resolution. This is all well and good, but what if you want to design a custom font? Something with some graphical flair that can't be achieved via True Type. Enter BlitzFont :)

BlitzFont allows you to use pass in any bitmap from your library, tell it how the font characters are arranged, and then it grabs it all for you. Once grabbed you can ask it for text back again, and it'll return bitmapData for ever more!

If this sounds a bit strange, take a look at this font here:

In this example the characters have between drawn in a grid and they are 32x32 pixels in size. Using them in your game requires just one call:

Actionscript:
  1. font.init(new tbjFontBD(0, 0), 32, 32, BlitzFont.SET10 + " 1234567890,.:'-<>!", 9, 2, 2, 1, 1);

All this does is give the name of the bitmap in your Flash library, the width and height of each character, the characters and the order in which they appear (SET10 is a built-in character sequence that you can extend), the 9 value is the number of characters per row, 2 + 2 is the distance (x and y) between each character and finally 1,1 are x/y offsets to start grabbing from.

Phew sounds quite a lot, but if you've got a well arranged font with no spaces, no offset and a standard ASCII ordering, then you only need to use 5 parameters!

Once you've initiated the font that's it - you can use it. BlitzFont has 3 methods for this:

getLine()
getMultiLine()
getCharacter()

getLine is ideal if you only need to get back 1 lines worth of text.
getMultiLine can be given as much text as you want (that will fit onto a bitmap) and supports carriage-returns.
getCharacter simply returns 1 character.

Each of the functions above all return bitmapData objects. You have alignment support, so you can left align, right align or center each line perfectly. You can also control the x/y spacing between characters!

Actionscript:
  1. var bd:BitmapData = font.getMultiLine("welcome to the\npixelblitz\nblitzfont demo", 1, 16, BlitzFont.ALIGN_CENTER);

The class does all the dirty work for you, like removing un-supported characters from your input string, making sure it deals with spaces efficiently, and wrapping text on carriage returns.

But wait, there's more! You can also create scrolling text messages with 1 line of code :)

Actionscript:
  1. defineScroller(width:uint, speed:uint, text:String, autoUpperCase:Boolean = true, wrap:Boolean = true, spacing:uint = 0):BitmapData

Ok I know, scrollers are old-hat now.. but sometimes in a game you want a little scrolling message, or status update or something, and with this you can easily create it :) You just define the scroll settings, and then call updateScroller() every loop. You can even set custom events to fire if a certain character scrolls on! and the scroller will fire events on text complete and text wrap too.

Here's a demo of this in action (refresh this blog entry if you didn't get to see it from the start!)

Again this is all now in Google code, and i'll upload example source when I update the examples packages in the coming days. If you are in need of some great bitmap fonts, here's a good resource.

PixelBlitz: BlitzMath is live

Thursday, September 4th, 2008

Tonight I pushed up a new build of the BlitzMath utility class. As dull as this may sound it gives you a set of functions to perform math tasks that either AS3 is very slow at, or that simply don't exist.

For example there is an extremely fast new rand function for when you only need a small integer back. There are enhancements to the standard Math.random() calls to provide for min, max, int and Float support. There's a faster abs(), a very fast sqrt replacement and a few other experimental things.

There's also a nifty little function I call "chanceRoll" which when give a value between 0 and 100 gives you a boolean back based on that weight. For example say you had a player hit a baddie in a game, you could give him a 30% chance of getting a critical hit by calling chanceRoll(30). I know, it's simple, but it's lots of simple little things that will make this framework great :)

There's also a blindingly fast simultaneous sine/cosine table generator. So fast in-fact you can generate the tables in real-time! The length, sin/cos amplitude and frequency are all under your control.

This is all now in Google Code, and here's a quick demo to play with:

PixelBlitz: New package, new domain

Thursday, September 4th, 2008

Yesterday I completed the move to re-package PixelBlitz. Norm agreed, and we registered a new domain (pixelblitz.org) and I went through and updated the library to use the new package location.

I think it makes it cleaner and easier to type :)

The domain name will be used to point to a PixelBlitz web site, once we've got some time to actually build it - in the meantime I'll redirect it to point to the Google Code site.

BlitzKeyboard is live!

Tuesday, September 2nd, 2008

After a mammoth coding session tonight I have committed the first version of BlitzKeyboard into the PixelBlitz Engine.

I'm really happy with this work - it's pretty much everything I've ever wanted from an advanced keyboard handler :)

So what can it do for you? In short it's about saving you time. At the core is an extremely fast keyboard event handler, so all you need to do is ask it if a key is pressed or not:

Actionscript:
  1. if (keyboard.isDown(BlitzKeyboard.LEFT))
  2. {
  3. player.x -= playerXSpeed;
  4. }
  5.  
  6. if (keyboard.isDown(BlitzKeyboard.RIGHT))
  7. {
  8. player.x += playerXSpeed;
  9. }

Simple. Fast. Efficient. Of course if that was all it could do it would be nothing special - but it can do so much more ...

Multiple Key Support
Accurate detection for one, two or three simultaneous key presses, including Location support. That means you can check for the difference between the left shift key and the right shift key. A full range of constants are built into the class, so rather than remember which keycode relates to which key, you just use our constants list. This list has been extended to support Enhanced keyboards, so you've got it detecting the Windows (or Apple Command) keys as well as the Application key.

Set the Key Rate
In an arcade game you need to pick-up the key presses as fast as possible, and BlitzKeyboard does just that. But you can also configure a Key Rate, so if you only want a certain key to fire once every second then that's no problem.

Bind Events or Functions to Keys
You can set a key (or key combination) to fire an Event or call a Function. You control if the Event should fire when the key/s are pressed down, or fire on the release (when you let them go again). You pass in the Event and then set an event listener to listen out for it, and it handles the rest. It even takes the Key Rate into account, so your Event will only fire at the frequency you set.

Wait Key support
Say you need to wait for the user to press a key before proceeding with your game - then just use the waitKey() function! You pass it an Event and a type, and the next time a key is pressed the Event is dispatched, no matter which key caused it.

Key Hit Counter
Want to know exactly how many times a key has been pressed? Then call keyHit() on it and this method will tell you just that.

I'll be adding a few final features, and preparing the demos in the coming days. But the core class now exists in Google Code for the curious.

Next up is BlitzMouse which will handle advanced mouse events - things like mouse zones, reporting on how fast the mouse is moving, scroll wheel handling and more.