BoxCutter

GetVertex/GetVertices can be replaced by just accessing the m_vertices of the b2PolygonShape (which is from some_fixture->shape).

I don't see GetSupport/GetSupportVertex in the BoxCutter code. They are still part of both b2CircleShape and b2DistanceProxy.
So after some work!

I managed all the code to "kind" of work of what i need! But now when you split some code, the bodies don't colide right with each other! i double check every single step, and i believe its everything exctly the same of this code, using new box2D stuffs, my code is here:
Code:
-(int)checkPolyShape:(const b2PolygonShape *)poly
{
    if(!(3 <= poly->m_vertexCount && poly->m_vertexCount <= b2_maxPolygonVertices))
    {
        NSLog(@"More vertices than max %i > %i",poly->m_vertexCount,b2_maxPolygonVertices);
        return -1;
    }
   
    b2Vec2 m_normals[b2_maxPolygonVertices];
   
    // Compute normals. Ensure the edges have non-zero length.
    for(int32 i = 0; i < poly->m_vertexCount; i++)
    {
        int32 i1 = i;
        int32 i2 = i + 1 < poly->m_vertexCount ? i + 1: 0;
       
        b2Vec2 edge = poly->m_vertices[i2] - poly->m_vertices[i1];
        if(!(edge.LengthSquared() > b2_epsilon * b2_epsilon))
        {
            NSLog(@"The Edge have a zero length: %f",b2_epsilon);
            return -1;
        }
        m_normals[i] = b2Cross(edge, 1.0);
        m_normals[i].Normalize();
    }
   
    // Ensure the polygon is convex.
    for(int32 i = 0; i < poly->m_vertexCount; i++)
    {
        for(int32 j = 0; j < poly->m_vertexCount; j++)
        {
            // Don't check vertices on the current edge.
            if(j == i || j == (i + 1) % poly->m_vertexCount)
            {
                continue;
            }
            // Your polygon is non-convex (it has an indentation).
            // Or your polygon is too skinny.
            float32 s = b2Dot(m_normals[i], poly->m_vertices[j] - poly->m_vertices[i]);
            if(!(s < -b2_linearSlop))
            {
                NSLog(@"%f > %f",s,-b2_angularSlop);
                return -1;
            }
        }
    }
    // Ensure the polygon is counter-clockwise.
    for(int32 i = 1; i < poly->m_vertexCount; i++)
    {
        float32 cross = b2Cross(m_normals[i-1], m_normals[i]);
       
        // Keep asinf happy.
        cross = b2Clamp(cross, -1.0f, 1.0f);
       
        // You have consecutive edges that are almost parallel on your polygon.
        float32 angle = asinf(cross);
       
        if(!(angle > b2_angularSlop))
        {
            NSLog(@"%f > %f",angle,b2_angularSlop);
            return -1;
        }
    }
   
    // Compute the polygon centroid.
    b2Vec2 m_centroid;
    m_centroid.Set(0.0f,0.0f);
    float32 area = 0.0f;
   
    // pRef is the reference point for forming triangles.
    // It's location doesn't change the result (except for rounding error).
    b2Vec2 pRef(0.0f, 0.0f);
   
    const float32 inv3 = 1.0f / 3.0f;
   
    for (int32 i = 0; i < poly->m_vertexCount; ++i)
    {
        b2Vec2 p1 = pRef;
        b2Vec2 p2 = poly->m_vertices[i];
        b2Vec2 p3 = i + 1 < poly->m_vertexCount ? poly->m_vertices[i+1] : poly->m_vertices[0];
       
        b2Vec2 e1 = p2 - p1;
        b2Vec2 e2 = p3 - p1;
       
        float32 D = b2Cross(e1, e2);
       
        float32 triangleArea = 0.5f * D;
        area += triangleArea;
       
        m_centroid += triangleArea * inv3 * (p1 + p2 + p3);
    }
   
    if(!(area > b2_epsilon))
    {
        NSLog(@"%f > %f",area,b2_epsilon);
        return -1;
    }
    m_centroid *= 1.0f / area;
   
    // Compute the oriented bounding box.
    //ComputeOBB(&m_obb, m_vertices, m_vertexCount);
   
    // Create core polygon shape by shifting edges inward.
    // Also compute the min/max radius for CCD.
    for (int32 i = 0; i < poly->m_vertexCount; ++i)
    {
        int32 i1 = i - 1 >= 0 ? i - 1 : poly->m_vertexCount - 1;
        int32 i2 = i;
       
        b2Vec2 n1 = m_normals[i1];
        b2Vec2 n2 = m_normals[i2];
        b2Vec2 v = poly->m_vertices[i] - m_centroid;
       
        b2Vec2 d;
        d.x = b2Dot(n1, v) - b2_linearSlop;
        d.y = b2Dot(n2, v) - b2_linearSlop;
       
        // Shifting the edge inward by b2_toiSlop should
        // not cause the plane to pass the centroid.
       
        // Your shape has a radius/extent less than b2_toiSlop.
        if(!(d.x >= 0.0f))
        {
            NSLog(@"(%f >= 0.0f)",d.x);
            return -1;
        }
        if(!(d.y >= 0.0f))
        {
            NSLog(@"(%f >= 0.0f)",d.y);
            return -1;
        }
    }
    return 0;
       
}
-(int)splitThisBodie:(b2Body*)pBody startAt:(b2Vec2 )pStart endingHere:(b2Vec2 )pEnd onThese:(b2PolygonShape *)newPolygon
{
   
    assert(pBody != NULL);
    assert(newPolygon != NULL);
   
    b2Vec2 localInPoint = pBody->GetLocalPoint(pStart);
    b2Vec2 localOutPoint = pBody->GetLocalPoint(pEnd);
   
    b2PolygonShape* bodyShape = (b2PolygonShape *)pBody->GetFixtureList()->GetShape();
   
    const b2Vec2* vertices = bodyShape->m_vertices;
    int cutAdded[2] = {-1,-1};
    int last = -1;
   
    for(int i = 0; i < bodyShape->GetVertexCount(); i++)
    {
        int n;
        if(b2Dot(b2Cross(localOutPoint-localInPoint, 1), vertices[i]-localInPoint) > 0)
        {
            n = 0;
        }
        else
        {
            n = 1;
        }
        if(last != n)
        {
            if(last == 0)
            {
                assert(cutAdded[0] == -1);
                cutAdded[0] = newPolygon[last].m_vertexCount;
                newPolygon[last].m_vertices[newPolygon[last].m_vertexCount] = localOutPoint;
                newPolygon[last].m_vertexCount++;
                newPolygon[last].m_vertices[newPolygon[last].m_vertexCount] = localInPoint;
                newPolygon[last].m_vertexCount++;
            }
            if(last == 1)
            {
                assert(cutAdded[last] == -1);
                cutAdded[last] = newPolygon[last].m_vertexCount;
                newPolygon[last].m_vertices[newPolygon[last].m_vertexCount] = localInPoint;
                newPolygon[last].m_vertexCount++;
                newPolygon[last].m_vertices[newPolygon[last].m_vertexCount] = localOutPoint;
                newPolygon[last].m_vertexCount++;
               
            }
        }
        newPolygon[n].m_vertices[newPolygon[n].m_vertexCount] = vertices[i];
        newPolygon[n].m_vertexCount++;
        last = n;
    }
    if(cutAdded[0] == -1)
    {
        cutAdded[0] = newPolygon[0].m_vertexCount;
        newPolygon[0].m_vertices[newPolygon[0].m_vertexCount] = localOutPoint;
        newPolygon[0].m_vertexCount++;
        newPolygon[0].m_vertices[newPolygon[0].m_vertexCount] = localInPoint;
        newPolygon[0].m_vertexCount++;
    }
    if(cutAdded[1] == -1)
    {
        cutAdded[1] = newPolygon[1].m_vertexCount;

        newPolygon[1].m_vertices[newPolygon[1].m_vertexCount] = localInPoint;
        newPolygon[1].m_vertexCount++;
        newPolygon[1].m_vertices[newPolygon[1].m_vertexCount] = localOutPoint;
        newPolygon[1].m_vertexCount++;
    }
    for(int n = 0; n < 2; n++)
    {
        b2Vec2 offSet;
        if(cutAdded[n] > 0)
        {
            offSet = (newPolygon[n].m_vertices[cutAdded[n]-1] - newPolygon[n].m_vertices[cutAdded[n]]);
        }
        else
        {
            offSet = (newPolygon[n].m_vertices[newPolygon[n].m_vertexCount-1] - newPolygon[n].m_vertices[0]);
        }
        offSet.Normalize();
       
        newPolygon[n].m_vertices[cutAdded[n]] += 0.05 * offSet;
       
        if(cutAdded[n] < newPolygon[n].m_vertexCount-2)
        {
            offSet = (newPolygon[n].m_vertices[cutAdded[n]+2] - newPolygon[n].m_vertices[cutAdded[n]+1]);
        }
        else
        {
            offSet = (newPolygon[n].m_vertices[0] - newPolygon[n].m_vertices[newPolygon[n].m_vertexCount-1]);
        }
        offSet.Normalize();
        newPolygon[n].m_vertices[cutAdded[n]+1] += 0.05 * offSet;
    }
    for( int n = 0; n < 2; n++)
    {
        const float Epsilon = 0.1f;
        for (int32 thisVert = 0; thisVert < newPolygon[n].m_vertexCount && newPolygon[n].m_vertexCount > 3; ++thisVert)
        {
            for (int32 otherVert = 0; otherVert < newPolygon[n].m_vertexCount && newPolygon[n].m_vertexCount > 3; ++otherVert)
            {
                if(thisVert != otherVert)
                {
                    if(fabs(newPolygon[n].m_vertices[thisVert].x - newPolygon[n].m_vertices[otherVert].x) < Epsilon
                       && fabs(newPolygon[n].m_vertices[thisVert].y - newPolygon[n].m_vertices[otherVert].y) < Epsilon)
                    {
                        // Duplicate vertex - remove the second one
                       
                        for (int shiftVerts = otherVert+1; shiftVerts < newPolygon[n].m_vertexCount; ++shiftVerts)
                        {
                            newPolygon[n].m_vertices[shiftVerts-1] = newPolygon[n].m_vertices[shiftVerts];
                        }
                       
                        --newPolygon[n].m_vertexCount;
                    }
                }
            }
        }
       
        if([self checkPolyShape:&newPolygon[n]])
        {
            NSLog(@"Something wrong with poly! can't cut");
            return -1;
        }
    }
    return 0;
}
-(void)cutBodyes
{
    CGPoint firstLocation = CGPointFromString([arrTouches objectAtIndex:0]);
    CGPoint secondLocation = CGPointFromString([arrTouches objectAtIndex:1]);
   
    firstLocation.x = firstLocation.x/PTM_RATIO;
    firstLocation.y = firstLocation.y/PTM_RATIO;
   
    secondLocation.x = secondLocation.x/PTM_RATIO;
    secondLocation.y = secondLocation.y/PTM_RATIO;
   
    b2Vec2 firstPoint(firstLocation.x, firstLocation.y);
    b2Vec2 secondPoint(secondLocation.x, secondLocation.y);
   
   
   
    // Get the Callback from In to Out
    RayCastMultipleCallback callbackIn;
    world->RayCast(&callbackIn ,firstPoint, secondPoint);
   
    // Get the Callback from Out to In
    RayCastMultipleCallback callbackOut;
    world->RayCast(&callbackOut ,secondPoint, firstPoint);
   
   
   
    for(int i = 0; i < callbackIn.m_count; i++)
    {
        b2Body *tryBody = callbackIn.m_body[i];
       
        if(tryBody->GetFixtureList()->GetShape()->GetType() != 1)
        {
            NSLog(@"Is not a Poly Shape, move on");
            continue;
        }
       
        b2Fixture *tempFixture = tryBody->GetFixtureList();
        b2PolygonShape pd[2];
       
       
        b2Vec2 inPointOfCollision = callbackIn.m_points[i];
        b2Vec2 outPointOfCollision = callbackOut.m_points[((callbackOut.m_count-1)-i)];
       
        [arrColision addObject:NSStringFromCGPoint(ccp(inPointOfCollision.x*PTM_RATIO,inPointOfCollision.y*PTM_RATIO))];
       
        [arrColision addObject:NSStringFromCGPoint(ccp(outPointOfCollision.x*PTM_RATIO,outPointOfCollision.y*PTM_RATIO))];
       
        if([self splitThisBodie:tryBody startAt:inPointOfCollision endingHere:outPointOfCollision onThese:pd] == 0)
        {
            NSLog(@"Splited Right! Move on");
            tryBody->DestroyFixture(tempFixture);
            tryBody->CreateFixture(&pd[0], 1.0f);
            tryBody->SetAwake(true);
           
           
            b2BodyDef bodyDef;
            bodyDef.type = b2_dynamicBody;
            //bodyDef.userData = (void *)1;
            bodyDef.position = tryBody->GetPosition();
            bodyDef.angle = tryBody->GetAngle();
           
            b2Body *newBody = world->CreateBody(&bodyDef);
            b2FixtureDef fixtureDef;
            fixtureDef.shape = &pd[1];   
            fixtureDef.density = 1.0f;
            fixtureDef.friction = 0.3f;
           
            newBody->SetAwake(true);
           
            newBody->CreateFixture(&fixtureDef);
            newBody->SetAngularVelocity(tryBody->GetAngularVelocity());
            newBody->SetLinearVelocity(tryBody->GetLinearVelocity());
           
        }
    }
}


