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

@ -186,8 +186,4 @@ B3_API void b3Sleep( int milliseconds );
#define B3_HASH_INIT 5381
B3_API uint32_t b3Hash( uint32_t hash, const uint8_t* data, int count );
// Dump file support functions
B3_API void b3WriteBinaryFile( void* data, int size, const char* fileName );
B3_API void* b3ReadBinaryFile( const char* prefix, const char* fileName, int* memSize );
//! @endcond

View file

@ -245,13 +245,6 @@ B3_API void b3World_RebuildStaticTree( b3WorldId worldId );
/// This is for internal testing
B3_API void b3World_EnableSpeculative( b3WorldId worldId, bool flag );
/// Dump world to a text file. Saves only awake bodies and associated static bodies.
/// Meshes are saved to binary b3m files.
B3_API void b3World_DumpAwake( b3WorldId worldId );
/// Dump world to a text file. Meshes are saved to binary b3m files.
B3_API void b3World_Dump( b3WorldId worldId );
/**
* @defgroup recording Recording
* @brief Record and replay world state for debugging.
@ -508,10 +501,10 @@ B3_API b3BodyType b3Body_GetType( b3BodyId bodyId );
/// properties regardless of the automatic mass setting.
B3_API void b3Body_SetType( b3BodyId bodyId, b3BodyType type );
/// Set the body name. Up to B3_BODY_NAME_LENGTH characters excluding null termination.
/// Set the body name.
B3_API void b3Body_SetName( b3BodyId bodyId, const char* name );
/// Get the body name.
/// Get the body name. Returns an empty string if the name isn't set.
B3_API const char* b3Body_GetName( b3BodyId bodyId );
/// Set the user data for a body
@ -846,10 +839,10 @@ B3_API b3WorldId b3Shape_GetWorld( b3ShapeId shapeId );
/// Returns true if the shape is a sensor
B3_API bool b3Shape_IsSensor( b3ShapeId shapeId );
/// Set the shape name. Up to B3_SHAPE_NAME_LENGTH characters excluding null termination.
/// Set the shape name.
B3_API void b3Shape_SetName( b3ShapeId shapeId, const char* name );
/// Get the shape name.
/// Get the shape name. Returns an empty string if the name isn't set.
B3_API const char* b3Shape_GetName( b3ShapeId shapeId );
/// Set the user data for a shape

View file

@ -97,16 +97,6 @@ B3_API float b3GetStallThreshold( void );
/// The time that a body must be still before it will go to sleep. In seconds.
#define B3_TIME_TO_SLEEP 0.5f
/// Maximum length of the body name. Can be 0 if you don't need names.
#ifndef B3_BODY_NAME_LENGTH
#define B3_BODY_NAME_LENGTH 18
#endif
/// Maximum length of the shape name. Can be 0 if you don't need names.
#ifndef B3_SHAPE_NAME_LENGTH
#define B3_SHAPE_NAME_LENGTH 0
#endif
/// The maximum number of contact points between two touching shapes.
#define B3_MAX_MANIFOLD_POINTS 4

View file

@ -302,7 +302,7 @@ typedef struct b3BodyDef
/// Sleep speed threshold, default is 0.05 meters per second
float sleepThreshold;
/// Optional body name for debugging. Up to B3_BODY_NAME_LENGTH characters (including null termination)
/// Optional body name for debugging.
const char* name;
/// Use this to store application specific body data.

View file

@ -11,6 +11,7 @@
#include <ctype.h>
#include <float.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
@ -179,7 +180,7 @@ static void FormatQueryLabel( char* out, int cap, const char* name, uint64_t id,
{
if ( name != nullptr && id != 0 )
{
snprintf( out, cap, "%s (%llu)", name, (unsigned long long)id );
snprintf( out, cap, "%s (%" PRIu64 ")", name, id );
}
else if ( name != nullptr )
{
@ -187,7 +188,7 @@ static void FormatQueryLabel( char* out, int cap, const char* name, uint64_t id,
}
else if ( id != 0 )
{
snprintf( out, cap, "#%llu", (unsigned long long)id );
snprintf( out, cap, "#%" PRIu64, id );
}
else
{
@ -1141,8 +1142,8 @@ public:
char base[64];
FormatQueryLabel( base, sizeof( base ), row.name, row.id, row.type, row.kindOrdinal );
char text[112];
snprintf( text, sizeof( text ), "f%-5d %s (%d) cat 0x%llx", row.frame, base, row.hitCount,
(unsigned long long)row.filter.categoryBits );
snprintf( text, sizeof( text ), "f%-5d %s (%d) cat 0x%" PRIx64, row.frame, base, row.hitCount,
row.filter.categoryBits );
if ( ContainsNoCase( text, m_querySearch ) == false )
{
continue;
@ -1449,8 +1450,8 @@ public:
ImGui::Text( "id %d", shape.index1 );
ImGui::Text( "type %s", ReplayShapeTypeName( b3Shape_GetType( shape ) ) );
b3Filter f = b3Shape_GetFilter( shape );
ImGui::Text( "category 0x%016llx", (unsigned long long)f.categoryBits );
ImGui::Text( "mask 0x%016llx", (unsigned long long)f.maskBits );
ImGui::Text( "category 0x%016" PRIx64, f.categoryBits );
ImGui::Text( "mask 0x%016" PRIx64, f.maskBits );
ImGui::Text( "group %d", f.groupIndex );
ImGui::Text( "density %.3g", b3Shape_GetDensity( shape ) );
ImGui::Text( "friction %.3g", b3Shape_GetFriction( shape ) );
@ -1557,7 +1558,7 @@ public:
}
if ( q.id != 0 )
{
ImGui::Text( "id %llu", (unsigned long long)q.id );
ImGui::Text( "id %" PRIu64, q.id );
}
if ( q.key != 0 )
{
@ -1567,8 +1568,8 @@ public:
{
ImGui::Text( "type %s #%d", ReplayQueryTypeName( q.type ), m_selQueryKindOrdinal );
}
ImGui::Text( "category 0x%016llx", (unsigned long long)q.filter.categoryBits );
ImGui::Text( "mask 0x%016llx", (unsigned long long)q.filter.maskBits );
ImGui::Text( "category 0x%016" PRIx64, q.filter.categoryBits );
ImGui::Text( "mask 0x%016" PRIx64, q.filter.maskBits );
if ( q.type != b3_recQueryOverlapAABB )
{
ImGui::Text( "origin (%.2f, %.2f, %.2f)", q.origin.x, q.origin.y, q.origin.z );

View file

@ -2,7 +2,6 @@
// SPDX-License-Identifier: MIT
#include "gfx/debug_adapter.h"
#include "gfx/draw.h"
#include "gfx/keycodes.h"
#include "imgui.h"
#include "mesh_loader.h"
@ -10,6 +9,8 @@
#include "box3d/box3d.h"
#include <stdio.h>
class CardHouseThick : public Sample
{
public:
@ -451,13 +452,9 @@ public:
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.baseMaterial.rollingResistance = 0.1f;
#if B3_SHAPE_NAME_LENGTH > 0
char buffer[B3_SHAPE_NAME_LENGTH + 1];
snprintf( buffer, sizeof( buffer ), "box_%d", i );
char buffer[16];
snprintf( buffer, sizeof( buffer ), "box_%.3d", i );
shapeDef.name = buffer;
#endif
b3CreateHullShape( bodyId, &shapeDef, &cube.base );
}

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;
}

View file

@ -19,6 +19,7 @@ set(BOX3D_TEST_FILES
test_macros.h
test_math.c
test_mover.c
test_name_cache.c
test_recording.c
test_shape.c
test_table.c

View file

@ -41,6 +41,7 @@ extern int JointTest( void );
extern int LargeWorldTest( void );
extern int MathTest( void );
extern int MoverTest( void );
extern int NameCacheTest( void );
extern int RecordingTest( void );
extern int ShapeTest( void );
extern int TableTest( void );
@ -111,6 +112,7 @@ int main( int argc, char** argv )
MAYBE_RUN_TEST( LargeWorldTest );
MAYBE_RUN_TEST( MathTest );
MAYBE_RUN_TEST( MoverTest );
MAYBE_RUN_TEST( NameCacheTest );
MAYBE_RUN_TEST( RecordingTest );
MAYBE_RUN_TEST( ShapeTest );
MAYBE_RUN_TEST( TableTest );

212
test/test_name_cache.c Normal file
View file

@ -0,0 +1,212 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#include "name_cache.h"
#include "test_macros.h"
#include "box3d/base.h"
#include "box3d/box3d.h"
#include <string.h>
// Direct unit test of the cache: dedup, reverse lookup, empty/null, arbitrary length, no leak.
static int CacheUnit( void )
{
int32_t base = b3GetByteCount();
b3NameCache cache = b3CreateNameCache();
// Empty and NULL map to the null id, which resolves to no string.
ENSURE( b3AddName( &cache, "" ) == B3_NULL_NAME );
ENSURE( b3AddName( &cache, NULL ) == B3_NULL_NAME );
ENSURE( b3FindName( &cache, B3_NULL_NAME ) == NULL );
// Distinct strings get distinct ids and round-trip.
uint32_t crate = b3AddName( &cache, "crate" );
uint32_t barrel = b3AddName( &cache, "barrel" );
ENSURE( crate != B3_NULL_NAME && barrel != B3_NULL_NAME && crate != barrel );
ENSURE( strcmp( b3FindName( &cache, crate ), "crate" ) == 0 );
ENSURE( strcmp( b3FindName( &cache, barrel ), "barrel" ) == 0 );
// Re-interning the same bytes returns the same id and stores no second entry.
ENSURE( b3AddName( &cache, "crate" ) == crate );
ENSURE( cache.entries.count == 2 );
// A name far longer than any inline buffer round-trips exactly.
char longName[4096];
for ( int i = 0; i < (int)sizeof( longName ) - 1; ++i )
{
longName[i] = (char)( 'a' + i % 26 );
}
longName[sizeof( longName ) - 1] = 0;
uint32_t longId = b3AddName( &cache, longName );
ENSURE( strcmp( b3FindName( &cache, longId ), longName ) == 0 );
ENSURE( cache.entries.count == 3 );
b3DestroyNameCache( &cache );
// The cache owns every interned copy, so all of it comes back on destroy.
ENSURE( b3GetByteCount() == base );
return 0;
}
// Build a ground plus named dynamic boxes. Two share a name to exercise dedup and one is longer
// than the old inline buffer to exercise variable length. Ground is ordinal 0, boxes 1..N.
static const char* s_bodyNames[] = {
"crate",
"barrel",
"crate",
"a_very_long_body_name_that_exceeds_any_inline_name_buffer",
};
// Each box also carries a named hull shape. Shapes could not hold a name at all before the cache
// (the old inline shape buffer had length 0), so this is a new path. Two shapes share a name for
// dedup, one shape shares a body's name to prove shape ids intern independently, and one is far
// longer than any inline buffer.
static const char* s_shapeNames[] = {
"box_hull",
"box_hull",
"crate",
"a_very_long_shape_name_that_never_fit_the_old_inline_buffer",
};
_Static_assert( ARRAY_COUNT( s_shapeNames ) == ARRAY_COUNT( s_bodyNames ), "name arrays must stay parallel" );
static void BuildNamedScene( b3WorldId worldId )
{
b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } );
b3BodyDef groundDef = b3DefaultBodyDef();
groundDef.type = b3_staticBody;
b3BodyId groundId = b3CreateBody( worldId, &groundDef );
b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f );
b3ShapeDef groundShape = b3DefaultShapeDef();
b3CreateHullShape( groundId, &groundShape, &groundBox.base );
b3ShapeDef boxShape = b3DefaultShapeDef();
boxShape.density = 1.0f;
for ( int i = 0; i < ARRAY_COUNT( s_bodyNames ); ++i )
{
b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ 0.0f, 1.0f + 1.1f * (float)i, 0.0f };
bodyDef.name = s_bodyNames[i];
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
boxShape.name = s_shapeNames[i];
b3CreateHullShape( bodyId, &boxShape, &box.base );
}
}
static int CheckReplayNames( b3RecPlayer* player )
{
for ( int i = 0; i < ARRAY_COUNT( s_bodyNames ); ++i )
{
b3BodyId id = b3RecPlayer_GetBodyId( player, 1 + i ); // ordinal 0 is the ground
ENSURE( b3Body_IsValid( id ) );
const char* name = b3Body_GetName( id );
ENSURE( name != NULL && strcmp( name, s_bodyNames[i] ) == 0 );
// Shape names ride the same world cache, so the snapshot must restore them too.
b3ShapeId shapeId;
ENSURE( b3Body_GetShapes( id, &shapeId, 1 ) == 1 );
const char* shapeName = b3Shape_GetName( shapeId );
ENSURE( shapeName != NULL && strcmp( shapeName, s_shapeNames[i] ) == 0 );
}
return 0;
}
// Names live on the world, so the world snapshot must carry them. Record a snapshot-seeded session
// and confirm every body and shape name resolves on the reconstructed replay world.
static int NameRoundTrip( void )
{
b3Recording* rec = b3CreateRecording( 0 );
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
BuildNamedScene( worldId );
// Record from a snapshot of the populated world, so names ride in the frame-0 image.
b3World_StartRecording( worldId, rec );
for ( int i = 0; i < 20; ++i )
{
b3World_Step( worldId, 1.0f / 60.0f, 4 );
}
b3World_StopRecording( worldId );
b3DestroyWorld( worldId );
ENSURE( b3ValidateReplay( b3Recording_GetData( rec ), b3Recording_GetSize( rec ), 1 ) );
b3RecPlayer* player = b3RecPlayer_Create( b3Recording_GetData( rec ), b3Recording_GetSize( rec ), 1 );
ENSURE( player != NULL );
b3RecPlayer_SeekFrame( player, 20 );
ENSURE( !b3RecPlayer_HasDiverged( player ) );
ENSURE( CheckReplayNames( player ) == 0 );
b3RecPlayer_Destroy( player );
b3DestroyRecording( rec );
return 0;
}
// Rollback preserves names: a backward seek restores from a keyframe, which rebuilds world->names
// on each restore. Scrub across keyframe boundaries, confirm names resolve every time, and require
// the tracked byte count to return to baseline so a re-load that drops duplicate copies leaks nothing.
static int RollbackNames( void )
{
int32_t base = b3GetByteCount();
b3Recording* rec = b3CreateRecording( 0 );
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
BuildNamedScene( worldId );
// Settle, then record a snapshot-seeded session long enough to span several keyframes.
for ( int i = 0; i < 10; ++i )
{
b3World_Step( worldId, 1.0f / 60.0f, 4 );
}
b3World_StartRecording( worldId, rec );
const int totalFrames = 80;
for ( int i = 0; i < totalFrames; ++i )
{
b3World_Step( worldId, 1.0f / 60.0f, 4 );
}
b3World_StopRecording( worldId );
b3DestroyWorld( worldId );
b3RecPlayer* player = b3RecPlayer_Create( b3Recording_GetData( rec ), b3Recording_GetSize( rec ), 1 );
ENSURE( player != NULL );
// Play to the end so the keyframe ring is populated.
b3RecPlayer_SeekFrame( player, totalFrames );
ENSURE( !b3RecPlayer_HasDiverged( player ) );
// Scrub backward and forward across keyframe boundaries. Each restore rebuilds the name table.
int targets[] = { 10, 60, 5, 70, 1, 40 };
for ( int k = 0; k < ARRAY_COUNT( targets ); ++k )
{
b3RecPlayer_SeekFrame( player, targets[k] );
ENSURE( b3RecPlayer_GetFrame( player ) == targets[k] );
ENSURE( !b3RecPlayer_HasDiverged( player ) );
ENSURE( CheckReplayNames( player ) == 0 );
}
b3RecPlayer_Destroy( player );
b3DestroyRecording( rec );
// Every restore reloaded the name table; dropped duplicate copies must be freed, not leaked.
ENSURE( b3GetByteCount() == base );
return 0;
}
int NameCacheTest( void )
{
RUN_SUBTEST( CacheUnit );
RUN_SUBTEST( NameRoundTrip );
RUN_SUBTEST( RollbackNames );
return 0;
}

View file

@ -5,12 +5,12 @@
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "box3d/box3d.h"
#include "box3d/collision.h"
#include "test_macros.h"
#include "physics_world.h"
#include "recording.h"
#include "test_macros.h"
#include "box3d/box3d.h"
#include "box3d/collision.h"
#include <stdint.h>
#include <stdio.h>
@ -25,7 +25,7 @@ static int SphereRoundTrip( void )
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_StartRecording( worldId, rec );
@ -34,28 +34,28 @@ static int SphereRoundTrip( void )
// Static ground
b3BodyDef groundDef = b3DefaultBodyDef();
groundDef.type = b3_staticBody;
b3BodyId groundId = b3CreateBody( worldId, &groundDef );
groundDef.type = b3_staticBody;
b3BodyId groundId = b3CreateBody( worldId, &groundDef );
b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f );
b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f );
b3ShapeDef groundShapeDef = b3DefaultShapeDef();
b3CreateHullShape( groundId, &groundShapeDef, &groundBox.base );
// Dynamic body with a sphere shape
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ 0.0f, 5.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ 0.0f, 5.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3Sphere sphere;
sphere.center = (b3Vec3){ 0.0f, 0.0f, 0.0f };
sphere.radius = 0.5f;
b3ShapeDef sphereDef = b3DefaultShapeDef();
sphereDef.density = 1.0f;
b3ShapeDef sphereDef = b3DefaultShapeDef();
sphereDef.density = 1.0f;
b3CreateSphereShape( bodyId, &sphereDef, &sphere );
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
for ( int i = 0; i < 30; ++i )
{
b3World_Step( worldId, timeStep, subStepCount );
@ -75,10 +75,8 @@ static int HullDedup( void )
{
// Build a small convex hull
b3Vec3 pts[8] = {
{ -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f },
{ 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f },
{ -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f },
{ 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f },
{ -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f }, { 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f },
{ -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f },
};
b3HullData* hull = b3CreateHull( pts, 8, 8 );
ENSURE( hull != NULL );
@ -87,19 +85,19 @@ static int HullDedup( void )
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_StartRecording( worldId, rec );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.density = 1.0f;
shapeDef.density = 1.0f;
for ( int i = 0; i < 3; ++i )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ (float)( i * 3 ), 5.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ (float)( i * 3 ), 5.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3CreateHullShape( bodyId, &shapeDef, hull );
}
@ -119,7 +117,7 @@ static int HullDedup( void )
// Confirm the registry was deduped to 1 hull entry.
// Parse registryOffset from the header and count entries.
const uint8_t* bytes = b3Recording_GetData( rec );
int sz = b3Recording_GetSize( rec );
int sz = b3Recording_GetSize( rec );
ENSURE( sz >= 48 );
uint64_t regOff = 0;
@ -127,9 +125,8 @@ static int HullDedup( void )
ENSURE( regOff != 0 && (int)regOff + 4 <= sz );
// entryCount is a little-endian u32 at the start of the registry block
const uint8_t* rp = bytes + (int)regOff;
uint32_t entryCount = (uint32_t)rp[0] | ( (uint32_t)rp[1] << 8 ) |
( (uint32_t)rp[2] << 16 ) | ( (uint32_t)rp[3] << 24 );
const uint8_t* rp = bytes + (int)regOff;
uint32_t entryCount = (uint32_t)rp[0] | ( (uint32_t)rp[1] << 8 ) | ( (uint32_t)rp[2] << 16 ) | ( (uint32_t)rp[3] << 24 );
ENSURE( entryCount == 1 );
b3DestroyRecording( rec );
@ -140,7 +137,7 @@ static int HullDedup( void )
static int MidStreamNoContacts( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } );
@ -148,20 +145,20 @@ static int MidStreamNoContacts( void )
sphere.center = (b3Vec3){ 0.0f, 0.0f, 0.0f };
sphere.radius = 0.5f;
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.density = 1.0f;
shapeDef.density = 1.0f;
// A few dynamic bodies well apart from each other so no contacts form
for ( int i = 0; i < 4; ++i )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ (float)( i * 10 ), 50.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ (float)( i * 10 ), 50.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3CreateSphereShape( bodyId, &shapeDef, &sphere );
}
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
for ( int i = 0; i < 10; ++i )
{
b3World_Step( worldId, timeStep, subStepCount );
@ -190,23 +187,23 @@ static int MidStreamNoContacts( void )
static int MidStreamContacts( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } );
// Static ground using a box hull
{
b3BodyDef groundDef = b3DefaultBodyDef();
groundDef.type = b3_staticBody;
b3BodyId groundId = b3CreateBody( worldId, &groundDef );
groundDef.type = b3_staticBody;
b3BodyId groundId = b3CreateBody( worldId, &groundDef );
b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f );
b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f );
b3ShapeDef groundShape = b3DefaultShapeDef();
b3CreateHullShape( groundId, &groundShape, &groundBox.base );
}
b3ShapeDef dynamicShape = b3DefaultShapeDef();
dynamicShape.density = 1.0f;
dynamicShape.density = 1.0f;
// A few dynamic boxes dropped onto the ground
for ( int i = 0; i < 3; ++i )
@ -214,14 +211,14 @@ static int MidStreamContacts( void )
b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ (float)( i * 2 ) - 2.0f, 5.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ (float)( i * 2 ) - 2.0f, 5.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3CreateHullShape( bodyId, &dynamicShape, &box.base );
}
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
// Let the scene settle: bodies hit ground, build manifolds, islands, graph colors
for ( int i = 0; i < 60; ++i )
@ -257,7 +254,7 @@ static int ScrubBackward( void )
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } );
@ -287,8 +284,8 @@ static int ScrubBackward( void )
}
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
int totalFrames = 80;
int subStepCount = 4;
int totalFrames = 80;
for ( int i = 0; i < totalFrames; ++i )
{
b3World_Step( worldId, timeStep, subStepCount );
@ -298,7 +295,7 @@ static int ScrubBackward( void )
b3DestroyWorld( worldId );
const uint8_t* data = b3Recording_GetData( rec );
int sz = b3Recording_GetSize( rec );
int sz = b3Recording_GetSize( rec );
// Create the player
b3RecPlayer* player = b3RecPlayer_Create( data, sz, 1 );
@ -354,10 +351,8 @@ static int ScrubBackward( void )
static int SeekWithHull( void )
{
b3Vec3 pts[8] = {
{ -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f },
{ 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f },
{ -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f },
{ 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f },
{ -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f }, { 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f },
{ -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f },
};
b3HullData* hull = b3CreateHull( pts, 8, 8 );
ENSURE( hull != NULL );
@ -366,7 +361,7 @@ static int SeekWithHull( void )
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } );
b3World_StartRecording( worldId, rec );
@ -387,14 +382,14 @@ static int SeekWithHull( void )
for ( int i = 0; i < 3; ++i )
{
b3BodyDef bd = b3DefaultBodyDef();
bd.type = b3_dynamicBody;
bd.position = (b3Pos){ (float)( i * 4 ) - 4.0f, 5.0f, 0.0f };
bd.type = b3_dynamicBody;
bd.position = (b3Pos){ (float)( i * 4 ) - 4.0f, 5.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bd );
b3CreateHullShape( bodyId, &sd, hull );
}
float timeStep = 1.0f / 60.0f;
int totalFrames = 40;
int totalFrames = 40;
for ( int i = 0; i < totalFrames; ++i )
{
b3World_Step( worldId, timeStep, 4 );
@ -405,7 +400,7 @@ static int SeekWithHull( void )
b3DestroyHull( hull );
const uint8_t* data = b3Recording_GetData( rec );
int sz = b3Recording_GetSize( rec );
int sz = b3Recording_GetSize( rec );
b3RecPlayer* player = b3RecPlayer_Create( data, sz, 1 );
ENSURE( player != NULL );
@ -484,13 +479,13 @@ static int DebugShapeCallbacks( void )
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_StartRecording( worldId, rec );
b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } );
b3BodyDef groundDef = b3DefaultBodyDef();
groundDef.type = b3_staticBody;
groundDef.type = b3_staticBody;
b3BodyId groundId = b3CreateBody( worldId, &groundDef );
b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f );
b3ShapeDef groundShape = b3DefaultShapeDef();
@ -503,9 +498,9 @@ static int DebugShapeCallbacks( void )
for ( int i = 0; i < 4; ++i )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ 0.0f, 1.0f + 1.1f * (float)i, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3CreateHullShape( bodyId, &boxShape, &box.base );
}
@ -564,7 +559,7 @@ static int DebugShapeCallbacks( void )
static int PlayerAccessors( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } );
// Static ground (creation ordinal 0)
@ -590,7 +585,7 @@ static int PlayerAccessors( void )
}
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
int subStepCount = 4;
// Settle, then record with a snapshot of the populated world.
for ( int i = 0; i < 10; ++i )
@ -666,11 +661,11 @@ static int PlayerAccessors( void )
static int KeyframeHandleReuse( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } );
b3BodyDef groundDef = b3DefaultBodyDef();
groundDef.type = b3_staticBody;
groundDef.type = b3_staticBody;
b3BodyId groundId = b3CreateBody( worldId, &groundDef );
b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f );
b3ShapeDef groundShape = b3DefaultShapeDef();
@ -683,9 +678,9 @@ static int KeyframeHandleReuse( void )
for ( int i = 0; i < dynamicCount; ++i )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ 0.0f, 1.0f + 1.1f * (float)i, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3CreateHullShape( bodyId, &boxShape, &box.base );
}
int shapeCount = 1 + dynamicCount;
@ -785,13 +780,13 @@ static int QueryReplay( void )
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } );
b3BodyDef groundDef = b3DefaultBodyDef();
groundDef.type = b3_staticBody;
b3BodyId groundId = b3CreateBody( worldId, &groundDef );
b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f );
groundDef.type = b3_staticBody;
b3BodyId groundId = b3CreateBody( worldId, &groundDef );
b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f );
b3ShapeDef groundShape = b3DefaultShapeDef();
b3CreateHullShape( groundId, &groundShape, &groundBox.base );
@ -799,12 +794,12 @@ static int QueryReplay( void )
for ( int i = 0; i < 4; ++i )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ (float)i - 1.5f, 3.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f };
b3ShapeDef sphereDef = b3DefaultShapeDef();
sphereDef.density = 1.0f;
sphereDef.density = 1.0f;
b3CreateSphereShape( bodyId, &sphereDef, &sphere );
}
@ -815,13 +810,13 @@ static int QueryReplay( void )
const int totalFrames = 30;
for ( int i = 0; i < totalFrames; ++i )
{
b3Pos origin = { 0.0f, 6.0f, 0.0f };
b3Pos origin = { 0.0f, 6.0f, 0.0f };
b3Vec3 translation = { 0.0f, -8.0f, 0.0f };
b3AABB aabb = { { -5.0f, -1.0f, -5.0f }, { 5.0f, 6.0f, 5.0f } };
b3AABB aabb = { { -5.0f, -1.0f, -5.0f }, { 5.0f, 6.0f, 5.0f } };
b3Vec3 proxyPts = { 0.0f, 0.0f, 0.0f };
b3ShapeProxy proxy = { &proxyPts, 1, 0.5f };
b3Capsule mover = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 0.3f };
b3Vec3 proxyPts = { 0.0f, 0.0f, 0.0f };
b3ShapeProxy proxy = { &proxyPts, 1, 0.5f };
b3Capsule mover = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 0.3f };
b3World_OverlapAABB( worldId, aabb, filter, QueryReplayOverlapFcn, NULL );
b3World_OverlapShape( worldId, origin, &proxy, filter, QueryReplayOverlapFcn, NULL );
@ -879,12 +874,12 @@ static int TaggedQuery( void )
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3BodyDef groundDef = b3DefaultBodyDef();
groundDef.type = b3_staticBody;
b3BodyId groundId = b3CreateBody( worldId, &groundDef );
b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f );
groundDef.type = b3_staticBody;
b3BodyId groundId = b3CreateBody( worldId, &groundDef );
b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f );
b3ShapeDef groundShape = b3DefaultShapeDef();
b3CreateHullShape( groundId, &groundShape, &groundBox.base );
@ -892,11 +887,11 @@ static int TaggedQuery( void )
// Same label, different entity ids: distinct logical queries with distinct keys.
b3QueryFilter bullet53 = b3DefaultQueryFilter();
bullet53.id = 53;
bullet53.id = 53;
bullet53.name = "bullet";
b3QueryFilter bullet54 = b3DefaultQueryFilter();
bullet54.id = 54;
bullet54.id = 54;
bullet54.name = "bullet";
b3QueryFilter untagged = b3DefaultQueryFilter();
@ -908,9 +903,9 @@ static int TaggedQuery( void )
const int totalFrames = 10;
for ( int i = 0; i < totalFrames; ++i )
{
b3Pos origin = { 0.0f, 6.0f, 0.0f };
b3Pos origin = { 0.0f, 6.0f, 0.0f };
b3Vec3 translation = { 0.0f, -8.0f, 0.0f };
b3AABB aabb = { { -5.0f, -1.0f, -5.0f }, { 5.0f, 6.0f, 5.0f } };
b3AABB aabb = { { -5.0f, -1.0f, -5.0f }, { 5.0f, 6.0f, 5.0f } };
// Two tagged rays sharing the label "bullet" plus one untagged overlap, every frame.
b3World_CastRay( worldId, origin, translation, bullet53, QueryReplayCastFcn, NULL );
@ -975,7 +970,7 @@ static int EmptyWorldRoundTrip( void )
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_StartRecording( worldId, rec );
b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } );
@ -989,7 +984,7 @@ static int EmptyWorldRoundTrip( void )
b3DestroyWorld( worldId );
const uint8_t* data = b3Recording_GetData( rec );
int size = b3Recording_GetSize( rec );
int size = b3Recording_GetSize( rec );
// The seed snapshot is written even with no bodies.
b3RecHeader hdr;
@ -1042,12 +1037,11 @@ static int AllOps( void )
b3ShapeId groundShapeId = b3CreateHullShape( groundId, &groundShapeDef, &groundBox.base );
ENSURE( b3Shape_IsValid( groundShapeId ) );
// Dynamic body with a sphere shape. The name is intentionally longer than B3_BODY_NAME_LENGTH so
// replay exercises the over-length name path in the body def reader.
// Dynamic body with a sphere shape.
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ 0.0f, 5.0f, 0.0f };
bodyDef.name = "testBodyWithVeryLongNameThatExceedsTheNameLength";
bodyDef.name = "testBodyWithVeryLongNameThatIsAVeryLongNameLength";
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
ENSURE( b3Body_IsValid( bodyId ) );
@ -1074,10 +1068,8 @@ static int AllOps( void )
// Custom hull shape on a third dynamic body
b3Vec3 hullPts[8] = {
{ -0.5f, -0.5f, -0.5f }, { 0.5f, -0.5f, -0.5f },
{ 0.5f, 0.5f, -0.5f }, { -0.5f, 0.5f, -0.5f },
{ -0.5f, -0.5f, 0.5f }, { 0.5f, -0.5f, 0.5f },
{ 0.5f, 0.5f, 0.5f }, { -0.5f, 0.5f, 0.5f },
{ -0.5f, -0.5f, -0.5f }, { 0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, -0.5f }, { -0.5f, 0.5f, -0.5f },
{ -0.5f, -0.5f, 0.5f }, { 0.5f, -0.5f, 0.5f }, { 0.5f, 0.5f, 0.5f }, { -0.5f, 0.5f, 0.5f },
};
b3HullData* customHull = b3CreateHull( hullPts, 8, 8 );
ENSURE( customHull != NULL );
@ -1115,8 +1107,8 @@ static int AllOps( void )
b3ShapeDef xformShapeDef = b3DefaultShapeDef();
xformShapeDef.density = 1.0f;
b3Transform xformXf = { (b3Vec3){ 0.1f, 0.2f, -0.1f }, b3MakeQuatFromAxisAngle( (b3Vec3){ 0.0f, 1.0f, 0.0f }, 0.4f ) };
b3ShapeId xformShapeId = b3CreateTransformedHullShape( xformBodyId, &xformShapeDef, customHull, xformXf,
(b3Vec3){ 1.25f, 0.75f, 1.5f } );
b3ShapeId xformShapeId =
b3CreateTransformedHullShape( xformBodyId, &xformShapeDef, customHull, xformXf, (b3Vec3){ 1.25f, 0.75f, 1.5f } );
ENSURE( b3Shape_IsValid( xformShapeId ) );
// Mesh, height field, and compound static shapes (3D-only)
@ -1540,10 +1532,8 @@ static int AllOps( void )
static int TransformedHullRoundTrip( void )
{
b3Vec3 pts[8] = {
{ -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f },
{ 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f },
{ -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f },
{ 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f },
{ -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f }, { 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f },
{ -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f },
};
b3HullData* hull = b3CreateHull( pts, 8, 8 );
ENSURE( hull != NULL );
@ -1552,22 +1542,22 @@ static int TransformedHullRoundTrip( void )
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_StartRecording( worldId, rec );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.density = 1.0f;
shapeDef.density = 1.0f;
// Baked transform with a rotation and non-uniform scale, the path Unreal uses for instanced hulls.
b3Transform xf = { (b3Vec3){ 0.25f, 0.0f, -0.5f }, b3MakeQuatFromAxisAngle( (b3Vec3){ 0.0f, 0.0f, 1.0f }, 0.3f ) };
b3Vec3 scl = { 1.5f, 0.5f, 2.0f };
b3Transform xf = { (b3Vec3){ 0.25f, 0.0f, -0.5f }, b3MakeQuatFromAxisAngle( (b3Vec3){ 0.0f, 0.0f, 1.0f }, 0.3f ) };
b3Vec3 scl = { 1.5f, 0.5f, 2.0f };
for ( int i = 0; i < 3; ++i )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ (float)( i * 3 ), 5.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ (float)( i * 3 ), 5.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3ShapeId sid = b3CreateTransformedHullShape( bodyId, &shapeDef, hull, xf, scl );
ENSURE( b3Shape_IsValid( sid ) );
}
@ -1576,9 +1566,9 @@ static int TransformedHullRoundTrip( void )
// shape's recorded id would not match what replay allocates and b3ValidateReplay would fail.
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ 0.0f, 10.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ 0.0f, 10.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3ShapeId sid = b3CreateHullShape( bodyId, &shapeDef, hull );
ENSURE( b3Shape_IsValid( sid ) );
}
@ -1723,8 +1713,8 @@ static int GeometryHashCollision( void )
uint8_t* live = (uint8_t*)b3Alloc( (size_t)n );
memset( live, 0xAA, (size_t)n );
uint32_t resolved = b3InternGeometry( &seeded, b3_geometryHull, sharedHash, live, n );
ENSURE( seeded.count == 3 ); // no growth
ENSURE( resolved == 0 || resolved == 2 ); // a valid slot index for that content
ENSURE( seeded.count == 3 ); // no growth
ENSURE( resolved == 0 || resolved == 2 ); // a valid slot index for that content
ENSURE( seeded.entries[resolved].byteCount == n );
ENSURE( memcmp( seeded.entries[resolved].bytes, slot0, (size_t)n ) == 0 );
@ -1743,13 +1733,13 @@ static int StagedStepCreationPose( void )
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } );
b3World_StartRecording( worldId, rec );
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
// A few empty steps so the creation lands inside the stream, not at frame 0.
const int leadFrames = 3;
@ -1762,9 +1752,9 @@ static int StagedStepCreationPose( void )
// Components are exact in float so the round-trip pose compares tight.
const b3Pos spawn = { 1.0, 20.0, -2.0 };
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.type = b3_dynamicBody;
bodyDef.position = spawn;
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f };
b3ShapeDef shapeDef = b3DefaultShapeDef();
@ -1787,7 +1777,7 @@ static int StagedStepCreationPose( void )
b3DestroyWorld( worldId );
const uint8_t* data = b3Recording_GetData( rec );
int sz = b3Recording_GetSize( rec );
int sz = b3Recording_GetSize( rec );
// Atomic replay fuses the create and its step, so at the creation frame the body is already
// integrated and displaced along +x. Capture that pose and the final state hash.
@ -1854,16 +1844,13 @@ static int StagedStepCreationPose( void )
// Shape names are debug only and do not feed the determinism hash, so b3ValidateReplay cannot catch a
// broken name round-trip. Replay through the player and read the names back to prove the def field and
// the ShapeSetName op survive serialization. Holds for any B3_SHAPE_NAME_LENGTH, including 0.
// the ShapeSetName op survive serialization.
static int ShapeNameReplay( void )
{
// Replay must reproduce exactly what the shape stores: its source truncated to B3_SHAPE_NAME_LENGTH.
// Asserting the shape cap rather than the body cap also traps the shared string reader, which clamps
// to the body length, from silently shortening shape names if the two caps ever cross.
const char* names[3] = {
"def", // carried on the shape def, survives whole
"set", // applied after create through the setter op
"abcdefghijklmnopqrstuvwxyz", // over-length, forces the clamp
"def",
"set",
"abcdefghijklmnopqrstuvwxyz",
};
b3Recording* rec = b3CreateRecording( 0 );
@ -1926,11 +1913,10 @@ static int ShapeNameReplay( void )
ENSURE( got != NULL );
int srcLen = (int)strlen( names[i] );
int expectLen = srcLen < B3_SHAPE_NAME_LENGTH ? srcLen : B3_SHAPE_NAME_LENGTH;
ENSURE( (int)strlen( got ) == expectLen );
if ( expectLen > 0 )
ENSURE( (int)strlen( got ) == srcLen );
if ( srcLen > 0 )
{
ENSURE( strncmp( got, names[i], (size_t)expectLen ) == 0 );
ENSURE( strncmp( got, names[i], (size_t)srcLen ) == 0 );
}
}

View file

@ -277,8 +277,8 @@ static int PointInShapeTest( void )
// Shared assertions for a surface hit. The normal points outward toward the ray,
// the point sits on the surface, and the point lies on the ray at the reported fraction.
static int CheckCastHit( b3CastOutput out, b3Vec3 origin, b3Vec3 translation, b3Vec3 point, b3Vec3 normal,
float fraction, float tol )
static int CheckCastHit( b3CastOutput out, b3Vec3 origin, b3Vec3 translation, b3Vec3 point, b3Vec3 normal, float fraction,
float tol )
{
ENSURE( out.hit );
ENSURE_SMALL( out.fraction - fraction, tol );
@ -313,22 +313,22 @@ static int RayCastSphereHitTest( void )
{
b3RayCastInput input = { { -4.0f, 0.0f, 0.0f }, { 8.0f, 0.0f, 0.0f }, 1.0f };
b3CastOutput out = b3RayCastSphere( &s, &input );
if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ -1.0f, 0.0f, 0.0f },
( b3Vec3 ){ -1.0f, 0.0f, 0.0f }, 3.0f / 8.0f, 1e-5f ) )
if ( CheckCastHit( out, input.origin, input.translation, (b3Vec3){ -1.0f, 0.0f, 0.0f }, (b3Vec3){ -1.0f, 0.0f, 0.0f },
3.0f / 8.0f, 1e-5f ) )
return 1;
}
{
b3RayCastInput input = { { 0.0f, 4.0f, 0.0f }, { 0.0f, -8.0f, 0.0f }, 1.0f };
b3CastOutput out = b3RayCastSphere( &s, &input );
if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ 0.0f, 1.0f, 0.0f },
( b3Vec3 ){ 0.0f, 1.0f, 0.0f }, 3.0f / 8.0f, 1e-5f ) )
if ( CheckCastHit( out, input.origin, input.translation, (b3Vec3){ 0.0f, 1.0f, 0.0f }, (b3Vec3){ 0.0f, 1.0f, 0.0f },
3.0f / 8.0f, 1e-5f ) )
return 1;
}
{
b3RayCastInput input = { { 0.0f, 0.0f, -4.0f }, { 0.0f, 0.0f, 8.0f }, 1.0f };
b3CastOutput out = b3RayCastSphere( &s, &input );
if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ 0.0f, 0.0f, -1.0f },
( b3Vec3 ){ 0.0f, 0.0f, -1.0f }, 3.0f / 8.0f, 1e-5f ) )
if ( CheckCastHit( out, input.origin, input.translation, (b3Vec3){ 0.0f, 0.0f, -1.0f }, (b3Vec3){ 0.0f, 0.0f, -1.0f },
3.0f / 8.0f, 1e-5f ) )
return 1;
}
@ -337,8 +337,8 @@ static int RayCastSphereHitTest( void )
b3Sphere s2 = { { 5.0f, 0.0f, 0.0f }, 2.0f };
b3RayCastInput input = { { 0.0f, 0.0f, 0.0f }, { 10.0f, 0.0f, 0.0f }, 1.0f };
b3CastOutput out = b3RayCastSphere( &s2, &input );
if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ 3.0f, 0.0f, 0.0f },
( b3Vec3 ){ -1.0f, 0.0f, 0.0f }, 0.3f, 1e-5f ) )
if ( CheckCastHit( out, input.origin, input.translation, (b3Vec3){ 3.0f, 0.0f, 0.0f }, (b3Vec3){ -1.0f, 0.0f, 0.0f },
0.3f, 1e-5f ) )
return 1;
}
@ -347,8 +347,8 @@ static int RayCastSphereHitTest( void )
float k = 0.70710678f;
b3RayCastInput input = { { -3.0f, -3.0f, 0.0f }, { 6.0f, 6.0f, 0.0f }, 1.0f };
b3CastOutput out = b3RayCastSphere( &s, &input );
if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ -k, -k, 0.0f },
( b3Vec3 ){ -k, -k, 0.0f }, 0.382149f, 1e-4f ) )
if ( CheckCastHit( out, input.origin, input.translation, (b3Vec3){ -k, -k, 0.0f }, (b3Vec3){ -k, -k, 0.0f }, 0.382149f,
1e-4f ) )
return 1;
}
@ -447,24 +447,24 @@ static int RayCastCapsuleSideTest( void )
{
b3RayCastInput input = { { 0.0f, 3.0f, 0.0f }, { 0.0f, -6.0f, 0.0f }, 1.0f };
b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input );
if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ 0.0f, 1.0f, 0.0f },
( b3Vec3 ){ 0.0f, 1.0f, 0.0f }, 1.0f / 3.0f, 1e-5f ) )
if ( CheckCastHit( out, input.origin, input.translation, (b3Vec3){ 0.0f, 1.0f, 0.0f }, (b3Vec3){ 0.0f, 1.0f, 0.0f },
1.0f / 3.0f, 1e-5f ) )
return 1;
}
// Same from +z to exercise the other transverse direction.
{
b3RayCastInput input = { { 0.0f, 0.0f, 3.0f }, { 0.0f, 0.0f, -6.0f }, 1.0f };
b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input );
if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ 0.0f, 0.0f, 1.0f },
( b3Vec3 ){ 0.0f, 0.0f, 1.0f }, 1.0f / 3.0f, 1e-5f ) )
if ( CheckCastHit( out, input.origin, input.translation, (b3Vec3){ 0.0f, 0.0f, 1.0f }, (b3Vec3){ 0.0f, 0.0f, 1.0f },
1.0f / 3.0f, 1e-5f ) )
return 1;
}
// Side hit nearer the c1 end.
{
b3RayCastInput input = { { -1.0f, 3.0f, 0.0f }, { 0.0f, -6.0f, 0.0f }, 1.0f };
b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input );
if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ -1.0f, 1.0f, 0.0f },
( b3Vec3 ){ 0.0f, 1.0f, 0.0f }, 1.0f / 3.0f, 1e-5f ) )
if ( CheckCastHit( out, input.origin, input.translation, (b3Vec3){ -1.0f, 1.0f, 0.0f }, (b3Vec3){ 0.0f, 1.0f, 0.0f },
1.0f / 3.0f, 1e-5f ) )
return 1;
}
return 0;
@ -477,8 +477,8 @@ static int RayCastCapsuleObliqueTest( void )
// dot(axis, rayAxis) != 0.
b3RayCastInput input = { { -3.0f, 3.0f, 0.0f }, { 4.0f, -4.0f, 0.0f }, 1.0f };
b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input );
return CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ -1.0f, 1.0f, 0.0f },
( b3Vec3 ){ 0.0f, 1.0f, 0.0f }, 0.5f, 1e-4f );
return CheckCastHit( out, input.origin, input.translation, (b3Vec3){ -1.0f, 1.0f, 0.0f }, (b3Vec3){ 0.0f, 1.0f, 0.0f }, 0.5f,
1e-4f );
}
static int RayCastCapsuleCapTest( void )
@ -489,24 +489,24 @@ static int RayCastCapsuleCapTest( void )
{
b3RayCastInput input = { { 5.0f, 0.0f, 0.0f }, { -8.0f, 0.0f, 0.0f }, 1.0f };
b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input );
if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ 3.0f, 0.0f, 0.0f },
( b3Vec3 ){ 1.0f, 0.0f, 0.0f }, 1.0f / 4.0f, 1e-5f ) )
if ( CheckCastHit( out, input.origin, input.translation, (b3Vec3){ 3.0f, 0.0f, 0.0f }, (b3Vec3){ 1.0f, 0.0f, 0.0f },
1.0f / 4.0f, 1e-5f ) )
return 1;
}
// Off-axis ray through the c2 cap center, approaching from outside the cylinder.
{
b3RayCastInput input = { { 4.0f, 2.0f, 0.0f }, { -4.0f, -4.0f, 0.0f }, 1.0f };
b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input );
if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ 2.0f + k, k, 0.0f },
( b3Vec3 ){ k, k, 0.0f }, 0.323223f, 1e-4f ) )
if ( CheckCastHit( out, input.origin, input.translation, (b3Vec3){ 2.0f + k, k, 0.0f }, (b3Vec3){ k, k, 0.0f }, 0.323223f,
1e-4f ) )
return 1;
}
// Mirror through the c1 cap center.
{
b3RayCastInput input = { { -4.0f, 2.0f, 0.0f }, { 4.0f, -4.0f, 0.0f }, 1.0f };
b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input );
if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ -2.0f - k, k, 0.0f },
( b3Vec3 ){ -k, k, 0.0f }, 0.323223f, 1e-4f ) )
if ( CheckCastHit( out, input.origin, input.translation, (b3Vec3){ -2.0f - k, k, 0.0f }, (b3Vec3){ -k, k, 0.0f },
0.323223f, 1e-4f ) )
return 1;
}
return 0;
@ -581,8 +581,8 @@ static int RayCastCapsuleDegenerateTest( void )
b3Capsule c = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, 1.0f };
b3RayCastInput input = { { -4.0f, 0.0f, 0.0f }, { 8.0f, 0.0f, 0.0f }, 1.0f };
b3CastOutput out = b3RayCastCapsule( &c, &input );
return CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ -1.0f, 0.0f, 0.0f },
( b3Vec3 ){ -1.0f, 0.0f, 0.0f }, 3.0f / 8.0f, 1e-5f );
return CheckCastHit( out, input.origin, input.translation, (b3Vec3){ -1.0f, 0.0f, 0.0f }, (b3Vec3){ -1.0f, 0.0f, 0.0f },
3.0f / 8.0f, 1e-5f );
}
static int RayCastCapsuleClipTest( void )
@ -774,7 +774,7 @@ static int RayCastFarOriginTest( void )
{
for ( int ib = 0; ib < ARRAY_COUNT( offsets ); ++ib )
{
b3Vec3 u = b3Normalize( ( b3Vec3 ){ offsets[ia], offsets[ib], 1.0f } );
b3Vec3 u = b3Normalize( (b3Vec3){ offsets[ia], offsets[ib], 1.0f } );
b3Vec3 origin = b3MulAdd( h, d, u );
b3Vec3 translation = b3MulSV( -2.0f * d, u );
b3RayCastInput input = { origin, translation, 1.0f };
@ -854,19 +854,20 @@ static int RayCastShapeTest( void )
return 0;
}
// The shape stores its name inline, capped at B3_SHAPE_NAME_LENGTH with a reserved null. The stored value
// is the source truncated to the cap, so derive the expectation from the cap and stay valid at any length.
static int CheckShapeName( b3ShapeId shapeId, const char* expected )
{
const char* got = b3Shape_GetName( shapeId );
ENSURE( got != NULL );
ENSURE( got != NULL || expected == NULL );
if ( got == NULL )
{
return 0;
}
int srcLen = expected != NULL ? (int)strlen( expected ) : 0;
int expectLen = srcLen < B3_SHAPE_NAME_LENGTH ? srcLen : B3_SHAPE_NAME_LENGTH;
ENSURE( (int)strlen( got ) == expectLen );
if ( expectLen > 0 )
ENSURE( (int)strlen( got ) == srcLen );
if ( srcLen > 0 )
{
ENSURE( strncmp( got, expected, (size_t)expectLen ) == 0 );
ENSURE( strncmp( got, expected, (size_t)srcLen ) == 0 );
}
return 0;
}
@ -888,7 +889,7 @@ static int ShapeNameTest( void )
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.density = 1.0f;
b3ShapeId shapeId = b3CreateSphereShape( bodyId, &shapeDef, &s );
if ( CheckShapeName( shapeId, "" ) )
if ( CheckShapeName( shapeId, NULL ) )
return 1;
// Name carried on the def.
@ -909,7 +910,7 @@ static int ShapeNameTest( void )
// NULL clears the name.
b3Shape_SetName( shapeId, NULL );
if ( CheckShapeName( shapeId, "" ) )
if ( CheckShapeName( shapeId, NULL ) )
return 1;
b3DestroyWorld( worldId );