babylon.oimoJSPlugin.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var OimoJSPlugin = (function () {
  4. function OimoJSPlugin(iterations) {
  5. this.name = "OimoJSPlugin";
  6. this._tmpImpostorsArray = [];
  7. this._tmpPositionVector = BABYLON.Vector3.Zero();
  8. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  9. this.world.clear();
  10. //making sure no stats are calculated
  11. this.world.isNoStat = true;
  12. }
  13. OimoJSPlugin.prototype.setGravity = function (gravity) {
  14. this.world.gravity.copy(gravity);
  15. };
  16. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  17. this.world.timeStep = timeStep;
  18. };
  19. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  20. var _this = this;
  21. impostors.forEach(function (impostor) {
  22. impostor.beforeStep();
  23. });
  24. this.world.step();
  25. impostors.forEach(function (impostor) {
  26. impostor.afterStep();
  27. //update the ordered impostors array
  28. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  29. });
  30. //check for collisions
  31. var contact = this.world.contacts;
  32. while (contact !== null) {
  33. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  34. contact = contact.next;
  35. continue;
  36. }
  37. //is this body colliding with any other? get the impostor
  38. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  39. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  40. if (!mainImpostor || !collidingImpostor) {
  41. contact = contact.next;
  42. continue;
  43. }
  44. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  45. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  46. contact = contact.next;
  47. }
  48. };
  49. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  50. var mass = impostor.physicsBody.massInfo.mass;
  51. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  52. };
  53. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  54. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  55. this.applyImpulse(impostor, force, contactPoint);
  56. };
  57. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  58. var _this = this;
  59. //parent-child relationship. Does this impostor has a parent impostor?
  60. if (impostor.parent) {
  61. if (impostor.physicsBody) {
  62. this.removePhysicsBody(impostor);
  63. //TODO is that needed?
  64. impostor.forceUpdate();
  65. }
  66. return;
  67. }
  68. if (impostor.isBodyInitRequired()) {
  69. var bodyConfig = {
  70. name: impostor.uniqueId,
  71. //Oimo must have mass, also for static objects.
  72. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  73. size: [],
  74. type: [],
  75. pos: [],
  76. rot: [],
  77. move: impostor.getParam("mass") !== 0,
  78. //Supporting older versions of Oimo
  79. world: this.world
  80. };
  81. var impostors = [impostor];
  82. function addToArray(parent) {
  83. if (!parent.getChildMeshes)
  84. return;
  85. parent.getChildMeshes().forEach(function (m) {
  86. if (m.physicsImpostor) {
  87. impostors.push(m.physicsImpostor);
  88. m.physicsImpostor._init();
  89. }
  90. });
  91. }
  92. addToArray(impostor.object);
  93. function checkWithEpsilon(value) {
  94. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  95. }
  96. impostors.forEach(function (i) {
  97. //get the correct bounding box
  98. var oldQuaternion = i.object.rotationQuaternion;
  99. var rot = new OIMO.Euler().setFromQuaternion({
  100. x: impostor.object.rotationQuaternion.x,
  101. y: impostor.object.rotationQuaternion.y,
  102. z: impostor.object.rotationQuaternion.z,
  103. s: impostor.object.rotationQuaternion.w
  104. });
  105. var extendSize = i.getObjectExtendSize();
  106. if (i === impostor) {
  107. var center = impostor.getObjectCenter();
  108. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  109. //Can also use Array.prototype.push.apply
  110. bodyConfig.pos.push(center.x);
  111. bodyConfig.pos.push(center.y);
  112. bodyConfig.pos.push(center.z);
  113. //tmp solution
  114. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  115. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  116. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  117. }
  118. else {
  119. bodyConfig.pos.push(i.object.position.x);
  120. bodyConfig.pos.push(i.object.position.y);
  121. bodyConfig.pos.push(i.object.position.z);
  122. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  123. bodyConfig.rot.push(0);
  124. bodyConfig.rot.push(0);
  125. bodyConfig.rot.push(0);
  126. }
  127. // register mesh
  128. switch (i.type) {
  129. case BABYLON.PhysicsImpostor.ParticleImpostor:
  130. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  131. case BABYLON.PhysicsImpostor.SphereImpostor:
  132. var radiusX = extendSize.x;
  133. var radiusY = extendSize.y;
  134. var radiusZ = extendSize.z;
  135. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  136. bodyConfig.type.push('sphere');
  137. //due to the way oimo works with compounds, add 3 times
  138. bodyConfig.size.push(size);
  139. bodyConfig.size.push(size);
  140. bodyConfig.size.push(size);
  141. break;
  142. case BABYLON.PhysicsImpostor.CylinderImpostor:
  143. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  144. var sizeY = checkWithEpsilon(extendSize.y);
  145. bodyConfig.type.push('cylinder');
  146. bodyConfig.size.push(sizeX);
  147. bodyConfig.size.push(sizeY);
  148. //due to the way oimo works with compounds, add one more value.
  149. bodyConfig.size.push(sizeY);
  150. break;
  151. case BABYLON.PhysicsImpostor.PlaneImpostor:
  152. case BABYLON.PhysicsImpostor.BoxImpostor:
  153. default:
  154. var sizeX = checkWithEpsilon(extendSize.x);
  155. var sizeY = checkWithEpsilon(extendSize.y);
  156. var sizeZ = checkWithEpsilon(extendSize.z);
  157. bodyConfig.type.push('box');
  158. bodyConfig.size.push(sizeX);
  159. bodyConfig.size.push(sizeY);
  160. bodyConfig.size.push(sizeZ);
  161. break;
  162. }
  163. //actually not needed, but hey...
  164. i.object.rotationQuaternion = oldQuaternion;
  165. });
  166. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  167. }
  168. else {
  169. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  170. }
  171. impostor.setDeltaPosition(this._tmpPositionVector);
  172. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  173. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  174. };
  175. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  176. //impostor.physicsBody.dispose();
  177. //Same as : (older oimo versions)
  178. this.world.removeRigidBody(impostor.physicsBody);
  179. };
  180. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  181. var mainBody = impostorJoint.mainImpostor.physicsBody;
  182. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  183. if (!mainBody || !connectedBody) {
  184. return;
  185. }
  186. var jointData = impostorJoint.joint.jointData;
  187. var options = jointData.nativeParams || {};
  188. var type;
  189. var nativeJointData = {
  190. body1: mainBody,
  191. body2: connectedBody,
  192. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  193. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  194. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  195. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  196. min: options.min,
  197. max: options.max,
  198. collision: options.collision || jointData.collision,
  199. spring: options.spring,
  200. //supporting older version of Oimo
  201. world: this.world
  202. };
  203. switch (impostorJoint.joint.type) {
  204. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  205. type = "jointBall";
  206. break;
  207. case BABYLON.PhysicsJoint.SpringJoint:
  208. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  209. var springData = jointData;
  210. nativeJointData.min = springData.length || nativeJointData.min;
  211. //Max should also be set, just make sure it is at least min
  212. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  213. case BABYLON.PhysicsJoint.DistanceJoint:
  214. type = "jointDistance";
  215. nativeJointData.max = jointData.maxDistance;
  216. break;
  217. case BABYLON.PhysicsJoint.PrismaticJoint:
  218. type = "jointPrisme";
  219. break;
  220. case BABYLON.PhysicsJoint.SliderJoint:
  221. type = "jointSlide";
  222. break;
  223. case BABYLON.PhysicsJoint.WheelJoint:
  224. type = "jointWheel";
  225. break;
  226. case BABYLON.PhysicsJoint.HingeJoint:
  227. default:
  228. type = "jointHinge";
  229. break;
  230. }
  231. nativeJointData.type = type;
  232. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  233. };
  234. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  235. //Bug in Oimo prevents us from disposing a joint in the playground
  236. //joint.joint.physicsJoint.dispose();
  237. //So we will bruteforce it!
  238. try {
  239. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  240. }
  241. catch (e) {
  242. BABYLON.Tools.Warn(e);
  243. }
  244. };
  245. OimoJSPlugin.prototype.isSupported = function () {
  246. return OIMO !== undefined;
  247. };
  248. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  249. if (!impostor.physicsBody.sleeping) {
  250. //TODO check that
  251. if (impostor.physicsBody.shapes.next) {
  252. var parentShape = this._getLastShape(impostor.physicsBody);
  253. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  254. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  255. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  256. }
  257. else {
  258. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  259. }
  260. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  261. }
  262. };
  263. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  264. var body = impostor.physicsBody;
  265. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  266. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  267. body.syncShapes();
  268. body.awake();
  269. };
  270. OimoJSPlugin.prototype._getLastShape = function (body) {
  271. var lastShape = body.shapes;
  272. while (lastShape.next) {
  273. lastShape = lastShape.next;
  274. }
  275. return lastShape;
  276. };
  277. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  278. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  279. };
  280. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  281. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  282. };
  283. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  284. var v = impostor.physicsBody.linearVelocity;
  285. if (!v)
  286. return null;
  287. return new BABYLON.Vector3(v.x, v.y, v.z);
  288. };
  289. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  290. var v = impostor.physicsBody.angularVelocity;
  291. if (!v)
  292. return null;
  293. return new BABYLON.Vector3(v.x, v.y, v.z);
  294. };
  295. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  296. var staticBody = mass === 0;
  297. //this will actually set the body's density and not its mass.
  298. //But this is how oimo treats the mass variable.
  299. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  300. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  301. };
  302. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  303. impostor.physicsBody.sleep();
  304. };
  305. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  306. impostor.physicsBody.awake();
  307. };
  308. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  309. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  310. if (minDistance !== void 0) {
  311. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  312. }
  313. };
  314. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  315. //TODO separate rotational and transational motors.
  316. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  317. if (motor) {
  318. motor.setMotor(speed, maxForce);
  319. }
  320. };
  321. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  322. //TODO separate rotational and transational motors.
  323. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  324. if (motor) {
  325. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  326. }
  327. };
  328. OimoJSPlugin.prototype.dispose = function () {
  329. this.world.clear();
  330. };
  331. return OimoJSPlugin;
  332. })();
  333. BABYLON.OimoJSPlugin = OimoJSPlugin;
  334. })(BABYLON || (BABYLON = {}));