Trace image to Edge Shapes, and terrain generation

A few weeks ago I was thinking about the easiest way to make levels for a game project. I'd recently studied an article in GPU Gems 3 ( http://http.developer.nvidia.com/GPUGem ... _ch01.html), which describes using the marching cubes algorithm to trace the contours of a 3D density function. I immediately took a fancy to the technique, and became keen to find an excuse to try out something similar. Eventually my thoughts landed upon a useful application: the ability to draw a 2D level (mask) image, have it traced, and turn the outline into Edge Shapes -- essentially turning Paint into a level editor.

To skip most of a long story, I managed to implement the 2D analogue of the marching cubes algorithm: marching squares; and it works a treat. One particularly nice thing is that it deals with anti-aliasing (AA) very nicely: AA in the source image == AA in the contour. Also, scaling is independant of the source image resolution, meaning the resolution instead determines the complexity of the generated outline polygon, i.e., shrinking the image (with AA) reduces the level's detail. As an alternative, I also implemented a vertex-culling algorithm, which simply removes vertices that form shallow angles -- it's very crude, and could do with re-writing or replacing with something more advanced (perhaps utilising cubic splines or something).

Image Image

After describing marching cubes, the GPU Gems article goes on to discuss methods for procedurally generating density functions, i.e., random terrains. I originally thought this would translate poorly into 2D, and put-off giving it a go. But once I had the tracing algorithm working, I figured it might be interesting to try it. The results are better than I'd originally predicted, but I think practical use of a random terrain generator might be hard in 2D games. It's still kind of cool though, and there are lots of ways to tweak the structure of the terrain via noise sample frequencies etc (see the GPU Gems article for cool examples, which admitedly look way more awesome in 3D). I'm sure there are some interesting games waiting out there in the undiscovered void that make use of something like this.

Image

Taking the idea beyond what I've done so far, I also thought you could draw friction and restitution values into separate colour channels and have them read and assigned on a per vertex basis. Another idea would be to use the system for destructable or deformable terrain, modifying and re-tracing the source image as necessary. The tracing algorithm is very fast, and although I haven't done any quantitative tests, I reckon it could handle real-time use.

A final use that came to mind was for rendering particle-based fluid simulations. Here, particles could be rendered to a source texture as meta-balls, and then the surface contours traced and turned into polygon meshes. However, this would be much better suited to implementation on the GPU.

I've implemented everything as a Test-Bed demo for simplicity, and attached a patch for quickly getting the code. You can also download the win32 exe here: http://users.bigpond.net.au/barsdell/TestBed_TerrainTracer.zip. The code's a little old-school in parts, lacks a bit of consistency, and may contain a memory access bug somewhere in the vertex-culling routine, but apart from that it's perfect 😀.

I hope this turns out to be useful for some people, and I look forward to hearing thoughts about it!

EDIT: I've now also attached a zip containing just the source code.
Good stuff, but you've neglected a few issues that physics engines have that make marching cubes less great.
Firstly, normals matter a great deal more. Marching cubes only generates 8 different normals, which is not a good surface approximation. Your screenshots show something more than that, so perhaps there's some better technique that I'm not aware of?
Secondly, if you plan to animate things, you need persistence of shapes, or else Box2D won't be able to do it's physics properly. Worse, as you are using thin line segments rather than tessellating polys, if the traced shape expands around something, that thing will simple get put inside, rather than expelled.

I'm pretty convinced people will be able to find cool uses for the project though. Worms like games come to mind, as you can recalculate chunks of an area without disturbing the rest.
This is awesome! Thank you, I'll definitly be taking a look at your work.

BorisTheBrave wrote:
Good stuff, but you've neglected a few issues that physics engines have that make marching cubes less great.
Firstly, normals matter a great deal more. Marching cubes only generates 8 different normals, which is not a good surface approximation. Your screenshots show something more than that, so perhaps there's some better technique that I'm not aware of?
Secondly, if you plan to animate things, you need persistence of shapes, or else Box2D won't be able to do it's physics properly. Worse, as you are using thin line segments rather than tessellating polys, if the traced shape expands around something, that thing will simple get put inside, rather than expelled.

I'm pretty convinced people will be able to find cool uses for the project though. Worms like games come to mind, as you can recalculate chunks of an area without disturbing the rest.


I'm not sure what you mean by 'animate.' For terrian, the animation can be represented on the drawn area, outside of Box2D. If you mean deformable terrian, I believe the only reasonable action would be to subtract from the terrian, not add to it.
Right, right. I thought you meant for stuff like metaballs, which would sometimes involve addition.
Brilliant! Hope I had this a couple months ago. I managed to do this on my own using vector tracing.
BorisTheBrave wrote:
Good stuff, but you've neglected a few issues that physics engines have that make marching cubes less great.
Firstly, normals matter a great deal more. Marching cubes only generates 8 different normals, which is not a good surface approximation. Your screenshots show something more than that, so perhaps there's some better technique that I'm not aware of?

Marching cubes (or squares, in this case) should give reasonable normals, they aren't quantized.

