Name cache (#53)

Removed B3_BODY_NAME_LENGTH and B3_SHAPE_NAME_LENGTH.
Now using a name cache instead to save memory and make recordings more
universal.
This is a recording version bump.
This commit is contained in:
Erin Catto 2026-07-06 17:33:45 -07:00 • committed by GitHub
commit 52f1a254ad
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
31 changed files with 759 additions and 824 deletions

View file

@ -47,6 +47,8 @@ set(BOX3D_SOURCE_FILES
mesh_contact.c
motor_joint.c
mover.c
name_cache.c
name_cache.h
parallel_for.c
parallel_for.h
parallel_joint.c

View file

@ -30,30 +30,29 @@ void* b3StackAlloc( b3Stack* stack, int size, const char* name )
return NULL;
}
// ensure allocation is 32 byte aligned to support 256-bit SIMD
int size32 = ( ( size - 1 ) | 0x1F ) + 1;
int alignedSize = ( ( size - 1 ) | ( B3_ALIGNMENT - 1 ) ) + 1;
b3StackEntry entry;
entry.size = size32;
entry.size = alignedSize;
entry.name = name;
if ( stack->index + size32 > stack->capacity )
if ( stack->index + alignedSize > stack->capacity )
{
// fall back to the heap (undesirable)
entry.data = (char*)b3Alloc( size32 );
entry.data = (char*)b3Alloc( alignedSize );
entry.usedMalloc = true;
B3_ASSERT( ( (uintptr_t)entry.data & 0x1F ) == 0 );
B3_ASSERT( ( (uintptr_t)entry.data & ( B3_ALIGNMENT - 1 ) ) == 0 );
}
else
{
entry.data = stack->memory + stack->index;
entry.usedMalloc = false;
stack->index += size32;
stack->index += alignedSize;
B3_ASSERT( ( (uintptr_t)entry.data & 0x1F ) == 0 );
B3_ASSERT( ( (uintptr_t)entry.data & ( B3_ALIGNMENT - 1 ) ) == 0 );
}
stack->allocation += size32;
stack->allocation += alignedSize;
if ( stack->allocation > stack->maxAllocation )
{
stack->maxAllocation = stack->allocation;

View file

@ -20,9 +20,6 @@
#include "box3d/id.h"
#include <stddef.h>
#include <string.h>
_Static_assert( B3_BODY_NAME_LENGTH >= 0, "minimum name length" );
// Get a validated body from a world using an id.
b3Body* b3GetBodyFullId( b3World* world, b3BodyId bodyId )
@ -270,9 +267,6 @@ b3BodyId b3CreateBody( b3WorldId worldId, const b3BodyDef* def )
}
b3Body* body = b3Array_Get( world->bodies, bodyId );
b3StrCpy( body->name, B3_BODY_NAME_LENGTH + 1, def->name );
body->userData = def->userData;
body->setIndex = setId;
body->localIndex = set->bodySims.count - 1;
@ -293,6 +287,7 @@ b3BodyId b3CreateBody( b3WorldId worldId, const b3BodyDef* def )
body->sleepVelocity = 0.0f;
body->mass = 0.0f;
body->inertia = b3Mat3_zero;
body->nameId = b3AddName( &world->names, def->name );
body->type = def->type;
body->flags = bodySim->flags;
@ -935,58 +930,6 @@ void b3UpdateBodyMassData( b3World* world, b3Body* body )
}
}
void b3DumpBody( b3World* world, b3Body* body )
{
// int32 bodyIndex = m_islandIndex;
b3BodySim* sim = b3GetBodySim( world, body );
b3Vec3 p = b3ToVec3( sim->transform.p );
b3Quat q = sim->transform.q;
b3Vec3 v = b3Vec3_zero;
b3Vec3 w = b3Vec3_zero;
b3BodyState* state = b3GetBodyState( world, body );
if ( state != NULL )
{
v = state->linearVelocity;
w = state->angularVelocity;
}
// %.9g is sufficient to save and load the same value using text
// FLT_DECIMAL_DIG == 9
b3Dump( "{\n" );
b3Dump( " b3BodyDef bd = b3DefaultBodyDef();\n" );
if ( body->name[0] != 0 )
{
b3Dump( " bd.name = \"%s\";\n", body->name );
}
b3Dump( " bd.type = b3BodyType(%d);\n", body->type );
b3Dump( " bd.position = {%.9g, %.9g, %.9g};\n", p.x, p.y, p.z );
b3Dump( " bd.rotation = {{%.9g, %.9g, %.9g}, %.9g};\n", q.v.x, q.v.y, q.v.z, q.s );
b3Dump( " bd.linearVelocity = {%.9g, %.9g, %.9g};\n", v.x, v.y, v.z );
b3Dump( " bd.angularVelocity = {%.9g, %.9g, %.9g};\n", w.x, w.y, w.z );
b3Dump( " bd.linearDamping = %.9g;\n", sim->linearDamping );
b3Dump( " bd.angularDamping = %.9g;\n", sim->angularDamping );
b3Dump( " bd.enableSleep = bool(%d);\n", body->flags & b3_enableSleep );
b3Dump( " bd.isAwake = bool(%d);\n", body->setIndex == b3_awakeSet );
b3Dump( " bd.gravityScale = %.9g;\n", sim->gravityScale );
b3Dump( " b3BodyId bodyId = b3CreateBody(m_worldId, &bd);\n" );
b3Dump( " bodies.push_back(bodyId);\n" );
b3Dump( "\n" );
int shapeIndex = body->headShapeId;
while ( shapeIndex != B3_NULL_INDEX )
{
b3Dump( " {\n" );
b3DumpShape( world, shapeIndex );
b3Dump( " }\n" );
b3Shape* shape = b3Array_Get( world->shapes, shapeIndex );
shapeIndex = shape->nextShapeId;
}
b3Dump( "}\n" );
}
b3Pos b3Body_GetPosition( b3BodyId bodyId )
{
b3World* world = b3GetWorld( bodyId.world0 );
@ -1722,14 +1665,14 @@ void b3Body_SetName( b3BodyId bodyId, const char* name )
B3_REC( world, BodySetName, bodyId, name );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3StrCpy( body->name, B3_BODY_NAME_LENGTH + 1, name );
body->nameId = b3AddName( &world->names, name );
}
const char* b3Body_GetName( b3BodyId bodyId )
{
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
return body->name;
return b3FindNameWithDefault( &world->names, body->nameId, "" );
}
void b3Body_SetUserData( b3BodyId bodyId, void* userData )

View file

@ -120,14 +120,13 @@ typedef struct b3Body
// b3BodyFlags
uint32_t flags;
uint32_t nameId;
b3BodyType type;
// This is monotonically advanced when a body is allocated in this slot
// Used to check for invalid b3BodyId
uint16_t generation;
char name[B3_BODY_NAME_LENGTH + 1];
} b3Body;
// Body State
@ -242,7 +241,6 @@ bool b3WakeBodyWithLock( b3World* world, b3Body* body );
void b3UpdateBodyMassData( b3World* world, b3Body* body );
void b3SyncBodyFlags( b3World* world, b3Body* body );
void b3DumpBody( b3World* world, b3Body* body );
// Make a sweep relative to a base position to keep TOI in float precision far from the origin.
static inline b3Sweep b3MakeRelativeSweep( const b3BodySim* bodySim, b3Pos base )

View file

