babylon.oimoJSPlugin.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. module BABYLON {
  2. declare var OIMO;
  3. export class OimoJSPlugin implements IPhysicsEnginePlugin {
  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.worldscale(1);
  9. this.world.clear();
  10. //making sure no stats are calculated
  11. this.world.isNoStat = true;
  12. }
  13. public setGravity(gravity: Vector3) {
  14. this.world.gravity.copy(gravity);
  15. }
  16. public setTimeStep(timeStep: number) {
  17. this.world.timeStep = timeStep;
  18. }
  19. private _tmpImpostorsArray: Array<PhysicsImpostor> = [];
  20. public executeStep(delta: number, impostors: Array<PhysicsImpostor>) {
  21. impostors.forEach(function (impostor) {
  22. impostor.beforeStep();
  23. });
  24. this.world.step();
  25. impostors.forEach((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. public applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  50. var mass = impostor.physicsBody.massInfo.mass;
  51. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  52. }
  53. public applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  54. Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  55. this.applyImpulse(impostor, force, contactPoint);
  56. }
  57. public generatePhysicsBody(impostor: PhysicsImpostor) {
  58. //parent-child relationship. Does this impostor has a parent impostor?
  59. if (impostor.parent) {
  60. if (impostor.physicsBody) {
  61. this.removePhysicsBody(impostor);
  62. //TODO is that needed?
  63. impostor.forceUpdate();
  64. }
  65. return;
  66. }
  67. if (impostor.isBodyInitRequired()) {
  68. var bodyConfig: any = {
  69. name: impostor.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. let addToArray = (parent: IPhysicsEnabledObject) => {
  82. if (!parent.getChildMeshes) return;
  83. parent.getChildMeshes().forEach(function (m) {
  84. if (m.physicsImpostor) {
  85. impostors.push(m.physicsImpostor);
  86. m.physicsImpostor._init();
  87. }
  88. });
  89. }
  90. addToArray(impostor.object)
  91. let checkWithEpsilon = (value: number): number => {
  92. return Math.max(value, PhysicsEngine.Epsilon);
  93. }
  94. impostors.forEach((i) => {
  95. //get the correct bounding box
  96. var oldQuaternion = i.object.rotationQuaternion;
  97. var rot = new OIMO.Euler().setFromQuaternion({
  98. x: impostor.object.rotationQuaternion.x,
  99. y: impostor.object.rotationQuaternion.y,
  100. z: impostor.object.rotationQuaternion.z,
  101. s: impostor.object.rotationQuaternion.w
  102. });
  103. var extendSize = i.getObjectExtendSize();
  104. if (i === impostor) {
  105. var center = impostor.getObjectCenter();
  106. impostor.object.position.subtractToRef(center, this._tmpPositionVector);
  107. //Can also use Array.prototype.push.apply
  108. bodyConfig.pos.push(center.x);
  109. bodyConfig.pos.push(center.y);
  110. bodyConfig.pos.push(center.z);
  111. //tmp solution
  112. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  113. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  114. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  115. } else {
  116. bodyConfig.pos.push(i.object.position.x);
  117. bodyConfig.pos.push(i.object.position.y);
  118. bodyConfig.pos.push(i.object.position.z);
  119. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  120. bodyConfig.rot.push(0);
  121. bodyConfig.rot.push(0);
  122. bodyConfig.rot.push(0);
  123. }
  124. // register mesh
  125. switch (i.type) {
  126. case PhysicsImpostor.ParticleImpostor:
  127. Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  128. case PhysicsImpostor.SphereImpostor:
  129. var radiusX = extendSize.x;
  130. var radiusY = extendSize.y;
  131. var radiusZ = extendSize.z;
  132. var size = Math.max(
  133. checkWithEpsilon(radiusX),
  134. checkWithEpsilon(radiusY),
  135. 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 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 PhysicsImpostor.PlaneImpostor:
  152. case 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. } else {
  168. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  169. }
  170. impostor.setDeltaPosition(this._tmpPositionVector);
  171. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  172. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  173. }
  174. private _tmpPositionVector: Vector3 = Vector3.Zero();
  175. public removePhysicsBody(impostor: PhysicsImpostor) {
  176. //impostor.physicsBody.dispose();
  177. //Same as : (older oimo versions)
  178. this.world.removeRigidBody(impostor.physicsBody);
  179. }
  180. public generateJoint(impostorJoint: PhysicsImpostorJoint) {
  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: any = {
  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 PhysicsJoint.BallAndSocketJoint:
  205. type = "jointBall";
  206. break;
  207. case PhysicsJoint.SpringJoint:
  208. Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  209. var springData = <SpringJointData>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 PhysicsJoint.DistanceJoint:
  214. type = "jointDistance";
  215. nativeJointData.max = (<DistanceJointData>jointData).maxDistance
  216. break;
  217. case PhysicsJoint.PrismaticJoint:
  218. type = "jointPrisme";
  219. break;
  220. case PhysicsJoint.SliderJoint:
  221. type = "jointSlide";
  222. break;
  223. case PhysicsJoint.WheelJoint:
  224. type = "jointWheel";
  225. break;
  226. case 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. public removeJoint(impostorJoint: PhysicsImpostorJoint) {
  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. } catch (e) {
  241. Tools.Warn(e);
  242. }
  243. }
  244. public isSupported(): boolean {
  245. return OIMO !== undefined;
  246. }
  247. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  248. if (!impostor.physicsBody.sleeping) {
  249. //TODO check that
  250. if (impostor.physicsBody.shapes.next) {
  251. var parentShape = this._getLastShape(impostor.physicsBody);
  252. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  253. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  254. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  255. } else {
  256. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  257. }
  258. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  259. impostor.object.rotationQuaternion.normalize();
  260. }
  261. }
  262. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  263. var body = impostor.physicsBody;
  264. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  265. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  266. body.syncShapes();
  267. body.awake();
  268. }
  269. private _getLastShape(body: any): any {
  270. var lastShape = body.shapes;
  271. while (lastShape.next) {
  272. lastShape = lastShape.next;
  273. }
  274. return lastShape;
  275. }
  276. public setLinearVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  277. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  278. }
  279. public setAngularVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  280. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  281. }
  282. public getLinearVelocity(impostor: PhysicsImpostor): Vector3 {
  283. var v = impostor.physicsBody.linearVelocity;
  284. if (!v) return null;
  285. return new Vector3(v.x, v.y, v.z)
  286. }
  287. public getAngularVelocity(impostor: PhysicsImpostor): Vector3 {
  288. var v = impostor.physicsBody.angularVelocity;
  289. if (!v) return null;
  290. return new Vector3(v.x, v.y, v.z)
  291. }
  292. public setBodyMass(impostor: PhysicsImpostor, mass: number) {
  293. var staticBody: boolean = mass === 0;
  294. //this will actually set the body's density and not its mass.
  295. //But this is how oimo treats the mass variable.
  296. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  297. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  298. }
  299. public getBodyMass(impostor: PhysicsImpostor):number {
  300. return impostor.physicsBody.shapes.density;
  301. }
  302. public getBodyFriction(impostor: PhysicsImpostor):number {
  303. return impostor.physicsBody.shapes.friction;
  304. }
  305. public setBodyFriction(impostor: PhysicsImpostor, friction:number) {
  306. impostor.physicsBody.shapes.friction = friction;
  307. }
  308. public getBodyRestitution(impostor: PhysicsImpostor):number {
  309. return impostor.physicsBody.shapes.restitution;
  310. }
  311. public setBodyRestitution(impostor: PhysicsImpostor, restitution:number) {
  312. impostor.physicsBody.shapes.restitution = restitution;
  313. }
  314. public sleepBody(impostor: PhysicsImpostor) {
  315. impostor.physicsBody.sleep();
  316. }
  317. public wakeUpBody(impostor: PhysicsImpostor) {
  318. impostor.physicsBody.awake();
  319. }
  320. public updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number) {
  321. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  322. if (minDistance !== void 0) {
  323. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  324. }
  325. }
  326. public setMotor(joint: IMotorEnabledJoint, speed: number, maxForce?: number, motorIndex?: number) {
  327. //TODO separate rotational and transational motors.
  328. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  329. if (motor) {
  330. motor.setMotor(speed, maxForce);
  331. }
  332. }
  333. public setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number, motorIndex?: number) {
  334. //TODO separate rotational and transational motors.
  335. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  336. if (motor) {
  337. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  338. }
  339. }
  340. public syncMeshWithImpostor(mesh:AbstractMesh, impostor:PhysicsImpostor){
  341. var body = impostor.physicsBody;
  342. mesh.position.x = body.position.x;
  343. mesh.position.y = body.position.y;
  344. mesh.position.z = body.position.z;
  345. mesh.rotationQuaternion.x = body.orientation.x;
  346. mesh.rotationQuaternion.y = body.orientation.y;
  347. mesh.rotationQuaternion.z = body.orientation.z;
  348. mesh.rotationQuaternion.w = body.orientation.s;
  349. }
  350. public getRadius(impostor: PhysicsImpostor):number{
  351. return impostor.physicsBody.shapes.radius;
  352. }
  353. public getBoxSizeToRef(impostor: PhysicsImpostor, result:Vector3):void{
  354. var shape = impostor.physicsBody.shapes;
  355. result.x = shape.halfWidth * 2;
  356. result.y = shape.halfHeight * 2;
  357. result.z = shape.halfDepth * 2;
  358. }
  359. public dispose() {
  360. this.world.clear();
  361. }
  362. }
  363. }