The algorithm samples the field at the square's corners, and then if it sees that the square seems to touch a boundary (i.e. the field crosses zero), it picks out the boundary point on each relevant edge by linearly interpolating between the corner values. For instance, if the value at one corner is -1 and the value at the next is +2, it will assume the field hits zero a third of the way. Usually I've seen it generate very reasonable normals, though for 3d rendering (metaballs and stuff like that) it's better to sample the derivatives at each point, too, since you can pass per-vertex normals to the renderer, which varies them smoothly across each polygon.
Hello, I am the guy who asked about generating shapes for a destructible terrain. Right now I am trying to implement it and was just wondering. The traceImage function what does channel count, external colour[] and density channel refer to? Channel count stands for the amount of channels? In a ARGB image would be 4? Density channel for the channel I want to be considered empty? ARGB = A = 0?

Some other parameters confused me too, the image one, const uchar[] I thought you couldnt pass arrays as parameters and the critical_density, act_inclusively ones which are initialized in the parameter list :s.

Thanks.
Reaper wrote:
Hello, I am the guy who asked about generating shapes for a destructible terrain. Right now I am trying to implement it and was just wondering. The traceImage function what does channel count, external colour[] and density channel refer to? Channel count stands for the amount of channels? In a ARGB image would be 4? Density channel for the channel I want to be considered empty? ARGB = A = 0?

Some other parameters confused me too, the image one, const uchar[] I thought you couldnt pass arrays as parameters and the critical_density, act_inclusively ones which are initialized in the parameter list :s.

Thanks.

Great to hear you're using this. To answer your questions, firstly here are some comments from the code:
Code:
// The core of the marching-squares tracing algorithm.
// Traces and returns a single shape in an image.
// The starting point must lie on a contour edge.
// external_colour: the colour value assumed beyond
//  the region of the image.
// critical_density: density value defining the
//  air/ground surface.
// act_inclusively: whether to "include" or "cut-off"
//  at saddle-points.
bool traceImageFromEdge(const uchar image[],
                        int width, int height,
                        uchar channel_count,
                        vector<char>* is_visited,
                        int start_x, int start_y,
                        uchar* external_colour,
                        uchar density_channel,
                        Shape& out_shape,
                        uchar critical_density=128,
                        bool act_inclusively=false)

To elaborate:
You can pass arrays to functions in the sense that uchar image[] really just passes the address of the first element in the array, from which the rest is accessed via an offset.
Channel count is indeed the numbers of colours in the image. I included it so that you could pass raw image data of any format without having to convert it first.
External colour is the colour that the function will assume for pixels that lie beyond the extents of the image, meaning the world "outside the image" is either solid ground (so the image forms a cave) or air (so the image forms an island).
Density channel is indeed the colour channel which will determine the density, i.e., the channel that will be traced.
Critical density is the density value that represents the boundary between air and solid ground. A value of 128 means that colours darker than mid-grey will be air while lighter ones will be solid.
And act_inclusively is used to deal with an ambiguous case that arises when tracing an edge. It happens when you get a "saddle-point", where two diagonal pixels are solid and the other two are air: there are two possible ways to treat it. A value of "true" for act_inclusively will mean diagonal solid pixels will form a single solid shape, while false will produce two separate shapes, one around each pixel. Since writing the code, I've found out there is a way to remove the ambiguity by using a weighted average of the pixels in the centre point between them. This would be pretty easy to implement, but I don't know that I'll find time to do it. If you feel up to it, you can give it a go yourself!

Hope that makes things a little clearer 🙂
Well I understand the theory now though the correct implementation still eludes me.. This is what I came up with to create a shape for an object based on a png black and white image/texture. I get an iterator not dereferencable at the pointed out line when I try to run it. I am currently trying to decipher the code.

Code:
   D3DLOCKED_RECT rect;
   LPDIRECT3DTEXTURE9 tex = sprt->tex;
   int width = sprt->width;
   int height = sprt->height;
   int size = width*height;
   uchar *bits = new uchar[size*sizeof(DWORD)];

   tex->LockRect(0, &rect, 0, 0);
   memcpy(bits, rect.pBits, sizeof(DWORD)*size);
   tex->UnlockRect(0);   

   uchar *ex_color = new uchar[sizeof(DWORD)];
   *ex_color = D3DCOLOR_ARGB(255,255,255,255);

   std::vector<Shape> out_shapes;
   traceImage(bits, //uchar[]
                48, //width
            48, //height
                4, //channel count
                ex_color, //external colour[]
                1, //density channel
                out_shapes,
            128, //critical density
            true); //inclusively?

   std::vector<Shape>::iterator shape_it = out_shapes.begin(); //Error here
   for(; shape_it != out_shapes.end(); shape_it++)
   {
      b2PolygonDef shapeDef;
      shapeDef.vertexCount = shape_it->size();

      int x = 0;
      std::list<Vertex>::iterator vertex_it = shape_it->begin();
      for(; vertex_it != shape_it->end(); vertex_it++)
      {
         shapeDef.vertices[x].Set(vertex_it->pos[1], vertex_it->pos[2]);
         x++;
      }

      obj->body->CreateShape(&shapeDef);
   }
My only guess is that traceImage( ) is not adding any shapes to the vector (for whatever reason) and thus out_shapes is still empty. Using gcc, setting an iterator to shapes.begin() where shapes is empty does not cause a problem, but I assume you're using MSVC, and perhaps it doesn't like it? (I found some similar issues discussed on the net). I could be completely off though; I can't fully tell what could be going on from what you've posted.

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