@ -51,13 +51,13 @@ float b3GetLengthUnitsPerMeter( void )
static float b3_stallThreshold = FLT_MAX;
void b3SetStallThreshold(float seconds)
void b3SetStallThreshold( float seconds )
{
B3_ASSERT( b3IsValidFloat( seconds ) && seconds > 0.0f );
b3_stallThreshold = seconds;
}
float b3GetStallThreshold(void)
float b3GetStallThreshold( void )
{
return b3_stallThreshold;
}
@ -138,9 +138,6 @@ void b3SetAllocator( b3AllocFcn* allocFcn, b3FreeFcn* freeFcn )
b3_freeFcn = freeFcn;
}
// Use 64 byte alignment for everything to align to 64 byte cache line and works with 256bit SIMD.
#define B3_ALIGNMENT 64
void* b3Alloc( size_t size )
{
if ( size == 0 )
@ -152,38 +149,38 @@ void* b3Alloc( size_t size )
// todo this is not true, Box3D allocates a lot.
b3AtomicFetchAddInt( &b3_byteCount, (int)size );
// Allocation must be a multiple of 32 or risk a seg fault
// Allocation must be a multiple of B3_ALIGNMENT (required by spec).
// https://en.cppreference.com/w/c/memory/aligned_alloc
int size64 = ( ( (int)size - 1 ) | 0x3F ) + 1;
int alignedSize = ( ( (int)size - 1 ) | ( B3_ALIGNMENT - 1 ) ) + 1;
if ( b3_allocFcn != NULL )
{
void* ptr = b3_allocFcn( size64, B3_ALIGNMENT );
void* ptr = b3_allocFcn( alignedSize, B3_ALIGNMENT );
b3TracyCAlloc( ptr, size );
B3_ASSERT( ptr != NULL );
B3_ASSERT( ( (uintptr_t)ptr & 0x3F ) == 0 );
B3_ASSERT( ( (uintptr_t)ptr & ( B3_ALIGNMENT - 1 ) ) == 0 );
return ptr;
}
#ifdef B3_PLATFORM_WINDOWS
void* ptr = _aligned_malloc( size64, B3_ALIGNMENT );
void* ptr = _aligned_malloc( alignedSize, B3_ALIGNMENT );
#elif defined( B3_PLATFORM_ANDROID )
void* ptr = NULL;
if ( posix_memalign( &ptr, B3_ALIGNMENT, size64 ) != 0 )
if ( posix_memalign( &ptr, B3_ALIGNMENT, alignedSize ) != 0 )
{
// allocation failed, exit the application
exit( EXIT_FAILURE );
}
#else
void* ptr = aligned_alloc( B3_ALIGNMENT, size64 );
void* ptr = aligned_alloc( B3_ALIGNMENT, alignedSize );
#endif
b3TracyCAlloc( ptr, size );
B3_ASSERT( ptr != NULL );
B3_ASSERT( ( (uintptr_t)ptr & 0x3F ) == 0 );
B3_ASSERT( ( (uintptr_t)ptr & ( B3_ALIGNMENT - 1 ) ) == 0 );
return ptr;
}
@ -215,8 +212,6 @@ void b3Free( void* mem, size_t size )
void* b3GrowAlloc( void* oldMem, int oldSize, int newSize )
{
// todo try _aligned_realloc
B3_ASSERT( newSize > oldSize );
void* newMem = b3Alloc( newSize );
if ( oldSize > 0 )
@ -239,63 +234,8 @@ void* b3AllocZeroed( size_t size )
return mem;
}
static FILE* b3OpenFile( const char* fileName, const char* mode )
{
FILE* file = NULL;
#if defined( _MSC_VER )
errno_t e = fopen_s( &file, fileName, mode );
if ( e != 0 )
{
return NULL;
}
#else
file = fopen( fileName, mode );
if ( file == NULL )
{
return NULL;
}
#endif
return file;
}
FILE* b3_dumpFile = NULL;
int b3_meshIndex = 0;
void b3OpenDump( const char* fileName )
{
B3_ASSERT( b3_dumpFile == NULL );
b3_dumpFile = b3OpenFile( fileName, "w" );
}
void b3Dump( const char* string, ... )
{
if ( b3_dumpFile == NULL )
{
return;
}
va_list args;
va_start( args, string );
vfprintf( b3_dumpFile, string, args );
va_end( args );
}
void b3CloseDump( void )
{
fclose( b3_dumpFile );
b3_dumpFile = NULL;
}
int b3FetchAddMeshDumpIndex( void )
{
int result = b3_meshIndex;
b3_meshIndex += 1;
return result;
}
void b3StrCpy(char* dst, int size, const char* src)
// Not used. Keeping around in case I need this.
void b3StrCpy( char* dst, int size, const char* src )
{
B3_ASSERT( size > 0 );
@ -313,74 +253,3 @@ void b3StrCpy(char* dst, int size, const char* src)
memset( dst, 0, size );
}
}
void b3WriteBinaryFile( void* data, int size, const char* fileName )
{
if ( data == NULL || size <= 0 || fileName == NULL )
{
return;
}
FILE* file = b3OpenFile( fileName, "wb" );
if ( file == NULL )
{
return;
}
// Write binary blob; ignore partial-write errors for simplicity
(void)fwrite( data, 1, (size_t)size, file );
fclose( file );
}
void* b3ReadBinaryFile( const char* prefix, const char* fileName, int* memSize )
{
*memSize = 0;
if ( prefix == NULL || fileName == NULL )
{
return NULL;
}
char buffer[128];
snprintf( buffer, sizeof( buffer ), "%s%s", prefix, fileName );
FILE* file = b3OpenFile( buffer, "rb" );
if ( file == NULL )
{
return NULL;
}
// Determine file size
if ( fseek( file, 0, SEEK_END ) != 0 )
{
fclose( file );
return NULL;
}
long size = ftell( file );
if ( size <= 0 )
{
fclose( file );
return NULL;
}
// Rewind
if ( fseek( file, 0, SEEK_SET ) != 0 )
{
fclose( file );
return NULL;
}
void* data = b3Alloc( (size_t)size );
size_t readCount = fread( data, 1, (size_t)size, file );
fclose( file );
if ( readCount != (size_t)size )
{
b3Free( data, (size_t)size );
return NULL;
}
*memSize = (int)size;
return data;
}

View file

@ -108,6 +108,9 @@ typedef struct b3AtomicU32
uint32_t value;
} b3AtomicU32;
// Minimum memory alignment used for all allocations
#define B3_ALIGNMENT 16
// Returns the number of elements of an array
#define B3_ARRAY_COUNT( A ) (int)( sizeof( A ) / sizeof( A[0] ) )
@ -155,10 +158,4 @@ typedef struct b3Thread b3Thread;
b3Thread* b3CreateThread( b3ThreadFunction* function, void* context, const char* name );
void b3JoinThread( b3Thread* t );
// Dump to a file. Only one dump file allowed at a time.
void b3OpenDump( const char* fileName );
void b3Dump( const char* string, ... );
void b3CloseDump( void );
int b3FetchAddMeshDumpIndex( void );
void b3StrCpy( char* dst, int size, const char* src );

View file

@ -62,9 +62,6 @@ b3DynamicTree b3DynamicTree_Create( int proxyCapacity )
tree.nodes = (b3TreeNode*)b3Alloc( tree.nodeCapacity * sizeof( b3TreeNode ) );
// Better to have 64 byte alignment
B3_VALIDATE( ( (uintptr_t)tree.nodes & 0x3F ) == 0 );
memset( tree.nodes, 0, tree.nodeCapacity * sizeof( b3TreeNode ) );
// Build a linked list for the free list.

