Pixel Smash Box2D

Hey guys, if anyone is interested in Pixel stuff, I was wondering if I could enlist your help.

There is this high optimization Physics engine called Nape and a guy from Photon Storm created an awesome little program which creates a physics object out of pixel bitmaps, see it here:

http://sandbox.photonstorm.com/pixelsmash/

He does claim that there is NO optimization done on it, but I can still run the Nape version of it at a steady 30fps.

I've just finished porting the nape version over to Box2D, but get a shocking 2-3fps, here is the main.as code:

Code:
package
{
   import Box2D.Collision.Shapes.b2PolygonShape;
   import Box2D.Common.Math.b2Vec2;
   import Box2D.Dynamics.b2BodyDef;
   import Box2D.Dynamics.b2DebugDraw;
   import Box2D.Dynamics.b2FixtureDef;
   import Box2D.Dynamics.b2World;
   import Box2D.Dynamics.b2Body;
   import flash.*;
   import flash.display.*;
   import flash.events.*;
   
   public class Main extends Sprite
   {
      [Embed(source = '../assets/face1.png')] private var spritePNG:Class;
      //[Embed(source = '../assets/blob.png')] private var spritePNG:Class;
      //[Embed(source = '../assets/ilija.png')] private var spritePNG:Class;
      
      public var world_scale:Number = 30;
      public var world:b2World = new b2World(new b2Vec2(0, 9.8), true);
      public var body_array:Array = new Array;
      
      private var stats:Stats;
      private var blockSize:int = 4;   // The blockSize controls how large a single pixel is represented as a Nape object
      
      public function Main():void
      {
         if (stage)
         {
            init();
         }
         else
         {
            addEventListener(Event.ADDED_TO_STAGE, init);
         }
      }

      private function init(e:Event = null):void
      {
         removeEventListener(Event.ADDED_TO_STAGE, init);
         
         body_array = [];
         
         makeSpace();
         makeSprite();
         
         debug_draw();
         
         stage.quality = StageQuality.LOW;
         stage.align = StageAlign.TOP_LEFT;
         stage.scaleMode = StageScaleMode.NO_SCALE;
         
         
         addEventListener(Event.ENTER_FRAME, mainLoop);
         
         stats = new Stats();
         
         addChild(stats);
      }
      
      private function makeSpace():void
      {
         //floor
         draw_walls(320, 480, 640, 2, false, null);
         //left
         draw_walls(0, 240, 2, 480, false, null);
         //top
         draw_walls(320, 0, 640, 2, false, null);
         //right
         draw_walls(640, 240, 2, 480, false, null);
         
         //   The walls are invisible, they just exist in the physics world, there's no visual representation of them
      }
      
      private function draw_walls(posx:int, posy:int, width:int, height:int, sensor:Boolean, userData:Sprite):void {
         
         var my_body:b2BodyDef = new b2BodyDef;
         my_body.position.Set(posx / world_scale, posy / world_scale);
         var my_box:b2PolygonShape = new b2PolygonShape();
         var my_fixture:b2FixtureDef = new b2FixtureDef();
         my_box.SetAsBox((width/2)/world_scale, (height/2)/world_scale);
         my_fixture.shape = my_box;
         my_fixture.friction = 1;
         var world_body:b2Body = world.CreateBody(my_body);
         my_body.userData = userData;
         
         world_body.CreateFixture(my_fixture);
      }
      
      private function debug_draw():void {            
         var debug_draw:b2DebugDraw = new b2DebugDraw();
         var debug_sprite:Sprite = new Sprite();
         addChild(debug_sprite);
         debug_draw.SetSprite(debug_sprite);
         debug_draw.SetDrawScale(world_scale);
         debug_draw.SetFlags(b2DebugDraw.e_shapeBit);
         world.SetDebugDraw(debug_draw);         
      }
      
      
      private function makeSprite():void
      {
         var tempA:Bitmap = new spritePNG;         
         
         for (var sy:int = 0; sy < tempA.height; sy++)
         {
            for (var sx:int = 0; sx < tempA.width; sx++)
            {
               if (tempA.bitmapData.getPixel32(sx, sy) > 0)
               {
                  var b:Sprite = makePixelSprite(blockSize, tempA.bitmapData.getPixel(sx, sy));                  
                  draw_crate(260 + (sx * blockSize), 64 + (sy * blockSize), blockSize, blockSize, false, b);   
                  addChild(b);
               }
            }
         }         
      }
      
      public function draw_crate(x:Number, y:Number, width:Number, height:Number, boolean:Boolean, userData:Sprite):void
      {
         var my_body:b2BodyDef = new b2BodyDef;
         my_body.position.Set(x / world_scale, y / world_scale);
         my_body.type=b2Body.b2_dynamicBody;
         var my_box:b2PolygonShape = new b2PolygonShape();
         var my_fixture:b2FixtureDef = new b2FixtureDef();
         my_box.SetAsBox((width/2)/world_scale, (height/2)/world_scale);
         my_fixture.shape = my_box;
         my_fixture.friction = 1;
         
         var world_body:b2Body = world.CreateBody(my_body);
         world_body.SetUserData(userData);
         body_array.push(my_body);
         
         world_body.CreateFixture(my_fixture);
      }   

      private function makePixelSprite(size:int, color:int):Sprite
      {
         var pixel:Sprite = new Sprite();
         pixel.graphics.beginFill(color, 1);
         pixel.graphics.drawRect( -(size/2), -(size/2), size, size);
         pixel.graphics.endFill();
         
         return pixel;
      }
      
      
      private function mainLoop(event:Event):void
      {         
         world.Step(1 / stage.frameRate, 10, 10);
         world.ClearForces();
         world.DrawDebugData();
         
         for (var bb:b2Body = world.GetBodyList(); bb; bb = bb.GetNext()){
            if (bb.GetUserData() is Sprite){
               var sprite:Sprite = bb.GetUserData() as Sprite;
               sprite.x = bb.GetPosition().x * 30;
               sprite.y = bb.GetPosition().y * 30;
               sprite.rotation = bb.GetAngle() * (180/Math.PI);
            }
         }         
      }      
   }
   
}


