Destroying a body causes a crash?

Jul 29, 2012 at 11:48 AM

Heya,

I've got a class named "Bullet", and, as the name implies, it's a bullet that is spawned when the user presses the fire button. Now, the bullets are destroyed if the bullet travels far enough from the player or if the lifetime of the bullet exceeds a certain amount of seconds.

I use body.Dispose() to get rid of the bullet bodies, but it causes random crashes every now and then. Sometimes I can shoot bullets for a few minutes, sometimes it crashes right on the first bullet.

The call stack tells me that the crash happens in DynamicTree.cs, in the Query() method. It's also weird that it's not always the same line of code - it varies every time. So far I've got call stacks to these rows:

_stack.Push(_root);
...
int nodeId = _stack.Pop();
...
_stack.Push(node.Child2);

The exception I get is IndexOutOfRangeException.

What could possibly be the problem? The world and the body.Dispose() call are ran in the same thread, so it shouldn't be a threading problem as was the case with another problem in the earlier discussions.

Jul 29, 2012 at 12:32 PM

Does this also happen if you just call World.RemoveBody() instead of Body.Dispose()? Could it be that the DynamicTree holds some stuff from the body that are not released when the GC tries to kick in or vice-versa.

Jul 29, 2012 at 1:07 PM

Yeah, I've tried both ways, there's no difference. I surrounded the insides of the Query() function into try-catch, and after a while of random single messages, the function goes batshit crazy, causing exceptions every frame, even if there's no bodies disposed.

Coordinator
Aug 7, 2012 at 2:30 AM

Are you doing this inside a collision event? I implemented a non-locking simulation in Farseer that should enable you to remove objects while an update is calculated, however, sometimes it can go crazy. If you are doing this in the OnCollision event, I would recommend that you return false inside it to avoid the engine calculating any further forces on the bullets as they are destroyed.

Aug 7, 2012 at 5:46 AM

I fiddled around with the code, and I noticed that while I was rapidly generating bodies, it wasn't caused by the destruction, but the creation. It only happens with the DynamicTreeBroadPhase. If I use QuadTree, this problem won't happen. I don't use the OnCollision / OnSeparation events with the bullets, instead I have a timer in the update function that checks whether or not the bullet has "lived" long enough.

Coordinator
Aug 27, 2012 at 11:51 PM

Could you post the code that replicates this? I would prefer it if you implemented it inside the Testbed project and uploaded the .cs file to a service like http://ge.tt or post it here if it is small.