From 5530c72706ea230d9c2cbfb292012c7bee7516b1 Mon Sep 17 00:00:00 2001 From: "jiaxin.lai" Date: Mon, 13 Apr 2020 16:25:55 +0800 Subject: [PATCH] minor refactor physics framework (#6518) * refactor framework * tweaks --- cocos/physics/ammo/ammo-util.ts | 2 +- cocos/physics/ammo/ammo-world.ts | 100 ++++++++---------- .../shapes/ammo-bvh-triangle-mesh-shape.ts | 2 - cocos/physics/cannon/cannon-shared-body.ts | 20 ++-- cocos/physics/cannon/cannon-world.ts | 28 +++-- .../cannon/shapes/cannon-cylinder-shape.ts | 2 +- cocos/physics/cannon/shapes/cannon-shape.ts | 13 +-- .../cannon/shapes/cannon-trimesh-shape.ts | 8 +- cocos/physics/cocos/builtin-world.ts | 15 ++- cocos/physics/framework/physics-system.ts | 42 ++++---- cocos/physics/spec/i-physics-world.ts | 23 ++-- package-lock.json | 12 +-- package.json | 4 +- 13 files changed, 122 insertions(+), 149 deletions(-) diff --git a/cocos/physics/ammo/ammo-util.ts b/cocos/physics/ammo/ammo-util.ts index c4c1055aa2..10aa54c787 100644 --- a/cocos/physics/ammo/ammo-util.ts +++ b/cocos/physics/ammo/ammo-util.ts @@ -27,6 +27,6 @@ export function ammo2CocosQuat (out: T, q: Ammo.btQuaternio } export function ammoDeletePtr (obj: Ammo.Type, klass: Constructor): void { - delete (klass as any).hi[(obj as any).fi]; + delete (klass as any).xi[(obj as any).vi]; } // TODO : Ammo['deletePtr'] = deletePtr; diff --git a/cocos/physics/ammo/ammo-world.ts b/cocos/physics/ammo/ammo-world.ts index a20de61d64..afc24d61a0 100644 --- a/cocos/physics/ammo/ammo-world.ts +++ b/cocos/physics/ammo/ammo-world.ts @@ -60,66 +60,15 @@ export class AmmoWorld implements IPhysicsWorld { } step (timeStep: number, fixTimeStep?: number, maxSubStep?: number) { - - for (let i = 0; i < this.ghosts.length; i++) { - this.ghosts[i].syncSceneToGhost(); - } - - for (let i = 0; i < this.bodies.length; i++) { - this.bodies[i].syncSceneToPhysics(); - } - + if (this.bodies.length == 0 && this.ghosts.length == 0) return; this._btWorld.stepSimulation(timeStep, maxSubStep, fixTimeStep); for (let i = 0; i < this.bodies.length; i++) { this.bodies[i].syncPhysicsToScene(); } + } - const numManifolds = this._btDispatcher.getNumManifolds(); - for (let i = 0; i < numManifolds; i++) { - const manifold = this._btDispatcher.getManifoldByIndexInternal(i); - const numContacts = manifold.getNumContacts(); - for (let j = 0; j < numContacts; j++) { - const manifoldPoint: Ammo.btManifoldPoint = manifold.getContactPoint(j); - const d = manifoldPoint.getDistance(); - if (d <= 0.0001) { - const s0 = manifoldPoint.getShape0(); - const s1 = manifoldPoint.getShape1(); - let shape0: any; - let shape1: any; - if (s0.isCompound()) { - const com = Ammo.castObject(s0, Ammo.btCompoundShape) as Ammo.btCompoundShape; - shape0 = (com.getChildShape(manifoldPoint.m_index0) as any).wrapped; - } else { - shape0 = (s0 as any).wrapped; - } - - if (s1.isCompound()) { - const com = Ammo.castObject(s1, Ammo.btCompoundShape) as Ammo.btCompoundShape; - shape1 = (com.getChildShape(manifoldPoint.m_index1) as any).wrapped; - } else { - shape1 = (s1 as any).wrapped; - } - - // current contact - var item = this.contactsDic.get(shape0.id, shape1.id) as any; - if (item == null) { - item = this.contactsDic.set(shape0.id, shape1.id, - { - shape0: shape0, - shape1: shape1, - contacts: [] - } - ); - } - item.contacts.push(manifoldPoint); - } - } - } - - this.emitEvents(); - - // sync scene to physics again + syncSceneToPhysics (): void { for (let i = 0; i < this.ghosts.length; i++) { this.ghosts[i].syncSceneToGhost(); } @@ -127,7 +76,6 @@ export class AmmoWorld implements IPhysicsWorld { for (let i = 0; i < this.bodies.length; i++) { this.bodies[i].syncSceneToPhysics(); } - } raycast (worldRay: ray, options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { @@ -237,6 +185,48 @@ export class AmmoWorld implements IPhysicsWorld { } emitEvents () { + const numManifolds = this._btDispatcher.getNumManifolds(); + for (let i = 0; i < numManifolds; i++) { + const manifold = this._btDispatcher.getManifoldByIndexInternal(i); + const numContacts = manifold.getNumContacts(); + for (let j = 0; j < numContacts; j++) { + const manifoldPoint: Ammo.btManifoldPoint = manifold.getContactPoint(j); + const d = manifoldPoint.getDistance(); + if (d <= 0.0001) { + const s0 = manifoldPoint.getShape0(); + const s1 = manifoldPoint.getShape1(); + let shape0: any; + let shape1: any; + if (s0.isCompound()) { + const com = Ammo.castObject(s0, Ammo.btCompoundShape) as Ammo.btCompoundShape; + shape0 = (com.getChildShape(manifoldPoint.m_index0) as any).wrapped; + } else { + shape0 = (s0 as any).wrapped; + } + + if (s1.isCompound()) { + const com = Ammo.castObject(s1, Ammo.btCompoundShape) as Ammo.btCompoundShape; + shape1 = (com.getChildShape(manifoldPoint.m_index1) as any).wrapped; + } else { + shape1 = (s1 as any).wrapped; + } + + // current contact + var item = this.contactsDic.get(shape0.id, shape1.id) as any; + if (item == null) { + item = this.contactsDic.set(shape0.id, shape1.id, + { + shape0: shape0, + shape1: shape1, + contacts: [] + } + ); + } + item.contacts.push(manifoldPoint); + } + } + } + // is enter or stay let dicL = this.contactsDic.getLength(); while (dicL--) { diff --git a/cocos/physics/ammo/shapes/ammo-bvh-triangle-mesh-shape.ts b/cocos/physics/ammo/shapes/ammo-bvh-triangle-mesh-shape.ts index f4b780548e..6945826b71 100644 --- a/cocos/physics/ammo/shapes/ammo-bvh-triangle-mesh-shape.ts +++ b/cocos/physics/ammo/shapes/ammo-bvh-triangle-mesh-shape.ts @@ -24,7 +24,6 @@ export class AmmoBvhTriangleMeshShape extends AmmoShape implements ITrimeshShape // TODO: change the mesh after initialization warnID(9620); } else { - const mesh = v; if (mesh && mesh.renderingSubMeshes.length > 0) { this._btTriangleMesh = new Ammo.btTriangleMesh(); @@ -85,7 +84,6 @@ export class AmmoBvhTriangleMeshShape extends AmmoShape implements ITrimeshShape } else { this._btShape = AmmoConstant.instance.EMPTY_SHAPE; } - } } diff --git a/cocos/physics/cannon/cannon-shared-body.ts b/cocos/physics/cannon/cannon-shared-body.ts index 88755e3cbe..07304f4f79 100644 --- a/cocos/physics/cannon/cannon-shared-body.ts +++ b/cocos/physics/cannon/cannon-shared-body.ts @@ -42,7 +42,7 @@ export class CannonSharedBody { readonly node: Node; readonly wrappedWorld: CannonWorld; - readonly body: CANNON.Body = new CANNON.Body(); + readonly body: CANNON.Body; readonly shapes: CannonShape[] = []; wrappedBody: CannonRigidBody | null = null; @@ -84,8 +84,9 @@ export class CannonSharedBody { private constructor (node: Node, wrappedWorld: CannonWorld) { this.wrappedWorld = wrappedWorld; this.node = node; + this.body = new CANNON.Body(); this.body.material = this.wrappedWorld.impl.defaultMaterial; - this.body.addEventListener('collide', this.onCollidedListener); + this.body.addEventListener('cc-collide', this.onCollidedListener); } addShape (v: CannonShape) { @@ -139,14 +140,13 @@ export class CannonSharedBody { syncInitial () { Vec3.copy(this.body.position, this.node.worldPosition); Quat.copy(this.body.quaternion, this.node.worldRotation); - + this.body.aabbNeedsUpdate = true; for (let i = 0; i < this.shapes.length; i++) { this.shapes[i].setScale(this.node.worldScale); } + commitShapeUpdates(this.body); - if (this.body.isSleeping()) { - this.body.wakeUp(); - } + if (this.body.isSleeping()) this.body.wakeUp(); } private destroy () { @@ -192,14 +192,6 @@ export class CannonSharedBody { for (i = 0; i < this.shapes.length; i++) { const shape = this.shapes[i]; shape.collider.emit(CollisionEventObject.type, CollisionEventObject); - - // if (self.collider.node.hasChangedFlags) { - // self.sharedBody.syncSceneToPhysics(); - // } - - // if (other.collider.node.hasChangedFlags) { - // other.sharedBody.syncSceneToPhysics(); - // } } } } diff --git a/cocos/physics/cannon/cannon-world.ts b/cocos/physics/cannon/cannon-world.ts index 3cde9e289a..1891829e36 100644 --- a/cocos/physics/cannon/cannon-world.ts +++ b/cocos/physics/cannon/cannon-world.ts @@ -43,28 +43,34 @@ export class CannonWorld implements IPhysicsWorld { constructor () { this._world = new CANNON.World(); this._world.broadphase = new CANNON.NaiveBroadphase(); + this._world.solver.iterations = 10; + (this._world.solver as any).tolerance = 0.0001; + this._world.defaultContactMaterial.contactEquationStiffness = 1000000; + this._world.defaultContactMaterial.frictionEquationStiffness = 1000000; + this._world.defaultContactMaterial.contactEquationRelaxation = 3; + this._world.defaultContactMaterial.frictionEquationRelaxation = 3; + } - step (deltaTime: number, timeSinceLastCalled?: number, maxSubStep?: number) { - // sync scene to physics + emitEvents (): void { + this._world.emitTriggeredEvents(); + this._world.emitCollisionEvents(); + } + + syncSceneToPhysics (): void { for (let i = 0; i < this.bodies.length; i++) { this.bodies[i].syncSceneToPhysics(); } + } + step (deltaTime: number, timeSinceLastCalled?: number, maxSubStep?: number) { + if (this.bodies.length == 0) return; this._world.step(deltaTime, timeSinceLastCalled, maxSubStep); // sync physics to scene for (let i = 0; i < this.bodies.length; i++) { this.bodies[i].syncPhysicsToScene(); } - - this._world.emitTriggeredEvents(); - this._world.emitCollisionEvents(); - - // sync scene to physics again - for (let i = 0; i < this.bodies.length; i++) { - this.bodies[i].syncSceneToPhysics(); - } } raycastClosest (worldRay: ray, options: IRaycastOptions, result: PhysicsRayResult): boolean { @@ -132,5 +138,5 @@ const raycastOpt: CANNON.IRaycastOptions = { 'checkCollisionResponse': false, 'collisionFilterGroup': -1, 'collisionFilterMask': -1, - 'skipBackFaces': false + 'skipBackFaces': true } \ No newline at end of file diff --git a/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts b/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts index 1d45403248..d55445e39d 100644 --- a/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts @@ -55,7 +55,7 @@ export class CannonCyliderShape extends CannonShape implements ICylinderShape { constructor (radius = 0.5, height = 2, direction = EAxisDirection.Y_AXIS) { super(); - this._shape = new CANNON.Cylinder(radius, radius, height, 18); + this._shape = new CANNON.Cylinder(radius, radius, height, 18, direction == EAxisDirection.Y_AXIS); } onLoad () { diff --git a/cocos/physics/cannon/shapes/cannon-shape.ts b/cocos/physics/cannon/shapes/cannon-shape.ts index 2cee74eee9..1ff2f26f43 100644 --- a/cocos/physics/cannon/shapes/cannon-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-shape.ts @@ -41,9 +41,9 @@ export class CannonShape implements IBaseShape { CannonShape.idToMaterial[mat._uuid] = new CANNON.Material(mat._uuid); } - this._shape!.material = CannonShape.idToMaterial[mat._uuid]; - this._shape!.material.friction = mat.friction; - this._shape!.material.restitution = mat.restitution; + this._shape.material = CannonShape.idToMaterial[mat._uuid]; + this._shape.material.friction = mat.friction; + this._shape.material.restitution = mat.restitution; } } @@ -79,15 +79,16 @@ export class CannonShape implements IBaseShape { this._isBinding = true; this.onComponentSet(); setWrap(this._shape, this); - this._shape.addEventListener('triggered', this.onTriggerListener); + this._shape.addEventListener('cc-trigger', this.onTriggerListener); this._sharedBody = (PhysicsSystem.instance.physicsWorld as CannonWorld).getSharedBody(this._collider.node as Node); this._sharedBody.reference = true; } // virtual - onComponentSet () { } + protected onComponentSet () { } onLoad () { + this.setMaterial(this._collider.sharedMaterial); this.setCenter(this._collider.center); this.setAsTrigger(this._collider.isTrigger); } @@ -167,7 +168,7 @@ export class CannonShape implements IBaseShape { this._orient = Orient; } - private _setCenter (v: IVec3Like) { + protected _setCenter (v: IVec3Like) { const lpos = this._offset as IVec3Like; Vec3.copy(lpos, v); Vec3.multiply(lpos, lpos, this._collider.node.worldScale); diff --git a/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts b/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts index 9af2b1694c..61dc031c1e 100644 --- a/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts @@ -25,9 +25,9 @@ export class CannonTrimeshShape extends CannonShape implements ITrimeshShape { if (mesh && mesh.renderingSubMeshes.length > 0) { const vertices = mesh.renderingSubMeshes[0].geometricInfo!.positions; const indices = mesh.renderingSubMeshes[0].geometricInfo!.indices as Uint16Array; - this._updateInternalMesh(vertices, indices); + this.updateProperties(vertices, indices); } else { - this._updateInternalMesh(new Float32Array(), new Uint16Array()); + this.updateProperties(new Float32Array(), new Uint16Array()); } } else { if (mesh && mesh.renderingSubMeshes.length > 0) { @@ -40,7 +40,7 @@ export class CannonTrimeshShape extends CannonShape implements ITrimeshShape { } } - onComponentSet () { + protected onComponentSet () { this.setMesh(this.collider.mesh); } @@ -55,7 +55,7 @@ export class CannonTrimeshShape extends CannonShape implements ITrimeshShape { this.impl.setScale(v3_cannon0); } - private _updateInternalMesh (vertices: Float32Array, indices: Uint16Array) { + updateProperties (vertices: Float32Array, indices: Uint16Array) { this.impl.vertices = new Float32Array(vertices); this.impl.indices = new Int16Array(indices); this.impl.normals = new Float32Array(indices.length); diff --git a/cocos/physics/cocos/builtin-world.ts b/cocos/physics/cocos/builtin-world.ts index 4157d69649..19917a65c0 100644 --- a/cocos/physics/cocos/builtin-world.ts +++ b/cocos/physics/cocos/builtin-world.ts @@ -46,11 +46,6 @@ export class BuiltInWorld implements IPhysicsWorld { this.shapeArr = tmp; this.shapeArr.length = 0; - // sync scene to physics - for (let i = 0; i < this.bodies.length; i++) { - this.bodies[i].syncSceneToPhysics(); - } - // collision detection for (let i = 0; i < this.bodies.length; i++) { const bodyA = this.bodies[i]; @@ -65,16 +60,18 @@ export class BuiltInWorld implements IPhysicsWorld { bodyA.intersects(bodyB); } } + } - // emit trigger event - this.emitTriggerEvent(); - - // sync scene to physics again + syncSceneToPhysics (): void { for (let i = 0; i < this.bodies.length; i++) { this.bodies[i].syncSceneToPhysics(); } } + emitEvents (): void { + this.emitTriggerEvent(); + } + raycastClosest (worldRay: ray, options: IRaycastOptions, out: PhysicsRayResult): boolean { let tmp_d = Infinity; const max_d = options.maxDistance!; diff --git a/cocos/physics/framework/physics-system.ts b/cocos/physics/framework/physics-system.ts index 3d5f6ea9f9..b0d0057e8b 100644 --- a/cocos/physics/framework/physics-system.ts +++ b/cocos/physics/framework/physics-system.ts @@ -31,6 +31,7 @@ export class PhysicsSystem extends System { return this._enable; } set enable (value: boolean) { + if (!value) this._timeReset = true; this._enable = value; } @@ -110,11 +111,11 @@ export class PhysicsSystem extends System { /** * @en - * Gets the global default physical material. Note that builtin is null. + * Gets the global default physical material. * @zh - * 获取全局的默认物理材质,注意:builtin 时为 null。 + * 获取全局的默认物理材质。 */ - get defaultMaterial (): PhysicMaterial | null { + get defaultMaterial (): PhysicMaterial { return this._material; } @@ -156,7 +157,7 @@ export class PhysicsSystem extends System { * @zh * 获取物理系统实例。 */ - static get instance () { + static get instance (): PhysicsSystem { if (DEBUG && checkPhysicsModule(PhysicsSystem._instance)) { return null as any; } return PhysicsSystem._instance; } @@ -169,10 +170,8 @@ export class PhysicsSystem extends System { private _maxSubStep = 1; private _deltaTime = 1.0 / 60.0; private _useFixedTime = true; - - // private _frameRate = 60; - // private _singleStep = false; - + private _timeSinceLastUpdate = 0; + private _timeReset = true; private readonly _material!: PhysicMaterial; private readonly raycastOptions: IRaycastOptions = { @@ -189,20 +188,18 @@ export class PhysicsSystem extends System { private constructor () { super(); this.physicsWorld = createPhysicsWorld(); - if (!PHYSICS_BUILTIN) { - this.gravity = this._gravity; - this.allowSleep = this._allowSleep; - this._material = new PhysicMaterial(); - this._material.friction = 0.5; - this._material.restitution = 0.0; - this._material.on('physics_material_update', this._updateMaterial, this); - this.physicsWorld.setDefaultMaterial(this._material); - } + this.gravity = this._gravity; + this.allowSleep = this._allowSleep; + this._material = new PhysicMaterial(); + this._material.friction = 0.5; + this._material.restitution = 0.1; + this._material.on('physics_material_update', this._updateMaterial, this); + this.physicsWorld.setDefaultMaterial(this._material); } /** * @en - * Perform a simulation of the physical system, which will now be performed automatically on each frame. + * Perform a simulation of the physics system, which will now be performed automatically on each frame. * @zh * 执行一次物理系统的模拟,目前将在每帧自动执行一次。 * @param deltaTime 与上一次执行相差的时间,目前为每帧消耗时间 @@ -211,18 +208,21 @@ export class PhysicsSystem extends System { if (EDITOR && !this._executeInEditMode) { return; } + if (!this._enable) { + this.physicsWorld.syncSceneToPhysics(); return; } + this._timeSinceLastUpdate = this._timeReset ? 0 : deltaTime; + this.physicsWorld.emitEvents(); director.emit(Director.EVENT_BEFORE_PHYSICS); - + this.physicsWorld.syncSceneToPhysics(); if (this._useFixedTime) { this.physicsWorld.step(this._deltaTime); } else { - this.physicsWorld.step(this._deltaTime, deltaTime, this._maxSubStep); + this.physicsWorld.step(this._deltaTime, this._timeSinceLastUpdate, this._maxSubStep); } - director.emit(Director.EVENT_AFTER_PHYSICS); } diff --git a/cocos/physics/spec/i-physics-world.ts b/cocos/physics/spec/i-physics-world.ts index 700c4f9005..7bf2520d8d 100644 --- a/cocos/physics/spec/i-physics-world.ts +++ b/cocos/physics/spec/i-physics-world.ts @@ -15,25 +15,14 @@ export interface IRaycastOptions { maxDistance: number; } -export interface ICollisionDetect { - - step (deltaTime: number, ...args: any): void; - - /** - * Ray cast, and return information of the closest hit. - * @return True if any body was hit. - */ - raycastClosest (worldRay: ray, options: IRaycastOptions, out: PhysicsRayResult): boolean; - - /** - * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument. - * @return True if any body was hit. - */ - raycast (worldRay: ray, options: IRaycastOptions, pool: RecyclePool, resultes: PhysicsRayResult[]): boolean -} -export interface IPhysicsWorld extends ICollisionDetect { +export interface IPhysicsWorld { readonly impl: any; setGravity: (v: IVec3Like) => void; setAllowSleep: (v: boolean) => void; setDefaultMaterial: (v: PhysicMaterial) => void; + step (deltaTime: number, ...args: any): void; + raycast (worldRay: ray, options: IRaycastOptions, pool: RecyclePool, resultes: PhysicsRayResult[]): boolean + raycastClosest (worldRay: ray, options: IRaycastOptions, out: PhysicsRayResult): boolean; + emitEvents (): void; + syncSceneToPhysics (): void; } \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index a80c2d445c..4ab2a56bac 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2578,9 +2578,9 @@ } }, "@cocos/ammo": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@cocos/ammo/-/ammo-1.0.4.tgz", - "integrity": "sha512-yY/uiYIAWJqlJroUa2coS1rVXCBpgV9denduOBFyEHSzE+EkMXdfATZRCE5g68vIe5ekZ33Dulyxdye6oKYEuw==" + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@cocos/ammo/-/ammo-1.0.6.tgz", + "integrity": "sha512-3qsa9HxZBYddVrxPO1EPXUzbl2YpeEkYvx1QsDXtpMHoFFF8DrxrxBdjc5m44vMpyrO+vYwVn6NjPq7Y1mQFKg==" }, "@cocos/babel-preset-cc": { "version": "2.0.0", @@ -2798,9 +2798,9 @@ } }, "@cocos/cannon": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/@cocos/cannon/-/cannon-1.0.6.tgz", - "integrity": "sha512-JS4t4ZRtw4qonUZ9rMONNa6ugdnm2crDFD8JDZQTJlkh3MKrMAbeqAwoOWrh9PZZM9lxJM2dgrWxIEnU554F6w==" + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@cocos/cannon/-/cannon-1.0.9.tgz", + "integrity": "sha512-bujDtfPI0AZpPkI0yzVoFN7nY1/w6Qbjkcl4jV1YF8uzq5ePCXH3QZefOv9KoGkva3PhPX/UTLnfZ9cP7wiGjA==" }, "@jest/console": { "version": "24.9.0", diff --git a/package.json b/package.json index 2dac3b6493..05221db9fe 100644 --- a/package.json +++ b/package.json @@ -52,7 +52,7 @@ "yargs": "^12.0.5" }, "dependencies": { - "@cocos/ammo": "^1.0.4", - "@cocos/cannon": "^1.0.6" + "@cocos/ammo": "^1.0.6", + "@cocos/cannon": "^1.0.9" } }