I assume that the reason behind it being so heavy is that it generates an individual box2d object for each pixel, and then in the update function it has to iterate through every single object and update it's position so that the sprite can follow it.

Can anyone suggest some ways in which I can increase the FPS of this project?

Thanks!

SC
Just tried it without the bitmap at all.

Still get 2-3 fps. I thought Box2D was a little more efficient then that, the pixel image that I'm using has 1017 objects, I just spawned 500 random objects into the world and it clogged the engine up like no ones business...

Odd.

SC
Well we know this kind of thing is no problem for C++ in the testbed, so I wouldn't say that it's a problem with Box2D itself.
http://www.youtube.com/watch?v=tGn3FAuwL6Y

How about if you don't draw anything at all?
I'll give it a whirl when I get home. It seemed odd that I couldn't simulate less then a thousand bodies...
-.- still get bugger all fps. Rage. I've taken gravity out and when the objects spawn, they all just slightly drift away from one another like they're having trouble with spawning location. Once all the objects go to sleep the frame rate returns to normal (derr), but it still doesn't fix the frame rate problem when objects are moving.
You only need to make a few little changes to squeeze some extra frames out of this thing =)
The first change is the most noticeable, and the rest might be quite negligible, but overall, the whole thing's running a little better.

First, bodies that are smaller than about 0.4 units can behave quite poorly.
The manual mentions somewhere that you should aim to simulate things between the size of a coke can and a bus, so pop your block size up to 16 for example and you'll see a pretty nice boost. 8 Will do, but with tiny blocks, the simulation looks a bit pitiful!

Secondly, make sure the density of the boxes are pretty high. I.e. 1 or higher.
Heavier objects will often behave a little more predictably, and speed up the simulation.

Third, add some restitution. This step is purely for funsies.

Fourth, reduce the position and velocity iterations.
Your simulation will be less robust... but when needs must...

Fifth, turn off the debug draw.
Even with most of the flags off, between the transparency, and iterating through every poly, it'll be a real hog with so many bodies on stage.

And lastly, add something like mySprite:Sprite to box2d.dynamics.b2Body.
It's a tiny (tiny tiny) bit faster than accessing a dynamic object/var. I.e
private var userData:*;

