浏览代码

initial commit

Benjamin Guignabert 8 年之前
父节点
当前提交
84d06a972c

文件差异内容过多而无法显示
+ 3592 - 3580
dist/preview release/babylon.d.ts


文件差异内容过多而无法显示
+ 3592 - 3580
dist/preview release/babylon.module.d.ts


+ 48 - 12
src/Materials/Textures/babylon.multiRenderTarget.ts

@@ -5,13 +5,36 @@ module BABYLON {
             return this._scene;
         }
 
-        private _textures: WebGLTexture[];
+        private _webGLTextures: WebGLTexture[];
+        private _textures: Texture[];
         private _count: number;
         private _scene: Scene;
         private _renderingManager: RenderingManager;
         private _doNotChangeAspectRatio: boolean;
         private _size: number;
 
+        /**
+        * An event triggered after the texture clear
+        * @type {BABYLON.Observable}
+        */
+        public onClearObservable = new Observable<Engine>();
+
+        private _onClearObserver: Observer<Engine>;
+        public set onClear(callback: (Engine: Engine) => void) {
+            if (this._onClearObserver) {
+                this.onClearObservable.remove(this._onClearObserver);
+            }
+            this._onClearObserver = this.onClearObservable.add(callback);
+        }
+
+        public get textures(): Texture[] {
+            return this._textures;
+        }
+
+        public get depthTexture(): Texture {
+            return this._textures[this._textures.length - 1];
+        }
+
         private _shouldRender(): boolean {
             return true;
         }
