From 3b4878b7f2e6370e13e7f3d8b8a73db83a0794fc Mon Sep 17 00:00:00 2001 From: Erin Catto Date: Fri, 30 Oct 2026 15:37:39 -0700 Subject: [PATCH] quantized neighbor normals --- include/box3d/collision.h | 11 ++ include/box3d/types.h | 9 +- src/mesh.c | 99 +++++++++++++++++- src/shape.h | 2 + test/test_mesh.c | 215 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 331 insertions(+), 5 deletions(-) diff --git a/include/box3d/collision.h b/include/box3d/collision.h index 36e4b3f..1485af6 100644 --- a/include/box3d/collision.h +++ b/include/box3d/collision.h @@ -342,6 +342,17 @@ B3_INLINE const uint8_t* b3GetMeshFlags( const b3MeshData* mesh ) return (const uint8_t*)( (intptr_t)mesh + mesh->flagsOffset ); } +// Get read only quantized angles between neighboring triangle normals. +B3_INLINE const int8_t* b3GetMeshEdgeAngles( const b3MeshData* mesh ) +{ + if ( mesh->edgeAngleOffset == 0 ) + { + return NULL; + } + + return (const int8_t*)( (intptr_t)mesh + mesh->edgeAngleOffset ); +} + /// Create a grid mesh along the x and z axes. /// @param xCount the number of rows in the x direction /// @param zCount the number of rows in the z direction diff --git a/include/box3d/types.h b/include/box3d/types.h index 20fd0ce..7cdc29c 100644 --- a/include/box3d/types.h +++ b/include/box3d/types.h @@ -2260,7 +2260,7 @@ typedef struct b3MeshDef } b3MeshDef; /// 64-bit mesh version. Useful for validating serialized data. -#define B3_MESH_VERSION 0xAAAB9A00F1A8AAF7ull +#define B3_MESH_VERSION 0x5DDAD5A2B47BACA5ull /// Triangle mesh edge flags. typedef enum b3MeshEdgeFlags @@ -2291,6 +2291,9 @@ typedef struct b3MeshTriangle int32_t index3; ///< Index of vertex 3. } b3MeshTriangle; +// Indicates an isolated edge. +#define B3_BOUNDARY_EDGE_ANGLE ( -128 ) + /// A mesh BVH node. typedef struct b3MeshNode { @@ -2379,8 +2382,8 @@ typedef struct b3MeshData /// Offset of the triangle flag array in bytes from the struct address. int32_t flagsOffset; - /// Explicit padding. - int32_t padding; + // Offset to the array of neighbor quantized normal offsets. + int32_t edgeAngleOffset; } b3MeshData; /// This allows mesh data to be re-used with different scales. diff --git a/src/mesh.c b/src/mesh.c index 7b8d617..48c8aa5 100644 --- a/src/mesh.c +++ b/src/mesh.c @@ -128,6 +128,16 @@ static uint8_t* b3GetMeshFlagsWrite( b3MeshData* mesh ) return (uint8_t*)( (intptr_t)mesh + mesh->flagsOffset ); } +static int8_t* b3GetMeshEdgeAnglesWrite( b3MeshData* mesh ) +{ + if ( mesh->edgeAngleOffset == 0 ) + { + return NULL; + } + + return (int8_t*)( (intptr_t)mesh + mesh->edgeAngleOffset ); +} + static int b3GetNodeHeight( const b3MeshNode* node ) { if ( b3IsLeaf( node ) ) @@ -1034,6 +1044,60 @@ typedef struct uint8_t triangleEdgeIndex2; } b3MeshEdge; +#define B3_EDGE_ANGLE_STEPS 127.0f + +static int8_t b3QuantizeEdgeAngle( float radians ) +{ + float scaled = radians * ( B3_EDGE_ANGLE_STEPS / B3_PI ); + int quantized = scaled >= 0.0f ? (int)( scaled + 0.5f ) : -(int)( 0.5f - scaled ); + return (int8_t)b3ClampInt( quantized, -127, 127 ); +} + +bool b3GetMeshNeighborNormal( const b3Mesh* mesh, int triangleIndex, int edgeIndex, b3Vec3* normal ) +{ + const b3MeshData* data = mesh->data; + B3_ASSERT( 0 <= triangleIndex && triangleIndex < data->triangleCount ); + B3_ASSERT( 0 <= edgeIndex && edgeIndex < 3 ); + + const int8_t* edgeAngles = b3GetMeshEdgeAngles( data ); + if ( edgeAngles == NULL ) + { + return false; + } + + b3Vec3 scale = mesh->scale; + if ( scale.x * scale.y * scale.z < 0.0f ) + { + // Reflected mesh. + edgeIndex = 2 - edgeIndex; + } + + int8_t quantized = edgeAngles[3 * triangleIndex + edgeIndex]; + if ( quantized == B3_BOUNDARY_EDGE_ANGLE ) + { + return false; + } + + const b3MeshTriangle* triangles = b3GetMeshTriangles( data ); + const b3Vec3* vertices = b3GetMeshVertices( data ); + b3MeshTriangle triangle = triangles[triangleIndex]; + int indices[3] = { triangle.index1, triangle.index2, triangle.index3 }; + + b3Vec3 a = vertices[indices[edgeIndex]]; + b3Vec3 b = vertices[indices[( edgeIndex + 1 ) % 3]]; + b3Vec3 c = vertices[indices[( edgeIndex + 2 ) % 3]]; + 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 ) ); + b3Vec3 unscaled = b3Add( b3MulSV( cs.cosine, n ), b3MulSV( cs.sine, outward ) ); + + // Handle non-uniform scale. + b3Vec3 invScale = { 1.0f / scale.x, 1.0f / scale.y, 1.0f / scale.z }; + *normal = b3Normalize( b3Mul( invScale, unscaled ) ); + return true; +} + #define NAME b3EdgeMap #define KEY_TY uint64_t #define VAL_TY int @@ -1067,9 +1131,17 @@ static void b3IdentifyEdges( b3MeshData* mesh ) b3MeshTriangle* triangles = b3GetMeshTrianglesWrite( mesh ); const b3Vec3* vertices = b3GetMeshVertices( mesh ); uint8_t* flags = b3GetMeshFlagsWrite( mesh ); + int8_t* edgeAngles = b3GetMeshEdgeAnglesWrite( mesh ); + B3_ASSERT( edgeAngles != NULL ); int triangleCount = mesh->triangleCount; int edgeCount = 3 * triangleCount; + + for ( int i = 0; i < edgeCount; ++i ) + { + edgeAngles[i] = B3_BOUNDARY_EDGE_ANGLE; + } + b3MeshEdge* edges = B3_ALLOC( b3MeshEdge, edgeCount ); b3Vec3* normals = B3_ALLOC( b3Vec3, triangleCount ); @@ -1199,11 +1271,27 @@ static void b3IdentifyEdges( b3MeshData* mesh ) b3Vec3 v2 = vertices[i2]; b3Vec3 v3 = vertices[i3]; b3Vec3 p = vertices[opposite]; + b3Vec3 n1 = normals[edge->triangle1]; + b3Vec3 n2 = normals[edge->triangle2]; + + // Quantize the angles between neighboring normals. + int indices1[3] = { i1, i2, i3 }; + int indices2[3] = { j1, j2, j3 }; + int k1 = edge->triangleEdgeIndex1; + int k2 = edge->triangleEdgeIndex2; + if ( indices1[k1] == indices2[( k2 + 1 ) % 3] ) + { + b3Vec3 a = vertices[indices1[k1]]; + b3Vec3 b = vertices[indices1[( k1 + 1 ) % 3]]; + b3Vec3 outward = b3Cross( b3Normalize( b3Sub( b, a ) ), n1 ); + float angle = b3Atan2( b3Dot( n2, outward ), b3Dot( n2, n1 ) ); + int8_t quantized = b3QuantizeEdgeAngle( angle ); + edgeAngles[3 * edge->triangle1 + k1] = quantized; + edgeAngles[3 * edge->triangle2 + k2] = quantized; + } float cos5Deg = 0.9962f; float signedVolume = b3SignedVolume( v1, v2, v3, p ); - b3Vec3 n1 = normals[edge->triangle1]; - b3Vec3 n2 = normals[edge->triangle2]; float cosAngle = b3Dot( n1, n2 ); if ( signedVolume > 0.0f || cosAngle > cos5Deg ) { @@ -1740,6 +1828,12 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices, byteCount += b3AlignUp8( triangleCount * sizeof( uint8_t ) ); int flagsOffset = (int)byteCount; byteCount += b3AlignUp8( triangleCount * sizeof( uint8_t ) ); + int edgeAngleOffset = 0; + if ( def->identifyEdges ) + { + edgeAngleOffset = (int)byteCount; + byteCount += b3AlignUp8( 3 * triangleCount * sizeof( int8_t ) ); + } b3MeshData* mesh = b3Alloc( byteCount ); @@ -1761,6 +1855,7 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices, mesh->materialOffset = materialIndicesOffset; mesh->materialCount = materialCount; mesh->flagsOffset = flagsOffset; + mesh->edgeAngleOffset = edgeAngleOffset; b3MeshNode* nodes = b3GetMeshNodesWrite( mesh ); b3MeshTriangle* triangles = b3GetMeshTrianglesWrite( mesh ); diff --git a/src/shape.h b/src/shape.h index f8c2acf..997c353 100644 --- a/src/shape.h +++ b/src/shape.h @@ -183,6 +183,8 @@ static inline b3Triangle b3GetMeshTriangle( const b3Mesh* mesh, int triangleInde return result; } +bool b3GetMeshNeighborNormal( const b3Mesh* mesh, int triangleIndex, int edgeIndex, b3Vec3* normal ); + bool b3IsValidMesh( const b3MeshData* meshData ); static inline bool b3ShouldShapesCollide( b3Filter filterA, b3Filter filterB ) diff --git a/test/test_mesh.c b/test/test_mesh.c index 52dd151..cc0a82a 100644 --- a/test/test_mesh.c +++ b/test/test_mesh.c @@ -443,6 +443,220 @@ static int MeshMirroredFlags( void ) return 0; } +// Brute force search for the triangle across edge a-b, walked b to a with consistent winding +static int FindNeighbor( const b3Mesh* mesh, int triangleIndex, int a, int b, int* edgeIndex ) +{ + for ( int i = 0; i < mesh->data->triangleCount; ++i ) + { + if ( i == triangleIndex ) + { + continue; + } + + b3Triangle triangle = b3GetMeshTriangle( mesh, i ); + int indices[3] = { triangle.i1, triangle.i2, triangle.i3 }; + for ( int j = 0; j < 3; ++j ) + { + if ( indices[j] == b && indices[( j + 1 ) % 3] == a ) + { + *edgeIndex = j; + return i; + } + } + } + + return B3_NULL_INDEX; +} + +// Both sides of an edge store the same angle +static bool EdgeAnglesAreSymmetric( const b3MeshData* data, int* boundaryCount ) +{ + b3Mesh mesh = { .data = data, .scale = b3Vec3_one }; + const int8_t* edgeAngles = b3GetMeshEdgeAngles( data ); + *boundaryCount = 0; + + for ( int i = 0; i < data->triangleCount; ++i ) + { + b3Triangle triangle = b3GetMeshTriangle( &mesh, i ); + int indices[3] = { triangle.i1, triangle.i2, triangle.i3 }; + + for ( int k = 0; k < 3; ++k ) + { + int8_t angle = edgeAngles[3 * i + k]; + if ( angle == B3_BOUNDARY_EDGE_ANGLE ) + { + *boundaryCount += 1; + continue; + } + + int edgeIndex = -1; + int neighbor = FindNeighbor( &mesh, i, indices[k], indices[( k + 1 ) % 3], &edgeIndex ); + if ( neighbor == B3_NULL_INDEX || edgeAngles[3 * neighbor + edgeIndex] != angle ) + { + return false; + } + } + } + + return true; +} + +// The rebuilt neighbor normal must match the real one under any scale. A non-uniform scale +// stretches the quantization error by up to the ratio of its largest and smallest components. +static bool NeighborNormalsMatch( const b3MeshData* data, b3Vec3 scale ) +{ + 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.8f * spread * B3_PI / 180.0f; + float cosTolerance = cosf( tolerance ); + + for ( int i = 0; i < data->triangleCount; ++i ) + { + b3Triangle triangle = b3GetMeshTriangle( &mesh, i ); + int indices[3] = { triangle.i1, triangle.i2, triangle.i3 }; + + for ( int k = 0; k < 3; ++k ) + { + int edgeIndex = -1; + int neighbor = FindNeighbor( &mesh, i, indices[k], indices[( k + 1 ) % 3], &edgeIndex ); + + b3Vec3 rebuilt; + bool found = b3GetMeshNeighborNormal( &mesh, i, k, &rebuilt ); + if ( found != ( neighbor != B3_NULL_INDEX ) ) + { + return false; + } + + if ( found == false ) + { + continue; + } + + b3Triangle other = b3GetMeshTriangle( &mesh, neighbor ); + b3Vec3 e1 = b3Sub( other.vertices[1], other.vertices[0] ); + b3Vec3 e2 = b3Sub( other.vertices[2], other.vertices[0] ); + b3Vec3 actual = b3Normalize( b3Cross( e1, e2 ) ); + if ( b3Dot( rebuilt, actual ) < cosTolerance ) + { + return false; + } + } + } + + return true; +} + +// Positive angles are convex, negative are concave. A right angle sits on a rounding boundary. +static bool HasRightAngle( const b3MeshData* data, int sign ) +{ + const int8_t* edgeAngles = b3GetMeshEdgeAngles( data ); + for ( int i = 0; i < 3 * data->triangleCount; ++i ) + { + int angle = sign * edgeAngles[i]; + if ( angle == 63 || angle == 64 ) + { + return true; + } + } + + return false; +} + +static int MeshEdgeAngles( void ) +{ + { + b3MeshData* grid = b3CreateGridMesh( 4, 4, 1.0f, 0, true ); + ENSURE( b3GetMeshEdgeAngles( grid ) != NULL ); + + int boundaryCount = 0; + ENSURE( EdgeAnglesAreSymmetric( grid, &boundaryCount ) ); + ENSURE( boundaryCount == 16 ); + + const int8_t* edgeAngles = b3GetMeshEdgeAngles( grid ); + for ( int i = 0; i < 3 * grid->triangleCount; ++i ) + { + ENSURE( edgeAngles[i] == 0 || edgeAngles[i] == B3_BOUNDARY_EDGE_ANGLE ); + } + + b3DestroyMesh( grid ); + } + + { + b3MeshData* grid = b3CreateGridMesh( 4, 4, 1.0f, 0, false ); + ENSURE( b3GetMeshEdgeAngles( grid ) == NULL ); + b3DestroyMesh( grid ); + } + + 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 ), + }; + + b3MeshData* valley = meshes[0]; + b3MeshData* box = meshes[1]; + ENSURE( HasRightAngle( valley, -1 ) ); + ENSURE( HasRightAngle( box, 1 ) ); + + int boundaryCount = 0; + ENSURE( EdgeAnglesAreSymmetric( box, &boundaryCount ) ); + ENSURE( boundaryCount == 0 ); + + 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 ); + ENSURE( EdgeAnglesAreSymmetric( meshes[i], &boundaryCount ) ); + + for ( int j = 0; j < ARRAY_COUNT( scales ); ++j ) + { + ENSURE( NeighborNormalsMatch( meshes[i], scales[j] ) ); + } + + b3DestroyMesh( meshes[i] ); + } + + { + // Three triangles on edge 0-1 are non-manifold. The last two share edge 5-6 walked the + // same way, which is inconsistent winding. Neither gets an angle. + b3Vec3 finVertices[] = { + { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, { 0.0f, 0.0f, -1.0f }, + { 0.0f, 1.0f, 0.0f }, { 5.0f, 0.0f, 0.0f }, { 5.0f, 0.0f, 1.0f }, { 5.0f, 1.0f, 0.0f }, + }; + + int32_t finIndices[] = { + 0, 1, 2, 1, 0, 3, 0, 1, 4, 5, 6, 7, 5, 6, 2, + }; + + b3MeshDef finDef = { 0 }; + finDef.vertices = finVertices; + finDef.vertexCount = ARRAY_COUNT( finVertices ); + finDef.indices = finIndices; + finDef.triangleCount = ARRAY_COUNT( finIndices ) / 3; + finDef.identifyEdges = true; + b3MeshData* fin = b3CreateMesh( &finDef, NULL, 0 ); + ENSURE( fin != NULL ); + + ENSURE( EdgeAnglesAreSymmetric( fin, &boundaryCount ) ); + ENSURE( boundaryCount == 15 ); + b3DestroyMesh( fin ); + } + + return 0; +} + // A wide box sliding over a fine grid sits on hundreds of flat internal edges. With no friction // any manifold off the face normal is a ghost that slows or lifts the box. static int WideHullSlide( b3Vec3 meshScale ) @@ -580,6 +794,7 @@ int MeshTest( void ) RUN_SUBTEST( MeshWideHullSlide ); RUN_SUBTEST( MeshManyTriangles ); RUN_SUBTEST( MeshMirroredFlags ); + RUN_SUBTEST( MeshEdgeAngles ); return 0; }