Browse Source

More files ported to Typescript

David Catuhe 11 years ago
parent
commit
05358eeb88
71 changed files with 9351 additions and 4323 deletions
  1. 1 6
      Babylon/Animations/babylon.animation.ts
  2. 1 1
      Babylon/Cameras/babylon.camera.js
  3. 1 1
      Babylon/Cameras/babylon.camera.ts
  4. 2 0
      Babylon/Collisions/babylon.collider.ts
  5. 1 1
      Babylon/Culling/Octrees/babylon.octree.ts
  6. 6 8
      Babylon/Culling/Octrees/babylon.octreeBlock.js
  7. 6 8
      Babylon/Culling/Octrees/babylon.octreeBlock.ts
  8. 2 3
      Babylon/Culling/babylon.boundingInfo.js
  9. 2 2
      Babylon/Culling/babylon.boundingInfo.ts
  10. 4 3
      Babylon/Culling/babylon.boundingSphere.js
  11. 5 2
      Babylon/Culling/babylon.boundingSphere.ts
  12. 268 279
      Babylon/Materials/babylon.effect.js
  13. 355 0
      Babylon/Materials/babylon.effect.ts
  14. 68 71
      Babylon/Materials/babylon.material.js
  15. 82 0
      Babylon/Materials/babylon.material.ts
  16. 39 32
      Babylon/Materials/babylon.multiMaterial.js
  17. 35 0
      Babylon/Materials/babylon.multiMaterial.ts
  18. 171 196
      Babylon/Materials/babylon.shaderMaterial.js
  19. 191 0
      Babylon/Materials/babylon.shaderMaterial.ts
  20. 432 434
      Babylon/Materials/babylon.standardMaterial.js
  21. 535 0
      Babylon/Materials/babylon.standardMaterial.ts
  22. 95 92
      Babylon/Materials/textures/babylon.baseTexture.js
  23. 120 0
      Babylon/Materials/textures/babylon.baseTexture.ts
  24. 61 55
      Babylon/Materials/textures/babylon.cubeTexture.js
  25. 59 0
      Babylon/Materials/textures/babylon.cubeTexture.ts
  26. 75 71
      Babylon/Materials/textures/babylon.dynamicTexture.js
  27. 79 0
      Babylon/Materials/textures/babylon.dynamicTexture.ts
  28. 57 58
      Babylon/Materials/textures/babylon.mirrorTexture.js
  29. 49 0
      Babylon/Materials/textures/babylon.mirrorTexture.ts
  30. 93 97
      Babylon/Materials/textures/babylon.renderTargetTexture.js
  31. 109 0
      Babylon/Materials/textures/babylon.renderTargetTexture.ts
  32. 187 190
      Babylon/Materials/textures/babylon.texture.js
  33. 225 0
      Babylon/Materials/textures/babylon.texture.ts
  34. 53 50
      Babylon/Materials/textures/babylon.videoTexture.js
  35. 57 0
      Babylon/Materials/textures/babylon.videoTexture.ts
  36. 7 0
      Babylon/Math/babylon.math.js
  37. 5 1
      Babylon/Math/babylon.math.ts
  38. 2 8
      Babylon/Mesh/babylon.mesh.js
  39. 2 9
      Babylon/Mesh/babylon.mesh.ts
  40. 2 3
      Babylon/Mesh/babylon.subMesh.js
  41. 2 2
      Babylon/Mesh/babylon.subMesh.ts
  42. 4 0
      Babylon/Mesh/babylon.vertexBuffer.js
  43. 5 1
      Babylon/Mesh/babylon.vertexBuffer.ts
  44. 4 3
      Babylon/Particles/babylon.particleSystem.js
  45. 1 1
      Babylon/Physics/babylon.physicsEngine.ts
  46. 4 4
      Babylon/PostProcess/babylon.postProcess.ts
  47. 83 82
      Babylon/PostProcess/babylon.postProcessManager.js
  48. 93 0
      Babylon/PostProcess/babylon.postProcessManager.ts
  49. 69 76
      Babylon/Rendering/babylon.boundingBoxRenderer.js
  50. 85 0
      Babylon/Rendering/babylon.boundingBoxRenderer.ts
  51. 86 87
      Babylon/Rendering/babylon.renderingGroup.js
  52. 105 0
      Babylon/Rendering/babylon.renderingGroup.ts
  53. 86 88
      Babylon/Rendering/babylon.renderingManager.js
  54. 108 0
      Babylon/Rendering/babylon.renderingManager.ts
  55. 63 69
      Babylon/Sprites/babylon.sprite.js
  56. 76 0
      Babylon/Sprites/babylon.sprite.ts
  57. 165 173
      Babylon/Sprites/babylon.spriteManager.js
  58. 188 0
      Babylon/Sprites/babylon.spriteManager.ts
  59. 91 120
      Babylon/Tools/babylon.andOrNotEvaluator.js
  60. 102 0
      Babylon/Tools/babylon.andOrNotEvaluator.ts
  61. 0 3
      Babylon/Tools/babylon.database.js
  62. 81 81
      Babylon/Tools/babylon.tags.js
  63. 93 0
      Babylon/Tools/babylon.tags.ts
  64. 1 0
      Babylon/Tools/babylon.tools.js
  65. 12 4
      Babylon/Tools/babylon.tools.ts
  66. 936 953
      Babylon/babylon.engine.js
  67. 1195 0
      Babylon/babylon.engine.ts
  68. 1 0
      Babylon/babylon.mixins.js
  69. 50 0
      Babylon/babylon.mixins.ts
  70. 858 895
      Babylon/babylon.scene.js
  71. 1160 0
      Babylon/babylon.scene.ts

+ 1 - 6
Babylon/Animations/babylon.animation.ts

@@ -1,8 +1,4 @@
 module BABYLON {
-    export interface IAnimatable {
-         animations: Array<Animation>;
-    }
-
     export class Animation {
         private _keys: Array<any>;
         private _offsetsCache = {};
@@ -121,7 +117,7 @@
             return this._keys[this._keys.length - 1].value;
         }
 
-        public animate(target, delay: number, from, to, loop: boolean, speedRatio: number): boolean {
+        public animate(target, delay: number, from: number, to: number, loop: boolean, speedRatio: number): boolean {
             if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
                 return false;
             }
@@ -224,6 +220,5 @@
         public static ANIMATIONLOOPMODE_RELATIVE = 0;
         public static ANIMATIONLOOPMODE_CYCLE = 1;
         public static ANIMATIONLOOPMODE_CONSTANT = 2;
-
     }
 } 

+ 1 - 1
Babylon/Cameras/babylon.camera.js

@@ -25,9 +25,9 @@ var BABYLON;
             this.mode = Camera.PERSPECTIVE_CAMERA;
             this.isIntermediate = false;
             this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
+            this.subCameras = [];
             this._computedViewMatrix = BABYLON.Matrix.Identity();
             this._projectionMatrix = new BABYLON.Matrix();
-            this.subCameras = [];
             this._postProcesses = [];
             this._postProcessesTakenIndices = [];
 

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

@@ -17,11 +17,11 @@
         public mode = Camera.PERSPECTIVE_CAMERA;
         public isIntermediate = false;
         public viewport = new Viewport(0, 0, 1.0, 1.0);
+        public subCameras = [];
 
         private _computedViewMatrix = BABYLON.Matrix.Identity();
         private _projectionMatrix = new BABYLON.Matrix();
         private _worldMatrix: Matrix;
-        private subCameras = [];
         public _postProcesses = [];
         public _postProcessesTakenIndices = [];
 

+ 2 - 0
Babylon/Collisions/babylon.collider.ts

@@ -64,6 +64,8 @@
         public basePointWorld = BABYLON.Vector3.Zero();
         public velocityWorld = BABYLON.Vector3.Zero();
         public normalizedVelocity = BABYLON.Vector3.Zero();
+        public initialVelocity: Vector3;
+        public initialPosition: Vector3;
         public nearestDistance: number;
         public intersectionPoint: Vector3;
         public collidedMesh; //ANY

+ 1 - 1
Babylon/Culling/Octrees/babylon.octree.ts

@@ -9,7 +9,7 @@
         private _selection;
 
 
-        constructor(maxBlockCapacity: number) {
+        constructor(maxBlockCapacity?: number) {
             this._maxBlockCapacity = maxBlockCapacity || 64;
             this._selection = new BABYLON.SmartArray(256);
         }

+ 6 - 8
Babylon/Culling/Octrees/babylon.octreeBlock.js

@@ -33,10 +33,6 @@
         }
         // Methods
         OctreeBlock.prototype.addMesh = function (mesh) {
-            if (!mesh.subMeshes) {
-                return;
-            }
-
             if (this.blocks) {
                 for (var index = 0; index < this.blocks.length; index++) {
                     var block = this.blocks[index];
@@ -50,10 +46,12 @@
                 this.meshes.push(mesh);
 
                 this.subMeshes[localMeshIndex] = [];
-                for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
-                    var subMesh = mesh.subMeshes[subIndex];
-                    if (mesh.subMeshes.length === 1 || subMesh.getBoundingInfo().boundingBox.intersectsMinMax(this._minPoint, this._maxPoint)) {
-                        this.subMeshes[localMeshIndex].push(subMesh);
+                if (mesh.subMeshes) {
+                    for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
+                        var subMesh = mesh.subMeshes[subIndex];
+                        if (mesh.subMeshes.length === 1 || subMesh.getBoundingInfo().boundingBox.intersectsMinMax(this._minPoint, this._maxPoint)) {
+                            this.subMeshes[localMeshIndex].push(subMesh);
+                        }
                     }
                 }
             }

+ 6 - 8
Babylon/Culling/Octrees/babylon.octreeBlock.ts

@@ -39,10 +39,6 @@
 
         // Methods
         public addMesh(mesh: Mesh): void {
-            if (!mesh.subMeshes) {
-                return;
-            }
-
             if (this.blocks) {
                 for (var index = 0; index < this.blocks.length; index++) {
                     var block = this.blocks[index];
@@ -56,10 +52,12 @@
                 this.meshes.push(mesh);
 
                 this.subMeshes[localMeshIndex] = [];
-                for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
-                    var subMesh = mesh.subMeshes[subIndex];
-                    if (mesh.subMeshes.length === 1 || subMesh.getBoundingInfo().boundingBox.intersectsMinMax(this._minPoint, this._maxPoint)) {
-                        this.subMeshes[localMeshIndex].push(subMesh);
+                if (mesh.subMeshes) {
+                    for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
+                        var subMesh = mesh.subMeshes[subIndex];
+                        if (mesh.subMeshes.length === 1 || subMesh.getBoundingInfo().boundingBox.intersectsMinMax(this._minPoint, this._maxPoint)) {
+                            this.subMeshes[localMeshIndex].push(subMesh);
+                        }
                     }
                 }
             }

+ 2 - 3
Babylon/Culling/babylon.boundingInfo.js

@@ -31,10 +31,9 @@
             this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
         }
         // Methods
-        BoundingInfo.prototype._update = function (world, scale) {
-            if (typeof scale === "undefined") { scale = 1.0; }
+        BoundingInfo.prototype._update = function (world) {
             this.boundingBox._update(world);
-            this.boundingSphere._update(world, scale);
+            this.boundingSphere._update(world);
         };
 
         BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {

+ 2 - 2
Babylon/Culling/babylon.boundingInfo.ts

@@ -32,9 +32,9 @@
         }
 
         // Methods
-        public _update(world: Matrix, scale: number = 1.0) {
+        public _update(world: Matrix) {
             this.boundingBox._update(world);
-            this.boundingSphere._update(world, scale);
+            this.boundingSphere._update(world);
         }
 
         public isInFrustum(frustumPlanes: Plane[]): boolean {

+ 4 - 3
Babylon/Culling/babylon.boundingSphere.js

@@ -4,6 +4,7 @@
         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);
@@ -14,10 +15,10 @@
             this._update(BABYLON.Matrix.Identity());
         }
         // Methods
-        BoundingSphere.prototype._update = function (world, scale) {
-            if (typeof scale === "undefined") { scale = 1.0; }
+        BoundingSphere.prototype._update = function (world) {
             BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
-            this.radiusWorld = this.radius * scale;
+            BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 0, 0, world, this._tempRadiusVector);
+            this.radiusWorld = this._tempRadiusVector.length() * this.radius;
         };
 
         BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {

+ 5 - 2
Babylon/Culling/babylon.boundingSphere.ts

@@ -5,6 +5,8 @@
         public centerWorld: Vector3;
         public radiusWorld: number;
 
+        private _tempRadiusVector = Vector3.Zero();
+
         constructor(public minimum: Vector3, public maximum: Vector3) {
             var distance = BABYLON.Vector3.Distance(minimum, maximum);
 
@@ -16,9 +18,10 @@
         }
 
         // Methods
-        public _update(world: Matrix, scale: number = 1.0): void {
+        public _update(world: Matrix): void {
             BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
-            this.radiusWorld = this.radius * scale;
+            BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 0, 0, world, this._tempRadiusVector);
+            this.radiusWorld = this._tempRadiusVector.length() * this.radius;
         }
 
         public isInFrustum(frustumPlanes: Plane[]): boolean {

+ 268 - 279
Babylon/Materials/babylon.effect.js

@@ -1,351 +1,340 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-
-    BABYLON.Effect = function (baseName, attributesNames, uniformsNames, samplers, engine, defines, optionalDefines, onCompiled, onError) {
-        this._engine = engine;
-        this.name = baseName;
-        this.defines = defines;
-        this._uniformsNames = uniformsNames.concat(samplers);
-        this._samplers = samplers;
-        this._isReady = false;
-        this._compilationError = "";
-        this._attributesNames = attributesNames;
-
-        this.onError = onError;
-        this.onCompiled = onCompiled;
-
-        var vertexSource;
-        var fragmentSource;
-
-        if (baseName.vertexElement) {
-            vertexSource = document.getElementById(baseName.vertexElement);
-            fragmentSource = document.getElementById(baseName.fragmentElement);
-        } else {
-            vertexSource = baseName.vertexElement || baseName.vertex || baseName;
-            fragmentSource = baseName.fragmentElement || baseName.fragment || baseName;
-        }
+var BABYLON;
+(function (BABYLON) {
+    var Effect = (function () {
+        function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, optionalDefines, 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);
+                fragmentSource = document.getElementById(baseName.fragmentElement);
+            } else {
+                vertexSource = baseName.vertexElement || baseName.vertex || baseName;
+                fragmentSource = baseName.fragmentElement || baseName.fragment || baseName;
+            }
 
-        var that = this;
-        this._loadVertexShader(vertexSource, function (vertexCode) {
-            that._loadFragmentShader(fragmentSource, function (fragmentCode) {
-                that._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, optionalDefines);
+            this._loadVertexShader(vertexSource, function (vertexCode) {
+                _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
+                    _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, optionalDefines);
+                });
             });
-        });
-
-        // Cache
-        this._valueCache = [];
-    };
-
-    // Events
-    BABYLON.Effect.prototype.onCompiled = null;
-    BABYLON.Effect.prototype.onError = null;
-
-    // Properties
-    BABYLON.Effect.prototype.isReady = function () {
-        return this._isReady;
-    };
-
-    BABYLON.Effect.prototype.getProgram = function () {
-        return this._program;
-    };
-
-    BABYLON.Effect.prototype.getAttributesNames = function () {
-        return this._attributesNames;
-    };
-
-    BABYLON.Effect.prototype.getAttribute = function (index) {
-        return this._attributes[index];
-    };
-
-    BABYLON.Effect.prototype.getAttributesCount = function () {
-        return this._attributes.length;
-    };
-
-    BABYLON.Effect.prototype.getUniformIndex = function (uniformName) {
-        return this._uniformsNames.indexOf(uniformName);
-    };
-
-    BABYLON.Effect.prototype.getUniform = function (uniformName) {
-        return this._uniforms[this._uniformsNames.indexOf(uniformName)];
-    };
-
-    BABYLON.Effect.prototype.getSamplers = function () {
-        return this._samplers;
-    };
-
-    BABYLON.Effect.prototype.getCompilationError = function () {
-        return this._compilationError;
-    };
-
-    // Methods
-    BABYLON.Effect.prototype._loadVertexShader = function (vertex, callback) {
-        // DOM element ?
-        if (vertex instanceof HTMLElement) {
-            var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
-            callback(vertexCode);
-            return;
         }
+        // Properties
+        Effect.prototype.isReady = function () {
+            return this._isReady;
+        };
+
+        Effect.prototype.getProgram = function () {
+            return this._program;
+        };
+
+        Effect.prototype.getAttributesNames = function () {
+            return this._attributesNames;
+        };
+
+        Effect.prototype.getAttribute = function (index) {
+            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 (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
-            callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
-            return;
-        }
+            // Is in local store ?
+            if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
+                callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
+                return;
+            }
 
-        var vertexShaderUrl;
+            var vertexShaderUrl;
 
-        if (vertex[0] === ".") {
-            vertexShaderUrl = vertex;
-        } else {
-            vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
-        }
+            if (vertex[0] === ".") {
+                vertexShaderUrl = vertex;
+            } else {
+                vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
+            }
 
-        // Vertex shader
-        BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
-    };
+            // Vertex shader
+            BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
+        };
 
-    BABYLON.Effect.prototype._loadFragmentShader = function (fragment, callback) {
-        // DOM element ?
-        if (fragment instanceof HTMLElement) {
-            var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
-            callback(fragmentCode);
-            return;
-        }
+        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 (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
-            callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
-            return;
-        }
+            // Is in local store ?
+            if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
+                callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
+                return;
+            }
 
-        var fragmentShaderUrl;
+            var fragmentShaderUrl;
 
-        if (fragment[0] === ".") {
-            fragmentShaderUrl = fragment;
-        } else {
-            fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
-        }
+            if (fragment[0] === ".") {
+                fragmentShaderUrl = fragment;
+            } else {
+                fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
+            }
 
-        // Fragment shader
-        BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
-    };
+            // Fragment shader
+            BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
+        };
 
-    BABYLON.Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, optionalDefines, useFallback) {
-        try {
-            var engine = this._engine;
-            this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
+        Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, optionalDefines, useFallback) {
+            try  {
+                var engine = this._engine;
+                this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
 
-            this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
-            this._attributes = engine.getAttributes(this._program, attributesNames);
+                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]);
+                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--;
+                    if (sampler == null) {
+                        this._samplers.splice(index, 1);
+                        index--;
+                    }
                 }
-            }
 
-            engine.bindSamplers(this);
+                engine.bindSamplers(this);
 
-            this._isReady = true;
-            if (this.onCompiled) {
-                this.onCompiled(this);
-            }
-        } catch (e) {
-            if (!useFallback && optionalDefines) {
-                for (var index = 0; index < optionalDefines.length; index++) {
-                    defines = defines.replace(optionalDefines[index], "");
+                this._isReady = true;
+                if (this.onCompiled) {
+                    this.onCompiled(this);
                 }
-                this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, optionalDefines, true);
-            } else {
-                console.error("Unable to compile effect: " + this.name);
-                console.error("Defines: " + defines);
-                console.error("Optional defines: " + optionalDefines);
-                this._compilationError = e.message;
-
-                if (this.onError) {
-                    this.onError(this, this._compilationError);
+            } catch (e) {
+                if (!useFallback && optionalDefines) {
+                    for (index = 0; index < optionalDefines.length; index++) {
+                        defines = defines.replace(optionalDefines[index], "");
+                    }
+                    this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, optionalDefines, true);
+                } else {
+                    console.error("Unable to compile effect: " + this.name);
+                    console.error("Defines: " + defines);
+                    console.error("Optional defines: " + optionalDefines);
+                    this._compilationError = e.message;
+
+                    if (this.onError) {
+                        this.onError(this, this._compilationError);
+                    }
                 }
             }
-        }
-    };
-
-    BABYLON.Effect.prototype._bindTexture = function (channel, texture) {
-        this._engine._bindTexture(this._samplers.indexOf(channel), texture);
-    };
-
-    BABYLON.Effect.prototype.setTexture = function (channel, texture) {
-        this._engine.setTexture(this._samplers.indexOf(channel), texture);
-    };
-
-    BABYLON.Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
-        this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
-    };
-
-    //BABYLON.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];
-    //    }
-    //};
-
-    BABYLON.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;
-    };
-
-    BABYLON.Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
-        if (!this._valueCache[uniformName]) {
-            this._valueCache[uniformName] = [x, y, z];
-            return;
-        }
+        };
+
+        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);
+        };
+
+        //public _cacheMatrix(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;
-        this._valueCache[uniformName][2] = z;
-    };
+            this._valueCache[uniformName][0] = x;
+            this._valueCache[uniformName][1] = y;
+        };
 
-    BABYLON.Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
-        if (!this._valueCache[uniformName]) {
-            this._valueCache[uniformName] = [x, y, z, w];
-            return;
-        }
+        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;
-        this._valueCache[uniformName][3] = w;
-    };
+            this._valueCache[uniformName][0] = x;
+            this._valueCache[uniformName][1] = y;
+            this._valueCache[uniformName][2] = z;
+        };
 
-    BABYLON.Effect.prototype.setArray = function (uniformName, array) {
-        this._engine.setArray(this.getUniform(uniformName), array);
+        Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
+            if (!this._valueCache[uniformName]) {
+                this._valueCache[uniformName] = [x, y, z, w];
+                return;
+            }
 
-        return this;
-    };
+            this._valueCache[uniformName][0] = x;
+            this._valueCache[uniformName][1] = y;
+            this._valueCache[uniformName][2] = z;
+            this._valueCache[uniformName][3] = w;
+        };
 
-    BABYLON.Effect.prototype.setMatrices = function (uniformName, matrices) {
-        this._engine.setMatrices(this.getUniform(uniformName), matrices);
+        Effect.prototype.setArray = function (uniformName, array) {
+            this._engine.setArray(this.getUniform(uniformName), array);
 
-        return this;
-    };
+            return this;
+        };
 
-    BABYLON.Effect.prototype.setMatrix = function (uniformName, matrix) {
-        //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
-        //    return;
+        Effect.prototype.setMatrices = function (uniformName, matrices) {
+            this._engine.setMatrices(this.getUniform(uniformName), matrices);
 
-        //this._cacheMatrix(uniformName, matrix);
-        this._engine.setMatrix(this.getUniform(uniformName), matrix);
+            return this;
+        };
 
-        return this;
-    };
+        Effect.prototype.setMatrix = function (uniformName, matrix) {
+            //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
+            //    return;
+            //this._cacheMatrix(uniformName, matrix);
+            this._engine.setMatrix(this.getUniform(uniformName), matrix);
 
-    BABYLON.Effect.prototype.setFloat = function (uniformName, value) {
-        if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
             return this;
+        };
 
-        this._valueCache[uniformName] = value;
+        Effect.prototype.setFloat = function (uniformName, value) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
+                return this;
 
-        this._engine.setFloat(this.getUniform(uniformName), value);
+            this._valueCache[uniformName] = value;
 
-        return this;
-    };
+            this._engine.setFloat(this.getUniform(uniformName), value);
 
-    BABYLON.Effect.prototype.setBool = function (uniformName, bool) {
-        if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
             return this;
+        };
 
-        this._valueCache[uniformName] = bool;
+        Effect.prototype.setBool = function (uniformName, bool) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
+                return this;
 
-        this._engine.setBool(this.getUniform(uniformName), bool);
+            this._valueCache[uniformName] = bool;
 
-        return this;
-    };
+            this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
 
-    BABYLON.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);
+        Effect.prototype.setVector2 = function (uniformName, vector2) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
+                return this;
 
-        return this;
-    };
+            this._cacheFloat2(uniformName, vector2.x, vector2.y);
+            this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
 
-    BABYLON.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);
+        Effect.prototype.setFloat2 = function (uniformName, x, y) {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
+                return this;
 
-        return this;
-    };
+            this._cacheFloat2(uniformName, x, y);
+            this._engine.setFloat2(this.getUniform(uniformName), x, y);
 
-    BABYLON.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);
+        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._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
+            this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
 
-        return this;
-    };
+            this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
 
-    BABYLON.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);
+        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;
 
-        return this;
-    };
+            this._cacheFloat3(uniformName, x, y, z);
+            this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
 
-    BABYLON.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);
+        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;
 
-        return this;
-    };
+            this._cacheFloat4(uniformName, x, y, z, w);
+            this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
 
-    BABYLON.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);
+        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;
 
-        return this;
-    };
+            this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
+            this._engine.setColor3(this.getUniform(uniformName), color3);
 
-    BABYLON.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);
+        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;
 
-        return this;
-    };
+            this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
+            this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
 
-    // Statics
-    BABYLON.Effect.ShadersStore = {};
-
-})();
+            return this;
+        };
+
+        Effect.ShadersStore = {};
+        return Effect;
+    })();
+    BABYLON.Effect = Effect;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.effect.js.map

+ 355 - 0
Babylon/Materials/babylon.effect.ts