155
src/name_cache.c Normal file
View file

@ -0,0 +1,155 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#include "name_cache.h"
#include "recording.h"
#include <string.h>
#define NAME b3NameMap
#define KEY_TY uint32_t
#define VAL_TY int
#define HASH_FN vt_hash_integer
#define CMPR_FN vt_cmpr_integer
#define MALLOC_FN b3Alloc
#define FREE_FN b3Free
#include "verstable.h"
#define FNV32_OFFSET_BASIS 0x811c9dc5u
#define FNV32_PRIME 0x01000193u
// This is designed to hash small strings and while avoiding collisions
// for a 32-bit hash.
// Note: changing this will break recordings
uint32_t b3Hash32( const void* data, size_t length )
{
// Cast to unsigned to avoid sign extension
const unsigned char* p = data;
// FNV-1a
uint32_t h = FNV32_OFFSET_BASIS;
for ( size_t i = 0; i < length; ++i )
{
h ^= p[i];
h *= FNV32_PRIME;
}
// Murmur3 finalizer to help with short strings
h ^= h >> 16;
h *= 0x85ebca6bu;
h ^= h >> 13;
h *= 0xc2b2ae35u;
h ^= h >> 16;
return h;
}
b3NameCache b3CreateNameCache( void )
{
b3NameCache cache = { 0 };
b3Array_Create( cache.entries );
b3NameMap* map = b3Alloc( sizeof( b3NameMap ) );
b3NameMap_init( map );
cache.map = map;
return cache;
}
void b3DestroyNameCache( b3NameCache* cache )
{
int count = cache->entries.count;
for ( int i = 0; i < count; ++i )
{
b3NameEntry* entry = cache->entries.data + i;
b3Free( entry->name, entry->length + 1 );
}
b3Array_Destroy( cache->entries );
b3NameMap_cleanup( (b3NameMap*)cache->map );
b3Free( cache->map, sizeof( b3NameMap ) );
}
uint32_t b3AddName( b3NameCache* cache, const char* name )
{
if ( name == NULL || name[0] == 0 )
{
return B3_NULL_NAME;
}
size_t length = strlen( name );
uint32_t id = b3Hash32( name, length );
id = id == 0 ? 1 : id;
b3NameMap* map = cache->map;
b3NameMap_itr itr = b3NameMap_get( map, id );
if ( b3NameMap_is_end( itr ) == false )
{
if ( strcmp( cache->entries.data[itr.data->val].name, name ) != 0 )
{
// Different name, same hash
b3Log( "Hash collision on %s", name );
}
return id;
}
char* clone = b3Alloc( length + 1 );
memcpy( clone, name, length + 1 );
int index = cache->entries.count;
b3NameEntry entry = {
.hash = id,
.name = clone,
.length = (int)length,
};
b3Array_Push( cache->entries, entry );
b3NameMap_insert( map, id, index );
return id;
}
const char* b3FindName( const b3NameCache* cache, uint32_t id )
{
b3NameMap* map = cache->map;
b3NameMap_itr itr = b3NameMap_get( map, id );
if ( b3NameMap_is_end( itr ) == false )
{
int index = itr.data->val;
const b3NameEntry* entry = b3Array_Get( cache->entries, index );
return entry->name;
}
return NULL;
}
void b3LoadName( b3NameCache* cache, uint32_t id, char* name, int length )
{
if ( name == NULL )
{
return;
}
if ( name[0] == 0 || id == B3_NULL_NAME )
{
b3Free( name, length + 1 );
return;
}
b3NameMap* map = cache->map;
b3NameMap_itr itr = b3NameMap_get( map, id );
if ( b3NameMap_is_end( itr ) == false )
{
b3Free( name, length + 1 );
return;
}
int index = cache->entries.count;
b3NameEntry entry = {
.hash = id,
.name = name,
.length = length,
};
b3Array_Push( cache->entries, entry );
b3NameMap_insert( map, id, index );
}

42
src/name_cache.h Normal file
View file

@ -0,0 +1,42 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "container.h"
#define B3_NULL_NAME 0u
typedef struct b3NameEntry
{
// Names are used for debugging and I'm favoring simplicity and
// minimal storage. Collisions will be logged.
uint32_t hash;
int length;
char* name;
} b3NameEntry;
b3DeclareArray( b3NameEntry );
typedef struct b3NameCache
{
b3Array( b3NameEntry ) entries;
void* map;
} b3NameCache;
b3NameCache b3CreateNameCache( void );
void b3DestroyNameCache( b3NameCache* cache );
uint32_t b3AddName( b3NameCache* cache, const char* name );
const char* b3FindName( const b3NameCache* cache, uint32_t id );
// Load a name from a recording. Name ownership is transferred.
void b3LoadName( b3NameCache* cache, uint32_t id, char* name, int length );
uint32_t b3Hash32( const void* data, size_t length );
static inline const char* b3FindNameWithDefault( const b3NameCache* cache, uint32_t id, const char* def )
{
const char* name = b3FindName( cache, id );
return name == NULL ? def : name;
}

View file

