Browse Source

BoundingInfo can be locked and updated

David Catuhe 9 years ago
parent
commit
80185c7387
100 changed files with 64280 additions and 64333 deletions
  1. 17 17
      dist/preview release/babylon.core.js
  2. 23 23
      dist/preview release/babylon.js
  3. 37668 37905
      dist/preview release/babylon.max.js
  4. 23 23
      dist/preview release/babylon.noworker.js
  5. 1 0
      dist/preview release/what's new.md
  6. 73 72
      src/Actions/babylon.action.js
  7. 465 464
      src/Actions/babylon.actionManager.js
  8. 118 117
      src/Actions/babylon.condition.js
  9. 205 204
      src/Actions/babylon.directActions.js
  10. 66 65
      src/Actions/babylon.interpolateValueAction.js
  11. 115 114
      src/Animations/babylon.animatable.js
  12. 583 582
      src/Animations/babylon.animation.js
  13. 250 249
      src/Animations/babylon.easing.js
  14. 112 111
      src/Audio/babylon.analyser.js
  15. 107 79
      src/Audio/babylon.audioEngine.js
  16. 31 0
      src/Audio/babylon.audioEngine.ts
  17. 554 546
      src/Audio/babylon.sound.js
  18. 21 12
      src/Audio/babylon.sound.ts
  19. 102 101
      src/Audio/babylon.soundtrack.js
  20. 128 127
      src/Bones/babylon.bone.js
  21. 266 265
      src/Bones/babylon.skeleton.js
  22. 48 47
      src/Cameras/VR/babylon.vrDeviceOrientationCamera.js
  23. 74 73
      src/Cameras/VR/babylon.webVRCamera.js
  24. 577 576
      src/Cameras/babylon.arcRotateCamera.js
  25. 668 667
      src/Cameras/babylon.camera.js
  26. 1 1
      src/Cameras/babylon.camera.ts
  27. 72 71
      src/Cameras/babylon.deviceOrientationCamera.js
  28. 99 98
      src/Cameras/babylon.followCamera.js
  29. 236 235
      src/Cameras/babylon.freeCamera.js
  30. 52 51
      src/Cameras/babylon.gamepadCamera.js
  31. 64 63
      src/Cameras/babylon.stereoscopicCameras.js
  32. 258 257
      src/Cameras/babylon.targetCamera.js
  33. 120 119
      src/Cameras/babylon.touchCamera.js
  34. 1 1
      src/Cameras/babylon.touchCamera.ts
  35. 52 51
      src/Cameras/babylon.virtualJoysticksCamera.js
  36. 273 272
      src/Collisions/babylon.collider.js
  37. 274 273
      src/Collisions/babylon.collisionCoordinator.js
  38. 244 243
      src/Collisions/babylon.collisionWorker.js
  39. 77 76
      src/Collisions/babylon.pickingInfo.js
  40. 89 88
      src/Culling/Octrees/babylon.octree.js
  41. 123 122
      src/Culling/Octrees/babylon.octreeBlock.js
  42. 140 139
      src/Culling/babylon.boundingBox.js
  43. 106 105
      src/Culling/babylon.boundingInfo.js
  44. 14 1
      src/Culling/babylon.boundingInfo.ts
  45. 50 49
      src/Culling/babylon.boundingSphere.js
  46. 630 624
      src/Debug/babylon.debugLayer.js
  47. 11 6
      src/Debug/babylon.debugLayer.ts
  48. 83 82
      src/Layer/babylon.layer.js
  49. 24 23
      src/LensFlare/babylon.lensFlare.js
  50. 209 208
      src/LensFlare/babylon.lensFlareSystem.js
  51. 406 405
      src/Lights/Shadows/babylon.shadowGenerator.js
  52. 116 115
      src/Lights/babylon.directionalLight.js
  53. 44 43
      src/Lights/babylon.hemisphericLight.js
  54. 144 143
      src/Lights/babylon.light.js
  55. 82 81
      src/Lights/babylon.pointLight.js
  56. 87 86
      src/Lights/babylon.spotLight.js
  57. 403 402
      src/Loading/Plugins/babylon.babylonFileLoader.js
  58. 177 176
      src/Loading/babylon.sceneLoader.js
  59. 125 124
      src/Materials/Textures/Procedurals/babylon.customProceduralTexture.js
  60. 250 249
      src/Materials/Textures/Procedurals/babylon.proceduralTexture.js
  61. 139 138
      src/Materials/Textures/babylon.baseTexture.js
  62. 87 86
      src/Materials/Textures/babylon.cubeTexture.js
  63. 94 93
      src/Materials/Textures/babylon.dynamicTexture.js
  64. 55 54
      src/Materials/Textures/babylon.mirrorTexture.js
  65. 58 57
      src/Materials/Textures/babylon.rawTexture.js
  66. 255 254
      src/Materials/Textures/babylon.renderTargetTexture.js
  67. 273 272
      src/Materials/Textures/babylon.texture.js
  68. 59 58
      src/Materials/Textures/babylon.videoTexture.js
  69. 398 397
      src/Materials/babylon.effect.js
  70. 291 290
      src/Materials/babylon.material.js
  71. 69 68
      src/Materials/babylon.multiMaterial.js
  72. 343 342
      src/Materials/babylon.shaderMaterial.js
  73. 1024 1023
      src/Materials/babylon.standardMaterial.js
  74. 270 269
      src/Math/babylon.math.SIMD.js
  75. 2968 2967
      src/Math/babylon.math.js
  76. 925 924
      src/Mesh/babylon.abstractMesh.js
  77. 1 1
      src/Mesh/babylon.abstractMesh.ts
  78. 514 513
      src/Mesh/babylon.csg.js
  79. 1014 1013
      src/Mesh/babylon.geometry.js
  80. 170 169
      src/Mesh/babylon.groundMesh.js
  81. 157 156
      src/Mesh/babylon.instancedMesh.js
  82. 72 71
      src/Mesh/babylon.linesMesh.js
  83. 1717 1716
      src/Mesh/babylon.mesh.js
  84. 1819 1818
      src/Mesh/babylon.mesh.vertexData.js
  85. 706 705
      src/Mesh/babylon.meshBuilder.js
  86. 15 14
      src/Mesh/babylon.meshLODLevel.js
  87. 659 658
      src/Mesh/babylon.meshSimplification.js
  88. 246 245
      src/Mesh/babylon.polygonMesh.js
  89. 163 162
      src/Mesh/babylon.subMesh.js
  90. 1 1
      src/Mesh/babylon.subMesh.ts
  91. 211 210
      src/Mesh/babylon.vertexBuffer.js
  92. 30 29
      src/Particles/babylon.particle.js
  93. 413 412
      src/Particles/babylon.particleSystem.js
  94. 33 32
      src/Particles/babylon.solidParticle.js
  95. 660 659
      src/Particles/babylon.solidParticleSystem.js
  96. 382 381
      src/Physics/Plugins/babylon.cannonJSPlugin.js
  97. 332 331
      src/Physics/Plugins/babylon.oimoJSPlugin.js
  98. 73 72
      src/Physics/babylon.physicsEngine.js
  99. 153 152
      src/PostProcess/RenderPipeline/babylon.postProcessRenderEffect.js
  100. 0 0
      src/PostProcess/RenderPipeline/babylon.postProcessRenderPass.js

File diff suppressed because it is too large
+ 17 - 17
dist/preview release/babylon.core.js


File diff suppressed because it is too large
+ 23 - 23
dist/preview release/babylon.js


File diff suppressed because it is too large
+ 37668 - 37905
dist/preview release/babylon.max.js


File diff suppressed because it is too large
+ 23 - 23
dist/preview release/babylon.noworker.js


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

@@ -22,6 +22,7 @@
       - Expanded AnimationRanges for Nodes (Mesh, Lights, & Cameras) ([Palmer-JC](https://github.com/Palmer-JC))
       - Support for added to Blender Exporter ([Palmer-JC](https://github.com/Palmer-JC))
   - **Updates**
+    - Bounding info can be locked and updated (`bb.isLocked` and `bb.update()`) ([deltakosh](https://github.com/deltakosh))
     - 2D layers now have a scale and offset properties ([deltakosh](https://github.com/deltakosh))
     - TouchCamera can now fallback to regular mouse/keyboard controls ([deltakosh](https://github.com/deltakosh))
     - Added ability to skip current prepared Action to next active Action (chained by Action.then(Action)) ([vouskprod](http://www.github.com/vousk)) 

+ 73 - 72
src/Actions/babylon.action.js

@@ -1,72 +1,73 @@
-var BABYLON;
-(function (BABYLON) {
-    var Action = (function () {
-        function Action(triggerOptions, condition) {
-            this.triggerOptions = triggerOptions;
-            if (triggerOptions.parameter) {
-                this.trigger = triggerOptions.trigger;
-                this._triggerParameter = triggerOptions.parameter;
-            }
-            else {
-                this.trigger = triggerOptions;
-            }
-            this._nextActiveAction = this;
-            this._condition = condition;
-        }
-        // Methods
-        Action.prototype._prepare = function () {
-        };
-        Action.prototype.getTriggerParameter = function () {
-            return this._triggerParameter;
-        };
-        Action.prototype._executeCurrent = function (evt) {
-            if (this._nextActiveAction._condition) {
-                var condition = this._nextActiveAction._condition;
-                var currentRenderId = this._actionManager.getScene().getRenderId();
-                // We cache the current evaluation for the current frame
-                if (condition._evaluationId === currentRenderId) {
-                    if (!condition._currentResult) {
-                        return;
-                    }
-                }
-                else {
-                    condition._evaluationId = currentRenderId;
-                    if (!condition.isValid()) {
-                        condition._currentResult = false;
-                        return;
-                    }
-                    condition._currentResult = true;
-                }
-            }
-            this._nextActiveAction.execute(evt);
-            this.skipToNextActiveAction();
-        };
-        Action.prototype.execute = function (evt) {
-        };
-        Action.prototype.skipToNextActiveAction = function () {
-            if (this._nextActiveAction._child) {
-                if (!this._nextActiveAction._child._actionManager) {
-                    this._nextActiveAction._child._actionManager = this._actionManager;
-                }
-                this._nextActiveAction = this._nextActiveAction._child;
-            }
-            else {
-                this._nextActiveAction = this;
-            }
-        };
-        Action.prototype.then = function (action) {
-            this._child = action;
-            action._actionManager = this._actionManager;
-            action._prepare();
-            return action;
-        };
-        Action.prototype._getProperty = function (propertyPath) {
-            return this._actionManager._getProperty(propertyPath);
-        };
-        Action.prototype._getEffectiveTarget = function (target, propertyPath) {
-            return this._actionManager._getEffectiveTarget(target, propertyPath);
-        };
-        return Action;
-    })();
-    BABYLON.Action = Action;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var Action = (function () {
+        function Action(triggerOptions, condition) {
+            this.triggerOptions = triggerOptions;
+            if (triggerOptions.parameter) {
+                this.trigger = triggerOptions.trigger;
+                this._triggerParameter = triggerOptions.parameter;
+            }
+            else {
+                this.trigger = triggerOptions;
+            }
+            this._nextActiveAction = this;
+            this._condition = condition;
+        }
+        // Methods
+        Action.prototype._prepare = function () {
+        };
+        Action.prototype.getTriggerParameter = function () {
+            return this._triggerParameter;
+        };
+        Action.prototype._executeCurrent = function (evt) {
+            if (this._nextActiveAction._condition) {
+                var condition = this._nextActiveAction._condition;
+                var currentRenderId = this._actionManager.getScene().getRenderId();
+                // We cache the current evaluation for the current frame
+                if (condition._evaluationId === currentRenderId) {
+                    if (!condition._currentResult) {
+                        return;
+                    }
+                }
+                else {
+                    condition._evaluationId = currentRenderId;
+                    if (!condition.isValid()) {
+                        condition._currentResult = false;
+                        return;
+                    }
+                    condition._currentResult = true;
+                }
+            }
+            this._nextActiveAction.execute(evt);
+            this.skipToNextActiveAction();
+        };
+        Action.prototype.execute = function (evt) {
+        };
+        Action.prototype.skipToNextActiveAction = function () {
+            if (this._nextActiveAction._child) {
+                if (!this._nextActiveAction._child._actionManager) {
+                    this._nextActiveAction._child._actionManager = this._actionManager;
+                }
+                this._nextActiveAction = this._nextActiveAction._child;
+            }
+            else {
+                this._nextActiveAction = this;
+            }
+        };
+        Action.prototype.then = function (action) {
+            this._child = action;
+            action._actionManager = this._actionManager;
+            action._prepare();
+            return action;
+        };
+        Action.prototype._getProperty = function (propertyPath) {
+            return this._actionManager._getProperty(propertyPath);
+        };
+        Action.prototype._getEffectiveTarget = function (target, propertyPath) {
+            return this._actionManager._getEffectiveTarget(target, propertyPath);
+        };
+        return Action;
+    })();
+    BABYLON.Action = Action;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.action.js.map

+ 465 - 464
src/Actions/babylon.actionManager.js

@@ -1,464 +1,465 @@
-var BABYLON;
-(function (BABYLON) {
-    /**
-     * ActionEvent is the event beint sent when an action is triggered.
-     */
-    var ActionEvent = (function () {
-        /**
-         * @constructor
-         * @param source The mesh or sprite that triggered the action.
-         * @param pointerX The X mouse cursor position at the time of the event
-         * @param pointerY The Y mouse cursor position at the time of the event
-         * @param meshUnderPointer The mesh that is currently pointed at (can be null)
-         * @param sourceEvent the original (browser) event that triggered the ActionEvent
-         */
-        function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
-            this.source = source;
-            this.pointerX = pointerX;
-            this.pointerY = pointerY;
-            this.meshUnderPointer = meshUnderPointer;
-            this.sourceEvent = sourceEvent;
-            this.additionalData = additionalData;
-        }
-        /**
-         * Helper function to auto-create an ActionEvent from a source mesh.
-         * @param source The source mesh that triggered the event
-         * @param evt {Event} The original (browser) event
-         */
-        ActionEvent.CreateNew = function (source, evt, additionalData) {
-            var scene = source.getScene();
-            return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
-        };
-        /**
-         * Helper function to auto-create an ActionEvent from a source mesh.
-         * @param source The source sprite that triggered the event
-         * @param scene Scene associated with the sprite
-         * @param evt {Event} The original (browser) event
-         */
-        ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
-            return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
-        };
-        /**
-         * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
-         * @param scene the scene where the event occurred
-         * @param evt {Event} The original (browser) event
-         */
-        ActionEvent.CreateNewFromScene = function (scene, evt) {
-            return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
-        };
-        return ActionEvent;
-    })();
-    BABYLON.ActionEvent = ActionEvent;
-    /**
-     * Action Manager manages all events to be triggered on a given mesh or the global scene.
-     * A single scene can have many Action Managers to handle predefined actions on specific meshes.
-     */
-    var ActionManager = (function () {
-        function ActionManager(scene) {
-            // Members
-            this.actions = new Array();
-            this._scene = scene;
-            scene._actionManagers.push(this);
-        }
-        Object.defineProperty(ActionManager, "NothingTrigger", {
-            get: function () {
-                return ActionManager._NothingTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnPickTrigger", {
-            get: function () {
-                return ActionManager._OnPickTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
-            get: function () {
-                return ActionManager._OnLeftPickTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnRightPickTrigger", {
-            get: function () {
-                return ActionManager._OnRightPickTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
-            get: function () {
-                return ActionManager._OnCenterPickTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnPickDownTrigger", {
-            get: function () {
-                return ActionManager._OnPickDownTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnPickUpTrigger", {
-            get: function () {
-                return ActionManager._OnPickUpTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnLongPressTrigger", {
-            get: function () {
-                return ActionManager._OnLongPressTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
-            get: function () {
-                return ActionManager._OnPointerOverTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
-            get: function () {
-                return ActionManager._OnPointerOutTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
-            get: function () {
-                return ActionManager._OnEveryFrameTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
-            get: function () {
-                return ActionManager._OnIntersectionEnterTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
-            get: function () {
-                return ActionManager._OnIntersectionExitTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
-            get: function () {
-                return ActionManager._OnKeyDownTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
-            get: function () {
-                return ActionManager._OnKeyUpTrigger;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        // Methods
-        ActionManager.prototype.dispose = function () {
-            var index = this._scene._actionManagers.indexOf(this);
-            if (index > -1) {
-                this._scene._actionManagers.splice(index, 1);
-            }
-        };
-        ActionManager.prototype.getScene = function () {
-            return this._scene;
-        };
-        /**
-         * Does this action manager handles actions of any of the given triggers
-         * @param {number[]} triggers - the triggers to be tested
-         * @return {boolean} whether one (or more) of the triggers is handeled
-         */
-        ActionManager.prototype.hasSpecificTriggers = function (triggers) {
-            for (var index = 0; index < this.actions.length; index++) {
-                var action = this.actions[index];
-                if (triggers.indexOf(action.trigger) > -1) {
-                    return true;
-                }
-            }
-            return false;
-        };
-        /**
-         * Does this action manager handles actions of a given trigger
-         * @param {number} trigger - the trigger to be tested
-         * @return {boolean} whether the trigger is handeled
-         */
-        ActionManager.prototype.hasSpecificTrigger = function (trigger) {
-            for (var index = 0; index < this.actions.length; index++) {
-                var action = this.actions[index];
-                if (action.trigger === trigger) {
-                    return true;
-                }
-            }
-            return false;
-        };
-        Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
-            /**
-             * Does this action manager has pointer triggers
-             * @return {boolean} whether or not it has pointer triggers
-             */
-            get: function () {
-                for (var index = 0; index < this.actions.length; index++) {
-                    var action = this.actions[index];
-                    if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
-                        return true;
-                    }
-                }
-                return false;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
-            /**
-             * Does this action manager has pick triggers
-             * @return {boolean} whether or not it has pick triggers
-             */
-            get: function () {
-                for (var index = 0; index < this.actions.length; index++) {
-                    var action = this.actions[index];
-                    if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
-                        return true;
-                    }
-                }
-                return false;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        /**
-         * Registers an action to this action manager
-         * @param {BABYLON.Action} action - the action to be registered
-         * @return {BABYLON.Action} the action amended (prepared) after registration
-         */
-        ActionManager.prototype.registerAction = function (action) {
-            if (action.trigger === ActionManager.OnEveryFrameTrigger) {
-                if (this.getScene().actionManager !== this) {
-                    BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
-                    return null;
-                }
-            }
-            this.actions.push(action);
-            action._actionManager = this;
-            action._prepare();
-            return action;
-        };
-        /**
-         * Process a specific trigger
-         * @param {number} trigger - the trigger to process
-         * @param evt {BABYLON.ActionEvent} the event details to be processed
-         */
-        ActionManager.prototype.processTrigger = function (trigger, evt) {
-            for (var index = 0; index < this.actions.length; index++) {
-                var action = this.actions[index];
-                if (action.trigger === trigger) {
-                    if (trigger === ActionManager.OnKeyUpTrigger
-                        || trigger === ActionManager.OnKeyDownTrigger) {
-                        var parameter = action.getTriggerParameter();
-                        if (parameter) {
-                            var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
-                            var actualkey = String.fromCharCode(unicode).toLowerCase();
-                            if (actualkey !== parameter.toLowerCase()) {
-                                continue;
-                            }
-                        }
-                    }
-                    action._executeCurrent(evt);
-                }
-            }
-        };
-        ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
-            var properties = propertyPath.split(".");
-            for (var index = 0; index < properties.length - 1; index++) {
-                target = target[properties[index]];
-            }
-            return target;
-        };
-        ActionManager.prototype._getProperty = function (propertyPath) {
-            var properties = propertyPath.split(".");
-            return properties[properties.length - 1];
-        };
-        ActionManager.Parse = function (parsedActions, object, scene) {
-            var actionManager = new BABYLON.ActionManager(scene);
-            if (object === null)
-                scene.actionManager = actionManager;
-            else
-                object.actionManager = actionManager;
-            // instanciate a new object
-            var instanciate = function (name, params) {
-                var newInstance = Object.create(BABYLON[name].prototype);
-                newInstance.constructor.apply(newInstance, params);
-                return newInstance;
-            };
-            var parseParameter = function (name, value, target, propertyPath) {
-                if (propertyPath === null) {
-                    // String, boolean or float
-                    var floatValue = parseFloat(value);
-                    if (value === "true" || value === "false")
-                        return value === "true";
-                    else
-                        return isNaN(floatValue) ? value : floatValue;
-                }
-                var effectiveTarget = propertyPath.split(".");
-                var values = value.split(",");
-                // Get effective Target
-                for (var i = 0; i < effectiveTarget.length; i++) {
-                    target = target[effectiveTarget[i]];
-                }
-                // Return appropriate value with its type
-                if (typeof (target) === "boolean")
-                    return values[0] === "true";
-                if (typeof (target) === "string")
-                    return values[0];
-                // Parameters with multiple values such as Vector3 etc.
-                var split = new Array();
-                for (var i = 0; i < values.length; i++)
-                    split.push(parseFloat(values[i]));
-                if (target instanceof BABYLON.Vector3)
-                    return BABYLON.Vector3.FromArray(split);
-                if (target instanceof BABYLON.Vector4)
-                    return BABYLON.Vector4.FromArray(split);
-                if (target instanceof BABYLON.Color3)
-                    return BABYLON.Color3.FromArray(split);
-                if (target instanceof BABYLON.Color4)
-                    return BABYLON.Color4.FromArray(split);
-                return parseFloat(values[0]);
-            };
-            // traverse graph per trigger
-            var traverse = function (parsedAction, trigger, condition, action, combineArray) {
-                if (combineArray === void 0) { combineArray = null; }
-                if (parsedAction.detached)
-                    return;
-                var parameters = new Array();
-                var target = null;
-                var propertyPath = null;
-                var combine = parsedAction.combine && parsedAction.combine.length > 0;
-                // Parameters
-                if (parsedAction.type === 2)
-                    parameters.push(actionManager);
-                else
-                    parameters.push(trigger);
-                if (combine) {
-                    var actions = new Array();
-                    for (var j = 0; j < parsedAction.combine.length; j++) {
-                        traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
-                    }
-                    parameters.push(actions);
-                }
-                else {
-                    for (var i = 0; i < parsedAction.properties.length; i++) {
-                        var value = parsedAction.properties[i].value;
-                        var name = parsedAction.properties[i].name;
-                        var targetType = parsedAction.properties[i].targetType;
-                        if (name === "target")
-                            if (targetType !== null && targetType === "SceneProperties")
-                                value = target = scene;
-                            else
-                                value = target = scene.getNodeByName(value);
-                        else if (name === "parent")
-                            value = scene.getNodeByName(value);
-                        else if (name === "sound")
-                            value = scene.getSoundByName(value);
-                        else if (name !== "propertyPath") {
-                            if (parsedAction.type === 2 && name === "operator")
-                                value = BABYLON.ValueCondition[value];
-                            else
-                                value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
-                        }
-                        else {
-                            propertyPath = value;
-                        }
-                        parameters.push(value);
-                    }
-                }
-                if (combineArray === null) {
-                    parameters.push(condition);
-                }
-                else {
-                    parameters.push(null);
-                }
-                // If interpolate value action
-                if (parsedAction.name === "InterpolateValueAction") {
-                    var param = parameters[parameters.length - 2];
-                    parameters[parameters.length - 1] = param;
-                    parameters[parameters.length - 2] = condition;
-                }
-                // Action or condition(s) and not CombineAction
-                var newAction = instanciate(parsedAction.name, parameters);
-                if (newAction instanceof BABYLON.Condition && condition !== null) {
-                    var nothing = new BABYLON.DoNothingAction(trigger, condition);
-                    if (action)
-                        action.then(nothing);
-                    else
-                        actionManager.registerAction(nothing);
-                    action = nothing;
-                }
-                if (combineArray === null) {
-                    if (newAction instanceof BABYLON.Condition) {
-                        condition = newAction;
-                        newAction = action;
-                    }
-                    else {
-                        condition = null;
-                        if (action)
-                            action.then(newAction);
-                        else
-                            actionManager.registerAction(newAction);
-                    }
-                }
-                else {
-                    combineArray.push(newAction);
-                }
-                for (var i = 0; i < parsedAction.children.length; i++)
-                    traverse(parsedAction.children[i], trigger, condition, newAction, null);
-            };
-            // triggers
-            for (var i = 0; i < parsedActions.children.length; i++) {
-                var triggerParams;
-                var trigger = parsedActions.children[i];
-                if (trigger.properties.length > 0) {
-                    var param = trigger.properties[0].value;
-                    var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
-                    triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
-                }
-                else
-                    triggerParams = BABYLON.ActionManager[trigger.name];
-                for (var j = 0; j < trigger.children.length; j++) {
-                    if (!trigger.detached)
-                        traverse(trigger.children[j], triggerParams, null, null);
-                }
-            }
-        };
-        // Statics
-        ActionManager._NothingTrigger = 0;
-        ActionManager._OnPickTrigger = 1;
-        ActionManager._OnLeftPickTrigger = 2;
-        ActionManager._OnRightPickTrigger = 3;
-        ActionManager._OnCenterPickTrigger = 4;
-        ActionManager._OnPickDownTrigger = 5;
-        ActionManager._OnPickUpTrigger = 6;
-        ActionManager._OnLongPressTrigger = 7;
-        ActionManager._OnPointerOverTrigger = 8;
-        ActionManager._OnPointerOutTrigger = 9;
-        ActionManager._OnEveryFrameTrigger = 10;
-        ActionManager._OnIntersectionEnterTrigger = 11;
-        ActionManager._OnIntersectionExitTrigger = 12;
-        ActionManager._OnKeyDownTrigger = 13;
-        ActionManager._OnKeyUpTrigger = 14;
-        ActionManager.DragMovementThreshold = 10; // in pixels
-        ActionManager.LongPressDelay = 500; // in milliseconds
-        return ActionManager;
-    })();
-    BABYLON.ActionManager = ActionManager;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    /**
+     * ActionEvent is the event beint sent when an action is triggered.
+     */
+    var ActionEvent = (function () {
+        /**
+         * @constructor
+         * @param source The mesh or sprite that triggered the action.
+         * @param pointerX The X mouse cursor position at the time of the event
+         * @param pointerY The Y mouse cursor position at the time of the event
+         * @param meshUnderPointer The mesh that is currently pointed at (can be null)
+         * @param sourceEvent the original (browser) event that triggered the ActionEvent
+         */
+        function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
+            this.source = source;
+            this.pointerX = pointerX;
+            this.pointerY = pointerY;
+            this.meshUnderPointer = meshUnderPointer;
+            this.sourceEvent = sourceEvent;
+            this.additionalData = additionalData;
+        }
+        /**
+         * Helper function to auto-create an ActionEvent from a source mesh.
+         * @param source The source mesh that triggered the event
+         * @param evt {Event} The original (browser) event
+         */
+        ActionEvent.CreateNew = function (source, evt, additionalData) {
+            var scene = source.getScene();
+            return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
+        };
+        /**
+         * Helper function to auto-create an ActionEvent from a source mesh.
+         * @param source The source sprite that triggered the event
+         * @param scene Scene associated with the sprite
+         * @param evt {Event} The original (browser) event
+         */
+        ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
+            return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
+        };
+        /**
+         * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
+         * @param scene the scene where the event occurred
+         * @param evt {Event} The original (browser) event
+         */
+        ActionEvent.CreateNewFromScene = function (scene, evt) {
+            return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
+        };
+        return ActionEvent;
+    })();
+    BABYLON.ActionEvent = ActionEvent;
+    /**
+     * Action Manager manages all events to be triggered on a given mesh or the global scene.
+     * A single scene can have many Action Managers to handle predefined actions on specific meshes.
+     */
+    var ActionManager = (function () {
+        function ActionManager(scene) {
+            // Members
+            this.actions = new Array();
+            this._scene = scene;
+            scene._actionManagers.push(this);
+        }
+        Object.defineProperty(ActionManager, "NothingTrigger", {
+            get: function () {
+                return ActionManager._NothingTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnPickTrigger", {
+            get: function () {
+                return ActionManager._OnPickTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
+            get: function () {
+                return ActionManager._OnLeftPickTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnRightPickTrigger", {
+            get: function () {
+                return ActionManager._OnRightPickTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
+            get: function () {
+                return ActionManager._OnCenterPickTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnPickDownTrigger", {
+            get: function () {
+                return ActionManager._OnPickDownTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnPickUpTrigger", {
+            get: function () {
+                return ActionManager._OnPickUpTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnLongPressTrigger", {
+            get: function () {
+                return ActionManager._OnLongPressTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
+            get: function () {
+                return ActionManager._OnPointerOverTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
+            get: function () {
+                return ActionManager._OnPointerOutTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
+            get: function () {
+                return ActionManager._OnEveryFrameTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
+            get: function () {
+                return ActionManager._OnIntersectionEnterTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
+            get: function () {
+                return ActionManager._OnIntersectionExitTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
+            get: function () {
+                return ActionManager._OnKeyDownTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
+            get: function () {
+                return ActionManager._OnKeyUpTrigger;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        // Methods
+        ActionManager.prototype.dispose = function () {
+            var index = this._scene._actionManagers.indexOf(this);
+            if (index > -1) {
+                this._scene._actionManagers.splice(index, 1);
+            }
+        };
+        ActionManager.prototype.getScene = function () {
+            return this._scene;
+        };
+        /**
+         * Does this action manager handles actions of any of the given triggers
+         * @param {number[]} triggers - the triggers to be tested
+         * @return {boolean} whether one (or more) of the triggers is handeled
+         */
+        ActionManager.prototype.hasSpecificTriggers = function (triggers) {
+            for (var index = 0; index < this.actions.length; index++) {
+                var action = this.actions[index];
+                if (triggers.indexOf(action.trigger) > -1) {
+                    return true;
+                }
+            }
+            return false;
+        };
+        /**
+         * Does this action manager handles actions of a given trigger
+         * @param {number} trigger - the trigger to be tested
+         * @return {boolean} whether the trigger is handeled
+         */
+        ActionManager.prototype.hasSpecificTrigger = function (trigger) {
+            for (var index = 0; index < this.actions.length; index++) {
+                var action = this.actions[index];
+                if (action.trigger === trigger) {
+                    return true;
+                }
+            }
+            return false;
+        };
+        Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
+            /**
+             * Does this action manager has pointer triggers
+             * @return {boolean} whether or not it has pointer triggers
+             */
+            get: function () {
+                for (var index = 0; index < this.actions.length; index++) {
+                    var action = this.actions[index];
+                    if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
+                        return true;
+                    }
+                }
+                return false;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
+            /**
+             * Does this action manager has pick triggers
+             * @return {boolean} whether or not it has pick triggers
+             */
+            get: function () {
+                for (var index = 0; index < this.actions.length; index++) {
+                    var action = this.actions[index];
+                    if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
+                        return true;
+                    }
+                }
+                return false;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        /**
+         * Registers an action to this action manager
+         * @param {BABYLON.Action} action - the action to be registered
+         * @return {BABYLON.Action} the action amended (prepared) after registration
+         */
+        ActionManager.prototype.registerAction = function (action) {
+            if (action.trigger === ActionManager.OnEveryFrameTrigger) {
+                if (this.getScene().actionManager !== this) {
+                    BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
+                    return null;
+                }
+            }
+            this.actions.push(action);
+            action._actionManager = this;
+            action._prepare();
+            return action;
+        };
+        /**
+         * Process a specific trigger
+         * @param {number} trigger - the trigger to process
+         * @param evt {BABYLON.ActionEvent} the event details to be processed
+         */
+        ActionManager.prototype.processTrigger = function (trigger, evt) {
+            for (var index = 0; index < this.actions.length; index++) {
+                var action = this.actions[index];
+                if (action.trigger === trigger) {
+                    if (trigger === ActionManager.OnKeyUpTrigger
+                        || trigger === ActionManager.OnKeyDownTrigger) {
+                        var parameter = action.getTriggerParameter();
+                        if (parameter) {
+                            var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
+                            var actualkey = String.fromCharCode(unicode).toLowerCase();
+                            if (actualkey !== parameter.toLowerCase()) {
+                                continue;
+                            }
+                        }
+                    }
+                    action._executeCurrent(evt);
+                }
+            }
+        };
+        ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
+            var properties = propertyPath.split(".");
+            for (var index = 0; index < properties.length - 1; index++) {
+                target = target[properties[index]];
+            }
+            return target;
+        };
+        ActionManager.prototype._getProperty = function (propertyPath) {
+            var properties = propertyPath.split(".");
+            return properties[properties.length - 1];
+        };
+        ActionManager.Parse = function (parsedActions, object, scene) {
+            var actionManager = new BABYLON.ActionManager(scene);
+            if (object === null)
+                scene.actionManager = actionManager;
+            else
+                object.actionManager = actionManager;
+            // instanciate a new object
+            var instanciate = function (name, params) {
+                var newInstance = Object.create(BABYLON[name].prototype);
+                newInstance.constructor.apply(newInstance, params);
+                return newInstance;
+            };
+            var parseParameter = function (name, value, target, propertyPath) {
+                if (propertyPath === null) {
+                    // String, boolean or float
+                    var floatValue = parseFloat(value);
+                    if (value === "true" || value === "false")
+                        return value === "true";
+                    else
+                        return isNaN(floatValue) ? value : floatValue;
+                }
+                var effectiveTarget = propertyPath.split(".");
+                var values = value.split(",");
+                // Get effective Target
+                for (var i = 0; i < effectiveTarget.length; i++) {
+                    target = target[effectiveTarget[i]];
+                }
+                // Return appropriate value with its type
+                if (typeof (target) === "boolean")
+                    return values[0] === "true";
+                if (typeof (target) === "string")
+                    return values[0];
+                // Parameters with multiple values such as Vector3 etc.
+                var split = new Array();
+                for (var i = 0; i < values.length; i++)
+                    split.push(parseFloat(values[i]));
+                if (target instanceof BABYLON.Vector3)
+                    return BABYLON.Vector3.FromArray(split);
+                if (target instanceof BABYLON.Vector4)
+                    return BABYLON.Vector4.FromArray(split);
+                if (target instanceof BABYLON.Color3)
+                    return BABYLON.Color3.FromArray(split);
+                if (target instanceof BABYLON.Color4)
+                    return BABYLON.Color4.FromArray(split);
+                return parseFloat(values[0]);
+            };
+            // traverse graph per trigger
+            var traverse = function (parsedAction, trigger, condition, action, combineArray) {
+                if (combineArray === void 0) { combineArray = null; }
+                if (parsedAction.detached)
+                    return;
+                var parameters = new Array();
+                var target = null;
+                var propertyPath = null;
+                var combine = parsedAction.combine && parsedAction.combine.length > 0;
+                // Parameters
+                if (parsedAction.type === 2)
+                    parameters.push(actionManager);
+                else
+                    parameters.push(trigger);
+                if (combine) {
+                    var actions = new Array();
+                    for (var j = 0; j < parsedAction.combine.length; j++) {
+                        traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
+                    }
+                    parameters.push(actions);
+                }
+                else {
+                    for (var i = 0; i < parsedAction.properties.length; i++) {
+                        var value = parsedAction.properties[i].value;
+                        var name = parsedAction.properties[i].name;
+                        var targetType = parsedAction.properties[i].targetType;
+                        if (name === "target")
+                            if (targetType !== null && targetType === "SceneProperties")
+                                value = target = scene;
+                            else
+                                value = target = scene.getNodeByName(value);
+                        else if (name === "parent")
+                            value = scene.getNodeByName(value);
+                        else if (name === "sound")
+                            value = scene.getSoundByName(value);
+                        else if (name !== "propertyPath") {
+                            if (parsedAction.type === 2 && name === "operator")
+                                value = BABYLON.ValueCondition[value];
+                            else
+                                value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
+                        }
+                        else {
+                            propertyPath = value;
+                        }
+                        parameters.push(value);
+                    }
+                }
+                if (combineArray === null) {
+                    parameters.push(condition);
+                }
+                else {
+                    parameters.push(null);
+                }
+                // If interpolate value action
+                if (parsedAction.name === "InterpolateValueAction") {
+                    var param = parameters[parameters.length - 2];
+                    parameters[parameters.length - 1] = param;
+                    parameters[parameters.length - 2] = condition;
+                }
+                // Action or condition(s) and not CombineAction
+                var newAction = instanciate(parsedAction.name, parameters);
+                if (newAction instanceof BABYLON.Condition && condition !== null) {
+                    var nothing = new BABYLON.DoNothingAction(trigger, condition);
+                    if (action)
+                        action.then(nothing);
+                    else
+                        actionManager.registerAction(nothing);
+                    action = nothing;
+                }
+                if (combineArray === null) {
+                    if (newAction instanceof BABYLON.Condition) {
+                        condition = newAction;
+                        newAction = action;
+                    }
+                    else {
+                        condition = null;
+                        if (action)
+                            action.then(newAction);
+                        else
+                            actionManager.registerAction(newAction);
+                    }
+                }
+                else {
+                    combineArray.push(newAction);
+                }
+                for (var i = 0; i < parsedAction.children.length; i++)
+                    traverse(parsedAction.children[i], trigger, condition, newAction, null);
+            };
+            // triggers
+            for (var i = 0; i < parsedActions.children.length; i++) {
+                var triggerParams;
+                var trigger = parsedActions.children[i];
+                if (trigger.properties.length > 0) {
+                    var param = trigger.properties[0].value;
+                    var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
+                    triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
+                }
+                else
+                    triggerParams = BABYLON.ActionManager[trigger.name];
+                for (var j = 0; j < trigger.children.length; j++) {
+                    if (!trigger.detached)
+                        traverse(trigger.children[j], triggerParams, null, null);
+                }
+            }
+        };
+        // Statics
+        ActionManager._NothingTrigger = 0;
+        ActionManager._OnPickTrigger = 1;
+        ActionManager._OnLeftPickTrigger = 2;
+        ActionManager._OnRightPickTrigger = 3;
+        ActionManager._OnCenterPickTrigger = 4;
+        ActionManager._OnPickDownTrigger = 5;
+        ActionManager._OnPickUpTrigger = 6;
+        ActionManager._OnLongPressTrigger = 7;
+        ActionManager._OnPointerOverTrigger = 8;
+        ActionManager._OnPointerOutTrigger = 9;
+        ActionManager._OnEveryFrameTrigger = 10;
+        ActionManager._OnIntersectionEnterTrigger = 11;
+        ActionManager._OnIntersectionExitTrigger = 12;
+        ActionManager._OnKeyDownTrigger = 13;
+        ActionManager._OnKeyUpTrigger = 14;
+        ActionManager.DragMovementThreshold = 10; // in pixels
+        ActionManager.LongPressDelay = 500; // in milliseconds
+        return ActionManager;
+    })();
+    BABYLON.ActionManager = ActionManager;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.actionManager.js.map

+ 118 - 117
src/Actions/babylon.condition.js

@@ -1,117 +1,118 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var Condition = (function () {
-        function Condition(actionManager) {
-            this._actionManager = actionManager;
-        }
-        Condition.prototype.isValid = function () {
-            return true;
-        };
-        Condition.prototype._getProperty = function (propertyPath) {
-            return this._actionManager._getProperty(propertyPath);
-        };
-        Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
-            return this._actionManager._getEffectiveTarget(target, propertyPath);
-        };
-        return Condition;
-    })();
-    BABYLON.Condition = Condition;
-    var ValueCondition = (function (_super) {
-        __extends(ValueCondition, _super);
-        function ValueCondition(actionManager, target, propertyPath, value, operator) {
-            if (operator === void 0) { operator = ValueCondition.IsEqual; }
-            _super.call(this, actionManager);
-            this.propertyPath = propertyPath;
-            this.value = value;
-            this.operator = operator;
-            this._target = this._getEffectiveTarget(target, this.propertyPath);
-            this._property = this._getProperty(this.propertyPath);
-        }
-        Object.defineProperty(ValueCondition, "IsEqual", {
-            get: function () {
-                return ValueCondition._IsEqual;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ValueCondition, "IsDifferent", {
-            get: function () {
-                return ValueCondition._IsDifferent;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ValueCondition, "IsGreater", {
-            get: function () {
-                return ValueCondition._IsGreater;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ValueCondition, "IsLesser", {
-            get: function () {
-                return ValueCondition._IsLesser;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        // Methods
-        ValueCondition.prototype.isValid = function () {
-            switch (this.operator) {
-                case ValueCondition.IsGreater:
-                    return this._target[this._property] > this.value;
-                case ValueCondition.IsLesser:
-                    return this._target[this._property] < this.value;
-                case ValueCondition.IsEqual:
-                case ValueCondition.IsDifferent:
-                    var check;
-                    if (this.value.equals) {
-                        check = this.value.equals(this._target[this._property]);
-                    }
-                    else {
-                        check = this.value === this._target[this._property];
-                    }
-                    return this.operator === ValueCondition.IsEqual ? check : !check;
-            }
-            return false;
-        };
-        // Statics
-        ValueCondition._IsEqual = 0;
-        ValueCondition._IsDifferent = 1;
-        ValueCondition._IsGreater = 2;
-        ValueCondition._IsLesser = 3;
-        return ValueCondition;
-    })(Condition);
-    BABYLON.ValueCondition = ValueCondition;
-    var PredicateCondition = (function (_super) {
-        __extends(PredicateCondition, _super);
-        function PredicateCondition(actionManager, predicate) {
-            _super.call(this, actionManager);
-            this.predicate = predicate;
-        }
-        PredicateCondition.prototype.isValid = function () {
-            return this.predicate();
-        };
-        return PredicateCondition;
-    })(Condition);
-    BABYLON.PredicateCondition = PredicateCondition;
-    var StateCondition = (function (_super) {
-        __extends(StateCondition, _super);
-        function StateCondition(actionManager, target, value) {
-            _super.call(this, actionManager);
-            this.value = value;
-            this._target = target;
-        }
-        // Methods
-        StateCondition.prototype.isValid = function () {
-            return this._target.state === this.value;
-        };
-        return StateCondition;
-    })(Condition);
-    BABYLON.StateCondition = StateCondition;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var Condition = (function () {
+        function Condition(actionManager) {
+            this._actionManager = actionManager;
+        }
+        Condition.prototype.isValid = function () {
+            return true;
+        };
+        Condition.prototype._getProperty = function (propertyPath) {
+            return this._actionManager._getProperty(propertyPath);
+        };
+        Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
+            return this._actionManager._getEffectiveTarget(target, propertyPath);
+        };
+        return Condition;
+    })();
+    BABYLON.Condition = Condition;
+    var ValueCondition = (function (_super) {
+        __extends(ValueCondition, _super);
+        function ValueCondition(actionManager, target, propertyPath, value, operator) {
+            if (operator === void 0) { operator = ValueCondition.IsEqual; }
+            _super.call(this, actionManager);
+            this.propertyPath = propertyPath;
+            this.value = value;
+            this.operator = operator;
+            this._target = this._getEffectiveTarget(target, this.propertyPath);
+            this._property = this._getProperty(this.propertyPath);
+        }
+        Object.defineProperty(ValueCondition, "IsEqual", {
+            get: function () {
+                return ValueCondition._IsEqual;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ValueCondition, "IsDifferent", {
+            get: function () {
+                return ValueCondition._IsDifferent;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ValueCondition, "IsGreater", {
+            get: function () {
+                return ValueCondition._IsGreater;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ValueCondition, "IsLesser", {
+            get: function () {
+                return ValueCondition._IsLesser;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        // Methods
+        ValueCondition.prototype.isValid = function () {
+            switch (this.operator) {
+                case ValueCondition.IsGreater:
+                    return this._target[this._property] > this.value;
+                case ValueCondition.IsLesser:
+                    return this._target[this._property] < this.value;
+                case ValueCondition.IsEqual:
+                case ValueCondition.IsDifferent:
+                    var check;
+                    if (this.value.equals) {
+                        check = this.value.equals(this._target[this._property]);
+                    }
+                    else {
+                        check = this.value === this._target[this._property];
+                    }
+                    return this.operator === ValueCondition.IsEqual ? check : !check;
+            }
+            return false;
+        };
+        // Statics
+        ValueCondition._IsEqual = 0;
+        ValueCondition._IsDifferent = 1;
+        ValueCondition._IsGreater = 2;
+        ValueCondition._IsLesser = 3;
+        return ValueCondition;
+    })(Condition);
+    BABYLON.ValueCondition = ValueCondition;
+    var PredicateCondition = (function (_super) {
+        __extends(PredicateCondition, _super);
+        function PredicateCondition(actionManager, predicate) {
+            _super.call(this, actionManager);
+            this.predicate = predicate;
+        }
+        PredicateCondition.prototype.isValid = function () {
+            return this.predicate();
+        };
+        return PredicateCondition;
+    })(Condition);
+    BABYLON.PredicateCondition = PredicateCondition;
+    var StateCondition = (function (_super) {
+        __extends(StateCondition, _super);
+        function StateCondition(actionManager, target, value) {
+            _super.call(this, actionManager);
+            this.value = value;
+            this._target = target;
+        }
+        // Methods
+        StateCondition.prototype.isValid = function () {
+            return this._target.state === this.value;
+        };
+        return StateCondition;
+    })(Condition);
+    BABYLON.StateCondition = StateCondition;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.condition.js.map

+ 205 - 204
src/Actions/babylon.directActions.js

@@ -1,204 +1,205 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var SwitchBooleanAction = (function (_super) {
-        __extends(SwitchBooleanAction, _super);
-        function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
-            _super.call(this, triggerOptions, condition);
-            this.propertyPath = propertyPath;
-            this._target = target;
-        }
-        SwitchBooleanAction.prototype._prepare = function () {
-            this._target = this._getEffectiveTarget(this._target, this.propertyPath);
-            this._property = this._getProperty(this.propertyPath);
-        };
-        SwitchBooleanAction.prototype.execute = function () {
-            this._target[this._property] = !this._target[this._property];
-        };
-        return SwitchBooleanAction;
-    })(BABYLON.Action);
-    BABYLON.SwitchBooleanAction = SwitchBooleanAction;
-    var SetStateAction = (function (_super) {
-        __extends(SetStateAction, _super);
-        function SetStateAction(triggerOptions, target, value, condition) {
-            _super.call(this, triggerOptions, condition);
-            this.value = value;
-            this._target = target;
-        }
-        SetStateAction.prototype.execute = function () {
-            this._target.state = this.value;
-        };
-        return SetStateAction;
-    })(BABYLON.Action);
-    BABYLON.SetStateAction = SetStateAction;
-    var SetValueAction = (function (_super) {
-        __extends(SetValueAction, _super);
-        function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
-            _super.call(this, triggerOptions, condition);
-            this.propertyPath = propertyPath;
-            this.value = value;
-            this._target = target;
-        }
-        SetValueAction.prototype._prepare = function () {
-            this._target = this._getEffectiveTarget(this._target, this.propertyPath);
-            this._property = this._getProperty(this.propertyPath);
-        };
-        SetValueAction.prototype.execute = function () {
-            this._target[this._property] = this.value;
-        };
-        return SetValueAction;
-    })(BABYLON.Action);
-    BABYLON.SetValueAction = SetValueAction;
-    var IncrementValueAction = (function (_super) {
-        __extends(IncrementValueAction, _super);
-        function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
-            _super.call(this, triggerOptions, condition);
-            this.propertyPath = propertyPath;
-            this.value = value;
-            this._target = target;
-        }
-        IncrementValueAction.prototype._prepare = function () {
-            this._target = this._getEffectiveTarget(this._target, this.propertyPath);
-            this._property = this._getProperty(this.propertyPath);
-            if (typeof this._target[this._property] !== "number") {
-                BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
-            }
-        };
-        IncrementValueAction.prototype.execute = function () {
-            this._target[this._property] += this.value;
-        };
-        return IncrementValueAction;
-    })(BABYLON.Action);
-    BABYLON.IncrementValueAction = IncrementValueAction;
-    var PlayAnimationAction = (function (_super) {
-        __extends(PlayAnimationAction, _super);
-        function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
-            _super.call(this, triggerOptions, condition);
-            this.from = from;
-            this.to = to;
-            this.loop = loop;
-            this._target = target;
-        }
-        PlayAnimationAction.prototype._prepare = function () {
-        };
-        PlayAnimationAction.prototype.execute = function () {
-            var scene = this._actionManager.getScene();
-            scene.beginAnimation(this._target, this.from, this.to, this.loop);
-        };
-        return PlayAnimationAction;
-    })(BABYLON.Action);
-    BABYLON.PlayAnimationAction = PlayAnimationAction;
-    var StopAnimationAction = (function (_super) {
-        __extends(StopAnimationAction, _super);
-        function StopAnimationAction(triggerOptions, target, condition) {
-            _super.call(this, triggerOptions, condition);
-            this._target = target;
-        }
-        StopAnimationAction.prototype._prepare = function () {
-        };
-        StopAnimationAction.prototype.execute = function () {
-            var scene = this._actionManager.getScene();
-            scene.stopAnimation(this._target);
-        };
-        return StopAnimationAction;
-    })(BABYLON.Action);
-    BABYLON.StopAnimationAction = StopAnimationAction;
-    var DoNothingAction = (function (_super) {
-        __extends(DoNothingAction, _super);
-        function DoNothingAction(triggerOptions, condition) {
-            if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
-            _super.call(this, triggerOptions, condition);
-        }
-        DoNothingAction.prototype.execute = function () {
-        };
-        return DoNothingAction;
-    })(BABYLON.Action);
-    BABYLON.DoNothingAction = DoNothingAction;
-    var CombineAction = (function (_super) {
-        __extends(CombineAction, _super);
-        function CombineAction(triggerOptions, children, condition) {
-            _super.call(this, triggerOptions, condition);
-            this.children = children;
-        }
-        CombineAction.prototype._prepare = function () {
-            for (var index = 0; index < this.children.length; index++) {
-                this.children[index]._actionManager = this._actionManager;
-                this.children[index]._prepare();
-            }
-        };
-        CombineAction.prototype.execute = function (evt) {
-            for (var index = 0; index < this.children.length; index++) {
-                this.children[index].execute(evt);
-            }
-        };
-        return CombineAction;
-    })(BABYLON.Action);
-    BABYLON.CombineAction = CombineAction;
-    var ExecuteCodeAction = (function (_super) {
-        __extends(ExecuteCodeAction, _super);
-        function ExecuteCodeAction(triggerOptions, func, condition) {
-            _super.call(this, triggerOptions, condition);
-            this.func = func;
-        }
-        ExecuteCodeAction.prototype.execute = function (evt) {
-            this.func(evt);
-        };
-        return ExecuteCodeAction;
-    })(BABYLON.Action);
-    BABYLON.ExecuteCodeAction = ExecuteCodeAction;
-    var SetParentAction = (function (_super) {
-        __extends(SetParentAction, _super);
-        function SetParentAction(triggerOptions, target, parent, condition) {
-            _super.call(this, triggerOptions, condition);
-            this._target = target;
-            this._parent = parent;
-        }
-        SetParentAction.prototype._prepare = function () {
-        };
-        SetParentAction.prototype.execute = function () {
-            if (this._target.parent === this._parent) {
-                return;
-            }
-            var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
-            invertParentWorldMatrix.invert();
-            this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
-            this._target.parent = this._parent;
-        };
-        return SetParentAction;
-    })(BABYLON.Action);
-    BABYLON.SetParentAction = SetParentAction;
-    var PlaySoundAction = (function (_super) {
-        __extends(PlaySoundAction, _super);
-        function PlaySoundAction(triggerOptions, sound, condition) {
-            _super.call(this, triggerOptions, condition);
-            this._sound = sound;
-        }
-        PlaySoundAction.prototype._prepare = function () {
-        };
-        PlaySoundAction.prototype.execute = function () {
-            if (this._sound !== undefined)
-                this._sound.play();
-        };
-        return PlaySoundAction;
-    })(BABYLON.Action);
-    BABYLON.PlaySoundAction = PlaySoundAction;
-    var StopSoundAction = (function (_super) {
-        __extends(StopSoundAction, _super);
-        function StopSoundAction(triggerOptions, sound, condition) {
-            _super.call(this, triggerOptions, condition);
-            this._sound = sound;
-        }
-        StopSoundAction.prototype._prepare = function () {
-        };
-        StopSoundAction.prototype.execute = function () {
-            if (this._sound !== undefined)
-                this._sound.stop();
-        };
-        return StopSoundAction;
-    })(BABYLON.Action);
-    BABYLON.StopSoundAction = StopSoundAction;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var SwitchBooleanAction = (function (_super) {
+        __extends(SwitchBooleanAction, _super);
+        function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
+            _super.call(this, triggerOptions, condition);
+            this.propertyPath = propertyPath;
+            this._target = target;
+        }
+        SwitchBooleanAction.prototype._prepare = function () {
+            this._target = this._getEffectiveTarget(this._target, this.propertyPath);
+            this._property = this._getProperty(this.propertyPath);
+        };
+        SwitchBooleanAction.prototype.execute = function () {
+            this._target[this._property] = !this._target[this._property];
+        };
+        return SwitchBooleanAction;
+    })(BABYLON.Action);
+    BABYLON.SwitchBooleanAction = SwitchBooleanAction;
+    var SetStateAction = (function (_super) {
+        __extends(SetStateAction, _super);
+        function SetStateAction(triggerOptions, target, value, condition) {
+            _super.call(this, triggerOptions, condition);
+            this.value = value;
+            this._target = target;
+        }
+        SetStateAction.prototype.execute = function () {
+            this._target.state = this.value;
+        };
+        return SetStateAction;
+    })(BABYLON.Action);
+    BABYLON.SetStateAction = SetStateAction;
+    var SetValueAction = (function (_super) {
+        __extends(SetValueAction, _super);
+        function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
+            _super.call(this, triggerOptions, condition);
+            this.propertyPath = propertyPath;
+            this.value = value;
+            this._target = target;
+        }
+        SetValueAction.prototype._prepare = function () {
+            this._target = this._getEffectiveTarget(this._target, this.propertyPath);
+            this._property = this._getProperty(this.propertyPath);
+        };
+        SetValueAction.prototype.execute = function () {
+            this._target[this._property] = this.value;
+        };
+        return SetValueAction;
+    })(BABYLON.Action);
+    BABYLON.SetValueAction = SetValueAction;
+    var IncrementValueAction = (function (_super) {
+        __extends(IncrementValueAction, _super);
+        function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
+            _super.call(this, triggerOptions, condition);
+            this.propertyPath = propertyPath;
+            this.value = value;
+            this._target = target;
+        }
+        IncrementValueAction.prototype._prepare = function () {
+            this._target = this._getEffectiveTarget(this._target, this.propertyPath);
+            this._property = this._getProperty(this.propertyPath);
+            if (typeof this._target[this._property] !== "number") {
+                BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
+            }
+        };
+        IncrementValueAction.prototype.execute = function () {
+            this._target[this._property] += this.value;
+        };
+        return IncrementValueAction;
+    })(BABYLON.Action);
+    BABYLON.IncrementValueAction = IncrementValueAction;
+    var PlayAnimationAction = (function (_super) {
+        __extends(PlayAnimationAction, _super);
+        function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
+            _super.call(this, triggerOptions, condition);
+            this.from = from;
+            this.to = to;
+            this.loop = loop;
+            this._target = target;
+        }
+        PlayAnimationAction.prototype._prepare = function () {
+        };
+        PlayAnimationAction.prototype.execute = function () {
+            var scene = this._actionManager.getScene();
+            scene.beginAnimation(this._target, this.from, this.to, this.loop);
+        };
+        return PlayAnimationAction;
+    })(BABYLON.Action);
+    BABYLON.PlayAnimationAction = PlayAnimationAction;
+    var StopAnimationAction = (function (_super) {
+        __extends(StopAnimationAction, _super);
+        function StopAnimationAction(triggerOptions, target, condition) {
+            _super.call(this, triggerOptions, condition);
+            this._target = target;
+        }
+        StopAnimationAction.prototype._prepare = function () {
+        };
+        StopAnimationAction.prototype.execute = function () {
+            var scene = this._actionManager.getScene();
+            scene.stopAnimation(this._target);
+        };
+        return StopAnimationAction;
+    })(BABYLON.Action);
+    BABYLON.StopAnimationAction = StopAnimationAction;
+    var DoNothingAction = (function (_super) {
+        __extends(DoNothingAction, _super);
+        function DoNothingAction(triggerOptions, condition) {
+            if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
+            _super.call(this, triggerOptions, condition);
+        }
+        DoNothingAction.prototype.execute = function () {
+        };
+        return DoNothingAction;
+    })(BABYLON.Action);
+    BABYLON.DoNothingAction = DoNothingAction;
+    var CombineAction = (function (_super) {
+        __extends(CombineAction, _super);
+        function CombineAction(triggerOptions, children, condition) {
+            _super.call(this, triggerOptions, condition);
+            this.children = children;
+        }
+        CombineAction.prototype._prepare = function () {
+            for (var index = 0; index < this.children.length; index++) {
+                this.children[index]._actionManager = this._actionManager;
+                this.children[index]._prepare();
+            }
+        };
+        CombineAction.prototype.execute = function (evt) {
+            for (var index = 0; index < this.children.length; index++) {
+                this.children[index].execute(evt);
+            }
+        };
+        return CombineAction;
+    })(BABYLON.Action);
+    BABYLON.CombineAction = CombineAction;
+    var ExecuteCodeAction = (function (_super) {
+        __extends(ExecuteCodeAction, _super);
+        function ExecuteCodeAction(triggerOptions, func, condition) {
+            _super.call(this, triggerOptions, condition);
+            this.func = func;
+        }
+        ExecuteCodeAction.prototype.execute = function (evt) {
+            this.func(evt);
+        };
+        return ExecuteCodeAction;
+    })(BABYLON.Action);
+    BABYLON.ExecuteCodeAction = ExecuteCodeAction;
+    var SetParentAction = (function (_super) {
+        __extends(SetParentAction, _super);
+        function SetParentAction(triggerOptions, target, parent, condition) {
+            _super.call(this, triggerOptions, condition);
+            this._target = target;
+            this._parent = parent;
+        }
+        SetParentAction.prototype._prepare = function () {
+        };
+        SetParentAction.prototype.execute = function () {
+            if (this._target.parent === this._parent) {
+                return;
+            }
+            var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
+            invertParentWorldMatrix.invert();
+            this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
+            this._target.parent = this._parent;
+        };
+        return SetParentAction;
+    })(BABYLON.Action);
+    BABYLON.SetParentAction = SetParentAction;
+    var PlaySoundAction = (function (_super) {
+        __extends(PlaySoundAction, _super);
+        function PlaySoundAction(triggerOptions, sound, condition) {
+            _super.call(this, triggerOptions, condition);
+            this._sound = sound;
+        }
+        PlaySoundAction.prototype._prepare = function () {
+        };
+        PlaySoundAction.prototype.execute = function () {
+            if (this._sound !== undefined)
+                this._sound.play();
+        };
+        return PlaySoundAction;
+    })(BABYLON.Action);
+    BABYLON.PlaySoundAction = PlaySoundAction;
+    var StopSoundAction = (function (_super) {
+        __extends(StopSoundAction, _super);
+        function StopSoundAction(triggerOptions, sound, condition) {
+            _super.call(this, triggerOptions, condition);
+            this._sound = sound;
+        }
+        StopSoundAction.prototype._prepare = function () {
+        };
+        StopSoundAction.prototype.execute = function () {
+            if (this._sound !== undefined)
+                this._sound.stop();
+        };
+        return StopSoundAction;
+    })(BABYLON.Action);
+    BABYLON.StopSoundAction = StopSoundAction;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.directActions.js.map

+ 66 - 65
src/Actions/babylon.interpolateValueAction.js

@@ -1,65 +1,66 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var InterpolateValueAction = (function (_super) {
-        __extends(InterpolateValueAction, _super);
-        function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
-            if (duration === void 0) { duration = 1000; }
-            _super.call(this, triggerOptions, condition);
-            this.propertyPath = propertyPath;
-            this.value = value;
-            this.duration = duration;
-            this.stopOtherAnimations = stopOtherAnimations;
-            this.onInterpolationDone = onInterpolationDone;
-            this._target = target;
-        }
-        InterpolateValueAction.prototype._prepare = function () {
-            this._target = this._getEffectiveTarget(this._target, this.propertyPath);
-            this._property = this._getProperty(this.propertyPath);
-        };
-        InterpolateValueAction.prototype.execute = function () {
-            var scene = this._actionManager.getScene();
-            var keys = [
-                {
-                    frame: 0,
-                    value: this._target[this._property]
-                }, {
-                    frame: 100,
-                    value: this.value
-                }
-            ];
-            var dataType;
-            if (typeof this.value === "number") {
-                dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
-            }
-            else if (this.value instanceof BABYLON.Color3) {
-                dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
-            }
-            else if (this.value instanceof BABYLON.Vector3) {
-                dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
-            }
-            else if (this.value instanceof BABYLON.Matrix) {
-                dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
-            }
-            else if (this.value instanceof BABYLON.Quaternion) {
-                dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
-            }
-            else {
-                BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
-                return;
-            }
-            var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
-            animation.setKeys(keys);
-            if (this.stopOtherAnimations) {
-                scene.stopAnimation(this._target);
-            }
-            scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
-        };
-        return InterpolateValueAction;
-    })(BABYLON.Action);
-    BABYLON.InterpolateValueAction = InterpolateValueAction;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var InterpolateValueAction = (function (_super) {
+        __extends(InterpolateValueAction, _super);
+        function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
+            if (duration === void 0) { duration = 1000; }
+            _super.call(this, triggerOptions, condition);
+            this.propertyPath = propertyPath;
+            this.value = value;
+            this.duration = duration;
+            this.stopOtherAnimations = stopOtherAnimations;
+            this.onInterpolationDone = onInterpolationDone;
+            this._target = target;
+        }
+        InterpolateValueAction.prototype._prepare = function () {
+            this._target = this._getEffectiveTarget(this._target, this.propertyPath);
+            this._property = this._getProperty(this.propertyPath);
+        };
+        InterpolateValueAction.prototype.execute = function () {
+            var scene = this._actionManager.getScene();
+            var keys = [
+                {
+                    frame: 0,
+                    value: this._target[this._property]
+                }, {
+                    frame: 100,
+                    value: this.value
+                }
+            ];
+            var dataType;
+            if (typeof this.value === "number") {
+                dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
+            }
+            else if (this.value instanceof BABYLON.Color3) {
+                dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
+            }
+            else if (this.value instanceof BABYLON.Vector3) {
+                dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
+            }
+            else if (this.value instanceof BABYLON.Matrix) {
+                dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
+            }
+            else if (this.value instanceof BABYLON.Quaternion) {
+                dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
+            }
+            else {
+                BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
+                return;
+            }
+            var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
+            animation.setKeys(keys);
+            if (this.stopOtherAnimations) {
+                scene.stopAnimation(this._target);
+            }
+            scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
+        };
+        return InterpolateValueAction;
+    })(BABYLON.Action);
+    BABYLON.InterpolateValueAction = InterpolateValueAction;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.interpolateValueAction.js.map

+ 115 - 114
src/Animations/babylon.animatable.js

@@ -1,114 +1,115 @@
-var BABYLON;
-(function (BABYLON) {
-    var Animatable = (function () {
-        function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
-            if (fromFrame === void 0) { fromFrame = 0; }
-            if (toFrame === void 0) { toFrame = 100; }
-            if (loopAnimation === void 0) { loopAnimation = false; }
-            if (speedRatio === void 0) { speedRatio = 1.0; }
-            this.target = target;
-            this.fromFrame = fromFrame;
-            this.toFrame = toFrame;
-            this.loopAnimation = loopAnimation;
-            this.speedRatio = speedRatio;
-            this.onAnimationEnd = onAnimationEnd;
-            this._animations = new Array();
-            this._paused = false;
-            this.animationStarted = false;
-            if (animations) {
-                this.appendAnimations(target, animations);
-            }
-            this._scene = scene;
-            scene._activeAnimatables.push(this);
-        }
-        // Methods
-        Animatable.prototype.getAnimations = function () {
-            return this._animations;
-        };
-        Animatable.prototype.appendAnimations = function (target, animations) {
-            for (var index = 0; index < animations.length; index++) {
-                var animation = animations[index];
-                animation._target = target;
-                this._animations.push(animation);
-            }
-        };
-        Animatable.prototype.getAnimationByTargetProperty = function (property) {
-            var animations = this._animations;
-            for (var index = 0; index < animations.length; index++) {
-                if (animations[index].targetProperty === property) {
-                    return animations[index];
-                }
-            }
-            return null;
-        };
-        Animatable.prototype.reset = function () {
-            var animations = this._animations;
-            for (var index = 0; index < animations.length; index++) {
-                animations[index].reset();
-            }
-            this._localDelayOffset = null;
-            this._pausedDelay = null;
-        };
-        Animatable.prototype.goToFrame = function (frame) {
-            var animations = this._animations;
-            for (var index = 0; index < animations.length; index++) {
-                animations[index].goToFrame(frame);
-            }
-        };
-        Animatable.prototype.pause = function () {
-            if (this._paused) {
-                return;
-            }
-            this._paused = true;
-        };
-        Animatable.prototype.restart = function () {
-            this._paused = false;
-        };
-        Animatable.prototype.stop = function () {
-            var index = this._scene._activeAnimatables.indexOf(this);
-            if (index > -1) {
-                this._scene._activeAnimatables.splice(index, 1);
-            }
-            if (this.onAnimationEnd) {
-                this.onAnimationEnd();
-            }
-        };
-        Animatable.prototype._animate = function (delay) {
-            if (this._paused) {
-                this.animationStarted = false;
-                if (!this._pausedDelay) {
-                    this._pausedDelay = delay;
-                }
-                return true;
-            }
-            if (!this._localDelayOffset) {
-                this._localDelayOffset = delay;
-            }
-            else if (this._pausedDelay) {
-                this._localDelayOffset += delay - this._pausedDelay;
-                this._pausedDelay = null;
-            }
-            // Animating
-            var running = false;
-            var animations = this._animations;
-            var index;
-            for (index = 0; index < animations.length; index++) {
-                var animation = animations[index];
-                var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
-                running = running || isRunning;
-            }
-            this.animationStarted = running;
-            if (!running) {
-                // Remove from active animatables
-                index = this._scene._activeAnimatables.indexOf(this);
-                this._scene._activeAnimatables.splice(index, 1);
-            }
-            if (!running && this.onAnimationEnd) {
-                this.onAnimationEnd();
-            }
-            return running;
-        };
-        return Animatable;
-    })();
-    BABYLON.Animatable = Animatable;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var Animatable = (function () {
+        function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
+            if (fromFrame === void 0) { fromFrame = 0; }
+            if (toFrame === void 0) { toFrame = 100; }
+            if (loopAnimation === void 0) { loopAnimation = false; }
+            if (speedRatio === void 0) { speedRatio = 1.0; }
+            this.target = target;
+            this.fromFrame = fromFrame;
+            this.toFrame = toFrame;
+            this.loopAnimation = loopAnimation;
+            this.speedRatio = speedRatio;
+            this.onAnimationEnd = onAnimationEnd;
+            this._animations = new Array();
+            this._paused = false;
+            this.animationStarted = false;
+            if (animations) {
+                this.appendAnimations(target, animations);
+            }
+            this._scene = scene;
+            scene._activeAnimatables.push(this);
+        }
+        // Methods
+        Animatable.prototype.getAnimations = function () {
+            return this._animations;
+        };
+        Animatable.prototype.appendAnimations = function (target, animations) {
+            for (var index = 0; index < animations.length; index++) {
+                var animation = animations[index];
+                animation._target = target;
+                this._animations.push(animation);
+            }
+        };
+        Animatable.prototype.getAnimationByTargetProperty = function (property) {
+            var animations = this._animations;
+            for (var index = 0; index < animations.length; index++) {
+                if (animations[index].targetProperty === property) {
+                    return animations[index];
+                }
+            }
+            return null;
+        };
+        Animatable.prototype.reset = function () {
+            var animations = this._animations;
+            for (var index = 0; index < animations.length; index++) {
+                animations[index].reset();
+            }
+            this._localDelayOffset = null;
+            this._pausedDelay = null;
+        };
+        Animatable.prototype.goToFrame = function (frame) {
+            var animations = this._animations;
+            for (var index = 0; index < animations.length; index++) {
+                animations[index].goToFrame(frame);
+            }
+        };
+        Animatable.prototype.pause = function () {
+            if (this._paused) {
+                return;
+            }
+            this._paused = true;
+        };
+        Animatable.prototype.restart = function () {
+            this._paused = false;
+        };
+        Animatable.prototype.stop = function () {
+            var index = this._scene._activeAnimatables.indexOf(this);
+            if (index > -1) {
+                this._scene._activeAnimatables.splice(index, 1);
+            }
+            if (this.onAnimationEnd) {
+                this.onAnimationEnd();
+            }
+        };
+        Animatable.prototype._animate = function (delay) {
+            if (this._paused) {
+                this.animationStarted = false;
+                if (!this._pausedDelay) {
+                    this._pausedDelay = delay;
+                }
+                return true;
+            }
+            if (!this._localDelayOffset) {
+                this._localDelayOffset = delay;
+            }
+            else if (this._pausedDelay) {
+                this._localDelayOffset += delay - this._pausedDelay;
+                this._pausedDelay = null;
+            }
+            // Animating
+            var running = false;
+            var animations = this._animations;
+            var index;
+            for (index = 0; index < animations.length; index++) {
+                var animation = animations[index];
+                var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
+                running = running || isRunning;
+            }
+            this.animationStarted = running;
+            if (!running) {
+                // Remove from active animatables
+                index = this._scene._activeAnimatables.indexOf(this);
+                this._scene._activeAnimatables.splice(index, 1);
+            }
+            if (!running && this.onAnimationEnd) {
+                this.onAnimationEnd();
+            }
+            return running;
+        };
+        return Animatable;
+    })();
+    BABYLON.Animatable = Animatable;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.animatable.js.map

File diff suppressed because it is too large
+ 583 - 582
src/Animations/babylon.animation.js


+ 250 - 249
src/Animations/babylon.easing.js

@@ -1,249 +1,250 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var EasingFunction = (function () {
-        function EasingFunction() {
-            // Properties
-            this._easingMode = EasingFunction.EASINGMODE_EASEIN;
-        }
-        Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
-            get: function () {
-                return EasingFunction._EASINGMODE_EASEIN;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
-            get: function () {
-                return EasingFunction._EASINGMODE_EASEOUT;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
-            get: function () {
-                return EasingFunction._EASINGMODE_EASEINOUT;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        EasingFunction.prototype.setEasingMode = function (easingMode) {
-            var n = Math.min(Math.max(easingMode, 0), 2);
-            this._easingMode = n;
-        };
-        EasingFunction.prototype.getEasingMode = function () {
-            return this._easingMode;
-        };
-        EasingFunction.prototype.easeInCore = function (gradient) {
-            throw new Error('You must implement this method');
-        };
-        EasingFunction.prototype.ease = function (gradient) {
-            switch (this._easingMode) {
-                case EasingFunction.EASINGMODE_EASEIN:
-                    return this.easeInCore(gradient);
-                case EasingFunction.EASINGMODE_EASEOUT:
-                    return (1 - this.easeInCore(1 - gradient));
-            }
-            if (gradient >= 0.5) {
-                return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
-            }
-            return (this.easeInCore(gradient * 2) * 0.5);
-        };
-        //Statics
-        EasingFunction._EASINGMODE_EASEIN = 0;
-        EasingFunction._EASINGMODE_EASEOUT = 1;
-        EasingFunction._EASINGMODE_EASEINOUT = 2;
-        return EasingFunction;
-    })();
-    BABYLON.EasingFunction = EasingFunction;
-    var CircleEase = (function (_super) {
-        __extends(CircleEase, _super);
-        function CircleEase() {
-            _super.apply(this, arguments);
-        }
-        CircleEase.prototype.easeInCore = function (gradient) {
-            gradient = Math.max(0, Math.min(1, gradient));
-            return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
-        };
-        return CircleEase;
-    })(EasingFunction);
-    BABYLON.CircleEase = CircleEase;
-    var BackEase = (function (_super) {
-        __extends(BackEase, _super);
-        function BackEase(amplitude) {
-            if (amplitude === void 0) { amplitude = 1; }
-            _super.call(this);
-            this.amplitude = amplitude;
-        }
-        BackEase.prototype.easeInCore = function (gradient) {
-            var num = Math.max(0, this.amplitude);
-            return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
-        };
-        return BackEase;
-    })(EasingFunction);
-    BABYLON.BackEase = BackEase;
-    var BounceEase = (function (_super) {
-        __extends(BounceEase, _super);
-        function BounceEase(bounces, bounciness) {
-            if (bounces === void 0) { bounces = 3; }
-            if (bounciness === void 0) { bounciness = 2; }
-            _super.call(this);
-            this.bounces = bounces;
-            this.bounciness = bounciness;
-        }
-        BounceEase.prototype.easeInCore = function (gradient) {
-            var y = Math.max(0.0, this.bounces);
-            var bounciness = this.bounciness;
-            if (bounciness <= 1.0) {
-                bounciness = 1.001;
-            }
-            var num9 = Math.pow(bounciness, y);
-            var num5 = 1.0 - bounciness;
-            var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
-            var num15 = gradient * num4;
-            var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
-            var num3 = Math.floor(num65);
-            var num13 = num3 + 1.0;
-            var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
-            var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
-            var num7 = (num8 + num12) * 0.5;
-            var num6 = gradient - num7;
-            var num2 = num7 - num8;
-            return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
-        };
-        return BounceEase;
-    })(EasingFunction);
-    BABYLON.BounceEase = BounceEase;
-    var CubicEase = (function (_super) {
-        __extends(CubicEase, _super);
-        function CubicEase() {
-            _super.apply(this, arguments);
-        }
-        CubicEase.prototype.easeInCore = function (gradient) {
-            return (gradient * gradient * gradient);
-        };
-        return CubicEase;
-    })(EasingFunction);
-    BABYLON.CubicEase = CubicEase;
-    var ElasticEase = (function (_super) {
-        __extends(ElasticEase, _super);
-        function ElasticEase(oscillations, springiness) {
-            if (oscillations === void 0) { oscillations = 3; }
-            if (springiness === void 0) { springiness = 3; }
-            _super.call(this);
-            this.oscillations = oscillations;
-            this.springiness = springiness;
-        }
-        ElasticEase.prototype.easeInCore = function (gradient) {
-            var num2;
-            var num3 = Math.max(0.0, this.oscillations);
-            var num = Math.max(0.0, this.springiness);
-            if (num == 0) {
-                num2 = gradient;
-            }
-            else {
-                num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
-            }
-            return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
-        };
-        return ElasticEase;
-    })(EasingFunction);
-    BABYLON.ElasticEase = ElasticEase;
-    var ExponentialEase = (function (_super) {
-        __extends(ExponentialEase, _super);
-        function ExponentialEase(exponent) {
-            if (exponent === void 0) { exponent = 2; }
-            _super.call(this);
-            this.exponent = exponent;
-        }
-        ExponentialEase.prototype.easeInCore = function (gradient) {
-            if (this.exponent <= 0) {
-                return gradient;
-            }
-            return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
-        };
-        return ExponentialEase;
-    })(EasingFunction);
-    BABYLON.ExponentialEase = ExponentialEase;
-    var PowerEase = (function (_super) {
-        __extends(PowerEase, _super);
-        function PowerEase(power) {
-            if (power === void 0) { power = 2; }
-            _super.call(this);
-            this.power = power;
-        }
-        PowerEase.prototype.easeInCore = function (gradient) {
-            var y = Math.max(0.0, this.power);
-            return Math.pow(gradient, y);
-        };
-        return PowerEase;
-    })(EasingFunction);
-    BABYLON.PowerEase = PowerEase;
-    var QuadraticEase = (function (_super) {
-        __extends(QuadraticEase, _super);
-        function QuadraticEase() {
-            _super.apply(this, arguments);
-        }
-        QuadraticEase.prototype.easeInCore = function (gradient) {
-            return (gradient * gradient);
-        };
-        return QuadraticEase;
-    })(EasingFunction);
-    BABYLON.QuadraticEase = QuadraticEase;
-    var QuarticEase = (function (_super) {
-        __extends(QuarticEase, _super);
-        function QuarticEase() {
-            _super.apply(this, arguments);
-        }
-        QuarticEase.prototype.easeInCore = function (gradient) {
-            return (gradient * gradient * gradient * gradient);
-        };
-        return QuarticEase;
-    })(EasingFunction);
-    BABYLON.QuarticEase = QuarticEase;
-    var QuinticEase = (function (_super) {
-        __extends(QuinticEase, _super);
-        function QuinticEase() {
-            _super.apply(this, arguments);
-        }
-        QuinticEase.prototype.easeInCore = function (gradient) {
-            return (gradient * gradient * gradient * gradient * gradient);
-        };
-        return QuinticEase;
-    })(EasingFunction);
-    BABYLON.QuinticEase = QuinticEase;
-    var SineEase = (function (_super) {
-        __extends(SineEase, _super);
-        function SineEase() {
-            _super.apply(this, arguments);
-        }
-        SineEase.prototype.easeInCore = function (gradient) {
-            return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
-        };
-        return SineEase;
-    })(EasingFunction);
-    BABYLON.SineEase = SineEase;
-    var BezierCurveEase = (function (_super) {
-        __extends(BezierCurveEase, _super);
-        function BezierCurveEase(x1, y1, x2, y2) {
-            if (x1 === void 0) { x1 = 0; }
-            if (y1 === void 0) { y1 = 0; }
-            if (x2 === void 0) { x2 = 1; }
-            if (y2 === void 0) { y2 = 1; }
-            _super.call(this);
-            this.x1 = x1;
-            this.y1 = y1;
-            this.x2 = x2;
-            this.y2 = y2;
-        }
-        BezierCurveEase.prototype.easeInCore = function (gradient) {
-            return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
-        };
-        return BezierCurveEase;
-    })(EasingFunction);
-    BABYLON.BezierCurveEase = BezierCurveEase;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var EasingFunction = (function () {
+        function EasingFunction() {
+            // Properties
+            this._easingMode = EasingFunction.EASINGMODE_EASEIN;
+        }
+        Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
+            get: function () {
+                return EasingFunction._EASINGMODE_EASEIN;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
+            get: function () {
+                return EasingFunction._EASINGMODE_EASEOUT;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
+            get: function () {
+                return EasingFunction._EASINGMODE_EASEINOUT;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        EasingFunction.prototype.setEasingMode = function (easingMode) {
+            var n = Math.min(Math.max(easingMode, 0), 2);
+            this._easingMode = n;
+        };
+        EasingFunction.prototype.getEasingMode = function () {
+            return this._easingMode;
+        };
+        EasingFunction.prototype.easeInCore = function (gradient) {
+            throw new Error('You must implement this method');
+        };
+        EasingFunction.prototype.ease = function (gradient) {
+            switch (this._easingMode) {
+                case EasingFunction.EASINGMODE_EASEIN:
+                    return this.easeInCore(gradient);
+                case EasingFunction.EASINGMODE_EASEOUT:
+                    return (1 - this.easeInCore(1 - gradient));
+            }
+            if (gradient >= 0.5) {
+                return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
+            }
+            return (this.easeInCore(gradient * 2) * 0.5);
+        };
+        //Statics
+        EasingFunction._EASINGMODE_EASEIN = 0;
+        EasingFunction._EASINGMODE_EASEOUT = 1;
+        EasingFunction._EASINGMODE_EASEINOUT = 2;
+        return EasingFunction;
+    })();
+    BABYLON.EasingFunction = EasingFunction;
+    var CircleEase = (function (_super) {
+        __extends(CircleEase, _super);
+        function CircleEase() {
+            _super.apply(this, arguments);
+        }
+        CircleEase.prototype.easeInCore = function (gradient) {
+            gradient = Math.max(0, Math.min(1, gradient));
+            return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
+        };
+        return CircleEase;
+    })(EasingFunction);
+    BABYLON.CircleEase = CircleEase;
+    var BackEase = (function (_super) {
+        __extends(BackEase, _super);
+        function BackEase(amplitude) {
+            if (amplitude === void 0) { amplitude = 1; }
+            _super.call(this);
+            this.amplitude = amplitude;
+        }
+        BackEase.prototype.easeInCore = function (gradient) {
+            var num = Math.max(0, this.amplitude);
+            return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
+        };
+        return BackEase;
+    })(EasingFunction);
+    BABYLON.BackEase = BackEase;
+    var BounceEase = (function (_super) {
+        __extends(BounceEase, _super);
+        function BounceEase(bounces, bounciness) {
+            if (bounces === void 0) { bounces = 3; }
+            if (bounciness === void 0) { bounciness = 2; }
+            _super.call(this);
+            this.bounces = bounces;
+            this.bounciness = bounciness;
+        }
+        BounceEase.prototype.easeInCore = function (gradient) {
+            var y = Math.max(0.0, this.bounces);
+            var bounciness = this.bounciness;
+            if (bounciness <= 1.0) {
+                bounciness = 1.001;
+            }
+            var num9 = Math.pow(bounciness, y);
+            var num5 = 1.0 - bounciness;
+            var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
+            var num15 = gradient * num4;
+            var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
+            var num3 = Math.floor(num65);
+            var num13 = num3 + 1.0;
+            var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
+            var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
+            var num7 = (num8 + num12) * 0.5;
+            var num6 = gradient - num7;
+            var num2 = num7 - num8;
+            return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
+        };
+        return BounceEase;
+    })(EasingFunction);
+    BABYLON.BounceEase = BounceEase;
+    var CubicEase = (function (_super) {
+        __extends(CubicEase, _super);
+        function CubicEase() {
+            _super.apply(this, arguments);
+        }
+        CubicEase.prototype.easeInCore = function (gradient) {
+            return (gradient * gradient * gradient);
+        };
+        return CubicEase;
+    })(EasingFunction);
+    BABYLON.CubicEase = CubicEase;
+    var ElasticEase = (function (_super) {
+        __extends(ElasticEase, _super);
+        function ElasticEase(oscillations, springiness) {
+            if (oscillations === void 0) { oscillations = 3; }
+            if (springiness === void 0) { springiness = 3; }
+            _super.call(this);
+            this.oscillations = oscillations;
+            this.springiness = springiness;
+        }
+        ElasticEase.prototype.easeInCore = function (gradient) {
+            var num2;
+            var num3 = Math.max(0.0, this.oscillations);
+            var num = Math.max(0.0, this.springiness);
+            if (num == 0) {
+                num2 = gradient;
+            }
+            else {
+                num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
+            }
+            return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
+        };
+        return ElasticEase;
+    })(EasingFunction);
+    BABYLON.ElasticEase = ElasticEase;
+    var ExponentialEase = (function (_super) {
+        __extends(ExponentialEase, _super);
+        function ExponentialEase(exponent) {
+            if (exponent === void 0) { exponent = 2; }
+            _super.call(this);
+            this.exponent = exponent;
+        }
+        ExponentialEase.prototype.easeInCore = function (gradient) {
+            if (this.exponent <= 0) {
+                return gradient;
+            }
+            return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
+        };
+        return ExponentialEase;
+    })(EasingFunction);
+    BABYLON.ExponentialEase = ExponentialEase;
+    var PowerEase = (function (_super) {
+        __extends(PowerEase, _super);
+        function PowerEase(power) {
+            if (power === void 0) { power = 2; }
+            _super.call(this);
+            this.power = power;
+        }
+        PowerEase.prototype.easeInCore = function (gradient) {
+            var y = Math.max(0.0, this.power);
+            return Math.pow(gradient, y);
+        };
+        return PowerEase;
+    })(EasingFunction);
+    BABYLON.PowerEase = PowerEase;
+    var QuadraticEase = (function (_super) {
+        __extends(QuadraticEase, _super);
+        function QuadraticEase() {
+            _super.apply(this, arguments);
+        }
+        QuadraticEase.prototype.easeInCore = function (gradient) {
+            return (gradient * gradient);
+        };
+        return QuadraticEase;
+    })(EasingFunction);
+    BABYLON.QuadraticEase = QuadraticEase;
+    var QuarticEase = (function (_super) {
+        __extends(QuarticEase, _super);
+        function QuarticEase() {
+            _super.apply(this, arguments);
+        }
+        QuarticEase.prototype.easeInCore = function (gradient) {
+            return (gradient * gradient * gradient * gradient);
+        };
+        return QuarticEase;
+    })(EasingFunction);
+    BABYLON.QuarticEase = QuarticEase;
+    var QuinticEase = (function (_super) {
+        __extends(QuinticEase, _super);
+        function QuinticEase() {
+            _super.apply(this, arguments);
+        }
+        QuinticEase.prototype.easeInCore = function (gradient) {
+            return (gradient * gradient * gradient * gradient * gradient);
+        };
+        return QuinticEase;
+    })(EasingFunction);
+    BABYLON.QuinticEase = QuinticEase;
+    var SineEase = (function (_super) {
+        __extends(SineEase, _super);
+        function SineEase() {
+            _super.apply(this, arguments);
+        }
+        SineEase.prototype.easeInCore = function (gradient) {
+            return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
+        };
+        return SineEase;
+    })(EasingFunction);
+    BABYLON.SineEase = SineEase;
+    var BezierCurveEase = (function (_super) {
+        __extends(BezierCurveEase, _super);
+        function BezierCurveEase(x1, y1, x2, y2) {
+            if (x1 === void 0) { x1 = 0; }
+            if (y1 === void 0) { y1 = 0; }
+            if (x2 === void 0) { x2 = 1; }
+            if (y2 === void 0) { y2 = 1; }
+            _super.call(this);
+            this.x1 = x1;
+            this.y1 = y1;
+            this.x2 = x2;
+            this.y2 = y2;
+        }
+        BezierCurveEase.prototype.easeInCore = function (gradient) {
+            return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
+        };
+        return BezierCurveEase;
+    })(EasingFunction);
+    BABYLON.BezierCurveEase = BezierCurveEase;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.easing.js.map

+ 112 - 111
src/Audio/babylon.analyser.js

@@ -1,111 +1,112 @@
-var BABYLON;
-(function (BABYLON) {
-    var Analyser = (function () {
-        function Analyser(scene) {
-            this.SMOOTHING = 0.75;
-            this.FFT_SIZE = 512;
-            this.BARGRAPHAMPLITUDE = 256;
-            this.DEBUGCANVASPOS = { x: 20, y: 20 };
-            this.DEBUGCANVASSIZE = { width: 320, height: 200 };
-            this._scene = scene;
-            this._audioEngine = BABYLON.Engine.audioEngine;
-            if (this._audioEngine.canUseWebAudio) {
-                this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
-                this._webAudioAnalyser.minDecibels = -140;
-                this._webAudioAnalyser.maxDecibels = 0;
-                this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
-                this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
-                this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
-            }
-        }
-        Analyser.prototype.getFrequencyBinCount = function () {
-            if (this._audioEngine.canUseWebAudio) {
-                return this._webAudioAnalyser.frequencyBinCount;
-            }
-            else {
-                return 0;
-            }
-        };
-        Analyser.prototype.getByteFrequencyData = function () {
-            if (this._audioEngine.canUseWebAudio) {
-                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
-                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
-                this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
-            }
-            return this._byteFreqs;
-        };
-        Analyser.prototype.getByteTimeDomainData = function () {
-            if (this._audioEngine.canUseWebAudio) {
-                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
-                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
-                this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
-            }
-            return this._byteTime;
-        };
-        Analyser.prototype.getFloatFrequencyData = function () {
-            if (this._audioEngine.canUseWebAudio) {
-                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
-                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
-                this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
-            }
-            return this._floatFreqs;
-        };
-        Analyser.prototype.drawDebugCanvas = function () {
-            var _this = this;
-            if (this._audioEngine.canUseWebAudio) {
-                if (!this._debugCanvas) {
-                    this._debugCanvas = document.createElement("canvas");
-                    this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
-                    this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
-                    this._debugCanvas.style.position = "absolute";
-                    this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
-                    this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
-                    this._debugCanvasContext = this._debugCanvas.getContext("2d");
-                    document.body.appendChild(this._debugCanvas);
-                    this._registerFunc = function () {
-                        _this.drawDebugCanvas();
-                    };
-                    this._scene.registerBeforeRender(this._registerFunc);
-                }
-                if (this._registerFunc) {
-                    var workingArray = this.getByteFrequencyData();
-                    this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
-                    this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
-                    // Draw the frequency domain chart.
-                    for (var i = 0; i < this.getFrequencyBinCount(); i++) {
-                        var value = workingArray[i];
-                        var percent = value / this.BARGRAPHAMPLITUDE;
-                        var height = this.DEBUGCANVASSIZE.height * percent;
-                        var offset = this.DEBUGCANVASSIZE.height - height - 1;
-                        var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
-                        var hue = i / this.getFrequencyBinCount() * 360;
-                        this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
-                        this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
-                    }
-                }
-            }
-        };
-        Analyser.prototype.stopDebugCanvas = function () {
-            if (this._debugCanvas) {
-                this._scene.unregisterBeforeRender(this._registerFunc);
-                this._registerFunc = null;
-                document.body.removeChild(this._debugCanvas);
-                this._debugCanvas = null;
-                this._debugCanvasContext = null;
-            }
-        };
-        Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
-            if (this._audioEngine.canUseWebAudio) {
-                inputAudioNode.connect(this._webAudioAnalyser);
-                this._webAudioAnalyser.connect(outputAudioNode);
-            }
-        };
-        Analyser.prototype.dispose = function () {
-            if (this._audioEngine.canUseWebAudio) {
-                this._webAudioAnalyser.disconnect();
-            }
-        };
-        return Analyser;
-    })();
-    BABYLON.Analyser = Analyser;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var Analyser = (function () {
+        function Analyser(scene) {
+            this.SMOOTHING = 0.75;
+            this.FFT_SIZE = 512;
+            this.BARGRAPHAMPLITUDE = 256;
+            this.DEBUGCANVASPOS = { x: 20, y: 20 };
+            this.DEBUGCANVASSIZE = { width: 320, height: 200 };
+            this._scene = scene;
+            this._audioEngine = BABYLON.Engine.audioEngine;
+            if (this._audioEngine.canUseWebAudio) {
+                this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
+                this._webAudioAnalyser.minDecibels = -140;
+                this._webAudioAnalyser.maxDecibels = 0;
+                this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
+                this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
+                this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
+            }
+        }
+        Analyser.prototype.getFrequencyBinCount = function () {
+            if (this._audioEngine.canUseWebAudio) {
+                return this._webAudioAnalyser.frequencyBinCount;
+            }
+            else {
+                return 0;
+            }
+        };
+        Analyser.prototype.getByteFrequencyData = function () {
+            if (this._audioEngine.canUseWebAudio) {
+                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
+                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
+                this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
+            }
+            return this._byteFreqs;
+        };
+        Analyser.prototype.getByteTimeDomainData = function () {
+            if (this._audioEngine.canUseWebAudio) {
+                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
+                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
+                this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
+            }
+            return this._byteTime;
+        };
+        Analyser.prototype.getFloatFrequencyData = function () {
+            if (this._audioEngine.canUseWebAudio) {
+                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
+                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
+                this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
+            }
+            return this._floatFreqs;
+        };
+        Analyser.prototype.drawDebugCanvas = function () {
+            var _this = this;
+            if (this._audioEngine.canUseWebAudio) {
+                if (!this._debugCanvas) {
+                    this._debugCanvas = document.createElement("canvas");
+                    this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
+                    this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
+                    this._debugCanvas.style.position = "absolute";
+                    this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
+                    this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
+                    this._debugCanvasContext = this._debugCanvas.getContext("2d");
+                    document.body.appendChild(this._debugCanvas);
+                    this._registerFunc = function () {
+                        _this.drawDebugCanvas();
+                    };
+                    this._scene.registerBeforeRender(this._registerFunc);
+                }
+                if (this._registerFunc) {
+                    var workingArray = this.getByteFrequencyData();
+                    this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
+                    this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
+                    // Draw the frequency domain chart.
+                    for (var i = 0; i < this.getFrequencyBinCount(); i++) {
+                        var value = workingArray[i];
+                        var percent = value / this.BARGRAPHAMPLITUDE;
+                        var height = this.DEBUGCANVASSIZE.height * percent;
+                        var offset = this.DEBUGCANVASSIZE.height - height - 1;
+                        var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
+                        var hue = i / this.getFrequencyBinCount() * 360;
+                        this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
+                        this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
+                    }
+                }
+            }
+        };
+        Analyser.prototype.stopDebugCanvas = function () {
+            if (this._debugCanvas) {
+                this._scene.unregisterBeforeRender(this._registerFunc);
+                this._registerFunc = null;
+                document.body.removeChild(this._debugCanvas);
+                this._debugCanvas = null;
+                this._debugCanvasContext = null;
+            }
+        };
+        Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
+            if (this._audioEngine.canUseWebAudio) {
+                inputAudioNode.connect(this._webAudioAnalyser);
+                this._webAudioAnalyser.connect(outputAudioNode);
+            }
+        };
+        Analyser.prototype.dispose = function () {
+            if (this._audioEngine.canUseWebAudio) {
+                this._webAudioAnalyser.disconnect();
+            }
+        };
+        return Analyser;
+    })();
+    BABYLON.Analyser = Analyser;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.analyser.js.map

+ 107 - 79
src/Audio/babylon.audioEngine.js

@@ -1,79 +1,107 @@
-var BABYLON;
-(function (BABYLON) {
-    var AudioEngine = (function () {
-        function AudioEngine() {
-            this._audioContext = null;
-            this._audioContextInitialized = false;
-            this.canUseWebAudio = false;
-            this.WarnedWebAudioUnsupported = false;
-            if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
-                window.AudioContext = window.AudioContext || window.webkitAudioContext;
-                this.canUseWebAudio = true;
-            }
-        }
-        Object.defineProperty(AudioEngine.prototype, "audioContext", {
-            get: function () {
-                if (!this._audioContextInitialized) {
-                    this._initializeAudioContext();
-                }
-                return this._audioContext;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        AudioEngine.prototype._initializeAudioContext = function () {
-            try {
-                if (this.canUseWebAudio) {
-                    this._audioContext = new AudioContext();
-                    // create a global volume gain node 
-                    this.masterGain = this._audioContext.createGain();
-                    this.masterGain.gain.value = 1;
-                    this.masterGain.connect(this._audioContext.destination);
-                    this._audioContextInitialized = true;
-                }
-            }
-            catch (e) {
-                this.canUseWebAudio = false;
-                BABYLON.Tools.Error("Web Audio: " + e.message);
-            }
-        };
-        AudioEngine.prototype.dispose = function () {
-            if (this.canUseWebAudio && this._audioContextInitialized) {
-                if (this._connectedAnalyser) {
-                    this._connectedAnalyser.stopDebugCanvas();
-                    this._connectedAnalyser.dispose();
-                    this.masterGain.disconnect();
-                    this.masterGain.connect(this._audioContext.destination);
-                    this._connectedAnalyser = null;
-                }
-                this.masterGain.gain.value = 1;
-            }
-            this.WarnedWebAudioUnsupported = false;
-        };
-        AudioEngine.prototype.getGlobalVolume = function () {
-            if (this.canUseWebAudio && this._audioContextInitialized) {
-                return this.masterGain.gain.value;
-            }
-            else {
-                return -1;
-            }
-        };
-        AudioEngine.prototype.setGlobalVolume = function (newVolume) {
-            if (this.canUseWebAudio && this._audioContextInitialized) {
-                this.masterGain.gain.value = newVolume;
-            }
-        };
-        AudioEngine.prototype.connectToAnalyser = function (analyser) {
-            if (this._connectedAnalyser) {
-                this._connectedAnalyser.stopDebugCanvas();
-            }
-            if (this.canUseWebAudio && this._audioContextInitialized) {
-                this._connectedAnalyser = analyser;
-                this.masterGain.disconnect();
-                this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
-            }
-        };
-        return AudioEngine;
-    })();
-    BABYLON.AudioEngine = AudioEngine;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var AudioEngine = (function () {
+        function AudioEngine() {
+            this._audioContext = null;
+            this._audioContextInitialized = false;
+            this.canUseWebAudio = false;
+            this.WarnedWebAudioUnsupported = false;
+            this.unlocked = false;
+            if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
+                window.AudioContext = window.AudioContext || window.webkitAudioContext;
+                this.canUseWebAudio = true;
+            }
+            if (/iPad|iPhone|iPod/.test(navigator.platform)) {
+                this._unlockiOSaudio();
+            }
+            else {
+                this.unlocked = true;
+            }
+        }
+        Object.defineProperty(AudioEngine.prototype, "audioContext", {
+            get: function () {
+                if (!this._audioContextInitialized) {
+                    this._initializeAudioContext();
+                }
+                return this._audioContext;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        AudioEngine.prototype._unlockiOSaudio = function () {
+            var _this = this;
+            var unlockaudio = function () {
+                var buffer = _this.audioContext.createBuffer(1, 1, 22050);
+                var source = _this.audioContext.createBufferSource();
+                source.buffer = buffer;
+                source.connect(_this.audioContext.destination);
+                source.start(0);
+                setTimeout(function () {
+                    if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
+                        _this.unlocked = true;
+                        window.removeEventListener('touchend', unlockaudio, false);
+                        if (_this.onAudioUnlocked) {
+                            _this.onAudioUnlocked();
+                        }
+                    }
+                }, 0);
+            };
+            window.addEventListener('touchend', unlockaudio, false);
+        };
+        AudioEngine.prototype._initializeAudioContext = function () {
+            try {
+                if (this.canUseWebAudio) {
+                    this._audioContext = new AudioContext();
+                    // create a global volume gain node 
+                    this.masterGain = this._audioContext.createGain();
+                    this.masterGain.gain.value = 1;
+                    this.masterGain.connect(this._audioContext.destination);
+                    this._audioContextInitialized = true;
+                }
+            }
+            catch (e) {
+                this.canUseWebAudio = false;
+                BABYLON.Tools.Error("Web Audio: " + e.message);
+            }
+        };
+        AudioEngine.prototype.dispose = function () {
+            if (this.canUseWebAudio && this._audioContextInitialized) {
+                if (this._connectedAnalyser) {
+                    this._connectedAnalyser.stopDebugCanvas();
+                    this._connectedAnalyser.dispose();
+                    this.masterGain.disconnect();
+                    this.masterGain.connect(this._audioContext.destination);
+                    this._connectedAnalyser = null;
+                }
+                this.masterGain.gain.value = 1;
+            }
+            this.WarnedWebAudioUnsupported = false;
+        };
+        AudioEngine.prototype.getGlobalVolume = function () {
+            if (this.canUseWebAudio && this._audioContextInitialized) {
+                return this.masterGain.gain.value;
+            }
+            else {
+                return -1;
+            }
+        };
+        AudioEngine.prototype.setGlobalVolume = function (newVolume) {
+            if (this.canUseWebAudio && this._audioContextInitialized) {
+                this.masterGain.gain.value = newVolume;
+            }
+        };
+        AudioEngine.prototype.connectToAnalyser = function (analyser) {
+            if (this._connectedAnalyser) {
+                this._connectedAnalyser.stopDebugCanvas();
+            }
+            if (this.canUseWebAudio && this._audioContextInitialized) {
+                this._connectedAnalyser = analyser;
+                this.masterGain.disconnect();
+                this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
+            }
+        };
+        return AudioEngine;
+    })();
+    BABYLON.AudioEngine = AudioEngine;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.audioEngine.js.map

+ 31 - 0
src/Audio/babylon.audioEngine.ts

@@ -7,6 +7,8 @@
 
         private _connectedAnalyser: Analyser;
         public WarnedWebAudioUnsupported: boolean = false;
+        public unlocked: boolean = false;
+        public onAudioUnlocked: () => any;
 
         public get audioContext(): AudioContext {
             if (!this._audioContextInitialized) {
@@ -20,6 +22,35 @@
                 window.AudioContext = window.AudioContext || window.webkitAudioContext;
                 this.canUseWebAudio = true;
             }
+
+            if (/iPad|iPhone|iPod/.test(navigator.platform)) {
+                this._unlockiOSaudio();
+            }
+            else {
+                this.unlocked = true;
+            }
+        }
+
+        private _unlockiOSaudio() {
+            var unlockaudio = () => {
+                var buffer = this.audioContext.createBuffer(1, 1, 22050);
+                var source = this.audioContext.createBufferSource();
+                source.buffer = buffer;
+                source.connect(this.audioContext.destination);
+                source.start(0);
+  
+                setTimeout(() => {
+                    if (((<any>source).playbackState === (<any>source).PLAYING_STATE || (<any>source).playbackState === (<any>source).FINISHED_STATE)) { 
+                        this.unlocked = true;
+                        window.removeEventListener('touchend', unlockaudio, false);
+                        if (this.onAudioUnlocked) {
+                            this.onAudioUnlocked();
+                        }
+                    }
+                }, 0);
+            };
+
+            window.addEventListener('touchend', unlockaudio, false);
         }
 
         private _initializeAudioContext() {

File diff suppressed because it is too large
+ 554 - 546
src/Audio/babylon.sound.js


+ 21 - 12
src/Audio/babylon.sound.ts

@@ -100,20 +100,21 @@
                         }
                         // Streaming sound using HTML5 Audio tag
                         else {
-                            this._htmlAudioElement = new Audio();
-                            this._htmlAudioElement.src = urlOrArrayBuffer;
+                            this._htmlAudioElement = new Audio(urlOrArrayBuffer);
                             this._htmlAudioElement.controls = false;
                             this._htmlAudioElement.loop = this.loop;
                             this._htmlAudioElement.crossOrigin = "anonymous";
-                            this._isReadyToPlay = true;
-                            document.body.appendChild(this._htmlAudioElement);
-                            // Simulating a ready to play event for consistent behavior with non streamed audio source
-                            if (this._readyToPlayCallback) {
-                                window.setTimeout(() => {
+                            this._htmlAudioElement.preload = "auto";
+                            this._htmlAudioElement.addEventListener("canplaythrough", () => {
+                                this._isReadyToPlay = true;
+                                if (this.autoplay) {
+                                    this.play();
+                                }
+                                if (this._readyToPlayCallback) {
                                     this._readyToPlayCallback();
-                                }, 1000);
-                            }
-                            if (this.autoplay) { this.play(); }
+                                }
+                            });
+                            document.body.appendChild(this._htmlAudioElement);
                         }
                     }
                     else {
@@ -376,7 +377,12 @@
                         this._soundSource.loop = this.loop;
                         this._soundSource.playbackRate.value = this._playbackRate;
                         this._soundSource.onended = () => { this._onended(); };
-                        this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
+                        if (!this.isPaused) {
+                            this._soundSource.start(startTime);
+                        }
+                        else {
+                            this._soundSource.start(0, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
+                        }
                     }
                     this._startTime = startTime;
                     this.isPlaying = true;
@@ -411,6 +417,9 @@
                 else {
                     var stopTime = time ? Engine.audioEngine.audioContext.currentTime + time : Engine.audioEngine.audioContext.currentTime;
                     this._soundSource.stop(stopTime);
+                    if (!this.isPaused) {
+                        this._startOffset = 0;
+                    }
                 }
                 this.isPlaying = false;
             }
@@ -418,6 +427,7 @@
 
         public pause() {
             if (this.isPlaying) {
+                this.isPaused = true;
                 if (this._streaming) {
                     this._htmlAudioElement.pause();
                 }
@@ -425,7 +435,6 @@
                     this.stop(0);
                     this._startOffset += Engine.audioEngine.audioContext.currentTime - this._startTime;
                 }
-                this.isPaused = true;
             }
         }
 

+ 102 - 101
src/Audio/babylon.soundtrack.js

@@ -1,101 +1,102 @@
-var BABYLON;
-(function (BABYLON) {
-    var SoundTrack = (function () {
-        function SoundTrack(scene, options) {
-            this.id = -1;
-            this._isMainTrack = false;
-            this._isInitialized = false;
-            this._scene = scene;
-            this.soundCollection = new Array();
-            this._options = options;
-            if (!this._isMainTrack) {
-                this._scene.soundTracks.push(this);
-                this.id = this._scene.soundTracks.length - 1;
-            }
-        }
-        SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
-            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
-                this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
-                if (this._options) {
-                    if (this._options.volume) {
-                        this._outputAudioNode.gain.value = this._options.volume;
-                    }
-                    if (this._options.mainTrack) {
-                        this._isMainTrack = this._options.mainTrack;
-                    }
-                }
-                this._isInitialized = true;
-            }
-        };
-        SoundTrack.prototype.dispose = function () {
-            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                if (this._connectedAnalyser) {
-                    this._connectedAnalyser.stopDebugCanvas();
-                }
-                while (this.soundCollection.length) {
-                    this.soundCollection[0].dispose();
-                }
-                if (this._outputAudioNode) {
-                    this._outputAudioNode.disconnect();
-                }
-                this._outputAudioNode = null;
-            }
-        };
-        SoundTrack.prototype.AddSound = function (sound) {
-            if (!this._isInitialized) {
-                this._initializeSoundTrackAudioGraph();
-            }
-            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                sound.connectToSoundTrackAudioNode(this._outputAudioNode);
-            }
-            if (sound.soundTrackId) {
-                if (sound.soundTrackId === -1) {
-                    this._scene.mainSoundTrack.RemoveSound(sound);
-                }
-                else {
-                    this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
-                }
-            }
-            this.soundCollection.push(sound);
-            sound.soundTrackId = this.id;
-        };
-        SoundTrack.prototype.RemoveSound = function (sound) {
-            var index = this.soundCollection.indexOf(sound);
-            if (index !== -1) {
-                this.soundCollection.splice(index, 1);
-            }
-        };
-        SoundTrack.prototype.setVolume = function (newVolume) {
-            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                this._outputAudioNode.gain.value = newVolume;
-            }
-        };
-        SoundTrack.prototype.switchPanningModelToHRTF = function () {
-            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                for (var i = 0; i < this.soundCollection.length; i++) {
-                    this.soundCollection[i].switchPanningModelToHRTF();
-                }
-            }
-        };
-        SoundTrack.prototype.switchPanningModelToEqualPower = function () {
-            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                for (var i = 0; i < this.soundCollection.length; i++) {
-                    this.soundCollection[i].switchPanningModelToEqualPower();
-                }
-            }
-        };
-        SoundTrack.prototype.connectToAnalyser = function (analyser) {
-            if (this._connectedAnalyser) {
-                this._connectedAnalyser.stopDebugCanvas();
-            }
-            this._connectedAnalyser = analyser;
-            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                this._outputAudioNode.disconnect();
-                this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
-            }
-        };
-        return SoundTrack;
-    })();
-    BABYLON.SoundTrack = SoundTrack;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var SoundTrack = (function () {
+        function SoundTrack(scene, options) {
+            this.id = -1;
+            this._isMainTrack = false;
+            this._isInitialized = false;
+            this._scene = scene;
+            this.soundCollection = new Array();
+            this._options = options;
+            if (!this._isMainTrack) {
+                this._scene.soundTracks.push(this);
+                this.id = this._scene.soundTracks.length - 1;
+            }
+        }
+        SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
+            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
+                this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
+                if (this._options) {
+                    if (this._options.volume) {
+                        this._outputAudioNode.gain.value = this._options.volume;
+                    }
+                    if (this._options.mainTrack) {
+                        this._isMainTrack = this._options.mainTrack;
+                    }
+                }
+                this._isInitialized = true;
+            }
+        };
+        SoundTrack.prototype.dispose = function () {
+            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                if (this._connectedAnalyser) {
+                    this._connectedAnalyser.stopDebugCanvas();
+                }
+                while (this.soundCollection.length) {
+                    this.soundCollection[0].dispose();
+                }
+                if (this._outputAudioNode) {
+                    this._outputAudioNode.disconnect();
+                }
+                this._outputAudioNode = null;
+            }
+        };
+        SoundTrack.prototype.AddSound = function (sound) {
+            if (!this._isInitialized) {
+                this._initializeSoundTrackAudioGraph();
+            }
+            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                sound.connectToSoundTrackAudioNode(this._outputAudioNode);
+            }
+            if (sound.soundTrackId) {
+                if (sound.soundTrackId === -1) {
+                    this._scene.mainSoundTrack.RemoveSound(sound);
+                }
+                else {
+                    this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
+                }
+            }
+            this.soundCollection.push(sound);
+            sound.soundTrackId = this.id;
+        };
+        SoundTrack.prototype.RemoveSound = function (sound) {
+            var index = this.soundCollection.indexOf(sound);
+            if (index !== -1) {
+                this.soundCollection.splice(index, 1);
+            }
+        };
+        SoundTrack.prototype.setVolume = function (newVolume) {
+            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                this._outputAudioNode.gain.value = newVolume;
+            }
+        };
+        SoundTrack.prototype.switchPanningModelToHRTF = function () {
+            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                for (var i = 0; i < this.soundCollection.length; i++) {
+                    this.soundCollection[i].switchPanningModelToHRTF();
+                }
+            }
+        };
+        SoundTrack.prototype.switchPanningModelToEqualPower = function () {
+            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                for (var i = 0; i < this.soundCollection.length; i++) {
+                    this.soundCollection[i].switchPanningModelToEqualPower();
+                }
+            }
+        };
+        SoundTrack.prototype.connectToAnalyser = function (analyser) {
+            if (this._connectedAnalyser) {
+                this._connectedAnalyser.stopDebugCanvas();
+            }
+            this._connectedAnalyser = analyser;
+            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                this._outputAudioNode.disconnect();
+                this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
+            }
+        };
+        return SoundTrack;
+    })();
+    BABYLON.SoundTrack = SoundTrack;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.soundtrack.js.map

+ 128 - 127
src/Bones/babylon.bone.js

@@ -1,127 +1,128 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var Bone = (function (_super) {
-        __extends(Bone, _super);
-        function Bone(name, skeleton, parentBone, matrix, restPose) {
-            _super.call(this, name, skeleton.getScene());
-            this.name = name;
-            this.children = new Array();
-            this.animations = new Array();
-            this._worldTransform = new BABYLON.Matrix();
-            this._absoluteTransform = new BABYLON.Matrix();
-            this._invertedAbsoluteTransform = new BABYLON.Matrix();
-            this._skeleton = skeleton;
-            this._matrix = matrix;
-            this._baseMatrix = matrix;
-            this._restPose = restPose ? restPose : matrix.clone();
-            skeleton.bones.push(this);
-            if (parentBone) {
-                this._parent = parentBone;
-                parentBone.children.push(this);
-            }
-            else {
-                this._parent = null;
-            }
-            this._updateDifferenceMatrix();
-        }
-        // Members
-        Bone.prototype.getParent = function () {
-            return this._parent;
-        };
-        Bone.prototype.getLocalMatrix = function () {
-            return this._matrix;
-        };
-        Bone.prototype.getBaseMatrix = function () {
-            return this._baseMatrix;
-        };
-        Bone.prototype.getRestPose = function () {
-            return this._restPose;
-        };
-        Bone.prototype.returnToRest = function () {
-            this.updateMatrix(this._restPose.clone());
-        };
-        Bone.prototype.getWorldMatrix = function () {
-            return this._worldTransform;
-        };
-        Bone.prototype.getInvertedAbsoluteTransform = function () {
-            return this._invertedAbsoluteTransform;
-        };
-        Bone.prototype.getAbsoluteTransform = function () {
-            return this._absoluteTransform;
-        };
-        // Methods
-        Bone.prototype.updateMatrix = function (matrix) {
-            this._baseMatrix = matrix.clone();
-            this._skeleton._markAsDirty();
-            this._updateDifferenceMatrix();
-        };
-        Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
-            if (!rootMatrix) {
-                rootMatrix = this._baseMatrix;
-            }
-            if (this._parent) {
-                rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
-            }
-            else {
-                this._absoluteTransform.copyFrom(rootMatrix);
-            }
-            this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
-            for (var index = 0; index < this.children.length; index++) {
-                this.children[index]._updateDifferenceMatrix();
-            }
-        };
-        Bone.prototype.markAsDirty = function () {
-            this._currentRenderId++;
-            this._skeleton._markAsDirty();
-        };
-        Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
-            if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
-            // all animation may be coming from a library skeleton, so may need to create animation
-            if (this.animations.length === 0) {
-                this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
-            }
-            // get animation info / verify there is such a range from the source bone
-            var sourceRange = source.animations[0].getRange(rangeName);
-            if (!sourceRange) {
-                return false;
-            }
-            var from = sourceRange.from;
-            var to = sourceRange.to;
-            var sourceKeys = source.animations[0].getKeys();
-            // rescaling prep
-            var sourceBoneLength = source.length;
-            var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
-            var ratio = scalingReqd ? this.length / sourceBoneLength : null;
-            var destKeys = this.animations[0].getKeys();
-            // loop vars declaration / initialization
-            var orig;
-            var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
-            var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
-            var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
-            var mat;
-            for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
-                orig = sourceKeys[key];
-                if (orig.frame >= from && orig.frame <= to) {
-                    if (scalingReqd) {
-                        orig.value.decompose(origScale, origRotation, origTranslation);
-                        origTranslation.scaleInPlace(ratio);
-                        mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
-                    }
-                    else {
-                        mat = orig.value;
-                    }
-                    destKeys.push({ frame: orig.frame + frameOffset, value: mat });
-                }
-            }
-            this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
-            return true;
-        };
-        return Bone;
-    })(BABYLON.Node);
-    BABYLON.Bone = Bone;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var Bone = (function (_super) {
+        __extends(Bone, _super);
+        function Bone(name, skeleton, parentBone, matrix, restPose) {
+            _super.call(this, name, skeleton.getScene());
+            this.name = name;
+            this.children = new Array();
+            this.animations = new Array();
+            this._worldTransform = new BABYLON.Matrix();
+            this._absoluteTransform = new BABYLON.Matrix();
+            this._invertedAbsoluteTransform = new BABYLON.Matrix();
+            this._skeleton = skeleton;
+            this._matrix = matrix;
+            this._baseMatrix = matrix;
+            this._restPose = restPose ? restPose : matrix.clone();
+            skeleton.bones.push(this);
+            if (parentBone) {
+                this._parent = parentBone;
+                parentBone.children.push(this);
+            }
+            else {
+                this._parent = null;
+            }
+            this._updateDifferenceMatrix();
+        }
+        // Members
+        Bone.prototype.getParent = function () {
+            return this._parent;
+        };
+        Bone.prototype.getLocalMatrix = function () {
+            return this._matrix;
+        };
+        Bone.prototype.getBaseMatrix = function () {
+            return this._baseMatrix;
+        };
+        Bone.prototype.getRestPose = function () {
+            return this._restPose;
+        };
+        Bone.prototype.returnToRest = function () {
+            this.updateMatrix(this._restPose.clone());
+        };
+        Bone.prototype.getWorldMatrix = function () {
+            return this._worldTransform;
+        };
+        Bone.prototype.getInvertedAbsoluteTransform = function () {
+            return this._invertedAbsoluteTransform;
+        };
+        Bone.prototype.getAbsoluteTransform = function () {
+            return this._absoluteTransform;
+        };
+        // Methods
+        Bone.prototype.updateMatrix = function (matrix) {
+            this._baseMatrix = matrix.clone();
+            this._skeleton._markAsDirty();
+            this._updateDifferenceMatrix();
+        };
+        Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
+            if (!rootMatrix) {
+                rootMatrix = this._baseMatrix;
+            }
+            if (this._parent) {
+                rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
+            }
+            else {
+                this._absoluteTransform.copyFrom(rootMatrix);
+            }
+            this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
+            for (var index = 0; index < this.children.length; index++) {
+                this.children[index]._updateDifferenceMatrix();
+            }
+        };
+        Bone.prototype.markAsDirty = function () {
+            this._currentRenderId++;
+            this._skeleton._markAsDirty();
+        };
+        Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
+            if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
+            // all animation may be coming from a library skeleton, so may need to create animation
+            if (this.animations.length === 0) {
+                this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
+            }
+            // get animation info / verify there is such a range from the source bone
+            var sourceRange = source.animations[0].getRange(rangeName);
+            if (!sourceRange) {
+                return false;
+            }
+            var from = sourceRange.from;
+            var to = sourceRange.to;
+            var sourceKeys = source.animations[0].getKeys();
+            // rescaling prep
+            var sourceBoneLength = source.length;
+            var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
+            var ratio = scalingReqd ? this.length / sourceBoneLength : null;
+            var destKeys = this.animations[0].getKeys();
+            // loop vars declaration / initialization
+            var orig;
+            var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
+            var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
+            var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
+            var mat;
+            for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
+                orig = sourceKeys[key];
+                if (orig.frame >= from && orig.frame <= to) {
+                    if (scalingReqd) {
+                        orig.value.decompose(origScale, origRotation, origTranslation);
+                        origTranslation.scaleInPlace(ratio);
+                        mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
+                    }
+                    else {
+                        mat = orig.value;
+                    }
+                    destKeys.push({ frame: orig.frame + frameOffset, value: mat });
+                }
+            }
+            this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
+            return true;
+        };
+        return Bone;
+    })(BABYLON.Node);
+    BABYLON.Bone = Bone;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.bone.js.map

+ 266 - 265
src/Bones/babylon.skeleton.js

@@ -1,265 +1,266 @@
-var BABYLON;
-(function (BABYLON) {
-    var Skeleton = (function () {
-        function Skeleton(name, id, scene) {
-            this.name = name;
-            this.id = id;
-            this.bones = new Array();
-            this.needInitialSkinMatrix = false;
-            this._isDirty = true;
-            this._meshesWithPoseMatrix = new Array();
-            this._identity = BABYLON.Matrix.Identity();
-            this._ranges = {};
-            this.bones = [];
-            this._scene = scene;
-            scene.skeletons.push(this);
-            this.prepare();
-            //make sure it will recalculate the matrix next time prepare is called.
-            this._isDirty = true;
-        }
-        // Members
-        Skeleton.prototype.getTransformMatrices = function (mesh) {
-            if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
-                return mesh._bonesTransformMatrices;
-            }
-            return this._transformMatrices;
-        };
-        Skeleton.prototype.getScene = function () {
-            return this._scene;
-        };
-        // Methods
-        Skeleton.prototype.createAnimationRange = function (name, from, to) {
-            // check name not already in use
-            if (!this._ranges[name]) {
-                this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
-                for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
-                    if (this.bones[i].animations[0]) {
-                        this.bones[i].animations[0].createRange(name, from, to);
-                    }
-                }
-            }
-        };
-        Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
-            if (deleteFrames === void 0) { deleteFrames = true; }
-            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
-                if (this.bones[i].animations[0]) {
-                    this.bones[i].animations[0].deleteRange(name, deleteFrames);
-                }
-            }
-            this._ranges[name] = undefined; // said much faster than 'delete this._range[name]' 
-        };
-        Skeleton.prototype.getAnimationRange = function (name) {
-            return this._ranges[name];
-        };
-        /**
-         *  note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
-         */
-        Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
-            if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
-            if (this._ranges[name] || !source.getAnimationRange(name)) {
-                return false;
-            }
-            var ret = true;
-            var frameOffset = this._getHighestAnimationFrame() + 1;
-            // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
-            var boneDict = {};
-            var sourceBones = source.bones;
-            for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
-                boneDict[sourceBones[i].name] = sourceBones[i];
-            }
-            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
-                var boneName = this.bones[i].name;
-                var sourceBone = boneDict[boneName];
-                if (sourceBone) {
-                    ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
-                }
-                else {
-                    BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
-                    ret = false;
-                }
-            }
-            // do not call createAnimationRange(), since it also is done to bones, which was already done
-            var range = source.getAnimationRange(name);
-            this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
-            return ret;
-        };
-        Skeleton.prototype.returnToRest = function () {
-            for (var index = 0; index < this.bones.length; index++) {
-                this.bones[index].returnToRest();
-            }
-        };
-        Skeleton.prototype._getHighestAnimationFrame = function () {
-            var ret = 0;
-            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
-                if (this.bones[i].animations[0]) {
-                    var highest = this.bones[i].animations[0].getHighestFrame();
-                    if (ret < highest) {
-                        ret = highest;
-                    }
-                }
-            }
-            return ret;
-        };
-        Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
-            var range = this.getAnimationRange(name);
-            if (!range) {
-                return null;
-            }
-            this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
-        };
-        Skeleton.prototype._markAsDirty = function () {
-            this._isDirty = true;
-        };
-        Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
-            this._meshesWithPoseMatrix.push(mesh);
-        };
-        Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
-            var index = this._meshesWithPoseMatrix.indexOf(mesh);
-            if (index > -1) {
-                this._meshesWithPoseMatrix.splice(index, 1);
-            }
-        };
-        Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
-            for (var index = 0; index < this.bones.length; index++) {
-                var bone = this.bones[index];
-                var parentBone = bone.getParent();
-                if (parentBone) {
-                    bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
-                }
-                else {
-                    if (initialSkinMatrix) {
-                        bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
-                    }
-                    else {
-                        bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
-                    }
-                }
-                bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
-            }
-            this._identity.copyToArray(targetMatrix, this.bones.length * 16);
-        };
-        Skeleton.prototype.prepare = function () {
-            if (!this._isDirty) {
-                return;
-            }
-            if (this.needInitialSkinMatrix) {
-                for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
-                    var mesh = this._meshesWithPoseMatrix[index];
-                    if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
-                        mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
-                    }
-                    var poseMatrix = mesh.getPoseMatrix();
-                    // Prepare bones
-                    for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
-                        var bone = this.bones[boneIndex];
-                        if (!bone.getParent()) {
-                            var matrix = bone.getBaseMatrix();
-                            matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
-                            bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
-                        }
-                    }
-                    this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
-                }
-            }
-            else {
-                if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
-                    this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
-                }
-                this._computeTransformMatrices(this._transformMatrices, null);
-            }
-            this._isDirty = false;
-            this._scene._activeBones += this.bones.length;
-        };
-        Skeleton.prototype.getAnimatables = function () {
-            if (!this._animatables || this._animatables.length !== this.bones.length) {
-                this._animatables = [];
-                for (var index = 0; index < this.bones.length; index++) {
-                    this._animatables.push(this.bones[index]);
-                }
-            }
-            return this._animatables;
-        };
-        Skeleton.prototype.clone = function (name, id) {
-            var result = new Skeleton(name, id || name, this._scene);
-            for (var index = 0; index < this.bones.length; index++) {
-                var source = this.bones[index];
-                var parentBone = null;
-                if (source.getParent()) {
-                    var parentIndex = this.bones.indexOf(source.getParent());
-                    parentBone = result.bones[parentIndex];
-                }
-                var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
-                BABYLON.Tools.DeepCopy(source.animations, bone.animations);
-            }
-            return result;
-        };
-        Skeleton.prototype.dispose = function () {
-            this._meshesWithPoseMatrix = [];
-            // Animations
-            this.getScene().stopAnimation(this);
-            // Remove from scene
-            this.getScene().removeSkeleton(this);
-        };
-        Skeleton.prototype.serialize = function () {
-            var serializationObject = {};
-            serializationObject.name = this.name;
-            serializationObject.id = this.id;
-            serializationObject.bones = [];
-            serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
-            for (var index = 0; index < this.bones.length; index++) {
-                var bone = this.bones[index];
-                var serializedBone = {
-                    parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
-                    name: bone.name,
-                    matrix: bone.getLocalMatrix().toArray(),
-                    rest: bone.getRestPose().toArray()
-                };
-                serializationObject.bones.push(serializedBone);
-                if (bone.length) {
-                    serializedBone.length = bone.length;
-                }
-                if (bone.animations && bone.animations.length > 0) {
-                    serializedBone.animation = bone.animations[0].serialize();
-                }
-                serializationObject.ranges = [];
-                for (var name in this._ranges) {
-                    var range = {};
-                    range.name = name;
-                    range.from = this._ranges[name].from;
-                    range.to = this._ranges[name].to;
-                    serializationObject.ranges.push(range);
-                }
-            }
-            return serializationObject;
-        };
-        Skeleton.Parse = function (parsedSkeleton, scene) {
-            var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
-            skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
-            for (var index = 0; index < parsedSkeleton.bones.length; index++) {
-                var parsedBone = parsedSkeleton.bones[index];
-                var parentBone = null;
-                if (parsedBone.parentBoneIndex > -1) {
-                    parentBone = skeleton.bones[parsedBone.parentBoneIndex];
-                }
-                var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
-                var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
-                if (parsedBone.length) {
-                    bone.length = parsedBone.length;
-                }
-                if (parsedBone.animation) {
-                    bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
-                }
-            }
-            // placed after bones, so createAnimationRange can cascade down
-            if (parsedSkeleton.ranges) {
-                for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
-                    var data = parsedSkeleton.ranges[index];
-                    skeleton.createAnimationRange(data.name, data.from, data.to);
-                }
-            }
-            return skeleton;
-        };
-        return Skeleton;
-    })();
-    BABYLON.Skeleton = Skeleton;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var Skeleton = (function () {
+        function Skeleton(name, id, scene) {
+            this.name = name;
+            this.id = id;
+            this.bones = new Array();
+            this.needInitialSkinMatrix = false;
+            this._isDirty = true;
+            this._meshesWithPoseMatrix = new Array();
+            this._identity = BABYLON.Matrix.Identity();
+            this._ranges = {};
+            this.bones = [];
+            this._scene = scene;
+            scene.skeletons.push(this);
+            this.prepare();
+            //make sure it will recalculate the matrix next time prepare is called.
+            this._isDirty = true;
+        }
+        // Members
+        Skeleton.prototype.getTransformMatrices = function (mesh) {
+            if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
+                return mesh._bonesTransformMatrices;
+            }
+            return this._transformMatrices;
+        };
+        Skeleton.prototype.getScene = function () {
+            return this._scene;
+        };
+        // Methods
+        Skeleton.prototype.createAnimationRange = function (name, from, to) {
+            // check name not already in use
+            if (!this._ranges[name]) {
+                this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
+                for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
+                    if (this.bones[i].animations[0]) {
+                        this.bones[i].animations[0].createRange(name, from, to);
+                    }
+                }
+            }
+        };
+        Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
+            if (deleteFrames === void 0) { deleteFrames = true; }
+            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
+                if (this.bones[i].animations[0]) {
+                    this.bones[i].animations[0].deleteRange(name, deleteFrames);
+                }
+            }
+            this._ranges[name] = undefined; // said much faster than 'delete this._range[name]' 
+        };
+        Skeleton.prototype.getAnimationRange = function (name) {
+            return this._ranges[name];
+        };
+        /**
+         *  note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
+         */
+        Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
+            if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
+            if (this._ranges[name] || !source.getAnimationRange(name)) {
+                return false;
+            }
+            var ret = true;
+            var frameOffset = this._getHighestAnimationFrame() + 1;
+            // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
+            var boneDict = {};
+            var sourceBones = source.bones;
+            for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
+                boneDict[sourceBones[i].name] = sourceBones[i];
+            }
+            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
+                var boneName = this.bones[i].name;
+                var sourceBone = boneDict[boneName];
+                if (sourceBone) {
+                    ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
+                }
+                else {
+                    BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
+                    ret = false;
+                }
+            }
+            // do not call createAnimationRange(), since it also is done to bones, which was already done
+            var range = source.getAnimationRange(name);
+            this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
+            return ret;
+        };
+        Skeleton.prototype.returnToRest = function () {
+            for (var index = 0; index < this.bones.length; index++) {
+                this.bones[index].returnToRest();
+            }
+        };
+        Skeleton.prototype._getHighestAnimationFrame = function () {
+            var ret = 0;
+            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
+                if (this.bones[i].animations[0]) {
+                    var highest = this.bones[i].animations[0].getHighestFrame();
+                    if (ret < highest) {
+                        ret = highest;
+                    }
+                }
+            }
+            return ret;
+        };
+        Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
+            var range = this.getAnimationRange(name);
+            if (!range) {
+                return null;
+            }
+            this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
+        };
+        Skeleton.prototype._markAsDirty = function () {
+            this._isDirty = true;
+        };
+        Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
+            this._meshesWithPoseMatrix.push(mesh);
+        };
+        Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
+            var index = this._meshesWithPoseMatrix.indexOf(mesh);
+            if (index > -1) {
+                this._meshesWithPoseMatrix.splice(index, 1);
+            }
+        };
+        Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
+            for (var index = 0; index < this.bones.length; index++) {
+                var bone = this.bones[index];
+                var parentBone = bone.getParent();
+                if (parentBone) {
+                    bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
+                }
+                else {
+                    if (initialSkinMatrix) {
+                        bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
+                    }
+                    else {
+                        bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
+                    }
+                }
+                bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
+            }
+            this._identity.copyToArray(targetMatrix, this.bones.length * 16);
+        };
+        Skeleton.prototype.prepare = function () {
+            if (!this._isDirty) {
+                return;
+            }
+            if (this.needInitialSkinMatrix) {
+                for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
+                    var mesh = this._meshesWithPoseMatrix[index];
+                    if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
+                        mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
+                    }
+                    var poseMatrix = mesh.getPoseMatrix();
+                    // Prepare bones
+                    for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
+                        var bone = this.bones[boneIndex];
+                        if (!bone.getParent()) {
+                            var matrix = bone.getBaseMatrix();
+                            matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
+                            bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
+                        }
+                    }
+                    this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
+                }
+            }
+            else {
+                if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
+                    this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
+                }
+                this._computeTransformMatrices(this._transformMatrices, null);
+            }
+            this._isDirty = false;
+            this._scene._activeBones += this.bones.length;
+        };
+        Skeleton.prototype.getAnimatables = function () {
+            if (!this._animatables || this._animatables.length !== this.bones.length) {
+                this._animatables = [];
+                for (var index = 0; index < this.bones.length; index++) {
+                    this._animatables.push(this.bones[index]);
+                }
+            }
+            return this._animatables;
+        };
+        Skeleton.prototype.clone = function (name, id) {
+            var result = new Skeleton(name, id || name, this._scene);
+            for (var index = 0; index < this.bones.length; index++) {
+                var source = this.bones[index];
+                var parentBone = null;
+                if (source.getParent()) {
+                    var parentIndex = this.bones.indexOf(source.getParent());
+                    parentBone = result.bones[parentIndex];
+                }
+                var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
+                BABYLON.Tools.DeepCopy(source.animations, bone.animations);
+            }
+            return result;
+        };
+        Skeleton.prototype.dispose = function () {
+            this._meshesWithPoseMatrix = [];
+            // Animations
+            this.getScene().stopAnimation(this);
+            // Remove from scene
+            this.getScene().removeSkeleton(this);
+        };
+        Skeleton.prototype.serialize = function () {
+            var serializationObject = {};
+            serializationObject.name = this.name;
+            serializationObject.id = this.id;
+            serializationObject.bones = [];
+            serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
+            for (var index = 0; index < this.bones.length; index++) {
+                var bone = this.bones[index];
+                var serializedBone = {
+                    parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
+                    name: bone.name,
+                    matrix: bone.getLocalMatrix().toArray(),
+                    rest: bone.getRestPose().toArray()
+                };
+                serializationObject.bones.push(serializedBone);
+                if (bone.length) {
+                    serializedBone.length = bone.length;
+                }
+                if (bone.animations && bone.animations.length > 0) {
+                    serializedBone.animation = bone.animations[0].serialize();
+                }
+                serializationObject.ranges = [];
+                for (var name in this._ranges) {
+                    var range = {};
+                    range.name = name;
+                    range.from = this._ranges[name].from;
+                    range.to = this._ranges[name].to;
+                    serializationObject.ranges.push(range);
+                }
+            }
+            return serializationObject;
+        };
+        Skeleton.Parse = function (parsedSkeleton, scene) {
+            var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
+            skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
+            for (var index = 0; index < parsedSkeleton.bones.length; index++) {
+                var parsedBone = parsedSkeleton.bones[index];
+                var parentBone = null;
+                if (parsedBone.parentBoneIndex > -1) {
+                    parentBone = skeleton.bones[parsedBone.parentBoneIndex];
+                }
+                var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
+                var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
+                if (parsedBone.length) {
+                    bone.length = parsedBone.length;
+                }
+                if (parsedBone.animation) {
+                    bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
+                }
+            }
+            // placed after bones, so createAnimationRange can cascade down
+            if (parsedSkeleton.ranges) {
+                for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
+                    var data = parsedSkeleton.ranges[index];
+                    skeleton.createAnimationRange(data.name, data.from, data.to);
+                }
+            }
+            return skeleton;
+        };
+        return Skeleton;
+    })();
+    BABYLON.Skeleton = Skeleton;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.skeleton.js.map

+ 48 - 47
src/Cameras/VR/babylon.vrDeviceOrientationCamera.js

@@ -1,47 +1,48 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var VRDeviceOrientationFreeCamera = (function (_super) {
-        __extends(VRDeviceOrientationFreeCamera, _super);
-        function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
-            if (compensateDistortion === void 0) { compensateDistortion = true; }
-            _super.call(this, name, position, scene);
-            this._alpha = 0;
-            this._beta = 0;
-            this._gamma = 0;
-            var metrics = BABYLON.VRCameraMetrics.GetDefault();
-            metrics.compensateDistortion = compensateDistortion;
-            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
-            this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
-        }
-        VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
-            this._alpha = +evt.alpha | 0;
-            this._beta = +evt.beta | 0;
-            this._gamma = +evt.gamma | 0;
-            if (this._gamma < 0) {
-                this._gamma = 90 + this._gamma;
-            }
-            else {
-                // Incline it in the correct angle.
-                this._gamma = 270 - this._gamma;
-            }
-            this.rotation.x = this._gamma / 180.0 * Math.PI;
-            this.rotation.y = -this._alpha / 180.0 * Math.PI;
-            this.rotation.z = this._beta / 180.0 * Math.PI;
-        };
-        VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
-            _super.prototype.attachControl.call(this, element, noPreventDefault);
-            window.addEventListener("deviceorientation", this._deviceOrientationHandler);
-        };
-        VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
-            _super.prototype.detachControl.call(this, element);
-            window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
-        };
-        return VRDeviceOrientationFreeCamera;
-    })(BABYLON.FreeCamera);
-    BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var VRDeviceOrientationFreeCamera = (function (_super) {
+        __extends(VRDeviceOrientationFreeCamera, _super);
+        function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
+            if (compensateDistortion === void 0) { compensateDistortion = true; }
+            _super.call(this, name, position, scene);
+            this._alpha = 0;
+            this._beta = 0;
+            this._gamma = 0;
+            var metrics = BABYLON.VRCameraMetrics.GetDefault();
+            metrics.compensateDistortion = compensateDistortion;
+            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
+            this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
+        }
+        VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
+            this._alpha = +evt.alpha | 0;
+            this._beta = +evt.beta | 0;
+            this._gamma = +evt.gamma | 0;
+            if (this._gamma < 0) {
+                this._gamma = 90 + this._gamma;
+            }
+            else {
+                // Incline it in the correct angle.
+                this._gamma = 270 - this._gamma;
+            }
+            this.rotation.x = this._gamma / 180.0 * Math.PI;
+            this.rotation.y = -this._alpha / 180.0 * Math.PI;
+            this.rotation.z = this._beta / 180.0 * Math.PI;
+        };
+        VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
+            _super.prototype.attachControl.call(this, element, noPreventDefault);
+            window.addEventListener("deviceorientation", this._deviceOrientationHandler);
+        };
+        VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
+            _super.prototype.detachControl.call(this, element);
+            window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
+        };
+        return VRDeviceOrientationFreeCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map

+ 74 - 73
src/Cameras/VR/babylon.webVRCamera.js

@@ -1,73 +1,74 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var WebVRFreeCamera = (function (_super) {
-        __extends(WebVRFreeCamera, _super);
-        function WebVRFreeCamera(name, position, scene, compensateDistortion) {
-            if (compensateDistortion === void 0) { compensateDistortion = true; }
-            _super.call(this, name, position, scene);
-            this._hmdDevice = null;
-            this._sensorDevice = null;
-            this._cacheState = null;
-            this._cacheQuaternion = new BABYLON.Quaternion();
-            this._cacheRotation = BABYLON.Vector3.Zero();
-            this._vrEnabled = false;
-            var metrics = BABYLON.VRCameraMetrics.GetDefault();
-            metrics.compensateDistortion = compensateDistortion;
-            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
-            this._getWebVRDevices = this._getWebVRDevices.bind(this);
-        }
-        WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
-            var size = devices.length;
-            var i = 0;
-            // Reset devices.
-            this._sensorDevice = null;
-            this._hmdDevice = null;
-            // Search for a HmdDevice.
-            while (i < size && this._hmdDevice === null) {
-                if (devices[i] instanceof HMDVRDevice) {
-                    this._hmdDevice = devices[i];
-                }
-                i++;
-            }
-            i = 0;
-            while (i < size && this._sensorDevice === null) {
-                if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
-                    this._sensorDevice = devices[i];
-                }
-                i++;
-            }
-            this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
-        };
-        WebVRFreeCamera.prototype._checkInputs = function () {
-            if (this._vrEnabled) {
-                this._cacheState = this._sensorDevice.getState();
-                this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
-                this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
-                this.rotation.x = -this._cacheRotation.z;
-                this.rotation.y = -this._cacheRotation.y;
-                this.rotation.z = this._cacheRotation.x;
-            }
-            _super.prototype._checkInputs.call(this);
-        };
-        WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
-            _super.prototype.attachControl.call(this, element, noPreventDefault);
-            if (navigator.getVRDevices) {
-                navigator.getVRDevices().then(this._getWebVRDevices);
-            }
-            else if (navigator.mozGetVRDevices) {
-                navigator.mozGetVRDevices(this._getWebVRDevices);
-            }
-        };
-        WebVRFreeCamera.prototype.detachControl = function (element) {
-            _super.prototype.detachControl.call(this, element);
-            this._vrEnabled = false;
-        };
-        return WebVRFreeCamera;
-    })(BABYLON.FreeCamera);
-    BABYLON.WebVRFreeCamera = WebVRFreeCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var WebVRFreeCamera = (function (_super) {
+        __extends(WebVRFreeCamera, _super);
+        function WebVRFreeCamera(name, position, scene, compensateDistortion) {
+            if (compensateDistortion === void 0) { compensateDistortion = true; }
+            _super.call(this, name, position, scene);
+            this._hmdDevice = null;
+            this._sensorDevice = null;
+            this._cacheState = null;
+            this._cacheQuaternion = new BABYLON.Quaternion();
+            this._cacheRotation = BABYLON.Vector3.Zero();
+            this._vrEnabled = false;
+            var metrics = BABYLON.VRCameraMetrics.GetDefault();
+            metrics.compensateDistortion = compensateDistortion;
+            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
+            this._getWebVRDevices = this._getWebVRDevices.bind(this);
+        }
+        WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
+            var size = devices.length;
+            var i = 0;
+            // Reset devices.
+            this._sensorDevice = null;
+            this._hmdDevice = null;
+            // Search for a HmdDevice.
+            while (i < size && this._hmdDevice === null) {
+                if (devices[i] instanceof HMDVRDevice) {
+                    this._hmdDevice = devices[i];
+                }
+                i++;
+            }
+            i = 0;
+            while (i < size && this._sensorDevice === null) {
+                if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
+                    this._sensorDevice = devices[i];
+                }
+                i++;
+            }
+            this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
+        };
+        WebVRFreeCamera.prototype._checkInputs = function () {
+            if (this._vrEnabled) {
+                this._cacheState = this._sensorDevice.getState();
+                this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
+                this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
+                this.rotation.x = -this._cacheRotation.z;
+                this.rotation.y = -this._cacheRotation.y;
+                this.rotation.z = this._cacheRotation.x;
+            }
+            _super.prototype._checkInputs.call(this);
+        };
+        WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
+            _super.prototype.attachControl.call(this, element, noPreventDefault);
+            if (navigator.getVRDevices) {
+                navigator.getVRDevices().then(this._getWebVRDevices);
+            }
+            else if (navigator.mozGetVRDevices) {
+                navigator.mozGetVRDevices(this._getWebVRDevices);
+            }
+        };
+        WebVRFreeCamera.prototype.detachControl = function (element) {
+            _super.prototype.detachControl.call(this, element);
+            this._vrEnabled = false;
+        };
+        return WebVRFreeCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.WebVRFreeCamera = WebVRFreeCamera;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.webVRCamera.js.map

File diff suppressed because it is too large
+ 577 - 576
src/Cameras/babylon.arcRotateCamera.js


File diff suppressed because it is too large
+ 668 - 667
src/Cameras/babylon.camera.js


+ 1 - 1
src/Cameras/babylon.camera.ts

@@ -663,7 +663,7 @@
                 camera = new VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
 
             } else if (parsedCamera.type === "FreeCamera") {
-                camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);   
+                camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);   
                         
             } else {
                 // Touch Camera is the default value

+ 72 - 71
src/Cameras/babylon.deviceOrientationCamera.js

@@ -1,71 +1,72 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    // We're mainly based on the logic defined into the FreeCamera code
-    var DeviceOrientationCamera = (function (_super) {
-        __extends(DeviceOrientationCamera, _super);
-        function DeviceOrientationCamera(name, position, scene) {
-            var _this = this;
-            _super.call(this, name, position, scene);
-            this._offsetX = null;
-            this._offsetY = null;
-            this._orientationGamma = 0;
-            this._orientationBeta = 0;
-            this._initialOrientationGamma = 0;
-            this._initialOrientationBeta = 0;
-            this.angularSensibility = 10000.0;
-            this.moveSensibility = 50.0;
-            window.addEventListener("resize", function () {
-                _this._initialOrientationGamma = null;
-            }, false);
-        }
-        DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
-            var _this = this;
-            if (this._attachedCanvas) {
-                return;
-            }
-            this._attachedCanvas = canvas;
-            if (!this._orientationChanged) {
-                this._orientationChanged = function (evt) {
-                    if (!_this._initialOrientationGamma) {
-                        _this._initialOrientationGamma = evt.gamma;
-                        _this._initialOrientationBeta = evt.beta;
-                    }
-                    _this._orientationGamma = evt.gamma;
-                    _this._orientationBeta = evt.beta;
-                    _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
-                    _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
-                };
-            }
-            window.addEventListener("deviceorientation", this._orientationChanged);
-        };
-        DeviceOrientationCamera.prototype.detachControl = function (canvas) {
-            if (this._attachedCanvas !== canvas) {
-                return;
-            }
-            window.removeEventListener("deviceorientation", this._orientationChanged);
-            this._attachedCanvas = null;
-            this._orientationGamma = 0;
-            this._orientationBeta = 0;
-            this._initialOrientationGamma = 0;
-            this._initialOrientationBeta = 0;
-        };
-        DeviceOrientationCamera.prototype._checkInputs = function () {
-            if (!this._offsetX) {
-                return;
-            }
-            this.cameraRotation.y -= this._offsetX / this.angularSensibility;
-            var speed = this._computeLocalCameraSpeed();
-            var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
-            BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
-            this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
-            _super.prototype._checkInputs.call(this);
-        };
-        return DeviceOrientationCamera;
-    })(BABYLON.FreeCamera);
-    BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var DeviceOrientationCamera = (function (_super) {
+        __extends(DeviceOrientationCamera, _super);
+        function DeviceOrientationCamera(name, position, scene) {
+            var _this = this;
+            _super.call(this, name, position, scene);
+            this._offsetX = null;
+            this._offsetY = null;
+            this._orientationGamma = 0;
+            this._orientationBeta = 0;
+            this._initialOrientationGamma = 0;
+            this._initialOrientationBeta = 0;
+            this.angularSensibility = 10000.0;
+            this.moveSensibility = 50.0;
+            window.addEventListener("resize", function () {
+                _this._initialOrientationGamma = null;
+            }, false);
+        }
+        DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
+            var _this = this;
+            if (this._attachedCanvas) {
+                return;
+            }
+            this._attachedCanvas = canvas;
+            if (!this._orientationChanged) {
+                this._orientationChanged = function (evt) {
+                    if (!_this._initialOrientationGamma) {
+                        _this._initialOrientationGamma = evt.gamma;
+                        _this._initialOrientationBeta = evt.beta;
+                    }
+                    _this._orientationGamma = evt.gamma;
+                    _this._orientationBeta = evt.beta;
+                    _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
+                    _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
+                };
+            }
+            window.addEventListener("deviceorientation", this._orientationChanged);
+        };
+        DeviceOrientationCamera.prototype.detachControl = function (canvas) {
+            if (this._attachedCanvas !== canvas) {
+                return;
+            }
+            window.removeEventListener("deviceorientation", this._orientationChanged);
+            this._attachedCanvas = null;
+            this._orientationGamma = 0;
+            this._orientationBeta = 0;
+            this._initialOrientationGamma = 0;
+            this._initialOrientationBeta = 0;
+        };
+        DeviceOrientationCamera.prototype._checkInputs = function () {
+            if (!this._offsetX) {
+                return;
+            }
+            this.cameraRotation.y -= this._offsetX / this.angularSensibility;
+            var speed = this._computeLocalCameraSpeed();
+            var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
+            BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
+            this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
+            _super.prototype._checkInputs.call(this);
+        };
+        return DeviceOrientationCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.deviceOrientationCamera.js.map

+ 99 - 98
src/Cameras/babylon.followCamera.js

@@ -1,98 +1,99 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var FollowCamera = (function (_super) {
-        __extends(FollowCamera, _super);
-        function FollowCamera(name, position, scene) {
-            _super.call(this, name, position, scene);
-            this.radius = 12;
-            this.rotationOffset = 0;
-            this.heightOffset = 4;
-            this.cameraAcceleration = 0.05;
-            this.maxCameraSpeed = 20;
-        }
-        FollowCamera.prototype.getRadians = function (degrees) {
-            return degrees * Math.PI / 180;
-        };
-        FollowCamera.prototype.follow = function (cameraTarget) {
-            if (!cameraTarget)
-                return;
-            var yRotation;
-            if (cameraTarget.rotationQuaternion) {
-                var rotMatrix = new BABYLON.Matrix();
-                cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
-                yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
-            }
-            else {
-                yRotation = cameraTarget.rotation.y;
-            }
-            var radians = this.getRadians(this.rotationOffset) + yRotation;
-            var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
-            var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
-            var dx = targetX - this.position.x;
-            var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
-            var dz = (targetZ) - this.position.z;
-            var vx = dx * this.cameraAcceleration * 2; //this is set to .05
-            var vy = dy * this.cameraAcceleration;
-            var vz = dz * this.cameraAcceleration * 2;
-            if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
-                vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
-            }
-            if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
-                vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
-            }
-            if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
-                vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
-            }
-            this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
-            this.setTarget(cameraTarget.position);
-        };
-        FollowCamera.prototype._checkInputs = function () {
-            _super.prototype._checkInputs.call(this);
-            this.follow(this.target);
-        };
-        FollowCamera.prototype.serialize = function () {
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.radius = this.radius;
-            serializationObject.heightOffset = this.heightOffset;
-            serializationObject.rotationOffset = this.rotationOffset;
-            return serializationObject;
-        };
-        return FollowCamera;
-    })(BABYLON.TargetCamera);
-    BABYLON.FollowCamera = FollowCamera;
-    var ArcFollowCamera = (function (_super) {
-        __extends(ArcFollowCamera, _super);
-        function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
-            _super.call(this, name, BABYLON.Vector3.Zero(), scene);
-            this.alpha = alpha;
-            this.beta = beta;
-            this.radius = radius;
-            this.target = target;
-            this._cartesianCoordinates = BABYLON.Vector3.Zero();
-            this.follow();
-        }
-        ArcFollowCamera.prototype.follow = function () {
-            this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
-            this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
-            this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
-            this.position = this.target.position.add(this._cartesianCoordinates);
-            this.setTarget(this.target.position);
-        };
-        ArcFollowCamera.prototype._checkInputs = function () {
-            _super.prototype._checkInputs.call(this);
-            this.follow();
-        };
-        ArcFollowCamera.prototype.serialize = function () {
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.radius = this.radius;
-            return serializationObject;
-        };
-        return ArcFollowCamera;
-    })(BABYLON.TargetCamera);
-    BABYLON.ArcFollowCamera = ArcFollowCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var FollowCamera = (function (_super) {
+        __extends(FollowCamera, _super);
+        function FollowCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this.radius = 12;
+            this.rotationOffset = 0;
+            this.heightOffset = 4;
+            this.cameraAcceleration = 0.05;
+            this.maxCameraSpeed = 20;
+        }
+        FollowCamera.prototype.getRadians = function (degrees) {
+            return degrees * Math.PI / 180;
+        };
+        FollowCamera.prototype.follow = function (cameraTarget) {
+            if (!cameraTarget)
+                return;
+            var yRotation;
+            if (cameraTarget.rotationQuaternion) {
+                var rotMatrix = new BABYLON.Matrix();
+                cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
+                yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
+            }
+            else {
+                yRotation = cameraTarget.rotation.y;
+            }
+            var radians = this.getRadians(this.rotationOffset) + yRotation;
+            var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
+            var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
+            var dx = targetX - this.position.x;
+            var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
+            var dz = (targetZ) - this.position.z;
+            var vx = dx * this.cameraAcceleration * 2; //this is set to .05
+            var vy = dy * this.cameraAcceleration;
+            var vz = dz * this.cameraAcceleration * 2;
+            if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
+                vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
+            }
+            if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
+                vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
+            }
+            if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
+                vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
+            }
+            this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
+            this.setTarget(cameraTarget.position);
+        };
+        FollowCamera.prototype._checkInputs = function () {
+            _super.prototype._checkInputs.call(this);
+            this.follow(this.target);
+        };
+        FollowCamera.prototype.serialize = function () {
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.radius = this.radius;
+            serializationObject.heightOffset = this.heightOffset;
+            serializationObject.rotationOffset = this.rotationOffset;
+            return serializationObject;
+        };
+        return FollowCamera;
+    })(BABYLON.TargetCamera);
+    BABYLON.FollowCamera = FollowCamera;
+    var ArcFollowCamera = (function (_super) {
+        __extends(ArcFollowCamera, _super);
+        function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
+            _super.call(this, name, BABYLON.Vector3.Zero(), scene);
+            this.alpha = alpha;
+            this.beta = beta;
+            this.radius = radius;
+            this.target = target;
+            this._cartesianCoordinates = BABYLON.Vector3.Zero();
+            this.follow();
+        }
+        ArcFollowCamera.prototype.follow = function () {
+            this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
+            this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
+            this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
+            this.position = this.target.position.add(this._cartesianCoordinates);
+            this.setTarget(this.target.position);
+        };
+        ArcFollowCamera.prototype._checkInputs = function () {
+            _super.prototype._checkInputs.call(this);
+            this.follow();
+        };
+        ArcFollowCamera.prototype.serialize = function () {
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.radius = this.radius;
+            return serializationObject;
+        };
+        return ArcFollowCamera;
+    })(BABYLON.TargetCamera);
+    BABYLON.ArcFollowCamera = ArcFollowCamera;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.followCamera.js.map

+ 236 - 235
src/Cameras/babylon.freeCamera.js

@@ -1,235 +1,236 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var FreeCamera = (function (_super) {
-        __extends(FreeCamera, _super);
-        function FreeCamera(name, position, scene) {
-            var _this = this;
-            _super.call(this, name, position, scene);
-            this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
-            this.keysUp = [38];
-            this.keysDown = [40];
-            this.keysLeft = [37];
-            this.keysRight = [39];
-            this.checkCollisions = false;
-            this.applyGravity = false;
-            this.angularSensibility = 2000.0;
-            this._keys = [];
-            this._collider = new BABYLON.Collider();
-            this._needMoveForGravity = false;
-            this._oldPosition = BABYLON.Vector3.Zero();
-            this._diffPosition = BABYLON.Vector3.Zero();
-            this._newPosition = BABYLON.Vector3.Zero();
-            this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
-                if (collidedMesh === void 0) { collidedMesh = null; }
-                //TODO move this to the collision coordinator!
-                if (_this.getScene().workerCollisions)
-                    newPosition.multiplyInPlace(_this._collider.radius);
-                var updatePosition = function (newPos) {
-                    _this._newPosition.copyFrom(newPos);
-                    _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
-                    var oldPosition = _this.position.clone();
-                    if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
-                        _this.position.addInPlace(_this._diffPosition);
-                        if (_this.onCollide && collidedMesh) {
-                            _this.onCollide(collidedMesh);
-                        }
-                    }
-                };
-                updatePosition(newPosition);
-            };
-        }
-        FreeCamera.prototype._onLostFocus = function (e) {
-            this._keys = [];
-        };
-        // Controls
-        FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
-            var _this = this;
-            var previousPosition;
-            var engine = this.getEngine();
-            if (this._attachedElement) {
-                return;
-            }
-            this._attachedElement = element;
-            if (this._onMouseDown === undefined) {
-                this._onMouseDown = function (evt) {
-                    previousPosition = {
-                        x: evt.clientX,
-                        y: evt.clientY
-                    };
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                };
-                this._onMouseUp = function (evt) {
-                    previousPosition = null;
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                };
-                this._onMouseOut = function (evt) {
-                    previousPosition = null;
-                    _this._keys = [];
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                };
-                this._onMouseMove = function (evt) {
-                    if (!previousPosition && !engine.isPointerLock) {
-                        return;
-                    }
-                    var offsetX;
-                    var offsetY;
-                    if (!engine.isPointerLock) {
-                        offsetX = evt.clientX - previousPosition.x;
-                        offsetY = evt.clientY - previousPosition.y;
-                    }
-                    else {
-                        offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
-                        offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
-                    }
-                    _this.cameraRotation.y += offsetX / _this.angularSensibility;
-                    _this.cameraRotation.x += offsetY / _this.angularSensibility;
-                    previousPosition = {
-                        x: evt.clientX,
-                        y: evt.clientY
-                    };
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                };
-                this._onKeyDown = function (evt) {
-                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysRight.indexOf(evt.keyCode) !== -1) {
-                        var index = _this._keys.indexOf(evt.keyCode);
-                        if (index === -1) {
-                            _this._keys.push(evt.keyCode);
-                        }
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                    }
-                };
-                this._onKeyUp = function (evt) {
-                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
-                        _this.keysRight.indexOf(evt.keyCode) !== -1) {
-                        var index = _this._keys.indexOf(evt.keyCode);
-                        if (index >= 0) {
-                            _this._keys.splice(index, 1);
-                        }
-                        if (!noPreventDefault) {
-                            evt.preventDefault();
-                        }
-                    }
-                };
-                this._reset = function () {
-                    _this._keys = [];
-                    previousPosition = null;
-                    _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
-                    _this.cameraRotation = new BABYLON.Vector2(0, 0);
-                };
-            }
-            element.addEventListener("mousedown", this._onMouseDown, false);
-            element.addEventListener("mouseup", this._onMouseUp, false);
-            element.addEventListener("mouseout", this._onMouseOut, false);
-            element.addEventListener("mousemove", this._onMouseMove, false);
-            BABYLON.Tools.RegisterTopRootEvents([
-                { name: "keydown", handler: this._onKeyDown },
-                { name: "keyup", handler: this._onKeyUp },
-                { name: "blur", handler: this._onLostFocus }
-            ]);
-        };
-        FreeCamera.prototype.detachControl = function (element) {
-            if (this._attachedElement !== element) {
-                return;
-            }
-            element.removeEventListener("mousedown", this._onMouseDown);
-            element.removeEventListener("mouseup", this._onMouseUp);
-            element.removeEventListener("mouseout", this._onMouseOut);
-            element.removeEventListener("mousemove", this._onMouseMove);
-            BABYLON.Tools.UnregisterTopRootEvents([
-                { name: "keydown", handler: this._onKeyDown },
-                { name: "keyup", handler: this._onKeyUp },
-                { name: "blur", handler: this._onLostFocus }
-            ]);
-            this._attachedElement = null;
-            if (this._reset) {
-                this._reset();
-            }
-        };
-        FreeCamera.prototype._collideWithWorld = function (velocity) {
-            var globalPosition;
-            if (this.parent) {
-                globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
-            }
-            else {
-                globalPosition = this.position;
-            }
-            globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
-            this._collider.radius = this.ellipsoid;
-            //no need for clone, as long as gravity is not on.
-            var actualVelocity = velocity;
-            //add gravity to the velocity to prevent the dual-collision checking
-            if (this.applyGravity) {
-                //this prevents mending with cameraDirection, a global variable of the free camera class.
-                actualVelocity = velocity.add(this.getScene().gravity);
-            }
-            this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
-        };
-        FreeCamera.prototype._checkInputs = function () {
-            if (!this._localDirection) {
-                this._localDirection = BABYLON.Vector3.Zero();
-                this._transformedDirection = BABYLON.Vector3.Zero();
-            }
-            // Keyboard
-            for (var index = 0; index < this._keys.length; index++) {
-                var keyCode = this._keys[index];
-                var speed = this._computeLocalCameraSpeed();
-                if (this.keysLeft.indexOf(keyCode) !== -1) {
-                    this._localDirection.copyFromFloats(-speed, 0, 0);
-                }
-                else if (this.keysUp.indexOf(keyCode) !== -1) {
-                    this._localDirection.copyFromFloats(0, 0, speed);
-                }
-                else if (this.keysRight.indexOf(keyCode) !== -1) {
-                    this._localDirection.copyFromFloats(speed, 0, 0);
-                }
-                else if (this.keysDown.indexOf(keyCode) !== -1) {
-                    this._localDirection.copyFromFloats(0, 0, -speed);
-                }
-                this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
-                BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
-                this.cameraDirection.addInPlace(this._transformedDirection);
-            }
-            _super.prototype._checkInputs.call(this);
-        };
-        FreeCamera.prototype._decideIfNeedsToMove = function () {
-            return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
-        };
-        FreeCamera.prototype._updatePosition = function () {
-            if (this.checkCollisions && this.getScene().collisionsEnabled) {
-                this._collideWithWorld(this.cameraDirection);
-            }
-            else {
-                this.position.addInPlace(this.cameraDirection);
-            }
-        };
-        FreeCamera.prototype.serialize = function () {
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.checkCollisions = this.checkCollisions;
-            serializationObject.applyGravity = this.applyGravity;
-            serializationObject.ellipsoid = this.ellipsoid.asArray();
-            return serializationObject;
-        };
-        return FreeCamera;
-    })(BABYLON.TargetCamera);
-    BABYLON.FreeCamera = FreeCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var FreeCamera = (function (_super) {
+        __extends(FreeCamera, _super);
+        function FreeCamera(name, position, scene) {
+            var _this = this;
+            _super.call(this, name, position, scene);
+            this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
+            this.keysUp = [38];
+            this.keysDown = [40];
+            this.keysLeft = [37];
+            this.keysRight = [39];
+            this.checkCollisions = false;
+            this.applyGravity = false;
+            this.angularSensibility = 2000.0;
+            this._keys = [];
+            this._collider = new BABYLON.Collider();
+            this._needMoveForGravity = false;
+            this._oldPosition = BABYLON.Vector3.Zero();
+            this._diffPosition = BABYLON.Vector3.Zero();
+            this._newPosition = BABYLON.Vector3.Zero();
+            this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
+                if (collidedMesh === void 0) { collidedMesh = null; }
+                //TODO move this to the collision coordinator!
+                if (_this.getScene().workerCollisions)
+                    newPosition.multiplyInPlace(_this._collider.radius);
+                var updatePosition = function (newPos) {
+                    _this._newPosition.copyFrom(newPos);
+                    _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
+                    var oldPosition = _this.position.clone();
+                    if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
+                        _this.position.addInPlace(_this._diffPosition);
+                        if (_this.onCollide && collidedMesh) {
+                            _this.onCollide(collidedMesh);
+                        }
+                    }
+                };
+                updatePosition(newPosition);
+            };
+        }
+        FreeCamera.prototype._onLostFocus = function (e) {
+            this._keys = [];
+        };
+        // Controls
+        FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
+            var _this = this;
+            var previousPosition;
+            var engine = this.getEngine();
+            if (this._attachedElement) {
+                return;
+            }
+            this._attachedElement = element;
+            if (this._onMouseDown === undefined) {
+                this._onMouseDown = function (evt) {
+                    previousPosition = {
+                        x: evt.clientX,
+                        y: evt.clientY
+                    };
+                    if (!noPreventDefault) {
+                        evt.preventDefault();
+                    }
+                };
+                this._onMouseUp = function (evt) {
+                    previousPosition = null;
+                    if (!noPreventDefault) {
+                        evt.preventDefault();
+                    }
+                };
+                this._onMouseOut = function (evt) {
+                    previousPosition = null;
+                    _this._keys = [];
+                    if (!noPreventDefault) {
+                        evt.preventDefault();
+                    }
+                };
+                this._onMouseMove = function (evt) {
+                    if (!previousPosition && !engine.isPointerLock) {
+                        return;
+                    }
+                    var offsetX;
+                    var offsetY;
+                    if (!engine.isPointerLock) {
+                        offsetX = evt.clientX - previousPosition.x;
+                        offsetY = evt.clientY - previousPosition.y;
+                    }
+                    else {
+                        offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
+                        offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
+                    }
+                    _this.cameraRotation.y += offsetX / _this.angularSensibility;
+                    _this.cameraRotation.x += offsetY / _this.angularSensibility;
+                    previousPosition = {
+                        x: evt.clientX,
+                        y: evt.clientY
+                    };
+                    if (!noPreventDefault) {
+                        evt.preventDefault();
+                    }
+                };
+                this._onKeyDown = function (evt) {
+                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
+                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
+                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
+                        _this.keysRight.indexOf(evt.keyCode) !== -1) {
+                        var index = _this._keys.indexOf(evt.keyCode);
+                        if (index === -1) {
+                            _this._keys.push(evt.keyCode);
+                        }
+                        if (!noPreventDefault) {
+                            evt.preventDefault();
+                        }
+                    }
+                };
+                this._onKeyUp = function (evt) {
+                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
+                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
+                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
+                        _this.keysRight.indexOf(evt.keyCode) !== -1) {
+                        var index = _this._keys.indexOf(evt.keyCode);
+                        if (index >= 0) {
+                            _this._keys.splice(index, 1);
+                        }
+                        if (!noPreventDefault) {
+                            evt.preventDefault();
+                        }
+                    }
+                };
+                this._reset = function () {
+                    _this._keys = [];
+                    previousPosition = null;
+                    _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
+                    _this.cameraRotation = new BABYLON.Vector2(0, 0);
+                };
+            }
+            element.addEventListener("mousedown", this._onMouseDown, false);
+            element.addEventListener("mouseup", this._onMouseUp, false);
+            element.addEventListener("mouseout", this._onMouseOut, false);
+            element.addEventListener("mousemove", this._onMouseMove, false);
+            BABYLON.Tools.RegisterTopRootEvents([
+                { name: "keydown", handler: this._onKeyDown },
+                { name: "keyup", handler: this._onKeyUp },
+                { name: "blur", handler: this._onLostFocus }
+            ]);
+        };
+        FreeCamera.prototype.detachControl = function (element) {
+            if (this._attachedElement !== element) {
+                return;
+            }
+            element.removeEventListener("mousedown", this._onMouseDown);
+            element.removeEventListener("mouseup", this._onMouseUp);
+            element.removeEventListener("mouseout", this._onMouseOut);
+            element.removeEventListener("mousemove", this._onMouseMove);
+            BABYLON.Tools.UnregisterTopRootEvents([
+                { name: "keydown", handler: this._onKeyDown },
+                { name: "keyup", handler: this._onKeyUp },
+                { name: "blur", handler: this._onLostFocus }
+            ]);
+            this._attachedElement = null;
+            if (this._reset) {
+                this._reset();
+            }
+        };
+        FreeCamera.prototype._collideWithWorld = function (velocity) {
+            var globalPosition;
+            if (this.parent) {
+                globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
+            }
+            else {
+                globalPosition = this.position;
+            }
+            globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
+            this._collider.radius = this.ellipsoid;
+            //no need for clone, as long as gravity is not on.
+            var actualVelocity = velocity;
+            //add gravity to the velocity to prevent the dual-collision checking
+            if (this.applyGravity) {
+                //this prevents mending with cameraDirection, a global variable of the free camera class.
+                actualVelocity = velocity.add(this.getScene().gravity);
+            }
+            this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
+        };
+        FreeCamera.prototype._checkInputs = function () {
+            if (!this._localDirection) {
+                this._localDirection = BABYLON.Vector3.Zero();
+                this._transformedDirection = BABYLON.Vector3.Zero();
+            }
+            // Keyboard
+            for (var index = 0; index < this._keys.length; index++) {
+                var keyCode = this._keys[index];
+                var speed = this._computeLocalCameraSpeed();
+                if (this.keysLeft.indexOf(keyCode) !== -1) {
+                    this._localDirection.copyFromFloats(-speed, 0, 0);
+                }
+                else if (this.keysUp.indexOf(keyCode) !== -1) {
+                    this._localDirection.copyFromFloats(0, 0, speed);
+                }
+                else if (this.keysRight.indexOf(keyCode) !== -1) {
+                    this._localDirection.copyFromFloats(speed, 0, 0);
+                }
+                else if (this.keysDown.indexOf(keyCode) !== -1) {
+                    this._localDirection.copyFromFloats(0, 0, -speed);
+                }
+                this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
+                BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
+                this.cameraDirection.addInPlace(this._transformedDirection);
+            }
+            _super.prototype._checkInputs.call(this);
+        };
+        FreeCamera.prototype._decideIfNeedsToMove = function () {
+            return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
+        };
+        FreeCamera.prototype._updatePosition = function () {
+            if (this.checkCollisions && this.getScene().collisionsEnabled) {
+                this._collideWithWorld(this.cameraDirection);
+            }
+            else {
+                this.position.addInPlace(this.cameraDirection);
+            }
+        };
+        FreeCamera.prototype.serialize = function () {
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.checkCollisions = this.checkCollisions;
+            serializationObject.applyGravity = this.applyGravity;
+            serializationObject.ellipsoid = this.ellipsoid.asArray();
+            return serializationObject;
+        };
+        return FreeCamera;
+    })(BABYLON.TargetCamera);
+    BABYLON.FreeCamera = FreeCamera;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.freeCamera.js.map

+ 52 - 51
src/Cameras/babylon.gamepadCamera.js

@@ -1,51 +1,52 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    // We're mainly based on the logic defined into the FreeCamera code
-    var GamepadCamera = (function (_super) {
-        __extends(GamepadCamera, _super);
-        function GamepadCamera(name, position, scene) {
-            var _this = this;
-            _super.call(this, name, position, scene);
-            this.angularSensibility = 200;
-            this.moveSensibility = 75;
-            this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
-        }
-        GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
-            // Only the first gamepad can control the camera
-            if (gamepad.index === 0) {
-                this._gamepad = gamepad;
-            }
-        };
-        GamepadCamera.prototype._checkInputs = function () {
-            if (this._gamepad) {
-                var LSValues = this._gamepad.leftStick;
-                var normalizedLX = LSValues.x / this.moveSensibility;
-                var normalizedLY = LSValues.y / this.moveSensibility;
-                LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
-                LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
-                var RSValues = this._gamepad.rightStick;
-                var normalizedRX = RSValues.x / this.angularSensibility;
-                var normalizedRY = RSValues.y / this.angularSensibility;
-                RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
-                RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
-                var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
-                var speed = this._computeLocalCameraSpeed() * 50.0;
-                var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
-                this.cameraDirection = this.cameraDirection.add(deltaTransform);
-                this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
-            }
-            _super.prototype._checkInputs.call(this);
-        };
-        GamepadCamera.prototype.dispose = function () {
-            this._gamepads.dispose();
-            _super.prototype.dispose.call(this);
-        };
-        return GamepadCamera;
-    })(BABYLON.FreeCamera);
-    BABYLON.GamepadCamera = GamepadCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var GamepadCamera = (function (_super) {
+        __extends(GamepadCamera, _super);
+        function GamepadCamera(name, position, scene) {
+            var _this = this;
+            _super.call(this, name, position, scene);
+            this.angularSensibility = 200;
+            this.moveSensibility = 75;
+            this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
+        }
+        GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
+            // Only the first gamepad can control the camera
+            if (gamepad.index === 0) {
+                this._gamepad = gamepad;
+            }
+        };
+        GamepadCamera.prototype._checkInputs = function () {
+            if (this._gamepad) {
+                var LSValues = this._gamepad.leftStick;
+                var normalizedLX = LSValues.x / this.moveSensibility;
+                var normalizedLY = LSValues.y / this.moveSensibility;
+                LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
+                LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
+                var RSValues = this._gamepad.rightStick;
+                var normalizedRX = RSValues.x / this.angularSensibility;
+                var normalizedRY = RSValues.y / this.angularSensibility;
+                RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
+                RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
+                var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
+                var speed = this._computeLocalCameraSpeed() * 50.0;
+                var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
+                this.cameraDirection = this.cameraDirection.add(deltaTransform);
+                this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
+            }
+            _super.prototype._checkInputs.call(this);
+        };
+        GamepadCamera.prototype.dispose = function () {
+            this._gamepads.dispose();
+            _super.prototype.dispose.call(this);
+        };
+        return GamepadCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.GamepadCamera = GamepadCamera;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.gamepadCamera.js.map

+ 64 - 63
src/Cameras/babylon.stereoscopicCameras.js

@@ -1,63 +1,64 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var AnaglyphFreeCamera = (function (_super) {
-        __extends(AnaglyphFreeCamera, _super);
-        function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
-            _super.call(this, name, position, scene);
-            this.interaxialDistance = interaxialDistance;
-            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
-        }
-        return AnaglyphFreeCamera;
-    })(BABYLON.FreeCamera);
-    BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
-    var AnaglyphArcRotateCamera = (function (_super) {
-        __extends(AnaglyphArcRotateCamera, _super);
-        function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
-            _super.call(this, name, alpha, beta, radius, target, scene);
-            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
-        }
-        return AnaglyphArcRotateCamera;
-    })(BABYLON.ArcRotateCamera);
-    BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
-    var AnaglyphGamepadCamera = (function (_super) {
-        __extends(AnaglyphGamepadCamera, _super);
-        function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
-            _super.call(this, name, position, scene);
-            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
-        }
-        return AnaglyphGamepadCamera;
-    })(BABYLON.GamepadCamera);
-    BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
-    var StereoscopicFreeCamera = (function (_super) {
-        __extends(StereoscopicFreeCamera, _super);
-        function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
-            _super.call(this, name, position, scene);
-            this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
-        }
-        return StereoscopicFreeCamera;
-    })(BABYLON.FreeCamera);
-    BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
-    var StereoscopicArcRotateCamera = (function (_super) {
-        __extends(StereoscopicArcRotateCamera, _super);
-        function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
-            _super.call(this, name, alpha, beta, radius, target, scene);
-            this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
-        }
-        return StereoscopicArcRotateCamera;
-    })(BABYLON.ArcRotateCamera);
-    BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
-    var StereoscopicGamepadCamera = (function (_super) {
-        __extends(StereoscopicGamepadCamera, _super);
-        function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
-            _super.call(this, name, position, scene);
-            this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
-        }
-        return StereoscopicGamepadCamera;
-    })(BABYLON.GamepadCamera);
-    BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var AnaglyphFreeCamera = (function (_super) {
+        __extends(AnaglyphFreeCamera, _super);
+        function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
+            _super.call(this, name, position, scene);
+            this.interaxialDistance = interaxialDistance;
+            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
+        }
+        return AnaglyphFreeCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
+    var AnaglyphArcRotateCamera = (function (_super) {
+        __extends(AnaglyphArcRotateCamera, _super);
+        function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
+            _super.call(this, name, alpha, beta, radius, target, scene);
+            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
+        }
+        return AnaglyphArcRotateCamera;
+    })(BABYLON.ArcRotateCamera);
+    BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
+    var AnaglyphGamepadCamera = (function (_super) {
+        __extends(AnaglyphGamepadCamera, _super);
+        function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
+            _super.call(this, name, position, scene);
+            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
+        }
+        return AnaglyphGamepadCamera;
+    })(BABYLON.GamepadCamera);
+    BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
+    var StereoscopicFreeCamera = (function (_super) {
+        __extends(StereoscopicFreeCamera, _super);
+        function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
+            _super.call(this, name, position, scene);
+            this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
+        }
+        return StereoscopicFreeCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
+    var StereoscopicArcRotateCamera = (function (_super) {
+        __extends(StereoscopicArcRotateCamera, _super);
+        function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
+            _super.call(this, name, alpha, beta, radius, target, scene);
+            this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
+        }
+        return StereoscopicArcRotateCamera;
+    })(BABYLON.ArcRotateCamera);
+    BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
+    var StereoscopicGamepadCamera = (function (_super) {
+        __extends(StereoscopicGamepadCamera, _super);
+        function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
+            _super.call(this, name, position, scene);
+            this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
+        }
+        return StereoscopicGamepadCamera;
+    })(BABYLON.GamepadCamera);
+    BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.stereoscopicCameras.js.map

+ 258 - 257
src/Cameras/babylon.targetCamera.js

@@ -1,257 +1,258 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var TargetCamera = (function (_super) {
-        __extends(TargetCamera, _super);
-        function TargetCamera(name, position, scene) {
-            _super.call(this, name, position, scene);
-            this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
-            this.cameraRotation = new BABYLON.Vector2(0, 0);
-            this.rotation = new BABYLON.Vector3(0, 0, 0);
-            this.speed = 2.0;
-            this.noRotationConstraint = false;
-            this.lockedTarget = null;
-            this._currentTarget = BABYLON.Vector3.Zero();
-            this._viewMatrix = BABYLON.Matrix.Zero();
-            this._camMatrix = BABYLON.Matrix.Zero();
-            this._cameraTransformMatrix = BABYLON.Matrix.Zero();
-            this._cameraRotationMatrix = BABYLON.Matrix.Zero();
-            this._referencePoint = new BABYLON.Vector3(0, 0, 1);
-            this._transformedReferencePoint = BABYLON.Vector3.Zero();
-            this._lookAtTemp = BABYLON.Matrix.Zero();
-            this._tempMatrix = BABYLON.Matrix.Zero();
-        }
-        TargetCamera.prototype.getFrontPosition = function (distance) {
-            var direction = this.getTarget().subtract(this.position);
-            direction.normalize();
-            direction.scaleInPlace(distance);
-            return this.globalPosition.add(direction);
-        };
-        TargetCamera.prototype._getLockedTargetPosition = function () {
-            if (!this.lockedTarget) {
-                return null;
-            }
-            return this.lockedTarget.position || this.lockedTarget;
-        };
-        // Cache
-        TargetCamera.prototype._initCache = function () {
-            _super.prototype._initCache.call(this);
-            this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
-            this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
-        };
-        TargetCamera.prototype._updateCache = function (ignoreParentClass) {
-            if (!ignoreParentClass) {
-                _super.prototype._updateCache.call(this);
-            }
-            var lockedTargetPosition = this._getLockedTargetPosition();
-            if (!lockedTargetPosition) {
-                this._cache.lockedTarget = null;
-            }
-            else {
-                if (!this._cache.lockedTarget) {
-                    this._cache.lockedTarget = lockedTargetPosition.clone();
-                }
-                else {
-                    this._cache.lockedTarget.copyFrom(lockedTargetPosition);
-                }
-            }
-            this._cache.rotation.copyFrom(this.rotation);
-        };
-        // Synchronized
-        TargetCamera.prototype._isSynchronizedViewMatrix = function () {
-            if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
-                return false;
-            }
-            var lockedTargetPosition = this._getLockedTargetPosition();
-            return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
-                && this._cache.rotation.equals(this.rotation);
-        };
-        // Methods
-        TargetCamera.prototype._computeLocalCameraSpeed = function () {
-            var engine = this.getEngine();
-            return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
-        };
-        // Target
-        TargetCamera.prototype.setTarget = function (target) {
-            this.upVector.normalize();
-            BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
-            this._camMatrix.invert();
-            this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
-            var vDir = target.subtract(this.position);
-            if (vDir.x >= 0.0) {
-                this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
-            }
-            else {
-                this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
-            }
-            this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
-            if (isNaN(this.rotation.x)) {
-                this.rotation.x = 0;
-            }
-            if (isNaN(this.rotation.y)) {
-                this.rotation.y = 0;
-            }
-            if (isNaN(this.rotation.z)) {
-                this.rotation.z = 0;
-            }
-        };
-        TargetCamera.prototype.getTarget = function () {
-            return this._currentTarget;
-        };
-        TargetCamera.prototype._decideIfNeedsToMove = function () {
-            return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
-        };
-        TargetCamera.prototype._updatePosition = function () {
-            this.position.addInPlace(this.cameraDirection);
-        };
-        TargetCamera.prototype._checkInputs = function () {
-            var needToMove = this._decideIfNeedsToMove();
-            var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
-            // Move
-            if (needToMove) {
-                this._updatePosition();
-            }
-            // Rotate
-            if (needToRotate) {
-                this.rotation.x += this.cameraRotation.x;
-                this.rotation.y += this.cameraRotation.y;
-                if (!this.noRotationConstraint) {
-                    var limit = (Math.PI / 2) * 0.95;
-                    if (this.rotation.x > limit)
-                        this.rotation.x = limit;
-                    if (this.rotation.x < -limit)
-                        this.rotation.x = -limit;
-                }
-            }
-            // Inertia
-            if (needToMove) {
-                if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
-                    this.cameraDirection.x = 0;
-                }
-                if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
-                    this.cameraDirection.y = 0;
-                }
-                if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
-                    this.cameraDirection.z = 0;
-                }
-                this.cameraDirection.scaleInPlace(this.inertia);
-            }
-            if (needToRotate) {
-                if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
-                    this.cameraRotation.x = 0;
-                }
-                if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
-                    this.cameraRotation.y = 0;
-                }
-                this.cameraRotation.scaleInPlace(this.inertia);
-            }
-            _super.prototype._checkInputs.call(this);
-        };
-        TargetCamera.prototype._getViewMatrix = function () {
-            if (!this.lockedTarget) {
-                // Compute
-                if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
-                    BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
-                    BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
-                    this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
-                    this._lookAtTemp.invert();
-                    this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
-                }
-                else {
-                    BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
-                }
-                BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
-                // Computing target and final matrix
-                this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
-            }
-            else {
-                this._currentTarget.copyFrom(this._getLockedTargetPosition());
-            }
-            BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
-            return this._viewMatrix;
-        };
-        TargetCamera.prototype._getVRViewMatrix = function () {
-            BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
-            BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
-            BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
-            // Computing target and final matrix
-            this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
-            BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
-            this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
-            return this._viewMatrix;
-        };
-        /**
-         * @override
-         * Override Camera.createRigCamera
-         */
-        TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
-            if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
-                var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
-                if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
-                    rigCamera._cameraRigParams = {};
-                    rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
-                    rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
-                }
-                return rigCamera;
-            }
-            return null;
-        };
-        /**
-         * @override
-         * Override Camera._updateRigCameras
-         */
-        TargetCamera.prototype._updateRigCameras = function () {
-            switch (this.cameraRigMode) {
-                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
-                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
-                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
-                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
-                case BABYLON.Camera.RIG_MODE_VR:
-                    var camLeft = this._rigCameras[0];
-                    var camRight = this._rigCameras[1];
-                    if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
-                        camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
-                        camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
-                        camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
-                        camLeft.position.copyFrom(this.position);
-                        camRight.position.copyFrom(this.position);
-                    }
-                    else {
-                        //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
-                        this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
-                        this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
-                        camLeft.setTarget(this.getTarget());
-                        camRight.setTarget(this.getTarget());
-                    }
-                    break;
-            }
-            _super.prototype._updateRigCameras.call(this);
-        };
-        TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
-            if (!this._rigCamTransformMatrix) {
-                this._rigCamTransformMatrix = new BABYLON.Matrix();
-            }
-            var target = this.getTarget();
-            BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
-            this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
-            BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
-        };
-        TargetCamera.prototype.serialize = function () {
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.speed = this.speed;
-            if (this.rotation) {
-                serializationObject.rotation = this.rotation.asArray();
-            }
-            if (this.lockedTarget && this.lockedTarget.id) {
-                serializationObject.lockedTargetId = this.lockedTarget.id;
-            }
-            return serializationObject;
-        };
-        return TargetCamera;
-    })(BABYLON.Camera);
-    BABYLON.TargetCamera = TargetCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var TargetCamera = (function (_super) {
+        __extends(TargetCamera, _super);
+        function TargetCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
+            this.cameraRotation = new BABYLON.Vector2(0, 0);
+            this.rotation = new BABYLON.Vector3(0, 0, 0);
+            this.speed = 2.0;
+            this.noRotationConstraint = false;
+            this.lockedTarget = null;
+            this._currentTarget = BABYLON.Vector3.Zero();
+            this._viewMatrix = BABYLON.Matrix.Zero();
+            this._camMatrix = BABYLON.Matrix.Zero();
+            this._cameraTransformMatrix = BABYLON.Matrix.Zero();
+            this._cameraRotationMatrix = BABYLON.Matrix.Zero();
+            this._referencePoint = new BABYLON.Vector3(0, 0, 1);
+            this._transformedReferencePoint = BABYLON.Vector3.Zero();
+            this._lookAtTemp = BABYLON.Matrix.Zero();
+            this._tempMatrix = BABYLON.Matrix.Zero();
+        }
+        TargetCamera.prototype.getFrontPosition = function (distance) {
+            var direction = this.getTarget().subtract(this.position);
+            direction.normalize();
+            direction.scaleInPlace(distance);
+            return this.globalPosition.add(direction);
+        };
+        TargetCamera.prototype._getLockedTargetPosition = function () {
+            if (!this.lockedTarget) {
+                return null;
+            }
+            return this.lockedTarget.position || this.lockedTarget;
+        };
+        // Cache
+        TargetCamera.prototype._initCache = function () {
+            _super.prototype._initCache.call(this);
+            this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+            this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+        };
+        TargetCamera.prototype._updateCache = function (ignoreParentClass) {
+            if (!ignoreParentClass) {
+                _super.prototype._updateCache.call(this);
+            }
+            var lockedTargetPosition = this._getLockedTargetPosition();
+            if (!lockedTargetPosition) {
+                this._cache.lockedTarget = null;
+            }
+            else {
+                if (!this._cache.lockedTarget) {
+                    this._cache.lockedTarget = lockedTargetPosition.clone();
+                }
+                else {
+                    this._cache.lockedTarget.copyFrom(lockedTargetPosition);
+                }
+            }
+            this._cache.rotation.copyFrom(this.rotation);
+        };
+        // Synchronized
+        TargetCamera.prototype._isSynchronizedViewMatrix = function () {
+            if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
+                return false;
+            }
+            var lockedTargetPosition = this._getLockedTargetPosition();
+            return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
+                && this._cache.rotation.equals(this.rotation);
+        };
+        // Methods
+        TargetCamera.prototype._computeLocalCameraSpeed = function () {
+            var engine = this.getEngine();
+            return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
+        };
+        // Target
+        TargetCamera.prototype.setTarget = function (target) {
+            this.upVector.normalize();
+            BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
+            this._camMatrix.invert();
+            this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
+            var vDir = target.subtract(this.position);
+            if (vDir.x >= 0.0) {
+                this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
+            }
+            else {
+                this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
+            }
+            this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
+            if (isNaN(this.rotation.x)) {
+                this.rotation.x = 0;
+            }
+            if (isNaN(this.rotation.y)) {
+                this.rotation.y = 0;
+            }
+            if (isNaN(this.rotation.z)) {
+                this.rotation.z = 0;
+            }
+        };
+        TargetCamera.prototype.getTarget = function () {
+            return this._currentTarget;
+        };
+        TargetCamera.prototype._decideIfNeedsToMove = function () {
+            return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
+        };
+        TargetCamera.prototype._updatePosition = function () {
+            this.position.addInPlace(this.cameraDirection);
+        };
+        TargetCamera.prototype._checkInputs = function () {
+            var needToMove = this._decideIfNeedsToMove();
+            var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
+            // Move
+            if (needToMove) {
+                this._updatePosition();
+            }
+            // Rotate
+            if (needToRotate) {
+                this.rotation.x += this.cameraRotation.x;
+                this.rotation.y += this.cameraRotation.y;
+                if (!this.noRotationConstraint) {
+                    var limit = (Math.PI / 2) * 0.95;
+                    if (this.rotation.x > limit)
+                        this.rotation.x = limit;
+                    if (this.rotation.x < -limit)
+                        this.rotation.x = -limit;
+                }
+            }
+            // Inertia
+            if (needToMove) {
+                if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
+                    this.cameraDirection.x = 0;
+                }
+                if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
+                    this.cameraDirection.y = 0;
+                }
+                if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
+                    this.cameraDirection.z = 0;
+                }
+                this.cameraDirection.scaleInPlace(this.inertia);
+            }
+            if (needToRotate) {
+                if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
+                    this.cameraRotation.x = 0;
+                }
+                if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
+                    this.cameraRotation.y = 0;
+                }
+                this.cameraRotation.scaleInPlace(this.inertia);
+            }
+            _super.prototype._checkInputs.call(this);
+        };
+        TargetCamera.prototype._getViewMatrix = function () {
+            if (!this.lockedTarget) {
+                // Compute
+                if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
+                    BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
+                    BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
+                    this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
+                    this._lookAtTemp.invert();
+                    this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
+                }
+                else {
+                    BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
+                }
+                BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
+                // Computing target and final matrix
+                this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
+            }
+            else {
+                this._currentTarget.copyFrom(this._getLockedTargetPosition());
+            }
+            BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
+            return this._viewMatrix;
+        };
+        TargetCamera.prototype._getVRViewMatrix = function () {
+            BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
+            BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
+            BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
+            // Computing target and final matrix
+            this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
+            BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
+            this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
+            return this._viewMatrix;
+        };
+        /**
+         * @override
+         * Override Camera.createRigCamera
+         */
+        TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
+            if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
+                var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
+                if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
+                    rigCamera._cameraRigParams = {};
+                    rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
+                    rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
+                }
+                return rigCamera;
+            }
+            return null;
+        };
+        /**
+         * @override
+         * Override Camera._updateRigCameras
+         */
+        TargetCamera.prototype._updateRigCameras = function () {
+            switch (this.cameraRigMode) {
+                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
+                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
+                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
+                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
+                case BABYLON.Camera.RIG_MODE_VR:
+                    var camLeft = this._rigCameras[0];
+                    var camRight = this._rigCameras[1];
+                    if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
+                        camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
+                        camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
+                        camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
+                        camLeft.position.copyFrom(this.position);
+                        camRight.position.copyFrom(this.position);
+                    }
+                    else {
+                        //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
+                        this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
+                        this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
+                        camLeft.setTarget(this.getTarget());
+                        camRight.setTarget(this.getTarget());
+                    }
+                    break;
+            }
+            _super.prototype._updateRigCameras.call(this);
+        };
+        TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
+            if (!this._rigCamTransformMatrix) {
+                this._rigCamTransformMatrix = new BABYLON.Matrix();
+            }
+            var target = this.getTarget();
+            BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
+            this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
+            BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
+        };
+        TargetCamera.prototype.serialize = function () {
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.speed = this.speed;
+            if (this.rotation) {
+                serializationObject.rotation = this.rotation.asArray();
+            }
+            if (this.lockedTarget && this.lockedTarget.id) {
+                serializationObject.lockedTargetId = this.lockedTarget.id;
+            }
+            return serializationObject;
+        };
+        return TargetCamera;
+    })(BABYLON.Camera);
+    BABYLON.TargetCamera = TargetCamera;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.targetCamera.js.map

+ 120 - 119
src/Cameras/babylon.touchCamera.js

@@ -1,119 +1,120 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    // We're mainly based on the logic defined into the FreeCamera code
-    var TouchCamera = (function (_super) {
-        __extends(TouchCamera, _super);
-        function TouchCamera(name, position, scene) {
-            _super.call(this, name, position, scene);
-            this._offsetX = null;
-            this._offsetY = null;
-            this._pointerCount = 0;
-            this._pointerPressed = [];
-            this.touchAngularSensibility = 200000.0;
-            this.touchMoveSensibility = 500.0;
-        }
-        TouchCamera.prototype._onLostFocus = function (e) {
-            this._offsetX = null;
-            this._offsetY = null;
-            _super.prototype._onLostFocus.call(this, e);
-        };
-        TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
-            var _this = this;
-            var previousPosition;
-            if (this._attachedCanvas) {
-                return;
-            }
-            if (this._onPointerDown === undefined) {
-                this._onPointerDown = function (evt) {
-                    if (evt.pointerType === "mouse") {
-                        return;
-                    }
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                    _this._pointerPressed.push(evt.pointerId);
-                    if (_this._pointerPressed.length !== 1) {
-                        return;
-                    }
-                    previousPosition = {
-                        x: evt.clientX,
-                        y: evt.clientY
-                    };
-                };
-                this._onPointerUp = function (evt) {
-                    if (evt.pointerType === "mouse") {
-                        return;
-                    }
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                    var index = _this._pointerPressed.indexOf(evt.pointerId);
-                    if (index === -1) {
-                        return;
-                    }
-                    _this._pointerPressed.splice(index, 1);
-                    if (index != 0) {
-                        return;
-                    }
-                    previousPosition = null;
-                    _this._offsetX = null;
-                    _this._offsetY = null;
-                };
-                this._onPointerMove = function (evt) {
-                    if (evt.pointerType === "mouse") {
-                        return;
-                    }
-                    if (!noPreventDefault) {
-                        evt.preventDefault();
-                    }
-                    if (!previousPosition) {
-                        return;
-                    }
-                    var index = _this._pointerPressed.indexOf(evt.pointerId);
-                    if (index != 0) {
-                        return;
-                    }
-                    _this._offsetX = evt.clientX - previousPosition.x;
-                    _this._offsetY = -(evt.clientY - previousPosition.y);
-                };
-            }
-            canvas.addEventListener("pointerdown", this._onPointerDown);
-            canvas.addEventListener("pointerup", this._onPointerUp);
-            canvas.addEventListener("pointerout", this._onPointerUp);
-            canvas.addEventListener("pointermove", this._onPointerMove);
-            _super.prototype.attachControl.call(this, canvas);
-        };
-        TouchCamera.prototype.detachControl = function (canvas) {
-            if (this._attachedCanvas !== canvas) {
-                return;
-            }
-            canvas.removeEventListener("pointerdown", this._onPointerDown);
-            canvas.removeEventListener("pointerup", this._onPointerUp);
-            canvas.removeEventListener("pointerout", this._onPointerUp);
-            canvas.removeEventListener("pointermove", this._onPointerMove);
-            _super.prototype.detachControl.call(this, canvas);
-        };
-        TouchCamera.prototype._checkInputs = function () {
-            if (this._offsetX) {
-                this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
-                if (this._pointerPressed.length > 1) {
-                    this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
-                }
-                else {
-                    var speed = this._computeLocalCameraSpeed();
-                    var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
-                    BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
-                    this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
-                }
-            }
-            _super.prototype._checkInputs.call(this);
-        };
-        return TouchCamera;
-    })(BABYLON.FreeCamera);
-    BABYLON.TouchCamera = TouchCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var TouchCamera = (function (_super) {
+        __extends(TouchCamera, _super);
+        function TouchCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this._offsetX = null;
+            this._offsetY = null;
+            this._pointerCount = 0;
+            this._pointerPressed = [];
+            this.touchAngularSensibility = 200000.0;
+            this.touchMoveSensibility = 250.0;
+        }
+        TouchCamera.prototype._onLostFocus = function (e) {
+            this._offsetX = null;
+            this._offsetY = null;
+            _super.prototype._onLostFocus.call(this, e);
+        };
+        TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
+            var _this = this;
+            var previousPosition;
+            if (this._attachedCanvas) {
+                return;
+            }
+            if (this._onPointerDown === undefined) {
+                this._onPointerDown = function (evt) {
+                    if (evt.pointerType === "mouse") {
+                        return;
+                    }
+                    if (!noPreventDefault) {
+                        evt.preventDefault();
+                    }
+                    _this._pointerPressed.push(evt.pointerId);
+                    if (_this._pointerPressed.length !== 1) {
+                        return;
+                    }
+                    previousPosition = {
+                        x: evt.clientX,
+                        y: evt.clientY
+                    };
+                };
+                this._onPointerUp = function (evt) {
+                    if (evt.pointerType === "mouse") {
+                        return;
+                    }
+                    if (!noPreventDefault) {
+                        evt.preventDefault();
+                    }
+                    var index = _this._pointerPressed.indexOf(evt.pointerId);
+                    if (index === -1) {
+                        return;
+                    }
+                    _this._pointerPressed.splice(index, 1);
+                    if (index != 0) {
+                        return;
+                    }
+                    previousPosition = null;
+                    _this._offsetX = null;
+                    _this._offsetY = null;
+                };
+                this._onPointerMove = function (evt) {
+                    if (evt.pointerType === "mouse") {
+                        return;
+                    }
+                    if (!noPreventDefault) {
+                        evt.preventDefault();
+                    }
+                    if (!previousPosition) {
+                        return;
+                    }
+                    var index = _this._pointerPressed.indexOf(evt.pointerId);
+                    if (index != 0) {
+                        return;
+                    }
+                    _this._offsetX = evt.clientX - previousPosition.x;
+                    _this._offsetY = -(evt.clientY - previousPosition.y);
+                };
+            }
+            canvas.addEventListener("pointerdown", this._onPointerDown);
+            canvas.addEventListener("pointerup", this._onPointerUp);
+            canvas.addEventListener("pointerout", this._onPointerUp);
+            canvas.addEventListener("pointermove", this._onPointerMove);
+            _super.prototype.attachControl.call(this, canvas);
+        };
+        TouchCamera.prototype.detachControl = function (canvas) {
+            if (this._attachedCanvas !== canvas) {
+                return;
+            }
+            canvas.removeEventListener("pointerdown", this._onPointerDown);
+            canvas.removeEventListener("pointerup", this._onPointerUp);
+            canvas.removeEventListener("pointerout", this._onPointerUp);
+            canvas.removeEventListener("pointermove", this._onPointerMove);
+            _super.prototype.detachControl.call(this, canvas);
+        };
+        TouchCamera.prototype._checkInputs = function () {
+            if (this._offsetX) {
+                this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
+                if (this._pointerPressed.length > 1) {
+                    this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
+                }
+                else {
+                    var speed = this._computeLocalCameraSpeed();
+                    var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
+                    BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
+                    this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
+                }
+            }
+            _super.prototype._checkInputs.call(this);
+        };
+        return TouchCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.TouchCamera = TouchCamera;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.touchCamera.js.map

+ 1 - 1
src/Cameras/babylon.touchCamera.ts

@@ -11,7 +11,7 @@ module BABYLON {
         private _onPointerMove: (e: PointerEvent) => any;
 
         public touchAngularSensibility: number = 200000.0;
-        public touchMoveSensibility: number = 500.0;
+        public touchMoveSensibility: number = 250.0;
 
         constructor(name: string, position: Vector3, scene: Scene) {
             super(name, position, scene);

+ 52 - 51
src/Cameras/babylon.virtualJoysticksCamera.js

@@ -1,51 +1,52 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    // We're mainly based on the logic defined into the FreeCamera code
-    var VirtualJoysticksCamera = (function (_super) {
-        __extends(VirtualJoysticksCamera, _super);
-        function VirtualJoysticksCamera(name, position, scene) {
-            _super.call(this, name, position, scene);
-            this._leftjoystick = new BABYLON.VirtualJoystick(true);
-            this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
-            this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
-            this._leftjoystick.setJoystickSensibility(0.15);
-            this._rightjoystick = new BABYLON.VirtualJoystick(false);
-            this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
-            this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
-            this._rightjoystick.reverseUpDown = true;
-            this._rightjoystick.setJoystickSensibility(0.05);
-            this._rightjoystick.setJoystickColor("yellow");
-        }
-        VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
-            return this._leftjoystick;
-        };
-        VirtualJoysticksCamera.prototype.getRightJoystick = function () {
-            return this._rightjoystick;
-        };
-        VirtualJoysticksCamera.prototype._checkInputs = function () {
-            var speed = this._computeLocalCameraSpeed() * 50;
-            var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
-            var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
-            this.cameraDirection = this.cameraDirection.add(deltaTransform);
-            this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
-            if (!this._leftjoystick.pressed) {
-                this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
-            }
-            if (!this._rightjoystick.pressed) {
-                this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
-            }
-            _super.prototype._checkInputs.call(this);
-        };
-        VirtualJoysticksCamera.prototype.dispose = function () {
-            this._leftjoystick.releaseCanvas();
-            _super.prototype.dispose.call(this);
-        };
-        return VirtualJoysticksCamera;
-    })(BABYLON.FreeCamera);
-    BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    // We're mainly based on the logic defined into the FreeCamera code
+    var VirtualJoysticksCamera = (function (_super) {
+        __extends(VirtualJoysticksCamera, _super);
+        function VirtualJoysticksCamera(name, position, scene) {
+            _super.call(this, name, position, scene);
+            this._leftjoystick = new BABYLON.VirtualJoystick(true);
+            this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
+            this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
+            this._leftjoystick.setJoystickSensibility(0.15);
+            this._rightjoystick = new BABYLON.VirtualJoystick(false);
+            this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
+            this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
+            this._rightjoystick.reverseUpDown = true;
+            this._rightjoystick.setJoystickSensibility(0.05);
+            this._rightjoystick.setJoystickColor("yellow");
+        }
+        VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
+            return this._leftjoystick;
+        };
+        VirtualJoysticksCamera.prototype.getRightJoystick = function () {
+            return this._rightjoystick;
+        };
+        VirtualJoysticksCamera.prototype._checkInputs = function () {
+            var speed = this._computeLocalCameraSpeed() * 50;
+            var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
+            var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
+            this.cameraDirection = this.cameraDirection.add(deltaTransform);
+            this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
+            if (!this._leftjoystick.pressed) {
+                this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
+            }
+            if (!this._rightjoystick.pressed) {
+                this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
+            }
+            _super.prototype._checkInputs.call(this);
+        };
+        VirtualJoysticksCamera.prototype.dispose = function () {
+            this._leftjoystick.releaseCanvas();
+            _super.prototype.dispose.call(this);
+        };
+        return VirtualJoysticksCamera;
+    })(BABYLON.FreeCamera);
+    BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.virtualJoysticksCamera.js.map

+ 273 - 272
src/Collisions/babylon.collider.js

@@ -1,272 +1,273 @@
-var BABYLON;
-(function (BABYLON) {
-    var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
-        if (boxMin.x > sphereCenter.x + sphereRadius)
-            return false;
-        if (sphereCenter.x - sphereRadius > boxMax.x)
-            return false;
-        if (boxMin.y > sphereCenter.y + sphereRadius)
-            return false;
-        if (sphereCenter.y - sphereRadius > boxMax.y)
-            return false;
-        if (boxMin.z > sphereCenter.z + sphereRadius)
-            return false;
-        if (sphereCenter.z - sphereRadius > boxMax.z)
-            return false;
-        return true;
-    };
-    var getLowestRoot = function (a, b, c, maxR) {
-        var determinant = b * b - 4.0 * a * c;
-        var result = { root: 0, found: false };
-        if (determinant < 0)
-            return result;
-        var sqrtD = Math.sqrt(determinant);
-        var r1 = (-b - sqrtD) / (2.0 * a);
-        var r2 = (-b + sqrtD) / (2.0 * a);
-        if (r1 > r2) {
-            var temp = r2;
-            r2 = r1;
-            r1 = temp;
-        }
-        if (r1 > 0 && r1 < maxR) {
-            result.root = r1;
-            result.found = true;
-            return result;
-        }
-        if (r2 > 0 && r2 < maxR) {
-            result.root = r2;
-            result.found = true;
-            return result;
-        }
-        return result;
-    };
-    var Collider = (function () {
-        function Collider() {
-            this.radius = new BABYLON.Vector3(1, 1, 1);
-            this.retry = 0;
-            this.basePointWorld = BABYLON.Vector3.Zero();
-            this.velocityWorld = BABYLON.Vector3.Zero();
-            this.normalizedVelocity = BABYLON.Vector3.Zero();
-            this._collisionPoint = BABYLON.Vector3.Zero();
-            this._planeIntersectionPoint = BABYLON.Vector3.Zero();
-            this._tempVector = BABYLON.Vector3.Zero();
-            this._tempVector2 = BABYLON.Vector3.Zero();
-            this._tempVector3 = BABYLON.Vector3.Zero();
-            this._tempVector4 = BABYLON.Vector3.Zero();
-            this._edge = BABYLON.Vector3.Zero();
-            this._baseToVertex = BABYLON.Vector3.Zero();
-            this._destinationPoint = BABYLON.Vector3.Zero();
-            this._slidePlaneNormal = BABYLON.Vector3.Zero();
-            this._displacementVector = BABYLON.Vector3.Zero();
-        }
-        // Methods
-        Collider.prototype._initialize = function (source, dir, e) {
-            this.velocity = dir;
-            BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
-            this.basePoint = source;
-            source.multiplyToRef(this.radius, this.basePointWorld);
-            dir.multiplyToRef(this.radius, this.velocityWorld);
-            this.velocityWorldLength = this.velocityWorld.length();
-            this.epsilon = e;
-            this.collisionFound = false;
-        };
-        Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
-            pa.subtractToRef(point, this._tempVector);
-            pb.subtractToRef(point, this._tempVector2);
-            BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
-            var d = BABYLON.Vector3.Dot(this._tempVector4, n);
-            if (d < 0)
-                return false;
-            pc.subtractToRef(point, this._tempVector3);
-            BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
-            d = BABYLON.Vector3.Dot(this._tempVector4, n);
-            if (d < 0)
-                return false;
-            BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
-            d = BABYLON.Vector3.Dot(this._tempVector4, n);
-            return d >= 0;
-        };
-        Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
-            var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
-            var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
-            if (distance > this.velocityWorldLength + max + sphereRadius) {
-                return false;
-            }
-            if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
-                return false;
-            return true;
-        };
-        Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
-            var t0;
-            var embeddedInPlane = false;
-            //defensive programming, actually not needed.
-            if (!trianglePlaneArray) {
-                trianglePlaneArray = [];
-            }
-            if (!trianglePlaneArray[faceIndex]) {
-                trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
-                trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
-            }
-            var trianglePlane = trianglePlaneArray[faceIndex];
-            if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
-                return;
-            var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
-            var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
-            if (normalDotVelocity == 0) {
-                if (Math.abs(signedDistToTrianglePlane) >= 1.0)
-                    return;
-                embeddedInPlane = true;
-                t0 = 0;
-            }
-            else {
-                t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
-                var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
-                if (t0 > t1) {
-                    var temp = t1;
-                    t1 = t0;
-                    t0 = temp;
-                }
-                if (t0 > 1.0 || t1 < 0.0)
-                    return;
-                if (t0 < 0)
-                    t0 = 0;
-                if (t0 > 1.0)
-                    t0 = 1.0;
-            }
-            this._collisionPoint.copyFromFloats(0, 0, 0);
-            var found = false;
-            var t = 1.0;
-            if (!embeddedInPlane) {
-                this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
-                this.velocity.scaleToRef(t0, this._tempVector);
-                this._planeIntersectionPoint.addInPlace(this._tempVector);
-                if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
-                    found = true;
-                    t = t0;
-                    this._collisionPoint.copyFrom(this._planeIntersectionPoint);
-                }
-            }
-            if (!found) {
-                var velocitySquaredLength = this.velocity.lengthSquared();
-                var a = velocitySquaredLength;
-                this.basePoint.subtractToRef(p1, this._tempVector);
-                var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
-                var c = this._tempVector.lengthSquared() - 1.0;
-                var lowestRoot = getLowestRoot(a, b, c, t);
-                if (lowestRoot.found) {
-                    t = lowestRoot.root;
-                    found = true;
-                    this._collisionPoint.copyFrom(p1);
-                }
-                this.basePoint.subtractToRef(p2, this._tempVector);
-                b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
-                c = this._tempVector.lengthSquared() - 1.0;
-                lowestRoot = getLowestRoot(a, b, c, t);
-                if (lowestRoot.found) {
-                    t = lowestRoot.root;
-                    found = true;
-                    this._collisionPoint.copyFrom(p2);
-                }
-                this.basePoint.subtractToRef(p3, this._tempVector);
-                b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
-                c = this._tempVector.lengthSquared() - 1.0;
-                lowestRoot = getLowestRoot(a, b, c, t);
-                if (lowestRoot.found) {
-                    t = lowestRoot.root;
-                    found = true;
-                    this._collisionPoint.copyFrom(p3);
-                }
-                p2.subtractToRef(p1, this._edge);
-                p1.subtractToRef(this.basePoint, this._baseToVertex);
-                var edgeSquaredLength = this._edge.lengthSquared();
-                var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
-                var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
-                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
-                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
-                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
-                lowestRoot = getLowestRoot(a, b, c, t);
-                if (lowestRoot.found) {
-                    var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
-                    if (f >= 0.0 && f <= 1.0) {
-                        t = lowestRoot.root;
-                        found = true;
-                        this._edge.scaleInPlace(f);
-                        p1.addToRef(this._edge, this._collisionPoint);
-                    }
-                }
-                p3.subtractToRef(p2, this._edge);
-                p2.subtractToRef(this.basePoint, this._baseToVertex);
-                edgeSquaredLength = this._edge.lengthSquared();
-                edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
-                edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
-                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
-                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
-                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
-                lowestRoot = getLowestRoot(a, b, c, t);
-                if (lowestRoot.found) {
-                    f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
-                    if (f >= 0.0 && f <= 1.0) {
-                        t = lowestRoot.root;
-                        found = true;
-                        this._edge.scaleInPlace(f);
-                        p2.addToRef(this._edge, this._collisionPoint);
-                    }
-                }
-                p1.subtractToRef(p3, this._edge);
-                p3.subtractToRef(this.basePoint, this._baseToVertex);
-                edgeSquaredLength = this._edge.lengthSquared();
-                edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
-                edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
-                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
-                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
-                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
-                lowestRoot = getLowestRoot(a, b, c, t);
-                if (lowestRoot.found) {
-                    f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
-                    if (f >= 0.0 && f <= 1.0) {
-                        t = lowestRoot.root;
-                        found = true;
-                        this._edge.scaleInPlace(f);
-                        p3.addToRef(this._edge, this._collisionPoint);
-                    }
-                }
-            }
-            if (found) {
-                var distToCollision = t * this.velocity.length();
-                if (!this.collisionFound || distToCollision < this.nearestDistance) {
-                    if (!this.intersectionPoint) {
-                        this.intersectionPoint = this._collisionPoint.clone();
-                    }
-                    else {
-                        this.intersectionPoint.copyFrom(this._collisionPoint);
-                    }
-                    this.nearestDistance = distToCollision;
-                    this.collisionFound = true;
-                }
-            }
-        };
-        Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
-            for (var i = indexStart; i < indexEnd; i += 3) {
-                var p1 = pts[indices[i] - decal];
-                var p2 = pts[indices[i + 1] - decal];
-                var p3 = pts[indices[i + 2] - decal];
-                this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
-            }
-        };
-        Collider.prototype._getResponse = function (pos, vel) {
-            pos.addToRef(vel, this._destinationPoint);
-            vel.scaleInPlace((this.nearestDistance / vel.length()));
-            this.basePoint.addToRef(vel, pos);
-            pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
-            this._slidePlaneNormal.normalize();
-            this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
-            pos.addInPlace(this._displacementVector);
-            this.intersectionPoint.addInPlace(this._displacementVector);
-            this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
-            this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
-            this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
-        };
-        return Collider;
-    })();
-    BABYLON.Collider = Collider;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
+        if (boxMin.x > sphereCenter.x + sphereRadius)
+            return false;
+        if (sphereCenter.x - sphereRadius > boxMax.x)
+            return false;
+        if (boxMin.y > sphereCenter.y + sphereRadius)
+            return false;
+        if (sphereCenter.y - sphereRadius > boxMax.y)
+            return false;
+        if (boxMin.z > sphereCenter.z + sphereRadius)
+            return false;
+        if (sphereCenter.z - sphereRadius > boxMax.z)
+            return false;
+        return true;
+    };
+    var getLowestRoot = function (a, b, c, maxR) {
+        var determinant = b * b - 4.0 * a * c;
+        var result = { root: 0, found: false };
+        if (determinant < 0)
+            return result;
+        var sqrtD = Math.sqrt(determinant);
+        var r1 = (-b - sqrtD) / (2.0 * a);
+        var r2 = (-b + sqrtD) / (2.0 * a);
+        if (r1 > r2) {
+            var temp = r2;
+            r2 = r1;
+            r1 = temp;
+        }
+        if (r1 > 0 && r1 < maxR) {
+            result.root = r1;
+            result.found = true;
+            return result;
+        }
+        if (r2 > 0 && r2 < maxR) {
+            result.root = r2;
+            result.found = true;
+            return result;
+        }
+        return result;
+    };
+    var Collider = (function () {
+        function Collider() {
+            this.radius = new BABYLON.Vector3(1, 1, 1);
+            this.retry = 0;
+            this.basePointWorld = BABYLON.Vector3.Zero();
+            this.velocityWorld = BABYLON.Vector3.Zero();
+            this.normalizedVelocity = BABYLON.Vector3.Zero();
+            this._collisionPoint = BABYLON.Vector3.Zero();
+            this._planeIntersectionPoint = BABYLON.Vector3.Zero();
+            this._tempVector = BABYLON.Vector3.Zero();
+            this._tempVector2 = BABYLON.Vector3.Zero();
+            this._tempVector3 = BABYLON.Vector3.Zero();
+            this._tempVector4 = BABYLON.Vector3.Zero();
+            this._edge = BABYLON.Vector3.Zero();
+            this._baseToVertex = BABYLON.Vector3.Zero();
+            this._destinationPoint = BABYLON.Vector3.Zero();
+            this._slidePlaneNormal = BABYLON.Vector3.Zero();
+            this._displacementVector = BABYLON.Vector3.Zero();
+        }
+        // Methods
+        Collider.prototype._initialize = function (source, dir, e) {
+            this.velocity = dir;
+            BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
+            this.basePoint = source;
+            source.multiplyToRef(this.radius, this.basePointWorld);
+            dir.multiplyToRef(this.radius, this.velocityWorld);
+            this.velocityWorldLength = this.velocityWorld.length();
+            this.epsilon = e;
+            this.collisionFound = false;
+        };
+        Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
+            pa.subtractToRef(point, this._tempVector);
+            pb.subtractToRef(point, this._tempVector2);
+            BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
+            var d = BABYLON.Vector3.Dot(this._tempVector4, n);
+            if (d < 0)
+                return false;
+            pc.subtractToRef(point, this._tempVector3);
+            BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
+            d = BABYLON.Vector3.Dot(this._tempVector4, n);
+            if (d < 0)
+                return false;
+            BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
+            d = BABYLON.Vector3.Dot(this._tempVector4, n);
+            return d >= 0;
+        };
+        Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
+            var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
+            var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
+            if (distance > this.velocityWorldLength + max + sphereRadius) {
+                return false;
+            }
+            if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
+                return false;
+            return true;
+        };
+        Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
+            var t0;
+            var embeddedInPlane = false;
+            //defensive programming, actually not needed.
+            if (!trianglePlaneArray) {
+                trianglePlaneArray = [];
+            }
+            if (!trianglePlaneArray[faceIndex]) {
+                trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
+                trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
+            }
+            var trianglePlane = trianglePlaneArray[faceIndex];
+            if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
+                return;
+            var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
+            var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
+            if (normalDotVelocity == 0) {
+                if (Math.abs(signedDistToTrianglePlane) >= 1.0)
+                    return;
+                embeddedInPlane = true;
+                t0 = 0;
+            }
+            else {
+                t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
+                var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
+                if (t0 > t1) {
+                    var temp = t1;
+                    t1 = t0;
+                    t0 = temp;
+                }
+                if (t0 > 1.0 || t1 < 0.0)
+                    return;
+                if (t0 < 0)
+                    t0 = 0;
+                if (t0 > 1.0)
+                    t0 = 1.0;
+            }
+            this._collisionPoint.copyFromFloats(0, 0, 0);
+            var found = false;
+            var t = 1.0;
+            if (!embeddedInPlane) {
+                this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
+                this.velocity.scaleToRef(t0, this._tempVector);
+                this._planeIntersectionPoint.addInPlace(this._tempVector);
+                if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
+                    found = true;
+                    t = t0;
+                    this._collisionPoint.copyFrom(this._planeIntersectionPoint);
+                }
+            }
+            if (!found) {
+                var velocitySquaredLength = this.velocity.lengthSquared();
+                var a = velocitySquaredLength;
+                this.basePoint.subtractToRef(p1, this._tempVector);
+                var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
+                var c = this._tempVector.lengthSquared() - 1.0;
+                var lowestRoot = getLowestRoot(a, b, c, t);
+                if (lowestRoot.found) {
+                    t = lowestRoot.root;
+                    found = true;
+                    this._collisionPoint.copyFrom(p1);
+                }
+                this.basePoint.subtractToRef(p2, this._tempVector);
+                b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
+                c = this._tempVector.lengthSquared() - 1.0;
+                lowestRoot = getLowestRoot(a, b, c, t);
+                if (lowestRoot.found) {
+                    t = lowestRoot.root;
+                    found = true;
+                    this._collisionPoint.copyFrom(p2);
+                }
+                this.basePoint.subtractToRef(p3, this._tempVector);
+                b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
+                c = this._tempVector.lengthSquared() - 1.0;
+                lowestRoot = getLowestRoot(a, b, c, t);
+                if (lowestRoot.found) {
+                    t = lowestRoot.root;
+                    found = true;
+                    this._collisionPoint.copyFrom(p3);
+                }
+                p2.subtractToRef(p1, this._edge);
+                p1.subtractToRef(this.basePoint, this._baseToVertex);
+                var edgeSquaredLength = this._edge.lengthSquared();
+                var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
+                var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
+                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
+                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
+                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
+                lowestRoot = getLowestRoot(a, b, c, t);
+                if (lowestRoot.found) {
+                    var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
+                    if (f >= 0.0 && f <= 1.0) {
+                        t = lowestRoot.root;
+                        found = true;
+                        this._edge.scaleInPlace(f);
+                        p1.addToRef(this._edge, this._collisionPoint);
+                    }
+                }
+                p3.subtractToRef(p2, this._edge);
+                p2.subtractToRef(this.basePoint, this._baseToVertex);
+                edgeSquaredLength = this._edge.lengthSquared();
+                edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
+                edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
+                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
+                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
+                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
+                lowestRoot = getLowestRoot(a, b, c, t);
+                if (lowestRoot.found) {
+                    f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
+                    if (f >= 0.0 && f <= 1.0) {
+                        t = lowestRoot.root;
+                        found = true;
+                        this._edge.scaleInPlace(f);
+                        p2.addToRef(this._edge, this._collisionPoint);
+                    }
+                }
+                p1.subtractToRef(p3, this._edge);
+                p3.subtractToRef(this.basePoint, this._baseToVertex);
+                edgeSquaredLength = this._edge.lengthSquared();
+                edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
+                edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
+                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
+                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
+                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
+                lowestRoot = getLowestRoot(a, b, c, t);
+                if (lowestRoot.found) {
+                    f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
+                    if (f >= 0.0 && f <= 1.0) {
+                        t = lowestRoot.root;
+                        found = true;
+                        this._edge.scaleInPlace(f);
+                        p3.addToRef(this._edge, this._collisionPoint);
+                    }
+                }
+            }
+            if (found) {
+                var distToCollision = t * this.velocity.length();
+                if (!this.collisionFound || distToCollision < this.nearestDistance) {
+                    if (!this.intersectionPoint) {
+                        this.intersectionPoint = this._collisionPoint.clone();
+                    }
+                    else {
+                        this.intersectionPoint.copyFrom(this._collisionPoint);
+                    }
+                    this.nearestDistance = distToCollision;
+                    this.collisionFound = true;
+                }
+            }
+        };
+        Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
+            for (var i = indexStart; i < indexEnd; i += 3) {
+                var p1 = pts[indices[i] - decal];
+                var p2 = pts[indices[i + 1] - decal];
+                var p3 = pts[indices[i + 2] - decal];
+                this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
+            }
+        };
+        Collider.prototype._getResponse = function (pos, vel) {
+            pos.addToRef(vel, this._destinationPoint);
+            vel.scaleInPlace((this.nearestDistance / vel.length()));
+            this.basePoint.addToRef(vel, pos);
+            pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
+            this._slidePlaneNormal.normalize();
+            this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
+            pos.addInPlace(this._displacementVector);
+            this.intersectionPoint.addInPlace(this._displacementVector);
+            this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
+            this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
+            this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
+        };
+        return Collider;
+    })();
+    BABYLON.Collider = Collider;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.collider.js.map

+ 274 - 273
src/Collisions/babylon.collisionCoordinator.js

@@ -1,273 +1,274 @@
-var BABYLON;
-(function (BABYLON) {
-    //WebWorker code will be inserted to this variable.
-    BABYLON.CollisionWorker = "";
-    (function (WorkerTaskType) {
-        WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
-        WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
-        WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
-    })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
-    var WorkerTaskType = BABYLON.WorkerTaskType;
-    (function (WorkerReplyType) {
-        WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
-        WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
-    })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
-    var WorkerReplyType = BABYLON.WorkerReplyType;
-    var CollisionCoordinatorWorker = (function () {
-        function CollisionCoordinatorWorker() {
-            var _this = this;
-            this._scaledPosition = BABYLON.Vector3.Zero();
-            this._scaledVelocity = BABYLON.Vector3.Zero();
-            this.onMeshUpdated = function (mesh) {
-                _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
-            };
-            this.onGeometryUpdated = function (geometry) {
-                _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
-            };
-            this._afterRender = function () {
-                if (!_this._init)
-                    return;
-                if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
-                    return;
-                }
-                //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
-                //TODO make sure update runs as fast as possible to be able to update 60 FPS.
-                if (_this._runningUpdated > 4) {
-                    return;
-                }
-                ++_this._runningUpdated;
-                var payload = {
-                    updatedMeshes: _this._addUpdateMeshesList,
-                    updatedGeometries: _this._addUpdateGeometriesList,
-                    removedGeometries: _this._toRemoveGeometryArray,
-                    removedMeshes: _this._toRemoveMeshesArray
-                };
-                var message = {
-                    payload: payload,
-                    taskType: WorkerTaskType.UPDATE
-                };
-                var serializable = [];
-                for (var id in payload.updatedGeometries) {
-                    if (payload.updatedGeometries.hasOwnProperty(id)) {
-                        //prepare transferables
-                        serializable.push(message.payload.updatedGeometries[id].indices.buffer);
-                        serializable.push(message.payload.updatedGeometries[id].normals.buffer);
-                        serializable.push(message.payload.updatedGeometries[id].positions.buffer);
-                    }
-                }
-                _this._worker.postMessage(message, serializable);
-                _this._addUpdateMeshesList = {};
-                _this._addUpdateGeometriesList = {};
-                _this._toRemoveGeometryArray = [];
-                _this._toRemoveMeshesArray = [];
-            };
-            this._onMessageFromWorker = function (e) {
-                var returnData = e.data;
-                if (returnData.error != WorkerReplyType.SUCCESS) {
-                    //TODO what errors can be returned from the worker?
-                    BABYLON.Tools.Warn("error returned from worker!");
-                    return;
-                }
-                switch (returnData.taskType) {
-                    case WorkerTaskType.INIT:
-                        _this._init = true;
-                        //Update the worked with ALL of the scene's current state
-                        _this._scene.meshes.forEach(function (mesh) {
-                            _this.onMeshAdded(mesh);
-                        });
-                        _this._scene.getGeometries().forEach(function (geometry) {
-                            _this.onGeometryAdded(geometry);
-                        });
-                        break;
-                    case WorkerTaskType.UPDATE:
-                        _this._runningUpdated--;
-                        break;
-                    case WorkerTaskType.COLLIDE:
-                        _this._runningCollisionTask = false;
-                        var returnPayload = returnData.payload;
-                        if (!_this._collisionsCallbackArray[returnPayload.collisionId])
-                            return;
-                        _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
-                        //cleanup
-                        _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
-                        break;
-                }
-            };
-            this._collisionsCallbackArray = [];
-            this._init = false;
-            this._runningUpdated = 0;
-            this._runningCollisionTask = false;
-            this._addUpdateMeshesList = {};
-            this._addUpdateGeometriesList = {};
-            this._toRemoveGeometryArray = [];
-            this._toRemoveMeshesArray = [];
-        }
-        CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
-            if (!this._init)
-                return;
-            if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
-                return;
-            position.divideToRef(collider.radius, this._scaledPosition);
-            velocity.divideToRef(collider.radius, this._scaledVelocity);
-            this._collisionsCallbackArray[collisionIndex] = onNewPosition;
-            var payload = {
-                collider: {
-                    position: this._scaledPosition.asArray(),
-                    velocity: this._scaledVelocity.asArray(),
-                    radius: collider.radius.asArray()
-                },
-                collisionId: collisionIndex,
-                excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
-                maximumRetry: maximumRetry
-            };
-            var message = {
-                payload: payload,
-                taskType: WorkerTaskType.COLLIDE
-            };
-            this._worker.postMessage(message);
-        };
-        CollisionCoordinatorWorker.prototype.init = function (scene) {
-            this._scene = scene;
-            this._scene.registerAfterRender(this._afterRender);
-            var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
-            this._worker = new Worker(workerUrl);
-            this._worker.onmessage = this._onMessageFromWorker;
-            var message = {
-                payload: {},
-                taskType: WorkerTaskType.INIT
-            };
-            this._worker.postMessage(message);
-        };
-        CollisionCoordinatorWorker.prototype.destroy = function () {
-            this._scene.unregisterAfterRender(this._afterRender);
-            this._worker.terminate();
-        };
-        CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
-            mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
-            this.onMeshUpdated(mesh);
-        };
-        CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
-            this._toRemoveMeshesArray.push(mesh.uniqueId);
-        };
-        CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
-            //TODO this will break if the user uses his own function. This should be an array of callbacks!
-            geometry.onGeometryUpdated = this.onGeometryUpdated;
-            this.onGeometryUpdated(geometry);
-        };
-        CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
-            this._toRemoveGeometryArray.push(geometry.id);
-        };
-        CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
-            var submeshes = [];
-            if (mesh.subMeshes) {
-                submeshes = mesh.subMeshes.map(function (sm, idx) {
-                    return {
-                        position: idx,
-                        verticesStart: sm.verticesStart,
-                        verticesCount: sm.verticesCount,
-                        indexStart: sm.indexStart,
-                        indexCount: sm.indexCount,
-                        hasMaterial: !!sm.getMaterial(),
-                        sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
-                        sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
-                        boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
-                        boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
-                    };
-                });
-            }
-            var geometryId = null;
-            if (mesh instanceof BABYLON.Mesh) {
-                geometryId = mesh.geometry ? mesh.geometry.id : null;
-            }
-            else if (mesh instanceof BABYLON.InstancedMesh) {
-                geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
-            }
-            return {
-                uniqueId: mesh.uniqueId,
-                id: mesh.id,
-                name: mesh.name,
-                geometryId: geometryId,
-                sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
-                sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
-                boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
-                boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
-                worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
-                subMeshes: submeshes,
-                checkCollisions: mesh.checkCollisions
-            };
-        };
-        CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
-            return {
-                id: geometry.id,
-                positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
-                normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
-                indices: new Int32Array(geometry.getIndices() || []),
-            };
-        };
-        return CollisionCoordinatorWorker;
-    })();
-    BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
-    var CollisionCoordinatorLegacy = (function () {
-        function CollisionCoordinatorLegacy() {
-            this._scaledPosition = BABYLON.Vector3.Zero();
-            this._scaledVelocity = BABYLON.Vector3.Zero();
-            this._finalPosition = BABYLON.Vector3.Zero();
-        }
-        CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
-            position.divideToRef(collider.radius, this._scaledPosition);
-            velocity.divideToRef(collider.radius, this._scaledVelocity);
-            collider.collidedMesh = null;
-            collider.retry = 0;
-            collider.initialVelocity = this._scaledVelocity;
-            collider.initialPosition = this._scaledPosition;
-            this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
-            this._finalPosition.multiplyInPlace(collider.radius);
-            //run the callback
-            onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
-        };
-        CollisionCoordinatorLegacy.prototype.init = function (scene) {
-            this._scene = scene;
-        };
-        CollisionCoordinatorLegacy.prototype.destroy = function () {
-            //Legacy need no destruction method.
-        };
-        //No update in legacy mode
-        CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
-        CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
-        CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
-        CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
-        CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
-        CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
-        CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
-            if (excludedMesh === void 0) { excludedMesh = null; }
-            var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
-            if (collider.retry >= maximumRetry) {
-                finalPosition.copyFrom(position);
-                return;
-            }
-            collider._initialize(position, velocity, closeDistance);
-            // Check all meshes
-            for (var index = 0; index < this._scene.meshes.length; index++) {
-                var mesh = this._scene.meshes[index];
-                if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
-                    mesh._checkCollision(collider);
-                }
-            }
-            if (!collider.collisionFound) {
-                position.addToRef(velocity, finalPosition);
-                return;
-            }
-            if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
-                collider._getResponse(position, velocity);
-            }
-            if (velocity.length() <= closeDistance) {
-                finalPosition.copyFrom(position);
-                return;
-            }
-            collider.retry++;
-            this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
-        };
-        return CollisionCoordinatorLegacy;
-    })();
-    BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    //WebWorker code will be inserted to this variable.
+    BABYLON.CollisionWorker = "";
+    (function (WorkerTaskType) {
+        WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
+        WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
+        WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
+    })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
+    var WorkerTaskType = BABYLON.WorkerTaskType;
+    (function (WorkerReplyType) {
+        WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
+        WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
+    })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
+    var WorkerReplyType = BABYLON.WorkerReplyType;
+    var CollisionCoordinatorWorker = (function () {
+        function CollisionCoordinatorWorker() {
+            var _this = this;
+            this._scaledPosition = BABYLON.Vector3.Zero();
+            this._scaledVelocity = BABYLON.Vector3.Zero();
+            this.onMeshUpdated = function (mesh) {
+                _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
+            };
+            this.onGeometryUpdated = function (geometry) {
+                _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
+            };
+            this._afterRender = function () {
+                if (!_this._init)
+                    return;
+                if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
+                    return;
+                }
+                //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
+                //TODO make sure update runs as fast as possible to be able to update 60 FPS.
+                if (_this._runningUpdated > 4) {
+                    return;
+                }
+                ++_this._runningUpdated;
+                var payload = {
+                    updatedMeshes: _this._addUpdateMeshesList,
+                    updatedGeometries: _this._addUpdateGeometriesList,
+                    removedGeometries: _this._toRemoveGeometryArray,
+                    removedMeshes: _this._toRemoveMeshesArray
+                };
+                var message = {
+                    payload: payload,
+                    taskType: WorkerTaskType.UPDATE
+                };
+                var serializable = [];
+                for (var id in payload.updatedGeometries) {
+                    if (payload.updatedGeometries.hasOwnProperty(id)) {
+                        //prepare transferables
+                        serializable.push(message.payload.updatedGeometries[id].indices.buffer);
+                        serializable.push(message.payload.updatedGeometries[id].normals.buffer);
+                        serializable.push(message.payload.updatedGeometries[id].positions.buffer);
+                    }
+                }
+                _this._worker.postMessage(message, serializable);
+                _this._addUpdateMeshesList = {};
+                _this._addUpdateGeometriesList = {};
+                _this._toRemoveGeometryArray = [];
+                _this._toRemoveMeshesArray = [];
+            };
+            this._onMessageFromWorker = function (e) {
+                var returnData = e.data;
+                if (returnData.error != WorkerReplyType.SUCCESS) {
+                    //TODO what errors can be returned from the worker?
+                    BABYLON.Tools.Warn("error returned from worker!");
+                    return;
+                }
+                switch (returnData.taskType) {
+                    case WorkerTaskType.INIT:
+                        _this._init = true;
+                        //Update the worked with ALL of the scene's current state
+                        _this._scene.meshes.forEach(function (mesh) {
+                            _this.onMeshAdded(mesh);
+                        });
+                        _this._scene.getGeometries().forEach(function (geometry) {
+                            _this.onGeometryAdded(geometry);
+                        });
+                        break;
+                    case WorkerTaskType.UPDATE:
+                        _this._runningUpdated--;
+                        break;
+                    case WorkerTaskType.COLLIDE:
+                        _this._runningCollisionTask = false;
+                        var returnPayload = returnData.payload;
+                        if (!_this._collisionsCallbackArray[returnPayload.collisionId])
+                            return;
+                        _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
+                        //cleanup
+                        _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
+                        break;
+                }
+            };
+            this._collisionsCallbackArray = [];
+            this._init = false;
+            this._runningUpdated = 0;
+            this._runningCollisionTask = false;
+            this._addUpdateMeshesList = {};
+            this._addUpdateGeometriesList = {};
+            this._toRemoveGeometryArray = [];
+            this._toRemoveMeshesArray = [];
+        }
+        CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
+            if (!this._init)
+                return;
+            if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
+                return;
+            position.divideToRef(collider.radius, this._scaledPosition);
+            velocity.divideToRef(collider.radius, this._scaledVelocity);
+            this._collisionsCallbackArray[collisionIndex] = onNewPosition;
+            var payload = {
+                collider: {
+                    position: this._scaledPosition.asArray(),
+                    velocity: this._scaledVelocity.asArray(),
+                    radius: collider.radius.asArray()
+                },
+                collisionId: collisionIndex,
+                excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
+                maximumRetry: maximumRetry
+            };
+            var message = {
+                payload: payload,
+                taskType: WorkerTaskType.COLLIDE
+            };
+            this._worker.postMessage(message);
+        };
+        CollisionCoordinatorWorker.prototype.init = function (scene) {
+            this._scene = scene;
+            this._scene.registerAfterRender(this._afterRender);
+            var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
+            this._worker = new Worker(workerUrl);
+            this._worker.onmessage = this._onMessageFromWorker;
+            var message = {
+                payload: {},
+                taskType: WorkerTaskType.INIT
+            };
+            this._worker.postMessage(message);
+        };
+        CollisionCoordinatorWorker.prototype.destroy = function () {
+            this._scene.unregisterAfterRender(this._afterRender);
+            this._worker.terminate();
+        };
+        CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
+            mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
+            this.onMeshUpdated(mesh);
+        };
+        CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
+            this._toRemoveMeshesArray.push(mesh.uniqueId);
+        };
+        CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
+            //TODO this will break if the user uses his own function. This should be an array of callbacks!
+            geometry.onGeometryUpdated = this.onGeometryUpdated;
+            this.onGeometryUpdated(geometry);
+        };
+        CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
+            this._toRemoveGeometryArray.push(geometry.id);
+        };
+        CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
+            var submeshes = [];
+            if (mesh.subMeshes) {
+                submeshes = mesh.subMeshes.map(function (sm, idx) {
+                    return {
+                        position: idx,
+                        verticesStart: sm.verticesStart,
+                        verticesCount: sm.verticesCount,
+                        indexStart: sm.indexStart,
+                        indexCount: sm.indexCount,
+                        hasMaterial: !!sm.getMaterial(),
+                        sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
+                        sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
+                        boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
+                        boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
+                    };
+                });
+            }
+            var geometryId = null;
+            if (mesh instanceof BABYLON.Mesh) {
+                geometryId = mesh.geometry ? mesh.geometry.id : null;
+            }
+            else if (mesh instanceof BABYLON.InstancedMesh) {
+                geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
+            }
+            return {
+                uniqueId: mesh.uniqueId,
+                id: mesh.id,
+                name: mesh.name,
+                geometryId: geometryId,
+                sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
+                sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
+                boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
+                boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
+                worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
+                subMeshes: submeshes,
+                checkCollisions: mesh.checkCollisions
+            };
+        };
+        CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
+            return {
+                id: geometry.id,
+                positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
+                normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
+                indices: new Int32Array(geometry.getIndices() || []),
+            };
+        };
+        return CollisionCoordinatorWorker;
+    })();
+    BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
+    var CollisionCoordinatorLegacy = (function () {
+        function CollisionCoordinatorLegacy() {
+            this._scaledPosition = BABYLON.Vector3.Zero();
+            this._scaledVelocity = BABYLON.Vector3.Zero();
+            this._finalPosition = BABYLON.Vector3.Zero();
+        }
+        CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
+            position.divideToRef(collider.radius, this._scaledPosition);
+            velocity.divideToRef(collider.radius, this._scaledVelocity);
+            collider.collidedMesh = null;
+            collider.retry = 0;
+            collider.initialVelocity = this._scaledVelocity;
+            collider.initialPosition = this._scaledPosition;
+            this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
+            this._finalPosition.multiplyInPlace(collider.radius);
+            //run the callback
+            onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
+        };
+        CollisionCoordinatorLegacy.prototype.init = function (scene) {
+            this._scene = scene;
+        };
+        CollisionCoordinatorLegacy.prototype.destroy = function () {
+            //Legacy need no destruction method.
+        };
+        //No update in legacy mode
+        CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
+        CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
+        CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
+        CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
+        CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
+        CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
+        CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
+            if (excludedMesh === void 0) { excludedMesh = null; }
+            var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
+            if (collider.retry >= maximumRetry) {
+                finalPosition.copyFrom(position);
+                return;
+            }
+            collider._initialize(position, velocity, closeDistance);
+            // Check all meshes
+            for (var index = 0; index < this._scene.meshes.length; index++) {
+                var mesh = this._scene.meshes[index];
+                if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
+                    mesh._checkCollision(collider);
+                }
+            }
+            if (!collider.collisionFound) {
+                position.addToRef(velocity, finalPosition);
+                return;
+            }
+            if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
+                collider._getResponse(position, velocity);
+            }
+            if (velocity.length() <= closeDistance) {
+                finalPosition.copyFrom(position);
+                return;
+            }
+            collider.retry++;
+            this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
+        };
+        return CollisionCoordinatorLegacy;
+    })();
+    BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.collisionCoordinator.js.map

+ 244 - 243
src/Collisions/babylon.collisionWorker.js

@@ -1,243 +1,244 @@
-var BABYLON;
-(function (BABYLON) {
-    //If this file is included in the main thread, this will be initialized.
-    BABYLON.WorkerIncluded = true;
-    var CollisionCache = (function () {
-        function CollisionCache() {
-            this._meshes = {};
-            this._geometries = {};
-        }
-        CollisionCache.prototype.getMeshes = function () {
-            return this._meshes;
-        };
-        CollisionCache.prototype.getGeometries = function () {
-            return this._geometries;
-        };
-        CollisionCache.prototype.getMesh = function (id) {
-            return this._meshes[id];
-        };
-        CollisionCache.prototype.addMesh = function (mesh) {
-            this._meshes[mesh.uniqueId] = mesh;
-        };
-        CollisionCache.prototype.removeMesh = function (uniqueId) {
-            delete this._meshes[uniqueId];
-        };
-        CollisionCache.prototype.getGeometry = function (id) {
-            return this._geometries[id];
-        };
-        CollisionCache.prototype.addGeometry = function (geometry) {
-            this._geometries[geometry.id] = geometry;
-        };
-        CollisionCache.prototype.removeGeometry = function (id) {
-            delete this._geometries[id];
-        };
-        return CollisionCache;
-    })();
-    BABYLON.CollisionCache = CollisionCache;
-    var CollideWorker = (function () {
-        function CollideWorker(collider, _collisionCache, finalPosition) {
-            this.collider = collider;
-            this._collisionCache = _collisionCache;
-            this.finalPosition = finalPosition;
-            this.collisionsScalingMatrix = BABYLON.Matrix.Zero();
-            this.collisionTranformationMatrix = BABYLON.Matrix.Zero();
-        }
-        CollideWorker.prototype.collideWithWorld = function (position, velocity, maximumRetry, excludedMeshUniqueId) {
-            //TODO CollisionsEpsilon should be defined here and not in the engine.
-            var closeDistance = 0.01; //is initializing here correct? A quick look - looks like it is fine.
-            if (this.collider.retry >= maximumRetry) {
-                this.finalPosition.copyFrom(position);
-                return;
-            }
-            this.collider._initialize(position, velocity, closeDistance);
-            // Check all meshes
-            var meshes = this._collisionCache.getMeshes();
-            var keys = Object.keys(meshes);
-            var len = keys.length;
-            var uniqueId;
-            for (var i = 0; i < len; ++i) {
-                uniqueId = keys[i];
-                if (parseInt(uniqueId) != excludedMeshUniqueId) {
-                    var mesh = meshes[uniqueId];
-                    if (mesh.checkCollisions)
-                        this.checkCollision(mesh);
-                }
-            }
-            if (!this.collider.collisionFound) {
-                position.addToRef(velocity, this.finalPosition);
-                return;
-            }
-            if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
-                this.collider._getResponse(position, velocity);
-            }
-            if (velocity.length() <= closeDistance) {
-                this.finalPosition.copyFrom(position);
-                return;
-            }
-            this.collider.retry++;
-            this.collideWithWorld(position, velocity, maximumRetry, excludedMeshUniqueId);
-        };
-        CollideWorker.prototype.checkCollision = function (mesh) {
-            if (!this.collider._canDoCollision(BABYLON.Vector3.FromArray(mesh.sphereCenter), mesh.sphereRadius, BABYLON.Vector3.FromArray(mesh.boxMinimum), BABYLON.Vector3.FromArray(mesh.boxMaximum))) {
-                return;
-            }
-            ;
-            // Transformation matrix
-            BABYLON.Matrix.ScalingToRef(1.0 / this.collider.radius.x, 1.0 / this.collider.radius.y, 1.0 / this.collider.radius.z, this.collisionsScalingMatrix);
-            var worldFromCache = BABYLON.Matrix.FromArray(mesh.worldMatrixFromCache);
-            worldFromCache.multiplyToRef(this.collisionsScalingMatrix, this.collisionTranformationMatrix);
-            this.processCollisionsForSubMeshes(this.collisionTranformationMatrix, mesh);
-            //return colTransMat;
-        };
-        CollideWorker.prototype.processCollisionsForSubMeshes = function (transformMatrix, mesh) {
-            //if (this._submeshesOctree && this.useOctreeForCollisions) {
-            //    var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
-            //    var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
-            //    len = intersections.length;
-            //    subMeshes = intersections.data;
-            //} else {
-            var subMeshes = mesh.subMeshes;
-            var len = subMeshes.length;
-            //}
-            if (!mesh.geometryId) {
-                console.log("no mesh geometry id");
-                return;
-            }
-            var meshGeometry = this._collisionCache.getGeometry(mesh.geometryId);
-            if (!meshGeometry) {
-                console.log("couldn't find geometry", mesh.geometryId);
-                return;
-            }
-            for (var index = 0; index < len; index++) {
-                var subMesh = subMeshes[index];
-                // Bounding test
-                if (len > 1 && !this.checkSubmeshCollision(subMesh))
-                    continue;
-                this.collideForSubMesh(subMesh, transformMatrix, meshGeometry);
-                if (this.collider.collisionFound) {
-                    this.collider.collidedMesh = mesh.uniqueId;
-                }
-            }
-        };
-        CollideWorker.prototype.collideForSubMesh = function (subMesh, transformMatrix, meshGeometry) {
-            if (!meshGeometry['positionsArray']) {
-                meshGeometry['positionsArray'] = [];
-                for (var i = 0, len = meshGeometry.positions.length; i < len; i = i + 3) {
-                    var p = BABYLON.Vector3.FromArray([meshGeometry.positions[i], meshGeometry.positions[i + 1], meshGeometry.positions[i + 2]]);
-                    meshGeometry['positionsArray'].push(p);
-                }
-            }
-            if (!subMesh['_lastColliderWorldVertices'] || !subMesh['_lastColliderTransformMatrix'].equals(transformMatrix)) {
-                subMesh['_lastColliderTransformMatrix'] = transformMatrix.clone();
-                subMesh['_lastColliderWorldVertices'] = [];
-                subMesh['_trianglePlanes'] = [];
-                var start = subMesh.verticesStart;
-                var end = (subMesh.verticesStart + subMesh.verticesCount);
-                for (var i = start; i < end; i++) {
-                    subMesh['_lastColliderWorldVertices'].push(BABYLON.Vector3.TransformCoordinates(meshGeometry['positionsArray'][i], transformMatrix));
-                }
-            }
-            // Collide
-            this.collider._collide(subMesh['_trianglePlanes'], subMesh['_lastColliderWorldVertices'], meshGeometry.indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, subMesh.hasMaterial);
-        };
-        CollideWorker.prototype.checkSubmeshCollision = function (subMesh) {
-            return this.collider._canDoCollision(BABYLON.Vector3.FromArray(subMesh.sphereCenter), subMesh.sphereRadius, BABYLON.Vector3.FromArray(subMesh.boxMinimum), BABYLON.Vector3.FromArray(subMesh.boxMaximum));
-        };
-        return CollideWorker;
-    })();
-    BABYLON.CollideWorker = CollideWorker;
-    var CollisionDetectorTransferable = (function () {
-        function CollisionDetectorTransferable() {
-        }
-        CollisionDetectorTransferable.prototype.onInit = function (payload) {
-            this._collisionCache = new CollisionCache();
-            var reply = {
-                error: BABYLON.WorkerReplyType.SUCCESS,
-                taskType: BABYLON.WorkerTaskType.INIT
-            };
-            postMessage(reply, undefined);
-        };
-        CollisionDetectorTransferable.prototype.onUpdate = function (payload) {
-            var _this = this;
-            var replay = {
-                error: BABYLON.WorkerReplyType.SUCCESS,
-                taskType: BABYLON.WorkerTaskType.UPDATE
-            };
-            try {
-                for (var id in payload.updatedGeometries) {
-                    if (payload.updatedGeometries.hasOwnProperty(id)) {
-                        this._collisionCache.addGeometry(payload.updatedGeometries[id]);
-                    }
-                }
-                for (var uniqueId in payload.updatedMeshes) {
-                    if (payload.updatedMeshes.hasOwnProperty(uniqueId)) {
-                        this._collisionCache.addMesh(payload.updatedMeshes[uniqueId]);
-                    }
-                }
-                payload.removedGeometries.forEach(function (id) {
-                    _this._collisionCache.removeGeometry(id);
-                });
-                payload.removedMeshes.forEach(function (uniqueId) {
-                    _this._collisionCache.removeMesh(uniqueId);
-                });
-            }
-            catch (x) {
-                replay.error = BABYLON.WorkerReplyType.UNKNOWN_ERROR;
-            }
-            postMessage(replay, undefined);
-        };
-        CollisionDetectorTransferable.prototype.onCollision = function (payload) {
-            var finalPosition = BABYLON.Vector3.Zero();
-            //create a new collider
-            var collider = new BABYLON.Collider();
-            collider.radius = BABYLON.Vector3.FromArray(payload.collider.radius);
-            var colliderWorker = new CollideWorker(collider, this._collisionCache, finalPosition);
-            colliderWorker.collideWithWorld(BABYLON.Vector3.FromArray(payload.collider.position), BABYLON.Vector3.FromArray(payload.collider.velocity), payload.maximumRetry, payload.excludedMeshUniqueId);
-            var replyPayload = {
-                collidedMeshUniqueId: collider.collidedMesh,
-                collisionId: payload.collisionId,
-                newPosition: finalPosition.asArray()
-            };
-            var reply = {
-                error: BABYLON.WorkerReplyType.SUCCESS,
-                taskType: BABYLON.WorkerTaskType.COLLIDE,
-                payload: replyPayload
-            };
-            postMessage(reply, undefined);
-        };
-        return CollisionDetectorTransferable;
-    })();
-    BABYLON.CollisionDetectorTransferable = CollisionDetectorTransferable;
-    //check if we are in a web worker, as this code should NOT run on the main UI thread
-    try {
-        if (self && self instanceof WorkerGlobalScope) {
-            //Window hack to allow including babylonjs native code. the <any> is for typescript.
-            window = {};
-            //scripts were not included, standalone worker
-            if (!BABYLON.Collider) {
-                importScripts("./babylon.collisionCoordinator.js");
-                importScripts("./babylon.collider.js");
-                importScripts("../Math/babylon.math.js");
-            }
-            var collisionDetector = new CollisionDetectorTransferable();
-            var onNewMessage = function (event) {
-                var message = event.data;
-                switch (message.taskType) {
-                    case BABYLON.WorkerTaskType.INIT:
-                        collisionDetector.onInit(message.payload);
-                        break;
-                    case BABYLON.WorkerTaskType.COLLIDE:
-                        collisionDetector.onCollision(message.payload);
-                        break;
-                    case BABYLON.WorkerTaskType.UPDATE:
-                        collisionDetector.onUpdate(message.payload);
-                        break;
-                }
-            };
-            self.onmessage = onNewMessage;
-        }
-    }
-    catch (e) {
-        console.log("single worker init");
-    }
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    //If this file is included in the main thread, this will be initialized.
+    BABYLON.WorkerIncluded = true;
+    var CollisionCache = (function () {
+        function CollisionCache() {
+            this._meshes = {};
+            this._geometries = {};
+        }
+        CollisionCache.prototype.getMeshes = function () {
+            return this._meshes;
+        };
+        CollisionCache.prototype.getGeometries = function () {
+            return this._geometries;
+        };
+        CollisionCache.prototype.getMesh = function (id) {
+            return this._meshes[id];
+        };
+        CollisionCache.prototype.addMesh = function (mesh) {
+            this._meshes[mesh.uniqueId] = mesh;
+        };
+        CollisionCache.prototype.removeMesh = function (uniqueId) {
+            delete this._meshes[uniqueId];
+        };
+        CollisionCache.prototype.getGeometry = function (id) {
+            return this._geometries[id];
+        };
+        CollisionCache.prototype.addGeometry = function (geometry) {
+            this._geometries[geometry.id] = geometry;
+        };
+        CollisionCache.prototype.removeGeometry = function (id) {
+            delete this._geometries[id];
+        };
+        return CollisionCache;
+    })();
+    BABYLON.CollisionCache = CollisionCache;
+    var CollideWorker = (function () {
+        function CollideWorker(collider, _collisionCache, finalPosition) {
+            this.collider = collider;
+            this._collisionCache = _collisionCache;
+            this.finalPosition = finalPosition;
+            this.collisionsScalingMatrix = BABYLON.Matrix.Zero();
+            this.collisionTranformationMatrix = BABYLON.Matrix.Zero();
+        }
+        CollideWorker.prototype.collideWithWorld = function (position, velocity, maximumRetry, excludedMeshUniqueId) {
+            //TODO CollisionsEpsilon should be defined here and not in the engine.
+            var closeDistance = 0.01; //is initializing here correct? A quick look - looks like it is fine.
+            if (this.collider.retry >= maximumRetry) {
+                this.finalPosition.copyFrom(position);
+                return;
+            }
+            this.collider._initialize(position, velocity, closeDistance);
+            // Check all meshes
+            var meshes = this._collisionCache.getMeshes();
+            var keys = Object.keys(meshes);
+            var len = keys.length;
+            var uniqueId;
+            for (var i = 0; i < len; ++i) {
+                uniqueId = keys[i];
+                if (parseInt(uniqueId) != excludedMeshUniqueId) {
+                    var mesh = meshes[uniqueId];
+                    if (mesh.checkCollisions)
+                        this.checkCollision(mesh);
+                }
+            }
+            if (!this.collider.collisionFound) {
+                position.addToRef(velocity, this.finalPosition);
+                return;
+            }
+            if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
+                this.collider._getResponse(position, velocity);
+            }
+            if (velocity.length() <= closeDistance) {
+                this.finalPosition.copyFrom(position);
+                return;
+            }
+            this.collider.retry++;
+            this.collideWithWorld(position, velocity, maximumRetry, excludedMeshUniqueId);
+        };
+        CollideWorker.prototype.checkCollision = function (mesh) {
+            if (!this.collider._canDoCollision(BABYLON.Vector3.FromArray(mesh.sphereCenter), mesh.sphereRadius, BABYLON.Vector3.FromArray(mesh.boxMinimum), BABYLON.Vector3.FromArray(mesh.boxMaximum))) {
+                return;
+            }
+            ;
+            // Transformation matrix
+            BABYLON.Matrix.ScalingToRef(1.0 / this.collider.radius.x, 1.0 / this.collider.radius.y, 1.0 / this.collider.radius.z, this.collisionsScalingMatrix);
+            var worldFromCache = BABYLON.Matrix.FromArray(mesh.worldMatrixFromCache);
+            worldFromCache.multiplyToRef(this.collisionsScalingMatrix, this.collisionTranformationMatrix);
+            this.processCollisionsForSubMeshes(this.collisionTranformationMatrix, mesh);
+            //return colTransMat;
+        };
+        CollideWorker.prototype.processCollisionsForSubMeshes = function (transformMatrix, mesh) {
+            //if (this._submeshesOctree && this.useOctreeForCollisions) {
+            //    var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
+            //    var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
+            //    len = intersections.length;
+            //    subMeshes = intersections.data;
+            //} else {
+            var subMeshes = mesh.subMeshes;
+            var len = subMeshes.length;
+            //}
+            if (!mesh.geometryId) {
+                console.log("no mesh geometry id");
+                return;
+            }
+            var meshGeometry = this._collisionCache.getGeometry(mesh.geometryId);
+            if (!meshGeometry) {
+                console.log("couldn't find geometry", mesh.geometryId);
+                return;
+            }
+            for (var index = 0; index < len; index++) {
+                var subMesh = subMeshes[index];
+                // Bounding test
+                if (len > 1 && !this.checkSubmeshCollision(subMesh))
+                    continue;
+                this.collideForSubMesh(subMesh, transformMatrix, meshGeometry);
+                if (this.collider.collisionFound) {
+                    this.collider.collidedMesh = mesh.uniqueId;
+                }
+            }
+        };
+        CollideWorker.prototype.collideForSubMesh = function (subMesh, transformMatrix, meshGeometry) {
+            if (!meshGeometry['positionsArray']) {
+                meshGeometry['positionsArray'] = [];
+                for (var i = 0, len = meshGeometry.positions.length; i < len; i = i + 3) {
+                    var p = BABYLON.Vector3.FromArray([meshGeometry.positions[i], meshGeometry.positions[i + 1], meshGeometry.positions[i + 2]]);
+                    meshGeometry['positionsArray'].push(p);
+                }
+            }
+            if (!subMesh['_lastColliderWorldVertices'] || !subMesh['_lastColliderTransformMatrix'].equals(transformMatrix)) {
+                subMesh['_lastColliderTransformMatrix'] = transformMatrix.clone();
+                subMesh['_lastColliderWorldVertices'] = [];
+                subMesh['_trianglePlanes'] = [];
+                var start = subMesh.verticesStart;
+                var end = (subMesh.verticesStart + subMesh.verticesCount);
+                for (var i = start; i < end; i++) {
+                    subMesh['_lastColliderWorldVertices'].push(BABYLON.Vector3.TransformCoordinates(meshGeometry['positionsArray'][i], transformMatrix));
+                }
+            }
+            // Collide
+            this.collider._collide(subMesh['_trianglePlanes'], subMesh['_lastColliderWorldVertices'], meshGeometry.indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, subMesh.hasMaterial);
+        };
+        CollideWorker.prototype.checkSubmeshCollision = function (subMesh) {
+            return this.collider._canDoCollision(BABYLON.Vector3.FromArray(subMesh.sphereCenter), subMesh.sphereRadius, BABYLON.Vector3.FromArray(subMesh.boxMinimum), BABYLON.Vector3.FromArray(subMesh.boxMaximum));
+        };
+        return CollideWorker;
+    })();
+    BABYLON.CollideWorker = CollideWorker;
+    var CollisionDetectorTransferable = (function () {
+        function CollisionDetectorTransferable() {
+        }
+        CollisionDetectorTransferable.prototype.onInit = function (payload) {
+            this._collisionCache = new CollisionCache();
+            var reply = {
+                error: BABYLON.WorkerReplyType.SUCCESS,
+                taskType: BABYLON.WorkerTaskType.INIT
+            };
+            postMessage(reply, undefined);
+        };
+        CollisionDetectorTransferable.prototype.onUpdate = function (payload) {
+            var _this = this;
+            var replay = {
+                error: BABYLON.WorkerReplyType.SUCCESS,
+                taskType: BABYLON.WorkerTaskType.UPDATE
+            };
+            try {
+                for (var id in payload.updatedGeometries) {
+                    if (payload.updatedGeometries.hasOwnProperty(id)) {
+                        this._collisionCache.addGeometry(payload.updatedGeometries[id]);
+                    }
+                }
+                for (var uniqueId in payload.updatedMeshes) {
+                    if (payload.updatedMeshes.hasOwnProperty(uniqueId)) {
+                        this._collisionCache.addMesh(payload.updatedMeshes[uniqueId]);
+                    }
+                }
+                payload.removedGeometries.forEach(function (id) {
+                    _this._collisionCache.removeGeometry(id);
+                });
+                payload.removedMeshes.forEach(function (uniqueId) {
+                    _this._collisionCache.removeMesh(uniqueId);
+                });
+            }
+            catch (x) {
+                replay.error = BABYLON.WorkerReplyType.UNKNOWN_ERROR;
+            }
+            postMessage(replay, undefined);
+        };
+        CollisionDetectorTransferable.prototype.onCollision = function (payload) {
+            var finalPosition = BABYLON.Vector3.Zero();
+            //create a new collider
+            var collider = new BABYLON.Collider();
+            collider.radius = BABYLON.Vector3.FromArray(payload.collider.radius);
+            var colliderWorker = new CollideWorker(collider, this._collisionCache, finalPosition);
+            colliderWorker.collideWithWorld(BABYLON.Vector3.FromArray(payload.collider.position), BABYLON.Vector3.FromArray(payload.collider.velocity), payload.maximumRetry, payload.excludedMeshUniqueId);
+            var replyPayload = {
+                collidedMeshUniqueId: collider.collidedMesh,
+                collisionId: payload.collisionId,
+                newPosition: finalPosition.asArray()
+            };
+            var reply = {
+                error: BABYLON.WorkerReplyType.SUCCESS,
+                taskType: BABYLON.WorkerTaskType.COLLIDE,
+                payload: replyPayload
+            };
+            postMessage(reply, undefined);
+        };
+        return CollisionDetectorTransferable;
+    })();
+    BABYLON.CollisionDetectorTransferable = CollisionDetectorTransferable;
+    //check if we are in a web worker, as this code should NOT run on the main UI thread
+    try {
+        if (self && self instanceof WorkerGlobalScope) {
+            //Window hack to allow including babylonjs native code. the <any> is for typescript.
+            window = {};
+            //scripts were not included, standalone worker
+            if (!BABYLON.Collider) {
+                importScripts("./babylon.collisionCoordinator.js");
+                importScripts("./babylon.collider.js");
+                importScripts("../Math/babylon.math.js");
+            }
+            var collisionDetector = new CollisionDetectorTransferable();
+            var onNewMessage = function (event) {
+                var message = event.data;
+                switch (message.taskType) {
+                    case BABYLON.WorkerTaskType.INIT:
+                        collisionDetector.onInit(message.payload);
+                        break;
+                    case BABYLON.WorkerTaskType.COLLIDE:
+                        collisionDetector.onCollision(message.payload);
+                        break;
+                    case BABYLON.WorkerTaskType.UPDATE:
+                        collisionDetector.onUpdate(message.payload);
+                        break;
+                }
+            };
+            self.onmessage = onNewMessage;
+        }
+    }
+    catch (e) {
+        console.log("single worker init");
+    }
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.collisionWorker.js.map

+ 77 - 76
src/Collisions/babylon.pickingInfo.js

@@ -1,76 +1,77 @@
-var BABYLON;
-(function (BABYLON) {
-    var IntersectionInfo = (function () {
-        function IntersectionInfo(bu, bv, distance) {
-            this.bu = bu;
-            this.bv = bv;
-            this.distance = distance;
-            this.faceId = 0;
-            this.subMeshId = 0;
-        }
-        return IntersectionInfo;
-    })();
-    BABYLON.IntersectionInfo = IntersectionInfo;
-    var PickingInfo = (function () {
-        function PickingInfo() {
-            this.hit = false;
-            this.distance = 0;
-            this.pickedPoint = null;
-            this.pickedMesh = null;
-            this.bu = 0;
-            this.bv = 0;
-            this.faceId = -1;
-            this.subMeshId = 0;
-            this.pickedSprite = null;
-        }
-        // Methods
-        PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
-            if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
-            if (useVerticesNormals === void 0) { useVerticesNormals = true; }
-            if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
-                return null;
-            }
-            var indices = this.pickedMesh.getIndices();
-            var result;
-            if (useVerticesNormals) {
-                var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
-                var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
-                var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
-                var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
-                normal0 = normal0.scale(this.bu);
-                normal1 = normal1.scale(this.bv);
-                normal2 = normal2.scale(1.0 - this.bu - this.bv);
-                result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
-            }
-            else {
-                var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
-                var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
-                var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
-                var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
-                var p1p2 = vertex1.subtract(vertex2);
-                var p3p2 = vertex3.subtract(vertex2);
-                result = BABYLON.Vector3.Cross(p1p2, p3p2);
-            }
-            if (useWorldCoordinates) {
-                result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
-            }
-            return BABYLON.Vector3.Normalize(result);
-        };
-        PickingInfo.prototype.getTextureCoordinates = function () {
-            if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
-                return null;
-            }
-            var indices = this.pickedMesh.getIndices();
-            var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
-            var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
-            var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
-            var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
-            uv0 = uv0.scale(1.0 - this.bu - this.bv);
-            uv1 = uv1.scale(this.bu);
-            uv2 = uv2.scale(this.bv);
-            return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
-        };
-        return PickingInfo;
-    })();
-    BABYLON.PickingInfo = PickingInfo;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var IntersectionInfo = (function () {
+        function IntersectionInfo(bu, bv, distance) {
+            this.bu = bu;
+            this.bv = bv;
+            this.distance = distance;
+            this.faceId = 0;
+            this.subMeshId = 0;
+        }
+        return IntersectionInfo;
+    })();
+    BABYLON.IntersectionInfo = IntersectionInfo;
+    var PickingInfo = (function () {
+        function PickingInfo() {
+            this.hit = false;
+            this.distance = 0;
+            this.pickedPoint = null;
+            this.pickedMesh = null;
+            this.bu = 0;
+            this.bv = 0;
+            this.faceId = -1;
+            this.subMeshId = 0;
+            this.pickedSprite = null;
+        }
+        // Methods
+        PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
+            if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
+            if (useVerticesNormals === void 0) { useVerticesNormals = true; }
+            if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
+                return null;
+            }
+            var indices = this.pickedMesh.getIndices();
+            var result;
+            if (useVerticesNormals) {
+                var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
+                var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
+                var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
+                var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
+                normal0 = normal0.scale(this.bu);
+                normal1 = normal1.scale(this.bv);
+                normal2 = normal2.scale(1.0 - this.bu - this.bv);
+                result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
+            }
+            else {
+                var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
+                var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
+                var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
+                var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
+                var p1p2 = vertex1.subtract(vertex2);
+                var p3p2 = vertex3.subtract(vertex2);
+                result = BABYLON.Vector3.Cross(p1p2, p3p2);
+            }
+            if (useWorldCoordinates) {
+                result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
+            }
+            return BABYLON.Vector3.Normalize(result);
+        };
+        PickingInfo.prototype.getTextureCoordinates = function () {
+            if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
+                return null;
+            }
+            var indices = this.pickedMesh.getIndices();
+            var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
+            var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
+            var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
+            var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
+            uv0 = uv0.scale(1.0 - this.bu - this.bv);
+            uv1 = uv1.scale(this.bu);
+            uv2 = uv2.scale(this.bv);
+            return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
+        };
+        return PickingInfo;
+    })();
+    BABYLON.PickingInfo = PickingInfo;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.pickingInfo.js.map

+ 89 - 88
src/Culling/Octrees/babylon.octree.js

@@ -1,88 +1,89 @@
-var BABYLON;
-(function (BABYLON) {
-    var Octree = (function () {
-        function Octree(creationFunc, maxBlockCapacity, maxDepth) {
-            if (maxDepth === void 0) { maxDepth = 2; }
-            this.maxDepth = maxDepth;
-            this.dynamicContent = new Array();
-            this._maxBlockCapacity = maxBlockCapacity || 64;
-            this._selectionContent = new BABYLON.SmartArray(1024);
-            this._creationFunc = creationFunc;
-        }
-        // Methods
-        Octree.prototype.update = function (worldMin, worldMax, entries) {
-            Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
-        };
-        Octree.prototype.addMesh = function (entry) {
-            for (var index = 0; index < this.blocks.length; index++) {
-                var block = this.blocks[index];
-                block.addEntry(entry);
-            }
-        };
-        Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
-            this._selectionContent.reset();
-            for (var index = 0; index < this.blocks.length; index++) {
-                var block = this.blocks[index];
-                block.select(frustumPlanes, this._selectionContent, allowDuplicate);
-            }
-            if (allowDuplicate) {
-                this._selectionContent.concat(this.dynamicContent);
-            }
-            else {
-                this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
-            }
-            return this._selectionContent;
-        };
-        Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
-            this._selectionContent.reset();
-            for (var index = 0; index < this.blocks.length; index++) {
-                var block = this.blocks[index];
-                block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
-            }
-            if (allowDuplicate) {
-                this._selectionContent.concat(this.dynamicContent);
-            }
-            else {
-                this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
-            }
-            return this._selectionContent;
-        };
-        Octree.prototype.intersectsRay = function (ray) {
-            this._selectionContent.reset();
-            for (var index = 0; index < this.blocks.length; index++) {
-                var block = this.blocks[index];
-                block.intersectsRay(ray, this._selectionContent);
-            }
-            this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
-            return this._selectionContent;
-        };
-        Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
-            target.blocks = new Array();
-            var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
-            // Segmenting space
-            for (var x = 0; x < 2; x++) {
-                for (var y = 0; y < 2; y++) {
-                    for (var z = 0; z < 2; z++) {
-                        var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
-                        var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
-                        var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
-                        block.addEntries(entries);
-                        target.blocks.push(block);
-                    }
-                }
-            }
-        };
-        Octree.CreationFuncForMeshes = function (entry, block) {
-            if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
-                block.entries.push(entry);
-            }
-        };
-        Octree.CreationFuncForSubMeshes = function (entry, block) {
-            if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
-                block.entries.push(entry);
-            }
-        };
-        return Octree;
-    })();
-    BABYLON.Octree = Octree;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var Octree = (function () {
+        function Octree(creationFunc, maxBlockCapacity, maxDepth) {
+            if (maxDepth === void 0) { maxDepth = 2; }
+            this.maxDepth = maxDepth;
+            this.dynamicContent = new Array();
+            this._maxBlockCapacity = maxBlockCapacity || 64;
+            this._selectionContent = new BABYLON.SmartArray(1024);
+            this._creationFunc = creationFunc;
+        }
+        // Methods
+        Octree.prototype.update = function (worldMin, worldMax, entries) {
+            Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
+        };
+        Octree.prototype.addMesh = function (entry) {
+            for (var index = 0; index < this.blocks.length; index++) {
+                var block = this.blocks[index];
+                block.addEntry(entry);
+            }
+        };
+        Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
+            this._selectionContent.reset();
+            for (var index = 0; index < this.blocks.length; index++) {
+                var block = this.blocks[index];
+                block.select(frustumPlanes, this._selectionContent, allowDuplicate);
+            }
+            if (allowDuplicate) {
+                this._selectionContent.concat(this.dynamicContent);
+            }
+            else {
+                this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
+            }
+            return this._selectionContent;
+        };
+        Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
+            this._selectionContent.reset();
+            for (var index = 0; index < this.blocks.length; index++) {
+                var block = this.blocks[index];
+                block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
+            }
+            if (allowDuplicate) {
+                this._selectionContent.concat(this.dynamicContent);
+            }
+            else {
+                this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
+            }
+            return this._selectionContent;
+        };
+        Octree.prototype.intersectsRay = function (ray) {
+            this._selectionContent.reset();
+            for (var index = 0; index < this.blocks.length; index++) {
+                var block = this.blocks[index];
+                block.intersectsRay(ray, this._selectionContent);
+            }
+            this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
+            return this._selectionContent;
+        };
+        Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
+            target.blocks = new Array();
+            var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
+            // Segmenting space
+            for (var x = 0; x < 2; x++) {
+                for (var y = 0; y < 2; y++) {
+                    for (var z = 0; z < 2; z++) {
+                        var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
+                        var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
+                        var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
+                        block.addEntries(entries);
+                        target.blocks.push(block);
+                    }
+                }
+            }
+        };
+        Octree.CreationFuncForMeshes = function (entry, block) {
+            if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
+                block.entries.push(entry);
+            }
+        };
+        Octree.CreationFuncForSubMeshes = function (entry, block) {
+            if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
+                block.entries.push(entry);
+            }
+        };
+        return Octree;
+    })();
+    BABYLON.Octree = Octree;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.octree.js.map

+ 123 - 122
src/Culling/Octrees/babylon.octreeBlock.js

@@ -1,122 +1,123 @@
-var BABYLON;
-(function (BABYLON) {
-    var OctreeBlock = (function () {
-        function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
-            this.entries = new Array();
-            this._boundingVectors = new Array();
-            this._capacity = capacity;
-            this._depth = depth;
-            this._maxDepth = maxDepth;
-            this._creationFunc = creationFunc;
-            this._minPoint = minPoint;
-            this._maxPoint = maxPoint;
-            this._boundingVectors.push(minPoint.clone());
-            this._boundingVectors.push(maxPoint.clone());
-            this._boundingVectors.push(minPoint.clone());
-            this._boundingVectors[2].x = maxPoint.x;
-            this._boundingVectors.push(minPoint.clone());
-            this._boundingVectors[3].y = maxPoint.y;
-            this._boundingVectors.push(minPoint.clone());
-            this._boundingVectors[4].z = maxPoint.z;
-            this._boundingVectors.push(maxPoint.clone());
-            this._boundingVectors[5].z = minPoint.z;
-            this._boundingVectors.push(maxPoint.clone());
-            this._boundingVectors[6].x = minPoint.x;
-            this._boundingVectors.push(maxPoint.clone());
-            this._boundingVectors[7].y = minPoint.y;
-        }
-        Object.defineProperty(OctreeBlock.prototype, "capacity", {
-            // Property
-            get: function () {
-                return this._capacity;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(OctreeBlock.prototype, "minPoint", {
-            get: function () {
-                return this._minPoint;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
-            get: function () {
-                return this._maxPoint;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        // Methods
-        OctreeBlock.prototype.addEntry = function (entry) {
-            if (this.blocks) {
-                for (var index = 0; index < this.blocks.length; index++) {
-                    var block = this.blocks[index];
-                    block.addEntry(entry);
-                }
-                return;
-            }
-            this._creationFunc(entry, this);
-            if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
-                this.createInnerBlocks();
-            }
-        };
-        OctreeBlock.prototype.addEntries = function (entries) {
-            for (var index = 0; index < entries.length; index++) {
-                var mesh = entries[index];
-                this.addEntry(mesh);
-            }
-        };
-        OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
-            if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
-                if (this.blocks) {
-                    for (var index = 0; index < this.blocks.length; index++) {
-                        var block = this.blocks[index];
-                        block.select(frustumPlanes, selection, allowDuplicate);
-                    }
-                    return;
-                }
-                if (allowDuplicate) {
-                    selection.concat(this.entries);
-                }
-                else {
-                    selection.concatWithNoDuplicate(this.entries);
-                }
-            }
-        };
-        OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
-            if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
-                if (this.blocks) {
-                    for (var index = 0; index < this.blocks.length; index++) {
-                        var block = this.blocks[index];
-                        block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
-                    }
-                    return;
-                }
-                if (allowDuplicate) {
-                    selection.concat(this.entries);
-                }
-                else {
-                    selection.concatWithNoDuplicate(this.entries);
-                }
-            }
-        };
-        OctreeBlock.prototype.intersectsRay = function (ray, selection) {
-            if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
-                if (this.blocks) {
-                    for (var index = 0; index < this.blocks.length; index++) {
-                        var block = this.blocks[index];
-                        block.intersectsRay(ray, selection);
-                    }
-                    return;
-                }
-                selection.concatWithNoDuplicate(this.entries);
-            }
-        };
-        OctreeBlock.prototype.createInnerBlocks = function () {
-            BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
-        };
-        return OctreeBlock;
-    })();
-    BABYLON.OctreeBlock = OctreeBlock;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var OctreeBlock = (function () {
+        function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
+            this.entries = new Array();
+            this._boundingVectors = new Array();
+            this._capacity = capacity;
+            this._depth = depth;
+            this._maxDepth = maxDepth;
+            this._creationFunc = creationFunc;
+            this._minPoint = minPoint;
+            this._maxPoint = maxPoint;
+            this._boundingVectors.push(minPoint.clone());
+            this._boundingVectors.push(maxPoint.clone());
+            this._boundingVectors.push(minPoint.clone());
+            this._boundingVectors[2].x = maxPoint.x;
+            this._boundingVectors.push(minPoint.clone());
+            this._boundingVectors[3].y = maxPoint.y;
+            this._boundingVectors.push(minPoint.clone());
+            this._boundingVectors[4].z = maxPoint.z;
+            this._boundingVectors.push(maxPoint.clone());
+            this._boundingVectors[5].z = minPoint.z;
+            this._boundingVectors.push(maxPoint.clone());
+            this._boundingVectors[6].x = minPoint.x;
+            this._boundingVectors.push(maxPoint.clone());
+            this._boundingVectors[7].y = minPoint.y;
+        }
+        Object.defineProperty(OctreeBlock.prototype, "capacity", {
+            // Property
+            get: function () {
+                return this._capacity;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(OctreeBlock.prototype, "minPoint", {
+            get: function () {
+                return this._minPoint;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
+            get: function () {
+                return this._maxPoint;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        // Methods
+        OctreeBlock.prototype.addEntry = function (entry) {
+            if (this.blocks) {
+                for (var index = 0; index < this.blocks.length; index++) {
+                    var block = this.blocks[index];
+                    block.addEntry(entry);
+                }
+                return;
+            }
+            this._creationFunc(entry, this);
+            if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
+                this.createInnerBlocks();
+            }
+        };
+        OctreeBlock.prototype.addEntries = function (entries) {
+            for (var index = 0; index < entries.length; index++) {
+                var mesh = entries[index];
+                this.addEntry(mesh);
+            }
+        };
+        OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
+            if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
+                if (this.blocks) {
+                    for (var index = 0; index < this.blocks.length; index++) {
+                        var block = this.blocks[index];
+                        block.select(frustumPlanes, selection, allowDuplicate);
+                    }
+                    return;
+                }
+                if (allowDuplicate) {
+                    selection.concat(this.entries);
+                }
+                else {
+                    selection.concatWithNoDuplicate(this.entries);
+                }
+            }
+        };
+        OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
+            if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
+                if (this.blocks) {
+                    for (var index = 0; index < this.blocks.length; index++) {
+                        var block = this.blocks[index];
+                        block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
+                    }
+                    return;
+                }
+                if (allowDuplicate) {
+                    selection.concat(this.entries);
+                }
+                else {
+                    selection.concatWithNoDuplicate(this.entries);
+                }
+            }
+        };
+        OctreeBlock.prototype.intersectsRay = function (ray, selection) {
+            if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
+                if (this.blocks) {
+                    for (var index = 0; index < this.blocks.length; index++) {
+                        var block = this.blocks[index];
+                        block.intersectsRay(ray, selection);
+                    }
+                    return;
+                }
+                selection.concatWithNoDuplicate(this.entries);
+            }
+        };
+        OctreeBlock.prototype.createInnerBlocks = function () {
+            BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
+        };
+        return OctreeBlock;
+    })();
+    BABYLON.OctreeBlock = OctreeBlock;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.octreeBlock.js.map

+ 140 - 139
src/Culling/babylon.boundingBox.js

@@ -1,139 +1,140 @@
-var BABYLON;
-(function (BABYLON) {
-    var BoundingBox = (function () {
-        function BoundingBox(minimum, maximum) {
-            this.minimum = minimum;
-            this.maximum = maximum;
-            this.vectors = new Array();
-            this.vectorsWorld = new Array();
-            // Bounding vectors            
-            this.vectors.push(this.minimum.clone());
-            this.vectors.push(this.maximum.clone());
-            this.vectors.push(this.minimum.clone());
-            this.vectors[2].x = this.maximum.x;
-            this.vectors.push(this.minimum.clone());
-            this.vectors[3].y = this.maximum.y;
-            this.vectors.push(this.minimum.clone());
-            this.vectors[4].z = this.maximum.z;
-            this.vectors.push(this.maximum.clone());
-            this.vectors[5].z = this.minimum.z;
-            this.vectors.push(this.maximum.clone());
-            this.vectors[6].x = this.minimum.x;
-            this.vectors.push(this.maximum.clone());
-            this.vectors[7].y = this.minimum.y;
-            // OBB
-            this.center = this.maximum.add(this.minimum).scale(0.5);
-            this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
-            this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
-            // World
-            for (var index = 0; index < this.vectors.length; index++) {
-                this.vectorsWorld[index] = BABYLON.Vector3.Zero();
-            }
-            this.minimumWorld = BABYLON.Vector3.Zero();
-            this.maximumWorld = BABYLON.Vector3.Zero();
-            this._update(BABYLON.Matrix.Identity());
-        }
-        // Methods
-        BoundingBox.prototype.getWorldMatrix = function () {
-            return this._worldMatrix;
-        };
-        BoundingBox.prototype._update = function (world) {
-            BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
-            BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
-            for (var index = 0; index < this.vectors.length; index++) {
-                var v = this.vectorsWorld[index];
-                BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
-                if (v.x < this.minimumWorld.x)
-                    this.minimumWorld.x = v.x;
-                if (v.y < this.minimumWorld.y)
-                    this.minimumWorld.y = v.y;
-                if (v.z < this.minimumWorld.z)
-                    this.minimumWorld.z = v.z;
-                if (v.x > this.maximumWorld.x)
-                    this.maximumWorld.x = v.x;
-                if (v.y > this.maximumWorld.y)
-                    this.maximumWorld.y = v.y;
-                if (v.z > this.maximumWorld.z)
-                    this.maximumWorld.z = v.z;
-            }
-            // OBB
-            this.maximumWorld.addToRef(this.minimumWorld, this.center);
-            this.center.scaleInPlace(0.5);
-            BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
-            BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
-            BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
-            this._worldMatrix = world;
-        };
-        BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
-            return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
-        };
-        BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
-            return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
-        };
-        BoundingBox.prototype.intersectsPoint = function (point) {
-            var delta = -BABYLON.Engine.Epsilon;
-            if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
-                return false;
-            if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
-                return false;
-            if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
-                return false;
-            return true;
-        };
-        BoundingBox.prototype.intersectsSphere = function (sphere) {
-            return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
-        };
-        BoundingBox.prototype.intersectsMinMax = function (min, max) {
-            if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
-                return false;
-            if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
-                return false;
-            if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
-                return false;
-            return true;
-        };
-        // Statics
-        BoundingBox.Intersects = function (box0, box1) {
-            if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
-                return false;
-            if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
-                return false;
-            if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
-                return false;
-            return true;
-        };
-        BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
-            var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
-            var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
-            return (num <= (sphereRadius * sphereRadius));
-        };
-        BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
-            for (var p = 0; p < 6; p++) {
-                for (var i = 0; i < 8; i++) {
-                    if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
-                        return false;
-                    }
-                }
-            }
-            return true;
-        };
-        BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
-            for (var p = 0; p < 6; p++) {
-                var inCount = 8;
-                for (var i = 0; i < 8; i++) {
-                    if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
-                        --inCount;
-                    }
-                    else {
-                        break;
-                    }
-                }
-                if (inCount === 0)
-                    return false;
-            }
-            return true;
-        };
-        return BoundingBox;
-    })();
-    BABYLON.BoundingBox = BoundingBox;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var BoundingBox = (function () {
+        function BoundingBox(minimum, maximum) {
+            this.minimum = minimum;
+            this.maximum = maximum;
+            this.vectors = new Array();
+            this.vectorsWorld = new Array();
+            // Bounding vectors            
+            this.vectors.push(this.minimum.clone());
+            this.vectors.push(this.maximum.clone());
+            this.vectors.push(this.minimum.clone());
+            this.vectors[2].x = this.maximum.x;
+            this.vectors.push(this.minimum.clone());
+            this.vectors[3].y = this.maximum.y;
+            this.vectors.push(this.minimum.clone());
+            this.vectors[4].z = this.maximum.z;
+            this.vectors.push(this.maximum.clone());
+            this.vectors[5].z = this.minimum.z;
+            this.vectors.push(this.maximum.clone());
+            this.vectors[6].x = this.minimum.x;
+            this.vectors.push(this.maximum.clone());
+            this.vectors[7].y = this.minimum.y;
+            // OBB
+            this.center = this.maximum.add(this.minimum).scale(0.5);
+            this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
+            this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
+            // World
+            for (var index = 0; index < this.vectors.length; index++) {
+                this.vectorsWorld[index] = BABYLON.Vector3.Zero();
+            }
+            this.minimumWorld = BABYLON.Vector3.Zero();
+            this.maximumWorld = BABYLON.Vector3.Zero();
+            this._update(BABYLON.Matrix.Identity());
+        }
+        // Methods
+        BoundingBox.prototype.getWorldMatrix = function () {
+            return this._worldMatrix;
+        };
+        BoundingBox.prototype._update = function (world) {
+            BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
+            BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
+            for (var index = 0; index < this.vectors.length; index++) {
+                var v = this.vectorsWorld[index];
+                BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
+                if (v.x < this.minimumWorld.x)
+                    this.minimumWorld.x = v.x;
+                if (v.y < this.minimumWorld.y)
+                    this.minimumWorld.y = v.y;
+                if (v.z < this.minimumWorld.z)
+                    this.minimumWorld.z = v.z;
+                if (v.x > this.maximumWorld.x)
+                    this.maximumWorld.x = v.x;
+                if (v.y > this.maximumWorld.y)
+                    this.maximumWorld.y = v.y;
+                if (v.z > this.maximumWorld.z)
+                    this.maximumWorld.z = v.z;
+            }
+            // OBB
+            this.maximumWorld.addToRef(this.minimumWorld, this.center);
+            this.center.scaleInPlace(0.5);
+            BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
+            BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
+            BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
+            this._worldMatrix = world;
+        };
+        BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
+            return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
+        };
+        BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
+            return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
+        };
+        BoundingBox.prototype.intersectsPoint = function (point) {
+            var delta = -BABYLON.Engine.Epsilon;
+            if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
+                return false;
+            if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
+                return false;
+            if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
+                return false;
+            return true;
+        };
+        BoundingBox.prototype.intersectsSphere = function (sphere) {
+            return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
+        };
+        BoundingBox.prototype.intersectsMinMax = function (min, max) {
+            if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
+                return false;
+            if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
+                return false;
+            if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
+                return false;
+            return true;
+        };
+        // Statics
+        BoundingBox.Intersects = function (box0, box1) {
+            if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
+                return false;
+            if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
+                return false;
+            if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
+                return false;
+            return true;
+        };
+        BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
+            var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
+            var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
+            return (num <= (sphereRadius * sphereRadius));
+        };
+        BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
+            for (var p = 0; p < 6; p++) {
+                for (var i = 0; i < 8; i++) {
+                    if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
+                        return false;
+                    }
+                }
+            }
+            return true;
+        };
+        BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
+            for (var p = 0; p < 6; p++) {
+                var inCount = 8;
+                for (var i = 0; i < 8; i++) {
+                    if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
+                        --inCount;
+                    }
+                    else {
+                        break;
+                    }
+                }
+                if (inCount === 0)
+                    return false;
+            }
+            return true;
+        };
+        return BoundingBox;
+    })();
+    BABYLON.BoundingBox = BoundingBox;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.boundingBox.js.map

+ 106 - 105
src/Culling/babylon.boundingInfo.js

@@ -1,105 +1,106 @@
-var BABYLON;
-(function (BABYLON) {
-    var computeBoxExtents = function (axis, box) {
-        var p = BABYLON.Vector3.Dot(box.center, axis);
-        var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
-        var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
-        var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
-        var r = r0 + r1 + r2;
-        return {
-            min: p - r,
-            max: p + r
-        };
-    };
-    var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
-    var axisOverlap = function (axis, box0, box1) {
-        var result0 = computeBoxExtents(axis, box0);
-        var result1 = computeBoxExtents(axis, box1);
-        return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
-    };
-    var BoundingInfo = (function () {
-        function BoundingInfo(minimum, maximum) {
-            this.minimum = minimum;
-            this.maximum = maximum;
-            this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
-            this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
-        }
-        // Methods
-        BoundingInfo.prototype._update = function (world) {
-            this.boundingBox._update(world);
-            this.boundingSphere._update(world);
-        };
-        BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
-            if (!this.boundingSphere.isInFrustum(frustumPlanes))
-                return false;
-            return this.boundingBox.isInFrustum(frustumPlanes);
-        };
-        BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
-            return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
-        };
-        BoundingInfo.prototype._checkCollision = function (collider) {
-            return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
-        };
-        BoundingInfo.prototype.intersectsPoint = function (point) {
-            if (!this.boundingSphere.centerWorld) {
-                return false;
-            }
-            if (!this.boundingSphere.intersectsPoint(point)) {
-                return false;
-            }
-            if (!this.boundingBox.intersectsPoint(point)) {
-                return false;
-            }
-            return true;
-        };
-        BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
-            if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
-                return false;
-            }
-            if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
-                return false;
-            }
-            if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
-                return false;
-            }
-            if (!precise) {
-                return true;
-            }
-            var box0 = this.boundingBox;
-            var box1 = boundingInfo.boundingBox;
-            if (!axisOverlap(box0.directions[0], box0, box1))
-                return false;
-            if (!axisOverlap(box0.directions[1], box0, box1))
-                return false;
-            if (!axisOverlap(box0.directions[2], box0, box1))
-                return false;
-            if (!axisOverlap(box1.directions[0], box0, box1))
-                return false;
-            if (!axisOverlap(box1.directions[1], box0, box1))
-                return false;
-            if (!axisOverlap(box1.directions[2], box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
-                return false;
-            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
-                return false;
-            return true;
-        };
-        return BoundingInfo;
-    })();
-    BABYLON.BoundingInfo = BoundingInfo;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var computeBoxExtents = function (axis, box) {
+        var p = BABYLON.Vector3.Dot(box.center, axis);
+        var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
+        var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
+        var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
+        var r = r0 + r1 + r2;
+        return {
+            min: p - r,
+            max: p + r
+        };
+    };
+    var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
+    var axisOverlap = function (axis, box0, box1) {
+        var result0 = computeBoxExtents(axis, box0);
+        var result1 = computeBoxExtents(axis, box1);
+        return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
+    };
+    var BoundingInfo = (function () {
+        function BoundingInfo(minimum, maximum) {
+            this.minimum = minimum;
+            this.maximum = maximum;
+            this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
+            this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
+        }
+        // Methods
+        BoundingInfo.prototype._update = function (world) {
+            this.boundingBox._update(world);
+            this.boundingSphere._update(world);
+        };
+        BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
+            if (!this.boundingSphere.isInFrustum(frustumPlanes))
+                return false;
+            return this.boundingBox.isInFrustum(frustumPlanes);
+        };
+        BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
+            return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
+        };
+        BoundingInfo.prototype._checkCollision = function (collider) {
+            return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
+        };
+        BoundingInfo.prototype.intersectsPoint = function (point) {
+            if (!this.boundingSphere.centerWorld) {
+                return false;
+            }
+            if (!this.boundingSphere.intersectsPoint(point)) {
+                return false;
+            }
+            if (!this.boundingBox.intersectsPoint(point)) {
+                return false;
+            }
+            return true;
+        };
+        BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
+            if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
+                return false;
+            }
+            if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
+                return false;
+            }
+            if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
+                return false;
+            }
+            if (!precise) {
+                return true;
+            }
+            var box0 = this.boundingBox;
+            var box1 = boundingInfo.boundingBox;
+            if (!axisOverlap(box0.directions[0], box0, box1))
+                return false;
+            if (!axisOverlap(box0.directions[1], box0, box1))
+                return false;
+            if (!axisOverlap(box0.directions[2], box0, box1))
+                return false;
+            if (!axisOverlap(box1.directions[0], box0, box1))
+                return false;
+            if (!axisOverlap(box1.directions[1], box0, box1))
+                return false;
+            if (!axisOverlap(box1.directions[2], box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
+                return false;
+            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
+                return false;
+            return true;
+        };
+        return BoundingInfo;
+    })();
+    BABYLON.BoundingInfo = BoundingInfo;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.boundingInfo.js.map

+ 14 - 1
src/Culling/babylon.boundingInfo.ts

@@ -26,13 +26,26 @@
         public boundingBox: BoundingBox;
         public boundingSphere: BoundingSphere;
 
+        private _isLocked = false;
+
         constructor(public minimum: Vector3, public maximum: Vector3) {
             this.boundingBox = new BoundingBox(minimum, maximum);
             this.boundingSphere = new BoundingSphere(minimum, maximum);
         }
 
+        public get isLocked(): boolean {
+            return this._isLocked;
+        }
+
+        public set isLocked(value: boolean) { 
+            this._isLocked = value;
+        }
+
         // Methods
-        public _update(world: Matrix) {
+        public update(world: Matrix) {
+            if (this._isLocked) {
+                return;
+            }
             this.boundingBox._update(world);
             this.boundingSphere._update(world);
         }

+ 50 - 49
src/Culling/babylon.boundingSphere.js

@@ -1,49 +1,50 @@
-var BABYLON;
-(function (BABYLON) {
-    var BoundingSphere = (function () {
-        function BoundingSphere(minimum, maximum) {
-            this.minimum = minimum;
-            this.maximum = maximum;
-            this._tempRadiusVector = BABYLON.Vector3.Zero();
-            var distance = BABYLON.Vector3.Distance(minimum, maximum);
-            this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
-            this.radius = distance * 0.5;
-            this.centerWorld = BABYLON.Vector3.Zero();
-            this._update(BABYLON.Matrix.Identity());
-        }
-        // Methods
-        BoundingSphere.prototype._update = function (world) {
-            BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
-            BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
-            this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
-        };
-        BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
-            for (var i = 0; i < 6; i++) {
-                if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
-                    return false;
-            }
-            return true;
-        };
-        BoundingSphere.prototype.intersectsPoint = function (point) {
-            var x = this.centerWorld.x - point.x;
-            var y = this.centerWorld.y - point.y;
-            var z = this.centerWorld.z - point.z;
-            var distance = Math.sqrt((x * x) + (y * y) + (z * z));
-            if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
-                return false;
-            return true;
-        };
-        // Statics
-        BoundingSphere.Intersects = function (sphere0, sphere1) {
-            var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
-            var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
-            var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
-            var distance = Math.sqrt((x * x) + (y * y) + (z * z));
-            if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
-                return false;
-            return true;
-        };
-        return BoundingSphere;
-    })();
-    BABYLON.BoundingSphere = BoundingSphere;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var BoundingSphere = (function () {
+        function BoundingSphere(minimum, maximum) {
+            this.minimum = minimum;
+            this.maximum = maximum;
+            this._tempRadiusVector = BABYLON.Vector3.Zero();
+            var distance = BABYLON.Vector3.Distance(minimum, maximum);
+            this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
+            this.radius = distance * 0.5;
+            this.centerWorld = BABYLON.Vector3.Zero();
+            this._update(BABYLON.Matrix.Identity());
+        }
+        // Methods
+        BoundingSphere.prototype._update = function (world) {
+            BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
+            BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
+            this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
+        };
+        BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
+            for (var i = 0; i < 6; i++) {
+                if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
+                    return false;
+            }
+            return true;
+        };
+        BoundingSphere.prototype.intersectsPoint = function (point) {
+            var x = this.centerWorld.x - point.x;
+            var y = this.centerWorld.y - point.y;
+            var z = this.centerWorld.z - point.z;
+            var distance = Math.sqrt((x * x) + (y * y) + (z * z));
+            if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
+                return false;
+            return true;
+        };
+        // Statics
+        BoundingSphere.Intersects = function (sphere0, sphere1) {
+            var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
+            var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
+            var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
+            var distance = Math.sqrt((x * x) + (y * y) + (z * z));
+            if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
+                return false;
+            return true;
+        };
+        return BoundingSphere;
+    })();
+    BABYLON.BoundingSphere = BoundingSphere;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.boundingSphere.js.map

File diff suppressed because it is too large
+ 630 - 624
src/Debug/babylon.debugLayer.js


+ 11 - 6
src/Debug/babylon.debugLayer.ts

@@ -732,7 +732,7 @@
             + "Active indices: " + scene.getActiveIndices() + "<br>"
             + "Active bones: " + scene.getActiveBones() + "<br>"
             + "Active particles: " + scene.getActiveParticles() + "<br>"
-            + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
+            + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
             + "<b>Duration</b><br>"
             + "Meshes selection:</i> " + Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
             + "Render Targets: " + Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
@@ -740,24 +740,29 @@
             + "Sprites: " + Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
             + "Render: <b>" + Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
             + "Frame: " + Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
-            + "Potential FPS: " + Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
-            + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
+            + "Potential FPS: " + Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
+            + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
             + "</div>"
             + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
             + "<b>Extensions</b><br>"
             + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
             + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
             + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
-            + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
+            + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
             + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
             + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
+            + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
+            + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
+            + "</div><br>"
+            + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
             + "<b>Caps.</b><br>"
             + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
             + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
-            + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
-            + "</div><br>"
+            + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
             + "<b>Info</b><br>"
+            + "WebGL feature level: " + engine.webGLVersion + "<br>"
             + glInfo.version + "<br>"
+            + "</div><br>"
             + glInfo.renderer + "<br>";
 
             if (this.customStatsFunction) {

+ 83 - 82
src/Layer/babylon.layer.js

@@ -1,82 +1,83 @@
-var BABYLON;
-(function (BABYLON) {
-    var Layer = (function () {
-        function Layer(name, imgUrl, scene, isBackground, color) {
-            this.name = name;
-            this.scale = new BABYLON.Vector2(1, 1);
-            this.offset = new BABYLON.Vector2(0, 0);
-            this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
-            this._vertexDeclaration = [2];
-            this._vertexStrideSize = 2 * 4;
-            this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
-            this.isBackground = isBackground === undefined ? true : isBackground;
-            this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
-            this._scene = scene;
-            this._scene.layers.push(this);
-            // VBO
-            var vertices = [];
-            vertices.push(1, 1);
-            vertices.push(-1, 1);
-            vertices.push(-1, -1);
-            vertices.push(1, -1);
-            this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
-            // Indices
-            var indices = [];
-            indices.push(0);
-            indices.push(1);
-            indices.push(2);
-            indices.push(0);
-            indices.push(2);
-            indices.push(3);
-            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
-            // Effects
-            this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
-        }
-        Layer.prototype.render = function () {
-            // Check
-            if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
-                return;
-            var engine = this._scene.getEngine();
-            // Render
-            engine.enableEffect(this._effect);
-            engine.setState(false);
-            // Texture
-            this._effect.setTexture("textureSampler", this.texture);
-            this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
-            // Color
-            this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
-            // Scale / offset
-            this._effect.setVector2("offset", this.offset);
-            this._effect.setVector2("scale", this.scale);
-            // VBOs
-            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
-            // Draw order
-            engine.setAlphaMode(this.alphaBlendingMode);
-            engine.draw(true, 0, 6);
-            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
-        };
-        Layer.prototype.dispose = function () {
-            if (this._vertexBuffer) {
-                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
-                this._vertexBuffer = null;
-            }
-            if (this._indexBuffer) {
-                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
-                this._indexBuffer = null;
-            }
-            if (this.texture) {
-                this.texture.dispose();
-                this.texture = null;
-            }
-            // Remove from scene
-            var index = this._scene.layers.indexOf(this);
-            this._scene.layers.splice(index, 1);
-            // Callback
-            if (this.onDispose) {
-                this.onDispose();
-            }
-        };
-        return Layer;
-    })();
-    BABYLON.Layer = Layer;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var Layer = (function () {
+        function Layer(name, imgUrl, scene, isBackground, color) {
+            this.name = name;
+            this.scale = new BABYLON.Vector2(1, 1);
+            this.offset = new BABYLON.Vector2(0, 0);
+            this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
+            this._vertexDeclaration = [2];
+            this._vertexStrideSize = 2 * 4;
+            this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
+            this.isBackground = isBackground === undefined ? true : isBackground;
+            this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
+            this._scene = scene;
+            this._scene.layers.push(this);
+            // VBO
+            var vertices = [];
+            vertices.push(1, 1);
+            vertices.push(-1, 1);
+            vertices.push(-1, -1);
+            vertices.push(1, -1);
+            this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
+            // Indices
+            var indices = [];
+            indices.push(0);
+            indices.push(1);
+            indices.push(2);
+            indices.push(0);
+            indices.push(2);
+            indices.push(3);
+            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
+            // Effects
+            this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
+        }
+        Layer.prototype.render = function () {
+            // Check
+            if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
+                return;
+            var engine = this._scene.getEngine();
+            // Render
+            engine.enableEffect(this._effect);
+            engine.setState(false);
+            // Texture
+            this._effect.setTexture("textureSampler", this.texture);
+            this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
+            // Color
+            this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
+            // Scale / offset
+            this._effect.setVector2("offset", this.offset);
+            this._effect.setVector2("scale", this.scale);
+            // VBOs
+            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
+            // Draw order
+            engine.setAlphaMode(this.alphaBlendingMode);
+            engine.draw(true, 0, 6);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
+        };
+        Layer.prototype.dispose = function () {
+            if (this._vertexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
+                this._vertexBuffer = null;
+            }
+            if (this._indexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
+                this._indexBuffer = null;
+            }
+            if (this.texture) {
+                this.texture.dispose();
+                this.texture = null;
+            }
+            // Remove from scene
+            var index = this._scene.layers.indexOf(this);
+            this._scene.layers.splice(index, 1);
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        };
+        return Layer;
+    })();
+    BABYLON.Layer = Layer;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.layer.js.map

+ 24 - 23
src/LensFlare/babylon.lensFlare.js

@@ -1,23 +1,24 @@
-var BABYLON;
-(function (BABYLON) {
-    var LensFlare = (function () {
-        function LensFlare(size, position, color, imgUrl, system) {
-            this.size = size;
-            this.position = position;
-            this.dispose = function () {
-                if (this.texture) {
-                    this.texture.dispose();
-                }
-                // Remove from scene
-                var index = this._system.lensFlares.indexOf(this);
-                this._system.lensFlares.splice(index, 1);
-            };
-            this.color = color || new BABYLON.Color3(1, 1, 1);
-            this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
-            this._system = system;
-            system.lensFlares.push(this);
-        }
-        return LensFlare;
-    })();
-    BABYLON.LensFlare = LensFlare;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var LensFlare = (function () {
+        function LensFlare(size, position, color, imgUrl, system) {
+            this.size = size;
+            this.position = position;
+            this.dispose = function () {
+                if (this.texture) {
+                    this.texture.dispose();
+                }
+                // Remove from scene
+                var index = this._system.lensFlares.indexOf(this);
+                this._system.lensFlares.splice(index, 1);
+            };
+            this.color = color || new BABYLON.Color3(1, 1, 1);
+            this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
+            this._system = system;
+            system.lensFlares.push(this);
+        }
+        return LensFlare;
+    })();
+    BABYLON.LensFlare = LensFlare;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.lensFlare.js.map

+ 209 - 208
src/LensFlare/babylon.lensFlareSystem.js

@@ -1,208 +1,209 @@
-var BABYLON;
-(function (BABYLON) {
-    var LensFlareSystem = (function () {
-        function LensFlareSystem(name, emitter, scene) {
-            this.name = name;
-            this.lensFlares = new Array();
-            this.borderLimit = 300;
-            this.layerMask = 0x0FFFFFFF;
-            this._vertexDeclaration = [2];
-            this._vertexStrideSize = 2 * 4;
-            this._isEnabled = true;
-            this._scene = scene;
-            this._emitter = emitter;
-            scene.lensFlareSystems.push(this);
-            this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
-            // VBO
-            var vertices = [];
-            vertices.push(1, 1);
-            vertices.push(-1, 1);
-            vertices.push(-1, -1);
-            vertices.push(1, -1);
-            this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
-            // Indices
-            var indices = [];
-            indices.push(0);
-            indices.push(1);
-            indices.push(2);
-            indices.push(0);
-            indices.push(2);
-            indices.push(3);
-            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
-            // Effects
-            this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
-        }
-        Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
-            get: function () {
-                return this._isEnabled;
-            },
-            set: function (value) {
-                this._isEnabled = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        LensFlareSystem.prototype.getScene = function () {
-            return this._scene;
-        };
-        LensFlareSystem.prototype.getEmitter = function () {
-            return this._emitter;
-        };
-        LensFlareSystem.prototype.setEmitter = function (newEmitter) {
-            this._emitter = newEmitter;
-        };
-        LensFlareSystem.prototype.getEmitterPosition = function () {
-            return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
-        };
-        LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
-            var position = this.getEmitterPosition();
-            position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
-            this._positionX = position.x;
-            this._positionY = position.y;
-            position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
-            if (position.z > 0) {
-                if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
-                    if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
-                        return true;
-                }
-            }
-            return false;
-        };
-        LensFlareSystem.prototype._isVisible = function () {
-            if (!this._isEnabled) {
-                return false;
-            }
-            var emitterPosition = this.getEmitterPosition();
-            var direction = emitterPosition.subtract(this._scene.activeCamera.position);
-            var distance = direction.length();
-            direction.normalize();
-            var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
-            var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
-            return !pickInfo.hit || pickInfo.distance > distance;
-        };
-        LensFlareSystem.prototype.render = function () {
-            if (!this._effect.isReady())
-                return false;
-            var engine = this._scene.getEngine();
-            var viewport = this._scene.activeCamera.viewport;
-            var globalViewport = viewport.toScreenGlobal(engine);
-            // Position
-            if (!this.computeEffectivePosition(globalViewport)) {
-                return false;
-            }
-            // Visibility
-            if (!this._isVisible()) {
-                return false;
-            }
-            // Intensity
-            var awayX;
-            var awayY;
-            if (this._positionX < this.borderLimit + globalViewport.x) {
-                awayX = this.borderLimit + globalViewport.x - this._positionX;
-            }
-            else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
-                awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
-            }
-            else {
-                awayX = 0;
-            }
-            if (this._positionY < this.borderLimit + globalViewport.y) {
-                awayY = this.borderLimit + globalViewport.y - this._positionY;
-            }
-            else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
-                awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
-            }
-            else {
-                awayY = 0;
-            }
-            var away = (awayX > awayY) ? awayX : awayY;
-            if (away > this.borderLimit) {
-                away = this.borderLimit;
-            }
-            var intensity = 1.0 - (away / this.borderLimit);
-            if (intensity < 0) {
-                return false;
-            }
-            if (intensity > 1.0) {
-                intensity = 1.0;
-            }
-            // Position
-            var centerX = globalViewport.x + globalViewport.width / 2;
-            var centerY = globalViewport.y + globalViewport.height / 2;
-            var distX = centerX - this._positionX;
-            var distY = centerY - this._positionY;
-            // Effects
-            engine.enableEffect(this._effect);
-            engine.setState(false);
-            engine.setDepthBuffer(false);
-            engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
-            // VBOs
-            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
-            // Flares
-            for (var index = 0; index < this.lensFlares.length; index++) {
-                var flare = this.lensFlares[index];
-                var x = centerX - (distX * flare.position);
-                var y = centerY - (distY * flare.position);
-                var cw = flare.size;
-                var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
-                var cx = 2 * (x / globalViewport.width) - 1.0;
-                var cy = 1.0 - 2 * (y / globalViewport.height);
-                var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
-                this._effect.setMatrix("viewportMatrix", viewportMatrix);
-                // Texture
-                this._effect.setTexture("textureSampler", flare.texture);
-                // Color
-                this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
-                // Draw order
-                engine.draw(true, 0, 6);
-            }
-            engine.setDepthBuffer(true);
-            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
-            return true;
-        };
-        LensFlareSystem.prototype.dispose = function () {
-            if (this._vertexBuffer) {
-                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
-                this._vertexBuffer = null;
-            }
-            if (this._indexBuffer) {
-                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
-                this._indexBuffer = null;
-            }
-            while (this.lensFlares.length) {
-                this.lensFlares[0].dispose();
-            }
-            // Remove from scene
-            var index = this._scene.lensFlareSystems.indexOf(this);
-            this._scene.lensFlareSystems.splice(index, 1);
-        };
-        LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
-            var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
-            var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
-            lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
-            for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
-                var parsedFlare = parsedLensFlareSystem.flares[index];
-                var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
-            }
-            return lensFlareSystem;
-        };
-        LensFlareSystem.prototype.serialize = function () {
-            var serializationObject = {};
-            serializationObject.emitterId = this.getEmitter().id;
-            serializationObject.borderLimit = this.borderLimit;
-            serializationObject.flares = [];
-            for (var index = 0; index < this.lensFlares.length; index++) {
-                var flare = this.lensFlares[index];
-                serializationObject.flares.push({
-                    size: flare.size,
-                    position: flare.position,
-                    color: flare.color.asArray(),
-                    textureName: BABYLON.Tools.GetFilename(flare.texture.name)
-                });
-            }
-            return serializationObject;
-        };
-        return LensFlareSystem;
-    })();
-    BABYLON.LensFlareSystem = LensFlareSystem;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var LensFlareSystem = (function () {
+        function LensFlareSystem(name, emitter, scene) {
+            this.name = name;
+            this.lensFlares = new Array();
+            this.borderLimit = 300;
+            this.layerMask = 0x0FFFFFFF;
+            this._vertexDeclaration = [2];
+            this._vertexStrideSize = 2 * 4;
+            this._isEnabled = true;
+            this._scene = scene;
+            this._emitter = emitter;
+            scene.lensFlareSystems.push(this);
+            this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
+            // VBO
+            var vertices = [];
+            vertices.push(1, 1);
+            vertices.push(-1, 1);
+            vertices.push(-1, -1);
+            vertices.push(1, -1);
+            this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
+            // Indices
+            var indices = [];
+            indices.push(0);
+            indices.push(1);
+            indices.push(2);
+            indices.push(0);
+            indices.push(2);
+            indices.push(3);
+            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
+            // Effects
+            this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
+        }
+        Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
+            get: function () {
+                return this._isEnabled;
+            },
+            set: function (value) {
+                this._isEnabled = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        LensFlareSystem.prototype.getScene = function () {
+            return this._scene;
+        };
+        LensFlareSystem.prototype.getEmitter = function () {
+            return this._emitter;
+        };
+        LensFlareSystem.prototype.setEmitter = function (newEmitter) {
+            this._emitter = newEmitter;
+        };
+        LensFlareSystem.prototype.getEmitterPosition = function () {
+            return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
+        };
+        LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
+            var position = this.getEmitterPosition();
+            position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
+            this._positionX = position.x;
+            this._positionY = position.y;
+            position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
+            if (position.z > 0) {
+                if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
+                    if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
+                        return true;
+                }
+            }
+            return false;
+        };
+        LensFlareSystem.prototype._isVisible = function () {
+            if (!this._isEnabled) {
+                return false;
+            }
+            var emitterPosition = this.getEmitterPosition();
+            var direction = emitterPosition.subtract(this._scene.activeCamera.position);
+            var distance = direction.length();
+            direction.normalize();
+            var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
+            var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
+            return !pickInfo.hit || pickInfo.distance > distance;
+        };
+        LensFlareSystem.prototype.render = function () {
+            if (!this._effect.isReady())
+                return false;
+            var engine = this._scene.getEngine();
+            var viewport = this._scene.activeCamera.viewport;
+            var globalViewport = viewport.toScreenGlobal(engine);
+            // Position
+            if (!this.computeEffectivePosition(globalViewport)) {
+                return false;
+            }
+            // Visibility
+            if (!this._isVisible()) {
+                return false;
+            }
+            // Intensity
+            var awayX;
+            var awayY;
+            if (this._positionX < this.borderLimit + globalViewport.x) {
+                awayX = this.borderLimit + globalViewport.x - this._positionX;
+            }
+            else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
+                awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
+            }
+            else {
+                awayX = 0;
+            }
+            if (this._positionY < this.borderLimit + globalViewport.y) {
+                awayY = this.borderLimit + globalViewport.y - this._positionY;
+            }
+            else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
+                awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
+            }
+            else {
+                awayY = 0;
+            }
+            var away = (awayX > awayY) ? awayX : awayY;
+            if (away > this.borderLimit) {
+                away = this.borderLimit;
+            }
+            var intensity = 1.0 - (away / this.borderLimit);
+            if (intensity < 0) {
+                return false;
+            }
+            if (intensity > 1.0) {
+                intensity = 1.0;
+            }
+            // Position
+            var centerX = globalViewport.x + globalViewport.width / 2;
+            var centerY = globalViewport.y + globalViewport.height / 2;
+            var distX = centerX - this._positionX;
+            var distY = centerY - this._positionY;
+            // Effects
+            engine.enableEffect(this._effect);
+            engine.setState(false);
+            engine.setDepthBuffer(false);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
+            // VBOs
+            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
+            // Flares
+            for (var index = 0; index < this.lensFlares.length; index++) {
+                var flare = this.lensFlares[index];
+                var x = centerX - (distX * flare.position);
+                var y = centerY - (distY * flare.position);
+                var cw = flare.size;
+                var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
+                var cx = 2 * (x / globalViewport.width) - 1.0;
+                var cy = 1.0 - 2 * (y / globalViewport.height);
+                var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
+                this._effect.setMatrix("viewportMatrix", viewportMatrix);
+                // Texture
+                this._effect.setTexture("textureSampler", flare.texture);
+                // Color
+                this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
+                // Draw order
+                engine.draw(true, 0, 6);
+            }
+            engine.setDepthBuffer(true);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
+            return true;
+        };
+        LensFlareSystem.prototype.dispose = function () {
+            if (this._vertexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
+                this._vertexBuffer = null;
+            }
+            if (this._indexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
+                this._indexBuffer = null;
+            }
+            while (this.lensFlares.length) {
+                this.lensFlares[0].dispose();
+            }
+            // Remove from scene
+            var index = this._scene.lensFlareSystems.indexOf(this);
+            this._scene.lensFlareSystems.splice(index, 1);
+        };
+        LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
+            var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
+            var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
+            lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
+            for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
+                var parsedFlare = parsedLensFlareSystem.flares[index];
+                var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
+            }
+            return lensFlareSystem;
+        };
+        LensFlareSystem.prototype.serialize = function () {
+            var serializationObject = {};
+            serializationObject.emitterId = this.getEmitter().id;
+            serializationObject.borderLimit = this.borderLimit;
+            serializationObject.flares = [];
+            for (var index = 0; index < this.lensFlares.length; index++) {
+                var flare = this.lensFlares[index];
+                serializationObject.flares.push({
+                    size: flare.size,
+                    position: flare.position,
+                    color: flare.color.asArray(),
+                    textureName: BABYLON.Tools.GetFilename(flare.texture.name)
+                });
+            }
+            return serializationObject;
+        };
+        return LensFlareSystem;
+    })();
+    BABYLON.LensFlareSystem = LensFlareSystem;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.lensFlareSystem.js.map

+ 406 - 405
src/Lights/Shadows/babylon.shadowGenerator.js

@@ -1,405 +1,406 @@
-var BABYLON;
-(function (BABYLON) {
-    var ShadowGenerator = (function () {
-        function ShadowGenerator(mapSize, light) {
-            var _this = this;
-            // Members
-            this._filter = ShadowGenerator.FILTER_NONE;
-            this.blurScale = 2;
-            this._blurBoxOffset = 0;
-            this._bias = 0.00005;
-            this._lightDirection = BABYLON.Vector3.Zero();
-            this.forceBackFacesOnly = false;
-            this._darkness = 0;
-            this._transparencyShadow = false;
-            this._viewMatrix = BABYLON.Matrix.Zero();
-            this._projectionMatrix = BABYLON.Matrix.Zero();
-            this._transformMatrix = BABYLON.Matrix.Zero();
-            this._worldViewProjection = BABYLON.Matrix.Zero();
-            this._currentFaceIndex = 0;
-            this._currentFaceIndexCache = 0;
-            this._light = light;
-            this._scene = light.getScene();
-            this._mapSize = mapSize;
-            light._shadowGenerator = this;
-            // Render target
-            this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
-            this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this._shadowMap.anisotropicFilteringLevel = 1;
-            this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
-            this._shadowMap.renderParticles = false;
-            this._shadowMap.onBeforeRender = function (faceIndex) {
-                _this._currentFaceIndex = faceIndex;
-            };
-            this._shadowMap.onAfterUnbind = function () {
-                if (!_this.useBlurVarianceShadowMap) {
-                    return;
-                }
-                if (!_this._shadowMap2) {
-                    _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
-                    _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-                    _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-                    _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
-                    _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
-                    _this._downSamplePostprocess.onApply = function (effect) {
-                        effect.setTexture("textureSampler", _this._shadowMap);
-                    };
-                    _this.blurBoxOffset = 1;
-                }
-                _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
-            };
-            // Custom render function
-            var renderSubMesh = function (subMesh) {
-                var mesh = subMesh.getRenderingMesh();
-                var scene = _this._scene;
-                var engine = scene.getEngine();
-                // Culling
-                engine.setState(subMesh.getMaterial().backFaceCulling);
-                // Managing instances
-                var batch = mesh._getInstancesRenderList(subMesh._id);
-                if (batch.mustReturn) {
-                    return;
-                }
-                var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
-                if (_this.isReady(subMesh, hardwareInstancedRendering)) {
-                    engine.enableEffect(_this._effect);
-                    mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
-                    var material = subMesh.getMaterial();
-                    _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
-                    _this._effect.setVector3("lightPosition", _this.getLight().position);
-                    if (_this.getLight().needCube()) {
-                        _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
-                    }
-                    // Alpha test
-                    if (material && material.needAlphaTesting()) {
-                        var alphaTexture = material.getAlphaTestTexture();
-                        _this._effect.setTexture("diffuseSampler", alphaTexture);
-                        _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
-                    }
-                    // Bones
-                    if (mesh.useBones && mesh.computeBonesUsingShaders) {
-                        _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
-                    }
-                    if (_this.forceBackFacesOnly) {
-                        engine.setState(true, 0, false, true);
-                    }
-                    // Draw
-                    mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
-                    if (_this.forceBackFacesOnly) {
-                        engine.setState(true, 0, false, false);
-                    }
-                }
-                else {
-                    // Need to reset refresh rate of the shadowMap
-                    _this._shadowMap.resetRefreshCounter();
-                }
-            };
-            this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
-                var index;
-                for (index = 0; index < opaqueSubMeshes.length; index++) {
-                    renderSubMesh(opaqueSubMeshes.data[index]);
-                }
-                for (index = 0; index < alphaTestSubMeshes.length; index++) {
-                    renderSubMesh(alphaTestSubMeshes.data[index]);
-                }
-                if (_this._transparencyShadow) {
-                    for (index = 0; index < transparentSubMeshes.length; index++) {
-                        renderSubMesh(transparentSubMeshes.data[index]);
-                    }
-                }
-            };
-            this._shadowMap.onClear = function (engine) {
-                if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
-                    engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
-                }
-                else {
-                    engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
-                }
-            };
-        }
-        Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
-            // Static
-            get: function () {
-                return ShadowGenerator._FILTER_NONE;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
-            get: function () {
-                return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
-            get: function () {
-                return ShadowGenerator._FILTER_POISSONSAMPLING;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
-            get: function () {
-                return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator.prototype, "bias", {
-            get: function () {
-                return this._bias;
-            },
-            set: function (bias) {
-                this._bias = bias;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
-            get: function () {
-                return this._blurBoxOffset;
-            },
-            set: function (value) {
-                var _this = this;
-                if (this._blurBoxOffset === value) {
-                    return;
-                }
-                this._blurBoxOffset = value;
-                if (this._boxBlurPostprocess) {
-                    this._boxBlurPostprocess.dispose();
-                }
-                this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
-                this._boxBlurPostprocess.onApply = function (effect) {
-                    effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
-                };
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator.prototype, "filter", {
-            get: function () {
-                return this._filter;
-            },
-            set: function (value) {
-                if (this._filter === value) {
-                    return;
-                }
-                this._filter = value;
-                if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
-                    this._shadowMap.anisotropicFilteringLevel = 16;
-                    this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
-                }
-                else {
-                    this._shadowMap.anisotropicFilteringLevel = 1;
-                    this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
-                }
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
-            get: function () {
-                return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
-            },
-            set: function (value) {
-                this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
-            get: function () {
-                return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
-                    (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
-                        this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
-            },
-            set: function (value) {
-                this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
-            get: function () {
-                return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
-            },
-            set: function (value) {
-                this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
-            var defines = [];
-            if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
-                defines.push("#define VSM");
-            }
-            if (this.getLight().needCube()) {
-                defines.push("#define CUBEMAP");
-            }
-            var attribs = [BABYLON.VertexBuffer.PositionKind];
-            var mesh = subMesh.getMesh();
-            var material = subMesh.getMaterial();
-            // Alpha test
-            if (material && material.needAlphaTesting()) {
-                defines.push("#define ALPHATEST");
-                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
-                    attribs.push(BABYLON.VertexBuffer.UVKind);
-                    defines.push("#define UV1");
-                }
-                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
-                    attribs.push(BABYLON.VertexBuffer.UV2Kind);
-                    defines.push("#define UV2");
-                }
-            }
-            // Bones
-            if (mesh.useBones && mesh.computeBonesUsingShaders) {
-                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
-                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
-                if (mesh.numBoneInfluencers > 4) {
-                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
-                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
-                }
-                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
-                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
-            }
-            else {
-                defines.push("#define NUM_BONE_INFLUENCERS 0");
-            }
-            // Instances
-            if (useInstances) {
-                defines.push("#define INSTANCES");
-                attribs.push("world0");
-                attribs.push("world1");
-                attribs.push("world2");
-                attribs.push("world3");
-            }
-            // Get correct effect      
-            var join = defines.join("\n");
-            if (this._cachedDefines !== join) {
-                this._cachedDefines = join;
-                this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
-            }
-            return this._effect.isReady();
-        };
-        ShadowGenerator.prototype.getShadowMap = function () {
-            return this._shadowMap;
-        };
-        ShadowGenerator.prototype.getShadowMapForRendering = function () {
-            if (this._shadowMap2) {
-                return this._shadowMap2;
-            }
-            return this._shadowMap;
-        };
-        ShadowGenerator.prototype.getLight = function () {
-            return this._light;
-        };
-        // Methods
-        ShadowGenerator.prototype.getTransformMatrix = function () {
-            var scene = this._scene;
-            if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
-                return this._transformMatrix;
-            }
-            this._currentRenderID = scene.getRenderId();
-            this._currentFaceIndexCache = this._currentFaceIndex;
-            var lightPosition = this._light.position;
-            BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
-            if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
-                this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
-            }
-            if (this._light.computeTransformedPosition()) {
-                lightPosition = this._light.transformedPosition;
-            }
-            if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
-                this._cachedPosition = lightPosition.clone();
-                this._cachedDirection = this._lightDirection.clone();
-                BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
-                this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
-                this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
-            }
-            return this._transformMatrix;
-        };
-        ShadowGenerator.prototype.getDarkness = function () {
-            return this._darkness;
-        };
-        ShadowGenerator.prototype.setDarkness = function (darkness) {
-            if (darkness >= 1.0)
-                this._darkness = 1.0;
-            else if (darkness <= 0.0)
-                this._darkness = 0.0;
-            else
-                this._darkness = darkness;
-        };
-        ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
-            this._transparencyShadow = hasShadow;
-        };
-        ShadowGenerator.prototype._packHalf = function (depth) {
-            var scale = depth * 255.0;
-            var fract = scale - Math.floor(scale);
-            return new BABYLON.Vector2(depth - fract / 255.0, fract);
-        };
-        ShadowGenerator.prototype.dispose = function () {
-            this._shadowMap.dispose();
-            if (this._shadowMap2) {
-                this._shadowMap2.dispose();
-            }
-            if (this._downSamplePostprocess) {
-                this._downSamplePostprocess.dispose();
-            }
-            if (this._boxBlurPostprocess) {
-                this._boxBlurPostprocess.dispose();
-            }
-        };
-        ShadowGenerator.prototype.serialize = function () {
-            var serializationObject = {};
-            serializationObject.lightId = this._light.id;
-            serializationObject.mapSize = this.getShadowMap().getRenderSize();
-            serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
-            serializationObject.usePoissonSampling = this.usePoissonSampling;
-            serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
-            serializationObject.renderList = [];
-            for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
-                var mesh = this.getShadowMap().renderList[meshIndex];
-                serializationObject.renderList.push(mesh.id);
-            }
-            return serializationObject;
-        };
-        ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
-            //casting to point light, as light is missing the position attr and typescript complains.
-            var light = scene.getLightByID(parsedShadowGenerator.lightId);
-            var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
-            for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
-                var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
-                shadowGenerator.getShadowMap().renderList.push(mesh);
-            }
-            if (parsedShadowGenerator.usePoissonSampling) {
-                shadowGenerator.usePoissonSampling = true;
-            }
-            else if (parsedShadowGenerator.useVarianceShadowMap) {
-                shadowGenerator.useVarianceShadowMap = true;
-            }
-            else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
-                shadowGenerator.useBlurVarianceShadowMap = true;
-                if (parsedShadowGenerator.blurScale) {
-                    shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
-                }
-                if (parsedShadowGenerator.blurBoxOffset) {
-                    shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
-                }
-            }
-            if (parsedShadowGenerator.bias !== undefined) {
-                shadowGenerator.bias = parsedShadowGenerator.bias;
-            }
-            shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
-            return shadowGenerator;
-        };
-        ShadowGenerator._FILTER_NONE = 0;
-        ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
-        ShadowGenerator._FILTER_POISSONSAMPLING = 2;
-        ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
-        return ShadowGenerator;
-    })();
-    BABYLON.ShadowGenerator = ShadowGenerator;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var ShadowGenerator = (function () {
+        function ShadowGenerator(mapSize, light) {
+            var _this = this;
+            // Members
+            this._filter = ShadowGenerator.FILTER_NONE;
+            this.blurScale = 2;
+            this._blurBoxOffset = 0;
+            this._bias = 0.00005;
+            this._lightDirection = BABYLON.Vector3.Zero();
+            this.forceBackFacesOnly = false;
+            this._darkness = 0;
+            this._transparencyShadow = false;
+            this._viewMatrix = BABYLON.Matrix.Zero();
+            this._projectionMatrix = BABYLON.Matrix.Zero();
+            this._transformMatrix = BABYLON.Matrix.Zero();
+            this._worldViewProjection = BABYLON.Matrix.Zero();
+            this._currentFaceIndex = 0;
+            this._currentFaceIndexCache = 0;
+            this._light = light;
+            this._scene = light.getScene();
+            this._mapSize = mapSize;
+            light._shadowGenerator = this;
+            // Render target
+            this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
+            this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._shadowMap.anisotropicFilteringLevel = 1;
+            this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
+            this._shadowMap.renderParticles = false;
+            this._shadowMap.onBeforeRender = function (faceIndex) {
+                _this._currentFaceIndex = faceIndex;
+            };
+            this._shadowMap.onAfterUnbind = function () {
+                if (!_this.useBlurVarianceShadowMap) {
+                    return;
+                }
+                if (!_this._shadowMap2) {
+                    _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
+                    _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+                    _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+                    _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
+                    _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
+                    _this._downSamplePostprocess.onApply = function (effect) {
+                        effect.setTexture("textureSampler", _this._shadowMap);
+                    };
+                    _this.blurBoxOffset = 1;
+                }
+                _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
+            };
+            // Custom render function
+            var renderSubMesh = function (subMesh) {
+                var mesh = subMesh.getRenderingMesh();
+                var scene = _this._scene;
+                var engine = scene.getEngine();
+                // Culling
+                engine.setState(subMesh.getMaterial().backFaceCulling);
+                // Managing instances
+                var batch = mesh._getInstancesRenderList(subMesh._id);
+                if (batch.mustReturn) {
+                    return;
+                }
+                var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
+                if (_this.isReady(subMesh, hardwareInstancedRendering)) {
+                    engine.enableEffect(_this._effect);
+                    mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
+                    var material = subMesh.getMaterial();
+                    _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
+                    _this._effect.setVector3("lightPosition", _this.getLight().position);
+                    if (_this.getLight().needCube()) {
+                        _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
+                    }
+                    // Alpha test
+                    if (material && material.needAlphaTesting()) {
+                        var alphaTexture = material.getAlphaTestTexture();
+                        _this._effect.setTexture("diffuseSampler", alphaTexture);
+                        _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
+                    }
+                    // Bones
+                    if (mesh.useBones && mesh.computeBonesUsingShaders) {
+                        _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
+                    }
+                    if (_this.forceBackFacesOnly) {
+                        engine.setState(true, 0, false, true);
+                    }
+                    // Draw
+                    mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
+                    if (_this.forceBackFacesOnly) {
+                        engine.setState(true, 0, false, false);
+                    }
+                }
+                else {
+                    // Need to reset refresh rate of the shadowMap
+                    _this._shadowMap.resetRefreshCounter();
+                }
+            };
+            this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
+                var index;
+                for (index = 0; index < opaqueSubMeshes.length; index++) {
+                    renderSubMesh(opaqueSubMeshes.data[index]);
+                }
+                for (index = 0; index < alphaTestSubMeshes.length; index++) {
+                    renderSubMesh(alphaTestSubMeshes.data[index]);
+                }
+                if (_this._transparencyShadow) {
+                    for (index = 0; index < transparentSubMeshes.length; index++) {
+                        renderSubMesh(transparentSubMeshes.data[index]);
+                    }
+                }
+            };
+            this._shadowMap.onClear = function (engine) {
+                if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
+                    engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
+                }
+                else {
+                    engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
+                }
+            };
+        }
+        Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
+            // Static
+            get: function () {
+                return ShadowGenerator._FILTER_NONE;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
+            get: function () {
+                return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
+            get: function () {
+                return ShadowGenerator._FILTER_POISSONSAMPLING;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
+            get: function () {
+                return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator.prototype, "bias", {
+            get: function () {
+                return this._bias;
+            },
+            set: function (bias) {
+                this._bias = bias;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
+            get: function () {
+                return this._blurBoxOffset;
+            },
+            set: function (value) {
+                var _this = this;
+                if (this._blurBoxOffset === value) {
+                    return;
+                }
+                this._blurBoxOffset = value;
+                if (this._boxBlurPostprocess) {
+                    this._boxBlurPostprocess.dispose();
+                }
+                this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
+                this._boxBlurPostprocess.onApply = function (effect) {
+                    effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
+                };
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator.prototype, "filter", {
+            get: function () {
+                return this._filter;
+            },
+            set: function (value) {
+                if (this._filter === value) {
+                    return;
+                }
+                this._filter = value;
+                if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
+                    this._shadowMap.anisotropicFilteringLevel = 16;
+                    this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
+                }
+                else {
+                    this._shadowMap.anisotropicFilteringLevel = 1;
+                    this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
+                }
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
+            get: function () {
+                return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
+            },
+            set: function (value) {
+                this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
+            get: function () {
+                return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
+                    (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
+                        this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
+            },
+            set: function (value) {
+                this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
+            get: function () {
+                return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
+            },
+            set: function (value) {
+                this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
+            var defines = [];
+            if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
+                defines.push("#define VSM");
+            }
+            if (this.getLight().needCube()) {
+                defines.push("#define CUBEMAP");
+            }
+            var attribs = [BABYLON.VertexBuffer.PositionKind];
+            var mesh = subMesh.getMesh();
+            var material = subMesh.getMaterial();
+            // Alpha test
+            if (material && material.needAlphaTesting()) {
+                defines.push("#define ALPHATEST");
+                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
+                    attribs.push(BABYLON.VertexBuffer.UVKind);
+                    defines.push("#define UV1");
+                }
+                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
+                    attribs.push(BABYLON.VertexBuffer.UV2Kind);
+                    defines.push("#define UV2");
+                }
+            }
+            // Bones
+            if (mesh.useBones && mesh.computeBonesUsingShaders) {
+                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
+                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
+                if (mesh.numBoneInfluencers > 4) {
+                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
+                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
+                }
+                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
+                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
+            }
+            else {
+                defines.push("#define NUM_BONE_INFLUENCERS 0");
+            }
+            // Instances
+            if (useInstances) {
+                defines.push("#define INSTANCES");
+                attribs.push("world0");
+                attribs.push("world1");
+                attribs.push("world2");
+                attribs.push("world3");
+            }
+            // Get correct effect      
+            var join = defines.join("\n");
+            if (this._cachedDefines !== join) {
+                this._cachedDefines = join;
+                this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
+            }
+            return this._effect.isReady();
+        };
+        ShadowGenerator.prototype.getShadowMap = function () {
+            return this._shadowMap;
+        };
+        ShadowGenerator.prototype.getShadowMapForRendering = function () {
+            if (this._shadowMap2) {
+                return this._shadowMap2;
+            }
+            return this._shadowMap;
+        };
+        ShadowGenerator.prototype.getLight = function () {
+            return this._light;
+        };
+        // Methods
+        ShadowGenerator.prototype.getTransformMatrix = function () {
+            var scene = this._scene;
+            if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
+                return this._transformMatrix;
+            }
+            this._currentRenderID = scene.getRenderId();
+            this._currentFaceIndexCache = this._currentFaceIndex;
+            var lightPosition = this._light.position;
+            BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
+            if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
+                this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
+            }
+            if (this._light.computeTransformedPosition()) {
+                lightPosition = this._light.transformedPosition;
+            }
+            if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
+                this._cachedPosition = lightPosition.clone();
+                this._cachedDirection = this._lightDirection.clone();
+                BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
+                this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
+                this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
+            }
+            return this._transformMatrix;
+        };
+        ShadowGenerator.prototype.getDarkness = function () {
+            return this._darkness;
+        };
+        ShadowGenerator.prototype.setDarkness = function (darkness) {
+            if (darkness >= 1.0)
+                this._darkness = 1.0;
+            else if (darkness <= 0.0)
+                this._darkness = 0.0;
+            else
+                this._darkness = darkness;
+        };
+        ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
+            this._transparencyShadow = hasShadow;
+        };
+        ShadowGenerator.prototype._packHalf = function (depth) {
+            var scale = depth * 255.0;
+            var fract = scale - Math.floor(scale);
+            return new BABYLON.Vector2(depth - fract / 255.0, fract);
+        };
+        ShadowGenerator.prototype.dispose = function () {
+            this._shadowMap.dispose();
+            if (this._shadowMap2) {
+                this._shadowMap2.dispose();
+            }
+            if (this._downSamplePostprocess) {
+                this._downSamplePostprocess.dispose();
+            }
+            if (this._boxBlurPostprocess) {
+                this._boxBlurPostprocess.dispose();
+            }
+        };
+        ShadowGenerator.prototype.serialize = function () {
+            var serializationObject = {};
+            serializationObject.lightId = this._light.id;
+            serializationObject.mapSize = this.getShadowMap().getRenderSize();
+            serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
+            serializationObject.usePoissonSampling = this.usePoissonSampling;
+            serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
+            serializationObject.renderList = [];
+            for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
+                var mesh = this.getShadowMap().renderList[meshIndex];
+                serializationObject.renderList.push(mesh.id);
+            }
+            return serializationObject;
+        };
+        ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
+            //casting to point light, as light is missing the position attr and typescript complains.
+            var light = scene.getLightByID(parsedShadowGenerator.lightId);
+            var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
+            for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
+                var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
+                shadowGenerator.getShadowMap().renderList.push(mesh);
+            }
+            if (parsedShadowGenerator.usePoissonSampling) {
+                shadowGenerator.usePoissonSampling = true;
+            }
+            else if (parsedShadowGenerator.useVarianceShadowMap) {
+                shadowGenerator.useVarianceShadowMap = true;
+            }
+            else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
+                shadowGenerator.useBlurVarianceShadowMap = true;
+                if (parsedShadowGenerator.blurScale) {
+                    shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
+                }
+                if (parsedShadowGenerator.blurBoxOffset) {
+                    shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
+                }
+            }
+            if (parsedShadowGenerator.bias !== undefined) {
+                shadowGenerator.bias = parsedShadowGenerator.bias;
+            }
+            shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
+            return shadowGenerator;
+        };
+        ShadowGenerator._FILTER_NONE = 0;
+        ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
+        ShadowGenerator._FILTER_POISSONSAMPLING = 2;
+        ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
+        return ShadowGenerator;
+    })();
+    BABYLON.ShadowGenerator = ShadowGenerator;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.shadowGenerator.js.map

+ 116 - 115
src/Lights/babylon.directionalLight.js

@@ -1,115 +1,116 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var DirectionalLight = (function (_super) {
-        __extends(DirectionalLight, _super);
-        function DirectionalLight(name, direction, scene) {
-            _super.call(this, name, scene);
-            this.direction = direction;
-            this.shadowOrthoScale = 0.5;
-            this.autoUpdateExtends = true;
-            // Cache
-            this._orthoLeft = Number.MAX_VALUE;
-            this._orthoRight = Number.MIN_VALUE;
-            this._orthoTop = Number.MIN_VALUE;
-            this._orthoBottom = Number.MAX_VALUE;
-            this.position = direction.scale(-1);
-        }
-        DirectionalLight.prototype.getAbsolutePosition = function () {
-            return this.transformedPosition ? this.transformedPosition : this.position;
-        };
-        DirectionalLight.prototype.setDirectionToTarget = function (target) {
-            this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
-            return this.direction;
-        };
-        DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
-            var activeCamera = this.getScene().activeCamera;
-            // Check extends
-            if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
-                var tempVector3 = BABYLON.Vector3.Zero();
-                this._orthoLeft = Number.MAX_VALUE;
-                this._orthoRight = Number.MIN_VALUE;
-                this._orthoTop = Number.MIN_VALUE;
-                this._orthoBottom = Number.MAX_VALUE;
-                for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
-                    var mesh = renderList[meshIndex];
-                    if (!mesh) {
-                        continue;
-                    }
-                    var boundingInfo = mesh.getBoundingInfo();
-                    if (!boundingInfo) {
-                        continue;
-                    }
-                    var boundingBox = boundingInfo.boundingBox;
-                    for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
-                        BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
-                        if (tempVector3.x < this._orthoLeft)
-                            this._orthoLeft = tempVector3.x;
-                        if (tempVector3.y < this._orthoBottom)
-                            this._orthoBottom = tempVector3.y;
-                        if (tempVector3.x > this._orthoRight)
-                            this._orthoRight = tempVector3.x;
-                        if (tempVector3.y > this._orthoTop)
-                            this._orthoTop = tempVector3.y;
-                    }
-                }
-            }
-            var xOffset = this._orthoRight - this._orthoLeft;
-            var yOffset = this._orthoTop - this._orthoBottom;
-            BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
-        };
-        DirectionalLight.prototype.supportsVSM = function () {
-            return true;
-        };
-        DirectionalLight.prototype.needRefreshPerFrame = function () {
-            return true;
-        };
-        DirectionalLight.prototype.needCube = function () {
-            return false;
-        };
-        DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
-            return this.direction;
-        };
-        DirectionalLight.prototype.computeTransformedPosition = function () {
-            if (this.parent && this.parent.getWorldMatrix) {
-                if (!this.transformedPosition) {
-                    this.transformedPosition = BABYLON.Vector3.Zero();
-                }
-                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
-                return true;
-            }
-            return false;
-        };
-        DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
-            if (this.parent && this.parent.getWorldMatrix) {
-                if (!this._transformedDirection) {
-                    this._transformedDirection = BABYLON.Vector3.Zero();
-                }
-                BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
-                effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
-                return;
-            }
-            effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
-        };
-        DirectionalLight.prototype._getWorldMatrix = function () {
-            if (!this._worldMatrix) {
-                this._worldMatrix = BABYLON.Matrix.Identity();
-            }
-            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
-            return this._worldMatrix;
-        };
-        DirectionalLight.prototype.serialize = function () {
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.type = 1;
-            serializationObject.position = this.position.asArray();
-            serializationObject.direction = this.direction.asArray();
-            return serializationObject;
-        };
-        return DirectionalLight;
-    })(BABYLON.Light);
-    BABYLON.DirectionalLight = DirectionalLight;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var DirectionalLight = (function (_super) {
+        __extends(DirectionalLight, _super);
+        function DirectionalLight(name, direction, scene) {
+            _super.call(this, name, scene);
+            this.direction = direction;
+            this.shadowOrthoScale = 0.5;
+            this.autoUpdateExtends = true;
+            // Cache
+            this._orthoLeft = Number.MAX_VALUE;
+            this._orthoRight = Number.MIN_VALUE;
+            this._orthoTop = Number.MIN_VALUE;
+            this._orthoBottom = Number.MAX_VALUE;
+            this.position = direction.scale(-1);
+        }
+        DirectionalLight.prototype.getAbsolutePosition = function () {
+            return this.transformedPosition ? this.transformedPosition : this.position;
+        };
+        DirectionalLight.prototype.setDirectionToTarget = function (target) {
+            this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
+            return this.direction;
+        };
+        DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
+            var activeCamera = this.getScene().activeCamera;
+            // Check extends
+            if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
+                var tempVector3 = BABYLON.Vector3.Zero();
+                this._orthoLeft = Number.MAX_VALUE;
+                this._orthoRight = Number.MIN_VALUE;
+                this._orthoTop = Number.MIN_VALUE;
+                this._orthoBottom = Number.MAX_VALUE;
+                for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
+                    var mesh = renderList[meshIndex];
+                    if (!mesh) {
+                        continue;
+                    }
+                    var boundingInfo = mesh.getBoundingInfo();
+                    if (!boundingInfo) {
+                        continue;
+                    }
+                    var boundingBox = boundingInfo.boundingBox;
+                    for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
+                        BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
+                        if (tempVector3.x < this._orthoLeft)
+                            this._orthoLeft = tempVector3.x;
+                        if (tempVector3.y < this._orthoBottom)
+                            this._orthoBottom = tempVector3.y;
+                        if (tempVector3.x > this._orthoRight)
+                            this._orthoRight = tempVector3.x;
+                        if (tempVector3.y > this._orthoTop)
+                            this._orthoTop = tempVector3.y;
+                    }
+                }
+            }
+            var xOffset = this._orthoRight - this._orthoLeft;
+            var yOffset = this._orthoTop - this._orthoBottom;
+            BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
+        };
+        DirectionalLight.prototype.supportsVSM = function () {
+            return true;
+        };
+        DirectionalLight.prototype.needRefreshPerFrame = function () {
+            return true;
+        };
+        DirectionalLight.prototype.needCube = function () {
+            return false;
+        };
+        DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
+            return this.direction;
+        };
+        DirectionalLight.prototype.computeTransformedPosition = function () {
+            if (this.parent && this.parent.getWorldMatrix) {
+                if (!this.transformedPosition) {
+                    this.transformedPosition = BABYLON.Vector3.Zero();
+                }
+                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
+                return true;
+            }
+            return false;
+        };
+        DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
+            if (this.parent && this.parent.getWorldMatrix) {
+                if (!this._transformedDirection) {
+                    this._transformedDirection = BABYLON.Vector3.Zero();
+                }
+                BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
+                effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
+                return;
+            }
+            effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
+        };
+        DirectionalLight.prototype._getWorldMatrix = function () {
+            if (!this._worldMatrix) {
+                this._worldMatrix = BABYLON.Matrix.Identity();
+            }
+            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
+            return this._worldMatrix;
+        };
+        DirectionalLight.prototype.serialize = function () {
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.type = 1;
+            serializationObject.position = this.position.asArray();
+            serializationObject.direction = this.direction.asArray();
+            return serializationObject;
+        };
+        return DirectionalLight;
+    })(BABYLON.Light);
+    BABYLON.DirectionalLight = DirectionalLight;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.directionalLight.js.map

+ 44 - 43
src/Lights/babylon.hemisphericLight.js

@@ -1,43 +1,44 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var HemisphericLight = (function (_super) {
-        __extends(HemisphericLight, _super);
-        function HemisphericLight(name, direction, scene) {
-            _super.call(this, name, scene);
-            this.direction = direction;
-            this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
-        }
-        HemisphericLight.prototype.setDirectionToTarget = function (target) {
-            this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
-            return this.direction;
-        };
-        HemisphericLight.prototype.getShadowGenerator = function () {
-            return null;
-        };
-        HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
-            var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
-            effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
-            effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
-        };
-        HemisphericLight.prototype._getWorldMatrix = function () {
-            if (!this._worldMatrix) {
-                this._worldMatrix = BABYLON.Matrix.Identity();
-            }
-            return this._worldMatrix;
-        };
-        HemisphericLight.prototype.serialize = function () {
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.type = 3;
-            serializationObject.direction = this.direction.asArray();
-            serializationObject.groundColor = this.groundColor.asArray();
-            return serializationObject;
-        };
-        return HemisphericLight;
-    })(BABYLON.Light);
-    BABYLON.HemisphericLight = HemisphericLight;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var HemisphericLight = (function (_super) {
+        __extends(HemisphericLight, _super);
+        function HemisphericLight(name, direction, scene) {
+            _super.call(this, name, scene);
+            this.direction = direction;
+            this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
+        }
+        HemisphericLight.prototype.setDirectionToTarget = function (target) {
+            this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
+            return this.direction;
+        };
+        HemisphericLight.prototype.getShadowGenerator = function () {
+            return null;
+        };
+        HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
+            var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
+            effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
+            effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
+        };
+        HemisphericLight.prototype._getWorldMatrix = function () {
+            if (!this._worldMatrix) {
+                this._worldMatrix = BABYLON.Matrix.Identity();
+            }
+            return this._worldMatrix;
+        };
+        HemisphericLight.prototype.serialize = function () {
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.type = 3;
+            serializationObject.direction = this.direction.asArray();
+            serializationObject.groundColor = this.groundColor.asArray();
+            return serializationObject;
+        };
+        return HemisphericLight;
+    })(BABYLON.Light);
+    BABYLON.HemisphericLight = HemisphericLight;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.hemisphericLight.js.map

+ 144 - 143
src/Lights/babylon.light.js

@@ -1,143 +1,144 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var Light = (function (_super) {
-        __extends(Light, _super);
-        function Light(name, scene) {
-            _super.call(this, name, scene);
-            this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
-            this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
-            this.intensity = 1.0;
-            this.range = Number.MAX_VALUE;
-            this.includeOnlyWithLayerMask = 0;
-            this.includedOnlyMeshes = new Array();
-            this.excludedMeshes = new Array();
-            this.excludeWithLayerMask = 0;
-            this._excludedMeshesIds = new Array();
-            this._includedOnlyMeshesIds = new Array();
-            scene.addLight(this);
-        }
-        Light.prototype.getShadowGenerator = function () {
-            return this._shadowGenerator;
-        };
-        Light.prototype.getAbsolutePosition = function () {
-            return BABYLON.Vector3.Zero();
-        };
-        Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
-        };
-        Light.prototype._getWorldMatrix = function () {
-            return BABYLON.Matrix.Identity();
-        };
-        Light.prototype.canAffectMesh = function (mesh) {
-            if (!mesh) {
-                return true;
-            }
-            if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
-                return false;
-            }
-            if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
-                return false;
-            }
-            if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
-                return false;
-            }
-            if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
-                return false;
-            }
-            return true;
-        };
-        Light.prototype.getWorldMatrix = function () {
-            this._currentRenderId = this.getScene().getRenderId();
-            var worldMatrix = this._getWorldMatrix();
-            if (this.parent && this.parent.getWorldMatrix) {
-                if (!this._parentedWorldMatrix) {
-                    this._parentedWorldMatrix = BABYLON.Matrix.Identity();
-                }
-                worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
-                this._markSyncedWithParent();
-                return this._parentedWorldMatrix;
-            }
-            return worldMatrix;
-        };
-        Light.prototype.dispose = function () {
-            if (this._shadowGenerator) {
-                this._shadowGenerator.dispose();
-                this._shadowGenerator = null;
-            }
-            // Animations
-            this.getScene().stopAnimation(this);
-            // Remove from scene
-            this.getScene().removeLight(this);
-        };
-        Light.prototype.serialize = function () {
-            var serializationObject = {};
-            serializationObject.name = this.name;
-            serializationObject.id = this.id;
-            serializationObject.tags = BABYLON.Tags.GetTags(this);
-            if (this.intensity) {
-                serializationObject.intensity = this.intensity;
-            }
-            serializationObject.range = this.range;
-            serializationObject.diffuse = this.diffuse.asArray();
-            serializationObject.specular = this.specular.asArray();
-            return serializationObject;
-        };
-        Light.Parse = function (parsedLight, scene) {
-            var light;
-            switch (parsedLight.type) {
-                case 0:
-                    light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
-                    break;
-                case 1:
-                    light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
-                    light.position = BABYLON.Vector3.FromArray(parsedLight.position);
-                    break;
-                case 2:
-                    light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
-                    break;
-                case 3:
-                    light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
-                    light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
-                    break;
-            }
-            light.id = parsedLight.id;
-            BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
-            if (parsedLight.intensity !== undefined) {
-                light.intensity = parsedLight.intensity;
-            }
-            if (parsedLight.range) {
-                light.range = parsedLight.range;
-            }
-            light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
-            light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
-            if (parsedLight.excludedMeshesIds) {
-                light._excludedMeshesIds = parsedLight.excludedMeshesIds;
-            }
-            // Parent
-            if (parsedLight.parentId) {
-                light._waitingParentId = parsedLight.parentId;
-            }
-            if (parsedLight.includedOnlyMeshesIds) {
-                light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
-            }
-            // Animations
-            if (parsedLight.animations) {
-                for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
-                    var parsedAnimation = parsedLight.animations[animationIndex];
-                    light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
-                }
-                BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
-            }
-            if (parsedLight.autoAnimate) {
-                scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
-            }
-            return light;
-        };
-        return Light;
-    })(BABYLON.Node);
-    BABYLON.Light = Light;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var Light = (function (_super) {
+        __extends(Light, _super);
+        function Light(name, scene) {
+            _super.call(this, name, scene);
+            this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
+            this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
+            this.intensity = 1.0;
+            this.range = Number.MAX_VALUE;
+            this.includeOnlyWithLayerMask = 0;
+            this.includedOnlyMeshes = new Array();
+            this.excludedMeshes = new Array();
+            this.excludeWithLayerMask = 0;
+            this._excludedMeshesIds = new Array();
+            this._includedOnlyMeshesIds = new Array();
+            scene.addLight(this);
+        }
+        Light.prototype.getShadowGenerator = function () {
+            return this._shadowGenerator;
+        };
+        Light.prototype.getAbsolutePosition = function () {
+            return BABYLON.Vector3.Zero();
+        };
+        Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
+        };
+        Light.prototype._getWorldMatrix = function () {
+            return BABYLON.Matrix.Identity();
+        };
+        Light.prototype.canAffectMesh = function (mesh) {
+            if (!mesh) {
+                return true;
+            }
+            if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
+                return false;
+            }
+            if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
+                return false;
+            }
+            if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
+                return false;
+            }
+            if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
+                return false;
+            }
+            return true;
+        };
+        Light.prototype.getWorldMatrix = function () {
+            this._currentRenderId = this.getScene().getRenderId();
+            var worldMatrix = this._getWorldMatrix();
+            if (this.parent && this.parent.getWorldMatrix) {
+                if (!this._parentedWorldMatrix) {
+                    this._parentedWorldMatrix = BABYLON.Matrix.Identity();
+                }
+                worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
+                this._markSyncedWithParent();
+                return this._parentedWorldMatrix;
+            }
+            return worldMatrix;
+        };
+        Light.prototype.dispose = function () {
+            if (this._shadowGenerator) {
+                this._shadowGenerator.dispose();
+                this._shadowGenerator = null;
+            }
+            // Animations
+            this.getScene().stopAnimation(this);
+            // Remove from scene
+            this.getScene().removeLight(this);
+        };
+        Light.prototype.serialize = function () {
+            var serializationObject = {};
+            serializationObject.name = this.name;
+            serializationObject.id = this.id;
+            serializationObject.tags = BABYLON.Tags.GetTags(this);
+            if (this.intensity) {
+                serializationObject.intensity = this.intensity;
+            }
+            serializationObject.range = this.range;
+            serializationObject.diffuse = this.diffuse.asArray();
+            serializationObject.specular = this.specular.asArray();
+            return serializationObject;
+        };
+        Light.Parse = function (parsedLight, scene) {
+            var light;
+            switch (parsedLight.type) {
+                case 0:
+                    light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
+                    break;
+                case 1:
+                    light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
+                    light.position = BABYLON.Vector3.FromArray(parsedLight.position);
+                    break;
+                case 2:
+                    light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
+                    break;
+                case 3:
+                    light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
+                    light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
+                    break;
+            }
+            light.id = parsedLight.id;
+            BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
+            if (parsedLight.intensity !== undefined) {
+                light.intensity = parsedLight.intensity;
+            }
+            if (parsedLight.range) {
+                light.range = parsedLight.range;
+            }
+            light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
+            light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
+            if (parsedLight.excludedMeshesIds) {
+                light._excludedMeshesIds = parsedLight.excludedMeshesIds;
+            }
+            // Parent
+            if (parsedLight.parentId) {
+                light._waitingParentId = parsedLight.parentId;
+            }
+            if (parsedLight.includedOnlyMeshesIds) {
+                light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
+            }
+            // Animations
+            if (parsedLight.animations) {
+                for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
+                    var parsedAnimation = parsedLight.animations[animationIndex];
+                    light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
+                }
+                BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
+            }
+            if (parsedLight.autoAnimate) {
+                scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
+            }
+            return light;
+        };
+        return Light;
+    })(BABYLON.Node);
+    BABYLON.Light = Light;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.light.js.map

+ 82 - 81
src/Lights/babylon.pointLight.js

@@ -1,81 +1,82 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var PointLight = (function (_super) {
-        __extends(PointLight, _super);
-        function PointLight(name, position, scene) {
-            _super.call(this, name, scene);
-            this.position = position;
-        }
-        PointLight.prototype.getAbsolutePosition = function () {
-            return this.transformedPosition ? this.transformedPosition : this.position;
-        };
-        PointLight.prototype.computeTransformedPosition = function () {
-            if (this.parent && this.parent.getWorldMatrix) {
-                if (!this.transformedPosition) {
-                    this.transformedPosition = BABYLON.Vector3.Zero();
-                }
-                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
-                return true;
-            }
-            return false;
-        };
-        PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
-            if (this.parent && this.parent.getWorldMatrix) {
-                this.computeTransformedPosition();
-                effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
-                return;
-            }
-            effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
-        };
-        PointLight.prototype.needCube = function () {
-            return true;
-        };
-        PointLight.prototype.supportsVSM = function () {
-            return false;
-        };
-        PointLight.prototype.needRefreshPerFrame = function () {
-            return false;
-        };
-        PointLight.prototype.getShadowDirection = function (faceIndex) {
-            switch (faceIndex) {
-                case 0:
-                    return new BABYLON.Vector3(1, 0, 0);
-                case 1:
-                    return new BABYLON.Vector3(-1, 0, 0);
-                case 2:
-                    return new BABYLON.Vector3(0, -1, 0);
-                case 3:
-                    return new BABYLON.Vector3(0, 1, 0);
-                case 4:
-                    return new BABYLON.Vector3(0, 0, 1);
-                case 5:
-                    return new BABYLON.Vector3(0, 0, -1);
-            }
-            return BABYLON.Vector3.Zero();
-        };
-        PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
-            var activeCamera = this.getScene().activeCamera;
-            BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
-        };
-        PointLight.prototype._getWorldMatrix = function () {
-            if (!this._worldMatrix) {
-                this._worldMatrix = BABYLON.Matrix.Identity();
-            }
-            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
-            return this._worldMatrix;
-        };
-        PointLight.prototype.serialize = function () {
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.type = 0;
-            serializationObject.position = this.position.asArray();
-            return serializationObject;
-        };
-        return PointLight;
-    })(BABYLON.Light);
-    BABYLON.PointLight = PointLight;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var PointLight = (function (_super) {
+        __extends(PointLight, _super);
+        function PointLight(name, position, scene) {
+            _super.call(this, name, scene);
+            this.position = position;
+        }
+        PointLight.prototype.getAbsolutePosition = function () {
+            return this.transformedPosition ? this.transformedPosition : this.position;
+        };
+        PointLight.prototype.computeTransformedPosition = function () {
+            if (this.parent && this.parent.getWorldMatrix) {
+                if (!this.transformedPosition) {
+                    this.transformedPosition = BABYLON.Vector3.Zero();
+                }
+                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
+                return true;
+            }
+            return false;
+        };
+        PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
+            if (this.parent && this.parent.getWorldMatrix) {
+                this.computeTransformedPosition();
+                effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
+                return;
+            }
+            effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
+        };
+        PointLight.prototype.needCube = function () {
+            return true;
+        };
+        PointLight.prototype.supportsVSM = function () {
+            return false;
+        };
+        PointLight.prototype.needRefreshPerFrame = function () {
+            return false;
+        };
+        PointLight.prototype.getShadowDirection = function (faceIndex) {
+            switch (faceIndex) {
+                case 0:
+                    return new BABYLON.Vector3(1, 0, 0);
+                case 1:
+                    return new BABYLON.Vector3(-1, 0, 0);
+                case 2:
+                    return new BABYLON.Vector3(0, -1, 0);
+                case 3:
+                    return new BABYLON.Vector3(0, 1, 0);
+                case 4:
+                    return new BABYLON.Vector3(0, 0, 1);
+                case 5:
+                    return new BABYLON.Vector3(0, 0, -1);
+            }
+            return BABYLON.Vector3.Zero();
+        };
+        PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
+            var activeCamera = this.getScene().activeCamera;
+            BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
+        };
+        PointLight.prototype._getWorldMatrix = function () {
+            if (!this._worldMatrix) {
+                this._worldMatrix = BABYLON.Matrix.Identity();
+            }
+            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
+            return this._worldMatrix;
+        };
+        PointLight.prototype.serialize = function () {
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.type = 0;
+            serializationObject.position = this.position.asArray();
+            return serializationObject;
+        };
+        return PointLight;
+    })(BABYLON.Light);
+    BABYLON.PointLight = PointLight;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.pointLight.js.map

+ 87 - 86
src/Lights/babylon.spotLight.js

@@ -1,86 +1,87 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var SpotLight = (function (_super) {
-        __extends(SpotLight, _super);
-        function SpotLight(name, position, direction, angle, exponent, scene) {
-            _super.call(this, name, scene);
-            this.position = position;
-            this.direction = direction;
-            this.angle = angle;
-            this.exponent = exponent;
-        }
-        SpotLight.prototype.getAbsolutePosition = function () {
-            return this.transformedPosition ? this.transformedPosition : this.position;
-        };
-        SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
-            var activeCamera = this.getScene().activeCamera;
-            BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
-        };
-        SpotLight.prototype.needCube = function () {
-            return false;
-        };
-        SpotLight.prototype.supportsVSM = function () {
-            return true;
-        };
-        SpotLight.prototype.needRefreshPerFrame = function () {
-            return false;
-        };
-        SpotLight.prototype.getShadowDirection = function (faceIndex) {
-            return this.direction;
-        };
-        SpotLight.prototype.setDirectionToTarget = function (target) {
-            this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
-            return this.direction;
-        };
-        SpotLight.prototype.computeTransformedPosition = function () {
-            if (this.parent && this.parent.getWorldMatrix) {
-                if (!this.transformedPosition) {
-                    this.transformedPosition = BABYLON.Vector3.Zero();
-                }
-                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
-                return true;
-            }
-            return false;
-        };
-        SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
-            var normalizeDirection;
-            if (this.parent && this.parent.getWorldMatrix) {
-                if (!this._transformedDirection) {
-                    this._transformedDirection = BABYLON.Vector3.Zero();
-                }
-                this.computeTransformedPosition();
-                BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
-                effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
-                normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
-            }
-            else {
-                effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
-                normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
-            }
-            effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
-        };
-        SpotLight.prototype._getWorldMatrix = function () {
-            if (!this._worldMatrix) {
-                this._worldMatrix = BABYLON.Matrix.Identity();
-            }
-            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
-            return this._worldMatrix;
-        };
-        SpotLight.prototype.serialize = function () {
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.type = 2;
-            serializationObject.position = this.position.asArray();
-            serializationObject.direction = this.position.asArray();
-            serializationObject.angle = this.angle;
-            serializationObject.exponent = this.exponent;
-            return serializationObject;
-        };
-        return SpotLight;
-    })(BABYLON.Light);
-    BABYLON.SpotLight = SpotLight;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var SpotLight = (function (_super) {
+        __extends(SpotLight, _super);
+        function SpotLight(name, position, direction, angle, exponent, scene) {
+            _super.call(this, name, scene);
+            this.position = position;
+            this.direction = direction;
+            this.angle = angle;
+            this.exponent = exponent;
+        }
+        SpotLight.prototype.getAbsolutePosition = function () {
+            return this.transformedPosition ? this.transformedPosition : this.position;
+        };
+        SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
+            var activeCamera = this.getScene().activeCamera;
+            BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
+        };
+        SpotLight.prototype.needCube = function () {
+            return false;
+        };
+        SpotLight.prototype.supportsVSM = function () {
+            return true;
+        };
+        SpotLight.prototype.needRefreshPerFrame = function () {
+            return false;
+        };
+        SpotLight.prototype.getShadowDirection = function (faceIndex) {
+            return this.direction;
+        };
+        SpotLight.prototype.setDirectionToTarget = function (target) {
+            this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
+            return this.direction;
+        };
+        SpotLight.prototype.computeTransformedPosition = function () {
+            if (this.parent && this.parent.getWorldMatrix) {
+                if (!this.transformedPosition) {
+                    this.transformedPosition = BABYLON.Vector3.Zero();
+                }
+                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
+                return true;
+            }
+            return false;
+        };
+        SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
+            var normalizeDirection;
+            if (this.parent && this.parent.getWorldMatrix) {
+                if (!this._transformedDirection) {
+                    this._transformedDirection = BABYLON.Vector3.Zero();
+                }
+                this.computeTransformedPosition();
+                BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
+                effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
+                normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
+            }
+            else {
+                effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
+                normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
+            }
+            effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
+        };
+        SpotLight.prototype._getWorldMatrix = function () {
+            if (!this._worldMatrix) {
+                this._worldMatrix = BABYLON.Matrix.Identity();
+            }
+            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
+            return this._worldMatrix;
+        };
+        SpotLight.prototype.serialize = function () {
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.type = 2;
+            serializationObject.position = this.position.asArray();
+            serializationObject.direction = this.position.asArray();
+            serializationObject.angle = this.angle;
+            serializationObject.exponent = this.exponent;
+            return serializationObject;
+        };
+        return SpotLight;
+    })(BABYLON.Light);
+    BABYLON.SpotLight = SpotLight;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.spotLight.js.map

+ 403 - 402
src/Loading/Plugins/babylon.babylonFileLoader.js

@@ -1,402 +1,403 @@
-var BABYLON;
-(function (BABYLON) {
-    var Internals;
-    (function (Internals) {
-        var parseMaterialById = function (id, parsedData, scene, rootUrl) {
-            for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
-                var parsedMaterial = parsedData.materials[index];
-                if (parsedMaterial.id === id) {
-                    return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
-                }
-            }
-            return null;
-        };
-        var isDescendantOf = function (mesh, names, hierarchyIds) {
-            names = (names instanceof Array) ? names : [names];
-            for (var i in names) {
-                if (mesh.name === names[i]) {
-                    hierarchyIds.push(mesh.id);
-                    return true;
-                }
-            }
-            if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
-                hierarchyIds.push(mesh.id);
-                return true;
-            }
-            return false;
-        };
-        BABYLON.SceneLoader.RegisterPlugin({
-            extensions: ".babylon",
-            importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
-                var parsedData = JSON.parse(data);
-                var loadedSkeletonsIds = [];
-                var loadedMaterialsIds = [];
-                var hierarchyIds = [];
-                var index;
-                var cache;
-                for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
-                    var parsedMesh = parsedData.meshes[index];
-                    if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
-                        if (meshesNames instanceof Array) {
-                            // Remove found mesh name from list.
-                            delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
-                        }
-                        //Geometry?
-                        if (parsedMesh.geometryId) {
-                            //does the file contain geometries?
-                            if (parsedData.geometries) {
-                                //find the correct geometry and add it to the scene
-                                var found = false;
-                                ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
-                                    if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
-                                        return;
-                                    }
-                                    else {
-                                        parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
-                                            if (parsedGeometryData.id === parsedMesh.geometryId) {
-                                                switch (geometryType) {
-                                                    case "boxes":
-                                                        BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
-                                                        break;
-                                                    case "spheres":
-                                                        BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
-                                                        break;
-                                                    case "cylinders":
-                                                        BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
-                                                        break;
-                                                    case "toruses":
-                                                        BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
-                                                        break;
-                                                    case "grounds":
-                                                        BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
-                                                        break;
-                                                    case "planes":
-                                                        BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
-                                                        break;
-                                                    case "torusKnots":
-                                                        BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
-                                                        break;
-                                                    case "vertexData":
-                                                        BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
-                                                        break;
-                                                }
-                                                found = true;
-                                            }
-                                        });
-                                    }
-                                });
-                                if (!found) {
-                                    BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
-                                }
-                            }
-                        }
-                        // Material ?
-                        if (parsedMesh.materialId) {
-                            var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
-                            if (!materialFound && parsedData.multiMaterials) {
-                                for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
-                                    var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
-                                    if (parsedMultiMaterial.id === parsedMesh.materialId) {
-                                        for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
-                                            var subMatId = parsedMultiMaterial.materials[matIndex];
-                                            loadedMaterialsIds.push(subMatId);
-                                            parseMaterialById(subMatId, parsedData, scene, rootUrl);
-                                        }
-                                        loadedMaterialsIds.push(parsedMultiMaterial.id);
-                                        BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
-                                        materialFound = true;
-                                        break;
-                                    }
-                                }
-                            }
-                            if (!materialFound) {
-                                loadedMaterialsIds.push(parsedMesh.materialId);
-                                if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
-                                    BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
-                                }
-                            }
-                        }
-                        // Skeleton ?
-                        if (parsedMesh.skeletonId > -1 && scene.skeletons) {
-                            var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
-                            if (!skeletonAlreadyLoaded) {
-                                for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
-                                    var parsedSkeleton = parsedData.skeletons[skeletonIndex];
-                                    if (parsedSkeleton.id === parsedMesh.skeletonId) {
-                                        skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
-                                        loadedSkeletonsIds.push(parsedSkeleton.id);
-                                    }
-                                }
-                            }
-                        }
-                        var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
-                        meshes.push(mesh);
-                    }
-                }
-                // Connecting parents
-                var currentMesh;
-                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                    currentMesh = scene.meshes[index];
-                    if (currentMesh._waitingParentId) {
-                        currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
-                        currentMesh._waitingParentId = undefined;
-                    }
-                }
-                // freeze and compute world matrix application
-                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                    currentMesh = scene.meshes[index];
-                    if (currentMesh._waitingFreezeWorldMatrix) {
-                        currentMesh.freezeWorldMatrix();
-                        currentMesh._waitingFreezeWorldMatrix = undefined;
-                    }
-                    else {
-                        currentMesh.computeWorldMatrix(true);
-                    }
-                }
-                // Particles
-                if (parsedData.particleSystems) {
-                    for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
-                        var parsedParticleSystem = parsedData.particleSystems[index];
-                        if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
-                            particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
-                        }
-                    }
-                }
-                return true;
-            },
-            load: function (scene, data, rootUrl) {
-                var parsedData = JSON.parse(data);
-                // Scene
-                scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
-                scene.autoClear = parsedData.autoClear;
-                scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
-                scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
-                if (parsedData.gravity) {
-                    scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
-                }
-                // Fog
-                if (parsedData.fogMode && parsedData.fogMode !== 0) {
-                    scene.fogMode = parsedData.fogMode;
-                    scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
-                    scene.fogStart = parsedData.fogStart;
-                    scene.fogEnd = parsedData.fogEnd;
-                    scene.fogDensity = parsedData.fogDensity;
-                }
-                //Physics
-                if (parsedData.physicsEnabled) {
-                    var physicsPlugin;
-                    if (parsedData.physicsEngine === "cannon") {
-                        physicsPlugin = new BABYLON.CannonJSPlugin();
-                    }
-                    else if (parsedData.physicsEngine === "oimo") {
-                        physicsPlugin = new BABYLON.OimoJSPlugin();
-                    }
-                    //else - default engine, which is currently oimo
-                    var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
-                    scene.enablePhysics(physicsGravity, physicsPlugin);
-                }
-                //collisions, if defined. otherwise, default is true
-                if (parsedData.collisionsEnabled != undefined) {
-                    scene.collisionsEnabled = parsedData.collisionsEnabled;
-                }
-                scene.workerCollisions = !!parsedData.workerCollisions;
-                var index;
-                var cache;
-                // Lights
-                for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
-                    var parsedLight = parsedData.lights[index];
-                    BABYLON.Light.Parse(parsedLight, scene);
-                }
-                // Materials
-                if (parsedData.materials) {
-                    for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
-                        var parsedMaterial = parsedData.materials[index];
-                        BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
-                    }
-                }
-                if (parsedData.multiMaterials) {
-                    for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
-                        var parsedMultiMaterial = parsedData.multiMaterials[index];
-                        BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
-                    }
-                }
-                // Skeletons
-                if (parsedData.skeletons) {
-                    for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
-                        var parsedSkeleton = parsedData.skeletons[index];
-                        BABYLON.Skeleton.Parse(parsedSkeleton, scene);
-                    }
-                }
-                // Geometries
-                var geometries = parsedData.geometries;
-                if (geometries) {
-                    // Boxes
-                    var boxes = geometries.boxes;
-                    if (boxes) {
-                        for (index = 0, cache = boxes.length; index < cache; index++) {
-                            var parsedBox = boxes[index];
-                            BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
-                        }
-                    }
-                    // Spheres
-                    var spheres = geometries.spheres;
-                    if (spheres) {
-                        for (index = 0, cache = spheres.length; index < cache; index++) {
-                            var parsedSphere = spheres[index];
-                            BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
-                        }
-                    }
-                    // Cylinders
-                    var cylinders = geometries.cylinders;
-                    if (cylinders) {
-                        for (index = 0, cache = cylinders.length; index < cache; index++) {
-                            var parsedCylinder = cylinders[index];
-                            BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
-                        }
-                    }
-                    // Toruses
-                    var toruses = geometries.toruses;
-                    if (toruses) {
-                        for (index = 0, cache = toruses.length; index < cache; index++) {
-                            var parsedTorus = toruses[index];
-                            BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
-                        }
-                    }
-                    // Grounds
-                    var grounds = geometries.grounds;
-                    if (grounds) {
-                        for (index = 0, cache = grounds.length; index < cache; index++) {
-                            var parsedGround = grounds[index];
-                            BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
-                        }
-                    }
-                    // Planes
-                    var planes = geometries.planes;
-                    if (planes) {
-                        for (index = 0, cache = planes.length; index < cache; index++) {
-                            var parsedPlane = planes[index];
-                            BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
-                        }
-                    }
-                    // TorusKnots
-                    var torusKnots = geometries.torusKnots;
-                    if (torusKnots) {
-                        for (index = 0, cache = torusKnots.length; index < cache; index++) {
-                            var parsedTorusKnot = torusKnots[index];
-                            BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
-                        }
-                    }
-                    // VertexData
-                    var vertexData = geometries.vertexData;
-                    if (vertexData) {
-                        for (index = 0, cache = vertexData.length; index < cache; index++) {
-                            var parsedVertexData = vertexData[index];
-                            BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
-                        }
-                    }
-                }
-                // Meshes
-                for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
-                    var parsedMesh = parsedData.meshes[index];
-                    BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
-                }
-                // Cameras
-                for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
-                    var parsedCamera = parsedData.cameras[index];
-                    BABYLON.Camera.Parse(parsedCamera, scene);
-                }
-                if (parsedData.activeCameraID) {
-                    scene.setActiveCameraByID(parsedData.activeCameraID);
-                }
-                // Browsing all the graph to connect the dots
-                for (index = 0, cache = scene.cameras.length; index < cache; index++) {
-                    var camera = scene.cameras[index];
-                    if (camera._waitingParentId) {
-                        camera.parent = scene.getLastEntryByID(camera._waitingParentId);
-                        camera._waitingParentId = undefined;
-                    }
-                }
-                for (index = 0, cache = scene.lights.length; index < cache; index++) {
-                    var light = scene.lights[index];
-                    if (light._waitingParentId) {
-                        light.parent = scene.getLastEntryByID(light._waitingParentId);
-                        light._waitingParentId = undefined;
-                    }
-                }
-                // Sounds
-                var loadedSounds = [];
-                var loadedSound;
-                if (BABYLON.AudioEngine && parsedData.sounds) {
-                    for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
-                        var parsedSound = parsedData.sounds[index];
-                        if (BABYLON.Engine.audioEngine.canUseWebAudio) {
-                            if (!parsedSound.url)
-                                parsedSound.url = parsedSound.name;
-                            if (!loadedSounds[parsedSound.url]) {
-                                loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
-                                loadedSounds[parsedSound.url] = loadedSound;
-                            }
-                            else {
-                                BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
-                            }
-                        }
-                        else {
-                            var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
-                        }
-                    }
-                }
-                loadedSounds = [];
-                // Connect parents & children and parse actions
-                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                    var mesh = scene.meshes[index];
-                    if (mesh._waitingParentId) {
-                        mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
-                        mesh._waitingParentId = undefined;
-                    }
-                    if (mesh._waitingActions) {
-                        BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
-                        mesh._waitingActions = undefined;
-                    }
-                }
-                // freeze world matrix application
-                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
-                    var currentMesh = scene.meshes[index];
-                    if (currentMesh._waitingFreezeWorldMatrix) {
-                        currentMesh.freezeWorldMatrix();
-                        currentMesh._waitingFreezeWorldMatrix = undefined;
-                    }
-                    else {
-                        currentMesh.computeWorldMatrix(true);
-                    }
-                }
-                // Particles Systems
-                if (parsedData.particleSystems) {
-                    for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
-                        var parsedParticleSystem = parsedData.particleSystems[index];
-                        BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
-                    }
-                }
-                // Lens flares
-                if (parsedData.lensFlareSystems) {
-                    for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
-                        var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
-                        BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
-                    }
-                }
-                // Shadows
-                if (parsedData.shadowGenerators) {
-                    for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
-                        var parsedShadowGenerator = parsedData.shadowGenerators[index];
-                        BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
-                    }
-                }
-                // Actions (scene)
-                if (parsedData.actions) {
-                    BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
-                }
-                // Finish
-                return true;
-            }
-        });
-    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var Internals;
+    (function (Internals) {
+        var parseMaterialById = function (id, parsedData, scene, rootUrl) {
+            for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
+                var parsedMaterial = parsedData.materials[index];
+                if (parsedMaterial.id === id) {
+                    return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
+                }
+            }
+            return null;
+        };
+        var isDescendantOf = function (mesh, names, hierarchyIds) {
+            names = (names instanceof Array) ? names : [names];
+            for (var i in names) {
+                if (mesh.name === names[i]) {
+                    hierarchyIds.push(mesh.id);
+                    return true;
+                }
+            }
+            if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
+                hierarchyIds.push(mesh.id);
+                return true;
+            }
+            return false;
+        };
+        BABYLON.SceneLoader.RegisterPlugin({
+            extensions: ".babylon",
+            importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
+                var parsedData = JSON.parse(data);
+                var loadedSkeletonsIds = [];
+                var loadedMaterialsIds = [];
+                var hierarchyIds = [];
+                var index;
+                var cache;
+                for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
+                    var parsedMesh = parsedData.meshes[index];
+                    if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
+                        if (meshesNames instanceof Array) {
+                            // Remove found mesh name from list.
+                            delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
+                        }
+                        //Geometry?
+                        if (parsedMesh.geometryId) {
+                            //does the file contain geometries?
+                            if (parsedData.geometries) {
+                                //find the correct geometry and add it to the scene
+                                var found = false;
+                                ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
+                                    if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
+                                        return;
+                                    }
+                                    else {
+                                        parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
+                                            if (parsedGeometryData.id === parsedMesh.geometryId) {
+                                                switch (geometryType) {
+                                                    case "boxes":
+                                                        BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
+                                                        break;
+                                                    case "spheres":
+                                                        BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
+                                                        break;
+                                                    case "cylinders":
+                                                        BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
+                                                        break;
+                                                    case "toruses":
+                                                        BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
+                                                        break;
+                                                    case "grounds":
+                                                        BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
+                                                        break;
+                                                    case "planes":
+                                                        BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
+                                                        break;
+                                                    case "torusKnots":
+                                                        BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
+                                                        break;
+                                                    case "vertexData":
+                                                        BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
+                                                        break;
+                                                }
+                                                found = true;
+                                            }
+                                        });
+                                    }
+                                });
+                                if (!found) {
+                                    BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
+                                }
+                            }
+                        }
+                        // Material ?
+                        if (parsedMesh.materialId) {
+                            var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
+                            if (!materialFound && parsedData.multiMaterials) {
+                                for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
+                                    var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
+                                    if (parsedMultiMaterial.id === parsedMesh.materialId) {
+                                        for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
+                                            var subMatId = parsedMultiMaterial.materials[matIndex];
+                                            loadedMaterialsIds.push(subMatId);
+                                            parseMaterialById(subMatId, parsedData, scene, rootUrl);
+                                        }
+                                        loadedMaterialsIds.push(parsedMultiMaterial.id);
+                                        BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
+                                        materialFound = true;
+                                        break;
+                                    }
+                                }
+                            }
+                            if (!materialFound) {
+                                loadedMaterialsIds.push(parsedMesh.materialId);
+                                if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
+                                    BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
+                                }
+                            }
+                        }
+                        // Skeleton ?
+                        if (parsedMesh.skeletonId > -1 && scene.skeletons) {
+                            var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
+                            if (!skeletonAlreadyLoaded) {
+                                for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
+                                    var parsedSkeleton = parsedData.skeletons[skeletonIndex];
+                                    if (parsedSkeleton.id === parsedMesh.skeletonId) {
+                                        skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
+                                        loadedSkeletonsIds.push(parsedSkeleton.id);
+                                    }
+                                }
+                            }
+                        }
+                        var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
+                        meshes.push(mesh);
+                    }
+                }
+                // Connecting parents
+                var currentMesh;
+                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                    currentMesh = scene.meshes[index];
+                    if (currentMesh._waitingParentId) {
+                        currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
+                        currentMesh._waitingParentId = undefined;
+                    }
+                }
+                // freeze and compute world matrix application
+                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                    currentMesh = scene.meshes[index];
+                    if (currentMesh._waitingFreezeWorldMatrix) {
+                        currentMesh.freezeWorldMatrix();
+                        currentMesh._waitingFreezeWorldMatrix = undefined;
+                    }
+                    else {
+                        currentMesh.computeWorldMatrix(true);
+                    }
+                }
+                // Particles
+                if (parsedData.particleSystems) {
+                    for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
+                        var parsedParticleSystem = parsedData.particleSystems[index];
+                        if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
+                            particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
+                        }
+                    }
+                }
+                return true;
+            },
+            load: function (scene, data, rootUrl) {
+                var parsedData = JSON.parse(data);
+                // Scene
+                scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
+                scene.autoClear = parsedData.autoClear;
+                scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
+                scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
+                if (parsedData.gravity) {
+                    scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
+                }
+                // Fog
+                if (parsedData.fogMode && parsedData.fogMode !== 0) {
+                    scene.fogMode = parsedData.fogMode;
+                    scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
+                    scene.fogStart = parsedData.fogStart;
+                    scene.fogEnd = parsedData.fogEnd;
+                    scene.fogDensity = parsedData.fogDensity;
+                }
+                //Physics
+                if (parsedData.physicsEnabled) {
+                    var physicsPlugin;
+                    if (parsedData.physicsEngine === "cannon") {
+                        physicsPlugin = new BABYLON.CannonJSPlugin();
+                    }
+                    else if (parsedData.physicsEngine === "oimo") {
+                        physicsPlugin = new BABYLON.OimoJSPlugin();
+                    }
+                    //else - default engine, which is currently oimo
+                    var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
+                    scene.enablePhysics(physicsGravity, physicsPlugin);
+                }
+                //collisions, if defined. otherwise, default is true
+                if (parsedData.collisionsEnabled != undefined) {
+                    scene.collisionsEnabled = parsedData.collisionsEnabled;
+                }
+                scene.workerCollisions = !!parsedData.workerCollisions;
+                var index;
+                var cache;
+                // Lights
+                for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
+                    var parsedLight = parsedData.lights[index];
+                    BABYLON.Light.Parse(parsedLight, scene);
+                }
+                // Materials
+                if (parsedData.materials) {
+                    for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
+                        var parsedMaterial = parsedData.materials[index];
+                        BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
+                    }
+                }
+                if (parsedData.multiMaterials) {
+                    for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
+                        var parsedMultiMaterial = parsedData.multiMaterials[index];
+                        BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
+                    }
+                }
+                // Skeletons
+                if (parsedData.skeletons) {
+                    for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
+                        var parsedSkeleton = parsedData.skeletons[index];
+                        BABYLON.Skeleton.Parse(parsedSkeleton, scene);
+                    }
+                }
+                // Geometries
+                var geometries = parsedData.geometries;
+                if (geometries) {
+                    // Boxes
+                    var boxes = geometries.boxes;
+                    if (boxes) {
+                        for (index = 0, cache = boxes.length; index < cache; index++) {
+                            var parsedBox = boxes[index];
+                            BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
+                        }
+                    }
+                    // Spheres
+                    var spheres = geometries.spheres;
+                    if (spheres) {
+                        for (index = 0, cache = spheres.length; index < cache; index++) {
+                            var parsedSphere = spheres[index];
+                            BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
+                        }
+                    }
+                    // Cylinders
+                    var cylinders = geometries.cylinders;
+                    if (cylinders) {
+                        for (index = 0, cache = cylinders.length; index < cache; index++) {
+                            var parsedCylinder = cylinders[index];
+                            BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
+                        }
+                    }
+                    // Toruses
+                    var toruses = geometries.toruses;
+                    if (toruses) {
+                        for (index = 0, cache = toruses.length; index < cache; index++) {
+                            var parsedTorus = toruses[index];
+                            BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
+                        }
+                    }
+                    // Grounds
+                    var grounds = geometries.grounds;
+                    if (grounds) {
+                        for (index = 0, cache = grounds.length; index < cache; index++) {
+                            var parsedGround = grounds[index];
+                            BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
+                        }
+                    }
+                    // Planes
+                    var planes = geometries.planes;
+                    if (planes) {
+                        for (index = 0, cache = planes.length; index < cache; index++) {
+                            var parsedPlane = planes[index];
+                            BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
+                        }
+                    }
+                    // TorusKnots
+                    var torusKnots = geometries.torusKnots;
+                    if (torusKnots) {
+                        for (index = 0, cache = torusKnots.length; index < cache; index++) {
+                            var parsedTorusKnot = torusKnots[index];
+                            BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
+                        }
+                    }
+                    // VertexData
+                    var vertexData = geometries.vertexData;
+                    if (vertexData) {
+                        for (index = 0, cache = vertexData.length; index < cache; index++) {
+                            var parsedVertexData = vertexData[index];
+                            BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
+                        }
+                    }
+                }
+                // Meshes
+                for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
+                    var parsedMesh = parsedData.meshes[index];
+                    BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
+                }
+                // Cameras
+                for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
+                    var parsedCamera = parsedData.cameras[index];
+                    BABYLON.Camera.Parse(parsedCamera, scene);
+                }
+                if (parsedData.activeCameraID) {
+                    scene.setActiveCameraByID(parsedData.activeCameraID);
+                }
+                // Browsing all the graph to connect the dots
+                for (index = 0, cache = scene.cameras.length; index < cache; index++) {
+                    var camera = scene.cameras[index];
+                    if (camera._waitingParentId) {
+                        camera.parent = scene.getLastEntryByID(camera._waitingParentId);
+                        camera._waitingParentId = undefined;
+                    }
+                }
+                for (index = 0, cache = scene.lights.length; index < cache; index++) {
+                    var light = scene.lights[index];
+                    if (light._waitingParentId) {
+                        light.parent = scene.getLastEntryByID(light._waitingParentId);
+                        light._waitingParentId = undefined;
+                    }
+                }
+                // Sounds
+                var loadedSounds = [];
+                var loadedSound;
+                if (BABYLON.AudioEngine && parsedData.sounds) {
+                    for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
+                        var parsedSound = parsedData.sounds[index];
+                        if (BABYLON.Engine.audioEngine.canUseWebAudio) {
+                            if (!parsedSound.url)
+                                parsedSound.url = parsedSound.name;
+                            if (!loadedSounds[parsedSound.url]) {
+                                loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
+                                loadedSounds[parsedSound.url] = loadedSound;
+                            }
+                            else {
+                                BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
+                            }
+                        }
+                        else {
+                            var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
+                        }
+                    }
+                }
+                loadedSounds = [];
+                // Connect parents & children and parse actions
+                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                    var mesh = scene.meshes[index];
+                    if (mesh._waitingParentId) {
+                        mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
+                        mesh._waitingParentId = undefined;
+                    }
+                    if (mesh._waitingActions) {
+                        BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
+                        mesh._waitingActions = undefined;
+                    }
+                }
+                // freeze world matrix application
+                for (index = 0, cache = scene.meshes.length; index < cache; index++) {
+                    var currentMesh = scene.meshes[index];
+                    if (currentMesh._waitingFreezeWorldMatrix) {
+                        currentMesh.freezeWorldMatrix();
+                        currentMesh._waitingFreezeWorldMatrix = undefined;
+                    }
+                    else {
+                        currentMesh.computeWorldMatrix(true);
+                    }
+                }
+                // Particles Systems
+                if (parsedData.particleSystems) {
+                    for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
+                        var parsedParticleSystem = parsedData.particleSystems[index];
+                        BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
+                    }
+                }
+                // Lens flares
+                if (parsedData.lensFlareSystems) {
+                    for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
+                        var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
+                        BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
+                    }
+                }
+                // Shadows
+                if (parsedData.shadowGenerators) {
+                    for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
+                        var parsedShadowGenerator = parsedData.shadowGenerators[index];
+                        BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
+                    }
+                }
+                // Actions (scene)
+                if (parsedData.actions) {
+                    BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
+                }
+                // Finish
+                return true;
+            }
+        });
+    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.babylonFileLoader.js.map

+ 177 - 176
src/Loading/babylon.sceneLoader.js

@@ -1,176 +1,177 @@
-var BABYLON;
-(function (BABYLON) {
-    var SceneLoader = (function () {
-        function SceneLoader() {
-        }
-        Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
-            get: function () {
-                return SceneLoader._ForceFullSceneLoadingForIncremental;
-            },
-            set: function (value) {
-                SceneLoader._ForceFullSceneLoadingForIncremental = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
-            get: function () {
-                return SceneLoader._ShowLoadingScreen;
-            },
-            set: function (value) {
-                SceneLoader._ShowLoadingScreen = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        SceneLoader._getPluginForFilename = function (sceneFilename) {
-            var dotPosition = sceneFilename.lastIndexOf(".");
-            var queryStringPosition = sceneFilename.indexOf("?");
-            if (queryStringPosition === -1) {
-                queryStringPosition = sceneFilename.length;
-            }
-            var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
-            for (var index = 0; index < this._registeredPlugins.length; index++) {
-                var plugin = this._registeredPlugins[index];
-                if (plugin.extensions.indexOf(extension) !== -1) {
-                    return plugin;
-                }
-            }
-            return this._registeredPlugins[this._registeredPlugins.length - 1];
-        };
-        // Public functions
-        SceneLoader.RegisterPlugin = function (plugin) {
-            plugin.extensions = plugin.extensions.toLowerCase();
-            SceneLoader._registeredPlugins.push(plugin);
-        };
-        SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
-            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
-                BABYLON.Tools.Error("Wrong sceneFilename parameter");
-                return;
-            }
-            var loadingToken = {};
-            scene._addPendingData(loadingToken);
-            var manifestChecked = function (success) {
-                scene.database = database;
-                var plugin = SceneLoader._getPluginForFilename(sceneFilename);
-                var importMeshFromData = function (data) {
-                    var meshes = [];
-                    var particleSystems = [];
-                    var skeletons = [];
-                    try {
-                        if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
-                            if (onerror) {
-                                onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
-                            }
-                            scene._removePendingData(loadingToken);
-                            return;
-                        }
-                    }
-                    catch (e) {
-                        if (onerror) {
-                            onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
-                        }
-                        scene._removePendingData(loadingToken);
-                        return;
-                    }
-                    if (onsuccess) {
-                        scene.importedMeshesFiles.push(rootUrl + sceneFilename);
-                        onsuccess(meshes, particleSystems, skeletons);
-                        scene._removePendingData(loadingToken);
-                    }
-                };
-                if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
-                    // Direct load
-                    importMeshFromData(sceneFilename.substr(5));
-                    return;
-                }
-                BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
-                    importMeshFromData(data);
-                }, progressCallBack, database);
-            };
-            if (scene.getEngine().enableOfflineSupport) {
-                // Checking if a manifest file has been set for this scene and if offline mode has been requested
-                var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
-            }
-            else {
-                manifestChecked(true);
-            }
-        };
-        /**
-        * Load a scene
-        * @param rootUrl a string that defines the root url for scene and resources
-        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
-        * @param engine is the instance of BABYLON.Engine to use to create the scene
-        */
-        SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
-            SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
-        };
-        /**
-        * Append a scene
-        * @param rootUrl a string that defines the root url for scene and resources
-        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
-        * @param scene is the instance of BABYLON.Scene to append to
-        */
-        SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
-            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
-                BABYLON.Tools.Error("Wrong sceneFilename parameter");
-                return;
-            }
-            var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
-            var database;
-            var loadingToken = {};
-            scene._addPendingData(loadingToken);
-            if (SceneLoader.ShowLoadingScreen) {
-                scene.getEngine().displayLoadingUI();
-            }
-            var loadSceneFromData = function (data) {
-                scene.database = database;
-                if (!plugin.load(scene, data, rootUrl)) {
-                    if (onerror) {
-                        onerror(scene);
-                    }
-                    scene._removePendingData(loadingToken);
-                    scene.getEngine().hideLoadingUI();
-                    return;
-                }
-                if (onsuccess) {
-                    onsuccess(scene);
-                }
-                scene._removePendingData(loadingToken);
-                if (SceneLoader.ShowLoadingScreen) {
-                    scene.executeWhenReady(function () {
-                        scene.getEngine().hideLoadingUI();
-                    });
-                }
-            };
-            var manifestChecked = function (success) {
-                BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
-            };
-            if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
-                // Direct load
-                loadSceneFromData(sceneFilename.substr(5));
-                return;
-            }
-            if (rootUrl.indexOf("file:") === -1) {
-                if (scene.getEngine().enableOfflineSupport) {
-                    // Checking if a manifest file has been set for this scene and if offline mode has been requested
-                    database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
-                }
-                else {
-                    manifestChecked(true);
-                }
-            }
-            else {
-                BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
-            }
-        };
-        // Flags
-        SceneLoader._ForceFullSceneLoadingForIncremental = false;
-        SceneLoader._ShowLoadingScreen = true;
-        // Members
-        SceneLoader._registeredPlugins = new Array();
-        return SceneLoader;
-    })();
-    BABYLON.SceneLoader = SceneLoader;
-    ;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var SceneLoader = (function () {
+        function SceneLoader() {
+        }
+        Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
+            get: function () {
+                return SceneLoader._ForceFullSceneLoadingForIncremental;
+            },
+            set: function (value) {
+                SceneLoader._ForceFullSceneLoadingForIncremental = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
+            get: function () {
+                return SceneLoader._ShowLoadingScreen;
+            },
+            set: function (value) {
+                SceneLoader._ShowLoadingScreen = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        SceneLoader._getPluginForFilename = function (sceneFilename) {
+            var dotPosition = sceneFilename.lastIndexOf(".");
+            var queryStringPosition = sceneFilename.indexOf("?");
+            if (queryStringPosition === -1) {
+                queryStringPosition = sceneFilename.length;
+            }
+            var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
+            for (var index = 0; index < this._registeredPlugins.length; index++) {
+                var plugin = this._registeredPlugins[index];
+                if (plugin.extensions.indexOf(extension) !== -1) {
+                    return plugin;
+                }
+            }
+            return this._registeredPlugins[this._registeredPlugins.length - 1];
+        };
+        // Public functions
+        SceneLoader.RegisterPlugin = function (plugin) {
+            plugin.extensions = plugin.extensions.toLowerCase();
+            SceneLoader._registeredPlugins.push(plugin);
+        };
+        SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
+            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
+                BABYLON.Tools.Error("Wrong sceneFilename parameter");
+                return;
+            }
+            var loadingToken = {};
+            scene._addPendingData(loadingToken);
+            var manifestChecked = function (success) {
+                scene.database = database;
+                var plugin = SceneLoader._getPluginForFilename(sceneFilename);
+                var importMeshFromData = function (data) {
+                    var meshes = [];
+                    var particleSystems = [];
+                    var skeletons = [];
+                    try {
+                        if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
+                            if (onerror) {
+                                onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
+                            }
+                            scene._removePendingData(loadingToken);
+                            return;
+                        }
+                    }
+                    catch (e) {
+                        if (onerror) {
+                            onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
+                        }
+                        scene._removePendingData(loadingToken);
+                        return;
+                    }
+                    if (onsuccess) {
+                        scene.importedMeshesFiles.push(rootUrl + sceneFilename);
+                        onsuccess(meshes, particleSystems, skeletons);
+                        scene._removePendingData(loadingToken);
+                    }
+                };
+                if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
+                    // Direct load
+                    importMeshFromData(sceneFilename.substr(5));
+                    return;
+                }
+                BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
+                    importMeshFromData(data);
+                }, progressCallBack, database);
+            };
+            if (scene.getEngine().enableOfflineSupport) {
+                // Checking if a manifest file has been set for this scene and if offline mode has been requested
+                var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
+            }
+            else {
+                manifestChecked(true);
+            }
+        };
+        /**
+        * Load a scene
+        * @param rootUrl a string that defines the root url for scene and resources
+        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
+        * @param engine is the instance of BABYLON.Engine to use to create the scene
+        */
+        SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
+            SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
+        };
+        /**
+        * Append a scene
+        * @param rootUrl a string that defines the root url for scene and resources
+        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
+        * @param scene is the instance of BABYLON.Scene to append to
+        */
+        SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
+            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
+                BABYLON.Tools.Error("Wrong sceneFilename parameter");
+                return;
+            }
+            var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
+            var database;
+            var loadingToken = {};
+            scene._addPendingData(loadingToken);
+            if (SceneLoader.ShowLoadingScreen) {
+                scene.getEngine().displayLoadingUI();
+            }
+            var loadSceneFromData = function (data) {
+                scene.database = database;
+                if (!plugin.load(scene, data, rootUrl)) {
+                    if (onerror) {
+                        onerror(scene);
+                    }
+                    scene._removePendingData(loadingToken);
+                    scene.getEngine().hideLoadingUI();
+                    return;
+                }
+                if (onsuccess) {
+                    onsuccess(scene);
+                }
+                scene._removePendingData(loadingToken);
+                if (SceneLoader.ShowLoadingScreen) {
+                    scene.executeWhenReady(function () {
+                        scene.getEngine().hideLoadingUI();
+                    });
+                }
+            };
+            var manifestChecked = function (success) {
+                BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
+            };
+            if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
+                // Direct load
+                loadSceneFromData(sceneFilename.substr(5));
+                return;
+            }
+            if (rootUrl.indexOf("file:") === -1) {
+                if (scene.getEngine().enableOfflineSupport) {
+                    // Checking if a manifest file has been set for this scene and if offline mode has been requested
+                    database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
+                }
+                else {
+                    manifestChecked(true);
+                }
+            }
+            else {
+                BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
+            }
+        };
+        // Flags
+        SceneLoader._ForceFullSceneLoadingForIncremental = false;
+        SceneLoader._ShowLoadingScreen = true;
+        // Members
+        SceneLoader._registeredPlugins = new Array();
+        return SceneLoader;
+    })();
+    BABYLON.SceneLoader = SceneLoader;
+    ;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.sceneLoader.js.map

+ 125 - 124
src/Materials/Textures/Procedurals/babylon.customProceduralTexture.js

@@ -1,124 +1,125 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var CustomProceduralTexture = (function (_super) {
-        __extends(CustomProceduralTexture, _super);
-        function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
-            _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
-            this._animate = true;
-            this._time = 0;
-            this._texturePath = texturePath;
-            //Try to load json
-            this.loadJson(texturePath);
-            this.refreshRate = 1;
-        }
-        CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
-            var _this = this;
-            var that = this;
-            function noConfigFile() {
-                BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
-                try {
-                    that.setFragment(that._texturePath);
-                }
-                catch (ex) {
-                    BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
-                }
-            }
-            var configFileUrl = jsonUrl + "/config.json";
-            var xhr = new XMLHttpRequest();
-            xhr.open("GET", configFileUrl, true);
-            xhr.addEventListener("load", function () {
-                if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
-                    try {
-                        _this._config = JSON.parse(xhr.response);
-                        _this.updateShaderUniforms();
-                        _this.updateTextures();
-                        _this.setFragment(_this._texturePath + "/custom");
-                        _this._animate = _this._config.animate;
-                        _this.refreshRate = _this._config.refreshrate;
-                    }
-                    catch (ex) {
-                        noConfigFile();
-                    }
-                }
-                else {
-                    noConfigFile();
-                }
-            }, false);
-            xhr.addEventListener("error", function () {
-                noConfigFile();
-            }, false);
-            try {
-                xhr.send();
-            }
-            catch (ex) {
-                BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
-            }
-        };
-        CustomProceduralTexture.prototype.isReady = function () {
-            if (!_super.prototype.isReady.call(this)) {
-                return false;
-            }
-            for (var name in this._textures) {
-                var texture = this._textures[name];
-                if (!texture.isReady()) {
-                    return false;
-                }
-            }
-            return true;
-        };
-        CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
-            if (this._animate) {
-                this._time += this.getScene().getAnimationRatio() * 0.03;
-                this.updateShaderUniforms();
-            }
-            _super.prototype.render.call(this, useCameraPostProcess);
-        };
-        CustomProceduralTexture.prototype.updateTextures = function () {
-            for (var i = 0; i < this._config.sampler2Ds.length; i++) {
-                this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
-            }
-        };
-        CustomProceduralTexture.prototype.updateShaderUniforms = function () {
-            if (this._config) {
-                for (var j = 0; j < this._config.uniforms.length; j++) {
-                    var uniform = this._config.uniforms[j];
-                    switch (uniform.type) {
-                        case "float":
-                            this.setFloat(uniform.name, uniform.value);
-                            break;
-                        case "color3":
-                            this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
-                            break;
-                        case "color4":
-                            this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
-                            break;
-                        case "vector2":
-                            this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
-                            break;
-                        case "vector3":
-                            this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
-                            break;
-                    }
-                }
-            }
-            this.setFloat("time", this._time);
-        };
-        Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
-            get: function () {
-                return this._animate;
-            },
-            set: function (value) {
-                this._animate = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        return CustomProceduralTexture;
-    })(BABYLON.ProceduralTexture);
-    BABYLON.CustomProceduralTexture = CustomProceduralTexture;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var CustomProceduralTexture = (function (_super) {
+        __extends(CustomProceduralTexture, _super);
+        function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
+            _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
+            this._animate = true;
+            this._time = 0;
+            this._texturePath = texturePath;
+            //Try to load json
+            this.loadJson(texturePath);
+            this.refreshRate = 1;
+        }
+        CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
+            var _this = this;
+            var that = this;
+            function noConfigFile() {
+                BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
+                try {
+                    that.setFragment(that._texturePath);
+                }
+                catch (ex) {
+                    BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
+                }
+            }
+            var configFileUrl = jsonUrl + "/config.json";
+            var xhr = new XMLHttpRequest();
+            xhr.open("GET", configFileUrl, true);
+            xhr.addEventListener("load", function () {
+                if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
+                    try {
+                        _this._config = JSON.parse(xhr.response);
+                        _this.updateShaderUniforms();
+                        _this.updateTextures();
+                        _this.setFragment(_this._texturePath + "/custom");
+                        _this._animate = _this._config.animate;
+                        _this.refreshRate = _this._config.refreshrate;
+                    }
+                    catch (ex) {
+                        noConfigFile();
+                    }
+                }
+                else {
+                    noConfigFile();
+                }
+            }, false);
+            xhr.addEventListener("error", function () {
+                noConfigFile();
+            }, false);
+            try {
+                xhr.send();
+            }
+            catch (ex) {
+                BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
+            }
+        };
+        CustomProceduralTexture.prototype.isReady = function () {
+            if (!_super.prototype.isReady.call(this)) {
+                return false;
+            }
+            for (var name in this._textures) {
+                var texture = this._textures[name];
+                if (!texture.isReady()) {
+                    return false;
+                }
+            }
+            return true;
+        };
+        CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
+            if (this._animate) {
+                this._time += this.getScene().getAnimationRatio() * 0.03;
+                this.updateShaderUniforms();
+            }
+            _super.prototype.render.call(this, useCameraPostProcess);
+        };
+        CustomProceduralTexture.prototype.updateTextures = function () {
+            for (var i = 0; i < this._config.sampler2Ds.length; i++) {
+                this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
+            }
+        };
+        CustomProceduralTexture.prototype.updateShaderUniforms = function () {
+            if (this._config) {
+                for (var j = 0; j < this._config.uniforms.length; j++) {
+                    var uniform = this._config.uniforms[j];
+                    switch (uniform.type) {
+                        case "float":
+                            this.setFloat(uniform.name, uniform.value);
+                            break;
+                        case "color3":
+                            this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
+                            break;
+                        case "color4":
+                            this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
+                            break;
+                        case "vector2":
+                            this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
+                            break;
+                        case "vector3":
+                            this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
+                            break;
+                    }
+                }
+            }
+            this.setFloat("time", this._time);
+        };
+        Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
+            get: function () {
+                return this._animate;
+            },
+            set: function (value) {
+                this._animate = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        return CustomProceduralTexture;
+    })(BABYLON.ProceduralTexture);
+    BABYLON.CustomProceduralTexture = CustomProceduralTexture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.customProceduralTexture.js.map

+ 250 - 249
src/Materials/Textures/Procedurals/babylon.proceduralTexture.js

@@ -1,249 +1,250 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var ProceduralTexture = (function (_super) {
-        __extends(ProceduralTexture, _super);
-        function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
-            if (generateMipMaps === void 0) { generateMipMaps = true; }
-            _super.call(this, null, scene, !generateMipMaps);
-            this.isEnabled = true;
-            this._currentRefreshId = -1;
-            this._refreshRate = 1;
-            this._vertexDeclaration = [2];
-            this._vertexStrideSize = 2 * 4;
-            this._uniforms = new Array();
-            this._samplers = new Array();
-            this._textures = new Array();
-            this._floats = new Array();
-            this._floatsArrays = {};
-            this._colors3 = new Array();
-            this._colors4 = new Array();
-            this._vectors2 = new Array();
-            this._vectors3 = new Array();
-            this._matrices = new Array();
-            this._fallbackTextureUsed = false;
-            scene._proceduralTextures.push(this);
-            this.name = name;
-            this.isRenderTarget = true;
-            this._size = size;
-            this._generateMipMaps = generateMipMaps;
-            this.setFragment(fragment);
-            this._fallbackTexture = fallbackTexture;
-            this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
-            // VBO
-            var vertices = [];
-            vertices.push(1, 1);
-            vertices.push(-1, 1);
-            vertices.push(-1, -1);
-            vertices.push(1, -1);
-            this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
-            // Indices
-            var indices = [];
-            indices.push(0);
-            indices.push(1);
-            indices.push(2);
-            indices.push(0);
-            indices.push(2);
-            indices.push(3);
-            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
-        }
-        ProceduralTexture.prototype.reset = function () {
-            if (this._effect === undefined) {
-                return;
-            }
-            var engine = this.getScene().getEngine();
-            engine._releaseEffect(this._effect);
-        };
-        ProceduralTexture.prototype.isReady = function () {
-            var _this = this;
-            var engine = this.getScene().getEngine();
-            var shaders;
-            if (!this._fragment) {
-                return false;
-            }
-            if (this._fallbackTextureUsed) {
-                return true;
-            }
-            if (this._fragment.fragmentElement !== undefined) {
-                shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
-            }
-            else {
-                shaders = { vertex: "procedural", fragment: this._fragment };
-            }
-            this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
-                _this.releaseInternalTexture();
-                if (_this._fallbackTexture) {
-                    _this._texture = _this._fallbackTexture._texture;
-                    _this._texture.references++;
-                }
-                _this._fallbackTextureUsed = true;
-            });
-            return this._effect.isReady();
-        };
-        ProceduralTexture.prototype.resetRefreshCounter = function () {
-            this._currentRefreshId = -1;
-        };
-        ProceduralTexture.prototype.setFragment = function (fragment) {
-            this._fragment = fragment;
-        };
-        Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
-            get: function () {
-                return this._refreshRate;
-            },
-            // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
-            set: function (value) {
-                this._refreshRate = value;
-                this.resetRefreshCounter();
-            },
-            enumerable: true,
-            configurable: true
-        });
-        ProceduralTexture.prototype._shouldRender = function () {
-            if (!this.isEnabled || !this.isReady() || !this._texture) {
-                return false;
-            }
-            if (this._fallbackTextureUsed) {
-                return false;
-            }
-            if (this._currentRefreshId === -1) {
-                this._currentRefreshId = 1;
-                return true;
-            }
-            if (this.refreshRate === this._currentRefreshId) {
-                this._currentRefreshId = 1;
-                return true;
-            }
-            this._currentRefreshId++;
-            return false;
-        };
-        ProceduralTexture.prototype.getRenderSize = function () {
-            return this._size;
-        };
-        ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
-            if (this._fallbackTextureUsed) {
-                return;
-            }
-            this.releaseInternalTexture();
-            this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
-        };
-        ProceduralTexture.prototype._checkUniform = function (uniformName) {
-            if (this._uniforms.indexOf(uniformName) === -1) {
-                this._uniforms.push(uniformName);
-            }
-        };
-        ProceduralTexture.prototype.setTexture = function (name, texture) {
-            if (this._samplers.indexOf(name) === -1) {
-                this._samplers.push(name);
-            }
-            this._textures[name] = texture;
-            return this;
-        };
-        ProceduralTexture.prototype.setFloat = function (name, value) {
-            this._checkUniform(name);
-            this._floats[name] = value;
-            return this;
-        };
-        ProceduralTexture.prototype.setFloats = function (name, value) {
-            this._checkUniform(name);
-            this._floatsArrays[name] = value;
-            return this;
-        };
-        ProceduralTexture.prototype.setColor3 = function (name, value) {
-            this._checkUniform(name);
-            this._colors3[name] = value;
-            return this;
-        };
-        ProceduralTexture.prototype.setColor4 = function (name, value) {
-            this._checkUniform(name);
-            this._colors4[name] = value;
-            return this;
-        };
-        ProceduralTexture.prototype.setVector2 = function (name, value) {
-            this._checkUniform(name);
-            this._vectors2[name] = value;
-            return this;
-        };
-        ProceduralTexture.prototype.setVector3 = function (name, value) {
-            this._checkUniform(name);
-            this._vectors3[name] = value;
-            return this;
-        };
-        ProceduralTexture.prototype.setMatrix = function (name, value) {
-            this._checkUniform(name);
-            this._matrices[name] = value;
-            return this;
-        };
-        ProceduralTexture.prototype.render = function (useCameraPostProcess) {
-            var scene = this.getScene();
-            var engine = scene.getEngine();
-            engine.bindFramebuffer(this._texture);
-            // Clear
-            engine.clear(scene.clearColor, true, true);
-            // Render
-            engine.enableEffect(this._effect);
-            engine.setState(false);
-            // Texture
-            for (var name in this._textures) {
-                this._effect.setTexture(name, this._textures[name]);
-            }
-            // Float    
-            for (name in this._floats) {
-                this._effect.setFloat(name, this._floats[name]);
-            }
-            // Floats   
-            for (name in this._floatsArrays) {
-                this._effect.setArray(name, this._floatsArrays[name]);
-            }
-            // Color3        
-            for (name in this._colors3) {
-                this._effect.setColor3(name, this._colors3[name]);
-            }
-            // Color4      
-            for (name in this._colors4) {
-                var color = this._colors4[name];
-                this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
-            }
-            // Vector2        
-            for (name in this._vectors2) {
-                this._effect.setVector2(name, this._vectors2[name]);
-            }
-            // Vector3        
-            for (name in this._vectors3) {
-                this._effect.setVector3(name, this._vectors3[name]);
-            }
-            // Matrix      
-            for (name in this._matrices) {
-                this._effect.setMatrix(name, this._matrices[name]);
-            }
-            // VBOs
-            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
-            // Draw order
-            engine.draw(true, 0, 6);
-            // Unbind
-            engine.unBindFramebuffer(this._texture);
-        };
-        ProceduralTexture.prototype.clone = function () {
-            var textureSize = this.getSize();
-            var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
-            // Base texture
-            newTexture.hasAlpha = this.hasAlpha;
-            newTexture.level = this.level;
-            // RenderTarget Texture
-            newTexture.coordinatesMode = this.coordinatesMode;
-            return newTexture;
-        };
-        ProceduralTexture.prototype.dispose = function () {
-            var index = this.getScene()._proceduralTextures.indexOf(this);
-            if (index >= 0) {
-                this.getScene()._proceduralTextures.splice(index, 1);
-            }
-            _super.prototype.dispose.call(this);
-        };
-        return ProceduralTexture;
-    })(BABYLON.Texture);
-    BABYLON.ProceduralTexture = ProceduralTexture;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var ProceduralTexture = (function (_super) {
+        __extends(ProceduralTexture, _super);
+        function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
+            if (generateMipMaps === void 0) { generateMipMaps = true; }
+            _super.call(this, null, scene, !generateMipMaps);
+            this.isEnabled = true;
+            this._currentRefreshId = -1;
+            this._refreshRate = 1;
+            this._vertexDeclaration = [2];
+            this._vertexStrideSize = 2 * 4;
+            this._uniforms = new Array();
+            this._samplers = new Array();
+            this._textures = new Array();
+            this._floats = new Array();
+            this._floatsArrays = {};
+            this._colors3 = new Array();
+            this._colors4 = new Array();
+            this._vectors2 = new Array();
+            this._vectors3 = new Array();
+            this._matrices = new Array();
+            this._fallbackTextureUsed = false;
+            scene._proceduralTextures.push(this);
+            this.name = name;
+            this.isRenderTarget = true;
+            this._size = size;
+            this._generateMipMaps = generateMipMaps;
+            this.setFragment(fragment);
+            this._fallbackTexture = fallbackTexture;
+            this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
+            // VBO
+            var vertices = [];
+            vertices.push(1, 1);
+            vertices.push(-1, 1);
+            vertices.push(-1, -1);
+            vertices.push(1, -1);
+            this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
+            // Indices
+            var indices = [];
+            indices.push(0);
+            indices.push(1);
+            indices.push(2);
+            indices.push(0);
+            indices.push(2);
+            indices.push(3);
+            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
+        }
+        ProceduralTexture.prototype.reset = function () {
+            if (this._effect === undefined) {
+                return;
+            }
+            var engine = this.getScene().getEngine();
+            engine._releaseEffect(this._effect);
+        };
+        ProceduralTexture.prototype.isReady = function () {
+            var _this = this;
+            var engine = this.getScene().getEngine();
+            var shaders;
+            if (!this._fragment) {
+                return false;
+            }
+            if (this._fallbackTextureUsed) {
+                return true;
+            }
+            if (this._fragment.fragmentElement !== undefined) {
+                shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
+            }
+            else {
+                shaders = { vertex: "procedural", fragment: this._fragment };
+            }
+            this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
+                _this.releaseInternalTexture();
+                if (_this._fallbackTexture) {
+                    _this._texture = _this._fallbackTexture._texture;
+                    _this._texture.references++;
+                }
+                _this._fallbackTextureUsed = true;
+            });
+            return this._effect.isReady();
+        };
+        ProceduralTexture.prototype.resetRefreshCounter = function () {
+            this._currentRefreshId = -1;
+        };
+        ProceduralTexture.prototype.setFragment = function (fragment) {
+            this._fragment = fragment;
+        };
+        Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
+            get: function () {
+                return this._refreshRate;
+            },
+            // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
+            set: function (value) {
+                this._refreshRate = value;
+                this.resetRefreshCounter();
+            },
+            enumerable: true,
+            configurable: true
+        });
+        ProceduralTexture.prototype._shouldRender = function () {
+            if (!this.isEnabled || !this.isReady() || !this._texture) {
+                return false;
+            }
+            if (this._fallbackTextureUsed) {
+                return false;
+            }
+            if (this._currentRefreshId === -1) {
+                this._currentRefreshId = 1;
+                return true;
+            }
+            if (this.refreshRate === this._currentRefreshId) {
+                this._currentRefreshId = 1;
+                return true;
+            }
+            this._currentRefreshId++;
+            return false;
+        };
+        ProceduralTexture.prototype.getRenderSize = function () {
+            return this._size;
+        };
+        ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
+            if (this._fallbackTextureUsed) {
+                return;
+            }
+            this.releaseInternalTexture();
+            this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
+        };
+        ProceduralTexture.prototype._checkUniform = function (uniformName) {
+            if (this._uniforms.indexOf(uniformName) === -1) {
+                this._uniforms.push(uniformName);
+            }
+        };
+        ProceduralTexture.prototype.setTexture = function (name, texture) {
+            if (this._samplers.indexOf(name) === -1) {
+                this._samplers.push(name);
+            }
+            this._textures[name] = texture;
+            return this;
+        };
+        ProceduralTexture.prototype.setFloat = function (name, value) {
+            this._checkUniform(name);
+            this._floats[name] = value;
+            return this;
+        };
+        ProceduralTexture.prototype.setFloats = function (name, value) {
+            this._checkUniform(name);
+            this._floatsArrays[name] = value;
+            return this;
+        };
+        ProceduralTexture.prototype.setColor3 = function (name, value) {
+            this._checkUniform(name);
+            this._colors3[name] = value;
+            return this;
+        };
+        ProceduralTexture.prototype.setColor4 = function (name, value) {
+            this._checkUniform(name);
+            this._colors4[name] = value;
+            return this;
+        };
+        ProceduralTexture.prototype.setVector2 = function (name, value) {
+            this._checkUniform(name);
+            this._vectors2[name] = value;
+            return this;
+        };
+        ProceduralTexture.prototype.setVector3 = function (name, value) {
+            this._checkUniform(name);
+            this._vectors3[name] = value;
+            return this;
+        };
+        ProceduralTexture.prototype.setMatrix = function (name, value) {
+            this._checkUniform(name);
+            this._matrices[name] = value;
+            return this;
+        };
+        ProceduralTexture.prototype.render = function (useCameraPostProcess) {
+            var scene = this.getScene();
+            var engine = scene.getEngine();
+            engine.bindFramebuffer(this._texture);
+            // Clear
+            engine.clear(scene.clearColor, true, true);
+            // Render
+            engine.enableEffect(this._effect);
+            engine.setState(false);
+            // Texture
+            for (var name in this._textures) {
+                this._effect.setTexture(name, this._textures[name]);
+            }
+            // Float    
+            for (name in this._floats) {
+                this._effect.setFloat(name, this._floats[name]);
+            }
+            // Floats   
+            for (name in this._floatsArrays) {
+                this._effect.setArray(name, this._floatsArrays[name]);
+            }
+            // Color3        
+            for (name in this._colors3) {
+                this._effect.setColor3(name, this._colors3[name]);
+            }
+            // Color4      
+            for (name in this._colors4) {
+                var color = this._colors4[name];
+                this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
+            }
+            // Vector2        
+            for (name in this._vectors2) {
+                this._effect.setVector2(name, this._vectors2[name]);
+            }
+            // Vector3        
+            for (name in this._vectors3) {
+                this._effect.setVector3(name, this._vectors3[name]);
+            }
+            // Matrix      
+            for (name in this._matrices) {
+                this._effect.setMatrix(name, this._matrices[name]);
+            }
+            // VBOs
+            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
+            // Draw order
+            engine.draw(true, 0, 6);
+            // Unbind
+            engine.unBindFramebuffer(this._texture);
+        };
+        ProceduralTexture.prototype.clone = function () {
+            var textureSize = this.getSize();
+            var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
+            // Base texture
+            newTexture.hasAlpha = this.hasAlpha;
+            newTexture.level = this.level;
+            // RenderTarget Texture
+            newTexture.coordinatesMode = this.coordinatesMode;
+            return newTexture;
+        };
+        ProceduralTexture.prototype.dispose = function () {
+            var index = this.getScene()._proceduralTextures.indexOf(this);
+            if (index >= 0) {
+                this.getScene()._proceduralTextures.splice(index, 1);
+            }
+            _super.prototype.dispose.call(this);
+        };
+        return ProceduralTexture;
+    })(BABYLON.Texture);
+    BABYLON.ProceduralTexture = ProceduralTexture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.proceduralTexture.js.map

+ 139 - 138
src/Materials/Textures/babylon.baseTexture.js

@@ -1,138 +1,139 @@
-var BABYLON;
-(function (BABYLON) {
-    var BaseTexture = (function () {
-        function BaseTexture(scene) {
-            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
-            this.hasAlpha = false;
-            this.getAlphaFromRGB = false;
-            this.level = 1;
-            this.isCube = false;
-            this.isRenderTarget = false;
-            this.animations = new Array();
-            this.coordinatesIndex = 0;
-            this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
-            this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
-            this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
-            this.anisotropicFilteringLevel = 4;
-            this._scene = scene;
-            this._scene.textures.push(this);
-        }
-        BaseTexture.prototype.getScene = function () {
-            return this._scene;
-        };
-        BaseTexture.prototype.getTextureMatrix = function () {
-            return null;
-        };
-        BaseTexture.prototype.getReflectionTextureMatrix = function () {
-            return null;
-        };
-        BaseTexture.prototype.getInternalTexture = function () {
-            return this._texture;
-        };
-        BaseTexture.prototype.isReady = function () {
-            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
-                return true;
-            }
-            if (this._texture) {
-                return this._texture.isReady;
-            }
-            return false;
-        };
-        BaseTexture.prototype.getSize = function () {
-            if (this._texture._width) {
-                return { width: this._texture._width, height: this._texture._height };
-            }
-            if (this._texture._size) {
-                return { width: this._texture._size, height: this._texture._size };
-            }
-            return { width: 0, height: 0 };
-        };
-        BaseTexture.prototype.getBaseSize = function () {
-            if (!this.isReady())
-                return { width: 0, height: 0 };
-            if (this._texture._size) {
-                return { width: this._texture._size, height: this._texture._size };
-            }
-            return { width: this._texture._baseWidth, height: this._texture._baseHeight };
-        };
-        BaseTexture.prototype.scale = function (ratio) {
-        };
-        Object.defineProperty(BaseTexture.prototype, "canRescale", {
-            get: function () {
-                return false;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
-            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
-            for (var index = 0; index < texturesCache.length; index++) {
-                var texturesCacheEntry = texturesCache[index];
-                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
-                    texturesCache.splice(index, 1);
-                    return;
-                }
-            }
-        };
-        BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
-            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
-            for (var index = 0; index < texturesCache.length; index++) {
-                var texturesCacheEntry = texturesCache[index];
-                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
-                    if (!sampling || sampling === texturesCacheEntry.samplingMode) {
-                        texturesCacheEntry.references++;
-                        return texturesCacheEntry;
-                    }
-                }
-            }
-            return null;
-        };
-        BaseTexture.prototype.delayLoad = function () {
-        };
-        BaseTexture.prototype.clone = function () {
-            return null;
-        };
-        BaseTexture.prototype.releaseInternalTexture = function () {
-            if (this._texture) {
-                this._scene.getEngine().releaseInternalTexture(this._texture);
-                delete this._texture;
-            }
-        };
-        BaseTexture.prototype.dispose = function () {
-            // Animations
-            this.getScene().stopAnimation(this);
-            // Remove from scene
-            var index = this._scene.textures.indexOf(this);
-            if (index >= 0) {
-                this._scene.textures.splice(index, 1);
-            }
-            if (this._texture === undefined) {
-                return;
-            }
-            // Release
-            this.releaseInternalTexture();
-            // Callback
-            if (this.onDispose) {
-                this.onDispose();
-            }
-        };
-        BaseTexture.prototype.serialize = function () {
-            var serializationObject = {};
-            if (!this.name) {
-                return null;
-            }
-            serializationObject.name = this.name;
-            serializationObject.hasAlpha = this.hasAlpha;
-            serializationObject.level = this.level;
-            serializationObject.coordinatesIndex = this.coordinatesIndex;
-            serializationObject.coordinatesMode = this.coordinatesMode;
-            serializationObject.wrapU = this.wrapU;
-            serializationObject.wrapV = this.wrapV;
-            // Animations
-            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
-            return serializationObject;
-        };
-        return BaseTexture;
-    })();
-    BABYLON.BaseTexture = BaseTexture;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var BaseTexture = (function () {
+        function BaseTexture(scene) {
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
+            this.hasAlpha = false;
+            this.getAlphaFromRGB = false;
+            this.level = 1;
+            this.isCube = false;
+            this.isRenderTarget = false;
+            this.animations = new Array();
+            this.coordinatesIndex = 0;
+            this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
+            this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
+            this.anisotropicFilteringLevel = 4;
+            this._scene = scene;
+            this._scene.textures.push(this);
+        }
+        BaseTexture.prototype.getScene = function () {
+            return this._scene;
+        };
+        BaseTexture.prototype.getTextureMatrix = function () {
+            return null;
+        };
+        BaseTexture.prototype.getReflectionTextureMatrix = function () {
+            return null;
+        };
+        BaseTexture.prototype.getInternalTexture = function () {
+            return this._texture;
+        };
+        BaseTexture.prototype.isReady = function () {
+            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return true;
+            }
+            if (this._texture) {
+                return this._texture.isReady;
+            }
+            return false;
+        };
+        BaseTexture.prototype.getSize = function () {
+            if (this._texture._width) {
+                return { width: this._texture._width, height: this._texture._height };
+            }
+            if (this._texture._size) {
+                return { width: this._texture._size, height: this._texture._size };
+            }
+            return { width: 0, height: 0 };
+        };
+        BaseTexture.prototype.getBaseSize = function () {
+            if (!this.isReady())
+                return { width: 0, height: 0 };
+            if (this._texture._size) {
+                return { width: this._texture._size, height: this._texture._size };
+            }
+            return { width: this._texture._baseWidth, height: this._texture._baseHeight };
+        };
+        BaseTexture.prototype.scale = function (ratio) {
+        };
+        Object.defineProperty(BaseTexture.prototype, "canRescale", {
+            get: function () {
+                return false;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
+            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
+            for (var index = 0; index < texturesCache.length; index++) {
+                var texturesCacheEntry = texturesCache[index];
+                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
+                    texturesCache.splice(index, 1);
+                    return;
+                }
+            }
+        };
+        BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
+            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
+            for (var index = 0; index < texturesCache.length; index++) {
+                var texturesCacheEntry = texturesCache[index];
+                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
+                    if (!sampling || sampling === texturesCacheEntry.samplingMode) {
+                        texturesCacheEntry.references++;
+                        return texturesCacheEntry;
+                    }
+                }
+            }
+            return null;
+        };
+        BaseTexture.prototype.delayLoad = function () {
+        };
+        BaseTexture.prototype.clone = function () {
+            return null;
+        };
+        BaseTexture.prototype.releaseInternalTexture = function () {
+            if (this._texture) {
+                this._scene.getEngine().releaseInternalTexture(this._texture);
+                delete this._texture;
+            }
+        };
+        BaseTexture.prototype.dispose = function () {
+            // Animations
+            this.getScene().stopAnimation(this);
+            // Remove from scene
+            var index = this._scene.textures.indexOf(this);
+            if (index >= 0) {
+                this._scene.textures.splice(index, 1);
+            }
+            if (this._texture === undefined) {
+                return;
+            }
+            // Release
+            this.releaseInternalTexture();
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        };
+        BaseTexture.prototype.serialize = function () {
+            var serializationObject = {};
+            if (!this.name) {
+                return null;
+            }
+            serializationObject.name = this.name;
+            serializationObject.hasAlpha = this.hasAlpha;
+            serializationObject.level = this.level;
+            serializationObject.coordinatesIndex = this.coordinatesIndex;
+            serializationObject.coordinatesMode = this.coordinatesMode;
+            serializationObject.wrapU = this.wrapU;
+            serializationObject.wrapV = this.wrapV;
+            // Animations
+            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
+            return serializationObject;
+        };
+        return BaseTexture;
+    })();
+    BABYLON.BaseTexture = BaseTexture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.baseTexture.js.map

+ 87 - 86
src/Materials/Textures/babylon.cubeTexture.js

@@ -1,86 +1,87 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var CubeTexture = (function (_super) {
-        __extends(CubeTexture, _super);
-        function CubeTexture(rootUrl, scene, extensions, noMipmap) {
-            _super.call(this, scene);
-            this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
-            this.name = rootUrl;
-            this.url = rootUrl;
-            this._noMipmap = noMipmap;
-            this.hasAlpha = false;
-            if (!rootUrl) {
-                return;
-            }
-            this._texture = this._getFromCache(rootUrl, noMipmap);
-            if (!extensions) {
-                extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
-            }
-            this._extensions = extensions;
-            if (!this._texture) {
-                if (!scene.useDelayedTextureLoading) {
-                    this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
-                }
-                else {
-                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
-                }
-            }
-            this.isCube = true;
-            this._textureMatrix = BABYLON.Matrix.Identity();
-        }
-        CubeTexture.prototype.clone = function () {
-            var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
-            // Base texture
-            newTexture.level = this.level;
-            newTexture.wrapU = this.wrapU;
-            newTexture.wrapV = this.wrapV;
-            newTexture.coordinatesIndex = this.coordinatesIndex;
-            newTexture.coordinatesMode = this.coordinatesMode;
-            return newTexture;
-        };
-        // Methods
-        CubeTexture.prototype.delayLoad = function () {
-            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
-                return;
-            }
-            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
-            this._texture = this._getFromCache(this.url, this._noMipmap);
-            if (!this._texture) {
-                this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
-            }
-        };
-        CubeTexture.prototype.getReflectionTextureMatrix = function () {
-            return this._textureMatrix;
-        };
-        CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
-            var texture = null;
-            if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
-                texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
-                texture.name = parsedTexture.name;
-                texture.hasAlpha = parsedTexture.hasAlpha;
-                texture.level = parsedTexture.level;
-                texture.coordinatesMode = parsedTexture.coordinatesMode;
-            }
-            return texture;
-        };
-        CubeTexture.prototype.serialize = function () {
-            if (!this.name) {
-                return null;
-            }
-            var serializationObject = {};
-            serializationObject.name = this.name;
-            serializationObject.hasAlpha = this.hasAlpha;
-            serializationObject.isCube = true;
-            serializationObject.level = this.level;
-            serializationObject.coordinatesMode = this.coordinatesMode;
-            return serializationObject;
-        };
-        return CubeTexture;
-    })(BABYLON.BaseTexture);
-    BABYLON.CubeTexture = CubeTexture;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var CubeTexture = (function (_super) {
+        __extends(CubeTexture, _super);
+        function CubeTexture(rootUrl, scene, extensions, noMipmap) {
+            _super.call(this, scene);
+            this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
+            this.name = rootUrl;
+            this.url = rootUrl;
+            this._noMipmap = noMipmap;
+            this.hasAlpha = false;
+            if (!rootUrl) {
+                return;
+            }
+            this._texture = this._getFromCache(rootUrl, noMipmap);
+            if (!extensions) {
+                extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
+            }
+            this._extensions = extensions;
+            if (!this._texture) {
+                if (!scene.useDelayedTextureLoading) {
+                    this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
+                }
+                else {
+                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                }
+            }
+            this.isCube = true;
+            this._textureMatrix = BABYLON.Matrix.Identity();
+        }
+        CubeTexture.prototype.clone = function () {
+            var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
+            // Base texture
+            newTexture.level = this.level;
+            newTexture.wrapU = this.wrapU;
+            newTexture.wrapV = this.wrapV;
+            newTexture.coordinatesIndex = this.coordinatesIndex;
+            newTexture.coordinatesMode = this.coordinatesMode;
+            return newTexture;
+        };
+        // Methods
+        CubeTexture.prototype.delayLoad = function () {
+            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return;
+            }
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this._texture = this._getFromCache(this.url, this._noMipmap);
+            if (!this._texture) {
+                this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
+            }
+        };
+        CubeTexture.prototype.getReflectionTextureMatrix = function () {
+            return this._textureMatrix;
+        };
+        CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
+            var texture = null;
+            if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
+                texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
+                texture.name = parsedTexture.name;
+                texture.hasAlpha = parsedTexture.hasAlpha;
+                texture.level = parsedTexture.level;
+                texture.coordinatesMode = parsedTexture.coordinatesMode;
+            }
+            return texture;
+        };
+        CubeTexture.prototype.serialize = function () {
+            if (!this.name) {
+                return null;
+            }
+            var serializationObject = {};
+            serializationObject.name = this.name;
+            serializationObject.hasAlpha = this.hasAlpha;
+            serializationObject.isCube = true;
+            serializationObject.level = this.level;
+            serializationObject.coordinatesMode = this.coordinatesMode;
+            return serializationObject;
+        };
+        return CubeTexture;
+    })(BABYLON.BaseTexture);
+    BABYLON.CubeTexture = CubeTexture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.cubeTexture.js.map

+ 94 - 93
src/Materials/Textures/babylon.dynamicTexture.js

@@ -1,93 +1,94 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var DynamicTexture = (function (_super) {
-        __extends(DynamicTexture, _super);
-        function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            _super.call(this, null, scene, !generateMipMaps);
-            this.name = name;
-            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this._generateMipMaps = generateMipMaps;
-            if (options.getContext) {
-                this._canvas = options;
-                this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
-            }
-            else {
-                this._canvas = document.createElement("canvas");
-                if (options.width) {
-                    this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
-                }
-                else {
-                    this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
-                }
-            }
-            var textureSize = this.getSize();
-            this._canvas.width = textureSize.width;
-            this._canvas.height = textureSize.height;
-            this._context = this._canvas.getContext("2d");
-        }
-        Object.defineProperty(DynamicTexture.prototype, "canRescale", {
-            get: function () {
-                return true;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        DynamicTexture.prototype.scale = function (ratio) {
-            var textureSize = this.getSize();
-            textureSize.width *= ratio;
-            textureSize.height *= ratio;
-            this._canvas.width = textureSize.width;
-            this._canvas.height = textureSize.height;
-            this.releaseInternalTexture();
-            this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
-        };
-        DynamicTexture.prototype.getContext = function () {
-            return this._context;
-        };
-        DynamicTexture.prototype.clear = function () {
-            var size = this.getSize();
-            this._context.fillRect(0, 0, size.width, size.height);
-        };
-        DynamicTexture.prototype.update = function (invertY) {
-            this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
-        };
-        DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
-            if (update === void 0) { update = true; }
-            var size = this.getSize();
-            if (clearColor) {
-                this._context.fillStyle = clearColor;
-                this._context.fillRect(0, 0, size.width, size.height);
-            }
-            this._context.font = font;
-            if (x === null) {
-                var textSize = this._context.measureText(text);
-                x = (size.width - textSize.width) / 2;
-            }
-            this._context.fillStyle = color;
-            this._context.fillText(text, x, y);
-            if (update) {
-                this.update(invertY);
-            }
-        };
-        DynamicTexture.prototype.clone = function () {
-            var textureSize = this.getSize();
-            var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
-            // Base texture
-            newTexture.hasAlpha = this.hasAlpha;
-            newTexture.level = this.level;
-            // Dynamic Texture
-            newTexture.wrapU = this.wrapU;
-            newTexture.wrapV = this.wrapV;
-            return newTexture;
-        };
-        return DynamicTexture;
-    })(BABYLON.Texture);
-    BABYLON.DynamicTexture = DynamicTexture;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var DynamicTexture = (function (_super) {
+        __extends(DynamicTexture, _super);
+        function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            _super.call(this, null, scene, !generateMipMaps);
+            this.name = name;
+            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._generateMipMaps = generateMipMaps;
+            if (options.getContext) {
+                this._canvas = options;
+                this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
+            }
+            else {
+                this._canvas = document.createElement("canvas");
+                if (options.width) {
+                    this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
+                }
+                else {
+                    this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
+                }
+            }
+            var textureSize = this.getSize();
+            this._canvas.width = textureSize.width;
+            this._canvas.height = textureSize.height;
+            this._context = this._canvas.getContext("2d");
+        }
+        Object.defineProperty(DynamicTexture.prototype, "canRescale", {
+            get: function () {
+                return true;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        DynamicTexture.prototype.scale = function (ratio) {
+            var textureSize = this.getSize();
+            textureSize.width *= ratio;
+            textureSize.height *= ratio;
+            this._canvas.width = textureSize.width;
+            this._canvas.height = textureSize.height;
+            this.releaseInternalTexture();
+            this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
+        };
+        DynamicTexture.prototype.getContext = function () {
+            return this._context;
+        };
+        DynamicTexture.prototype.clear = function () {
+            var size = this.getSize();
+            this._context.fillRect(0, 0, size.width, size.height);
+        };
+        DynamicTexture.prototype.update = function (invertY) {
+            this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
+        };
+        DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
+            if (update === void 0) { update = true; }
+            var size = this.getSize();
+            if (clearColor) {
+                this._context.fillStyle = clearColor;
+                this._context.fillRect(0, 0, size.width, size.height);
+            }
+            this._context.font = font;
+            if (x === null) {
+                var textSize = this._context.measureText(text);
+                x = (size.width - textSize.width) / 2;
+            }
+            this._context.fillStyle = color;
+            this._context.fillText(text, x, y);
+            if (update) {
+                this.update(invertY);
+            }
+        };
+        DynamicTexture.prototype.clone = function () {
+            var textureSize = this.getSize();
+            var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
+            // Base texture
+            newTexture.hasAlpha = this.hasAlpha;
+            newTexture.level = this.level;
+            // Dynamic Texture
+            newTexture.wrapU = this.wrapU;
+            newTexture.wrapV = this.wrapV;
+            return newTexture;
+        };
+        return DynamicTexture;
+    })(BABYLON.Texture);
+    BABYLON.DynamicTexture = DynamicTexture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.dynamicTexture.js.map

+ 55 - 54
src/Materials/Textures/babylon.mirrorTexture.js

@@ -1,54 +1,55 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var MirrorTexture = (function (_super) {
-        __extends(MirrorTexture, _super);
-        function MirrorTexture(name, size, scene, generateMipMaps) {
-            var _this = this;
-            _super.call(this, name, size, scene, generateMipMaps, true);
-            this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
-            this._transformMatrix = BABYLON.Matrix.Zero();
-            this._mirrorMatrix = BABYLON.Matrix.Zero();
-            this.onBeforeRender = function () {
-                BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
-                _this._savedViewMatrix = scene.getViewMatrix();
-                _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
-                scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
-                scene.clipPlane = _this.mirrorPlane;
-                scene.getEngine().cullBackFaces = false;
-                scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
-            };
-            this.onAfterRender = function () {
-                scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
-                scene.getEngine().cullBackFaces = true;
-                scene._mirroredCameraPosition = null;
-                delete scene.clipPlane;
-            };
-        }
-        MirrorTexture.prototype.clone = function () {
-            var textureSize = this.getSize();
-            var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
-            // Base texture
-            newTexture.hasAlpha = this.hasAlpha;
-            newTexture.level = this.level;
-            // Mirror Texture
-            newTexture.mirrorPlane = this.mirrorPlane.clone();
-            newTexture.renderList = this.renderList.slice(0);
-            return newTexture;
-        };
-        MirrorTexture.prototype.serialize = function () {
-            if (!this.name) {
-                return null;
-            }
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.mirrorPlane = this.mirrorPlane.asArray();
-            return serializationObject;
-        };
-        return MirrorTexture;
-    })(BABYLON.RenderTargetTexture);
-    BABYLON.MirrorTexture = MirrorTexture;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var MirrorTexture = (function (_super) {
+        __extends(MirrorTexture, _super);
+        function MirrorTexture(name, size, scene, generateMipMaps) {
+            var _this = this;
+            _super.call(this, name, size, scene, generateMipMaps, true);
+            this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
+            this._transformMatrix = BABYLON.Matrix.Zero();
+            this._mirrorMatrix = BABYLON.Matrix.Zero();
+            this.onBeforeRender = function () {
+                BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
+                _this._savedViewMatrix = scene.getViewMatrix();
+                _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
+                scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
+                scene.clipPlane = _this.mirrorPlane;
+                scene.getEngine().cullBackFaces = false;
+                scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
+            };
+            this.onAfterRender = function () {
+                scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
+                scene.getEngine().cullBackFaces = true;
+                scene._mirroredCameraPosition = null;
+                delete scene.clipPlane;
+            };
+        }
+        MirrorTexture.prototype.clone = function () {
+            var textureSize = this.getSize();
+            var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
+            // Base texture
+            newTexture.hasAlpha = this.hasAlpha;
+            newTexture.level = this.level;
+            // Mirror Texture
+            newTexture.mirrorPlane = this.mirrorPlane.clone();
+            newTexture.renderList = this.renderList.slice(0);
+            return newTexture;
+        };
+        MirrorTexture.prototype.serialize = function () {
+            if (!this.name) {
+                return null;
+            }
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.mirrorPlane = this.mirrorPlane.asArray();
+            return serializationObject;
+        };
+        return MirrorTexture;
+    })(BABYLON.RenderTargetTexture);
+    BABYLON.MirrorTexture = MirrorTexture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.mirrorTexture.js.map

+ 58 - 57
src/Materials/Textures/babylon.rawTexture.js

@@ -1,57 +1,58 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var RawTexture = (function (_super) {
-        __extends(RawTexture, _super);
-        function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
-            if (generateMipMaps === void 0) { generateMipMaps = true; }
-            if (invertY === void 0) { invertY = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            _super.call(this, null, scene, !generateMipMaps, invertY);
-            this.format = format;
-            this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
-            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-        }
-        RawTexture.prototype.update = function (data) {
-            this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
-        };
-        // Statics
-        RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
-            if (generateMipMaps === void 0) { generateMipMaps = true; }
-            if (invertY === void 0) { invertY = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
-        };
-        RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
-            if (generateMipMaps === void 0) { generateMipMaps = true; }
-            if (invertY === void 0) { invertY = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
-        };
-        RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
-            if (generateMipMaps === void 0) { generateMipMaps = true; }
-            if (invertY === void 0) { invertY = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
-        };
-        RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
-            if (generateMipMaps === void 0) { generateMipMaps = true; }
-            if (invertY === void 0) { invertY = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
-        };
-        RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
-            if (generateMipMaps === void 0) { generateMipMaps = true; }
-            if (invertY === void 0) { invertY = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
-        };
-        return RawTexture;
-    })(BABYLON.Texture);
-    BABYLON.RawTexture = RawTexture;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var RawTexture = (function (_super) {
+        __extends(RawTexture, _super);
+        function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
+            if (generateMipMaps === void 0) { generateMipMaps = true; }
+            if (invertY === void 0) { invertY = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            _super.call(this, null, scene, !generateMipMaps, invertY);
+            this.format = format;
+            this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
+            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+        }
+        RawTexture.prototype.update = function (data) {
+            this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
+        };
+        // Statics
+        RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
+            if (generateMipMaps === void 0) { generateMipMaps = true; }
+            if (invertY === void 0) { invertY = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
+        };
+        RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
+            if (generateMipMaps === void 0) { generateMipMaps = true; }
+            if (invertY === void 0) { invertY = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
+        };
+        RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
+            if (generateMipMaps === void 0) { generateMipMaps = true; }
+            if (invertY === void 0) { invertY = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
+        };
+        RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
+            if (generateMipMaps === void 0) { generateMipMaps = true; }
+            if (invertY === void 0) { invertY = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
+        };
+        RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
+            if (generateMipMaps === void 0) { generateMipMaps = true; }
+            if (invertY === void 0) { invertY = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
+        };
+        return RawTexture;
+    })(BABYLON.Texture);
+    BABYLON.RawTexture = RawTexture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.rawTexture.js.map

+ 255 - 254
src/Materials/Textures/babylon.renderTargetTexture.js

@@ -1,254 +1,255 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var RenderTargetTexture = (function (_super) {
-        __extends(RenderTargetTexture, _super);
-        function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
-            if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
-            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
-            if (isCube === void 0) { isCube = false; }
-            _super.call(this, null, scene, !generateMipMaps);
-            this.isCube = isCube;
-            this.renderList = new Array();
-            this.renderParticles = true;
-            this.renderSprites = false;
-            this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
-            this._currentRefreshId = -1;
-            this._refreshRate = 1;
-            this.name = name;
-            this.isRenderTarget = true;
-            this._size = size;
-            this._generateMipMaps = generateMipMaps;
-            this._doNotChangeAspectRatio = doNotChangeAspectRatio;
-            if (isCube) {
-                this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
-                this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
-                this._textureMatrix = BABYLON.Matrix.Identity();
-            }
-            else {
-                this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
-            }
-            // Rendering groups
-            this._renderingManager = new BABYLON.RenderingManager(scene);
-        }
-        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
-            get: function () {
-                return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
-            get: function () {
-                return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
-            get: function () {
-                return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        RenderTargetTexture.prototype.resetRefreshCounter = function () {
-            this._currentRefreshId = -1;
-        };
-        Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
-            get: function () {
-                return this._refreshRate;
-            },
-            // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
-            set: function (value) {
-                this._refreshRate = value;
-                this.resetRefreshCounter();
-            },
-            enumerable: true,
-            configurable: true
-        });
-        RenderTargetTexture.prototype._shouldRender = function () {
-            if (this._currentRefreshId === -1) {
-                this._currentRefreshId = 1;
-                return true;
-            }
-            if (this.refreshRate === this._currentRefreshId) {
-                this._currentRefreshId = 1;
-                return true;
-            }
-            this._currentRefreshId++;
-            return false;
-        };
-        RenderTargetTexture.prototype.isReady = function () {
-            if (!this.getScene().renderTargetsEnabled) {
-                return false;
-            }
-            return _super.prototype.isReady.call(this);
-        };
-        RenderTargetTexture.prototype.getRenderSize = function () {
-            return this._size;
-        };
-        Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
-            get: function () {
-                return true;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        RenderTargetTexture.prototype.scale = function (ratio) {
-            var newSize = this._size * ratio;
-            this.resize(newSize, this._generateMipMaps);
-        };
-        RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
-            if (this.isCube) {
-                return this._textureMatrix;
-            }
-            return _super.prototype.getReflectionTextureMatrix.call(this);
-        };
-        RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
-            this.releaseInternalTexture();
-            if (this.isCube) {
-                this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
-            }
-            else {
-                this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
-            }
-        };
-        RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
-            var scene = this.getScene();
-            if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
-                scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
-            }
-            if (this._waitingRenderList) {
-                this.renderList = [];
-                for (var index = 0; index < this._waitingRenderList.length; index++) {
-                    var id = this._waitingRenderList[index];
-                    this.renderList.push(scene.getMeshByID(id));
-                }
-                delete this._waitingRenderList;
-            }
-            if (this.renderList && this.renderList.length === 0) {
-                return;
-            }
-            // Prepare renderingManager
-            this._renderingManager.reset();
-            var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
-            for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
-                var mesh = currentRenderList[meshIndex];
-                if (mesh) {
-                    if (!mesh.isReady()) {
-                        // Reset _currentRefreshId
-                        this.resetRefreshCounter();
-                        continue;
-                    }
-                    if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
-                        mesh._activate(scene.getRenderId());
-                        for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
-                            var subMesh = mesh.subMeshes[subIndex];
-                            scene._activeIndices += subMesh.indexCount;
-                            this._renderingManager.dispatch(subMesh);
-                        }
-                    }
-                }
-            }
-            if (this.isCube) {
-                for (var face = 0; face < 6; face++) {
-                    this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
-                    scene.incrementRenderId();
-                }
-            }
-            else {
-                this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
-            }
-            if (this.onAfterUnbind) {
-                this.onAfterUnbind();
-            }
-            if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
-                scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
-            }
-            scene.resetCachedMaterial();
-        };
-        RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
-            var scene = this.getScene();
-            var engine = scene.getEngine();
-            // Bind
-            if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
-                if (this.isCube) {
-                    engine.bindFramebuffer(this._texture, faceIndex);
-                }
-                else {
-                    engine.bindFramebuffer(this._texture);
-                }
-            }
-            if (this.onBeforeRender) {
-                this.onBeforeRender(faceIndex);
-            }
-            // Clear
-            if (this.onClear) {
-                this.onClear(engine);
-            }
-            else {
-                engine.clear(scene.clearColor, true, true);
-            }
-            if (!this._doNotChangeAspectRatio) {
-                scene.updateTransformMatrix(true);
-            }
-            // Render
-            this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
-            if (useCameraPostProcess) {
-                scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
-            }
-            if (!this._doNotChangeAspectRatio) {
-                scene.updateTransformMatrix(true);
-            }
-            if (this.onAfterRender) {
-                this.onAfterRender(faceIndex);
-            }
-            // Dump ?
-            if (dumpForDebug) {
-                BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
-            }
-            // Unbind
-            if (!this.isCube || faceIndex === 5) {
-                if (this.isCube) {
-                    if (faceIndex === 5) {
-                        engine.generateMipMapsForCubemap(this._texture);
-                    }
-                }
-                engine.unBindFramebuffer(this._texture, this.isCube);
-            }
-        };
-        RenderTargetTexture.prototype.clone = function () {
-            var textureSize = this.getSize();
-            var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
-            // Base texture
-            newTexture.hasAlpha = this.hasAlpha;
-            newTexture.level = this.level;
-            // RenderTarget Texture
-            newTexture.coordinatesMode = this.coordinatesMode;
-            newTexture.renderList = this.renderList.slice(0);
-            return newTexture;
-        };
-        RenderTargetTexture.prototype.serialize = function () {
-            if (!this.name) {
-                return null;
-            }
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.renderTargetSize = this.getRenderSize();
-            serializationObject.renderList = [];
-            for (var index = 0; index < this.renderList.length; index++) {
-                serializationObject.renderList.push(this.renderList[index].id);
-            }
-            return serializationObject;
-        };
-        RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
-        RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
-        RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
-        return RenderTargetTexture;
-    })(BABYLON.Texture);
-    BABYLON.RenderTargetTexture = RenderTargetTexture;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var RenderTargetTexture = (function (_super) {
+        __extends(RenderTargetTexture, _super);
+        function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
+            if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
+            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
+            if (isCube === void 0) { isCube = false; }
+            _super.call(this, null, scene, !generateMipMaps);
+            this.isCube = isCube;
+            this.renderList = new Array();
+            this.renderParticles = true;
+            this.renderSprites = false;
+            this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
+            this._currentRefreshId = -1;
+            this._refreshRate = 1;
+            this.name = name;
+            this.isRenderTarget = true;
+            this._size = size;
+            this._generateMipMaps = generateMipMaps;
+            this._doNotChangeAspectRatio = doNotChangeAspectRatio;
+            if (isCube) {
+                this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
+                this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
+                this._textureMatrix = BABYLON.Matrix.Identity();
+            }
+            else {
+                this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
+            }
+            // Rendering groups
+            this._renderingManager = new BABYLON.RenderingManager(scene);
+        }
+        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
+            get: function () {
+                return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
+            get: function () {
+                return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
+            get: function () {
+                return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        RenderTargetTexture.prototype.resetRefreshCounter = function () {
+            this._currentRefreshId = -1;
+        };
+        Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
+            get: function () {
+                return this._refreshRate;
+            },
+            // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
+            set: function (value) {
+                this._refreshRate = value;
+                this.resetRefreshCounter();
+            },
+            enumerable: true,
+            configurable: true
+        });
+        RenderTargetTexture.prototype._shouldRender = function () {
+            if (this._currentRefreshId === -1) {
+                this._currentRefreshId = 1;
+                return true;
+            }
+            if (this.refreshRate === this._currentRefreshId) {
+                this._currentRefreshId = 1;
+                return true;
+            }
+            this._currentRefreshId++;
+            return false;
+        };
+        RenderTargetTexture.prototype.isReady = function () {
+            if (!this.getScene().renderTargetsEnabled) {
+                return false;
+            }
+            return _super.prototype.isReady.call(this);
+        };
+        RenderTargetTexture.prototype.getRenderSize = function () {
+            return this._size;
+        };
+        Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
+            get: function () {
+                return true;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        RenderTargetTexture.prototype.scale = function (ratio) {
+            var newSize = this._size * ratio;
+            this.resize(newSize, this._generateMipMaps);
+        };
+        RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
+            if (this.isCube) {
+                return this._textureMatrix;
+            }
+            return _super.prototype.getReflectionTextureMatrix.call(this);
+        };
+        RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
+            this.releaseInternalTexture();
+            if (this.isCube) {
+                this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
+            }
+            else {
+                this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
+            }
+        };
+        RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
+            var scene = this.getScene();
+            if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
+                scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
+            }
+            if (this._waitingRenderList) {
+                this.renderList = [];
+                for (var index = 0; index < this._waitingRenderList.length; index++) {
+                    var id = this._waitingRenderList[index];
+                    this.renderList.push(scene.getMeshByID(id));
+                }
+                delete this._waitingRenderList;
+            }
+            if (this.renderList && this.renderList.length === 0) {
+                return;
+            }
+            // Prepare renderingManager
+            this._renderingManager.reset();
+            var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
+            for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
+                var mesh = currentRenderList[meshIndex];
+                if (mesh) {
+                    if (!mesh.isReady()) {
+                        // Reset _currentRefreshId
+                        this.resetRefreshCounter();
+                        continue;
+                    }
+                    if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
+                        mesh._activate(scene.getRenderId());
+                        for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
+                            var subMesh = mesh.subMeshes[subIndex];
+                            scene._activeIndices += subMesh.indexCount;
+                            this._renderingManager.dispatch(subMesh);
+                        }
+                    }
+                }
+            }
+            if (this.isCube) {
+                for (var face = 0; face < 6; face++) {
+                    this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
+                    scene.incrementRenderId();
+                }
+            }
+            else {
+                this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
+            }
+            if (this.onAfterUnbind) {
+                this.onAfterUnbind();
+            }
+            if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
+                scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
+            }
+            scene.resetCachedMaterial();
+        };
+        RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
+            var scene = this.getScene();
+            var engine = scene.getEngine();
+            // Bind
+            if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
+                if (this.isCube) {
+                    engine.bindFramebuffer(this._texture, faceIndex);
+                }
+                else {
+                    engine.bindFramebuffer(this._texture);
+                }
+            }
+            if (this.onBeforeRender) {
+                this.onBeforeRender(faceIndex);
+            }
+            // Clear
+            if (this.onClear) {
+                this.onClear(engine);
+            }
+            else {
+                engine.clear(scene.clearColor, true, true);
+            }
+            if (!this._doNotChangeAspectRatio) {
+                scene.updateTransformMatrix(true);
+            }
+            // Render
+            this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
+            if (useCameraPostProcess) {
+                scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
+            }
+            if (!this._doNotChangeAspectRatio) {
+                scene.updateTransformMatrix(true);
+            }
+            if (this.onAfterRender) {
+                this.onAfterRender(faceIndex);
+            }
+            // Dump ?
+            if (dumpForDebug) {
+                BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
+            }
+            // Unbind
+            if (!this.isCube || faceIndex === 5) {
+                if (this.isCube) {
+                    if (faceIndex === 5) {
+                        engine.generateMipMapsForCubemap(this._texture);
+                    }
+                }
+                engine.unBindFramebuffer(this._texture, this.isCube);
+            }
+        };
+        RenderTargetTexture.prototype.clone = function () {
+            var textureSize = this.getSize();
+            var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
+            // Base texture
+            newTexture.hasAlpha = this.hasAlpha;
+            newTexture.level = this.level;
+            // RenderTarget Texture
+            newTexture.coordinatesMode = this.coordinatesMode;
+            newTexture.renderList = this.renderList.slice(0);
+            return newTexture;
+        };
+        RenderTargetTexture.prototype.serialize = function () {
+            if (!this.name) {
+                return null;
+            }
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.renderTargetSize = this.getRenderSize();
+            serializationObject.renderList = [];
+            for (var index = 0; index < this.renderList.length; index++) {
+                serializationObject.renderList.push(this.renderList[index].id);
+            }
+            return serializationObject;
+        };
+        RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
+        RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
+        RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
+        return RenderTargetTexture;
+    })(BABYLON.Texture);
+    BABYLON.RenderTargetTexture = RenderTargetTexture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.renderTargetTexture.js.map

+ 273 - 272
src/Materials/Textures/babylon.texture.js

@@ -1,272 +1,273 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var Texture = (function (_super) {
-        __extends(Texture, _super);
-        function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
-            if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
-            if (onLoad === void 0) { onLoad = null; }
-            if (onError === void 0) { onError = null; }
-            if (buffer === void 0) { buffer = null; }
-            if (deleteBuffer === void 0) { deleteBuffer = false; }
-            _super.call(this, scene);
-            this.uOffset = 0;
-            this.vOffset = 0;
-            this.uScale = 1.0;
-            this.vScale = 1.0;
-            this.uAng = 0;
-            this.vAng = 0;
-            this.wAng = 0;
-            this.name = url;
-            this.url = url;
-            this._noMipmap = noMipmap;
-            this._invertY = invertY;
-            this._samplingMode = samplingMode;
-            this._buffer = buffer;
-            this._deleteBuffer = deleteBuffer;
-            if (!url) {
-                return;
-            }
-            this._texture = this._getFromCache(url, noMipmap, samplingMode);
-            if (!this._texture) {
-                if (!scene.useDelayedTextureLoading) {
-                    this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
-                    if (deleteBuffer) {
-                        delete this._buffer;
-                    }
-                }
-                else {
-                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
-                }
-            }
-            else {
-                BABYLON.Tools.SetImmediate(function () {
-                    if (onLoad) {
-                        onLoad();
-                    }
-                });
-            }
-        }
-        Texture.prototype.delayLoad = function () {
-            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
-                return;
-            }
-            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
-            this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
-            if (!this._texture) {
-                this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
-                if (this._deleteBuffer) {
-                    delete this._buffer;
-                }
-            }
-        };
-        Texture.prototype.updateSamplingMode = function (samplingMode) {
-            if (!this._texture) {
-                return;
-            }
-            this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
-        };
-        Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
-            x *= this.uScale;
-            y *= this.vScale;
-            x -= 0.5 * this.uScale;
-            y -= 0.5 * this.vScale;
-            z -= 0.5;
-            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
-            t.x += 0.5 * this.uScale + this.uOffset;
-            t.y += 0.5 * this.vScale + this.vOffset;
-            t.z += 0.5;
-        };
-        Texture.prototype.getTextureMatrix = function () {
-            if (this.uOffset === this._cachedUOffset &&
-                this.vOffset === this._cachedVOffset &&
-                this.uScale === this._cachedUScale &&
-                this.vScale === this._cachedVScale &&
-                this.uAng === this._cachedUAng &&
-                this.vAng === this._cachedVAng &&
-                this.wAng === this._cachedWAng) {
-                return this._cachedTextureMatrix;
-            }
-            this._cachedUOffset = this.uOffset;
-            this._cachedVOffset = this.vOffset;
-            this._cachedUScale = this.uScale;
-            this._cachedVScale = this.vScale;
-            this._cachedUAng = this.uAng;
-            this._cachedVAng = this.vAng;
-            this._cachedWAng = this.wAng;
-            if (!this._cachedTextureMatrix) {
-                this._cachedTextureMatrix = BABYLON.Matrix.Zero();
-                this._rowGenerationMatrix = new BABYLON.Matrix();
-                this._t0 = BABYLON.Vector3.Zero();
-                this._t1 = BABYLON.Vector3.Zero();
-                this._t2 = BABYLON.Vector3.Zero();
-            }
-            BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
-            this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
-            this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
-            this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
-            this._t1.subtractInPlace(this._t0);
-            this._t2.subtractInPlace(this._t0);
-            BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
-            this._cachedTextureMatrix.m[0] = this._t1.x;
-            this._cachedTextureMatrix.m[1] = this._t1.y;
-            this._cachedTextureMatrix.m[2] = this._t1.z;
-            this._cachedTextureMatrix.m[4] = this._t2.x;
-            this._cachedTextureMatrix.m[5] = this._t2.y;
-            this._cachedTextureMatrix.m[6] = this._t2.z;
-            this._cachedTextureMatrix.m[8] = this._t0.x;
-            this._cachedTextureMatrix.m[9] = this._t0.y;
-            this._cachedTextureMatrix.m[10] = this._t0.z;
-            return this._cachedTextureMatrix;
-        };
-        Texture.prototype.getReflectionTextureMatrix = function () {
-            if (this.uOffset === this._cachedUOffset &&
-                this.vOffset === this._cachedVOffset &&
-                this.uScale === this._cachedUScale &&
-                this.vScale === this._cachedVScale &&
-                this.coordinatesMode === this._cachedCoordinatesMode) {
-                return this._cachedTextureMatrix;
-            }
-            if (!this._cachedTextureMatrix) {
-                this._cachedTextureMatrix = BABYLON.Matrix.Zero();
-                this._projectionModeMatrix = BABYLON.Matrix.Zero();
-            }
-            this._cachedCoordinatesMode = this.coordinatesMode;
-            switch (this.coordinatesMode) {
-                case Texture.PLANAR_MODE:
-                    BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
-                    this._cachedTextureMatrix[0] = this.uScale;
-                    this._cachedTextureMatrix[5] = this.vScale;
-                    this._cachedTextureMatrix[12] = this.uOffset;
-                    this._cachedTextureMatrix[13] = this.vOffset;
-                    break;
-                case Texture.PROJECTION_MODE:
-                    BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
-                    this._projectionModeMatrix.m[0] = 0.5;
-                    this._projectionModeMatrix.m[5] = -0.5;
-                    this._projectionModeMatrix.m[10] = 0.0;
-                    this._projectionModeMatrix.m[12] = 0.5;
-                    this._projectionModeMatrix.m[13] = 0.5;
-                    this._projectionModeMatrix.m[14] = 1.0;
-                    this._projectionModeMatrix.m[15] = 1.0;
-                    this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
-                    break;
-                default:
-                    BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
-                    break;
-            }
-            return this._cachedTextureMatrix;
-        };
-        Texture.prototype.clone = function () {
-            var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
-            // Base texture
-            newTexture.hasAlpha = this.hasAlpha;
-            newTexture.level = this.level;
-            newTexture.wrapU = this.wrapU;
-            newTexture.wrapV = this.wrapV;
-            newTexture.coordinatesIndex = this.coordinatesIndex;
-            newTexture.coordinatesMode = this.coordinatesMode;
-            // Texture
-            newTexture.uOffset = this.uOffset;
-            newTexture.vOffset = this.vOffset;
-            newTexture.uScale = this.uScale;
-            newTexture.vScale = this.vScale;
-            newTexture.uAng = this.uAng;
-            newTexture.vAng = this.vAng;
-            newTexture.wAng = this.wAng;
-            return newTexture;
-        };
-        Texture.prototype.serialize = function () {
-            if (!this.name) {
-                return null;
-            }
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.uOffset = this.uOffset;
-            serializationObject.vOffset = this.vOffset;
-            serializationObject.uScale = this.uScale;
-            serializationObject.vScale = this.vScale;
-            serializationObject.uAng = this.uAng;
-            serializationObject.vAng = this.vAng;
-            serializationObject.wAng = this.wAng;
-            return serializationObject;
-        };
-        // Statics
-        Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
-            if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
-            if (onLoad === void 0) { onLoad = null; }
-            if (onError === void 0) { onError = null; }
-            return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
-        };
-        Texture.Parse = function (parsedTexture, scene, rootUrl) {
-            if (parsedTexture.isCube) {
-                return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
-            }
-            if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
-                return null;
-            }
-            var texture;
-            if (parsedTexture.mirrorPlane) {
-                texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
-                texture._waitingRenderList = parsedTexture.renderList;
-                texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
-            }
-            else if (parsedTexture.isRenderTarget) {
-                texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
-                texture._waitingRenderList = parsedTexture.renderList;
-            }
-            else {
-                if (parsedTexture.base64String) {
-                    texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
-                }
-                else {
-                    texture = new Texture(rootUrl + parsedTexture.name, scene);
-                }
-            }
-            texture.name = parsedTexture.name;
-            texture.hasAlpha = parsedTexture.hasAlpha;
-            texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
-            texture.level = parsedTexture.level;
-            texture.coordinatesIndex = parsedTexture.coordinatesIndex;
-            texture.coordinatesMode = parsedTexture.coordinatesMode;
-            texture.uOffset = parsedTexture.uOffset;
-            texture.vOffset = parsedTexture.vOffset;
-            texture.uScale = parsedTexture.uScale;
-            texture.vScale = parsedTexture.vScale;
-            texture.uAng = parsedTexture.uAng;
-            texture.vAng = parsedTexture.vAng;
-            texture.wAng = parsedTexture.wAng;
-            texture.wrapU = parsedTexture.wrapU;
-            texture.wrapV = parsedTexture.wrapV;
-            // Animations
-            if (parsedTexture.animations) {
-                for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
-                    var parsedAnimation = parsedTexture.animations[animationIndex];
-                    texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
-                }
-            }
-            return texture;
-        };
-        // Constants
-        Texture.NEAREST_SAMPLINGMODE = 1;
-        Texture.BILINEAR_SAMPLINGMODE = 2;
-        Texture.TRILINEAR_SAMPLINGMODE = 3;
-        Texture.EXPLICIT_MODE = 0;
-        Texture.SPHERICAL_MODE = 1;
-        Texture.PLANAR_MODE = 2;
-        Texture.CUBIC_MODE = 3;
-        Texture.PROJECTION_MODE = 4;
-        Texture.SKYBOX_MODE = 5;
-        Texture.INVCUBIC_MODE = 6;
-        Texture.EQUIRECTANGULAR_MODE = 7;
-        Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
-        Texture.CLAMP_ADDRESSMODE = 0;
-        Texture.WRAP_ADDRESSMODE = 1;
-        Texture.MIRROR_ADDRESSMODE = 2;
-        return Texture;
-    })(BABYLON.BaseTexture);
-    BABYLON.Texture = Texture;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var Texture = (function (_super) {
+        __extends(Texture, _super);
+        function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
+            if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
+            if (onLoad === void 0) { onLoad = null; }
+            if (onError === void 0) { onError = null; }
+            if (buffer === void 0) { buffer = null; }
+            if (deleteBuffer === void 0) { deleteBuffer = false; }
+            _super.call(this, scene);
+            this.uOffset = 0;
+            this.vOffset = 0;
+            this.uScale = 1.0;
+            this.vScale = 1.0;
+            this.uAng = 0;
+            this.vAng = 0;
+            this.wAng = 0;
+            this.name = url;
+            this.url = url;
+            this._noMipmap = noMipmap;
+            this._invertY = invertY;
+            this._samplingMode = samplingMode;
+            this._buffer = buffer;
+            this._deleteBuffer = deleteBuffer;
+            if (!url) {
+                return;
+            }
+            this._texture = this._getFromCache(url, noMipmap, samplingMode);
+            if (!this._texture) {
+                if (!scene.useDelayedTextureLoading) {
+                    this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
+                    if (deleteBuffer) {
+                        delete this._buffer;
+                    }
+                }
+                else {
+                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                }
+            }
+            else {
+                BABYLON.Tools.SetImmediate(function () {
+                    if (onLoad) {
+                        onLoad();
+                    }
+                });
+            }
+        }
+        Texture.prototype.delayLoad = function () {
+            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return;
+            }
+            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
+            if (!this._texture) {
+                this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
+                if (this._deleteBuffer) {
+                    delete this._buffer;
+                }
+            }
+        };
+        Texture.prototype.updateSamplingMode = function (samplingMode) {
+            if (!this._texture) {
+                return;
+            }
+            this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
+        };
+        Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
+            x *= this.uScale;
+            y *= this.vScale;
+            x -= 0.5 * this.uScale;
+            y -= 0.5 * this.vScale;
+            z -= 0.5;
+            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
+            t.x += 0.5 * this.uScale + this.uOffset;
+            t.y += 0.5 * this.vScale + this.vOffset;
+            t.z += 0.5;
+        };
+        Texture.prototype.getTextureMatrix = function () {
+            if (this.uOffset === this._cachedUOffset &&
+                this.vOffset === this._cachedVOffset &&
+                this.uScale === this._cachedUScale &&
+                this.vScale === this._cachedVScale &&
+                this.uAng === this._cachedUAng &&
+                this.vAng === this._cachedVAng &&
+                this.wAng === this._cachedWAng) {
+                return this._cachedTextureMatrix;
+            }
+            this._cachedUOffset = this.uOffset;
+            this._cachedVOffset = this.vOffset;
+            this._cachedUScale = this.uScale;
+            this._cachedVScale = this.vScale;
+            this._cachedUAng = this.uAng;
+            this._cachedVAng = this.vAng;
+            this._cachedWAng = this.wAng;
+            if (!this._cachedTextureMatrix) {
+                this._cachedTextureMatrix = BABYLON.Matrix.Zero();
+                this._rowGenerationMatrix = new BABYLON.Matrix();
+                this._t0 = BABYLON.Vector3.Zero();
+                this._t1 = BABYLON.Vector3.Zero();
+                this._t2 = BABYLON.Vector3.Zero();
+            }
+            BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
+            this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
+            this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
+            this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
+            this._t1.subtractInPlace(this._t0);
+            this._t2.subtractInPlace(this._t0);
+            BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
+            this._cachedTextureMatrix.m[0] = this._t1.x;
+            this._cachedTextureMatrix.m[1] = this._t1.y;
+            this._cachedTextureMatrix.m[2] = this._t1.z;
+            this._cachedTextureMatrix.m[4] = this._t2.x;
+            this._cachedTextureMatrix.m[5] = this._t2.y;
+            this._cachedTextureMatrix.m[6] = this._t2.z;
+            this._cachedTextureMatrix.m[8] = this._t0.x;
+            this._cachedTextureMatrix.m[9] = this._t0.y;
+            this._cachedTextureMatrix.m[10] = this._t0.z;
+            return this._cachedTextureMatrix;
+        };
+        Texture.prototype.getReflectionTextureMatrix = function () {
+            if (this.uOffset === this._cachedUOffset &&
+                this.vOffset === this._cachedVOffset &&
+                this.uScale === this._cachedUScale &&
+                this.vScale === this._cachedVScale &&
+                this.coordinatesMode === this._cachedCoordinatesMode) {
+                return this._cachedTextureMatrix;
+            }
+            if (!this._cachedTextureMatrix) {
+                this._cachedTextureMatrix = BABYLON.Matrix.Zero();
+                this._projectionModeMatrix = BABYLON.Matrix.Zero();
+            }
+            this._cachedCoordinatesMode = this.coordinatesMode;
+            switch (this.coordinatesMode) {
+                case Texture.PLANAR_MODE:
+                    BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
+                    this._cachedTextureMatrix[0] = this.uScale;
+                    this._cachedTextureMatrix[5] = this.vScale;
+                    this._cachedTextureMatrix[12] = this.uOffset;
+                    this._cachedTextureMatrix[13] = this.vOffset;
+                    break;
+                case Texture.PROJECTION_MODE:
+                    BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
+                    this._projectionModeMatrix.m[0] = 0.5;
+                    this._projectionModeMatrix.m[5] = -0.5;
+                    this._projectionModeMatrix.m[10] = 0.0;
+                    this._projectionModeMatrix.m[12] = 0.5;
+                    this._projectionModeMatrix.m[13] = 0.5;
+                    this._projectionModeMatrix.m[14] = 1.0;
+                    this._projectionModeMatrix.m[15] = 1.0;
+                    this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
+                    break;
+                default:
+                    BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
+                    break;
+            }
+            return this._cachedTextureMatrix;
+        };
+        Texture.prototype.clone = function () {
+            var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
+            // Base texture
+            newTexture.hasAlpha = this.hasAlpha;
+            newTexture.level = this.level;
+            newTexture.wrapU = this.wrapU;
+            newTexture.wrapV = this.wrapV;
+            newTexture.coordinatesIndex = this.coordinatesIndex;
+            newTexture.coordinatesMode = this.coordinatesMode;
+            // Texture
+            newTexture.uOffset = this.uOffset;
+            newTexture.vOffset = this.vOffset;
+            newTexture.uScale = this.uScale;
+            newTexture.vScale = this.vScale;
+            newTexture.uAng = this.uAng;
+            newTexture.vAng = this.vAng;
+            newTexture.wAng = this.wAng;
+            return newTexture;
+        };
+        Texture.prototype.serialize = function () {
+            if (!this.name) {
+                return null;
+            }
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.uOffset = this.uOffset;
+            serializationObject.vOffset = this.vOffset;
+            serializationObject.uScale = this.uScale;
+            serializationObject.vScale = this.vScale;
+            serializationObject.uAng = this.uAng;
+            serializationObject.vAng = this.vAng;
+            serializationObject.wAng = this.wAng;
+            return serializationObject;
+        };
+        // Statics
+        Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
+            if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
+            if (onLoad === void 0) { onLoad = null; }
+            if (onError === void 0) { onError = null; }
+            return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
+        };
+        Texture.Parse = function (parsedTexture, scene, rootUrl) {
+            if (parsedTexture.isCube) {
+                return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
+            }
+            if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
+                return null;
+            }
+            var texture;
+            if (parsedTexture.mirrorPlane) {
+                texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
+                texture._waitingRenderList = parsedTexture.renderList;
+                texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
+            }
+            else if (parsedTexture.isRenderTarget) {
+                texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
+                texture._waitingRenderList = parsedTexture.renderList;
+            }
+            else {
+                if (parsedTexture.base64String) {
+                    texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
+                }
+                else {
+                    texture = new Texture(rootUrl + parsedTexture.name, scene);
+                }
+            }
+            texture.name = parsedTexture.name;
+            texture.hasAlpha = parsedTexture.hasAlpha;
+            texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
+            texture.level = parsedTexture.level;
+            texture.coordinatesIndex = parsedTexture.coordinatesIndex;
+            texture.coordinatesMode = parsedTexture.coordinatesMode;
+            texture.uOffset = parsedTexture.uOffset;
+            texture.vOffset = parsedTexture.vOffset;
+            texture.uScale = parsedTexture.uScale;
+            texture.vScale = parsedTexture.vScale;
+            texture.uAng = parsedTexture.uAng;
+            texture.vAng = parsedTexture.vAng;
+            texture.wAng = parsedTexture.wAng;
+            texture.wrapU = parsedTexture.wrapU;
+            texture.wrapV = parsedTexture.wrapV;
+            // Animations
+            if (parsedTexture.animations) {
+                for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
+                    var parsedAnimation = parsedTexture.animations[animationIndex];
+                    texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
+                }
+            }
+            return texture;
+        };
+        // Constants
+        Texture.NEAREST_SAMPLINGMODE = 1;
+        Texture.BILINEAR_SAMPLINGMODE = 2;
+        Texture.TRILINEAR_SAMPLINGMODE = 3;
+        Texture.EXPLICIT_MODE = 0;
+        Texture.SPHERICAL_MODE = 1;
+        Texture.PLANAR_MODE = 2;
+        Texture.CUBIC_MODE = 3;
+        Texture.PROJECTION_MODE = 4;
+        Texture.SKYBOX_MODE = 5;
+        Texture.INVCUBIC_MODE = 6;
+        Texture.EQUIRECTANGULAR_MODE = 7;
+        Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
+        Texture.CLAMP_ADDRESSMODE = 0;
+        Texture.WRAP_ADDRESSMODE = 1;
+        Texture.MIRROR_ADDRESSMODE = 2;
+        return Texture;
+    })(BABYLON.BaseTexture);
+    BABYLON.Texture = Texture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.texture.js.map

+ 59 - 58
src/Materials/Textures/babylon.videoTexture.js

@@ -1,58 +1,59 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var VideoTexture = (function (_super) {
-        __extends(VideoTexture, _super);
-        function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
-            var _this = this;
-            if (generateMipMaps === void 0) { generateMipMaps = false; }
-            if (invertY === void 0) { invertY = false; }
-            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
-            _super.call(this, null, scene, !generateMipMaps, invertY);
-            this._autoLaunch = true;
-            this.name = name;
-            this.video = document.createElement("video");
-            this.video.autoplay = false;
-            this.video.loop = true;
-            this.video.addEventListener("canplaythrough", function () {
-                if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
-                    _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
-                    _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
-                }
-                else {
-                    _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-                    _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-                    generateMipMaps = false;
-                }
-                _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
-                _this._texture.isReady = true;
-            });
-            urls.forEach(function (url) {
-                //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
-                var source = document.createElement("source");
-                source.src = url;
-                _this.video.appendChild(source);
-            });
-            this._lastUpdate = BABYLON.Tools.Now;
-        }
-        VideoTexture.prototype.update = function () {
-            if (this._autoLaunch) {
-                this._autoLaunch = false;
-                this.video.play();
-            }
-            var now = BABYLON.Tools.Now;
-            if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
-                return false;
-            }
-            this._lastUpdate = now;
-            this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
-            return true;
-        };
-        return VideoTexture;
-    })(BABYLON.Texture);
-    BABYLON.VideoTexture = VideoTexture;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var VideoTexture = (function (_super) {
+        __extends(VideoTexture, _super);
+        function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
+            var _this = this;
+            if (generateMipMaps === void 0) { generateMipMaps = false; }
+            if (invertY === void 0) { invertY = false; }
+            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
+            _super.call(this, null, scene, !generateMipMaps, invertY);
+            this._autoLaunch = true;
+            this.name = name;
+            this.video = document.createElement("video");
+            this.video.autoplay = false;
+            this.video.loop = true;
+            this.video.addEventListener("canplaythrough", function () {
+                if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
+                    _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
+                    _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
+                }
+                else {
+                    _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+                    _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+                    generateMipMaps = false;
+                }
+                _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
+                _this._texture.isReady = true;
+            });
+            urls.forEach(function (url) {
+                //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
+                var source = document.createElement("source");
+                source.src = url;
+                _this.video.appendChild(source);
+            });
+            this._lastUpdate = BABYLON.Tools.Now;
+        }
+        VideoTexture.prototype.update = function () {
+            if (this._autoLaunch) {
+                this._autoLaunch = false;
+                this.video.play();
+            }
+            var now = BABYLON.Tools.Now;
+            if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
+                return false;
+            }
+            this._lastUpdate = now;
+            this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
+            return true;
+        };
+        return VideoTexture;
+    })(BABYLON.Texture);
+    BABYLON.VideoTexture = VideoTexture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.videoTexture.js.map

+ 398 - 397
src/Materials/babylon.effect.js

@@ -1,397 +1,398 @@
-var BABYLON;
-(function (BABYLON) {
-    var EffectFallbacks = (function () {
-        function EffectFallbacks() {
-            this._defines = {};
-            this._currentRank = 32;
-            this._maxRank = -1;
-        }
-        EffectFallbacks.prototype.addFallback = function (rank, define) {
-            if (!this._defines[rank]) {
-                if (rank < this._currentRank) {
-                    this._currentRank = rank;
-                }
-                if (rank > this._maxRank) {
-                    this._maxRank = rank;
-                }
-                this._defines[rank] = new Array();
-            }
-            this._defines[rank].push(define);
-        };
-        EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
-            this._meshRank = rank;
-            this._mesh = mesh;
-            if (rank > this._maxRank) {
-                this._maxRank = rank;
-            }
-        };
-        Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
-            get: function () {
-                return this._currentRank <= this._maxRank;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        EffectFallbacks.prototype.reduce = function (currentDefines) {
-            var currentFallbacks = this._defines[this._currentRank];
-            for (var index = 0; index < currentFallbacks.length; index++) {
-                currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
-            }
-            if (this._mesh && this._currentRank === this._meshRank) {
-                this._mesh.computeBonesUsingShaders = false;
-                currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
-                BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
-            }
-            this._currentRank++;
-            return currentDefines;
-        };
-        return EffectFallbacks;
-    })();
-    BABYLON.EffectFallbacks = EffectFallbacks;
-    var Effect = (function () {
-        function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
-            var _this = this;
-            this._isReady = false;
-            this._compilationError = "";
-            this._valueCache = [];
-            this._engine = engine;
-            this.name = baseName;
-            this.defines = defines;
-            this._uniformsNames = uniformsNames.concat(samplers);
-            this._samplers = samplers;
-            this._attributesNames = attributesNames;
-            this.onError = onError;
-            this.onCompiled = onCompiled;
-            var vertexSource;
-            var fragmentSource;
-            if (baseName.vertexElement) {
-                vertexSource = document.getElementById(baseName.vertexElement);
-                if (!vertexSource) {
-                    vertexSource = baseName.vertexElement;
-                }
-            }
-            else {
-                vertexSource = baseName.vertex || baseName;
-            }
-            if (baseName.fragmentElement) {
-                fragmentSource = document.getElementById(baseName.fragmentElement);
-                if (!fragmentSource) {
-                    fragmentSource = baseName.fragmentElement;
-                }
-            }
-            else {
-                fragmentSource = baseName.fragment || baseName;
-            }
-            this._loadVertexShader(vertexSource, function (vertexCode) {
-                _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
-                    _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
-                });
-            });
-        }
-        // Properties
-        Effect.prototype.isReady = function () {
-            return this._isReady;
-        };
-        Effect.prototype.getProgram = function () {
-            return this._program;
-        };
-        Effect.prototype.getAttributesNames = function () {
-            return this._attributesNames;
-        };
-        Effect.prototype.getAttributeLocation = function (index) {
-            return this._attributes[index];
-        };
-        Effect.prototype.getAttributeLocationByName = function (name) {
-            var index = this._attributesNames.indexOf(name);
-            return this._attributes[index];
-        };
-        Effect.prototype.getAttributesCount = function () {
-            return this._attributes.length;
-        };
-        Effect.prototype.getUniformIndex = function (uniformName) {
-            return this._uniformsNames.indexOf(uniformName);
-        };
-        Effect.prototype.getUniform = function (uniformName) {
-            return this._uniforms[this._uniformsNames.indexOf(uniformName)];
-        };
-        Effect.prototype.getSamplers = function () {
-            return this._samplers;
-        };
-        Effect.prototype.getCompilationError = function () {
-            return this._compilationError;
-        };
-        // Methods
-        Effect.prototype._loadVertexShader = function (vertex, callback) {
-            // DOM element ?
-            if (vertex instanceof HTMLElement) {
-                var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
-                callback(vertexCode);
-                return;
-            }
-            // Is in local store ?
-            if (Effect.ShadersStore[vertex + "VertexShader"]) {
-                callback(Effect.ShadersStore[vertex + "VertexShader"]);
-                return;
-            }
-            var vertexShaderUrl;
-            if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
-                vertexShaderUrl = vertex;
-            }
-            else {
-                vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
-            }
-            // Vertex shader
-            BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
-        };
-        Effect.prototype._loadFragmentShader = function (fragment, callback) {
-            // DOM element ?
-            if (fragment instanceof HTMLElement) {
-                var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
-                callback(fragmentCode);
-                return;
-            }
-            // Is in local store ?
-            if (Effect.ShadersStore[fragment + "PixelShader"]) {
-                callback(Effect.ShadersStore[fragment + "PixelShader"]);
-                return;
-            }
-            if (Effect.ShadersStore[fragment + "FragmentShader"]) {
-                callback(Effect.ShadersStore[fragment + "FragmentShader"]);
-                return;
-            }
-            var fragmentShaderUrl;
-            if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
-                fragmentShaderUrl = fragment;
-            }
-            else {
-                fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
-            }
-            // Fragment shader
-            BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
-        };
-        Effect.prototype._dumpShadersName = function () {
-            if (this.name.vertexElement) {
-                BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
-                BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
-            }
-            else if (this.name.vertex) {
-                BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
-                BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
-            }
-            else {
-                BABYLON.Tools.Error("Vertex shader:" + this.name);
-                BABYLON.Tools.Error("Fragment shader:" + this.name);
-            }
-        };
-        Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
-            try {
-                var engine = this._engine;
-                if (!engine.getCaps().highPrecisionShaderSupported) {
-                    vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
-                    fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
-                }
-                this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
-                this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
-                this._attributes = engine.getAttributes(this._program, attributesNames);
-                for (var index = 0; index < this._samplers.length; index++) {
-                    var sampler = this.getUniform(this._samplers[index]);
-                    if (sampler == null) {
-                        this._samplers.splice(index, 1);
-                        index--;
-                    }
-                }
-                engine.bindSamplers(this);
-                this._isReady = true;
-                if (this.onCompiled) {
-                    this.onCompiled(this);
-                }
-            }
-            catch (e) {
-                // Is it a problem with precision?
-                if (e.message.indexOf("highp") !== -1) {
-                    vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
-                    fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
-                    this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
-                    return;
-                }
-                // Let's go through fallbacks then
-                if (fallbacks && fallbacks.isMoreFallbacks) {
-                    BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
-                    this._dumpShadersName();
-                    defines = fallbacks.reduce(defines);
-                    this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
-                }
-                else {
-                    BABYLON.Tools.Error("Unable to compile effect: ");
-                    this._dumpShadersName();
-                    BABYLON.Tools.Error("Defines: " + defines);
-                    BABYLON.Tools.Error("Error: " + e.message);
-                    this._compilationError = e.message;
-                    if (this.onError) {
-                        this.onError(this, this._compilationError);
-                    }
-                }
-            }
-        };
-        Object.defineProperty(Effect.prototype, "isSupported", {
-            get: function () {
-                return this._compilationError === "";
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Effect.prototype._bindTexture = function (channel, texture) {
-            this._engine._bindTexture(this._samplers.indexOf(channel), texture);
-        };
-        Effect.prototype.setTexture = function (channel, texture) {
-            this._engine.setTexture(this._samplers.indexOf(channel), texture);
-        };
-        Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
-            this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
-        };
-        Effect.prototype._cacheMatrix = function (uniformName, matrix) {
-            if (!this._valueCache[uniformName]) {
-                this._valueCache[uniformName] = new BABYLON.Matrix();
-            }
-            for (var index = 0; index < 16; index++) {
-                this._valueCache[uniformName].m[index] = matrix.m[index];
-            }
-        };
-        Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
-            if (!this._valueCache[uniformName]) {
-                this._valueCache[uniformName] = [x, y];
-                return;
-            }
-            this._valueCache[uniformName][0] = x;
-            this._valueCache[uniformName][1] = y;
-        };
-        Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
-            if (!this._valueCache[uniformName]) {
-                this._valueCache[uniformName] = [x, y, z];
-                return;
-            }
-            this._valueCache[uniformName][0] = x;
-            this._valueCache[uniformName][1] = y;
-            this._valueCache[uniformName][2] = z;
-        };
-        Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
-            if (!this._valueCache[uniformName]) {
-                this._valueCache[uniformName] = [x, y, z, w];
-                return;
-            }
-            this._valueCache[uniformName][0] = x;
-            this._valueCache[uniformName][1] = y;
-            this._valueCache[uniformName][2] = z;
-            this._valueCache[uniformName][3] = w;
-        };
-        Effect.prototype.setArray = function (uniformName, array) {
-            this._engine.setArray(this.getUniform(uniformName), array);
-            return this;
-        };
-        Effect.prototype.setArray2 = function (uniformName, array) {
-            this._engine.setArray2(this.getUniform(uniformName), array);
-            return this;
-        };
-        Effect.prototype.setArray3 = function (uniformName, array) {
-            this._engine.setArray3(this.getUniform(uniformName), array);
-            return this;
-        };
-        Effect.prototype.setArray4 = function (uniformName, array) {
-            this._engine.setArray4(this.getUniform(uniformName), array);
-            return this;
-        };
-        Effect.prototype.setMatrices = function (uniformName, matrices) {
-            this._engine.setMatrices(this.getUniform(uniformName), matrices);
-            return this;
-        };
-        Effect.prototype.setMatrix = function (uniformName, matrix) {
-            //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
-            //    return this;
-            // this._cacheMatrix(uniformName, matrix);
-            this._engine.setMatrix(this.getUniform(uniformName), matrix);
-            return this;
-        };
-        Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
-            this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
-            return this;
-        };
-        Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
-            this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
-            return this;
-        };
-        Effect.prototype.setFloat = function (uniformName, value) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
-                return this;
-            this._valueCache[uniformName] = value;
-            this._engine.setFloat(this.getUniform(uniformName), value);
-            return this;
-        };
-        Effect.prototype.setBool = function (uniformName, bool) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
-                return this;
-            this._valueCache[uniformName] = bool;
-            this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
-            return this;
-        };
-        Effect.prototype.setVector2 = function (uniformName, vector2) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
-                return this;
-            this._cacheFloat2(uniformName, vector2.x, vector2.y);
-            this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
-            return this;
-        };
-        Effect.prototype.setFloat2 = function (uniformName, x, y) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
-                return this;
-            this._cacheFloat2(uniformName, x, y);
-            this._engine.setFloat2(this.getUniform(uniformName), x, y);
-            return this;
-        };
-        Effect.prototype.setVector3 = function (uniformName, vector3) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
-                return this;
-            this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
-            this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
-            return this;
-        };
-        Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
-                return this;
-            this._cacheFloat3(uniformName, x, y, z);
-            this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
-            return this;
-        };
-        Effect.prototype.setVector4 = function (uniformName, vector4) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
-                return this;
-            this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
-            this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
-            return this;
-        };
-        Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
-                return this;
-            this._cacheFloat4(uniformName, x, y, z, w);
-            this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
-            return this;
-        };
-        Effect.prototype.setColor3 = function (uniformName, color3) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
-                return this;
-            this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
-            this._engine.setColor3(this.getUniform(uniformName), color3);
-            return this;
-        };
-        Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
-            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
-                return this;
-            this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
-            this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
-            return this;
-        };
-        // Statics
-        Effect.ShadersStore = {};
-        return Effect;
-    })();
-    BABYLON.Effect = Effect;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var EffectFallbacks = (function () {
+        function EffectFallbacks() {
+            this._defines = {};
+            this._currentRank = 32;
+            this._maxRank = -1;
+        }
+        EffectFallbacks.prototype.addFallback = function (rank, define) {
+            if (!this._defines[rank]) {
+                if (rank < this._currentRank) {
+                    this._currentRank = rank;
+                }
+                if (rank > this._maxRank) {
+                    this._maxRank = rank;
+                }
+                this._defines[rank] = new Array();
+            }
+            this._defines[rank].push(define);
+        };
+        EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
+            this._meshRank = rank;
+            this._mesh = mesh;
+            if (rank > this._maxRank) {
+                this._maxRank = rank;
+            }
+        };
+        Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
+            get: function () {
+                return this._currentRank <= this._maxRank;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        EffectFallbacks.prototype.reduce = function (currentDefines) {
+            var currentFallbacks = this._defines[this._currentRank];
+            for (var index = 0; index < currentFallbacks.length; index++) {
+                currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
+            }
+            if (this._mesh && this._currentRank === this._meshRank) {
+                this._mesh.computeBonesUsingShaders = false;
+                currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
+                BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
+            }
+            this._currentRank++;
+            return currentDefines;
+        };
+        return EffectFallbacks;
+    })();
+    BABYLON.EffectFallbacks = EffectFallbacks;
+    var Effect = (function () {
+        function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
+            var _this = this;
+            this._isReady = false;
+            this._compilationError = "";
+            this._valueCache = [];
+            this._engine = engine;
+            this.name = baseName;
+            this.defines = defines;
+            this._uniformsNames = uniformsNames.concat(samplers);
+            this._samplers = samplers;
+            this._attributesNames = attributesNames;
+            this.onError = onError;
+            this.onCompiled = onCompiled;
+            var vertexSource;
+            var fragmentSource;
+            if (baseName.vertexElement) {
+                vertexSource = document.getElementById(baseName.vertexElement);
+                if (!vertexSource) {
+                    vertexSource = baseName.vertexElement;
+                }
+            }
+            else {
+                vertexSource = baseName.vertex || baseName;
+            }
+            if (baseName.fragmentElement) {
+                fragmentSource = document.getElementById(baseName.fragmentElement);
+                if (!fragmentSource) {
+                    fragmentSource = baseName.fragmentElement;
+                }
+            }
+            else {
+                fragmentSource = baseName.fragment || baseName;
+            }
+            this._loadVertexShader(vertexSource, function (vertexCode) {
+                _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
+                    _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
+                });
+            });
+        }
+        // Properties
+        Effect.prototype.isReady = function () {
+            return this._isReady;
+        };
+        Effect.prototype.getProgram = function () {
+            return this._program;
+        };
+        Effect.prototype.getAttributesNames = function () {
+            return this._attributesNames;
+        };
+        Effect.prototype.getAttributeLocation = function (index) {
+            return this._attributes[index];
+        };
+        Effect.prototype.getAttributeLocationByName = function (name) {
+            var index = this._attributesNames.indexOf(name);
+            return this._attributes[index];
+        };
+        Effect.prototype.getAttributesCount = function () {
+            return this._attributes.length;
+        };
+        Effect.prototype.getUniformIndex = function (uniformName) {
+            return this._uniformsNames.indexOf(uniformName);
+        };
+        Effect.prototype.getUniform = function (uniformName) {
+            return this._uniforms[this._uniformsNames.indexOf(uniformName)];
+        };
+        Effect.prototype.getSamplers = function () {
+            return this._samplers;
+        };
+        Effect.prototype.getCompilationError = function () {
+            return this._compilationError;
+        };
+        // Methods
+        Effect.prototype._loadVertexShader = function (vertex, callback) {
+            // DOM element ?
+            if (vertex instanceof HTMLElement) {
+                var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
+                callback(vertexCode);
+                return;
+            }
+            // Is in local store ?
+            if (Effect.ShadersStore[vertex + "VertexShader"]) {
+                callback(Effect.ShadersStore[vertex + "VertexShader"]);
+                return;
+            }
+            var vertexShaderUrl;
+            if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
+                vertexShaderUrl = vertex;
+            }
+            else {
+                vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
+            }
+            // Vertex shader
+            BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
+        };
+        Effect.prototype._loadFragmentShader = function (fragment, callback) {
+            // DOM element ?
+            if (fragment instanceof HTMLElement) {
+                var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
+                callback(fragmentCode);
+                return;
+            }
+            // Is in local store ?
+            if (Effect.ShadersStore[fragment + "PixelShader"]) {
+                callback(Effect.ShadersStore[fragment + "PixelShader"]);
+                return;
+            }
+            if (Effect.ShadersStore[fragment + "FragmentShader"]) {
+                callback(Effect.ShadersStore[fragment + "FragmentShader"]);
+                return;
+            }
+            var fragmentShaderUrl;
+            if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
+                fragmentShaderUrl = fragment;
+            }
+            else {
+                fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
+            }
+            // Fragment shader
+            BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
+        };
+        Effect.prototype._dumpShadersName = function () {
+            if (this.name.vertexElement) {
+                BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
+                BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
+            }
+            else if (this.name.vertex) {
+                BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
+                BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
+            }
+            else {
+                BABYLON.Tools.Error("Vertex shader:" + this.name);
+                BABYLON.Tools.Error("Fragment shader:" + this.name);
+            }
+        };
+        Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
+            try {
+                var engine = this._engine;
+                if (!engine.getCaps().highPrecisionShaderSupported) {
+                    vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
+                    fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
+                }
+                this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
+                this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
+                this._attributes = engine.getAttributes(this._program, attributesNames);
+                for (var index = 0; index < this._samplers.length; index++) {
+                    var sampler = this.getUniform(this._samplers[index]);
+                    if (sampler == null) {
+                        this._samplers.splice(index, 1);
+                        index--;
+                    }
+                }
+                engine.bindSamplers(this);
+                this._isReady = true;
+                if (this.onCompiled) {
+                    this.onCompiled(this);
+                }
+            }
+            catch (e) {
+                // Is it a problem with precision?
+                if (e.message.indexOf("highp") !== -1) {
+                    vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
+                    fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
+                    this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
+                    return;
+                }
+                // Let's go through fallbacks then
+                if (fallbacks && fallbacks.isMoreFallbacks) {
+                    BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
+                    this._dumpShadersName();
+                    defines = fallbacks.reduce(defines);
+                    this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
+                }
+                else {
+                    BABYLON.Tools.Error("Unable to compile effect: ");
+                    this._dumpShadersName();
+                    BABYLON.Tools.Error("Defines: " + defines);
+                    BABYLON.Tools.Error("Error: " + e.message);
+                    this._compilationError = e.message;
+                    if (this.onError) {
+                        this.onError(this, this._compilationError);
+                    }
+                }
+            }
+        };
+        Object.defineProperty(Effect.prototype, "isSupported", {
+            get: function () {
+                return this._compilationError === "";
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Effect.prototype._bindTexture = function (channel, texture) {
+            this._engine._bindTexture(this._samplers.indexOf(channel), texture);
+        };
+        Effect.prototype.setTexture = function (channel, texture) {
+            this._engine.setTexture(this._samplers.indexOf(channel), texture);
+        };
+        Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
+            this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
+        };
+        Effect.prototype._cacheMatrix = function (uniformName, matrix) {
+            if (!this._valueCache[uniformName]) {
+                this._valueCache[uniformName] = new BABYLON.Matrix();
+            }
+            for (var index = 0; index < 16; index++) {
+                this._valueCache[uniformName].m[index] = matrix.m[index];
+            }
+        };
+        Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
+            if (!this._valueCache[uniformName]) {
+                this._valueCache[uniformName] = [x, y];
+                return;
+            }
+            this._valueCache[uniformName][0] = x;
+            this._valueCache[uniformName][1] = y;
+        };
+        Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
+            if (!this._valueCache[uniformName]) {
+                this._valueCache[uniformName] = [x, y, z];
+                return;
+            }
+            this._valueCache[uniformName][0] = x;
+            this._valueCache[uniformName][1] = y;
+            this._valueCache[uniformName][2] = z;
+        };
+        Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
+            if (!this._valueCache[uniformName]) {
+                this._valueCache[uniformName] = [x, y, z, w];
+                return;
+            }
+            this._valueCache[uniformName][0] = x;
+            this._valueCache[uniformName][1] = y;
+            this._valueCache[uniformName][2] = z;
+            this._valueCache[uniformName][3] = w;
+        };
+        Effect.prototype.setArray = function (uniformName, array) {
+            this._engine.setArray(this.getUniform(uniformName), array);
+            return this;
+        };
+        Effect.prototype.setArray2 = function (uniformName, array) {
+            this._engine.setArray2(this.getUniform(uniformName), array);
+            return this;
+        };
+        Effect.prototype.setArray3 = function (uniformName, array) {
+            this._engine.setArray3(this.getUniform(uniformName), array);
+            return this;
+        };
+        Effect.prototype.setArray4 = function (uniformName, array) {
+            this._engine.setArray4(this.getUniform(uniformName), array);
+            return this;
+        };
+        Effect.prototype.setMatrices = function (uniformName, matrices) {
+            this._engine.setMatrices(this.getUniform(uniformName), matrices);
+            return this;
+        };
+        Effect.prototype.setMatrix = function (uniformName, matrix) {
+            //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
+            //    return this;
+            // this._cacheMatrix(uniformName, matrix);
+            this._engine.setMatrix(this.getUniform(uniformName), matrix);
+            return this;
+        };
+        Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
+            this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
+            return this;
+        };
+        Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
+            this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
+            return this;
+        };
+        Effect.prototype.setFloat = function (uniformName, value) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
+                return this;
+            this._valueCache[uniformName] = value;
+            this._engine.setFloat(this.getUniform(uniformName), value);
+            return this;
+        };
+        Effect.prototype.setBool = function (uniformName, bool) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
+                return this;
+            this._valueCache[uniformName] = bool;
+            this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
+            return this;
+        };
+        Effect.prototype.setVector2 = function (uniformName, vector2) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
+                return this;
+            this._cacheFloat2(uniformName, vector2.x, vector2.y);
+            this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
+            return this;
+        };
+        Effect.prototype.setFloat2 = function (uniformName, x, y) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
+                return this;
+            this._cacheFloat2(uniformName, x, y);
+            this._engine.setFloat2(this.getUniform(uniformName), x, y);
+            return this;
+        };
+        Effect.prototype.setVector3 = function (uniformName, vector3) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
+                return this;
+            this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
+            this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
+            return this;
+        };
+        Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
+                return this;
+            this._cacheFloat3(uniformName, x, y, z);
+            this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
+            return this;
+        };
+        Effect.prototype.setVector4 = function (uniformName, vector4) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
+                return this;
+            this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
+            this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
+            return this;
+        };
+        Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
+                return this;
+            this._cacheFloat4(uniformName, x, y, z, w);
+            this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
+            return this;
+        };
+        Effect.prototype.setColor3 = function (uniformName, color3) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
+                return this;
+            this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
+            this._engine.setColor3(this.getUniform(uniformName), color3);
+            return this;
+        };
+        Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
+                return this;
+            this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
+            this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
+            return this;
+        };
+        // Statics
+        Effect.ShadersStore = {};
+        return Effect;
+    })();
+    BABYLON.Effect = Effect;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.effect.js.map

+ 291 - 290
src/Materials/babylon.material.js

@@ -1,290 +1,291 @@
-var BABYLON;
-(function (BABYLON) {
-    var MaterialDefines = (function () {
-        function MaterialDefines() {
-        }
-        MaterialDefines.prototype.isEqual = function (other) {
-            for (var index = 0; index < this._keys.length; index++) {
-                var prop = this._keys[index];
-                if (this[prop] !== other[prop]) {
-                    return false;
-                }
-            }
-            return true;
-        };
-        MaterialDefines.prototype.cloneTo = function (other) {
-            for (var index = 0; index < this._keys.length; index++) {
-                var prop = this._keys[index];
-                other[prop] = this[prop];
-            }
-        };
-        MaterialDefines.prototype.reset = function () {
-            for (var index = 0; index < this._keys.length; index++) {
-                var prop = this._keys[index];
-                if (typeof (this[prop]) === "number") {
-                    this[prop] = 0;
-                }
-                else {
-                    this[prop] = false;
-                }
-            }
-        };
-        MaterialDefines.prototype.toString = function () {
-            var result = "";
-            for (var index = 0; index < this._keys.length; index++) {
-                var prop = this._keys[index];
-                if (typeof (this[prop]) === "number") {
-                    result += "#define " + prop + " " + this[prop] + "\n";
-                }
-                else if (this[prop]) {
-                    result += "#define " + prop + "\n";
-                }
-            }
-            return result;
-        };
-        return MaterialDefines;
-    })();
-    BABYLON.MaterialDefines = MaterialDefines;
-    var Material = (function () {
-        function Material(name, scene, doNotAdd) {
-            this.name = name;
-            this.checkReadyOnEveryCall = false;
-            this.checkReadyOnlyOnce = false;
-            this.state = "";
-            this.alpha = 1.0;
-            this.backFaceCulling = true;
-            this.sideOrientation = Material.CounterClockWiseSideOrientation;
-            this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
-            this.disableDepthWrite = false;
-            this.fogEnabled = true;
-            this._wasPreviouslyReady = false;
-            this._fillMode = Material.TriangleFillMode;
-            this.pointSize = 1.0;
-            this.zOffset = 0;
-            this.id = name;
-            this._scene = scene;
-            if (!doNotAdd) {
-                scene.materials.push(this);
-            }
-        }
-        Object.defineProperty(Material, "TriangleFillMode", {
-            get: function () {
-                return Material._TriangleFillMode;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material, "WireFrameFillMode", {
-            get: function () {
-                return Material._WireFrameFillMode;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material, "PointFillMode", {
-            get: function () {
-                return Material._PointFillMode;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material, "ClockWiseSideOrientation", {
-            get: function () {
-                return Material._ClockWiseSideOrientation;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
-            get: function () {
-                return Material._CounterClockWiseSideOrientation;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material.prototype, "wireframe", {
-            get: function () {
-                return this._fillMode === Material.WireFrameFillMode;
-            },
-            set: function (value) {
-                this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material.prototype, "pointsCloud", {
-            get: function () {
-                return this._fillMode === Material.PointFillMode;
-            },
-            set: function (value) {
-                this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material.prototype, "fillMode", {
-            get: function () {
-                return this._fillMode;
-            },
-            set: function (value) {
-                this._fillMode = value;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(Material.prototype, "isFrozen", {
-            get: function () {
-                return this.checkReadyOnlyOnce;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Material.prototype.freeze = function () {
-            this.checkReadyOnlyOnce = true;
-        };
-        Material.prototype.unfreeze = function () {
-            this.checkReadyOnlyOnce = false;
-        };
-        Material.prototype.isReady = function (mesh, useInstances) {
-            return true;
-        };
-        Material.prototype.getEffect = function () {
-            return this._effect;
-        };
-        Material.prototype.getScene = function () {
-            return this._scene;
-        };
-        Material.prototype.needAlphaBlending = function () {
-            return (this.alpha < 1.0);
-        };
-        Material.prototype.needAlphaTesting = function () {
-            return false;
-        };
-        Material.prototype.getAlphaTestTexture = function () {
-            return null;
-        };
-        Material.prototype.trackCreation = function (onCompiled, onError) {
-        };
-        Material.prototype.markDirty = function () {
-            this._wasPreviouslyReady = false;
-        };
-        Material.prototype._preBind = function () {
-            var engine = this._scene.getEngine();
-            engine.enableEffect(this._effect);
-            engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
-        };
-        Material.prototype.bind = function (world, mesh) {
-            this._scene._cachedMaterial = this;
-            if (this.onBind) {
-                this.onBind(this, mesh);
-            }
-            if (this.disableDepthWrite) {
-                var engine = this._scene.getEngine();
-                this._cachedDepthWriteState = engine.getDepthWrite();
-                engine.setDepthWrite(false);
-            }
-        };
-        Material.prototype.bindOnlyWorldMatrix = function (world) {
-        };
-        Material.prototype.unbind = function () {
-            if (this.disableDepthWrite) {
-                var engine = this._scene.getEngine();
-                engine.setDepthWrite(this._cachedDepthWriteState);
-            }
-        };
-        Material.prototype.clone = function (name) {
-            return null;
-        };
-        Material.prototype.getBindedMeshes = function () {
-            var result = new Array();
-            for (var index = 0; index < this._scene.meshes.length; index++) {
-                var mesh = this._scene.meshes[index];
-                if (mesh.material === this) {
-                    result.push(mesh);
-                }
-            }
-            return result;
-        };
-        Material.prototype.dispose = function (forceDisposeEffect) {
-            // Animations
-            this.getScene().stopAnimation(this);
-            // Remove from scene
-            var index = this._scene.materials.indexOf(this);
-            if (index >= 0) {
-                this._scene.materials.splice(index, 1);
-            }
-            // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
-            if (forceDisposeEffect && this._effect) {
-                this._scene.getEngine()._releaseEffect(this._effect);
-                this._effect = null;
-            }
-            // Remove from meshes
-            for (index = 0; index < this._scene.meshes.length; index++) {
-                var mesh = this._scene.meshes[index];
-                if (mesh.material === this) {
-                    mesh.material = null;
-                }
-            }
-            // Callback
-            if (this.onDispose) {
-                this.onDispose();
-            }
-        };
-        Material.prototype.copyTo = function (other) {
-            other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
-            other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
-            other.alpha = this.alpha;
-            other.fillMode = this.fillMode;
-            other.backFaceCulling = this.backFaceCulling;
-            other.fogEnabled = this.fogEnabled;
-            other.wireframe = this.wireframe;
-            other.zOffset = this.zOffset;
-            other.alphaMode = this.alphaMode;
-            other.sideOrientation = this.sideOrientation;
-            other.disableDepthWrite = this.disableDepthWrite;
-            other.pointSize = this.pointSize;
-            other.pointsCloud = this.pointsCloud;
-        };
-        Material.prototype.serialize = function () {
-            var serializationObject = {};
-            serializationObject.name = this.name;
-            serializationObject.alpha = this.alpha;
-            serializationObject.id = this.id;
-            serializationObject.tags = BABYLON.Tags.GetTags(this);
-            serializationObject.backFaceCulling = this.backFaceCulling;
-            serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
-            serializationObject.disableDepthWrite = this.disableDepthWrite;
-            return serializationObject;
-        };
-        Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
-            var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
-            multiMaterial.id = parsedMultiMaterial.id;
-            BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
-            for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
-                var subMatId = parsedMultiMaterial.materials[matIndex];
-                if (subMatId) {
-                    multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
-                }
-                else {
-                    multiMaterial.subMaterials.push(null);
-                }
-            }
-            return multiMaterial;
-        };
-        Material.Parse = function (parsedMaterial, scene, rootUrl) {
-            if (!parsedMaterial.customType) {
-                return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
-            }
-            var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
-            return materialType.Parse(parsedMaterial, scene, rootUrl);
-            ;
-        };
-        Material._TriangleFillMode = 0;
-        Material._WireFrameFillMode = 1;
-        Material._PointFillMode = 2;
-        Material._ClockWiseSideOrientation = 0;
-        Material._CounterClockWiseSideOrientation = 1;
-        return Material;
-    })();
-    BABYLON.Material = Material;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var MaterialDefines = (function () {
+        function MaterialDefines() {
+        }
+        MaterialDefines.prototype.isEqual = function (other) {
+            for (var index = 0; index < this._keys.length; index++) {
+                var prop = this._keys[index];
+                if (this[prop] !== other[prop]) {
+                    return false;
+                }
+            }
+            return true;
+        };
+        MaterialDefines.prototype.cloneTo = function (other) {
+            for (var index = 0; index < this._keys.length; index++) {
+                var prop = this._keys[index];
+                other[prop] = this[prop];
+            }
+        };
+        MaterialDefines.prototype.reset = function () {
+            for (var index = 0; index < this._keys.length; index++) {
+                var prop = this._keys[index];
+                if (typeof (this[prop]) === "number") {
+                    this[prop] = 0;
+                }
+                else {
+                    this[prop] = false;
+                }
+            }
+        };
+        MaterialDefines.prototype.toString = function () {
+            var result = "";
+            for (var index = 0; index < this._keys.length; index++) {
+                var prop = this._keys[index];
+                if (typeof (this[prop]) === "number") {
+                    result += "#define " + prop + " " + this[prop] + "\n";
+                }
+                else if (this[prop]) {
+                    result += "#define " + prop + "\n";
+                }
+            }
+            return result;
+        };
+        return MaterialDefines;
+    })();
+    BABYLON.MaterialDefines = MaterialDefines;
+    var Material = (function () {
+        function Material(name, scene, doNotAdd) {
+            this.name = name;
+            this.checkReadyOnEveryCall = false;
+            this.checkReadyOnlyOnce = false;
+            this.state = "";
+            this.alpha = 1.0;
+            this.backFaceCulling = true;
+            this.sideOrientation = Material.CounterClockWiseSideOrientation;
+            this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
+            this.disableDepthWrite = false;
+            this.fogEnabled = true;
+            this._wasPreviouslyReady = false;
+            this._fillMode = Material.TriangleFillMode;
+            this.pointSize = 1.0;
+            this.zOffset = 0;
+            this.id = name;
+            this._scene = scene;
+            if (!doNotAdd) {
+                scene.materials.push(this);
+            }
+        }
+        Object.defineProperty(Material, "TriangleFillMode", {
+            get: function () {
+                return Material._TriangleFillMode;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material, "WireFrameFillMode", {
+            get: function () {
+                return Material._WireFrameFillMode;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material, "PointFillMode", {
+            get: function () {
+                return Material._PointFillMode;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material, "ClockWiseSideOrientation", {
+            get: function () {
+                return Material._ClockWiseSideOrientation;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
+            get: function () {
+                return Material._CounterClockWiseSideOrientation;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material.prototype, "wireframe", {
+            get: function () {
+                return this._fillMode === Material.WireFrameFillMode;
+            },
+            set: function (value) {
+                this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material.prototype, "pointsCloud", {
+            get: function () {
+                return this._fillMode === Material.PointFillMode;
+            },
+            set: function (value) {
+                this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material.prototype, "fillMode", {
+            get: function () {
+                return this._fillMode;
+            },
+            set: function (value) {
+                this._fillMode = value;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(Material.prototype, "isFrozen", {
+            get: function () {
+                return this.checkReadyOnlyOnce;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Material.prototype.freeze = function () {
+            this.checkReadyOnlyOnce = true;
+        };
+        Material.prototype.unfreeze = function () {
+            this.checkReadyOnlyOnce = false;
+        };
+        Material.prototype.isReady = function (mesh, useInstances) {
+            return true;
+        };
+        Material.prototype.getEffect = function () {
+            return this._effect;
+        };
+        Material.prototype.getScene = function () {
+            return this._scene;
+        };
+        Material.prototype.needAlphaBlending = function () {
+            return (this.alpha < 1.0);
+        };
+        Material.prototype.needAlphaTesting = function () {
+            return false;
+        };
+        Material.prototype.getAlphaTestTexture = function () {
+            return null;
+        };
+        Material.prototype.trackCreation = function (onCompiled, onError) {
+        };
+        Material.prototype.markDirty = function () {
+            this._wasPreviouslyReady = false;
+        };
+        Material.prototype._preBind = function () {
+            var engine = this._scene.getEngine();
+            engine.enableEffect(this._effect);
+            engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
+        };
+        Material.prototype.bind = function (world, mesh) {
+            this._scene._cachedMaterial = this;
+            if (this.onBind) {
+                this.onBind(this, mesh);
+            }
+            if (this.disableDepthWrite) {
+                var engine = this._scene.getEngine();
+                this._cachedDepthWriteState = engine.getDepthWrite();
+                engine.setDepthWrite(false);
+            }
+        };
+        Material.prototype.bindOnlyWorldMatrix = function (world) {
+        };
+        Material.prototype.unbind = function () {
+            if (this.disableDepthWrite) {
+                var engine = this._scene.getEngine();
+                engine.setDepthWrite(this._cachedDepthWriteState);
+            }
+        };
+        Material.prototype.clone = function (name) {
+            return null;
+        };
+        Material.prototype.getBindedMeshes = function () {
+            var result = new Array();
+            for (var index = 0; index < this._scene.meshes.length; index++) {
+                var mesh = this._scene.meshes[index];
+                if (mesh.material === this) {
+                    result.push(mesh);
+                }
+            }
+            return result;
+        };
+        Material.prototype.dispose = function (forceDisposeEffect) {
+            // Animations
+            this.getScene().stopAnimation(this);
+            // Remove from scene
+            var index = this._scene.materials.indexOf(this);
+            if (index >= 0) {
+                this._scene.materials.splice(index, 1);
+            }
+            // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
+            if (forceDisposeEffect && this._effect) {
+                this._scene.getEngine()._releaseEffect(this._effect);
+                this._effect = null;
+            }
+            // Remove from meshes
+            for (index = 0; index < this._scene.meshes.length; index++) {
+                var mesh = this._scene.meshes[index];
+                if (mesh.material === this) {
+                    mesh.material = null;
+                }
+            }
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        };
+        Material.prototype.copyTo = function (other) {
+            other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
+            other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
+            other.alpha = this.alpha;
+            other.fillMode = this.fillMode;
+            other.backFaceCulling = this.backFaceCulling;
+            other.fogEnabled = this.fogEnabled;
+            other.wireframe = this.wireframe;
+            other.zOffset = this.zOffset;
+            other.alphaMode = this.alphaMode;
+            other.sideOrientation = this.sideOrientation;
+            other.disableDepthWrite = this.disableDepthWrite;
+            other.pointSize = this.pointSize;
+            other.pointsCloud = this.pointsCloud;
+        };
+        Material.prototype.serialize = function () {
+            var serializationObject = {};
+            serializationObject.name = this.name;
+            serializationObject.alpha = this.alpha;
+            serializationObject.id = this.id;
+            serializationObject.tags = BABYLON.Tags.GetTags(this);
+            serializationObject.backFaceCulling = this.backFaceCulling;
+            serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
+            serializationObject.disableDepthWrite = this.disableDepthWrite;
+            return serializationObject;
+        };
+        Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
+            var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
+            multiMaterial.id = parsedMultiMaterial.id;
+            BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
+            for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
+                var subMatId = parsedMultiMaterial.materials[matIndex];
+                if (subMatId) {
+                    multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
+                }
+                else {
+                    multiMaterial.subMaterials.push(null);
+                }
+            }
+            return multiMaterial;
+        };
+        Material.Parse = function (parsedMaterial, scene, rootUrl) {
+            if (!parsedMaterial.customType) {
+                return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
+            }
+            var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
+            return materialType.Parse(parsedMaterial, scene, rootUrl);
+            ;
+        };
+        Material._TriangleFillMode = 0;
+        Material._WireFrameFillMode = 1;
+        Material._PointFillMode = 2;
+        Material._ClockWiseSideOrientation = 0;
+        Material._CounterClockWiseSideOrientation = 1;
+        return Material;
+    })();
+    BABYLON.Material = Material;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.material.js.map

+ 69 - 68
src/Materials/babylon.multiMaterial.js

@@ -1,68 +1,69 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var MultiMaterial = (function (_super) {
-        __extends(MultiMaterial, _super);
-        function MultiMaterial(name, scene) {
-            _super.call(this, name, scene, true);
-            this.subMaterials = new Array();
-            scene.multiMaterials.push(this);
-        }
-        // Properties
-        MultiMaterial.prototype.getSubMaterial = function (index) {
-            if (index < 0 || index >= this.subMaterials.length) {
-                return this.getScene().defaultMaterial;
-            }
-            return this.subMaterials[index];
-        };
-        // Methods
-        MultiMaterial.prototype.isReady = function (mesh) {
-            for (var index = 0; index < this.subMaterials.length; index++) {
-                var subMaterial = this.subMaterials[index];
-                if (subMaterial) {
-                    if (!this.subMaterials[index].isReady(mesh)) {
-                        return false;
-                    }
-                }
-            }
-            return true;
-        };
-        MultiMaterial.prototype.clone = function (name, cloneChildren) {
-            var newMultiMaterial = new MultiMaterial(name, this.getScene());
-            for (var index = 0; index < this.subMaterials.length; index++) {
-                var subMaterial = null;
-                if (cloneChildren) {
-                    subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
-                }
-                else {
-                    subMaterial = this.subMaterials[index];
-                }
-                newMultiMaterial.subMaterials.push(subMaterial);
-            }
-            return newMultiMaterial;
-        };
-        MultiMaterial.prototype.serialize = function () {
-            var serializationObject = {};
-            serializationObject.name = this.name;
-            serializationObject.id = this.id;
-            serializationObject.tags = BABYLON.Tags.GetTags(this);
-            serializationObject.materials = [];
-            for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
-                var subMat = this.subMaterials[matIndex];
-                if (subMat) {
-                    serializationObject.materials.push(subMat.id);
-                }
-                else {
-                    serializationObject.materials.push(null);
-                }
-            }
-            return serializationObject;
-        };
-        return MultiMaterial;
-    })(BABYLON.Material);
-    BABYLON.MultiMaterial = MultiMaterial;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var MultiMaterial = (function (_super) {
+        __extends(MultiMaterial, _super);
+        function MultiMaterial(name, scene) {
+            _super.call(this, name, scene, true);
+            this.subMaterials = new Array();
+            scene.multiMaterials.push(this);
+        }
+        // Properties
+        MultiMaterial.prototype.getSubMaterial = function (index) {
+            if (index < 0 || index >= this.subMaterials.length) {
+                return this.getScene().defaultMaterial;
+            }
+            return this.subMaterials[index];
+        };
+        // Methods
+        MultiMaterial.prototype.isReady = function (mesh) {
+            for (var index = 0; index < this.subMaterials.length; index++) {
+                var subMaterial = this.subMaterials[index];
+                if (subMaterial) {
+                    if (!this.subMaterials[index].isReady(mesh)) {
+                        return false;
+                    }
+                }
+            }
+            return true;
+        };
+        MultiMaterial.prototype.clone = function (name, cloneChildren) {
+            var newMultiMaterial = new MultiMaterial(name, this.getScene());
+            for (var index = 0; index < this.subMaterials.length; index++) {
+                var subMaterial = null;
+                if (cloneChildren) {
+                    subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
+                }
+                else {
+                    subMaterial = this.subMaterials[index];
+                }
+                newMultiMaterial.subMaterials.push(subMaterial);
+            }
+            return newMultiMaterial;
+        };
+        MultiMaterial.prototype.serialize = function () {
+            var serializationObject = {};
+            serializationObject.name = this.name;
+            serializationObject.id = this.id;
+            serializationObject.tags = BABYLON.Tags.GetTags(this);
+            serializationObject.materials = [];
+            for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
+                var subMat = this.subMaterials[matIndex];
+                if (subMat) {
+                    serializationObject.materials.push(subMat.id);
+                }
+                else {
+                    serializationObject.materials.push(null);
+                }
+            }
+            return serializationObject;
+        };
+        return MultiMaterial;
+    })(BABYLON.Material);
+    BABYLON.MultiMaterial = MultiMaterial;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.multiMaterial.js.map

+ 343 - 342
src/Materials/babylon.shaderMaterial.js

@@ -1,342 +1,343 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var ShaderMaterial = (function (_super) {
-        __extends(ShaderMaterial, _super);
-        function ShaderMaterial(name, scene, shaderPath, options) {
-            _super.call(this, name, scene);
-            this._textures = {};
-            this._floats = {};
-            this._floatsArrays = {};
-            this._colors3 = {};
-            this._colors4 = {};
-            this._vectors2 = {};
-            this._vectors3 = {};
-            this._vectors4 = {};
-            this._matrices = {};
-            this._matrices3x3 = {};
-            this._matrices2x2 = {};
-            this._cachedWorldViewMatrix = new BABYLON.Matrix();
-            this._shaderPath = shaderPath;
-            options.needAlphaBlending = options.needAlphaBlending || false;
-            options.needAlphaTesting = options.needAlphaTesting || false;
-            options.attributes = options.attributes || ["position", "normal", "uv"];
-            options.uniforms = options.uniforms || ["worldViewProjection"];
-            options.samplers = options.samplers || [];
-            options.defines = options.defines || [];
-            this._options = options;
-        }
-        ShaderMaterial.prototype.needAlphaBlending = function () {
-            return this._options.needAlphaBlending;
-        };
-        ShaderMaterial.prototype.needAlphaTesting = function () {
-            return this._options.needAlphaTesting;
-        };
-        ShaderMaterial.prototype._checkUniform = function (uniformName) {
-            if (this._options.uniforms.indexOf(uniformName) === -1) {
-                this._options.uniforms.push(uniformName);
-            }
-        };
-        ShaderMaterial.prototype.setTexture = function (name, texture) {
-            if (this._options.samplers.indexOf(name) === -1) {
-                this._options.samplers.push(name);
-            }
-            this._textures[name] = texture;
-            return this;
-        };
-        ShaderMaterial.prototype.setFloat = function (name, value) {
-            this._checkUniform(name);
-            this._floats[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setFloats = function (name, value) {
-            this._checkUniform(name);
-            this._floatsArrays[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setColor3 = function (name, value) {
-            this._checkUniform(name);
-            this._colors3[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setColor4 = function (name, value) {
-            this._checkUniform(name);
-            this._colors4[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setVector2 = function (name, value) {
-            this._checkUniform(name);
-            this._vectors2[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setVector3 = function (name, value) {
-            this._checkUniform(name);
-            this._vectors3[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setVector4 = function (name, value) {
-            this._checkUniform(name);
-            this._vectors4[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setMatrix = function (name, value) {
-            this._checkUniform(name);
-            this._matrices[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
-            this._checkUniform(name);
-            this._matrices3x3[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
-            this._checkUniform(name);
-            this._matrices2x2[name] = value;
-            return this;
-        };
-        ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
-            var scene = this.getScene();
-            var engine = scene.getEngine();
-            if (!this.checkReadyOnEveryCall) {
-                if (this._renderId === scene.getRenderId()) {
-                    return true;
-                }
-            }
-            // Instances
-            var defines = [];
-            var fallbacks = new BABYLON.EffectFallbacks();
-            if (useInstances) {
-                defines.push("#define INSTANCES");
-            }
-            for (var index = 0; index < this._options.defines.length; index++) {
-                defines.push(this._options.defines[index]);
-            }
-            // Bones
-            if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
-                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
-                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
-                fallbacks.addCPUSkinningFallback(0, mesh);
-            }
-            // Alpha test
-            if (engine.getAlphaTesting()) {
-                defines.push("#define ALPHATEST");
-            }
-            var previousEffect = this._effect;
-            var join = defines.join("\n");
-            this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
-            if (!this._effect.isReady()) {
-                return false;
-            }
-            if (previousEffect !== this._effect) {
-                scene.resetCachedMaterial();
-            }
-            this._renderId = scene.getRenderId();
-            return true;
-        };
-        ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
-            var scene = this.getScene();
-            if (this._options.uniforms.indexOf("world") !== -1) {
-                this._effect.setMatrix("world", world);
-            }
-            if (this._options.uniforms.indexOf("worldView") !== -1) {
-                world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
-                this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
-            }
-            if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
-                this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
-            }
-        };
-        ShaderMaterial.prototype.bind = function (world, mesh) {
-            // Std values
-            this.bindOnlyWorldMatrix(world);
-            if (this.getScene().getCachedMaterial() !== this) {
-                if (this._options.uniforms.indexOf("view") !== -1) {
-                    this._effect.setMatrix("view", this.getScene().getViewMatrix());
-                }
-                if (this._options.uniforms.indexOf("projection") !== -1) {
-                    this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
-                }
-                if (this._options.uniforms.indexOf("viewProjection") !== -1) {
-                    this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
-                }
-                // Bones
-                if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
-                    this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
-                }
-                // Texture
-                for (var name in this._textures) {
-                    this._effect.setTexture(name, this._textures[name]);
-                }
-                // Float    
-                for (name in this._floats) {
-                    this._effect.setFloat(name, this._floats[name]);
-                }
-                // Float s   
-                for (name in this._floatsArrays) {
-                    this._effect.setArray(name, this._floatsArrays[name]);
-                }
-                // Color3        
-                for (name in this._colors3) {
-                    this._effect.setColor3(name, this._colors3[name]);
-                }
-                // Color4      
-                for (name in this._colors4) {
-                    var color = this._colors4[name];
-                    this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
-                }
-                // Vector2        
-                for (name in this._vectors2) {
-                    this._effect.setVector2(name, this._vectors2[name]);
-                }
-                // Vector3        
-                for (name in this._vectors3) {
-                    this._effect.setVector3(name, this._vectors3[name]);
-                }
-                // Vector4        
-                for (name in this._vectors4) {
-                    this._effect.setVector4(name, this._vectors4[name]);
-                }
-                // Matrix      
-                for (name in this._matrices) {
-                    this._effect.setMatrix(name, this._matrices[name]);
-                }
-                // Matrix 3x3
-                for (name in this._matrices3x3) {
-                    this._effect.setMatrix3x3(name, this._matrices3x3[name]);
-                }
-                // Matrix 2x2
-                for (name in this._matrices2x2) {
-                    this._effect.setMatrix2x2(name, this._matrices2x2[name]);
-                }
-            }
-            _super.prototype.bind.call(this, world, mesh);
-        };
-        ShaderMaterial.prototype.clone = function (name) {
-            var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
-            return newShaderMaterial;
-        };
-        ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
-            for (var name in this._textures) {
-                this._textures[name].dispose();
-            }
-            this._textures = {};
-            _super.prototype.dispose.call(this, forceDisposeEffect);
-        };
-        ShaderMaterial.prototype.serialize = function () {
-            var serializationObject = _super.prototype.serialize.call(this);
-            serializationObject.options = this._options;
-            serializationObject.shaderPath = this._shaderPath;
-            serializationObject.customType = "BABYLON.ShaderMaterial";
-            // Texture
-            serializationObject.textures = {};
-            for (var name in this._textures) {
-                serializationObject.textures[name] = this._textures[name].serialize();
-            }
-            // Float    
-            serializationObject.floats = {};
-            for (name in this._floats) {
-                serializationObject.floats[name] = this._floats[name];
-            }
-            // Float s   
-            serializationObject.floatArrays = {};
-            for (name in this._floatsArrays) {
-                serializationObject.floatArrays[name] = this._floatsArrays[name];
-            }
-            // Color3    
-            serializationObject.colors3 = {};
-            for (name in this._colors3) {
-                serializationObject.colors3[name] = this._colors3[name].asArray();
-            }
-            // Color4  
-            serializationObject.colors4 = {};
-            for (name in this._colors4) {
-                serializationObject.colors4[name] = this._colors4[name].asArray();
-            }
-            // Vector2  
-            serializationObject.vectors2 = {};
-            for (name in this._vectors2) {
-                serializationObject.vectors2[name] = this._vectors2[name].asArray();
-            }
-            // Vector3        
-            serializationObject.vectors3 = {};
-            for (name in this._vectors3) {
-                serializationObject.vectors3[name] = this._vectors3[name].asArray();
-            }
-            // Vector4        
-            serializationObject.vectors4 = {};
-            for (name in this._vectors4) {
-                serializationObject.vectors4[name] = this._vectors4[name].asArray();
-            }
-            // Matrix      
-            serializationObject.matrices = {};
-            for (name in this._matrices) {
-                serializationObject.matrices[name] = this._matrices[name].asArray();
-            }
-            // Matrix 3x3
-            serializationObject.matrices3x3 = {};
-            for (name in this._matrices3x3) {
-                serializationObject.matrices3x3[name] = this._matrices3x3[name];
-            }
-            // Matrix 2x2
-            serializationObject.matrices2x2 = {};
-            for (name in this._matrices2x2) {
-                serializationObject.matrices2x2[name] = this._matrices2x2[name];
-            }
-            return serializationObject;
-        };
-        ShaderMaterial.Parse = function (source, scene, rootUrl) {
-            var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
-            // Texture
-            for (var name in source.textures) {
-                material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
-            }
-            // Float    
-            for (name in source.floats) {
-                material.setFloat(name, source.floats[name]);
-            }
-            // Float s   
-            for (name in source.floatsArrays) {
-                material.setFloats(name, source.floatsArrays[name]);
-            }
-            // Color3        
-            for (name in source.colors3) {
-                material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
-            }
-            // Color4      
-            for (name in source.colors4) {
-                material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
-            }
-            // Vector2        
-            for (name in source.vectors2) {
-                material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
-            }
-            // Vector3        
-            for (name in source.vectors3) {
-                material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
-            }
-            // Vector4        
-            for (name in source.vectors4) {
-                material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
-            }
-            // Matrix      
-            for (name in source.matrices) {
-                material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
-            }
-            // Matrix 3x3
-            for (name in source.matrices3x3) {
-                material.setMatrix3x3(name, source.matrices3x3[name]);
-            }
-            // Matrix 2x2
-            for (name in source.matrices2x2) {
-                material.setMatrix2x2(name, source.matrices2x2[name]);
-            }
-            return material;
-        };
-        return ShaderMaterial;
-    })(BABYLON.Material);
-    BABYLON.ShaderMaterial = ShaderMaterial;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var ShaderMaterial = (function (_super) {
+        __extends(ShaderMaterial, _super);
+        function ShaderMaterial(name, scene, shaderPath, options) {
+            _super.call(this, name, scene);
+            this._textures = {};
+            this._floats = {};
+            this._floatsArrays = {};
+            this._colors3 = {};
+            this._colors4 = {};
+            this._vectors2 = {};
+            this._vectors3 = {};
+            this._vectors4 = {};
+            this._matrices = {};
+            this._matrices3x3 = {};
+            this._matrices2x2 = {};
+            this._cachedWorldViewMatrix = new BABYLON.Matrix();
+            this._shaderPath = shaderPath;
+            options.needAlphaBlending = options.needAlphaBlending || false;
+            options.needAlphaTesting = options.needAlphaTesting || false;
+            options.attributes = options.attributes || ["position", "normal", "uv"];
+            options.uniforms = options.uniforms || ["worldViewProjection"];
+            options.samplers = options.samplers || [];
+            options.defines = options.defines || [];
+            this._options = options;
+        }
+        ShaderMaterial.prototype.needAlphaBlending = function () {
+            return this._options.needAlphaBlending;
+        };
+        ShaderMaterial.prototype.needAlphaTesting = function () {
+            return this._options.needAlphaTesting;
+        };
+        ShaderMaterial.prototype._checkUniform = function (uniformName) {
+            if (this._options.uniforms.indexOf(uniformName) === -1) {
+                this._options.uniforms.push(uniformName);
+            }
+        };
+        ShaderMaterial.prototype.setTexture = function (name, texture) {
+            if (this._options.samplers.indexOf(name) === -1) {
+                this._options.samplers.push(name);
+            }
+            this._textures[name] = texture;
+            return this;
+        };
+        ShaderMaterial.prototype.setFloat = function (name, value) {
+            this._checkUniform(name);
+            this._floats[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setFloats = function (name, value) {
+            this._checkUniform(name);
+            this._floatsArrays[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setColor3 = function (name, value) {
+            this._checkUniform(name);
+            this._colors3[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setColor4 = function (name, value) {
+            this._checkUniform(name);
+            this._colors4[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setVector2 = function (name, value) {
+            this._checkUniform(name);
+            this._vectors2[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setVector3 = function (name, value) {
+            this._checkUniform(name);
+            this._vectors3[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setVector4 = function (name, value) {
+            this._checkUniform(name);
+            this._vectors4[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setMatrix = function (name, value) {
+            this._checkUniform(name);
+            this._matrices[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
+            this._checkUniform(name);
+            this._matrices3x3[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
+            this._checkUniform(name);
+            this._matrices2x2[name] = value;
+            return this;
+        };
+        ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
+            var scene = this.getScene();
+            var engine = scene.getEngine();
+            if (!this.checkReadyOnEveryCall) {
+                if (this._renderId === scene.getRenderId()) {
+                    return true;
+                }
+            }
+            // Instances
+            var defines = [];
+            var fallbacks = new BABYLON.EffectFallbacks();
+            if (useInstances) {
+                defines.push("#define INSTANCES");
+            }
+            for (var index = 0; index < this._options.defines.length; index++) {
+                defines.push(this._options.defines[index]);
+            }
+            // Bones
+            if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
+                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
+                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
+                fallbacks.addCPUSkinningFallback(0, mesh);
+            }
+            // Alpha test
+            if (engine.getAlphaTesting()) {
+                defines.push("#define ALPHATEST");
+            }
+            var previousEffect = this._effect;
+            var join = defines.join("\n");
+            this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
+            if (!this._effect.isReady()) {
+                return false;
+            }
+            if (previousEffect !== this._effect) {
+                scene.resetCachedMaterial();
+            }
+            this._renderId = scene.getRenderId();
+            return true;
+        };
+        ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
+            var scene = this.getScene();
+            if (this._options.uniforms.indexOf("world") !== -1) {
+                this._effect.setMatrix("world", world);
+            }
+            if (this._options.uniforms.indexOf("worldView") !== -1) {
+                world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
+                this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
+            }
+            if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
+                this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
+            }
+        };
+        ShaderMaterial.prototype.bind = function (world, mesh) {
+            // Std values
+            this.bindOnlyWorldMatrix(world);
+            if (this.getScene().getCachedMaterial() !== this) {
+                if (this._options.uniforms.indexOf("view") !== -1) {
+                    this._effect.setMatrix("view", this.getScene().getViewMatrix());
+                }
+                if (this._options.uniforms.indexOf("projection") !== -1) {
+                    this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
+                }
+                if (this._options.uniforms.indexOf("viewProjection") !== -1) {
+                    this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
+                }
+                // Bones
+                if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
+                    this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
+                }
+                // Texture
+                for (var name in this._textures) {
+                    this._effect.setTexture(name, this._textures[name]);
+                }
+                // Float    
+                for (name in this._floats) {
+                    this._effect.setFloat(name, this._floats[name]);
+                }
+                // Float s   
+                for (name in this._floatsArrays) {
+                    this._effect.setArray(name, this._floatsArrays[name]);
+                }
+                // Color3        
+                for (name in this._colors3) {
+                    this._effect.setColor3(name, this._colors3[name]);
+                }
+                // Color4      
+                for (name in this._colors4) {
+                    var color = this._colors4[name];
+                    this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
+                }
+                // Vector2        
+                for (name in this._vectors2) {
+                    this._effect.setVector2(name, this._vectors2[name]);
+                }
+                // Vector3        
+                for (name in this._vectors3) {
+                    this._effect.setVector3(name, this._vectors3[name]);
+                }
+                // Vector4        
+                for (name in this._vectors4) {
+                    this._effect.setVector4(name, this._vectors4[name]);
+                }
+                // Matrix      
+                for (name in this._matrices) {
+                    this._effect.setMatrix(name, this._matrices[name]);
+                }
+                // Matrix 3x3
+                for (name in this._matrices3x3) {
+                    this._effect.setMatrix3x3(name, this._matrices3x3[name]);
+                }
+                // Matrix 2x2
+                for (name in this._matrices2x2) {
+                    this._effect.setMatrix2x2(name, this._matrices2x2[name]);
+                }
+            }
+            _super.prototype.bind.call(this, world, mesh);
+        };
+        ShaderMaterial.prototype.clone = function (name) {
+            var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
+            return newShaderMaterial;
+        };
+        ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
+            for (var name in this._textures) {
+                this._textures[name].dispose();
+            }
+            this._textures = {};
+            _super.prototype.dispose.call(this, forceDisposeEffect);
+        };
+        ShaderMaterial.prototype.serialize = function () {
+            var serializationObject = _super.prototype.serialize.call(this);
+            serializationObject.options = this._options;
+            serializationObject.shaderPath = this._shaderPath;
+            serializationObject.customType = "BABYLON.ShaderMaterial";
+            // Texture
+            serializationObject.textures = {};
+            for (var name in this._textures) {
+                serializationObject.textures[name] = this._textures[name].serialize();
+            }
+            // Float    
+            serializationObject.floats = {};
+            for (name in this._floats) {
+                serializationObject.floats[name] = this._floats[name];
+            }
+            // Float s   
+            serializationObject.floatArrays = {};
+            for (name in this._floatsArrays) {
+                serializationObject.floatArrays[name] = this._floatsArrays[name];
+            }
+            // Color3    
+            serializationObject.colors3 = {};
+            for (name in this._colors3) {
+                serializationObject.colors3[name] = this._colors3[name].asArray();
+            }
+            // Color4  
+            serializationObject.colors4 = {};
+            for (name in this._colors4) {
+                serializationObject.colors4[name] = this._colors4[name].asArray();
+            }
+            // Vector2  
+            serializationObject.vectors2 = {};
+            for (name in this._vectors2) {
+                serializationObject.vectors2[name] = this._vectors2[name].asArray();
+            }
+            // Vector3        
+            serializationObject.vectors3 = {};
+            for (name in this._vectors3) {
+                serializationObject.vectors3[name] = this._vectors3[name].asArray();
+            }
+            // Vector4        
+            serializationObject.vectors4 = {};
+            for (name in this._vectors4) {
+                serializationObject.vectors4[name] = this._vectors4[name].asArray();
+            }
+            // Matrix      
+            serializationObject.matrices = {};
+            for (name in this._matrices) {
+                serializationObject.matrices[name] = this._matrices[name].asArray();
+            }
+            // Matrix 3x3
+            serializationObject.matrices3x3 = {};
+            for (name in this._matrices3x3) {
+                serializationObject.matrices3x3[name] = this._matrices3x3[name];
+            }
+            // Matrix 2x2
+            serializationObject.matrices2x2 = {};
+            for (name in this._matrices2x2) {
+                serializationObject.matrices2x2[name] = this._matrices2x2[name];
+            }
+            return serializationObject;
+        };
+        ShaderMaterial.Parse = function (source, scene, rootUrl) {
+            var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
+            // Texture
+            for (var name in source.textures) {
+                material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
+            }
+            // Float    
+            for (name in source.floats) {
+                material.setFloat(name, source.floats[name]);
+            }
+            // Float s   
+            for (name in source.floatsArrays) {
+                material.setFloats(name, source.floatsArrays[name]);
+            }
+            // Color3        
+            for (name in source.colors3) {
+                material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
+            }
+            // Color4      
+            for (name in source.colors4) {
+                material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
+            }
+            // Vector2        
+            for (name in source.vectors2) {
+                material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
+            }
+            // Vector3        
+            for (name in source.vectors3) {
+                material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
+            }
+            // Vector4        
+            for (name in source.vectors4) {
+                material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
+            }
+            // Matrix      
+            for (name in source.matrices) {
+                material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
+            }
+            // Matrix 3x3
+            for (name in source.matrices3x3) {
+                material.setMatrix3x3(name, source.matrices3x3[name]);
+            }
+            // Matrix 2x2
+            for (name in source.matrices2x2) {
+                material.setMatrix2x2(name, source.matrices2x2[name]);
+            }
+            return material;
+        };
+        return ShaderMaterial;
+    })(BABYLON.Material);
+    BABYLON.ShaderMaterial = ShaderMaterial;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.shaderMaterial.js.map

File diff suppressed because it is too large
+ 1024 - 1023
src/Materials/babylon.standardMaterial.js


+ 270 - 269
src/Math/babylon.math.SIMD.js

@@ -1,269 +1,270 @@
-var BABYLON;
-(function (BABYLON) {
-    var SIMDVector3 = (function () {
-        function SIMDVector3() {
-        }
-        SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
-            var v = SIMD.float32x4.loadXYZ(vector._data, 0);
-            var m0 = SIMD.float32x4.load(transformation.m, 0);
-            var m1 = SIMD.float32x4.load(transformation.m, 4);
-            var m2 = SIMD.float32x4.load(transformation.m, 8);
-            var m3 = SIMD.float32x4.load(transformation.m, 12);
-            var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
-            r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
-            SIMD.float32x4.storeXYZ(result._data, 0, r);
-        };
-        SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
-            var v0 = SIMD.float32x4.splat(x);
-            var v1 = SIMD.float32x4.splat(y);
-            var v2 = SIMD.float32x4.splat(z);
-            var m0 = SIMD.float32x4.load(transformation.m, 0);
-            var m1 = SIMD.float32x4.load(transformation.m, 4);
-            var m2 = SIMD.float32x4.load(transformation.m, 8);
-            var m3 = SIMD.float32x4.load(transformation.m, 12);
-            var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
-            r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
-            SIMD.float32x4.storeXYZ(result._data, 0, r);
-        };
-        return SIMDVector3;
-    })();
-    BABYLON.SIMDVector3 = SIMDVector3;
-    var SIMDMatrix = (function () {
-        function SIMDMatrix() {
-        }
-        SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
-            if (offset === void 0) { offset = 0; }
-            var tm = this.m;
-            var om = other.m;
-            var om0 = SIMD.float32x4.load(om, 0);
-            var om1 = SIMD.float32x4.load(om, 4);
-            var om2 = SIMD.float32x4.load(om, 8);
-            var om3 = SIMD.float32x4.load(om, 12);
-            var tm0 = SIMD.float32x4.load(tm, 0);
-            SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
-            var tm1 = SIMD.float32x4.load(tm, 4);
-            SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
-            var tm2 = SIMD.float32x4.load(tm, 8);
-            SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
-            var tm3 = SIMD.float32x4.load(tm, 12);
-            SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
-        };
-        SIMDMatrix.prototype.invertToRefSIMD = function (other) {
-            var src = this.m;
-            var dest = other.m;
-            var row0, row1, row2, row3;
-            var tmp1;
-            var minor0, minor1, minor2, minor3;
-            var det;
-            // Load the 4 rows
-            var src0 = SIMD.float32x4.load(src, 0);
-            var src1 = SIMD.float32x4.load(src, 4);
-            var src2 = SIMD.float32x4.load(src, 8);
-            var src3 = SIMD.float32x4.load(src, 12);
-            // Transpose the source matrix.  Sort of.  Not a true transpose operation
-            tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
-            row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
-            row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
-            row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
-            tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
-            row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
-            row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
-            row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
-            // This is a true transposition, but it will lead to an incorrect result
-            //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
-            //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
-            //row0  = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
-            //row1  = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
-            //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
-            //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
-            //row2  = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
-            //row3  = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
-            // ----
-            tmp1 = SIMD.float32x4.mul(row2, row3);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
-            minor0 = SIMD.float32x4.mul(row1, tmp1);
-            minor1 = SIMD.float32x4.mul(row0, tmp1);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
-            minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
-            minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
-            minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
-            // ----
-            tmp1 = SIMD.float32x4.mul(row1, row2);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
-            minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
-            minor3 = SIMD.float32x4.mul(row0, tmp1);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
-            minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
-            minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
-            minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
-            // ----
-            tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
-            row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
-            minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
-            minor2 = SIMD.float32x4.mul(row0, tmp1);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
-            minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
-            minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
-            minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
-            // ----
-            tmp1 = SIMD.float32x4.mul(row0, row1);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
-            minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
-            minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
-            minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
-            minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
-            // ----
-            tmp1 = SIMD.float32x4.mul(row0, row3);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
-            minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
-            minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
-            minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
-            minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
-            // ----
-            tmp1 = SIMD.float32x4.mul(row0, row2);
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
-            minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
-            minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
-            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
-            minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
-            minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
-            // Compute determinant
-            det = SIMD.float32x4.mul(row0, minor0);
-            det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
-            det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
-            tmp1 = SIMD.float32x4.reciprocalApproximation(det);
-            det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
-            det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
-            // These shuffles aren't necessary if the faulty transposition is done
-            // up at the top of this function.
-            //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
-            //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
-            //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
-            //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
-            // Compute final values by multiplying with 1/det
-            minor0 = SIMD.float32x4.mul(det, minor0);
-            minor1 = SIMD.float32x4.mul(det, minor1);
-            minor2 = SIMD.float32x4.mul(det, minor2);
-            minor3 = SIMD.float32x4.mul(det, minor3);
-            SIMD.float32x4.store(dest, 0, minor0);
-            SIMD.float32x4.store(dest, 4, minor1);
-            SIMD.float32x4.store(dest, 8, minor2);
-            SIMD.float32x4.store(dest, 12, minor3);
-            return this;
-        };
-        SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
-            var out = result.m;
-            var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
-            var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
-            var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
-            // cc.kmVec3Subtract(f, pCenter, pEye);
-            var f = SIMD.float32x4.sub(center, eye);
-            // cc.kmVec3Normalize(f, f);    
-            var tmp = SIMD.float32x4.mul(f, f);
-            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
-            f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
-            // cc.kmVec3Assign(up, pUp);
-            // cc.kmVec3Normalize(up, up);
-            tmp = SIMD.float32x4.mul(up, up);
-            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
-            up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
-            // cc.kmVec3Cross(s, f, up);
-            var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
-            // cc.kmVec3Normalize(s, s);
-            tmp = SIMD.float32x4.mul(s, s);
-            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
-            s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
-            // cc.kmVec3Cross(u, s, f);
-            var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
-            // cc.kmVec3Normalize(s, s);
-            tmp = SIMD.float32x4.mul(s, s);
-            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
-            s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
-            var zero = SIMD.float32x4.splat(0.0);
-            s = SIMD.float32x4.neg(s);
-            var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
-            var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
-            var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
-            var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
-            tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
-            tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
-            var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
-            var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
-            var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
-            var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
-            var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
-            var b3 = SIMD.float32x4.neg(eye);
-            b3 = SIMD.float32x4.withW(b3, 1.0);
-            SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
-            SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
-            SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
-            SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
-        };
-        return SIMDMatrix;
-    })();
-    BABYLON.SIMDMatrix = SIMDMatrix;
-    var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
-    var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
-    var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
-    var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
-    var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
-    var SIMDHelper = (function () {
-        function SIMDHelper() {
-        }
-        Object.defineProperty(SIMDHelper, "IsEnabled", {
-            get: function () {
-                return SIMDHelper._isEnabled;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        SIMDHelper.DisableSIMD = function () {
-            // Replace functions
-            BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
-            BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
-            BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
-            BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
-            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
-            SIMDHelper._isEnabled = false;
-        };
-        SIMDHelper.EnableSIMD = function () {
-            if (window.SIMD === undefined) {
-                return;
-            }
-            // Replace functions
-            BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
-            BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
-            BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
-            BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
-            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
-            Object.defineProperty(BABYLON.Vector3.prototype, "x", {
-                get: function () { return this._data[0]; },
-                set: function (value) {
-                    if (!this._data) {
-                        this._data = new Float32Array(3);
-                    }
-                    this._data[0] = value;
-                }
-            });
-            Object.defineProperty(BABYLON.Vector3.prototype, "y", {
-                get: function () { return this._data[1]; },
-                set: function (value) {
-                    this._data[1] = value;
-                }
-            });
-            Object.defineProperty(BABYLON.Vector3.prototype, "z", {
-                get: function () { return this._data[2]; },
-                set: function (value) {
-                    this._data[2] = value;
-                }
-            });
-            SIMDHelper._isEnabled = true;
-        };
-        SIMDHelper._isEnabled = false;
-        return SIMDHelper;
-    })();
-    BABYLON.SIMDHelper = SIMDHelper;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var SIMDVector3 = (function () {
+        function SIMDVector3() {
+        }
+        SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
+            var v = SIMD.float32x4.loadXYZ(vector._data, 0);
+            var m0 = SIMD.float32x4.load(transformation.m, 0);
+            var m1 = SIMD.float32x4.load(transformation.m, 4);
+            var m2 = SIMD.float32x4.load(transformation.m, 8);
+            var m3 = SIMD.float32x4.load(transformation.m, 12);
+            var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
+            r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
+            SIMD.float32x4.storeXYZ(result._data, 0, r);
+        };
+        SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
+            var v0 = SIMD.float32x4.splat(x);
+            var v1 = SIMD.float32x4.splat(y);
+            var v2 = SIMD.float32x4.splat(z);
+            var m0 = SIMD.float32x4.load(transformation.m, 0);
+            var m1 = SIMD.float32x4.load(transformation.m, 4);
+            var m2 = SIMD.float32x4.load(transformation.m, 8);
+            var m3 = SIMD.float32x4.load(transformation.m, 12);
+            var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
+            r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
+            SIMD.float32x4.storeXYZ(result._data, 0, r);
+        };
+        return SIMDVector3;
+    })();
+    BABYLON.SIMDVector3 = SIMDVector3;
+    var SIMDMatrix = (function () {
+        function SIMDMatrix() {
+        }
+        SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
+            if (offset === void 0) { offset = 0; }
+            var tm = this.m;
+            var om = other.m;
+            var om0 = SIMD.float32x4.load(om, 0);
+            var om1 = SIMD.float32x4.load(om, 4);
+            var om2 = SIMD.float32x4.load(om, 8);
+            var om3 = SIMD.float32x4.load(om, 12);
+            var tm0 = SIMD.float32x4.load(tm, 0);
+            SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
+            var tm1 = SIMD.float32x4.load(tm, 4);
+            SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
+            var tm2 = SIMD.float32x4.load(tm, 8);
+            SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
+            var tm3 = SIMD.float32x4.load(tm, 12);
+            SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
+        };
+        SIMDMatrix.prototype.invertToRefSIMD = function (other) {
+            var src = this.m;
+            var dest = other.m;
+            var row0, row1, row2, row3;
+            var tmp1;
+            var minor0, minor1, minor2, minor3;
+            var det;
+            // Load the 4 rows
+            var src0 = SIMD.float32x4.load(src, 0);
+            var src1 = SIMD.float32x4.load(src, 4);
+            var src2 = SIMD.float32x4.load(src, 8);
+            var src3 = SIMD.float32x4.load(src, 12);
+            // Transpose the source matrix.  Sort of.  Not a true transpose operation
+            tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
+            row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
+            row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
+            row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
+            tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
+            row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
+            row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
+            row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
+            // This is a true transposition, but it will lead to an incorrect result
+            //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
+            //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
+            //row0  = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
+            //row1  = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
+            //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
+            //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
+            //row2  = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
+            //row3  = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
+            // ----
+            tmp1 = SIMD.float32x4.mul(row2, row3);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+            minor0 = SIMD.float32x4.mul(row1, tmp1);
+            minor1 = SIMD.float32x4.mul(row0, tmp1);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+            minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
+            minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
+            minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
+            // ----
+            tmp1 = SIMD.float32x4.mul(row1, row2);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+            minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
+            minor3 = SIMD.float32x4.mul(row0, tmp1);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+            minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
+            minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
+            minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
+            // ----
+            tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+            row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
+            minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
+            minor2 = SIMD.float32x4.mul(row0, tmp1);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+            minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
+            minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
+            minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
+            // ----
+            tmp1 = SIMD.float32x4.mul(row0, row1);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+            minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
+            minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+            minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
+            minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
+            // ----
+            tmp1 = SIMD.float32x4.mul(row0, row3);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+            minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
+            minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+            minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
+            minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
+            // ----
+            tmp1 = SIMD.float32x4.mul(row0, row2);
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+            minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
+            minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
+            tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+            minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
+            minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
+            // Compute determinant
+            det = SIMD.float32x4.mul(row0, minor0);
+            det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
+            det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
+            tmp1 = SIMD.float32x4.reciprocalApproximation(det);
+            det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
+            det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
+            // These shuffles aren't necessary if the faulty transposition is done
+            // up at the top of this function.
+            //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
+            //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
+            //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
+            //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
+            // Compute final values by multiplying with 1/det
+            minor0 = SIMD.float32x4.mul(det, minor0);
+            minor1 = SIMD.float32x4.mul(det, minor1);
+            minor2 = SIMD.float32x4.mul(det, minor2);
+            minor3 = SIMD.float32x4.mul(det, minor3);
+            SIMD.float32x4.store(dest, 0, minor0);
+            SIMD.float32x4.store(dest, 4, minor1);
+            SIMD.float32x4.store(dest, 8, minor2);
+            SIMD.float32x4.store(dest, 12, minor3);
+            return this;
+        };
+        SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
+            var out = result.m;
+            var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
+            var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
+            var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
+            // cc.kmVec3Subtract(f, pCenter, pEye);
+            var f = SIMD.float32x4.sub(center, eye);
+            // cc.kmVec3Normalize(f, f);    
+            var tmp = SIMD.float32x4.mul(f, f);
+            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
+            f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
+            // cc.kmVec3Assign(up, pUp);
+            // cc.kmVec3Normalize(up, up);
+            tmp = SIMD.float32x4.mul(up, up);
+            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
+            up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
+            // cc.kmVec3Cross(s, f, up);
+            var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
+            // cc.kmVec3Normalize(s, s);
+            tmp = SIMD.float32x4.mul(s, s);
+            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
+            s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
+            // cc.kmVec3Cross(u, s, f);
+            var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
+            // cc.kmVec3Normalize(s, s);
+            tmp = SIMD.float32x4.mul(s, s);
+            tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
+            s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
+            var zero = SIMD.float32x4.splat(0.0);
+            s = SIMD.float32x4.neg(s);
+            var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
+            var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
+            var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
+            var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
+            tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
+            tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
+            var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
+            var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
+            var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
+            var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
+            var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
+            var b3 = SIMD.float32x4.neg(eye);
+            b3 = SIMD.float32x4.withW(b3, 1.0);
+            SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
+            SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
+            SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
+            SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
+        };
+        return SIMDMatrix;
+    })();
+    BABYLON.SIMDMatrix = SIMDMatrix;
+    var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
+    var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
+    var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
+    var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
+    var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
+    var SIMDHelper = (function () {
+        function SIMDHelper() {
+        }
+        Object.defineProperty(SIMDHelper, "IsEnabled", {
+            get: function () {
+                return SIMDHelper._isEnabled;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        SIMDHelper.DisableSIMD = function () {
+            // Replace functions
+            BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
+            BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
+            BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
+            BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
+            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
+            SIMDHelper._isEnabled = false;
+        };
+        SIMDHelper.EnableSIMD = function () {
+            if (window.SIMD === undefined) {
+                return;
+            }
+            // Replace functions
+            BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
+            BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
+            BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
+            BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
+            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
+            Object.defineProperty(BABYLON.Vector3.prototype, "x", {
+                get: function () { return this._data[0]; },
+                set: function (value) {
+                    if (!this._data) {
+                        this._data = new Float32Array(3);
+                    }
+                    this._data[0] = value;
+                }
+            });
+            Object.defineProperty(BABYLON.Vector3.prototype, "y", {
+                get: function () { return this._data[1]; },
+                set: function (value) {
+                    this._data[1] = value;
+                }
+            });
+            Object.defineProperty(BABYLON.Vector3.prototype, "z", {
+                get: function () { return this._data[2]; },
+                set: function (value) {
+                    this._data[2] = value;
+                }
+            });
+            SIMDHelper._isEnabled = true;
+        };
+        SIMDHelper._isEnabled = false;
+        return SIMDHelper;
+    })();
+    BABYLON.SIMDHelper = SIMDHelper;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.math.SIMD.js.map

File diff suppressed because it is too large
+ 2968 - 2967
src/Math/babylon.math.js


File diff suppressed because it is too large
+ 925 - 924
src/Mesh/babylon.abstractMesh.js


+ 1 - 1
src/Mesh/babylon.abstractMesh.ts

@@ -455,7 +455,7 @@
         public _updateBoundingInfo(): void {
             this._boundingInfo = this._boundingInfo || new BoundingInfo(this.absolutePosition, this.absolutePosition);
 
-            this._boundingInfo._update(this.worldMatrixFromCache);
+            this._boundingInfo.update(this.worldMatrixFromCache);
 
             this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
         }

File diff suppressed because it is too large
+ 514 - 513
src/Mesh/babylon.csg.js


File diff suppressed because it is too large
+ 1014 - 1013
src/Mesh/babylon.geometry.js


+ 170 - 169
src/Mesh/babylon.groundMesh.js

@@ -1,169 +1,170 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var GroundMesh = (function (_super) {
-        __extends(GroundMesh, _super);
-        function GroundMesh(name, scene) {
-            _super.call(this, name, scene);
-            this.generateOctree = false;
-            this._worldInverse = new BABYLON.Matrix();
-        }
-        Object.defineProperty(GroundMesh.prototype, "subdivisions", {
-            get: function () {
-                return this._subdivisions;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
-            if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
-            this._subdivisions = chunksCount;
-            this.subdivide(this._subdivisions);
-            this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
-        };
-        /**
-         * Returns a height (y) value in the Worl system :
-         * the ground altitude at the coordinates (x, z) expressed in the World system.
-         * Returns the ground y position if (x, z) are outside the ground surface.
-         * Not pertinent if the ground is rotated.
-         */
-        GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
-            // express x and y in the ground local system
-            x -= this.position.x;
-            z -= this.position.z;
-            x /= this.scaling.x;
-            z /= this.scaling.z;
-            if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
-                return this.position.y;
-            }
-            if (!this._heightQuads || this._heightQuads.length == 0) {
-                this._computeHeightQuads();
-            }
-            var facet = this._getFacetAt(x, z);
-            var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
-            // return y in the World system
-            return y * this.scaling.y + this.position.y;
-        };
-        /**
-         * Returns a normalized vector (Vector3) orthogonal to the ground
-         * at the ground coordinates (x, z) expressed in the World system.
-         * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
-         * Not pertinent if the ground is rotated.
-         */
-        GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
-            var normal = new BABYLON.Vector3(0, 1, 0);
-            this.getNormalAtCoordinatesToRef(x, z, normal);
-            return normal;
-        };
-        /**
-         * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
-         * at the ground coordinates (x, z) expressed in the World system.
-         * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
-         * Not pertinent if the ground is rotated.
-         */
-        GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
-            // express x and y in the ground local system
-            x -= this.position.x;
-            z -= this.position.z;
-            x /= this.scaling.x;
-            z /= this.scaling.z;
-            if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
-                return;
-            }
-            if (!this._heightQuads || this._heightQuads.length == 0) {
-                this._computeHeightQuads();
-            }
-            var facet = this._getFacetAt(x, z);
-            ref.x = facet.x;
-            ref.y = facet.y;
-            ref.z = facet.z;
-        };
-        // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
-        GroundMesh.prototype._getFacetAt = function (x, z) {
-            // retrieve col and row from x, z coordinates in the ground local system
-            var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
-            var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
-            var quad = this._heightQuads[row * this._subdivisions + col];
-            var facet;
-            if (z < quad.slope.x * x + quad.slope.y) {
-                facet = quad.facet1;
-            }
-            else {
-                facet = quad.facet2;
-            }
-            return facet;
-        };
-        // Populates the heightMap array with "facet" elements :
-        // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
-        // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
-        // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
-        // facet2 :  Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
-        GroundMesh.prototype._computeHeightQuads = function () {
-            this._heightQuads = new Array();
-            var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
-            var v1 = BABYLON.Vector3.Zero();
-            var v2 = BABYLON.Vector3.Zero();
-            var v3 = BABYLON.Vector3.Zero();
-            var v4 = BABYLON.Vector3.Zero();
-            var v1v2 = BABYLON.Vector3.Zero();
-            var v1v3 = BABYLON.Vector3.Zero();
-            var v1v4 = BABYLON.Vector3.Zero();
-            var norm1 = BABYLON.Vector3.Zero();
-            var norm2 = BABYLON.Vector3.Zero();
-            var i = 0;
-            var j = 0;
-            var k = 0;
-            var cd = 0; // 2D slope coefficient : z = cd * x + h
-            var h = 0;
-            var d1 = 0; // facet plane equation : ax + by + cz + d = 0
-            var d2 = 0;
-            for (var row = 0; row < this._subdivisions; row++) {
-                for (var col = 0; col < this._subdivisions; col++) {
-                    i = col * 3;
-                    j = row * (this._subdivisions + 1) * 3;
-                    k = (row + 1) * (this._subdivisions + 1) * 3;
-                    v1.x = positions[j + i];
-                    v1.y = positions[j + i + 1];
-                    v1.z = positions[j + i + 2];
-                    v2.x = positions[j + i + 3];
-                    v2.y = positions[j + i + 4];
-                    v2.z = positions[j + i + 5];
-                    v3.x = positions[k + i];
-                    v3.y = positions[k + i + 1];
-                    v3.z = positions[k + i + 2];
-                    v4.x = positions[k + i + 3];
-                    v4.y = positions[k + i + 4];
-                    v4.z = positions[k + i + 5];
-                    // 2D slope V1V4
-                    cd = (v4.z - v1.z) / (v4.x - v1.x);
-                    h = v1.z - cd * v1.x; // v1 belongs to the slope
-                    var slope = new BABYLON.Vector2(cd, h);
-                    // facet equations :
-                    // we compute each facet normal vector
-                    // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
-                    // we compute the value d by applying the equation to v1 which belongs to the plane
-                    // then we store the facet equation in a Vector4
-                    v2.subtractToRef(v1, v1v2);
-                    v3.subtractToRef(v1, v1v3);
-                    v4.subtractToRef(v1, v1v4);
-                    BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
-                    BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
-                    norm1.normalize();
-                    norm2.normalize();
-                    d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
-                    d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
-                    var facet1 = new BABYLON.Vector4(norm1.x, norm1.y, norm1.z, d1);
-                    var facet2 = new BABYLON.Vector4(norm2.x, norm2.y, norm2.z, d2);
-                    var quad = { slope: slope, facet1: facet1, facet2: facet2 };
-                    this._heightQuads.push(quad);
-                }
-            }
-        };
-        return GroundMesh;
-    })(BABYLON.Mesh);
-    BABYLON.GroundMesh = GroundMesh;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var GroundMesh = (function (_super) {
+        __extends(GroundMesh, _super);
+        function GroundMesh(name, scene) {
+            _super.call(this, name, scene);
+            this.generateOctree = false;
+            this._worldInverse = new BABYLON.Matrix();
+        }
+        Object.defineProperty(GroundMesh.prototype, "subdivisions", {
+            get: function () {
+                return this._subdivisions;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
+            if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
+            this._subdivisions = chunksCount;
+            this.subdivide(this._subdivisions);
+            this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
+        };
+        /**
+         * Returns a height (y) value in the Worl system :
+         * the ground altitude at the coordinates (x, z) expressed in the World system.
+         * Returns the ground y position if (x, z) are outside the ground surface.
+         * Not pertinent if the ground is rotated.
+         */
+        GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
+            // express x and y in the ground local system
+            x -= this.position.x;
+            z -= this.position.z;
+            x /= this.scaling.x;
+            z /= this.scaling.z;
+            if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
+                return this.position.y;
+            }
+            if (!this._heightQuads || this._heightQuads.length == 0) {
+                this._computeHeightQuads();
+            }
+            var facet = this._getFacetAt(x, z);
+            var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
+            // return y in the World system
+            return y * this.scaling.y + this.position.y;
+        };
+        /**
+         * Returns a normalized vector (Vector3) orthogonal to the ground
+         * at the ground coordinates (x, z) expressed in the World system.
+         * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
+         * Not pertinent if the ground is rotated.
+         */
+        GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
+            var normal = new BABYLON.Vector3(0, 1, 0);
+            this.getNormalAtCoordinatesToRef(x, z, normal);
+            return normal;
+        };
+        /**
+         * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
+         * at the ground coordinates (x, z) expressed in the World system.
+         * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
+         * Not pertinent if the ground is rotated.
+         */
+        GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
+            // express x and y in the ground local system
+            x -= this.position.x;
+            z -= this.position.z;
+            x /= this.scaling.x;
+            z /= this.scaling.z;
+            if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
+                return;
+            }
+            if (!this._heightQuads || this._heightQuads.length == 0) {
+                this._computeHeightQuads();
+            }
+            var facet = this._getFacetAt(x, z);
+            ref.x = facet.x;
+            ref.y = facet.y;
+            ref.z = facet.z;
+        };
+        // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
+        GroundMesh.prototype._getFacetAt = function (x, z) {
+            // retrieve col and row from x, z coordinates in the ground local system
+            var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
+            var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
+            var quad = this._heightQuads[row * this._subdivisions + col];
+            var facet;
+            if (z < quad.slope.x * x + quad.slope.y) {
+                facet = quad.facet1;
+            }
+            else {
+                facet = quad.facet2;
+            }
+            return facet;
+        };
+        // Populates the heightMap array with "facet" elements :
+        // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
+        // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
+        // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
+        // facet2 :  Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
+        GroundMesh.prototype._computeHeightQuads = function () {
+            this._heightQuads = new Array();
+            var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
+            var v1 = BABYLON.Vector3.Zero();
+            var v2 = BABYLON.Vector3.Zero();
+            var v3 = BABYLON.Vector3.Zero();
+            var v4 = BABYLON.Vector3.Zero();
+            var v1v2 = BABYLON.Vector3.Zero();
+            var v1v3 = BABYLON.Vector3.Zero();
+            var v1v4 = BABYLON.Vector3.Zero();
+            var norm1 = BABYLON.Vector3.Zero();
+            var norm2 = BABYLON.Vector3.Zero();
+            var i = 0;
+            var j = 0;
+            var k = 0;
+            var cd = 0; // 2D slope coefficient : z = cd * x + h
+            var h = 0;
+            var d1 = 0; // facet plane equation : ax + by + cz + d = 0
+            var d2 = 0;
+            for (var row = 0; row < this._subdivisions; row++) {
+                for (var col = 0; col < this._subdivisions; col++) {
+                    i = col * 3;
+                    j = row * (this._subdivisions + 1) * 3;
+                    k = (row + 1) * (this._subdivisions + 1) * 3;
+                    v1.x = positions[j + i];
+                    v1.y = positions[j + i + 1];
+                    v1.z = positions[j + i + 2];
+                    v2.x = positions[j + i + 3];
+                    v2.y = positions[j + i + 4];
+                    v2.z = positions[j + i + 5];
+                    v3.x = positions[k + i];
+                    v3.y = positions[k + i + 1];
+                    v3.z = positions[k + i + 2];
+                    v4.x = positions[k + i + 3];
+                    v4.y = positions[k + i + 4];
+                    v4.z = positions[k + i + 5];
+                    // 2D slope V1V4
+                    cd = (v4.z - v1.z) / (v4.x - v1.x);
+                    h = v1.z - cd * v1.x; // v1 belongs to the slope
+                    var slope = new BABYLON.Vector2(cd, h);
+                    // facet equations :
+                    // we compute each facet normal vector
+                    // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
+                    // we compute the value d by applying the equation to v1 which belongs to the plane
+                    // then we store the facet equation in a Vector4
+                    v2.subtractToRef(v1, v1v2);
+                    v3.subtractToRef(v1, v1v3);
+                    v4.subtractToRef(v1, v1v4);
+                    BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
+                    BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
+                    norm1.normalize();
+                    norm2.normalize();
+                    d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
+                    d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
+                    var facet1 = new BABYLON.Vector4(norm1.x, norm1.y, norm1.z, d1);
+                    var facet2 = new BABYLON.Vector4(norm2.x, norm2.y, norm2.z, d2);
+                    var quad = { slope: slope, facet1: facet1, facet2: facet2 };
+                    this._heightQuads.push(quad);
+                }
+            }
+        };
+        return GroundMesh;
+    })(BABYLON.Mesh);
+    BABYLON.GroundMesh = GroundMesh;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.groundMesh.js.map

+ 157 - 156
src/Mesh/babylon.instancedMesh.js

@@ -1,156 +1,157 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    /**
-     * Creates an instance based on a source mesh.
-     */
-    var InstancedMesh = (function (_super) {
-        __extends(InstancedMesh, _super);
-        function InstancedMesh(name, source) {
-            _super.call(this, name, source.getScene());
-            source.instances.push(this);
-            this._sourceMesh = source;
-            this.position.copyFrom(source.position);
-            this.rotation.copyFrom(source.rotation);
-            this.scaling.copyFrom(source.scaling);
-            if (source.rotationQuaternion) {
-                this.rotationQuaternion = source.rotationQuaternion.clone();
-            }
-            this.infiniteDistance = source.infiniteDistance;
-            this.setPivotMatrix(source.getPivotMatrix());
-            this.refreshBoundingInfo();
-            this._syncSubMeshes();
-        }
-        Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
-            // Methods
-            get: function () {
-                return this._sourceMesh.receiveShadows;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(InstancedMesh.prototype, "material", {
-            get: function () {
-                return this._sourceMesh.material;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(InstancedMesh.prototype, "visibility", {
-            get: function () {
-                return this._sourceMesh.visibility;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(InstancedMesh.prototype, "skeleton", {
-            get: function () {
-                return this._sourceMesh.skeleton;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
-            get: function () {
-                return this._sourceMesh.renderingGroupId;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        InstancedMesh.prototype.getTotalVertices = function () {
-            return this._sourceMesh.getTotalVertices();
-        };
-        Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
-            get: function () {
-                return this._sourceMesh;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
-            return this._sourceMesh.getVerticesData(kind, copyWhenShared);
-        };
-        InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
-            return this._sourceMesh.isVerticesDataPresent(kind);
-        };
-        InstancedMesh.prototype.getIndices = function () {
-            return this._sourceMesh.getIndices();
-        };
-        Object.defineProperty(InstancedMesh.prototype, "_positions", {
-            get: function () {
-                return this._sourceMesh._positions;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        InstancedMesh.prototype.refreshBoundingInfo = function () {
-            var meshBB = this._sourceMesh.getBoundingInfo();
-            this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
-            this._updateBoundingInfo();
-        };
-        InstancedMesh.prototype._preActivate = function () {
-            if (this._currentLOD) {
-                this._currentLOD._preActivate();
-            }
-        };
-        InstancedMesh.prototype._activate = function (renderId) {
-            if (this._currentLOD) {
-                this._currentLOD._registerInstanceForRenderId(this, renderId);
-            }
-        };
-        InstancedMesh.prototype.getLOD = function (camera) {
-            this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
-            if (this._currentLOD === this.sourceMesh) {
-                return this;
-            }
-            return this._currentLOD;
-        };
-        InstancedMesh.prototype._syncSubMeshes = function () {
-            this.releaseSubMeshes();
-            if (this._sourceMesh.subMeshes) {
-                for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
-                    this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
-                }
-            }
-        };
-        InstancedMesh.prototype._generatePointsArray = function () {
-            return this._sourceMesh._generatePointsArray();
-        };
-        // Clone
-        InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
-            var result = this._sourceMesh.createInstance(name);
-            // Deep copy
-            BABYLON.Tools.DeepCopy(this, result, ["name"], []);
-            // Bounding info
-            this.refreshBoundingInfo();
-            // Parent
-            if (newParent) {
-                result.parent = newParent;
-            }
-            if (!doNotCloneChildren) {
-                // Children
-                for (var index = 0; index < this.getScene().meshes.length; index++) {
-                    var mesh = this.getScene().meshes[index];
-                    if (mesh.parent === this) {
-                        mesh.clone(mesh.name, result);
-                    }
-                }
-            }
-            result.computeWorldMatrix(true);
-            return result;
-        };
-        // Dispoe
-        InstancedMesh.prototype.dispose = function (doNotRecurse) {
-            // Remove from mesh
-            var index = this._sourceMesh.instances.indexOf(this);
-            this._sourceMesh.instances.splice(index, 1);
-            _super.prototype.dispose.call(this, doNotRecurse);
-        };
-        return InstancedMesh;
-    })(BABYLON.AbstractMesh);
-    BABYLON.InstancedMesh = InstancedMesh;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    /**
+     * Creates an instance based on a source mesh.
+     */
+    var InstancedMesh = (function (_super) {
+        __extends(InstancedMesh, _super);
+        function InstancedMesh(name, source) {
+            _super.call(this, name, source.getScene());
+            source.instances.push(this);
+            this._sourceMesh = source;
+            this.position.copyFrom(source.position);
+            this.rotation.copyFrom(source.rotation);
+            this.scaling.copyFrom(source.scaling);
+            if (source.rotationQuaternion) {
+                this.rotationQuaternion = source.rotationQuaternion.clone();
+            }
+            this.infiniteDistance = source.infiniteDistance;
+            this.setPivotMatrix(source.getPivotMatrix());
+            this.refreshBoundingInfo();
+            this._syncSubMeshes();
+        }
+        Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
+            // Methods
+            get: function () {
+                return this._sourceMesh.receiveShadows;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(InstancedMesh.prototype, "material", {
+            get: function () {
+                return this._sourceMesh.material;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(InstancedMesh.prototype, "visibility", {
+            get: function () {
+                return this._sourceMesh.visibility;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(InstancedMesh.prototype, "skeleton", {
+            get: function () {
+                return this._sourceMesh.skeleton;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
+            get: function () {
+                return this._sourceMesh.renderingGroupId;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        InstancedMesh.prototype.getTotalVertices = function () {
+            return this._sourceMesh.getTotalVertices();
+        };
+        Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
+            get: function () {
+                return this._sourceMesh;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
+            return this._sourceMesh.getVerticesData(kind, copyWhenShared);
+        };
+        InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
+            return this._sourceMesh.isVerticesDataPresent(kind);
+        };
+        InstancedMesh.prototype.getIndices = function () {
+            return this._sourceMesh.getIndices();
+        };
+        Object.defineProperty(InstancedMesh.prototype, "_positions", {
+            get: function () {
+                return this._sourceMesh._positions;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        InstancedMesh.prototype.refreshBoundingInfo = function () {
+            var meshBB = this._sourceMesh.getBoundingInfo();
+            this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
+            this._updateBoundingInfo();
+        };
+        InstancedMesh.prototype._preActivate = function () {
+            if (this._currentLOD) {
+                this._currentLOD._preActivate();
+            }
+        };
+        InstancedMesh.prototype._activate = function (renderId) {
+            if (this._currentLOD) {
+                this._currentLOD._registerInstanceForRenderId(this, renderId);
+            }
+        };
+        InstancedMesh.prototype.getLOD = function (camera) {
+            this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
+            if (this._currentLOD === this.sourceMesh) {
+                return this;
+            }
+            return this._currentLOD;
+        };
+        InstancedMesh.prototype._syncSubMeshes = function () {
+            this.releaseSubMeshes();
+            if (this._sourceMesh.subMeshes) {
+                for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
+                    this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
+                }
+            }
+        };
+        InstancedMesh.prototype._generatePointsArray = function () {
+            return this._sourceMesh._generatePointsArray();
+        };
+        // Clone
+        InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
+            var result = this._sourceMesh.createInstance(name);
+            // Deep copy
+            BABYLON.Tools.DeepCopy(this, result, ["name"], []);
+            // Bounding info
+            this.refreshBoundingInfo();
+            // Parent
+            if (newParent) {
+                result.parent = newParent;
+            }
+            if (!doNotCloneChildren) {
+                // Children
+                for (var index = 0; index < this.getScene().meshes.length; index++) {
+                    var mesh = this.getScene().meshes[index];
+                    if (mesh.parent === this) {
+                        mesh.clone(mesh.name, result);
+                    }
+                }
+            }
+            result.computeWorldMatrix(true);
+            return result;
+        };
+        // Dispoe
+        InstancedMesh.prototype.dispose = function (doNotRecurse) {
+            // Remove from mesh
+            var index = this._sourceMesh.instances.indexOf(this);
+            this._sourceMesh.instances.splice(index, 1);
+            _super.prototype.dispose.call(this, doNotRecurse);
+        };
+        return InstancedMesh;
+    })(BABYLON.AbstractMesh);
+    BABYLON.InstancedMesh = InstancedMesh;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.instancedMesh.js.map

+ 72 - 71
src/Mesh/babylon.linesMesh.js

@@ -1,71 +1,72 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var LinesMesh = (function (_super) {
-        __extends(LinesMesh, _super);
-        function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
-            if (parent === void 0) { parent = null; }
-            _super.call(this, name, scene, parent, source, doNotCloneChildren);
-            this.color = new BABYLON.Color3(1, 1, 1);
-            this.alpha = 1;
-            this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
-                attributes: ["position"],
-                uniforms: ["worldViewProjection", "color"],
-                needAlphaBlending: true
-            });
-        }
-        Object.defineProperty(LinesMesh.prototype, "material", {
-            get: function () {
-                return this._colorShader;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(LinesMesh.prototype, "isPickable", {
-            get: function () {
-                return false;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
-            get: function () {
-                return false;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
-            var engine = this.getScene().getEngine();
-            var indexToBind = this._geometry.getIndexBuffer();
-            // VBOs
-            engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
-            // Color
-            this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
-        };
-        LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
-            if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
-                return;
-            }
-            var engine = this.getScene().getEngine();
-            // Draw order
-            engine.draw(false, subMesh.indexStart, subMesh.indexCount);
-        };
-        LinesMesh.prototype.intersects = function (ray, fastCheck) {
-            return null;
-        };
-        LinesMesh.prototype.dispose = function (doNotRecurse) {
-            this._colorShader.dispose();
-            _super.prototype.dispose.call(this, doNotRecurse);
-        };
-        LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
-            return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
-        };
-        return LinesMesh;
-    })(BABYLON.Mesh);
-    BABYLON.LinesMesh = LinesMesh;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var LinesMesh = (function (_super) {
+        __extends(LinesMesh, _super);
+        function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
+            if (parent === void 0) { parent = null; }
+            _super.call(this, name, scene, parent, source, doNotCloneChildren);
+            this.color = new BABYLON.Color3(1, 1, 1);
+            this.alpha = 1;
+            this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
+                attributes: ["position"],
+                uniforms: ["worldViewProjection", "color"],
+                needAlphaBlending: true
+            });
+        }
+        Object.defineProperty(LinesMesh.prototype, "material", {
+            get: function () {
+                return this._colorShader;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(LinesMesh.prototype, "isPickable", {
+            get: function () {
+                return false;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
+            get: function () {
+                return false;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
+            var engine = this.getScene().getEngine();
+            var indexToBind = this._geometry.getIndexBuffer();
+            // VBOs
+            engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
+            // Color
+            this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
+        };
+        LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
+            if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
+                return;
+            }
+            var engine = this.getScene().getEngine();
+            // Draw order
+            engine.draw(false, subMesh.indexStart, subMesh.indexCount);
+        };
+        LinesMesh.prototype.intersects = function (ray, fastCheck) {
+            return null;
+        };
+        LinesMesh.prototype.dispose = function (doNotRecurse) {
+            this._colorShader.dispose();
+            _super.prototype.dispose.call(this, doNotRecurse);
+        };
+        LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
+            return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
+        };
+        return LinesMesh;
+    })(BABYLON.Mesh);
+    BABYLON.LinesMesh = LinesMesh;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.linesMesh.js.map

File diff suppressed because it is too large
+ 1717 - 1716
src/Mesh/babylon.mesh.js


File diff suppressed because it is too large
+ 1819 - 1818
src/Mesh/babylon.mesh.vertexData.js


File diff suppressed because it is too large
+ 706 - 705
src/Mesh/babylon.meshBuilder.js


+ 15 - 14
src/Mesh/babylon.meshLODLevel.js

@@ -1,14 +1,15 @@
-var BABYLON;
-(function (BABYLON) {
-    var Internals;
-    (function (Internals) {
-        var MeshLODLevel = (function () {
-            function MeshLODLevel(distance, mesh) {
-                this.distance = distance;
-                this.mesh = mesh;
-            }
-            return MeshLODLevel;
-        })();
-        Internals.MeshLODLevel = MeshLODLevel;
-    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var Internals;
+    (function (Internals) {
+        var MeshLODLevel = (function () {
+            function MeshLODLevel(distance, mesh) {
+                this.distance = distance;
+                this.mesh = mesh;
+            }
+            return MeshLODLevel;
+        })();
+        Internals.MeshLODLevel = MeshLODLevel;
+    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.meshLODLevel.js.map

File diff suppressed because it is too large
+ 659 - 658
src/Mesh/babylon.meshSimplification.js


+ 246 - 245
src/Mesh/babylon.polygonMesh.js

@@ -1,245 +1,246 @@
-var __extends = (this && this.__extends) || function (d, b) {
-    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
-    function __() { this.constructor = d; }
-    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-};
-var BABYLON;
-(function (BABYLON) {
-    var IndexedVector2 = (function (_super) {
-        __extends(IndexedVector2, _super);
-        function IndexedVector2(original, index) {
-            _super.call(this, original.x, original.y);
-            this.index = index;
-        }
-        return IndexedVector2;
-    })(BABYLON.Vector2);
-    var PolygonPoints = (function () {
-        function PolygonPoints() {
-            this.elements = new Array();
-        }
-        PolygonPoints.prototype.add = function (originalPoints) {
-            var _this = this;
-            var result = new Array();
-            originalPoints.forEach(function (point) {
-                if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
-                    var newPoint = new IndexedVector2(point, _this.elements.length);
-                    result.push(newPoint);
-                    _this.elements.push(newPoint);
-                }
-            });
-            return result;
-        };
-        PolygonPoints.prototype.computeBounds = function () {
-            var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
-            var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
-            this.elements.forEach(function (point) {
-                // x
-                if (point.x < lmin.x) {
-                    lmin.x = point.x;
-                }
-                else if (point.x > lmax.x) {
-                    lmax.x = point.x;
-                }
-                // y
-                if (point.y < lmin.y) {
-                    lmin.y = point.y;
-                }
-                else if (point.y > lmax.y) {
-                    lmax.y = point.y;
-                }
-            });
-            return {
-                min: lmin,
-                max: lmax,
-                width: lmax.x - lmin.x,
-                height: lmax.y - lmin.y
-            };
-        };
-        return PolygonPoints;
-    })();
-    var Polygon = (function () {
-        function Polygon() {
-        }
-        Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
-            return [
-                new BABYLON.Vector2(xmin, ymin),
-                new BABYLON.Vector2(xmax, ymin),
-                new BABYLON.Vector2(xmax, ymax),
-                new BABYLON.Vector2(xmin, ymax)
-            ];
-        };
-        Polygon.Circle = function (radius, cx, cy, numberOfSides) {
-            if (cx === void 0) { cx = 0; }
-            if (cy === void 0) { cy = 0; }
-            if (numberOfSides === void 0) { numberOfSides = 32; }
-            var result = new Array();
-            var angle = 0;
-            var increment = (Math.PI * 2) / numberOfSides;
-            for (var i = 0; i < numberOfSides; i++) {
-                result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
-                angle -= increment;
-            }
-            return result;
-        };
-        Polygon.Parse = function (input) {
-            var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
-            var i, result = [];
-            for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
-                result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
-            }
-            return result;
-        };
-        Polygon.StartingAt = function (x, y) {
-            return BABYLON.Path2.StartingAt(x, y);
-        };
-        return Polygon;
-    })();
-    BABYLON.Polygon = Polygon;
-    var PolygonMeshBuilder = (function () {
-        function PolygonMeshBuilder(name, contours, scene) {
-            this._points = new PolygonPoints();
-            this._outlinepoints = new PolygonPoints();
-            this._holes = [];
-            if (!("poly2tri" in window)) {
-                throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
-            }
-            this._name = name;
-            this._scene = scene;
-            var points;
-            if (contours instanceof BABYLON.Path2) {
-                points = contours.getPoints();
-            }
-            else {
-                points = contours;
-            }
-            this._swctx = new poly2tri.SweepContext(this._points.add(points));
-            this._outlinepoints.add(points);
-        }
-        PolygonMeshBuilder.prototype.addHole = function (hole) {
-            this._swctx.addHole(this._points.add(hole));
-            var holepoints = new PolygonPoints();
-            holepoints.add(hole);
-            this._holes.push(holepoints);
-            return this;
-        };
-        PolygonMeshBuilder.prototype.build = function (updatable, depth) {
-            var _this = this;
-            if (updatable === void 0) { updatable = false; }
-            var result = new BABYLON.Mesh(this._name, this._scene);
-            var normals = [];
-            var positions = [];
-            var uvs = [];
-            var bounds = this._points.computeBounds();
-            this._points.elements.forEach(function (p) {
-                normals.push(0, 1.0, 0);
-                positions.push(p.x, 0, p.y);
-                uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
-            });
-            var indices = [];
-            this._swctx.triangulate();
-            this._swctx.getTriangles().forEach(function (triangle) {
-                triangle.getPoints().forEach(function (point) {
-                    indices.push(point.index);
-                });
-            });
-            if (depth > 0) {
-                var positionscount = (positions.length / 3); //get the current pointcount
-                this._points.elements.forEach(function (p) {
-                    normals.push(0, -1.0, 0);
-                    positions.push(p.x, -depth, p.y);
-                    uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
-                });
-                var p1; //we need to change order of point so the triangles are made in the rigth way.
-                var p2;
-                var poscounter = 0;
-                this._swctx.getTriangles().forEach(function (triangle) {
-                    triangle.getPoints().forEach(function (point) {
-                        switch (poscounter) {
-                            case 0:
-                                p1 = point;
-                                break;
-                            case 1:
-                                p2 = point;
-                                break;
-                            case 2:
-                                indices.push(point.index + positionscount);
-                                indices.push(p2.index + positionscount);
-                                indices.push(p1.index + positionscount);
-                                poscounter = -1;
-                                break;
-                        }
-                        poscounter++;
-                        //indices.push((<IndexedVector2>point).index + positionscount);
-                    });
-                });
-                //Add the sides
-                this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
-                this._holes.forEach(function (hole) {
-                    _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
-                });
-            }
-            result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
-            result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
-            result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
-            result.setIndices(indices);
-            return result;
-        };
-        PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
-            var StartIndex = positions.length / 3;
-            var ulength = 0;
-            for (var i = 0; i < points.elements.length; i++) {
-                var p = points.elements[i];
-                var p1;
-                if ((i + 1) > points.elements.length - 1) {
-                    p1 = points.elements[0];
-                }
-                else {
-                    p1 = points.elements[i + 1];
-                }
-                positions.push(p.x, 0, p.y);
-                positions.push(p.x, -depth, p.y);
-                positions.push(p1.x, 0, p1.y);
-                positions.push(p1.x, -depth, p1.y);
-                var v1 = new BABYLON.Vector3(p.x, 0, p.y);
-                var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
-                var v3 = v2.subtract(v1);
-                var v4 = new BABYLON.Vector3(0, 1, 0);
-                var vn = BABYLON.Vector3.Cross(v3, v4);
-                vn = vn.normalize();
-                uvs.push(ulength / bounds.width, 0);
-                uvs.push(ulength / bounds.width, 1);
-                ulength += v3.length();
-                uvs.push((ulength / bounds.width), 0);
-                uvs.push((ulength / bounds.width), 1);
-                if (!flip) {
-                    normals.push(-vn.x, -vn.y, -vn.z);
-                    normals.push(-vn.x, -vn.y, -vn.z);
-                    normals.push(-vn.x, -vn.y, -vn.z);
-                    normals.push(-vn.x, -vn.y, -vn.z);
-                    indices.push(StartIndex);
-                    indices.push(StartIndex + 1);
-                    indices.push(StartIndex + 2);
-                    indices.push(StartIndex + 1);
-                    indices.push(StartIndex + 3);
-                    indices.push(StartIndex + 2);
-                }
-                else {
-                    normals.push(vn.x, vn.y, vn.z);
-                    normals.push(vn.x, vn.y, vn.z);
-                    normals.push(vn.x, vn.y, vn.z);
-                    normals.push(vn.x, vn.y, vn.z);
-                    indices.push(StartIndex);
-                    indices.push(StartIndex + 2);
-                    indices.push(StartIndex + 1);
-                    indices.push(StartIndex + 1);
-                    indices.push(StartIndex + 2);
-                    indices.push(StartIndex + 3);
-                }
-                StartIndex += 4;
-            }
-            ;
-        };
-        return PolygonMeshBuilder;
-    })();
-    BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
-})(BABYLON || (BABYLON = {}));
+var __extends = (this && this.__extends) || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var BABYLON;
+(function (BABYLON) {
+    var IndexedVector2 = (function (_super) {
+        __extends(IndexedVector2, _super);
+        function IndexedVector2(original, index) {
+            _super.call(this, original.x, original.y);
+            this.index = index;
+        }
+        return IndexedVector2;
+    })(BABYLON.Vector2);
+    var PolygonPoints = (function () {
+        function PolygonPoints() {
+            this.elements = new Array();
+        }
+        PolygonPoints.prototype.add = function (originalPoints) {
+            var _this = this;
+            var result = new Array();
+            originalPoints.forEach(function (point) {
+                if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
+                    var newPoint = new IndexedVector2(point, _this.elements.length);
+                    result.push(newPoint);
+                    _this.elements.push(newPoint);
+                }
+            });
+            return result;
+        };
+        PolygonPoints.prototype.computeBounds = function () {
+            var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
+            var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
+            this.elements.forEach(function (point) {
+                // x
+                if (point.x < lmin.x) {
+                    lmin.x = point.x;
+                }
+                else if (point.x > lmax.x) {
+                    lmax.x = point.x;
+                }
+                // y
+                if (point.y < lmin.y) {
+                    lmin.y = point.y;
+                }
+                else if (point.y > lmax.y) {
+                    lmax.y = point.y;
+                }
+            });
+            return {
+                min: lmin,
+                max: lmax,
+                width: lmax.x - lmin.x,
+                height: lmax.y - lmin.y
+            };
+        };
+        return PolygonPoints;
+    })();
+    var Polygon = (function () {
+        function Polygon() {
+        }
+        Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
+            return [
+                new BABYLON.Vector2(xmin, ymin),
+                new BABYLON.Vector2(xmax, ymin),
+                new BABYLON.Vector2(xmax, ymax),
+                new BABYLON.Vector2(xmin, ymax)
+            ];
+        };
+        Polygon.Circle = function (radius, cx, cy, numberOfSides) {
+            if (cx === void 0) { cx = 0; }
+            if (cy === void 0) { cy = 0; }
+            if (numberOfSides === void 0) { numberOfSides = 32; }
+            var result = new Array();
+            var angle = 0;
+            var increment = (Math.PI * 2) / numberOfSides;
+            for (var i = 0; i < numberOfSides; i++) {
+                result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
+                angle -= increment;
+            }
+            return result;
+        };
+        Polygon.Parse = function (input) {
+            var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
+            var i, result = [];
+            for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
+                result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
+            }
+            return result;
+        };
+        Polygon.StartingAt = function (x, y) {
+            return BABYLON.Path2.StartingAt(x, y);
+        };
+        return Polygon;
+    })();
+    BABYLON.Polygon = Polygon;
+    var PolygonMeshBuilder = (function () {
+        function PolygonMeshBuilder(name, contours, scene) {
+            this._points = new PolygonPoints();
+            this._outlinepoints = new PolygonPoints();
+            this._holes = [];
+            if (!("poly2tri" in window)) {
+                throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
+            }
+            this._name = name;
+            this._scene = scene;
+            var points;
+            if (contours instanceof BABYLON.Path2) {
+                points = contours.getPoints();
+            }
+            else {
+                points = contours;
+            }
+            this._swctx = new poly2tri.SweepContext(this._points.add(points));
+            this._outlinepoints.add(points);
+        }
+        PolygonMeshBuilder.prototype.addHole = function (hole) {
+            this._swctx.addHole(this._points.add(hole));
+            var holepoints = new PolygonPoints();
+            holepoints.add(hole);
+            this._holes.push(holepoints);
+            return this;
+        };
+        PolygonMeshBuilder.prototype.build = function (updatable, depth) {
+            var _this = this;
+            if (updatable === void 0) { updatable = false; }
+            var result = new BABYLON.Mesh(this._name, this._scene);
+            var normals = [];
+            var positions = [];
+            var uvs = [];
+            var bounds = this._points.computeBounds();
+            this._points.elements.forEach(function (p) {
+                normals.push(0, 1.0, 0);
+                positions.push(p.x, 0, p.y);
+                uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
+            });
+            var indices = [];
+            this._swctx.triangulate();
+            this._swctx.getTriangles().forEach(function (triangle) {
+                triangle.getPoints().forEach(function (point) {
+                    indices.push(point.index);
+                });
+            });
+            if (depth > 0) {
+                var positionscount = (positions.length / 3); //get the current pointcount
+                this._points.elements.forEach(function (p) {
+                    normals.push(0, -1.0, 0);
+                    positions.push(p.x, -depth, p.y);
+                    uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
+                });
+                var p1; //we need to change order of point so the triangles are made in the rigth way.
+                var p2;
+                var poscounter = 0;
+                this._swctx.getTriangles().forEach(function (triangle) {
+                    triangle.getPoints().forEach(function (point) {
+                        switch (poscounter) {
+                            case 0:
+                                p1 = point;
+                                break;
+                            case 1:
+                                p2 = point;
+                                break;
+                            case 2:
+                                indices.push(point.index + positionscount);
+                                indices.push(p2.index + positionscount);
+                                indices.push(p1.index + positionscount);
+                                poscounter = -1;
+                                break;
+                        }
+                        poscounter++;
+                        //indices.push((<IndexedVector2>point).index + positionscount);
+                    });
+                });
+                //Add the sides
+                this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
+                this._holes.forEach(function (hole) {
+                    _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
+                });
+            }
+            result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
+            result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
+            result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
+            result.setIndices(indices);
+            return result;
+        };
+        PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
+            var StartIndex = positions.length / 3;
+            var ulength = 0;
+            for (var i = 0; i < points.elements.length; i++) {
+                var p = points.elements[i];
+                var p1;
+                if ((i + 1) > points.elements.length - 1) {
+                    p1 = points.elements[0];
+                }
+                else {
+                    p1 = points.elements[i + 1];
+                }
+                positions.push(p.x, 0, p.y);
+                positions.push(p.x, -depth, p.y);
+                positions.push(p1.x, 0, p1.y);
+                positions.push(p1.x, -depth, p1.y);
+                var v1 = new BABYLON.Vector3(p.x, 0, p.y);
+                var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
+                var v3 = v2.subtract(v1);
+                var v4 = new BABYLON.Vector3(0, 1, 0);
+                var vn = BABYLON.Vector3.Cross(v3, v4);
+                vn = vn.normalize();
+                uvs.push(ulength / bounds.width, 0);
+                uvs.push(ulength / bounds.width, 1);
+                ulength += v3.length();
+                uvs.push((ulength / bounds.width), 0);
+                uvs.push((ulength / bounds.width), 1);
+                if (!flip) {
+                    normals.push(-vn.x, -vn.y, -vn.z);
+                    normals.push(-vn.x, -vn.y, -vn.z);
+                    normals.push(-vn.x, -vn.y, -vn.z);
+                    normals.push(-vn.x, -vn.y, -vn.z);
+                    indices.push(StartIndex);
+                    indices.push(StartIndex + 1);
+                    indices.push(StartIndex + 2);
+                    indices.push(StartIndex + 1);
+                    indices.push(StartIndex + 3);
+                    indices.push(StartIndex + 2);
+                }
+                else {
+                    normals.push(vn.x, vn.y, vn.z);
+                    normals.push(vn.x, vn.y, vn.z);
+                    normals.push(vn.x, vn.y, vn.z);
+                    normals.push(vn.x, vn.y, vn.z);
+                    indices.push(StartIndex);
+                    indices.push(StartIndex + 2);
+                    indices.push(StartIndex + 1);
+                    indices.push(StartIndex + 1);
+                    indices.push(StartIndex + 2);
+                    indices.push(StartIndex + 3);
+                }
+                StartIndex += 4;
+            }
+            ;
+        };
+        return PolygonMeshBuilder;
+    })();
+    BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.polygonMesh.js.map

+ 163 - 162
src/Mesh/babylon.subMesh.js

@@ -1,162 +1,163 @@
-var BABYLON;
-(function (BABYLON) {
-    var SubMesh = (function () {
-        function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
-            if (createBoundingBox === void 0) { createBoundingBox = true; }
-            this.materialIndex = materialIndex;
-            this.verticesStart = verticesStart;
-            this.verticesCount = verticesCount;
-            this.indexStart = indexStart;
-            this.indexCount = indexCount;
-            this._renderId = 0;
-            this._mesh = mesh;
-            this._renderingMesh = renderingMesh || mesh;
-            mesh.subMeshes.push(this);
-            this._trianglePlanes = [];
-            this._id = mesh.subMeshes.length - 1;
-            if (createBoundingBox) {
-                this.refreshBoundingInfo();
-                mesh.computeWorldMatrix(true);
-            }
-        }
-        Object.defineProperty(SubMesh.prototype, "IsGlobal", {
-            get: function () {
-                return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
-            },
-            enumerable: true,
-            configurable: true
-        });
-        SubMesh.prototype.getBoundingInfo = function () {
-            if (this.IsGlobal) {
-                return this._mesh.getBoundingInfo();
-            }
-            return this._boundingInfo;
-        };
-        SubMesh.prototype.getMesh = function () {
-            return this._mesh;
-        };
-        SubMesh.prototype.getRenderingMesh = function () {
-            return this._renderingMesh;
-        };
-        SubMesh.prototype.getMaterial = function () {
-            var rootMaterial = this._renderingMesh.material;
-            if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
-                var multiMaterial = rootMaterial;
-                return multiMaterial.getSubMaterial(this.materialIndex);
-            }
-            if (!rootMaterial) {
-                return this._mesh.getScene().defaultMaterial;
-            }
-            return rootMaterial;
-        };
-        // Methods
-        SubMesh.prototype.refreshBoundingInfo = function () {
-            if (this.IsGlobal) {
-                return;
-            }
-            var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
-            if (!data) {
-                this._boundingInfo = this._mesh._boundingInfo;
-                return;
-            }
-            var indices = this._renderingMesh.getIndices();
-            var extend;
-            //is this the only submesh?
-            if (this.indexStart === 0 && this.indexCount === indices.length) {
-                //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
-                extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
-            }
-            else {
-                extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
-            }
-            this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
-        };
-        SubMesh.prototype._checkCollision = function (collider) {
-            return this.getBoundingInfo()._checkCollision(collider);
-        };
-        SubMesh.prototype.updateBoundingInfo = function (world) {
-            if (!this.getBoundingInfo()) {
-                this.refreshBoundingInfo();
-            }
-            this.getBoundingInfo()._update(world);
-        };
-        SubMesh.prototype.isInFrustum = function (frustumPlanes) {
-            return this.getBoundingInfo().isInFrustum(frustumPlanes);
-        };
-        SubMesh.prototype.render = function (enableAlphaMode) {
-            this._renderingMesh.render(this, enableAlphaMode);
-        };
-        SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
-            if (!this._linesIndexBuffer) {
-                var linesIndices = [];
-                for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
-                    linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
-                }
-                this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
-                this.linesIndexCount = linesIndices.length;
-            }
-            return this._linesIndexBuffer;
-        };
-        SubMesh.prototype.canIntersects = function (ray) {
-            return ray.intersectsBox(this.getBoundingInfo().boundingBox);
-        };
-        SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
-            var intersectInfo = null;
-            // Triangles test
-            for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
-                var p0 = positions[indices[index]];
-                var p1 = positions[indices[index + 1]];
-                var p2 = positions[indices[index + 2]];
-                var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
-                if (currentIntersectInfo) {
-                    if (currentIntersectInfo.distance < 0) {
-                        continue;
-                    }
-                    if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
-                        intersectInfo = currentIntersectInfo;
-                        intersectInfo.faceId = index / 3;
-                        if (fastCheck) {
-                            break;
-                        }
-                    }
-                }
-            }
-            return intersectInfo;
-        };
-        // Clone    
-        SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
-            var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
-            if (!this.IsGlobal) {
-                result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
-            }
-            return result;
-        };
-        // Dispose
-        SubMesh.prototype.dispose = function () {
-            if (this._linesIndexBuffer) {
-                this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
-                this._linesIndexBuffer = null;
-            }
-            // Remove from mesh
-            var index = this._mesh.subMeshes.indexOf(this);
-            this._mesh.subMeshes.splice(index, 1);
-        };
-        // Statics
-        SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
-            var minVertexIndex = Number.MAX_VALUE;
-            var maxVertexIndex = -Number.MAX_VALUE;
-            renderingMesh = renderingMesh || mesh;
-            var indices = renderingMesh.getIndices();
-            for (var index = startIndex; index < startIndex + indexCount; index++) {
-                var vertexIndex = indices[index];
-                if (vertexIndex < minVertexIndex)
-                    minVertexIndex = vertexIndex;
-                if (vertexIndex > maxVertexIndex)
-                    maxVertexIndex = vertexIndex;
-            }
-            return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
-        };
-        return SubMesh;
-    })();
-    BABYLON.SubMesh = SubMesh;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var SubMesh = (function () {
+        function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
+            if (createBoundingBox === void 0) { createBoundingBox = true; }
+            this.materialIndex = materialIndex;
+            this.verticesStart = verticesStart;
+            this.verticesCount = verticesCount;
+            this.indexStart = indexStart;
+            this.indexCount = indexCount;
+            this._renderId = 0;
+            this._mesh = mesh;
+            this._renderingMesh = renderingMesh || mesh;
+            mesh.subMeshes.push(this);
+            this._trianglePlanes = [];
+            this._id = mesh.subMeshes.length - 1;
+            if (createBoundingBox) {
+                this.refreshBoundingInfo();
+                mesh.computeWorldMatrix(true);
+            }
+        }
+        Object.defineProperty(SubMesh.prototype, "IsGlobal", {
+            get: function () {
+                return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
+            },
+            enumerable: true,
+            configurable: true
+        });
+        SubMesh.prototype.getBoundingInfo = function () {
+            if (this.IsGlobal) {
+                return this._mesh.getBoundingInfo();
+            }
+            return this._boundingInfo;
+        };
+        SubMesh.prototype.getMesh = function () {
+            return this._mesh;
+        };
+        SubMesh.prototype.getRenderingMesh = function () {
+            return this._renderingMesh;
+        };
+        SubMesh.prototype.getMaterial = function () {
+            var rootMaterial = this._renderingMesh.material;
+            if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
+                var multiMaterial = rootMaterial;
+                return multiMaterial.getSubMaterial(this.materialIndex);
+            }
+            if (!rootMaterial) {
+                return this._mesh.getScene().defaultMaterial;
+            }
+            return rootMaterial;
+        };
+        // Methods
+        SubMesh.prototype.refreshBoundingInfo = function () {
+            if (this.IsGlobal) {
+                return;
+            }
+            var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
+            if (!data) {
+                this._boundingInfo = this._mesh._boundingInfo;
+                return;
+            }
+            var indices = this._renderingMesh.getIndices();
+            var extend;
+            //is this the only submesh?
+            if (this.indexStart === 0 && this.indexCount === indices.length) {
+                //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
+                extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
+            }
+            else {
+                extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
+            }
+            this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
+        };
+        SubMesh.prototype._checkCollision = function (collider) {
+            return this.getBoundingInfo()._checkCollision(collider);
+        };
+        SubMesh.prototype.updateBoundingInfo = function (world) {
+            if (!this.getBoundingInfo()) {
+                this.refreshBoundingInfo();
+            }
+            this.getBoundingInfo()._update(world);
+        };
+        SubMesh.prototype.isInFrustum = function (frustumPlanes) {
+            return this.getBoundingInfo().isInFrustum(frustumPlanes);
+        };
+        SubMesh.prototype.render = function (enableAlphaMode) {
+            this._renderingMesh.render(this, enableAlphaMode);
+        };
+        SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
+            if (!this._linesIndexBuffer) {
+                var linesIndices = [];
+                for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
+                    linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
+                }
+                this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
+                this.linesIndexCount = linesIndices.length;
+            }
+            return this._linesIndexBuffer;
+        };
+        SubMesh.prototype.canIntersects = function (ray) {
+            return ray.intersectsBox(this.getBoundingInfo().boundingBox);
+        };
+        SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
+            var intersectInfo = null;
+            // Triangles test
+            for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
+                var p0 = positions[indices[index]];
+                var p1 = positions[indices[index + 1]];
+                var p2 = positions[indices[index + 2]];
+                var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
+                if (currentIntersectInfo) {
+                    if (currentIntersectInfo.distance < 0) {
+                        continue;
+                    }
+                    if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
+                        intersectInfo = currentIntersectInfo;
+                        intersectInfo.faceId = index / 3;
+                        if (fastCheck) {
+                            break;
+                        }
+                    }
+                }
+            }
+            return intersectInfo;
+        };
+        // Clone    
+        SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
+            var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
+            if (!this.IsGlobal) {
+                result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
+            }
+            return result;
+        };
+        // Dispose
+        SubMesh.prototype.dispose = function () {
+            if (this._linesIndexBuffer) {
+                this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
+                this._linesIndexBuffer = null;
+            }
+            // Remove from mesh
+            var index = this._mesh.subMeshes.indexOf(this);
+            this._mesh.subMeshes.splice(index, 1);
+        };
+        // Statics
+        SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
+            var minVertexIndex = Number.MAX_VALUE;
+            var maxVertexIndex = -Number.MAX_VALUE;
+            renderingMesh = renderingMesh || mesh;
+            var indices = renderingMesh.getIndices();
+            for (var index = startIndex; index < startIndex + indexCount; index++) {
+                var vertexIndex = indices[index];
+                if (vertexIndex < minVertexIndex)
+                    minVertexIndex = vertexIndex;
+                if (vertexIndex > maxVertexIndex)
+                    maxVertexIndex = vertexIndex;
+            }
+            return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
+        };
+        return SubMesh;
+    })();
+    BABYLON.SubMesh = SubMesh;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.subMesh.js.map

+ 1 - 1
src/Mesh/babylon.subMesh.ts

@@ -98,7 +98,7 @@
             if (!this.getBoundingInfo()) {
                 this.refreshBoundingInfo();
             }
-            this.getBoundingInfo()._update(world);
+            this.getBoundingInfo().update(world);
         }
 
         public isInFrustum(frustumPlanes: Plane[]): boolean {

+ 211 - 210
src/Mesh/babylon.vertexBuffer.js

@@ -1,210 +1,211 @@
-var BABYLON;
-(function (BABYLON) {
-    var VertexBuffer = (function () {
-        function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
-            if (engine instanceof BABYLON.Mesh) {
-                this._engine = engine.getScene().getEngine();
-            }
-            else {
-                this._engine = engine;
-            }
-            this._updatable = updatable;
-            this._data = data;
-            if (!postponeInternalCreation) {
-                this.create();
-            }
-            this._kind = kind;
-            if (stride) {
-                this._strideSize = stride;
-                return;
-            }
-            // Deduce stride from kind
-            switch (kind) {
-                case VertexBuffer.PositionKind:
-                    this._strideSize = 3;
-                    break;
-                case VertexBuffer.NormalKind:
-                    this._strideSize = 3;
-                    break;
-                case VertexBuffer.UVKind:
-                case VertexBuffer.UV2Kind:
-                case VertexBuffer.UV3Kind:
-                case VertexBuffer.UV4Kind:
-                case VertexBuffer.UV5Kind:
-                case VertexBuffer.UV6Kind:
-                    this._strideSize = 2;
-                    break;
-                case VertexBuffer.ColorKind:
-                    this._strideSize = 4;
-                    break;
-                case VertexBuffer.MatricesIndicesKind:
-                case VertexBuffer.MatricesIndicesExtraKind:
-                    this._strideSize = 4;
-                    break;
-                case VertexBuffer.MatricesWeightsKind:
-                case VertexBuffer.MatricesWeightsExtraKind:
-                    this._strideSize = 4;
-                    break;
-            }
-        }
-        // Properties
-        VertexBuffer.prototype.isUpdatable = function () {
-            return this._updatable;
-        };
-        VertexBuffer.prototype.getData = function () {
-            return this._data;
-        };
-        VertexBuffer.prototype.getBuffer = function () {
-            return this._buffer;
-        };
-        VertexBuffer.prototype.getStrideSize = function () {
-            return this._strideSize;
-        };
-        // Methods
-        VertexBuffer.prototype.create = function (data) {
-            if (!data && this._buffer) {
-                return; // nothing to do
-            }
-            data = data || this._data;
-            if (!this._buffer) {
-                if (this._updatable) {
-                    this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
-                }
-                else {
-                    this._buffer = this._engine.createVertexBuffer(data);
-                }
-            }
-            if (this._updatable) {
-                this._engine.updateDynamicVertexBuffer(this._buffer, data);
-                this._data = data;
-            }
-        };
-        VertexBuffer.prototype.update = function (data) {
-            this.create(data);
-        };
-        VertexBuffer.prototype.updateDirectly = function (data, offset) {
-            if (!this._buffer) {
-                return;
-            }
-            if (this._updatable) {
-                this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
-                this._data = null;
-            }
-        };
-        VertexBuffer.prototype.dispose = function () {
-            if (!this._buffer) {
-                return;
-            }
-            if (this._engine._releaseBuffer(this._buffer)) {
-                this._buffer = null;
-            }
-        };
-        Object.defineProperty(VertexBuffer, "PositionKind", {
-            get: function () {
-                return VertexBuffer._PositionKind;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VertexBuffer, "NormalKind", {
-            get: function () {
-                return VertexBuffer._NormalKind;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VertexBuffer, "UVKind", {
-            get: function () {
-                return VertexBuffer._UVKind;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VertexBuffer, "UV2Kind", {
-            get: function () {
-                return VertexBuffer._UV2Kind;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VertexBuffer, "UV3Kind", {
-            get: function () {
-                return VertexBuffer._UV3Kind;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VertexBuffer, "UV4Kind", {
-            get: function () {
-                return VertexBuffer._UV4Kind;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VertexBuffer, "UV5Kind", {
-            get: function () {
-                return VertexBuffer._UV5Kind;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VertexBuffer, "UV6Kind", {
-            get: function () {
-                return VertexBuffer._UV6Kind;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VertexBuffer, "ColorKind", {
-            get: function () {
-                return VertexBuffer._ColorKind;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
-            get: function () {
-                return VertexBuffer._MatricesIndicesKind;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
-            get: function () {
-                return VertexBuffer._MatricesWeightsKind;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
-            get: function () {
-                return VertexBuffer._MatricesIndicesExtraKind;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
-            get: function () {
-                return VertexBuffer._MatricesWeightsExtraKind;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        // Enums
-        VertexBuffer._PositionKind = "position";
-        VertexBuffer._NormalKind = "normal";
-        VertexBuffer._UVKind = "uv";
-        VertexBuffer._UV2Kind = "uv2";
-        VertexBuffer._UV3Kind = "uv3";
-        VertexBuffer._UV4Kind = "uv4";
-        VertexBuffer._UV5Kind = "uv5";
-        VertexBuffer._UV6Kind = "uv6";
-        VertexBuffer._ColorKind = "color";
-        VertexBuffer._MatricesIndicesKind = "matricesIndices";
-        VertexBuffer._MatricesWeightsKind = "matricesWeights";
-        VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
-        VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
-        return VertexBuffer;
-    })();
-    BABYLON.VertexBuffer = VertexBuffer;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var VertexBuffer = (function () {
+        function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
+            if (engine instanceof BABYLON.Mesh) {
+                this._engine = engine.getScene().getEngine();
+            }
+            else {
+                this._engine = engine;
+            }
+            this._updatable = updatable;
+            this._data = data;
+            if (!postponeInternalCreation) {
+                this.create();
+            }
+            this._kind = kind;
+            if (stride) {
+                this._strideSize = stride;
+                return;
+            }
+            // Deduce stride from kind
+            switch (kind) {
+                case VertexBuffer.PositionKind:
+                    this._strideSize = 3;
+                    break;
+                case VertexBuffer.NormalKind:
+                    this._strideSize = 3;
+                    break;
+                case VertexBuffer.UVKind:
+                case VertexBuffer.UV2Kind:
+                case VertexBuffer.UV3Kind:
+                case VertexBuffer.UV4Kind:
+                case VertexBuffer.UV5Kind:
+                case VertexBuffer.UV6Kind:
+                    this._strideSize = 2;
+                    break;
+                case VertexBuffer.ColorKind:
+                    this._strideSize = 4;
+                    break;
+                case VertexBuffer.MatricesIndicesKind:
+                case VertexBuffer.MatricesIndicesExtraKind:
+                    this._strideSize = 4;
+                    break;
+                case VertexBuffer.MatricesWeightsKind:
+                case VertexBuffer.MatricesWeightsExtraKind:
+                    this._strideSize = 4;
+                    break;
+            }
+        }
+        // Properties
+        VertexBuffer.prototype.isUpdatable = function () {
+            return this._updatable;
+        };
+        VertexBuffer.prototype.getData = function () {
+            return this._data;
+        };
+        VertexBuffer.prototype.getBuffer = function () {
+            return this._buffer;
+        };
+        VertexBuffer.prototype.getStrideSize = function () {
+            return this._strideSize;
+        };
+        // Methods
+        VertexBuffer.prototype.create = function (data) {
+            if (!data && this._buffer) {
+                return; // nothing to do
+            }
+            data = data || this._data;
+            if (!this._buffer) {
+                if (this._updatable) {
+                    this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
+                }
+                else {
+                    this._buffer = this._engine.createVertexBuffer(data);
+                }
+            }
+            if (this._updatable) {
+                this._engine.updateDynamicVertexBuffer(this._buffer, data);
+                this._data = data;
+            }
+        };
+        VertexBuffer.prototype.update = function (data) {
+            this.create(data);
+        };
+        VertexBuffer.prototype.updateDirectly = function (data, offset) {
+            if (!this._buffer) {
+                return;
+            }
+            if (this._updatable) {
+                this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
+                this._data = null;
+            }
+        };
+        VertexBuffer.prototype.dispose = function () {
+            if (!this._buffer) {
+                return;
+            }
+            if (this._engine._releaseBuffer(this._buffer)) {
+                this._buffer = null;
+            }
+        };
+        Object.defineProperty(VertexBuffer, "PositionKind", {
+            get: function () {
+                return VertexBuffer._PositionKind;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VertexBuffer, "NormalKind", {
+            get: function () {
+                return VertexBuffer._NormalKind;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VertexBuffer, "UVKind", {
+            get: function () {
+                return VertexBuffer._UVKind;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VertexBuffer, "UV2Kind", {
+            get: function () {
+                return VertexBuffer._UV2Kind;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VertexBuffer, "UV3Kind", {
+            get: function () {
+                return VertexBuffer._UV3Kind;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VertexBuffer, "UV4Kind", {
+            get: function () {
+                return VertexBuffer._UV4Kind;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VertexBuffer, "UV5Kind", {
+            get: function () {
+                return VertexBuffer._UV5Kind;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VertexBuffer, "UV6Kind", {
+            get: function () {
+                return VertexBuffer._UV6Kind;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VertexBuffer, "ColorKind", {
+            get: function () {
+                return VertexBuffer._ColorKind;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
+            get: function () {
+                return VertexBuffer._MatricesIndicesKind;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
+            get: function () {
+                return VertexBuffer._MatricesWeightsKind;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
+            get: function () {
+                return VertexBuffer._MatricesIndicesExtraKind;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
+            get: function () {
+                return VertexBuffer._MatricesWeightsExtraKind;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        // Enums
+        VertexBuffer._PositionKind = "position";
+        VertexBuffer._NormalKind = "normal";
+        VertexBuffer._UVKind = "uv";
+        VertexBuffer._UV2Kind = "uv2";
+        VertexBuffer._UV3Kind = "uv3";
+        VertexBuffer._UV4Kind = "uv4";
+        VertexBuffer._UV5Kind = "uv5";
+        VertexBuffer._UV6Kind = "uv6";
+        VertexBuffer._ColorKind = "color";
+        VertexBuffer._MatricesIndicesKind = "matricesIndices";
+        VertexBuffer._MatricesWeightsKind = "matricesWeights";
+        VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
+        VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
+        return VertexBuffer;
+    })();
+    BABYLON.VertexBuffer = VertexBuffer;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.vertexBuffer.js.map

+ 30 - 29
src/Particles/babylon.particle.js

@@ -1,29 +1,30 @@
-var BABYLON;
-(function (BABYLON) {
-    var Particle = (function () {
-        function Particle() {
-            this.position = BABYLON.Vector3.Zero();
-            this.direction = BABYLON.Vector3.Zero();
-            this.color = new BABYLON.Color4(0, 0, 0, 0);
-            this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
-            this.lifeTime = 1.0;
-            this.age = 0;
-            this.size = 0;
-            this.angle = 0;
-            this.angularSpeed = 0;
-        }
-        Particle.prototype.copyTo = function (other) {
-            other.position.copyFrom(this.position);
-            other.direction.copyFrom(this.direction);
-            other.color.copyFrom(this.color);
-            other.colorStep.copyFrom(this.colorStep);
-            other.lifeTime = this.lifeTime;
-            other.age = this.age;
-            other.size = this.size;
-            other.angle = this.angle;
-            other.angularSpeed = this.angularSpeed;
-        };
-        return Particle;
-    })();
-    BABYLON.Particle = Particle;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var Particle = (function () {
+        function Particle() {
+            this.position = BABYLON.Vector3.Zero();
+            this.direction = BABYLON.Vector3.Zero();
+            this.color = new BABYLON.Color4(0, 0, 0, 0);
+            this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
+            this.lifeTime = 1.0;
+            this.age = 0;
+            this.size = 0;
+            this.angle = 0;
+            this.angularSpeed = 0;
+        }
+        Particle.prototype.copyTo = function (other) {
+            other.position.copyFrom(this.position);
+            other.direction.copyFrom(this.direction);
+            other.color.copyFrom(this.color);
+            other.colorStep.copyFrom(this.colorStep);
+            other.lifeTime = this.lifeTime;
+            other.age = this.age;
+            other.size = this.size;
+            other.angle = this.angle;
+            other.angularSpeed = this.angularSpeed;
+        };
+        return Particle;
+    })();
+    BABYLON.Particle = Particle;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.particle.js.map

+ 413 - 412
src/Particles/babylon.particleSystem.js

@@ -1,412 +1,413 @@
-var BABYLON;
-(function (BABYLON) {
-    var randomNumber = function (min, max) {
-        if (min === max) {
-            return (min);
-        }
-        var random = Math.random();
-        return ((random * (max - min)) + min);
-    };
-    var ParticleSystem = (function () {
-        function ParticleSystem(name, capacity, scene, customEffect) {
-            var _this = this;
-            this.name = name;
-            this.renderingGroupId = 0;
-            this.emitter = null;
-            this.emitRate = 10;
-            this.manualEmitCount = -1;
-            this.updateSpeed = 0.01;
-            this.targetStopDuration = 0;
-            this.disposeOnStop = false;
-            this.minEmitPower = 1;
-            this.maxEmitPower = 1;
-            this.minLifeTime = 1;
-            this.maxLifeTime = 1;
-            this.minSize = 1;
-            this.maxSize = 1;
-            this.minAngularSpeed = 0;
-            this.maxAngularSpeed = 0;
-            this.layerMask = 0x0FFFFFFF;
-            this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
-            this.forceDepthWrite = false;
-            this.gravity = BABYLON.Vector3.Zero();
-            this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
-            this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
-            this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
-            this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
-            this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
-            this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
-            this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
-            this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
-            this.particles = new Array();
-            this._vertexDeclaration = [3, 4, 4];
-            this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
-            this._stockParticles = new Array();
-            this._newPartsExcess = 0;
-            this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
-            this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
-            this._scaledDirection = BABYLON.Vector3.Zero();
-            this._scaledGravity = BABYLON.Vector3.Zero();
-            this._currentRenderId = -1;
-            this._started = false;
-            this._stopped = false;
-            this._actualFrame = 0;
-            this.id = name;
-            this._capacity = capacity;
-            this._scene = scene;
-            this._customEffect = customEffect;
-            scene.particleSystems.push(this);
-            // VBO
-            this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
-            var indices = [];
-            var index = 0;
-            for (var count = 0; count < capacity; count++) {
-                indices.push(index);
-                indices.push(index + 1);
-                indices.push(index + 2);
-                indices.push(index);
-                indices.push(index + 2);
-                indices.push(index + 3);
-                index += 4;
-            }
-            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
-            this._vertices = new Float32Array(capacity * this._vertexStrideSize);
-            // Default behaviors
-            this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
-                var randX = randomNumber(_this.direction1.x, _this.direction2.x);
-                var randY = randomNumber(_this.direction1.y, _this.direction2.y);
-                var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
-                BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
-            };
-            this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
-                var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
-                var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
-                var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
-                BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
-            };
-            this.updateFunction = function (particles) {
-                for (var index = 0; index < particles.length; index++) {
-                    var particle = particles[index];
-                    particle.age += _this._scaledUpdateSpeed;
-                    if (particle.age >= particle.lifeTime) {
-                        _this.recycleParticle(particle);
-                        index--;
-                        continue;
-                    }
-                    else {
-                        particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
-                        particle.color.addInPlace(_this._scaledColorStep);
-                        if (particle.color.a < 0)
-                            particle.color.a = 0;
-                        particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
-                        particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
-                        particle.position.addInPlace(_this._scaledDirection);
-                        _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
-                        particle.direction.addInPlace(_this._scaledGravity);
-                    }
-                }
-            };
-        }
-        ParticleSystem.prototype.recycleParticle = function (particle) {
-            var lastParticle = this.particles.pop();
-            if (lastParticle !== particle) {
-                lastParticle.copyTo(particle);
-                this._stockParticles.push(lastParticle);
-            }
-        };
-        ParticleSystem.prototype.getCapacity = function () {
-            return this._capacity;
-        };
-        ParticleSystem.prototype.isAlive = function () {
-            return this._alive;
-        };
-        ParticleSystem.prototype.isStarted = function () {
-            return this._started;
-        };
-        ParticleSystem.prototype.start = function () {
-            this._started = true;
-            this._stopped = false;
-            this._actualFrame = 0;
-        };
-        ParticleSystem.prototype.stop = function () {
-            this._stopped = true;
-        };
-        ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
-            var offset = index * 11;
-            this._vertices[offset] = particle.position.x;
-            this._vertices[offset + 1] = particle.position.y;
-            this._vertices[offset + 2] = particle.position.z;
-            this._vertices[offset + 3] = particle.color.r;
-            this._vertices[offset + 4] = particle.color.g;
-            this._vertices[offset + 5] = particle.color.b;
-            this._vertices[offset + 6] = particle.color.a;
-            this._vertices[offset + 7] = particle.angle;
-            this._vertices[offset + 8] = particle.size;
-            this._vertices[offset + 9] = offsetX;
-            this._vertices[offset + 10] = offsetY;
-        };
-        ParticleSystem.prototype._update = function (newParticles) {
-            // Update current
-            this._alive = this.particles.length > 0;
-            this.updateFunction(this.particles);
-            // Add new ones
-            var worldMatrix;
-            if (this.emitter.position) {
-                worldMatrix = this.emitter.getWorldMatrix();
-            }
-            else {
-                worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
-            }
-            var particle;
-            for (var index = 0; index < newParticles; index++) {
-                if (this.particles.length === this._capacity) {
-                    break;
-                }
-                if (this._stockParticles.length !== 0) {
-                    particle = this._stockParticles.pop();
-                    particle.age = 0;
-                }
-                else {
-                    particle = new BABYLON.Particle();
-                }
-                this.particles.push(particle);
-                var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
-                this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
-                particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
-                particle.size = randomNumber(this.minSize, this.maxSize);
-                particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
-                this.startPositionFunction(worldMatrix, particle.position, particle);
-                var step = randomNumber(0, 1.0);
-                BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
-                this.colorDead.subtractToRef(particle.color, this._colorDiff);
-                this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
-            }
-        };
-        ParticleSystem.prototype._getEffect = function () {
-            if (this._customEffect) {
-                return this._customEffect;
-            }
-            ;
-            var defines = [];
-            if (this._scene.clipPlane) {
-                defines.push("#define CLIPPLANE");
-            }
-            // Effect
-            var join = defines.join("\n");
-            if (this._cachedDefines !== join) {
-                this._cachedDefines = join;
-                this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
-            }
-            return this._effect;
-        };
-        ParticleSystem.prototype.animate = function () {
-            if (!this._started)
-                return;
-            var effect = this._getEffect();
-            // Check
-            if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
-                return;
-            if (this._currentRenderId === this._scene.getRenderId()) {
-                return;
-            }
-            this._currentRenderId = this._scene.getRenderId();
-            this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
-            // determine the number of particles we need to create   
-            var newParticles;
-            if (this.manualEmitCount > -1) {
-                newParticles = this.manualEmitCount;
-                this._newPartsExcess = 0;
-                this.manualEmitCount = 0;
-            }
-            else {
-                newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
-                this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
-            }
-            if (this._newPartsExcess > 1.0) {
-                newParticles += this._newPartsExcess >> 0;
-                this._newPartsExcess -= this._newPartsExcess >> 0;
-            }
-            this._alive = false;
-            if (!this._stopped) {
-                this._actualFrame += this._scaledUpdateSpeed;
-                if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
-                    this.stop();
-            }
-            else {
-                newParticles = 0;
-            }
-            this._update(newParticles);
-            // Stopped?
-            if (this._stopped) {
-                if (!this._alive) {
-                    this._started = false;
-                    if (this.disposeOnStop) {
-                        this._scene._toBeDisposed.push(this);
-                    }
-                }
-            }
-            // Update VBO
-            var offset = 0;
-            for (var index = 0; index < this.particles.length; index++) {
-                var particle = this.particles[index];
-                this._appendParticleVertex(offset++, particle, 0, 0);
-                this._appendParticleVertex(offset++, particle, 1, 0);
-                this._appendParticleVertex(offset++, particle, 1, 1);
-                this._appendParticleVertex(offset++, particle, 0, 1);
-            }
-            var engine = this._scene.getEngine();
-            engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
-        };
-        ParticleSystem.prototype.render = function () {
-            var effect = this._getEffect();
-            // Check
-            if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
-                return 0;
-            var engine = this._scene.getEngine();
-            // Render
-            engine.enableEffect(effect);
-            engine.setState(false);
-            var viewMatrix = this._scene.getViewMatrix();
-            effect.setTexture("diffuseSampler", this.particleTexture);
-            effect.setMatrix("view", viewMatrix);
-            effect.setMatrix("projection", this._scene.getProjectionMatrix());
-            effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
-            if (this._scene.clipPlane) {
-                var clipPlane = this._scene.clipPlane;
-                var invView = viewMatrix.clone();
-                invView.invert();
-                effect.setMatrix("invView", invView);
-                effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
-            }
-            // VBOs
-            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
-            // Draw order
-            if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
-                engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
-            }
-            else {
-                engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
-            }
-            if (this.forceDepthWrite) {
-                engine.setDepthWrite(true);
-            }
-            engine.draw(true, 0, this.particles.length * 6);
-            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
-            return this.particles.length;
-        };
-        ParticleSystem.prototype.dispose = function () {
-            if (this._vertexBuffer) {
-                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
-                this._vertexBuffer = null;
-            }
-            if (this._indexBuffer) {
-                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
-                this._indexBuffer = null;
-            }
-            if (this.particleTexture) {
-                this.particleTexture.dispose();
-                this.particleTexture = null;
-            }
-            // Remove from scene
-            var index = this._scene.particleSystems.indexOf(this);
-            this._scene.particleSystems.splice(index, 1);
-            // Callback
-            if (this.onDispose) {
-                this.onDispose();
-            }
-        };
-        // Clone
-        ParticleSystem.prototype.clone = function (name, newEmitter) {
-            var result = new ParticleSystem(name, this._capacity, this._scene);
-            BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
-            if (newEmitter === undefined) {
-                newEmitter = this.emitter;
-            }
-            result.emitter = newEmitter;
-            if (this.particleTexture) {
-                result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
-            }
-            result.start();
-            return result;
-        };
-        ParticleSystem.prototype.serialize = function () {
-            var serializationObject = {};
-            serializationObject.name = this.name;
-            if (this.emitter.position) {
-                serializationObject.emitterId = this.emitter.id;
-            }
-            else {
-                serializationObject.emitter = this.emitter.asArray();
-                ;
-            }
-            serializationObject.capacity = this.getCapacity();
-            if (this.particleTexture) {
-                serializationObject.textureName = this.particleTexture.name;
-            }
-            serializationObject.minAngularSpeed = this.minAngularSpeed;
-            serializationObject.maxAngularSpeed = this.maxAngularSpeed;
-            serializationObject.minSize = this.minSize;
-            serializationObject.maxSize = this.maxSize;
-            serializationObject.minEmitPower = this.minEmitPower;
-            serializationObject.maxEmitPower = this.maxEmitPower;
-            serializationObject.minLifeTime = this.minLifeTime;
-            serializationObject.maxLifeTime = this.maxLifeTime;
-            serializationObject.emitRate = this.emitRate;
-            serializationObject.minEmitBox = this.minEmitBox.asArray();
-            serializationObject.maxEmitBox = this.maxEmitBox.asArray();
-            serializationObject.gravity = this.gravity.asArray();
-            serializationObject.direction1 = this.direction1.asArray();
-            serializationObject.direction2 = this.direction2.asArray();
-            serializationObject.color1 = this.color1.asArray();
-            serializationObject.color2 = this.color2.asArray();
-            serializationObject.colorDead = this.colorDead.asArray();
-            serializationObject.updateSpeed = this.updateSpeed;
-            serializationObject.targetStopDuration = this.targetStopDuration;
-            serializationObject.textureMask = this.textureMask.asArray();
-            serializationObject.blendMode = this.blendMode;
-            return serializationObject;
-        };
-        ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
-            var name = parsedParticleSystem.name;
-            var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
-            if (parsedParticleSystem.textureName) {
-                particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
-                particleSystem.particleTexture.name = parsedParticleSystem.textureName;
-            }
-            if (parsedParticleSystem.emitterId) {
-                particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
-            }
-            else {
-                particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
-            }
-            particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
-            particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
-            particleSystem.minSize = parsedParticleSystem.minSize;
-            particleSystem.maxSize = parsedParticleSystem.maxSize;
-            particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
-            particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
-            particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
-            particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
-            particleSystem.emitRate = parsedParticleSystem.emitRate;
-            particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
-            particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
-            particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
-            particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
-            particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
-            particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
-            particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
-            particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
-            particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
-            particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
-            particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
-            particleSystem.blendMode = parsedParticleSystem.blendMode;
-            particleSystem.start();
-            return particleSystem;
-        };
-        // Statics
-        ParticleSystem.BLENDMODE_ONEONE = 0;
-        ParticleSystem.BLENDMODE_STANDARD = 1;
-        return ParticleSystem;
-    })();
-    BABYLON.ParticleSystem = ParticleSystem;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var randomNumber = function (min, max) {
+        if (min === max) {
+            return (min);
+        }
+        var random = Math.random();
+        return ((random * (max - min)) + min);
+    };
+    var ParticleSystem = (function () {
+        function ParticleSystem(name, capacity, scene, customEffect) {
+            var _this = this;
+            this.name = name;
+            this.renderingGroupId = 0;
+            this.emitter = null;
+            this.emitRate = 10;
+            this.manualEmitCount = -1;
+            this.updateSpeed = 0.01;
+            this.targetStopDuration = 0;
+            this.disposeOnStop = false;
+            this.minEmitPower = 1;
+            this.maxEmitPower = 1;
+            this.minLifeTime = 1;
+            this.maxLifeTime = 1;
+            this.minSize = 1;
+            this.maxSize = 1;
+            this.minAngularSpeed = 0;
+            this.maxAngularSpeed = 0;
+            this.layerMask = 0x0FFFFFFF;
+            this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
+            this.forceDepthWrite = false;
+            this.gravity = BABYLON.Vector3.Zero();
+            this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
+            this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
+            this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
+            this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
+            this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
+            this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
+            this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
+            this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
+            this.particles = new Array();
+            this._vertexDeclaration = [3, 4, 4];
+            this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
+            this._stockParticles = new Array();
+            this._newPartsExcess = 0;
+            this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
+            this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
+            this._scaledDirection = BABYLON.Vector3.Zero();
+            this._scaledGravity = BABYLON.Vector3.Zero();
+            this._currentRenderId = -1;
+            this._started = false;
+            this._stopped = false;
+            this._actualFrame = 0;
+            this.id = name;
+            this._capacity = capacity;
+            this._scene = scene;
+            this._customEffect = customEffect;
+            scene.particleSystems.push(this);
+            // VBO
+            this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
+            var indices = [];
+            var index = 0;
+            for (var count = 0; count < capacity; count++) {
+                indices.push(index);
+                indices.push(index + 1);
+                indices.push(index + 2);
+                indices.push(index);
+                indices.push(index + 2);
+                indices.push(index + 3);
+                index += 4;
+            }
+            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
+            this._vertices = new Float32Array(capacity * this._vertexStrideSize);
+            // Default behaviors
+            this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
+                var randX = randomNumber(_this.direction1.x, _this.direction2.x);
+                var randY = randomNumber(_this.direction1.y, _this.direction2.y);
+                var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
+                BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
+            };
+            this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
+                var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
+                var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
+                var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
+                BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
+            };
+            this.updateFunction = function (particles) {
+                for (var index = 0; index < particles.length; index++) {
+                    var particle = particles[index];
+                    particle.age += _this._scaledUpdateSpeed;
+                    if (particle.age >= particle.lifeTime) {
+                        _this.recycleParticle(particle);
+                        index--;
+                        continue;
+                    }
+                    else {
+                        particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
+                        particle.color.addInPlace(_this._scaledColorStep);
+                        if (particle.color.a < 0)
+                            particle.color.a = 0;
+                        particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
+                        particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
+                        particle.position.addInPlace(_this._scaledDirection);
+                        _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
+                        particle.direction.addInPlace(_this._scaledGravity);
+                    }
+                }
+            };
+        }
+        ParticleSystem.prototype.recycleParticle = function (particle) {
+            var lastParticle = this.particles.pop();
+            if (lastParticle !== particle) {
+                lastParticle.copyTo(particle);
+                this._stockParticles.push(lastParticle);
+            }
+        };
+        ParticleSystem.prototype.getCapacity = function () {
+            return this._capacity;
+        };
+        ParticleSystem.prototype.isAlive = function () {
+            return this._alive;
+        };
+        ParticleSystem.prototype.isStarted = function () {
+            return this._started;
+        };
+        ParticleSystem.prototype.start = function () {
+            this._started = true;
+            this._stopped = false;
+            this._actualFrame = 0;
+        };
+        ParticleSystem.prototype.stop = function () {
+            this._stopped = true;
+        };
+        ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
+            var offset = index * 11;
+            this._vertices[offset] = particle.position.x;
+            this._vertices[offset + 1] = particle.position.y;
+            this._vertices[offset + 2] = particle.position.z;
+            this._vertices[offset + 3] = particle.color.r;
+            this._vertices[offset + 4] = particle.color.g;
+            this._vertices[offset + 5] = particle.color.b;
+            this._vertices[offset + 6] = particle.color.a;
+            this._vertices[offset + 7] = particle.angle;
+            this._vertices[offset + 8] = particle.size;
+            this._vertices[offset + 9] = offsetX;
+            this._vertices[offset + 10] = offsetY;
+        };
+        ParticleSystem.prototype._update = function (newParticles) {
+            // Update current
+            this._alive = this.particles.length > 0;
+            this.updateFunction(this.particles);
+            // Add new ones
+            var worldMatrix;
+            if (this.emitter.position) {
+                worldMatrix = this.emitter.getWorldMatrix();
+            }
+            else {
+                worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
+            }
+            var particle;
+            for (var index = 0; index < newParticles; index++) {
+                if (this.particles.length === this._capacity) {
+                    break;
+                }
+                if (this._stockParticles.length !== 0) {
+                    particle = this._stockParticles.pop();
+                    particle.age = 0;
+                }
+                else {
+                    particle = new BABYLON.Particle();
+                }
+                this.particles.push(particle);
+                var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
+                this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
+                particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
+                particle.size = randomNumber(this.minSize, this.maxSize);
+                particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
+                this.startPositionFunction(worldMatrix, particle.position, particle);
+                var step = randomNumber(0, 1.0);
+                BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
+                this.colorDead.subtractToRef(particle.color, this._colorDiff);
+                this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
+            }
+        };
+        ParticleSystem.prototype._getEffect = function () {
+            if (this._customEffect) {
+                return this._customEffect;
+            }
+            ;
+            var defines = [];
+            if (this._scene.clipPlane) {
+                defines.push("#define CLIPPLANE");
+            }
+            // Effect
+            var join = defines.join("\n");
+            if (this._cachedDefines !== join) {
+                this._cachedDefines = join;
+                this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
+            }
+            return this._effect;
+        };
+        ParticleSystem.prototype.animate = function () {
+            if (!this._started)
+                return;
+            var effect = this._getEffect();
+            // Check
+            if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
+                return;
+            if (this._currentRenderId === this._scene.getRenderId()) {
+                return;
+            }
+            this._currentRenderId = this._scene.getRenderId();
+            this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
+            // determine the number of particles we need to create   
+            var newParticles;
+            if (this.manualEmitCount > -1) {
+                newParticles = this.manualEmitCount;
+                this._newPartsExcess = 0;
+                this.manualEmitCount = 0;
+            }
+            else {
+                newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
+                this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
+            }
+            if (this._newPartsExcess > 1.0) {
+                newParticles += this._newPartsExcess >> 0;
+                this._newPartsExcess -= this._newPartsExcess >> 0;
+            }
+            this._alive = false;
+            if (!this._stopped) {
+                this._actualFrame += this._scaledUpdateSpeed;
+                if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
+                    this.stop();
+            }
+            else {
+                newParticles = 0;
+            }
+            this._update(newParticles);
+            // Stopped?
+            if (this._stopped) {
+                if (!this._alive) {
+                    this._started = false;
+                    if (this.disposeOnStop) {
+                        this._scene._toBeDisposed.push(this);
+                    }
+                }
+            }
+            // Update VBO
+            var offset = 0;
+            for (var index = 0; index < this.particles.length; index++) {
+                var particle = this.particles[index];
+                this._appendParticleVertex(offset++, particle, 0, 0);
+                this._appendParticleVertex(offset++, particle, 1, 0);
+                this._appendParticleVertex(offset++, particle, 1, 1);
+                this._appendParticleVertex(offset++, particle, 0, 1);
+            }
+            var engine = this._scene.getEngine();
+            engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
+        };
+        ParticleSystem.prototype.render = function () {
+            var effect = this._getEffect();
+            // Check
+            if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
+                return 0;
+            var engine = this._scene.getEngine();
+            // Render
+            engine.enableEffect(effect);
+            engine.setState(false);
+            var viewMatrix = this._scene.getViewMatrix();
+            effect.setTexture("diffuseSampler", this.particleTexture);
+            effect.setMatrix("view", viewMatrix);
+            effect.setMatrix("projection", this._scene.getProjectionMatrix());
+            effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
+            if (this._scene.clipPlane) {
+                var clipPlane = this._scene.clipPlane;
+                var invView = viewMatrix.clone();
+                invView.invert();
+                effect.setMatrix("invView", invView);
+                effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
+            }
+            // VBOs
+            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
+            // Draw order
+            if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
+                engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
+            }
+            else {
+                engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
+            }
+            if (this.forceDepthWrite) {
+                engine.setDepthWrite(true);
+            }
+            engine.draw(true, 0, this.particles.length * 6);
+            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
+            return this.particles.length;
+        };
+        ParticleSystem.prototype.dispose = function () {
+            if (this._vertexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
+                this._vertexBuffer = null;
+            }
+            if (this._indexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
+                this._indexBuffer = null;
+            }
+            if (this.particleTexture) {
+                this.particleTexture.dispose();
+                this.particleTexture = null;
+            }
+            // Remove from scene
+            var index = this._scene.particleSystems.indexOf(this);
+            this._scene.particleSystems.splice(index, 1);
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        };
+        // Clone
+        ParticleSystem.prototype.clone = function (name, newEmitter) {
+            var result = new ParticleSystem(name, this._capacity, this._scene);
+            BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
+            if (newEmitter === undefined) {
+                newEmitter = this.emitter;
+            }
+            result.emitter = newEmitter;
+            if (this.particleTexture) {
+                result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
+            }
+            result.start();
+            return result;
+        };
+        ParticleSystem.prototype.serialize = function () {
+            var serializationObject = {};
+            serializationObject.name = this.name;
+            if (this.emitter.position) {
+                serializationObject.emitterId = this.emitter.id;
+            }
+            else {
+                serializationObject.emitter = this.emitter.asArray();
+                ;
+            }
+            serializationObject.capacity = this.getCapacity();
+            if (this.particleTexture) {
+                serializationObject.textureName = this.particleTexture.name;
+            }
+            serializationObject.minAngularSpeed = this.minAngularSpeed;
+            serializationObject.maxAngularSpeed = this.maxAngularSpeed;
+            serializationObject.minSize = this.minSize;
+            serializationObject.maxSize = this.maxSize;
+            serializationObject.minEmitPower = this.minEmitPower;
+            serializationObject.maxEmitPower = this.maxEmitPower;
+            serializationObject.minLifeTime = this.minLifeTime;
+            serializationObject.maxLifeTime = this.maxLifeTime;
+            serializationObject.emitRate = this.emitRate;
+            serializationObject.minEmitBox = this.minEmitBox.asArray();
+            serializationObject.maxEmitBox = this.maxEmitBox.asArray();
+            serializationObject.gravity = this.gravity.asArray();
+            serializationObject.direction1 = this.direction1.asArray();
+            serializationObject.direction2 = this.direction2.asArray();
+            serializationObject.color1 = this.color1.asArray();
+            serializationObject.color2 = this.color2.asArray();
+            serializationObject.colorDead = this.colorDead.asArray();
+            serializationObject.updateSpeed = this.updateSpeed;
+            serializationObject.targetStopDuration = this.targetStopDuration;
+            serializationObject.textureMask = this.textureMask.asArray();
+            serializationObject.blendMode = this.blendMode;
+            return serializationObject;
+        };
+        ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
+            var name = parsedParticleSystem.name;
+            var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
+            if (parsedParticleSystem.textureName) {
+                particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
+                particleSystem.particleTexture.name = parsedParticleSystem.textureName;
+            }
+            if (parsedParticleSystem.emitterId) {
+                particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
+            }
+            else {
+                particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
+            }
+            particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
+            particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
+            particleSystem.minSize = parsedParticleSystem.minSize;
+            particleSystem.maxSize = parsedParticleSystem.maxSize;
+            particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
+            particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
+            particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
+            particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
+            particleSystem.emitRate = parsedParticleSystem.emitRate;
+            particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
+            particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
+            particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
+            particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
+            particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
+            particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
+            particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
+            particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
+            particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
+            particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
+            particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
+            particleSystem.blendMode = parsedParticleSystem.blendMode;
+            particleSystem.start();
+            return particleSystem;
+        };
+        // Statics
+        ParticleSystem.BLENDMODE_ONEONE = 0;
+        ParticleSystem.BLENDMODE_STANDARD = 1;
+        return ParticleSystem;
+    })();
+    BABYLON.ParticleSystem = ParticleSystem;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.particleSystem.js.map

+ 33 - 32
src/Particles/babylon.solidParticle.js

@@ -1,32 +1,33 @@
-var BABYLON;
-(function (BABYLON) {
-    var SolidParticle = (function () {
-        function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
-            this.color = new BABYLON.Color4(1, 1, 1, 1); // color
-            this.position = BABYLON.Vector3.Zero(); // position
-            this.rotation = BABYLON.Vector3.Zero(); // rotation
-            this.scale = new BABYLON.Vector3(1, 1, 1); // scale
-            this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
-            this.velocity = BABYLON.Vector3.Zero(); // velocity
-            this.alive = true; // alive
-            this.idx = particleIndex;
-            this._pos = positionIndex;
-            this._model = model;
-            this.shapeId = shapeId;
-            this.idxInShape = idxInShape;
-        }
-        return SolidParticle;
-    })();
-    BABYLON.SolidParticle = SolidParticle;
-    var ModelShape = (function () {
-        function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
-            this.shapeID = id;
-            this._shape = shape;
-            this._shapeUV = shapeUV;
-            this._positionFunction = posFunction;
-            this._vertexFunction = vtxFunction;
-        }
-        return ModelShape;
-    })();
-    BABYLON.ModelShape = ModelShape;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var SolidParticle = (function () {
+        function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
+            this.color = new BABYLON.Color4(1, 1, 1, 1); // color
+            this.position = BABYLON.Vector3.Zero(); // position
+            this.rotation = BABYLON.Vector3.Zero(); // rotation
+            this.scale = new BABYLON.Vector3(1, 1, 1); // scale
+            this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
+            this.velocity = BABYLON.Vector3.Zero(); // velocity
+            this.alive = true; // alive
+            this.idx = particleIndex;
+            this._pos = positionIndex;
+            this._model = model;
+            this.shapeId = shapeId;
+            this.idxInShape = idxInShape;
+        }
+        return SolidParticle;
+    })();
+    BABYLON.SolidParticle = SolidParticle;
+    var ModelShape = (function () {
+        function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
+            this.shapeID = id;
+            this._shape = shape;
+            this._shapeUV = shapeUV;
+            this._positionFunction = posFunction;
+            this._vertexFunction = vtxFunction;
+        }
+        return ModelShape;
+    })();
+    BABYLON.ModelShape = ModelShape;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.solidParticle.js.map

File diff suppressed because it is too large
+ 660 - 659
src/Particles/babylon.solidParticleSystem.js


+ 382 - 381
src/Physics/Plugins/babylon.cannonJSPlugin.js

@@ -1,381 +1,382 @@
-var BABYLON;
-(function (BABYLON) {
-    var CannonJSPlugin = (function () {
-        function CannonJSPlugin() {
-            this._registeredMeshes = [];
-            this._physicsMaterials = [];
-            this.name = "cannon";
-            this.updateBodyPosition = function (mesh) {
-                for (var index = 0; index < this._registeredMeshes.length; index++) {
-                    var registeredMesh = this._registeredMeshes[index];
-                    if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
-                        var body = registeredMesh.body;
-                        var center = mesh.getBoundingInfo().boundingBox.center.clone();
-                        body.quaternion.copy(mesh.rotationQuaternion);
-                        if (registeredMesh.deltaRotation) {
-                            var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
-                            body.quaternion = body.quaternion.mult(tmpQ);
-                        }
-                        if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
-                            //calculate the correct body position:
-                            var rotationQuaternion = mesh.rotationQuaternion;
-                            mesh.rotationQuaternion = new BABYLON.Quaternion();
-                            mesh.computeWorldMatrix(true);
-                            //get original center with no rotation
-                            var center = mesh.getBoundingInfo().boundingBox.center.clone();
-                            var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
-                            //rotation is back
-                            mesh.rotationQuaternion = rotationQuaternion;
-                            //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
-                            var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
-                            mesh.setPivotMatrix(p);
-                            mesh.computeWorldMatrix(true);
-                            //calculate the translation
-                            var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
-                            center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
-                            //add it inverted to the delta 
-                            registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
-                            registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
-                            mesh.setPivotMatrix(oldPivot);
-                            mesh.computeWorldMatrix(true);
-                        }
-                        else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
-                            center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
-                        }
-                        body.position.set(center.x, center.y, center.z);
-                        return;
-                    }
-                }
-            };
-        }
-        CannonJSPlugin.prototype.initialize = function (iterations) {
-            if (iterations === void 0) { iterations = 10; }
-            this._world = new CANNON.World();
-            this._world.broadphase = new CANNON.NaiveBroadphase();
-            this._world.solver.iterations = iterations;
-        };
-        CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
-            return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
-        };
-        CannonJSPlugin.prototype.runOneStep = function (delta) {
-            var _this = this;
-            this._world.step(delta);
-            this._registeredMeshes.forEach(function (registeredMesh) {
-                // Body position
-                var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
-                registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
-                registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
-                registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
-                registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
-                if (registeredMesh.deltaRotation) {
-                    registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
-                }
-                //is the physics collision callback is set?
-                if (registeredMesh.mesh.onPhysicsCollide) {
-                    if (!registeredMesh.collisionFunction) {
-                        registeredMesh.collisionFunction = function (e) {
-                            //find the mesh that collided with the registered mesh
-                            for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
-                                if (_this._registeredMeshes[idx].body == e.body) {
-                                    registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
-                                }
-                            }
-                        };
-                        registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
-                    }
-                }
-                else {
-                    //unregister, in case the function was removed for some reason
-                    if (registeredMesh.collisionFunction) {
-                        registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
-                    }
-                }
-            });
-        };
-        CannonJSPlugin.prototype.setGravity = function (gravity) {
-            this._gravity = gravity;
-            this._world.gravity.set(gravity.x, gravity.y, gravity.z);
-        };
-        CannonJSPlugin.prototype.getGravity = function () {
-            return this._gravity;
-        };
-        CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
-            this.unregisterMesh(mesh);
-            if (!mesh.rotationQuaternion) {
-                mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
-            }
-            mesh.computeWorldMatrix(true);
-            var shape = this._createShape(mesh, impostor);
-            return this._createRigidBodyFromShape(shape, mesh, options);
-        };
-        CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
-            //get the correct bounding box
-            var oldQuaternion = mesh.rotationQuaternion;
-            mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
-            mesh.computeWorldMatrix(true);
-            var returnValue;
-            switch (impostor) {
-                case BABYLON.PhysicsEngine.SphereImpostor:
-                    var bbox = mesh.getBoundingInfo().boundingBox;
-                    var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
-                    var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
-                    var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
-                    returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
-                    break;
-                //TMP also for cylinder - TODO Cannon supports cylinder natively.
-                case BABYLON.PhysicsEngine.CylinderImpostor:
-                    BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
-                case BABYLON.PhysicsEngine.BoxImpostor:
-                    bbox = mesh.getBoundingInfo().boundingBox;
-                    var min = bbox.minimumWorld;
-                    var max = bbox.maximumWorld;
-                    var box = max.subtract(min).scale(0.5);
-                    returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
-                    break;
-                case BABYLON.PhysicsEngine.PlaneImpostor:
-                    BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
-                    returnValue = new CANNON.Plane();
-                    break;
-                case BABYLON.PhysicsEngine.MeshImpostor:
-                    var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
-                    var rawFaces = mesh.getIndices();
-                    BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
-                    returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
-                    break;
-                case BABYLON.PhysicsEngine.HeightmapImpostor:
-                    returnValue = this._createHeightmap(mesh);
-                    break;
-            }
-            mesh.rotationQuaternion = oldQuaternion;
-            return returnValue;
-        };
-        CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
-            var verts = [], faces = [];
-            mesh.computeWorldMatrix(true);
-            //reuse this variable
-            var transformed = BABYLON.Vector3.Zero();
-            // Get vertices
-            for (var i = 0; i < rawVerts.length; i += 3) {
-                BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
-                verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
-            }
-            // Get faces
-            for (var j = 0; j < rawFaces.length; j += 3) {
-                faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
-            }
-            var shape = new CANNON.ConvexPolyhedron(verts, faces);
-            return shape;
-        };
-        CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
-            var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
-            var matrix = [];
-            //For now pointDepth will not be used and will be automatically calculated.
-            //Future reference - try and find the best place to add a reference to the pointDepth variable.
-            var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
-            var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
-            var elementSize = dim * 2 / arraySize;
-            var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
-            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 + 2]) / elementSize - arraySize / 2) * -1);
-                var y = pos[i + 1] + minY;
-                if (!matrix[x]) {
-                    matrix[x] = [];
-                }
-                if (!matrix[x][z]) {
-                    matrix[x][z] = y;
-                }
-                matrix[x][z] = Math.max(y, matrix[x][z]);
-            }
-            for (var x = 0; x <= arraySize; ++x) {
-                if (!matrix[x]) {
-                    var loc = 1;
-                    while (!matrix[(x + loc) % arraySize]) {
-                        loc++;
-                    }
-                    matrix[x] = matrix[(x + loc) % arraySize].slice();
-                }
-                for (var z = 0; z <= arraySize; ++z) {
-                    if (!matrix[x][z]) {
-                        var loc = 1;
-                        var newValue;
-                        while (newValue === undefined) {
-                            newValue = matrix[x][(z + loc++) % arraySize];
-                        }
-                        matrix[x][z] = newValue;
-                    }
-                }
-            }
-            var shape = new CANNON.Heightfield(matrix, {
-                elementSize: elementSize
-            });
-            //For future reference, needed for body transformation
-            shape.minY = minY;
-            return shape;
-        };
-        CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
-            var index;
-            var mat;
-            for (index = 0; index < this._physicsMaterials.length; index++) {
-                mat = this._physicsMaterials[index];
-                if (mat.friction === friction && mat.restitution === restitution) {
-                    return mat;
-                }
-            }
-            var currentMat = new CANNON.Material("mat");
-            this._physicsMaterials.push(currentMat);
-            for (index = 0; index < this._physicsMaterials.length; index++) {
-                mat = this._physicsMaterials[index];
-                var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
-                this._world.addContactMaterial(contactMaterial);
-            }
-            return currentMat;
-        };
-        CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
-            if (!mesh.rotationQuaternion) {
-                mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
-            }
-            // The delta between the mesh position and the mesh bounding box center
-            var bbox = mesh.getBoundingInfo().boundingBox;
-            var deltaPosition = mesh.position.subtract(bbox.center);
-            var deltaRotation;
-            var material = this._addMaterial(options.friction, options.restitution);
-            var body = new CANNON.Body({
-                mass: options.mass,
-                material: material,
-                position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
-            });
-            body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
-            //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
-            if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
-                //-90 DEG in X, precalculated
-                var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
-                body.quaternion = body.quaternion.mult(tmpQ);
-                //Invert! (Precalculated, 90 deg in X)
-                deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
-            }
-            //If it is a heightfield, if should be centered.
-            if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
-                //calculate the correct body position:
-                var rotationQuaternion = mesh.rotationQuaternion;
-                mesh.rotationQuaternion = new BABYLON.Quaternion();
-                mesh.computeWorldMatrix(true);
-                //get original center with no rotation
-                var center = mesh.getBoundingInfo().boundingBox.center.clone();
-                var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
-                //rotation is back
-                mesh.rotationQuaternion = rotationQuaternion;
-                //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
-                var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
-                mesh.setPivotMatrix(p);
-                mesh.computeWorldMatrix(true);
-                //calculate the translation
-                var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
-                body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
-                //add it inverted to the delta 
-                deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
-                deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
-                mesh.setPivotMatrix(oldPivot);
-                mesh.computeWorldMatrix(true);
-            }
-            else if (shape.type === CANNON.Shape.types.TRIMESH) {
-                deltaPosition = BABYLON.Vector3.Zero();
-            }
-            //add the shape
-            body.addShape(shape);
-            this._world.add(body);
-            this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
-            return body;
-        };
-        CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
-            var initialMesh = parts[0].mesh;
-            this.unregisterMesh(initialMesh);
-            initialMesh.computeWorldMatrix(true);
-            var initialShape = this._createShape(initialMesh, parts[0].impostor);
-            var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
-            for (var index = 1; index < parts.length; index++) {
-                var mesh = parts[index].mesh;
-                mesh.computeWorldMatrix(true);
-                var shape = this._createShape(mesh, parts[index].impostor);
-                var localPosition = mesh.position;
-                body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
-            }
-            return body;
-        };
-        CannonJSPlugin.prototype._unbindBody = function (body) {
-            for (var index = 0; index < this._registeredMeshes.length; index++) {
-                var registeredMesh = this._registeredMeshes[index];
-                if (registeredMesh.body === body) {
-                    this._world.remove(registeredMesh.body);
-                    registeredMesh.body = null;
-                    registeredMesh.delta = null;
-                    registeredMesh.deltaRotation = null;
-                }
-            }
-        };
-        CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
-            for (var index = 0; index < this._registeredMeshes.length; index++) {
-                var registeredMesh = this._registeredMeshes[index];
-                if (registeredMesh.mesh === mesh) {
-                    // Remove body
-                    if (registeredMesh.body) {
-                        this._unbindBody(registeredMesh.body);
-                    }
-                    this._registeredMeshes.splice(index, 1);
-                    return;
-                }
-            }
-        };
-        CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
-            var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
-            var impulse = new CANNON.Vec3(force.x, force.y, force.z);
-            for (var index = 0; index < this._registeredMeshes.length; index++) {
-                var registeredMesh = this._registeredMeshes[index];
-                if (registeredMesh.mesh === mesh) {
-                    registeredMesh.body.applyImpulse(impulse, worldPoint);
-                    return;
-                }
-            }
-        };
-        CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
-            var body1 = null, body2 = null;
-            for (var index = 0; index < this._registeredMeshes.length; index++) {
-                var registeredMesh = this._registeredMeshes[index];
-                if (registeredMesh.mesh === mesh1) {
-                    body1 = registeredMesh.body;
-                }
-                else if (registeredMesh.mesh === mesh2) {
-                    body2 = registeredMesh.body;
-                }
-            }
-            if (!body1 || !body2) {
-                return false;
-            }
-            var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.y, pivot1.z), body2, new CANNON.Vec3(pivot2.x, pivot2.y, pivot2.z));
-            this._world.addConstraint(constraint);
-            return true;
-        };
-        CannonJSPlugin.prototype.dispose = function () {
-            while (this._registeredMeshes.length) {
-                this.unregisterMesh(this._registeredMeshes[0].mesh);
-            }
-        };
-        CannonJSPlugin.prototype.isSupported = function () {
-            return window.CANNON !== undefined;
-        };
-        CannonJSPlugin.prototype.getWorldObject = function () {
-            return this._world;
-        };
-        CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
-            for (var index = 0; index < this._registeredMeshes.length; index++) {
-                var registeredMesh = this._registeredMeshes[index];
-                if (registeredMesh.mesh === mesh) {
-                    return registeredMesh.body;
-                }
-            }
-            return null;
-        };
-        return CannonJSPlugin;
-    })();
-    BABYLON.CannonJSPlugin = CannonJSPlugin;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var CannonJSPlugin = (function () {
+        function CannonJSPlugin() {
+            this._registeredMeshes = [];
+            this._physicsMaterials = [];
+            this.name = "cannon";
+            this.updateBodyPosition = function (mesh) {
+                for (var index = 0; index < this._registeredMeshes.length; index++) {
+                    var registeredMesh = this._registeredMeshes[index];
+                    if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
+                        var body = registeredMesh.body;
+                        var center = mesh.getBoundingInfo().boundingBox.center.clone();
+                        body.quaternion.copy(mesh.rotationQuaternion);
+                        if (registeredMesh.deltaRotation) {
+                            var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
+                            body.quaternion = body.quaternion.mult(tmpQ);
+                        }
+                        if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
+                            //calculate the correct body position:
+                            var rotationQuaternion = mesh.rotationQuaternion;
+                            mesh.rotationQuaternion = new BABYLON.Quaternion();
+                            mesh.computeWorldMatrix(true);
+                            //get original center with no rotation
+                            var center = mesh.getBoundingInfo().boundingBox.center.clone();
+                            var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
+                            //rotation is back
+                            mesh.rotationQuaternion = rotationQuaternion;
+                            //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
+                            var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
+                            mesh.setPivotMatrix(p);
+                            mesh.computeWorldMatrix(true);
+                            //calculate the translation
+                            var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
+                            center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
+                            //add it inverted to the delta 
+                            registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
+                            registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
+                            mesh.setPivotMatrix(oldPivot);
+                            mesh.computeWorldMatrix(true);
+                        }
+                        else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
+                            center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
+                        }
+                        body.position.set(center.x, center.y, center.z);
+                        return;
+                    }
+                }
+            };
+        }
+        CannonJSPlugin.prototype.initialize = function (iterations) {
+            if (iterations === void 0) { iterations = 10; }
+            this._world = new CANNON.World();
+            this._world.broadphase = new CANNON.NaiveBroadphase();
+            this._world.solver.iterations = iterations;
+        };
+        CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
+            return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
+        };
+        CannonJSPlugin.prototype.runOneStep = function (delta) {
+            var _this = this;
+            this._world.step(delta);
+            this._registeredMeshes.forEach(function (registeredMesh) {
+                // Body position
+                var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
+                registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
+                registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
+                registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
+                registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
+                if (registeredMesh.deltaRotation) {
+                    registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
+                }
+                //is the physics collision callback is set?
+                if (registeredMesh.mesh.onPhysicsCollide) {
+                    if (!registeredMesh.collisionFunction) {
+                        registeredMesh.collisionFunction = function (e) {
+                            //find the mesh that collided with the registered mesh
+                            for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
+                                if (_this._registeredMeshes[idx].body == e.body) {
+                                    registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
+                                }
+                            }
+                        };
+                        registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
+                    }
+                }
+                else {
+                    //unregister, in case the function was removed for some reason
+                    if (registeredMesh.collisionFunction) {
+                        registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
+                    }
+                }
+            });
+        };
+        CannonJSPlugin.prototype.setGravity = function (gravity) {
+            this._gravity = gravity;
+            this._world.gravity.set(gravity.x, gravity.y, gravity.z);
+        };
+        CannonJSPlugin.prototype.getGravity = function () {
+            return this._gravity;
+        };
+        CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
+            this.unregisterMesh(mesh);
+            if (!mesh.rotationQuaternion) {
+                mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
+            }
+            mesh.computeWorldMatrix(true);
+            var shape = this._createShape(mesh, impostor);
+            return this._createRigidBodyFromShape(shape, mesh, options);
+        };
+        CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
+            //get the correct bounding box
+            var oldQuaternion = mesh.rotationQuaternion;
+            mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
+            mesh.computeWorldMatrix(true);
+            var returnValue;
+            switch (impostor) {
+                case BABYLON.PhysicsEngine.SphereImpostor:
+                    var bbox = mesh.getBoundingInfo().boundingBox;
+                    var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
+                    var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
+                    var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
+                    returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
+                    break;
+                //TMP also for cylinder - TODO Cannon supports cylinder natively.
+                case BABYLON.PhysicsEngine.CylinderImpostor:
+                    BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
+                case BABYLON.PhysicsEngine.BoxImpostor:
+                    bbox = mesh.getBoundingInfo().boundingBox;
+                    var min = bbox.minimumWorld;
+                    var max = bbox.maximumWorld;
+                    var box = max.subtract(min).scale(0.5);
+                    returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
+                    break;
+                case BABYLON.PhysicsEngine.PlaneImpostor:
+                    BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
+                    returnValue = new CANNON.Plane();
+                    break;
+                case BABYLON.PhysicsEngine.MeshImpostor:
+                    var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
+                    var rawFaces = mesh.getIndices();
+                    BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
+                    returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
+                    break;
+                case BABYLON.PhysicsEngine.HeightmapImpostor:
+                    returnValue = this._createHeightmap(mesh);
+                    break;
+            }
+            mesh.rotationQuaternion = oldQuaternion;
+            return returnValue;
+        };
+        CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
+            var verts = [], faces = [];
+            mesh.computeWorldMatrix(true);
+            //reuse this variable
+            var transformed = BABYLON.Vector3.Zero();
+            // Get vertices
+            for (var i = 0; i < rawVerts.length; i += 3) {
+                BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
+                verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
+            }
+            // Get faces
+            for (var j = 0; j < rawFaces.length; j += 3) {
+                faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
+            }
+            var shape = new CANNON.ConvexPolyhedron(verts, faces);
+            return shape;
+        };
+        CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
+            var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
+            var matrix = [];
+            //For now pointDepth will not be used and will be automatically calculated.
+            //Future reference - try and find the best place to add a reference to the pointDepth variable.
+            var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
+            var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
+            var elementSize = dim * 2 / arraySize;
+            var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
+            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 + 2]) / elementSize - arraySize / 2) * -1);
+                var y = pos[i + 1] + minY;
+                if (!matrix[x]) {
+                    matrix[x] = [];
+                }
+                if (!matrix[x][z]) {
+                    matrix[x][z] = y;
+                }
+                matrix[x][z] = Math.max(y, matrix[x][z]);
+            }
+            for (var x = 0; x <= arraySize; ++x) {
+                if (!matrix[x]) {
+                    var loc = 1;
+                    while (!matrix[(x + loc) % arraySize]) {
+                        loc++;
+                    }
+                    matrix[x] = matrix[(x + loc) % arraySize].slice();
+                }
+                for (var z = 0; z <= arraySize; ++z) {
+                    if (!matrix[x][z]) {
+                        var loc = 1;
+                        var newValue;
+                        while (newValue === undefined) {
+                            newValue = matrix[x][(z + loc++) % arraySize];
+                        }
+                        matrix[x][z] = newValue;
+                    }
+                }
+            }
+            var shape = new CANNON.Heightfield(matrix, {
+                elementSize: elementSize
+            });
+            //For future reference, needed for body transformation
+            shape.minY = minY;
+            return shape;
+        };
+        CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
+            var index;
+            var mat;
+            for (index = 0; index < this._physicsMaterials.length; index++) {
+                mat = this._physicsMaterials[index];
+                if (mat.friction === friction && mat.restitution === restitution) {
+                    return mat;
+                }
+            }
+            var currentMat = new CANNON.Material("mat");
+            this._physicsMaterials.push(currentMat);
+            for (index = 0; index < this._physicsMaterials.length; index++) {
+                mat = this._physicsMaterials[index];
+                var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
+                this._world.addContactMaterial(contactMaterial);
+            }
+            return currentMat;
+        };
+        CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
+            if (!mesh.rotationQuaternion) {
+                mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
+            }
+            // The delta between the mesh position and the mesh bounding box center
+            var bbox = mesh.getBoundingInfo().boundingBox;
+            var deltaPosition = mesh.position.subtract(bbox.center);
+            var deltaRotation;
+            var material = this._addMaterial(options.friction, options.restitution);
+            var body = new CANNON.Body({
+                mass: options.mass,
+                material: material,
+                position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
+            });
+            body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
+            //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
+            if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
+                //-90 DEG in X, precalculated
+                var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
+                body.quaternion = body.quaternion.mult(tmpQ);
+                //Invert! (Precalculated, 90 deg in X)
+                deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
+            }
+            //If it is a heightfield, if should be centered.
+            if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
+                //calculate the correct body position:
+                var rotationQuaternion = mesh.rotationQuaternion;
+                mesh.rotationQuaternion = new BABYLON.Quaternion();
+                mesh.computeWorldMatrix(true);
+                //get original center with no rotation
+                var center = mesh.getBoundingInfo().boundingBox.center.clone();
+                var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
+                //rotation is back
+                mesh.rotationQuaternion = rotationQuaternion;
+                //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
+                var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
+                mesh.setPivotMatrix(p);
+                mesh.computeWorldMatrix(true);
+                //calculate the translation
+                var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
+                body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
+                //add it inverted to the delta 
+                deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
+                deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
+                mesh.setPivotMatrix(oldPivot);
+                mesh.computeWorldMatrix(true);
+            }
+            else if (shape.type === CANNON.Shape.types.TRIMESH) {
+                deltaPosition = BABYLON.Vector3.Zero();
+            }
+            //add the shape
+            body.addShape(shape);
+            this._world.add(body);
+            this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
+            return body;
+        };
+        CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
+            var initialMesh = parts[0].mesh;
+            this.unregisterMesh(initialMesh);
+            initialMesh.computeWorldMatrix(true);
+            var initialShape = this._createShape(initialMesh, parts[0].impostor);
+            var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
+            for (var index = 1; index < parts.length; index++) {
+                var mesh = parts[index].mesh;
+                mesh.computeWorldMatrix(true);
+                var shape = this._createShape(mesh, parts[index].impostor);
+                var localPosition = mesh.position;
+                body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
+            }
+            return body;
+        };
+        CannonJSPlugin.prototype._unbindBody = function (body) {
+            for (var index = 0; index < this._registeredMeshes.length; index++) {
+                var registeredMesh = this._registeredMeshes[index];
+                if (registeredMesh.body === body) {
+                    this._world.remove(registeredMesh.body);
+                    registeredMesh.body = null;
+                    registeredMesh.delta = null;
+                    registeredMesh.deltaRotation = null;
+                }
+            }
+        };
+        CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
+            for (var index = 0; index < this._registeredMeshes.length; index++) {
+                var registeredMesh = this._registeredMeshes[index];
+                if (registeredMesh.mesh === mesh) {
+                    // Remove body
+                    if (registeredMesh.body) {
+                        this._unbindBody(registeredMesh.body);
+                    }
+                    this._registeredMeshes.splice(index, 1);
+                    return;
+                }
+            }
+        };
+        CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
+            var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
+            var impulse = new CANNON.Vec3(force.x, force.y, force.z);
+            for (var index = 0; index < this._registeredMeshes.length; index++) {
+                var registeredMesh = this._registeredMeshes[index];
+                if (registeredMesh.mesh === mesh) {
+                    registeredMesh.body.applyImpulse(impulse, worldPoint);
+                    return;
+                }
+            }
+        };
+        CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
+            var body1 = null, body2 = null;
+            for (var index = 0; index < this._registeredMeshes.length; index++) {
+                var registeredMesh = this._registeredMeshes[index];
+                if (registeredMesh.mesh === mesh1) {
+                    body1 = registeredMesh.body;
+                }
+                else if (registeredMesh.mesh === mesh2) {
+                    body2 = registeredMesh.body;
+                }
+            }
+            if (!body1 || !body2) {
+                return false;
+            }
+            var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.y, pivot1.z), body2, new CANNON.Vec3(pivot2.x, pivot2.y, pivot2.z));
+            this._world.addConstraint(constraint);
+            return true;
+        };
+        CannonJSPlugin.prototype.dispose = function () {
+            while (this._registeredMeshes.length) {
+                this.unregisterMesh(this._registeredMeshes[0].mesh);
+            }
+        };
+        CannonJSPlugin.prototype.isSupported = function () {
+            return window.CANNON !== undefined;
+        };
+        CannonJSPlugin.prototype.getWorldObject = function () {
+            return this._world;
+        };
+        CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
+            for (var index = 0; index < this._registeredMeshes.length; index++) {
+                var registeredMesh = this._registeredMeshes[index];
+                if (registeredMesh.mesh === mesh) {
+                    return registeredMesh.body;
+                }
+            }
+            return null;
+        };
+        return CannonJSPlugin;
+    })();
+    BABYLON.CannonJSPlugin = CannonJSPlugin;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.cannonJSPlugin.js.map

+ 332 - 331
src/Physics/Plugins/babylon.oimoJSPlugin.js

@@ -1,331 +1,332 @@
-var BABYLON;
-(function (BABYLON) {
-    var OimoJSPlugin = (function () {
-        function OimoJSPlugin() {
-            this._registeredMeshes = [];
-            this.name = "oimo";
-            /**
-             * Update the body position according to the mesh position
-             * @param mesh
-             */
-            this.updateBodyPosition = function (mesh) {
-                for (var index = 0; index < this._registeredMeshes.length; index++) {
-                    var registeredMesh = this._registeredMeshes[index];
-                    var body = registeredMesh.body.body;
-                    var updated = false;
-                    var newPosition;
-                    if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
-                        mesh.computeWorldMatrix(true);
-                        newPosition = mesh.getBoundingInfo().boundingBox.center;
-                        updated = true;
-                    }
-                    else if (registeredMesh.mesh.parent === mesh) {
-                        mesh.computeWorldMatrix(true);
-                        registeredMesh.mesh.computeWorldMatrix(true);
-                        newPosition = registeredMesh.mesh.getAbsolutePosition();
-                        updated = true;
-                    }
-                    if (updated) {
-                        body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
-                        body.setQuaternion(mesh.rotationQuaternion);
-                        body.sleeping = false;
-                        //force Oimo to update the body's position
-                        body.updatePosition(1);
-                    }
-                }
-            };
-        }
-        OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
-            return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
-        };
-        OimoJSPlugin.prototype.initialize = function (iterations) {
-            this._world = new OIMO.World(null, null, iterations);
-            this._world.clear();
-        };
-        OimoJSPlugin.prototype.setGravity = function (gravity) {
-            this._gravity = this._world.gravity = gravity;
-        };
-        OimoJSPlugin.prototype.getGravity = function () {
-            return this._gravity;
-        };
-        OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
-            this.unregisterMesh(mesh);
-            if (!mesh.rotationQuaternion) {
-                mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
-            }
-            mesh.computeWorldMatrix(true);
-            var bbox = mesh.getBoundingInfo().boundingBox;
-            // The delta between the mesh position and the mesh bounding box center
-            var deltaPosition = mesh.position.subtract(bbox.center);
-            //calculate rotation to fit Oimo's needs (Euler...)
-            var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
-            //get the correct bounding box
-            var oldQuaternion = mesh.rotationQuaternion;
-            mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
-            mesh.computeWorldMatrix(true);
-            var bodyConfig = {
-                name: mesh.uniqueId,
-                pos: [bbox.center.x, bbox.center.y, bbox.center.z],
-                rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
-                move: options.mass != 0,
-                config: [options.mass, options.friction, options.restitution],
-                world: this._world
-            };
-            // register mesh
-            switch (impostor) {
-                case BABYLON.PhysicsEngine.SphereImpostor:
-                    var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
-                    var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
-                    var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
-                    var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
-                    bodyConfig.type = 'sphere';
-                    bodyConfig.size = [size];
-                    break;
-                case BABYLON.PhysicsEngine.PlaneImpostor:
-                //Oimo "fakes" a cylinder as a box, so why don't we!
-                case BABYLON.PhysicsEngine.CylinderImpostor:
-                case BABYLON.PhysicsEngine.BoxImpostor:
-                    var min = bbox.minimumWorld;
-                    var max = bbox.maximumWorld;
-                    var box = max.subtract(min);
-                    var sizeX = this._checkWithEpsilon(box.x);
-                    var sizeY = this._checkWithEpsilon(box.y);
-                    var sizeZ = this._checkWithEpsilon(box.z);
-                    bodyConfig.type = 'box';
-                    bodyConfig.size = [sizeX, sizeY, sizeZ];
-                    break;
-            }
-            var body = new OIMO.Body(bodyConfig);
-            //We have to access the rigid body's properties to set the quaternion. 
-            //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
-            //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
-            //TEST
-            //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
-            //update the internal rotation matrix
-            //body.body.syncShapes();
-            this._registeredMeshes.push({
-                mesh: mesh,
-                body: body,
-                delta: deltaPosition
-            });
-            //for the sake of consistency.
-            mesh.rotationQuaternion = oldQuaternion;
-            return body;
-        };
-        OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
-            var types = [], sizes = [], positions = [], rotations = [];
-            var initialMesh = parts[0].mesh;
-            for (var index = 0; index < parts.length; index++) {
-                var part = parts[index];
-                var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
-                types.push(bodyParameters.type);
-                sizes.push.apply(sizes, bodyParameters.size);
-                positions.push.apply(positions, bodyParameters.pos);
-                rotations.push.apply(rotations, bodyParameters.rot);
-            }
-            var body = new OIMO.Body({
-                name: initialMesh.uniqueId,
-                type: types,
-                size: sizes,
-                pos: positions,
-                rot: rotations,
-                move: options.mass != 0,
-                config: [options.mass, options.friction, options.restitution],
-                world: this._world
-            });
-            //Reset the body's rotation to be of the initial mesh's.
-            var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
-            body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
-            this._registeredMeshes.push({
-                mesh: initialMesh,
-                body: body
-            });
-            return body;
-        };
-        OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
-            var mesh = part.mesh;
-            if (!mesh.rotationQuaternion) {
-                mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
-            }
-            // We need the bounding box/sphere info to compute the physics body
-            mesh.computeWorldMatrix(true);
-            var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
-            var bodyParameters = {
-                name: mesh.uniqueId,
-                pos: [mesh.position.x, mesh.position.y, mesh.position.z],
-                //A bug in Oimo (Body class) prevents us from using rot directly.
-                rot: [0, 0, 0],
-                //For future reference, if the bug will ever be fixed.
-                realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
-            };
-            var oldQuaternion = mesh.rotationQuaternion;
-            mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
-            mesh.computeWorldMatrix(true);
-            switch (part.impostor) {
-                case BABYLON.PhysicsEngine.SphereImpostor:
-                    var bbox = mesh.getBoundingInfo().boundingBox;
-                    var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
-                    var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
-                    var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
-                    var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
-                    bodyParameters.type = 'sphere';
-                    bodyParameters.size = [size, size, size];
-                    break;
-                case BABYLON.PhysicsEngine.PlaneImpostor:
-                case BABYLON.PhysicsEngine.CylinderImpostor:
-                case BABYLON.PhysicsEngine.BoxImpostor:
-                    bbox = mesh.getBoundingInfo().boundingBox;
-                    var min = bbox.minimumWorld;
-                    var max = bbox.maximumWorld;
-                    var box = max.subtract(min);
-                    var sizeX = this._checkWithEpsilon(box.x);
-                    var sizeY = this._checkWithEpsilon(box.y);
-                    var sizeZ = this._checkWithEpsilon(box.z);
-                    bodyParameters.type = 'box';
-                    bodyParameters.size = [sizeX, sizeY, sizeZ];
-                    break;
-            }
-            mesh.rotationQuaternion = oldQuaternion;
-            return bodyParameters;
-        };
-        OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
-            for (var index = 0; index < this._registeredMeshes.length; index++) {
-                var registeredMesh = this._registeredMeshes[index];
-                if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
-                    if (registeredMesh.body) {
-                        this._world.removeRigidBody(registeredMesh.body.body);
-                        this._unbindBody(registeredMesh.body);
-                    }
-                    this._registeredMeshes.splice(index, 1);
-                    return;
-                }
-            }
-        };
-        OimoJSPlugin.prototype._unbindBody = function (body) {
-            for (var index = 0; index < this._registeredMeshes.length; index++) {
-                var registeredMesh = this._registeredMeshes[index];
-                if (registeredMesh.body === body) {
-                    registeredMesh.body = null;
-                }
-            }
-        };
-        OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
-            for (var index = 0; index < this._registeredMeshes.length; index++) {
-                var registeredMesh = this._registeredMeshes[index];
-                if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
-                    // Get object mass to have a behaviour similar to cannon.js
-                    var mass = registeredMesh.body.body.massInfo.mass;
-                    // The force is scaled with the mass of object
-                    registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
-                    return;
-                }
-            }
-        };
-        OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
-            var body1 = null, body2 = null;
-            for (var index = 0; index < this._registeredMeshes.length; index++) {
-                var registeredMesh = this._registeredMeshes[index];
-                if (registeredMesh.mesh === mesh1) {
-                    body1 = registeredMesh.body.body;
-                }
-                else if (registeredMesh.mesh === mesh2) {
-                    body2 = registeredMesh.body.body;
-                }
-            }
-            if (!body1 || !body2) {
-                return false;
-            }
-            if (!options) {
-                options = {};
-            }
-            new OIMO.Link({
-                type: options.type,
-                body1: body1,
-                body2: body2,
-                min: options.min,
-                max: options.max,
-                axe1: options.axe1,
-                axe2: options.axe2,
-                pos1: [pivot1.x, pivot1.y, pivot1.z],
-                pos2: [pivot2.x, pivot2.y, pivot2.z],
-                collision: options.collision,
-                spring: options.spring,
-                world: this._world
-            });
-            return true;
-        };
-        OimoJSPlugin.prototype.dispose = function () {
-            this._world.clear();
-            while (this._registeredMeshes.length) {
-                this.unregisterMesh(this._registeredMeshes[0].mesh);
-            }
-        };
-        OimoJSPlugin.prototype.isSupported = function () {
-            return OIMO !== undefined;
-        };
-        OimoJSPlugin.prototype.getWorldObject = function () {
-            return this._world;
-        };
-        OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
-            for (var index = 0; index < this._registeredMeshes.length; index++) {
-                var registeredMesh = this._registeredMeshes[index];
-                if (registeredMesh.mesh === mesh) {
-                    return registeredMesh.body;
-                }
-            }
-            return null;
-        };
-        OimoJSPlugin.prototype._getLastShape = function (body) {
-            var lastShape = body.shapes;
-            while (lastShape.next) {
-                lastShape = lastShape.next;
-            }
-            return lastShape;
-        };
-        OimoJSPlugin.prototype.runOneStep = function (time) {
-            this._world.step();
-            // Update the position of all registered meshes
-            var i = this._registeredMeshes.length;
-            var m;
-            while (i--) {
-                var body = this._registeredMeshes[i].body.body;
-                var mesh = this._registeredMeshes[i].mesh;
-                if (!this._registeredMeshes[i].delta) {
-                    this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
-                }
-                if (!body.sleeping) {
-                    //TODO check that
-                    if (body.shapes.next) {
-                        var parentShape = this._getLastShape(body);
-                        mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
-                        mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
-                        mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
-                    }
-                    else {
-                        mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
-                    }
-                    mesh.rotationQuaternion.copyFrom(body.getQuaternion());
-                    mesh.computeWorldMatrix();
-                }
-                //check if the collide callback is set. 
-                if (mesh.onPhysicsCollide) {
-                    var meshUniqueName = mesh.uniqueId;
-                    var contact = this._world.contacts;
-                    while (contact !== null) {
-                        //is this body colliding with any other?
-                        if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
-                            var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
-                            //get the mesh and execute the callback
-                            var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
-                            if (otherMesh)
-                                mesh.onPhysicsCollide(otherMesh, contact);
-                        }
-                        contact = contact.next;
-                    }
-                }
-            }
-        };
-        return OimoJSPlugin;
-    })();
-    BABYLON.OimoJSPlugin = OimoJSPlugin;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var OimoJSPlugin = (function () {
+        function OimoJSPlugin() {
+            this._registeredMeshes = [];
+            this.name = "oimo";
+            /**
+             * Update the body position according to the mesh position
+             * @param mesh
+             */
+            this.updateBodyPosition = function (mesh) {
+                for (var index = 0; index < this._registeredMeshes.length; index++) {
+                    var registeredMesh = this._registeredMeshes[index];
+                    var body = registeredMesh.body.body;
+                    var updated = false;
+                    var newPosition;
+                    if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
+                        mesh.computeWorldMatrix(true);
+                        newPosition = mesh.getBoundingInfo().boundingBox.center;
+                        updated = true;
+                    }
+                    else if (registeredMesh.mesh.parent === mesh) {
+                        mesh.computeWorldMatrix(true);
+                        registeredMesh.mesh.computeWorldMatrix(true);
+                        newPosition = registeredMesh.mesh.getAbsolutePosition();
+                        updated = true;
+                    }
+                    if (updated) {
+                        body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
+                        body.setQuaternion(mesh.rotationQuaternion);
+                        body.sleeping = false;
+                        //force Oimo to update the body's position
+                        body.updatePosition(1);
+                    }
+                }
+            };
+        }
+        OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
+            return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
+        };
+        OimoJSPlugin.prototype.initialize = function (iterations) {
+            this._world = new OIMO.World(null, null, iterations);
+            this._world.clear();
+        };
+        OimoJSPlugin.prototype.setGravity = function (gravity) {
+            this._gravity = this._world.gravity = gravity;
+        };
+        OimoJSPlugin.prototype.getGravity = function () {
+            return this._gravity;
+        };
+        OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
+            this.unregisterMesh(mesh);
+            if (!mesh.rotationQuaternion) {
+                mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
+            }
+            mesh.computeWorldMatrix(true);
+            var bbox = mesh.getBoundingInfo().boundingBox;
+            // The delta between the mesh position and the mesh bounding box center
+            var deltaPosition = mesh.position.subtract(bbox.center);
+            //calculate rotation to fit Oimo's needs (Euler...)
+            var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
+            //get the correct bounding box
+            var oldQuaternion = mesh.rotationQuaternion;
+            mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
+            mesh.computeWorldMatrix(true);
+            var bodyConfig = {
+                name: mesh.uniqueId,
+                pos: [bbox.center.x, bbox.center.y, bbox.center.z],
+                rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
+                move: options.mass != 0,
+                config: [options.mass, options.friction, options.restitution],
+                world: this._world
+            };
+            // register mesh
+            switch (impostor) {
+                case BABYLON.PhysicsEngine.SphereImpostor:
+                    var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
+                    var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
+                    var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
+                    var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
+                    bodyConfig.type = 'sphere';
+                    bodyConfig.size = [size];
+                    break;
+                case BABYLON.PhysicsEngine.PlaneImpostor:
+                //Oimo "fakes" a cylinder as a box, so why don't we!
+                case BABYLON.PhysicsEngine.CylinderImpostor:
+                case BABYLON.PhysicsEngine.BoxImpostor:
+                    var min = bbox.minimumWorld;
+                    var max = bbox.maximumWorld;
+                    var box = max.subtract(min);
+                    var sizeX = this._checkWithEpsilon(box.x);
+                    var sizeY = this._checkWithEpsilon(box.y);
+                    var sizeZ = this._checkWithEpsilon(box.z);
+                    bodyConfig.type = 'box';
+                    bodyConfig.size = [sizeX, sizeY, sizeZ];
+                    break;
+            }
+            var body = new OIMO.Body(bodyConfig);
+            //We have to access the rigid body's properties to set the quaternion. 
+            //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
+            //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
+            //TEST
+            //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
+            //update the internal rotation matrix
+            //body.body.syncShapes();
+            this._registeredMeshes.push({
+                mesh: mesh,
+                body: body,
+                delta: deltaPosition
+            });
+            //for the sake of consistency.
+            mesh.rotationQuaternion = oldQuaternion;
+            return body;
+        };
+        OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
+            var types = [], sizes = [], positions = [], rotations = [];
+            var initialMesh = parts[0].mesh;
+            for (var index = 0; index < parts.length; index++) {
+                var part = parts[index];
+                var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
+                types.push(bodyParameters.type);
+                sizes.push.apply(sizes, bodyParameters.size);
+                positions.push.apply(positions, bodyParameters.pos);
+                rotations.push.apply(rotations, bodyParameters.rot);
+            }
+            var body = new OIMO.Body({
+                name: initialMesh.uniqueId,
+                type: types,
+                size: sizes,
+                pos: positions,
+                rot: rotations,
+                move: options.mass != 0,
+                config: [options.mass, options.friction, options.restitution],
+                world: this._world
+            });
+            //Reset the body's rotation to be of the initial mesh's.
+            var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
+            body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
+            this._registeredMeshes.push({
+                mesh: initialMesh,
+                body: body
+            });
+            return body;
+        };
+        OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
+            var mesh = part.mesh;
+            if (!mesh.rotationQuaternion) {
+                mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
+            }
+            // We need the bounding box/sphere info to compute the physics body
+            mesh.computeWorldMatrix(true);
+            var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
+            var bodyParameters = {
+                name: mesh.uniqueId,
+                pos: [mesh.position.x, mesh.position.y, mesh.position.z],
+                //A bug in Oimo (Body class) prevents us from using rot directly.
+                rot: [0, 0, 0],
+                //For future reference, if the bug will ever be fixed.
+                realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
+            };
+            var oldQuaternion = mesh.rotationQuaternion;
+            mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
+            mesh.computeWorldMatrix(true);
+            switch (part.impostor) {
+                case BABYLON.PhysicsEngine.SphereImpostor:
+                    var bbox = mesh.getBoundingInfo().boundingBox;
+                    var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
+                    var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
+                    var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
+                    var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
+                    bodyParameters.type = 'sphere';
+                    bodyParameters.size = [size, size, size];
+                    break;
+                case BABYLON.PhysicsEngine.PlaneImpostor:
+                case BABYLON.PhysicsEngine.CylinderImpostor:
+                case BABYLON.PhysicsEngine.BoxImpostor:
+                    bbox = mesh.getBoundingInfo().boundingBox;
+                    var min = bbox.minimumWorld;
+                    var max = bbox.maximumWorld;
+                    var box = max.subtract(min);
+                    var sizeX = this._checkWithEpsilon(box.x);
+                    var sizeY = this._checkWithEpsilon(box.y);
+                    var sizeZ = this._checkWithEpsilon(box.z);
+                    bodyParameters.type = 'box';
+                    bodyParameters.size = [sizeX, sizeY, sizeZ];
+                    break;
+            }
+            mesh.rotationQuaternion = oldQuaternion;
+            return bodyParameters;
+        };
+        OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
+            for (var index = 0; index < this._registeredMeshes.length; index++) {
+                var registeredMesh = this._registeredMeshes[index];
+                if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
+                    if (registeredMesh.body) {
+                        this._world.removeRigidBody(registeredMesh.body.body);
+                        this._unbindBody(registeredMesh.body);
+                    }
+                    this._registeredMeshes.splice(index, 1);
+                    return;
+                }
+            }
+        };
+        OimoJSPlugin.prototype._unbindBody = function (body) {
+            for (var index = 0; index < this._registeredMeshes.length; index++) {
+                var registeredMesh = this._registeredMeshes[index];
+                if (registeredMesh.body === body) {
+                    registeredMesh.body = null;
+                }
+            }
+        };
+        OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
+            for (var index = 0; index < this._registeredMeshes.length; index++) {
+                var registeredMesh = this._registeredMeshes[index];
+                if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
+                    // Get object mass to have a behaviour similar to cannon.js
+                    var mass = registeredMesh.body.body.massInfo.mass;
+                    // The force is scaled with the mass of object
+                    registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
+                    return;
+                }
+            }
+        };
+        OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
+            var body1 = null, body2 = null;
+            for (var index = 0; index < this._registeredMeshes.length; index++) {
+                var registeredMesh = this._registeredMeshes[index];
+                if (registeredMesh.mesh === mesh1) {
+                    body1 = registeredMesh.body.body;
+                }
+                else if (registeredMesh.mesh === mesh2) {
+                    body2 = registeredMesh.body.body;
+                }
+            }
+            if (!body1 || !body2) {
+                return false;
+            }
+            if (!options) {
+                options = {};
+            }
+            new OIMO.Link({
+                type: options.type,
+                body1: body1,
+                body2: body2,
+                min: options.min,
+                max: options.max,
+                axe1: options.axe1,
+                axe2: options.axe2,
+                pos1: [pivot1.x, pivot1.y, pivot1.z],
+                pos2: [pivot2.x, pivot2.y, pivot2.z],
+                collision: options.collision,
+                spring: options.spring,
+                world: this._world
+            });
+            return true;
+        };
+        OimoJSPlugin.prototype.dispose = function () {
+            this._world.clear();
+            while (this._registeredMeshes.length) {
+                this.unregisterMesh(this._registeredMeshes[0].mesh);
+            }
+        };
+        OimoJSPlugin.prototype.isSupported = function () {
+            return OIMO !== undefined;
+        };
+        OimoJSPlugin.prototype.getWorldObject = function () {
+            return this._world;
+        };
+        OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
+            for (var index = 0; index < this._registeredMeshes.length; index++) {
+                var registeredMesh = this._registeredMeshes[index];
+                if (registeredMesh.mesh === mesh) {
+                    return registeredMesh.body;
+                }
+            }
+            return null;
+        };
+        OimoJSPlugin.prototype._getLastShape = function (body) {
+            var lastShape = body.shapes;
+            while (lastShape.next) {
+                lastShape = lastShape.next;
+            }
+            return lastShape;
+        };
+        OimoJSPlugin.prototype.runOneStep = function (time) {
+            this._world.step();
+            // Update the position of all registered meshes
+            var i = this._registeredMeshes.length;
+            var m;
+            while (i--) {
+                var body = this._registeredMeshes[i].body.body;
+                var mesh = this._registeredMeshes[i].mesh;
+                if (!this._registeredMeshes[i].delta) {
+                    this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
+                }
+                if (!body.sleeping) {
+                    //TODO check that
+                    if (body.shapes.next) {
+                        var parentShape = this._getLastShape(body);
+                        mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
+                        mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
+                        mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
+                    }
+                    else {
+                        mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
+                    }
+                    mesh.rotationQuaternion.copyFrom(body.getQuaternion());
+                    mesh.computeWorldMatrix();
+                }
+                //check if the collide callback is set. 
+                if (mesh.onPhysicsCollide) {
+                    var meshUniqueName = mesh.uniqueId;
+                    var contact = this._world.contacts;
+                    while (contact !== null) {
+                        //is this body colliding with any other?
+                        if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
+                            var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
+                            //get the mesh and execute the callback
+                            var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
+                            if (otherMesh)
+                                mesh.onPhysicsCollide(otherMesh, contact);
+                        }
+                        contact = contact.next;
+                    }
+                }
+            }
+        };
+        return OimoJSPlugin;
+    })();
+    BABYLON.OimoJSPlugin = OimoJSPlugin;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.oimoJSPlugin.js.map

+ 73 - 72
src/Physics/babylon.physicsEngine.js

@@ -1,72 +1,73 @@
-var BABYLON;
-(function (BABYLON) {
-    var PhysicsEngine = (function () {
-        function PhysicsEngine(plugin) {
-            this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
-        }
-        PhysicsEngine.prototype._initialize = function (gravity) {
-            this._currentPlugin.initialize();
-            this._setGravity(gravity);
-        };
-        PhysicsEngine.prototype._runOneStep = function (delta) {
-            if (delta > 0.1) {
-                delta = 0.1;
-            }
-            else if (delta <= 0) {
-                delta = 1.0 / 60.0;
-            }
-            this._currentPlugin.runOneStep(delta);
-        };
-        PhysicsEngine.prototype._setGravity = function (gravity) {
-            this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
-            this._currentPlugin.setGravity(this.gravity);
-        };
-        PhysicsEngine.prototype._getGravity = function () {
-            return this._currentPlugin.getGravity();
-        };
-        PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
-            return this._currentPlugin.registerMesh(mesh, impostor, options);
-        };
-        PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
-            return this._currentPlugin.registerMeshesAsCompound(parts, options);
-        };
-        PhysicsEngine.prototype._unregisterMesh = function (mesh) {
-            this._currentPlugin.unregisterMesh(mesh);
-        };
-        PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
-            this._currentPlugin.applyImpulse(mesh, force, contactPoint);
-        };
-        PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
-            return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
-        };
-        PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
-            this._currentPlugin.updateBodyPosition(mesh);
-        };
-        PhysicsEngine.prototype.dispose = function () {
-            this._currentPlugin.dispose();
-        };
-        PhysicsEngine.prototype.isSupported = function () {
-            return this._currentPlugin.isSupported();
-        };
-        PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
-            return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
-        };
-        PhysicsEngine.prototype.getPhysicsPluginName = function () {
-            return this._currentPlugin.name;
-        };
-        // Statics
-        PhysicsEngine.NoImpostor = 0;
-        PhysicsEngine.SphereImpostor = 1;
-        PhysicsEngine.BoxImpostor = 2;
-        PhysicsEngine.PlaneImpostor = 3;
-        PhysicsEngine.MeshImpostor = 4;
-        PhysicsEngine.CapsuleImpostor = 5;
-        PhysicsEngine.ConeImpostor = 6;
-        PhysicsEngine.CylinderImpostor = 7;
-        PhysicsEngine.ConvexHullImpostor = 8;
-        PhysicsEngine.HeightmapImpostor = 9;
-        PhysicsEngine.Epsilon = 0.001;
-        return PhysicsEngine;
-    })();
-    BABYLON.PhysicsEngine = PhysicsEngine;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var PhysicsEngine = (function () {
+        function PhysicsEngine(plugin) {
+            this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
+        }
+        PhysicsEngine.prototype._initialize = function (gravity) {
+            this._currentPlugin.initialize();
+            this._setGravity(gravity);
+        };
+        PhysicsEngine.prototype._runOneStep = function (delta) {
+            if (delta > 0.1) {
+                delta = 0.1;
+            }
+            else if (delta <= 0) {
+                delta = 1.0 / 60.0;
+            }
+            this._currentPlugin.runOneStep(delta);
+        };
+        PhysicsEngine.prototype._setGravity = function (gravity) {
+            this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
+            this._currentPlugin.setGravity(this.gravity);
+        };
+        PhysicsEngine.prototype._getGravity = function () {
+            return this._currentPlugin.getGravity();
+        };
+        PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
+            return this._currentPlugin.registerMesh(mesh, impostor, options);
+        };
+        PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
+            return this._currentPlugin.registerMeshesAsCompound(parts, options);
+        };
+        PhysicsEngine.prototype._unregisterMesh = function (mesh) {
+            this._currentPlugin.unregisterMesh(mesh);
+        };
+        PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
+            this._currentPlugin.applyImpulse(mesh, force, contactPoint);
+        };
+        PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
+            return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
+        };
+        PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
+            this._currentPlugin.updateBodyPosition(mesh);
+        };
+        PhysicsEngine.prototype.dispose = function () {
+            this._currentPlugin.dispose();
+        };
+        PhysicsEngine.prototype.isSupported = function () {
+            return this._currentPlugin.isSupported();
+        };
+        PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
+            return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
+        };
+        PhysicsEngine.prototype.getPhysicsPluginName = function () {
+            return this._currentPlugin.name;
+        };
+        // Statics
+        PhysicsEngine.NoImpostor = 0;
+        PhysicsEngine.SphereImpostor = 1;
+        PhysicsEngine.BoxImpostor = 2;
+        PhysicsEngine.PlaneImpostor = 3;
+        PhysicsEngine.MeshImpostor = 4;
+        PhysicsEngine.CapsuleImpostor = 5;
+        PhysicsEngine.ConeImpostor = 6;
+        PhysicsEngine.CylinderImpostor = 7;
+        PhysicsEngine.ConvexHullImpostor = 8;
+        PhysicsEngine.HeightmapImpostor = 9;
+        PhysicsEngine.Epsilon = 0.001;
+        return PhysicsEngine;
+    })();
+    BABYLON.PhysicsEngine = PhysicsEngine;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.physicsEngine.js.map

+ 153 - 152
src/PostProcess/RenderPipeline/babylon.postProcessRenderEffect.js

@@ -1,152 +1,153 @@
-var BABYLON;
-(function (BABYLON) {
-    var PostProcessRenderEffect = (function () {
-        function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
-            this._engine = engine;
-            this._name = name;
-            this._singleInstance = singleInstance || true;
-            this._getPostProcess = getPostProcess;
-            this._cameras = [];
-            this._indicesForCamera = [];
-            this._postProcesses = {};
-            this._renderPasses = {};
-            this._renderEffectAsPasses = {};
-        }
-        Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
-            get: function () {
-                for (var index in this._postProcesses) {
-                    if (!this._postProcesses[index].isSupported) {
-                        return false;
-                    }
-                }
-                return true;
-            },
-            enumerable: true,
-            configurable: true
-        });
-        PostProcessRenderEffect.prototype._update = function () {
-            for (var renderPassName in this._renderPasses) {
-                this._renderPasses[renderPassName]._update();
-            }
-        };
-        PostProcessRenderEffect.prototype.addPass = function (renderPass) {
-            this._renderPasses[renderPass._name] = renderPass;
-            this._linkParameters();
-        };
-        PostProcessRenderEffect.prototype.removePass = function (renderPass) {
-            delete this._renderPasses[renderPass._name];
-            this._linkParameters();
-        };
-        PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
-            this._renderEffectAsPasses[renderEffect._name] = renderEffect;
-            this._linkParameters();
-        };
-        PostProcessRenderEffect.prototype.getPass = function (passName) {
-            for (var renderPassName in this._renderPasses) {
-                if (renderPassName === passName) {
-                    return this._renderPasses[passName];
-                }
-            }
-        };
-        PostProcessRenderEffect.prototype.emptyPasses = function () {
-            this._renderPasses = {};
-            this._linkParameters();
-        };
-        PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
-            var cameraKey;
-            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
-            for (var i = 0; i < _cam.length; i++) {
-                var camera = _cam[i];
-                var cameraName = camera.name;
-                if (this._singleInstance) {
-                    cameraKey = 0;
-                }
-                else {
-                    cameraKey = cameraName;
-                }
-                this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
-                var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
-                if (!this._indicesForCamera[cameraName]) {
-                    this._indicesForCamera[cameraName] = [];
-                }
-                this._indicesForCamera[cameraName].push(index);
-                if (this._cameras.indexOf(camera) === -1) {
-                    this._cameras[cameraName] = camera;
-                }
-                for (var passName in this._renderPasses) {
-                    this._renderPasses[passName]._incRefCount();
-                }
-            }
-            this._linkParameters();
-        };
-        PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
-            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
-            for (var i = 0; i < _cam.length; i++) {
-                var camera = _cam[i];
-                var cameraName = camera.name;
-                camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
-                var index = this._cameras.indexOf(cameraName);
-                this._indicesForCamera.splice(index, 1);
-                this._cameras.splice(index, 1);
-                for (var passName in this._renderPasses) {
-                    this._renderPasses[passName]._decRefCount();
-                }
-            }
-        };
-        PostProcessRenderEffect.prototype._enable = function (cameras) {
-            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
-            for (var i = 0; i < _cam.length; i++) {
-                var camera = _cam[i];
-                var cameraName = camera.name;
-                for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
-                    if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
-                        cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
-                    }
-                }
-                for (var passName in this._renderPasses) {
-                    this._renderPasses[passName]._incRefCount();
-                }
-            }
-        };
-        PostProcessRenderEffect.prototype._disable = function (cameras) {
-            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
-            for (var i = 0; i < _cam.length; i++) {
-                var camera = _cam[i];
-                var cameraName = camera.Name;
-                camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
-                for (var passName in this._renderPasses) {
-                    this._renderPasses[passName]._decRefCount();
-                }
-            }
-        };
-        PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
-            if (this._singleInstance) {
-                return this._postProcesses[0];
-            }
-            else {
-                return this._postProcesses[camera.name];
-            }
-        };
-        PostProcessRenderEffect.prototype._linkParameters = function () {
-            var _this = this;
-            for (var index in this._postProcesses) {
-                if (this.applyParameters) {
-                    this.applyParameters(this._postProcesses[index]);
-                }
-                this._postProcesses[index].onBeforeRender = function (effect) {
-                    _this._linkTextures(effect);
-                };
-            }
-        };
-        PostProcessRenderEffect.prototype._linkTextures = function (effect) {
-            for (var renderPassName in this._renderPasses) {
-                effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
-            }
-            for (var renderEffectName in this._renderEffectAsPasses) {
-                effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
-            }
-        };
-        return PostProcessRenderEffect;
-    })();
-    BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
-})(BABYLON || (BABYLON = {}));
+var BABYLON;
+(function (BABYLON) {
+    var PostProcessRenderEffect = (function () {
+        function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
+            this._engine = engine;
+            this._name = name;
+            this._singleInstance = singleInstance || true;
+            this._getPostProcess = getPostProcess;
+            this._cameras = [];
+            this._indicesForCamera = [];
+            this._postProcesses = {};
+            this._renderPasses = {};
+            this._renderEffectAsPasses = {};
+        }
+        Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
+            get: function () {
+                for (var index in this._postProcesses) {
+                    if (!this._postProcesses[index].isSupported) {
+                        return false;
+                    }
+                }
+                return true;
+            },
+            enumerable: true,
+            configurable: true
+        });
+        PostProcessRenderEffect.prototype._update = function () {
+            for (var renderPassName in this._renderPasses) {
+                this._renderPasses[renderPassName]._update();
+            }
+        };
+        PostProcessRenderEffect.prototype.addPass = function (renderPass) {
+            this._renderPasses[renderPass._name] = renderPass;
+            this._linkParameters();
+        };
+        PostProcessRenderEffect.prototype.removePass = function (renderPass) {
+            delete this._renderPasses[renderPass._name];
+            this._linkParameters();
+        };
+        PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
+            this._renderEffectAsPasses[renderEffect._name] = renderEffect;
+            this._linkParameters();
+        };
+        PostProcessRenderEffect.prototype.getPass = function (passName) {
+            for (var renderPassName in this._renderPasses) {
+                if (renderPassName === passName) {
+                    return this._renderPasses[passName];
+                }
+            }
+        };
+        PostProcessRenderEffect.prototype.emptyPasses = function () {
+            this._renderPasses = {};
+            this._linkParameters();
+        };
+        PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
+            var cameraKey;
+            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
+            for (var i = 0; i < _cam.length; i++) {
+                var camera = _cam[i];
+                var cameraName = camera.name;
+                if (this._singleInstance) {
+                    cameraKey = 0;
+                }
+                else {
+                    cameraKey = cameraName;
+                }
+                this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
+                var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
+                if (!this._indicesForCamera[cameraName]) {
+                    this._indicesForCamera[cameraName] = [];
+                }
+                this._indicesForCamera[cameraName].push(index);
+                if (this._cameras.indexOf(camera) === -1) {
+                    this._cameras[cameraName] = camera;
+                }
+                for (var passName in this._renderPasses) {
+                    this._renderPasses[passName]._incRefCount();
+                }
+            }
+            this._linkParameters();
+        };
+        PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
+            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
+            for (var i = 0; i < _cam.length; i++) {
+                var camera = _cam[i];
+                var cameraName = camera.name;
+                camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
+                var index = this._cameras.indexOf(cameraName);
+                this._indicesForCamera.splice(index, 1);
+                this._cameras.splice(index, 1);
+                for (var passName in this._renderPasses) {
+                    this._renderPasses[passName]._decRefCount();
+                }
+            }
+        };
+        PostProcessRenderEffect.prototype._enable = function (cameras) {
+            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
+            for (var i = 0; i < _cam.length; i++) {
+                var camera = _cam[i];
+                var cameraName = camera.name;
+                for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
+                    if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
+                        cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
+                    }
+                }
+                for (var passName in this._renderPasses) {
+                    this._renderPasses[passName]._incRefCount();
+                }
+            }
+        };
+        PostProcessRenderEffect.prototype._disable = function (cameras) {
+            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
+            for (var i = 0; i < _cam.length; i++) {
+                var camera = _cam[i];
+                var cameraName = camera.Name;
+                camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
+                for (var passName in this._renderPasses) {
+                    this._renderPasses[passName]._decRefCount();
+                }
+            }
+        };
+        PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
+            if (this._singleInstance) {
+                return this._postProcesses[0];
+            }
+            else {
+                return this._postProcesses[camera.name];
+            }
+        };
+        PostProcessRenderEffect.prototype._linkParameters = function () {
+            var _this = this;
+            for (var index in this._postProcesses) {
+                if (this.applyParameters) {
+                    this.applyParameters(this._postProcesses[index]);
+                }
+                this._postProcesses[index].onBeforeRender = function (effect) {
+                    _this._linkTextures(effect);
+                };
+            }
+        };
+        PostProcessRenderEffect.prototype._linkTextures = function (effect) {
+            for (var renderPassName in this._renderPasses) {
+                effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
+            }
+            for (var renderEffectName in this._renderEffectAsPasses) {
+                effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
+            }
+        };
+        return PostProcessRenderEffect;
+    })();
+    BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.postProcessRenderEffect.js.map

+ 0 - 0
src/PostProcess/RenderPipeline/babylon.postProcessRenderPass.js


Some files were not shown because too many files changed in this diff