oimoJSPlugin.ts 19 KB

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