@ -27,6 +27,7 @@
#include "box3d/constants.h"
#include <float.h>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
@ -290,6 +291,8 @@ b3WorldId b3CreateWorld( const b3WorldDef* def )
world->hullDatabase = b3Alloc( sizeof( b3HullMap ) );
b3HullMap_init( world->hullDatabase );
world->names = b3CreateNameCache();
world->contactIdPool = b3CreateIdPool();
b3Array_Reserve( world->contacts, b3MaxInt( 16, def->capacity.contactCount ) );
@ -473,6 +476,8 @@ void b3DestroyWorld( b3WorldId worldId )
b3Free( world->hullDatabase, sizeof( b3HullMap ) );
world->hullDatabase = NULL;
b3DestroyNameCache( &world->names );
b3Array_Destroy( world->shapes );
b3Array_Destroy( world->contacts );
b3Array_Destroy( world->joints );
@ -1413,12 +1418,16 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
b3Body* body = b3Array_Get( world->bodies, bodyId );
b3BodySim* bodySim = b3GetBodySim( world, body );
if ( draw->drawBodyNames && body->name[0] != 0 )
if ( draw->drawBodyNames && body->nameId != B3_NULL_NAME )
{
b3Vec3 offset = { 0.05f, 0.05f, 0.05f };
b3WorldTransform transform = { bodySim->center, bodySim->transform.q };
b3Pos p = b3TransformWorldPoint( transform, offset );
draw->DrawStringFcn( p, body->name, b3_colorOrange, draw->context );
const char* name = b3FindName( &world->names, body->nameId );
if ( name != NULL )
{
draw->DrawStringFcn( p, name, b3_colorOrange, draw->context );
}
}
if ( draw->drawMass && body->type == b3_dynamicBody )
@ -2305,23 +2314,6 @@ void b3World_StopRecording( b3WorldId worldId )
b3StopRecordingInternal( world );
}
static FILE* b3OpenFile( const char* fileName )
{
FILE* file = NULL;
#if defined( _MSC_VER )
errno_t e = fopen_s( &file, fileName, "w" );
if ( e != 0 )
{
return NULL;
}
#else
file = fopen( fileName, "w" );
#endif
return file;
}
void b3World_DumpMemoryStats( b3WorldId worldId )
{
b3World* world = b3GetUnlockedWorldFromId( worldId );
@ -2409,8 +2401,8 @@ void b3World_DumpMemoryStats( b3WorldId worldId )
total += hullMapBytes + hullDataBytes;
b3Log( "hulls" );
b3Log( "database: %llu (%d, %d)", (unsigned long long)hullMapBytes, hullCount, hullBucketCount );
b3Log( "hull data: %llu", (unsigned long long)hullDataBytes );
b3Log( "database: %d (%d, %d)", (int)hullMapBytes, hullCount, hullBucketCount );
b3Log( "hull data: %d", (int)hullDataBytes );
// broad-phase
int staticTreeBytes = b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_staticBody );
@ -2557,44 +2549,7 @@ void b3World_DumpMemoryStats( b3WorldId worldId )
total += world->stack.capacity;
b3Log( "stack allocator: %d", world->stack.capacity );
b3Log( "total: %llu", (unsigned long long)total );
}
void b3World_DumpShapeBounds( b3WorldId worldId, b3BodyType type )
{
B3_ASSERT( b3_staticBody <= type && type <= b3_dynamicBody );
b3World* world = b3GetUnlockedWorldFromId( worldId );
if ( world == NULL )
{
return;
}
FILE* file = b3OpenFile( "box3d_bounds.txt" );
if ( file == NULL )
{
return;
}
b3DynamicTree* tree = world->broadPhase.trees + type;
b3TreeNode* nodes = tree->nodes;
uint16_t requiredFlags = b3_allocatedNode | b3_leafNode;
int capacity = tree->nodeCapacity;
for ( int i = 0; i < capacity; ++i )
{
b3TreeNode* node = nodes + i;
if ( ( node->flags & requiredFlags ) != requiredFlags )
{
// skip internal and free nodes
continue;
}
b3Vec3 a = node->aabb.lowerBound;
b3Vec3 b = node->aabb.upperBound;
fprintf( file, "%.9f %.9f %.9f %.9f %.9f %.9f\n", a.x, a.y, a.z, b.x, b.y, b.z );
}
fclose( file );
b3Log( "total: %u KB", (uint32_t)( total / 1024 ) );
}
typedef struct WorldQueryContext
@ -4142,123 +4097,3 @@ void b3ValidateContacts( b3World* world )
}
#endif
#define NAME int_set
#define KEY_TY int
#define MALLOC_FN b3Alloc
#define FREE_FN b3Free
#define HASH_FN vt_hash_integer
#define CMPR_FN vt_cmpr_integer
#include "verstable.h"
void b3World_DumpAwake( b3WorldId worldId )
{
b3World* world = b3GetWorldFromId( worldId );
if ( world->locked == true )
{
return;
}
b3OpenDump( "box3d_dump.inl" );
b3Vec3 g = world->gravity;
b3Dump( "b3Vec3 gravity = {%.9g, %.9g, %.9g};\n", g.x, g.y, g.z );
b3Dump( "b3World_SetGravity(m_worldId, gravity);\n" );
b3Dump( "std::vector<b3BodyId> bodies;\n" );
b3Dump( "std::vector<b3JointId> joints;\n\n" );
int_set staticBodies;
int_set_init( &staticBodies );
b3Body* bodies = world->bodies.data;
for ( int i = 0; i < world->bodies.count; ++i )
{
b3Body* body = bodies + i;
if ( body->id == B3_NULL_INDEX )
{
continue;
}
if ( body->setIndex != b3_awakeSet )
{
continue;
}
b3DumpBody( world, body );
// Gather
int edgeKey = body->headContactKey;
while ( edgeKey != B3_NULL_INDEX )
{
int contactId = edgeKey >> 1;
int edgeIndex = edgeKey & 1;
b3Contact* contact = b3Array_Get( world->contacts, contactId );
edgeKey = contact->edges[edgeIndex].nextKey;
if ( ( contact->flags & b3_contactTouchingFlag ) == 0 )
{
continue;
}
int otherIndex = 1 - edgeIndex;
b3Body* otherBody = b3Array_Get( world->bodies, contact->edges[otherIndex].bodyId );
if ( otherBody->setIndex == b3_staticSet )
{
(void)int_set_insert( &staticBodies, otherBody->id );
}
}
}
// Dump the bodies that are touching
for ( int_set_itr itr = int_set_first( &staticBodies ); int_set_is_end( itr ) == false; itr = int_set_next( itr ) )
{
b3Body* body = b3Array_Get( world->bodies, itr.data->key );
b3DumpBody( world, body );
}
int_set_cleanup( &staticBodies );
b3CloseDump();
}
void b3World_Dump( b3WorldId worldId )
{
b3World* world = b3GetWorldFromId( worldId );
if ( world->locked == true )
{
return;
}
b3OpenDump( "box3d_dump.inl" );
b3Vec3 g = world->gravity;
b3Dump( "b3Vec3 gravity = {%.9g, %.9g, %.9g};\n", g.x, g.y, g.z );
b3Dump( "b3World_SetGravity(m_worldId, gravity);\n" );
b3Dump( "std::vector<b3BodyId> bodies;\n" );
b3Dump( "std::vector<b3JointId> joints;\n\n" );
b3Body* bodies = world->bodies.data;
for ( int i = 0; i < world->bodies.count; ++i )
{
b3Body* body = bodies + i;
if ( body->id == B3_NULL_INDEX )
{
continue;
}
if ( body->setIndex != b3_awakeSet )
{
continue;
}
b3DumpBody( world, body );
}
b3CloseDump();
}

View file

@ -9,6 +9,7 @@
#include "broad_phase.h"
#include "constraint_graph.h"
#include "id_pool.h"
#include "name_cache.h"
#include "box3d/types.h"
@ -181,6 +182,9 @@ typedef struct b3World
// type into this header.
void* hullDatabase;
// Name cache for shape and body names. This works with recording.
b3NameCache names;
// This is a dense array of sensor data.
b3Array( b3Sensor ) sensors;
@ -258,6 +262,10 @@ typedef struct b3World
void* userData;
// Non-NULL while a recording session is active. Set by b3World_StartRecording,
// cleared by b3World_StopRecording. Hooks in mutators check this before writing.
struct b3Recording* recording;
// latest inverse sub-step
float inv_h;
@ -274,11 +282,6 @@ typedef struct b3World
// This indicates there is a world write operation in progress. This is for debugging and
// not a real mutex. This should have minimal performance impact.
bool locked;
// Non-NULL while a recording session is active. Set by b3World_StartRecording,
// cleared by b3World_StopRecording. Hooks in mutators check this before writing.
struct b3Recording* recording;
bool enableWarmStarting;
bool enableContinuous;
bool enableSpeculative;

View file