@@ -0,0 +1,355 @@
+module BABYLON {
+    export class Effect {
+        public name: any;
+        public defines: string;
+        public onCompiled: (effect: Effect) => void;
+        public onError: (effect: Effect, errors: string) => void;
+
+        private _engine: Engine;
+        private _uniformsNames: string[];
+        private _samplers: string[];
+        private _isReady = false;
+        private _compilationError = "";
+        private _attributesNames: string[];
+        private _attributes: number[];
+        private _uniforms: WebGLUniformLocation[];
+        public _key: string;
+
+        private _program: WebGLProgram;
+        private _valueCache = [];
+
+        constructor(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], engine, defines?: string, optionalDefines?: string, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void) {
+            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);
+                fragmentSource = document.getElementById(baseName.fragmentElement);
+            } else {
+                vertexSource = baseName.vertexElement || baseName.vertex || baseName;
+                fragmentSource = baseName.fragmentElement || baseName.fragment || baseName;
+            }
+
+            this._loadVertexShader(vertexSource, vertexCode => {
+                this._loadFragmentShader(fragmentSource, (fragmentCode) => {
+                    this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, optionalDefines);
+                });
+            });
+        }
+
+        // Properties
+        public isReady(): boolean {
+            return this._isReady;
+        }
+
+        public getProgram(): WebGLProgram {
+            return this._program;
+        }
+
+        public getAttributesNames(): string[] {
+            return this._attributesNames;
+        }
+
+        public getAttribute(index: number): number {
+            return this._attributes[index];
+        }
+
+        public getAttributesCount(): number {
+            return this._attributes.length;
+        }
+
+        public getUniformIndex(uniformName: string): number {
+            return this._uniformsNames.indexOf(uniformName);
+        }
+
+        public getUniform(uniformName: string): WebGLUniformLocation {
+            return this._uniforms[this._uniformsNames.indexOf(uniformName)];
+        }
+
+        public getSamplers(): string[] {
+            return this._samplers;
+        }
+
+        public getCompilationError(): string {
+            return this._compilationError;
+        }
+
+        // Methods
+        public _loadVertexShader(vertex: any, callback: (data: any) => void): void {
+            // DOM element ?
+            if (vertex instanceof HTMLElement) {
+                var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
+                callback(vertexCode);
+                return;
+            }
+
+            // Is in local store ?
+            if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
+                callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
+                return;
+            }
+
+            var vertexShaderUrl;
+
+            if (vertex[0] === ".") {
+                vertexShaderUrl = vertex;
+            } else {
+                vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
+            }
+
+            // Vertex shader
+            BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
+        }
+
+        public _loadFragmentShader(fragment: any, callback: (data: any) => void): void {
+            // DOM element ?
+            if (fragment instanceof HTMLElement) {
+                var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
+                callback(fragmentCode);
+                return;
+            }
+
+            // Is in local store ?
+            if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
+                callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
+                return;
+            }
+
+            var fragmentShaderUrl;
+
+            if (fragment[0] === ".") {
+                fragmentShaderUrl = fragment;
+            } else {
+                fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
+            }
+
+            // Fragment shader
+            BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
+        }
+
+        public _prepareEffect(vertexSourceCode: string, fragmentSourceCode: string, attributesNames: string[], defines: string, optionalDefines?: string, useFallback?: boolean): void {
+            try {
+                var engine = this._engine;
+                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) {
+                if (!useFallback && optionalDefines) {
+                    for (index = 0; index < optionalDefines.length; index++) {
+                        defines = defines.replace(optionalDefines[index], "");
+                    }
+                    this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, optionalDefines, true);
+                } else {
+                    console.error("Unable to compile effect: " + this.name);
+                    console.error("Defines: " + defines);
+                    console.error("Optional defines: " + optionalDefines);
+                    this._compilationError = e.message;
+
+                    if (this.onError) {
+                        this.onError(this, this._compilationError);
+                    }
+                }
+            }
+        }
+
+        public _bindTexture(channel: string, texture: WebGLTexture): void {
+            this._engine._bindTexture(this._samplers.indexOf(channel), texture);
+        }
+
+        public setTexture(channel: string, texture: Texture): void {
+            this._engine.setTexture(this._samplers.indexOf(channel), texture);
+        }
+
+        public setTextureFromPostProcess(channel: string, postProcess: PostProcess): void {
+            this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
+        }
+
+        //public _cacheMatrix(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];
+        //    }
+        //};
+
+        public _cacheFloat2(uniformName: string, x: number, y: number): void {
+            if (!this._valueCache[uniformName]) {
+                this._valueCache[uniformName] = [x, y];
+                return;
+            }
+
+            this._valueCache[uniformName][0] = x;
+            this._valueCache[uniformName][1] = y;
+        }
+
+        public _cacheFloat3(uniformName: string, x: number, y: number, z: number): void {
+            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;
+        }
+
+        public _cacheFloat4(uniformName: string, x: number, y: number, z: number, w: number): void {
+            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;
+        }
+
+        public setArray(uniformName: string, array: number[]): Effect {
+            this._engine.setArray(this.getUniform(uniformName), array);
+
+            return this;
+        }
+
+        public setMatrices(uniformName: string, matrices: Float32Array): Effect {
+            this._engine.setMatrices(this.getUniform(uniformName), matrices);
+
+            return this;
+        }
+
+        public setMatrix(uniformName: string, matrix: Matrix): Effect {
+            //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
+            //    return;
+
+            //this._cacheMatrix(uniformName, matrix);
+            this._engine.setMatrix(this.getUniform(uniformName), matrix);
+
+            return this;
+        }
+
+        public setFloat(uniformName: string, value: number): Effect {
+            if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
+                return this;
+
+            this._valueCache[uniformName] = value;
+
+            this._engine.setFloat(this.getUniform(uniformName), value);
+
+            return this;
+        }
+
+        public setBool(uniformName: string, bool: boolean): Effect {
+            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;
+        }
+
+        public setVector2(uniformName: string, vector2: Vector2): Effect {
+            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;
+        }
+
+        public setFloat2(uniformName: string, x: number, y: number): Effect {
+            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;
+        }
+
+        public setVector3(uniformName: string, vector3: Vector3): Effect {
+            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;
+        }
+
+        public setFloat3(uniformName: string, x: number, y: number, z: number): Effect {
+            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;
+        }
+
+        public setFloat4(uniformName: string, x: number, y: number, z: number, w: number): Effect {
+            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;
+        }
+
+        public setColor3(uniformName: string, color3: Color3): Effect {
+            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;
+        }
+
+        public setColor4(uniformName: string, color3: Color3, alpha: number): Effect {
+            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
+        public static ShadersStore = {};
+    }
+} 

+ 68 - 71
Babylon/Materials/babylon.material.js

@@ -1,82 +1,79 @@
-"use strict";
+var BABYLON;
+(function (BABYLON) {
+    var Material = (function () {
+        //ANY
+        function Material(name, scene, doNotAdd) {
+            this.name = name;
+            this.checkReadyOnEveryCall = true;
+            this.checkReadyOnlyOnce = false;
+            this.alpha = 1.0;
+            this.wireframe = false;
+            this.backFaceCulling = true;
+            this._effect = null;
+            this._wasPreviouslyReady = false;
+            this.id = name;
 
-var BABYLON = BABYLON || {};
+            this._scene = scene;
 
-(function () {
-    BABYLON.Material = function (name, scene) {
-        this.name = name;
-        this.id = name;
-        
-        this._scene = scene;
-        scene.materials.push(this);
-    };
-    
-    // Members
-    BABYLON.Material.prototype.checkReadyOnEveryCall = true;
-    BABYLON.Material.prototype.checkReadyOnlyOnce = false;
-    BABYLON.Material.prototype.alpha = 1.0;
-    BABYLON.Material.prototype.wireframe = false;
-    BABYLON.Material.prototype.backFaceCulling = true;
-    BABYLON.Material.prototype._effect = null;
-    BABYLON.Material.prototype._wasPreviouslyReady = false;
+            if (!doNotAdd) {
+                scene.materials.push(this);
+            }
+        }
+        Material.prototype.isReady = function (mesh) {
+            return true;
+        };
 
-    // Events
-    BABYLON.Effect.prototype.onCompiled = null;
-    BABYLON.Effect.prototype.onError = null;
-    BABYLON.Material.prototype.onDispose = null;
+        Material.prototype.getEffect = function () {
+            return this._effect;
+        };
 
-    // Properties
-    BABYLON.Material.prototype.isReady = function (mesh) {
-        return true;
-    };
+        //ANY
+        Material.prototype.getScene = function () {
+            return this._scene;
+        };
 
-    BABYLON.Material.prototype.getEffect = function () {
-        return this._effect;
-    };
-    
-    BABYLON.Material.prototype.needAlphaBlending = function () {
-        return (this.alpha < 1.0);
-    };
-    
-    BABYLON.Material.prototype.needAlphaTesting = function () {
-        return false;
-    };
+        Material.prototype.needAlphaBlending = function () {
+            return (this.alpha < 1.0);
+        };
 
-    // Methods   
-    BABYLON.Material.prototype.trackCreation = function (onCompiled, onError) {
-    };
+        Material.prototype.needAlphaTesting = function () {
+            return false;
+        };
 
-    BABYLON.Material.prototype._preBind = function () {
-        var engine = this._scene.getEngine();
-        
-        engine.enableEffect(this._effect);
-        engine.setState(this.backFaceCulling);
-    };
+        Material.prototype.trackCreation = function (onCompiled, onError) {
+        };
 
-    BABYLON.Material.prototype.bind = function (world, mesh) {       
-    };
-    
-    BABYLON.Material.prototype.unbind = function () {
-    };
-    
-    BABYLON.Material.prototype.baseDispose = function (forceDisposeEffect) {
-        // Remove from scene
-        var index = this._scene.materials.indexOf(this);
-        this._scene.materials.splice(index, 1);
+        Material.prototype._preBind = function () {
+            var engine = this._scene.getEngine();
 
-        // 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;
-        }
+            engine.enableEffect(this._effect);
+            engine.setState(this.backFaceCulling);
+        };
 
-        // Callback
-        if (this.onDispose) {
-            this.onDispose();
-        }
-    };
+        Material.prototype.bind = function (world, mesh) {
+        };
+
+        Material.prototype.unbind = function () {
+        };
+
+        Material.prototype.dispose = function (forceDisposeEffect) {
+            // Remove from scene
+            var index = this._scene.materials.indexOf(this);
+            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;
+            }
 
-    BABYLON.Material.prototype.dispose = function (forceDisposeEffect) {
-        this.baseDispose(forceDisposeEffect);
-    };
-})();
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        };
+        return Material;
+    })();
+    BABYLON.Material = Material;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.material.js.map

+ 82 - 0
Babylon/Materials/babylon.material.ts

@@ -0,0 +1,82 @@
+module BABYLON {
+    export class Material {
+        public id: string;
+        public checkReadyOnEveryCall = true;
+        public checkReadyOnlyOnce = false;
+        public alpha = 1.0;
+        public wireframe = false;
+        public backFaceCulling = true;
+        public onCompiled: (effect: Effect) => void;
+        public onError: (effect: Effect, errors: string) => void;
+        public onDispose: () => void;
+
+        public _effect = null;
+        public _wasPreviouslyReady = false;
+        private _scene; //ANY
+
+        //ANY
+        constructor(public name: string, scene, doNotAdd?: boolean) {
+            this.id = name;
+
+            this._scene = scene;
+
+            if (!doNotAdd) {
+                scene.materials.push(this);
+            }
+        }
+
+        public isReady(mesh?: Mesh): boolean {
+            return true;
+        }
+
+        public getEffect(): Effect {
+            return this._effect;
+        }
+
+        //ANY
+        public getScene() {
+            return this._scene;
+        }
+
+        public needAlphaBlending(): boolean {
+            return (this.alpha < 1.0);
+        }
+
+        public needAlphaTesting(): boolean {
+            return false;
+        }
+
+        public trackCreation(onCompiled: (effect: Effect) => void, onError: (effect: Effect, errors: string) => void) {
+        }
+
+        public _preBind(): void {
+            var engine = this._scene.getEngine();
+
+            engine.enableEffect(this._effect);
+            engine.setState(this.backFaceCulling);
+        }
+
+        public bind(world: Matrix, mesh: Mesh): void {
+        }
+
+        public unbind(): void {
+        }
+
+        public dispose(forceDisposeEffect?: boolean): void {
+            // Remove from scene
+            var index = this._scene.materials.indexOf(this);
+            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;
+            }
+
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        }
+    }
+} 

+ 39 - 32
Babylon/Materials/babylon.multiMaterial.js

@@ -1,37 +1,44 @@
-"use strict";
+var __extends = this.__extends || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    __.prototype = b.prototype;
+    d.prototype = new __();
+};
+var BABYLON;
+(function (BABYLON) {
+    var MultiMaterial = (function (_super) {
+        __extends(MultiMaterial, _super);
+        //ANY
+        function MultiMaterial(name, scene) {
+            _super.call(this, name, scene, true);
+            this.subMaterials = new Array();
 
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.MultiMaterial = function (name, scene) {
-        this.name = name;
-        this.id = name;
-        
-        this._scene = scene;
-        scene.multiMaterials.push(this);
-
-        this.subMaterials = [];
-    };
-
-    // Properties
-    BABYLON.MultiMaterial.prototype.getSubMaterial = function (index) {
-        if (index < 0 || index >= this.subMaterials.length) {
-            return this._scene.defaultMaterial;
+            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];
+        };
 
-        return this.subMaterials[index];
-    };
-    
-    // Methods
-    BABYLON.MultiMaterial.prototype.isReady = function (mesh) {
-        var result = true;
-        for (var index = 0; index < this.subMaterials.length; index++) {
-            var subMaterial = this.subMaterials[index];
-            if (subMaterial) {
-                result &= this.subMaterials[index].isReady(mesh);
+        // 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 result;
-    };
-})();
+            return true;
+        };
+        return MultiMaterial;
+    })(BABYLON.Material);
+    BABYLON.MultiMaterial = MultiMaterial;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.multiMaterial.js.map

+ 35 - 0
Babylon/Materials/babylon.multiMaterial.ts

@@ -0,0 +1,35 @@
+module BABYLON {
+    export class MultiMaterial extends Material {
+        public subMaterials = new Array<Material>();
+
+        //ANY
+        constructor(name: string, scene) {
+            super(name, scene, true);
+
+            scene.multiMaterials.push(this);
+        }
+
+        // Properties
+        public getSubMaterial(index) {
+            if (index < 0 || index >= this.subMaterials.length) {
+                return this.getScene().defaultMaterial;
+            }
+
+            return this.subMaterials[index];
+        }
+
+        // Methods
+        public isReady(mesh?: Mesh): boolean {
+            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;
+        }
+    }
+} 

+ 171 - 196
Babylon/Materials/babylon.shaderMaterial.js

@@ -1,211 +1,186 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.ShaderMaterial = function (name, scene, shaderPath, options) {
-        this.name = name;
-        this.id = name;
-        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 || [];
-        
-        this._options = options;
-        this._scene = scene;
-        scene.materials.push(this);
-
-        this._textures = [];
-        this._floats = [];
-        this._floatsArrays = [];
-        this._colors3 = [];
-        this._colors4 = [];
-        this._vectors2 = [];
-        this._vectors3 = [];
-        this._vectors4 = [];
-        this._matrices = [];
-
-        this._cachedWorldViewMatrix = new BABYLON.Matrix();
-    };
-
-    BABYLON.ShaderMaterial.prototype = Object.create(BABYLON.Material.prototype);
-
-    // Properties   
-    BABYLON.ShaderMaterial.prototype.needAlphaBlending = function () {
-        return this._options.needAlphaBlending;
-    };
-
-    BABYLON.ShaderMaterial.prototype.needAlphaTesting = function () {
-        return this._options.needAlphaTesting;
-    };
-
-    // Methods   
-    BABYLON.ShaderMaterial.prototype._checkUniform = function (uniformName) {
-        if (this._options.uniforms.indexOf(uniformName) === -1) {
-            this._options.uniforms.push(uniformName);
-        }
-    };
-
-    BABYLON.ShaderMaterial.prototype.setTexture = function (name, texture) {
-        if (this._options.samplers.indexOf(name) === -1) {
-            this._options.samplers.push(name);
-        }
-        this._textures[name] = texture;
-
-        return this;
-    };
-
-    BABYLON.ShaderMaterial.prototype.setFloat = function (name, value) {
-        this._checkUniform(name);
-        this._floats[name] = value;
-
-        return this;
-    };
-
-    BABYLON.ShaderMaterial.prototype.setFloats = function (name, value) {
-        this._checkUniform(name);
-        this._floatsArrays[name] = value;
-
-        return this;
-    };
-
-    BABYLON.ShaderMaterial.prototype.setColor3 = function (name, value) {
-        this._checkUniform(name);
-        this._colors3[name] = value;
-
-        return this;
-    };
-
-    BABYLON.ShaderMaterial.prototype.setColor4 = function (name, value) {
-        this._checkUniform(name);
-        this._colors4[name] = value;
-
-        return this;
-    };
-
-    BABYLON.ShaderMaterial.prototype.setVector2 = function (name, value) {
-        this._checkUniform(name);
-        this._vectors2[name] = value;
-
-        return this;
-    };
-
-    BABYLON.ShaderMaterial.prototype.setVector3 = function (name, value) {
-        this._checkUniform(name);
-        this._vectors3[name] = value;
-
-        return this;
-    };
-
-    BABYLON.ShaderMaterial.prototype.setVector4 = function (name, value) {
-        this._checkUniform(name);
-        this._vectors4[name] = value;
-
-        return this;
-    };
-
-    BABYLON.ShaderMaterial.prototype.setMatrix = function (name, value) {
-        this._checkUniform(name);
-        this._matrices[name] = value;
-
-        return this;
-    };
+var __extends = this.__extends || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    __.prototype = b.prototype;
+    d.prototype = new __();
+};
+var BABYLON;
+(function (BABYLON) {
+    var ShaderMaterial = (function (_super) {
+        __extends(ShaderMaterial, _super);
+        //ANY
+        function ShaderMaterial(name, scene, shaderPath, options) {
+            _super.call(this, name, scene);
+            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._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 || [];
+
+            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.setMatrix = function (name, value) {
+            this._checkUniform(name);
+            this._matrices[name] = value;
+
+            return this;
+        };
+
+        ShaderMaterial.prototype.isReady = function (mesh) {
+            var engine = this.getScene().getEngine();
+
+            this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
+
+            if (!this._effect.isReady()) {
+                return false;
+            }
+
+            return true;
+        };
+
+        ShaderMaterial.prototype.bind = function (world, mesh) {
+            // Std values
+            if (this._options.uniforms.indexOf("world") !== -1) {
+                this._effect.setMatrix("world", world);
+            }
 
-    BABYLON.ShaderMaterial.prototype.isReady = function (mesh) {
-        var engine = this._scene.getEngine();
+            if (this._options.uniforms.indexOf("view") !== -1) {
+                this._effect.setMatrix("view", this.getScene().getViewMatrix());
+            }
 
-        this._effect = engine.createEffect(this._shaderPath,
-            this._options.attributes,
-            this._options.uniforms,
-            this._options.samplers,            
-            "", null, this.onCompiled, this.onError);
+            if (this._options.uniforms.indexOf("worldView") !== -1) {
+                world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
+                this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
+            }
 
-        if (!this._effect.isReady()) {
-            return false;
-        }
-
-        return true;
-    };
-
-    BABYLON.ShaderMaterial.prototype.bind = function (world, mesh) {
-        // Std values
-        if (this._options.uniforms.indexOf("world") !== -1) {
-            this._effect.setMatrix("world", world);
-        }
-
-        if (this._options.uniforms.indexOf("view") !== -1) {
-            this._effect.setMatrix("view", this._scene.getViewMatrix());
-        }
-
-        if (this._options.uniforms.indexOf("worldView") !== -1) {
-            world.multiplyToRef(this._scene.getViewMatrix(), this._cachedWorldViewMatrix);
-            this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
-        }
-
-        if (this._options.uniforms.indexOf("projection") !== -1) {
-            this._effect.setMatrix("projection", this._scene.getProjectionMatrix());
-        }
+            if (this._options.uniforms.indexOf("projection") !== -1) {
+                this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
+            }
 
-        if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
-            this._effect.setMatrix("worldViewProjection", world.multiply(this._scene.getTransformMatrix()));
-        }        
+            if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
+                this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
+            }
 
-        // Texture
-        for (var name in this._textures) {
-            this._effect.setTexture(name, this._textures[name]);
-        }
+            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]);
-        }
+            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]);
-        }
+            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]);
-        }
+            for (name in this._colors3) {
+                this._effect.setColor3(name, this._colors3[name]);
+            }
 
-        // Color4      
-        for (name in this._colors4) {
-            this._effect.setColor4(name, this._colors4[name]);
-        }
+            for (name in this._colors4) {
+                this._effect.setColor4(name, this._colors4[name]);
+            }
 
-        // Vector2        
-        for (name in this._vectors2) {
-            this._effect.setVector2(name, this._vectors2[name]);
-        }
+            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]);
-        }
+            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]);
-        }
+            for (name in this._matrices) {
+                this._effect.setMatrix(name, this._matrices[name]);
+            }
+        };
 
-        // Matrix      
-        for (name in this._matrices) {
-            this._effect.setMatrix(name, this._matrices[name]);
-        }
-    };
+        ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
+            for (var name in this._textures) {
+                this._textures[name].dispose();
+            }
 
-    BABYLON.ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
-        for (var name in this._textures) {
-            this._textures[name].dispose();
-        }
+            this._textures = [];
 
-        this._textures = [];
-        
-        this.baseDispose(forceDisposeEffect);
-    };
-})();
+            _super.prototype.dispose.call(this, forceDisposeEffect);
+        };
+        return ShaderMaterial;
+    })(BABYLON.Material);
+    BABYLON.ShaderMaterial = ShaderMaterial;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.shaderMaterial.js.map

+ 191 - 0
Babylon/Materials/babylon.shaderMaterial.ts

@@ -0,0 +1,191 @@
+module BABYLON {
+    export class ShaderMaterial extends Material {
+        private _shaderPath: string;
+        private _options: any;
+        private _textures = new Array<Texture>();
+        private _floats = new Array<number>();
+        private _floatsArrays = {};
+        private _colors3 = new Array<Color3>();
+        private _colors4 = new Array<Color4>();
+        private _vectors2 = new Array<Vector2>();
+        private _vectors3 = new Array<Vector3>();
+        private _matrices = new Array<Matrix>();
+        private _cachedWorldViewMatrix = new BABYLON.Matrix();
+
+        //ANY
+        constructor(name: string, scene, shaderPath: string, options) {
+            super(name, scene);
+            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 || [];
+
+            this._options = options;
+        }
+
+        public needAlphaBlending(): boolean {
+            return this._options.needAlphaBlending;
+        }
+
+        public needAlphaTesting(): boolean {
+            return this._options.needAlphaTesting;
+        }
+   
+        private _checkUniform(uniformName): void {
+            if (this._options.uniforms.indexOf(uniformName) === -1) {
+                this._options.uniforms.push(uniformName);
+            }
+        }
+
+        public setTexture(name: string, texture: Texture): ShaderMaterial {
+            if (this._options.samplers.indexOf(name) === -1) {
+                this._options.samplers.push(name);
+            }
+            this._textures[name] = texture;
+
+            return this;
+        }
+
+        public setFloat(name: string, value: number): ShaderMaterial {
+            this._checkUniform(name);
+            this._floats[name] = value;
+
+            return this;
+        }
+
+        public setFloats(name: string, value: number[]): ShaderMaterial {
+            this._checkUniform(name);
+            this._floatsArrays[name] = value;
+
+            return this;
+        }
+
+        public setColor3(name: string, value: Color3): ShaderMaterial {
+            this._checkUniform(name);
+            this._colors3[name] = value;
+
+            return this;
+        }
+
+        public setColor4(name: string, value: Color4): ShaderMaterial {
+            this._checkUniform(name);
+            this._colors4[name] = value;
+
+            return this;
+        }
+
+        public setVector2(name: string, value: Vector2): ShaderMaterial {
+            this._checkUniform(name);
+            this._vectors2[name] = value;
+
+            return this;
+        }
+
+        public setVector3(name: string, value: Vector3): ShaderMaterial {
+            this._checkUniform(name);
+            this._vectors3[name] = value;
+
+            return this;
+        }
+
+        public setMatrix(name: string, value: Matrix): ShaderMaterial {
+            this._checkUniform(name);
+            this._matrices[name] = value;
+
+            return this;
+        }
+
+        public isReady(mesh?: Mesh): boolean {
+            var engine = this.getScene().getEngine();
+
+            this._effect = engine.createEffect(this._shaderPath,
+                this._options.attributes,
+                this._options.uniforms,
+                this._options.samplers,
+                "", null, this.onCompiled, this.onError);
+
+            if (!this._effect.isReady()) {
+                return false;
+            }
+
+            return true;
+        }
+
+        public bind(world: Matrix, mesh: Mesh): void {
+            // Std values
+            if (this._options.uniforms.indexOf("world") !== -1) {
+                this._effect.setMatrix("world", world);
+            }
+
+            if (this._options.uniforms.indexOf("view") !== -1) {
+                this._effect.setMatrix("view", this.getScene().getViewMatrix());
+            }
+
+            if (this._options.uniforms.indexOf("worldView") !== -1) {
+                world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
+                this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
+            }
+
+            if (this._options.uniforms.indexOf("projection") !== -1) {
+                this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
+            }
+
+            if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
+                this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
+            }
+
+            // 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) {
+                this._effect.setColor4(name, this._colors4[name]);
+            }
+
+            // 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]);
+            }
+        }
+
+        public dispose(forceDisposeEffect?: boolean): void {
+            for (var name in this._textures) {
+                this._textures[name].dispose();
+            }
+
+            this._textures = [];
+
+            super.dispose(forceDisposeEffect);
+        }
+    }
+} 

+ 432 - 434
Babylon/Materials/babylon.standardMaterial.js

