erincatto / box2d

Box2D is a 2D physics engine for games
https://box2d.org
MIT License
8.36k stars 1.54k forks source link

Provide a more library friendly API for userdata, allocators and logging. #719

Closed Dandielo closed 3 months ago

Dandielo commented 2 years ago

Hey! Just as is written in the repo, here is my proposal for a PR on some API's.

I really enjoy your project, however due to myself strongly avoiding the use of 3rd party libraries in my own project structure I have a few issues explicitly related to box2d's approach to user defined data and functionality.

The biggest offenders are the allocation and userdata API's. If I compile box2d as a standalone library I'm locked out of replacing these functions or changing the userdata without hitting a hard UB wall.

Currently I got around by only defining the symbols and providing them myself during link-time in the final application.

Allocation

However, I would like to provide a PR where the bWorld and related would accept an 'Allocator` structure with three members:

Which would be then used to allocate all the objects instead of the macro approach. This allows you to make use of any allocation API because the user can pass anything he needs and make use of it in the provided function pointers.

Userdata

The userdata issue could also be solved by providing information on size and alignment required and keeping that data in the same memory block a specific box2d is allocated in. For example, if we had the need of userdata of 16 bytes with an alignment of 4 bytes, a box2d type layout would be this:

Then the box2d Type would return a pointer to the userdata by storing that pointed explicitly inside. (If the data is less or equal to 8 you could return the location of the pointer value itself as a optimization)

Logging

Personally, not having a more customizable logging API is less of a problem because it's in most cases anyway not in Release builds, having the way to provide a void* for the userdata would be neat and allow, again, more customization.

If you like the ideas, I'll try to find the time to implement these changes and provide a PR to see what the changes would look like.

Cheers!