"Rubble" A tank game.

Hey, my first post here!

I was making a game in Flash with Box2DAS3.. it keeps amazing me how fast it is!! The problem is usually that the drawing is slow, not the physics!.

Anyway, here is a current build: http://tank.noio.nl/tank_game%202008-05-14.swf (i think it works fastests if you download in stead of viewing in a browser, because a browser limits the framerate.. And it's not embedded so i can't use wmode = transparent (thats like + 20fps 😀)

Also, you can see here that I made a pretty fast (I think it's about O(n)) [edit] LOL NO [/edit] algorithm for dividing a concave polygon in to large convex ones!! This is ideal for box2d, where you want as few shapes as possible, but they have to be convex.. Would anybody be interested in the source code for that?

Let me know what you think!
Quote:
Also, you can see here that I made a pretty fast (I think it's about O(n)) algorithm for dividing a concave polygon in to large convex ones!! This is ideal for box2d, where you want as few shapes as possible, but they have to be convex.. Would anybody be interested in the source code for that?

If it's actually O(N) non-randomized and works on arbitrary simple polygons, and you've implemented it successfully, then you've solved one of the biggest outstanding problems in computational geometry, so forget posting the code here, publish a paper! 😉

If not, I suspect your algorithm is probably restricted to height-fields. In which case it will still definitely be useful for Box2d purposes - the code would be very appreciated, I'm sure!
That's a really great game you're working on there.

Bill
Well you can trivially divide heightfields in O(n) by making tons of trapeziums. Better code would be that which uses less than n shapes to do so, so you should benchmark that, too, for some random curves.

But it is surprisingly fast, I'd always assumed that it'd be much slower.
I love the little tank. Keep us posted on your progress.
ewjordan wrote:
Quote:
Also, you can see here that I made a pretty fast (I think it's about O(n)) algorithm for dividing a concave polygon in to large convex ones!! This is ideal for box2d, where you want as few shapes as possible, but they have to be convex.. Would anybody be interested in the source code for that?

If it's actually O(N) non-randomized and works on arbitrary simple polygons, and you've implemented it successfully, then you've solved one of the biggest outstanding problems in computational geometry, so forget posting the code here, publish a paper! 😉

If not, I suspect your algorithm is probably restricted to height-fields. In which case it will still definitely be useful for Box2d purposes - the code would be very appreciated, I'm sure!


You are right... 🙄 I wasn't so sure about the O(n), and now that I *actually* checked it, it's probably a lot worse: like O(n*n). (Sorry for unjustified bragging 😳 ) But ... it's efficient O(n*n) 😆 Efficient O(n*n) can still be faster than a slow O(n), right? [edit] for low amounts of points [/edit]
On the other hand, don't forget that it is *not* an optimal division, so it's not worth anything really (scientifically).. I made the tradeoff of having a "sloppy" division, and then letting Box2D handle the extra poly's that are created. Also, it doesn't only work on heightmaps, but any simple polygons.

Btw, isn't there a triangulation algorithm in O(log n) already? (Or is triangulation fundamentally different from (easier than) finding convex poly's?)

BorisTheBrave wrote:
Well you can trivially divide heightfields in O(n) by making tons of trapeziums. Better code would be that which uses less than n shapes to do so, so you should benchmark that, too, for some random curves.
But it is surprisingly fast, I'd always assumed that it'd be much slower.


In an old version I used to do just that, but it ended up generating too many polygons, so I'm doing this now. Disadvantage is that the whole terrain has to be recalculated even if a single section is adjusted.
android wrote:
Btw, isn't there a triangulation algorithm in O(log n) already? (Or is triangulation fundamentally different from (easier than) finding convex poly's?)

Nope, the best case is O(N) (couldn't possibly be O(log n) - you can't even loop through the vertices in that time), thank to Chazelle (see http://mathworld.wolfram.com/Triangulation.html for more results), but it's so complicated that apparently nobody has ever gotten it implemented. To my knowledge, the fastest reasonable ones to implement are O(n log n).

Triangulation and convex decomposition are fairly similar, algorithmically, as most decomposition algorithms rely on triangulation to start; however, optimal convex decomposition is extremely difficult and slow, I think at least O(N^3), maybe even worse.

For most of the cases we're concerned with, you can easily get away with O(N^2) algorithms when you do pre-processing stuff on shapes, because you're rarely dealing with more than 100 or so vertices, and 10,000 ops (within an order of magnitude) happen in a blink of an eye. O(N^2) algorithms tend to be considerably more straightforward than the O(N log N) ones, so this is a good thing. You only have trouble if you need to use them literally every frame.
hi great little demo you got here! I would love to see the way you incorporated that triangulation in as3 so please do post your source for that part if you can 🙂
Ok, here goes.. But I'm kind of embarassed 😳 , because I see now that it's checking against *ALL* other points multiple times! So I don't think it's even O(n*n), but worse.

How to use:
Just pass your simple polygon to the function getConvexShapeSet() You can also tell the function how many points maximum you want per shape, because Box2D shapes can only be 8 vertices by default. The function will return an array of arrays, each sub-array contains a single shape.

The way I use it: every time the terrain changes I make a pointset out of the heightmap, and then I split that up into convex poly's with this function.

Code:
package noio.game.geom{
   
   import flash.display.Shape;
   import flash.display.Sprite;
   
   public class Poly {
      
      /*
      * Transforms a heightmap array to a pointset
      * @param h the heightmap
      * @param step the distance between points on the heightmap
      * @param base the distance that is added to heightmap values. (because flash coordinates are upside-down)
      * @param pointclass, a class that has X and Y properties, and a constructor that takes (x,y):
      *                                 for example: the Box2D b2Vec2 Class (so you can return points to b2Vec2)
      */
      public static function heightmapToPointset(h:Array,step:Number,base:Number,pointClass:Class = null):Array{
         if(!pointClass) pointClass = DefaultPoint
         var output:Array = new Array();
         var xpos:Number = 0;
         output.push(new pointClass(0,base));
         for each(var val:Number in h){
            output.push(new pointClass(xpos,base-val));
            xpos += step;
         }
         output.push(new pointClass(xpos-step,base));
         return output;
      }
      /*
      * Transforms a heightmap array to a pointset, but points that don't cause large extrusions are left out.
      * So for example: A whole flat heightmap (like 10,10,10,10,10,10)
      * would only generate 4 points (top, right, bottom ,left).
      * "tol" stands for tolerance, and that is hardcoded for convenience.
      * @param h the heightmap
      * @param step the distance between points on the heightmap
      * @param base the distance that is added to heightmap values. (because flash coordinates are upside-down)
      * @param pointclass, a class that has X and Y properties, and a constructor that takes (x,y):
      *                              for example: the Box2D b2Vec2 Class (so you can return points to b2Vec2)
      */
      public static function heightmapToSimplifiedPointset(h:Array,step:Number,base:Number, pointClass:Class = null):Array{
         if(!pointClass) pointClass = DefaultPoint;
         var output:Array = new Array();
         var xpos:Number = step;
         var tol = step/6;
         var hL = h.length;
         
         output.push(new pointClass(0,base));
         output.push(new pointClass(0,base-h[0]));
         var last:int = 0;
         for(var i:int = 1; i<hL - 1; ++i){
            if(Math.abs(h[last] + h[i+1] - 2*h[i]) > tol){
               output.push(new pointClass(xpos,base-h[i]));
               last = i;
            }
            xpos += step;
         }
         output.push(new pointClass(xpos,base - h[hL-1]));
         output.push(new pointClass(xpos,base));
         return output;
      }
      
      /*
      * Returns a set of convex polygons that make up the given polygon. Polygon cannot overlap and has to be in CCW order
      */
      public static function getConvexShapeSet(points:Array, maxPointsPerShape:int = 8):Array {
         var shapes:Array = new Array()

         while(points.length > 2){
            var curShape = points.slice(0,3);
            
            var STOP:int = 40; //Stop after 40 tries, (when you give it a complex polygon, it will never find an ear)
            //Shift the polygon to find an 'ear'.
            while((!Poly.isConvex(curShape)) || convexIncludesAny(curShape,points.slice(3))){
               points.push(points.shift());
               curShape = points.slice(0,3);
               if(--STOP < 0){ throw new Error("Poly.getConvexShapeSet: Cannot find polygon ear")};
            }

            points.splice(1,1);
            //shapes.push(curShape);
            //continue;
            //Expand the 'ear' to span more points.
            var cL = curShape.length;
            while((points.length > 2) && (cL < maxPointsPerShape) &&
                     (isLeft(curShape[cL-2],curShape[cL-1],points[2]) > 0) &&
                     (isLeft(curShape[cL-1],points[2],curShape[0]) > 0) &&
                     (isLeft(points[2],curShape[0],curShape[1]) > 0) &&
                     !convexIncludesAny(curShape.concat(points[2]),points.slice(3))
            ){      
               //If new shape is still convex with one point added, add that point
               //trace("expansion loop",points[2].x,points[2].y);
               curShape.push(points[2])
               points.splice(1,1);
               cL = curShape.length;
            }
            shapes.push(curShape);            
         }
         return shapes;
      }
      
      /*
      * Test whether the given polygon is convex, points have to be given in CCW order
      */
      public static function isConvex(points:Array):Boolean {
         var l = points.length
         if(l <3 ) return false;
         for(var i:int = 0; i < l -2 ; i++){
            if(isLeft(points[i],points[i+1],points[i+2]) < 0) {
               return false;
            }
         }
         if (isLeft(points[l - 2], points[ l - 1], points[0]) < 0){
            return false;
         }
         if(isLeft(points[l - 1], points[0], points[1]) < 0) {
            return false;
         }
         return true;
      }
   
      
      /*
      * Test whether P2 is on/left of/right of the line through P0 and P1
      */
      public static function isLeft(P0:*, P1:*, P2:* ):Number
      {
            return (P1.x - P0.x)*(P2.y - P0.y) - (P2.x - P0.x)*(P1.y - P0.y);
      }
      
      public static function convexIncludesAny(shape:Array, points:Array){
         for each(var point in points){
            if(convexIncludes(shape, point)) return true;
         }
         return false;
      }
   
      public static function convexIncludes(points:Array,point:*){
         for(var i:int = 0, j = points.length - 1; i < points.length; j = i++){
            if(isLeft(points[j],points[i], point) < 0){
               return false;
            }
         }
         return true;
      }
   
      public static function drawMultiple(shapes:Array){
         var s = new Sprite();
         for each(var shape:Array in shapes){
            s.addChild(draw(shape));
         }
         return s;
      }
      
      public static function draw(points:Array):Shape{
         var s = new Shape;
         s.graphics.lineStyle(1,0xffffff);
         s.graphics.moveTo(points[0].x,points[0].y);
         for ( var i : int = 1; i < points.length ; i ++){
            s.graphics.lineTo(points[i].x,points[i].y);
         }
         s.graphics.lineTo(points[0].x,points[0].y);
         return s;
      }
   }
   
}

class DefaultPoint {
   var x : Number;
   var y : Number;
   
   public function DefaultPoint(_x:Number = 0, _y:Number = 0){
      x = _x; y = _y;
   }
}

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