@@ -21,9 +44,9 @@ module BABYLON {
         constructor(name: string, size: any, count: number, scene: Scene, options?: any) {
             options = options || {};
 
-            var generateMipMaps = options.generateMipMaps ? options.generateMipMaps[0] : true;
-            var doNotChangeAspectRatio = options.doNotChangeAspectRatio;
-            var type = options.types ? options.types[0] : Engine.TEXTURETYPE_UNSIGNED_INT;
+            var generateMipMaps = options.generateMipMaps ? options.generateMipMaps[0] : false;
+            var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
+            var type = options.types ? options.types[0] : Engine.TEXTURETYPE_FLOAT;
             var samplingMode = options.samplingModes ? options.samplingModes[0] : Texture.TRILINEAR_SAMPLINGMODE;
             var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
             var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
@@ -32,7 +55,7 @@ module BABYLON {
             this._scene = scene;
             this._doNotChangeAspectRatio = doNotChangeAspectRatio;
             this._size = size;
-            this._textures = scene.getEngine().createMultipleRenderTarget(size, {
+            this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, {
                 samplingMode: samplingMode,
                 generateMipMaps: generateMipMaps,
                 generateDepthBuffer: generateDepthBuffer,
@@ -41,6 +64,13 @@ module BABYLON {
                 textureCount: count
             });
 
+            this._textures = [];
+            for (var i = 0; i < this._webGLTextures.length; i++) {
+                var texture = new BABYLON.Texture(null, scene);
+                texture._texture = this._webGLTextures[i];
+                this._textures.push(texture);
+            }
+
             // Rendering groups
             this._renderingManager = new RenderingManager(scene);
         }
@@ -87,8 +117,14 @@ module BABYLON {
             var engine = scene.getEngine();
 
             // Bind
-            engine.bindFramebuffer(this._textures[0]);
-            engine.clear(scene.clearColor, true, true, true);
+            engine.bindFramebuffer(this._webGLTextures[0]);
+
+            // Clear
+            if (this.onClearObservable.hasObservers()) {
+                this.onClearObservable.notifyObservers(engine);
+            } else {
+                engine.clear(scene.clearColor, true, true, true);
+            }
 
             if (!this._doNotChangeAspectRatio) {
                 scene.updateTransformMatrix(true);
@@ -107,7 +143,7 @@ module BABYLON {
             }
 
             // Unbind
-            engine.unBindFramebuffer(this._textures[0]);
+            engine.unBindFramebuffer(this._webGLTextures[0]);
         }
 
 
@@ -118,10 +154,10 @@ module BABYLON {
             // Remove from scene
             this._scene._removePendingData(this);
 
-            for (var i = this._textures.length - 1; i >= 0; i--) {
-                if (this._textures[i] !== undefined) {
-                    this._scene.getEngine().releaseInternalTexture(this._textures[i]);
-                    this._textures.splice(i, 1);
+            for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
+                if (this._webGLTextures[i] !== undefined) {
+                    this._scene.getEngine().releaseInternalTexture(this._webGLTextures[i]);
+                    this._webGLTextures.splice(i, 1);
                 }
             }
         }

+ 10 - 7
src/PostProcess/babylon.postProcess.ts

@@ -180,8 +180,8 @@
                 let textureSize = { width: this.width, height: this.height };
                 let textureOptions = { 
                     generateMipMaps: false, 
-                    generateDepthBuffer: camera._postProcesses.indexOf(this) === 0, 
-                    generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
+                    generateDepthBuffer: false, //camera._postProcesses.indexOf(this) === 0, 
+                    generateStencilBuffer: false, //camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
                     samplingMode: this.renderTargetSamplingMode, 
                     type: this._textureType 
                 };
@@ -191,15 +191,18 @@
                 if (this._reusable) {
                     this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
                 }
+ 
+                //Debug
+                this._engine.updateRenderTargetTextureSampleCount(this._textures.data[this._textures.length - 1], 64);
 
                 this.onSizeChangedObservable.notifyObservers(this);
             }
 
-            this._textures.forEach(texture => {
-                if (texture.samples !== this.samples) {
-                    this._engine.updateRenderTargetTextureSampleCount(texture, this.samples);
-                }
-            });
+            // this._textures.forEach(texture => {
+            //     if (texture.samples !== this.samples) {
+            //         this._engine.updateRenderTargetTextureSampleCount(texture, this.samples);
+            //     }
+            // });
 
             if (this.enablePixelPerfectMode) {
                 this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);

+ 14 - 9
src/PostProcess/babylon.ssaoRenderingPipeline.ts

@@ -69,7 +69,8 @@
         public base: number = 0.5;
 
         private _scene: Scene;
-        private _depthTexture: RenderTargetTexture;
+        private _depthTexture: Texture;
+        private _normalTexture: Texture;
         private _randomTexture: DynamicTexture;
 
         private _originalColorPostProcess: PassPostProcess;
@@ -97,7 +98,9 @@
 
             // Set up assets
             this._createRandomTexture();
-            this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
+            this._depthTexture = scene.enableGeometryRenderer().getGBuffer().depthTexture; 
+            // this._depthTexture = scene.enableGeometryRenderer().getGBuffer().textures[0]; // Force depth renderer "on"
+            this._normalTexture = scene.enableGeometryRenderer().getGBuffer().textures[1]; // Force depth renderer "on"
 
             var ssaoRatio = ratio.ssaoRatio || ratio;
             var combineRatio = ratio.combineRatio || ratio;
@@ -112,12 +115,11 @@
             this._createSSAOCombinePostProcess(combineRatio);
 
             // Set up pipeline
-            this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, () => { return this._originalColorPostProcess; }, true));
+            // this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, () => { return this._originalColorPostProcess; }, true));
             this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, () => { return this._ssaoPostProcess; }, true));
-            this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, () => { return this._blurHPostProcess; }, true));
-            this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, () => { return this._blurVPostProcess; }, true));
-
-            this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, () => { return this._ssaoCombinePostProcess; }, true));
+            // this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, () => { return this._blurHPostProcess; }, true));
+            // this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, () => { return this._blurVPostProcess; }, true));
+            // this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, () => { return this._ssaoCombinePostProcess; }, true));
 
             // Finish
             scene.postProcessRenderPipelineManager.addPipeline(this);
@@ -214,9 +216,9 @@
             this._ssaoPostProcess = new PostProcess("ssao", "ssao",
                                                     [
                                                         "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
-                                                        "area", "fallOff", "base", "range", "viewport"
+                                                        "area", "fallOff", "base", "range", "viewport", "width", "height"
                                                     ],
-                                                    ["randomSampler"],
+                                                    ["randomSampler", "normalSampler"],
                                                     ratio, null, Texture.BILINEAR_SAMPLINGMODE,
                                                     this._scene.getEngine(), false,
                                                     "#define SAMPLES " + numSamples + "\n#define SSAO");
