Trace image to Edge Shapes, and terrain generation

Oh well. I removed the culling vertices code(Although it didnt seem to be used, I looked for any call to the vertex culling function but there werent any) atleast now it doesn't return millions of shapes it returns just dozens but it still doesnt work. It still gives me an unreferenceable vector iterator. I changed a bit the routine.

Maybe the image format is the problem? I used a .png. Or maybe it's trying to get it from the LPDIRECT3DTEXTURE9?

I made a test for the image, I painted the corner red and then I took 'bits'(After copying the bits from the LPDIRECT3DTEXTURE9) and set 4 int variables to bit[0], bit[1], bit[2], bit[3]. The first one gave me 0, second one game me 255 third one gave me 0 and last one gave me 0 as would be expected I think.

Code:
void PlayState::CreateShapes(Object *obj)
{
   D3DLOCKED_RECT rect;
   LPDIRECT3DTEXTURE9 mTexture = obj->mSpriteInstance->mSprite->mTexture;
   int width = 64;//obj->mSpriteInstance->mSprite->mTextureWidth;
   int height = 64;//obj->mSpriteInstance->mSprite->mTextureHeight;
   int size = width*height;
   uchar *bits = new uchar[size*sizeof(DWORD)];

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

   uchar *ex_color = new uchar[sizeof(DWORD)];
   ex_color[0] = 0;
   ex_color[1] = 0;
   ex_color[2] = 0;
   ex_color[3] = 0;

   std::vector<Shape> out_shapes;
   traceImage(bits,
                width, //width
            height, //hmTextureHeight
                4, //channel count //4 channels? ARGB?
                ex_color, //Alpha
                0, //Alpha
                out_shapes,
            128,
            true);

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

      std::list<Vertex>::iterator vertexIt = shapeIt->begin();
      int x = 0;
      while(vertexIt != shapeIt->end()){
         shapeDef.vertices[x].Set(vertexIt->pos[0], vertexIt->pos[1]);
         x++;
         vertexIt++;
      }
      
      obj->mBody->CreateShape(&shapeDef);
   }
}
on compiling I dont getting an error...
but on start iam getting ...
any tips ? using the code in the zip with TestBed ...
got it running with:

Code:
bool cullVertices(Shape& shape, double angle_tolerance=5*3.1415926535897932/180.0)
{
    // TODO: This algorithm is a bit cruddy.
    //       Try out some more complex culling algos.
    //       Could try using avg. angle of more verts, or
    //       perhaps linear cubic-spline decomposition.
   
    // Basically keep going around the polygon removing
    // vertices which join edges of similar angles.
    VertexIterator it = shape.begin();
      VertexIterator end = shape.end();
      end--;
    int change_count = 1;
    int times_around = 0;
    while (true) {
        if( shape.size() < 3 )
            break;
        // Find iterators pointing to the previous and next
        // vertices, applied circularly.
        VertexIterator it_prev = it;

            if( it_prev == shape.begin() ) {
            it_prev = end;
            } else {
               --it_prev;
            }
       
        VertexIterator it_next = it;
       
            if( it_next == end ) {
            it_next = shape.begin(); // Loop around
            } else {
               ++it_next;
            }
       
        double angle = fabs(atan2(it->pos[1]-it_prev->pos[1],
                            it->pos[0]-it_prev->pos[0]) -
                           (atan2(it_next->pos[1]-it->pos[1],
                           it_next->pos[0]-it->pos[0])));
        double dist2 = (it->pos[0]-it_next->pos[0])*(it->pos[0]-it_next->pos[0]) +
                       (it->pos[1]-it_next->pos[1])*(it->pos[1]-it_next->pos[1]);
       
        if( it == end ) {
           if( change_count == 0 )
               break;
            //cout << "Change count = " << change_count << ". Times around = " << times_around + 1 << endl;
            //cout << "Vertex count = " << shape.size() << endl;
           change_count = 0;
           // Back to the start
           it = shape.begin();
           ++times_around;
          }
       
        static const double eps = 1e-100;
        if( angle < angle_tolerance || dist2 < eps*eps ) {
            it = shape.erase(it);
            ++change_count;
        }
        else
            ++it;
        //std::cin.get();
    }
    //std::cout << "Times around = " << times_around << std::endl;
    return true;
}