@@ -1,539 +1,537 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.StandardMaterial = function (name, scene) {
-        BABYLON.Material.call(this, name, scene);
-
-        this.diffuseTexture = null;
-        this.ambientTexture = null;
-        this.opacityTexture = null;
-        this.reflectionTexture = null;
-        this.emissiveTexture = null;
-        this.specularTexture = null;
-        this.bumpTexture = null;
-
-        this.ambientColor = new BABYLON.Color3(0, 0, 0);
-        this.diffuseColor = new BABYLON.Color3(1, 1, 1);
-        this.specularColor = new BABYLON.Color3(1, 1, 1);
-        this.specularPower = 64;
-        this.emissiveColor = new BABYLON.Color3(0, 0, 0);
-
-        this._cachedDefines = null;
-
-        this._renderTargets = new BABYLON.SmartArray(16);
-
-        // Internals
-        this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
-        this._lightMatrix = BABYLON.Matrix.Zero();
-        this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
-        this._baseColor = new BABYLON.Color3();
-        this._scaledDiffuse = new BABYLON.Color3();
-        this._scaledSpecular = new BABYLON.Color3();
-    };
-
-    BABYLON.StandardMaterial.prototype = Object.create(BABYLON.Material.prototype);
-
-    // Properties   
-    BABYLON.StandardMaterial.prototype.needAlphaBlending = function () {
-        return (this.alpha < 1.0) || (this.opacityTexture != null);
-    };
-
-    BABYLON.StandardMaterial.prototype.needAlphaTesting = function () {
-        return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
-    };
-
-    // Methods   
-    BABYLON.StandardMaterial.prototype.isReady = function (mesh) {
-        if (this.checkReadyOnlyOnce) {
-            if (this._wasPreviouslyReady) {
-                return true;
+var __extends = this.__extends || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    __.prototype = b.prototype;
+    d.prototype = new __();
+};
+var BABYLON;
+(function (BABYLON) {
+    var StandardMaterial = (function (_super) {
+        __extends(StandardMaterial, _super);
+        //ANY
+        function StandardMaterial(name, scene) {
+            _super.call(this, name, scene);
+            this.diffuseTexture = null;
+            this.ambientTexture = null;
+            this.opacityTexture = null;
+            this.reflectionTexture = null;
+            this.emissiveTexture = null;
+            this.specularTexture = null;
+            this.bumpTexture = null;
+            this.ambientColor = new BABYLON.Color3(0, 0, 0);
+            this.diffuseColor = new BABYLON.Color3(1, 1, 1);
+            this.specularColor = new BABYLON.Color3(1, 1, 1);
+            this.specularPower = 64;
+            this.emissiveColor = new BABYLON.Color3(0, 0, 0);
+            this._cachedDefines = null;
+            this._renderTargets = new BABYLON.SmartArray(16);
+            this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
+            this._lightMatrix = BABYLON.Matrix.Zero();
+            this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
+            this._baseColor = new BABYLON.Color3();
+            this._scaledDiffuse = new BABYLON.Color3();
+            this._scaledSpecular = new BABYLON.Color3();
+        }
+        StandardMaterial.prototype.needAlphaBlending = function () {
+            return (this.alpha < 1.0) || (this.opacityTexture != null);
+        };
+
+        StandardMaterial.prototype.needAlphaTesting = function () {
+            return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
+        };
+
+        // Methods
+        StandardMaterial.prototype.isReady = function (mesh) {
+            if (this.checkReadyOnlyOnce) {
+                if (this._wasPreviouslyReady) {
+                    return true;
+                }
             }
-        }
 
-        if (!this.checkReadyOnEveryCall) {
-            if (this._renderId === this._scene.getRenderId()) {
-                return true;
+            var scene = this.getScene();
+
+            if (!this.checkReadyOnEveryCall) {
+                if (this._renderId === scene.getRenderId()) {
+                    return true;
+                }
             }
-        }       
 
-        var engine = this._scene.getEngine();
-        var defines = [];
-        var optionalDefines = [];
+            var engine = scene.getEngine();
+            var defines = [];
+            var optionalDefines = [];
+
+            // Textures
+            if (scene.texturesEnabled) {
+                if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
+                    if (!this.diffuseTexture.isReady()) {
+                        return false;
+                    } else {
+                        defines.push("#define DIFFUSE");
+                    }
+                }
 
-        // Textures
-        if (this._scene.texturesEnabled) {
-            if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
-                if (!this.diffuseTexture.isReady()) {
-                    return false;
-                } else {
-                    defines.push("#define DIFFUSE");
+                if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
+                    if (!this.ambientTexture.isReady()) {
+                        return false;
+                    } else {
+                        defines.push("#define AMBIENT");
+                    }
                 }
-            }
 
-            if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
-                if (!this.ambientTexture.isReady()) {
-                    return false;
-                } else {
-                    defines.push("#define AMBIENT");
+                if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
+                    if (!this.opacityTexture.isReady()) {
+                        return false;
+                    } else {
+                        defines.push("#define OPACITY");
+                    }
                 }
-            }
 
-            if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
-                if (!this.opacityTexture.isReady()) {
-                    return false;
-                } else {
-                    defines.push("#define OPACITY");
+                if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
+                    if (!this.reflectionTexture.isReady()) {
+                        return false;
+                    } else {
+                        defines.push("#define REFLECTION");
+                    }
                 }
-            }
 
-            if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
-                if (!this.reflectionTexture.isReady()) {
-                    return false;
-                } else {
-                    defines.push("#define REFLECTION");
+                if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
+                    if (!this.emissiveTexture.isReady()) {
+                        return false;
+                    } else {
+                        defines.push("#define EMISSIVE");
+                    }
                 }
-            }
 
-            if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
-                if (!this.emissiveTexture.isReady()) {
-                    return false;
-                } else {
-                    defines.push("#define EMISSIVE");
+                if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
+                    if (!this.specularTexture.isReady()) {
+                        return false;
+                    } else {
+                        defines.push("#define SPECULAR");
+                        optionalDefines.push(defines[defines.length - 1]);
+                    }
                 }
             }
 
-            if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
-                if (!this.specularTexture.isReady()) {
+            if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
+                if (!this.bumpTexture.isReady()) {
                     return false;
                 } else {
-                    defines.push("#define SPECULAR");
+                    defines.push("#define BUMP");
                     optionalDefines.push(defines[defines.length - 1]);
                 }
             }
-        }
 
-        if (this._scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
-            if (!this.bumpTexture.isReady()) {
-                return false;
-            } else {
-                defines.push("#define BUMP");
-                optionalDefines.push(defines[defines.length - 1]);
+            // Effect
+            if (scene.clipPlane) {
+                defines.push("#define CLIPPLANE");
             }
-        }
 
-        // Effect
-        if (BABYLON.clipPlane) {
-            defines.push("#define CLIPPLANE");
-        }
-
-        if (engine.getAlphaTesting()) {
-            defines.push("#define ALPHATEST");
-        }
-
-        // Fog
-        if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
-            defines.push("#define FOG");
-            optionalDefines.push(defines[defines.length - 1]);
-        }
-
-        var shadowsActivated = false;
-        var lightIndex = 0;
-        if (this._scene.lightsEnabled) {
-            for (var index = 0; index < this._scene.lights.length; index++) {
-                var light = this._scene.lights[index];
+            if (engine.getAlphaTesting()) {
+                defines.push("#define ALPHATEST");
+            }
 
-                if (!light.isEnabled()) {
-                    continue;
-                }
+            // Fog
+            if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
+                defines.push("#define FOG");
+                optionalDefines.push(defines[defines.length - 1]);
+            }
 
-                if (mesh && light.excludedMeshes.indexOf(mesh) !== -1) {
-                    continue;
-                }
+            var shadowsActivated = false;
+            var lightIndex = 0;
+            if (scene.lightsEnabled) {
+                for (var index = 0; index < scene.lights.length; index++) {
+                    var light = scene.lights[index];
 
-                defines.push("#define LIGHT" + lightIndex);
+                    if (!light.isEnabled()) {
+                        continue;
+                    }
 
-                if (lightIndex > 0) {
-                    optionalDefines.push(defines[defines.length - 1]);
-                }
+                    if (mesh && light.excludedMeshes.indexOf(mesh) !== -1) {
+                        continue;
+                    }
 
-                var type;
-                if (light instanceof BABYLON.SpotLight) {
-                    type = "#define SPOTLIGHT" + lightIndex;
-                } else if (light instanceof BABYLON.HemisphericLight) {
-                    type = "#define HEMILIGHT" + lightIndex;
-                } else {
-                    type = "#define POINTDIRLIGHT" + lightIndex;
-                }
+                    defines.push("#define LIGHT" + lightIndex);
 
-                defines.push(type);
-                if (lightIndex > 0) {
-                    optionalDefines.push(defines[defines.length - 1]);
-                }
+                    if (lightIndex > 0) {
+                        optionalDefines.push(defines[defines.length - 1]);
+                    }
 
-                // Shadows
-                var shadowGenerator = light.getShadowGenerator();
-                if (mesh && mesh.receiveShadows && shadowGenerator) {
-                    defines.push("#define SHADOW" + lightIndex);
+                    var type;
+                    if (light instanceof BABYLON.SpotLight) {
+                        type = "#define SPOTLIGHT" + lightIndex;
+                    } else if (light instanceof BABYLON.HemisphericLight) {
+                        type = "#define HEMILIGHT" + lightIndex;
+                    } else {
+                        type = "#define POINTDIRLIGHT" + lightIndex;
+                    }
 
+                    defines.push(type);
                     if (lightIndex > 0) {
                         optionalDefines.push(defines[defines.length - 1]);
                     }
 
-                    if (!shadowsActivated) {
-                        defines.push("#define SHADOWS");
-                        shadowsActivated = true;
-                    }
+                    // Shadows
+                    var shadowGenerator = light.getShadowGenerator();
+                    if (mesh && mesh.receiveShadows && shadowGenerator) {
+                        defines.push("#define SHADOW" + lightIndex);
 
-                    if (shadowGenerator.useVarianceShadowMap) {
-                        defines.push("#define SHADOWVSM" + lightIndex);
                         if (lightIndex > 0) {
                             optionalDefines.push(defines[defines.length - 1]);
                         }
+
+                        if (!shadowsActivated) {
+                            defines.push("#define SHADOWS");
+                            shadowsActivated = true;
+                        }
+
+                        if (shadowGenerator.useVarianceShadowMap) {
+                            defines.push("#define SHADOWVSM" + lightIndex);
+                            if (lightIndex > 0) {
+                                optionalDefines.push(defines[defines.length - 1]);
+                            }
+                        }
                     }
-                }
 
-                lightIndex++;
-                if (lightIndex == 4)
-                    break;
+                    lightIndex++;
+                    if (lightIndex == 4)
+                        break;
+                }
             }
-        }
 
-        var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
-        if (mesh) {
-            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");
-            }
-            if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
-                attribs.push(BABYLON.VertexBuffer.ColorKind);
-                defines.push("#define VERTEXCOLOR");
-            }
-            if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
-                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
-                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
-                defines.push("#define BONES");
-                defines.push("#define BonesPerMesh " + mesh.skeleton.bones.length);
-                defines.push("#define BONES4");
-                optionalDefines.push(defines[defines.length - 1]);
+            var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
+            if (mesh) {
+                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");
+                }
+                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
+                    attribs.push(BABYLON.VertexBuffer.ColorKind);
+                    defines.push("#define VERTEXCOLOR");
+                }
+                if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
+                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
+                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
+                    defines.push("#define BONES");
+                    defines.push("#define BonesPerMesh " + mesh.skeleton.bones.length);
+                    defines.push("#define BONES4");
+                    optionalDefines.push(defines[defines.length - 1]);
+                }
             }
-        }
-
-        // Get correct effect      
-        var join = defines.join("\n");
-        if (this._cachedDefines != join) {
-            this._cachedDefines = join;
-
-            // Legacy browser patch
-            var shaderName = "default";
-            if (!this._scene.getEngine().getCaps().standardDerivatives) {
-                shaderName = "legacydefault";
-            }
-
-            this._effect = this._scene.getEngine().createEffect(shaderName,
-                attribs,
-                ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
-                "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
-                "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
-                "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
-                "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
-                "vFogInfos", "vFogColor",
-                 "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
-                 "mBones",
-                 "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
-                 "darkness0", "darkness1", "darkness2", "darkness3"],
-                ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
-                 "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
-                ],
-                join, optionalDefines, this.onCompiled, this.onError);
-        }
-        if (!this._effect.isReady()) {
-            return false;
-        }
 
-        this._renderId = this._scene.getRenderId();
-        this._wasPreviouslyReady = true;
-        return true;
-    };
+            // Get correct effect
+            var join = defines.join("\n");
+            if (this._cachedDefines != join) {
+                this._cachedDefines = join;
 
-    BABYLON.StandardMaterial.prototype.getRenderTargetTextures = function () {
-        this._renderTargets.reset();
+                // Legacy browser patch
+                var shaderName = "default";
+                if (!scene.getEngine().getCaps().standardDerivatives) {
+                    shaderName = "legacydefault";
+                }
 
-        if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
-            this._renderTargets.push(this.reflectionTexture);
-        }
+                this._effect = scene.getEngine().createEffect(shaderName, attribs, [
+                    "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
+                    "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
+                    "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
+                    "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
+                    "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
+                    "vFogInfos", "vFogColor",
+                    "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
+                    "mBones",
+                    "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
+                    "darkness0", "darkness1", "darkness2", "darkness3"], [
+                    "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
+                    "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
+                ], join, optionalDefines, this.onCompiled, this.onError);
+            }
+            if (!this._effect.isReady()) {
+                return false;
+            }
 
-        return this._renderTargets;
-    };
+            this._renderId = scene.getRenderId();
+            this._wasPreviouslyReady = true;
+            return true;
+        };
 
-    BABYLON.StandardMaterial.prototype.unbind = function () {
-        if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
-            this._effect.setTexture("reflection2DSampler", null);
-        }
-    };
+        StandardMaterial.prototype.getRenderTargetTextures = function () {
+            this._renderTargets.reset();
 
-    BABYLON.StandardMaterial.prototype.bind = function (world, mesh) {
-        this._baseColor.copyFrom(this.diffuseColor);
+            if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
+                this._renderTargets.push(this.reflectionTexture);
+            }
 
-        // Matrices        
-        this._effect.setMatrix("world", world);
-        this._effect.setMatrix("viewProjection", this._scene.getTransformMatrix());
+            return this._renderTargets;
+        };
 
-        // Bones
-        if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
-            this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
-        }
+        StandardMaterial.prototype.unbind = function () {
+            if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
+                this._effect.setTexture("reflection2DSampler", null);
+            }
+        };
 
-        // Textures        
-        if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
-            this._effect.setTexture("diffuseSampler", this.diffuseTexture);
+        StandardMaterial.prototype.bind = function (world, mesh) {
+            var scene = this.getScene();
+            this._baseColor.copyFrom(this.diffuseColor);
 
-            this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
-            this._effect.setMatrix("diffuseMatrix", this.diffuseTexture._computeTextureMatrix());
+            // Matrices
+            this._effect.setMatrix("world", world);
+            this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
 
-            this._baseColor.copyFromFloats(1, 1, 1);
-        }
+            // Bones
+            if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
+                this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
+            }
 
-        if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
-            this._effect.setTexture("ambientSampler", this.ambientTexture);
+            // Textures
+            if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
+                this._effect.setTexture("diffuseSampler", this.diffuseTexture);
 
-            this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
-            this._effect.setMatrix("ambientMatrix", this.ambientTexture._computeTextureMatrix());
-        }
+                this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
+                this._effect.setMatrix("diffuseMatrix", this.diffuseTexture._computeTextureMatrix());
 
-        if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
-            this._effect.setTexture("opacitySampler", this.opacityTexture);
+                this._baseColor.copyFromFloats(1, 1, 1);
+            }
 
-            this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
-            this._effect.setMatrix("opacityMatrix", this.opacityTexture._computeTextureMatrix());
-        }
+            if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
+                this._effect.setTexture("ambientSampler", this.ambientTexture);
 
-        if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
-            if (this.reflectionTexture.isCube) {
-                this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
-            } else {
-                this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
+                this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
+                this._effect.setMatrix("ambientMatrix", this.ambientTexture._computeTextureMatrix());
             }
 
-            this._effect.setMatrix("reflectionMatrix", this.reflectionTexture._computeReflectionTextureMatrix());
-            this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
-        }
-
-        if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
-            this._effect.setTexture("emissiveSampler", this.emissiveTexture);
+            if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
+                this._effect.setTexture("opacitySampler", this.opacityTexture);
 
-            this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
-            this._effect.setMatrix("emissiveMatrix", this.emissiveTexture._computeTextureMatrix());
-        }
+                this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
+                this._effect.setMatrix("opacityMatrix", this.opacityTexture._computeTextureMatrix());
+            }
 
-        if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
-            this._effect.setTexture("specularSampler", this.specularTexture);
+            if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
+                if (this.reflectionTexture.isCube) {
+                    this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
+                } else {
+                    this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
+                }
 
-            this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
-            this._effect.setMatrix("specularMatrix", this.specularTexture._computeTextureMatrix());
-        }
+                this._effect.setMatrix("reflectionMatrix", this.reflectionTexture._computeReflectionTextureMatrix());
+                this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
+            }
 
-        if (this.bumpTexture && this._scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
-            this._effect.setTexture("bumpSampler", this.bumpTexture);
+            if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
+                this._effect.setTexture("emissiveSampler", this.emissiveTexture);
 
-            this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
-            this._effect.setMatrix("bumpMatrix", this.bumpTexture._computeTextureMatrix());
-        }
+                this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
+                this._effect.setMatrix("emissiveMatrix", this.emissiveTexture._computeTextureMatrix());
+            }
 
-        // Colors
-        this._scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
+            if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
+                this._effect.setTexture("specularSampler", this.specularTexture);
 
-        this._effect.setVector3("vEyePosition", this._scene.activeCamera.position);
-        this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
-        this._effect.setColor4("vDiffuseColor", this._baseColor, this.alpha * mesh.visibility);
-        this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
-        this._effect.setColor3("vEmissiveColor", this.emissiveColor);
+                this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
+                this._effect.setMatrix("specularMatrix", this.specularTexture._computeTextureMatrix());
+            }
 
-        if (this._scene.lightsEnabled) {
-            var lightIndex = 0;
-            for (var index = 0; index < this._scene.lights.length; index++) {
-                var light = this._scene.lights[index];
+            if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
+                this._effect.setTexture("bumpSampler", this.bumpTexture);
 
-                if (!light.isEnabled()) {
-                    continue;
-                }
+                this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
+                this._effect.setMatrix("bumpMatrix", this.bumpTexture._computeTextureMatrix());
+            }
 
-                if (mesh && light.excludedMeshes.indexOf(mesh) !== -1) {
-                    continue;
-                }
+            // Colors
+            scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
 
-                if (light instanceof BABYLON.PointLight) {
-                    // Point Light
-                    light.transferToEffect(this._effect, "vLightData" + lightIndex);
-                } else if (light instanceof BABYLON.DirectionalLight) {
-                    // Directional Light
-                    light.transferToEffect(this._effect, "vLightData" + lightIndex);
-                } else if (light instanceof BABYLON.SpotLight) {
-                    // Spot Light
-                    light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
-                } else if (light instanceof BABYLON.HemisphericLight) {
-                    // Hemispheric Light
-                    light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
-                }
+            this._effect.setVector3("vEyePosition", scene.activeCamera.position);
+            this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
+            this._effect.setColor4("vDiffuseColor", this._baseColor, this.alpha * mesh.visibility);
+            this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
+            this._effect.setColor3("vEmissiveColor", this.emissiveColor);
 
-                light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
-                light.specular.scaleToRef(light.intensity, this._scaledSpecular);
-                this._effect.setColor3("vLightDiffuse" + lightIndex, this._scaledDiffuse);
-                this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
-
-                // Shadows
-                var shadowGenerator = light.getShadowGenerator();
-                if (mesh.receiveShadows && shadowGenerator) {
-                    world.multiplyToRef(shadowGenerator.getTransformMatrix(), this._lightMatrix);
-                    this._effect.setMatrix("lightMatrix" + lightIndex, this._lightMatrix);
-                    this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
-                    this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
-                }
+            if (scene.lightsEnabled) {
+                var lightIndex = 0;
+                for (var index = 0; index < scene.lights.length; index++) {
+                    var light = scene.lights[index];
 
-                lightIndex++;
+                    if (!light.isEnabled()) {
+                        continue;
+                    }
 
-                if (lightIndex == 4)
-                    break;
-            }
-        }
+                    if (mesh && light.excludedMeshes.indexOf(mesh) !== -1) {
+                        continue;
+                    }
 
-        if (BABYLON.clipPlane) {
-            this._effect.setFloat4("vClipPlane", BABYLON.clipPlane.normal.x, BABYLON.clipPlane.normal.y, BABYLON.clipPlane.normal.z, BABYLON.clipPlane.d);
-        }
+                    if (light instanceof BABYLON.PointLight) {
+                        // Point Light
+                        light.transferToEffect(this._effect, "vLightData" + lightIndex);
+                    } else if (light instanceof BABYLON.DirectionalLight) {
+                        // Directional Light
+                        light.transferToEffect(this._effect, "vLightData" + lightIndex);
+                    } else if (light instanceof BABYLON.SpotLight) {
+                        // Spot Light
+                        light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
+                    } else if (light instanceof BABYLON.HemisphericLight) {
+                        // Hemispheric Light
+                        light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
+                    }
 
-        // View
-        if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
-            this._effect.setMatrix("view", this._scene.getViewMatrix());
-        }
+                    light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
+                    light.specular.scaleToRef(light.intensity, this._scaledSpecular);
+                    this._effect.setColor3("vLightDiffuse" + lightIndex, this._scaledDiffuse);
+                    this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
+
+                    // Shadows
+                    var shadowGenerator = light.getShadowGenerator();
+                    if (mesh.receiveShadows && shadowGenerator) {
+                        world.multiplyToRef(shadowGenerator.getTransformMatrix(), this._lightMatrix);
+                        this._effect.setMatrix("lightMatrix" + lightIndex, this._lightMatrix);
+                        this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
+                        this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
+                    }
 
-        // Fog
-        if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
-            this._effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
-            this._effect.setColor3("vFogColor", this._scene.fogColor);
-        }
-    };
+                    lightIndex++;
 
-    BABYLON.StandardMaterial.prototype.getAnimatables = function () {
-        var results = [];
+                    if (lightIndex == 4)
+                        break;
+                }
+            }
 
-        if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
-            results.push(this.diffuseTexture);
-        }
+            if (scene.clipPlane) {
+                var clipPlane = scene.clipPlane;
+                this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
+            }
 
-        if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
-            results.push(this.ambientTexture);
-        }
+            // View
+            if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
+                this._effect.setMatrix("view", scene.getViewMatrix());
+            }
 
-        if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
-            results.push(this.opacityTexture);
-        }
+            // Fog
+            if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
+                this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
+                this._effect.setColor3("vFogColor", scene.fogColor);
+            }
+        };
 
-        if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
-            results.push(this.reflectionTexture);
-        }
+        StandardMaterial.prototype.getAnimatables = function () {
+            var results = [];
 
-        if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
-            results.push(this.emissiveTexture);
-        }
+            if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
+                results.push(this.diffuseTexture);
+            }
 
-        if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
-            results.push(this.specularTexture);
-        }
+            if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
+                results.push(this.ambientTexture);
+            }
 
-        if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
-            results.push(this.bumpTexture);
-        }
+            if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
+                results.push(this.opacityTexture);
+            }
 
-        return results;
-    };
+            if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
+                results.push(this.reflectionTexture);
+            }
 
-    BABYLON.StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
-        if (this.diffuseTexture) {
-            this.diffuseTexture.dispose();
-        }
+            if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
+                results.push(this.emissiveTexture);
+            }
 
-        if (this.ambientTexture) {
-            this.ambientTexture.dispose();
-        }
+            if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
+                results.push(this.specularTexture);
+            }
 
-        if (this.opacityTexture) {
-            this.opacityTexture.dispose();
-        }
+            if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
+                results.push(this.bumpTexture);
+            }
 
-        if (this.reflectionTexture) {
-            this.reflectionTexture.dispose();
-        }
+            return results;
+        };
 
-        if (this.emissiveTexture) {
-            this.emissiveTexture.dispose();
-        }
+        StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
+            if (this.diffuseTexture) {
+                this.diffuseTexture.dispose();
+            }
 
-        if (this.specularTexture) {
-            this.specularTexture.dispose();
-        }
+            if (this.ambientTexture) {
+                this.ambientTexture.dispose();
+            }
 
-        if (this.bumpTexture) {
-            this.bumpTexture.dispose();
-        }
+            if (this.opacityTexture) {
+                this.opacityTexture.dispose();
+            }
 
-        this.baseDispose(forceDisposeEffect);
-    };
+            if (this.reflectionTexture) {
+                this.reflectionTexture.dispose();
+            }
 
-    BABYLON.StandardMaterial.prototype.clone = function (name) {
-        var newStandardMaterial = new BABYLON.StandardMaterial(name, this._scene);
+            if (this.emissiveTexture) {
+                this.emissiveTexture.dispose();
+            }
 
-        // Base material
-        newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
-        newStandardMaterial.alpha = this.alpha;
-        newStandardMaterial.wireframe = this.wireframe;
-        newStandardMaterial.backFaceCulling = this.backFaceCulling;
+            if (this.specularTexture) {
+                this.specularTexture.dispose();
+            }
 
-        // Standard material
-        if (this.diffuseTexture && this.diffuseTexture.clone) {
-            newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
-        }
-        if (this.ambientTexture && this.ambientTexture.clone) {
-            newStandardMaterial.ambientTexture = this.ambientTexture.clone();
-        }
-        if (this.opacityTexture && this.opacityTexture.clone) {
-            newStandardMaterial.opacityTexture = this.opacityTexture.clone();
-        }
-        if (this.reflectionTexture && this.reflectionTexture.clone) {
-            newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
-        }
-        if (this.emissiveTexture && this.emissiveTexture.clone) {
-            newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
-        }
-        if (this.specularTexture && this.specularTexture.clone) {
-            newStandardMaterial.specularTexture = this.specularTexture.clone();
-        }
-        if (this.bumpTexture && this.bumpTexture.clone) {
-            newStandardMaterial.bumpTexture = this.bumpTexture.clone();
-        }
+            if (this.bumpTexture) {
+                this.bumpTexture.dispose();
+            }
 
-        newStandardMaterial.ambientColor = this.ambientColor.clone();
-        newStandardMaterial.diffuseColor = this.diffuseColor.clone();
-        newStandardMaterial.specularColor = this.specularColor.clone();
-        newStandardMaterial.specularPower = this.specularPower;
-        newStandardMaterial.emissiveColor = this.emissiveColor.clone();
+            _super.prototype.dispose.call(this, forceDisposeEffect);
+        };
 
-        return newStandardMaterial;
-    };
+        StandardMaterial.prototype.clone = function (name) {
+            var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
 
-    // Statics
+            // Base material
+            newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
+            newStandardMaterial.alpha = this.alpha;
+            newStandardMaterial.wireframe = this.wireframe;
+            newStandardMaterial.backFaceCulling = this.backFaceCulling;
 
-    // Flags used to enable or disable a type of texture for all Standard Materials
-    BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
-    BABYLON.StandardMaterial.AmbientTextureEnabled = true;
-    BABYLON.StandardMaterial.OpacityTextureEnabled = true;
-    BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
-    BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
-    BABYLON.StandardMaterial.SpecularTextureEnabled = true;
-    BABYLON.StandardMaterial.BumpTextureEnabled = true;
+            // Standard material
+            if (this.diffuseTexture && this.diffuseTexture.clone) {
+                newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
+            }
+            if (this.ambientTexture && this.ambientTexture.clone) {
+                newStandardMaterial.ambientTexture = this.ambientTexture.clone();
+            }
+            if (this.opacityTexture && this.opacityTexture.clone) {
+                newStandardMaterial.opacityTexture = this.opacityTexture.clone();
+            }
+            if (this.reflectionTexture && this.reflectionTexture.clone) {
+                newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
+            }
+            if (this.emissiveTexture && this.emissiveTexture.clone) {
+                newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
+            }
+            if (this.specularTexture && this.specularTexture.clone) {
+                newStandardMaterial.specularTexture = this.specularTexture.clone();
+            }
+            if (this.bumpTexture && this.bumpTexture.clone) {
+                newStandardMaterial.bumpTexture = this.bumpTexture.clone();
+            }
 
-})();
+            newStandardMaterial.ambientColor = this.ambientColor.clone();
+            newStandardMaterial.diffuseColor = this.diffuseColor.clone();
+            newStandardMaterial.specularColor = this.specularColor.clone();
+            newStandardMaterial.specularPower = this.specularPower;
+            newStandardMaterial.emissiveColor = this.emissiveColor.clone();
+
+            return newStandardMaterial;
+        };
+
+        StandardMaterial.DiffuseTextureEnabled = true;
+        StandardMaterial.AmbientTextureEnabled = true;
+        StandardMaterial.OpacityTextureEnabled = true;
+        StandardMaterial.ReflectionTextureEnabled = true;
+        StandardMaterial.EmissiveTextureEnabled = true;
+        StandardMaterial.SpecularTextureEnabled = true;
+        StandardMaterial.BumpTextureEnabled = true;
+        return StandardMaterial;
+    })(BABYLON.Material);
+    BABYLON.StandardMaterial = StandardMaterial;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.standardMaterial.js.map

+ 535 - 0
Babylon/Materials/babylon.standardMaterial.ts