@@ -235,8 +237,11 @@
                 effect.setFloat("area", this.area);
                 effect.setFloat("fallOff", this.fallOff);
                 effect.setFloat("base", this.base);
+                effect.setFloat("width", this._scene.getEngine().getRenderWidth());
+                effect.setFloat("height", this._scene.getEngine().getRenderHeight());
 
                 effect.setTexture("textureSampler", this._depthTexture);
+                effect.setTexture("normalSampler", this._normalTexture);
                 effect.setTexture("randomSampler", this._randomTexture);
             };
         }

+ 9 - 4
src/Rendering/babylon.geometryRenderer.ts

@@ -16,8 +16,12 @@ module BABYLON {
             var engine = scene.getEngine();
 
             // Render target
-            this._multiRenderTarget = new MultiRenderTarget("gBuffer", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, 2, this._scene);
-            
+            this._multiRenderTarget = new MultiRenderTarget("gBuffer", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, 2, this._scene, {generateMipMaps : [true]});
+            // set default depth value to 1.0 (far away)
+            this._multiRenderTarget.onClearObservable.add((engine: Engine) => {
+                engine.clear(new Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
+            });
+
             // Custom render function
             var renderSubMesh = (subMesh: SubMesh): void => {
                 var mesh = subMesh.getRenderingMesh();
@@ -42,6 +46,7 @@ module BABYLON {
                     var material = subMesh.getMaterial();
 
                     this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
+                    this._effect.setMatrix("view", scene.getViewMatrix());
 
                     this._effect.setFloat("far", scene.activeCamera.maxZ);
 
@@ -74,7 +79,7 @@ module BABYLON {
 
             var defines = [];
 
-            var attribs = [VertexBuffer.PositionKind];
+            var attribs = [VertexBuffer.PositionKind, VertexBuffer.NormalKind];
 
             var mesh = subMesh.getMesh();
             var scene = mesh.getScene();
@@ -90,7 +95,7 @@ module BABYLON {
                 this._cachedDefines = join;
                 this._effect = this._scene.getEngine().createEffect("geometry",
                     attribs,
-                    ["world", "viewProjection", "far"],
+                    ["world", "viewProjection", "view", "far"],
                     [], join);
             }
 

+ 167 - 0
src/Shaders/alternativessao.fragment.fx

@@ -0,0 +1,167 @@
+/*
+SSAO GLSL shader v1.2
+assembled by Martins Upitis (martinsh) (devlog-martinsh.blogspot.com)
+original technique is made by Arkano22 (www.gamedev.net/topic/550699-ssao-no-halo-artifacts/)
+
+changelog:
+1.2 - added fog calculation to mask AO. Minor fixes.
+1.1 - added spiral sampling method from here:
+(http://www.cgafaq.info/wiki/Evenly_distributed_points_on_sphere)
+*/
+uniform sampler2D textureSampler;
+uniform float width;
+uniform float height;
+
+#define PI    3.14159265
+varying vec2 vUV;
+
+//------------------------------------------
+//general stuff
+
+//make sure that these two values are the same for your camera, otherwise distances will be wrong.
+
+float znear = 0.3; //Z-near
+float zfar = 100.0; //Z-far
+
+//user variables
+int samples = 1; //ao sample count
+
+float radius = 2.5; //ao radius
+float aoclamp = 0.25; //depth clamp - reduces haloing at screen edges
+bool noise = true; //use noise instead of pattern for sample dithering
+float noiseamount = 0.0002; //dithering amount
+
+float diffarea = 0.25; //self-shadowing reduction
+float gdisplace = 0.4; //gauss bell center
+
+bool mist = false; //use mist?
+float miststart = 0.0; //mist start
+float mistend = 16.0; //mist end
+
+bool onlyAO = true; //use only ambient occlusion pass?
+float lumInfluence = 0.7; //how much luminance affects occlusion
+
+//--------------------------------------------------------
+
+vec2 rand(vec2 coord) //generating noise/pattern texture for dithering
+{
+	float noiseX = ((fract(1.0-coord.s*(width/2.0))*0.25)+(fract(coord.t*(height/2.0))*0.75))*2.0-1.0;
+	float noiseY = ((fract(1.0-coord.s*(width/2.0))*0.75)+(fract(coord.t*(height/2.0))*0.25))*2.0-1.0;
+	
+	if (noise)
+	{
+		noiseX = clamp(fract(sin(dot(coord ,vec2(12.9898,78.233))) * 43758.5453),0.0,1.0)*2.0-1.0;
+		noiseY = clamp(fract(sin(dot(coord ,vec2(12.9898,78.233)*2.0)) * 43758.5453),0.0,1.0)*2.0-1.0;
+	}
+	return vec2(noiseX,noiseY)*noiseamount;
+}
+
+float doMist()
+{
+	float zdepth = texture2D(textureSampler,vUV.xy).x;
+	float depth = -zfar * znear / (zdepth * (zfar - znear) - zfar);
+	return clamp((depth-miststart)/mistend,0.0,1.0);
+}
+
+float readDepth(in vec2 coord) 
+{
+	if (vUV.x<0.0||vUV.y<0.0) return 1.0;
+	return (2.0 * znear) / (zfar + znear - texture2D(textureSampler, coord ).x * (zfar-znear));
+}
+
+float compareDepths(in float depth1, in float depth2,inout int far)
+{   
+	float garea = 2.0; //gauss bell width    
+	float diff = (depth1 - depth2)*100.0; //depth difference (0-100)
+	//reduce left bell width to avoid self-shadowing 
+	if (diff<gdisplace)
+	{
+	garea = diffarea;
+	}else{
+	far = 1;
+	}
+	
+	float gauss = pow(2.7182,-2.0*(diff-gdisplace)*(diff-gdisplace)/(garea*garea));
+	return gauss;
+}   
+
+float calAO(float depth,float dw, float dh)
+{   
+	float dd = (1.0-depth)*radius;
+	
+	float temp = 0.0;
+	float temp2 = 0.0;
+	float coordw = vUV.x + dw*dd;
+	float coordh = vUV.y + dh*dd;
+	float coordw2 = vUV.x - dw*dd;
+	float coordh2 = vUV.y - dh*dd;
+	
+	vec2 coord = vec2(coordw , coordh);
+	vec2 coord2 = vec2(coordw2, coordh2);
+	
+	int far = 0;
+	temp = compareDepths(depth, readDepth(coord),far);
+	//DEPTH EXTRAPOLATION:
+	if (far > 0)
+	{
+		temp2 = compareDepths(readDepth(coord2),depth,far);
+		temp += (1.0-temp)*temp2;
+	}
+	
+	return temp;
+} 
+
+void main(void)
+{
+	vec2 noise = rand(vUV); 
+	float depth = readDepth(vUV);
+	
+	float w = (1.0 / width)/clamp(depth,aoclamp,1.0)+(noise.x*(1.0-noise.x));
+	float h = (1.0 / height)/clamp(depth,aoclamp,1.0)+(noise.y*(1.0-noise.y));
+	
+	float pw;
+	float ph;
+	
+	float ao;
+	
+	float dl = PI*(3.0-sqrt(5.0));
+	float dz = 1.0/float(samples);
+	float l = 0.0;
+	float z = 1.0 - dz/2.0;
+	
+	for (int i = 0; i <= samples; i ++)
+	{     
+		float r = sqrt(1.0-z);
+		
+		pw = cos(l)*r;
+		ph = sin(l)*r;
+		ao += calAO(depth,pw*w,ph*h);        
+		z = z - dz;
+		l = l + dl;
+	}
+	
+	ao /= float(samples);
+	ao = 1.0-ao;	
+	
+	if (mist)
+	{
+	ao = mix(ao, 1.0,doMist());
+	}
+	
+	vec3 color = vec3(0.5, 0.5, 0.5);
+	
+	vec3 lumcoeff = vec3(0.299,0.587,0.114);
+	float lum = dot(color.rgb, lumcoeff);
+	vec3 luminance = vec3(lum, lum, lum);
+	
+	vec3 final = vec3(color*mix(vec3(ao),vec3(1.0),luminance*lumInfluence));//mix(color*ao, white, luminance)
+	
+	if (onlyAO)
+	{
+	final = vec3(mix(vec3(ao),vec3(1.0),luminance*lumInfluence)); //ambient occlusion only
+	}
+	
+	
+	gl_FragColor = vec4(final,1.0); 
+	
+}

+ 5 - 1
src/Shaders/geometry.fragment.fx

@@ -3,6 +3,9 @@
 precision highp float;
 precision highp int;
 
+in vec3 vNormalV;
+//in vec3 vPositionV;
+
 layout(location = 0) out vec4 color0;
 layout(location = 1) out vec4 color1;
 
@@ -11,5 +14,6 @@ uniform float far;
 void main() {
     float depth = (gl_FragCoord.z / gl_FragCoord.w) / far;
     color0 = vec4(depth, depth * depth, 0.0, 1.0);
-    color1 = vec4(1.0, 0.0, 0.0, 1.0);
+    color1 = vec4(normalize(vNormalV), 1.0);
+    //color2 = vec4(vPositionV, 1.0);
 }

+ 5 - 0
src/Shaders/geometry.vertex.fx

@@ -4,12 +4,17 @@ precision highp float;
 precision highp int;
 
 in vec3 position;
+in vec3 normal;
 
 // Uniform
 uniform mat4 viewProjection;
 uniform mat4 world;
+uniform mat4 view;
+
+out vec3 vNormalV;
 
 void main(void)
 {
+	vNormalV = normalize(vec3((view * world) * vec4(normal, 0.0)));
 	gl_Position = viewProjection * world * vec4(position, 1.0);
 }

+ 24 - 8
src/Shaders/ssao.fragment.fx

@@ -5,6 +5,7 @@ varying vec2 vUV;
 
 #ifdef SSAO
 uniform sampler2D randomSampler;
+uniform sampler2D normalSampler;
 
 uniform float randTextureTiles;
 uniform float samplesFactor;
@@ -17,7 +18,7 @@ uniform float fallOff;
 uniform float base;
 
 vec3 normalFromDepth(float depth, vec2 coords)
-{
+{	
 	vec2 offset1 = vec2(0.0, radius);
 	vec2 offset2 = vec2(radius, 0.0);
 
@@ -33,12 +34,25 @@ vec3 normalFromDepth(float depth, vec2 coords)
 	return normalize(normal);
 }
 
+float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {
+	return ( near * far ) / ( ( far - near ) * invClipZ - far );
+}
+
+float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
+	return ( viewZ + near ) / ( near - far );
+}
+
 void main()
 {
 	vec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);
 	float depth = texture2D(textureSampler, vUV).r;
+	float n = 0.1;                                // the near plane
+	float f = 10.0;
+	depth = perspectiveDepthToViewZ(depth, n, f);
+	depth = viewZToOrthographicDepth(depth, n, f);
+	// depth = (2.0 * n * f) / (f + n - (2.0 * depth - 1.0) * (f - n));  // convert to linear values 
 	vec3 position = vec3(vUV, depth);
-	vec3 normal = normalFromDepth(depth, vUV);
+	vec3 normal = texture2D(normalSampler, vUV).rgb;//normalFromDepth(depth, vUV); 
 	float radiusDepth = radius / depth;
 	float occlusion = 0.0;
 
@@ -49,10 +63,10 @@ void main()
 
 	for (int i = 0; i < SAMPLES; i++)
 	{
-		ray = radiusDepth * reflect(sampleSphere[i], random);
+		ray = clamp(radiusDepth * reflect(sampleSphere[i], random), vec3(-0.002, -0.002, -1000), vec3(0.002, 0.002, 1000));
 		hemiRay = position + sign(dot(ray, normal)) * ray;
 
-		occlusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;
+		occlusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999) )).r;
 		difference = depth - occlusionDepth;
 
 		occlusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));
@@ -61,10 +75,12 @@ void main()
 	float ao = 1.0 - totalStrength * occlusion * samplesFactor;
 	float result = clamp(ao + base, 0.0, 1.0);
 
-	gl_FragColor.r = result;
-	gl_FragColor.g = result;
-	gl_FragColor.b = result;
-	gl_FragColor.a = 1.0;
+	// gl_FragColor.r = result;
+	// gl_FragColor.g = result;
+	// gl_FragColor.b = result;
+	// gl_FragColor.a = 1.0;
+	// gl_FragColor = vec4(depth, depth, depth, 1.0);
+	gl_FragColor = texture2D(textureSampler, vUV);
 }
 #endif
 