Here is what is going on:

When you make the line:
http://img607.imageshack.us/i/capturade ... 411s0.png/


The objects are splited in the perfect way, but they have some issues, don't collide, crash with future splits and things like that:
http://img402.imageshack.us/i/capturade ... 411s0.png/
I made a video to better understanding the problem:

http://www.youtube.com/watch?v=jjxsw4VeMMQ
When I ran into issues while porting, instead of doing the actual splitting, I would just make it draw the shapes a split would create.

Perhaps doing that would shed some light on what's going on.
@kne

Following your steps, i make the draw of the shapes! and in the first cut ever its everything perfect! but the second ones, everything mess up:

Check this video:
http://www.youtube.com/watch?v=br84DqUyqQo

I'm really out of ideas of what is going on on my project!

i'm almost giving up.
Are you reusing the new polygon shapes and not clearing its vertex count/list?

Er, that looks like it somehow, yet it appears you're using a local variable for them...
I'm using in the exact same way of the original BoxCutter do?! I must clear my m_vertexCount? And verticesArray?!
But even the first cut, where he is exactly correct, the two new boxes generated, still has problems.
The first cut looks fine. Figure out why your second cut results in re-using some of the first cut's vertices, then we can go from there.
But at the first Cut, when everything its allright, all vertices are clear yet, i have the same bug!