@@ -0,0 +1,535 @@
+module BABYLON {
+    export class StandardMaterial extends Material {
+        public diffuseTexture = null;
+        public ambientTexture = null;
+        public opacityTexture = null;
+        public reflectionTexture = null;
+        public emissiveTexture = null;
+        public specularTexture = null;
+        public bumpTexture = null;
+
+        public ambientColor = new BABYLON.Color3(0, 0, 0);
+        public diffuseColor = new BABYLON.Color3(1, 1, 1);
+        public specularColor = new BABYLON.Color3(1, 1, 1);
+        public specularPower = 64;
+        public emissiveColor = new BABYLON.Color3(0, 0, 0);
+
+        private _cachedDefines = null;
+        private _renderTargets = new BABYLON.SmartArray(16);
+        private _worldViewProjectionMatrix = BABYLON.Matrix.Zero();
+        private _lightMatrix = BABYLON.Matrix.Zero();
+        private _globalAmbientColor = new BABYLON.Color3(0, 0, 0);
+        private _baseColor = new BABYLON.Color3();
+        private _scaledDiffuse = new BABYLON.Color3();
+        private _scaledSpecular = new BABYLON.Color3();
+        private _renderId: number;
+
+        //ANY
+        constructor(name: string, scene) {
+            super(name, scene);
+        }
+
+        public needAlphaBlending(): boolean {
+            return (this.alpha < 1.0) || (this.opacityTexture != null);
+        }
+
+        public needAlphaTesting(): boolean {
+            return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
+        }
+
+        // Methods   
+        public isReady(mesh?: Mesh): boolean {
+            if (this.checkReadyOnlyOnce) {
+                if (this._wasPreviouslyReady) {
+                    return true;
+                }
+            }
+
+            var scene = this.getScene();
+
+            if (!this.checkReadyOnEveryCall) {
+                if (this._renderId ===scene.getRenderId()) {
+                    return true;
+                }
+            }
+
+            var engine =scene.getEngine();
+            var defines = [];
+            var optionalDefines = [];
+
+            // Textures
+            if (scene.texturesEnabled) {
+                if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
+                    if (!this.diffuseTexture.isReady()) {
+                        return false;
+                    } else {
+                        defines.push("#define DIFFUSE");
+                    }
+                }
+
+                if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
+                    if (!this.ambientTexture.isReady()) {
+                        return false;
+                    } else {
+                        defines.push("#define AMBIENT");
+                    }
+                }
+
+                if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
+                    if (!this.opacityTexture.isReady()) {
+                        return false;
+                    } else {
+                        defines.push("#define OPACITY");
+                    }
+                }
+
+                if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
+                    if (!this.reflectionTexture.isReady()) {
+                        return false;
+                    } else {
+                        defines.push("#define REFLECTION");
+                    }
+                }
+
+                if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
+                    if (!this.emissiveTexture.isReady()) {
+                        return false;
+                    } else {
+                        defines.push("#define EMISSIVE");
+                    }
+                }
+
+                if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
+                    if (!this.specularTexture.isReady()) {
+                        return false;
+                    } else {
+                        defines.push("#define SPECULAR");
+                        optionalDefines.push(defines[defines.length - 1]);
+                    }
+                }
+            }
+
+            if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
+                if (!this.bumpTexture.isReady()) {
+                    return false;
+                } else {
+                    defines.push("#define BUMP");
+                    optionalDefines.push(defines[defines.length - 1]);
+                }
+            }
+
+            // Effect
+            if (scene.clipPlane) {
+                defines.push("#define CLIPPLANE");
+            }
+
+            if (engine.getAlphaTesting()) {
+                defines.push("#define ALPHATEST");
+            }
+
+            // Fog
+            if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
+                defines.push("#define FOG");
+                optionalDefines.push(defines[defines.length - 1]);
+            }
+
+            var shadowsActivated = false;
+            var lightIndex = 0;
+            if (scene.lightsEnabled) {
+                for (var index = 0; index <scene.lights.length; index++) {
+                    var light =scene.lights[index];
+
+                    if (!light.isEnabled()) {
+                        continue;
+                    }
+
+                    if (mesh && light.excludedMeshes.indexOf(mesh) !== -1) {
+                        continue;
+                    }
+
+                    defines.push("#define LIGHT" + lightIndex);
+
+                    if (lightIndex > 0) {
+                        optionalDefines.push(defines[defines.length - 1]);
+                    }
+
+                    var type;
+                    if (light instanceof BABYLON.SpotLight) {
+                        type = "#define SPOTLIGHT" + lightIndex;
+                    } else if (light instanceof BABYLON.HemisphericLight) {
+                        type = "#define HEMILIGHT" + lightIndex;
+                    } else {
+                        type = "#define POINTDIRLIGHT" + lightIndex;
+                    }
+
+                    defines.push(type);
+                    if (lightIndex > 0) {
+                        optionalDefines.push(defines[defines.length - 1]);
+                    }
+
+                    // Shadows
+                    var shadowGenerator = light.getShadowGenerator();
+                    if (mesh && mesh.receiveShadows && shadowGenerator) {
+                        defines.push("#define SHADOW" + lightIndex);
+
+                        if (lightIndex > 0) {
+                            optionalDefines.push(defines[defines.length - 1]);
+                        }
+
+                        if (!shadowsActivated) {
+                            defines.push("#define SHADOWS");
+                            shadowsActivated = true;
+                        }
+
+                        if (shadowGenerator.useVarianceShadowMap) {
+                            defines.push("#define SHADOWVSM" + lightIndex);
+                            if (lightIndex > 0) {
+                                optionalDefines.push(defines[defines.length - 1]);
+                            }
+                        }
+                    }
+
+                    lightIndex++;
+                    if (lightIndex == 4)
+                        break;
+                }
+            }
+
+            var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
+            if (mesh) {
+                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");
+                }
+                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
+                    attribs.push(BABYLON.VertexBuffer.ColorKind);
+                    defines.push("#define VERTEXCOLOR");
+                }
+                if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
+                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
+                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
+                    defines.push("#define BONES");
+                    defines.push("#define BonesPerMesh " + mesh.skeleton.bones.length);
+                    defines.push("#define BONES4");
+                    optionalDefines.push(defines[defines.length - 1]);
+                }
+            }
+
+            // Get correct effect      
+            var join = defines.join("\n");
+            if (this._cachedDefines != join) {
+                this._cachedDefines = join;
+
+                // Legacy browser patch
+                var shaderName = "default";
+                if (!scene.getEngine().getCaps().standardDerivatives) {
+                    shaderName = "legacydefault";
+                }
+
+                this._effect =scene.getEngine().createEffect(shaderName,
+                    attribs,
+                    ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
+                        "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
+                        "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
+                        "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
+                        "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
+                        "vFogInfos", "vFogColor",
+                        "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
+                        "mBones",
+                        "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
+                        "darkness0", "darkness1", "darkness2", "darkness3"],
+                    ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
+                        "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
+                    ],
+                    join, optionalDefines, this.onCompiled, this.onError);
+            }
+            if (!this._effect.isReady()) {
+                return false;
+            }
+
+            this._renderId =scene.getRenderId();
+            this._wasPreviouslyReady = true;
+            return true;
+        }
+
+        public getRenderTargetTextures(): SmartArray {
+            this._renderTargets.reset();
+
+            if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
+                this._renderTargets.push(this.reflectionTexture);
+            }
+
+            return this._renderTargets;
+        }
+
+        public unbind(): void {
+            if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
+                this._effect.setTexture("reflection2DSampler", null);
+            }
+        }
+
+        public bind(world: Matrix, mesh: Mesh): void {
+            var scene = this.getScene();
+            this._baseColor.copyFrom(this.diffuseColor);
+
+            // Matrices        
+            this._effect.setMatrix("world", world);
+            this._effect.setMatrix("viewProjection",scene.getTransformMatrix());
+
+            // Bones
+            if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
+                this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
+            }
+
+            // Textures        
+            if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
+                this._effect.setTexture("diffuseSampler", this.diffuseTexture);
+
+                this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
+                this._effect.setMatrix("diffuseMatrix", this.diffuseTexture._computeTextureMatrix());
+
+                this._baseColor.copyFromFloats(1, 1, 1);
+            }
+
+            if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
+                this._effect.setTexture("ambientSampler", this.ambientTexture);
+
+                this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
+                this._effect.setMatrix("ambientMatrix", this.ambientTexture._computeTextureMatrix());
+            }
+
+            if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
+                this._effect.setTexture("opacitySampler", this.opacityTexture);
+
+                this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
+                this._effect.setMatrix("opacityMatrix", this.opacityTexture._computeTextureMatrix());
+            }
+
+            if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
+                if (this.reflectionTexture.isCube) {
+                    this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
+                } else {
+                    this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
+                }
+
+                this._effect.setMatrix("reflectionMatrix", this.reflectionTexture._computeReflectionTextureMatrix());
+                this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
+            }
+
+            if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
+                this._effect.setTexture("emissiveSampler", this.emissiveTexture);
+
+                this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
+                this._effect.setMatrix("emissiveMatrix", this.emissiveTexture._computeTextureMatrix());
+            }
+
+            if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
+                this._effect.setTexture("specularSampler", this.specularTexture);
+
+                this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
+                this._effect.setMatrix("specularMatrix", this.specularTexture._computeTextureMatrix());
+            }
+
+            if (this.bumpTexture &&scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
+                this._effect.setTexture("bumpSampler", this.bumpTexture);
+
+                this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
+                this._effect.setMatrix("bumpMatrix", this.bumpTexture._computeTextureMatrix());
+            }
+
+            // Colors
+           scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
+
+            this._effect.setVector3("vEyePosition",scene.activeCamera.position);
+            this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
+            this._effect.setColor4("vDiffuseColor", this._baseColor, this.alpha * mesh.visibility);
+            this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
+            this._effect.setColor3("vEmissiveColor", this.emissiveColor);
+
+            if (scene.lightsEnabled) {
+                var lightIndex = 0;
+                for (var index = 0; index <scene.lights.length; index++) {
+                    var light =scene.lights[index];
+
+                    if (!light.isEnabled()) {
+                        continue;
+                    }
+
+                    if (mesh && light.excludedMeshes.indexOf(mesh) !== -1) {
+                        continue;
+                    }
+
+                    if (light instanceof BABYLON.PointLight) {
+                        // Point Light
+                        light.transferToEffect(this._effect, "vLightData" + lightIndex);
+                    } else if (light instanceof BABYLON.DirectionalLight) {
+                        // Directional Light
+                        light.transferToEffect(this._effect, "vLightData" + lightIndex);
+                    } else if (light instanceof BABYLON.SpotLight) {
+                        // Spot Light
+                        light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
+                    } else if (light instanceof BABYLON.HemisphericLight) {
+                        // Hemispheric Light
+                        light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
+                    }
+
+                    light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
+                    light.specular.scaleToRef(light.intensity, this._scaledSpecular);
+                    this._effect.setColor3("vLightDiffuse" + lightIndex, this._scaledDiffuse);
+                    this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
+
+                    // Shadows
+                    var shadowGenerator = light.getShadowGenerator();
+                    if (mesh.receiveShadows && shadowGenerator) {
+                        world.multiplyToRef(shadowGenerator.getTransformMatrix(), this._lightMatrix);
+                        this._effect.setMatrix("lightMatrix" + lightIndex, this._lightMatrix);
+                        this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
+                        this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
+                    }
+
+                    lightIndex++;
+
+                    if (lightIndex == 4)
+                        break;
+                }
+            }
+
+            if (scene.clipPlane) {
+                var clipPlane =scene.clipPlane;
+                this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
+            }
+
+            // View
+            if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
+                this._effect.setMatrix("view",scene.getViewMatrix());
+            }
+
+            // Fog
+            if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
+                this._effect.setFloat4("vFogInfos",scene.fogMode,scene.fogStart,scene.fogEnd,scene.fogDensity);
+                this._effect.setColor3("vFogColor",scene.fogColor);
+            }
+        }
+
+        public getAnimatables(): IAnimatable[] {
+            var results = [];
+
+            if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
+                results.push(this.diffuseTexture);
+            }
+
+            if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
+                results.push(this.ambientTexture);
+            }
+
+            if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
+                results.push(this.opacityTexture);
+            }
+
+            if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
+                results.push(this.reflectionTexture);
+            }
+
+            if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
+                results.push(this.emissiveTexture);
+            }
+
+            if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
+                results.push(this.specularTexture);
+            }
+
+            if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
+                results.push(this.bumpTexture);
+            }
+
+            return results;
+        }
+
+        public dispose(forceDisposeEffect?: boolean): void {
+            if (this.diffuseTexture) {
+                this.diffuseTexture.dispose();
+            }
+
+            if (this.ambientTexture) {
+                this.ambientTexture.dispose();
+            }
+
+            if (this.opacityTexture) {
+                this.opacityTexture.dispose();
+            }
+
+            if (this.reflectionTexture) {
+                this.reflectionTexture.dispose();
+            }
+
+            if (this.emissiveTexture) {
+                this.emissiveTexture.dispose();
+            }
+
+            if (this.specularTexture) {
+                this.specularTexture.dispose();
+            }
+
+            if (this.bumpTexture) {
+                this.bumpTexture.dispose();
+            }
+
+            super.dispose(forceDisposeEffect);
+        }
+
+        public clone(name: string): StandardMaterial {
+            var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
+
+            // Base material
+            newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
+            newStandardMaterial.alpha = this.alpha;
+            newStandardMaterial.wireframe = this.wireframe;
+            newStandardMaterial.backFaceCulling = this.backFaceCulling;
+
+            // Standard material
+            if (this.diffuseTexture && this.diffuseTexture.clone) {
+                newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
+            }
+            if (this.ambientTexture && this.ambientTexture.clone) {
+                newStandardMaterial.ambientTexture = this.ambientTexture.clone();
+            }
+            if (this.opacityTexture && this.opacityTexture.clone) {
+                newStandardMaterial.opacityTexture = this.opacityTexture.clone();
+            }
+            if (this.reflectionTexture && this.reflectionTexture.clone) {
+                newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
+            }
+            if (this.emissiveTexture && this.emissiveTexture.clone) {
+                newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
+            }
+            if (this.specularTexture && this.specularTexture.clone) {
+                newStandardMaterial.specularTexture = this.specularTexture.clone();
+            }
+            if (this.bumpTexture && this.bumpTexture.clone) {
+                newStandardMaterial.bumpTexture = this.bumpTexture.clone();
+            }
+
+            newStandardMaterial.ambientColor = this.ambientColor.clone();
+            newStandardMaterial.diffuseColor = this.diffuseColor.clone();
+            newStandardMaterial.specularColor = this.specularColor.clone();
+            newStandardMaterial.specularPower = this.specularPower;
+            newStandardMaterial.emissiveColor = this.emissiveColor.clone();
+
+            return newStandardMaterial;
+        }
+
+        // Statics
+        // Flags used to enable or disable a type of texture for all Standard Materials
+        public static DiffuseTextureEnabled = true;
+        public static AmbientTextureEnabled = true;
+        public static OpacityTextureEnabled = true;
+        public static ReflectionTextureEnabled = true;
+        public static EmissiveTextureEnabled = true;
+        public static SpecularTextureEnabled = true;
+        public static BumpTextureEnabled = true;
+    }
+} 

+ 95 - 92
Babylon/Materials/textures/babylon.baseTexture.js

@@ -1,115 +1,118 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.BaseTexture = function (url, scene) {
-        this._scene = scene;
-        this._scene.textures.push(this);
-    };
-
-    // Members
-    BABYLON.BaseTexture.prototype.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
-    BABYLON.BaseTexture.prototype.hasAlpha = false;
-    BABYLON.BaseTexture.prototype.level = 1;
-    BABYLON.BaseTexture.prototype._texture = null;
-
-    BABYLON.BaseTexture.prototype.onDispose = null;
-
-    // Properties
-    BABYLON.BaseTexture.prototype.getInternalTexture = function () {
-        return this._texture;
-    };
-
-    BABYLON.BaseTexture.prototype.isReady = function () {
-        if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
-            return true;
-        }
-
-        if (this._texture) {
-            return this._texture.isReady;
+var BABYLON;
+(function (BABYLON) {
+    var BaseTexture = (function () {
+        //ANY
+        function BaseTexture(scene) {
+            this.delayLoadState = 0;
+            this.hasAlpha = false;
+            this.level = 1;
+            this.isCube = false;
+            this._texture = null;
+            this._scene = scene;
+            this._scene.textures.push(this);
         }
+        //ANY
+        BaseTexture.prototype.getScene = function () {
+            return this._scene;
+        };
+
+        //ANY
+        BaseTexture.prototype.getInternalTexture = function () {
+            return this._texture;
+        };
+
+        BaseTexture.prototype.isReady = function () {
+            if (this.delayLoadState === 4) {
+                return true;
+            }
 
-        return false;
-    };
+            if (this._texture) {
+                return this._texture.isReady;
+            }
 
-    // Methods
-    BABYLON.BaseTexture.prototype.getSize = function () {
-        if (this._texture._width) {
-            return { width: this._texture._width, height: this._texture._height };
-        }
+            return false;
+        };
 
-        if (this._texture._size) {
-            return { width: this._texture._size, height: this._texture._size };
-        }
+        BaseTexture.prototype.getSize = function () {
+            if (this._texture._width) {
+                return { width: this._texture._width, height: this._texture._height };
+            }
 
-        return { width: 0, height: 0 };
-    };
+            if (this._texture._size) {
+                return { width: this._texture._size, height: this._texture._size };
+            }
 
-    BABYLON.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 };
-        }
+        BaseTexture.prototype.getBaseSize = function () {
+            if (!this.isReady())
+                return { width: 0, height: 0 };
 
-        return { width: this._texture._baseWidth, height: this._texture._baseHeight };
-    };
+            if (this._texture._size) {
+                return { width: this._texture._size, height: this._texture._size };
+            }
+
+            return { width: this._texture._baseWidth, height: this._texture._baseHeight };
+        };
 
-    BABYLON.BaseTexture.prototype._getFromCache = function (url, noMipmap) {
-        var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
-        for (var index = 0; index < texturesCache.length; index++) {
-            var texturesCacheEntry = texturesCache[index];
+        //ANY
+        BaseTexture.prototype._getFromCache = 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) {
-                texturesCacheEntry.references++;
-                return texturesCacheEntry;
+                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
+                    texturesCacheEntry.references++;
+                    return texturesCacheEntry;
+                }
             }
-        }
 
-        return null;
-    };
+            return null;
+        };
 
-    BABYLON.BaseTexture.prototype.delayLoad = function () {
-    };
+        BaseTexture.prototype.delayLoad = function () {
+        };
 
-    BABYLON.BaseTexture.prototype.releaseInternalTexture = function () {
-        if (!this._texture) {
-            return;
-        }
-        var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
-        this._texture.references--;
-
-        // Final reference ?
-        if (this._texture.references == 0) {
-            var index = texturesCache.indexOf(this._texture);
-            texturesCache.splice(index, 1);
+        BaseTexture.prototype.releaseInternalTexture = function () {
+            if (!this._texture) {
+                return;
+            }
+            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
+            this._texture.references--;
 
-            this._scene.getEngine()._releaseTexture(this._texture);
+            // Final reference ?
+            if (this._texture.references == 0) {
+                var index = texturesCache.indexOf(this._texture);
+                texturesCache.splice(index, 1);
 
-            delete this._texture;
-        }
-    };
+                this._scene.getEngine()._releaseTexture(this._texture);
 
-    BABYLON.BaseTexture.prototype.dispose = function () {
-        // Remove from scene
-        var index = this._scene.textures.indexOf(this);
+                delete this._texture;
+            }
+        };
 
-        if (index >= 0) {
-            this._scene.textures.splice(index, 1);
-        }
+        BaseTexture.prototype.dispose = function () {
+            // Remove from scene
+            var index = this._scene.textures.indexOf(this);
 
-        if (this._texture === undefined) {
-            return;
-        }
+            if (index >= 0) {
+                this._scene.textures.splice(index, 1);
+            }
 
-        this.releaseInternalTexture();
+            if (this._texture === undefined) {
+                return;
+            }
 
+            this.releaseInternalTexture();
 
-        // Callback
-        if (this.onDispose) {
-            this.onDispose();
-        }
-    };
-})();
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        };
+        return BaseTexture;
+    })();
+    BABYLON.BaseTexture = BaseTexture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.baseTexture.js.map

+ 120 - 0
Babylon/Materials/textures/babylon.baseTexture.ts

@@ -0,0 +1,120 @@
+module BABYLON {
+    export class BaseTexture {
+        public delayLoadState = 0; //ANY BABYLON.Engine.DELAYLOADSTATE_NONE;
+        public hasAlpha = false;
+        public level = 1;
+        public isCube = false;
+        public _texture = null; //ANY
+        public onDispose: () => void;
+
+        private _scene; //ANY
+
+        //ANY
+        constructor(scene) {
+            this._scene = scene;
+            this._scene.textures.push(this);
+        }
+
+        //ANY
+        public getScene() {
+            return this._scene;
+        }
+
+        //ANY
+        public getInternalTexture() {
+            return this._texture;
+        }
+
+        public isReady(): boolean {
+            if (this.delayLoadState === 4) { //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return true;
+            }
+
+            if (this._texture) {
+                return this._texture.isReady;
+            }
+
+            return false;
+        }
+
+        public getSize(): ISize  {
+            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 };
+        }
+
+        public getBaseSize(): ISize {
+            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 };
+        }
+
+        //ANY
+        public _getFromCache(url: string, noMipmap: boolean) {
+            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) {
+                    texturesCacheEntry.references++;
+                    return texturesCacheEntry;
+                }
+            }
+
+            return null;
+        }
+
+        public delayLoad(): void {
+        }
+
+        public releaseInternalTexture(): void {
+            if (!this._texture) {
+                return;
+            }
+            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
+            this._texture.references--;
+
+            // Final reference ?
+            if (this._texture.references == 0) {
+                var index = texturesCache.indexOf(this._texture);
+                texturesCache.splice(index, 1);
+
+                this._scene.getEngine()._releaseTexture(this._texture);
+
+                delete this._texture;
+            }
+        }
+
+        public dispose(): void {
+            // Remove from scene
+            var index = this._scene.textures.indexOf(this);
+
+            if (index >= 0) {
+                this._scene.textures.splice(index, 1);
+            }
+
+            if (this._texture === undefined) {
+                return;
+            }
+
+            this.releaseInternalTexture();
+
+
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        }
+    }
+} 

+ 61 - 55
Babylon/Materials/textures/babylon.cubeTexture.js

@@ -1,56 +1,62 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {    
-    BABYLON.CubeTexture = function (rootUrl, scene, extensions, noMipmap) {
-        this._scene = scene;
-        this._scene.textures.push(this);
-        
-        this.name = rootUrl;
-        this.url = rootUrl;
-        this._noMipmap = noMipmap;
-        this.hasAlpha = false;
-        this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
-
-        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();
-    };
-
-    BABYLON.CubeTexture.prototype = Object.create(BABYLON.BaseTexture.prototype);
-
-    // Methods
-    BABYLON.CubeTexture.prototype.delayLoad = function () {
-        if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
-            return;
+var __extends = this.__extends || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    __.prototype = b.prototype;
+    d.prototype = new __();
+};
+var BABYLON;
+(function (BABYLON) {
+    var CubeTexture = (function (_super) {
+        __extends(CubeTexture, _super);
+        //ANY
+        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;
+
+            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 = 4; //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                }
+            }
+
+            this.isCube = true;
+
+            this._textureMatrix = BABYLON.Matrix.Identity();
         }
-
-        this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
-        this._texture = this._getFromCache(this.url, this._noMipmap);
-
-        if (!this._texture) {
-            this._texture = this._scene.getEngine().createCubeTexture(this.url, this._scene, this._extensions);
-        }
-    };
-
-    BABYLON.CubeTexture.prototype._computeReflectionTextureMatrix = function() {
-        return this._textureMatrix;
-    };
-})();
+        // Methods
+        CubeTexture.prototype.delayLoad = function () {
+            if (this.delayLoadState != 4) {
+                return;
+            }
+
+            this.delayLoadState = 1; //ANY 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._computeReflectionTextureMatrix = function () {
+            return this._textureMatrix;
+        };
+        return CubeTexture;
+    })(BABYLON.BaseTexture);
+    BABYLON.CubeTexture = CubeTexture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.cubeTexture.js.map

+ 59 - 0
Babylon/Materials/textures/babylon.cubeTexture.ts

@@ -0,0 +1,59 @@
+module BABYLON {
+    export class CubeTexture extends BaseTexture {
+        public name: string;
+        public url: string;
+        public coordinatesMode = BABYLON.Texture.CUBIC_MODE;
+
+        private _noMipmap: boolean;
+        private _extensions: string[];
+        private _textureMatrix: Matrix;
+
+        //ANY
+        constructor(rootUrl: string, scene, extensions: string[], noMipmap?: boolean) {
+            super(scene);
+
+            this.name = rootUrl;
+            this.url = rootUrl;
+            this._noMipmap = noMipmap;
+            this.hasAlpha = false;
+
+            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 = 4; //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                }
+            }
+
+            this.isCube = true;
+
+            this._textureMatrix = BABYLON.Matrix.Identity();
+        }
+
+        // Methods
+        public delayLoad(): void {
+            if (this.delayLoadState != 4) { //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return;
+            }
+
+            this.delayLoadState = 1; //ANY 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);
+            }
+        }
+
+        public _computeReflectionTextureMatrix(): Matrix {
+            return this._textureMatrix;
+        }
+    }
+} 

+ 75 - 71
Babylon/Materials/textures/babylon.dynamicTexture.js

@@ -1,81 +1,85 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.DynamicTexture = function (name, options, scene, generateMipMaps) {
-        this._scene = scene;
-        this._scene.textures.push(this);
-
-        this.name = name;
+var __extends = this.__extends || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    __.prototype = b.prototype;
+    d.prototype = new __();
+};
+var BABYLON;
+(function (BABYLON) {
+    var DynamicTexture = (function (_super) {
+        __extends(DynamicTexture, _super);
+        function DynamicTexture(name, options, scene, generateMipMaps) {
+            _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);
+            } else {
+                this._canvas = document.createElement("canvas");
 
-        this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-        this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+                if (options.width) {
+                    this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps);
+                } else {
+                    this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps);
+                }
+            }
 
-        this._generateMipMaps = generateMipMaps;
+            var textureSize = this.getSize();
 
-        if (options.getContext) {
-            this._canvas = options;
-            this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps);
-        } else {
-            this._canvas = document.createElement("canvas");
+            this._canvas.width = textureSize.width;
+            this._canvas.height = textureSize.height;
+            this._context = this._canvas.getContext("2d");
+        }
+        DynamicTexture.prototype.getContext = function () {
+            return this._context;
+        };
+
+        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) {
+            var size = this.getSize();
+            if (clearColor) {
+                this._context.fillStyle = clearColor;
+                this._context.fillRect(0, 0, size.width, size.height);
+            }
 
-            if (options.width) {
-                this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps);
-            } else {
-                this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps);
+            this._context.font = font;
+            if (x === null) {
+                var textSize = this._context.measureText(text);
+                x = (size.width - textSize.width) / 2;
             }
-        }
-        
-        var textureSize = this.getSize();
-
-        this._canvas.width = textureSize.width;
-        this._canvas.height = textureSize.height;
-        this._context = this._canvas.getContext("2d");
-    };
-
-    BABYLON.DynamicTexture.prototype = Object.create(BABYLON.Texture.prototype);
-
-    // Methods
-    BABYLON.DynamicTexture.prototype.getContext = function () {
-        return this._context;
-    };
-
-    BABYLON.DynamicTexture.prototype.update = function (invertY) {
-        this._scene.getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
-    };
-
-    BABYLON.DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
-        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);
+            this._context.fillStyle = color;
+            this._context.fillText(text, x, y);
+
+            this.update(invertY);
+        };
 
-        this.update(invertY);
-    };
-    
-    BABYLON.DynamicTexture.prototype.clone = function () {
-        var textureSize = this.getSize();
-        var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this._scene, this._generateMipMaps);
+        DynamicTexture.prototype.clone = function () {
+            var textureSize = this.getSize();
+            var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
 
-        // Base texture
-        newTexture.hasAlpha = this.hasAlpha;
-        newTexture.level = this.level;
+            // Base texture
+            newTexture.hasAlpha = this.hasAlpha;
+            newTexture.level = this.level;
 
-        // Dynamic Texture
-        newTexture.wrapU = this.wrapU;
-        newTexture.wrapV = this.wrapV;
+            // Dynamic Texture
+            newTexture.wrapU = this.wrapU;
+            newTexture.wrapV = this.wrapV;
 
-        return newTexture;
-    };
-})();
+            return newTexture;
+        };
+        return DynamicTexture;
+    })(BABYLON.Texture);
+    BABYLON.DynamicTexture = DynamicTexture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.dynamicTexture.js.map

+ 79 - 0
Babylon/Materials/textures/babylon.dynamicTexture.ts