@ -308,16 +308,6 @@ static void b3RecW_STR( b3RecBuffer* buf, const char* s )
}
}
void b3RecW_BODYSTR( b3RecBuffer* buf, const char* s )
{
b3RecW_STR( buf, s );
}
void b3RecW_SHAPESTR( b3RecBuffer* buf, const char* s )
{
b3RecW_STR( buf, s );
}
// Hand-written def helpers. Zero pointer and cookie fields before serializing.
// Readers call b3Default*Def() first to get the cookie, then overwrite fields.
@ -950,12 +940,12 @@ void b3RecInternTag( b3Recording* rec, uint64_t key, uint64_t id, const char* na
tag->key = key;
tag->id = id;
int n = 0;
while ( name != NULL && name[n] != '\0' && n < B3_BODY_NAME_LENGTH )
while ( name != NULL && name[n] != '\0' && n < B3_MAX_QUERY_NAME_LENGTH )
{
tag->name[n] = name[n];
tag->queryName[n] = name[n];
n++;
}
tag->name[n] = '\0';
tag->queryName[n] = '\0';
b3RecTagMap_insert( map, key, index );
}
@ -978,7 +968,7 @@ void b3RecWriteRegistry( b3Recording* rec )
{
b3RecW_U64( &rec->buffer, rec->tags[i].key );
b3RecW_U64( &rec->buffer, rec->tags[i].id );
b3RecW_STR( &rec->buffer, rec->tags[i].name );
b3RecW_STR( &rec->buffer, rec->tags[i].queryName );
}
}

View file

@ -46,12 +46,12 @@ typedef struct b3World b3World;
#define B3_REC_MAGIC 0x43523342u
// Major recording version is bumped when writers change.
// Major version 3 added shape names
// Major version 3 added shape names.
#define B3_REC_VERSION_MAJOR 3
// Minor tracks op-stream additions that keep the 48 byte header shape.
// Minor version 2 added the QueryTag op and the interned query-tag table at the tail of the registry block.
#define B3_REC_VERSION_MINOR 2
// Minor version 3 added name cache.
#define B3_REC_VERSION_MINOR 3
// File header, fixed 48 bytes, little-endian. Contains the registry locator so the player
// can load geometry before replaying any ops.
@ -116,14 +116,19 @@ typedef struct b3GeometryRegistry
void* dedupMap;
} b3GeometryRegistry;
// Limit the maximum query name length to make recording simpler. Query names longer than this
// probably indicate a bug in user code.
#define B3_MAX_QUERY_NAME_LENGTH 64
// Query tag from b3QueryFilter.
// Stored once per key in the trailing block so a tagged query carries only the 8 byte key on the wire.
// Shared by the recorder (accumulate) and the player (load).
typedef struct b3RecTag
{
uint64_t key; // hash of (id, name)
uint64_t id; // entity/actor id
char name[B3_BODY_NAME_LENGTH + 1]; // query label
// hash of (id, queryName)
uint64_t key;
uint64_t id;
char queryName[B3_MAX_QUERY_NAME_LENGTH + 1];
} b3RecTag;
// User-owned recording buffer. The world appends into it while active; the host saves and
@ -173,8 +178,7 @@ typedef b3Filter b3RecCType_FILTER;
typedef b3SurfaceMaterial b3RecCType_MATERIAL;
typedef b3MassData b3RecCType_MASSDATA;
typedef b3MotionLocks b3RecCType_LOCKS;
typedef const char* b3RecCType_BODYSTR;
typedef const char* b3RecCType_SHAPESTR;
typedef const char* b3RecCType_STR;
typedef b3WorldId b3RecCType_WORLDID;
typedef b3BodyId b3RecCType_BODYID;
typedef b3ShapeId b3RecCType_SHAPEID;
@ -249,8 +253,6 @@ void b3RecW_FILTER( b3RecBuffer* buf, b3Filter v );
void b3RecW_MATERIAL( b3RecBuffer* buf, b3SurfaceMaterial v );
void b3RecW_MASSDATA( b3RecBuffer* buf, b3MassData v );
void b3RecW_LOCKS( b3RecBuffer* buf, b3MotionLocks v );
void b3RecW_BODYSTR( b3RecBuffer* buf, const char* s );
void b3RecW_SHAPESTR( b3RecBuffer* buf, const char* s );
void b3RecW_EXPLOSIONDEF( b3RecBuffer* buf, b3ExplosionDef v );
void b3RecW_BODYDEF( b3RecBuffer* buf, b3BodyDef v );
void b3RecW_SHAPEDEF( b3RecBuffer* buf, b3ShapeDef v );
@ -361,7 +363,6 @@ void b3RecWriteRegistry( b3Recording* rec );
uint64_t b3HashQueryTag( uint64_t id, const char* name );
// Record a key->(id, name) mapping once, deduped by key (a repeated key keeps its first id/name).
// The name is clamped to B3_BODY_NAME_LENGTH.
void b3RecInternTag( b3Recording* rec, uint64_t key, uint64_t id, const char* name );
// Intern each large geometry kind and return a stable u32 id for use in create ops.

View file

