From b7869b595da3e3edd201df7a7597cb63d11b06e2 Mon Sep 17 00:00:00 2001 From: Leslie Leigh Date: Fri, 8 Mar 2019 11:30:14 +0800 Subject: [PATCH] restructure physics (#3985) --- cocos/3d/assets/physics/material.ts | 10 - .../framework/physics/collider-component.ts | 28 +- cocos/3d/framework/physics/constraints.ts | 149 ---- .../3d/framework/physics/contact-material.ts | 90 --- .../physics/detail/physics-based-component.ts | 210 ++---- cocos/3d/framework/physics/index.ts | 2 - cocos/3d/framework/physics/physics-system.ts | 7 +- .../framework/physics/rigid-body-component.ts | 104 +-- cocos/3d/framework/physics/util.ts | 33 - cocos/3d/framework/physics/world.ts | 133 ---- cocos/3d/{index.js => index.ts} | 3 +- cocos/3d/physics/api.d.ts | 240 +++++++ cocos/3d/physics/cannon-impl.ts | 657 ++++++++++++++++++ cocos/3d/physics/impl-selector.ts | 8 + cocos/3d/physics/instance.ts | 25 + cocos/core/value-types/mat4.ts | 2 +- 16 files changed, 1030 insertions(+), 671 deletions(-) delete mode 100644 cocos/3d/framework/physics/constraints.ts delete mode 100644 cocos/3d/framework/physics/contact-material.ts delete mode 100644 cocos/3d/framework/physics/util.ts delete mode 100644 cocos/3d/framework/physics/world.ts rename cocos/3d/{index.js => index.ts} (96%) create mode 100644 cocos/3d/physics/api.d.ts create mode 100644 cocos/3d/physics/cannon-impl.ts create mode 100644 cocos/3d/physics/impl-selector.ts create mode 100644 cocos/3d/physics/instance.ts diff --git a/cocos/3d/assets/physics/material.ts b/cocos/3d/assets/physics/material.ts index 788dc97e9c..49191f2886 100644 --- a/cocos/3d/assets/physics/material.ts +++ b/cocos/3d/assets/physics/material.ts @@ -1,7 +1,6 @@ // @ts-check -import CANNON from 'cannon'; import { Asset } from '../../../assets/asset'; import { ccclass, property } from '../../../core/data/class-decorator'; @@ -13,8 +12,6 @@ export class PhysicsMaterial extends Asset { @property public _restitution = -1; - private _cannonMaterial: CANNON.Material; - /** * Friction for this material. * If non-negative, it will be used instead of the friction given by ContactMaterials. @@ -26,7 +23,6 @@ export class PhysicsMaterial extends Asset { set friction (value) { this._friction = value; - this._cannonMaterial.friction = value; } /** @@ -40,16 +36,10 @@ export class PhysicsMaterial extends Asset { set restitution (value) { this._restitution = value; - this._cannonMaterial.restitution = value; } constructor () { super(); - this._cannonMaterial = new CANNON.Material(''); - } - - public _getImpl () { - return this._cannonMaterial; } } cc.PhysicsMaterial = PhysicsMaterial; diff --git a/cocos/3d/framework/physics/collider-component.ts b/cocos/3d/framework/physics/collider-component.ts index 607a2a09d2..b9b47f9423 100644 --- a/cocos/3d/framework/physics/collider-component.ts +++ b/cocos/3d/framework/physics/collider-component.ts @@ -7,9 +7,13 @@ import { } from '../../../core/data/class-decorator'; import Vec3 from '../../../core/value-types/vec3'; import { vec3 } from '../../../core/vmath'; +import { BoxShapeBase, ShapeBase, SphereShapeBase } from '../../physics/api'; +import { createBoxShape, createSphereShape } from '../../physics/instance'; import { PhysicsBasedComponent } from './detail/physics-based-component'; export class ColliderComponentBase extends PhysicsBasedComponent { + protected _shapeBase: ShapeBase | null = null; + /** * The center of the collider, in local space. */ @@ -20,9 +24,7 @@ export class ColliderComponentBase extends PhysicsBasedComponent { set center (value: Vec3) { vec3.copy(this._center, value); - if (this.sharedBody) { - this.sharedBody.updateCollidier(this); - } + this._shapeBase!.setCenter(this._center); } @property @@ -38,16 +40,16 @@ export class ColliderComponentBase extends PhysicsBasedComponent { } public onEnable () { - this.sharedBody!.addCollider(this); + this.sharedBody!.body.addShape(this._shapeBase!); } public onDisable () { - this.sharedBody!.removeCollider(this); + this.sharedBody!.body.removeShape(this._shapeBase!); } public destroy () { if (this.sharedBody) { - this.sharedBody.removeCollider(this); + this.sharedBody.body.removeShape(this._shapeBase!); } super.destroy(); } @@ -61,8 +63,12 @@ export class BoxColliderComponent extends ColliderComponentBase { @property private _size: Vec3 = new Vec3(0, 0, 0); + private _shape: BoxShapeBase; + constructor () { super(); + this._shape = createBoxShape(this._size); + this._shapeBase = this._shape; } public onLoad () { @@ -81,8 +87,9 @@ export class BoxColliderComponent extends ColliderComponentBase { set size (value) { vec3.copy(this._size, value); + this._shape.setSize(this._size); if (this.sharedBody) { - this.sharedBody.updateCollidier(this); + this.sharedBody.body.commitShapeUpdates(); } } } @@ -95,8 +102,12 @@ export class SphereColliderComponent extends ColliderComponentBase { @property private _radius: number = 0; + private _shape: SphereShapeBase; + constructor () { super(); + this._shape = createSphereShape(this._radius); + this._shapeBase = this._shape; } public onLoad () { @@ -114,8 +125,9 @@ export class SphereColliderComponent extends ColliderComponentBase { set radius (value) { this._radius = value; + this._shape.setRadius(value); if (this.sharedBody) { - this.sharedBody.updateCollidier(this); + this.sharedBody.body.commitShapeUpdates(); } } } diff --git a/cocos/3d/framework/physics/constraints.ts b/cocos/3d/framework/physics/constraints.ts deleted file mode 100644 index 726bc00753..0000000000 --- a/cocos/3d/framework/physics/constraints.ts +++ /dev/null @@ -1,149 +0,0 @@ - -import CANNON from 'cannon'; -import { Vec3 } from '../../../core/value-types'; -import { PhysicsBody } from './body'; -import { getWrap, setWrap, toCannonVec3 } from './util'; - -/** - * Constraint options. - */ -export interface IConstraintOptions { - /** - * Set to true if you want the bodies to collide when they are connected. - * @default true - */ - collideConnected?: boolean; - - /** - * @default true - */ - wakeUpBodies?: boolean; -} - -/** - * Base class for Constraint classes. - */ -export class Constraint { - protected _cannonConstraint: CANNON.Constraint; - - /** - * @param first The first body. - * @param second The second body. - * @param options Options. - */ - protected constructor (cannonConstraint: CANNON.Constraint) { - this._cannonConstraint = cannonConstraint; - setWrap(this._cannonConstraint, this); - } - - get first () { - return getWrap(this._cannonConstraint.bodyA); - } - - get second () { - return getWrap(this._cannonConstraint.bodyB); - } - - public enable () { - this._cannonConstraint.enable(); - } - - public disable () { - this._cannonConstraint.disable(); - } - - public update () { - this._cannonConstraint.update(); - } - - public _getImpl () { - return this._cannonConstraint; - } -} - -/** - * DistanceConstraint options. - */ -export interface IDistanceConstraintOptions { - /** - * The maximum force that should be applied to constrain the bodies. - */ - maxForce?: number; -} - -/** - * Constrains two bodies to be at a constant distance from each others center of mass. - */ -export class DistanceConstraint extends Constraint { - /** - * @param first The first body. - * @param second The second body. - * @param distance The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB. - * @param options Options. - */ - constructor (first: PhysicsBody, second: PhysicsBody, distance?: number, options?: IDistanceConstraintOptions) { - super(new CANNON.DistanceConstraint( - first._getCannonBody(), - second._getCannonBody(), - distance!, - options === undefined ? undefined : options.maxForce)); - } -} - -/** - * PointToPointConstraint options. - */ -export interface IPointToPointConstraintOptions { - /** - * The maximum force that should be applied to constrain the bodies. - */ - maxForce?: number; -} - -/** - * Connects two bodies at given offset points. - */ -export class PointToPointConstraint extends Constraint { - /** - * @param first The first body. - * @param firstPivot The point relative to the center of mass of the first body which the first body is constrained to. - * @param second The second body. - * @param secondPivot The point relative to the center of mass of the second body which the second body is constrained to. - * @param options Options. - */ - constructor (first: PhysicsBody, firstPivot: Vec3, second: PhysicsBody, secondPivot: Vec3, options?: IPointToPointConstraintOptions) { - super(new CANNON.PointToPointConstraint( - first._getCannonBody(), - toCannonVec3(firstPivot), - second._getCannonBody(), - toCannonVec3(secondPivot), - options === undefined ? undefined : options.maxForce)); - } -} - -/** - * LockConstraint options. - */ -export interface ILockConstraintOptions { - /** - * The maximum force that should be applied to constrain the bodies. - */ - maxForce?: number; -} - -/** - * The Lock constraint will remove all degrees of freedom between the bodies. - */ -export class LockConstraint extends Constraint { - /** - * @param first The first body. - * @param second The second body. - * @param options Options. - */ - constructor (first: PhysicsBody, second: PhysicsBody, options?: ILockConstraintOptions) { - super(new CANNON.LockConstraint( - first._getCannonBody(), - second._getCannonBody(), - options)); - } -} diff --git a/cocos/3d/framework/physics/contact-material.ts b/cocos/3d/framework/physics/contact-material.ts deleted file mode 100644 index eee05162bb..0000000000 --- a/cocos/3d/framework/physics/contact-material.ts +++ /dev/null @@ -1,90 +0,0 @@ -import CANNON from 'cannon'; -import { PhysicsMaterial } from '../../assets/physics/material'; - -export class ContactMaterial { - private _cannonContactMaterial: CANNON.ContactMaterial; - - constructor (lhs: PhysicsMaterial, rhs: PhysicsMaterial) { - const opts: CANNON.IContactMaterialOptions = { - friction: 0.3, - restitution: 0.3, - contactEquationStiffness: 1e7, - contactEquationRelaxation: 3, - frictionEquationStiffness: 1e7, - frictionEquationRelaxation: 3, - }; - this._cannonContactMaterial = new CANNON.ContactMaterial(lhs._getImpl(), rhs._getImpl(), opts); - } - - /** - * Friction coefficient. Default value 0.3. - */ - get friction () { - return this._cannonContactMaterial.friction; - } - - set friction (value) { - this._cannonContactMaterial.friction = value; - } - - /** - * Restitution coefficient. Default value 0.3. - */ - get restitution () { - return this._cannonContactMaterial.restitution; - } - - set restitution (value) { - this._cannonContactMaterial.restitution = value; - } - - /** - * Stiffness of the produced contact equations. Default value 1e7. - */ - get contactEquationStiffness () { - return this._cannonContactMaterial.contactEquationStiffness; - } - - set contactEquationStiffness (value) { - this._cannonContactMaterial.contactEquationStiffness = value; - } - - /** - * Relaxation time of the produced contact equations. Default value 0.3. - */ - get contactEquationRelaxation () { - return this._cannonContactMaterial.contactEquationRelaxation; - } - - set contactEquationRelaxation (value) { - this._cannonContactMaterial.contactEquationRelaxation = value; - } - - /** - * Stiffness of the produced friction equations. Default value 1e7. - */ - get frictionEquationStiffness () { - return this._cannonContactMaterial.frictionEquationStiffness; - } - - set frictionEquationStiffness (value) { - this._cannonContactMaterial.frictionEquationStiffness = value; - } - - /** - * Relaxation time of the produced friction equations. Default value 3. - */ - get frictionEquationRelaxation () { - return this._cannonContactMaterial.frictionEquationRelaxation; - } - - set frictionEquationRelaxation (value) { - this._cannonContactMaterial.frictionEquationRelaxation = value; - } - - public _getImpl () { - return this._cannonContactMaterial; - } -} - -cc.ContactMaterial = ContactMaterial; diff --git a/cocos/3d/framework/physics/detail/physics-based-component.ts b/cocos/3d/framework/physics/detail/physics-based-component.ts index 48113e380b..c8fc9ab27e 100644 --- a/cocos/3d/framework/physics/detail/physics-based-component.ts +++ b/cocos/3d/framework/physics/detail/physics-based-component.ts @@ -1,13 +1,10 @@ -import CANNON from 'cannon'; import { Component } from '../../../../components/component'; import { ccclass } from '../../../../core/data/class-decorator'; import { Quat, Vec3 } from '../../../../core/value-types'; import { quat, vec3 } from '../../../../core/vmath'; import { Node } from '../../../../scene-graph/node'; -import { BoxColliderComponent, ColliderComponentBase, SphereColliderComponent } from '../collider-component'; -import { DefaultPhysicsMaterial } from '../default-material'; -import { getWrap, setWrap } from '../util'; -import { PhysicsWorld } from '../world'; +import { AfterStepCallback, BeforeStepCallback, ICollisionCallback, ICollisionEvent, PhysicsWorldBase, RigidBodyBase } from '../../../physics/api'; +import { createRigidBody } from '../../../physics/instance'; export class PhysicsBasedComponent extends Component { @@ -26,11 +23,6 @@ export class PhysicsBasedComponent extends Component { public onLoad () { this._refSharedBody(); - this._sharedBody!.syncPhysWithScene(); - } - - public start () { - this._sharedBody!.syncPhysWithScene(); } public destroy () { @@ -42,7 +34,7 @@ export class PhysicsBasedComponent extends Component { public syncPhysWithScene () { if (this.sharedBody) { - this.sharedBody.syncPhysWithScene(); + this.sharedBody.syncPhysWithScene(this.node); } } @@ -66,79 +58,42 @@ export class PhysicsBasedComponent extends Component { } } -export enum TransformSource { - Scene, - Phycis, -} - -type Collider = ColliderComponentBase; - -function isBoxCollider (collider: Collider): collider is BoxColliderComponent { - return 'size' in collider; -} - -function isSphereCollider (collider: Collider): collider is SphereColliderComponent { - return 'radius' in collider; -} - class SharedRigidBody { - private _body: CANNON.Body; - - private _onCollidedListener: (event: CANNON.ICollisionEvent) => any; - - private _cancelGravityListener: (event: CANNON.IEvent) => any; - - private _onWorldBeforeStepListener: (event: CANNON.IEvent) => any; - - private _onWorldPostStepListener: (event: CANNON.IEvent) => any; + private _body: RigidBodyBase; private _refCount = 0; private _actived = false; - private _world: PhysicsWorld; + private _world: PhysicsWorldBase; private _node: Node; - private _transformSource: TransformSource = TransformSource.Scene; - - private _colliders: Map = new Map(); - private _worldScale: Vec3 = new Vec3(1, 1, 1); - private _useGravity = true; + private _beforeStepCallback: BeforeStepCallback; - constructor (node: Node, world: PhysicsWorld) { - this._body = new CANNON.Body({ - material: DefaultPhysicsMaterial._getImpl(), - }); + private _afterStepCallback: AfterStepCallback; + + private _onCollidedCallback: ICollisionCallback; + + private _transformInitialized: boolean = false; + + constructor (node: Node, world: PhysicsWorldBase) { + this._body = createRigidBody(); this._node = node; - setWrap(this._body, this._node); this._world = world; - - this._onCollidedListener = this._onCollided.bind(this); - this._onWorldBeforeStepListener = this._onWorldBeforeStep.bind(this); - this._onWorldPostStepListener = this._onWorldPostStep.bind(this); - this._cancelGravityListener = (event) => { - if (!this._useGravity && this._body) { - const gravity = this._body.world.gravity; - vec3.scaleAndAdd(this._body.force, this._body.force, gravity, this._body.mass * -1); - } - }; + this._body.setUserData(this._node); + this._beforeStepCallback = this._beforeStep.bind(this); + this._afterStepCallback = this._afterStep.bind(this); + this._onCollidedCallback = this._onCollided.bind(this); + this._body.addCollisionCallback(this._onCollidedCallback); } public get body () { return this._body; } - public get transformSource () { - return this._transformSource; - } - - public set transformSource (value) { - this._transformSource = value; - } - public ref () { if (!this._refCount) { this._activeBody(); @@ -161,66 +116,18 @@ class SharedRigidBody { this._deactiveBody(); } - public addCollider (collider: Collider) { - let shape: CANNON.Shape | undefined; - if (isBoxCollider(collider)) { - shape = new CANNON.Box(new CANNON.Vec3()); - } else if (isSphereCollider(collider)) { - shape = new CANNON.Sphere(0); - } - if (!shape) { - return; - } - setWrap(shape, collider); - const ishape = this.body.shapes.length; - this.body.addShape(shape); - this._colliders.set(collider, ishape); - this.updateCollidier(collider); - } + public syncPhysWithScene (node: Node) { + const p = node.getWorldPosition(); + const r = node.getWorldRotation(); + console.log(`Set ${node.name} pos to ${p.x}, ${p.y}, ${p.z}, rot to ${r.x}, ${r.y}, ${r.z}, ${r.w}`); - public updateCollidier (collider: Collider) { - const ishape = this._colliders.get(collider); - if (ishape === undefined) { - return; - } - if (isBoxCollider(collider)) { - const shape = this.body.shapes[ishape] as CANNON.Box; - vec3.scale(shape.halfExtents, collider.size, 0.5); - vec3.multiply(shape.halfExtents, shape.halfExtents, this._worldScale); - shape.updateConvexPolyhedronRepresentation(); - shape.updateBoundingSphereRadius(); - } else if (isSphereCollider(collider)) { - const shape = this.body.shapes[ishape] as CANNON.Sphere; - shape.radius = collider.radius * maxComponent(this._worldScale); - shape.updateBoundingSphereRadius(); - } - const center = this.body.shapeOffsets[ishape]; - vec3.multiply(center, center, this._worldScale); - this.body.updateBoundingRadius(); - } - - public removeCollider (collider: Collider) { - const ishape = this._colliders.get(collider); - if (ishape === undefined) { - return; - } - this._colliders.delete(collider); - this._removeShape(ishape); - } - - public syncPhysWithScene () { - vec3.copy(this._body.position, this._node.getWorldPosition()); - quat.copy(this._body.quaternion, this._node.getWorldRotation()); + this.body.setPosition(p); + this.body.setRotation(r); // Because we sync the scale, we should update shape parameters. - this._node.getWorldScale(this._worldScale); - this._colliders.forEach((shape, collider) => { - this.updateCollidier(collider); - }); - } - - public setUseGravity (value: boolean) { - this._useGravity = value; + node.getWorldScale(this._worldScale); + this.body.scaleAllShapes(this._worldScale); + this.body.commitShapeUpdates(); } /** @@ -231,10 +138,12 @@ class SharedRigidBody { return; } - const p = this._body.position; + const p = new Vec3(); + this.body.getPosition(p); this._node.setWorldPosition(p.x, p.y, p.z); - if (!this._body.fixedRotation) { - const q = this._body.quaternion; + if (!this._body.getFreezeRotation()) { + const q = new Quat(); + this.body.getRotation(q); this._node.setWorldRotation(q.x, q.y, q.z, q.w); } } @@ -244,11 +153,9 @@ class SharedRigidBody { return; } this._actived = true; - this._world.addBody(this._body); - this._body.addEventListener('collide', this._onCollidedListener); - this._body.world.addEventListener('beforeStep', this._onWorldBeforeStepListener); - this._body.world.addEventListener('postStep', this._onWorldPostStepListener); - this._body.world.addEventListener('beforeStep', this._cancelGravityListener); + this._body.setWorld(this._world); + this._world.addBeforeStep(this._beforeStepCallback); + this._world.addAfterStep(this._afterStepCallback); } private _deactiveBody () { @@ -256,48 +163,31 @@ class SharedRigidBody { return; } this._actived = false; - this._body.removeEventListener('collide', this._onCollidedListener); - this._body.world.removeEventListener('postStep', this._onWorldPostStepListener); - this._body.world.removeEventListener('beforeStep', this._onWorldBeforeStepListener); - this._body.world.removeEventListener('beforeStep', this._cancelGravityListener); - this._world.removeBody(this._body); + this._world.removeAfterStep(this._afterStepCallback); + this._world.removeBeforeStep(this._beforeStepCallback); + this._body.setWorld(null); } - private _onCollided (event: CANNON.ICollisionEvent) { + private _onCollided (event: ICollisionEvent) { if (!this._node) { return; } this._node.emit('collided', { - source: getWrap(event.body), - target: getWrap((event as any).target), + source: event.source.getUserData() as Node, + target: event.target.getUserData() as Node, }); } - private _onWorldBeforeStep (event: CANNON.IEvent) { - // if (this._transformSource === TransformSource.Scene) { - // this.syncPhysWithScene(); - // } - } - - private _onWorldPostStep (event: CANNON.IEvent) { - if (this._transformSource === TransformSource.Phycis) { - this._syncSceneWithPhys(); + private _beforeStep () { + if (!this._transformInitialized) { + this._transformInitialized = true; + this.syncPhysWithScene(this._node); } } - private _removeShape (iShape: number) { - const body = this._body; - const shape = body.shapes[iShape]; - body.shapes.splice(iShape, 1); - body.shapeOffsets.splice(iShape, 1); - body.shapeOrientations.splice(iShape, 1); - body.updateMassProperties(); - body.updateBoundingRadius(); - body.aabbNeedsUpdate = true; - (shape as any).body = null; + private _afterStep () { + if (this.body.shouldRender()) { + this._syncSceneWithPhys(); + } } } - -function maxComponent (v: Vec3) { - return Math.max(v.x, Math.max(v.y, v.z)); -} diff --git a/cocos/3d/framework/physics/index.ts b/cocos/3d/framework/physics/index.ts index 330ce93261..ceb1e286da 100644 --- a/cocos/3d/framework/physics/index.ts +++ b/cocos/3d/framework/physics/index.ts @@ -1,3 +1 @@ -export { ContactMaterial } from './contact-material'; export * from './physics-system'; -export * from './world'; diff --git a/cocos/3d/framework/physics/physics-system.ts b/cocos/3d/framework/physics/physics-system.ts index 24d89e5e27..e18ff7bc8b 100644 --- a/cocos/3d/framework/physics/physics-system.ts +++ b/cocos/3d/framework/physics/physics-system.ts @@ -1,10 +1,11 @@ -import { PhysicsWorld } from './world'; +import { PhysicsWorldBase } from '../../physics/api'; +import { createPhysicsWorld } from '../../physics/instance'; export class PhysicsSystem { - private _world: PhysicsWorld; + private _world: PhysicsWorldBase; constructor () { - this._world = new PhysicsWorld(); + this._world = createPhysicsWorld(); } public update (deltaTime: number) { diff --git a/cocos/3d/framework/physics/rigid-body-component.ts b/cocos/3d/framework/physics/rigid-body-component.ts index 2ac304894b..4b5971d97a 100644 --- a/cocos/3d/framework/physics/rigid-body-component.ts +++ b/cocos/3d/framework/physics/rigid-body-component.ts @@ -1,5 +1,4 @@ -import CANNON from 'cannon'; import { ccclass, executeInEditMode, @@ -11,8 +10,7 @@ import { Quat, Vec3 } from '../../../core/value-types'; import { vec3 } from '../../../core/vmath'; import { PhysicsMaterial } from '../../assets/physics/material'; import { DefaultPhysicsMaterial as DefaultPhysicsMaterial } from './default-material'; -import { PhysicsBasedComponent, TransformSource } from './detail/physics-based-component'; -import { toCannonVec3 } from './util'; +import { PhysicsBasedComponent } from './detail/physics-based-component'; const NonRigidBodyProperties = { mass: 0, @@ -65,15 +63,15 @@ export class RigidBodyComponent extends PhysicsBasedComponent { this.angularDamping = this._angularDamping; this.material = this._material; this.useGravity = this._useGravity; - if (this.sharedBody) { - this.sharedBody.body.wakeUp(); - } + // if (this.sharedBody) { + // this.sharedBody.body.wakeUp(); + // } } public onDisable () { - if (this.sharedBody) { - this.sharedBody.body.sleep(); - } + // if (this.sharedBody) { + // this.sharedBody.body.sleep(); + // } } @property({ @@ -85,9 +83,9 @@ export class RigidBodyComponent extends PhysicsBasedComponent { set material (value) { this._material = value; - if (this._body) { - this._body.material = (this._material || DefaultPhysicsMaterial)._getImpl(); - } + // if (this._body) { + // this._body.material = (this._material || DefaultPhysicsMaterial)._getImpl(); + // } } @property @@ -98,12 +96,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { set mass (value) { this._mass = value; if (this._body) { - this._body.mass = value; - this._body.updateMassProperties(); - if (this._body.type !== CANNON.Body.KINEMATIC) { - this._resetBodyTypeAccordingMess(); - this._onBodyTypeUpdated(); - } + this._body.setMass(value); } } @@ -115,12 +108,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { set isKinematic (value) { this._isKinematic = value; if (this._body) { - if (value) { - this._body.type = CANNON.Body.KINEMATIC; - } else { - this._resetBodyTypeAccordingMess(); - } - this._onBodyTypeUpdated(); + this._body.setIsKinematic(value); } } @@ -131,8 +119,8 @@ export class RigidBodyComponent extends PhysicsBasedComponent { set useGravity (value) { this._useGravity = value; - if (this.sharedBody) { - this.sharedBody.setUseGravity(value); + if (this._body) { + this._body.setUseGravity(value); } } @@ -144,7 +132,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { set linearDamping (value) { this._linearDamping = value; if (this._body) { - this._body.linearDamping = value; + this._body.setLinearDamping(value); } } @@ -156,7 +144,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { set angularDamping (value) { this._angularDamping = value; if (this._body) { - this._body.angularDamping = value; + this._body.setAngularDamping(value); } } @@ -167,8 +155,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { set fixedRotation (value) { this._fixedRotation = value; if (this._body) { - this._body.fixedRotation = value; - this._body.updateMassProperties(); + this._body.setFreezeRotation(!value); } } @@ -179,13 +166,13 @@ export class RigidBodyComponent extends PhysicsBasedComponent { set isTrigger (value) { this._triggered = value; if (this._body) { - this._body.collisionResponse = value; + this._body.setIsTrigger(value); } } get velocity () { if (this._body) { - vec3.copy(this._velocity, this._body!.velocity); + vec3.copy(this._velocity, this._body!.getVelocity()); } return this._velocity; } @@ -193,64 +180,19 @@ export class RigidBodyComponent extends PhysicsBasedComponent { set velocity (value: Vec3) { vec3.copy(this._velocity, value); if (this._body) { - vec3.copy(this._body.velocity, this._velocity); + this._body.setVelocity(this._velocity); } } public applyForce (force: Vec3, position?: Vec3) { - if (!position) { - position = new Vec3(); - vec3.copy(position, this._body!.position); - } - this._body!.applyForce(toCannonVec3(force), toCannonVec3(position)); + this._body!.applyForce(force, position); } public applyImpulse (impulse: Vec3) { - this._body!.applyImpulse(toCannonVec3(impulse), toCannonVec3(new Vec3())); + this._body!.applyImpulse(impulse); } - /** - * Set the collision filter of this body, remember that they are tested bitwise. - * @param {number} group The group which this body will be put into. - * @param {number} mask The groups which this body can collide with. - */ public setCollisionFilter (group: number, mask: number) { - if (this._body) { - this._body.collisionFilterGroup = group; - this._body.collisionFilterMask = mask; - } - } - - // /** - // * Is this body currently in contact with the specified body? - // * @param {CannonBody} body The body to test against. - // */ - // public isInContactWith (body: PhysicsBody) { - // if (!this._cannonBody.world) { - // return false; - // } - - // return this._cannonBody.world.collisionMatrix.get( - // this._cannonBody.id, body._cannonBody.id) > 0; - // } - - private _resetBodyTypeAccordingMess () { - if (this._body) { - if (this.mass <= 0) { - this._body.type = CANNON.Body.STATIC; - } else { - this._body.type = CANNON.Body.DYNAMIC; - } - } - } - - private _onBodyTypeUpdated () { - if (this.sharedBody) { - if (this.sharedBody.body.type === CANNON.Body.STATIC) { - this.sharedBody.transformSource = TransformSource.Scene; - } else { - this.sharedBody.transformSource = TransformSource.Phycis; - } - } + this._body!.setCollisionFilter(group, mask); } } diff --git a/cocos/3d/framework/physics/util.ts b/cocos/3d/framework/physics/util.ts deleted file mode 100644 index aedd3aa24d..0000000000 --- a/cocos/3d/framework/physics/util.ts +++ /dev/null @@ -1,33 +0,0 @@ -import CANNON from 'cannon'; -import { Vec3 } from '../../../core/value-types'; - -export interface IWrappedCANNON { - __cc_wrapper__: T; -} - -export function setWrap (cannonObject: any, wrapper: Wrapper) { - (cannonObject as unknown as IWrappedCANNON).__cc_wrapper__ = wrapper; -} - -export function getWrap (cannonObject: any) { - return (cannonObject as unknown as IWrappedCANNON).__cc_wrapper__; -} - -export function toCannonVec3 (value: Vec3) { - return new CANNON.Vec3(value.x, value.y, value.z); -} - -export function toCannonOptions (options: any, optionsRename?: { [x: string]: string; }) { - const result = {}; - for (const key of Object.keys(options)) { - let destKey = key; - if (optionsRename) { - const rename = optionsRename[key]; - if (rename) { - destKey = rename; - } - } - result[destKey] = options[key]; - } - return result as T; -} diff --git a/cocos/3d/framework/physics/world.ts b/cocos/3d/framework/physics/world.ts deleted file mode 100644 index 278732dbec..0000000000 --- a/cocos/3d/framework/physics/world.ts +++ /dev/null @@ -1,133 +0,0 @@ -import CANNON from 'cannon'; -import { Component } from '../../../components/component'; -import { Vec3 } from '../../../core/value-types'; -import { Node } from '../../../scene-graph/node'; -import { PhysicsMaterial } from '../../assets/physics/material'; -import { Constraint } from './constraints'; -import { ContactMaterial } from './contact-material'; -import { DefaultPhysicsMaterial } from './default-material'; -import { getWrap, setWrap, toCannonOptions } from './util'; - -export interface IRaycastOptions { - collisionFilterMask?: number; - collisionFilterGroup?: number; - queryTriggerInteraction?: boolean; -} - -export class RaycastResult { - public _cannonResult: CANNON.RaycastResult = new CANNON.RaycastResult(); - - get hit () { - return this._cannonResult.hasHit; - } - - get hitPoint () { - return this._cannonResult.hitPointWorld; - } - - get distance () { - return this._cannonResult.distance; - } - - get shape () { - return getWrap(this._cannonResult.shape); - } - - get body () { - return getWrap(this._cannonResult.body); - } -} -cc.RaycastResult = RaycastResult; - -export class PhysicsWorld { - private _cannonWorld: CANNON.World; - private _defaultContactMaterial: ContactMaterial; - private _beforeStepEvent: CANNON.IEvent = { - type: 'beforeStep', - }; - - constructor () { - this._defaultContactMaterial = new ContactMaterial(DefaultPhysicsMaterial, DefaultPhysicsMaterial); - this._defaultContactMaterial.friction = 0.06; - this._defaultContactMaterial.restitution = 0; - - this._cannonWorld = new CANNON.World(); - setWrap(this._cannonWorld, this); - this._cannonWorld.gravity.set(0, -9.81, 0); - this._cannonWorld.broadphase = new CANNON.NaiveBroadphase(); - this._cannonWorld.defaultMaterial = DefaultPhysicsMaterial._getImpl(); - this._cannonWorld.defaultContactMaterial = this._defaultContactMaterial._getImpl(); - } - - get defaultContactMaterial () { - return this._defaultContactMaterial; - } - - public addBody (body: CANNON.Body) { - this._cannonWorld.addBody(body); - } - - public removeBody (body: CANNON.Body) { - this._cannonWorld.remove(body); - } - - public step (deltaTime: number) { - this._cannonWorld.dispatchEvent(this._beforeStepEvent); - this._cannonWorld.step(deltaTime); - } - - /** - * Ray cast, and return information of the closest hit. - * @return True if any body was hit. - */ - public raycastClosest (from: Vec3, to: Vec3, options: IRaycastOptions, result: RaycastResult): boolean { - const hit = (this._cannonWorld as any).raycastClosest(from, to, toCannonRaycastOptions(options), result._cannonResult); - return hit; - } - - /** - * Ray cast, and stop at the first result. Note that the order is random - but the method is fast. - * @return True if any body was hit. - */ - public raycastAny (from: Vec3, to: Vec3, options: IRaycastOptions, result: RaycastResult): boolean { - const hit = (this._cannonWorld as any).raycastAny(from, to, toCannonRaycastOptions(options), result._cannonResult); - return hit; - } - - /** - * 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. - */ - public raycastAll (from: Vec3, to: Vec3, options: IRaycastOptions, callback: (result: RaycastResult) => void): boolean { - return (this._cannonWorld as any).raycastAll(from, to, toCannonRaycastOptions(options), (cannonResult: CANNON.RaycastResult) => { - const result = new RaycastResult(); - result._cannonResult = cannonResult; - callback(result); - }); - } - - public addContactMaterial (contactMaterial: ContactMaterial) { - this._cannonWorld.addContactMaterial(contactMaterial._getImpl()); - } - - public addConstraint (constraint: Constraint) { - this._cannonWorld.addConstraint(constraint._getImpl()); - } - - public removeConstraint (constraint: Constraint) { - this._cannonWorld.removeConstraint(constraint._getImpl()); - } -} - -interface ICANNONRaycastOptions { - collisionFilterMask?: number; - collisionFilterGroup?: number; - checkCollisionResponse?: boolean; - skipBackfaces?: boolean; -} - -function toCannonRaycastOptions (options: IRaycastOptions): ICANNONRaycastOptions { - return toCannonOptions(options, { - queryTriggerInteraction: 'checkCollisionResponse', - }); -} diff --git a/cocos/3d/index.js b/cocos/3d/index.ts similarity index 96% rename from cocos/3d/index.js rename to cocos/3d/index.ts index c3998ccf3c..965215160f 100644 --- a/cocos/3d/index.js +++ b/cocos/3d/index.ts @@ -27,10 +27,11 @@ export * from './assets'; export * from './builtin'; export * from './framework'; export * from './memop'; +import * as geometry from './geom-utils'; import * as utils from './misc/utils'; import * as primitives from './primitive'; -import * as geometry from './geom-utils'; import './ui'; +export { createRaycastResult } from './physics/instance'; export { utils, diff --git a/cocos/3d/physics/api.d.ts b/cocos/3d/physics/api.d.ts new file mode 100644 index 0000000000..dc1a76bd8e --- /dev/null +++ b/cocos/3d/physics/api.d.ts @@ -0,0 +1,240 @@ +import { Vec3, Quat } from '../../core/value-types'; +import { Node } from '../../scene-graph'; + +export interface IRaycastOptions { + collisionFilterMask?: number; + collisionFilterGroup?: number; + queryTriggerInteraction?: boolean; +} + +export interface ICollisionEvent { + source: RigidBodyBase; + + target: RigidBodyBase; +} + +export type ICollisionCallback = (event: ICollisionEvent) => void; + +export type BeforeStepCallback = () => void; + +export type AfterStepCallback = () => void; + +export class PhysicsWorldBase { + constructor (); + + step (deltaTime: number): void; + + addBeforeStep (cb: BeforeStepCallback): void; + + removeBeforeStep (cb: BeforeStepCallback): void; + + addAfterStep (cb: AfterStepCallback): void; + + removeAfterStep (cb: AfterStepCallback): void; + + /** + * Ray cast, and return information of the closest hit. + * @return True if any body was hit. + */ + raycastClosest (from: Vec3, to: Vec3, options: IRaycastOptions, result: RaycastResultBase): boolean; + + /** + * Ray cast, and stop at the first result. Note that the order is random - but the method is fast. + * @return True if any body was hit. + */ + raycastAny (from: Vec3, to: Vec3, options: IRaycastOptions, result: RaycastResultBase): 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. + */ + raycastAll (from: Vec3, to: Vec3, options: IRaycastOptions, callback: (result: RaycastResultBase) => void): boolean; +} + +export class RigidBodyBase { + constructor (); + + addShape (shape: ShapeBase): void; + + removeShape (shape: ShapeBase): void; + + getMass (): number; + + setMass (value: number): void; + + applyForce (force: Vec3, position?: Vec3): void; + + applyImpulse (impulse: Vec3): void; + + getIsKinematic (): boolean; + + setIsKinematic (value: boolean): void; + + getLinearDamping (): number; + + setLinearDamping (value: number): void; + + getAngularDamping (): number; + + setAngularDamping (value: number): void; + + getUseGravity (): boolean; + + setUseGravity (value: boolean): void; + + getIsTrigger (): boolean; + + setIsTrigger (value: boolean): void; + + getVelocity (): Vec3; + + setVelocity (value: Vec3): void; + + getFreezeRotation (): boolean; + + setFreezeRotation (value: boolean): void; + + /** + * Set the collision filter of this body, remember that they are tested bitwise. + * @param group The group which this body will be put into. + * @param mask The groups which this body can collide with. + */ + setCollisionFilter (group: number, mask: number): void; + + setWorld (world: PhysicsWorldBase | null): void; + + commitShapeUpdates (): void; + + shouldRender (): boolean; + + getPosition (out: Vec3): void; + + setPosition (value: Vec3): void; + + getRotation (out: Quat): void; + + setRotation (out: Quat): void; + + scaleAllShapes (scale: Vec3): void; + + addCollisionCallback (callback: ICollisionCallback): void; + + removeCollisionCllback (callback: ICollisionCallback): void; + + getUserData (): any; + + setUserData(data: any): void; +} + +export class ShapeBase { + setCenter (center: Vec3): void; + + setScale (scale: Vec3): void; + + setRotation (rotation: Quat): void; +} + +export class SphereShapeBase extends ShapeBase { + constructor (radius: number); + + setRadius (radius: number): void; +} + +export class BoxShapeBase extends ShapeBase { + constructor (size: Vec3); + + setSize (size: Vec3): void; +} + +/** + * Base class for Constraint classes. + */ +export class ConstraintBase { + first: RigidBodyBase; + second: RigidBodyBase; + enable (): void; + disable (): void; + update (): void; +} + +/** + * DistanceConstraint options. + */ +export interface IDistanceConstraintOptions { + /** + * The maximum force that should be applied to constrain the bodies. + */ + maxForce?: number; +} + +/** + * Constrains two bodies to be at a constant distance from each others center of mass. + */ +export class DistanceConstraintBase extends ConstraintBase { + /** + * @param first The first body. + * @param second The second body. + * @param distance The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB. + * @param options Options. + */ + constructor (first: RigidBodyBase, second: RigidBodyBase, distance?: number, options?: IDistanceConstraintOptions); +} + +/** + * PointToPointConstraint options. + */ +export interface IPointToPointConstraintOptions { + /** + * The maximum force that should be applied to constrain the bodies. + */ + maxForce?: number; +} + +/** + * Connects two bodies at given offset points. + */ +export class PointToPointConstraintBase extends ConstraintBase { + /** + * @param first The first body. + * @param firstPivot The point relative to the center of mass of the first body which the first body is constrained to. + * @param second The second body. + * @param secondPivot The point relative to the center of mass of the second body which the second body is constrained to. + * @param options Options. + */ + constructor (first: RigidBodyBase, firstPivot: Vec3, second: RigidBodyBase, secondPivot: Vec3, options?: IPointToPointConstraintOptions); +} + +/** + * LockConstraint options. + */ +export interface ILockConstraintOptions { + /** + * The maximum force that should be applied to constrain the bodies. + */ + maxForce?: number; +} + +/** + * The Lock constraint will remove all degrees of freedom between the bodies. + */ +export class LockConstraintBase extends ConstraintBase { + /** + * @param first The first body. + * @param second The second body. + * @param options Options. + */ + constructor (first: RigidBodyBase, second: RigidBodyBase, options?: ILockConstraintOptions); +} + +export class RaycastResultBase { + readonly hit: boolean; + readonly hitPoint: Vec3; + readonly distance: number; + readonly shape: ShapeBase; + readonly body: RigidBodyBase; +} + +export enum TransformSource { + Scene, + Phycis, +} \ No newline at end of file diff --git a/cocos/3d/physics/cannon-impl.ts b/cocos/3d/physics/cannon-impl.ts new file mode 100644 index 0000000000..153a6e0940 --- /dev/null +++ b/cocos/3d/physics/cannon-impl.ts @@ -0,0 +1,657 @@ +import CANNON from 'cannon'; +import { Quat, Vec3 } from '../../core/value-types'; +import { quat, vec3 } from '../../core/vmath'; +import { AfterStepCallback, BeforeStepCallback, + BoxShapeBase, + ConstraintBase, DistanceConstraintBase, + ICollisionCallback, ICollisionEvent, + IDistanceConstraintOptions, ILockConstraintOptions, + IPointToPointConstraintOptions, + IRaycastOptions, + LockConstraintBase, PhysicsWorldBase, PointToPointConstraintBase, + RaycastResultBase, RigidBodyBase, ShapeBase, SphereShapeBase } from './api'; + +const defaultCannonMaterial = new CANNON.Material(''); +const defaultCannonContactMaterial = new CANNON.ContactMaterial( + defaultCannonMaterial, defaultCannonMaterial, { + friction: 0.06, + restitution: 0, + }); + +export class CannonWorld implements PhysicsWorldBase { + private _cannonWorld: CANNON.World; + private _beforeStepEvent: CANNON.IEvent = { + type: 'beforeStep', + }; + private _customBeforeStepListener: BeforeStepCallback[] = []; + private _customAfterStepListener: AfterStepCallback[] = []; + + constructor () { + this._cannonWorld = new CANNON.World(); + setWrap(this._cannonWorld, this); + this._cannonWorld.gravity.set(0, -9.81, 0); + this._cannonWorld.broadphase = new CANNON.NaiveBroadphase(); + this._cannonWorld.defaultMaterial = defaultCannonMaterial; + this._cannonWorld.defaultContactMaterial = defaultCannonContactMaterial; + } + + get impl () { + return this._cannonWorld; + } + + // get defaultContactMaterial () { + // return this._defaultContactMaterial; + // } + + public step (deltaTime: number) { + this._customBeforeStepListener.forEach((fx) => fx()); + this._cannonWorld.dispatchEvent(this._beforeStepEvent); + this._cannonWorld.step(deltaTime); + this._customAfterStepListener.forEach((fx) => fx()); + } + + public addBeforeStep (cb: BeforeStepCallback) { + this._customBeforeStepListener.push(cb); + } + + public removeBeforeStep (cb: BeforeStepCallback) { + const i = this._customBeforeStepListener.indexOf(cb); + if (i < 0) { + return; + } + this._customBeforeStepListener.splice(i, 1); + } + + public addAfterStep (cb: AfterStepCallback) { + this._customAfterStepListener.push(cb); + } + + public removeAfterStep (cb: AfterStepCallback) { + const i = this._customAfterStepListener.indexOf(cb); + if (i < 0) { + return; + } + this._customAfterStepListener.splice(i, 1); + } + + public raycastClosest (from: Vec3, to: Vec3, options: IRaycastOptions, result_: RaycastResultBase): boolean { + const result = result_ as unknown as CannonRaycastResult; + const hit = (this._cannonWorld as any).raycastClosest(from, to, toCannonRaycastOptions(options), result._cannonResult); + return hit; + } + + public raycastAny (from: Vec3, to: Vec3, options: IRaycastOptions, result_: RaycastResultBase): boolean { + const result = result_ as unknown as CannonRaycastResult; + const hit = (this._cannonWorld as any).raycastAny(from, to, toCannonRaycastOptions(options), result._cannonResult); + return hit; + } + + public raycastAll (from: Vec3, to: Vec3, options: IRaycastOptions, callback: (result: RaycastResultBase) => void): boolean { + return (this._cannonWorld as any).raycastAll(from, to, toCannonRaycastOptions(options), (cannonResult: CANNON.RaycastResult) => { + const result = new CannonRaycastResult(); + result._cannonResult = cannonResult; + callback(result); + }); + } + + // public addContactMaterial (contactMaterial: ContactMaterial) { + // this._cannonWorld.addContactMaterial(contactMaterial._getImpl()); + // } + + public addConstraint (constraint: CannonConstraint) { + this._cannonWorld.addConstraint(constraint.impl); + } + + public removeConstraint (constraint: CannonConstraint) { + this._cannonWorld.removeConstraint(constraint.impl); + } +} +enum TransformSource { + Scene, + Phycis, +} + +export class CannonRigidBody implements RigidBodyBase { + + get impl (): CANNON.Body { + return this._cannonBody; + } + private _cannonBody: CANNON.Body; + private _velocityResult: Vec3 = new Vec3(); + private _useGravity = true; + private _cannonMaterial: CANNON.Material; + private _onCollidedListener: (event: CANNON.ICollisionEvent) => any; + private _cancelGravityListener: (event: CANNON.IEvent) => any; + private _onWorldBeforeStepListener: (event: CANNON.IEvent) => any; + private _onWorldPostStepListener: (event: CANNON.IEvent) => any; + private _collisionCallbacks: ICollisionCallback[] = []; + private _shapes: CannonShape[] = []; + private _transformSource: TransformSource = TransformSource.Scene; + private _userData: any; + + constructor () { + this._cannonMaterial = defaultCannonMaterial; + this._cannonBody = new CANNON.Body({ + material: this._cannonMaterial, + }); + setWrap(this._cannonBody, this); + + this._onCollidedListener = this._onCollided.bind(this); + this._onWorldBeforeStepListener = this._onWorldBeforeStep.bind(this); + this._onWorldPostStepListener = this._onWorldPostStep.bind(this); + this._cancelGravityListener = (event) => { + if (!this._useGravity) { + const gravity = this._cannonBody.world.gravity; + vec3.scaleAndAdd(this._cannonBody.force, this._cannonBody.force, gravity, this._cannonBody.mass * -1); + } + }; + } + + public addShape (shape: CannonShape) { + const index = this._shapes.length; + this._shapes.push(shape); + this._cannonBody.addShape(shape.impl); + shape._setBody(this._cannonBody, index); + } + + public removeShape (shape: CannonShape) { + const i = this._shapes.indexOf(shape); + if (i < 0) { + return; + } + this._removeShape(i); + for (let j = i + 1; j < this._shapes.length; ++j) { + const s = this._shapes[j]; + s._setIndex(j - 1); + } + this._shapes.splice(i, 1); + } + + public commitShapeUpdates () { + this._cannonBody.updateBoundingRadius(); + } + + public getMass () { + return this._cannonBody.mass; + } + + public setMass (value: number) { + this._cannonBody.mass = value; + this._cannonBody.updateMassProperties(); + if (this._cannonBody.type !== CANNON.Body.KINEMATIC) { + this._resetBodyTypeAccordingMess(); + this._onBodyTypeUpdated(); + } + } + + public getIsKinematic () { + return this._cannonBody.type === CANNON.Body.KINEMATIC; + } + + public setIsKinematic (value: boolean) { + if (value) { + this._cannonBody.type = CANNON.Body.KINEMATIC; + } else { + this._resetBodyTypeAccordingMess(); + } + this._onBodyTypeUpdated(); + } + + public getLinearDamping () { + return this._cannonBody.linearDamping; + } + + public setLinearDamping (value: number) { + this._cannonBody.linearDamping = value; + } + + public getAngularDamping () { + return this._cannonBody.angularDamping; + } + + public setAngularDamping (value: number) { + this._cannonBody.angularDamping = value; + } + + public getUseGravity (): boolean { + return this._useGravity; + } + + public setUseGravity (value: boolean) { + this._useGravity = value; + } + + public getIsTrigger (): boolean { + return this._cannonBody.collisionResponse; + } + + public setIsTrigger (value: boolean): void { + this._cannonBody.collisionResponse = value; + } + + public getVelocity (): Vec3 { + vec3.copy(this._velocityResult, this._cannonBody.velocity); + return this._velocityResult; + } + + public setVelocity (value: Vec3): void { + vec3.copy(this._cannonBody.velocity, value); + } + + public getFreezeRotation (): boolean { + return this._cannonBody.fixedRotation; + } + + public setFreezeRotation (value: boolean) { + this._cannonBody.fixedRotation = value; + this._cannonBody.updateMassProperties(); + } + + public applyForce (force: Vec3, position?: Vec3) { + if (!position) { + position = new Vec3(); + vec3.copy(position, this._cannonBody.position); + } + this._cannonBody.applyForce(toCannonVec3(force), toCannonVec3(position)); + } + + public applyImpulse (impulse: Vec3) { + this._cannonBody.applyImpulse(toCannonVec3(impulse), toCannonVec3(new Vec3())); + } + + public setCollisionFilter (group: number, mask: number) { + this._cannonBody.collisionFilterGroup = group; + this._cannonBody.collisionFilterMask = mask; + } + + // /** + // * Is this body currently in contact with the specified body? + // * @param {CannonBody} body The body to test against. + // */ + // public isInContactWith (body: PhysicsBody) { + // if (!this._cannonBody.world) { + // return false; + // } + + // return this._cannonBody.world.collisionMatrix.get( + // this._cannonBody.id, body._cannonBody.id) > 0; + // } + + public setWorld (world_: PhysicsWorldBase | null) { + const world = world_ as unknown as (CannonWorld | null); + if (world) { + world.impl.addBody(this._cannonBody); + this._cannonBody.addEventListener('collide', this._onCollidedListener); + this._cannonBody.world.addEventListener('beforeStep', this._onWorldBeforeStepListener); + this._cannonBody.world.addEventListener('postStep', this._onWorldPostStepListener); + this._cannonBody.world.addEventListener('beforeStep', this._cancelGravityListener); + } else { + this._cannonBody.world.removeEventListener('beforeStep', this._cancelGravityListener); + this._cannonBody.world.removeEventListener('postStep', this._onWorldPostStepListener); + this._cannonBody.world.removeEventListener('beforeStep', this._onWorldBeforeStepListener); + this._cannonBody.removeEventListener('collide', this._onCollidedListener); + this._cannonBody.world.remove(this._cannonBody); + } + } + + public shouldRender (): boolean { + return this._transformSource === TransformSource.Phycis; + } + + public getPosition (out: Vec3) { + vec3.copy(out, this._cannonBody.position); + } + + public setPosition (value: Vec3) { + vec3.copy(this._cannonBody.position, value); + } + + public getRotation (out: Quat) { + quat.copy(out, this._cannonBody.quaternion); + } + + public setRotation (value: Quat) { + quat.copy(this._cannonBody.quaternion, value); + } + + public scaleAllShapes (scale: Vec3) { + for (const shape of this._shapes) { + shape.setScale(scale); + } + } + + public addCollisionCallback (callback: ICollisionCallback): void { + this._collisionCallbacks.push(callback); + } + + public removeCollisionCllback (callback: ICollisionCallback): void { + const i = this._collisionCallbacks.indexOf(callback); + if (i >= 0) { + this._collisionCallbacks.splice(i, 1); + } + } + + public getUserData (): any { + return this._userData; + } + + public setUserData (data: any): void { + this._userData = data; + } + + private _resetBodyTypeAccordingMess () { + if (this._cannonBody.mass <= 0) { + this._cannonBody.type = CANNON.Body.STATIC; + } else { + this._cannonBody.type = CANNON.Body.DYNAMIC; + } + } + + private _onBodyTypeUpdated () { + if (this._cannonBody) { + if (this._cannonBody.type === CANNON.Body.STATIC) { + this._transformSource = TransformSource.Scene; + } else { + this._transformSource = TransformSource.Phycis; + } + } + } + + private _onCollided (event: CANNON.ICollisionEvent) { + const evt: ICollisionEvent = { + source: getWrap(event.body), + target: getWrap((event as any).target), + }; + for (const callback of this._collisionCallbacks) { + callback(evt); + } + } + + private _onWorldBeforeStep (event: CANNON.IEvent) { + } + + private _onWorldPostStep (event: CANNON.IEvent) { + } + + private _removeShape (iShape: number) { + const body = this._cannonBody; + const shape = body.shapes[iShape]; + body.shapes.splice(iShape, 1); + body.shapeOffsets.splice(iShape, 1); + body.shapeOrientations.splice(iShape, 1); + body.updateMassProperties(); + body.updateBoundingRadius(); + body.aabbNeedsUpdate = true; + (shape as any).body = null; + } +} + +export class CannonShape implements ShapeBase { + + public get impl () { + return this._cannonShape!; + } + + protected _scale: Vec3 = new Vec3(1, 1, 1); + + protected _cannonShape: CANNON.Shape | null = null; + + private _index: number = -1; + + private _body: CANNON.Body | null = null; + + private _center: Vec3 = new Vec3(0, 0, 0); + + public constructor () { + + } + + public _setIndex (index: number) { + this._index = index; + this._recalcCenter(); + } + + public _setBody (body: CANNON.Body, index: number) { + this._body = body; + this._setIndex(index); + } + + public setCenter (center: Vec3): void { + vec3.copy(this._center, center); + this._recalcCenter(); + } + + public setScale (scale: Vec3): void { + vec3.copy(this._scale, scale); + this._recalcCenter(); + } + + public setRotation (rotation: Quat): void { + + } + + private _recalcCenter () { + if (!this._body) { + return; + } + const shapeOffset = this._body.shapeOffsets[this._index]; + vec3.copy(shapeOffset, this._center); + vec3.multiply(shapeOffset, shapeOffset, this._scale); + } +} + +export class CannonSphereShape extends CannonShape implements SphereShapeBase { + private _cannonSphere: CANNON.Sphere; + + private _radius: number = 0; + + constructor (radius: number) { + super(); + this._radius = radius; + this._cannonSphere = new CANNON.Sphere(this._radius); + setWrap(this._cannonSphere, this); + this._cannonShape = this._cannonSphere; + } + + public setScale (scale: Vec3): void { + super.setScale(scale); + this._recalcRadius(); + } + + public setRadius (radius: number) { + this._radius = radius; + this._recalcRadius(); + } + + private _recalcRadius () { + this._cannonSphere.radius = this._radius * maxComponent(this._scale); + this._cannonSphere.updateBoundingSphereRadius(); + } +} + +export class CannonBoxShape extends CannonShape implements BoxShapeBase { + private _cannonBox: CANNON.Box; + private _halfExtent: CANNON.Vec3 = new CANNON.Vec3(); + + constructor (size: Vec3) { + super(); + vec3.scale(this._halfExtent, size, 0.5); + this._cannonBox = new CANNON.Box(this._halfExtent); + setWrap(this._cannonBox, this); + this._cannonShape = this._cannonBox; + } + + public setScale (scale: Vec3): void { + super.setScale(scale); + this._recalcExtents(); + } + + public setSize (size: Vec3) { + vec3.scale(this._halfExtent, size, 0.5); + this._recalcExtents(); + } + + private _recalcExtents () { + vec3.multiply(this._cannonBox.halfExtents, this._halfExtent, this._scale); + this._cannonBox.updateConvexPolyhedronRepresentation(); + this._cannonBox.updateBoundingSphereRadius(); + } +} + +/** + * Constraint options. + */ +export interface IConstraintOptions { + /** + * Set to true if you want the bodies to collide when they are connected. + * @default true + */ + collideConnected?: boolean; + + /** + * @default true + */ + wakeUpBodies?: boolean; +} + +export class CannonConstraint implements ConstraintBase { + protected _cannonConstraint: CANNON.Constraint; + + /** + * @param first The first body. + * @param second The second body. + * @param options Options. + */ + protected constructor (cannonConstraint: CANNON.Constraint) { + this._cannonConstraint = cannonConstraint; + setWrap(this._cannonConstraint, this); + } + + get first () { + return getWrap(this._cannonConstraint.bodyA); + } + + get second () { + return getWrap(this._cannonConstraint.bodyB); + } + + public enable () { + this._cannonConstraint.enable(); + } + + public disable () { + this._cannonConstraint.disable(); + } + + public update () { + this._cannonConstraint.update(); + } + + public get impl () { + return this._cannonConstraint; + } +} + +export class CannonDistanceConstraint extends CannonConstraint implements DistanceConstraintBase { + constructor (first: CannonRigidBody, second: CannonRigidBody, distance?: number, options?: IDistanceConstraintOptions) { + super(new CANNON.DistanceConstraint( + first.impl, + second.impl, + distance!, + options === undefined ? undefined : options.maxForce)); + } +} + +export class CannonPointToPointConstraint extends CannonConstraint implements PointToPointConstraintBase { + constructor (first: CannonRigidBody, firstPivot: Vec3, second: CannonRigidBody, secondPivot: Vec3, options?: IPointToPointConstraintOptions) { + super(new CANNON.PointToPointConstraint( + first.impl, + toCannonVec3(firstPivot), + second.impl, + toCannonVec3(secondPivot), + options === undefined ? undefined : options.maxForce)); + } +} + +export class CannonLockConstraint extends CannonConstraint implements LockConstraintBase { + constructor (first: CannonRigidBody, second: CannonRigidBody, options?: ILockConstraintOptions) { + super(new CANNON.LockConstraint( + first.impl, + second.impl, + options)); + } +} + +export class CannonRaycastResult implements RaycastResultBase { + public _cannonResult: CANNON.RaycastResult = new CANNON.RaycastResult(); + public _hitPoint: Vec3 = new Vec3(); + + get hit () { + return this._cannonResult.hasHit; + } + + get hitPoint () { + vec3.copy(this._hitPoint, this._cannonResult.hitPointWorld); + return this._hitPoint; + } + + get distance () { + return this._cannonResult.distance; + } + + get shape () { + return getWrap(this._cannonResult.shape); + } + + get body () { + return getWrap(this._cannonResult.body); + } +} + +interface ICANNONRaycastOptions { + collisionFilterMask?: number; + collisionFilterGroup?: number; + checkCollisionResponse?: boolean; + skipBackfaces?: boolean; +} + +function toCannonRaycastOptions (options: IRaycastOptions): ICANNONRaycastOptions { + return toCannonOptions(options, { + queryTriggerInteraction: 'checkCollisionResponse', + }); +} + +interface IWrappedCANNON { + __cc_wrapper__: T; +} + +function setWrap (cannonObject: any, wrapper: Wrapper) { + (cannonObject as unknown as IWrappedCANNON).__cc_wrapper__ = wrapper; +} + +function getWrap (cannonObject: any) { + return (cannonObject as unknown as IWrappedCANNON).__cc_wrapper__; +} + +function toCannonVec3 (value: Vec3) { + return new CANNON.Vec3(value.x, value.y, value.z); +} + +function toCannonOptions (options: any, optionsRename?: { [x: string]: string; }) { + const result = {}; + for (const key of Object.keys(options)) { + let destKey = key; + if (optionsRename) { + const rename = optionsRename[key]; + if (rename) { + destKey = rename; + } + } + result[destKey] = options[key]; + } + return result as T; +} + +function maxComponent (v: Vec3) { + return Math.max(v.x, Math.max(v.y, v.z)); +} diff --git a/cocos/3d/physics/impl-selector.ts b/cocos/3d/physics/impl-selector.ts new file mode 100644 index 0000000000..0df3c3f88f --- /dev/null +++ b/cocos/3d/physics/impl-selector.ts @@ -0,0 +1,8 @@ + +export { + CannonBoxShape as BoxShape, + CannonRaycastResult as RaycastResult, + CannonRigidBody as RigidBody, + CannonSphereShape as SphereShape, + CannonWorld as PhysicsWorld, +} from './cannon-impl'; diff --git a/cocos/3d/physics/instance.ts b/cocos/3d/physics/instance.ts new file mode 100644 index 0000000000..7041644bba --- /dev/null +++ b/cocos/3d/physics/instance.ts @@ -0,0 +1,25 @@ +import { Vec3 } from '../../core/value-types'; +import { BoxShapeBase, PhysicsWorldBase, RaycastResultBase, RigidBodyBase } from './api'; +import { BoxShape, PhysicsWorld, RaycastResult, RigidBody, SphereShape } from './impl-selector'; + +export function createPhysicsWorld (): PhysicsWorldBase { + return new PhysicsWorld(); +} + +export function createRigidBody (): RigidBodyBase { + return new RigidBody(); +} + +export function createBoxShape (size: Vec3): BoxShapeBase { + return new BoxShape(size); +} + +export function createSphereShape (radius: number): SphereShape { + return new SphereShape(radius); +} + +export function createRaycastResult (): RaycastResultBase { + return new RaycastResult(); +} + +cc.createRaycastResult = createRaycastResult; diff --git a/cocos/core/value-types/mat4.ts b/cocos/core/value-types/mat4.ts index e9a7db86a2..8d6f8ce0b1 100644 --- a/cocos/core/value-types/mat4.ts +++ b/cocos/core/value-types/mat4.ts @@ -23,11 +23,11 @@ THE SOFTWARE. ****************************************************************************/ -import { Vec3 } from 'cannon'; import CCClass from '../data/class'; import { mat4 } from '../vmath'; import Quat from './quat'; import { ValueType } from './value-type'; +import Vec3 from './vec3'; /** * !#en Representation of 4*4 matrix.