Repository: galacean/engine
Pull request #2648: Fix the memory leak issue of the physics
Author: login: luzhuang
Labels: name: bug
description: Something isn't working
name: physics
description: Engine's physical system
Created: 2025-05-06T09:57:58Z | Merged: 2025-05-07T11:56:23Z

### Please check if the PR fulfills these requirements

- [x] The commit message follows our [guidelines](https://github.com/galacean/engine/blob/main/.github/COMMIT_MESSAGE_CONVENTION.md)
- [ ] Tests for the changes have been added (for bug fixes / features)
- [ ] Docs have been added / updated (for bug fixes / features)

### What kind of change does this PR introduce? (Bug fix, feature, docs update, ...)
link: https://github.com/galacean/engine/issues/2647

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **New Features**
  - Improved resource management for physics scenes and objects, including new cleanup and destruction methods for physics engines and scenes.

- **Bug Fixes**
  - Enhanced cleanup of physics resources to prevent potential memory leaks during scene or object destruction.

- **Documentation**
  - Updated documentation to clarify references and improve accuracy regarding physics scene interfaces.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->


Diff:
diff --git a/packages/core/src/Engine.ts b/packages/core/src/Engine.ts
index fa04ef0eda..7aff18f945 100644
--- a/packages/core/src/Engine.ts
+++ b/packages/core/src/Engine.ts
@@ -58,6 +58,8 @@ export class Engine extends EventDispatcher {
   static _pixelsPerUnit: number = 100;
   /** @internal */
   static _physicalObjectsMap: Record<number, ColliderShape> = {};
+  /** @internal */
+  static _nativePhysics: IPhysics;
 
   /** Input manager of Engine. */
   readonly inputManager: InputManager;
@@ -505,7 +507,6 @@ export class Engine extends EventDispatcher {
     this._hardwareRenderer.destroy();
 
     this.removeAllEventListeners();
-
     this._waitingDestroy = false;
     this._destroyed = true;
   }
@@ -622,7 +623,12 @@ export class Engine extends EventDispatcher {
     if (physics) {
       initializePromises.push(
         physics.initialize().then(() => {
-          PhysicsScene._nativePhysics = physics;
+          if (Engine._nativePhysics) {
+            console.warn(
+              "A physics engine has already been configured. All physics operations will now be handled by the newly specified physics engine."
+            );
+          }
+          Engine._nativePhysics = physics;
           this._nativePhysicsManager = physics.createPhysicsManager();
           this._physicsInitialized = true;
           return this;
diff --git a/packages/core/src/Scene.ts b/packages/core/src/Scene.ts
index 973a25bb20..6f13003ee2 100644
--- a/packages/core/src/Scene.ts
+++ b/packages/core/src/Scene.ts
@@ -514,6 +514,8 @@ export class Scene extends EngineObject {
 
     const allCreatedScenes = sceneManager._allCreatedScenes;
     allCreatedScenes.splice(allCreatedScenes.indexOf(this), 1);
+
+    this.physics._destroy();
   }
 
   private _computeLinearFogParams(fogStart: number, fogEnd: number): void {
diff --git a/packages/core/src/physics/CharacterController.ts b/packages/core/src/physics/CharacterController.ts
index 2cef370d3a..f05125b1e5 100644
--- a/packages/core/src/physics/CharacterController.ts
+++ b/packages/core/src/physics/CharacterController.ts
@@ -1,8 +1,8 @@
 import { ICharacterController } from "@galacean/engine-design";
 import { Vector3 } from "@galacean/engine-math";
+import { Engine } from "../Engine";
 import { Entity } from "../Entity";
 import { Collider } from "./Collider";
-import { PhysicsScene } from "./PhysicsScene";
 import { ControllerNonWalkableMode } from "./enums/ControllerNonWalkableMode";
 import { ColliderShape } from "./shape";
 import { deepClone, ignoreClone } from "../clone/CloneManager";
@@ -80,7 +80,7 @@ export class CharacterController extends Collider {
    */
   constructor(entity: Entity) {
     super(entity);
-    (<ICharacterController>this._nativeCollider) = PhysicsScene._nativePhysics.createCharacterController();
+    (<ICharacterController>this._nativeCollider) = Engine._nativePhysics.createCharacterController();
 
     this._setUpDirection = this._setUpDirection.bind(this);
     //@ts-ignore
diff --git a/packages/core/src/physics/DynamicCollider.ts b/packages/core/src/physics/DynamicCollider.ts
index 2f25595ad5..62b469864a 100644
--- a/packages/core/src/physics/DynamicCollider.ts
+++ b/packages/core/src/physics/DynamicCollider.ts
@@ -1,9 +1,9 @@
 import { IDynamicCollider } from "@galacean/engine-design";
 import { Quaternion, Vector3 } from "@galacean/engine-math";
+import { Engine } from "../Engine";
 import { ignoreClone } from "../clone/CloneManager";
 import { Entity } from "../Entity";
 import { Collider } from "./Collider";
-import { PhysicsScene } from "./PhysicsScene";
 
 /**
  * A dynamic collider can act with self-defined movement or physical force.
@@ -306,7 +306,7 @@ export class DynamicCollider extends Collider {
   constructor(entity: Entity) {
     super(entity);
     const { transform } = this.entity;
-    this._nativeCollider = PhysicsScene._nativePhysics.createDynamicCollider(
+    this._nativeCollider = Engine._nativePhysics.createDynamicCollider(
       transform.worldPosition,
       transform.worldRotationQuaternion
     );
diff --git a/packages/core/src/physics/PhysicsMaterial.ts b/packages/core/src/physics/PhysicsMaterial.ts
index 382e469043..3ac16e66d8 100644
--- a/packages/core/src/physics/PhysicsMaterial.ts
+++ b/packages/core/src/physics/PhysicsMaterial.ts
@@ -1,5 +1,5 @@
 import { IPhysicsMaterial } from "@galacean/engine-design";
-import { PhysicsScene } from "./PhysicsScene";
+import { Engine } from "../Engine";
 import { PhysicsMaterialCombineMode } from "./enums/PhysicsMaterialCombineMode";
 
 /**
@@ -17,7 +17,7 @@ export class PhysicsMaterial {
   _nativeMaterial: IPhysicsMaterial;
 
   constructor() {
-    this._nativeMaterial = PhysicsScene._nativePhysics.createPhysicsMaterial(
+    this._nativeMaterial = Engine._nativePhysics.createPhysicsMaterial(
       this._staticFriction,
       this._dynamicFriction,
       this._bounciness,
diff --git a/packages/core/src/physics/PhysicsScene.ts b/packages/core/src/physics/PhysicsScene.ts
index bbcf59863e..5373fd34f9 100644
--- a/packages/core/src/physics/PhysicsScene.ts
+++ b/packages/core/src/physics/PhysicsScene.ts
@@ -14,9 +14,6 @@ import { HitResult } from "./HitResult";
  * A physics scene is a collection of colliders and constraints which can interact.
  */
 export class PhysicsScene {
-  /** @internal */
-  static _nativePhysics: IPhysics;
-
   private static _collision = new Collision();
 
   private _scene: Scene;
@@ -219,7 +216,7 @@ export class PhysicsScene {
 
     const engine = scene.engine;
     if (engine._physicsInitialized) {
-      this._nativePhysicsScene = PhysicsScene._nativePhysics.createPhysicsScene(
+      this._nativePhysicsScene = Engine._nativePhysics.createPhysicsScene(
         engine._nativePhysicsManager,
         this._onContactEnter,
         this._onContactExit,
@@ -445,6 +442,13 @@ export class PhysicsScene {
     this._colliders.garbageCollection();
   }
 
+  /**
+   * @internal
+   */
+  _destroy() {
+    this._nativePhysicsScene?.destroy();
+  }
+
   private _setGravity(): void {
     this._nativePhysicsScene.setGravity(this._gravity);
   }
diff --git a/packages/core/src/physics/StaticCollider.ts b/packages/core/src/physics/StaticCollider.ts
index e81962cbdb..39cdb849be 100644
--- a/packages/core/src/physics/StaticCollider.ts
+++ b/packages/core/src/physics/StaticCollider.ts
@@ -1,6 +1,6 @@
+import { Engine } from "../Engine";
 import { Entity } from "../Entity";
 import { Collider } from "./Collider";
-import { PhysicsScene } from "./PhysicsScene";
 
 /**
  * A static collider component that will not move.
@@ -13,7 +13,7 @@ export class StaticCollider extends Collider {
   constructor(entity: Entity) {
     super(entity);
     const { transform } = this.entity;
-    this._nativeCollider = PhysicsScene._nativePhysics.createStaticCollider(
+    this._nativeCollider = Engine._nativePhysics.createStaticCollider(
       transform.worldPosition,
       transform.worldRotationQuaternion
     );
diff --git a/packages/core/src/physics/joint/FixedJoint.ts b/packages/core/src/physics/joint/FixedJoint.ts
index 569eba4f46..4349041bd3 100644
--- a/packages/core/src/physics/joint/FixedJoint.ts
+++ b/packages/core/src/physics/joint/FixedJoint.ts
@@ -1,5 +1,5 @@
+import { Engine } from "../../Engine";
 import { Collider } from "../Collider";
-import { PhysicsScene } from "../PhysicsScene";
 import { Joint } from "./Joint";
 
 /*
@@ -9,6 +9,6 @@ export class FixedJoint extends Joint {
   protected _createJoint(): void {
     const colliderInfo = this._colliderInfo;
     colliderInfo.collider = this.entity.getComponent(Collider);
-    this._nativeJoint = PhysicsScene._nativePhysics.createFixedJoint(colliderInfo.collider._nativeCollider);
+    this._nativeJoint = Engine._nativePhysics.createFixedJoint(colliderInfo.collider._nativeCollider);
   }
 }
diff --git a/packages/core/src/physics/joint/HingeJoint.ts b/packages/core/src/physics/joint/HingeJoint.ts
index 99fe911bb6..acffbae4b6 100644
--- a/packages/core/src/physics/joint/HingeJoint.ts
+++ b/packages/core/src/physics/joint/HingeJoint.ts
@@ -1,7 +1,7 @@
 import { IHingeJoint } from "@galacean/engine-design";
 import { Vector3 } from "@galacean/engine-math";
+import { Engine } from "../../Engine";
 import { Collider } from "../Collider";
-import { PhysicsScene } from "../PhysicsScene";
 import { HingeJointFlag } from "../enums/HingeJointFlag";
 import { Joint } from "./Joint";
 import { JointLimits } from "./JointLimits";
@@ -160,7 +160,7 @@ export class HingeJoint extends Joint {
   protected _createJoint(): void {
     const colliderInfo = this._colliderInfo;
     colliderInfo.collider = this.entity.getComponent(Collider);
-    this._nativeJoint = PhysicsScene._nativePhysics.createHingeJoint(colliderInfo.collider._nativeCollider);
+    this._nativeJoint = Engine._nativePhysics.createHingeJoint(colliderInfo.collider._nativeCollider);
   }
 
   protected override _syncNative(): void {
diff --git a/packages/core/src/physics/joint/SpringJoint.ts b/packages/core/src/physics/joint/SpringJoint.ts
index edc2d86a63..06708702fc 100644
--- a/packages/core/src/physics/joint/SpringJoint.ts
+++ b/packages/core/src/physics/joint/SpringJoint.ts
@@ -1,6 +1,6 @@
 import { ISpringJoint } from "@galacean/engine-design";
+import { Engine } from "../../Engine";
 import { Collider } from "../Collider";
-import { PhysicsScene } from "../PhysicsScene";
 import { Joint } from "./Joint";
 
 /**
@@ -86,7 +86,7 @@ export class SpringJoint extends Joint {
   protected _createJoint(): void {
     const colliderInfo = this._colliderInfo;
     colliderInfo.collider = this.entity.getComponent(Collider);
-    this._nativeJoint = PhysicsScene._nativePhysics.createSpringJoint(colliderInfo.collider._nativeCollider);
+    this._nativeJoint = Engine._nativePhysics.createSpringJoint(colliderInfo.collider._nativeCollider);
   }
 
   protected override _syncNative(): void {
diff --git a/packages/core/src/physics/shape/BoxColliderShape.ts b/packages/core/src/physics/shape/BoxColliderShape.ts
index c329f8b9d8..12c32a0a4b 100644
--- a/packages/core/src/physics/shape/BoxColliderShape.ts
+++ b/packages/core/src/physics/shape/BoxColliderShape.ts
@@ -1,7 +1,7 @@
 import { ColliderShape } from "./ColliderShape";
 import { IBoxColliderShape } from "@galacean/engine-design";
 import { Vector3 } from "@galacean/engine-math";
-import { PhysicsScene } from "../PhysicsScene";
+import { Engine } from "../../Engine";
 import { deepClone, ignoreClone } from "../../clone/CloneManager";
 
 /**
@@ -26,7 +26,7 @@ export class BoxColliderShape extends ColliderShape {
 
   constructor() {
     super();
-    this._nativeShape = PhysicsScene._nativePhysics.createBoxColliderShape(
+    this._nativeShape = Engine._nativePhysics.createBoxColliderShape(
       this._id,
       this._size,
       this._material._nativeMaterial
diff --git a/packages/core/src/physics/shape/CapsuleColliderShape.ts b/packages/core/src/physics/shape/CapsuleColliderShape.ts
index 87be5c1e26..9df22d6c8c 100644
--- a/packages/core/src/physics/shape/CapsuleColliderShape.ts
+++ b/packages/core/src/physics/shape/CapsuleColliderShape.ts
@@ -1,8 +1,7 @@
 import { ColliderShape } from "./ColliderShape";
 import { ICapsuleColliderShape } from "@galacean/engine-design";
-import { PhysicsScene } from "../PhysicsScene";
+import { Engine } from "../../Engine";
 import { ColliderShapeUpAxis } from "../enums/ColliderShapeUpAxis";
-import { ignoreClone } from "../../clone/CloneManager";
 
 /**
  * Physical collider shape for capsule.
@@ -56,7 +55,7 @@ export class CapsuleColliderShape extends ColliderShape {
 
   constructor() {
     super();
-    this._nativeShape = PhysicsScene._nativePhysics.createCapsuleColliderShape(
+    this._nativeShape = Engine._nativePhysics.createCapsuleColliderShape(
       this._id,
       this._radius,
       this._height,
diff --git a/packages/core/src/physics/shape/PlaneColliderShape.ts b/packages/core/src/physics/shape/PlaneColliderShape.ts
index 82e7f77a58..6d0f56c677 100644
--- a/packages/core/src/physics/shape/PlaneColliderShape.ts
+++ b/packages/core/src/physics/shape/PlaneColliderShape.ts
@@ -1,5 +1,5 @@
 import { Vector3 } from "@galacean/engine-math";
-import { PhysicsScene } from "../PhysicsScene";
+import { Engine } from "../../Engine";
 import { ColliderShape } from "./ColliderShape";
 
 /**
@@ -8,7 +8,7 @@ import { ColliderShape } from "./ColliderShape";
 export class PlaneColliderShape extends ColliderShape {
   constructor() {
     super();
-    this._nativeShape = PhysicsScene._nativePhysics.createPlaneColliderShape(this._id, this._material._nativeMaterial);
+    this._nativeShape = Engine._nativePhysics.createPlaneColliderShape(this._id, this._material._nativeMaterial);
   }
 
   override getClosestPoint(point: Vector3, closestPoint: Vector3): number {
diff --git a/packages/core/src/physics/shape/SphereColliderShape.ts b/packages/core/src/physics/shape/SphereColliderShape.ts
index 16ec6c07b3..13cddc9b44 100644
--- a/packages/core/src/physics/shape/SphereColliderShape.ts
+++ b/packages/core/src/physics/shape/SphereColliderShape.ts
@@ -1,7 +1,6 @@
 import { ColliderShape } from "./ColliderShape";
 import { ISphereColliderShape } from "@galacean/engine-design";
-import { PhysicsScene } from "../PhysicsScene";
-import { ignoreClone } from "../../clone/CloneManager";
+import { Engine } from "../../Engine";
 
 /**
  * Physical collider shape for sphere.
@@ -25,7 +24,7 @@ export class SphereColliderShape extends ColliderShape {
 
   constructor() {
     super();
-    this._nativeShape = PhysicsScene._nativePhysics.createSphereColliderShape(
+    this._nativeShape = Engine._nativePhysics.createSphereColliderShape(
       this._id,
       this._radius,
       this._material._nativeMaterial
diff --git a/packages/design/src/physics/IPhysics.ts b/packages/design/src/physics/IPhysics.ts
index 4ddaa242fc..6522d918ab 100644
--- a/packages/design/src/physics/IPhysics.ts
+++ b/packages/design/src/physics/IPhysics.ts
@@ -134,4 +134,9 @@ export interface IPhysics {
    * @param collider - Affector of joint
    */
   createSpringJoint(collider: ICollider): ISpringJoint;
+
+  /**
+   * Destroy physics scene.
+   */
+  destroy(): void;
 }
diff --git a/packages/design/src/physics/IPhysicsScene.ts b/packages/design/src/physics/IPhysicsScene.ts
index b57138a5aa..a13abe5949 100644
--- a/packages/design/src/physics/IPhysicsScene.ts
+++ b/packages/design/src/physics/IPhysicsScene.ts
@@ -57,4 +57,9 @@ export interface IPhysicsScene {
     onRaycast: (obj: number) => boolean,
     outHitResult?: (shapeUniqueID: number, distance: number, point: Vector3, normal: Vector3) => void
   ): boolean;
+
+  /**
+   * Destroy the physics scene.
+   */
+  destroy(): void;
 }
diff --git a/packages/physics-lite/src/LitePhysics.ts b/packages/physics-lite/src/LitePhysics.ts
index b666f857f0..19bf261abe 100644
--- a/packages/physics-lite/src/LitePhysics.ts
+++ b/packages/physics-lite/src/LitePhysics.ts
@@ -148,4 +148,9 @@ export class LitePhysics implements IPhysics {
   createSpringJoint(collider: LiteCollider): ISpringJoint {
     throw "Physics-lite don't support CapsuleColliderShape. Use Physics-PhysX instead!";
   }
+
+  /**
+   * {@inheritDoc IPhysics.destroy }
+   */
+  destroy(): void {}
 }
diff --git a/packages/physics-lite/src/LitePhysicsScene.ts b/packages/physics-lite/src/LitePhysicsScene.ts
index 13e1bb11ca..ce27dff0ae 100644
--- a/packages/physics-lite/src/LitePhysicsScene.ts
+++ b/packages/physics-lite/src/LitePhysicsScene.ts
@@ -50,14 +50,14 @@ export class LitePhysicsScene implements IPhysicsScene {
   }
 
   /**
-   * {@inheritDoc IPhysicsManager.setGravity }
+   * {@inheritDoc IPhysicsScene.setGravity }
    */
   setGravity(value: Vector3): void {
     console.log("Physics-lite don't support gravity. Use Physics-PhysX instead!");
   }
 
   /**
-   * {@inheritDoc IPhysicsManager.addCollider }
+   * {@inheritDoc IPhysicsScene.addCollider }
    */
   addCollider(actor: LiteCollider): void {
     actor._scene = this;
@@ -70,7 +70,7 @@ export class LitePhysicsScene implements IPhysicsScene {
   }
 
   /**
-   * {@inheritDoc IPhysicsManager.removeCollider }
+   * {@inheritDoc IPhysicsScene.removeCollider }
    */
   removeCollider(collider: LiteCollider): void {
     collider._scene = null;
@@ -84,7 +84,7 @@ export class LitePhysicsScene implements IPhysicsScene {
   }
 
   /**
-   * {@inheritDoc IPhysicsManager.update }
+   * {@inheritDoc IPhysicsScene.update }
    */
   update(deltaTime: number): void {
     const dynamicColliders = this._dynamicColliders;
@@ -97,7 +97,7 @@ export class LitePhysicsScene implements IPhysicsScene {
   }
 
   /**
-   * {@inheritDoc IPhysicsManager.raycast }
+   * {@inheritDoc IPhysicsScene.raycast }
    */
   raycast(
     ray: Ray,
@@ -134,19 +134,24 @@ export class LitePhysicsScene implements IPhysicsScene {
   }
 
   /**
-   * {@inheritDoc IPhysicsManager.addCharacterController }
+   * {@inheritDoc IPhysicsScene.addCharacterController }
    */
   addCharacterController(characterController: ICharacterController): void {
     throw "Physics-lite don't support addCharacterController. Use Physics-PhysX instead!";
   }
 
   /**
-   * {@inheritDoc IPhysicsManager.removeCharacterController }
+   * {@inheritDoc IPhysicsScene.removeCharacterController }
    */
   removeCharacterController(characterController: ICharacterController): void {
     throw "Physics-lite don't support removeCharacterController. Use Physics-PhysX instead!";
   }
 
+  /**
+   * {@inheritDoc IPhysicsScene.destroy }
+   */
+  destroy(): void {}
+
   /**
    * @internal
    */
diff --git a/packages/physics-physx/src/PhysXCharacterController.ts b/packages/physics-physx/src/PhysXCharacterController.ts
index 69c1b99400..97efde7556 100644
--- a/packages/physics-physx/src/PhysXCharacterController.ts
+++ b/packages/physics-physx/src/PhysXCharacterController.ts
@@ -136,6 +136,7 @@ export class PhysXCharacterController implements ICharacterController {
 
     this._pxController = pxManager._getControllerManager().createController(desc);
     this._pxController.setUUID(shape._id);
+    desc.delete();
   }
 
   /**
diff --git a/packages/physics-physx/src/PhysXPhysics.ts b/packages/physics-physx/src/PhysXPhysics.ts
index 4c25e7aef4..a8f7ff4478 100644
--- a/packages/physics-physx/src/PhysXPhysics.ts
+++ b/packages/physics-physx/src/PhysXPhysics.ts
@@ -47,6 +47,9 @@ export class PhysXPhysics implements IPhysics {
   private _runTimeMode: PhysXRuntimeMode;
   private _initializeState: InitializeState = InitializeState.Uninitialized;
   private _initializePromise: Promise<void>;
+  private _defaultErrorCallback: any;
+  private _allocator: any;
+  private _tolerancesScale: any;
 
   constructor(runtimeMode: PhysXRuntimeMode = PhysXRuntimeMode.Auto) {
     this._runTimeMode = runtimeMode;
@@ -90,9 +93,9 @@ export class PhysXPhysics implements IPhysics {
       }
 
       if (runtimeMode == PhysXRuntimeMode.JavaScript) {
-        script.src = `https://mdn.alipayobjects.com/rms/afts/file/A*PXxaQrGL0XsAAAAAAAAAAAAAARQnAQ/physx.release.downgrade.js`;
+        script.src = `https://mdn.alipayobjects.com/rms/afts/file/A*V4pqRqM65UMAAAAAAAAAAAAAARQnAQ/physx.release.downgrade.js`;
       } else if (runtimeMode == PhysXRuntimeMode.WebAssembly) {
-        script.src = `https://mdn.alipayobjects.com/rms/afts/file/A*0Qq8Rob3_5oAAAAAAAAAAAAAARQnAQ/physx.release.js`;
+        script.src = `https://mdn.alipayobjects.com/rms/afts/file/A*jlLNQqp6mBsAAAAAAAAAAAAAARQnAQ/physx.release.js`;
       }
     });
 
@@ -123,9 +126,9 @@ export class PhysXPhysics implements IPhysics {
     this._physX.PxCloseExtensions();
     this._pxPhysics.release();
     this._pxFoundation.release();
-    this._physX = null;
-    this._pxFoundation = null;
-    this._pxPhysics = null;
+    this._defaultErrorCallback.delete();
+    this._allocator.delete();
+    this._tolerancesScale.delete();
   }
 
   /**
@@ -253,12 +256,16 @@ export class PhysXPhysics implements IPhysics {
     const defaultErrorCallback = new physX.PxDefaultErrorCallback();
     const allocator = new physX.PxDefaultAllocator();
     const pxFoundation = physX.PxCreateFoundation(version, allocator, defaultErrorCallback);
-    const pxPhysics = physX.PxCreatePhysics(version, pxFoundation, new physX.PxTolerancesScale(), false, null);
+    const tolerancesScale = new physX.PxTolerancesScale();
+    const pxPhysics = physX.PxCreatePhysics(version, pxFoundation, tolerancesScale, false, null);
 
     physX.PxInitExtensions(pxPhysics, null);
     this._physX = physX;
     this._pxFoundation = pxFoundation;
     this._pxPhysics = pxPhysics;
+    this._defaultErrorCallback = defaultErrorCallback;
+    this._allocator = allocator;
+    this._tolerancesScale = tolerancesScale;
   }
 }
 
diff --git a/packages/physics-physx/src/PhysXPhysicsScene.ts b/packages/physics-physx/src/PhysXPhysicsScene.ts
index 8535227224..b1a2cea0b0 100644
--- a/packages/physics-physx/src/PhysXPhysicsScene.ts
+++ b/packages/physics-physx/src/PhysXPhysicsScene.ts
@@ -21,6 +21,7 @@ export class PhysXPhysicsScene implements IPhysicsScene {
   private _pxFilterData: any;
 
   private _pxScene: any;
+  private _physXSimulationCallbackInstance: any;
 
   private readonly _onContactEnter?: (collision: ICollision) => void;
   private readonly _onContactExit?: (collision: ICollision) => void;
@@ -90,20 +91,25 @@ export class PhysXPhysicsScene implements IPhysicsScene {
     };
 
     const pxPhysics = physXPhysics._pxPhysics;
-    const physXSimulationCallbackInstance = physX.PxSimulationEventCallback.implement(triggerCallback);
-    const sceneDesc = physX.getDefaultSceneDesc(pxPhysics.getTolerancesScale(), 0, physXSimulationCallbackInstance);
+    this._physXSimulationCallbackInstance = physX.PxSimulationEventCallback.implement(triggerCallback);
+    const sceneDesc = physX.getDefaultSceneDesc(
+      pxPhysics.getTolerancesScale(),
+      0,
+      this._physXSimulationCallbackInstance
+    );
     this._pxScene = pxPhysics.createScene(sceneDesc);
+    sceneDesc.delete();
   }
 
   /**
-   * {@inheritDoc IPhysicsManager.setGravity }
+   * {@inheritDoc IPhysicsScene.setGravity }
    */
   setGravity(value: Vector3) {
     this._pxScene.setGravity(value);
   }
 
   /**
-   * {@inheritDoc IPhysicsManager.addCollider }
+   * {@inheritDoc IPhysicsScene.addCollider }
    */
   addCollider(collider: PhysXCollider): void {
     collider._scene = this;
@@ -115,7 +121,7 @@ export class PhysXPhysicsScene implements IPhysicsScene {
   }
 
   /**
-   * {@inheritDoc IPhysicsManager.removeCollider }
+   * {@inheritDoc IPhysicsScene.removeCollider }
    */
   removeCollider(collider: PhysXCollider): void {
     collider._scene = null;
@@ -127,7 +133,7 @@ export class PhysXPhysicsScene implements IPhysicsScene {
   }
 
   /**
-   * {@inheritDoc IPhysicsManager.addCharacterController }
+   * {@inheritDoc IPhysicsScene.addCharacterController }
    */
   addCharacterController(characterController: PhysXCharacterController): void {
     characterController._scene = this;
@@ -148,7 +154,7 @@ export class PhysXPhysicsScene implements IPhysicsScene {
   }
 
   /**
-   * {@inheritDoc IPhysicsManager.removeCharacterController }
+   * {@inheritDoc IPhysicsScene.removeCharacterController }
    */
   removeCharacterController(characterController: PhysXCharacterController): void {
     characterController._scene = null;
@@ -159,7 +165,7 @@ export class PhysXPhysicsScene implements IPhysicsScene {
   }
 
   /**
-   * {@inheritDoc IPhysicsManager.update }
+   * {@inheritDoc IPhysicsScene.update }
    */
   update(elapsedTime: number): void {
     this._simulate(elapsedTime);
@@ -168,7 +174,7 @@ export class PhysXPhysicsScene implements IPhysicsScene {
   }
 
   /**
-   * {@inheritDoc IPhysicsManager.raycast }
+   * {@inheritDoc IPhysicsScene.raycast }
    */
   raycast(
     ray: Ray,
@@ -190,15 +196,18 @@ export class PhysXPhysicsScene implements IPhysicsScene {
       postFilter: (filterData, hit) => {}
     };
 
+    const pxRaycastCallback = this._physXPhysics._physX.PxQueryFilterCallback.implement(raycastCallback);
     const result = this._pxScene.raycastSingle(
       ray.origin,
       ray.direction,
       distance,
       pxHitResult,
       this._pxFilterData,
-      this._physXPhysics._physX.PxQueryFilterCallback.implement(raycastCallback)
+      pxRaycastCallback
     );
 
+    pxRaycastCallback.delete();
+
     if (result && hit != undefined) {
       const { _tempPosition: position, _tempNormal: normal } = PhysXPhysicsScene;
       const { position: pxPosition, normal: pxNormal } = pxHitResult;
@@ -210,6 +219,18 @@ export class PhysXPhysicsScene implements IPhysicsScene {
     return result;
   }
 
+  /**
+   * {@inheritDoc IPhysicsScene.destroy }
+   */
+  destroy(): void {
+    this._pxScene.release();
+    this._physXSimulationCallbackInstance.delete();
+    this._pxRaycastHit.delete();
+    this._pxFilterData.flags.delete();
+    this._pxFilterData.delete();
+    this._pxControllerManager?.release();
+  }
+
   /**
    * @internal
    */
@@ -225,7 +246,7 @@ export class PhysXPhysicsScene implements IPhysicsScene {
    * @internal
    */
   _addColliderShape(id: number) {
-    this._physXManager._eventMap[id] = {};
+    this._physXManager._eventMap[id] = Object.create(null);
   }
 
   /**
diff --git a/packages/physics-physx/src/joint/PhysXJoint.ts b/packages/physics-physx/src/joint/PhysXJoint.ts
index 15ae3bcc67..3284eb2390 100644
--- a/packages/physics-physx/src/joint/PhysXJoint.ts
+++ b/packages/physics-physx/src/joint/PhysXJoint.ts
@@ -102,7 +102,6 @@ export class PhysXJoint implements IJoint {
   destroy(): void {
     if (!this._pxJoint) return;
     this._pxJoint.release();
-    this._pxJoint = null;
     this._collider = null;
   }
   /**
diff --git a/packages/physics-physx/src/shape/PhysXColliderShape.ts b/packages/physics-physx/src/shape/PhysXColliderShape.ts
index 676c6dc5f3..6017721a17 100644
--- a/packages/physics-physx/src/shape/PhysXColliderShape.ts
+++ b/packages/physics-physx/src/shape/PhysXColliderShape.ts
@@ -146,6 +146,7 @@ export abstract class PhysXColliderShape implements IColliderShape {
    */
   destroy(): void {
     this._pxShape.release();
+    this._pxGeometry.delete();
   }
 
   /**
@@ -153,7 +154,9 @@ export abstract class PhysXColliderShape implements IColliderShape {
    */
   _setShapeFlags(flags: ShapeFlag) {
     this._shapeFlags = flags;
-    this._pxShape.setFlags(new this._physXPhysics._physX.PxShapeFlags(this._shapeFlags));
+    const shapeFlags = new this._physXPhysics._physX.PxShapeFlags(this._shapeFlags);
+    this._pxShape.setFlags(shapeFlags);
+    shapeFlags.delete();
   }
 
   protected _setLocalPose(): void {
@@ -166,12 +169,9 @@ export abstract class PhysXColliderShape implements IColliderShape {
   protected _initialize(material: PhysXPhysicsMaterial, id: number): void {
     this._id = id;
     this._pxMaterial = material._pxMaterial;
-    this._pxShape = this._physXPhysics._pxPhysics.createShape(
-      this._pxGeometry,
-      material._pxMaterial,
-      true,
-      new this._physXPhysics._physX.PxShapeFlags(this._shapeFlags)
-    );
+    const shapeFlags = new this._physXPhysics._physX.PxShapeFlags(this._shapeFlags);
+    this._pxShape = this._physXPhysics._pxPhysics.createShape(this._pxGeometry, material._pxMaterial, true, shapeFlags);
+    shapeFlags.delete();
     this._pxShape.setUUID(id);
   }
 


Reviews:
user: login: copilot-pull-request-reviewer[bot]
body: ## Pull Request Overview

This PR addresses a memory leak issue in the physics engine by updating native physics resource management and ensuring proper cleanup of simulation callbacks and scenes. Key changes include:
- Replacing direct accesses to PhysicsScene._nativePhysics with Engine._nativePhysics for improved resource management.
- Adding explicit deletion of simulation callback and native scene resources in PhysXPhysicsScene.
- Implementing destroy methods for LitePhysics and updating API definitions in design interfaces.

### Reviewed Changes

Copilot reviewed 20 out of 20 changed files in this pull request and generated 2 comments.

<details>
<summary>Show a summary per file</summary>

| File | Description |
| ---- | ----------- |
| packages/physics-physx/src/PhysXPhysicsScene.ts | Added deletion and proper management of simulation callbacks and native scene resources. |
| packages/physics-physx/src/PhysXPhysics.ts | Updated native script URLs and changed native physics reference. |
| packages/physics-lite/src/LitePhysicsScene.ts, LitePhysics.ts | Introduced empty destroy() methods to satisfy updated interface contracts. |
| packages/design/src/physics/IPhysicsScene.ts, IPhysics.ts | Added destroy() methods to the physics interfaces. |
| packages/core/src/physics/* | Updated native physics calls to use Engine._nativePhysics. |
| packages/core/src/Scene.ts, Engine.ts | Adjusted cleanup routines to correctly reset native physics references. |
</details>





state: COMMENTED
author_association: NONE
submitted_at: 2025-05-06T09:58:52Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 1**

<details>
<summary>🧹 Nitpick comments (1)</summary><blockquote>

<details>
<summary>packages/physics-lite/src/LitePhysics.ts (1)</summary><blockquote>

`152-155`: **Consider adding comment explaining empty implementation**

While the empty implementation of destroy() is likely appropriate for this lite physics implementation, it would be helpful to add a comment explaining that this is intentional (e.g., "No resources to clean up in lite implementation").

```diff
  /**
   * {@inheritDoc IPhysics.destroy }
   */
-  destroy(): void {}
+  destroy(): void {
+    // No resources to clean up in lite implementation
+  }
```

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 5c732088e453b8bb9c03581bcfe69ee7b99a63ea and 9f3dafd592236175d1212f94e48c32ce26a94e10.

</details>

<details>
<summary>📒 Files selected for processing (20)</summary>

* `packages/core/src/Engine.ts` (3 hunks)
* `packages/core/src/Scene.ts` (1 hunks)
* `packages/core/src/physics/CharacterController.ts` (2 hunks)
* `packages/core/src/physics/DynamicCollider.ts` (2 hunks)
* `packages/core/src/physics/PhysicsMaterial.ts` (2 hunks)
* `packages/core/src/physics/PhysicsScene.ts` (2 hunks)
* `packages/core/src/physics/StaticCollider.ts` (2 hunks)
* `packages/core/src/physics/joint/FixedJoint.ts` (2 hunks)
* `packages/core/src/physics/joint/HingeJoint.ts` (2 hunks)
* `packages/core/src/physics/joint/SpringJoint.ts` (2 hunks)
* `packages/core/src/physics/shape/BoxColliderShape.ts` (2 hunks)
* `packages/core/src/physics/shape/CapsuleColliderShape.ts` (2 hunks)
* `packages/core/src/physics/shape/PlaneColliderShape.ts` (2 hunks)
* `packages/core/src/physics/shape/SphereColliderShape.ts` (2 hunks)
* `packages/design/src/physics/IPhysics.ts` (1 hunks)
* `packages/design/src/physics/IPhysicsScene.ts` (1 hunks)
* `packages/physics-lite/src/LitePhysics.ts` (1 hunks)
* `packages/physics-lite/src/LitePhysicsScene.ts` (1 hunks)
* `packages/physics-physx/src/PhysXPhysics.ts` (1 hunks)
* `packages/physics-physx/src/PhysXPhysicsScene.ts` (4 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🧬 Code Graph Analysis (5)</summary>

<details>
<summary>packages/core/src/physics/StaticCollider.ts (1)</summary><blockquote>

<details>
<summary>packages/core/src/Engine.ts (1)</summary>

* `Engine` (52-692)

</details>

</blockquote></details>
<details>
<summary>packages/core/src/physics/shape/PlaneColliderShape.ts (1)</summary><blockquote>

<details>
<summary>packages/core/src/Engine.ts (1)</summary>

* `Engine` (52-692)

</details>

</blockquote></details>
<details>
<summary>packages/core/src/physics/shape/CapsuleColliderShape.ts (1)</summary><blockquote>

<details>
<summary>packages/core/src/Engine.ts (1)</summary>

* `Engine` (52-692)

</details>

</blockquote></details>
<details>
<summary>packages/core/src/physics/joint/HingeJoint.ts (1)</summary><blockquote>

<details>
<summary>packages/core/src/Engine.ts (1)</summary>

* `Engine` (52-692)

</details>

</blockquote></details>
<details>
<summary>packages/core/src/physics/joint/SpringJoint.ts (1)</summary><blockquote>

<details>
<summary>packages/core/src/Engine.ts (1)</summary>

* `Engine` (52-692)

</details>

</blockquote></details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (2)</summary>

* GitHub Check: codecov
* GitHub Check: e2e (22.x)

</details>

<details>
<summary>🔇 Additional comments (30)</summary><blockquote>

<details>
<summary>packages/core/src/physics/StaticCollider.ts (1)</summary>

`1-1`: **LGTM - Physics reference centralization looks good**

The change shifts the reference from `PhysicsScene._nativePhysics` to `Engine._nativePhysics`, which aligns with the broader refactoring effort to centralize physics management. This is a good architectural change that will help address the memory leak issue by improving lifecycle management.




Also applies to: 16-16

</details>
<details>
<summary>packages/design/src/physics/IPhysics.ts (1)</summary>

`137-141`: **Essential addition for proper resource cleanup**

Adding the `destroy()` method to the `IPhysics` interface is a critical part of fixing the memory leak. This ensures that all implementations provide a way to properly clean up physics resources when they're no longer needed.

</details>
<details>
<summary>packages/core/src/physics/joint/SpringJoint.ts (1)</summary>

`2-2`: **LGTM - Consistent with physics reference centralization**

The change to use `Engine._nativePhysics` instead of `PhysicsScene._nativePhysics` is consistent with the other changes and helps centralize physics resource management in the Engine class. This is part of the architectural improvement to address the memory leak.




Also applies to: 89-89

</details>
<details>
<summary>packages/core/src/physics/shape/CapsuleColliderShape.ts (1)</summary>

`3-3`: **LGTM - Physics reference centralization properly implemented**

The change from `PhysicsScene._nativePhysics` to `Engine._nativePhysics` follows the same pattern as the other files. This consistent implementation across all physics-related classes ensures that the memory leak fix is comprehensive.




Also applies to: 58-58

</details>
<details>
<summary>packages/design/src/physics/IPhysicsScene.ts (1)</summary>

`60-64`: **Appropriate interface extension for resource management.**

Adding the `destroy()` method to the `IPhysicsScene` interface establishes a standardized way for physics scenes to clean up their resources, which directly addresses the memory leak issue mentioned in the PR.

</details>
<details>
<summary>packages/core/src/physics/PhysicsMaterial.ts (2)</summary>

`2-2`: **LGTM: Import change aligns with refactoring.**

Replacing the PhysicsScene import with Engine import is consistent with the centralization of physics resources management.

---

`20-20`: **LGTM: Centralized physics reference.**

Using `Engine._nativePhysics` instead of `PhysicsScene._nativePhysics` properly centralizes the physics interface reference, which helps address the memory leak issue by ensuring consistent resource management.

</details>
<details>
<summary>packages/core/src/physics/joint/HingeJoint.ts (2)</summary>

`3-3`: **LGTM: Import change aligns with refactoring.**

Replacing the PhysicsScene import with Engine import is consistent with the centralization of physics resources management.

---

`163-163`: **LGTM: Centralized physics reference.**

Using `Engine._nativePhysics` instead of `PhysicsScene._nativePhysics` properly centralizes the physics interface reference, which helps address the memory leak issue by ensuring consistent resource management.

</details>
<details>
<summary>packages/core/src/physics/shape/PlaneColliderShape.ts (2)</summary>

`2-2`: **LGTM: Import change aligns with refactoring.**

Replacing the PhysicsScene import with Engine import is consistent with the centralization of physics resources management.

---

`11-11`: **LGTM: Centralized physics reference.**

Using `Engine._nativePhysics` instead of `PhysicsScene._nativePhysics` properly centralizes the physics interface reference, which helps address the memory leak issue by ensuring consistent resource management.

</details>
<details>
<summary>packages/core/src/physics/DynamicCollider.ts (1)</summary>

`3-3`: **Import and usage of Engine._nativePhysics looks good**

The change from PhysicsScene to Engine for accessing the native physics interface is consistent with the PR objective of addressing memory leaks by centralizing physics resource management.



Also applies to: 309-312

</details>
<details>
<summary>packages/core/src/physics/shape/SphereColliderShape.ts (1)</summary>

`3-3`: **Properly updated to use Engine._nativePhysics**

The change correctly aligns this component with the new centralized physics resource management approach.



Also applies to: 27-31

</details>
<details>
<summary>packages/core/src/physics/shape/BoxColliderShape.ts (1)</summary>

`4-4`: **Import and usage of Engine._nativePhysics looks good**

The change correctly aligns this component with the centralized physics resource management pattern.



Also applies to: 29-33

</details>
<details>
<summary>packages/core/src/physics/joint/FixedJoint.ts (2)</summary>

`1-1`: **Updated import to use Engine instead of PhysicsScene**

This change is part of the memory leak fix by centralizing the native physics interface in the Engine class instead of PhysicsScene.

---

`12-12`: **Changed physics interface reference source**

The code now references `Engine._nativePhysics` instead of `PhysicsScene._nativePhysics`, which centralizes the native physics interface management at the engine level.

</details>
<details>
<summary>packages/core/src/physics/CharacterController.ts (2)</summary>

`3-3`: **Updated import to use Engine instead of PhysicsScene**

This change is part of the memory leak fix by centralizing the native physics interface in the Engine class instead of PhysicsScene.

---

`83-83`: **Changed physics interface reference source**

The code now references `Engine._nativePhysics` instead of `PhysicsScene._nativePhysics`, which centralizes the native physics interface management at the engine level.

</details>
<details>
<summary>packages/physics-physx/src/PhysXPhysics.ts (2)</summary>

`93-93`: **Updated URL for PhysX JavaScript runtime**

The source URL for loading the PhysX JavaScript runtime has been updated to a new location at alipayobjects.com.

---

`95-95`: **Updated URL for PhysX WebAssembly runtime**

The source URL for loading the PhysX WebAssembly runtime has been updated to a new location at alipayobjects.com.

</details>
<details>
<summary>packages/physics-lite/src/LitePhysicsScene.ts (1)</summary>

`150-153`: **Good implementation of the destroy method.**

The added empty `destroy()` method appropriately implements the `IPhysicsManager.destroy` interface. Since this is a lightweight physics implementation without any resource allocations that need cleanup, an empty implementation is appropriate.

</details>
<details>
<summary>packages/core/src/Engine.ts (3)</summary>

`61-62`: **Good refactoring - centralizing physics access.**

Moving the native physics reference to a static property on the Engine class is a good architectural decision. This centralization creates a single point of access to the physics system.

---

`626-627`: **Proper initialization of the physics reference.**

Properly assigns the physics instance to the newly added static property. This change complements the architectural refactoring.

---

`509-510`: **Good cleanup - preventing memory leaks.**

Explicitly setting `_nativePhysicsManager` to null during engine destruction helps prevent memory leaks by allowing the garbage collector to reclaim resources.

</details>
<details>
<summary>packages/core/src/physics/PhysicsScene.ts (2)</summary>

`219-219`: **Good update to use centralized physics reference.**

Updated to use `Engine._nativePhysics` instead of the previous static reference. This aligns with the architectural change of centralizing physics access in the Engine class.

---

`445-453`: **Excellent addition of resource cleanup.**

Added a proper destroy method that:
1. Checks if the native physics scene exists before cleanup
2. Calls the native destroy method to release resources
3. Nullifies the reference to allow garbage collection

This is an essential improvement for preventing memory leaks when scenes are destroyed.

</details>
<details>
<summary>packages/physics-physx/src/PhysXPhysicsScene.ts (4)</summary>

`24-24`: **Good improvement - storing the callback instance.**

Added a private member to store the PhysX simulation callback instance, which allows proper cleanup later. This is an important change for memory management.

---

`94-101`: **Good enhancement - proper resource management.**

The PhysX simulation callback is now stored in a class member for later cleanup, and the scene description object is explicitly deleted after use. These changes help prevent memory leaks.

---

`199-210`: **Great improvement in callback management.**

Properly manages the lifecycle of the PhysX query filter callback by:
1. Creating it explicitly outside the raycast call
2. Passing it to the raycast function
3. Explicitly deleting it after use

This pattern prevents memory leaks by ensuring proper cleanup of native resources.

---

`222-230`: **Excellent addition of comprehensive resource cleanup.**

Added a complete destroy method that:
1. Releases the PhysX scene through proper API calls
2. Deletes the native scene object
3. Deletes the simulation callback instance
4. Nullifies the reference to prevent further access

This is a crucial improvement for preventing memory leaks when PhysX resources are no longer needed.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: NONE
submitted_at: 2025-05-06T10:00:50Z
user: login: GuoLei1990
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-05-07T03:29:59Z
user: login: GuoLei1990
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-05-07T03:36:56Z
user: login: GuoLei1990
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-05-07T03:43:35Z
user: login: GuoLei1990
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-05-07T03:46:29Z
user: login: GuoLei1990
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-05-07T04:00:02Z
user: login: luzhuang
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-07T06:53:19Z
user: login: luzhuang
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-07T07:07:05Z
user: login: luzhuang
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-07T07:09:54Z
user: login: luzhuang
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-07T07:10:04Z
user: login: luzhuang
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-07T07:10:08Z

Review comments:
diff_hunk: @@ -210,6 +219,16 @@ export class PhysXPhysicsScene implements IPhysicsScene {
     return result;
   }
 
+  /**
+   * {@inheritDoc IPhysicsManager.destroy }
+   */
+  destroy(): void {
+    this._pxScene.release();
+    this._pxScene.delete();
+    this._physXSimulationCallbackInstance.delete();
+    this._physXSimulationCallbackInstance = null;
path: packages/physics-physx/src/PhysXPhysicsScene.ts
user: login: Copilot
body: Consider adding a null-check before calling delete() on _physXSimulationCallbackInstance to prevent potential errors if destroy() is called multiple times.
```suggestion
    if (this._physXSimulationCallbackInstance) {
      this._physXSimulationCallbackInstance.delete();
      this._physXSimulationCallbackInstance = null;
    }
```
created_at: 2025-05-06T09:58:51Z
author_association: NONE
diff_hunk: @@ -190,15 +196,18 @@ export class PhysXPhysicsScene implements IPhysicsScene {
       postFilter: (filterData, hit) => {}
     };
 
+    const pxRaycastCallback = this._physXPhysics._physX.PxQueryFilterCallback.implement(raycastCallback);
     const result = this._pxScene.raycastSingle(
       ray.origin,
       ray.direction,
       distance,
       pxHitResult,
       this._pxFilterData,
-      this._physXPhysics._physX.PxQueryFilterCallback.implement(raycastCallback)
+      pxRaycastCallback
     );
 
+    pxRaycastCallback.delete();
path: packages/physics-physx/src/PhysXPhysicsScene.ts
user: login: Copilot
body: Add a conditional check to ensure pxRaycastCallback exists before calling delete(), which can improve the resilience of the callback cleanup process.
```suggestion
    if (pxRaycastCallback) {
      pxRaycastCallback.delete();
    }
```
created_at: 2025-05-06T09:58:52Z
author_association: NONE
diff_hunk: @@ -514,6 +514,8 @@ export class Scene extends EngineObject {
 
     const allCreatedScenes = sceneManager._allCreatedScenes;
     allCreatedScenes.splice(allCreatedScenes.indexOf(this), 1);
+
+    this.physics._destroy();
path: packages/core/src/Scene.ts
user: login: coderabbitai[bot]
body: _⚠️ Potential issue_

**Added explicit physics destruction to fix memory leak**

This is the critical change that fixes the memory leak issue. The scene now explicitly calls `physics._destroy()` during scene destruction, which properly cleans up physics resources that were previously leaking.

<!-- This is an auto-generated comment by CodeRabbit -->
created_at: 2025-05-06T10:00:49Z
author_association: NONE
diff_hunk: @@ -505,7 +507,7 @@ export class Engine extends EventDispatcher {
     this._hardwareRenderer.destroy();
 
     this.removeAllEventListeners();
-
+    this._nativePhysicsManager = null;
path: packages/core/src/Engine.ts
user: login: GuoLei1990
body: Maybe don't need
created_at: 2025-05-07T03:27:54Z
author_association: MEMBER
diff_hunk: @@ -445,6 +442,16 @@ export class PhysicsScene {
     this._colliders.garbageCollection();
   }
 
+  /**
+   * @internal
+   */
+  _destroy() {
+    if (this._nativePhysicsScene) {
+      this._nativePhysicsScene.destroy();
+      this._nativePhysicsScene = null;
+    }
path: packages/core/src/physics/PhysicsScene.ts
user: login: GuoLei1990
body: Only `this._nativePhysicsScene.destroy();` is OK!
created_at: 2025-05-07T03:36:46Z
author_association: MEMBER
diff_hunk: @@ -147,6 +147,11 @@ export class LitePhysicsScene implements IPhysicsScene {
     throw "Physics-lite don't support removeCharacterController. Use Physics-PhysX instead!";
   }
 
+  /**
+   * {@inheritDoc IPhysicsManager.destroy }
path: packages/physics-lite/src/LitePhysicsScene.ts
user: login: GuoLei1990
body: Update comments
created_at: 2025-05-07T03:43:30Z
author_association: MEMBER
diff_hunk: @@ -210,6 +219,16 @@ export class PhysXPhysicsScene implements IPhysicsScene {
     return result;
   }
 
+  /**
+   * {@inheritDoc IPhysicsManager.destroy }
+   */
+  destroy(): void {
+    this._pxScene.release();
+    this._pxScene.delete();
+    this._physXSimulationCallbackInstance.delete();
+    this._physXSimulationCallbackInstance = null;
path: packages/physics-physx/src/PhysXPhysicsScene.ts
user: login: GuoLei1990
body: Maybe don't need!
created_at: 2025-05-07T03:46:20Z
author_association: MEMBER
diff_hunk: @@ -622,7 +624,7 @@ export class Engine extends EventDispatcher {
     if (physics) {
       initializePromises.push(
         physics.initialize().then(() => {
-          PhysicsScene._nativePhysics = physics;
+          Engine._nativePhysics = physics;
path: packages/core/src/Engine.ts
user: login: GuoLei1990
body: Maybe use `this.engine` is better!
created_at: 2025-05-07T03:59:58Z
author_association: MEMBER
diff_hunk: @@ -622,7 +624,7 @@ export class Engine extends EventDispatcher {
     if (physics) {
       initializePromises.push(
         physics.initialize().then(() => {
-          PhysicsScene._nativePhysics = physics;
+          Engine._nativePhysics = physics;
path: packages/core/src/Engine.ts
user: login: luzhuang
body: ColliderShape cannot get engine, use console.warn remind the user
created_at: 2025-05-07T06:53:19Z
author_association: CONTRIBUTOR
diff_hunk: @@ -147,6 +147,11 @@ export class LitePhysicsScene implements IPhysicsScene {
     throw "Physics-lite don't support removeCharacterController. Use Physics-PhysX instead!";
   }
 
+  /**
+   * {@inheritDoc IPhysicsManager.destroy }
path: packages/physics-lite/src/LitePhysicsScene.ts
user: login: luzhuang
body: done
created_at: 2025-05-07T07:07:05Z
author_association: CONTRIBUTOR
diff_hunk: @@ -210,6 +219,16 @@ export class PhysXPhysicsScene implements IPhysicsScene {
     return result;
   }
 
+  /**
+   * {@inheritDoc IPhysicsManager.destroy }
+   */
+  destroy(): void {
+    this._pxScene.release();
+    this._pxScene.delete();
+    this._physXSimulationCallbackInstance.delete();
+    this._physXSimulationCallbackInstance = null;
path: packages/physics-physx/src/PhysXPhysicsScene.ts
user: login: luzhuang
body: done
created_at: 2025-05-07T07:09:54Z
author_association: CONTRIBUTOR
diff_hunk: @@ -445,6 +442,16 @@ export class PhysicsScene {
     this._colliders.garbageCollection();
   }
 
+  /**
+   * @internal
+   */
+  _destroy() {
+    if (this._nativePhysicsScene) {
+      this._nativePhysicsScene.destroy();
+      this._nativePhysicsScene = null;
+    }
path: packages/core/src/physics/PhysicsScene.ts
user: login: luzhuang
body: done
created_at: 2025-05-07T07:10:04Z
author_association: CONTRIBUTOR
diff_hunk: @@ -505,7 +507,7 @@ export class Engine extends EventDispatcher {
     this._hardwareRenderer.destroy();
 
     this.removeAllEventListeners();
-
+    this._nativePhysicsManager = null;
path: packages/core/src/Engine.ts
user: login: luzhuang
body: done
created_at: 2025-05-07T07:10:08Z
author_association: CONTRIBUTOR

PR comments:
user: login: coderabbitai[bot]
created_at: 2025-05-06T09:58:05Z
body: <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- walkthrough_start -->

## Walkthrough

This update centralizes the management of the native physics engine by moving the static `_nativePhysics` property from `PhysicsScene` to `Engine`. All physics-related classes now reference `Engine._nativePhysics` for creating native objects. Interfaces and implementations are extended with explicit `destroy()` methods to improve resource cleanup, and PhysX-specific classes now handle native object deletion more robustly.

## Changes

| Files/Groups                                                                                       | Change Summary |
|----------------------------------------------------------------------------------------------------|---------------|
| `packages/core/src/Engine.ts`, `packages/core/src/Scene.ts`                                        | Added static `Engine._nativePhysics` property; updated initialization and destruction logic to manage physics engine and cleanup via `Engine`. |
| `packages/core/src/physics/CharacterController.ts`, `DynamicCollider.ts`, `PhysicsMaterial.ts`, `StaticCollider.ts`, `joint/FixedJoint.ts`, `joint/HingeJoint.ts`, `joint/SpringJoint.ts`, `shape/BoxColliderShape.ts`, `shape/CapsuleColliderShape.ts`, `shape/PlaneColliderShape.ts`, `shape/SphereColliderShape.ts` | Changed all native physics object creation to use `Engine._nativePhysics` instead of `PhysicsScene._nativePhysics`. |
| `packages/core/src/physics/PhysicsScene.ts`                                                        | Removed static `_nativePhysics`; now uses `Engine._nativePhysics`; added `_destroy()` method for cleanup. |
| `packages/design/src/physics/IPhysics.ts`, `IPhysicsScene.ts`                                      | Added `destroy(): void` method to interfaces for explicit resource cleanup. |
| `packages/physics-lite/src/LitePhysics.ts`, `LitePhysicsScene.ts`                                  | Implemented empty `destroy()` methods; updated JSDoc to reference `IPhysicsScene`. |
| `packages/physics-physx/src/PhysXPhysics.ts`                                                       | Added private members for PhysX internals; improved resource cleanup in `destroy()`; updated script URLs. |
| `packages/physics-physx/src/PhysXPhysicsScene.ts`                                                  | Added private member for simulation callback; improved object deletion and added `destroy()` method for cleanup. |
| `packages/physics-physx/src/PhysXCharacterController.ts`                                           | Ensured deletion of descriptor after PhysX controller creation. |
| `packages/physics-physx/src/joint/PhysXJoint.ts`                                                   | Refined `destroy()` to avoid nullifying `_pxJoint` after release. |
| `packages/physics-physx/src/shape/PhysXColliderShape.ts`                                           | Explicitly deletes temporary PhysX flag objects and geometry in `destroy()`. |

## Sequence Diagram(s)

```mermaid
sequenceDiagram
    participant App
    participant Engine
    participant PhysicsScene
    participant NativePhysics

    App->>Engine: Initialize()
    Engine->>NativePhysics: Assign to Engine._nativePhysics
    Engine->>PhysicsScene: Create PhysicsScene with Engine._nativePhysics
    PhysicsScene->>NativePhysics: Create native physics scene

    App->>Scene: Destroy()
    Scene->>PhysicsScene: _destroy()
    PhysicsScene->>NativePhysics: destroy()
    PhysicsScene->>Engine: Cleanup references
```

## Possibly related PRs

- galacean/engine#2481: Modifies `PhysicsMaterial` lifecycle and native integration, directly relating to changes in how native physics objects are managed and destroyed.

## Poem

> A hop and a leap, the engine’s now neat,  
> Physics flows through Engine, no more repeat!  
> With cleanup in tow and destroyers in place,  
> No memory leaks will rabbits chase.  
> The code now is tidy, the logic precise—  
> For every collider, a burrowed device!  
> 🐇✨

<!-- walkthrough_end -->


---

<details>
<summary>📜 Recent review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 1b4e5d3d3372e874af432cb1c71766cf85a91cf2 and 8efa84ba58c3b099bcbb0f71941782bb438c168e.

</details>

<details>
<summary>📒 Files selected for processing (5)</summary>

* `packages/physics-physx/src/PhysXCharacterController.ts` (1 hunks)
* `packages/physics-physx/src/PhysXPhysics.ts` (4 hunks)
* `packages/physics-physx/src/PhysXPhysicsScene.ts` (10 hunks)
* `packages/physics-physx/src/joint/PhysXJoint.ts` (0 hunks)
* `packages/physics-physx/src/shape/PhysXColliderShape.ts` (2 hunks)

</details>

<details>
<summary>💤 Files with no reviewable changes (1)</summary>

* packages/physics-physx/src/joint/PhysXJoint.ts

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (4)</summary>

* packages/physics-physx/src/PhysXCharacterController.ts
* packages/physics-physx/src/shape/PhysXColliderShape.ts
* packages/physics-physx/src/PhysXPhysicsScene.ts
* packages/physics-physx/src/PhysXPhysics.ts

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (3)</summary>

* GitHub Check: codecov
* GitHub Check: build (22.x, windows-latest)
* GitHub Check: e2e (22.x)

</details>

</details>
<!-- internal state start -->


<!-- DwQgtGAEAqAWCWBnSTIEMB26CuAXA9mAOYCmGJATmriQCaQDG+Ats2bgFyQAOFk+AIwBWJBrngA3EsgEBPRvlqU0AgfFwA6NPEgQAfACgjoCEYDEZyAAUASpETZWaCrKNwSPbABsvkCiQBHbGlcSHFcLzpIACIAMXgADzDYDzZmfBdISLQAaxREBw98ADNkj25YWUR4BkRoyAB3NGQHAWZ1Gno5MshsREos7AAvWGxMInRkW0gMRwEBgCYANgAWAA5+LFwUyABxNC80BhJMSABRDCJ4cj8SbnxqghcNGAQpuzRaWn8C6XRINIZeTZPK8QSRZi3Q6dML4HoVKo1ZBMZj3cgYUIlHpkK7kF7uBSsdQA6SINCkSDFfA+fANZDbcoUfAiMQAcmRLHaoTYBXJHiI2HgSi812kLwAErSSFIKAAaGZwmiIXDIDKQWj4BiOdjUeD4LDYbi0ah/BqUDzXBhebBKegNdSwZKoBiwcYkfE7aaoEUYHJRAj5QozOaLVYAdnlDQQLp4P0cKi88iUuG0XnpO0BmRBsfBJEh82uE2KiToHo8Lrd+UYJqIGXgQyizX+AmwRcSZesdgYp3mtwk8BIZvo1B6AFUbAA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lAA -->

<!-- internal state end -->
<!-- finishing_touch_checkbox_start -->

<details open="true">
<summary>✨ Finishing Touches</summary>

- [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate Docstrings

</details>

<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->

---

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=galacean/engine&utm_content=2648):

- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
  - `I pushed a fix in commit <commit_id>, please review it.`
  - `Generate unit testing code for this file.`
  - `Open a follow-up GitHub issue for this discussion.`
- Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples:
  - `@coderabbitai generate unit testing code for this file.`
  -	`@coderabbitai modularize this function.`
- PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
  - `@coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.`
  - `@coderabbitai read src/utils.ts and generate unit testing code.`
  - `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.`
  - `@coderabbitai help me debug CodeRabbit configuration file.`

### Support

Need help? Create a ticket on our [support page](https://www.coderabbit.ai/contact-us/support) for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

### CodeRabbit Commands (Invoked using PR comments)

- `@coderabbitai pause` to pause the reviews on a PR.
- `@coderabbitai resume` to resume the paused reviews.
- `@coderabbitai review` to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
- `@coderabbitai full review` to do a full review from scratch and review all the files again.
- `@coderabbitai summary` to regenerate the summary of the PR.
- `@coderabbitai generate docstrings` to [generate docstrings](https://docs.coderabbit.ai/finishing-touches/docstrings) for this PR.
- `@coderabbitai generate sequence diagram` to generate a sequence diagram of the changes in this PR.
- `@coderabbitai resolve` resolve all the CodeRabbit review comments.
- `@coderabbitai configuration` to show the current CodeRabbit configuration for the repository.
- `@coderabbitai help` to get help.

### Other keywords and placeholders

- Add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed.
- Add `@coderabbitai summary` to generate the high-level summary at a specific location in the PR description.
- Add `@coderabbitai` anywhere in the PR title to generate the title automatically.

### CodeRabbit Configuration File (`.coderabbit.yaml`)

- You can programmatically configure CodeRabbit by adding a `.coderabbit.yaml` file to the root of your repository.
- Please see the [configuration documentation](https://docs.coderabbit.ai/guides/configure-coderabbit) for more information.
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: `# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json`

### Documentation and Community

- Visit our [Documentation](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->
author_association: NONE
user: login: codecov[bot]
created_at: 2025-05-06T10:00:46Z
body: ## [Codecov](https://app.codecov.io/gh/galacean/engine/pull/2648?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=galacean) Report
Attention: Patch coverage is `95.41284%` with `5 lines` in your changes missing coverage. Please review.
> Project coverage is 68.92%. Comparing base [(`5c73208`)](https://app.codecov.io/gh/galacean/engine/commit/5c732088e453b8bb9c03581bcfe69ee7b99a63ea?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=galacean) to head [(`8efa84b`)](https://app.codecov.io/gh/galacean/engine/commit/8efa84ba58c3b099bcbb0f71941782bb438c168e?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=galacean).
> Report is 2 commits behind head on main.

| [Files with missing lines](https://app.codecov.io/gh/galacean/engine/pull/2648?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=galacean) | Patch % | Lines |
|---|---|---|
| [packages/physics-physx/src/PhysXPhysics.ts](https://app.codecov.io/gh/galacean/engine/pull/2648?src=pr&el=tree&filepath=packages%2Fphysics-physx%2Fsrc%2FPhysXPhysics.ts&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=galacean#diff-cGFja2FnZXMvcGh5c2ljcy1waHlzeC9zcmMvUGh5c1hQaHlzaWNzLnRz) | 69.23% | [4 Missing :warning: ](https://app.codecov.io/gh/galacean/engine/pull/2648?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=galacean) |
| [packages/core/src/physics/PhysicsScene.ts](https://app.codecov.io/gh/galacean/engine/pull/2648?src=pr&el=tree&filepath=packages%2Fcore%2Fsrc%2Fphysics%2FPhysicsScene.ts&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=galacean#diff-cGFja2FnZXMvY29yZS9zcmMvcGh5c2ljcy9QaHlzaWNzU2NlbmUudHM=) | 87.50% | [1 Missing :warning: ](https://app.codecov.io/gh/galacean/engine/pull/2648?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=galacean) |

<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff             @@
##             main    #2648      +/-   ##
==========================================
+ Coverage   68.90%   68.92%   +0.02%     
==========================================
  Files         961      961              
  Lines      100604   100691      +87     
  Branches     8715     8730      +15     
==========================================
+ Hits        69322    69403      +81     
- Misses      31022    31028       +6     
  Partials      260      260              
```

| [Flag](https://app.codecov.io/gh/galacean/engine/pull/2648/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=galacean) | Coverage Δ | |
|---|---|---|
| [unittests](https://app.codecov.io/gh/galacean/engine/pull/2648/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=galacean) | `68.92% <95.41%> (+0.02%)` | :arrow_up: |

Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=galacean#carryforward-flags-in-the-pull-request-comment) to find out more.

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/galacean/engine/pull/2648?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=galacean).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=galacean).

<details><summary> :rocket: New features to boost your workflow: </summary>

- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
author_association: NONE