BeRo1985 / kraft

Kraft Physics Engine is an open source Object Pascal physics engine library that can be used in 3D games.
107 stars 21 forks source link

Fixed crash when you add rigid body that collides with other and remove it in the same physics step. #21

Closed and3md closed 3 years ago

and3md commented 5 years ago

This PR fixes crash after add and remove rigid body in the same physics step. I have this problem in my game in Castle Game Engine. When level starts I show "Get ready", start timer and set SceneManager.TimeScale := 0;. But user can go back to menu and select another level in this case Kraft rigid bodies are created and destroyed without making physics step. That make Kraft crash, when added and removed body was in collision with something else.

The reason for the crash is AABB box not removed from broad phase: When you add TKraftRigidBody with new shape to Kraft physics (In TKraftRigidBody.Finish) it's calls TKraftShape.SynchronizeProxies. This procedure creates AABB box, adds it to proper AABBDynamicTree and to fPhysics.fBroadPhase. Destruction of the shape remove AABB box from AABB dynamic tree, but not remove it from fPhysics.fBroadPhase. When next physics step come physics engine try to make contact pair with this not existing rigid body and crashes.

More info and CGE example code in this PR: https://github.com/castle-engine/castle-engine/pull/138

BeRo1985 commented 3 years ago

Fixed in a slightly different way. But I will optimize that later, for example via additional ProxyID-Is-In-Linear-Array-Lookup-Bitmap, so that the slow linear searching of the array can be omitted also then.