From 8948da4715bf79cc13a82534874c2833312b8c0e Mon Sep 17 00:00:00 2001 From: Erin Catto Date: Sat, 7 Nov 2026 11:47:38 -0800 Subject: [PATCH] compressed vertex neighbors --- .editorconfig | 2 +- include/box3d/types.h | 23 +- src/height_field.c | 1 - src/mesh.c | 499 ++++++++++++++++++++++++++++++++++++---- src/mesh_contact.c | 203 +++++++--------- src/shape.h | 2 +- test/test_determinism.c | 4 +- test/test_mesh.c | 167 ++++++++++++++ 8 files changed, 716 insertions(+), 185 deletions(-) diff --git a/.editorconfig b/.editorconfig index 2f3b107..a07077e 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,5 +1,5 @@ root = true [*.{c,h,cpp,inl}] -guidelines = 100 +guidelines = 120 guidelines_style = 1px dotted gray diff --git a/include/box3d/types.h b/include/box3d/types.h index f458dad..08959d9 100644 --- a/include/box3d/types.h +++ b/include/box3d/types.h @@ -2259,7 +2259,7 @@ typedef struct b3MeshDef } b3MeshDef; /// 64-bit mesh version. Useful for validating serialized data. -#define B3_MESH_VERSION 0x7C41E9B2D3058F6Aull +#define B3_MESH_VERSION 0x2E94C7A1F05B3D68ull /// Triangle mesh edge flags. typedef enum b3MeshEdgeFlags @@ -2336,7 +2336,8 @@ typedef struct b3MeshNode uint32_t triangleOffset; } b3MeshNode; -/// This is a sorted triangle collision bounding volume hierarchy. +/// This is a sorted triangle collision bounding volume hierarchy. Offsets are a byte +/// count offset from the struct address. /// @note This struct has data hanging off the end and cannot be directly copied. typedef struct b3MeshData { @@ -2361,41 +2362,41 @@ typedef struct b3MeshData /// The number of degenerate triangles. Diagnostic. int32_t degenerateCount; - /// Offset of the node array in bytes from the struct address. + /// Offset of the node array. int32_t nodeOffset; /// The number of BVH nodes. int32_t nodeCount; - /// Offset of the vertex array in bytes from the struct address. + /// Offset of the vertex array. int32_t vertexOffset; /// The number of vertices. int32_t vertexCount; - /// Offset of the triangle array in bytes from the struct address. + /// Offset of the triangle array. int32_t triangleOffset; /// The number of triangles. int32_t triangleCount; - /// Offset of the material array in bytes from the struct address. + /// Offset of the material array. int32_t materialOffset; /// The number of materials. int32_t materialCount; - /// Offset of the triangle flag array in bytes from the struct address. + /// Offset of the triangle flag array. int32_t flagsOffset; - // Offset to the array of neighbor quantized normal offsets. + // Offset to the edge neighbor angles. int32_t edgeAngleOffset; - /// Offset of the vertex flag array in bytes from the struct address. + /// Offset of the vertex flag array. int32_t vertexFlagOffset; - // todo comment - int32_t vertexTriangleOffset; + /// Offset the vertex neighbor angle ring. + int32_t vertexRingOffset; } b3MeshData; /// This allows mesh data to be re-used with different scales. diff --git a/src/height_field.c b/src/height_field.c index bfdcaba..12e8fdd 100644 --- a/src/height_field.c +++ b/src/height_field.c @@ -794,7 +794,6 @@ int b3GetHeightFieldVertexTriangles( const b3HeightFieldData* heightField, int v int row = vertex / columnCount; int column = vertex - row * columnCount; - // todo comment int rowOffsets[4] = { 0, 0, -1, -1 }; int columnOffsets[4] = { 0, -1, 0, -1 }; int firstParity[4] = { 0, 0, 0, 1 }; diff --git a/src/mesh.c b/src/mesh.c index 38e0e9d..d175c81 100644 --- a/src/mesh.c +++ b/src/mesh.c @@ -148,16 +148,6 @@ static uint8_t* b3GetMeshVertexFlagsWrite( b3MeshData* mesh ) return (uint8_t*)( (intptr_t)mesh + mesh->vertexFlagOffset ); } -static int* b3GetMeshVertexTrianglesWrite( b3MeshData* mesh ) -{ - if ( mesh->vertexTriangleOffset == 0 ) - { - return NULL; - } - - return (int*)( (intptr_t)mesh + mesh->vertexTriangleOffset ); -} - static int b3GetNodeHeight( const b3MeshNode* node ) { if ( b3IsLeaf( node ) ) @@ -1066,6 +1056,107 @@ typedef struct #define B3_EDGE_ANGLE_STEPS 127.0f +// Lookup table for 8-bit compressed triangle neighbor angles. +static const b3CosSin s_quantizedCosSin[255] = { + { 1.0f, 0.0f }, { 0.9999235f, 0.012368159f }, { 0.99969405f, 0.024734428f }, + { 0.9993117f, 0.03709691f }, { 0.99877644f, 0.04945372f }, { 0.99808836f, 0.061802965f }, + { 0.99724764f, 0.074142754f }, { 0.9962543f, 0.0864712f }, { 0.99510866f, 0.09878642f }, + { 0.9938107f, 0.111086525f }, { 0.9923608f, 0.12336964f }, { 0.990759f, 0.13563387f }, + { 0.9890057f, 0.14787737f }, { 0.9871011f, 0.16009824f }, { 0.9850455f, 0.17229462f }, + { 0.98283917f, 0.18446463f }, { 0.98048246f, 0.19660644f }, { 0.97797585f, 0.20871817f }, + { 0.97531956f, 0.22079796f }, { 0.9725141f, 0.23284398f }, { 0.96955985f, 0.24485438f }, + { 0.9664573f, 0.25682732f }, { 0.9632069f, 0.26876098f }, { 0.9598091f, 0.2806535f }, + { 0.95626456f, 0.29250312f }, { 0.9525737f, 0.304308f }, { 0.9487371f, 0.3160663f }, + { 0.9447554f, 0.32777625f }, { 0.9406291f, 0.33943605f }, { 0.936359f, 0.35104394f }, + { 0.9319456f, 0.36259815f }, { 0.9273896f, 0.37409684f }, { 0.9226918f, 0.38553834f }, + { 0.9178528f, 0.39692086f }, { 0.91287345f, 0.40824264f }, { 0.9077544f, 0.419502f }, + { 0.9024965f, 0.43069714f }, { 0.89710057f, 0.44182643f }, { 0.89156735f, 0.4528881f }, + { 0.88589776f, 0.4638805f }, { 0.8800927f, 0.47480196f }, { 0.8741529f, 0.48565078f }, + { 0.8680794f, 0.4964253f }, { 0.8618732f, 0.5071239f }, { 0.8555351f, 0.51774484f }, + { 0.8490661f, 0.52828664f }, { 0.8424672f, 0.5387476f }, { 0.83573943f, 0.5491262f }, + { 0.8288838f, 0.55942076f }, { 0.82190144f, 0.5696297f }, { 0.8147933f, 0.57975155f }, + { 0.8075605f, 0.58978474f }, { 0.8002042f, 0.59972763f }, { 0.79272544f, 0.60957885f }, + { 0.78512543f, 0.6193367f }, { 0.7774054f, 0.62899995f }, { 0.7695663f, 0.6385669f }, + { 0.76160955f, 0.6480362f }, { 0.7535363f, 0.65740633f }, { 0.74534774f, 0.66667587f }, + { 0.73704517f, 0.6758435f }, { 0.7286299f, 0.6849077f }, { 0.7201031f, 0.6938671f }, + { 0.71146613f, 0.70272034f }, { 0.70272034f, 0.71146613f }, { 0.6938671f, 0.7201031f }, + { 0.6849077f, 0.7286299f }, { 0.6758435f, 0.73704517f }, { 0.66667587f, 0.74534774f }, + { 0.65740633f, 0.7535363f }, { 0.6480362f, 0.76160955f }, { 0.6385669f, 0.7695663f }, + { 0.62899995f, 0.7774054f }, { 0.6193367f, 0.78512543f }, { 0.60957885f, 0.79272544f }, + { 0.59972763f, 0.8002042f }, { 0.58978474f, 0.8075605f }, { 0.57975155f, 0.8147933f }, + { 0.5696297f, 0.82190144f }, { 0.55942076f, 0.8288838f }, { 0.5491262f, 0.83573943f }, + { 0.5387476f, 0.8424672f }, { 0.52828664f, 0.8490661f }, { 0.51774484f, 0.8555351f }, + { 0.5071239f, 0.8618732f }, { 0.4964253f, 0.8680794f }, { 0.48565078f, 0.8741529f }, + { 0.47480196f, 0.8800927f }, { 0.4638805f, 0.88589776f }, { 0.4528881f, 0.89156735f }, + { 0.44182643f, 0.89710057f }, { 0.43069714f, 0.9024965f }, { 0.419502f, 0.9077544f }, + { 0.40824264f, 0.91287345f }, { 0.39692086f, 0.9178528f }, { 0.38553834f, 0.9226918f }, + { 0.37409684f, 0.9273896f }, { 0.36259815f, 0.9319456f }, { 0.35104394f, 0.936359f }, + { 0.33943605f, 0.9406291f }, { 0.32777625f, 0.9447554f }, { 0.3160663f, 0.9487371f }, + { 0.304308f, 0.9525737f }, { 0.29250312f, 0.95626456f }, { 0.2806535f, 0.9598091f }, + { 0.26876098f, 0.9632069f }, { 0.25682732f, 0.9664573f }, { 0.24485438f, 0.96955985f }, + { 0.23284398f, 0.9725141f }, { 0.22079796f, 0.97531956f }, { 0.20871817f, 0.97797585f }, + { 0.19660644f, 0.98048246f }, { 0.18446463f, 0.98283917f }, { 0.17229462f, 0.9850455f }, + { 0.16009824f, 0.9871011f }, { 0.14787737f, 0.9890057f }, { 0.13563387f, 0.990759f }, + { 0.12336964f, 0.9923608f }, { 0.111086525f, 0.9938107f }, { 0.09878642f, 0.99510866f }, + { 0.0864712f, 0.9962543f }, { 0.074142754f, 0.99724764f }, { 0.061802965f, 0.99808836f }, + { 0.04945372f, 0.99877644f }, { 0.03709691f, 0.9993117f }, { 0.024734428f, 0.99969405f }, + { 0.012368159f, 0.9999235f }, { 0.0f, 1.0f }, { -0.012368159f, 0.9999235f }, + { -0.024734428f, 0.99969405f }, { -0.03709691f, 0.9993117f }, { -0.04945372f, 0.99877644f }, + { -0.061802965f, 0.99808836f }, { -0.074142754f, 0.99724764f }, { -0.0864712f, 0.9962543f }, + { -0.09878642f, 0.99510866f }, { -0.111086525f, 0.9938107f }, { -0.12336964f, 0.9923608f }, + { -0.13563387f, 0.990759f }, { -0.14787737f, 0.9890057f }, { -0.16009824f, 0.9871011f }, + { -0.17229462f, 0.9850455f }, { -0.18446463f, 0.98283917f }, { -0.19660644f, 0.98048246f }, + { -0.20871817f, 0.97797585f }, { -0.22079796f, 0.97531956f }, { -0.23284398f, 0.9725141f }, + { -0.24485438f, 0.96955985f }, { -0.25682732f, 0.9664573f }, { -0.26876098f, 0.9632069f }, + { -0.2806535f, 0.9598091f }, { -0.29250312f, 0.95626456f }, { -0.304308f, 0.9525737f }, + { -0.3160663f, 0.9487371f }, { -0.32777625f, 0.9447554f }, { -0.33943605f, 0.9406291f }, + { -0.35104394f, 0.936359f }, { -0.36259815f, 0.9319456f }, { -0.37409684f, 0.9273896f }, + { -0.38553834f, 0.9226918f }, { -0.39692086f, 0.9178528f }, { -0.40824264f, 0.91287345f }, + { -0.419502f, 0.9077544f }, { -0.43069714f, 0.9024965f }, { -0.44182643f, 0.89710057f }, + { -0.4528881f, 0.89156735f }, { -0.4638805f, 0.88589776f }, { -0.47480196f, 0.8800927f }, + { -0.48565078f, 0.8741529f }, { -0.4964253f, 0.8680794f }, { -0.5071239f, 0.8618732f }, + { -0.51774484f, 0.8555351f }, { -0.52828664f, 0.8490661f }, { -0.5387476f, 0.8424672f }, + { -0.5491262f, 0.83573943f }, { -0.55942076f, 0.8288838f }, { -0.5696297f, 0.82190144f }, + { -0.57975155f, 0.8147933f }, { -0.58978474f, 0.8075605f }, { -0.59972763f, 0.8002042f }, + { -0.60957885f, 0.79272544f }, { -0.6193367f, 0.78512543f }, { -0.62899995f, 0.7774054f }, + { -0.6385669f, 0.7695663f }, { -0.6480362f, 0.76160955f }, { -0.65740633f, 0.7535363f }, + { -0.66667587f, 0.74534774f }, { -0.6758435f, 0.73704517f }, { -0.6849077f, 0.7286299f }, + { -0.6938671f, 0.7201031f }, { -0.70272034f, 0.71146613f }, { -0.71146613f, 0.70272034f }, + { -0.7201031f, 0.6938671f }, { -0.7286299f, 0.6849077f }, { -0.73704517f, 0.6758435f }, + { -0.74534774f, 0.66667587f }, { -0.7535363f, 0.65740633f }, { -0.76160955f, 0.6480362f }, + { -0.7695663f, 0.6385669f }, { -0.7774054f, 0.62899995f }, { -0.78512543f, 0.6193367f }, + { -0.79272544f, 0.60957885f }, { -0.8002042f, 0.59972763f }, { -0.8075605f, 0.58978474f }, + { -0.8147933f, 0.57975155f }, { -0.82190144f, 0.5696297f }, { -0.8288838f, 0.55942076f }, + { -0.83573943f, 0.5491262f }, { -0.8424672f, 0.5387476f }, { -0.8490661f, 0.52828664f }, + { -0.8555351f, 0.51774484f }, { -0.8618732f, 0.5071239f }, { -0.8680794f, 0.4964253f }, + { -0.8741529f, 0.48565078f }, { -0.8800927f, 0.47480196f }, { -0.88589776f, 0.4638805f }, + { -0.89156735f, 0.4528881f }, { -0.89710057f, 0.44182643f }, { -0.9024965f, 0.43069714f }, + { -0.9077544f, 0.419502f }, { -0.91287345f, 0.40824264f }, { -0.9178528f, 0.39692086f }, + { -0.9226918f, 0.38553834f }, { -0.9273896f, 0.37409684f }, { -0.9319456f, 0.36259815f }, + { -0.936359f, 0.35104394f }, { -0.9406291f, 0.33943605f }, { -0.9447554f, 0.32777625f }, + { -0.9487371f, 0.3160663f }, { -0.9525737f, 0.304308f }, { -0.95626456f, 0.29250312f }, + { -0.9598091f, 0.2806535f }, { -0.9632069f, 0.26876098f }, { -0.9664573f, 0.25682732f }, + { -0.96955985f, 0.24485438f }, { -0.9725141f, 0.23284398f }, { -0.97531956f, 0.22079796f }, + { -0.97797585f, 0.20871817f }, { -0.98048246f, 0.19660644f }, { -0.98283917f, 0.18446463f }, + { -0.9850455f, 0.17229462f }, { -0.9871011f, 0.16009824f }, { -0.9890057f, 0.14787737f }, + { -0.990759f, 0.13563387f }, { -0.9923608f, 0.12336964f }, { -0.9938107f, 0.111086525f }, + { -0.99510866f, 0.09878642f }, { -0.9962543f, 0.0864712f }, { -0.99724764f, 0.074142754f }, + { -0.99808836f, 0.061802965f }, { -0.99877644f, 0.04945372f }, { -0.9993117f, 0.03709691f }, + { -0.99969405f, 0.024734428f }, { -0.9999235f, 0.012368159f }, { -1.0f, 0.0f }, +}; + +static b3CosSin b3GetQuantizedCosSin( int code ) +{ + B3_ASSERT( -254 <= code && code <= 254 ); + b3CosSin cs = s_quantizedCosSin[code < 0 ? -code : code]; + if ( code < 0 ) + { + cs.sine = -cs.sine; + } + + return cs; +} + int8_t b3QuantizeEdgeAngle( float radians ) { float scaled = radians * ( B3_EDGE_ANGLE_STEPS / B3_PI ); @@ -1073,6 +1164,85 @@ int8_t b3QuantizeEdgeAngle( float radians ) return (int8_t)b3ClampInt( quantized, -127, 127 ); } +typedef struct b3VertexRing +{ + uint16_t axis; + uint16_t wallCount; +} b3VertexRing; + +typedef struct b3VertexRingEntry +{ + int8_t yaw; + int8_t tilt; +} b3VertexRingEntry; + +static b3Vec3 b3FoldOctahedral( float x, float y ) +{ + return ( b3Vec3 ){ + ( 1.0f - b3AbsFloat( y ) ) * ( x >= 0.0f ? 1.0f : -1.0f ), + ( 1.0f - b3AbsFloat( x ) ) * ( y >= 0.0f ? 1.0f : -1.0f ), + 0.0f, + }; +} + +static uint16_t b3EncodeRingAxis( b3Vec3 axis ) +{ + float sum = b3AbsFloat( axis.x ) + b3AbsFloat( axis.y ) + b3AbsFloat( axis.z ); + float x = axis.x / sum; + float y = axis.y / sum; + if ( axis.z < 0.0f ) + { + b3Vec3 folded = b3FoldOctahedral( x, y ); + x = folded.x; + y = folded.y; + } + + int u = b3ClampInt( (int)( 127.5f * ( x + 1.0f ) + 0.5f ), 0, 255 ); + int v = b3ClampInt( (int)( 127.5f * ( y + 1.0f ) + 0.5f ), 0, 255 ); + return (uint16_t)( u | ( v << 8 ) ); +} + +static b3Vec3 b3DecodeRingAxis( uint16_t code ) +{ + float x = (float)( code & 0xFF ) * ( 2.0f / 255.0f ) - 1.0f; + float y = (float)( code >> 8 ) * ( 2.0f / 255.0f ) - 1.0f; + float z = 1.0f - b3AbsFloat( x ) - b3AbsFloat( y ); + if ( z < 0.0f ) + { + b3Vec3 folded = b3FoldOctahedral( x, y ); + x = folded.x; + y = folded.y; + } + + return b3Normalize( ( b3Vec3 ){ x, y, z } ); +} + +static void b3MakeRingFrame( b3Vec3 axis, b3Vec3* tangent1, b3Vec3* tangent2 ) +{ + *tangent1 = b3Perp( axis ); + *tangent2 = b3Cross( axis, *tangent1 ); +} + +static b3VertexRingEntry b3EncodeRingEntry( b3Vec3 direction, b3Vec3 tangent1, b3Vec3 tangent2, b3Vec3 axis ) +{ + float x = b3Dot( direction, tangent1 ); + float y = b3Dot( direction, tangent2 ); + float z = b3Dot( direction, axis ); + float yaw = b3Atan2( y, x ); + float tilt = b3Atan2( z, sqrtf( x * x + y * y ) ); + + // todo comment + return ( b3VertexRingEntry ){ b3QuantizeEdgeAngle( yaw ), b3QuantizeEdgeAngle( 2.0f * tilt ) }; +} + +// todo comment +static b3Vec3 b3DecodeRingEntry( b3VertexRingEntry entry ) +{ + b3CosSin yaw = b3GetQuantizedCosSin( 2 * entry.yaw ); + b3CosSin tilt = b3GetQuantizedCosSin( entry.tilt ); + return ( b3Vec3 ){ tilt.cosine * yaw.cosine, tilt.cosine * yaw.sine, tilt.sine }; +} + bool b3GetMeshNeighborNormal( const b3Mesh* mesh, int triangleIndex, int edgeIndex, b3Vec3* normal ) { const b3MeshData* data = mesh->data; @@ -1109,7 +1279,7 @@ bool b3GetMeshNeighborNormal( const b3Mesh* mesh, int triangleIndex, int edgeInd b3Vec3 n = b3Normalize( b3Cross( b3Sub( b, a ), b3Sub( c, a ) ) ); b3Vec3 outward = b3Cross( b3Normalize( b3Sub( b, a ) ), n ); - b3CosSin cs = b3ComputeCosSin( (float)quantized * ( B3_PI / B3_EDGE_ANGLE_STEPS ) ); + b3CosSin cs = b3GetQuantizedCosSin( 2 * quantized ); b3Vec3 unscaled = b3Add( b3MulSV( cs.cosine, n ), b3MulSV( cs.sine, outward ) ); b3Vec3 absScale = b3Abs( scale ); @@ -1130,6 +1300,19 @@ bool b3GetMeshNeighborNormal( const b3Mesh* mesh, int triangleIndex, int edgeInd return true; } +static int b3GetMeshVertexIndex( const b3Mesh* mesh, b3MeshTriangle triangle, int vertexIndex ) +{ + b3Vec3 scale = mesh->scale; + if ( scale.x * scale.y * scale.z < 0.0f ) + { + // Handle reflection. + vertexIndex = ( 3 - vertexIndex ) % 3; + } + + int indices[3] = { triangle.index1, triangle.index2, triangle.index3 }; + return indices[vertexIndex]; +} + int b3GetMeshVertexFlag( const b3Mesh* mesh, int triangleIndex, int vertexIndex ) { const b3MeshData* data = mesh->data; @@ -1142,31 +1325,87 @@ int b3GetMeshVertexFlag( const b3Mesh* mesh, int triangleIndex, int vertexIndex return b3_flatVertex; } - b3Vec3 scale = mesh->scale; - if ( scale.x * scale.y * scale.z < 0.0f ) + b3MeshTriangle triangle = b3GetMeshTriangles( data )[triangleIndex]; + return vertexFlags[b3GetMeshVertexIndex( mesh, triangle, vertexIndex )]; +} + +bool b3IsInMeshVertexRing( const b3Mesh* mesh, int triangleIndex, int vertexIndex, b3Vec3 normal, float tolerance ) +{ + const b3MeshData* data = mesh->data; + B3_ASSERT( 0 <= triangleIndex && triangleIndex < data->triangleCount ); + B3_ASSERT( 0 <= vertexIndex && vertexIndex < 3 ); + + if ( data->vertexRingOffset == 0 ) { - // Handle reflection. - vertexIndex = ( 3 - vertexIndex ) % 3; + return true; } b3MeshTriangle triangle = b3GetMeshTriangles( data )[triangleIndex]; - int indices[3] = { triangle.index1, triangle.index2, triangle.index3 }; - return vertexFlags[indices[vertexIndex]]; -} + int vertex = b3GetMeshVertexIndex( mesh, triangle, vertexIndex ); -int b3GetMeshVertexTriangles( const b3MeshData* mesh, int vertex, const int** triangles ) -{ - B3_ASSERT( 0 <= vertex && vertex < mesh->vertexCount ); - - if ( mesh->vertexTriangleOffset == 0 ) + // todo comment + b3Vec3 scale = mesh->scale; + b3Vec3 edgeScale, wallScale; + b3Vec3 absScale = b3Abs( scale ); + bool uniform = absScale.y == absScale.x && absScale.z == absScale.x; + if ( uniform ) { - *triangles = NULL; - return 0; + edgeScale = ( b3Vec3 ){ scale.x < 0.0f ? -1.0f : 1.0f, scale.y < 0.0f ? -1.0f : 1.0f, scale.z < 0.0f ? -1.0f : 1.0f }; + wallScale = edgeScale; + } + else + { + edgeScale = scale; + wallScale = ( b3Vec3 ){ 1.0f / scale.x, 1.0f / scale.y, 1.0f / scale.z }; } - const int* starts = (const int*)( (intptr_t)mesh + mesh->vertexTriangleOffset ); - *triangles = starts + mesh->vertexCount + 1 + starts[vertex]; - return starts[vertex + 1] - starts[vertex]; + const int* starts = (const int*)( (intptr_t)data + data->vertexRingOffset ); + int byteCount = starts[vertex + 1] - starts[vertex]; + if ( byteCount == 0 ) + { + // todo comment + const b3Vec3* vertices = b3GetMeshVertices( data ); + b3Vec3 faceNormal = + b3MakeNormalFromPoints( vertices[triangle.index1], vertices[triangle.index2], vertices[triangle.index3] ); + faceNormal = b3Normalize( b3Mul( wallScale, faceNormal ) ); + float cosAngle = b3Dot( normal, faceNormal ); + return cosAngle > 0.0f && cosAngle * cosAngle >= 1.0f - tolerance * tolerance; + } + + const b3VertexRing* ring = (const b3VertexRing*)( (intptr_t)data + starts[vertex] ); + const b3VertexRingEntry* entries = (const b3VertexRingEntry*)( ring + 1 ); + int entryCount = ( byteCount - (int)sizeof( b3VertexRing ) ) / (int)sizeof( b3VertexRingEntry ); + int edgeCount = entryCount - ring->wallCount; + + b3Vec3 axis = b3DecodeRingAxis( ring->axis ); + b3Vec3 tangent1, tangent2; + b3MakeRingFrame( axis, &tangent1, &tangent2 ); + + b3Vec3 edgeNormal = b3Mul( edgeScale, normal ); + b3Vec3 wallNormal = b3Mul( wallScale, normal ); + b3Vec3 localEdgeNormal = { b3Dot( edgeNormal, tangent1 ), b3Dot( edgeNormal, tangent2 ), b3Dot( edgeNormal, axis ) }; + b3Vec3 localWallNormal = { b3Dot( wallNormal, tangent1 ), b3Dot( wallNormal, tangent2 ), b3Dot( wallNormal, axis ) }; + + for ( int i = 0; i < entryCount; ++i ) + { + bool isWall = i >= edgeCount; + b3Vec3 direction = b3DecodeRingEntry( entries[i] ); + float lean = b3Dot( isWall ? localWallNormal : localEdgeNormal, direction ); + + float limit = tolerance; + if ( uniform == false ) + { + b3Vec3 meshDirection = b3MulAdd( b3MulAdd( b3MulSV( direction.x, tangent1 ), direction.y, tangent2 ), direction.z, axis ); + limit *= b3Length( b3Mul( isWall ? wallScale : edgeScale, meshDirection ) ); + } + + if ( lean > limit ) + { + return false; + } + } + + return true; } static void b3IdentifyEdges( b3MeshData* mesh ) @@ -1424,35 +1663,203 @@ static void b3IdentifyEdges( b3MeshData* mesh ) } } - int* vertexStarts = b3GetMeshVertexTrianglesWrite( mesh ); - B3_ASSERT( vertexStarts != NULL ); - int* vertexTriangles = vertexStarts + vertexCount + 1; + B3_FREE( normals, b3Vec3, triangleCount ); + B3_FREE( edges, b3MeshEdge, edgeCount ); +} +// todo comment +static int b3BuildVertexRing( const b3MeshData* mesh, const int* fan, int fanCount, int vertex, int* stamps, int stamp, + b3VertexRing* ring ) +{ + const b3MeshTriangle* triangles = b3GetMeshTriangles( mesh ); + const b3Vec3* vertices = b3GetMeshVertices( mesh ); + const int8_t* edgeAngles = b3GetMeshEdgeAngles( mesh ); + + b3Vec3 axis = b3Vec3_zero; + b3Vec3 tangent1 = b3Vec3_zero; + b3Vec3 tangent2 = b3Vec3_zero; + b3VertexRingEntry* entries = NULL; + if ( ring != NULL ) + { + b3Vec3 normalSum = b3Vec3_zero; + for ( int i = 0; i < fanCount; ++i ) + { + b3MeshTriangle triangle = triangles[fan[i]]; + b3Vec3 normal = + b3MakeNormalFromPoints( vertices[triangle.index1], vertices[triangle.index2], vertices[triangle.index3] ); + normalSum = b3Add( normalSum, normal ); + } + + float length; + axis = b3GetLengthAndNormalize( &length, normalSum ); + if ( length == 0.0f ) + { + axis = ( b3Vec3 ){ 0.0f, 1.0f, 0.0f }; + } + + ring->axis = b3EncodeRingAxis( axis ); + axis = b3DecodeRingAxis( ring->axis ); + b3MakeRingFrame( axis, &tangent1, &tangent2 ); + entries = (b3VertexRingEntry*)( ring + 1 ); + } + + int entryCount = 0; + for ( int i = 0; i < fanCount; ++i ) + { + b3MeshTriangle triangle = triangles[fan[i]]; + int indices[3] = { triangle.index1, triangle.index2, triangle.index3 }; + int k = indices[0] == vertex ? 0 : ( indices[1] == vertex ? 1 : 2 ); + int others[2] = { indices[k < 2 ? k + 1 : 0], indices[k > 0 ? k - 1 : 2] }; + + for ( int j = 0; j < 2; ++j ) + { + int other = others[j]; + if ( stamps[other] == stamp ) + { + continue; + } + + stamps[other] = stamp; + if ( entries != NULL ) + { + b3Vec3 direction = b3Normalize( b3Sub( vertices[other], vertices[vertex] ) ); + entries[entryCount] = b3EncodeRingEntry( direction, tangent1, tangent2, axis ); + } + + entryCount += 1; + } + } + + int wallCount = 0; + for ( int i = 0; i < fanCount; ++i ) + { + int triangleIndex = fan[i]; + b3MeshTriangle triangle = triangles[triangleIndex]; + int indices[3] = { triangle.index1, triangle.index2, triangle.index3 }; + int k = indices[0] == vertex ? 0 : ( indices[1] == vertex ? 1 : 2 ); + int edgeIndices[2] = { k, k > 0 ? k - 1 : 2 }; + + for ( int j = 0; j < 2; ++j ) + { + if ( edgeAngles[3 * triangleIndex + edgeIndices[j]] != B3_BOUNDARY_EDGE_ANGLE ) + { + continue; + } + + if ( entries != NULL ) + { + b3Vec3 normal = + b3MakeNormalFromPoints( vertices[triangle.index1], vertices[triangle.index2], vertices[triangle.index3] ); + entries[entryCount] = b3EncodeRingEntry( b3Neg( normal ), tangent1, tangent2, axis ); + } + + entryCount += 1; + wallCount += 1; + } + } + + if ( ring != NULL ) + { + B3_ASSERT( wallCount <= UINT16_MAX ); + ring->wallCount = (uint16_t)wallCount; + } + + return (int)( sizeof( b3VertexRing ) + entryCount * sizeof( b3VertexRingEntry ) ); +} + +// Build a neighbor angle ring for each vertex. Used to mitigate ghost collisions with minimal tolerances +// and fudge factors. +static b3MeshData* b3AppendVertexRings( b3MeshData* mesh ) +{ + const b3MeshTriangle* triangles = b3GetMeshTriangles( mesh ); + const uint8_t* vertexFlags = b3GetMeshVertexFlags( mesh ); + B3_ASSERT( vertexFlags != NULL ); + + int vertexCount = mesh->vertexCount; + int triangleCount = mesh->triangleCount; + + int* fanStarts = B3_ALLOC( int, ( vertexCount + 1 ) ); + int* fans = B3_ALLOC( int, ( 3 * triangleCount ) ); + int* cursors = B3_ALLOC( int, vertexCount ); + int* stamps = B3_ALLOC( int, vertexCount ); + int* ringStarts = B3_ALLOC( int, ( vertexCount + 1 ) ); + + memset( fanStarts, 0, ( vertexCount + 1 ) * sizeof( int ) ); for ( int i = 0; i < triangleCount; ++i ) { - vertexStarts[triangles[i].index1 + 1] += 1; - vertexStarts[triangles[i].index2 + 1] += 1; - vertexStarts[triangles[i].index3 + 1] += 1; + fanStarts[triangles[i].index1 + 1] += 1; + fanStarts[triangles[i].index2 + 1] += 1; + fanStarts[triangles[i].index3 + 1] += 1; } for ( int i = 0; i < vertexCount; ++i ) { - vertexStarts[i + 1] += vertexStarts[i]; + fanStarts[i + 1] += fanStarts[i]; } - int* cursors = B3_ALLOC( int, vertexCount ); - memcpy( cursors, vertexStarts, vertexCount * sizeof( int ) ); - + memcpy( cursors, fanStarts, vertexCount * sizeof( int ) ); for ( int i = 0; i < triangleCount; ++i ) { - vertexTriangles[cursors[triangles[i].index1]++] = i; - vertexTriangles[cursors[triangles[i].index2]++] = i; - vertexTriangles[cursors[triangles[i].index3]++] = i; + fans[cursors[triangles[i].index1]++] = i; + fans[cursors[triangles[i].index2]++] = i; + fans[cursors[triangles[i].index3]++] = i; } + for ( int i = 0; i < vertexCount; ++i ) + { + stamps[i] = B3_NULL_INDEX; + } + + size_t startsOffset = mesh->byteCount; + size_t ringOffset = startsOffset + b3AlignUp8( ( vertexCount + 1 ) * sizeof( int ) ); + size_t offset = ringOffset; + for ( int i = 0; i < vertexCount; ++i ) + { + ringStarts[i] = (int)offset; + if ( vertexFlags[i] & b3_flatVertex ) + { + continue; + } + + const int* fan = fans + fanStarts[i]; + int fanCount = fanStarts[i + 1] - fanStarts[i]; + offset += b3BuildVertexRing( mesh, fan, fanCount, i, stamps, i, NULL ); + } + + ringStarts[vertexCount] = (int)offset; + + size_t byteCount = ringOffset + b3AlignUp8( offset - ringOffset ); + b3MeshData* result = b3Alloc( byteCount ); + memset( result, 0, byteCount ); + memcpy( result, mesh, mesh->byteCount ); + b3Free( mesh, mesh->byteCount ); + + result->byteCount = (int)byteCount; + result->vertexRingOffset = (int)startsOffset; + memcpy( (uint8_t*)result + startsOffset, ringStarts, ( vertexCount + 1 ) * sizeof( int ) ); + + for ( int i = 0; i < vertexCount; ++i ) + { + if ( ringStarts[i + 1] == ringStarts[i] ) + { + continue; + } + + const int* fan = fans + fanStarts[i]; + int fanCount = fanStarts[i + 1] - fanStarts[i]; + b3VertexRing* ring = (b3VertexRing*)( (uint8_t*)result + ringStarts[i] ); + int ringByteCount = b3BuildVertexRing( result, fan, fanCount, i, stamps, vertexCount + i, ring ); + B3_ASSERT( ringByteCount == ringStarts[i + 1] - ringStarts[i] ); + B3_UNUSED( ringByteCount ); + } + + B3_FREE( ringStarts, int, ( vertexCount + 1 ) ); + B3_FREE( stamps, int, vertexCount ); B3_FREE( cursors, int, vertexCount ); - B3_FREE( normals, b3Vec3, triangleCount ); - B3_FREE( edges, b3MeshEdge, edgeCount ); + B3_FREE( fans, int, ( 3 * triangleCount ) ); + B3_FREE( fanStarts, int, ( vertexCount + 1 ) ); + + return result; } b3MeshData* b3CreateGridMesh( int xCount, int zCount, float cellWidth, int materialCount, bool identifyEdges ) @@ -1973,15 +2380,12 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices, byteCount += b3AlignUp8( triangleCount * sizeof( uint8_t ) ); int edgeAngleOffset = 0; int vertexFlagOffset = 0; - int vertexTriangleOffset = 0; if ( def->identifyEdges ) { edgeAngleOffset = (int)byteCount; byteCount += b3AlignUp8( 3 * triangleCount * sizeof( int8_t ) ); vertexFlagOffset = (int)byteCount; byteCount += b3AlignUp8( vertexCount * sizeof( uint8_t ) ); - vertexTriangleOffset = (int)byteCount; - byteCount += b3AlignUp8( ( vertexCount + 1 + 3 * triangleCount ) * sizeof( int ) ); } b3MeshData* mesh = b3Alloc( byteCount ); @@ -2006,7 +2410,6 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices, mesh->flagsOffset = flagsOffset; mesh->edgeAngleOffset = edgeAngleOffset; mesh->vertexFlagOffset = vertexFlagOffset; - mesh->vertexTriangleOffset = vertexTriangleOffset; b3MeshNode* nodes = b3GetMeshNodesWrite( mesh ); b3MeshTriangle* triangles = b3GetMeshTrianglesWrite( mesh ); @@ -2059,6 +2462,8 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices, if ( def->identifyEdges ) { b3IdentifyEdges( mesh ); + + mesh = b3AppendVertexRings( mesh ); } B3_VALIDATE( b3IsNonDegenerate( mesh, minArea ) ); diff --git a/src/mesh_contact.c b/src/mesh_contact.c index 1003763..bb3534a 100644 --- a/src/mesh_contact.c +++ b/src/mesh_contact.c @@ -40,8 +40,7 @@ typedef struct b3TriangleQueryContext int count; } b3TriangleQueryContext; -static bool b3CollectTriangleIndicesCallback( b3Vec3 a, b3Vec3 b, b3Vec3 c, int triangleIndex, - void* context ) +static bool b3CollectTriangleIndicesCallback( b3Vec3 a, b3Vec3 b, b3Vec3 c, int triangleIndex, void* context ) { B3_UNUSED( a, b, c ); b3TriangleQueryContext* triangleContext = context; @@ -59,8 +58,8 @@ static bool b3CollectTriangleIndicesCallback( b3Vec3 a, b3Vec3 b, b3Vec3 c, int return true; } -static void b3RefreshCache( b3Contact* contact, const b3Shape* shapeA, b3WorldTransform xfA, - const b3AABB* bounds, b3Arena arena ) +static void b3RefreshCache( b3Contact* contact, const b3Shape* shapeA, b3WorldTransform xfA, const b3AABB* bounds, + b3Arena arena ) { B3_ASSERT( shapeA->type == b3_meshShape || shapeA->type == b3_heightShape ); @@ -99,8 +98,7 @@ static void b3RefreshCache( b3Contact* contact, const b3Shape* shapeA, b3WorldTr // Bounds are in world space. Convert to the local mesh frame. The broadphase bounds are float, // so the demoted mesh transform is the matching float world frame (exact in float mode). b3Transform meshTransform = b3ToRelativeTransform( xfA, b3Pos_zero ); - b3AABB localBounds = - b3AABB_Transform( b3InvertTransform( meshTransform ), meshContact->queryBounds ); + b3AABB localBounds = b3AABB_Transform( b3InvertTransform( meshTransform ), meshContact->queryBounds ); if ( shapeA->type == b3_meshShape ) { b3QueryMesh( &shapeA->mesh, localBounds, b3CollectTriangleIndicesCallback, &queryContext ); @@ -108,8 +106,7 @@ static void b3RefreshCache( b3Contact* contact, const b3Shape* shapeA, b3WorldTr else { B3_ASSERT( shapeA->type == b3_heightShape ); - b3QueryHeightField( shapeA->heightField, localBounds, b3CollectTriangleIndicesCallback, - &queryContext ); + b3QueryHeightField( shapeA->heightField, localBounds, b3CollectTriangleIndicesCallback, &queryContext ); } int* triangleIndices = queryContext.indices; @@ -127,15 +124,13 @@ static void b3RefreshCache( b3Contact* contact, const b3Shape* shapeA, b3WorldTr contactCache[index1] = (b3ContactCache){ 0 }; while ( index2 < contact->meshContact.triangleCache.count && - contact->meshContact.triangleCache.data[index2].triangleIndex < - triangleIndices[index1] ) + contact->meshContact.triangleCache.data[index2].triangleIndex < triangleIndices[index1] ) { index2 += 1; } if ( index2 < contact->meshContact.triangleCache.count && - contact->meshContact.triangleCache.data[index2].triangleIndex == - triangleIndices[index1] ) + contact->meshContact.triangleCache.data[index2].triangleIndex == triangleIndices[index1] ) { contactCache[index1] = contact->meshContact.triangleCache.data[index2].cache; } @@ -145,14 +140,12 @@ static void b3RefreshCache( b3Contact* contact, const b3Shape* shapeA, b3WorldTr b3Array_Resize( contact->meshContact.triangleCache, triangleCount ); for ( int i = 0; i < triangleCount; ++i ) { - contact->meshContact.triangleCache.data[i] = - (b3TriangleCache){ triangleIndices[i], contactCache[i] }; + contact->meshContact.triangleCache.data[i] = (b3TriangleCache){ triangleIndices[i], contactCache[i] }; if ( shapeA->type == b3_meshShape ) { B3_ASSERT( 0 <= contact->meshContact.triangleCache.data[i].triangleIndex && - contact->meshContact.triangleCache.data[i].triangleIndex < - shapeA->mesh.data->triangleCount ); + contact->meshContact.triangleCache.data[i].triangleIndex < shapeA->mesh.data->triangleCount ); } } } @@ -160,9 +153,8 @@ static void b3RefreshCache( b3Contact* contact, const b3Shape* shapeA, b3WorldTr #if B3_MAX_MANIFOLD_POINTS == 4 // Returns true if (score, separation) should replace (bestScore, bestSeparation). -static inline bool b3IsBetterCullCandidate( float score, float separation, float bestScore, - float bestSeparation, float scoreTol, - float separationTol ) +static inline bool b3IsBetterCullCandidate( float score, float separation, float bestScore, float bestSeparation, + float scoreTol, float separationTol ) { if ( score > bestScore + scoreTol ) { @@ -206,8 +198,7 @@ static int b3CullPoints( b3Point2D* points, int count ) // Separation sum heuristic float separation = points[i].separation + points[j].separation; - if ( b3IsBetterCullCandidate( score, separation, bestScore, bestSeparation, tolSqr, - separationTol ) ) + if ( b3IsBetterCullCandidate( score, separation, bestScore, bestSeparation, tolSqr, separationTol ) ) { bestIndex1 = i; bestIndex2 = j; @@ -271,8 +262,7 @@ static int b3CullPoints( b3Point2D* points, int count ) float signedArea = b3Cross2( ba, b3Sub2( p, a ) ); float score = b3AbsFloat( signedArea ); - if ( b3IsBetterCullCandidate( score, points[i].separation, bestScore, bestSeparation, - tolSqr, separationTol ) ) + if ( b3IsBetterCullCandidate( score, points[i].separation, bestScore, bestSeparation, tolSqr, separationTol ) ) { bestSignedArea = signedArea; bestScore = score; @@ -331,8 +321,7 @@ static int b3CullPoints( b3Point2D* points, int count ) float score = b3MaxFloat( u1, b3MaxFloat( u2, u3 ) ); // Use the area tolerance for collinear points and hysteresis - if ( b3IsBetterCullCandidate( score, points[i].separation, bestScore, bestSeparation, - tolSqr, separationTol ) ) + if ( b3IsBetterCullCandidate( score, points[i].separation, bestScore, bestSeparation, tolSqr, separationTol ) ) { bestScore = score; bestSeparation = points[i].separation; @@ -460,52 +449,42 @@ static bool b3IsInVertexRegion( const b3Vec3* vertices, int vertexIndex, b3Vec3 return b3Dot( normal, e1 ) <= 0.0f && b3Dot( normal, e2 ) <= 0.0f; } -static b3Triangle b3GetSurfaceTriangle( const b3Shape* shape, int triangleIndex ) -{ - if ( shape->type == b3_meshShape ) - { - return b3GetMeshTriangle( &shape->mesh, triangleIndex ); - } - - B3_ASSERT( shape->type == b3_heightShape ); - return b3GetHeightFieldTriangle( shape->heightField, triangleIndex ); -} - -// todo comment +// This is used to avoid ghost collisions at vertices. It is called rarely. +// trees25 : 2.6% +// mesh_drop : 0.04% static bool b3IsInVertexCone( const b3Shape* shape, int triangleIndex, int vertexIndex, b3Matrix3 meshToLocal, b3Vec3 normal ) { b3Vec3 meshNormal = b3MulMV( b3Transpose( meshToLocal ), normal ); float tolerance = B3_NEIGHBOR_TOLERANCE; + + if ( shape->type == b3_meshShape ) + { + return b3IsInMeshVertexRing( &shape->mesh, triangleIndex, vertexIndex, meshNormal, tolerance ); + } + + B3_ASSERT( shape->type == b3_heightShape ); float toleranceSquared = tolerance * tolerance; - b3Triangle triangle = b3GetSurfaceTriangle( shape, triangleIndex ); + b3Triangle triangle = b3GetHeightFieldTriangle( shape->heightField, triangleIndex ); int indices[3] = { triangle.i1, triangle.i2, triangle.i3 }; int vertex = indices[vertexIndex]; - int heightFieldTriangles[6]; - const int* fanTriangles = heightFieldTriangles; - int fanCount; - if ( shape->type == b3_meshShape ) - { - fanCount = b3GetMeshVertexTriangles( shape->mesh.data, vertex, &fanTriangles ); - } - else - { - fanCount = b3GetHeightFieldVertexTriangles( shape->heightField, vertex, heightFieldTriangles ); - } + int fanTriangles[6]; + int fanCount = b3GetHeightFieldVertexTriangles( shape->heightField, vertex, fanTriangles ); for ( int i = 0; i < fanCount; ++i ) { int fanIndex = fanTriangles[i]; - b3Triangle fan = b3GetSurfaceTriangle( shape, fanIndex ); + b3Triangle fan = b3GetHeightFieldTriangle( shape->heightField, fanIndex ); int fanIndices[3] = { fan.i1, fan.i2, fan.i3 }; int k = fanIndices[0] == vertex ? 0 : ( fanIndices[1] == vertex ? 1 : 2 ); B3_ASSERT( fanIndices[k] == vertex ); int next = k < 2 ? k + 1 : 0; int previous = k > 0 ? k - 1 : 2; - b3Vec3 edges[2] = { b3Sub( fan.vertices[next], fan.vertices[k] ), b3Sub( fan.vertices[previous], fan.vertices[k] ) }; + b3Vec3 edges[2] = { b3Sub( fan.vertices[next], fan.vertices[k] ), + b3Sub( fan.vertices[previous], fan.vertices[k] ) }; int edgeIndices[2] = { k, previous }; for ( int j = 0; j < 2; ++j ) @@ -551,9 +530,9 @@ static bool b3AdmitsVertexNormal( const b3Shape* shape, int triangleIndex, const } // Voronoi test of an edge or vertex normal against the neighbor normals. -static b3NeighborResult b3TestNeighbors( const b3Shape* shape, int triangleIndex, - const b3Vec3* vertices, b3Matrix3 meshToLocal, - b3TriangleFeature feature, b3Vec3 normal, int* ownerEdge ) +static b3NeighborResult b3TestNeighbors( const b3Shape* shape, int triangleIndex, const b3Vec3* vertices, + b3Matrix3 meshToLocal, b3TriangleFeature feature, b3Vec3 normal, + int* ownerEdge ) { *ownerEdge = B3_NULL_INDEX; @@ -608,8 +587,7 @@ static b3NeighborResult b3TestNeighbors( const b3Shape* shape, int triangleIndex for ( int i = 0; i < edgeCount; ++i ) { b3Vec3 direction; - bool haveNeighbor = b3GetNeighborDirection( shape, triangleIndex, vertices, meshToLocal, - edges[i], &direction ); + bool haveNeighbor = b3GetNeighborDirection( shape, triangleIndex, vertices, meshToLocal, edges[i], &direction ); bool admitted = b3Dot( normal, direction ) <= tolerance; if ( admitted == false && haveNeighbor && *ownerEdge == B3_NULL_INDEX ) @@ -623,7 +601,8 @@ static b3NeighborResult b3TestNeighbors( const b3Shape* shape, int triangleIndex if ( admit ) { - if ( vertexIndex == B3_NULL_INDEX || b3IsInVertexCone( shape, triangleIndex, vertexIndex, meshToLocal, normal ) ) + if ( vertexIndex == B3_NULL_INDEX || + b3IsInVertexCone( shape, triangleIndex, vertexIndex, meshToLocal, normal ) ) { return b3_neighborAdmit; } @@ -649,9 +628,8 @@ static b3NeighborResult b3TestNeighbors( const b3Shape* shape, int triangleIndex } // Voronoi test of neighbors based on deepest point. -static b3NeighborResult b3TestHullFaceNeighbors( const b3Shape* shape, int triangleIndex, - const b3Vec3* vertices, b3Matrix3 meshToLocal, - const b3LocalManifold* manifold, +static b3NeighborResult b3TestHullFaceNeighbors( const b3Shape* shape, int triangleIndex, const b3Vec3* vertices, + b3Matrix3 meshToLocal, const b3LocalManifold* manifold, b3TriangleFeature* nearFeature ) { *nearFeature = b3_featureNone; @@ -716,7 +694,8 @@ static b3NeighborResult b3TestHullFaceNeighbors( const b3Shape* shape, int trian nearEdges[nearCount] = i; nearCount += 1; - // An edge or vertex normal cone tilts outward from the triangle and an edge cone is perpendicular to the edge, a hull face normal need be neither. + // An edge or vertex normal cone tilts outward from the triangle and an edge cone is perpendicular to the + // edge, a hull face normal need be neither. inwardTilt = inwardTilt || b3Dot( normal, inward ) > tolerance; alongEdge = alongEdge || b3AbsFloat( b3Dot( normal, edge ) ) > tolerance; } @@ -777,8 +756,7 @@ static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shape *clustersOut = NULL; // Collide with triangles and build manifolds - b3LocalManifold** acceptedManifolds = - b3Bump( arena, triangleCount * sizeof( b3LocalManifold* ) ); + b3LocalManifold** acceptedManifolds = b3Bump( arena, triangleCount * sizeof( b3LocalManifold* ) ); int acceptedManifoldCount = 0; b3Matrix3 relativeMatrix = b3MakeMatrixFromQuat( transformAtoB.q ); @@ -793,8 +771,7 @@ static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shape const b3HullData* hullB = shapeB->type == b3_hullShape ? shapeB->hull : NULL; float hullSpeculativeDistance = enableSpeculative ? B3_SPECULATIVE_DISTANCE : restOffset; - b3Vec3 hullMargin = { hullSpeculativeDistance, hullSpeculativeDistance, - hullSpeculativeDistance }; + b3Vec3 hullMargin = { hullSpeculativeDistance, hullSpeculativeDistance, hullSpeculativeDistance }; int* survivorIndices = b3Bump( arena, triangleCount * sizeof( int ) ); b3Vec3* survivorVertices = b3Bump( arena, 3 * triangleCount * sizeof( b3Vec3 ) ); @@ -868,8 +845,7 @@ static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shape else { B3_ASSERT( shapeA->type == b3_heightShape ); - b3Triangle triangle = - b3GetHeightFieldTriangle( shapeA->heightField, triangleIndex ); + b3Triangle triangle = b3GetHeightFieldTriangle( shapeA->heightField, triangleIndex ); lanes[0][lane] = triangle.vertices[0]; lanes[1][lane] = triangle.vertices[1]; lanes[2][lane] = triangle.vertices[2]; @@ -884,15 +860,9 @@ static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shape b3FloatW4 ay = b3SetW4( lanes[k][0].y, lanes[k][1].y, lanes[k][2].y, lanes[k][3].y ); b3FloatW4 az = b3SetW4( lanes[k][0].z, lanes[k][1].z, lanes[k][2].z, lanes[k][3].z ); - vx[k] = b3AddW4( - b3AddW4( b3AddW4( b3MulW4( cxx, ax ), b3MulW4( cyx, ay ) ), b3MulW4( czx, az ) ), - px ); - vy[k] = b3AddW4( - b3AddW4( b3AddW4( b3MulW4( cxy, ax ), b3MulW4( cyy, ay ) ), b3MulW4( czy, az ) ), - py ); - vz[k] = b3AddW4( - b3AddW4( b3AddW4( b3MulW4( cxz, ax ), b3MulW4( cyz, ay ) ), b3MulW4( czz, az ) ), - pz ); + vx[k] = b3AddW4( b3AddW4( b3AddW4( b3MulW4( cxx, ax ), b3MulW4( cyx, ay ) ), b3MulW4( czx, az ) ), px ); + vy[k] = b3AddW4( b3AddW4( b3AddW4( b3MulW4( cxy, ax ), b3MulW4( cyy, ay ) ), b3MulW4( czy, az ) ), py ); + vz[k] = b3AddW4( b3AddW4( b3AddW4( b3MulW4( cxz, ax ), b3MulW4( cyz, ay ) ), b3MulW4( czz, az ) ), pz ); } uint32_t keepMask = ( 1u << laneCount ) - 1u; @@ -905,12 +875,11 @@ static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shape b3FloatW4 upperY = b3AddW4( b3MaxW4( vy[0], b3MaxW4( vy[1], vy[2] ) ), marginW ); b3FloatW4 upperZ = b3AddW4( b3MaxW4( vz[0], b3MaxW4( vz[1], vz[2] ) ), marginW ); - b3FloatW4 separated = - b3OrW4( b3LessThanW4( upperX, hullLowerX ), b3GreaterThanW4( lowerX, hullUpperX ) ); - separated = b3OrW4( separated, b3OrW4( b3LessThanW4( upperY, hullLowerY ), - b3GreaterThanW4( lowerY, hullUpperY ) ) ); - separated = b3OrW4( separated, b3OrW4( b3LessThanW4( upperZ, hullLowerZ ), - b3GreaterThanW4( lowerZ, hullUpperZ ) ) ); + b3FloatW4 separated = b3OrW4( b3LessThanW4( upperX, hullLowerX ), b3GreaterThanW4( lowerX, hullUpperX ) ); + separated = b3OrW4( separated, + b3OrW4( b3LessThanW4( upperY, hullLowerY ), b3GreaterThanW4( lowerY, hullUpperY ) ) ); + separated = b3OrW4( separated, + b3OrW4( b3LessThanW4( upperZ, hullLowerZ ), b3GreaterThanW4( lowerZ, hullUpperZ ) ) ); uint32_t cullMask = keepMask & (uint32_t)b3MoveMaskW4( separated ); keepMask &= ~cullMask; @@ -953,8 +922,7 @@ static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shape // Make room for clip points. Additional capacity for a heavy clip. int pointBufferCapacity = B3_MAX_POINTS_PER_TRIANGLE * survivorCount + 2 * B3_MAX_CLIP_POINTS; - b3LocalManifoldPoint* pointBuffer = - b3Bump( arena, pointBufferCapacity * sizeof( b3LocalManifoldPoint ) ); + b3LocalManifoldPoint* pointBuffer = b3Bump( arena, pointBufferCapacity * sizeof( b3LocalManifoldPoint ) ); int totalPointCount = 0; b3LocalManifold* manifoldBuffer = b3Bump( arena, survivorCount * sizeof( b3LocalManifold ) ); @@ -965,8 +933,7 @@ static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shape int* survivorManifolds = b3Bump( arena, survivorCount * sizeof( int ) ); memset( survivorManifolds, 0xFF, survivorCount * sizeof( int ) ); - for ( int survivorIndex = 0; - survivorIndex < survivorCount && totalPointCount + 3 < pointBufferCapacity; + for ( int survivorIndex = 0; survivorIndex < survivorCount && totalPointCount + 3 < pointBufferCapacity; ++survivorIndex ) { int index = survivorIndices[survivorIndex]; @@ -1006,9 +973,8 @@ static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shape cache->satCache = (b3SATCache){ 0 }; } - b3CollideTriangleAndHull( manifold, pointCapacity, vertices[0], vertices[1], - vertices[2], triangle.flags, hullB, &cache->satCache, - enableSpeculative ); + b3CollideTriangleAndHull( manifold, pointCapacity, vertices[0], vertices[1], vertices[2], + triangle.flags, hullB, &cache->satCache, enableSpeculative ); if ( context != NULL ) { context->satCallCount += 1; @@ -1029,13 +995,12 @@ static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shape b3NeighborResult result = b3_neighborAdmit; int ownerEdge = B3_NULL_INDEX; uint8_t meshFlags = manifold->feature == b3_featureHullFace ? b3_meshContactHullFace : 0; - if ( validateNeighbors && manifold->pointCount > 0 && - manifold->feature != b3_featureTriangleFace ) + if ( validateNeighbors && manifold->pointCount > 0 && manifold->feature != b3_featureTriangleFace ) { if ( manifold->feature == b3_featureHullFace ) { - result = b3TestHullFaceNeighbors( shapeA, triangleIndex, vertices, - relativeMatrix, manifold, &nearFeature ); + result = + b3TestHullFaceNeighbors( shapeA, triangleIndex, vertices, relativeMatrix, manifold, &nearFeature ); } else { @@ -1111,11 +1076,13 @@ static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shape B3_ASSERT( manifold->feature != b3_featureNone ); b3TriangleFeature pointFeature = manifold->feature; - if ( pointFeature == b3_featureHullFace && nearFeature != b3_featureHullFace && nearFeature != b3_featureNone ) + if ( pointFeature == b3_featureHullFace && nearFeature != b3_featureHullFace && + nearFeature != b3_featureNone ) { pointFeature = nearFeature; } - else if ( pointFeature == b3_featureHullFace && nearFeature == b3_featureNone && result == b3_neighborAdmit ) + else if ( pointFeature == b3_featureHullFace && nearFeature == b3_featureNone && + result == b3_neighborAdmit ) { pointFeature = b3_featureTriangleFace; } @@ -1127,8 +1094,7 @@ static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shape } manifold->triangleIndex = triangleIndex; - manifold->triangleNormal = - b3MakeNormalFromPoints( vertices[0], vertices[1], vertices[2] ); + manifold->triangleNormal = b3MakeNormalFromPoints( vertices[0], vertices[1], vertices[2] ); survivorManifolds[survivorIndex] = manifoldCount; manifoldCount += 1; @@ -1260,8 +1226,7 @@ static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shape } // Setup clusters - b3LocalManifoldPoint* clusterPoints = - b3Bump( arena, clusterPointCount * sizeof( b3LocalManifoldPoint ) ); + b3LocalManifoldPoint* clusterPoints = b3Bump( arena, clusterPointCount * sizeof( b3LocalManifoldPoint ) ); int pointOffset = 0; for ( int i = 0; i < clusterCount; ++i ) @@ -1314,10 +1279,9 @@ static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shape return clusterCount; } -bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact, - const b3Shape* shapeA, const uint16_t* materialMap, - b3WorldTransform xfA, const b3Shape* shapeB, b3WorldTransform xfB, - bool isFast, b3Arena arena ) +bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact, const b3Shape* shapeA, + const uint16_t* materialMap, b3WorldTransform xfA, const b3Shape* shapeB, + b3WorldTransform xfB, bool isFast, b3Arena arena ) { B3_ASSERT( shapeA->type == b3_meshShape || shapeA->type == b3_heightShape ); b3TaskContext* context = b3Array_Get( world->taskContexts, workerIndex ); @@ -1330,9 +1294,9 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact bool handleGhosts = B3_FORCE_GHOST_COLLISIONS == 0; b3Cluster* clusters; - int clusterCount = - b3CollideMeshTriangles( &clusters, shapeA, shapeB, transformAtoB, meshContact->triangleCache.data, - meshContact->triangleCache.count, enableSpeculative, handleGhosts, isFast, context, &arena ); + int clusterCount = b3CollideMeshTriangles( &clusters, shapeA, shapeB, transformAtoB, + meshContact->triangleCache.data, meshContact->triangleCache.count, + enableSpeculative, handleGhosts, isFast, context, &arena ); if ( clusterCount == 0 ) { @@ -1441,8 +1405,7 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact { b3ManifoldPoint* oldPt = matchedManifold->points + k; - if ( target->featureId == oldPt->featureId && - target->triangleIndex == oldPt->triangleIndex ) + if ( target->featureId == oldPt->featureId && target->triangleIndex == oldPt->triangleIndex ) { target->normalImpulse = oldPt->normalImpulse; target->persisted = true; @@ -1501,12 +1464,10 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact materialIndex = b3ClampInt( materialIndex, 0, shapeA->materialCount - 1 ); b3SurfaceMaterial material = materialsA[materialIndex]; - friction += - world->frictionCallback( material.friction, material.userMaterialId, - materialB->friction, materialB->userMaterialId ); - restitution += - world->restitutionCallback( material.restitution, material.userMaterialId, - materialB->restitution, materialB->userMaterialId ); + friction += world->frictionCallback( material.friction, material.userMaterialId, materialB->friction, + materialB->userMaterialId ); + restitution += world->restitutionCallback( material.restitution, material.userMaterialId, + materialB->restitution, materialB->userMaterialId ); tangentVelocityA = b3Add( tangentVelocityA, material.tangentVelocity ); @@ -1528,12 +1489,10 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact else { // Keep these updated in case the values on the shapes are modified - contact->friction = - world->frictionCallback( materialsA[0].friction, materialsA[0].userMaterialId, - materialB->friction, materialB->userMaterialId ); - contact->restitution = - world->restitutionCallback( materialsA[0].restitution, materialsA[0].userMaterialId, - materialB->restitution, materialB->userMaterialId ); + contact->friction = world->frictionCallback( materialsA[0].friction, materialsA[0].userMaterialId, + materialB->friction, materialB->userMaterialId ); + contact->restitution = world->restitutionCallback( materialsA[0].restitution, materialsA[0].userMaterialId, + materialB->restitution, materialB->userMaterialId ); tangentVelocityA = materialsA[0].tangentVelocity; } @@ -1607,8 +1566,8 @@ int b3CollideMeshAndHull( b3Manifold* manifolds, int capacity, const b3Mesh* mes b3Transform transformAtoB = b3InvertTransform( transformBtoA ); b3Cluster* clusters; - int clusterCount = b3CollideMeshTriangles( &clusters, &meshShape, &hullShape, transformAtoB, triangleCaches, triangleCount, - enableSpeculative, handleGhosts, false, NULL, &arena ); + int clusterCount = b3CollideMeshTriangles( &clusters, &meshShape, &hullShape, transformAtoB, triangleCaches, + triangleCount, enableSpeculative, handleGhosts, false, NULL, &arena ); int count = b3MinInt( clusterCount, capacity ); b3Matrix3 matrixB = b3MakeMatrixFromQuat( transformBtoA.q ); diff --git a/src/shape.h b/src/shape.h index 6009151..d6cb5c4 100644 --- a/src/shape.h +++ b/src/shape.h @@ -202,7 +202,7 @@ static inline bool b3GetNeighborNormal( const b3Shape* shape, int triangleIndex, } int b3GetMeshVertexFlag( const b3Mesh* mesh, int triangleIndex, int vertexIndex ); -int b3GetMeshVertexTriangles( const b3MeshData* mesh, int vertex, const int** triangles ); +bool b3IsInMeshVertexRing( const b3Mesh* mesh, int triangleIndex, int vertexIndex, b3Vec3 normal, float tolerance ); int8_t b3QuantizeEdgeAngle( float radians ); static inline bool b3IsConvexVertex( const b3Shape* shape, int triangleIndex, int vertexIndex ) diff --git a/test/test_determinism.c b/test/test_determinism.c index 087389f..9ae700f 100644 --- a/test/test_determinism.c +++ b/test/test_determinism.c @@ -28,7 +28,7 @@ #define QUERY_SPAWN_HIT_COUNT 59 #define QUERY_SPAWN_QUERY_HASH 0x5B4429DC #define MESH_DROP_SLEEP_STEP 197 -#define MESH_DROP_HASH 0x26FF13D8 +#define MESH_DROP_HASH 0xBE011939 #else #define RAGDOLL_SLEEP_STEP 289 #define RAGDOLL_HASH 0xF290ED4B @@ -39,7 +39,7 @@ #define QUERY_SPAWN_HIT_COUNT 59 #define QUERY_SPAWN_QUERY_HASH 0xE3271F3D #define MESH_DROP_SLEEP_STEP 197 -#define MESH_DROP_HASH 0x30DB4916 +#define MESH_DROP_HASH 0x8D5604D3 #endif // The goldens above pin exact values for the default four point manifold. A build that diff --git a/test/test_mesh.c b/test/test_mesh.c index 5d2e365..15b962d 100644 --- a/test/test_mesh.c +++ b/test/test_mesh.c @@ -1157,6 +1157,172 @@ static int MeshPeelCylinder( void ) return 0; } +// Exact vertex cone from every triangle at the vertex. Returns the largest lean of the normal past +// an edge at the vertex or past the wall below a boundary edge. +static float ExactVertexLean( const b3Mesh* mesh, int vertex, b3Vec3 normal ) +{ + float lean = -FLT_MAX; + for ( int i = 0; i < mesh->data->triangleCount; ++i ) + { + b3Triangle triangle = b3GetMeshTriangle( mesh, i ); + int indices[3] = { triangle.i1, triangle.i2, triangle.i3 }; + int k = indices[0] == vertex ? 0 : ( indices[1] == vertex ? 1 : ( indices[2] == vertex ? 2 : -1 ) ); + if ( k < 0 ) + { + continue; + } + + int next = ( k + 1 ) % 3; + int previous = ( k + 2 ) % 3; + b3Vec3 edges[2] = { b3Sub( triangle.vertices[next], triangle.vertices[k] ), + b3Sub( triangle.vertices[previous], triangle.vertices[k] ) }; + int edgeIndices[2] = { k, previous }; + b3Vec3 faceNormal = b3MakeNormalFromPoints( triangle.vertices[0], triangle.vertices[1], triangle.vertices[2] ); + + for ( int j = 0; j < 2; ++j ) + { + lean = b3MaxFloat( lean, b3Dot( normal, b3Normalize( edges[j] ) ) ); + + b3Vec3 neighborNormal; + if ( b3GetMeshNeighborNormal( mesh, i, edgeIndices[j], &neighborNormal ) == false ) + { + lean = b3MaxFloat( lean, -b3Dot( normal, faceNormal ) ); + } + } + } + + return lean; +} + +static uint32_t NextRandom( uint32_t* state ) +{ + *state = *state * 1664525u + 1013904223u; + return *state; +} + +static float RandomFloat( uint32_t* state ) +{ + return (float)( NextRandom( state ) >> 8 ) / (float)( 1 << 24 ) * 2.0f - 1.0f; +} + +// The quantized ring must admit normals well inside the exact cone and reject normals well outside. +// The band between is quantization noise. A non-uniform scale stretches it. +static bool VertexRingMatches( const b3MeshData* data, b3Vec3 scale, int* insideCount, int* outsideCount ) +{ + b3Mesh mesh = { .data = data, .scale = scale }; + + b3Vec3 s = b3Abs( scale ); + float spread = b3MaxFloat( s.x, b3MaxFloat( s.y, s.z ) ) / b3MinFloat( s.x, b3MinFloat( s.y, s.z ) ); + float tolerance = 0.0175f; + float margin = 0.025f * spread; + uint32_t state = 12345; + + for ( int i = 0; i < data->triangleCount; ++i ) + { + b3Triangle triangle = b3GetMeshTriangle( &mesh, i ); + int indices[3] = { triangle.i1, triangle.i2, triangle.i3 }; + b3Vec3 faceNormal = b3MakeNormalFromPoints( triangle.vertices[0], triangle.vertices[1], triangle.vertices[2] ); + + for ( int k = 0; k < 3; ++k ) + { + b3Vec3 samples[24]; + int sampleCount = 0; + samples[sampleCount++] = faceNormal; + + // Fan normals and their blends land near the cone + for ( int j = 0; j < data->triangleCount && sampleCount < 12; ++j ) + { + b3Triangle other = b3GetMeshTriangle( &mesh, j ); + if ( j == i || ( other.i1 != indices[k] && other.i2 != indices[k] && other.i3 != indices[k] ) ) + { + continue; + } + + b3Vec3 otherNormal = b3MakeNormalFromPoints( other.vertices[0], other.vertices[1], other.vertices[2] ); + samples[sampleCount++] = otherNormal; + samples[sampleCount++] = b3Normalize( b3Add( faceNormal, otherNormal ) ); + } + + while ( sampleCount < 24 ) + { + b3Vec3 tilt = { RandomFloat( &state ), RandomFloat( &state ), RandomFloat( &state ) }; + float amount = sampleCount % 2 == 0 ? 0.1f : 1.0f; + samples[sampleCount++] = b3Normalize( b3MulAdd( faceNormal, amount, tilt ) ); + } + + for ( int j = 0; j < sampleCount; ++j ) + { + b3Vec3 normal = samples[j]; + float lean = ExactVertexLean( &mesh, indices[k], normal ); + bool admit = b3IsInMeshVertexRing( &mesh, i, k, normal, tolerance ); + + if ( lean <= tolerance - margin ) + { + *insideCount += 1; + if ( admit == false ) + { + return false; + } + } + else if ( lean > tolerance + margin ) + { + *outsideCount += 1; + if ( admit ) + { + return false; + } + } + } + } + } + + return true; +} + +static int MeshVertexRing( void ) +{ + b3Vec3 vertices[VALLEY_VERTEX_COUNT]; + int32_t indices[3 * VALLEY_TRIANGLE_COUNT]; + MakeValley( vertices, indices ); + b3MeshDef def = MakeValleyDef( vertices, indices ); + + b3MeshData* meshes[] = { + b3CreateMesh( &def, NULL, 0 ), + b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 1.0f, 2.0f, 3.0f }, true ), + b3CreateWaveMesh( 8, 8, 1.0f, 0.5f, 0.2f, 0.15f ), + b3CreateTorusMesh( 8, 6, 2.0f, 0.5f ), + b3CreateGridMesh( 4, 4, 1.0f, 0, true ), + }; + + b3Vec3 scales[] = { + { 1.0f, 1.0f, 1.0f }, { 3.0f, 3.0f, 3.0f }, { -1.0f, 1.0f, 1.0f }, + { 2.0f, 0.5f, 1.5f }, { 0.5f, -2.0f, 1.0f }, { -1.0f, -1.0f, -1.0f }, + }; + + for ( int i = 0; i < ARRAY_COUNT( meshes ); ++i ) + { + ENSURE( meshes[i] != NULL ); + + for ( int j = 0; j < ARRAY_COUNT( scales ); ++j ) + { + int insideCount = 0; + int outsideCount = 0; + ENSURE( VertexRingMatches( meshes[i], scales[j], &insideCount, &outsideCount ) ); + ENSURE( insideCount > 0 && outsideCount > 0 ); + } + + b3DestroyMesh( meshes[i] ); + } + + // Without edge data every normal passes + b3MeshData* bare = b3CreateGridMesh( 4, 4, 1.0f, 0, false ); + b3Mesh mesh = { .data = bare, .scale = b3Vec3_one }; + ENSURE( b3IsInMeshVertexRing( &mesh, 0, 0, (b3Vec3){ 1.0f, 0.0f, 0.0f }, 0.0175f ) ); + b3DestroyMesh( bare ); + + return 0; +} + int MeshTest( void ) { RUN_SUBTEST( MeshDenseStride ); @@ -1170,6 +1336,7 @@ int MeshTest( void ) RUN_SUBTEST( MeshManyTriangles ); RUN_SUBTEST( MeshMirroredFlags ); RUN_SUBTEST( MeshEdgeAngles ); + RUN_SUBTEST( MeshVertexRing ); RUN_SUBTEST( MeshSphereOnRidge ); RUN_SUBTEST( MeshCapsuleOverCrest ); RUN_SUBTEST( MeshApexContact );