jrouwe / JoltPhysics

A multi core friendly rigid body physics and collision detection library. Written in C++. Suitable for games and VR applications. Used by Horizon Forbidden West.
MIT License
6.71k stars 447 forks source link

Question regarding objects lifecycle #966

Closed MrOnlineCoder closed 8 months ago

MrOnlineCoder commented 8 months ago

Hi! I have a few questions about objects lifecycle (memory allocation/freeing), as I am getting some strange double-free/segfault errors, and I guess maybe I missed something the docs about it :

1) Does calling JPH::BodyInterface::removeBody() also deletes (frees the memory) of the body itself, or the cleanup is left for my user-code? 2) As I understand, many of Jolt methods return a JPH::Ref<T> which from my understading is a some sort of reference-counting smart pointer? Is it okay to have utility methods like this:

JPH::ShapeRefC PhysicsUtils::createBoxShape(
    float halfWidth,
    float halfHeight,
    float halfDepth)
{
    JPH::BoxShapeSettings shapeSettings(
        JPH::Vec3(halfWidth, halfHeight, halfDepth), 0);

    auto boxShapeResult = shapeSettings.Create();

    return boxShapeResult.Get();
}

Do I need to take care of boxShapeResult in any way, or will it be freed automatically? 3) Does the destruction of the physics system also removes and deletes all rigid bodies that were added to it?

Thanks in advance and big thumbs up for the work - I really enjoy working with the engine!

jrouwe commented 8 months ago

Does calling JPH::BodyInterface::removeBody() also deletes (frees the memory) of the body itself, or the cleanup is left for my user-code?

No BodyInterface::DestroyBody deletes the body (and releases the reference to the shape).

Do I need to take care of boxShapeResult in any way, or will it be freed automatically?

Your function should be correct as long as the caller of createBoxShape immediately stores the result in a ShapeRefC

3) Does the destruction of the physics system also removes and deletes all rigid bodies that were added to it?

All bodies are automatically cleaned up on destruction.

MrOnlineCoder commented 8 months ago

Thanks for explanations, just the Remove/DestroyBody part was a bit confusing to me.

jrouwe commented 8 months ago

I added a bit of documentation here: https://jrouwe.github.io/JoltPhysics/index.html#memory-management

MrOnlineCoder commented 8 months ago

Amazing, much clearer now, thanks