babylon.oimoJSPlugin.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. module BABYLON {
  2. declare var OIMO;
  3. export class OimoJSPlugin {
  4. public world: any;
  5. public name: string = "OimoJSPlugin";
  6. constructor(iterations?: number) {
  7. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  8. this.world.clear();
  9. //making sure no stats are calculated
  10. this.world.isNoStat = true;
  11. }
  12. public setGravity(gravity: Vector3) {
  13. this.world.gravity.copy(gravity);
  14. }
  15. private _tmpImpostorsArray: Array<PhysicsImpostor> = [];
  16. public executeStep(delta: number, impostors: Array<PhysicsImpostor>) {
  17. impostors.forEach(function(impostor) {
  18. impostor.beforeStep();
  19. });
  20. this.world.step();
  21. impostors.forEach((impostor) => {
  22. impostor.afterStep();
  23. //update the ordered impostors array
  24. this._tmpImpostorsArray[impostor.mesh.uniqueId] = impostor;
  25. });
  26. //check for collisions
  27. var contact = this.world.contacts;
  28. while (contact !== null) {
  29. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  30. contact = contact.next;
  31. continue;
  32. }
  33. //is this body colliding with any other? get the impostor
  34. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  35. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  36. if (!mainImpostor || !collidingImpostor) {
  37. contact = contact.next;
  38. continue;
  39. }
  40. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  41. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  42. contact = contact.next;
  43. }
  44. }
  45. public applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  46. var mass = impostor.physicsBody.massInfo.mass;
  47. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  48. }
  49. public applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  50. Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  51. this.applyImpulse(impostor, force, contactPoint);
  52. }
  53. public generatePhysicsBody(impostor: PhysicsImpostor) {
  54. //parent-child relationship. Does this impostor has a parent impostor?
  55. if (impostor.parent) {
  56. if (impostor.physicsBody) {
  57. this.removePhysicsBody(impostor);
  58. //TODO is that needed?
  59. impostor.forceUpdate();
  60. }
  61. return;
  62. }
  63. impostor.mesh.computeWorldMatrix(true);
  64. if (impostor.isBodyInitRequired()) {
  65. if (!impostor.mesh.rotationQuaternion) {
  66. impostor.mesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  67. }
  68. var bodyConfig: any = {
  69. name: impostor.mesh.uniqueId,
  70. //Oimo must have mass, also for static objects.
  71. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  72. size: [],
  73. type: [],
  74. pos: [],
  75. rot: [],
  76. move: impostor.getParam("mass") !== 0,
  77. //Supporting older versions of Oimo
  78. world: this.world
  79. };
  80. var impostors = [impostor];
  81. function addToArray(parent: AbstractMesh) {
  82. parent.getChildMeshes().forEach(function(m) {
  83. if (m.physicsImpostor) {
  84. impostors.push(m.physicsImpostor);
  85. m.physicsImpostor._init();
  86. }
  87. });
  88. }
  89. addToArray(impostor.mesh)
  90. function checkWithEpsilon(value: number): number {
  91. return Math.max(value, PhysicsEngine.Epsilon);
  92. }
  93. impostors.forEach((i) => {
  94. //get the correct bounding box
  95. var oldQuaternion = i.mesh.rotationQuaternion;
  96. var rot = new OIMO.Euler().setFromQuaternion({ x: impostor.mesh.rotationQuaternion.x, y: impostor.mesh.rotationQuaternion.y, z: impostor.mesh.rotationQuaternion.z, s: impostor.mesh.rotationQuaternion.w });
  97. i.mesh.rotationQuaternion = new Quaternion(0, 0, 0, 1);
  98. i.mesh.computeWorldMatrix(true);
  99. var bbox = i.mesh.getBoundingInfo().boundingBox;
  100. if (i === impostor) {
  101. impostor.mesh.position.subtractToRef(impostor.mesh.getBoundingInfo().boundingBox.center, this._tmpPositionVector);
  102. //Can also use Array.prototype.push.apply
  103. bodyConfig.pos.push(bbox.center.x);
  104. bodyConfig.pos.push(bbox.center.y);
  105. bodyConfig.pos.push(bbox.center.z);
  106. //tmp solution
  107. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  108. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  109. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  110. } else {
  111. bodyConfig.pos.push(i.mesh.position.x);
  112. bodyConfig.pos.push(i.mesh.position.y);
  113. bodyConfig.pos.push(i.mesh.position.z);
  114. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  115. bodyConfig.rot.push(0);
  116. bodyConfig.rot.push(0);
  117. bodyConfig.rot.push(0);
  118. }
  119. // register mesh
  120. switch (i.type) {
  121. case PhysicsEngine.SphereImpostor:
  122. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  123. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  124. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  125. var size = Math.max(
  126. checkWithEpsilon(radiusX),
  127. checkWithEpsilon(radiusY),
  128. checkWithEpsilon(radiusZ)) / 2;
  129. bodyConfig.type.push('sphere');
  130. //due to the way oimo works with compounds, add 3 times
  131. bodyConfig.size.push(size);
  132. bodyConfig.size.push(size);
  133. bodyConfig.size.push(size);
  134. break;
  135. case PhysicsEngine.PlaneImpostor:
  136. //TODO Oimo now supports cylinder!
  137. case PhysicsEngine.CylinderImpostor:
  138. case PhysicsEngine.BoxImpostor:
  139. default:
  140. var min = bbox.minimumWorld;
  141. var max = bbox.maximumWorld;
  142. var box = max.subtract(min);
  143. var sizeX = checkWithEpsilon(box.x);
  144. var sizeY = checkWithEpsilon(box.y);
  145. var sizeZ = checkWithEpsilon(box.z);
  146. bodyConfig.type.push('box');
  147. bodyConfig.size.push(sizeX);
  148. bodyConfig.size.push(sizeY);
  149. bodyConfig.size.push(sizeZ);
  150. break;
  151. }
  152. //actually not needed, but hey...
  153. i.mesh.rotationQuaternion = oldQuaternion;
  154. });
  155. impostor.physicsBody = new OIMO.Body(bodyConfig).body//this.world.add(bodyConfig);
  156. } else {
  157. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  158. }
  159. impostor.setDeltaPosition(this._tmpPositionVector);
  160. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  161. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  162. }
  163. private _tmpPositionVector: Vector3 = Vector3.Zero();
  164. public removePhysicsBody(impostor: PhysicsImpostor) {
  165. //impostor.physicsBody.dispose();
  166. //Same as : (older oimo versions)
  167. this.world.removeRigidBody(impostor.physicsBody);
  168. }
  169. public generateJoint(impostorJoint: PhysicsImpostorJoint) {
  170. var mainBody = impostorJoint.mainImpostor.physicsBody;
  171. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  172. if (!mainBody || !connectedBody) {
  173. return;
  174. }
  175. var jointData = impostorJoint.joint.jointData;
  176. var options = jointData.nativeParams || {};
  177. var type;
  178. var nativeJointData: any = {
  179. body1: mainBody,
  180. body2: connectedBody,
  181. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  182. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  183. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  184. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  185. min: options.min,
  186. max: options.max,
  187. collision: options.collision || jointData.collision,
  188. spring: options.spring,
  189. //supporting older version of Oimo
  190. world: this.world
  191. }
  192. switch (impostorJoint.joint.type) {
  193. case PhysicsJoint.BallAndSocketJoint:
  194. type = "jointBall";
  195. break;
  196. case PhysicsJoint.SpringJoint:
  197. Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  198. var springData = <SpringJointData>jointData;
  199. nativeJointData.min = springData.length || nativeJointData.min;
  200. //Max should also be set, just make sure it is at least min
  201. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  202. case PhysicsJoint.DistanceJoint:
  203. type = "jointDistance";
  204. nativeJointData.max = (<DistanceJointData>jointData).maxDistance
  205. break;
  206. case PhysicsJoint.PrismaticJoint:
  207. type = "jointPrisme";
  208. break;
  209. case PhysicsJoint.SliderJoint:
  210. type = "jointSlide";
  211. break;
  212. case PhysicsJoint.WheelJoint:
  213. type = "jointWheel";
  214. break;
  215. case PhysicsJoint.HingeJoint:
  216. default:
  217. type = "jointHinge";
  218. break;
  219. }
  220. nativeJointData.type = type;
  221. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint//this.world.add(nativeJointData);
  222. }
  223. public removeJoint(joint: PhysicsImpostorJoint) {
  224. joint.joint.physicsJoint.dispose();
  225. }
  226. public isSupported(): boolean {
  227. return OIMO !== undefined;
  228. }
  229. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  230. if (!impostor.physicsBody.sleeping) {
  231. //TODO check that
  232. if (impostor.physicsBody.shapes.next) {
  233. var parentShape = this._getLastShape(impostor.physicsBody);
  234. impostor.mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  235. impostor.mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  236. impostor.mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  237. } else {
  238. impostor.mesh.position.copyFrom(impostor.physicsBody.getPosition());
  239. }
  240. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  241. }
  242. }
  243. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  244. var body = impostor.physicsBody;
  245. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  246. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  247. body.syncShapes();
  248. body.awake();
  249. }
  250. private _getLastShape(body: any): any {
  251. var lastShape = body.shapes;
  252. while (lastShape.next) {
  253. lastShape = lastShape.next;
  254. }
  255. return lastShape;
  256. }
  257. public setVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  258. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  259. }
  260. public sleepBody(impostor: PhysicsImpostor) {
  261. impostor.physicsBody.sleep();
  262. }
  263. public wakeUpBody(impostor: PhysicsImpostor) {
  264. impostor.physicsBody.awake();
  265. }
  266. public dispose() {
  267. this.world.clear();
  268. }
  269. }
  270. }