I try to post here, every single diference i have to do, to make the code work:

1 - Remake how you get the entry and exit points of collision, to the new raycast method, this is working, because i can draw this, and see this is the perfect point of colision, and Box2D don't have anymore the b2Segment, so i must use the Touch points:

Quote:
Change from This:
Code:
const b2Body* b = shape->GetBody();
      const b2XForm xf = b->GetXForm();
      if (shape->TestSegment(xf, &lambda, &normal, segment, 1.0f) != e_hitCollide)
         return -1;
      b2Vec2 entryPoint = (1-lambda)*segment.p1+lambda*segment.p2;
      
      b2Segment reverseSegment;
      reverseSegment.p1 = segment.p2;
      reverseSegment.p2 = segment.p1;

      if (shape->TestSegment(xf, &lambda, &normal, reverseSegment, 1.0f) != e_hitCollide)
         return -1;
      b2Vec2 exitPoint = (1-lambda)*reverseSegment.p1+lambda*reverseSegment.p2;
      
      b2Vec2 localEntryPoint = b->GetLocalPoint(entryPoint);
      b2Vec2 localExitPoint = b->GetLocalPoint(exitPoint);



To this:
Code:
CGPoint firstLocation = CGPointFromString([arrTouches objectAtIndex:0]);
    CGPoint secondLocation = CGPointFromString([arrTouches objectAtIndex:1]);
   
    firstLocation.x = firstLocation.x/PTM_RATIO;
    firstLocation.y = firstLocation.y/PTM_RATIO;
   
    secondLocation.x = secondLocation.x/PTM_RATIO;
    secondLocation.y = secondLocation.y/PTM_RATIO;
   
    b2Vec2 firstPoint(firstLocation.x, firstLocation.y);
    b2Vec2 secondPoint(secondLocation.x, secondLocation.y);
   
   
    RayCastMultipleCallback callbackIn;
    world->RayCast(&callbackIn ,firstPoint, secondPoint);
   
    RayCastMultipleCallback callbackOut;
    world->RayCast(&callbackOut ,secondPoint, firstPoint);
   
    for(int i = 0; i < callbackIn.m_count; i++)
    {
        b2Body *tryBody = callbackIn.m_body[i];
        if(tryBody->GetFixtureList()->GetShape()->GetType() != 1)
        {
            NSLog(@"This Shape is not a Poly Shape, we can't continue");
            continue;
        }
       
        b2Fixture *tempFixture = tryBody->GetFixtureList();
        b2PolygonShape* bodyShape = (b2PolygonShape *)tryBody->GetFixtureList()->GetShape();
       
        b2PolygonShape pd[2];
       
        b2Vec2 inPointOfCollision = callbackIn.m_points[i];
        b2Vec2 outPointOfCollision = callbackOut.m_points[((callbackOut.m_count-1)-i)];

        b2Vec2 localEntryPoint = tryBody->GetLocalPoint(inPointOfCollision);
        b2Vec2 localExitPoint = tryBody->GetLocalPoint(outPointOfCollision);



2 - In the Function checkPolyShape i can't figure out what is the best way to doing that, but like someone said in this topic, you cant alloc the array like that:
Quote:
Can't do that:
Code:
b2Vec2 m_normals[poly->vertexCount];


So, just to make this work i change to that:
Code:
b2Vec2 m_normals[b2_maxPolygonVertices];



But i don't believe this is the problem, because, even if don't do this verification in checkPolyShape, like @kne do in the python code, the bug still exist


3 - And another modification i have to do is the part where you recreate your body:
Quote:
In original its like that:
Code:
if (SplitShape(polyShape, segment, 0.1, pd) == 0)
         {
            b->DestroyShape(shapes[i]);
            b->CreateShape(&pd[0]);
            b->SetMassFromShapes();
            b->WakeUp();
            
            b2BodyDef bd;
            bd.userData = (void*)1;
            bd.position = b->GetPosition();
            bd.angle = b->GetAngle();
            b2Body* newBody = m_world->CreateBody(&bd);
            newBody->CreateShape(&pd[1]);
            newBody->SetMassFromShapes();
            newBody->SetAngularVelocity(b->GetAngularVelocity());
            newBody->SetLinearVelocity(b->GetLinearVelocity());
         }


I'm have to change to this:
Code:
if([self SplitBody:tryBody from:inPointOfCollision to:outPointOfCollision andReturnInThisObject:pd] == 0)
        {
            tryBody->DestroyFixture(tempFixture);
            tryBody->CreateFixture(&pd[0], 1.0f);
           
            b2BodyDef bodyDef;
            bodyDef.type = b2_dynamicBody;
            //bodyDef.userData = (void *)1;
            bodyDef.position = tryBody->GetPosition();
            bodyDef.angle = tryBody->GetAngle();
           
            b2Body *newBody = world->CreateBody(&bodyDef);
            b2FixtureDef fixtureDef;
            fixtureDef.shape = &pd[1];   
            fixtureDef.density = 1.0f;
            fixtureDef.friction = 0.3f;
           
           
            newBody->CreateFixture(&fixtureDef);
            newBody->SetAngularVelocity(tryBody->GetAngularVelocity());
            newBody->SetLinearVelocity(tryBody->GetLinearVelocity());
        }



Looks like it's something when you recreate the bodie, some filter, something i have to do in diferent way in this new box2D version, like the SetMassFromShapes(), i try to rewrote this to another things, but i keep geting this bug! The objects acting like that in this movie:
http://www.youtube.com/watch?v=jkN4Yla_9Ek
The SetMassFromShapes() was removed from b2body and now the Mass is automatically updated when you create/destroy fixture.

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