+ 1 - 1
src/Shaders/ssaoCombine.fragment.fx

@@ -7,5 +7,5 @@ void main(void) {
 	vec4 ssaoColor = texture2D(textureSampler, vUV);
 	vec4 sceneColor = texture2D(originalColor, vUV);
 
-	gl_FragColor = sceneColor * ssaoColor;
+	gl_FragColor = ssaoColor;
 }

+ 58 - 3
src/babylon.engine.ts

@@ -2668,6 +2668,14 @@
             var framebuffer = gl.createFramebuffer();
             this.bindUnboundFramebuffer(framebuffer);
 
+            var colorRenderbuffer = gl.createRenderbuffer();
+            gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
+            gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 16, gl.RGBA8, width, height);
+            gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
+            gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
+            gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.RENDERBUFFER, colorRenderbuffer);
+            gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, colorRenderbuffer);
+
             var width = size.width || size;
             var height = size.height || size;
             var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
@@ -2697,7 +2705,7 @@
             
                 gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
 
-                texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
+                // texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
 
                 if (generateMipMaps) {
                     this._gl.generateMipmap(this._gl.TEXTURE_2D);
@@ -2705,8 +2713,6 @@
 
                 // Unbind
                 this._bindTextureDirectly(gl.TEXTURE_2D, null);
-                gl.bindRenderbuffer(gl.RENDERBUFFER, null);
-                this.bindUnboundFramebuffer(null);
 
                 texture._framebuffer = framebuffer;
                 texture._baseWidth = width;
@@ -2723,7 +2729,56 @@
                 texture._generateStencilBuffer = generateStencilBuffer;
             }
 