@@ -0,0 +1,79 @@
+module BABYLON {
+    export class DynamicTexture extends Texture {
+        private _generateMipMaps: boolean;
+        private _canvas: HTMLCanvasElement;
+        private _context: CanvasRenderingContext2D;
+
+        constructor(name, options, scene, generateMipMaps) {
+            super(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);
+            } else {
+                this._canvas = document.createElement("canvas");
+
+                if (options.width) {
+                    this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps);
+                } else {
+                    this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps);
+                }
+            }
+
+            var textureSize = this.getSize();
+
+            this._canvas.width = textureSize.width;
+            this._canvas.height = textureSize.height;
+            this._context = this._canvas.getContext("2d");
+        }
+
+        public getContext(): CanvasRenderingContext2D {
+            return this._context;
+        }
+
+        public update(invertY?: boolean): void {
+            this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
+        }
+
+        public drawText(text: string, x: number, y: number, font: string, color: string, clearColor: string, invertY?: boolean) {
+            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);
+
+            this.update(invertY);
+        }
+
+        public clone(): DynamicTexture {
+            var textureSize = this.getSize();
+            var newTexture = new BABYLON.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;
+        }
+    }
+} 

+ 57 - 58
Babylon/Materials/textures/babylon.mirrorTexture.js

@@ -1,58 +1,57 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.MirrorTexture = function (name, size, scene, generateMipMaps) {
-        BABYLON.RenderTargetTexture.call(this, name, size, scene, generateMipMaps);
-        
-        // Internals
-        this._transformMatrix = BABYLON.Matrix.Zero();
-        this._mirrorMatrix = BABYLON.Matrix.Zero();
-    };
-
-    BABYLON.MirrorTexture.prototype = Object.create(BABYLON.RenderTargetTexture.prototype);
-    
-    // Members
-    BABYLON.MirrorTexture.prototype.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
-    
-    // Method
-    BABYLON.MirrorTexture.prototype.onBeforeRender = function () {
-        var scene = this._scene;
-
-        BABYLON.Matrix.ReflectionToRef(this.mirrorPlane, this._mirrorMatrix);
-        this._savedViewMatrix = scene.getViewMatrix();
-
-        this._mirrorMatrix.multiplyToRef(this._savedViewMatrix, this._transformMatrix);
-
-        scene.setTransformMatrix(this._transformMatrix, scene.getProjectionMatrix());
-
-        BABYLON.clipPlane = this.mirrorPlane;
-
-        scene.getEngine().cullBackFaces = false;
-    };
-
-    BABYLON.MirrorTexture.prototype.onAfterRender = function () {
-        var scene = this._scene;
-
-        scene.setTransformMatrix(this._savedViewMatrix, scene.getProjectionMatrix());
-        scene.getEngine().cullBackFaces = true;
-
-        delete BABYLON.clipPlane;
-    };
-    
-    BABYLON.MirrorTexture.prototype.clone = function () {
-        var textureSize = this.getSize();
-        var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this._scene, 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;
-    };
-})();
+var __extends = this.__extends || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    __.prototype = b.prototype;
+    d.prototype = new __();
+};
+var BABYLON;
+(function (BABYLON) {
+    var MirrorTexture = (function (_super) {
+        __extends(MirrorTexture, _super);
+        //ANY
+        function MirrorTexture(name, size, scene, generateMipMaps) {
+            var _this = this;
+            _super.call(this, name, size, scene, generateMipMaps);
+            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;
+            };
+
+            this.onAfterRender = function () {
+                scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
+                scene.getEngine().cullBackFaces = true;
+
+                delete scene.clipPlane;
+            };
+        }
+        MirrorTexture.prototype.clone = function () {
+            var textureSize = this.getSize();
+            var newTexture = new BABYLON.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;
+        };
+        return MirrorTexture;
+    })(BABYLON.RenderTargetTexture);
+    BABYLON.MirrorTexture = MirrorTexture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.mirrorTexture.js.map

+ 49 - 0
Babylon/Materials/textures/babylon.mirrorTexture.ts

@@ -0,0 +1,49 @@
+module BABYLON {
+    export class MirrorTexture extends RenderTargetTexture {
+        public mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
+
+        private _transformMatrix = BABYLON.Matrix.Zero();
+        private _mirrorMatrix = BABYLON.Matrix.Zero();
+        private _savedViewMatrix: Matrix;
+
+        //ANY
+        constructor(name: string, size: number, scene, generateMipMaps?: boolean) {
+            super(name, size, scene, generateMipMaps);
+
+            this.onBeforeRender = () => {
+                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;
+            }
+
+            this.onAfterRender = () => {
+                scene.setTransformMatrix(this._savedViewMatrix, scene.getProjectionMatrix());
+                scene.getEngine().cullBackFaces = true;
+
+                delete scene.clipPlane;
+            }
+        }
+
+        public clone(): MirrorTexture {
+            var textureSize = this.getSize();
+            var newTexture = new BABYLON.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;
+        }
+    }
+} 

+ 93 - 97
Babylon/Materials/textures/babylon.renderTargetTexture.js

@@ -1,113 +1,109 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.RenderTargetTexture = function (name, size, scene, generateMipMaps) {
-        this._scene = scene;
-        this._scene.textures.push(this);
-
-        this.name = name;
-        this._size = size;
-        this._generateMipMaps = generateMipMaps;
-
-        this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
-
-        // Render list
-        this.renderList = [];
-
-        // Rendering groups
-        this._renderingManager = new BABYLON.RenderingManager(scene);
-    };
-
-    BABYLON.RenderTargetTexture.prototype = Object.create(BABYLON.Texture.prototype);
-
-    // Members        
-    BABYLON.RenderTargetTexture.prototype.renderParticles = true;
-    BABYLON.RenderTargetTexture.prototype.renderSprites = false;
-    BABYLON.RenderTargetTexture.prototype.isRenderTarget = true;
-    BABYLON.RenderTargetTexture.prototype.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
-
-    // Methods  
-    BABYLON.RenderTargetTexture.prototype.onBeforeRender = null;
-    BABYLON.RenderTargetTexture.prototype.onAfterRender = null;
-
-    BABYLON.RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
-        this.releaseInternalTexture();
-        this._texture = this._scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
-    };
-
-    BABYLON.RenderTargetTexture.prototype.render = function () {
-
-        if (this.onBeforeRender) {
-            this.onBeforeRender();
+var __extends = this.__extends || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    __.prototype = b.prototype;
+    d.prototype = new __();
+};
+var BABYLON;
+(function (BABYLON) {
+    var RenderTargetTexture = (function (_super) {
+        __extends(RenderTargetTexture, _super);
+        //ANY
+        function RenderTargetTexture(name, size, scene, generateMipMaps) {
+            _super.call(this, null, scene, !generateMipMaps);
+            this.renderList = new Array();
+            this.renderParticles = true;
+            this.renderSprites = false;
+            this.isRenderTarget = true;
+            this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
+
+            this.name = name;
+            this._size = size;
+            this._generateMipMaps = generateMipMaps;
+
+            this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
+
+            // Rendering groups
+            this._renderingManager = new BABYLON.RenderingManager(scene);
         }
-
-        var scene = this._scene;
-        var engine = scene.getEngine();
-
-        if (this._waitingRenderList) {
-            this.renderList = [];
-            for (var index = 0; index < this._waitingRenderList.length; index++) {
-                var id = this._waitingRenderList[index];
-                this.renderList.push(this._scene.getMeshByID(id));
+        RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
+            this.releaseInternalTexture();
+            this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
+        };
+
+        RenderTargetTexture.prototype.render = function () {
+            if (this.onBeforeRender) {
+                this.onBeforeRender();
             }
 
-            delete this._waitingRenderList;
-        }
+            var scene = this.getScene();
+            var engine = scene.getEngine();
 
-        if (!this.renderList || this.renderList.length == 0) {
-            if (this.onAfterRender) {
-                this.onAfterRender();
-            }
-            return;
-        }
-
-        // Bind
-        engine.bindFramebuffer(this._texture);
-
-        // Clear
-        engine.clear(scene.clearColor, true, true);
-
-        this._renderingManager.reset();
+            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));
+                }
 
-        for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
-            var mesh = this.renderList[meshIndex];
+                delete this._waitingRenderList;
+            }
 
-            if (mesh && mesh.isEnabled() && mesh.isVisible) {
-                for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
-                    var subMesh = mesh.subMeshes[subIndex];
-                    scene._activeVertices += subMesh.verticesCount;
-                    this._renderingManager.dispatch(subMesh);
+            if (!this.renderList || this.renderList.length == 0) {
+                if (this.onAfterRender) {
+                    this.onAfterRender();
                 }
+                return;
             }
-        }
 
-        // Render
-        this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
+            // Bind
+            engine.bindFramebuffer(this._texture);
 
-        //Call this before unBinding Framebuffer in case of manipulating texture with WebGL commands inside the onAfterRender method.
-        if (this.onAfterRender) {
-            this.onAfterRender();
-        }
+            // Clear
+            engine.clear(scene.clearColor, true, true);
 
-        // Unbind
-        engine.unBindFramebuffer(this._texture);
-    };
+            this._renderingManager.reset();
 
-    BABYLON.RenderTargetTexture.prototype.clone = function () {
-        var textureSize = this.getSize();
-        var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this._scene, this._generateMipMaps);
+            for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
+                var mesh = this.renderList[meshIndex];
 
-        // Base texture
-        newTexture.hasAlpha = this.hasAlpha;
-        newTexture.level = this.level;
+                if (mesh && mesh.isEnabled() && mesh.isVisible) {
+                    for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
+                        var subMesh = mesh.subMeshes[subIndex];
+                        scene._activeVertices += subMesh.verticesCount;
+                        this._renderingManager.dispatch(subMesh);
+                    }
+                }
+            }
 
-        // RenderTarget Texture
-        newTexture.coordinatesMode = this.coordinatesMode;
-        newTexture.renderList = this.renderList.slice(0);
+            // Render
+            this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
 
-        return newTexture;
-    };
+            //Call this before unBinding Framebuffer in case of manipulating texture with WebGL commands inside the onAfterRender method.
+            if (this.onAfterRender) {
+                this.onAfterRender();
+            }
 
-})();
+            // Unbind
+            engine.unBindFramebuffer(this._texture);
+        };
+
+        RenderTargetTexture.prototype.clone = function () {
+            var textureSize = this.getSize();
+            var newTexture = new BABYLON.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;
+        };
+        return RenderTargetTexture;
+    })(BABYLON.Texture);
+    BABYLON.RenderTargetTexture = RenderTargetTexture;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.renderTargetTexture.js.map

+ 109 - 0
Babylon/Materials/textures/babylon.renderTargetTexture.ts

@@ -0,0 +1,109 @@
+module BABYLON {
+    export class RenderTargetTexture extends Texture {
+        public renderList = new Array<Mesh>();
+        public renderParticles = true;
+        public renderSprites = false;
+        public isRenderTarget = true;
+        public coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
+        public onBeforeRender: () => void;
+        public onAfterRender: () => void;
+        public customRenderFunction: (opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray, beforeTransparents: () => void) => void;
+
+        private _size: number;
+        public _generateMipMaps: boolean;
+        private _renderingManager
+        public _waitingRenderList: number[];
+
+        //ANY
+        constructor(name: string, size: number, scene, generateMipMaps?: boolean) {
+            super(null, scene, !generateMipMaps);
+
+            this.name = name;
+            this._size = size;
+            this._generateMipMaps = generateMipMaps;
+
+            this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
+
+            // Rendering groups
+            this._renderingManager = new BABYLON.RenderingManager(scene);
+        }
+
+        public resize(size, generateMipMaps) {
+            this.releaseInternalTexture();
+            this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
+        }
+
+        public render() {
+
+            if (this.onBeforeRender) {
+                this.onBeforeRender();
+            }
+
+            var scene = this.getScene();
+            var engine = scene.getEngine();
+
+            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) {
+                if (this.onAfterRender) {
+                    this.onAfterRender();
+                }
+                return;
+            }
+
+            // Bind
+            engine.bindFramebuffer(this._texture);
+
+            // Clear
+            engine.clear(scene.clearColor, true, true);
+
+            this._renderingManager.reset();
+
+            for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
+                var mesh = this.renderList[meshIndex];
+
+                if (mesh && mesh.isEnabled() && mesh.isVisible) {
+                    for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
+                        var subMesh = mesh.subMeshes[subIndex];
+                        scene._activeVertices += subMesh.verticesCount;
+                        this._renderingManager.dispatch(subMesh);
+                    }
+                }
+            }
+
+            // Render
+            this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
+
+            //Call this before unBinding Framebuffer in case of manipulating texture with WebGL commands inside the onAfterRender method.
+            if (this.onAfterRender) {
+                this.onAfterRender();
+            }
+
+            // Unbind
+            engine.unBindFramebuffer(this._texture);
+        }
+
+        public clone(): RenderTargetTexture {
+            var textureSize = this.getSize();
+            var newTexture = new BABYLON.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;
+        }
+    }
+} 

+ 187 - 190
Babylon/Materials/textures/babylon.texture.js

@@ -1,207 +1,204 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
+var __extends = this.__extends || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    __.prototype = b.prototype;
+    d.prototype = new __();
+};
+var BABYLON;
+(function (BABYLON) {
+    var Texture = (function (_super) {
+        __extends(Texture, _super);
+        //ANY
+        function Texture(url, scene, noMipmap, invertY) {
+            _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.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
+            this.coordinatesIndex = 0;
+            this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
+            this.anisotropicFilteringLevel = 4;
+            this.animations = new Array();
+
+            this.name = url;
+            this.url = url;
+            this._noMipmap = noMipmap;
+            this._invertY = invertY;
+
+            if (!url) {
+                return;
+            }
 
-(function () {
-    BABYLON.Texture = function (url, scene, noMipmap, invertY) {
-        this._scene = scene;
-        this._scene.textures.push(this);
+            this._texture = this._getFromCache(url, noMipmap);
 
-        this.name = url;
-        this.url = url;
-        this._noMipmap = noMipmap;
-        this._invertY = invertY;
+            if (!this._texture) {
+                if (!scene.useDelayedTextureLoading) {
+                    this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene);
+                } else {
+                    this.delayLoadState = 4; //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                }
+            }
+        }
+        Texture.prototype.delayLoad = function () {
+            if (this.delayLoadState != 4) {
+                return;
+            }
 
-        this._texture = this._getFromCache(url, noMipmap);
+            this.delayLoadState = 1; //ANY BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this._texture = this._getFromCache(this.url, this._noMipmap);
 
-        if (!this._texture) {
-            if (!scene.useDelayedTextureLoading) {
-                this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene);
-            } else {
-                this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+            if (!this._texture) {
+                this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene());
             }
-        }
+        };
 
-        // Animations
-        this.animations = [];
-    };
-
-    BABYLON.Texture.prototype = Object.create(BABYLON.BaseTexture.prototype);
-
-    // Constants
-    BABYLON.Texture.NEAREST_SAMPLINGMODE = 1;
-    BABYLON.Texture.BILINEAR_SAMPLINGMODE = 2;
-    BABYLON.Texture.TRILINEAR_SAMPLINGMODE = 3;
-
-    BABYLON.Texture.EXPLICIT_MODE = 0;
-    BABYLON.Texture.SPHERICAL_MODE = 1;
-    BABYLON.Texture.PLANAR_MODE = 2;
-    BABYLON.Texture.CUBIC_MODE = 3;
-    BABYLON.Texture.PROJECTION_MODE = 4;
-    BABYLON.Texture.SKYBOX_MODE = 5;
-
-    BABYLON.Texture.CLAMP_ADDRESSMODE = 0;
-    BABYLON.Texture.WRAP_ADDRESSMODE = 1;
-    BABYLON.Texture.MIRROR_ADDRESSMODE = 2;
-
-    // Members
-    BABYLON.Texture.prototype.uOffset = 0;
-    BABYLON.Texture.prototype.vOffset = 0;
-    BABYLON.Texture.prototype.uScale = 1.0;
-    BABYLON.Texture.prototype.vScale = 1.0;
-    BABYLON.Texture.prototype.uAng = 0;
-    BABYLON.Texture.prototype.vAng = 0;
-    BABYLON.Texture.prototype.wAng = 0;
-    BABYLON.Texture.prototype.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
-    BABYLON.Texture.prototype.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
-    BABYLON.Texture.prototype.coordinatesIndex = 0;
-    BABYLON.Texture.prototype.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
-    BABYLON.Texture.prototype.anisotropicFilteringLevel = 4;
-
-    // Methods    
-    BABYLON.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);
+        Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
+            x -= this.uOffset + 0.5;
+            y -= this.vOffset + 0.5;
+            z -= 0.5;
 
-        if (!this._texture) {
-            this._texture = this._scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, this._scene);
-        }
-    };
-
-    BABYLON.Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
-        x -= this.uOffset + 0.5;
-        y -= this.vOffset + 0.5;
-        z -= 0.5;
-
-        BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
-
-        t.x *= this.uScale;
-        t.y *= this.vScale;
-
-        t.x += 0.5;
-        t.y += 0.5;
-        t.z += 0.5;
-    };
-
-    BABYLON.Texture.prototype._computeTextureMatrix = 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;
-        }
+            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
 
-        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();
-        }
+            t.x *= this.uScale;
+            t.y *= this.vScale;
 
-        BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
+            t.x += 0.5;
+            t.y += 0.5;
+            t.z += 0.5;
+        };
 
-        this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
-        this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
-        this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
+        Texture.prototype._computeTextureMatrix = 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._t1.subtractInPlace(this._t0);
-        this._t2.subtractInPlace(this._t0);
+            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);
 
-        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;
+            this._t1.subtractInPlace(this._t0);
+            this._t2.subtractInPlace(this._t0);
 
-        return this._cachedTextureMatrix;
-    };
+            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;
 
-    BABYLON.Texture.prototype._computeReflectionTextureMatrix = 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();
-        }
+        Texture.prototype._computeReflectionTextureMatrix = 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;
+            }
 
-        switch (this.coordinatesMode) {
-            case BABYLON.Texture.SPHERICAL_MODE:
-                BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
-                this._cachedTextureMatrix[0] = -0.5 * this.uScale;
-                this._cachedTextureMatrix[5] = -0.5 * this.vScale;
-                this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
-                this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
-                break;
-            case BABYLON.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 BABYLON.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._scene.getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
-                break;
-            default:
-                BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
-                break;
-        }
-        return this._cachedTextureMatrix;
-    };
-
-    BABYLON.Texture.prototype.clone = function () {
-        var newTexture = new BABYLON.Texture(this._texture.url, this._scene, this._noMipmap, this._invertY);
-
-        // Base texture
-        newTexture.hasAlpha = this.hasAlpha;
-        newTexture.level = this.level;
-
-        // 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;
-        newTexture.wrapU = this.wrapU;
-        newTexture.wrapV = this.wrapV;
-        newTexture.coordinatesIndex = this.coordinatesIndex;
-        newTexture.coordinatesMode = this.coordinatesMode;
-
-        return newTexture;
-    };
-})();
+            if (!this._cachedTextureMatrix) {
+                this._cachedTextureMatrix = BABYLON.Matrix.Zero();
+                this._projectionModeMatrix = BABYLON.Matrix.Zero();
+            }
+
+            switch (this.coordinatesMode) {
+                case BABYLON.Texture.SPHERICAL_MODE:
+                    BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
+                    this._cachedTextureMatrix[0] = -0.5 * this.uScale;
+                    this._cachedTextureMatrix[5] = -0.5 * this.vScale;
+                    this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
+                    this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
+                    break;
+                case BABYLON.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 BABYLON.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 BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
+
+            // Base texture
+            newTexture.hasAlpha = this.hasAlpha;
+            newTexture.level = this.level;
+
+            // 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;
+            newTexture.wrapU = this.wrapU;
+            newTexture.wrapV = this.wrapV;
+            newTexture.coordinatesIndex = this.coordinatesIndex;
+            newTexture.coordinatesMode = this.coordinatesMode;
+
+            return newTexture;
+        };
+        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.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

+ 225 - 0
Babylon/Materials/textures/babylon.texture.ts

@@ -0,0 +1,225 @@
+module BABYLON {
+    export class Texture extends BaseTexture {
+        // Constants
+        public static NEAREST_SAMPLINGMODE = 1;
+        public static BILINEAR_SAMPLINGMODE = 2;
+        public static TRILINEAR_SAMPLINGMODE = 3;
+
+        public static EXPLICIT_MODE = 0;
+        public static SPHERICAL_MODE = 1;
+        public static PLANAR_MODE = 2;
+        public static CUBIC_MODE = 3;
+        public static PROJECTION_MODE = 4;
+        public static SKYBOX_MODE = 5;
+
+        public static CLAMP_ADDRESSMODE = 0;
+        public static WRAP_ADDRESSMODE = 1;
+        public static MIRROR_ADDRESSMODE = 2;
+
+        // Members
+        public name: string;
+        public url: string;
+        public uOffset = 0;
+        public vOffset = 0;
+        public uScale = 1.0;
+        public vScale = 1.0;
+        public uAng = 0;
+        public vAng = 0;
+        public wAng = 0;
+        public wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
+        public wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
+        public coordinatesIndex = 0;
+        public coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
+        public anisotropicFilteringLevel = 4;
+        public animations = new Array<Animation>();
+
+        private _noMipmap: boolean;
+        public _invertY: boolean;
+        private _rowGenerationMatrix: Matrix;
+        private _cachedTextureMatrix: Matrix;
+        private _projectionModeMatrix: Matrix;
+        private _t0: Vector3;
+        private _t1: Vector3;
+        private _t2: Vector3;
+
+        public _cachedAnisotropicFilteringLevel: number;
+        private _cachedUOffset: number;
+        private _cachedVOffset: number;
+        private _cachedUScale: number;
+        private _cachedVScale: number;
+        private _cachedUAng: number;
+        private _cachedVAng: number;
+        private _cachedWAng: number;
+        private _cachedCoordinatesMode: number;
+
+        //ANY
+        constructor(url: string, scene, noMipmap?: boolean, invertY?: boolean) {
+            super(scene);
+
+            this.name = url;
+            this.url = url;
+            this._noMipmap = noMipmap;
+            this._invertY = invertY;
+
+            if (!url) {
+                return;
+            }
+
+            this._texture = this._getFromCache(url, noMipmap);
+
+            if (!this._texture) {
+                if (!scene.useDelayedTextureLoading) {
+                    this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene);
+                } else {
+                    this.delayLoadState = 4; //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
+                }
+            }
+        }
+
+        public delayLoad(): void {
+            if (this.delayLoadState != 4) { //ANY BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
+                return;
+            }
+
+            this.delayLoadState = 1;//ANY BABYLON.Engine.DELAYLOADSTATE_LOADED;
+            this._texture = this._getFromCache(this.url, this._noMipmap);
+
+            if (!this._texture) {
+                this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene());
+            }
+        }
+
+        private _prepareRowForTextureGeneration(x: number, y: number, z: number, t: Vector3): void {
+            x -= this.uOffset + 0.5;
+            y -= this.vOffset + 0.5;
+            z -= 0.5;
+
+            Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
+
+            t.x *= this.uScale;
+            t.y *= this.vScale;
+
+            t.x += 0.5;
+            t.y += 0.5;
+            t.z += 0.5;
+        }
+
+        private _computeTextureMatrix(): Matrix {
+            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;
+        }
+
+        private _computeReflectionTextureMatrix(): Matrix {
+            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();
+            }
+
+            switch (this.coordinatesMode) {
+                case BABYLON.Texture.SPHERICAL_MODE:
+                    BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
+                    this._cachedTextureMatrix[0] = -0.5 * this.uScale;
+                    this._cachedTextureMatrix[5] = -0.5 * this.vScale;
+                    this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
+                    this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
+                    break;
+                case BABYLON.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 BABYLON.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;
+        }
+
+        public clone(): Texture {
+            var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
+
+            // Base texture
+            newTexture.hasAlpha = this.hasAlpha;
+            newTexture.level = this.level;
+
+            // 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;
+            newTexture.wrapU = this.wrapU;
+            newTexture.wrapV = this.wrapV;
+            newTexture.coordinatesIndex = this.coordinatesIndex;
+            newTexture.coordinatesMode = this.coordinatesMode;
+
+            return newTexture;
+        }
+    }
+} 

+ 53 - 50
Babylon/Materials/textures/babylon.videoTexture.js

