minor refactor physics framework (#6518)

* refactor framework

* tweaks
This commit is contained in:
jiaxin.lai
2020-04-13 16:25:55 +08:00
committed by GitHub
parent 9e7c3097ba
commit 5530c72706
13 changed files with 122 additions and 149 deletions
+1 -1
View File
@@ -27,6 +27,6 @@ export function ammo2CocosQuat<T extends IQuatLike> (out: T, q: Ammo.btQuaternio
}
export function ammoDeletePtr (obj: Ammo.Type, klass: Constructor<Ammo.Type>): void {
delete (klass as any).hi[(obj as any).fi];
delete (klass as any).xi[(obj as any).vi];
}
// TODO : Ammo['deletePtr'] = deletePtr;
+45 -55
View File
@@ -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<PhysicsRayResult>, 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--) {
@@ -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;
}
}
}
+6 -14
View File
@@ -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();
// }
}
}
}
+17 -11
View File
@@ -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
}
@@ -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 () {
+7 -6
View File
@@ -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);
@@ -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);
+6 -9
View File
@@ -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!;
+21 -21
View File
@@ -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);
}
+6 -17
View File
@@ -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<PhysicsRayResult>, 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<PhysicsRayResult>, resultes: PhysicsRayResult[]): boolean
raycastClosest (worldRay: ray, options: IRaycastOptions, out: PhysicsRayResult): boolean;
emitEvents (): void;
syncSceneToPhysics (): void;
}
+6 -6
View File
@@ -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",
+2 -2
View File
@@ -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"
}
}