@ -45,7 +45,7 @@ B3_REC_OP( 0x11, DestroyBody, RET_NONE, ARG( BODYID, body ) )
B3_REC_OP( 0x20, BodySetTransform, RET_NONE, ARG( BODYID, body ) ARG( POSITION, position ) ARG( QUAT, rotation ) )
B3_REC_OP( 0x21, BodySetLinearVelocity, RET_NONE, ARG( BODYID, body ) ARG( VEC3, v ) )
B3_REC_OP( 0x22, BodySetType, RET_NONE, ARG( BODYID, body ) ARG( I32, type ) )
B3_REC_OP( 0x23, BodySetName, RET_NONE, ARG( BODYID, body ) ARG( BODYSTR, name ) )
B3_REC_OP( 0x23, BodySetName, RET_NONE, ARG( BODYID, body ) ARG( STR, name ) )
B3_REC_OP( 0x24, BodySetAngularVelocity, RET_NONE, ARG( BODYID, body ) ARG( VEC3, w ) )
B3_REC_OP( 0x25, BodySetTargetTransform, RET_NONE, ARG( BODYID, body ) ARG( WORLDXF, target ) ARG( F32, timeStep ) ARG( BOOL, wake ) )
B3_REC_OP( 0x26, BodyApplyForce, RET_NONE, ARG( BODYID, body ) ARG( VEC3, force ) ARG( POSITION, point ) ARG( BOOL, wake ) )
@ -92,7 +92,7 @@ B3_REC_OP( 0x59, ShapeSetSphere, RET_NONE, ARG( SHAPEID, shape ) ARG( SPHERE, sp
B3_REC_OP( 0x5A, ShapeSetCapsule, RET_NONE, ARG( SHAPEID, shape ) ARG( CAPSULE, capsule ) )
B3_REC_OP( 0x5B, ShapeApplyWind, RET_NONE,
ARG( SHAPEID, shape ) ARG( VEC3, wind ) ARG( F32, drag ) ARG( F32, lift ) ARG( F32, maxSpeed ) ARG( BOOL, wake ) )
B3_REC_OP( 0x5C, ShapeSetName, RET_NONE, ARG( SHAPEID, shape ) ARG( SHAPESTR, name ) )
B3_REC_OP( 0x5C, ShapeSetName, RET_NONE, ARG( SHAPEID, shape ) ARG( STR, name ) )
// Joint create and destroy
B3_REC_OP( 0x90, CreateParallelJoint, RET_JOINTID, ARG( WORLDID, world ) ARG( PARALLELJOINTDEF, def ) )

View file

@ -14,6 +14,7 @@
#include "box3d/box3d.h"
#include <inttypes.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
@ -373,10 +374,10 @@ b3MotionLocks b3RecR_LOCKS( b3RecReader* rdr )
}
// Rotating set of static string buffers, valid until the next 4 STR reads.
const char* b3RecR_BODYSTR( b3RecReader* rdr )
const char* b3RecR_STR( b3RecReader* rdr )
{
char* buf = rdr->bodyStrBufs[rdr->bodyStrNext];
rdr->bodyStrNext = ( rdr->bodyStrNext + 1 ) & 3;
char* buf = rdr->stringBuffers[rdr->nextString];
rdr->nextString = ( rdr->nextString + 1 ) & 3;
uint16_t len = b3RecR_U16( rdr );
if ( len == 0xFFFFu )
@ -385,35 +386,9 @@ const char* b3RecR_BODYSTR( b3RecReader* rdr )
}
int n = (int)len;
if ( n > B3_BODY_NAME_LENGTH )
if ( n > B3_MAX_NAME_LENGTH )
{
n = B3_BODY_NAME_LENGTH;
}
b3RecRdrCheck( rdr, (int)len );
if ( rdr->ok && n > 0 )
{
memcpy( buf, rdr->data + rdr->cursor, (size_t)n );
}
rdr->cursor += (int)len;
buf[n] = '\0';
return buf;
}
const char* b3RecR_SHAPESTR( b3RecReader* rdr )
{
char* buf = rdr->shapeStrBufs[rdr->shapeStrNext];
rdr->shapeStrNext = ( rdr->shapeStrNext + 1 ) & 3;
uint16_t len = b3RecR_U16( rdr );
if ( len == 0xFFFFu )
{
return NULL;
}
int n = (int)len;
if ( n > B3_SHAPE_NAME_LENGTH )
{
n = B3_SHAPE_NAME_LENGTH;
n = B3_MAX_NAME_LENGTH;
}
b3RecRdrCheck( rdr, (int)len );
if ( rdr->ok && n > 0 )
@ -451,7 +426,7 @@ b3BodyDef b3RecR_BODYDEF( b3RecReader* rdr )
def.angularDamping = b3RecR_F32( rdr );
def.gravityScale = b3RecR_F32( rdr );
def.sleepThreshold = b3RecR_F32( rdr );
def.name = b3RecR_BODYSTR( rdr );
def.name = b3RecR_STR( rdr );
(void)b3RecR_U64( rdr ); // userData placeholder
def.motionLocks = b3RecR_LOCKS( rdr );
def.enableSleep = b3RecR_BOOL( rdr );
@ -468,7 +443,7 @@ b3ShapeDef b3RecR_SHAPEDEF( b3RecReader* rdr )
{
b3ShapeDef def = b3DefaultShapeDef();
def.name = b3RecR_SHAPESTR( rdr );
def.name = b3RecR_STR( rdr );
(void)b3RecR_U64( rdr ); // userData placeholder
int matCount = b3RecR_I32( rdr );
@ -1664,8 +1639,7 @@ static void b3RecDispatch_StateHash( const b3RecArgs_StateHash* a, b3RecReader*
uint64_t computed = b3HashWorldState( world );
if ( computed != a->hash )
{
printf( "b3ReplayFile: StateHash mismatch (recorded=0x%llX, computed=0x%llX)\n", (unsigned long long)a->hash,
(unsigned long long)computed );
printf( "b3ReplayFile: StateHash mismatch (recorded=0x%" PRIx64 ", computed=0x%" PRIx64 ")\n", a->hash, computed );
rdr->diverged = true;
}
}
@ -2366,14 +2340,14 @@ static void b3RecLoadTags( b3RecReader* rdr, const uint8_t* rp, const uint8_t* d
{
break;
}
int n = len > B3_BODY_NAME_LENGTH ? B3_BODY_NAME_LENGTH : (int)len;
int n = len > B3_MAX_QUERY_NAME_LENGTH ? B3_MAX_QUERY_NAME_LENGTH : (int)len;
tags[loaded].key = key;
tags[loaded].id = id;
if ( n > 0 )
{
memcpy( tags[loaded].name, sub.data + sub.cursor, (size_t)n );
memcpy( tags[loaded].queryName, sub.data + sub.cursor, (size_t)n );
}
tags[loaded].name[n] = '\0';
tags[loaded].queryName[n] = '\0';
sub.cursor += len;
b3RecTagLookup_insert( map, key, loaded );
loaded += 1;
@ -2767,10 +2741,10 @@ b3RecPlayer* b3RecPlayer_Create( const void* data, int size, int workerCount )
int registryEnd = (int)registryEnd64;
// Own a private copy so the caller can free their buffer right away.
uint8_t* copy = (uint8_t*)b3Alloc( (size_t)size );
uint8_t* copy = b3Alloc( (size_t)size );
memcpy( copy, data, (size_t)size );
b3RecPlayer* player = (b3RecPlayer*)b3Alloc( sizeof( b3RecPlayer ) );
b3RecPlayer* player = b3Alloc( sizeof( b3RecPlayer ) );
memset( player, 0, sizeof( b3RecPlayer ) );
player->data = copy;
@ -3133,12 +3107,13 @@ void b3RecPlayer_Restart( b3RecPlayer* player )
void b3RecPlayer_SeekFrame( b3RecPlayer* player, int targetFrame )
{
player->atPreStep = false;
if ( player == NULL )
{
return;
}
player->atPreStep = false;
if ( targetFrame < 0 )
{
targetFrame = 0;
@ -3518,22 +3493,22 @@ void b3RecPlayer_DrawFrameQueries( b3RecPlayer* player, b3DebugDraw* draw, int q
if ( b3RecTagLookup_is_end( it ) == false )
{
const b3RecTag* tag = &player->rdr.tags[it.data->val];
name = tag->name;
name = tag->queryName;
id = tag->id;
}
}
char label[64];
if ( name != NULL && name[0] != '\0' && id != 0 )
{
snprintf( label, sizeof( label ), "%s (%llu)", name, (unsigned long long)id );
snprintf( label, sizeof( label ), "%.40s (%" PRIu64 ")", name, id );
}
else if ( name != NULL && name[0] != '\0' )
{
snprintf( label, sizeof( label ), "%s", name );
snprintf( label, sizeof( label ), "%.40s", name );
}
else
{
snprintf( label, sizeof( label ), "#%llu", (unsigned long long)id );
snprintf( label, sizeof( label ), "#%" PRIu64, id );
}
b3Pos labelPos = q->origin;
if ( q->kind == B3_RECQ_OVERLAP_AABB )
@ -3589,7 +3564,7 @@ b3RecQueryInfo b3RecPlayer_GetFrameQuery( const b3RecPlayer* player, int index )
const b3RecTag* tag = &player->rdr.tags[it.data->val];
info.id = tag->id;
// An id-only tag interns an empty name; report it as none so the viewer shows the id alone.
info.name = tag->name[0] != '\0' ? tag->name : NULL;
info.name = tag->queryName[0] != '\0' ? tag->queryName : NULL;
}
}
return info;

View file

@ -72,6 +72,10 @@ typedef struct b3RegistrySlot
void* live; // reconstructed live object, freed after b3DestroyWorld
} b3RegistrySlot;
// This is used to simplify the scratch buffer lifetime. Names longer than this probably
// indicate a bug.
#define B3_MAX_NAME_LENGTH 256
// Reader state threaded through the replay loop and all dispatch functions
typedef struct b3RecReader
{
@ -90,12 +94,9 @@ typedef struct b3RecReader
b3SurfaceMaterial* matScratch;
int matScratchCap;
// Scratch for string reads: rotating slots, valid until the next 4 STR reads
char bodyStrBufs[4][B3_BODY_NAME_LENGTH + 1];
int bodyStrNext;
char shapeStrBufs[4][B3_SHAPE_NAME_LENGTH + 1];
int shapeStrNext;
// Scratch for string reads. Used by b3RecR_STR to pass names to b3BodyDef and b3ShapeDef.
char stringBuffers[4][B3_MAX_NAME_LENGTH + 1];
int nextString;
// Preloaded geometry registry
b3RegistrySlot* slots;
@ -137,7 +138,7 @@ typedef struct b3RecKeyframe
int bodyIdCount;
} b3RecKeyframe;
struct b3RecPlayer
typedef struct b3RecPlayer
{
uint8_t* data; // owned copy of recording bytes
int size;
@ -203,7 +204,7 @@ struct b3RecPlayer
// Pre-populated recording used by b3SerializeWorld during keyframe capture.
// Its registry mirrors rdr.slots so geometry ids stay stable.
b3Recording* keyframeRec;
};
} b3RecPlayer;
// Read primitives
uint8_t b3RecR_U8( b3RecReader* rdr );
@ -233,8 +234,7 @@ b3Filter b3RecR_FILTER( b3RecReader* rdr );
b3SurfaceMaterial b3RecR_MATERIAL( b3RecReader* rdr );
b3MassData b3RecR_MASSDATA( b3RecReader* rdr );
b3MotionLocks b3RecR_LOCKS( b3RecReader* rdr );
const char* b3RecR_BODYSTR( b3RecReader* rdr );
const char* b3RecR_SHAPESTR( b3RecReader* rdr );
const char* b3RecR_STR( b3RecReader* rdr );
b3ExplosionDef b3RecR_EXPLOSIONDEF( b3RecReader* rdr );
b3BodyDef b3RecR_BODYDEF( b3RecReader* rdr );
b3ShapeDef b3RecR_SHAPEDEF( b3RecReader* rdr );

View file

@ -16,11 +16,6 @@
#include "box3d/box3d.h"
#include <inttypes.h>
#include <stdio.h>
_Static_assert( B3_SHAPE_NAME_LENGTH >= 0, "minimum name length" );
static b3Shape* b3GetShape( b3World* world, b3ShapeId shapeId )
{
int id = shapeId.index1 - 1;
@ -191,10 +186,9 @@ static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3WorldTran
shape->aabbMargin = b3ComputeShapeMargin( shape );
shape->aabb = (b3AABB){ b3Vec3_zero, b3Vec3_zero };
shape->fatAABB = (b3AABB){ b3Vec3_zero, b3Vec3_zero };
shape->nameId = b3AddName( &world->names, def->name );
shape->generation += 1;
b3StrCpy( shape->name, B3_SHAPE_NAME_LENGTH + 1, def->name );
if ( shape->type == b3_compoundShape )
{
// Own a copy of the compound materials so every shape frees its array the same way. Compounds
@ -1144,14 +1138,14 @@ void b3Shape_SetName( b3ShapeId shapeId, const char* name )
B3_REC( world, ShapeSetName, shapeId, name );
b3Shape* shape = b3GetShape( world, shapeId );
b3StrCpy( shape->name, B3_SHAPE_NAME_LENGTH + 1, name );
shape->nameId = b3AddName( &world->names, name );
}
const char* b3Shape_GetName( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
return shape->name;
return b3FindNameWithDefault( &world->names, shape->nameId, "" );
}
bool b3Shape_IsSensor( b3ShapeId shapeId )
@ -2396,100 +2390,3 @@ uint64_t b3GetShapeUserMaterialId( const b3Shape* shape, int childIndex, int tri
materialIndex = b3ClampInt( materialIndex, 0, shape->materialCount - 1 );
return b3GetShapeMaterials( shape )[materialIndex].userMaterialId;
}
void b3DumpShape( b3World* world, int shapeIndex )
{
b3Shape* shape = b3Array_Get( world->shapes, shapeIndex );
b3Dump( " b3ShapeDef sd = b3DefaultShapeDef();\n" );
// printf("%" PRIx64 ";\n", t);
b3Dump( " sd.density = %.9g;\n", shape->density );
b3Dump( " sd.isSensor = bool(%d);\n", shape->sensorIndex != B3_NULL_INDEX );
b3Dump( " sd.filter.categoryBits = 0x%" PRIx64 ";\n", shape->filter.categoryBits );
b3Dump( " sd.filter.maskBits = 0x%" PRIx64 ";\n", shape->filter.maskBits );
b3Dump( " sd.filter.groupIndex = %d;\n", shape->filter.groupIndex );
B3_ASSERT( shape->materialCount >= 1 );
const b3SurfaceMaterial* m = b3GetShapeMaterials( shape );
b3Dump( " sd.baseMaterial.friction = %.9g;\n", m->friction );
b3Dump( " sd.baseMaterial.restitution = %.9g;\n", m->restitution );
b3Dump( " sd.baseMaterial.rollingResistance = %.9g;\n", m->rollingResistance );
switch ( shape->type )
{
case b3_capsuleShape:
{
b3Capsule* s = &shape->capsule;
b3Dump( " b3CapsuleShape shape;\n" );
b3Dump( " shape.center1 = {%.9g, %.9g, %.9g};\n", s->center1.x, s->center1.y, s->center1.z );
b3Dump( " shape.center2 = {%.9g, %.9g, %.9g};\n", s->center2.x, s->center2.y, s->center2.z );
b3Dump( " shape.radius = %.9g;\n", s->radius );
b3Dump( " b3CreateCapsuleShape(bodyId, &sd, &shape);\n" );
}
break;
case b3_compoundShape:
{
// todo
}
break;
case b3_heightShape:
{
// todo
}
break;
case b3_hullShape:
{
const b3HullData* s = shape->hull;
int vertexCount = s->vertexCount;
const b3Vec3* vs = b3GetHullPoints( s );
b3Dump( " b3Vec3 vs[%d];\n", vertexCount );
for ( int i = 0; i < vertexCount; ++i )
{
b3Dump( " vs[%d] = {%.9g, %.9g, %.9g};\n", i, vs[i].x, vs[i].y, vs[i].z );
}
b3Dump( " b3HullData* hullData = b3CreateHull(vs, %d, %d);\n", vertexCount, vertexCount );
b3Dump( " b3CreateHullShape(bodyId, &sd, hullData);\n" );
b3Dump( " b3DestroyHull(hullData);\n" );
}
break;
case b3_meshShape:
{
const b3MeshData* s = shape->mesh.data;
b3Vec3 scale = shape->mesh.scale;
int meshIndex = b3FetchAddMeshDumpIndex();
char buffer[64];
snprintf( buffer, 64, "mesh_dump_%d.b3m", meshIndex );
b3WriteBinaryFile( (void*)s, s->byteCount, buffer );
b3Dump( " int dataSize = 0;\n" );
b3Dump( " b3MeshData* data = (b3MeshData*)b3ReadBinaryFile(dumpPrefix, \"%s\", &dataSize);\n", buffer );
b3Dump( " if (data == nullptr || data->version != B3_MESH_VERSION || data->byteCount != dataSize)\n" );
b3Dump( " {\n" );
b3Dump( " return;\n" );
b3Dump( " }\n" );
b3Dump( " b3Vec3 scale = { %.9g, %.9g, %.9g };\n", scale.x, scale.y, scale.z );
b3Dump( " b3CreateMeshShape(bodyId, &sd, data, scale);\n" );
// Host code must have this container and destroy the mesh data when the world is destroyed.
b3Dump( " m_meshes.push_back(data);\n" );
}
break;
case b3_sphereShape:
{
b3Sphere* s = &shape->sphere;
b3Dump( " b3SphereShape shape;\n" );
b3Dump( " shape.center = {%.9g, %.9g, %.9g};\n", s->center.x, s->center.y, s->center.z );
b3Dump( " shape.radius = %.9g;\n", s->radius );
b3Dump( " b3CreateSphereShape(bodyId, &sd, &shape);\n" );
}
break;
default:
return;
}
}

View file

@ -47,6 +47,12 @@ typedef struct b3Shape
void* userData;
void* userShape;
uint32_t nameId;
uint16_t generation;
// b3ShapeFlags
uint8_t flags;
union
{
b3Capsule capsule;
@ -57,10 +63,6 @@ typedef struct b3Shape
const b3CompoundData* compound;
};
uint16_t generation;
// b3ShapeFlags
uint8_t flags;
char name[B3_SHAPE_NAME_LENGTH + 1];
} b3Shape;
// A single material shape keeps its material inline. Multi material meshes and compounds own a heap
@ -134,7 +136,6 @@ static inline int b3GetHeightFieldTriangleCount( const b3HeightFieldData* height
// Mesh
b3Triangle b3GetMeshTriangle( const b3Mesh* mesh, int triangleIndex );
bool b3IsValidMesh( const b3MeshData* meshData );
void b3DumpShape( b3World* world, int shapeIndex );
static inline bool b3ShouldShapesCollide( b3Filter filterA, b3Filter filterB )
{

View file

@ -461,7 +461,9 @@ static bool b3ContinuousQueryCallback( int proxyId, uint64_t userData, void* con
float ms = b3GetMilliseconds( ticks );
if ( ms > 1000.0f * b3GetStallThreshold() )
{
b3Log( "CCD stall: duration %.1f ms for %s versus %s", ms, fastBody->name, body->name );
const char* nameFast = b3FindNameWithDefault( &world->names, fastBody->nameId, "NULL" );
const char* name = b3FindNameWithDefault( &world->names, body->nameId, "NULL" );
b3Log( "CCD stall: duration %.1f ms for %s versus %s", ms, nameFast, name );
}
// Continue query
@ -642,11 +644,12 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
float ms = b3GetMilliseconds( ticks );
if ( ms > 1000.0f * b3GetStallThreshold() )
{
const char* nameFast = b3FindNameWithDefault( &world->names, fastBody->nameId, "NULL" );
b3Vec3 c1 = sweep.c1;
b3Vec3 c2 = sweep.c2;
int vc = context.visitCount;
b3Log( "CCD stall: duration %.1f ms and visit count %d for %s: c1 = (%g, %g, %g), c2 = (%g, %g, %g)", ms, vc,
fastBody->name, c1.x, c1.y, c1.z, c2.x, c2.y, c2.z );
b3Log( "CCD stall: duration %.1f ms and visit count %d for %s: c1 = (%g, %g, %g), c2 = (%g, %g, %g)", ms, vc, nameFast,
c1.x, c1.y, c1.z, c2.x, c2.y, c2.z );
}
b3TracyCZoneEnd( ccd );
@ -692,7 +695,8 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex,
if ( b3IsValidVec3( v ) == false || b3IsValidVec3( w ) == false )
{
b3Log( "unstable: %s", bodies[sim->bodyId].name );
const char* name = b3FindNameWithDefault( &world->names, bodies[sim->bodyId].nameId, "NULL" );
b3Log( "unstable: %s", name );
}
B3_ASSERT( b3IsValidVec3( v ) );
@ -832,7 +836,7 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex,
b3AABB aabb = b3ComputeFatShapeAABB( shape, transform, speculativeScalar );
shape->aabb = aabb;
B3_ASSERT( (shape->flags & b3_enlargedAABB) == 0 );
B3_ASSERT( ( shape->flags & b3_enlargedAABB ) == 0 );
if ( b3AABB_Contains( shape->fatAABB, aabb ) == false )
{
@ -2201,7 +2205,7 @@ void b3Solve( b3World* world, b3StepContext* stepContext )
while ( shapeId != B3_NULL_INDEX )
{
b3Shape* shape = shapeArray + shapeId;
if ( (shape->flags & b3_enlargedAABB) == 0 )
if ( ( shape->flags & b3_enlargedAABB ) == 0 )
{
shapeId = shape->nextShapeId;
continue;

View file

@ -33,7 +33,7 @@
// Snapshot image magic 'BNS3' and version
#define B3_SNAP_MAGIC 0x33534E42u
#define B3_SNAP_VERSION 1u
#define B3_SNAP_VERSION 2u
#define B3_SNAP_FLAG_VALIDATION 0x1u
#define B3_SNAP_FLAG_DOUBLE_PRECISION 0x2u
@ -361,6 +361,50 @@ static void b3DesSolverSet( b3SnapReader* r, b3SolverSet* set )
b3DesPodArray( r, set->islandSims );
}
static void b3SerNames( b3RecBuffer* buf, const b3NameCache* cache )
{
b3SnapW_I32( buf, cache->entries.count );
int count = cache->entries.count;
for ( int i = 0; i < count; ++i )
{
const b3NameEntry* entry = cache->entries.data + i;
b3SnapW_U32( buf, entry->hash );
b3SnapW_I32( buf, entry->length );
b3RecBufAppend( buf, entry->name, entry->length );
}
}
static void b3DesNames( b3SnapReader* r, b3NameCache* cache )
{
int count = b3SnapR_I32( r );
if ( r->ok && b3SnapCheckCount( r, count, (int)sizeof( b3NameEntry ), 8 ) == false )
{
r->ok = false;
}
if ( r->ok == false )
{
return;
}
b3Array_Reserve( cache->entries, count );
for ( int i = 0; i < count; ++i )
{
uint32_t hash = b3SnapR_U32( r );
int length = b3SnapR_I32( r );
if ( r->ok == false || length < 0 || length > r->size - r->cursor )
{
r->ok = false;
return;
}
char* name = b3Alloc( length + 1 );
b3SnapR_Bytes( r, name, length );
name[length] = 0;
b3LoadName( cache, hash, name, length );
}
}
// Graph color: bodySet (non-overflow only) + jointSims + convexContacts + contacts
static void b3SerGraphColor( b3RecBuffer* buf, const b3GraphColor* color, bool isOverflow )
{
@ -437,7 +481,7 @@ static void b3DesWorldConfig( b3SnapReader* r, b3World* world )
// Shapes carry pointer fields: materials, userData, userShape, and the geometry union.
// Serialize the POD scalars with pointers nulled, then the owned materials array, then geometry.
// A single material lives inline in the struct image. The name is a fixed array, also inline.
// A single material lives inline in the struct image.
// Hull/mesh/heightField/compound are interned into the recording registry; sphere/capsule inline.
static void b3SerShapes( b3RecBuffer* buf, b3World* world, b3Recording* rec )
{
@ -1048,6 +1092,8 @@ int b3SerializeWorld( b3World* world, b3RecBuffer* buf, b3Recording* rec )
b3SerGraphColor( buf, &graph->colors[c], c == B3_OVERFLOW_INDEX );
}
b3SerNames( buf, &world->names );
return buf->size - startSize;
}
@ -1283,5 +1329,7 @@ bool b3DeserializeIntoShell( const uint8_t* data, int size, b3World* world, b3Re
}
}
b3DesNames( r, &world->names );
return r->ok;
}