oimoJSPlugin.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. import { IPhysicsEnginePlugin, PhysicsImpostorJoint } from "../../Physics/IPhysicsEngine";
  2. import { PhysicsImpostor, IPhysicsEnabledObject } from "../../Physics/physicsImpostor";
  3. import { PhysicsJoint, IMotorEnabledJoint, DistanceJointData, SpringJointData } from "../../Physics/physicsJoint";
  4. import { PhysicsEngine } from "../../Physics/physicsEngine";
  5. import { AbstractMesh } from "../../Meshes/abstractMesh";
  6. import { Vector3, Quaternion } from "../../Maths/math";
  7. import { Nullable } from "../../types";
  8. import { Logger } from "../../Misc/logger";
  9. import { PhysicsRaycastResult } from "../physicsRaycastResult";
  10. declare var OIMO: any;
  11. /** @hidden */
  12. export class OimoJSPlugin implements IPhysicsEnginePlugin {
  13. public world: any;
  14. public name: string = "OimoJSPlugin";
  15. public BJSOIMO: any;
  16. private _raycastResult: PhysicsRaycastResult;
  17. constructor(iterations?: number, oimoInjection = OIMO) {
  18. this.BJSOIMO = oimoInjection;
  19. this.world = new this.BJSOIMO.World({
  20. iterations: iterations
  21. });
  22. this.world.clear();
  23. this._raycastResult = new PhysicsRaycastResult();
  24. }
  25. public setGravity(gravity: Vector3) {
  26. this.world.gravity.copy(gravity);
  27. }
  28. public setTimeStep(timeStep: number) {
  29. this.world.timeStep = timeStep;
  30. }
  31. public getTimeStep(): number {
  32. return this.world.timeStep;
  33. }
  34. private _tmpImpostorsArray: Array<PhysicsImpostor> = [];
  35. public executeStep(delta: number, impostors: Array<PhysicsImpostor>) {
  36. impostors.forEach(function(impostor) {
  37. impostor.beforeStep();
  38. });
  39. this.world.step();
  40. impostors.forEach((impostor) => {
  41. impostor.afterStep();
  42. //update the ordered impostors array
  43. this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  44. });
  45. //check for collisions
  46. var contact = this.world.contacts;
  47. while (contact !== null) {
  48. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  49. contact = contact.next;
  50. continue;
  51. }
  52. //is this body colliding with any other? get the impostor
  53. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  54. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  55. if (!mainImpostor || !collidingImpostor) {
  56. contact = contact.next;
  57. continue;
  58. }
  59. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  60. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  61. contact = contact.next;
  62. }
  63. }
  64. public applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  65. var mass = impostor.physicsBody.mass;
  66. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  67. }
  68. public applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  69. Logger.Warn("Oimo doesn't support applying force. Using impule instead.");
  70. this.applyImpulse(impostor, force, contactPoint);
  71. }
  72. public generatePhysicsBody(impostor: PhysicsImpostor) {
  73. //parent-child relationship. Does this impostor has a parent impostor?
  74. if (impostor.parent) {
  75. if (impostor.physicsBody) {
  76. this.removePhysicsBody(impostor);
  77. //TODO is that needed?
  78. impostor.forceUpdate();
  79. }
  80. return;
  81. }
  82. if (impostor.isBodyInitRequired()) {
  83. var bodyConfig: any = {
  84. name: impostor.uniqueId,
  85. //Oimo must have mass, also for static objects.
  86. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  87. size: [],
  88. type: [],
  89. pos: [],
  90. posShape: [],
  91. rot: [],
  92. rotShape: [],
  93. move: impostor.getParam("mass") !== 0,
  94. density: impostor.getParam("mass"),
  95. friction: impostor.getParam("friction"),
  96. restitution: impostor.getParam("restitution"),
  97. //Supporting older versions of Oimo
  98. world: this.world
  99. };
  100. var impostors = [impostor];
  101. let addToArray = (parent: IPhysicsEnabledObject) => {
  102. if (!parent.getChildMeshes) { return; }
  103. parent.getChildMeshes().forEach(function(m) {
  104. if (m.physicsImpostor) {
  105. impostors.push(m.physicsImpostor);
  106. //m.physicsImpostor._init();
  107. }
  108. });
  109. };
  110. addToArray(impostor.object);
  111. let checkWithEpsilon = (value: number): number => {
  112. return Math.max(value, PhysicsEngine.Epsilon);
  113. };
  114. let globalQuaternion: Quaternion = new Quaternion();
  115. impostors.forEach((i) => {
  116. if (!i.object.rotationQuaternion) {
  117. return;
  118. }
  119. //get the correct bounding box
  120. var oldQuaternion = i.object.rotationQuaternion;
  121. globalQuaternion = oldQuaternion.clone();
  122. var rot = oldQuaternion.toEulerAngles();
  123. var extendSize = i.getObjectExtendSize();
  124. const radToDeg = 57.295779513082320876;
  125. if (i === impostor) {
  126. var center = impostor.getObjectCenter();
  127. impostor.object.getAbsolutePivotPoint().subtractToRef(center, this._tmpPositionVector);
  128. this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  129. //Can also use Array.prototype.push.apply
  130. bodyConfig.pos.push(center.x);
  131. bodyConfig.pos.push(center.y);
  132. bodyConfig.pos.push(center.z);
  133. bodyConfig.posShape.push(0, 0, 0);
  134. bodyConfig.rotShape.push(0, 0, 0);
  135. } else {
  136. let localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  137. bodyConfig.posShape.push(localPosition.x);
  138. bodyConfig.posShape.push(localPosition.y);
  139. bodyConfig.posShape.push(localPosition.z);
  140. bodyConfig.pos.push(0, 0, 0);
  141. bodyConfig.rotShape.push(rot.x * radToDeg);
  142. bodyConfig.rotShape.push(rot.y * radToDeg);
  143. bodyConfig.rotShape.push(rot.z * radToDeg);
  144. }
  145. // register mesh
  146. switch (i.type) {
  147. case PhysicsImpostor.ParticleImpostor:
  148. Logger.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  149. case PhysicsImpostor.SphereImpostor:
  150. var radiusX = extendSize.x;
  151. var radiusY = extendSize.y;
  152. var radiusZ = extendSize.z;
  153. var size = Math.max(
  154. checkWithEpsilon(radiusX),
  155. checkWithEpsilon(radiusY),
  156. checkWithEpsilon(radiusZ)) / 2;
  157. bodyConfig.type.push('sphere');
  158. //due to the way oimo works with compounds, add 3 times
  159. bodyConfig.size.push(size);
  160. bodyConfig.size.push(size);
  161. bodyConfig.size.push(size);
  162. break;
  163. case PhysicsImpostor.CylinderImpostor:
  164. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  165. var sizeY = checkWithEpsilon(extendSize.y);
  166. bodyConfig.type.push('cylinder');
  167. bodyConfig.size.push(sizeX);
  168. bodyConfig.size.push(sizeY);
  169. //due to the way oimo works with compounds, add one more value.
  170. bodyConfig.size.push(sizeY);
  171. break;
  172. case PhysicsImpostor.PlaneImpostor:
  173. case PhysicsImpostor.BoxImpostor:
  174. default:
  175. var sizeX = checkWithEpsilon(extendSize.x);
  176. var sizeY = checkWithEpsilon(extendSize.y);
  177. var sizeZ = checkWithEpsilon(extendSize.z);
  178. bodyConfig.type.push('box');
  179. //if (i === impostor) {
  180. bodyConfig.size.push(sizeX);
  181. bodyConfig.size.push(sizeY);
  182. bodyConfig.size.push(sizeZ);
  183. //} else {
  184. // bodyConfig.size.push(0,0,0);
  185. //}
  186. break;
  187. }
  188. //actually not needed, but hey...
  189. i.object.rotationQuaternion = oldQuaternion;
  190. });
  191. impostor.physicsBody = this.world.add(bodyConfig);
  192. // set the quaternion, ignoring the previously defined (euler) rotation
  193. impostor.physicsBody.resetQuaternion(globalQuaternion);
  194. // update with delta 0, so the body will reveive the new rotation.
  195. impostor.physicsBody.updatePosition(0);
  196. } else {
  197. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  198. }
  199. impostor.setDeltaPosition(this._tmpPositionVector);
  200. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  201. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  202. }
  203. private _tmpPositionVector: Vector3 = Vector3.Zero();
  204. public removePhysicsBody(impostor: PhysicsImpostor) {
  205. //impostor.physicsBody.dispose();
  206. //Same as : (older oimo versions)
  207. this.world.removeRigidBody(impostor.physicsBody);
  208. }
  209. public generateJoint(impostorJoint: PhysicsImpostorJoint) {
  210. var mainBody = impostorJoint.mainImpostor.physicsBody;
  211. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  212. if (!mainBody || !connectedBody) {
  213. return;
  214. }
  215. var jointData = impostorJoint.joint.jointData;
  216. var options = jointData.nativeParams || {};
  217. var type;
  218. var nativeJointData: any = {
  219. body1: mainBody,
  220. body2: connectedBody,
  221. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  222. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  223. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  224. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  225. min: options.min,
  226. max: options.max,
  227. collision: options.collision || jointData.collision,
  228. spring: options.spring,
  229. //supporting older version of Oimo
  230. world: this.world
  231. };
  232. switch (impostorJoint.joint.type) {
  233. case PhysicsJoint.BallAndSocketJoint:
  234. type = "jointBall";
  235. break;
  236. case PhysicsJoint.SpringJoint:
  237. Logger.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  238. var springData = <SpringJointData>jointData;
  239. nativeJointData.min = springData.length || nativeJointData.min;
  240. //Max should also be set, just make sure it is at least min
  241. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  242. case PhysicsJoint.DistanceJoint:
  243. type = "jointDistance";
  244. nativeJointData.max = (<DistanceJointData>jointData).maxDistance;
  245. break;
  246. case PhysicsJoint.PrismaticJoint:
  247. type = "jointPrisme";
  248. break;
  249. case PhysicsJoint.SliderJoint:
  250. type = "jointSlide";
  251. break;
  252. case PhysicsJoint.WheelJoint:
  253. type = "jointWheel";
  254. break;
  255. case PhysicsJoint.HingeJoint:
  256. default:
  257. type = "jointHinge";
  258. break;
  259. }
  260. nativeJointData.type = type;
  261. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  262. }
  263. public removeJoint(impostorJoint: PhysicsImpostorJoint) {
  264. //Bug in Oimo prevents us from disposing a joint in the playground
  265. //joint.joint.physicsJoint.dispose();
  266. //So we will bruteforce it!
  267. try {
  268. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  269. } catch (e) {
  270. Logger.Warn(e);
  271. }
  272. }
  273. public isSupported(): boolean {
  274. return this.BJSOIMO !== undefined;
  275. }
  276. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  277. if (!impostor.physicsBody.sleeping) {
  278. //TODO check that
  279. /*if (impostor.physicsBody.shapes.next) {
  280. var parentShape = this._getLastShape(impostor.physicsBody);
  281. impostor.object.position.copyFrom(parentShape.position);
  282. console.log(parentShape.position);
  283. } else {*/
  284. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  285. //}
  286. if (impostor.object.rotationQuaternion) {
  287. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  288. }
  289. }
  290. }
  291. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  292. var body = impostor.physicsBody;
  293. body.position.copy(newPosition);
  294. body.orientation.copy(newRotation);
  295. body.syncShapes();
  296. body.awake();
  297. }
  298. /*private _getLastShape(body: any): any {
  299. var lastShape = body.shapes;
  300. while (lastShape.next) {
  301. lastShape = lastShape.next;
  302. }
  303. return lastShape;
  304. }*/
  305. public setLinearVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  306. impostor.physicsBody.linearVelocity.copy(velocity);
  307. }
  308. public setAngularVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  309. impostor.physicsBody.angularVelocity.copy(velocity);
  310. }
  311. public getLinearVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  312. var v = impostor.physicsBody.linearVelocity;
  313. if (!v) {
  314. return null;
  315. }
  316. return new Vector3(v.x, v.y, v.z);
  317. }
  318. public getAngularVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  319. var v = impostor.physicsBody.angularVelocity;
  320. if (!v) {
  321. return null;
  322. }
  323. return new Vector3(v.x, v.y, v.z);
  324. }
  325. public setBodyMass(impostor: PhysicsImpostor, mass: number) {
  326. var staticBody: boolean = mass === 0;
  327. //this will actually set the body's density and not its mass.
  328. //But this is how oimo treats the mass variable.
  329. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  330. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  331. }
  332. public getBodyMass(impostor: PhysicsImpostor): number {
  333. return impostor.physicsBody.shapes.density;
  334. }
  335. public getBodyFriction(impostor: PhysicsImpostor): number {
  336. return impostor.physicsBody.shapes.friction;
  337. }
  338. public setBodyFriction(impostor: PhysicsImpostor, friction: number) {
  339. impostor.physicsBody.shapes.friction = friction;
  340. }
  341. public getBodyRestitution(impostor: PhysicsImpostor): number {
  342. return impostor.physicsBody.shapes.restitution;
  343. }
  344. public setBodyRestitution(impostor: PhysicsImpostor, restitution: number) {
  345. impostor.physicsBody.shapes.restitution = restitution;
  346. }
  347. public sleepBody(impostor: PhysicsImpostor) {
  348. impostor.physicsBody.sleep();
  349. }
  350. public wakeUpBody(impostor: PhysicsImpostor) {
  351. impostor.physicsBody.awake();
  352. }
  353. public updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number) {
  354. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  355. if (minDistance !== void 0) {
  356. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  357. }
  358. }
  359. public setMotor(joint: IMotorEnabledJoint, speed: number, force?: number, motorIndex?: number) {
  360. if (force !== undefined) {
  361. Logger.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter");
  362. } else {
  363. force = 1e6;
  364. }
  365. speed *= -1;
  366. //TODO separate rotational and transational motors.
  367. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  368. if (motor) {
  369. motor.setMotor(speed, force);
  370. }
  371. }
  372. public setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number, motorIndex?: number) {
  373. //TODO separate rotational and transational motors.
  374. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  375. if (motor) {
  376. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  377. }
  378. }
  379. public syncMeshWithImpostor(mesh: AbstractMesh, impostor: PhysicsImpostor) {
  380. var body = impostor.physicsBody;
  381. mesh.position.x = body.position.x;
  382. mesh.position.y = body.position.y;
  383. mesh.position.z = body.position.z;
  384. if (mesh.rotationQuaternion) {
  385. mesh.rotationQuaternion.x = body.orientation.x;
  386. mesh.rotationQuaternion.y = body.orientation.y;
  387. mesh.rotationQuaternion.z = body.orientation.z;
  388. mesh.rotationQuaternion.w = body.orientation.s;
  389. }
  390. }
  391. public getRadius(impostor: PhysicsImpostor): number {
  392. return impostor.physicsBody.shapes.radius;
  393. }
  394. public getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void {
  395. var shape = impostor.physicsBody.shapes;
  396. result.x = shape.halfWidth * 2;
  397. result.y = shape.halfHeight * 2;
  398. result.z = shape.halfDepth * 2;
  399. }
  400. public dispose() {
  401. this.world.clear();
  402. }
  403. /**
  404. * Does a raycast in the physics world
  405. * @param from when should the ray start?
  406. * @param to when should the ray end?
  407. * @returns PhysicsRaycastResult
  408. */
  409. public raycast(from: Vector3, to: Vector3): PhysicsRaycastResult {
  410. Logger.Warn("raycast is not currently supported by the Oimo physics plugin");
  411. this._raycastResult.reset(from, to);
  412. return this._raycastResult;
  413. }
  414. }