浏览代码

Merge pull request #8830 from RaananW/physicsFix

Fixing compound initialization when including rotation
David Catuhe 5 年之前
父节点
当前提交
f6e1bcdc51

+ 1 - 0
dist/preview release/what's new.md

@@ -295,6 +295,7 @@
 - Fixed bug in sphereBuilder where top and bottom segments added 6 indices per triangle instead of 3. ([aWeirdo](https://github.com/aWeirdo))
 - Fixed bug in sphereBuilder where top and bottom segments added 6 indices per triangle instead of 3. ([aWeirdo](https://github.com/aWeirdo))
 - Fixed issue with Babylon scene export of loaded glTF meshes.([Drigax]/(https://github.com/drigax))
 - Fixed issue with Babylon scene export of loaded glTF meshes.([Drigax]/(https://github.com/drigax))
 - Fixed an issue with text block wrap and unicode strings (not working in IE11) ([#8822](https://github.com/BabylonJS/Babylon.js/issues/8822)) ([RaananW](https://github.com/RaananW))
 - Fixed an issue with text block wrap and unicode strings (not working in IE11) ([#8822](https://github.com/BabylonJS/Babylon.js/issues/8822)) ([RaananW](https://github.com/RaananW))
+- Fixed an issue with compound initialization that has rotation ([#8744](https://github.com/BabylonJS/Babylon.js/issues/8744)) ([RaananW](https://github.com/RaananW))
 
 
 ## Breaking changes
 ## Breaking changes
 - `FollowCamera.target` was renamed to `FollowCamera.meshTarget` to not be in conflict with `TargetCamera.target` ([Deltakosh](https://github.com/deltakosh))
 - `FollowCamera.target` was renamed to `FollowCamera.meshTarget` to not be in conflict with `TargetCamera.target` ([Deltakosh](https://github.com/deltakosh))

+ 31 - 30
src/Physics/Plugins/cannonJSPlugin.ts

@@ -14,7 +14,6 @@ declare var CANNON: any;
 
 
 /** @hidden */
 /** @hidden */
 export class CannonJSPlugin implements IPhysicsEnginePlugin {
 export class CannonJSPlugin implements IPhysicsEnginePlugin {
-
     public world: any;
     public world: any;
     public name: string = "CannonJSPlugin";
     public name: string = "CannonJSPlugin";
     private _physicsMaterials = new Array();
     private _physicsMaterials = new Array();
@@ -108,7 +107,6 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
 
 
         //should a new body be created for this impostor?
         //should a new body be created for this impostor?
         if (impostor.isBodyInitRequired()) {
         if (impostor.isBodyInitRequired()) {
-
             var shape = this._createShape(impostor);
             var shape = this._createShape(impostor);
 
 
             //unregister events, if body is being changed
             //unregister events, if body is being changed
@@ -122,7 +120,7 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
 
 
             var bodyCreationObject = {
             var bodyCreationObject = {
                 mass: impostor.getParam("mass"),
                 mass: impostor.getParam("mass"),
-                material: material
+                material: material,
             };
             };
             // A simple extend, in case native options were used.
             // A simple extend, in case native options were used.
             var nativeOptions = impostor.getParam("nativeOptions");
             var nativeOptions = impostor.getParam("nativeOptions");
@@ -141,7 +139,7 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
             //try to keep the body moving in the right direction by taking old properties.
             //try to keep the body moving in the right direction by taking old properties.
             //Should be tested!
             //Should be tested!
             if (oldBody) {
             if (oldBody) {
-                ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function(param) {
+                ["force", "torque", "velocity", "angularVelocity"].forEach(function (param) {
                     const vec = oldBody[param];
                     const vec = oldBody[param];
                     impostor.physicsBody[param].set(vec.x, vec.y, vec.z);
                     impostor.physicsBody[param].set(vec.x, vec.y, vec.z);
                 });
                 });
@@ -158,7 +156,6 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
         let currentRotation: Nullable<Quaternion> = mainImpostor.object.rotationQuaternion;
         let currentRotation: Nullable<Quaternion> = mainImpostor.object.rotationQuaternion;
         if (meshChildren.length) {
         if (meshChildren.length) {
             var processMesh = (localPosition: Vector3, mesh: AbstractMesh) => {
             var processMesh = (localPosition: Vector3, mesh: AbstractMesh) => {
-
                 if (!currentRotation || !mesh.rotationQuaternion) {
                 if (!currentRotation || !mesh.rotationQuaternion) {
                     return;
                     return;
                 }
                 }
@@ -168,20 +165,22 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
                     var parent = childImpostor.parent;
                     var parent = childImpostor.parent;
                     if (parent !== mainImpostor) {
                     if (parent !== mainImpostor) {
                         var pPosition = mesh.position.clone();
                         var pPosition = mesh.position.clone();
-                        let localRotation = mesh.rotationQuaternion.multiply(Quaternion.Inverse(currentRotation));
+                        // let localRotation = mesh.rotationQuaternion.multiply(Quaternion.Inverse(currentRotation));
                         if (childImpostor.physicsBody) {
                         if (childImpostor.physicsBody) {
                             this.removePhysicsBody(childImpostor);
                             this.removePhysicsBody(childImpostor);
                             childImpostor.physicsBody = null;
                             childImpostor.physicsBody = null;
                         }
                         }
                         childImpostor.parent = mainImpostor;
                         childImpostor.parent = mainImpostor;
                         childImpostor.resetUpdateFlags();
                         childImpostor.resetUpdateFlags();
-                        mainImpostor.physicsBody.addShape(this._createShape(childImpostor), new this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));
+                        mainImpostor.physicsBody.addShape(this._createShape(childImpostor), new this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z) /*, new this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w)*/);
                         //Add the mass of the children.
                         //Add the mass of the children.
                         mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
                         mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
                     }
                     }
                 }
                 }
                 currentRotation.multiplyInPlace(mesh.rotationQuaternion);
                 currentRotation.multiplyInPlace(mesh.rotationQuaternion);
-                mesh.getChildMeshes(true).filter((m) => !!m.physicsImpostor).forEach(processMesh.bind(this, mesh.getAbsolutePosition()));
+                mesh.getChildMeshes(true)
+                    .filter((m) => !!m.physicsImpostor)
+                    .forEach(processMesh.bind(this, mesh.getAbsolutePosition()));
             };
             };
             meshChildren.filter((m) => !!m.physicsImpostor).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
             meshChildren.filter((m) => !!m.physicsImpostor).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
         }
         }
@@ -213,7 +212,7 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
             axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().set(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z) : null,
             axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().set(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z) : null,
             axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().set(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z) : null,
             axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().set(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z) : null,
             maxForce: jointData.nativeParams.maxForce,
             maxForce: jointData.nativeParams.maxForce,
-            collideConnected: !!jointData.collision
+            collideConnected: !!jointData.collision,
         };
         };
         switch (impostorJoint.joint.type) {
         switch (impostorJoint.joint.type) {
             case PhysicsJoint.HingeJoint:
             case PhysicsJoint.HingeJoint:
@@ -230,7 +229,7 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
                     stiffness: springData.stiffness,
                     stiffness: springData.stiffness,
                     damping: springData.damping,
                     damping: springData.damping,
                     localAnchorA: constraintData.pivotA,
                     localAnchorA: constraintData.pivotA,
-                    localAnchorB: constraintData.pivotB
+                    localAnchorB: constraintData.pivotB,
                 });
                 });
                 break;
                 break;
             case PhysicsJoint.LockJoint:
             case PhysicsJoint.LockJoint:
@@ -249,9 +248,11 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
         if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) {
         if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) {
             this.world.addConstraint(constraint);
             this.world.addConstraint(constraint);
         } else {
         } else {
-            (<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback = (<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback || function() {
-                constraint.applyForce();
-            };
+            (<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback =
+                (<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback ||
+                function () {
+                    constraint.applyForce();
+                };
             impostorJoint.mainImpostor.registerAfterPhysicsStep((<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback);
             impostorJoint.mainImpostor.registerAfterPhysicsStep((<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback);
         }
         }
     }
     }
@@ -262,7 +263,6 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
         } else {
         } else {
             impostorJoint.mainImpostor.unregisterAfterPhysicsStep((<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback);
             impostorJoint.mainImpostor.unregisterAfterPhysicsStep((<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback);
         }
         }
-
     }
     }
 
 
     private _addMaterial(name: string, friction: number, restitution: number) {
     private _addMaterial(name: string, friction: number, restitution: number) {
@@ -333,7 +333,9 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
                 // should transform the vertex data to world coordinates!!
                 // should transform the vertex data to world coordinates!!
                 var rawVerts = object.getVerticesData ? object.getVerticesData(VertexBuffer.PositionKind) : [];
                 var rawVerts = object.getVerticesData ? object.getVerticesData(VertexBuffer.PositionKind) : [];
                 var rawFaces = object.getIndices ? object.getIndices() : [];
                 var rawFaces = object.getIndices ? object.getIndices() : [];
-                if (!rawVerts) { return; }
+                if (!rawVerts) {
+                    return;
+                }
                 // get only scale! so the object could transform correctly.
                 // get only scale! so the object could transform correctly.
                 let oldPosition = object.position.clone();
                 let oldPosition = object.position.clone();
                 let oldRotation = object.rotation && object.rotation.clone();
                 let oldRotation = object.rotation && object.rotation.clone();
@@ -387,7 +389,7 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
     }
     }
 
 
     private _createHeightmap(object: IPhysicsEnabledObject, pointDepth?: number) {
     private _createHeightmap(object: IPhysicsEnabledObject, pointDepth?: number) {
-        var pos = <FloatArray>(object.getVerticesData(VertexBuffer.PositionKind));
+        var pos = <FloatArray>object.getVerticesData(VertexBuffer.PositionKind);
         let transform = object.computeWorldMatrix(true);
         let transform = object.computeWorldMatrix(true);
         // convert rawVerts to object space
         // convert rawVerts to object space
         var temp = new Array<number>();
         var temp = new Array<number>();
@@ -405,11 +407,11 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
         var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
         var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
         var minY = boundingInfo.boundingBox.extendSizeWorld.z;
         var minY = boundingInfo.boundingBox.extendSizeWorld.z;
 
 
-        var elementSize = dim * 2 / arraySize;
+        var elementSize = (dim * 2) / arraySize;
 
 
         for (var i = 0; i < pos.length; i = i + 3) {
         for (var i = 0; i < pos.length; i = i + 3) {
-            var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
-            var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
+            var x = Math.round(pos[i + 0] / elementSize + arraySize / 2);
+            var z = Math.round((pos[i + 1] / elementSize - arraySize / 2) * -1);
             var y = -pos[i + 2] + minY;
             var y = -pos[i + 2] + minY;
             if (!matrix[x]) {
             if (!matrix[x]) {
                 matrix[x] = [];
                 matrix[x] = [];
@@ -437,13 +439,12 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
                         newValue = matrix[x][(z + loc++) % arraySize];
                         newValue = matrix[x][(z + loc++) % arraySize];
                     }
                     }
                     matrix[x][z] = newValue;
                     matrix[x][z] = newValue;
-
                 }
                 }
             }
             }
         }
         }
 
 
         var shape = new this.BJSCANNON.Heightfield(matrix, {
         var shape = new this.BJSCANNON.Heightfield(matrix, {
-            elementSize: elementSize
+            elementSize: elementSize,
         });
         });
 
 
         //For future reference, needed for body transformation
         //For future reference, needed for body transformation
@@ -464,7 +465,9 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
         object.computeWorldMatrix && object.computeWorldMatrix(true);
         object.computeWorldMatrix && object.computeWorldMatrix(true);
         // The delta between the mesh position and the mesh bounding box center
         // The delta between the mesh position and the mesh bounding box center
         let bInfo = object.getBoundingInfo();
         let bInfo = object.getBoundingInfo();
-        if (!bInfo) { return; }
+        if (!bInfo) {
+            return;
+        }
         var center = impostor.getObjectCenter();
         var center = impostor.getObjectCenter();
         //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
         //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
         this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
         this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
@@ -502,8 +505,7 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
             if (oldPivot) {
             if (oldPivot) {
                 // create a copy the pivot Matrix as it is modified in place
                 // create a copy the pivot Matrix as it is modified in place
                 oldPivot = oldPivot.clone();
                 oldPivot = oldPivot.clone();
-            }
-            else {
+            } else {
                 oldPivot = Matrix.Identity();
                 oldPivot = Matrix.Identity();
             }
             }
 
 
@@ -653,16 +655,13 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
         result.z = shape.halfExtents.z * 2;
         result.z = shape.halfExtents.z * 2;
     }
     }
 
 
-    public dispose() {
-
-    }
+    public dispose() {}
 
 
     private _extendNamespace() {
     private _extendNamespace() {
-
         //this will force cannon to execute at least one step when using interpolation
         //this will force cannon to execute at least one step when using interpolation
         let step_tmp1 = new this.BJSCANNON.Vec3();
         let step_tmp1 = new this.BJSCANNON.Vec3();
         let Engine = this.BJSCANNON;
         let Engine = this.BJSCANNON;
-        this.BJSCANNON.World.prototype.step = function(dt: number, timeSinceLastCalled: number, maxSubSteps: number) {
+        this.BJSCANNON.World.prototype.step = function (dt: number, timeSinceLastCalled: number, maxSubSteps: number) {
             maxSubSteps = maxSubSteps || 10;
             maxSubSteps = maxSubSteps || 10;
             timeSinceLastCalled = timeSinceLastCalled || 0;
             timeSinceLastCalled = timeSinceLastCalled || 0;
             if (timeSinceLastCalled === 0) {
             if (timeSinceLastCalled === 0) {
@@ -730,4 +729,6 @@ export class CannonJSPlugin implements IPhysicsEnginePlugin {
     }
     }
 }
 }
 
 
-PhysicsEngine.DefaultPluginFactory = () => { return new CannonJSPlugin(); };
+PhysicsEngine.DefaultPluginFactory = () => {
+    return new CannonJSPlugin();
+};

+ 17 - 26
src/Physics/Plugins/oimoJSPlugin.ts

@@ -12,7 +12,6 @@ declare var OIMO: any;
 
 
 /** @hidden */
 /** @hidden */
 export class OimoJSPlugin implements IPhysicsEnginePlugin {
 export class OimoJSPlugin implements IPhysicsEnginePlugin {
-
     public world: any;
     public world: any;
     public name: string = "OimoJSPlugin";
     public name: string = "OimoJSPlugin";
     public BJSOIMO: any;
     public BJSOIMO: any;
@@ -22,7 +21,7 @@ export class OimoJSPlugin implements IPhysicsEnginePlugin {
     constructor(private _useDeltaForWorldStep: boolean = true, iterations?: number, oimoInjection = OIMO) {
     constructor(private _useDeltaForWorldStep: boolean = true, iterations?: number, oimoInjection = OIMO) {
         this.BJSOIMO = oimoInjection;
         this.BJSOIMO = oimoInjection;
         this.world = new this.BJSOIMO.World({
         this.world = new this.BJSOIMO.World({
-            iterations: iterations
+            iterations: iterations,
         });
         });
         this.world.clear();
         this.world.clear();
         this._raycastResult = new PhysicsRaycastResult();
         this._raycastResult = new PhysicsRaycastResult();
@@ -43,8 +42,7 @@ export class OimoJSPlugin implements IPhysicsEnginePlugin {
     private _tmpImpostorsArray: Array<PhysicsImpostor> = [];
     private _tmpImpostorsArray: Array<PhysicsImpostor> = [];
 
 
     public executeStep(delta: number, impostors: Array<PhysicsImpostor>) {
     public executeStep(delta: number, impostors: Array<PhysicsImpostor>) {
-
-        impostors.forEach(function(impostor) {
+        impostors.forEach(function (impostor) {
             impostor.beforeStep();
             impostor.beforeStep();
         });
         });
 
 
@@ -78,7 +76,6 @@ export class OimoJSPlugin implements IPhysicsEnginePlugin {
             collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
             collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
             contact = contact.next;
             contact = contact.next;
         }
         }
-
     }
     }
 
 
     public applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
     public applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
@@ -116,13 +113,15 @@ export class OimoJSPlugin implements IPhysicsEnginePlugin {
                 friction: impostor.getParam("friction"),
                 friction: impostor.getParam("friction"),
                 restitution: impostor.getParam("restitution"),
                 restitution: impostor.getParam("restitution"),
                 //Supporting older versions of Oimo
                 //Supporting older versions of Oimo
-                world: this.world
+                world: this.world,
             };
             };
 
 
             var impostors = [impostor];
             var impostors = [impostor];
             let addToArray = (parent: IPhysicsEnabledObject) => {
             let addToArray = (parent: IPhysicsEnabledObject) => {
-                if (!parent.getChildMeshes) { return; }
-                parent.getChildMeshes().forEach(function(m) {
+                if (!parent.getChildMeshes) {
+                    return;
+                }
+                parent.getChildMeshes().forEach(function (m) {
                     if (m.physicsImpostor) {
                     if (m.physicsImpostor) {
                         impostors.push(m.physicsImpostor);
                         impostors.push(m.physicsImpostor);
                         //m.physicsImpostor._init();
                         //m.physicsImpostor._init();
@@ -135,7 +134,7 @@ export class OimoJSPlugin implements IPhysicsEnginePlugin {
                 return Math.max(value, PhysicsEngine.Epsilon);
                 return Math.max(value, PhysicsEngine.Epsilon);
             };
             };
 
 
-            let globalQuaternion: Quaternion = new Quaternion();
+            const globalQuaternion: Quaternion = new Quaternion();
 
 
             impostors.forEach((i) => {
             impostors.forEach((i) => {
                 if (!i.object.rotationQuaternion) {
                 if (!i.object.rotationQuaternion) {
@@ -143,12 +142,12 @@ export class OimoJSPlugin implements IPhysicsEnginePlugin {
                 }
                 }
                 //get the correct bounding box
                 //get the correct bounding box
                 var oldQuaternion = i.object.rotationQuaternion;
                 var oldQuaternion = i.object.rotationQuaternion;
-                globalQuaternion = oldQuaternion.clone();
+                globalQuaternion.copyFrom(oldQuaternion);
 
 
                 i.object.rotationQuaternion.set(0, 0, 0, 1);
                 i.object.rotationQuaternion.set(0, 0, 0, 1);
                 i.object.computeWorldMatrix(true);
                 i.object.computeWorldMatrix(true);
 
 
-                var rot = oldQuaternion.toEulerAngles();
+                var rot = globalQuaternion.toEulerAngles();
                 var extendSize = i.getObjectExtendSize();
                 var extendSize = i.getObjectExtendSize();
 
 
                 const radToDeg = 57.295779513082320876;
                 const radToDeg = 57.295779513082320876;
@@ -174,9 +173,7 @@ export class OimoJSPlugin implements IPhysicsEnginePlugin {
 
 
                     // bodyConfig.pos.push(0, 0, 0);
                     // bodyConfig.pos.push(0, 0, 0);
 
 
-                    bodyConfig.rotShape.push(rot.x * radToDeg);
-                    bodyConfig.rotShape.push(rot.y * radToDeg);
-                    bodyConfig.rotShape.push(rot.z * radToDeg);
+                    bodyConfig.rotShape.push(rot.x * radToDeg, rot.y * radToDeg, rot.z * radToDeg);
                 }
                 }
 
 
                 i.object.rotationQuaternion.copyFrom(globalQuaternion);
                 i.object.rotationQuaternion.copyFrom(globalQuaternion);
@@ -190,12 +187,9 @@ export class OimoJSPlugin implements IPhysicsEnginePlugin {
                         var radiusY = extendSize.y;
                         var radiusY = extendSize.y;
                         var radiusZ = extendSize.z;
                         var radiusZ = extendSize.z;
 
 
-                        var size = Math.max(
-                            checkWithEpsilon(radiusX),
-                            checkWithEpsilon(radiusY),
-                            checkWithEpsilon(radiusZ)) / 2;
+                        var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
 
 
-                        bodyConfig.type.push('sphere');
+                        bodyConfig.type.push("sphere");
                         //due to the way oimo works with compounds, add 3 times
                         //due to the way oimo works with compounds, add 3 times
                         bodyConfig.size.push(size);
                         bodyConfig.size.push(size);
                         bodyConfig.size.push(size);
                         bodyConfig.size.push(size);
@@ -205,7 +199,7 @@ export class OimoJSPlugin implements IPhysicsEnginePlugin {
                     case PhysicsImpostor.CylinderImpostor:
                     case PhysicsImpostor.CylinderImpostor:
                         var sizeX = checkWithEpsilon(extendSize.x) / 2;
                         var sizeX = checkWithEpsilon(extendSize.x) / 2;
                         var sizeY = checkWithEpsilon(extendSize.y);
                         var sizeY = checkWithEpsilon(extendSize.y);
-                        bodyConfig.type.push('cylinder');
+                        bodyConfig.type.push("cylinder");
                         bodyConfig.size.push(sizeX);
                         bodyConfig.size.push(sizeX);
                         bodyConfig.size.push(sizeY);
                         bodyConfig.size.push(sizeY);
                         //due to the way oimo works with compounds, add one more value.
                         //due to the way oimo works with compounds, add one more value.
@@ -219,7 +213,7 @@ export class OimoJSPlugin implements IPhysicsEnginePlugin {
                         var sizeY = checkWithEpsilon(extendSize.y);
                         var sizeY = checkWithEpsilon(extendSize.y);
                         var sizeZ = checkWithEpsilon(extendSize.z);
                         var sizeZ = checkWithEpsilon(extendSize.z);
 
 
-                        bodyConfig.type.push('box');
+                        bodyConfig.type.push("box");
                         //if (i === impostor) {
                         //if (i === impostor) {
                         bodyConfig.size.push(sizeX);
                         bodyConfig.size.push(sizeX);
                         bodyConfig.size.push(sizeY);
                         bodyConfig.size.push(sizeY);
@@ -236,9 +230,8 @@ export class OimoJSPlugin implements IPhysicsEnginePlugin {
             impostor.physicsBody = this.world.add(bodyConfig);
             impostor.physicsBody = this.world.add(bodyConfig);
             // set the quaternion, ignoring the previously defined (euler) rotation
             // set the quaternion, ignoring the previously defined (euler) rotation
             impostor.physicsBody.resetQuaternion(globalQuaternion);
             impostor.physicsBody.resetQuaternion(globalQuaternion);
-            // update with delta 0, so the body will reveive the new rotation.
+            // update with delta 0, so the body will receive the new rotation.
             impostor.physicsBody.updatePosition(0);
             impostor.physicsBody.updatePosition(0);
-
         } else {
         } else {
             this._tmpPositionVector.copyFromFloats(0, 0, 0);
             this._tmpPositionVector.copyFromFloats(0, 0, 0);
         }
         }
@@ -282,8 +275,7 @@ export class OimoJSPlugin implements IPhysicsEnginePlugin {
             spring: options.spring,
             spring: options.spring,
 
 
             //supporting older version of Oimo
             //supporting older version of Oimo
-            world: this.world
-
+            world: this.world,
         };
         };
         switch (impostorJoint.joint.type) {
         switch (impostorJoint.joint.type) {
             case PhysicsJoint.BallAndSocketJoint:
             case PhysicsJoint.BallAndSocketJoint:
@@ -326,7 +318,6 @@ export class OimoJSPlugin implements IPhysicsEnginePlugin {
         } catch (e) {
         } catch (e) {
             Logger.Warn(e);
             Logger.Warn(e);
         }
         }
-
     }
     }
 
 
     public isSupported(): boolean {
     public isSupported(): boolean {

+ 49 - 45
src/Physics/physicsImpostor.ts

@@ -10,7 +10,7 @@ import { Bone } from "../Bones/bone";
 import { BoundingInfo } from "../Culling/boundingInfo";
 import { BoundingInfo } from "../Culling/boundingInfo";
 import { IPhysicsEngine } from "./IPhysicsEngine";
 import { IPhysicsEngine } from "./IPhysicsEngine";
 import { PhysicsJoint, PhysicsJointData } from "./physicsJoint";
 import { PhysicsJoint, PhysicsJointData } from "./physicsJoint";
-import { Space } from '../Maths/math.axis';
+import { Space } from "../Maths/math.axis";
 
 
 /**
 /**
  * The interface for the physics imposter parameters
  * The interface for the physics imposter parameters
@@ -183,12 +183,17 @@ export interface IPhysicsEnabledObject {
     getClassName(): string;
     getClassName(): string;
 }
 }
 
 
-Mesh._PhysicsImpostorParser = function(scene: Scene, physicObject: IPhysicsEnabledObject, jsonObject: any): PhysicsImpostor {
-    return new PhysicsImpostor(physicObject, jsonObject.physicsImpostor, {
-        mass: jsonObject.physicsMass,
-        friction: jsonObject.physicsFriction,
-        restitution: jsonObject.physicsRestitution
-    }, scene);
+Mesh._PhysicsImpostorParser = function (scene: Scene, physicObject: IPhysicsEnabledObject, jsonObject: any): PhysicsImpostor {
+    return new PhysicsImpostor(
+        physicObject,
+        jsonObject.physicsImpostor,
+        {
+            mass: jsonObject.physicsMass,
+            friction: jsonObject.physicsFriction,
+            restitution: jsonObject.physicsRestitution,
+        },
+        scene
+    );
 };
 };
 
 
 /**
 /**
@@ -196,7 +201,6 @@ Mesh._PhysicsImpostorParser = function(scene: Scene, physicObject: IPhysicsEnabl
  * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  */
  */
 export class PhysicsImpostor {
 export class PhysicsImpostor {
-
     /**
     /**
      * The default object size of the imposter
      * The default object size of the imposter
      */
      */
@@ -218,7 +222,7 @@ export class PhysicsImpostor {
     private _onBeforePhysicsStepCallbacks = new Array<(impostor: PhysicsImpostor) => void>();
     private _onBeforePhysicsStepCallbacks = new Array<(impostor: PhysicsImpostor) => void>();
     private _onAfterPhysicsStepCallbacks = new Array<(impostor: PhysicsImpostor) => void>();
     private _onAfterPhysicsStepCallbacks = new Array<(impostor: PhysicsImpostor) => void>();
     /** @hidden */
     /** @hidden */
-    public _onPhysicsCollideCallbacks: Array<{ callback: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor) => void, otherImpostors: Array<PhysicsImpostor> }> = [];
+    public _onPhysicsCollideCallbacks: Array<{ callback: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor) => void; otherImpostors: Array<PhysicsImpostor> }> = [];
 
 
     private _deltaPosition: Vector3 = Vector3.Zero();
     private _deltaPosition: Vector3 = Vector3.Zero();
     private _deltaRotation: Quaternion;
     private _deltaRotation: Quaternion;
@@ -416,8 +420,8 @@ export class PhysicsImpostor {
     public segments: number = 0;
     public segments: number = 0;
 
 
     private _joints: Array<{
     private _joints: Array<{
-        joint: PhysicsJoint,
-        otherImpostor: PhysicsImpostor
+        joint: PhysicsJoint;
+        otherImpostor: PhysicsImpostor;
     }>;
     }>;
 
 
     /**
     /**
@@ -435,8 +439,10 @@ export class PhysicsImpostor {
         /**
         /**
          * The type of the physics imposter
          * The type of the physics imposter
          */
          */
-        public type: number, private _options: PhysicsImpostorParameters = { mass: 0 }, private _scene?: Scene) {
-
+        public type: number,
+        private _options: PhysicsImpostorParameters = { mass: 0 },
+        private _scene?: Scene
+    ) {
         //sanity check!
         //sanity check!
         if (!this.object) {
         if (!this.object) {
             Logger.Error("No object was provided. A physics object is obligatory");
             Logger.Error("No object was provided. A physics object is obligatory");
@@ -470,24 +476,23 @@ export class PhysicsImpostor {
                 } else {
                 } else {
                     this.object.rotationQuaternion = new Quaternion();
                     this.object.rotationQuaternion = new Quaternion();
                 }
                 }
-
             }
             }
             //default options params
             //default options params
-            this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
-            this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
-            this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
+            this._options.mass = _options.mass === void 0 ? 0 : _options.mass;
+            this._options.friction = _options.friction === void 0 ? 0.2 : _options.friction;
+            this._options.restitution = _options.restitution === void 0 ? 0.2 : _options.restitution;
             if (this.soft) {
             if (this.soft) {
                 //softbody mass must be above 0;
                 //softbody mass must be above 0;
                 this._options.mass = this._options.mass > 0 ? this._options.mass : 1;
                 this._options.mass = this._options.mass > 0 ? this._options.mass : 1;
-                this._options.pressure = (_options.pressure === void 0) ? 200 : _options.pressure;
-                this._options.stiffness = (_options.stiffness === void 0) ? 1 : _options.stiffness;
-                this._options.velocityIterations = (_options.velocityIterations === void 0) ? 20 : _options.velocityIterations;
-                this._options.positionIterations = (_options.positionIterations === void 0) ? 20 : _options.positionIterations;
-                this._options.fixedPoints = (_options.fixedPoints === void 0) ? 0 : _options.fixedPoints;
-                this._options.margin = (_options.margin === void 0) ? 0 : _options.margin;
-                this._options.damping = (_options.damping === void 0) ? 0 : _options.damping;
-                this._options.path = (_options.path === void 0) ? null : _options.path;
-                this._options.shape = (_options.shape === void 0) ? null : _options.shape;
+                this._options.pressure = _options.pressure === void 0 ? 200 : _options.pressure;
+                this._options.stiffness = _options.stiffness === void 0 ? 1 : _options.stiffness;
+                this._options.velocityIterations = _options.velocityIterations === void 0 ? 20 : _options.velocityIterations;
+                this._options.positionIterations = _options.positionIterations === void 0 ? 20 : _options.positionIterations;
+                this._options.fixedPoints = _options.fixedPoints === void 0 ? 0 : _options.fixedPoints;
+                this._options.margin = _options.margin === void 0 ? 0 : _options.margin;
+                this._options.damping = _options.damping === void 0 ? 0 : _options.damping;
+                this._options.path = _options.path === void 0 ? null : _options.path;
+                this._options.shape = _options.shape === void 0 ? null : _options.shape;
             }
             }
             this._joints = [];
             this._joints = [];
             //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
             //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
@@ -562,7 +567,7 @@ export class PhysicsImpostor {
      * Gets the body that holds this impostor. Either its own, or its parent.
      * Gets the body that holds this impostor. Either its own, or its parent.
      */
      */
     public get physicsBody(): any {
     public get physicsBody(): any {
-        return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
+        return this._parent && !this._options.ignoreParent ? this._parent.physicsBody : this._physicsBody;
     }
     }
 
 
     /**
     /**
@@ -609,9 +614,9 @@ export class PhysicsImpostor {
             this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
             this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
             //calculate the world matrix with no rotation
             //calculate the world matrix with no rotation
             this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
             this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
-            let boundingInfo = this.object.getBoundingInfo();
-            let size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
-
+            const boundingInfo = this.object.getBoundingInfo();
+            const size = boundingInfo.boundingBox.extendSize.scale(2).multiplyInPlace(this.object.scaling);
+            console.log(size, q);
             //bring back the rotation
             //bring back the rotation
             this.object.rotationQuaternion = q;
             this.object.rotationQuaternion = q;
             //calculate the world matrix with the new rotation
             //calculate the world matrix with the new rotation
@@ -846,7 +851,7 @@ export class PhysicsImpostor {
         this._onBeforePhysicsStepCallbacks.forEach((func) => {
         this._onBeforePhysicsStepCallbacks.forEach((func) => {
             func(this);
             func(this);
         });
         });
-    }
+    };
 
 
     /**
     /**
      * this function is executed by the physics engine
      * this function is executed by the physics engine
@@ -871,7 +876,7 @@ export class PhysicsImpostor {
         this.object.setAbsolutePosition(this.object.position);
         this.object.setAbsolutePosition(this.object.position);
         this._deltaRotation && this.object.rotationQuaternion && this.object.rotationQuaternion.multiplyToRef(this._deltaRotation, this.object.rotationQuaternion);
         this._deltaRotation && this.object.rotationQuaternion && this.object.rotationQuaternion.multiplyToRef(this._deltaRotation, this.object.rotationQuaternion);
         this.object.translate(this._deltaPosition, 1);
         this.object.translate(this._deltaPosition, 1);
-    }
+    };
 
 
     /**
     /**
      * Legacy collision detection event support
      * Legacy collision detection event support
@@ -888,7 +893,6 @@ export class PhysicsImpostor {
 
 
         if (!this._physicsEngine) {
         if (!this._physicsEngine) {
             return;
             return;
-
         }
         }
         var otherImpostor = this._physicsEngine.getImpostorWithPhysicsBody(e.body);
         var otherImpostor = this._physicsEngine.getImpostorWithPhysicsBody(e.body);
         if (otherImpostor) {
         if (otherImpostor) {
@@ -896,13 +900,15 @@ export class PhysicsImpostor {
             if (this.onCollideEvent) {
             if (this.onCollideEvent) {
                 this.onCollideEvent(this, otherImpostor);
                 this.onCollideEvent(this, otherImpostor);
             }
             }
-            this._onPhysicsCollideCallbacks.filter((obj) => {
-                return obj.otherImpostors.indexOf((<PhysicsImpostor>otherImpostor)) !== -1;
-            }).forEach((obj) => {
-                obj.callback(this, <PhysicsImpostor>otherImpostor);
-            });
+            this._onPhysicsCollideCallbacks
+                .filter((obj) => {
+                    return obj.otherImpostors.indexOf(<PhysicsImpostor>otherImpostor) !== -1;
+                })
+                .forEach((obj) => {
+                    obj.callback(this, <PhysicsImpostor>otherImpostor);
+                });
         }
         }
-    }
+    };
 
 
     /**
     /**
      * Apply a force
      * Apply a force
@@ -954,7 +960,7 @@ export class PhysicsImpostor {
     public addJoint(otherImpostor: PhysicsImpostor, joint: PhysicsJoint): PhysicsImpostor {
     public addJoint(otherImpostor: PhysicsImpostor, joint: PhysicsJoint): PhysicsImpostor {
         this._joints.push({
         this._joints.push({
             otherImpostor: otherImpostor,
             otherImpostor: otherImpostor,
-            joint: joint
+            joint: joint,
         });
         });
 
 
         if (this._physicsEngine) {
         if (this._physicsEngine) {
@@ -1039,7 +1045,9 @@ export class PhysicsImpostor {
      * @returns A nullable physics imposter
      * @returns A nullable physics imposter
      */
      */
     public clone(newObject: IPhysicsEnabledObject): Nullable<PhysicsImpostor> {
     public clone(newObject: IPhysicsEnabledObject): Nullable<PhysicsImpostor> {
-        if (!newObject) { return null; }
+        if (!newObject) {
+            return null;
+        }
         return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
         return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
     }
     }
 
 
@@ -1125,7 +1133,6 @@ export class PhysicsImpostor {
      * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
      * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
      */
      */
     public syncBoneWithImpostor(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion) {
     public syncBoneWithImpostor(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion) {
-
         var tempVec = PhysicsImpostor._tmpVecs[0];
         var tempVec = PhysicsImpostor._tmpVecs[0];
         var mesh = <AbstractMesh>this.object;
         var mesh = <AbstractMesh>this.object;
 
 
@@ -1168,7 +1175,6 @@ export class PhysicsImpostor {
             boneMesh.position.y -= tempVec.y;
             boneMesh.position.y -= tempVec.y;
             boneMesh.position.z -= tempVec.z;
             boneMesh.position.z -= tempVec.z;
         }
         }
-
     }
     }
 
 
     /**
     /**
@@ -1181,7 +1187,6 @@ export class PhysicsImpostor {
      * @param boneAxis Optional vector3 axis the bone is aligned with
      * @param boneAxis Optional vector3 axis the bone is aligned with
      */
      */
     public syncImpostorWithBone(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion, boneAxis?: Vector3) {
     public syncImpostorWithBone(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion, boneAxis?: Vector3) {
-
         var mesh = <AbstractMesh>this.object;
         var mesh = <AbstractMesh>this.object;
 
 
         if (mesh.rotationQuaternion) {
         if (mesh.rotationQuaternion) {
@@ -1218,7 +1223,6 @@ export class PhysicsImpostor {
         }
         }
 
 
         mesh.setAbsolutePosition(pos);
         mesh.setAbsolutePosition(pos);
-
     }
     }
 
 
     //Impostor types
     //Impostor types