clockwise option, joint is awake (#130)

- b3MeshDef gets stride and clockwise option
- Added b3Joint_IsAwake
- Added b3Body_TimeOfImpactMover
- #116
- Smoother mover collision: #141
- Shape casts now ignore backside collision on mesh and height-field
triangles, same as ray casts.
This commit is contained in:
Erin Catto 2026-08-29 21:47:53 -07:00 • committed by GitHub
commit 47d7f7cc7e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
35 changed files with 2466 additions and 303 deletions

View file

@ -779,6 +779,87 @@ int b3Body_CollideMover( b3BodyId bodyId, b3BodyPlaneResult* bodyPlanes, int pla
return resultCount;
}
b3BodyTOIResult b3Body_TimeOfImpactMover( b3BodyId bodyId, b3Pos origin, const b3Capsule* mover, b3Vec3 moverTranslation,
b3QueryFilter filter, b3WorldTransform bodyTransform1, b3WorldTransform bodyTransform2 )
{
b3BodyTOIResult result = { 0 };
result.fraction = 1.0f;
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world == NULL )
{
return result;
}
b3Transform xf1 = b3ToRelativeTransform( bodyTransform1, origin );
b3Transform xf2 = b3ToRelativeTransform( bodyTransform2, origin );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3BodySim* bodySim = b3GetBodySim( world, body );
b3Vec3 localCenter = bodySim->localCenter;
b3Vec3 capsulePoints[2] = { mover->center1, mover->center2 };
b3TOIInput input = { 0 };
input.proxyB = (b3ShapeProxy){
.points = capsulePoints,
.count = 2,
.radius = mover->radius,
};
input.sweepA.c1 = b3TransformPoint( xf1, localCenter );
input.sweepA.c2 = b3TransformPoint( xf2, localCenter );
input.sweepA.q1 = bodyTransform1.q;
input.sweepA.q2 = bodyTransform2.q;
input.sweepA.localCenter = localCenter;
input.sweepB.c1 = b3Vec3_zero;
input.sweepB.c2 = moverTranslation;
input.sweepB.q1 = b3Quat_identity;
input.sweepB.q2 = b3Quat_identity;
input.sweepB.localCenter = b3Vec3_zero;
input.maxFraction = 1.0f;
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )
{
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
shapeId = shape->nextShapeId;
if ( b3ShouldQueryCollide( &shape->filter, &filter ) == false )
{
continue;
}
b3ShapeType type = shape->type;
if ( type != b3_sphereShape && type != b3_capsuleShape && type != b3_hullShape )
{
continue;
}
input.proxyA = b3MakeShapeProxy( shape );
b3TOIOutput output = b3TimeOfImpact( &input );
B3_VALIDATE( output.state != b3_toiStateUnknown );
// Mimic behavior in b3ContinuousQueryCallback. Ignore shapes that initially overlap.
if (0.0f < output.fraction && output.fraction < result.fraction)
{
input.maxFraction = output.fraction;
result.point = b3OffsetPos( origin, output.point );
result.normal = output.normal;
result.fraction = output.fraction;
result.shapeId = (b3ShapeId){
.index1 = shape->id + 1,
.world0 = world->worldId,
.generation = shape->generation,
};
}
}
return result;
}
void b3UpdateBodyMassData( b3World* world, b3Body* body )
{
b3BodySim* bodySim = b3GetBodySim( world, body );
@ -2303,7 +2384,7 @@ bool b3Body_IsBullet( b3BodyId bodyId )
return ( body->flags & b3_isBullet ) != 0;
}
void b3Body_AllowFastRotation(b3BodyId bodyId, bool flag)
void b3Body_AllowFastRotation( b3BodyId bodyId, bool flag )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world == NULL )
@ -2327,7 +2408,7 @@ void b3Body_AllowFastRotation(b3BodyId bodyId, bool flag)
b3SyncBodyFlags( world, body );
}
bool b3Body_IsFastRotationAllowed(b3BodyId bodyId)
bool b3Body_IsFastRotationAllowed( b3BodyId bodyId )
{
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
@ -2481,3 +2562,27 @@ bool b3ShouldBodiesCollide( b3World* world, b3Body* bodyA, b3Body* bodyB )
return true;
}
float b3Body_GetMinExtent( b3BodyId bodyId )
{
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3BodySim* bodySim = b3GetBodySim( world, body );
return bodySim->minExtent;
}
b3Vec3 b3Body_GetMaxExtent( b3BodyId bodyId )
{
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3BodySim* bodySim = b3GetBodySim( world, body );
return bodySim->maxExtent;
}
b3Vec3 b3Body_GetMaxExtentOrigin( b3BodyId bodyId )
{
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3BodySim* bodySim = b3GetBodySim( world, body );
return b3Add( bodySim->maxExtent, b3Abs( bodySim->localCenter ) );
}

View file

@ -380,6 +380,6 @@ int b3CollideMoverAndCapsule( b3PlaneResult* result, const b3Capsule* shape, con
}
b3Plane plane = { normal, totalRadius - distance };
*result = (b3PlaneResult){ plane, approach.point1 };
*result = (b3PlaneResult){ plane, approach.point1, 0, 0, 0 };
return 1;
}

View file