@@ -1,61 +1,64 @@
-"use strict";
+var __extends = this.__extends || function (d, b) {
+    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+    function __() { this.constructor = d; }
+    __.prototype = b.prototype;
+    d.prototype = new __();
+};
+var BABYLON;
+(function (BABYLON) {
+    var VideoTexture = (function (_super) {
+        __extends(VideoTexture, _super);
+        function VideoTexture(name, urls, size, scene, generateMipMaps, invertY) {
+            var _this = this;
+            _super.call(this, null, scene, !generateMipMaps, invertY);
+            this._autoLaunch = true;
 
-var BABYLON = BABYLON || {};
+            this.name = name;
 
-(function () {
-    BABYLON.VideoTexture = function (name, urls, size, scene, generateMipMaps, invertY) {
-        this._scene = scene;
-        this._scene.textures.push(this);
+            this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
 
-        this.name = name;
-        this._invertY = invertY;
+            this._texture = scene.getEngine().createDynamicTexture(size, size, generateMipMaps);
+            var textureSize = this.getSize();
 
-        this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
-        this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
+            this.video = document.createElement("video");
+            this.video.width = textureSize.width;
+            this.video.height = textureSize.height;
+            this.video.autoplay = false;
+            this.video.loop = true;
 
-        this._texture = scene.getEngine().createDynamicTexture(size, size, generateMipMaps);
-        var textureSize = this.getSize();
+            this.video.addEventListener("canplaythrough", function () {
+                if (_this._texture) {
+                    _this._texture.isReady = true;
+                }
+            });
 
-        this.video = document.createElement("video");
-        this.video.width = textureSize.width;
-        this.video.height = textureSize.height;
-        this.video.autoplay = false;
-        this.video.loop = true;
-        this.video.preload = true;
-        this._autoLaunch = true;
+            urls.forEach(function (url) {
+                var source = document.createElement("source");
+                source.src = url;
+                _this.video.appendChild(source);
+            });
 
-        var that = this;
-        this.video.addEventListener("canplaythrough", function () {
-            if (that._texture) {
-                that._texture.isReady = true;
+            this._lastUpdate = new Date().getTime();
+        }
+        VideoTexture.prototype.update = function () {
+            if (this._autoLaunch) {
+                this._autoLaunch = false;
+                this.video.play();
             }
-        });
-
-        urls.forEach(function (url) {
-            var source = document.createElement("source");
-            source.src = url;
-            that.video.appendChild(source);
-        });
 
-        this._lastUpdate = new Date();
-    };
+            var now = new Date().getTime();
 
-    BABYLON.VideoTexture.prototype = Object.create(BABYLON.Texture.prototype);
-
-    BABYLON.VideoTexture.prototype._update = function () {
-        if (this._autoLaunch) {
-            this._autoLaunch = false;
-            this.video.play();
-        }
-        
-        var now = new Date();
-
-        if (now - this._lastUpdate < 15) {
-            return false;
-        }
+            if (now - this._lastUpdate < 15) {
+                return false;
+            }
 
-        this._lastUpdate = now;
-        this._scene.getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
-        return true;
-    };
-})();
+            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

+ 57 - 0
Babylon/Materials/textures/babylon.videoTexture.ts

@@ -0,0 +1,57 @@
+module BABYLON {
+    export class VideoTexture extends Texture {
+        public video: HTMLVideoElement;
+
+        private _autoLaunch = true;
+        private _lastUpdate: number;
+
+        constructor(name: string, urls, size, scene, generateMipMaps, invertY) {
+            super(null, scene, !generateMipMaps, invertY);
+
+            this.name = name;
+
+            this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
+            this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
+
+            this._texture = scene.getEngine().createDynamicTexture(size, size, generateMipMaps);
+            var textureSize = this.getSize();
+
+            this.video = document.createElement("video");
+            this.video.width = textureSize.width;
+            this.video.height = textureSize.height;
+            this.video.autoplay = false;
+            this.video.loop = true;
+
+            this.video.addEventListener("canplaythrough", () => {
+                if (this._texture) {
+                    this._texture.isReady = true;
+                }
+            });
+
+            urls.forEach(url => {
+                var source = document.createElement("source");
+                source.src = url;
+                this.video.appendChild(source);
+            });
+
+            this._lastUpdate = new Date().getTime();
+        }
+
+        public update(): boolean {
+            if (this._autoLaunch) {
+                this._autoLaunch = false;
+                this.video.play();
+            }
+
+            var now = new Date().getTime();
+
+            if (now - this._lastUpdate < 15) {
+                return false;
+            }
+
+            this._lastUpdate = now;
+            this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
+            return true;
+        }
+    }
+} 

+ 7 - 0
Babylon/Math/babylon.math.js

@@ -2,6 +2,9 @@
 (function (BABYLON) {
     var Color3 = (function () {
         function Color3(r, g, b) {
+            if (typeof r === "undefined") { r = 0; }
+            if (typeof g === "undefined") { g = 0; }
+            if (typeof b === "undefined") { b = 0; }
             this.r = r;
             this.g = g;
             this.b = b;
@@ -1612,6 +1615,10 @@
         };
 
         // Methods
+        Plane.prototype.clone = function () {
+            return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
+        };
+
         Plane.prototype.normalize = function () {
             var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
             var magnitude = 0;

+ 5 - 1
Babylon/Math/babylon.math.ts

@@ -1,6 +1,6 @@
 module BABYLON {
     export class Color3 {
-        constructor(public r: number, public g: number, public b: number) {
+        constructor(public r: number = 0, public g: number = 0, public b: number = 0) {
         }
 
         public toString(): string {
@@ -1643,6 +1643,10 @@
         }
 
         // Methods
+        public clone(): Plane {
+            return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
+        }
+
         public normalize(): void {
             var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
             var magnitude = 0;

+ 2 - 8
Babylon/Mesh/babylon.mesh.js

@@ -277,13 +277,7 @@ var BABYLON;
         Mesh.prototype._updateBoundingInfo = function () {
             this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this._absolutePosition, this._absolutePosition);
 
-            this._scaleFactor = Math.max(this.scaling.x, this.scaling.y);
-            this._scaleFactor = Math.max(this._scaleFactor, this.scaling.z);
-
-            if (this.parent && this.parent instanceof Mesh)
-                this._scaleFactor = this._scaleFactor * this.parent._scaleFactor;
-
-            this._boundingInfo._update(this._worldMatrix, this._scaleFactor);
+            this._boundingInfo._update(this._worldMatrix);
 
             if (!this.subMeshes) {
                 return;
@@ -292,7 +286,7 @@ var BABYLON;
             for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
                 var subMesh = this.subMeshes[subIndex];
 
-                subMesh.updateBoundingInfo(this._worldMatrix, this._scaleFactor);
+                subMesh.updateBoundingInfo(this._worldMatrix);
             }
         };
 

+ 2 - 9
Babylon/Mesh/babylon.mesh.ts

@@ -60,7 +60,6 @@
         private _delayInfo; //ANY
         private _vertexStrideSize = 0;
         private _animationStarted = false;
-        private _scaleFactor: number;
         private _vertexBuffers;
         private _indexBuffer;
         private _delayLoadingFunction: (any, Mesh) => void;
@@ -296,13 +295,7 @@
         public _updateBoundingInfo(): void {
             this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this._absolutePosition, this._absolutePosition);
 
-            this._scaleFactor = Math.max(this.scaling.x, this.scaling.y);
-            this._scaleFactor = Math.max(this._scaleFactor, this.scaling.z);
-
-            if (this.parent && this.parent instanceof Mesh)
-                this._scaleFactor = this._scaleFactor * (<any>this.parent)._scaleFactor;
-
-            this._boundingInfo._update(this._worldMatrix, this._scaleFactor);
+            this._boundingInfo._update(this._worldMatrix);
 
             if (!this.subMeshes) {
                 return;
@@ -311,7 +304,7 @@
             for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
                 var subMesh = this.subMeshes[subIndex];
 
-                subMesh.updateBoundingInfo(this._worldMatrix, this._scaleFactor);
+                subMesh.updateBoundingInfo(this._worldMatrix);
             }
         }
 

+ 2 - 3
Babylon/Mesh/babylon.subMesh.js

@@ -51,9 +51,8 @@
             return this._boundingInfo._checkCollision(collider);
         };
 
-        SubMesh.prototype.updateBoundingInfo = function (world, scale) {
-            if (typeof scale === "undefined") { scale = 1.0; }
-            this._boundingInfo._update(world, scale);
+        SubMesh.prototype.updateBoundingInfo = function (world) {
+            this._boundingInfo._update(world);
         };
 
         SubMesh.prototype.isInFrustum = function (frustumPlanes) {

+ 2 - 2
Babylon/Mesh/babylon.subMesh.ts

@@ -55,8 +55,8 @@
             return this._boundingInfo._checkCollision(collider);
         }
 
-        public updateBoundingInfo(world: Matrix, scale: number = 1.0): void {
-            this._boundingInfo._update(world, scale);
+        public updateBoundingInfo(world: Matrix): void {
+            this._boundingInfo._update(world);
         }
 
         public isInFrustum(frustumPlanes: Plane[]): boolean {

+ 4 - 0
Babylon/Mesh/babylon.vertexBuffer.js

@@ -53,6 +53,10 @@
             return this._data;
         };
 
+        VertexBuffer.prototype.getBuffer = function () {
+            return this._buffer;
+        };
+
         VertexBuffer.prototype.getStrideSize = function () {
             return this._strideSize;
         };

+ 5 - 1
Babylon/Mesh/babylon.vertexBuffer.ts

@@ -2,7 +2,7 @@
     export class VertexBuffer {
         private _mesh; //ANY
         private _engine; //ANY
-        private _buffer;
+        private _buffer: WebGLBuffer;
         private _data: number[];
         private _updatable: boolean;
         private _kind: string;
@@ -61,6 +61,10 @@
             return this._data;
         }
 
+        public getBuffer(): WebGLBuffer {
+            return this._buffer;
+        }
+
         public getStrideSize(): number {
             return this._strideSize;
         }

+ 4 - 3
Babylon/Particles/babylon.particleSystem.js

@@ -207,7 +207,7 @@ var BABYLON = BABYLON || {};
     BABYLON.ParticleSystem.prototype._getEffect = function () {
         var defines = [];
         
-        if (BABYLON.clipPlane) {
+        if (this._scene.clipPlane) {
             defines.push("#define CLIPPLANE");
         }
         
@@ -315,11 +315,12 @@ var BABYLON = BABYLON || {};
         effect.setMatrix("projection", this._scene.getProjectionMatrix());
         effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
 
-        if (BABYLON.clipPlane) {
+        if (this._scene.clipPlane) {
+            var clipPlane = this._scene.clipPlane;
             var invView = viewMatrix.clone();
             invView.invert();
             effect.setMatrix("invView", invView);
-            effect.setFloat4("vClipPlane", BABYLON.clipPlane.normal.x, BABYLON.clipPlane.normal.y, BABYLON.clipPlane.normal.z, BABYLON.clipPlane.d);
+            effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
         }        
 
         // VBOs

+ 1 - 1
Babylon/Physics/babylon.physicsEngine.ts

@@ -164,7 +164,7 @@
             return body;
         }
 
-        public _registerCompound(options): void {
+        public _registerCompound(options): any {
             var compoundShape = new CANNON.Compound();
             var initialMesh = options.parts[0].mesh;
             var initialPosition = initialMesh.position;

+ 4 - 4
Babylon/PostProcess/babylon.postProcess.ts

@@ -13,9 +13,9 @@
         private _engine; //ANY
         private _renderRatio: number;
         private _reusable = false;
-        private _textures = new BABYLON.SmartArray(2);
-        private _currentRenderTextureInd = 0;
-        private _effect; //ANY
+        public _textures = new BABYLON.SmartArray(2);
+        public _currentRenderTextureInd = 0;
+        private _effect: Effect;
 
         //ANY
         constructor(public name: string, fragmentUrl: string, parameters: string[], samplers: string[], ratio: number, camera: Camera, samplingMode: number, engine, reusable?: boolean) {
@@ -85,7 +85,7 @@
             }
         }
 
-        public apply(): void {
+        public apply(): Effect {
             // Check
             if (!this._effect.isReady())
                 return null;

+ 83 - 82
Babylon/PostProcess/babylon.postProcessManager.js

@@ -1,91 +1,92 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.PostProcessManager = function (scene) {
-        this._scene = scene;
-        
-        // VBO
-        var vertices = [];
-        vertices.push(1, 1);
-        vertices.push(-1, 1);
-        vertices.push(-1, -1);
-        vertices.push(1, -1);
-        this._vertexDeclaration = [2];
-        this._vertexStrideSize = 2 * 4;
-        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);
-    };
-
-    // Methods
-    BABYLON.PostProcessManager.prototype._prepareFrame = function () {
-        var postProcesses = this._scene.activeCamera._postProcesses;
-        var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
-		
-        if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
-            return;
-        }
-        
-        postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera);
-    };
-    
-    BABYLON.PostProcessManager.prototype._finalizeFrame = function (doNotPresent) {
-        var postProcesses = this._scene.activeCamera._postProcesses;
-        var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
-        if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
-            return;
+var BABYLON;
+(function (BABYLON) {
+    var PostProcessManager = (function () {
+        function PostProcessManager(scene) {
+            this._vertexDeclaration = [2];
+            this._vertexStrideSize = 2 * 4;
+            this._scene = scene;
+
+            // 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);
         }
+        // Methods
+        PostProcessManager.prototype._prepareFrame = function () {
+            var postProcesses = this._scene.activeCamera._postProcesses;
+            var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
 
-        var engine = this._scene.getEngine();
-        
-        for (var index = 0; index < postProcessesTakenIndices.length; index++) {
-            if (index < postProcessesTakenIndices.length - 1) {
-                postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
-            } else {
-                engine.restoreDefaultFramebuffer();
+            if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
+                return;
             }
 
-            if (doNotPresent) {
-                break;
+            postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera);
+        };
+
+        PostProcessManager.prototype._finalizeFrame = function (doNotPresent) {
+            var postProcesses = this._scene.activeCamera._postProcesses;
+            var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
+            if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
+                return;
             }
 
-            var effect = postProcesses[postProcessesTakenIndices[index]].apply();
+            var engine = this._scene.getEngine();
+
+            for (var index = 0; index < postProcessesTakenIndices.length; index++) {
+                if (index < postProcessesTakenIndices.length - 1) {
+                    postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
+                } else {
+                    engine.restoreDefaultFramebuffer();
+                }
+
+                if (doNotPresent) {
+                    break;
+                }
+
+                var effect = postProcesses[postProcessesTakenIndices[index]].apply();
 
-            if (effect) {
-                // VBOs
-                engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
-                
-                // Draw order
-                engine.draw(true, 0, 6);
+                if (effect) {
+                    // VBOs
+                    engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
+
+                    // Draw order
+                    engine.draw(true, 0, 6);
+                }
             }
-        }
-        
-        // Restore depth buffer
-        engine.setDepthBuffer(true);
-        engine.setDepthWrite(true);
-    };
-
-    BABYLON.PostProcessManager.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;
-        }
-    };
-})();
+            // Restore depth buffer
+            engine.setDepthBuffer(true);
+            engine.setDepthWrite(true);
+        };
+
+        PostProcessManager.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;
+            }
+        };
+        return PostProcessManager;
+    })();
+    BABYLON.PostProcessManager = PostProcessManager;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.postProcessManager.js.map

+ 93 - 0
Babylon/PostProcess/babylon.postProcessManager.ts

@@ -0,0 +1,93 @@
+module BABYLON {
+    export class PostProcessManager {
+        private _scene: Scene;
+        private _indexBuffer: WebGLBuffer;
+        private _vertexDeclaration = [2];
+        private _vertexStrideSize = 2 * 4;
+        private _vertexBuffer: WebGLBuffer;
+
+        constructor(scene: Scene) {
+            this._scene = scene;
+
+            // 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);
+        }
+
+        // Methods
+        public _prepareFrame(): void {
+            var postProcesses = this._scene.activeCamera._postProcesses;
+            var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
+
+            if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
+                return;
+            }
+
+            postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera);
+        }
+
+        public _finalizeFrame(doNotPresent?: boolean): void {
+            var postProcesses = this._scene.activeCamera._postProcesses;
+            var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
+            if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
+                return;
+            }
+
+            var engine = this._scene.getEngine();
+
+            for (var index = 0; index < postProcessesTakenIndices.length; index++) {
+                if (index < postProcessesTakenIndices.length - 1) {
+                    postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
+                } else {
+                    engine.restoreDefaultFramebuffer();
+                }
+
+                if (doNotPresent) {
+                    break;
+                }
+
+                var effect = postProcesses[postProcessesTakenIndices[index]].apply();
+
+                if (effect) {
+                    // VBOs
+                    engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
+
+                    // Draw order
+                    engine.draw(true, 0, 6);
+                }
+            }
+
+            // Restore depth buffer
+            engine.setDepthBuffer(true);
+            engine.setDepthWrite(true);
+        }
+
+        public dispose(): void {
+            if (this._vertexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
+                this._vertexBuffer = null;
+            }
+
+            if (this._indexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
+                this._indexBuffer = null;
+            }
+        }
+    }
+} 

+ 69 - 76
Babylon/Rendering/babylon.boundingBoxRenderer.js

@@ -1,84 +1,77 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.BoundingBoxRenderer = function (scene) {
-        this._scene = scene;
-        this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color",
-        {
-            attributes: ["position"],
-            uniforms: ["worldViewProjection", "color"]
-        });
-        this.frontColor = new BABYLON.Color3(1, 1, 1);
-        this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
-
-        var engine = this._scene.getEngine();
-        var boxdata = BABYLON.VertexData.CreateBox(1.0);
-        this._vb = new BABYLON.VertexBuffer(null, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false, engine);
-        this._ib = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
-
-        this.renderList = new BABYLON.SmartArray(32);
-    };
-
-    // Members
-    BABYLON.BoundingBoxRenderer.prototype.showBackLines = true;
-
-    // Functions
-    BABYLON.BoundingBoxRenderer.prototype.reset = function() {
-        this.renderList.reset();
-    };
-
-    BABYLON.BoundingBoxRenderer.prototype.render = function () {
-        if (this.renderList.length == 0 || !this._colorShader.isReady()) {
-            return;
+var BABYLON;
+(function (BABYLON) {
+    var BoundingBoxRenderer = (function () {
+        function BoundingBoxRenderer(scene) {
+            this.frontColor = new BABYLON.Color3(1, 1, 1);
+            this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
+            this.showBackLines = true;
+            this.renderList = new BABYLON.SmartArray(32);
+            this._scene = scene;
+            this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
+                attributes: ["position"],
+                uniforms: ["worldViewProjection", "color"]
+            });
+
+            var engine = this._scene.getEngine();
+            var boxdata = BABYLON.VertexData.CreateBox(1.0);
+            this._vb = new BABYLON.VertexBuffer(null, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false, engine);
+            this._ib = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
         }
+        BoundingBoxRenderer.prototype.reset = function () {
+            this.renderList.reset();
+        };
 
-        var engine = this._scene.getEngine();
-        engine.setDepthWrite(false);
-        this._colorShader._preBind();
-        for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
-            var mesh = this.renderList.data[boundingBoxIndex];
-            var boundingBox = mesh.getBoundingInfo().boundingBox;
-            var min = boundingBox.minimum;
-            var max = boundingBox.maximum;
-            var diff = max.subtract(min);
-            var median = min.add(diff.scale(0.5));
-
-            var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
-                .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
-                .multiply(mesh.getWorldMatrix());
-
-            // VBOs
-            engine.bindBuffers(this._vb._buffer, this._ib, [3], 3 * 4, this._colorShader.getEffect());
+        BoundingBoxRenderer.prototype.render = function () {
+            if (this.renderList.length == 0 || !this._colorShader.isReady()) {
+                return;
+            }
 
-            if (this.showBackLines) {
-                // Back
-                engine.setDepthFunctionToGreaterOrEqual();
-                this._colorShader.setColor3("color", this.backColor);
+            var engine = this._scene.getEngine();
+            engine.setDepthWrite(false);
+            this._colorShader._preBind();
+            for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
+                var mesh = this.renderList.data[boundingBoxIndex];
+                var boundingBox = mesh.getBoundingInfo().boundingBox;
+                var min = boundingBox.minimum;
+                var max = boundingBox.maximum;
+                var diff = max.subtract(min);
+                var median = min.add(diff.scale(0.5));
+
+                var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(mesh.getWorldMatrix());
+
+                // VBOs
+                engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
+
+                if (this.showBackLines) {
+                    // Back
+                    engine.setDepthFunctionToGreaterOrEqual();
+                    this._colorShader.setColor3("color", this.backColor);
+                    this._colorShader.bind(worldMatrix, mesh);
+
+                    // Draw order
+                    engine.draw(false, 0, 24);
+                }
+
+                // Front
+                engine.setDepthFunctionToLess();
+                this._colorShader.setColor3("color", this.frontColor);
                 this._colorShader.bind(worldMatrix, mesh);
 
                 // Draw order
                 engine.draw(false, 0, 24);
             }
-
-            // Front
-            engine.setDepthFunctionToLess();
-            this._colorShader.setColor3("color", this.frontColor);
-            this._colorShader.bind(worldMatrix, mesh);
-
-            // Draw order
-            engine.draw(false, 0, 24);
-        }
-        this._colorShader.unbind();
-        engine.setDepthFunctionToLessOrEqual();
-        engine.setDepthWrite(true);
-    };
-
-
-    BABYLON.BoundingBoxRenderer.prototype.dispose = function () {
-        this._colorShader.dispose();
-        this._vb.dispose();
-        this._scene.getEngine()._releaseBuffer(this._ib);
-    };
-})();
+            this._colorShader.unbind();
+            engine.setDepthFunctionToLessOrEqual();
+            engine.setDepthWrite(true);
+        };
+
+        BoundingBoxRenderer.prototype.dispose = function () {
+            this._colorShader.dispose();
+            this._vb.dispose();
+            this._scene.getEngine()._releaseBuffer(this._ib);
+        };
+        return BoundingBoxRenderer;
+    })();
+    BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.boundingBoxRenderer.js.map

+ 85 - 0
Babylon/Rendering/babylon.boundingBoxRenderer.ts

@@ -0,0 +1,85 @@
+module BABYLON {
+    export class BoundingBoxRenderer {
+        public frontColor = new BABYLON.Color3(1, 1, 1);
+        public backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
+        public showBackLines = true;
+        public renderList = new BABYLON.SmartArray(32);
+
+        private _scene: Scene;
+        private _colorShader: ShaderMaterial;
+        private _vb: VertexBuffer;
+        private _ib: WebGLBuffer;
+
+        constructor(scene: Scene) {
+
+            this._scene = scene;
+            this._colorShader = new ShaderMaterial("colorShader", scene, "color",
+                {
+                    attributes: ["position"],
+                    uniforms: ["worldViewProjection", "color"]
+                });
+
+
+            var engine = this._scene.getEngine();
+            var boxdata = BABYLON.VertexData.CreateBox(1.0);
+            this._vb = new BABYLON.VertexBuffer(null, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false, engine);
+            this._ib = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
+        }
+
+        public reset(): void {
+            this.renderList.reset();
+        }
+
+        public render(): void {
+            if (this.renderList.length == 0 || !this._colorShader.isReady()) {
+                return;
+            }
+
+            var engine = this._scene.getEngine();
+            engine.setDepthWrite(false);
+            this._colorShader._preBind();
+            for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
+                var mesh = this.renderList.data[boundingBoxIndex];
+                var boundingBox = mesh.getBoundingInfo().boundingBox;
+                var min = boundingBox.minimum;
+                var max = boundingBox.maximum;
+                var diff = max.subtract(min);
+                var median = min.add(diff.scale(0.5));
+
+                var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
+                    .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
+                    .multiply(mesh.getWorldMatrix());
+
+                // VBOs
+                engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
+
+                if (this.showBackLines) {
+                    // Back
+                    engine.setDepthFunctionToGreaterOrEqual();
+                    this._colorShader.setColor3("color", this.backColor);
+                    this._colorShader.bind(worldMatrix, mesh);
+
+                    // Draw order
+                    engine.draw(false, 0, 24);
+                }
+
+                // Front
+                engine.setDepthFunctionToLess();
+                this._colorShader.setColor3("color", this.frontColor);
+                this._colorShader.bind(worldMatrix, mesh);
+
+                // Draw order
+                engine.draw(false, 0, 24);
+            }
+            this._colorShader.unbind();
+            engine.setDepthFunctionToLessOrEqual();
+            engine.setDepthWrite(true);
+        }
+
+        public dispose(): void {
+            this._colorShader.dispose();
+            this._vb.dispose();
+            this._scene.getEngine()._releaseBuffer(this._ib);
+        }
+    }
+} 

+ 86 - 87
Babylon/Rendering/babylon.renderingGroup.js

@@ -1,105 +1,104 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.RenderingGroup = function (index, scene) {
-        this.index = index;
-        this._scene = scene;
-
-        this._opaqueSubMeshes = new BABYLON.SmartArray(256);
-        this._transparentSubMeshes = new BABYLON.SmartArray(256);
-        this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
-    };
-
-    // Methods
-    BABYLON.RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
-        if (customRenderFunction) {
-            customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
-            return true;
-        }
-
-        if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes === 0) {
-            return false;
+var BABYLON;
+(function (BABYLON) {
+    var RenderingGroup = (function () {
+        //ANY
+        function RenderingGroup(index, scene) {
+            this.index = index;
+            this._opaqueSubMeshes = new BABYLON.SmartArray(256);
+            this._transparentSubMeshes = new BABYLON.SmartArray(256);
+            this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
+            this._scene = scene;
         }
-        var engine = this._scene.getEngine();
-        // Opaque
-        var subIndex;
-        var submesh;
-        for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
-            submesh = this._opaqueSubMeshes.data[subIndex];
-            this._activeVertices += submesh.verticesCount;
+        RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
+            if (customRenderFunction) {
+                customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
+                return true;
+            }
 
-            submesh.render();
-        }
+            if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
+                return false;
+            }
+            var engine = this._scene.getEngine();
 
-        // Alpha test
-        engine.setAlphaTesting(true);
-        for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
-            submesh = this._alphaTestSubMeshes.data[subIndex];
-            this._activeVertices += submesh.verticesCount;
+            // Opaque
+            var subIndex;
+            var submesh;
+            for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
+                submesh = this._opaqueSubMeshes.data[subIndex];
+                this._activeVertices += submesh.verticesCount;
 
-            submesh.render();
-        }
-        engine.setAlphaTesting(false);
+                submesh.render();
+            }
 
-        if (beforeTransparents) {
-            beforeTransparents();
-        }
+            // Alpha test
+            engine.setAlphaTesting(true);
+            for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
+                submesh = this._alphaTestSubMeshes.data[subIndex];
+                this._activeVertices += submesh.verticesCount;
 
-        // Transparent
-        if (this._transparentSubMeshes.length) {
-            // Sorting
-            for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
-                submesh = this._transparentSubMeshes.data[subIndex];
-                submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
+                submesh.render();
             }
+            engine.setAlphaTesting(false);
 
-            var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
+            if (beforeTransparents) {
+                beforeTransparents();
+            }
 
-            sortedArray.sort(function (a, b) {
-                if (a._distanceToCamera < b._distanceToCamera) {
-                    return 1;
-                }
-                if (a._distanceToCamera > b._distanceToCamera) {
-                    return -1;
+            // Transparent
+            if (this._transparentSubMeshes.length) {
+                for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
+                    submesh = this._transparentSubMeshes.data[subIndex];
+                    submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
                 }
 
-                return 0;
-            });
+                var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
 
-            // Rendering
-            engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
-            for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
-                submesh = sortedArray[subIndex];
-                this._activeVertices += submesh.verticesCount;
+                sortedArray.sort(function (a, b) {
+                    if (a._distanceToCamera < b._distanceToCamera) {
+                        return 1;
+                    }
+                    if (a._distanceToCamera > b._distanceToCamera) {
+                        return -1;
+                    }
 
-                submesh.render();
-            }
-            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
-        }
-        return true;
-    };
+                    return 0;
+                });
 
+                // Rendering
+                engine.setAlphaMode(2); //ANY BABYLON.Engine.ALPHA_COMBINE);
+                for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
+                    submesh = sortedArray[subIndex];
+                    this._activeVertices += submesh.verticesCount;
 
-    BABYLON.RenderingGroup.prototype.prepare = function () {
-        this._opaqueSubMeshes.reset();
-        this._transparentSubMeshes.reset();
-        this._alphaTestSubMeshes.reset();
-    };
+                    submesh.render();
+                }
+                engine.setAlphaMode(0); //ANY BABYLON.Engine.ALPHA_DISABLE);
+            }
+            return true;
+        };
 
-    BABYLON.RenderingGroup.prototype.dispatch = function (subMesh) {
-        var material = subMesh.getMaterial();
-        var mesh = subMesh.getMesh();
+        RenderingGroup.prototype.prepare = function () {
+            this._opaqueSubMeshes.reset();
+            this._transparentSubMeshes.reset();
+            this._alphaTestSubMeshes.reset();
+        };
 
-        if (material.needAlphaBlending() || mesh.visibility < 1.0) { // Transparent
-            if (material.alpha > 0 || mesh.visibility < 1.0) {
-                this._transparentSubMeshes.push(subMesh);
+        RenderingGroup.prototype.dispatch = function (subMesh) {
+            var material = subMesh.getMaterial();
+            var mesh = subMesh.getMesh();
+
+            if (material.needAlphaBlending() || mesh.visibility < 1.0) {
+                if (material.alpha > 0 || mesh.visibility < 1.0) {
+                    this._transparentSubMeshes.push(subMesh);
+                }
+            } else if (material.needAlphaTesting()) {
+                this._alphaTestSubMeshes.push(subMesh);
+            } else {
+                this._opaqueSubMeshes.push(subMesh); // Opaque
             }
-        } else if (material.needAlphaTesting()) { // Alpha test
-            this._alphaTestSubMeshes.push(subMesh);
-        } else {
-            this._opaqueSubMeshes.push(subMesh); // Opaque
-        }
-    };
-})();
+        };
+        return RenderingGroup;
+    })();
+    BABYLON.RenderingGroup = RenderingGroup;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.renderingGroup.js.map

+ 105 - 0
Babylon/Rendering/babylon.renderingGroup.ts

