浏览代码

Update to typescript 2.6.1
no extra flags were enabled. strictFunctionCheck will have to wait.

Raanan Weber 7 年之前
父节点
当前提交
0c02a72dd7

+ 2 - 1
Tools/Gulp/gulpfile.js

@@ -48,7 +48,8 @@ var tsConfig = {
     noImplicitReturns: true,
     noImplicitThis: true,
     noUnusedLocals: true,
-    strictNullChecks: true
+    strictNullChecks: true,
+    strictFunctionTypes: false
 };
 var tsProject = typescript.createProject(tsConfig);
 

+ 41 - 41
Tools/Gulp/package.json

@@ -1,43 +1,43 @@
 {
-  "name": "BabylonJS",
-  "version": "3.0.0",
-  "description": "Babylon.js is a 3D engine based on webgl and javascript",
-  "main": "",
-  "repository": {
-    "url": "https://github.com/BabylonJS/Babylon.js/"
-  },
-  "readme": "https://github.com/BabylonJS/Babylon.js/edit/master/readme.md",
-  "license": "(Apache-2.0)",
-  "devDependencies": {
-    "css-loader": "^0.25.0",
-    "del": "2.2.2",
-    "exports-loader": "^0.6.3",
-    "gulp": "^3.8.11",
-    "gulp-changed-in-place": "2.0.3",
-    "gulp-clean-ts-extends": "~0.1.1",
-    "gulp-concat": "~2.5.2",
-    "gulp-content-to-variable": "^0.1.0",
-    "gulp-debug": "^3.0.0",
-    "gulp-expect-file": "^0.0.7",
-    "gulp-optimize-js": "^1.0.2",
-    "gulp-rename": "~1.2.2",
-    "gulp-replace": "~0.5.3",
-    "gulp-sass": "3.1.0",
-    "gulp-sourcemaps": "~1.9.1",
-    "gulp-typescript": "^3.2.2",
-    "gulp-uglify": "^2.1.2",
-    "gulp-util": "~3.0.4",
-    "gulp-webserver": "^0.9.1",
-    "imports-loader": "^0.7.0",
-    "merge2": "~0.3.5",
-    "minimist": "^1.2.0",
-    "run-sequence": "~1.1.0",
-    "style-loader": "^0.13.1",
-    "through2": "~0.6.5",
-    "typescript": "~2.5.3",
-    "webpack-stream": "^3.2.0"
-  },
-  "scripts": {
-    "install": "npm --prefix ../../Playground/ install ../../Playground/ && gulp typescript-compile && gulp typescript-libraries && gulp deployLocalDev"
-  }
+    "name": "BabylonJS",
+    "version": "3.0.0",
+    "description": "Babylon.js is a 3D engine based on webgl and javascript",
+    "main": "",
+    "repository": {
+        "url": "https://github.com/BabylonJS/Babylon.js/"
+    },
+    "readme": "https://github.com/BabylonJS/Babylon.js/edit/master/readme.md",
+    "license": "(Apache-2.0)",
+    "devDependencies": {
+        "css-loader": "^0.25.0",
+        "del": "2.2.2",
+        "exports-loader": "^0.6.3",
+        "gulp": "^3.8.11",
+        "gulp-changed-in-place": "2.0.3",
+        "gulp-clean-ts-extends": "~0.1.1",
+        "gulp-concat": "~2.5.2",
+        "gulp-content-to-variable": "^0.1.0",
+        "gulp-debug": "^3.0.0",
+        "gulp-expect-file": "^0.0.7",
+        "gulp-optimize-js": "^1.0.2",
+        "gulp-rename": "~1.2.2",
+        "gulp-replace": "~0.5.3",
+        "gulp-sass": "3.1.0",
+        "gulp-sourcemaps": "~1.9.1",
+        "gulp-typescript": "^3.2.2",
+        "gulp-uglify": "^2.1.2",
+        "gulp-util": "~3.0.4",
+        "gulp-webserver": "^0.9.1",
+        "imports-loader": "^0.7.0",
+        "merge2": "~0.3.5",
+        "minimist": "^1.2.0",
+        "run-sequence": "~1.1.0",
+        "style-loader": "^0.13.1",
+        "through2": "~0.6.5",
+        "typescript": "~2.6.1",
+        "webpack-stream": "^3.2.0"
+    },
+    "scripts": {
+        "install": "npm --prefix ../../Playground/ install ../../Playground/ && gulp typescript-compile && gulp typescript-libraries && gulp deployLocalDev"
+    }
 }

+ 3 - 5
src/Audio/babylon.sound.ts