at the example image i get right vaues... but not with my image... is TGA format needed?
Sorry for not replying, I find myself so busy these days.

I noted the problem with MSVC and list decrementers previously in this thread. I'm not sure what you changed in the code to get it working, but if it works then it's good 😉. I advised before that you should just remove the vertex culling routine if it's causing you troubles, as it's not very well written anyway, and you can get the same functionality by reducing the resolution of your source image.

Regarding the image format, the code accepts data as a sequence of interlaced bytes (i.e., unsigned chars), e.g., RGBA, for each pixel. It allows you to specify how many colours (i.e., bytes) per pixel your image has, and which colour to use to define the shape. No matter what image format you read in, you must convert it/get it to a raw form like this. How are you loading your png images? Are you handling possible compression?

Btw if you get this working and are doing something cool with it, let me know, I wanna hear 🙂
Hi

This looks really interesting, and I'm very much hoping to use it in a current project

I just wanted to know if its compatible with the latest SVN release Revision 222, or whether its caught up in the changes being made to Edges?

Currently I'm getting the following errors in VC++2008 as shown below:

Any help much appreciated. (BTW where is the best documentation on how to use edges, as I am looking but it seems hard to find?)

Thanks

Nalin


1>------ Build started: Project: HelloWorld, Configuration: Debug Win32 ------
2>------ Build started: Project: TestBed, Configuration: Debug Win32 ------
1>Compiling...
2>Compiling...
2>cl : Command line warning D9035 : option 'Wp64' has been deprecated and will be removed in a future release
2>TestEntries.cpp
1>cl : Command line warning D9035 : option 'Wp64' has been deprecated and will be removed in a future release
1>HelloWorld.cpp
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer/ImageTracer.h(141) : error C2220: warning treated as error - no 'object' file generated
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer/ImageTracer.h(141) : warning C4127: conditional expression is constant
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer/ImageTracer.h(207) : error C2668: 'fabs' : ambiguous call to overloaded function
2> C:\Program Files\Microsoft Visual Studio 9.0\VC\include\math.h(557): could be 'long double fabs(long double)'
2> C:\Program Files\Microsoft Visual Studio 9.0\VC\include\math.h(509): or 'float fabs(float)'
2> C:\Program Files\Microsoft Visual Studio 9.0\VC\include\math.h(119): or 'double fabs(double)'
2> while trying to match the argument list '(int)'
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer/ImageTracer.h(208) : error C2668: 'fabs' : ambiguous call to overloaded function
2> C:\Program Files\Microsoft Visual Studio 9.0\VC\include\math.h(557): could be 'long double fabs(long double)'
2> C:\Program Files\Microsoft Visual Studio 9.0\VC\include\math.h(509): or 'float fabs(float)'
2> C:\Program Files\Microsoft Visual Studio 9.0\VC\include\math.h(119): or 'double fabs(double)'
2> while trying to match the argument list '(int)'
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer/ImageTracer.h(209) : error C2668: 'fabs' : ambiguous call to overloaded function
2> C:\Program Files\Microsoft Visual Studio 9.0\VC\include\math.h(557): could be 'long double fabs(long double)'
2> C:\Program Files\Microsoft Visual Studio 9.0\VC\include\math.h(509): or 'float fabs(float)'
2> C:\Program Files\Microsoft Visual Studio 9.0\VC\include\math.h(119): or 'double fabs(double)'
2> while trying to match the argument list '(int)'
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer/ImageTracer.h(210) : error C2668: 'fabs' : ambiguous call to overloaded function
2> C:\Program Files\Microsoft Visual Studio 9.0\VC\include\math.h(557): could be 'long double fabs(long double)'
2> C:\Program Files\Microsoft Visual Studio 9.0\VC\include\math.h(509): or 'float fabs(float)'
2> C:\Program Files\Microsoft Visual Studio 9.0\VC\include\math.h(119): or 'double fabs(double)'
2> while trying to match the argument list '(int)'
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer/ImageTracer.h(366) : warning C4127: conditional expression is constant
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer/ImageTracer.h(530) : warning C4127: conditional expression is constant
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer/tga_image.h(135) : warning C4267: '=' : conversion from 'size_t' to 'int', possible loss of data
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer/tga_image.h(148) : warning C4244: '=' : conversion from 'int' to 'unsigned char', possible loss of data
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer/tga_image.h(150) : warning C4244: '=' : conversion from 'int' to 'unsigned char', possible loss of data
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer/tga_image.h(154) : warning C4267: '=' : conversion from 'size_t' to 'int', possible loss of data
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer/tga_image.h(189) : warning C4267: '=' : conversion from 'size_t' to 'int', possible loss of data
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer.h(98) : error C3861: 'clock': identifier not found
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer.h(170) : warning C4267: '+=' : conversion from 'size_t' to 'int', possible loss of data
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer.h(186) : error C2039: 'isALoop' : is not a member of 'b2EdgeChainDef'
2> c:\dev\box2d_svn2\trunk\include\../Source/Dynamics/b2EdgeChain.h(28) : see declaration of 'b2EdgeChainDef'
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer.h(190) : warning C4244: 'argument' : conversion from 'double' to 'float32', possible loss of data
1>Linking...
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer.h(190) : warning C4244: 'argument' : conversion from 'double' to 'float32', possible loss of data
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer.h(195) : warning C4267: '=' : conversion from 'size_t' to 'int32', possible loss of data
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer.h(198) : error C2039: 'CreateShape' : is not a member of 'b2Body'
2> c:\dev\box2d_svn2\trunk\source\dynamics\controllers\../../Dynamics/b2Body.h(110) : see declaration of 'b2Body'
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer.h(244) : error C2039: 'DestroyShape' : is not a member of 'b2Body'
2> c:\dev\box2d_svn2\trunk\source\dynamics\controllers\../../Dynamics/b2Body.h(110) : see declaration of 'b2Body'
2>c:\dev\box2d_svn2\trunk\examples\testbed\tests\TerrainTracer.h(248) : error C2039: 'DestroyShape' : is not a member of 'b2Body'
2> c:\dev\box2d_svn2\trunk\source\dynamics\controllers\../../Dynamics/b2Body.h(110) : see declaration of 'b2Body'
2>Build log was saved at "file://c:\Dev\Box2D_SVN2\trunk\Build\VC8\TestBed\Debug\BuildLog.htm"
2>TestBed - 10 error(s), 13 warning(s)
1>Embedding manifest...
1>Microsoft (R) Windows (R) Resource Compiler Version 6.1.6723.1
1>Copyright (C) Microsoft Corporation. All rights reserved.
1>Build log was saved at "file://c:\Dev\Box2D_SVN2\trunk\Build\VC8\HelloWorld\Debug\BuildLog.htm"
1>HelloWorld - 0 error(s), 1 warning(s)
Fixed and appears to work...

Ok, after spending a few hours piecing together the various updates and getting it to compile on 2.0.2 (tagged) I now have it working.

Reaper, you should be able to use this as it now outputs a file as per your specification / example 😀 - basically there were a few bugs in the code to write out the vertices.

Vertex Culling is left in because without it the sample was generating around 800 vertices rather than 144.

I have not used this in an app yet but hope to soon on iPhone.

Updated files are attached - Imagetracer.h and TerrainTracer.h

BTW bb_vb - this is great and really cool!
I haven't read the code, so if this doesn't apply, forgive me. From what I read earlier in the thread it looks like you're using a home baked algorithm to cull the extra verticies. My team faced similar problem a month ago. We really put our minds to it, but never really got something we liked. So we put it on the back burner and moved onto other tasks.

Then, last week we discovered Douglas Peucker. Holy Cow! It's so simple and effective we all felt like complete idiots for not seeing it. In our defense, all our attempts focused on removing meaningless verticies, whereas Douglas-Peucker focuses on added back in the important verticies.

Check it out, the algorithm really is simple, and the results really are quite good.

The basic description:
http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm

A really fancied up version:
http://www.codeproject.com/KB/recipes/dphull.aspx

-nick

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