@ -399,7 +399,9 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
// No effort to share mesh materials. It would be easier to do if the number of materials was limited.
B3_ASSERT( meshData->materialCount == meshDef->materialCount );
for ( int j = 0; j < meshDef->materialCount; ++j )
int meshMaterialCount = b3MinInt( meshDef->materialCount, B3_MAX_COMPOUND_MESH_MATERIALS );
for ( int j = 0; j < meshMaterialCount; ++j )
{
// Look for an existing material.
b3MaterialMap_itr materialItr =
@ -1168,6 +1170,10 @@ static bool b3CompoundMoverCallback( int proxyId, uint64_t userData, void* conte
{
planes[i].plane.normal = b3RotateVector( child.transform.q, planes[i].plane.normal );
planes[i].point = b3TransformPoint( child.transform, planes[i].point );
planes[i].childIndex = childIndex;
int childMaterialIndex = b3MinInt( planes[i].materialIndex, B3_MAX_COMPOUND_MESH_MATERIALS - 1 );
planes[i].materialIndex = child.materialIndices[childMaterialIndex];
}
moverContext->planeCount += planeCount;

View file

@ -278,7 +278,6 @@ static void b3ReduceManifoldPoints( b3LocalManifold* manifold, int capacity, b3L
// Step 2: Find farthest point in 2D
bestScore = 0.0f;
bestIndex = B3_NULL_INDEX;
float maxDistanceSquared = 0.0f;
for ( int index = 0; index < count; ++index )
{
@ -286,7 +285,6 @@ static void b3ReduceManifoldPoints( b3LocalManifold* manifold, int capacity, b3L
b3Vec3 d = b3Sub( p, a );
b3Vec3 v = b3MulSub( d, b3Dot( d, normal ), normal );
float distanceSquared = b3LengthSquared( v );
maxDistanceSquared = b3MaxFloat( maxDistanceSquared, distanceSquared );
float separation = b3MaxFloat( 0.0f, -points[index].separation );
float score = distanceSquared + 4.0f * separation * separation;
if ( bias * score > bestScore )

View file

@ -847,6 +847,10 @@ b3DistanceOutput b3ShapeDistance( const b3DistanceInput* input, b3SimplexCache*
b3ComputeWitnessPoints( &simplex, &localPointA, &localPointB );
distanceOutput.pointA = localPointA;
distanceOutput.pointB = localPointB;
distanceOutput.normal = b3Vec3_zero;
distanceOutput.distance = 0.0f;
distanceOutput.iterations = iteration;
distanceOutput.simplexCount = simplexIndex;
return distanceOutput;
}
@ -943,6 +947,10 @@ b3DistanceOutput b3ShapeDistance( const b3DistanceInput* input, b3SimplexCache*
b3ComputeWitnessPoints( &simplex, &localPointA, &localPointB );
distanceOutput.pointA = localPointA;
distanceOutput.pointB = localPointB;
distanceOutput.normal = b3Vec3_zero;
distanceOutput.distance = 0.0f;
distanceOutput.iterations = iteration;
distanceOutput.simplexCount = simplexIndex;
B3_VALIDATE( b3Distance( localPointA, localPointB ) < FLT_EPSILON );
return distanceOutput;
}
@ -984,25 +992,27 @@ b3DistanceOutput b3ShapeDistance( const b3DistanceInput* input, b3SimplexCache*
simplex.count += 1;
}
// Build witness points.
b3Vec3 localPointA, localPointB;
b3ComputeWitnessPoints( &simplex, &localPointA, &localPointB );
distanceOutput.pointA = localPointA;
distanceOutput.pointB = localPointB;
distanceOutput.iterations = iteration;
distanceOutput.simplexCount = simplexIndex;
normal = b3Normalize( normal );
if ( b3IsNormalized( normal ) == false )
{
// Treat as overlap
distanceOutput.distance = 0.0f;
distanceOutput.normal = b3Vec3_zero;
return distanceOutput;
}
// Build witness points and safe cache
b3Vec3 localPointA, localPointB;
b3ComputeWitnessPoints( &simplex, &localPointA, &localPointB );
b3WriteCache( cache, &simplex );
// Results stay in frame A
distanceOutput.pointA = localPointA;
distanceOutput.pointB = localPointB;
distanceOutput.distance = b3Distance( localPointA, localPointB );
distanceOutput.normal = normal;
distanceOutput.iterations = iteration;
distanceOutput.simplexCount = simplexIndex;
// Apply radii if requested
if ( input->useRadii )
@ -1016,10 +1026,12 @@ b3DistanceOutput b3ShapeDistance( const b3DistanceInput* input, b3SimplexCache*
distanceOutput.pointB = b3Sub( distanceOutput.pointB, b3MulSV( rB, normal ) );
}
// Simplex is useful, cache it.
b3WriteCache( cache, &simplex );
return distanceOutput;
}
// Separation function:
// f(t) = (c2 + t * dp2 - c1 - t * dp1 ) * n
@ -1703,6 +1715,14 @@ b3TOIOutput b3TimeOfImpact( const b3TOIInput* input )
{
output.state = b3_toiStateOverlapped;
output.fraction = 0.0f;
// Averaged hit point
b3Vec3 pA = b3MulAdd( worldPointA, proxyA.radius, worldNormal );
b3Vec3 pB = b3MulAdd( worldPointB, -proxyB.radius, worldNormal );
output.point = b3Lerp( pA, pB, 0.5f );
output.point = b3Add( output.point, origin );
output.normal = worldNormal;
break;
}

View file

@ -608,6 +608,7 @@ b3CastOutput b3ShapeCastHeightField( const b3HeightFieldData* heightField, const
b3Vec3 shapeTranslation = input->translation;
b3Vec3 scale = heightField->scale;
// The shape start is the center of the proxy.
b3Vec3 shapeStart = b3AABB_Center( shapeBounds );
b3Vec3 shapeDelta = b3MulSV( input->maxFraction, shapeTranslation );
b3Vec3 shapeEnd = b3Add( shapeStart, shapeDelta );
@ -768,9 +769,12 @@ b3CastOutput b3ShapeCastHeightField( const b3HeightFieldData* heightField, const
castBounds.lowerBound = b3Sub( b3Min( centerStart, centerEnd ), shapeExtents );
castBounds.upperBound = b3Add( b3Max( centerStart, centerEnd ), shapeExtents );
// The ray origin is the center of the shape.
b3V32 rayOrigin = b3LoadV( &shapeStart.x );
b3V32 rayTranslation = b3LoadV( &shapeTranslation.x );
bool clockwise = heightField->clockwise;
while ( true )
{
int column1, column2;
@ -827,6 +831,11 @@ b3CastOutput b3ShapeCastHeightField( const b3HeightFieldData* heightField, const
b3Vec3 point21 = corners[2];
b3Vec3 point22 = corners[3];
if ( clockwise )
{
B3_SWAP( point12, point21 );
}
// I know the min/max x and z values, but not the min/max heights.
b3AABB bounds;
bounds.lowerBound = b3Min( b3Min( point11, point12 ), b3Min( point21, point22 ) );
@ -846,18 +855,8 @@ b3CastOutput b3ShapeCastHeightField( const b3HeightFieldData* heightField, const
// Ray cast
{
b3V32 vertex1 = b3LoadV( &point11.x );
b3V32 vertex2, vertex3;
if ( heightField->clockwise )
{
vertex2 = b3LoadV( &point12.x );
vertex3 = b3LoadV( &point21.x );
}
else
{
vertex2 = b3LoadV( &point21.x );
vertex3 = b3LoadV( &point12.x );
}
b3V32 vertex2 = b3LoadV( &point21.x );
b3V32 vertex3 = b3LoadV( &point12.x );
float alpha = b3IntersectRayTriangle( rayOrigin, rayTranslation, vertex1, vertex2, vertex3 );
B3_ASSERT( 0 <= alpha && alpha <= 1.0f );
@ -866,7 +865,7 @@ b3CastOutput b3ShapeCastHeightField( const b3HeightFieldData* heightField, const
{
b3Vec3 edge1 = b3Sub( point21, point11 );
b3Vec3 edge2 = b3Sub( point12, point11 );
b3Vec3 normal = heightField->clockwise ? b3Cross( edge2, edge1 ) : b3Cross( edge1, edge2 );
b3Vec3 normal = b3Cross( edge1, edge2 );
result.point = b3MulAdd( shapeStart, alpha, shapeTranslation );
result.normal = b3Normalize( normal );
@ -880,18 +879,8 @@ b3CastOutput b3ShapeCastHeightField( const b3HeightFieldData* heightField, const
{
b3V32 vertex1 = b3LoadV( &point22.x );
b3V32 vertex2, vertex3;
if ( heightField->clockwise )
{
vertex2 = b3LoadV( &point21.x );
vertex3 = b3LoadV( &point12.x );
}
else
{
vertex2 = b3LoadV( &point12.x );
vertex3 = b3LoadV( &point21.x );
}
b3V32 vertex2 = b3LoadV( &point12.x );
b3V32 vertex3 = b3LoadV( &point21.x );
float alpha = b3IntersectRayTriangle( rayOrigin, rayTranslation, vertex1, vertex2, vertex3 );
B3_ASSERT( 0 <= alpha && alpha <= 1.0f );
@ -900,7 +889,7 @@ b3CastOutput b3ShapeCastHeightField( const b3HeightFieldData* heightField, const
{
b3Vec3 edge1 = b3Sub( point22, point21 );
b3Vec3 edge2 = b3Sub( point12, point21 );
b3Vec3 normal = heightField->clockwise ? b3Cross( edge2, edge1 ) : b3Cross( edge1, edge2 );
b3Vec3 normal = b3Cross( edge1, edge2 );
result.point = b3MulAdd( shapeStart, alpha, shapeTranslation );
result.normal = b3Normalize( normal );
@ -915,44 +904,55 @@ b3CastOutput b3ShapeCastHeightField( const b3HeightFieldData* heightField, const
else
{
// Shape cast
// todo back-side culling
{
// Shift origin to first vertex
b3Vec3 origin = point11;
b3Vec3 triangleVertices[] = { b3Vec3_zero, b3Sub( point21, origin ), b3Sub( point12, origin ) };
pairInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f };
pairInput.maxFraction = bestFraction;
pairInput.transform.p = b3Neg( origin );
// shapeStart is the center of the proxy.
float signedVolume = b3SignedVolume( point11, point21, point12, shapeStart );
b3CastOutput pairOutput = b3ShapeCast( &pairInput );
if ( pairOutput.hit )
if ( signedVolume >= 0.0f )
{
bestFraction = pairOutput.fraction;
result = pairOutput;
result.point = b3Add( result.point, origin );
result.triangleIndex = triangleIndex1;
result.materialIndex = materialIndex;
// Shift origin to first vertex
b3Vec3 origin = point11;
b3Vec3 triangleVertices[] = { b3Vec3_zero, b3Sub( point21, origin ), b3Sub( point12, origin ) };
pairInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f };
pairInput.maxFraction = bestFraction;
pairInput.transform.p = b3Neg( origin );
b3CastOutput pairOutput = b3ShapeCast( &pairInput );
if ( pairOutput.hit )
{
bestFraction = pairOutput.fraction;
result = pairOutput;
result.point = b3Add( result.point, origin );
result.triangleIndex = triangleIndex1;
result.materialIndex = materialIndex;
}
}
}
{
// Shift origin to first vertex
b3Vec3 origin = point21;
b3Vec3 triangleVertices[] = { b3Vec3_zero, b3Sub( point22, origin ), b3Sub( point12, origin ) };
pairInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f };
pairInput.maxFraction = bestFraction;
pairInput.transform.p = b3Neg( origin );
// shapeStart is the center of the proxy.
float signedVolume = b3SignedVolume( point21, point22, point12, shapeStart );
b3CastOutput pairOutput = b3ShapeCast( &pairInput );
if ( pairOutput.hit )
if ( signedVolume >= 0.0f )
{
bestFraction = pairOutput.fraction;
result = pairOutput;
result.point = b3Add( result.point, origin );
result.triangleIndex = triangleIndex2;
result.materialIndex = materialIndex;
// Shift origin to first vertex
b3Vec3 origin = point21;
b3Vec3 triangleVertices[] = { b3Vec3_zero, b3Sub( point22, origin ), b3Sub( point12, origin ) };
pairInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f };
pairInput.maxFraction = bestFraction;
pairInput.transform.p = b3Neg( origin );
b3CastOutput pairOutput = b3ShapeCast( &pairInput );
if ( pairOutput.hit )
{
bestFraction = pairOutput.fraction;
result = pairOutput;
result.point = b3Add( result.point, origin );
result.triangleIndex = triangleIndex2;
result.materialIndex = materialIndex;
}
}
}
}
@ -1055,8 +1055,7 @@ bool b3OverlapHeightField( const b3HeightFieldData* shape, b3Transform shapeTran
b3SimplexCache cache = { 0 };
// Outer loop on rows and inner loop on columns so that triangle indices
// increase monotonically.
// Outer loop on rows and inner loop on columns so that triangle indices increase monotonically.
for ( int row = minRow; row <= maxRow; ++row )
{
if ( row < 0 || shape->rowCount - 1 <= row )
@ -1210,6 +1209,7 @@ int b3CollideMoverAndHeightField( b3PlaneResult* planes, int capacity, const b3H
b3SimplexCache cache = { 0 };
float radius = mover->radius;
b3Vec3 center = b3Lerp( mover->center1, mover->center2, 0.5f );
b3V32 center1 = b3LoadV( &mover->center1.x );
b3V32 center2 = b3LoadV( &mover->center2.x );
b3V32 r = b3SplatV( radius );
@ -1229,6 +1229,8 @@ int b3CollideMoverAndHeightField( b3PlaneResult* planes, int capacity, const b3H
int minCol = (int)floorf( localMinX / scale.x );
int maxCol = (int)floorf( localMaxX / scale.x );
bool clockWise = shape->clockwise;
int planeCount = 0;
// Outer loop on rows and inner loop on columns so that triangle indices
@ -1262,63 +1264,84 @@ int b3CollideMoverAndHeightField( b3PlaneResult* planes, int capacity, const b3H
b3Vec3 point21 = corners[2];
b3Vec3 point22 = corners[3];
if ( clockWise )
{
B3_SWAP( point12, point21 );
}
b3V32 v11 = b3LoadV( &point11.x );
b3V32 v12 = b3LoadV( &point12.x );
b3V32 v21 = b3LoadV( &point21.x );
b3V32 v22 = b3LoadV( &point22.x );
if ( b3TestBoundsTriangleOverlap( boundsCenter, boundsExtent, v11, v21, v12 ) )
bool overlap1 = b3TestBoundsTriangleOverlap( boundsCenter, boundsExtent, v11, v21, v12 );
if ( overlap1 )
{
b3Vec3 triangleVertices[] = { point11, point21, point12 };
distanceInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f };
float signedVolume = b3SignedVolume( point11, point21, point12, center );
// reset the cache
cache.count = 0;
// get distance between triangle and mover
b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 );
if ( distanceOutput.distance == 0.0f )
// Front side?
if ( signedVolume >= 0.0f )
{
// todo SAT
}
else if ( distanceOutput.distance <= mover->radius )
{
b3Plane plane = { distanceOutput.normal, mover->radius - distanceOutput.distance };
planes[planeCount] = (b3PlaneResult){ plane, distanceOutput.pointA };
planeCount += 1;
b3Vec3 triangleVertices[] = { point11, point21, point12 };
distanceInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f };
if ( planeCount == capacity )
// reset the cache
cache.count = 0;
// get distance between triangle and mover
b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 );
if ( distanceOutput.distance == 0.0f )
{
return planeCount;
// deep overlap
}
else if ( distanceOutput.distance <= mover->radius )
{
int triangleIndex = 2 * cellIndex;
b3Plane plane = { distanceOutput.normal, mover->radius - distanceOutput.distance };
planes[planeCount] = (b3PlaneResult){ plane, distanceOutput.pointA, triangleIndex, 0, material };
planeCount += 1;
if ( planeCount == capacity )
{
return planeCount;
}
}
}
}
if ( b3TestBoundsTriangleOverlap( boundsCenter, boundsExtent, v21, v22, v12 ) )
bool overlap2 = b3TestBoundsTriangleOverlap( boundsCenter, boundsExtent, v21, v22, v12 );
if ( overlap2 )
{
b3Vec3 triangleVertices[] = { point22, point12, point21 };
distanceInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f };
float signedVolume = b3SignedVolume( point22, point12, point21, center );
// reset the cache
cache.count = 0;
// get distance between triangle and mover
b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 );
if ( distanceOutput.distance == 0.0f )
// Front side?
if ( signedVolume >= 0.0f )
{
// todo SAT
}
else if ( distanceOutput.distance <= mover->radius )
{
b3Plane plane = { distanceOutput.normal, mover->radius - distanceOutput.distance };
planes[planeCount] = (b3PlaneResult){ plane, distanceOutput.pointA };
planeCount += 1;
b3Vec3 triangleVertices[] = { point22, point12, point21 };
distanceInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f };
if ( planeCount == capacity )
// reset the cache
cache.count = 0;
// get distance between triangle and mover
b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 );
if ( distanceOutput.distance == 0.0f )
{
return planeCount;
// deep overlap
}
else if ( distanceOutput.distance <= mover->radius )
{
int triangleIndex = 2 * cellIndex + 1;
b3Plane plane = { distanceOutput.normal, mover->radius - distanceOutput.distance };
planes[planeCount] = (b3PlaneResult){ plane, distanceOutput.pointA, triangleIndex, 0, material };
planeCount += 1;
if ( planeCount == capacity )
{
return planeCount;
}
}
}
}

View file

@ -2655,7 +2655,7 @@ int b3CollideMoverAndHull( b3PlaneResult* result, const b3HullData* shape, const
if ( distanceOutput.distance <= totalRadius )
{
b3Plane plane = { distanceOutput.normal, totalRadius - distanceOutput.distance };
*result = (b3PlaneResult){ plane, distanceOutput.pointA };
*result = (b3PlaneResult){ plane, distanceOutput.pointA, 0, 0, 0 };
return 1;
}

View file

@ -120,7 +120,7 @@ b3ExplosionDef b3DefaultExplosionDef( void )
b3Joint* b3GetJointFullId( b3World* world, b3JointId jointId )
{
int id = jointId.index1 - 1;
b3Joint* joint = b3Array_Get( world->joints, id );
b3Joint* joint = b3Array_Get( world->joints, id );
B3_ASSERT( joint->jointId == id && joint->generation == jointId.generation );
return joint;
}
@ -131,11 +131,11 @@ b3JointSim* b3GetJointSim( b3World* world, b3Joint* joint )
{
B3_ASSERT( 0 <= joint->colorIndex && joint->colorIndex < B3_GRAPH_COLOR_COUNT );
b3GraphColor* color = world->constraintGraph.colors + joint->colorIndex;
return b3Array_Get( color->jointSims, joint->localIndex );
return b3Array_Get( color->jointSims, joint->localIndex );
}
b3SolverSet* set = b3Array_Get( world->solverSets, joint->setIndex );
return b3Array_Get( set->jointSims, joint->localIndex );
b3SolverSet* set = b3Array_Get( world->solverSets, joint->setIndex );
return b3Array_Get( set->jointSims, joint->localIndex );
}
b3JointSim* b3GetJointSimCheckType( b3JointId jointId, b3JointType type )
@ -171,10 +171,10 @@ static b3JointPair b3CreateJoint( b3World* world, const b3JointDef* def, b3Joint
int jointId = b3AllocId( &world->jointIdPool );
if ( jointId == world->joints.count )
{
b3Array_Push( world->joints, (b3Joint){ 0 } );
b3Array_Push( world->joints, (b3Joint){ 0 } );
}
b3Joint* joint = b3Array_Get( world->joints, jointId );
b3Joint* joint = b3Array_Get( world->joints, jointId );
joint->jointId = jointId;
joint->userData = def->userData;
joint->generation += 1;
@ -195,7 +195,7 @@ static b3JointPair b3CreateJoint( b3World* world, const b3JointDef* def, b3Joint
int keyA = ( jointId << 1 ) | 0;
if ( bodyA->headJointKey != B3_NULL_INDEX )
{
b3Joint* jointA = b3Array_Get( world->joints, bodyA->headJointKey >> 1 );
b3Joint* jointA = b3Array_Get( world->joints, bodyA->headJointKey >> 1 );
b3JointEdge* edgeA = jointA->edges + ( bodyA->headJointKey & 1 );
edgeA->prevKey = keyA;
}
@ -210,7 +210,7 @@ static b3JointPair b3CreateJoint( b3World* world, const b3JointDef* def, b3Joint
int keyB = ( jointId << 1 ) | 1;
if ( bodyB->headJointKey != B3_NULL_INDEX )
{
b3Joint* jointB = b3Array_Get( world->joints, bodyB->headJointKey >> 1 );
b3Joint* jointB = b3Array_Get( world->joints, bodyB->headJointKey >> 1 );
b3JointEdge* edgeB = jointB->edges + ( bodyB->headJointKey & 1 );
edgeB->prevKey = keyB;
}
@ -222,7 +222,7 @@ static b3JointPair b3CreateJoint( b3World* world, const b3JointDef* def, b3Joint
if ( bodyA->setIndex == b3_disabledSet || bodyB->setIndex == b3_disabledSet )
{
// if either body is disabled, create in disabled set
b3SolverSet* set = b3Array_Get( world->solverSets, b3_disabledSet );
b3SolverSet* set = b3Array_Get( world->solverSets, b3_disabledSet );
joint->setIndex = b3_disabledSet;
joint->localIndex = set->jointSims.count;
@ -236,7 +236,7 @@ static b3JointPair b3CreateJoint( b3World* world, const b3JointDef* def, b3Joint
else if ( bodyA->type != b3_dynamicBody && bodyB->type != b3_dynamicBody )
{
// joint is not attached to a dynamic body
b3SolverSet* set = b3Array_Get( world->solverSets, b3_staticSet );
b3SolverSet* set = b3Array_Get( world->solverSets, b3_staticSet );
joint->setIndex = b3_staticSet;
joint->localIndex = set->jointSims.count;
@ -271,7 +271,7 @@ static b3JointPair b3CreateJoint( b3World* world, const b3JointDef* def, b3Joint
// joint should go into the sleeping set (not static set)
int setIndex = maxSetIndex;
b3SolverSet* set = b3Array_Get( world->solverSets, setIndex );
b3SolverSet* set = b3Array_Get( world->solverSets, setIndex );
joint->setIndex = setIndex;
joint->localIndex = set->jointSims.count;
@ -292,10 +292,10 @@ static b3JointPair b3CreateJoint( b3World* world, const b3JointDef* def, b3Joint
// fix potentially invalid set index
setIndex = bodyA->setIndex;
b3SolverSet* mergedSet = b3Array_Get( world->solverSets, setIndex );
b3SolverSet* mergedSet = b3Array_Get( world->solverSets, setIndex );
// Careful! The joint sim pointer was orphaned by the set merge.
jointSim = b3Array_Get( mergedSet->jointSims, joint->localIndex );
jointSim = b3Array_Get( mergedSet->jointSims, joint->localIndex );
}
B3_ASSERT( joint->setIndex == setIndex );
@ -359,7 +359,7 @@ static void b3DestroyContactsBetweenBodies( b3World* world, b3Body* bodyA, b3Bod
int contactId = contactKey >> 1;
int edgeIndex = contactKey & 1;
b3Contact* contact = b3Array_Get( world->contacts, contactId );
b3Contact* contact = b3Array_Get( world->contacts, contactId );
contactKey = contact->edges[edgeIndex].nextKey;
int otherEdgeIndex = edgeIndex ^ 1;
@ -437,7 +437,7 @@ b3JointId b3CreateDistanceJoint( b3WorldId worldId, const b3DistanceJointDef* de
{
B3_CHECK_JOINT_DEF( def );
b3World* world = b3GetUnlockedWorldFromId( worldId );
if (world == NULL)
if ( world == NULL )
{
return (b3JointId){ 0 };
}
@ -505,7 +505,7 @@ b3JointId b3CreateFilterJoint( b3WorldId worldId, const b3FilterJointDef* def )
{
B3_CHECK_JOINT_DEF( def );
b3World* world = b3GetUnlockedWorldFromId( worldId );
if (world == NULL)
if ( world == NULL )
{
return (b3JointId){ 0 };
}
@ -523,7 +523,7 @@ b3JointId b3CreateParallelJoint( b3WorldId worldId, const b3ParallelJointDef* de
{
B3_CHECK_JOINT_DEF( def );
b3World* world = b3GetUnlockedWorldFromId( worldId );
if (world == NULL)
if ( world == NULL )
{
return (b3JointId){ 0 };
}
@ -552,7 +552,7 @@ b3JointId b3CreatePrismaticJoint( b3WorldId worldId, const b3PrismaticJointDef*
B3_ASSERT( def->lowerTranslation <= def->upperTranslation );
b3World* world = b3GetUnlockedWorldFromId( worldId );
if (world == NULL)
if ( world == NULL )
{
return (b3JointId){ 0 };
}
@ -583,7 +583,7 @@ b3JointId b3CreateRevoluteJoint( b3WorldId worldId, const b3RevoluteJointDef* de
B3_CHECK_JOINT_DEF( def );
b3World* world = b3GetUnlockedWorldFromId( worldId );
if (world == NULL)
if ( world == NULL )
{
return (b3JointId){ 0 };
}
@ -620,7 +620,7 @@ b3JointId b3CreateSphericalJoint( b3WorldId worldId, const b3SphericalJointDef*
B3_ASSERT( b3IsValidQuat( def->targetRotation ) );
b3World* world = b3GetUnlockedWorldFromId( worldId );
if (world == NULL)
if ( world == NULL )
{
return (b3JointId){ 0 };
}
@ -661,7 +661,7 @@ b3JointId b3CreateWeldJoint( b3WorldId worldId, const b3WeldJointDef* def )
B3_ASSERT( 0.0f <= def->linearDampingRatio );
b3World* world = b3GetUnlockedWorldFromId( worldId );
if (world == NULL)
if ( world == NULL )
{
return (b3JointId){ 0 };
}
@ -687,7 +687,7 @@ b3JointId b3CreateWheelJoint( b3WorldId worldId, const b3WheelJointDef* def )
B3_ASSERT( def->lowerSuspensionLimit <= def->upperSuspensionLimit );
b3World* world = b3GetUnlockedWorldFromId( worldId );
if (world == NULL)
if ( world == NULL )
{
return (b3JointId){ 0 };
}
@ -730,20 +730,20 @@ void b3DestroyJointInternal( b3World* world, b3Joint* joint, bool wakeBodies )
int idA = edgeA->bodyId;
int idB = edgeB->bodyId;
b3Body* bodyA = b3Array_Get( world->bodies, idA );
b3Body* bodyB = b3Array_Get( world->bodies, idB );
b3Body* bodyA = b3Array_Get( world->bodies, idA );
b3Body* bodyB = b3Array_Get( world->bodies, idB );
// Remove from body A
if ( edgeA->prevKey != B3_NULL_INDEX )
{
b3Joint* prevJoint = b3Array_Get( world->joints, edgeA->prevKey >> 1 );
b3Joint* prevJoint = b3Array_Get( world->joints, edgeA->prevKey >> 1 );
b3JointEdge* prevEdge = prevJoint->edges + ( edgeA->prevKey & 1 );
prevEdge->nextKey = edgeA->nextKey;
}
if ( edgeA->nextKey != B3_NULL_INDEX )
{
b3Joint* nextJoint = b3Array_Get( world->joints, edgeA->nextKey >> 1 );
b3Joint* nextJoint = b3Array_Get( world->joints, edgeA->nextKey >> 1 );
b3JointEdge* nextEdge = nextJoint->edges + ( edgeA->nextKey & 1 );
nextEdge->prevKey = edgeA->prevKey;
}
@ -759,14 +759,14 @@ void b3DestroyJointInternal( b3World* world, b3Joint* joint, bool wakeBodies )
// Remove from body B
if ( edgeB->prevKey != B3_NULL_INDEX )
{
b3Joint* prevJoint = b3Array_Get( world->joints, edgeB->prevKey >> 1 );
b3Joint* prevJoint = b3Array_Get( world->joints, edgeB->prevKey >> 1 );
b3JointEdge* prevEdge = prevJoint->edges + ( edgeB->prevKey & 1 );
prevEdge->nextKey = edgeB->nextKey;
}
if ( edgeB->nextKey != B3_NULL_INDEX )
{
b3Joint* nextJoint = b3Array_Get( world->joints, edgeB->nextKey >> 1 );
b3Joint* nextJoint = b3Array_Get( world->joints, edgeB->nextKey >> 1 );
b3JointEdge* nextEdge = nextJoint->edges + ( edgeB->nextKey & 1 );
nextEdge->prevKey = edgeB->prevKey;
}
@ -799,14 +799,14 @@ void b3DestroyJointInternal( b3World* world, b3Joint* joint, bool wakeBodies )
}
else
{
b3SolverSet* set = b3Array_Get( world->solverSets, setIndex );
int movedIndex = b3Array_RemoveSwap( set->jointSims, localIndex );
b3SolverSet* set = b3Array_Get( world->solverSets, setIndex );
int movedIndex = b3Array_RemoveSwap( set->jointSims, localIndex );
if ( movedIndex != B3_NULL_INDEX )
{
// Fix moved joint
b3JointSim* movedJointSim = set->jointSims.data + localIndex;
int movedId = movedJointSim->jointId;
b3Joint* movedJoint = b3Array_Get( world->joints, movedId );
b3Joint* movedJoint = b3Array_Get( world->joints, movedId );
B3_ASSERT( movedJoint->localIndex == movedIndex );
movedJoint->localIndex = localIndex;
}
@ -926,8 +926,8 @@ void b3Joint_SetCollideConnected( b3JointId jointId, bool shouldCollide )
joint->collideConnected = shouldCollide;
b3Body* bodyA = b3Array_Get( world->bodies, joint->edges[0].bodyId );
b3Body* bodyB = b3Array_Get( world->bodies, joint->edges[1].bodyId );
b3Body* bodyA = b3Array_Get( world->bodies, joint->edges[0].bodyId );
b3Body* bodyB = b3Array_Get( world->bodies, joint->edges[1].bodyId );
if ( shouldCollide )
{
@ -939,7 +939,7 @@ void b3Joint_SetCollideConnected( b3JointId jointId, bool shouldCollide )
int shapeId = shapeCountA < shapeCountB ? bodyA->headShapeId : bodyB->headShapeId;
while ( shapeId != B3_NULL_INDEX )
{
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
if ( shape->proxyKey != B3_NULL_INDEX )
{
@ -989,8 +989,8 @@ void b3Joint_WakeBodies( b3JointId jointId )
world->locked = true;
b3Joint* joint = b3GetJointFullId( world, jointId );
b3Body* bodyA = b3Array_Get( world->bodies, joint->edges[0].bodyId );
b3Body* bodyB = b3Array_Get( world->bodies, joint->edges[1].bodyId );
b3Body* bodyA = b3Array_Get( world->bodies, joint->edges[0].bodyId );
b3Body* bodyB = b3Array_Get( world->bodies, joint->edges[1].bodyId );
b3WakeBody( world, bodyA );
b3WakeBody( world, bodyB );
@ -998,6 +998,15 @@ void b3Joint_WakeBodies( b3JointId jointId )
world->locked = false;
}
bool b3Joint_IsAwake( b3JointId jointId )
{
b3World* world = b3GetWorld( jointId.world0 );
b3Joint* joint = b3GetJointFullId( world, jointId );
// Cheaper than checking if the bodies are awake.
return joint->setIndex == b3_awakeSet;
}
void b3GetJointReaction( b3World* world, b3JointSim* sim, float invTimeStep, float* force, float* torque )
{
float linearImpulse = 0.0f;
@ -1651,8 +1660,8 @@ void b3SolveJoints_Overflow( b3StepContext* context, bool useBias )
void b3DrawJoint( b3DebugDraw* draw, b3World* world, b3Joint* joint )
{
b3Body* bodyA = b3Array_Get( world->bodies, joint->edges[0].bodyId );
b3Body* bodyB = b3Array_Get( world->bodies, joint->edges[1].bodyId );
b3Body* bodyA = b3Array_Get( world->bodies, joint->edges[0].bodyId );
b3Body* bodyB = b3Array_Get( world->bodies, joint->edges[1].bodyId );
if ( bodyA->setIndex == b3_disabledSet || bodyB->setIndex == b3_disabledSet )
{
return;

View file

@ -244,12 +244,12 @@ static bool b3IsConsistent( const b3MeshData* mesh )
const b3MeshNode* child2 = b3GetRightChild( node );
b3AABB bounds2 = b3GetNodeAABB( child2 );
if ( !b3AABB_Contains( nodeBounds, bounds1 ) )
if ( b3AABB_Contains( nodeBounds, bounds1 ) == false )
{
return false;
}
if ( !b3AABB_Contains( nodeBounds, bounds2 ) )
if ( b3AABB_Contains( nodeBounds, bounds2 ) == false )
{
return false;
}
@ -329,6 +329,11 @@ bool b3IsValidMesh( const b3MeshData* meshData )
#endif
static inline b3Vec3 b3GetStridedVertex( const b3Vec3* vertices, int index, size_t stride )
{
return *(const b3Vec3*)( (const uint8_t*)vertices + index * stride );
}
// Node for a vertex linked list
typedef struct b3VertexNode
{
@ -350,15 +355,17 @@ typedef struct b3SpatialHash
b3Array( b3VertexNode ) nodes;
const b3Vec3* vertices;
int vertexCount;
size_t stride;
b3VertexMap vertexMap;
float cellSize;
float tolerance;
} b3SpatialHash;
static void b3SpatialHash_Create( b3SpatialHash* h, const b3Vec3* vertices, int vertexCount, float tolerance )
static void b3CreateSpatialHash( b3SpatialHash* h, const b3Vec3* vertices, int vertexCount, size_t stride, float tolerance )
{
h->vertices = vertices;
h->vertexCount = vertexCount;
h->stride = stride;
h->tolerance = tolerance;
h->cellSize = 2.0f * tolerance;
b3Array_CreateN( h->nodes, vertexCount );
@ -369,7 +376,7 @@ static void b3SpatialHash_Create( b3SpatialHash* h, const b3Vec3* vertices, int
B3_ASSERT( h->cellSize > 0.0f );
}
static void b3SpatialHash_Destroy( b3SpatialHash* h )
static void b3DestroySpatialHash( b3SpatialHash* h )
{
b3VertexMap_cleanup( &h->vertexMap );
b3Array_Destroy( h->nodes );
@ -380,7 +387,8 @@ static void b3SpatialHash_Destroy( b3SpatialHash* h )
static int32_t b3SpatialHash_FindDuplicate( b3SpatialHash* h, int32_t currentIndex )
{
B3_ASSERT( currentIndex < h->vertexCount );
b3Vec3 vertex = h->vertices[currentIndex];
size_t stride = h->stride;
b3Vec3 vertex = b3GetStridedVertex( h->vertices, currentIndex, stride );
float cellSize = h->cellSize;
float tolerance = h->tolerance;
@ -420,7 +428,7 @@ static int32_t b3SpatialHash_FindDuplicate( b3SpatialHash* h, int32_t currentInd
B3_ASSERT( existingIndex < currentIndex );
B3_ASSERT( existingIndex < h->vertexCount );
b3Vec3 other = h->vertices[existingIndex];
b3Vec3 other = b3GetStridedVertex( h->vertices, existingIndex, stride );
// IsEqual inlined: check if vertices are within tolerance
if ( fabsf( vertex.x - other.x ) <= tolerance && fabsf( vertex.y - other.y ) <= tolerance &&
@ -481,16 +489,18 @@ typedef struct b3WeldData
int vertexCount;
int indexCount;
size_t stride;
} b3WeldData;
static int b3WeldVertices( b3WeldData* data, float tolerance )
{
int vertexCount = data->vertexCount;
int uniqueCount = 0;
size_t stride = data->stride;
// Create spatial hash and find duplicates
b3SpatialHash spatialHash;
b3SpatialHash_Create( &spatialHash, data->srcVertices, vertexCount, tolerance );
b3CreateSpatialHash( &spatialHash, data->srcVertices, vertexCount, stride, tolerance );
b3Array( int ) vertexMapping = { 0 };
b3Array_Resize( vertexMapping, vertexCount );
@ -502,7 +512,7 @@ static int b3WeldVertices( b3WeldData* data, float tolerance )
{
// New unique vertex
vertexMapping.data[i] = uniqueCount;
data->dstVertices[uniqueCount] = data->srcVertices[i];
data->dstVertices[uniqueCount] = b3GetStridedVertex( data->srcVertices, i, stride );
uniqueCount += 1;
}
else
@ -517,11 +527,11 @@ static int b3WeldVertices( b3WeldData* data, float tolerance )
for ( int i = 0; i < indexCount; ++i )
{
int srcIndex = data->srcIndices[i];
B3_ASSERT( srcIndex < vertexCount );
B3_ASSERT( 0 <= srcIndex && srcIndex < vertexCount );
data->dstIndices[i] = vertexMapping.data[srcIndex];
}
b3SpatialHash_Destroy( &spatialHash );
b3DestroySpatialHash( &spatialHash );
b3Array_Destroy( vertexMapping );
return uniqueCount;
@ -1555,9 +1565,36 @@ b3MeshData* b3CreatePlatformMesh( b3Vec3 center, float height, float topWidth, f
return b3CreateMesh( &def, NULL, 0 );
}
static void b3CopyVerticesWithStride( b3Vec3* dst, const b3Vec3* src, int count, size_t stride )
{
if ( stride == sizeof( b3Vec3 ) )
{
memcpy( dst, src, count * sizeof( b3Vec3 ) );
return;
}
for ( int i = 0; i < count; ++i )
{
dst[i] = *(const b3Vec3*)( (const uint8_t*)src + i * stride );
}
}
// Stride larger than this likely indicates stride is uninitialized memory.
#define B3_MAX_STRIDE 4096
// todo this should fail if the mesh has a height greater than B3_MESH_STACK_SIZE
b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices, int degenerateCapacity )
{
if ( def->stride != 0 && ( def->stride < sizeof( b3Vec3 ) || B3_MAX_STRIDE < def->stride ) )
{
return NULL;
}
if ( ( def->stride & 3 ) != 0 )
{
return NULL;
}
if ( def->vertexCount < 3 || def->vertices == NULL || def->triangleCount <= 0 || def->indices == NULL )
{
return NULL;
@ -1570,6 +1607,7 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
}
int vertexCount = def->vertexCount;
size_t stride = def->stride == 0 ? sizeof( b3Vec3 ) : def->stride;
b3AABB meshBounds = B3_BOUNDS3_EMPTY;
@ -1584,6 +1622,7 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
{
b3Array_Resize( vertices, vertexCount );
b3Array_Resize( indices, 3 * triangleCount );
b3WeldData data = {
.srcVertices = def->vertices,
.srcIndices = def->indices,
@ -1591,14 +1630,17 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
.dstIndices = indices.data,
.vertexCount = vertexCount,
.indexCount = 3 * triangleCount,
.stride = stride,
};
vertices.count = b3WeldVertices( &data, def->weldTolerance );
vertexCount = vertices.count;
B3_ASSERT( vertexCount <= def->vertexCount );
}
else
{
b3Array_Append( vertices, def->vertices, vertexCount );
vertices.count = vertexCount;
b3CopyVerticesWithStride( vertices.data, def->vertices, vertexCount, stride );
b3Array_Append( indices, def->indices, 3 * triangleCount );
}
@ -1608,6 +1650,7 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
float minArea = 0.01f * B3_LINEAR_SLOP * B3_LINEAR_SLOP;
float surfaceArea = 0.0f;
int materialCount = 1;
bool clockWise = def->clockWiseWinding;
for ( int index = 0; index < triangleCount; ++index )
{
@ -1615,6 +1658,10 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
int index2 = indices.data[3 * index + 1];
int index3 = indices.data[3 * index + 2];
B3_ASSERT( 0 <= index1 && index1 < vertexCount );
B3_ASSERT( 0 <= index2 && index2 < vertexCount );
B3_ASSERT( 0 <= index3 && index3 < vertexCount );
b3Vec3 vertex1 = vertices.data[index1];
b3Vec3 vertex2 = vertices.data[index2];
b3Vec3 vertex3 = vertices.data[index3];
@ -1628,11 +1675,12 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
if ( index1 != index2 && index1 != index3 && index2 != index3 )
{
degenerateCount += 1;
if ( degenerateTriangleIndices != NULL && degenerateCount < degenerateCapacity )
{
degenerateTriangleIndices[degenerateCount - 1] = index;
degenerateTriangleIndices[degenerateCount] = index;
}
degenerateCount += 1;
}
continue;
@ -1641,8 +1689,8 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
surfaceArea += area;
b3AABB box = {
b3Min( vertex1, b3Min( vertex2, vertex3 ) ),
b3Max( vertex1, b3Max( vertex2, vertex3 ) ),
.lowerBound = b3Min( vertex1, b3Min( vertex2, vertex3 ) ),
.upperBound = b3Max( vertex1, b3Max( vertex2, vertex3 ) ),
};
b3Vec3 center = b3AABB_Center( box );
@ -1668,6 +1716,8 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
if ( b3IsSaneAABB( meshBounds ) == false )
{
b3Array_Destroy( primitives );
b3Array_Destroy( indices );
b3Array_Destroy( vertices );
return NULL;
}
@ -1724,9 +1774,18 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
for ( int index = 0; index < triangleCount; ++index )
{
b3Primitive primitive = primitives.data[index];
triangles[index].index1 = indices.data[3 * primitive.triangleIndex + 0];
triangles[index].index2 = indices.data[3 * primitive.triangleIndex + 1];
triangles[index].index3 = indices.data[3 * primitive.triangleIndex + 2];
int i1 = 3 * primitive.triangleIndex + 0;
int i2 = 3 * primitive.triangleIndex + 1;
int i3 = 3 * primitive.triangleIndex + 2;
if ( clockWise )
{
B3_SWAP( i2, i3 );
}
triangles[index].index1 = indices.data[i1];
triangles[index].index2 = indices.data[i2];
triangles[index].index3 = indices.data[i3];
flags[index] = 0;
// Copy material indices if they exist. Otherwise the material indices are all zeroes.
@ -1745,6 +1804,9 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
{
b3Array_Destroy( tempNodes );
b3Array_Destroy( primitives );
b3Array_Destroy( indices );
b3Array_Destroy( vertices );
b3Free( mesh, byteCount );
return NULL;
}
@ -1762,7 +1824,7 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
b3Array_Destroy( vertices );
mesh->hash = 0;
mesh->hash = b3Hash64NonZero((uint8_t*)mesh, mesh->byteCount );
mesh->hash = b3Hash64NonZero( (uint8_t*)mesh, mesh->byteCount );
return mesh;
}
@ -1896,7 +1958,7 @@ b3CastOutput b3RayCastMesh( const b3Mesh* mesh, const b3RayCastInput* input )
b3V32 scale = b3LoadV( &meshScale.x );
b3V32 invScale = b3DivV( b3_oneV, scale );
bool clockwise = meshScale.x * meshScale.y * meshScale.z < 0.0f;
bool ccw = meshScale.x * meshScale.y * meshScale.z > 0.0f;
// Use the inverse scaled ray for traversal of the BVH
b3V32 invScaledRayStart = b3MulV( invScale, rayStart );
@ -1936,16 +1998,16 @@ b3CastOutput b3RayCastMesh( const b3Mesh* mesh, const b3RayCastInput* input )
b3Vec3 vertex2, vertex3;
// The CPU should predict this branch
if ( clockwise )
{
vertex2 = b3Mul( meshScale, vertices[triangle.index3] );
vertex3 = b3Mul( meshScale, vertices[triangle.index2] );
}
else
if ( ccw )
{
vertex2 = b3Mul( meshScale, vertices[triangle.index2] );
vertex3 = b3Mul( meshScale, vertices[triangle.index3] );
}
else
{
vertex2 = b3Mul( meshScale, vertices[triangle.index3] );
vertex3 = b3Mul( meshScale, vertices[triangle.index2] );
}
// Collide ray with triangle in scaled space
b3V32 v1 = b3LoadV( &vertex1.x );
@ -2030,7 +2092,7 @@ b3CastOutput b3ShapeCastMesh( const b3Mesh* mesh, const b3ShapeCastInput* input
b3V32 scale = b3LoadV( &meshScale.x );
b3V32 invScale = b3DivV( b3_oneV, scale );
b3V32 absInvScale = b3AbsV( invScale );
bool clockwise = meshScale.x * meshScale.y * meshScale.z < 0.0f;
bool ccw = meshScale.x * meshScale.y * meshScale.z > 0.0f;
// Use the inverse scaled shape cast for traversal of the BVH
b3V32 invScaledRayStart = b3MulV( invScale, rayStart );
@ -2067,21 +2129,21 @@ b3CastOutput b3ShapeCastMesh( const b3Mesh* mesh, const b3ShapeCastInput* input
int triangleIndex = triangleOffset + index;
b3MeshTriangle triangle = triangles[triangleIndex];
// Collide ray with triangle in scaled space
// Collide shape with triangle in scaled space
b3Vec3 vertex1 = b3Mul( meshScale, vertices[triangle.index1] );
b3Vec3 vertex2, vertex3;
// The CPU should predict this branch
if ( clockwise )
{
vertex2 = b3Mul( meshScale, vertices[triangle.index3] );
vertex3 = b3Mul( meshScale, vertices[triangle.index2] );
}
else
if ( ccw )
{
vertex2 = b3Mul( meshScale, vertices[triangle.index2] );
vertex3 = b3Mul( meshScale, vertices[triangle.index3] );
}
else
{
vertex2 = b3Mul( meshScale, vertices[triangle.index3] );
vertex3 = b3Mul( meshScale, vertices[triangle.index2] );
}
b3V32 v1 = b3LoadV( &vertex1.x );
b3V32 v2 = b3LoadV( &vertex2.x );
@ -2090,43 +2152,54 @@ b3CastOutput b3ShapeCastMesh( const b3Mesh* mesh, const b3ShapeCastInput* input
b3V32 triangleMin = b3SubV( b3MinV( v1, b3MinV( v2, v3 ) ), shapeExtent );
b3V32 triangleMax = b3AddV( b3MaxV( v1, b3MaxV( v2, v3 ) ), shapeExtent );
// Test triangle-ray overlap in scaled space
if ( b3TestBoundsOverlap( triangleMin, triangleMax, rayMin, rayMax ) )
// Test extended triangle vs ray bounds overlap in scaled space. Skip edge tests.
bool overlap = b3TestBoundsOverlap( triangleMin, triangleMax, rayMin, rayMax );
if (overlap == false)
{
// Collide shape with triangle in scaled space
b3Vec3 origin = vertex1;
b3Vec3 triangleVertices[] = { b3Vec3_zero, b3Sub( vertex2, origin ), b3Sub( vertex3, origin ) };
b3Transform shiftedOrigin = { b3Neg( origin ), b3Quat_identity };
continue;
}
b3ShapeCastPairInput pairInput;
pairInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f };
pairInput.proxyB = input->proxy;
pairInput.transform = shiftedOrigin;
pairInput.maxFraction = bestOutput.fraction;
pairInput.translationB = input->translation;
pairInput.canEncroach = input->canEncroach;
// This test is in scaled space. vertices and center are scaled.
float signedVolume = b3SignedVolume( vertex1, vertex2, vertex3, center );
if ( signedVolume < 0.0f )
{
// Backside
continue;
}
b3CastOutput pairOutput = b3ShapeCast( &pairInput );
// Collide shape with triangle in scaled space.
b3Vec3 origin = vertex1;
b3Vec3 triangleVertices[] = { b3Vec3_zero, b3Sub( vertex2, origin ), b3Sub( vertex3, origin ) };
b3Transform shiftedOrigin = { b3Neg( origin ), b3Quat_identity };
if ( pairOutput.hit )
{
pairOutput.point = b3Add( pairOutput.point, origin );
b3ShapeCastPairInput pairInput;
pairInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f };
pairInput.proxyB = input->proxy;
pairInput.transform = shiftedOrigin;
pairInput.maxFraction = bestOutput.fraction;
pairInput.translationB = input->translation;
pairInput.canEncroach = input->canEncroach;
bestOutput = pairOutput;
bestOutput.triangleIndex = triangleIndex;
bestOutput.materialIndex = materialIndices[triangleIndex];
b3CastOutput pairOutput = b3ShapeCast( &pairInput );
// Update ray bounds in scaled space
lambda = b3SplatV( pairOutput.fraction );
rayEnd = b3AddV( rayStart, b3MulV( lambda, rayDelta ) );
rayMin = b3MinV( rayStart, rayEnd );
rayMax = b3MaxV( rayStart, rayEnd );
if ( pairOutput.hit )
{
pairOutput.point = b3Add( pairOutput.point, origin );
// Ray bounds in unscaled space
invScaledRayEnd = b3AddV( invScaledRayStart, b3MulV( lambda, invScaledRayDelta ) );
invScaledRayMin = b3MinV( invScaledRayStart, invScaledRayEnd );
invScaledRayMax = b3MaxV( invScaledRayStart, invScaledRayEnd );
}
bestOutput = pairOutput;
bestOutput.triangleIndex = triangleIndex;
bestOutput.materialIndex = materialIndices[triangleIndex];
// Update ray bounds in scaled space
lambda = b3SplatV( pairOutput.fraction );
rayEnd = b3AddV( rayStart, b3MulV( lambda, rayDelta ) );
rayMin = b3MinV( rayStart, rayEnd );
rayMax = b3MaxV( rayStart, rayEnd );
// Ray bounds in unscaled space
invScaledRayEnd = b3AddV( invScaledRayStart, b3MulV( lambda, invScaledRayDelta ) );
invScaledRayMin = b3MinV( invScaledRayStart, invScaledRayEnd );
invScaledRayMax = b3MaxV( invScaledRayStart, invScaledRayEnd );
}
}
}
@ -2219,7 +2292,7 @@ int b3CollideMoverAndMesh( b3PlaneResult* planes, int capacity, const b3Mesh* sh
b3SimplexCache cache = { 0 };
float radius = mover->radius;
b3Vec3 center = b3Lerp( mover->center1, mover->center2, 0.5f );
b3V32 center1 = b3LoadV( &mover->center1.x );
b3V32 center2 = b3LoadV( &mover->center2.x );
b3V32 r = b3SplatV( radius );
@ -2228,6 +2301,7 @@ int b3CollideMoverAndMesh( b3PlaneResult* planes, int capacity, const b3Mesh* sh
// Scale may have reflection so min/max may become invalid when unscaled
b3Vec3 meshScale = shape->scale;
bool ccw = meshScale.x * meshScale.y * meshScale.z > 0.0f;
b3V32 scale = b3LoadV( &meshScale.x );
b3V32 invScale = b3DivV( b3_oneV, scale );
b3V32 temp1 = b3MulV( invScale, boundsMin );
@ -2242,6 +2316,7 @@ int b3CollideMoverAndMesh( b3PlaneResult* planes, int capacity, const b3Mesh* sh
const b3MeshNode* node = b3GetRoot( shape->data );
const b3MeshTriangle* triangles = b3GetMeshTriangles( shape->data );
const b3Vec3* vertices = b3GetMeshVertices( shape->data );
const uint8_t* materialIndices = b3GetMeshMaterialIndices( shape->data );
int planeCount = 0;
while ( planeCount < capacity )
@ -2264,6 +2339,12 @@ int b3CollideMoverAndMesh( b3PlaneResult* planes, int capacity, const b3Mesh* sh
b3Vec3 vertex1 = vertices[triangle.index1];
b3Vec3 vertex2 = vertices[triangle.index2];
b3Vec3 vertex3 = vertices[triangle.index3];
if ( ccw == false )
{
B3_SWAP( vertex2, vertex3 );
}
b3V32 v1 = b3LoadV( &vertex1.x );
b3V32 v2 = b3LoadV( &vertex2.x );
b3V32 v3 = b3LoadV( &vertex3.x );
@ -2271,10 +2352,19 @@ int b3CollideMoverAndMesh( b3PlaneResult* planes, int capacity, const b3Mesh* sh
// Test triangle bounds overlap in unscaled space
if ( b3TestBoundsTriangleOverlap( invScaledBoundsCenter, invScaledBoundsExtent, v1, v2, v3 ) )
{
// Compute shape distance in scaled space. Winding order doesn't matter.
// todo implement one-sided collision?
// Compute shape distance in scaled space.
b3Vec3 triangleVertices[] = { b3Mul( meshScale, vertex1 ), b3Mul( meshScale, vertex2 ),
b3Mul( meshScale, vertex3 ) };
// Vertices and center are in scaled space.
float signedVolume =
b3SignedVolume( triangleVertices[0], triangleVertices[1], triangleVertices[2], center );
if ( signedVolume < 0.0f )
{
// Backside
continue;
}
distanceInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f };
// reset the cache
@ -2285,12 +2375,13 @@ int b3CollideMoverAndMesh( b3PlaneResult* planes, int capacity, const b3Mesh* sh
if ( distanceOutput.distance == 0.0f )
{
// todo SAT
// deep overlap
}
else if ( distanceOutput.distance <= mover->radius )
{
b3Plane plane = { distanceOutput.normal, mover->radius - distanceOutput.distance };
planes[planeCount] = (b3PlaneResult){ plane, distanceOutput.pointA };
planes[planeCount] =
(b3PlaneResult){ plane, distanceOutput.pointA, triangleIndex, 0, materialIndices[triangleIndex] };
planeCount += 1;
if ( planeCount == capacity )
@ -2325,7 +2416,7 @@ int b3CollideMoverAndMesh( b3PlaneResult* planes, int capacity, const b3Mesh* sh
void b3QueryMesh( const b3Mesh* mesh, b3AABB bounds, b3MeshQueryFcn* fcn, void* context )
{
b3Vec3 meshScale = mesh->scale;
bool clockwise = meshScale.x * meshScale.y * meshScale.z > 0.0f;
bool ccw = meshScale.x * meshScale.y * meshScale.z > 0.0f;
// Scale may have reflection so min/max may become invalid when unscaled
b3V32 scale = b3LoadV( &meshScale.x );
@ -2370,13 +2461,13 @@ void b3QueryMesh( const b3Mesh* mesh, b3AABB bounds, b3MeshQueryFcn* fcn, void*
b3V32 v2 = b3LoadV( &vertex2.x );
b3V32 v3 = b3LoadV( &vertex3.x );
// Perform triangle overlap test in unscaled space. Winding order doesn't matter.
// Perform triangle overlap test in unscaled space.
// todo it is possible that some margins are getting scaled
if ( b3TestBoundsTriangleOverlap( invScaledBoundsCenter, invScaledBoundsExtent, v1, v2, v3 ) )
{
b3Vec3 a = b3Mul( meshScale, vertex1 );
b3Vec3 b, c;
if ( clockwise )
if ( ccw )
{
b = b3Mul( meshScale, vertex2 );
c = b3Mul( meshScale, vertex3 );

View file

@ -11,8 +11,6 @@
#include <stdio.h>
// This guards against excessive memory usage and complex collision
#define B3_MAX_MESH_CONTACT_TRIANGLES 256
#define B3_MAX_POINTS_PER_TRIANGLE 32
#if B3_ENABLE_VALIDATION

View file

@ -609,9 +609,7 @@ static void b3CollideTask( int startIndex, int endIndex, int workerIndex, void*
continue;
}
// Update contact respecting shape/body order (A,B). Bodies behind awake-set
// contacts are always either awake or static - inline b3GetBodySim with that
// invariant to skip the cross-TU call and per-call solverSets indirection.
// Update contact respecting shape/body order (A,B)
b3Body* bodyA = bodies + shapeA->bodyId;
b3Body* bodyB = bodies + shapeB->bodyId;
bool isStaticA = bodyA->type == b3_staticBody;
@ -2811,7 +2809,6 @@ void b3World_CollideMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mov
b3Vec3 r = { mover->radius, mover->radius, mover->radius };
// Relative box lifted to world float with outward rounding, conservative for the tree
b3AABB relBox;
relBox.lowerBound = b3Sub( b3Min( mover->center1, mover->center2 ), r );
relBox.upperBound = b3Add( b3Max( mover->center1, mover->center2 ), r );
@ -2828,7 +2825,6 @@ void b3World_CollideMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mov
if ( world->recording != NULL )
{
// CollideMover returns void: no treestats tail, just the per-shape plane batches.
b3RecPatchU32( &recWriter.buf, recWriter.countOffset, recWriter.hitCount );
b3RecQueryCommit( world->recording, b3_recOpQueryCollideMover, &recWriter );
}

View file

@ -217,6 +217,9 @@ void b3RecW_PLANERESULT( b3RecBuffer* buf, b3PlaneResult v )
b3RecW_VEC3( buf, v.plane.normal );
b3RecW_F32( buf, v.plane.offset );
b3RecW_VEC3( buf, v.point );
b3RecW_I32( buf, v.triangleIndex );
b3RecW_I32( buf, v.childIndex );
b3RecW_I32( buf, v.materialIndex );
}
void b3RecW_WORLDID( b3RecBuffer* buf, b3WorldId v )

View file

@ -47,8 +47,8 @@ typedef struct b3World b3World;
#define B3_REC_MAGIC 0x43523342u
// Major recording version is bumped when writers change.
// Major version 4 added b3ShapeDef::enableSpeculativeContact
#define B3_REC_VERSION_MAJOR 4
// Major version 5 added b3PlaneResult fields.
#define B3_REC_VERSION_MAJOR 5
// Minor tracks op-stream additions that keep the 48 byte header shape.
// Minor version 4 added b3Shape_SetMeshMaterial, b3Shape_SetHull, b3Shape_SetMesh

View file

@ -288,6 +288,9 @@ b3PlaneResult b3RecR_PLANERESULT( b3RecReader* rdr )
v.plane.normal = b3RecR_VEC3( rdr );
v.plane.offset = b3RecR_F32( rdr );
v.point = b3RecR_VEC3( rdr );
v.triangleIndex = b3RecR_I32( rdr );
v.childIndex = b3RecR_I32( rdr );
v.materialIndex = b3RecR_I32( rdr );
return v;
}
@ -1801,7 +1804,8 @@ static bool b3RecReplayPlaneTrampoline( b3ShapeId id, const b3PlaneResult* plane
const b3RecRecordedHit* h = &rc->hits[rc->cursor + i];
if ( b3RecVec3Differs( h->plane.plane.normal, planes[i].plane.normal ) ||
b3RecF32Differs( h->plane.plane.offset, planes[i].plane.offset ) ||
b3RecVec3Differs( h->plane.point, planes[i].point ) )
b3RecVec3Differs( h->plane.point, planes[i].point ) || h->plane.triangleIndex != planes[i].triangleIndex ||
h->plane.childIndex != planes[i].childIndex || h->plane.materialIndex != planes[i].materialIndex )
{
rc->rdr->diverged = true;
}

View file

@ -778,7 +778,7 @@ b3ShapeExtent b3ComputeShapeExtent( const b3Shape* shape, b3Vec3 localCenter )
b3Vec3 c1 = b3Sub( shape->capsule.center1, localCenter );
b3Vec3 c2 = b3Sub( shape->capsule.center2, localCenter );
b3Vec3 r = { radius, radius, radius };
extent.maxExtent = b3Add( b3Max( c1, c2 ), r );
extent.maxExtent = b3Add( b3Max( b3Abs( c1 ), b3Abs( c2 ) ), r );
}
break;
@ -798,9 +798,9 @@ b3ShapeExtent b3ComputeShapeExtent( const b3Shape* shape, b3Vec3 localCenter )
{
float radius = shape->sphere.radius;
extent.minExtent = radius;
b3Vec3 h = b3Abs( b3Sub( shape->sphere.center, localCenter ) );
b3Vec3 r = { radius, radius, radius };
b3Vec3 p = b3Add( b3Sub( shape->sphere.center, localCenter ), r );
extent.maxExtent = b3Abs( b3Sub( p, localCenter ) );
extent.maxExtent = b3Add( h, r );
}
break;
@ -816,7 +816,7 @@ b3ShapeExtent b3ComputeShapeExtent( const b3Shape* shape, b3Vec3 localCenter )
float r2 = b3Length( b3Sub( aabb.upperBound, localCenter ) );
extent.minExtent = b3MinFloat( r1, r2 );
b3Vec3 p = b3FarthestPointOnAABB( aabb, localCenter );
extent.maxExtent = b3Abs( p );
extent.maxExtent = b3Abs( b3Sub( p, localCenter ) );
}
break;
@ -939,32 +939,6 @@ bool b3OverlapShape( const b3Shape* shape, b3Transform transform, const b3ShapeP
B3_ASSERT( false );
return false;
}
#if 0
b3Vec3 localPoints[B3_MAX_SHAPE_CAST_POINTS];
b3ShapeProxy localProxy;
b3Transform invTransform = b3InvertTransform( transform );
b3Matrix3 R = b3MakeMatrixFromQuat( invTransform.q );
localProxy.count = b3MinInt( proxy->count, B3_MAX_SHAPE_CAST_POINTS );
for ( int i = 0; i < localProxy.count; ++i )
{
localPoints[i] = b3Add( b3MulMV( R, proxy->points[i] ), invTransform.p );
}
localProxy.points = localPoints;
localProxy.radius = proxy->radius;
if ( type == b3_meshShape )
{
return b3OverlapMesh( &localProxy, shape->mesh.data, shape->mesh.scale );
}
B3_ASSERT( type == b3_heightShape );
return b3OverlapHeightField( &localProxy, shape->heightField );
#endif
}
int b3CollideMover( b3PlaneResult* planes, int planeCapacity, const b3Shape* shape, b3Transform transform,
@ -1016,6 +990,7 @@ int b3CollideMover( b3PlaneResult* planes, int planeCapacity, const b3Shape* sha
{
planes[i].plane.normal = b3RotateVector( transform.q, planes[i].plane.normal );
planes[i].point = b3TransformPoint( transform, planes[i].point );
planes[i].materialIndex = b3ClampInt( planes[i].materialIndex, 0, shape->materialCount - 1 );
}
return planeCount;

View file

@ -242,6 +242,6 @@ int b3CollideMoverAndSphere( b3PlaneResult* result, const b3Sphere* shape, const
}
b3Plane plane = { normal, totalRadius - distance };
*result = ( b3PlaneResult ){ plane, shape->center };
*result = (b3PlaneResult){ plane, shape->center, 0, 0, 0 };
return 1;
}

View file

@ -478,6 +478,7 @@ void b3SolveSphericalJoint( b3JointSim* base, b3StepContext* context, bool useBi
{
b3Vec3 cdot = b3Sub( wB, wA );
// todo it might be more accurate to have the motor velocity in frameA due to sub-stepping.
b3Vec3 lambda = b3Neg( b3MulMV( joint->rotationMass, b3Sub( cdot, joint->motorVelocity ) ) );
b3Vec3 newImpulse = b3Add( joint->motorImpulse, lambda );
float length = b3Length( newImpulse );