@@ -0,0 +1,105 @@
+module BABYLON {
+    export class RenderingGroup {
+        private _scene; //ANY
+        private _opaqueSubMeshes = new BABYLON.SmartArray(256);
+        private _transparentSubMeshes = new BABYLON.SmartArray(256);
+        private _alphaTestSubMeshes = new BABYLON.SmartArray(256);
+        private _activeVertices: number;
+
+        //ANY
+        constructor(public index: number, scene) {
+            this._scene = scene;
+        }
+
+        public render(customRenderFunction: (opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray, beforeTransparents: () => void) => void,
+                      beforeTransparents): boolean {
+            if (customRenderFunction) {
+                customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
+                return true;
+            }
+
+            if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
+                return false;
+            }
+            var engine = this._scene.getEngine();
+            // Opaque
+            var subIndex;
+            var submesh;
+            for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
+                submesh = this._opaqueSubMeshes.data[subIndex];
+                this._activeVertices += submesh.verticesCount;
+
+                submesh.render();
+            }
+
+            // Alpha test
+            engine.setAlphaTesting(true);
+            for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
+                submesh = this._alphaTestSubMeshes.data[subIndex];
+                this._activeVertices += submesh.verticesCount;
+
+                submesh.render();
+            }
+            engine.setAlphaTesting(false);
+
+            if (beforeTransparents) {
+                beforeTransparents();
+            }
+
+            // Transparent
+            if (this._transparentSubMeshes.length) {
+                // Sorting
+                for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
+                    submesh = this._transparentSubMeshes.data[subIndex];
+                    submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
+                }
+
+                var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
+
+                sortedArray.sort((a, b) => {
+                    if (a._distanceToCamera < b._distanceToCamera) {
+                        return 1;
+                    }
+                    if (a._distanceToCamera > b._distanceToCamera) {
+                        return -1;
+                    }
+
+                    return 0;
+                });
+
+                // Rendering
+                engine.setAlphaMode(2); //ANY BABYLON.Engine.ALPHA_COMBINE);
+                for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
+                    submesh = sortedArray[subIndex];
+                    this._activeVertices += submesh.verticesCount;
+
+                    submesh.render();
+                }
+                engine.setAlphaMode(0); //ANY BABYLON.Engine.ALPHA_DISABLE);
+            }
+            return true;
+        }
+
+
+        public prepare(): void {
+            this._opaqueSubMeshes.reset();
+            this._transparentSubMeshes.reset();
+            this._alphaTestSubMeshes.reset();
+        }
+
+        public dispatch(subMesh: SubMesh): void {
+            var material = subMesh.getMaterial();
+            var mesh = subMesh.getMesh();
+
+            if (material.needAlphaBlending() || mesh.visibility < 1.0) { // Transparent
+                if (material.alpha > 0 || mesh.visibility < 1.0) {
+                    this._transparentSubMeshes.push(subMesh);
+                }
+            } else if (material.needAlphaTesting()) { // Alpha test
+                this._alphaTestSubMeshes.push(subMesh);
+            } else {
+                this._opaqueSubMeshes.push(subMesh); // Opaque
+            }
+        }
+    }
+} 

+ 86 - 88
Babylon/Rendering/babylon.renderingManager.js

@@ -1,108 +1,106 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.RenderingManager = function (scene) {
-        this._scene = scene;
-        this._renderingGroups = [];
-    };
-
-    // Methods
-    BABYLON.RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
-        if (this._scene._activeParticleSystems.length === 0) {
-            return;
+var BABYLON;
+(function (BABYLON) {
+    var RenderingManager = (function () {
+        //ANY
+        function RenderingManager(scene) {
+            this._renderingGroups = new Array();
+            this._scene = scene;
         }
-
-        // Particles
-        var beforeParticlesDate = new Date();
-        for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
-            var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
-
-            if (particleSystem.renderingGroupId !== index) {
-                continue;
-            }
-
-            this._clearDepthBuffer();
-
-            if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
-                this._scene._activeParticles += particleSystem.render();
+        RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
+            if (this._scene._activeParticleSystems.length === 0) {
+                return;
             }
-        }
-        this._scene._particlesDuration += new Date() - beforeParticlesDate;
-    };
 
-    BABYLON.RenderingManager.prototype._renderSprites = function (index) {
-        if (this._scene.spriteManagers.length === 0) {
-            return;
-        }
+            // Particles
+            var beforeParticlesDate = new Date().getTime();
+            for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
+                var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
 
-        // Sprites       
-        var beforeSpritessDate = new Date();
-        for (var id = 0; id < this._scene.spriteManagers.length; id++) {
-            var spriteManager = this._scene.spriteManagers[id];
+                if (particleSystem.renderingGroupId !== index) {
+                    continue;
+                }
 
-            if (spriteManager.renderingGroupId === index) {
                 this._clearDepthBuffer();
-                spriteManager.render();
+
+                if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
+                    this._scene._activeParticles += particleSystem.render();
+                }
             }
-        }
-        this._scene._spritesDuration += new Date() - beforeSpritessDate;
-    };
+            this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
+        };
 
-    BABYLON.RenderingManager.prototype._clearDepthBuffer = function () {
-        if (this._depthBufferAlreadyCleaned) {
-            return;
-        }
+        RenderingManager.prototype._renderSprites = function (index) {
+            if (this._scene.spriteManagers.length === 0) {
+                return;
+            }
 
-        this._scene.getEngine().clear(0, false, true);
-        this._depthBufferAlreadyCleaned = true;
-    };
+            // Sprites
+            var beforeSpritessDate = new Date().getTime();
+            for (var id = 0; id < this._scene.spriteManagers.length; id++) {
+                var spriteManager = this._scene.spriteManagers[id];
 
-    BABYLON.RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
-        var that = this;
+                if (spriteManager.renderingGroupId === index) {
+                    this._clearDepthBuffer();
+                    spriteManager.render();
+                }
+            }
+            this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
+        };
 
-        for (var index = 0 ; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
-            this._depthBufferAlreadyCleaned = index == 0;
-            var renderingGroup = this._renderingGroups[index];
+        RenderingManager.prototype._clearDepthBuffer = function () {
+            if (this._depthBufferAlreadyCleaned) {
+                return;
+            }
 
-            if (renderingGroup) {
-                this._clearDepthBuffer();
-                if (!renderingGroup.render(customRenderFunction, function () {
-                    if (renderSprites) {
-                        that._renderSprites(index);
+            this._scene.getEngine().clear(0, false, true);
+            this._depthBufferAlreadyCleaned = true;
+        };
+
+        RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
+            var _this = this;
+            for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
+                this._depthBufferAlreadyCleaned = index == 0;
+                var renderingGroup = this._renderingGroups[index];
+
+                if (renderingGroup) {
+                    this._clearDepthBuffer();
+                    if (!renderingGroup.render(customRenderFunction, function () {
+                        if (renderSprites) {
+                            _this._renderSprites(index);
+                        }
+                    })) {
+                        this._renderingGroups.splice(index, 1);
+                    }
+                } else if (renderSprites) {
+                    this._renderSprites(index);
                 }
-                })) {
-                    this._renderingGroups.splice(index, 1);
+
+                if (renderParticles) {
+                    this._renderParticles(index, activeMeshes);
                 }
-            } else if (renderSprites) {
-                this._renderSprites(index);
             }
+        };
 
-            if (renderParticles) {
-                this._renderParticles(index, activeMeshes);
+        RenderingManager.prototype.reset = function () {
+            for (var index in this._renderingGroups) {
+                var renderingGroup = this._renderingGroups[index];
+                renderingGroup.prepare();
             }
-        }
-    };
-
-    BABYLON.RenderingManager.prototype.reset = function () {
-        for (var index in this._renderingGroups) {
-            var renderingGroup = this._renderingGroups[index];
-            renderingGroup.prepare();
-        }
-    };
+        };
 
-    BABYLON.RenderingManager.prototype.dispatch = function (subMesh) {
-        var mesh = subMesh.getMesh();
-        var renderingGroupId = mesh.renderingGroupId || 0;
+        RenderingManager.prototype.dispatch = function (subMesh) {
+            var mesh = subMesh.getMesh();
+            var renderingGroupId = mesh.renderingGroupId || 0;
 
-        if (!this._renderingGroups[renderingGroupId]) {
-            this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
-        }
-
-        this._renderingGroups[renderingGroupId].dispatch(subMesh);
-    };
+            if (!this._renderingGroups[renderingGroupId]) {
+                this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
+            }
 
-    // Statics
-    BABYLON.RenderingManager.MAX_RENDERINGGROUPS = 4;
-})();
+            this._renderingGroups[renderingGroupId].dispatch(subMesh);
+        };
+        RenderingManager.MAX_RENDERINGGROUPS = 4;
+        return RenderingManager;
+    })();
+    BABYLON.RenderingManager = RenderingManager;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.renderingManager.js.map

+ 108 - 0
Babylon/Rendering/babylon.renderingManager.ts

@@ -0,0 +1,108 @@
+module BABYLON {
+    export class RenderingManager {
+        public static MAX_RENDERINGGROUPS = 4;
+
+        private _scene; //ANY
+        private _renderingGroups = new Array<RenderingGroup>();
+        private _depthBufferAlreadyCleaned: boolean;
+
+        //ANY
+        constructor(scene) {
+            this._scene = scene;
+        }
+
+        private _renderParticles(index: number, activeMeshes: Mesh[]): void {
+            if (this._scene._activeParticleSystems.length === 0) {
+                return;
+            }
+
+            // Particles
+            var beforeParticlesDate = new Date().getTime();
+            for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
+                var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
+
+                if (particleSystem.renderingGroupId !== index) {
+                    continue;
+                }
+
+                this._clearDepthBuffer();
+
+                if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
+                    this._scene._activeParticles += particleSystem.render();
+                }
+            }
+            this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
+        }
+
+        private _renderSprites(index: number): void {
+            if (this._scene.spriteManagers.length === 0) {
+                return;
+            }
+
+            // Sprites       
+            var beforeSpritessDate = new Date().getTime();
+            for (var id = 0; id < this._scene.spriteManagers.length; id++) {
+                var spriteManager = this._scene.spriteManagers[id];
+
+                if (spriteManager.renderingGroupId === index) {
+                    this._clearDepthBuffer();
+                    spriteManager.render();
+                }
+            }
+            this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
+        }
+
+        private _clearDepthBuffer(): void {
+            if (this._depthBufferAlreadyCleaned) {
+                return;
+            }
+
+            this._scene.getEngine().clear(0, false, true);
+            this._depthBufferAlreadyCleaned = true;
+        }
+
+        public render(customRenderFunction: (opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray, beforeTransparents: () => void) => void,
+            activeMeshes: Mesh[], renderParticles: boolean, renderSprites: boolean): void {
+            for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
+                this._depthBufferAlreadyCleaned = index == 0;
+                var renderingGroup = this._renderingGroups[index];
+
+                if (renderingGroup) {
+                    this._clearDepthBuffer();
+                    if (!renderingGroup.render(customRenderFunction, () => {
+                        if (renderSprites) {
+                            this._renderSprites(index);
+                        }
+                    })) {
+                        this._renderingGroups.splice(index, 1);
+                    }
+                } else if (renderSprites) {
+                    this._renderSprites(index);
+                }
+
+                if (renderParticles) {
+                    this._renderParticles(index, activeMeshes);
+                }
+            }
+        }
+
+        public reset(): void {
+            for (var index in this._renderingGroups) {
+                var renderingGroup = this._renderingGroups[index];
+                renderingGroup.prepare();
+            }
+        }
+
+        public dispatch(subMesh: SubMesh): void {
+            var mesh = subMesh.getMesh();
+            var renderingGroupId = mesh.renderingGroupId || 0;
+
+            if (!this._renderingGroups[renderingGroupId]) {
+                this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
+            }
+
+            this._renderingGroups[renderingGroupId].dispatch(subMesh);
+        }
+
+    }
+} 

+ 63 - 69
Babylon/Sprites/babylon.sprite.js

@@ -1,81 +1,75 @@
-"use strict";
+var BABYLON;
+(function (BABYLON) {
+    var Sprite = (function () {
+        function Sprite(name, manager) {
+            this.name = name;
+            this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
+            this.size = 1.0;
+            this.angle = 0;
+            this.cellIndex = 0;
+            this.invertU = 0;
+            this.invertV = 0;
+            this._animationStarted = false;
+            this._loopAnimation = false;
+            this._fromIndex = 0;
+            this._toIndex = 0;
+            this._delay = 0;
+            this._direction = 1;
+            this._frameCount = 0;
+            this._time = 0;
+            this._manager = manager;
 
-var BABYLON = BABYLON || {};
+            this._manager.sprites.push(this);
 
-(function () {
-    BABYLON.Sprite = function (name, manager) {
-        this.name = name;
-        this._manager = manager;
-
-        this._manager.sprites.push(this);
-
-        this.position = BABYLON.Vector3.Zero();
-        this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
-
-        this._frameCount = 0;
-    };
-
-    // Members
-    BABYLON.Sprite.prototype.position = null;
-    BABYLON.Sprite.prototype.size = 1.0;
-    BABYLON.Sprite.prototype.angle = 0;
-    BABYLON.Sprite.prototype.cellIndex = 0;
-    BABYLON.Sprite.prototype.invertU = 0;
-    BABYLON.Sprite.prototype.invertV = 0;
-    BABYLON.Sprite.prototype.disposeWhenFinishedAnimating = false;
-
-    BABYLON.Sprite.prototype._animationStarted = false;
-    BABYLON.Sprite.prototype._loopAnimation = false;
-    BABYLON.Sprite.prototype._fromIndex = false;
-    BABYLON.Sprite.prototype._toIndex = false;
-    BABYLON.Sprite.prototype._delay = false;
-    BABYLON.Sprite.prototype._direction = 1;
-
-    // Methods
-    BABYLON.Sprite.prototype.playAnimation = function (from, to, loop, delay) {
-        this._fromIndex = from;
-        this._toIndex = to;
-        this._loopAnimation = loop;
-        this._delay = delay;
-        this._animationStarted = true;
+            this.position = BABYLON.Vector3.Zero();
+        }
+        Sprite.prototype.playAnimation = function (from, to, loop, delay) {
+            this._fromIndex = from;
+            this._toIndex = to;
+            this._loopAnimation = loop;
+            this._delay = delay;
+            this._animationStarted = true;
 
-        this._direction = from < to ? 1 : -1;
+            this._direction = from < to ? 1 : -1;
 
-        this.cellIndex = from;
-        this._time = 0;
-    };
+            this.cellIndex = from;
+            this._time = 0;
+        };
 
-    BABYLON.Sprite.prototype.stopAnimation = function () {
-        this._animationStarted = false;
-    };
+        Sprite.prototype.stopAnimation = function () {
+            this._animationStarted = false;
+        };
 
-    BABYLON.Sprite.prototype._animate = function (deltaTime) {
-        if (!this._animationStarted)
-            return;
+        Sprite.prototype._animate = function (deltaTime) {
+            if (!this._animationStarted)
+                return;
 
-        this._time += deltaTime;
-        if (this._time > this._delay) {
-            this._time = this._time % this._delay;
-            this.cellIndex += this._direction;
-            if (this.cellIndex == this._toIndex) {
-                if (this._loopAnimation) {
-                    this.cellIndex = this._fromIndex;
-                } else {
-                    this._animationStarted = false;
-                    if (this.disposeWhenFinishedAnimating) {
-                        this.dispose();
+            this._time += deltaTime;
+            if (this._time > this._delay) {
+                this._time = this._time % this._delay;
+                this.cellIndex += this._direction;
+                if (this.cellIndex == this._toIndex) {
+                    if (this._loopAnimation) {
+                        this.cellIndex = this._fromIndex;
+                    } else {
+                        this._animationStarted = false;
+                        if (this.disposeWhenFinishedAnimating) {
+                            this.dispose();
+                        }
                     }
                 }
             }
-        }
-    };
+        };
 
-    BABYLON.Sprite.prototype.dispose = function () {
-        for (var i = 0; i < this._manager.sprites.length; i++) {
-            if (this._manager.sprites[i] == this) {
-                this._manager.sprites.splice(i, 1);
+        Sprite.prototype.dispose = function () {
+            for (var i = 0; i < this._manager.sprites.length; i++) {
+                if (this._manager.sprites[i] == this) {
+                    this._manager.sprites.splice(i, 1);
+                }
             }
-        }
-    };
-
-})();
+        };
+        return Sprite;
+    })();
+    BABYLON.Sprite = Sprite;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.sprite.js.map

+ 76 - 0
Babylon/Sprites/babylon.sprite.ts

@@ -0,0 +1,76 @@
+module BABYLON {
+    export class Sprite {
+        public position: Vector3;
+        public color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
+        public size = 1.0;
+        public angle = 0;
+        public cellIndex = 0;
+        public invertU = 0;
+        public invertV = 0;
+        public disposeWhenFinishedAnimating: () => void;
+
+        private _animationStarted = false;
+        private _loopAnimation = false;
+        private _fromIndex = 0;
+        private _toIndex = 0;
+        private _delay = 0;
+        private _direction = 1;
+        private _frameCount = 0;
+        private _manager: SpriteManager;
+        private _time = 0;
+
+        constructor(public name: string, manager: SpriteManager) {
+            this._manager = manager;
+
+            this._manager.sprites.push(this);
+
+            this.position = BABYLON.Vector3.Zero();
+        }
+
+        public playAnimation(from: number, to: number, loop: boolean, delay: number): void {
+            this._fromIndex = from;
+            this._toIndex = to;
+            this._loopAnimation = loop;
+            this._delay = delay;
+            this._animationStarted = true;
+
+            this._direction = from < to ? 1 : -1;
+
+            this.cellIndex = from;
+            this._time = 0;
+        }
+
+        public stopAnimation(): void {
+            this._animationStarted = false;
+        }
+
+        public _animate(deltaTime: number): void {
+            if (!this._animationStarted)
+                return;
+
+            this._time += deltaTime;
+            if (this._time > this._delay) {
+                this._time = this._time % this._delay;
+                this.cellIndex += this._direction;
+                if (this.cellIndex == this._toIndex) {
+                    if (this._loopAnimation) {
+                        this.cellIndex = this._fromIndex;
+                    } else {
+                        this._animationStarted = false;
+                        if (this.disposeWhenFinishedAnimating) {
+                            this.dispose();
+                        }
+                    }
+                }
+            }
+        }
+
+        public dispose(): void {
+            for (var i = 0; i < this._manager.sprites.length; i++) {
+                if (this._manager.sprites[i] == this) {
+                    this._manager.sprites.splice(i, 1);
+                }
+            }
+        }
+    }
+} 

+ 165 - 173
Babylon/Sprites/babylon.spriteManager.js

@@ -1,182 +1,174 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {   
-    BABYLON.SpriteManager = function (name, imgUrl, capacity, cellSize, scene, epsilon) {
-        this.name = name;
-        this._capacity = capacity;
-        this.cellSize = cellSize;
-        this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
-        this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
-        this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
-        this._epsilon = epsilon === undefined ? 0.01 : epsilon;
-
-        this._scene = scene;
-        this._scene.spriteManagers.push(this);
-        
-        // VBO
-        this._vertexDeclaration = [3, 4, 4, 4];
-        this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
-        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;
+var BABYLON;
+(function (BABYLON) {
+    var SpriteManager = (function () {
+        //ANY
+        function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
+            this.name = name;
+            this.cellSize = cellSize;
+            this.sprites = new Array();
+            this.renderingGroupId = 0;
+            this._vertexDeclaration = [3, 4, 4, 4];
+            this._vertexStrideSize = 15 * 4;
+            this._capacity = capacity;
+            this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
+            this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._epsilon = epsilon === undefined ? 0.01 : epsilon;
+
+            this._scene = scene;
+            this._scene.spriteManagers.push(this);
+
+            // VBO
+            this._vertexDeclaration = [3, 4, 4, 4];
+            this._vertexStrideSize = 15 * 4;
+            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);
+
+            // Effects
+            this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
+
+            this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
         }
+        SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
+            var arrayOffset = index * 15;
+
+            if (offsetX == 0)
+                offsetX = this._epsilon;
+            else if (offsetX == 1)
+                offsetX = 1 - this._epsilon;
+
+            if (offsetY == 0)
+                offsetY = this._epsilon;
+            else if (offsetY == 1)
+                offsetY = 1 - this._epsilon;
+
+            this._vertices[arrayOffset] = sprite.position.x;
+            this._vertices[arrayOffset + 1] = sprite.position.y;
+            this._vertices[arrayOffset + 2] = sprite.position.z;
+            this._vertices[arrayOffset + 3] = sprite.angle;
+            this._vertices[arrayOffset + 4] = sprite.size;
+            this._vertices[arrayOffset + 5] = offsetX;
+            this._vertices[arrayOffset + 6] = offsetY;
+            this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
+            this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
+            var offset = (sprite.cellIndex / rowSize) >> 0;
+            this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
+            this._vertices[arrayOffset + 10] = offset;
+
+            // Color
+            this._vertices[arrayOffset + 11] = sprite.color.r;
+            this._vertices[arrayOffset + 12] = sprite.color.g;
+            this._vertices[arrayOffset + 13] = sprite.color.b;
+            this._vertices[arrayOffset + 14] = sprite.color.a;
+        };
+
+        SpriteManager.prototype.render = function () {
+            // Check
+            if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
+                return;
+
+            var engine = this._scene.getEngine();
+            var baseSize = this._spriteTexture.getBaseSize();
+
+            // Sprites
+            var deltaTime = BABYLON.Tools.GetDeltaTime();
+            var max = Math.min(this._capacity, this.sprites.length);
+            var rowSize = baseSize.width / this.cellSize;
+
+            var offset = 0;
+            for (var index = 0; index < max; index++) {
+                var sprite = this.sprites[index];
+                if (!sprite) {
+                    continue;
+                }
+
+                sprite._animate(deltaTime);
+
+                this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
+                this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
+                this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
+                this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
+            }
+            engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
+
+            // Render
+            var effect = this._effectBase;
 
-        this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
-        this._vertices = new Float32Array(capacity * this._vertexStrideSize);
-        
-        // Sprites
-        this.sprites = [];
-        
-        // Effects
-        this._effectBase = this._scene.getEngine().createEffect("sprites",
-                    ["position", "options", "cellInfo", "color"],
-                    ["view", "projection", "textureInfos", "alphaTest"],
-                    ["diffuseSampler"], "");
-        
-        this._effectFog = this._scene.getEngine().createEffect("sprites",
-                    ["position", "options", "cellInfo", "color"],
-                    ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"],
-                    ["diffuseSampler"], "#define FOG");
-    };
-    
-    // Members
-    BABYLON.SpriteManager.prototype.renderingGroupId = 0;
-    BABYLON.SpriteManager.prototype.onDispose = null;
-
-    // Methods
-    BABYLON.SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
-        var arrayOffset = index * 15;
-
-        if (offsetX == 0)
-            offsetX = this._epsilon;
-        else if (offsetX == 1)
-            offsetX = 1 - this._epsilon;
-
-        if (offsetY == 0)
-            offsetY = this._epsilon;
-        else if (offsetY == 1)
-            offsetY = 1 - this._epsilon;
-
-        this._vertices[arrayOffset] = sprite.position.x;
-        this._vertices[arrayOffset + 1] = sprite.position.y;
-        this._vertices[arrayOffset + 2] = sprite.position.z;
-        this._vertices[arrayOffset + 3] = sprite.angle;
-        this._vertices[arrayOffset + 4] = sprite.size;
-        this._vertices[arrayOffset + 5] = offsetX;
-        this._vertices[arrayOffset + 6] = offsetY;
-        this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
-        this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
-        var offset = (sprite.cellIndex / rowSize) >> 0;
-        this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
-        this._vertices[arrayOffset + 10] = offset;
-        // Color
-        this._vertices[arrayOffset + 11] = sprite.color.r;
-        this._vertices[arrayOffset + 12] = sprite.color.g;
-        this._vertices[arrayOffset + 13] = sprite.color.b;
-        this._vertices[arrayOffset + 14] = sprite.color.a;
-    };
-
-    BABYLON.SpriteManager.prototype.render = function() {
-        // Check
-        if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
-            return 0;
-
-        var engine = this._scene.getEngine();
-        var baseSize = this._spriteTexture.getBaseSize();
-
-        // Sprites
-        var deltaTime = BABYLON.Tools.GetDeltaTime();
-        var max = Math.min(this._capacity, this.sprites.length);
-        var rowSize = baseSize.width / this.cellSize;
-
-        var offset = 0;
-        for (var index = 0; index < max; index++) {
-            var sprite = this.sprites[index];
-            if (!sprite) {
-                 continue;
+            if (this._scene.fogMode !== 0) {
+                effect = this._effectFog;
             }
-            
-            sprite._animate(deltaTime);
 
-            this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
-            this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
-            this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
-            this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
-        }
-        engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
-       
-        // Render
-        var effect = this._effectBase;
+            engine.enableEffect(effect);
 
-        if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
-            effect = this._effectFog;
-        }
-        
-        engine.enableEffect(effect);
-
-        var viewMatrix = this._scene.getViewMatrix();
-        effect.setTexture("diffuseSampler", this._spriteTexture);
-        effect.setMatrix("view", viewMatrix);
-        effect.setMatrix("projection", this._scene.getProjectionMatrix());
-
-        effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
-        
-        // Fog
-        if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
-            effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
-            effect.setColor3("vFogColor", this._scene.fogColor);
-        }
+            var viewMatrix = this._scene.getViewMatrix();
+            effect.setTexture("diffuseSampler", this._spriteTexture);
+            effect.setMatrix("view", viewMatrix);
+            effect.setMatrix("projection", this._scene.getProjectionMatrix());
 
-        // VBOs
-        engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
-
-        // Draw order
-        effect.setBool("alphaTest", true);
-        engine.setColorWrite(false);
-        engine.draw(true, 0, max * 6);
-        engine.setColorWrite(true);
-        effect.setBool("alphaTest", false);
-        
-        engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
-        engine.draw(true, 0, max * 6);
-        engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
-    };
-    
-    BABYLON.SpriteManager.prototype.dispose = function () {
-        if (this._vertexBuffer) {
-            this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
-            this._vertexBuffer = null;
-        }
+            effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
 
-        if (this._indexBuffer) {
-            this._scene.getEngine()._releaseBuffer(this._indexBuffer);
-            this._indexBuffer = null;
-        }
+            // Fog
+            if (this._scene.fogMode !== 0) {
+                effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
+                effect.setColor3("vFogColor", this._scene.fogColor);
+            }
 
-        if (this._spriteTexture) {
-            this._spriteTexture.dispose();
-            this._spriteTexture = null;
-        }
+            // VBOs
+            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
+
+            // Draw order
+            effect.setBool("alphaTest", true);
+            engine.setColorWrite(false);
+            engine.draw(true, 0, max * 6);
+            engine.setColorWrite(true);
+            effect.setBool("alphaTest", false);
+
+            engine.setAlphaMode(2); //ANY BABYLON.Engine.ALPHA_COMBINE);
+            engine.draw(true, 0, max * 6);
+            engine.setAlphaMode(0); //BABYLON.Engine.ALPHA_DISABLE);
+        };
+
+        SpriteManager.prototype.dispose = function () {
+            if (this._vertexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
+                this._vertexBuffer = null;
+            }
 
-        // Remove from scene
-        var index = this._scene.spriteManagers.indexOf(this);
-        this._scene.spriteManagers.splice(index, 1);
-        
-        // Callback
-        if (this.onDispose) {
-            this.onDispose();
-        }
-    };
-    
-})();
+            if (this._indexBuffer) {
+                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
+                this._indexBuffer = null;
+            }
+
+            if (this._spriteTexture) {
+                this._spriteTexture.dispose();
+                this._spriteTexture = null;
+            }
+
+            // Remove from scene
+            var index = this._scene.spriteManagers.indexOf(this);
+            this._scene.spriteManagers.splice(index, 1);
+
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        };
+        return SpriteManager;
+    })();
+    BABYLON.SpriteManager = SpriteManager;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.spriteManager.js.map

+ 188 - 0
Babylon/Sprites/babylon.spriteManager.ts

@@ -0,0 +1,188 @@
+module BABYLON {
+    export class SpriteManager {
+        public sprites = new Array<Sprite>();
+        public renderingGroupId = 0;
+        public onDispose: () => void;
+
+        private _capacity: number;
+        private _spriteTexture; //ANY
+        private _epsilon: number;
+
+        private _scene; //ANY
+
+        private _vertexDeclaration = [3, 4, 4, 4];
+        private _vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
+        private _vertexBuffer; //ANY
+        private _indexBuffer; //ANY
+        private _vertices: Float32Array;
+        private _effectBase; //ANY
+        private _effectFog; //ANY
+
+        //ANY
+        constructor(public name: string, imgUrl: string, capacity: number, public cellSize: number, scene, epsilon?: number) {
+            this._capacity = capacity;
+            this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
+            this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
+            this._epsilon = epsilon === undefined ? 0.01 : epsilon;
+
+            this._scene = scene;
+            this._scene.spriteManagers.push(this);
+
+            // VBO
+            this._vertexDeclaration = [3, 4, 4, 4];
+            this._vertexStrideSize = 15 * 4;
+            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);
+
+            // Effects
+            this._effectBase = this._scene.getEngine().createEffect("sprites",
+                ["position", "options", "cellInfo", "color"],
+                ["view", "projection", "textureInfos", "alphaTest"],
+                ["diffuseSampler"], "");
+
+            this._effectFog = this._scene.getEngine().createEffect("sprites",
+                ["position", "options", "cellInfo", "color"],
+                ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"],
+                ["diffuseSampler"], "#define FOG");
+        }
+
+        private _appendSpriteVertex(index: number, sprite: Sprite, offsetX: number, offsetY: number, rowSize: number): void {
+            var arrayOffset = index * 15;
+
+            if (offsetX == 0)
+                offsetX = this._epsilon;
+            else if (offsetX == 1)
+                offsetX = 1 - this._epsilon;
+
+            if (offsetY == 0)
+                offsetY = this._epsilon;
+            else if (offsetY == 1)
+                offsetY = 1 - this._epsilon;
+
+            this._vertices[arrayOffset] = sprite.position.x;
+            this._vertices[arrayOffset + 1] = sprite.position.y;
+            this._vertices[arrayOffset + 2] = sprite.position.z;
+            this._vertices[arrayOffset + 3] = sprite.angle;
+            this._vertices[arrayOffset + 4] = sprite.size;
+            this._vertices[arrayOffset + 5] = offsetX;
+            this._vertices[arrayOffset + 6] = offsetY;
+            this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
+            this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
+            var offset = (sprite.cellIndex / rowSize) >> 0;
+            this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
+            this._vertices[arrayOffset + 10] = offset;
+            // Color
+            this._vertices[arrayOffset + 11] = sprite.color.r;
+            this._vertices[arrayOffset + 12] = sprite.color.g;
+            this._vertices[arrayOffset + 13] = sprite.color.b;
+            this._vertices[arrayOffset + 14] = sprite.color.a;
+        }
+
+        public render(): void {
+            // Check
+            if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
+                return;
+
+            var engine = this._scene.getEngine();
+            var baseSize = this._spriteTexture.getBaseSize();
+
+            // Sprites
+            var deltaTime = BABYLON.Tools.GetDeltaTime();
+            var max = Math.min(this._capacity, this.sprites.length);
+            var rowSize = baseSize.width / this.cellSize;
+
+            var offset = 0;
+            for (var index = 0; index < max; index++) {
+                var sprite = this.sprites[index];
+                if (!sprite) {
+                    continue;
+                }
+
+                sprite._animate(deltaTime);
+
+                this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
+                this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
+                this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
+                this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
+            }
+            engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
+
+            // Render
+            var effect = this._effectBase;
+
+            if (this._scene.fogMode !== 0) { //ANY BABYLON.Scene.FOGMODE_NONE) {
+                effect = this._effectFog;
+            }
+
+            engine.enableEffect(effect);
+
+            var viewMatrix = this._scene.getViewMatrix();
+            effect.setTexture("diffuseSampler", this._spriteTexture);
+            effect.setMatrix("view", viewMatrix);
+            effect.setMatrix("projection", this._scene.getProjectionMatrix());
+
+            effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
+
+            // Fog
+            if (this._scene.fogMode !== 0) { //ANY BABYLON.Scene.FOGMODE_NONE) {
+                effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
+                effect.setColor3("vFogColor", this._scene.fogColor);
+            }
+
+            // VBOs
+            engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
+
+            // Draw order
+            effect.setBool("alphaTest", true);
+            engine.setColorWrite(false);
+            engine.draw(true, 0, max * 6);
+            engine.setColorWrite(true);
+            effect.setBool("alphaTest", false);
+
+            engine.setAlphaMode(2); //ANY BABYLON.Engine.ALPHA_COMBINE);
+            engine.draw(true, 0, max * 6);
+            engine.setAlphaMode(0); //BABYLON.Engine.ALPHA_DISABLE);
+        }
+
+        public dispose(): void {
+            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._spriteTexture) {
+                this._spriteTexture.dispose();
+                this._spriteTexture = null;
+            }
+
+            // Remove from scene
+            var index = this._scene.spriteManagers.indexOf(this);
+            this._scene.spriteManagers.splice(index, 1);
+
+            // Callback
+            if (this.onDispose) {
+                this.onDispose();
+            }
+        }
+    }
+} 

