Skip to content

Commit 8f81661

Browse files
committed
Merge pull request #108239 from mihe/jolt/scene-switch-crash
Fix crash in Jolt Physics when switching scenes in editor
2 parents 6340fa0 + e2985a2 commit 8f81661

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

modules/jolt_physics/spaces/jolt_space_3d.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,12 @@ void JoltSpace3D::remove_object(const JPH::BodyID &p_jolt_id) {
436436
}
437437

438438
body_iface.DestroyBody(p_jolt_id);
439+
440+
// If we're never going to step this space, like in the editor viewport, we need to manually clean up Jolt's broad phase instead, otherwise performance can degrade when doing things like switching scenes.
441+
// We'll never actually have zero bodies in any space though, since we always have the default area, so we check if there's one or fewer left instead.
442+
if (!JoltPhysicsServer3D::get_singleton()->is_active() && physics_system->GetNumBodies() <= 1) {
443+
physics_system->OptimizeBroadPhase();
444+
}
439445
}
440446

441447
void JoltSpace3D::flush_pending_objects() {

thirdparty/jolt_physics/Jolt/Physics/Collision/BroadPhase/BroadPhaseQuadTree.cpp

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,14 +73,15 @@ void BroadPhaseQuadTree::Optimize()
7373
{
7474
JPH_PROFILE_FUNCTION();
7575

76+
// Free the previous tree so we can create a new optimized tree
7677
FrameSync();
7778

7879
LockModifications();
7980

8081
for (uint l = 0; l < mNumLayers; ++l)
8182
{
8283
QuadTree &tree = mLayers[l];
83-
if (tree.HasBodies())
84+
if (tree.HasBodies() || tree.IsDirty())
8485
{
8586
QuadTree::UpdateState update_state;
8687
tree.UpdatePrepare(mBodyManager->GetBodies(), mTracking, update_state, true);
@@ -90,6 +91,9 @@ void BroadPhaseQuadTree::Optimize()
9091

9192
UnlockModifications();
9293

94+
// Free the tree from before we created a new optimized tree
95+
FrameSync();
96+
9397
mNextLayerToUpdate = 0;
9498
}
9599

thirdparty/jolt_physics/Jolt/Physics/Collision/BroadPhase/QuadTree.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,7 @@ void QuadTree::UpdatePrepare(const BodyVector &inBodies, TrackingVector &ioTrack
301301
#endif
302302

303303
// Create space for all body ID's
304-
NodeID *node_ids = new NodeID [mNumBodies];
304+
NodeID *node_ids = mNumBodies > 0? new NodeID [mNumBodies] : nullptr;
305305
NodeID *cur_node_id = node_ids;
306306

307307
// Collect all bodies

0 commit comments

Comments
 (0)