+            if (generateDepthBuffer) {
+                // Depth texture
+                var depthTexture = gl.createTexture();
+
+                gl.activeTexture(gl.TEXTURE0);
+                gl.bindTexture(gl.TEXTURE_2D, depthTexture);
+                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+                gl.texImage2D(
+                    gl.TEXTURE_2D,
+                    0,
+                    gl.DEPTH_COMPONENT16,
+                    width,
+                    height,
+                    0,
+                    gl.DEPTH_COMPONENT,
+                    gl.UNSIGNED_SHORT,
+                    null
+                );
+
+                gl.framebufferTexture2D(
+                    gl.FRAMEBUFFER,
+                    gl.DEPTH_ATTACHMENT,
+                    gl.TEXTURE_2D,
+                    depthTexture,
+                    0
+                );
+
+                depthTexture._framebuffer = framebuffer;
+                depthTexture._baseWidth = width;
+                depthTexture._baseHeight = height;
+                depthTexture._width = width;
+                depthTexture._height = height;
+                depthTexture.isReady = true;
+                depthTexture.samples = 1;
+                depthTexture.generateMipMaps = generateMipMaps;
+                depthTexture.references = 1;
+                depthTexture.samplingMode = gl.NEAREST;
+                // depthTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
+                depthTexture._generateDepthBuffer = generateDepthBuffer;
+                depthTexture._generateStencilBuffer = generateStencilBuffer;
+
+                textures.push(depthTexture)
+            }
+
             gl.drawBuffers(attachments);
+            gl.bindRenderbuffer(gl.RENDERBUFFER, null);
+            this.bindUnboundFramebuffer(null);
 
             this.resetTextureCache();
 

+ 2 - 0
src/babylon.mixins.ts

@@ -52,6 +52,8 @@ interface WebGLRenderingContext {
 
     /* Multiple Render Targets */
     drawBuffers(buffers: number[]): void;
+    readBuffer(src: number): void;
+
 
     readonly COLOR_ATTACHMENT0: number;                             // 0x8CE1
     readonly COLOR_ATTACHMENT1: number;                             // 0x8CE2