+ 91 - 120
Babylon/Tools/babylon.andOrNotEvaluator.js

@@ -1,135 +1,106 @@
-"use strict";
-
-var BABYLON = BABYLON || {};
-
-(function () {
-    BABYLON.AndOrNotEvaluator = BABYLON.AndOrNotEvaluator || {};
-
-    BABYLON.AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
-        if (!query.match(/\([^\(\)]*\)/g)) {
-            query = BABYLON.AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
-        }
-        else {
-            query = query.replace(/\([^\(\)]*\)/g, function (r) {
-                // remove parenthesis
-                r = r.slice(1, r.length - 1);
-                return BABYLON.AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
-            });
-        }
-
-        if (query === "true") {
-            return true;
-        }
-
-        if (query === "false") {
-            return false;
-        }
-
-        return BABYLON.AndOrNotEvaluator.Eval(query, evaluateCallback);
-    };
+var BABYLON;
+(function (BABYLON) {
+    (function (Internals) {
+        var AndOrNotEvaluator = (function () {
+            function AndOrNotEvaluator() {
+            }
+            AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
+                if (!query.match(/\([^\(\)]*\)/g)) {
+                    query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
+                } else {
+                    query = query.replace(/\([^\(\)]*\)/g, function (r) {
+                        // remove parenthesis
+                        r = r.slice(1, r.length - 1);
+                        return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
+                    });
+                }
 
-    BABYLON.AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
-        evaluateCallback = evaluateCallback || function (r) {
-            /*switch(r)
-            {
-                case "true":
+                if (query === "true") {
                     return true;
-                case "false":
-                case "0":
-                case "":
-                case "undefined":
-                case "null":
-                default:
-                    return false;
-            }*/
-            return r === "true" ? true : false;
-        };
-
-        var result;
-        var or = parenthesisContent.split("||");
+                }
 
-        for (var i in or) {
-            var ori = BABYLON.AndOrNotEvaluator._SimplifyNegation(or[i].trim());
-            var and = ori.split("&&");
+                if (query === "false") {
+                    return false;
+                }
 
-            if (and.length > 1) {
-                for (var j = 0; j < and.length; ++j) {
-                    var andj = BABYLON.AndOrNotEvaluator._SimplifyNegation(and[j].trim());
-                    if (andj !== "true" && andj !== "false") {
-                        if (andj[0] === "!") {
-                            result = andj.substring(1);
-                            if (evaluateCallback) {
-                                result = evaluateCallback(result);
+                return AndOrNotEvaluator.Eval(query, evaluateCallback);
+            };
+
+            AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
+                evaluateCallback = evaluateCallback || (function (r) {
+                    return r === "true" ? true : false;
+                });
+
+                var result;
+                var or = parenthesisContent.split("||");
+
+                for (var i in or) {
+                    var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
+                    var and = ori.split("&&");
+
+                    if (and.length > 1) {
+                        for (var j = 0; j < and.length; ++j) {
+                            var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
+                            if (andj !== "true" && andj !== "false") {
+                                if (andj[0] === "!") {
+                                    result = !evaluateCallback(andj.substring(1));
+                                } else {
+                                    result = evaluateCallback(andj);
+                                }
+                            } else {
+                                result = andj === "true" ? true : false;
                             }
-                            result = !result;
-                        }
-                        else {
-                            result = andj;
-                            if (evaluateCallback) {
-                                result = evaluateCallback(result);
+                            if (!result) {
+                                ori = "false";
+                                break;
                             }
                         }
                     }
-                    else {
-                        result = andj === "true" ? true : false;
-                    }
-                    if (!result) { // no need to continue since 'false && ... && ...' will always return false
-                        ori = "false";
+
+                    if (result || ori === "true") {
+                        result = true;
                         break;
                     }
-                }
-            }
-
-            if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
-                result = true;
-                break;
-            }
 
-            // result equals false (or undefined)
-
-            if (ori !== "true" && ori !== "false") {
-                if (ori[0] === "!") {
-                    result = ori.substring(1);
-                    if (evaluateCallback) {
-                        result = evaluateCallback(result);
-                    }
-                    result = !result;
-                }
-                else {
-                    result = ori;
-                    if (evaluateCallback) {
-                        result = evaluateCallback(result);
+                    // result equals false (or undefined)
+                    if (ori !== "true" && ori !== "false") {
+                        if (ori[0] === "!") {
+                            result = !evaluateCallback(ori.substring(1));
+                        } else {
+                            result = evaluateCallback(ori);
+                        }
+                    } else {
+                        result = ori === "true" ? true : false;
                     }
                 }
-            }
-            else {
-                result = ori === "true" ? true : false;
-            }
-        }
-
-        // the whole parenthesis scope is replaced by 'true' or 'false'
-        return result ? "true" : "false";
-    };
-
-    BABYLON.AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
-        booleanString = booleanString.replace(/^[\s!]+/, function (r) {
-            // remove whitespaces
-            r = r.replace(/[\s]/g, function (r) {
-                return "";
-            });
-            return r.length % 2 ? "!" : "";
-        });
 
-        booleanString = booleanString.trim();
-
-        if (booleanString === "!true") {
-            booleanString = "false";
-        }
-        else if (booleanString === "!false") {
-            booleanString = "true";
-        }
-
-        return booleanString;
-    };
+                // the whole parenthesis scope is replaced by 'true' or 'false'
+                return result ? "true" : "false";
+            };
+
+            AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
+                booleanString = booleanString.replace(/^[\s!]+/, function (r) {
+                    // remove whitespaces
+                    r = r.replace(/[\s]/g, function () {
+                        return "";
+                    });
+                    return r.length % 2 ? "!" : "";
+                });
+
+                booleanString = booleanString.trim();
+
+                if (booleanString === "!true") {
+                    booleanString = "false";
+                } else if (booleanString === "!false") {
+                    booleanString = "true";
+                }
 
-})();
+                return booleanString;
+            };
+            return AndOrNotEvaluator;
+        })();
+        Internals.AndOrNotEvaluator = AndOrNotEvaluator;
+    })(BABYLON.Internals || (BABYLON.Internals = {}));
+    var Internals = BABYLON.Internals;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.andOrNotEvaluator.js.map

+ 102 - 0
Babylon/Tools/babylon.andOrNotEvaluator.ts

@@ -0,0 +1,102 @@
+module BABYLON.Internals {
+    export class AndOrNotEvaluator {
+        public static Eval(query: string, evaluateCallback: (val) => boolean): boolean {
+            if (!query.match(/\([^\(\)]*\)/g)) {
+                query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
+            }
+            else {
+                query = query.replace(/\([^\(\)]*\)/g, r => {
+                    // remove parenthesis
+                    r = r.slice(1, r.length - 1);
+                    return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
+                });
+            }
+
+            if (query === "true") {
+                return true;
+            }
+
+            if (query === "false") {
+                return false;
+            }
+
+            return AndOrNotEvaluator.Eval(query, evaluateCallback);
+        }
+
+        private static _HandleParenthesisContent(parenthesisContent: string, evaluateCallback: (val) => boolean): string {
+            evaluateCallback = evaluateCallback || ((r) => {
+                return r === "true" ? true : false;
+            });
+
+            var result;
+            var or = parenthesisContent.split("||");
+
+            for (var i in or) {
+                var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
+                var and = ori.split("&&");
+
+                if (and.length > 1) {
+                    for (var j = 0; j < and.length; ++j) {
+                        var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
+                        if (andj !== "true" && andj !== "false") {
+                            if (andj[0] === "!") {
+                                result = !evaluateCallback(andj.substring(1));
+                            }
+                            else {
+                                result = evaluateCallback(andj);
+                            }
+                        }
+                        else {
+                            result = andj === "true" ? true : false;
+                        }
+                        if (!result) { // no need to continue since 'false && ... && ...' will always return false
+                            ori = "false";
+                            break;
+                        }
+                    }
+                }
+
+                if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
+                    result = true;
+                    break;
+                }
+
+                // result equals false (or undefined)
+
+                if (ori !== "true" && ori !== "false") {
+                    if (ori[0] === "!") {
+                        result = !evaluateCallback(ori.substring(1));
+                    }
+                    else {
+                        result = evaluateCallback(ori);
+                    }
+                }
+                else {
+                    result = ori === "true" ? true : false;
+                }
+            }
+
+            // the whole parenthesis scope is replaced by 'true' or 'false'
+            return result ? "true" : "false";
+        }
+
+        private static _SimplifyNegation(booleanString: string): string {
+            booleanString = booleanString.replace(/^[\s!]+/, r => {
+                // remove whitespaces
+                r = r.replace(/[\s]/g, () => "");
+                return r.length % 2 ? "!" : "";
+            });
+
+            booleanString = booleanString.trim();
+
+            if (booleanString === "!true") {
+                booleanString = "false";
+            }
+            else if (booleanString === "!false") {
+                booleanString = "true";
+            }
+
+            return booleanString;
+        }
+    }
+} 

+ 0 - 3
Babylon/Tools/babylon.database.js

@@ -264,7 +264,6 @@ var BABYLON = BABYLON || {};
                             // Put the blob into the dabase
                             var addRequest = transaction.objectStore("textures").put(newTexture);
                             addRequest.onsuccess = function (event) {
-                                console.log("");
                             };
                             addRequest.onerror = function (event) {
                                 generateBlobUrl();
@@ -389,7 +388,6 @@ var BABYLON = BABYLON || {};
                 // Put the scene into the database
                 var addRequest = transaction.objectStore("versions").put(newVersion);
                 addRequest.onsuccess = function (event) {
-                    console.log("");
                 };
                 addRequest.onerror = function (event) {
                     console.log("Error in DB add version request in BABYLON.Database.");
@@ -507,7 +505,6 @@ var BABYLON = BABYLON || {};
                             // Put the scene into the database
                             var addRequest = transaction.objectStore("scenes").put(newScene);
                             addRequest.onsuccess = function (event) {
-                                console.log("");
                             };
                             addRequest.onerror = function (event) {
                                 console.log("Error in DB add scene request in BABYLON.Database.");

+ 81 - 81
Babylon/Tools/babylon.tags.js

@@ -1,101 +1,101 @@
-"use strict";
+var BABYLON;
+(function (BABYLON) {
+    var Tags = (function () {
+        function Tags() {
+        }
+        Tags.EnableFor = function (obj) {
+            obj._tags = obj._tags || {};
 
-var BABYLON = BABYLON || {};
+            obj.hasTags = function () {
+                return Tags.HasTags(obj);
+            };
 
-(function () {
-    BABYLON.Tags = BABYLON.Tags || {};
+            obj.addTags = function (tagsString) {
+                return Tags.AddTagsTo(obj, tagsString);
+            };
 
-    BABYLON.Tags.EnableFor = function (obj) {
-        obj._tags = obj._tags || {};
+            obj.removeTags = function (tagsString) {
+                return Tags.RemoveTagsFrom(obj, tagsString);
+            };
 
-        obj.hasTags = function () {
-            return BABYLON.Tags.HasTags(obj);
+            obj.matchesTagsQuery = function (tagsQuery) {
+                return Tags.MatchesQuery(obj, tagsQuery);
+            };
         };
 
-        obj.addTags = function (tagsString) {
-            return BABYLON.Tags.AddTagsTo(obj, tagsString);
+        Tags.DisableFor = function (obj) {
+            delete obj._tags;
+            delete obj.hasTags;
+            delete obj.addTags;
+            delete obj.removeTags;
+            delete obj.matchesTagsQuery;
         };
 
-        obj.removeTags = function (tagsString) {
-            return BABYLON.Tags.RemoveTagsFrom(obj, tagsString);
+        Tags.HasTags = function (obj) {
+            if (!obj._tags) {
+                return false;
+            }
+            return !BABYLON.Tools.IsEmpty(obj._tags);
         };
 
-        obj.matchesTagsQuery = function (tagsQuery) {
-            return BABYLON.Tags.MatchesQuery(obj, tagsQuery);
+        // the tags 'true' and 'false' are reserved and cannot be used as tags
+        // a tag cannot start with '||', '&&', and '!'
+        // it cannot contain whitespaces
+        Tags.AddTagsTo = function (obj, tagsString) {
+            if (!tagsString) {
+                return;
+            }
+
+            var tags = tagsString.split(" ");
+            for (var t in tags) {
+                Tags._AddTagTo(obj, tags[t]);
+            }
         };
-    };
-
-    BABYLON.Tags.DisableFor = function (obj) {
-        delete obj._tags;
-        delete obj.hasTags;
-        delete obj.addTags;
-        delete obj.removeTags;
-        delete obj.matchesTagsQuery;
-    };
-
-    BABYLON.Tags.HasTags = function (obj) {
-        if (!obj._tags) {
-            return false;
-        }
-        return !BABYLON.Tools.IsEmpty(obj._tags);
-    };
-
-    // the tags 'true' and 'false' are reserved and cannot be used as tags
-    // a tag cannot start with '||', '&&', and '!'
-    // it cannot contain whitespaces
-    BABYLON.Tags.AddTagsTo = function (obj, tagsString) {
-        if (!tagsString) {
-            return;
-        }
-
-        var tags = tagsString.split(" ");
-        for (var t in tags) {
-            BABYLON.Tags._AddTagTo(obj, tags[t]);
-        }
-    };
-
-    BABYLON.Tags._AddTagTo = function (obj, tag) {
-        tag = tag.trim();
 
-        if (tag === "" || tag === "true" || tag === "false") {
-            return;
-        }
+        Tags._AddTagTo = function (obj, tag) {
+            tag = tag.trim();
 
-        if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
-            return;
-        }
+            if (tag === "" || tag === "true" || tag === "false") {
+                return;
+            }
 
-        BABYLON.Tags.EnableFor(obj);
-        obj._tags[tag] = true;
-    };
+            if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
+                return;
+            }
 
-    BABYLON.Tags.RemoveTagsFrom = function (obj, tagsString) {
-        if (!BABYLON.Tags.HasTags(obj)) {
-            return;
-        }
-        var tags = tagsString.split(" ");
-        for (var t in tags) {
-            BABYLON.Tags._RemoveTagFrom(obj, tags[t]);
-        }
-    };
-    
+            Tags.EnableFor(obj);
+            obj._tags[tag] = true;
+        };
 
-    BABYLON.Tags._RemoveTagFrom = function (obj, tag) {
-        delete obj._tags[tag];
-    };
+        Tags.RemoveTagsFrom = function (obj, tagsString) {
+            if (!Tags.HasTags(obj)) {
+                return;
+            }
+            var tags = tagsString.split(" ");
+            for (var t in tags) {
+                Tags._RemoveTagFrom(obj, tags[t]);
+            }
+        };
 
-    BABYLON.Tags.MatchesQuery = function (obj, tagsQuery) {
-        if (tagsQuery === undefined) {
-            return true;
-        }
+        Tags._RemoveTagFrom = function (obj, tag) {
+            delete obj._tags[tag];
+        };
 
-        if (tagsQuery === "") {
-            return BABYLON.Tags.HasTags(obj);
-        }
+        Tags.MatchesQuery = function (obj, tagsQuery) {
+            if (tagsQuery === undefined) {
+                return true;
+            }
 
-        return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
-            return BABYLON.Tags.HasTags(obj) && obj._tags[r];
-        });
-    };
+            if (tagsQuery === "") {
+                return Tags.HasTags(obj);
+            }
 
-})();
+            return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
+                return Tags.HasTags(obj) && obj._tags[r];
+            });
+        };
+        return Tags;
+    })();
+    BABYLON.Tags = Tags;
+})(BABYLON || (BABYLON = {}));
+//# sourceMappingURL=babylon.tags.js.map

+ 93 - 0
Babylon/Tools/babylon.tags.ts

@@ -0,0 +1,93 @@
+module BABYLON {
+    export class Tags {
+        public static EnableFor(obj: any): void {
+            obj._tags = obj._tags || {};
+
+            obj.hasTags = () => {
+                return Tags.HasTags(obj);
+            };
+
+            obj.addTags = (tagsString) => {
+                return Tags.AddTagsTo(obj, tagsString);
+            };
+
+            obj.removeTags = (tagsString) => {
+                return Tags.RemoveTagsFrom(obj, tagsString);
+            };
+
+            obj.matchesTagsQuery = (tagsQuery) => {
+                return Tags.MatchesQuery(obj, tagsQuery);
+            };
+        }
+
+        public static DisableFor(obj: any): void {
+            delete obj._tags;
+            delete obj.hasTags;
+            delete obj.addTags;
+            delete obj.removeTags;
+            delete obj.matchesTagsQuery;
+        }
+
+        public static HasTags(obj: any): boolean {
+            if (!obj._tags) {
+                return false;
+            }
+            return !BABYLON.Tools.IsEmpty(obj._tags);
+        }
+
+        // the tags 'true' and 'false' are reserved and cannot be used as tags
+        // a tag cannot start with '||', '&&', and '!'
+        // it cannot contain whitespaces
+        public static AddTagsTo(obj: any, tagsString: string): void {
+            if (!tagsString) {
+                return;
+            }
+
+            var tags = tagsString.split(" ");
+            for (var t in tags) {
+                Tags._AddTagTo(obj, tags[t]);
+            }
+        }
+
+        public static _AddTagTo(obj: any, tag: string): void {
+            tag = tag.trim();
+
+            if (tag === "" || tag === "true" || tag === "false") {
+                return;
+            }
+
+            if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
+                return;
+            }
+
+            Tags.EnableFor(obj);
+            obj._tags[tag] = true;
+        }
+
+        public static RemoveTagsFrom(obj: any, tagsString: string) {
+            if (!Tags.HasTags(obj)) {
+                return;
+            }
+            var tags = tagsString.split(" ");
+            for (var t in tags) {
+                Tags._RemoveTagFrom(obj, tags[t]);
+            }
+        }
+
+        public static _RemoveTagFrom(obj: any, tag: string): void {
+            delete obj._tags[tag];
+        }
+
+        public static MatchesQuery(obj: any, tagsQuery: string): boolean {
+            if (tagsQuery === undefined) {
+                return true;
+            }
+
+            if (tagsQuery === "") {
+                return Tags.HasTags(obj);
+            }
+
+            return Internals.AndOrNotEvaluator.Eval(tagsQuery, r => Tags.HasTags(obj) && obj._tags[r]);
+        }
+    }
+}

+ 1 - 0
Babylon/Tools/babylon.tools.js

@@ -178,6 +178,7 @@
             return img;
         };
 
+        //ANY
         Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer) {
             var noIndexedDB = function () {
                 var request = new XMLHttpRequest();

+ 12 - 4
Babylon/Tools/babylon.tools.ts

@@ -1,9 +1,16 @@
 module BABYLON {
-    declare var window;
-    declare var document;
 
     declare var FilesTextures; //ANY
 
+    export interface IAnimatable {
+        animations: Array<Animation>;
+    }
+
+    export interface ISize {
+        width: number;
+        height: number;
+    }
+
     // FPS
     var fpsRange = 60;
     var previousFramesDuration = [];
@@ -160,7 +167,7 @@
 
 
             //ANY database to do!
-            if (database && database.enableTexturesOffline) { //} && BABYLON.Database.isUASupportingBlobStorage) {
+            if (database && database.enableTexturesOffline) { //ANY } && BABYLON.Database.isUASupportingBlobStorage) {
                 database.openAsync(loadFromIndexedDB, noIndexedDB);
             }
             else {
@@ -190,7 +197,8 @@
             return img;
         }
 
-        public static LoadFile(url: string, callback: (string) => void, progressCallBack: () => void, database, useArrayBuffer?: boolean): void {
+        //ANY
+        public static LoadFile(url: string, callback: (data: any) => void, progressCallBack?: () => void, database?, useArrayBuffer?: boolean): void {
             var noIndexedDB = () => {
                 var request = new XMLHttpRequest();
                 var loadUrl = Tools.BaseUrl + url;

File diff suppressed because it is too large
+ 936 - 953
Babylon/babylon.engine.js


File diff suppressed because it is too large
+ 1195 - 0
Babylon/babylon.engine.ts


+ 1 - 0
Babylon/babylon.mixins.js

@@ -0,0 +1 @@
+//# sourceMappingURL=babylon.mixins.js.map

+ 50 - 0
Babylon/babylon.mixins.ts

@@ -0,0 +1,50 @@
+// Mixins
+interface Window {
+    webkitRequestAnimationFrame(func: any): any;
+    mozRequestAnimationFrame(func: any): any;
+    oRequestAnimationFrame(func: any): any;
+    WebGLRenderingContext: WebGLRenderingContext;
+}
+
+interface Document {
+    exitFullscreen(): void;
+    webkitCancelFullScreen(): void;
+    mozCancelFullScreen(): void;
+    msCancelFullScreen(): void;
+    webkitIsFullScreen: boolean;
+    mozFullScreen: boolean;
+    msIsFullScreen: boolean;
+    fullscreen: boolean;
+    mozPointerLockElement: HTMLElement;
+    msPointerLockElement: HTMLElement;
+    webkitPointerLockElement: HTMLElement;
+    pointerLockElement: HTMLElement;
+}
+
+interface HTMLCanvasElement {
+    requestPointerLock(): void;
+    msRequestPointerLock(): void;
+    mozRequestPointerLock(): void;
+    webkitRequestPointerLock(): void;
+}
+
+interface WebGLTexture {
+    isReady: boolean;
+    isCube:boolean;
+    url: string;
+    noMipmap: boolean;
+    references: number;
+    generateMipMaps: boolean;
+    _baseWidth: number;
+    _baseHeight: number;
+    _width: number;
+    _height: number;
+    _workingCanvas: HTMLCanvasElement;
+    _workingContext: CanvasRenderingContext2D;
+    _framebuffer: WebGLFramebuffer;
+    _depthBuffer: WebGLRenderbuffer;
+}
+
+interface WebGLBuffer {
+    references: number;
+}

File diff suppressed because it is too large
+ 858 - 895
Babylon/babylon.scene.js


File diff suppressed because it is too large
+ 1160 - 0
Babylon/babylon.scene.ts