@@ -19,7 +19,6 @@ module BABYLON {
         private _position: Vector3 = Vector3.Zero();
         private _localDirection: Vector3 = new Vector3(1, 0, 0);
         private _volume: number = 1;
-        private _isLoaded: boolean = false;
         private _isReadyToPlay: boolean = false;
         public isPlaying: boolean = false;
         public isPaused: boolean = false;
@@ -98,9 +97,9 @@ module BABYLON {
                     if (Array.isArray(urlOrArrayBuffer)) this._urlType = "Array";
                     if (urlOrArrayBuffer instanceof ArrayBuffer) this._urlType = "ArrayBuffer";
 
-                    var urls:string[] = [];
+                    var urls: string[] = [];
                     var codecSupportedFound = false;
- 
+
                     switch (this._urlType) {
                         case "ArrayBuffer":
                             if ((<ArrayBuffer>urlOrArrayBuffer).byteLength > 0) {
@@ -239,7 +238,6 @@ module BABYLON {
         }
 
         private _soundLoaded(audioData: ArrayBuffer) {
-            this._isLoaded = true;
             if (!Engine.audioEngine.audioContext) {
                 return;
             }
@@ -482,7 +480,7 @@ module BABYLON {
                 else if (Engine.audioEngine.audioContext && this._soundSource) {
                     var stopTime = time ? Engine.audioEngine.audioContext.currentTime + time : Engine.audioEngine.audioContext.currentTime;
                     this._soundSource.stop(stopTime);
-                    this._soundSource.onended = () => {};
+                    this._soundSource.onended = () => { };
                     if (!this.isPaused) {
                         this._startOffset = 0;
                     }

+ 1 - 6
src/Cameras/Inputs/babylon.arcRotateCameraVRDeviceOrientationInput.ts

@@ -7,7 +7,6 @@ module BABYLON {
         public gammaCorrection = 1;
 
         private _alpha = 0;
-        private _beta = 0;
         private _gamma = 0;
         private _dirty = false;
 
@@ -27,11 +26,7 @@ module BABYLON {
                 this._alpha = +evt.alpha | 0;
             }
 
-            if (evt.beta !== null) {
-                this._beta = +evt.beta | 0;
-            }
-
-            if (evt.gamma !== null) {               
+            if (evt.gamma !== null) {
                 this._gamma = +evt.gamma | 0;
             }
             this._dirty = true;

+ 2 - 3
src/Cameras/Inputs/babylon.freeCameraTouchInput.ts

@@ -4,7 +4,7 @@ module BABYLON {
 
         private _offsetX: Nullable<number> = null;
         private _offsetY: Nullable<number> = null;
-        private _pointerCount: number = 0;
+
         private _pointerPressed = new Array<number>();
         private _pointerInput: (p: PointerInfo, s: EventState) => void;
         private _observer: Nullable<Observer<PointerInfo>>;
@@ -17,7 +17,7 @@ module BABYLON {
         public touchMoveSensibility: number = 250.0;
 
         attachControl(element: HTMLElement, noPreventDefault?: boolean) {
-            var previousPosition: Nullable<{x: number, y: number}> = null;
+            var previousPosition: Nullable<{ x: number, y: number }> = null;
 
             if (this._pointerInput === undefined) {
                 this._onLostFocus = (evt) => {
@@ -112,7 +112,6 @@ module BABYLON {
                 this._pointerPressed = [];
                 this._offsetX = null;
                 this._offsetY = null;
-                this._pointerCount = 0;
             }
         }
 

+ 2 - 5
src/Collisions/babylon.collisionCoordinator.ts

@@ -115,7 +115,6 @@ module BABYLON {
 
         private _init: boolean;
         private _runningUpdated: number;
-        private _runningCollisionTask: boolean;
         private _worker: Worker;
 
         private _addUpdateMeshesList: { [n: number]: SerializedMesh; }
@@ -127,7 +126,6 @@ module BABYLON {
             this._collisionsCallbackArray = [];
             this._init = false;
             this._runningUpdated = 0;
-            this._runningCollisionTask = false;
 
             this._addUpdateMeshesList = {};
             this._addUpdateGeometriesList = {};
@@ -332,7 +330,6 @@ module BABYLON {
                     this._runningUpdated--;
                     break;
                 case WorkerTaskType.COLLIDE:
-                    this._runningCollisionTask = false;
                     var returnPayload: CollisionReplyPayload = returnData.payload;
                     if (!this._collisionsCallbackArray[returnPayload.collisionId]) return;
 
@@ -345,7 +342,7 @@ module BABYLON {
                             callback(returnPayload.collisionId, Vector3.FromArray(returnPayload.newPosition), mesh);
                         }
                     }
-                    
+
                     //cleanup
                     this._collisionsCallbackArray[returnPayload.collisionId] = null;
                     break;
@@ -408,7 +405,7 @@ module BABYLON {
             // Check all meshes
             for (var index = 0; index < this._scene.meshes.length; index++) {
                 var mesh = this._scene.meshes[index];
-                if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh &&  ((collisionMask & mesh.collisionGroup) !== 0)) {
+                if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
                     mesh._checkCollision(collider);
                 }
             }

+ 5 - 7
src/Engine/babylon.engine.ts

@@ -1453,7 +1453,7 @@
             } else {
                 this._gl.enable(this._gl.RASTERIZER_DISCARD);
             }
-        }        
+        }
 
         /**
          * stop executing a render loop function and remove it from the execution array
@@ -3003,7 +3003,7 @@
                 // fallback for when compressed file not found to try again.  For instance, etc1 does not have an alpha capable type
                 if (isKTX) {
                     this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
-                } else if ((isTGA || isDDS )&& BABYLON.Tools.UseFallbackTexture) {
+                } else if ((isTGA || isDDS) && BABYLON.Tools.UseFallbackTexture) {
                     this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
                 } else if (onError) {
                     onError();
@@ -3379,7 +3379,7 @@
             }
         }
 
-        public createRenderTargetTexture(size: number | {width: number, height: number}, options: boolean | RenderTargetCreationOptions): InternalTexture {
+        public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): InternalTexture {
             let fullOptions = new RenderTargetCreationOptions();
 
             if (options !== undefined && typeof options === "object") {
@@ -3409,8 +3409,8 @@
             var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
             this._bindTextureDirectly(gl.TEXTURE_2D, texture);
 
-            var width =  (<{width: number, height: number}>size).width || <number>size;
-            var height = (<{width: number, height: number}>size).height || <number>size;
+            var width = (<{ width: number, height: number }>size).width || <number>size;
+            var height = (<{ width: number, height: number }>size).height || <number>size;
 
             var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
 
@@ -4089,10 +4089,8 @@
             var textureType = this._getWebGLTextureType(type);
             var internalFormat = this._getInternalFormat(format);
 
-            var needConversion = false;
             if (internalFormat === gl.RGB) {
                 internalFormat = gl.RGBA;
-                needConversion = true;
             }
 
             var width = size;

+ 8 - 10
src/Materials/Textures/babylon.multiRenderTarget.ts

@@ -12,7 +12,6 @@ module BABYLON {
 
         private _internalTextures: InternalTexture[];
         private _textures: Texture[];
-        private _count: number;
 
         public get isSupported(): boolean {
             return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
@@ -28,7 +27,7 @@ module BABYLON {
             return this._textures[this._textures.length - 1];
         }
 
-        public set wrapU (wrap: number) {
+        public set wrapU(wrap: number) {
             if (this._textures) {
                 for (var i = 0; i < this._textures.length; i++) {
                     this._textures[i].wrapU = wrap;
@@ -36,7 +35,7 @@ module BABYLON {
             }
         }
 
-        public set wrapV (wrap: number) {
+        public set wrapV(wrap: number) {
             if (this._textures) {
                 for (var i = 0; i < this._textures.length; i++) {
                     this._textures[i].wrapV = wrap;
@@ -53,7 +52,7 @@ module BABYLON {
 
             super(name, size, scene, generateMipMaps, doNotChangeAspectRatio);
 
-            this._engine = scene.getEngine();            
+            this._engine = scene.getEngine();
 
             if (!this.isSupported) {
                 this.dispose();
@@ -80,7 +79,6 @@ module BABYLON {
             var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
             var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
 
-            this._count = count;
             this._size = size;
             this._multiRenderTargetOptions = {
                 samplingModes: samplingModes,
@@ -90,8 +88,8 @@ module BABYLON {
                 generateDepthTexture: generateDepthTexture,
                 types: types,
                 textureCount: count
-            };            
-            
+            };
+
             this._createInternalTextures();
             this._createTextures();
         }
@@ -110,7 +108,7 @@ module BABYLON {
         }
 
         private _createInternalTextures(): void {
-            this._internalTextures = this._engine.createMultipleRenderTarget(this._size , this._multiRenderTargetOptions);
+            this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
         }
 
         private _createTextures(): void {
@@ -133,8 +131,8 @@ module BABYLON {
             if (this._samples === value) {
                 return;
             }
-            
-            for (var i = 0 ; i < this._internalTextures.length; i++) {
+
+            for (var i = 0; i < this._internalTextures.length; i++) {
                 this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
             }
         }

+ 23 - 25
src/Materials/babylon.effect.ts

@@ -1,12 +1,11 @@
 module BABYLON {
     export class EffectFallbacks {
-        private _defines: {[key: string]: Array<String>} = {};
+        private _defines: { [key: string]: Array<String> } = {};
 
         private _currentRank = 32;
         private _maxRank = -1;
 
         private _mesh: Nullable<AbstractMesh>;
-        private _meshRank: number;
 
         public unBindMesh() {
             this._mesh = null;
@@ -29,7 +28,6 @@
         }
 
         public addCPUSkinningFallback(rank: number, mesh: BABYLON.AbstractMesh) {
-            this._meshRank = rank;
             this._mesh = mesh;
 
             if (rank < this._currentRank) {
@@ -123,8 +121,8 @@
         private _valueCache: { [key: string]: any };
         private static _baseCache: { [key: number]: WebGLBuffer } = {};
 
-        constructor(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers: Nullable<string[]> = null, engine?: Engine, defines: Nullable<string> = null, 
-                    fallbacks: Nullable<EffectFallbacks> = null, onCompiled: Nullable<(effect: Effect) => void> = null, onError: Nullable<(effect: Effect, errors: string) => void> = null, indexParameters?: any) {
+        constructor(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers: Nullable<string[]> = null, engine?: Engine, defines: Nullable<string> = null,
+            fallbacks: Nullable<EffectFallbacks> = null, onCompiled: Nullable<(effect: Effect) => void> = null, onError: Nullable<(effect: Effect, errors: string) => void> = null, indexParameters?: any) {
             this.name = baseName;
 
             if ((<EffectCreationOptions>attributesNamesOrOptions).attributes) {
@@ -138,14 +136,14 @@
                 this.onError = options.onError;
                 this.onCompiled = options.onCompiled;
                 this._fallbacks = options.fallbacks;
-                this._indexParameters = options.indexParameters;  
+                this._indexParameters = options.indexParameters;
                 this._transformFeedbackVaryings = options.transformFeedbackVaryings;
 
                 if (options.uniformBuffersNames) {
                     for (var i = 0; i < options.uniformBuffersNames.length; i++) {
                         this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
-                    }          
-                }    
+                    }
+                }
             } else {
                 this._engine = <Engine>engine;
                 this.defines = <string>defines;
@@ -159,7 +157,7 @@
                 this._indexParameters = indexParameters;
                 this._fallbacks = fallbacks;
             }
-        
+
             this.uniqueId = Effect._uniqueIdSeed++;
 
             var vertexSource: any;
@@ -194,7 +192,7 @@
                                     if (baseName) {
                                         var vertex = baseName.vertexElement || baseName.vertex || baseName;
                                         var fragment = baseName.fragmentElement || baseName.fragment || baseName;
-                            
+
                                         this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
                                         this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
                                     } else {
@@ -267,7 +265,7 @@
                 func(this);
                 return;
             }
-            
+
             this.onCompileObservable.add((effect) => {
                 func(effect);
             });
@@ -285,9 +283,9 @@
 
             // Base64 encoded ?
             if (vertex.substr(0, 7) === "base64:") {
-            	var vertexBinary = window.atob(vertex.substr(7));
-            	callback(vertexBinary);
-            	return;
+                var vertexBinary = window.atob(vertex.substr(7));
+                callback(vertexBinary);
+                return;
             }
 
             // Is in local store ?
@@ -320,9 +318,9 @@
 
             // Base64 encoded ?
             if (fragment.substr(0, 7) === "base64:") {
-            	var fragmentBinary = window.atob(fragment.substr(7));
-            	callback(fragmentBinary);
-            	return;
+                var fragmentBinary = window.atob(fragment.substr(7));
+                callback(fragmentBinary);
+                return;
             }
 
             // Is in local store ?
@@ -358,9 +356,9 @@
             // Number lines of shaders source code
             var i = 2;
             var regex = /\n/gm;
-            var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function() { return "\n" + (i++) + "\t"; });
+            var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
             i = 2;
-            var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function() { return "\n" + (i++) + "\t"; });
+            var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
 
             // Dump shaders name and formatted source code
             if (this.name.vertexElement) {
@@ -393,7 +391,7 @@
             }
 
             var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
-            
+
             // Remove extensions 
             // #extension GL_OES_standard_derivatives : enable
             // #extension GL_EXT_shader_texture_lod : enable
@@ -406,7 +404,7 @@
             result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
             result = result.replace(/attribute[ \t]/g, "in ");
             result = result.replace(/[ \t]attribute/g, " in");
-            
+
             if (isFragment) {
                 result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
                 result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
@@ -417,7 +415,7 @@
                 result = result.replace(/gl_FragData/g, "glFragData");
                 result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
             }
-            
+
             callback(result);
         }
 
@@ -607,10 +605,10 @@
 
                 // Let's go through fallbacks then
                 Tools.Error("Unable to compile effect:");
-                BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function(uniform) {
+                BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
                     return " " + uniform;
                 }));
-                BABYLON.Tools.Error("Attributes: " + attributesNames.map(function(attribute) {
+                BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
                     return " " + attribute;
                 }));
                 this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
@@ -641,7 +639,7 @@
                         this._fallbacks.unBindMesh();
                     }
                 }
-            }            
+            }
         }
 
         public get isSupported(): boolean {

+ 35 - 38
src/Mesh/babylon.meshSimplification.ts

@@ -66,7 +66,7 @@
                 //parallel simplifier
                 task.settings.forEach((setting) => {
                     var simplifier = this.getSimplifier(task);
-                    simplifier.simplify(setting,(newMesh) => {
+                    simplifier.simplify(setting, (newMesh) => {
                         task.mesh.addLODLevel(setting.distance, newMesh);
                         newMesh.isVisible = true;
                         //check if it is the last
@@ -82,7 +82,7 @@
                 var simplifier = this.getSimplifier(task);
 
                 var runDecimation = (setting: ISimplificationSettings, callback: () => void) => {
-                    simplifier.simplify(setting,(newMesh) => {
+                    simplifier.simplify(setting, (newMesh) => {
                         task.mesh.addLODLevel(setting.distance, newMesh);
                         newMesh.isVisible = true;
                         //run the next quality level
@@ -90,17 +90,17 @@
                     });
                 }
 
-                AsyncLoop.Run(task.settings.length,(loop: AsyncLoop) => {
-                    runDecimation(task.settings[loop.index],() => {
+                AsyncLoop.Run(task.settings.length, (loop: AsyncLoop) => {
+                    runDecimation(task.settings[loop.index], () => {
                         loop.executeNext();
                     });
-                },() => {
-                        //execution ended, run the success callback.
-                        if (task.successCallback) {
-                            task.successCallback();
-                        }
-                        this.executeNext();
-                    });
+                }, () => {
+                    //execution ended, run the success callback.
+                    if (task.successCallback) {
+                        task.successCallback();
+                    }
+                    this.executeNext();
+                });
             }
         }
 
@@ -229,8 +229,6 @@
         private vertices: Array<DecimationVertex>;
         private references: Array<Reference>;
 
-        private initialized: boolean = false;
-
         private _reconstructedMesh: Mesh;
 
         public syncIterations = 5000;
@@ -249,17 +247,17 @@
         public simplify(settings: ISimplificationSettings, successCallback: (simplifiedMesh: Mesh) => void) {
             this.initDecimatedMesh();
             //iterating through the submeshes array, one after the other.
-            AsyncLoop.Run(this._mesh.subMeshes.length,(loop: AsyncLoop) => {
-                this.initWithMesh(loop.index,() => {
-                    this.runDecimation(settings, loop.index,() => {
+            AsyncLoop.Run(this._mesh.subMeshes.length, (loop: AsyncLoop) => {
+                this.initWithMesh(loop.index, () => {
+                    this.runDecimation(settings, loop.index, () => {
                         loop.executeNext();
                     });
                 }, settings.optimizeMesh);
-            },() => {
-                    setTimeout(() => {
-                        successCallback(this._reconstructedMesh);
-                    }, 0);
-                });
+            }, () => {
+                setTimeout(() => {
+                    successCallback(this._reconstructedMesh);
+                }, 0);
+            });
         }
 
         private runDecimation(settings: ISimplificationSettings, submeshIndex: number, successCallback: () => void) {
@@ -348,24 +346,24 @@
                             }
                         }
                     };
-                    AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, trianglesIterator, callback,() => { return (triangleCount - deletedTriangles <= targetCount) });
+                    AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, trianglesIterator, callback, () => { return (triangleCount - deletedTriangles <= targetCount) });
                 }, 0);
             };
 
-            AsyncLoop.Run(this.decimationIterations,(loop: AsyncLoop) => {
+            AsyncLoop.Run(this.decimationIterations, (loop: AsyncLoop) => {
                 if (triangleCount - deletedTriangles <= targetCount) loop.breakLoop();
                 else {
-                    iterationFunction(loop.index,() => {
+                    iterationFunction(loop.index, () => {
                         loop.executeNext();
                     });
                 }
-            },() => {
-                    setTimeout(() => {
-                        //reconstruct this part of the mesh
-                        this.reconstructMesh(submeshIndex);
-                        successCallback();
-                    }, 0);
-                });
+            }, () => {
+                setTimeout(() => {
+                    //reconstruct this part of the mesh
+                    this.reconstructMesh(submeshIndex);
+                    successCallback();
+                }, 0);
+            });
         }
 
         private initWithMesh(submeshIndex: number, callback: Function, optimizeMesh?: boolean) {
@@ -408,7 +406,7 @@
             };
             //var totalVertices = mesh.getTotalVertices();
             var totalVertices = submesh.verticesCount;
-            AsyncLoop.SyncAsyncForLoop(totalVertices,(this.syncIterations / 4) >> 0, vertexInit,() => {
+            AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, () => {
 
                 var indicesInit = (i: number) => {
                     if (!indices) {
@@ -427,7 +425,7 @@
                     triangle.originalOffset = pos;
                     this.triangles.push(triangle);
                 };
-                AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, this.syncIterations, indicesInit,() => {
+                AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, this.syncIterations, indicesInit, () => {
                     this.init(callback);
                 });
             });
@@ -441,7 +439,7 @@
                     t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(Vector3.Dot(t.normal, t.vertices[0].position))));
                 }
             };
-            AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1,() => {
+            AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, () => {
 
                 var triangleInit2 = (i: number) => {
                     var t = this.triangles[i];
@@ -450,8 +448,7 @@
                     }
                     t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
                 };
-                AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit2,() => {
-                    this.initialized = true;
+                AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit2, () => {
                     callback();
                 });
             });
@@ -542,7 +539,7 @@
                 this._reconstructedMesh.setVerticesData(VertexBuffer.UVKind, newUVsData);
             if (newColorsData.length > 0)
                 this._reconstructedMesh.setVerticesData(VertexBuffer.ColorKind, newColorsData);
-            
+
             //create submesh
             var originalSubmesh = this._mesh.subMeshes[submeshIndex];
             if (submeshIndex > 0) {
@@ -559,7 +556,7 @@
             this._reconstructedMesh.material = this._mesh.material;
             this._reconstructedMesh.parent = this._mesh.parent;
             this._reconstructedMesh.isVisible = false;
-            this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId; 
+            this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
         }
 
         private isFlipped(vertex1: DecimationVertex, vertex2: DecimationVertex, point: Vector3, deletedArray: Array<boolean>, borderFactor: number, delTr: Array<DecimationTriangle>): boolean {

+ 28 - 35
src/PostProcess/RenderPipeline/Pipelines/babylon.ssao2RenderingPipeline.ts

@@ -88,9 +88,9 @@
         private _expensiveBlur: boolean = true;
         public set expensiveBlur(b: boolean) {
             this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n",
-                                                null, ["textureSampler", "depthSampler"]);
+                null, ["textureSampler", "depthSampler"]);
             this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n",
-                                                null, ["textureSampler", "depthSampler"]);
+                null, ["textureSampler", "depthSampler"]);
             this._expensiveBlur = b;
             this._firstUpdate = true;
         }
@@ -139,9 +139,6 @@
 
         private _firstUpdate: boolean = true;
 
-        @serialize()
-        private _ratio: any;
-
         /**
          * @constructor
          * @param {string} name - The rendering pipeline name
@@ -161,15 +158,11 @@
 
             var ssaoRatio = ratio.ssaoRatio || ratio;
             var blurRatio = ratio.blurRatio || ratio;
-            this._ratio = {
-                ssaoRatio: ssaoRatio,
-                blurRatio: blurRatio
-            };
 
             // Set up assets
             let geometryBufferRenderer = <GeometryBufferRenderer>scene.enableGeometryBufferRenderer();
             this._createRandomTexture();
-            this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0]; 
+            this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
             this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
 
             this._originalColorPostProcess = new PassPostProcess("SSAOOriginalSceneColor", 1.0, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
@@ -261,7 +254,7 @@
                 }
             };
         }
-        
+
         public _rebuild() {
             this._firstUpdate = true;
 
@@ -279,18 +272,18 @@
 
             var i = 0;
             while (i < numSamples) {
-               vector = new BABYLON.Vector3(
-                   rand(-1.0, 1.0),
-                   rand(-1.0, 1.0),
-                   rand(0.30, 1.0));
-               vector.normalize();
-               scale = i / numSamples;
-               scale = Scalar.Lerp(0.1, 1.0, scale*scale);
-               vector.scaleInPlace(scale);
-
-
-               result.push(vector.x, vector.y, vector.z);
-               i++;
+                vector = new BABYLON.Vector3(
+                    rand(-1.0, 1.0),
+                    rand(-1.0, 1.0),
+                    rand(0.30, 1.0));
+                vector.normalize();
+                scale = i / numSamples;
+                scale = Scalar.Lerp(0.1, 1.0, scale * scale);
+                vector.scaleInPlace(scale);
+
+
+                result.push(vector.x, vector.y, vector.z);
+                i++;
             }
 
             return result;
@@ -302,15 +295,15 @@
             this._sampleSphere = this._generateHemisphere();
 
             this._ssaoPostProcess = new PostProcess("ssao2", "ssao2",
-                                                    [
-                                                        "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
-                                                        "base", "range", "projection", "near", "far", "texelSize",
-                                                        "xViewport", "yViewport", "maxZ", "minZAspect"
-                                                    ],
-                                                    ["randomSampler", "normalSampler"],
-                                                    ratio, null, Texture.BILINEAR_SAMPLINGMODE,
-                                                    this._scene.getEngine(), false,
-                                                    "#define SAMPLES " + numSamples + "\n#define SSAO");
+                [
+                    "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
+                    "base", "range", "projection", "near", "far", "texelSize",
+                    "xViewport", "yViewport", "maxZ", "minZAspect"
+                ],
+                ["randomSampler", "normalSampler"],
+                ratio, null, Texture.BILINEAR_SAMPLINGMODE,
+                this._scene.getEngine(), false,
+                "#define SAMPLES " + numSamples + "\n#define SSAO");
 
             this._ssaoPostProcess.onApply = (effect: Effect) => {
                 if (this._firstUpdate) {
@@ -332,7 +325,7 @@
                 effect.setFloat("near", this._scene.activeCamera.minZ);
                 effect.setFloat("far", this._scene.activeCamera.maxZ);
                 effect.setFloat("xViewport", Math.tan(this._scene.activeCamera.fov / 2) * this._scene.getEngine().getAspectRatio(this._scene.activeCamera, true));
-                effect.setFloat("yViewport", Math.tan(this._scene.activeCamera.fov / 2) );
+                effect.setFloat("yViewport", Math.tan(this._scene.activeCamera.fov / 2));
                 effect.setMatrix("projection", this._scene.getProjectionMatrix());
 
                 effect.setTexture("textureSampler", this._depthTexture);
@@ -343,8 +336,8 @@
 
         private _createSSAOCombinePostProcess(ratio: number): void {
             this._ssaoCombinePostProcess = new PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"],
-                                                           ratio, null, Texture.BILINEAR_SAMPLINGMODE,
-                                                           this._scene.getEngine(), false);
+                ratio, null, Texture.BILINEAR_SAMPLINGMODE,
+                this._scene.getEngine(), false);
 
             this._ssaoCombinePostProcess.onApply = (effect: Effect) => {
                 effect.setTextureFromPostProcess("originalColor", this._originalColorPostProcess);

+ 11 - 18
src/PostProcess/RenderPipeline/Pipelines/babylon.ssaoRenderingPipeline.ts

@@ -80,9 +80,6 @@
 
         private _firstUpdate: boolean = true;
 
-        @serialize()
-        private _ratio: any;
-
         /**
          * @constructor
          * @param {string} name - The rendering pipeline name
@@ -101,10 +98,6 @@
 
             var ssaoRatio = ratio.ssaoRatio || ratio;
             var combineRatio = ratio.combineRatio || ratio;
-            this._ratio = {
-                ssaoRatio: ssaoRatio,
-                combineRatio: combineRatio
-            };
 
             this._originalColorPostProcess = new PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
             this._createSSAOPostProcess(ssaoRatio);
@@ -171,7 +164,7 @@
 
         public _rebuild() {
             this._firstUpdate = true;
-            super._rebuild();            
+            super._rebuild();
         }
 
         private _createSSAOPostProcess(ratio: number): void {
@@ -197,14 +190,14 @@
             var samplesFactor = 1.0 / numSamples;
 
             this._ssaoPostProcess = new PostProcess("ssao", "ssao",
-                                                    [
-                                                        "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
-                                                        "area", "fallOff", "base", "range", "viewport"
-                                                    ],
-                                                    ["randomSampler"],
-                                                    ratio, null, Texture.BILINEAR_SAMPLINGMODE,
-                                                    this._scene.getEngine(), false,
-                                                    "#define SAMPLES " + numSamples + "\n#define SSAO");
+                [
+                    "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
+                    "area", "fallOff", "base", "range", "viewport"
+                ],
+                ["randomSampler"],
+                ratio, null, Texture.BILINEAR_SAMPLINGMODE,
+                this._scene.getEngine(), false,
+                "#define SAMPLES " + numSamples + "\n#define SSAO");
 
             this._ssaoPostProcess.onApply = (effect: Effect) => {
                 if (this._firstUpdate) {
@@ -226,8 +219,8 @@
 
         private _createSSAOCombinePostProcess(ratio: number): void {
             this._ssaoCombinePostProcess = new PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"],
-                                                           ratio, null, Texture.BILINEAR_SAMPLINGMODE,
-                                                           this._scene.getEngine(), false);
+                ratio, null, Texture.BILINEAR_SAMPLINGMODE,
+                this._scene.getEngine(), false);
 
             this._ssaoCombinePostProcess.onApply = (effect: Effect) => {
                 effect.setTextureFromPostProcess("originalColor", this._originalColorPostProcess);

+ 2 - 5
src/PostProcess/RenderPipeline/babylon.postProcessRenderEffect.ts

@@ -1,14 +1,12 @@
 module BABYLON {
     export class PostProcessRenderEffect {
-        private _engine: Engine;
-
         private _postProcesses: any;
         private _getPostProcess: () => Nullable<PostProcess>;
 
         private _singleInstance: boolean;
 
-        private _cameras: { [key:string]: Nullable<Camera>};
-        private _indicesForCamera: { [key:string]: number[]};
+        private _cameras: { [key: string]: Nullable<Camera> };
+        private _indicesForCamera: { [key: string]: number[] };
 
         private _renderPasses: any;
         private _renderEffectAsPasses: any;
@@ -19,7 +17,6 @@ module BABYLON {
         public applyParameters: (postProcess: PostProcess) => void;
 
         constructor(engine: Engine, name: string, getPostProcess: () => Nullable<PostProcess>, singleInstance?: boolean) {
-            this._engine = engine;
             this._name = name;
             this._singleInstance = singleInstance || true;
 

+ 12 - 16
src/Rendering/babylon.renderingManager.ts

@@ -30,21 +30,19 @@
         private _renderingGroups = new Array<RenderingGroup>();
         private _depthStencilBufferAlreadyCleaned: boolean;
 
-        private _currentIndex: number;
-
-        private _autoClearDepthStencil: { [id:number]: RenderingManageAutoClearOptions } = {};
-        private _customOpaqueSortCompareFn: { [id:number]: Nullable<(a: SubMesh, b: SubMesh) => number> } = {};
-        private _customAlphaTestSortCompareFn: { [id:number]: Nullable<(a: SubMesh, b: SubMesh) => number> } = {};
-        private _customTransparentSortCompareFn: { [id:number]: Nullable<(a: SubMesh, b: SubMesh) => number> } = {};
+        private _autoClearDepthStencil: { [id: number]: RenderingManageAutoClearOptions } = {};
+        private _customOpaqueSortCompareFn: { [id: number]: Nullable<(a: SubMesh, b: SubMesh) => number> } = {};
+        private _customAlphaTestSortCompareFn: { [id: number]: Nullable<(a: SubMesh, b: SubMesh) => number> } = {};
+        private _customTransparentSortCompareFn: { [id: number]: Nullable<(a: SubMesh, b: SubMesh) => number> } = {};
         private _renderinGroupInfo: Nullable<RenderingGroupInfo> = null;
 
         constructor(scene: Scene) {
             this._scene = scene;
 
             for (let i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
-                this._autoClearDepthStencil[i] = { autoClear: true, depth:true, stencil: true };
+                this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
             }
-        }        
+        }
 
         private _clearDepthStencilBuffer(depth = true, stencil = true): void {
             if (this._depthStencilBufferAlreadyCleaned) {
@@ -56,8 +54,8 @@
         }
 
         public render(customRenderFunction: Nullable<(opaqueSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>) => void>,
-            activeMeshes: Nullable<AbstractMesh[]>, renderParticles: boolean, renderSprites: boolean): void {          
-                  
+            activeMeshes: Nullable<AbstractMesh[]>, renderParticles: boolean, renderSprites: boolean): void {
+
             // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
             let observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
             let info: Nullable<RenderingGroupInfo> = null;
@@ -82,11 +80,9 @@
             for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
                 this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
                 var renderingGroup = this._renderingGroups[index];
-                if(!renderingGroup && !observable)
+                if (!renderingGroup && !observable)
                     continue;
 
-                this._currentIndex = index;
-
                 let renderingGroupMask = 0;
 
                 // Fire PRECLEAR stage
@@ -197,7 +193,7 @@
             this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
             this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
             this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
-                
+
             if (this._renderingGroups[renderingGroupId]) {
                 var group = this._renderingGroups[renderingGroupId];
                 group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
@@ -216,8 +212,8 @@
          */
         public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean,
             depth = true,
-            stencil = true): void {            
-            this._autoClearDepthStencil[renderingGroupId] = { 
+            stencil = true): void {
+            this._autoClearDepthStencil[renderingGroupId] = {
                 autoClear: autoClearDepthStencil,
                 depth: depth,
                 stencil: stencil

+ 111 - 114
src/Tools/babylon.performanceMonitor.ts

@@ -3,235 +3,232 @@ namespace BABYLON {
 	/**
 	 * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
 	 */
-	export class PerformanceMonitor {
+    export class PerformanceMonitor {
 
-		private _enabled: boolean = true;
-		private _rollingFrameTime: RollingAverage;
-		private _lastFrameTimeMs: Nullable<number>;
-		private _lastChangeTimeMs: Nullable<number>;
+        private _enabled: boolean = true;
+        private _rollingFrameTime: RollingAverage;
+        private _lastFrameTimeMs: Nullable<number>;
 
 		/**
 		 * constructor
 		 * @param frameSampleSize The number of samples required to saturate the sliding window
 		 */
-		constructor(frameSampleSize: number = 30) {
-			this._rollingFrameTime = new RollingAverage(frameSampleSize);
-		}
+        constructor(frameSampleSize: number = 30) {
+            this._rollingFrameTime = new RollingAverage(frameSampleSize);
+        }
 
 		/**
 		 * Samples current frame
 		 * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
 		 */
-		public sampleFrame(timeMs: number = Tools.Now) {
-			if (!this._enabled) return;
+        public sampleFrame(timeMs: number = Tools.Now) {
+            if (!this._enabled) return;
 
-			if (this._lastFrameTimeMs != null) {
-				let dt = timeMs - this._lastFrameTimeMs;
-				this._rollingFrameTime.add(dt);
-			}
+            if (this._lastFrameTimeMs != null) {
+                let dt = timeMs - this._lastFrameTimeMs;
+                this._rollingFrameTime.add(dt);
+            }
 
-			this._lastFrameTimeMs = timeMs;
-		}
+            this._lastFrameTimeMs = timeMs;
+        }
 
 		/**
 		 * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
 		 * @return Average frame time in milliseconds
 		 */
-		public get averageFrameTime(): number {
-			return this._rollingFrameTime.average;
-		}
+        public get averageFrameTime(): number {
+            return this._rollingFrameTime.average;
+        }
 
 		/**
 		 * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
 		 * @return Frame time variance in milliseconds squared
 		 */
-		public get averageFrameTimeVariance(): number {
-			return this._rollingFrameTime.variance;
-		}
+        public get averageFrameTimeVariance(): number {
+            return this._rollingFrameTime.variance;
+        }
 
 		/**
 		 * Returns the frame time of the most recent frame
 		 * @return Frame time in milliseconds
 		 */
-		public get instantaneousFrameTime(): number {
-			return this._rollingFrameTime.history(0);
-		}
+        public get instantaneousFrameTime(): number {
+            return this._rollingFrameTime.history(0);
+        }
 
 		/**
 		 * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
 		 * @return Framerate in frames per second
 		 */
-		public get averageFPS(): number {
-			return 1000.0 / this._rollingFrameTime.average;
-		}
+        public get averageFPS(): number {
+            return 1000.0 / this._rollingFrameTime.average;
+        }
 
 		/**
 		 * Returns the average framerate in frames per second using the most recent frame time
 		 * @return Framerate in frames per second
 		 */
-		public get instantaneousFPS(): number {
-			let history = this._rollingFrameTime.history(0);
+        public get instantaneousFPS(): number {
+            let history = this._rollingFrameTime.history(0);
 
-			if (history === 0) {
-				return 0;
-			}
+            if (history === 0) {
+                return 0;
+            }
 
-			return 1000.0 / history;
-		}
+            return 1000.0 / history;
+        }
 
 		/**
 		 * Returns true if enough samples have been taken to completely fill the sliding window
 		 * @return true if saturated
 		 */
-		public get isSaturated(): boolean {
-			return this._rollingFrameTime.isSaturated();
-		}
+        public get isSaturated(): boolean {
+            return this._rollingFrameTime.isSaturated();
+        }
 
 		/**
 		 * Enables contributions to the sliding window sample set
 		 */
-		public enable() {
-			this._enabled = true;
-		}
+        public enable() {
+            this._enabled = true;
+        }
 
 		/**
 		 * Disables contributions to the sliding window sample set
 		 * Samples will not be interpolated over the disabled period
 		 */
-		public disable() {
-			this._enabled = false;
-			//clear last sample to avoid interpolating over the disabled period when next enabled
-			this._lastFrameTimeMs = null;
-			this._lastChangeTimeMs = null;
-		}
+        public disable() {
+            this._enabled = false;
+            //clear last sample to avoid interpolating over the disabled period when next enabled
+            this._lastFrameTimeMs = null;
+        }
 
 		/**
 		 * Returns true if sampling is enabled
 		 * @return true if enabled
 		 */
-		public get isEnabled(): boolean {
-			return this._enabled;
-		}
+        public get isEnabled(): boolean {
+            return this._enabled;
+        }
 
 		/**
 		 * Resets performance monitor
 		 */
-		public reset() {
-			//clear last sample to avoid interpolating over the disabled period when next enabled
-			this._lastFrameTimeMs = null;
-			this._lastChangeTimeMs = null;
-			//wipe record
-			this._rollingFrameTime.reset();
-		}
+        public reset() {
+            //clear last sample to avoid interpolating over the disabled period when next enabled
+            this._lastFrameTimeMs = null;
+            //wipe record
+            this._rollingFrameTime.reset();
+        }
 
-	}
+    }
 
 	/**
 	 * RollingAverage
 	 *
 	 * Utility to efficiently compute the rolling average and variance over a sliding window of samples
 	 */
-	export class RollingAverage {
+    export class RollingAverage {
 
 		/**
 		 * Current average
 		 */
-		public average: number;
+        public average: number;
 		/**
 		 * Current variance
 		 */
-		public variance: number;
+        public variance: number;
 
-		protected _samples: Array<number>;
-		protected _sampleCount: number;
-		protected _pos: number;
-		protected _m2: number;//sum of squares of differences from the (current) mean
+        protected _samples: Array<number>;
+        protected _sampleCount: number;
+        protected _pos: number;
+        protected _m2: number;//sum of squares of differences from the (current) mean
 
 		/**
 		 * constructor
 		 * @param length The number of samples required to saturate the sliding window
 		 */
-		constructor(length: number) {
-			this._samples = new Array<number>(length);
-			this.reset();
-		}
+        constructor(length: number) {
+            this._samples = new Array<number>(length);
+            this.reset();
+        }
 
 		/**
 		 * Adds a sample to the sample set
 		 * @param v The sample value
 		 */
-		public add(v: number) {
-			//http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
-			let delta: number;
+        public add(v: number) {
+            //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
+            let delta: number;
 
-			//we need to check if we've already wrapped round
-			if (this.isSaturated()) {
-				//remove bottom of stack from mean
-				let bottomValue = this._samples[this._pos];
-				delta = bottomValue - this.average;
-				this.average -= delta / (this._sampleCount - 1);
-				this._m2 -= delta * (bottomValue - this.average);
-			} else {
-				this._sampleCount++;
-			}
+            //we need to check if we've already wrapped round
+            if (this.isSaturated()) {
+                //remove bottom of stack from mean
+                let bottomValue = this._samples[this._pos];
+                delta = bottomValue - this.average;
+                this.average -= delta / (this._sampleCount - 1);
+                this._m2 -= delta * (bottomValue - this.average);
+            } else {
+                this._sampleCount++;
+            }
 
-			//add new value to mean
-			delta = v - this.average;
-			this.average += delta / (this._sampleCount);
-			this._m2 += delta * (v - this.average);
+            //add new value to mean
+            delta = v - this.average;
+            this.average += delta / (this._sampleCount);
+            this._m2 += delta * (v - this.average);
 
-			//set the new variance
-			this.variance = this._m2 / (this._sampleCount - 1);
+            //set the new variance
+            this.variance = this._m2 / (this._sampleCount - 1);
 
-			this._samples[this._pos] = v;
-			this._pos++;
+            this._samples[this._pos] = v;
+            this._pos++;
 
-			this._pos %= this._samples.length;//positive wrap around
-		}
+            this._pos %= this._samples.length;//positive wrap around
+        }
 
 		/**
 		 * Returns previously added values or null if outside of history or outside the sliding window domain
 		 * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
 		 * @return Value previously recorded with add() or null if outside of range
 		 */
-		public history(i: number): number {
-			if ((i >= this._sampleCount) || (i >= this._samples.length)) {
-				return 0;
-			}
+        public history(i: number): number {
+            if ((i >= this._sampleCount) || (i >= this._samples.length)) {
+                return 0;
+            }
 
-			let i0 = this._wrapPosition(this._pos - 1.0);
-			return this._samples[this._wrapPosition(i0 - i)];
-		}
+            let i0 = this._wrapPosition(this._pos - 1.0);
+            return this._samples[this._wrapPosition(i0 - i)];
+        }
 
 		/**
 		 * Returns true if enough samples have been taken to completely fill the sliding window
 		 * @return true if sample-set saturated
 		 */
-		public isSaturated(): boolean {
-			return this._sampleCount >= this._samples.length;
-		}
+        public isSaturated(): boolean {
+            return this._sampleCount >= this._samples.length;
+        }
 
 		/**
 		 * Resets the rolling average (equivalent to 0 samples taken so far)
 		 */
-		public reset() {
-			this.average = 0;
-			this.variance = 0;
-			this._sampleCount = 0;
-			this._pos = 0;
-			this._m2 = 0;
-		}
+        public reset() {
+            this.average = 0;
+            this.variance = 0;
+            this._sampleCount = 0;
+            this._pos = 0;
+            this._m2 = 0;
+        }
 
 		/**
 		 * Wraps a value around the sample range boundaries
 		 * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
 		 * @return Wrapped position in sample range
 		 */
-		protected _wrapPosition(i: number): number {
-			let max = this._samples.length;
-			return ((i % max) + max) % max;
-		}
+        protected _wrapPosition(i: number): number {
+            let max = this._samples.length;
+            return ((i % max) + max) % max;
+        }
 
-	}
+    }
 
 }

+ 3 - 4
src/Tools/babylon.tga.ts

@@ -65,7 +65,6 @@
 
             var use_rle = false;
             var use_pal = false;
-            var use_rgb = false;
             var use_grey = false;
 
             // Get some informations.
@@ -79,7 +78,7 @@
                 case TGATools._TYPE_RLE_RGB:
                     use_rle = true;
                 case TGATools._TYPE_RGB:
-                    use_rgb = true;
+                    // use_rgb = true;
                     break;
 
                 case TGATools._TYPE_RLE_GREY:
@@ -91,7 +90,7 @@
 
             var pixel_data;
 
-           // var numAlphaBits = header.flags & 0xf;
+            // var numAlphaBits = header.flags & 0xf;
             var pixel_size = header.pixel_size >> 3;
             var pixel_total = header.width * header.height * pixel_size;
 
@@ -143,7 +142,7 @@
                 pixel_data = data.subarray(
                     offset,
                     offset += (use_pal ? header.width * header.height : pixel_total)
-                    );
+                );
             }
 
             // Load to texture

+ 12 - 12
src/Tools/babylon.tools.ts

@@ -721,7 +721,7 @@
             }
         }
 
-        public static DumpFramebuffer(width: number, height: number, engine: Engine, successCallback?: (data: string) => void, mimeType: string = "image/png", fileName? : string): void {
+        public static DumpFramebuffer(width: number, height: number, engine: Engine, successCallback?: (data: string) => void, mimeType: string = "image/png", fileName?: string): void {
             // Read the contents of the framebuffer
             var numberOfChannelsByLine = width * 4;
             var halfHeight = height / 2;
@@ -761,7 +761,7 @@
             }
         }
 
-        static EncodeScreenshotCanvasData(successCallback?: (data: string) => void, mimeType: string = "image/png", fileName? : string) {
+        static EncodeScreenshotCanvasData(successCallback?: (data: string) => void, mimeType: string = "image/png", fileName?: string) {
             var base64Image = screenshotCanvas.toDataURL(mimeType);
             if (successCallback) {
                 successCallback(base64Image);
@@ -771,26 +771,25 @@
                 if (!screenshotCanvas.toBlob) {
                     //  low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
                     screenshotCanvas.toBlob = function (callback, type, quality) {
-                        var canvas = this;
-                        setTimeout(function() {
-                            var binStr = atob( canvas.toDataURL(type, quality).split(',')[1] ),
+                        setTimeout(() => {
+                            var binStr = atob(this.toDataURL(type, quality).split(',')[1]),
                                 len = binStr.length,
                                 arr = new Uint8Array(len);
 
-                            for (var i = 0; i < len; i++ ) {
+                            for (var i = 0; i < len; i++) {
                                 arr[i] = binStr.charCodeAt(i);
                             }
-                            callback( new Blob( [arr], {type: type || 'image/png'} ) );
+                            callback(new Blob([arr], { type: type || 'image/png' }));
                         });
                     }
                 }
-                screenshotCanvas.toBlob(function(blob) {
+                screenshotCanvas.toBlob(function (blob) {
                     var url = URL.createObjectURL(blob);
                     //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
                     if (("download" in document.createElement("a"))) {
                         var a = window.document.createElement("a");
                         a.href = url;
-                        if(fileName) {
+                        if (fileName) {
                             a.setAttribute("download", fileName);
                         }
                         else {
@@ -808,8 +807,9 @@
                     }
                     else {
                         var newWindow = window.open("");
+                        if (!newWindow) return;
                         var img = newWindow.document.createElement("img");
-                        img.onload = function() {
+                        img.onload = function () {
                             // no longer need to read the blob so it's revoked
                             URL.revokeObjectURL(url);
                         };
@@ -882,7 +882,7 @@
             Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
         }
 
-        public static CreateScreenshotUsingRenderTarget(engine: Engine, camera: Camera, size: any, successCallback?: (data: string) => void, mimeType: string = "image/png", samples: number = 1, antialiasing : boolean = false, fileName? : string): void {
+        public static CreateScreenshotUsingRenderTarget(engine: Engine, camera: Camera, size: any, successCallback?: (data: string) => void, mimeType: string = "image/png", samples: number = 1, antialiasing: boolean = false, fileName?: string): void {
             var width: number;
             var height: number;
 
@@ -930,7 +930,7 @@
             var texture = new RenderTargetTexture("screenShot", size, scene, false, false, Engine.TEXTURETYPE_UNSIGNED_INT, false, Texture.NEAREST_SAMPLINGMODE);
             texture.renderList = null;
             texture.samples = samples;
-            if(antialiasing) {
+            if (antialiasing) {
                 texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
             }
             texture.onAfterRenderObservable.add(() => {

+ 6 - 20
src/Tools/babylon.virtualJoystick.ts

@@ -22,16 +22,13 @@ module BABYLON {
         private static vjCanvasWidth: number;
         private static vjCanvasHeight: number;
         private static halfWidth: number;
-        private static halfHeight: number;
+
 
         private _action: () => any;
         private _axisTargetedByLeftAndRight: JoystickAxis;
         private _axisTargetedByUpAndDown: JoystickAxis;
         private _joystickSensibility: number;
         private _inversedSensibility: number;
-        private _rotationSpeed: number;
-        private _inverseRotationSpeed: number;
-        private _rotateOnAxisRelativeToMesh: boolean;
         private _joystickPointerID: number;
         private _joystickColor: string;
         private _joystickPointerPos: Vector2;
@@ -39,13 +36,11 @@ module BABYLON {
         private _joystickPointerStartPos: Vector2;
         private _deltaJoystickVector: Vector2;
         private _leftJoystick: boolean;
-        private _joystickIndex: number;
         private _touches: StringDictionary<{ x: number, y: number, prevX: number, prevY: number } | PointerEvent>;
 
         private _onPointerDownHandlerRef: (e: PointerEvent) => any;
         private _onPointerMoveHandlerRef: (e: PointerEvent) => any;
         private _onPointerUpHandlerRef: (e: PointerEvent) => any;
-        private _onPointerOutHandlerRef: (e: PointerEvent) => any;
         private _onResize: (e: any) => any;
 
         constructor(leftJoystick?: boolean) {
@@ -56,7 +51,6 @@ module BABYLON {
                 this._leftJoystick = false;
             }
 
-            this._joystickIndex = VirtualJoystick._globalJoystickIndex;
             VirtualJoystick._globalJoystickIndex++;
 
             // By default left & right arrow keys are moving the X
@@ -73,9 +67,6 @@ module BABYLON {
 
             this._joystickSensibility = 25;
             this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
-            this._rotationSpeed = 25;
-            this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
-            this._rotateOnAxisRelativeToMesh = false;
 
             this._onResize = evt => {
                 VirtualJoystick.vjCanvasWidth = window.innerWidth;
@@ -85,7 +76,6 @@ module BABYLON {
                     VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
                 }
                 VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
-                VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
             }
 
             // injecting a canvas element on top of the canvas 3D game
@@ -118,7 +108,6 @@ module BABYLON {
                 document.body.appendChild(VirtualJoystick.vjCanvas);
             }
             VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
-            VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
             this.pressed = false;
             // default joystick color
             this._joystickColor = "cyan";
@@ -130,16 +119,13 @@ module BABYLON {
             // origin joystick position
             this._joystickPointerStartPos = new Vector2(0, 0);
             this._deltaJoystickVector = new Vector2(0, 0);
-            
+
             this._onPointerDownHandlerRef = evt => {
                 this._onPointerDown(evt);
             }
             this._onPointerMoveHandlerRef = evt => {
                 this._onPointerMove(evt);
             }
-            this._onPointerOutHandlerRef = evt => {
-                this._onPointerUp(evt);
-            }
             this._onPointerUpHandlerRef = evt => {
                 this._onPointerUp(evt);
             }
@@ -148,7 +134,7 @@ module BABYLON {
             VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
             VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
             VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
-            VirtualJoystick.vjCanvas.addEventListener("contextmenu",(evt) => {
+            VirtualJoystick.vjCanvas.addEventListener("contextmenu", (evt) => {
                 evt.preventDefault();    // Disables system menu
             }, false);
             requestAnimationFrame(() => { this._drawVirtualJoystick(); });
@@ -231,7 +217,7 @@ module BABYLON {
                 let data = this._touches.get(e.pointerId.toString());
                 if (data) {
                     (data as any).x = e.clientX;
-                    (data as any).y = e.clientY;                     
+                    (data as any).y = e.clientY;
                 }
             }
         }
@@ -299,7 +285,7 @@ module BABYLON {
             if (this.pressed) {
                 this._touches.forEach((key, touch) => {
                     if ((<PointerEvent>touch).pointerId === this._joystickPointerID) {
-                        VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);                       
+                        VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
                         VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
                         VirtualJoystick.vjCanvasContext.beginPath();
                         VirtualJoystick.vjCanvasContext.lineWidth = 6;
@@ -317,7 +303,7 @@ module BABYLON {
                         VirtualJoystick.vjCanvasContext.strokeStyle = this._joystickColor;
                         VirtualJoystick.vjCanvasContext.arc(this._joystickPointerPos.x, this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
                         VirtualJoystick.vjCanvasContext.stroke();
-                        VirtualJoystick.vjCanvasContext.closePath(); 
+                        VirtualJoystick.vjCanvasContext.closePath();
                         this._joystickPreviousPointerPos = this._joystickPointerPos.clone();
                     }
                     else {