Anyhoo, here's an example, and the FlashDevelop source
http://sicklebrick.com/wp-stuff/nape/
http://sicklebrick.com/wp-stuff/nape/nape.rar

You're just not going to get the sort of performance you can with the C++ version in flash simply because the whole thing runs in a virtual machine. Perhaps using haXe or the Alchemy versions would speed a few things up, and I've seen people use Pixel Bender shaders to process things faster, but I have no idea how that would affect box2d performance if it were even a viable option.
(eg posting.php?mode=reply&f=8&t=7714)

Enjoy.
I may be a bit late on this, but...

Have you tried drawing the pixels/squares in a single draw container rather than putting them in separate sprites? I've looked online on the ups and downs between redrawing in one sprite versus multiple sprites, and seems as though the advantages and disadvantages come down to how many objects need to be rendered at any given time. Redrawing every frame to a single sprite is slower than repositioning and/or changing the angles of each sprite per frame, until you hit around 500 sprites (ballpark figure). After hitting that mark, it is theoretically better to redraw to a single sprite every frame. I personally haven't done a comparison myself, so I wouldn't really know if this theory is accurate.

If you don't want to make that drastic step in changing how it updates the screen, you can use the Shape class instead of the Sprite class. The Shape class is basically a display class that only has the graphics (drawing) portion of it (it can't hold any children or events), so it's a lightweight graphics-only version of Sprite. It's been said that the Shape class doesn't have any significant rendering improvements after they've been created, but it doesn't hurt to try. -]
Hey Jayther, I actually tried a few rendering methods here.

First, using a vectored shape\graphic exported from the flash IDE , and recolored, this was pretty slow.

Second time around I drew directly to a bitmapdata, and even tried to re-use the same Matrix instance
over and over to keep it easy on the garbage collector. This can be fairly fast, but I think simply 'cause
there are so many objects to draw, the Sprite class is faster on account of the sprite renderer running
natively, whereas the AS3 part where you prepare the draw matrix and coloring is enough to slow the
bitmapdata method (even though the actual blitting part is handled natively).

Didn't test it thoroughly though, so if anyone can prove otherwise it'd be pretty interesting.
sicklebrick wrote:
Hey Jayther, I actually tried a few rendering methods here.

First, using a vectored shape\graphic exported from the flash IDE , and recolored, this was pretty slow.

Second time around I drew directly to a bitmapdata, and even tried to re-use the same Matrix instance
over and over to keep it easy on the garbage collector. This can be fairly fast, but I think simply 'cause
there are so many objects to draw, the Sprite class is faster on account of the sprite renderer running
natively, whereas the AS3 part where you prepare the draw matrix and coloring is enough to slow the
bitmapdata method (even though the actual blitting part is handled natively).

Didn't test it thoroughly though, so if anyone can prove otherwise it'd be pretty interesting.
Hm, interesting.

I was actually thinking more of using the graphics class (with beginFills and moveTos and lineTos) to draw on a single sprite or shape, but the more I thought about it, the less this is a viable solution, as my game struggles when drawing quite a bit of moving shapes in the screen. A lot of it may actually be the amount of processing through the Box2D engine, but I haven't bothered testing that yet.

I think after all this discussion, I think the problem is less about how efficient Flash draws and updates its graphical parts and more about the processing speed in the Box2D engine. As we have said that Flash is slower than C++ in any kind of processing, the key issue may just be processing speed in general (as anything graphical also involves quite a bit of processing). Plus, the C++ version's testbed uses OpenGL, which sometimes uses the computer's graphics card processor(s) to process everything (including Box2D), while Flash cannot (and hardware acceleration only helps the graphical portion of Flash's screen updates). sicklebrick did mention there were people who used Pixel Bender shader to sort of force the processing to use of the graphics card, but I'm still not sure if the processing will include the Box2D grunt work.
To be honest I don't see how box2d could outsource some of the work to pixel bender - but I'm none too familiar with the inner workings.
On androids for example the heart and soul of the physics processing is handled by a native C++ library that the b2World class calls (java), and my phone can easily handle 200+ little boxes. I guess our best bet would be some kinda of box2d intergration into the flash binary from the kind folks at adobe :\

Original thread: https://box2d.org/forum/viewtopic.php?t=7714