Browse Source

Merge pull request #7940 from Popov72/shadowdepthmat

Allow to use a custom shadow depth material for shadow rendering
David Catuhe 5 years ago
parent
commit
992c39df8d

+ 1 - 0
Tools/Gulp/helpers/gulp-processShaders.js

@@ -109,6 +109,7 @@ function main(isCore) {
             if (isCore) {
                 if (isInclude) {
                     effectLocation = "../../Materials/effect";
+                    includeText = includeText.replace(/ShadersInclude\//g, "");
                 }
                 else {
                     effectLocation = "../Materials/effect";

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

@@ -3,6 +3,7 @@
 ## Major updates
 
 - Added particle editor to the Inspector ([Deltakosh](https://github.com/deltakosh)
+- Added the `ShadowDepthWrapper` class to support accurate shadow generation for custom as well as node material shaders ([Popov72](https://github.com/Popov72))
 
 ## Updates
 

+ 11 - 2
materialsLibrary/src/custom/customMaterial.ts

@@ -1,6 +1,6 @@
 import { Texture } from "babylonjs/Materials/Textures/texture";
 import { Effect } from "babylonjs/Materials/effect";
-import { StandardMaterialDefines } from "babylonjs/Materials/standardMaterial";
+import { MaterialDefines } from "babylonjs/Materials/materialDefines";
 import { StandardMaterial } from "babylonjs/Materials/standardMaterial";
 import { Mesh } from "babylonjs/Meshes/mesh";
 import { Scene } from "babylonjs/scene";
@@ -43,6 +43,9 @@ export class ShaderSpecialParts {
     // normalUpdated
     public Vertex_Before_NormalUpdated: string;
 
+    // worldPosComputed
+    public Vertex_After_WorldPosComputed: string;
+
     // mainEnd
     public Vertex_MainEnd: string;
 }
@@ -106,7 +109,7 @@ export class CustomMaterial extends StandardMaterial {
         return arr; 
     }
 
-    public Builder(shaderName: string, uniforms: string[], uniformBuffers: string[], samplers: string[], defines: StandardMaterialDefines, attributes?: string[]): string {
+    public Builder(shaderName: string, uniforms: string[], uniformBuffers: string[], samplers: string[], defines: MaterialDefines | string[], attributes?: string[]): string {
 
         if (attributes && this._customAttributes && this._customAttributes.length > 0) {
             attributes.push(...this._customAttributes);
@@ -139,6 +142,7 @@ export class CustomMaterial extends StandardMaterial {
             .replace('#define CUSTOM_VERTEX_MAIN_BEGIN', (this.CustomParts.Vertex_MainBegin ? this.CustomParts.Vertex_MainBegin : ""))
             .replace('#define CUSTOM_VERTEX_UPDATE_POSITION', (this.CustomParts.Vertex_Before_PositionUpdated ? this.CustomParts.Vertex_Before_PositionUpdated : ""))
             .replace('#define CUSTOM_VERTEX_UPDATE_NORMAL', (this.CustomParts.Vertex_Before_NormalUpdated ? this.CustomParts.Vertex_Before_NormalUpdated : ""))
+            .replace('#define CUSTOM_VERTEX_UPDATE_WORLDPOS', (this.CustomParts.Vertex_After_WorldPosComputed ? this.CustomParts.Vertex_After_WorldPosComputed : ""))
             .replace('#define CUSTOM_VERTEX_MAIN_END', (this.CustomParts.Vertex_MainEnd ? this.CustomParts.Vertex_MainEnd : ""));
 
         Effect.ShadersStore[name + "PixelShader"] = this.FragmentShader
@@ -262,6 +266,11 @@ export class CustomMaterial extends StandardMaterial {
         return this;
     }
 
+    public Vertex_After_WorldPosComputed(shaderPart: string): CustomMaterial {
+        this.CustomParts.Vertex_After_WorldPosComputed = shaderPart;
+        return this;
+    }
+
     public Vertex_MainEnd(shaderPart: string): CustomMaterial {
         this.CustomParts.Vertex_MainEnd = shaderPart;
         return this;

+ 11 - 2
materialsLibrary/src/custom/pbrCustomMaterial.ts

@@ -1,6 +1,6 @@
 import { Texture } from "babylonjs/Materials/Textures/texture";
 import { Effect } from "babylonjs/Materials/effect";
-import { PBRMaterialDefines } from "babylonjs/Materials/PBR/pbrBaseMaterial";
+import { MaterialDefines } from "babylonjs/Materials/materialDefines";
 import { PBRMaterial } from "babylonjs/Materials/PBR/pbrMaterial";
 import { Mesh } from "babylonjs/Meshes/mesh";
 import { Scene } from "babylonjs/scene";
@@ -39,6 +39,9 @@ export class ShaderAlebdoParts {
     // normalUpdated
     public Vertex_Before_NormalUpdated: string;
 
+    // worldPosComputed
+    public Vertex_After_WorldPosComputed: string;
+
     // mainEnd
     public Vertex_MainEnd: string;
 }
@@ -102,7 +105,7 @@ export class PBRCustomMaterial extends PBRMaterial {
         return arr; 
     }
 
-    public Builder(shaderName: string, uniforms: string[], uniformBuffers: string[], samplers: string[], defines: PBRMaterialDefines, attributes?: string[]): string {
+    public Builder(shaderName: string, uniforms: string[], uniformBuffers: string[], samplers: string[], defines: MaterialDefines | string[], attributes?: string[]): string {
 
         if (attributes && this._customAttributes && this._customAttributes.length > 0) {
             attributes.push(...this._customAttributes);
@@ -135,6 +138,7 @@ export class PBRCustomMaterial extends PBRMaterial {
             .replace('#define CUSTOM_VERTEX_MAIN_BEGIN', (this.CustomParts.Vertex_MainBegin ? this.CustomParts.Vertex_MainBegin : ""))
             .replace('#define CUSTOM_VERTEX_UPDATE_POSITION', (this.CustomParts.Vertex_Before_PositionUpdated ? this.CustomParts.Vertex_Before_PositionUpdated : ""))
             .replace('#define CUSTOM_VERTEX_UPDATE_NORMAL', (this.CustomParts.Vertex_Before_NormalUpdated ? this.CustomParts.Vertex_Before_NormalUpdated : ""))
+            .replace('#define CUSTOM_VERTEX_UPDATE_WORLDPOS', (this.CustomParts.Vertex_After_WorldPosComputed ? this.CustomParts.Vertex_After_WorldPosComputed : ""))
             .replace('#define CUSTOM_VERTEX_MAIN_END', (this.CustomParts.Vertex_MainEnd ? this.CustomParts.Vertex_MainEnd : ""));
 
         Effect.ShadersStore[name + "PixelShader"] = this.FragmentShader
@@ -270,6 +274,11 @@ export class PBRCustomMaterial extends PBRMaterial {
         return this;
     }
 
+    public Vertex_After_WorldPosComputed(shaderPart: string): PBRCustomMaterial {
+        this.CustomParts.Vertex_After_WorldPosComputed = shaderPart;
+        return this;
+    }
+
     public Vertex_MainEnd(shaderPart: string): PBRCustomMaterial {
         this.CustomParts.Vertex_MainEnd = shaderPart;
         return this;

+ 8 - 1
src/Engines/Processors/shaderProcessor.ts

@@ -288,6 +288,7 @@ export class ShaderProcessor {
         var match = regex.exec(sourceCode);
 
         var returnValue = new String(sourceCode);
+        var keepProcessing = false;
 
         while (match != null) {
             var includeFile = match[1];
@@ -352,6 +353,8 @@ export class ShaderProcessor {
 
                 // Replace
                 returnValue = returnValue.replace(match[0], includeContent);
+
+                keepProcessing = keepProcessing || includeContent.indexOf("#include<") >= 0;
             } else {
                 var includeShaderUrl = options.shadersRepository + "ShadersInclude/" + includeFile + ".fx";
 
@@ -365,7 +368,11 @@ export class ShaderProcessor {
             match = regex.exec(sourceCode);
         }
 
-        callback(returnValue);
+        if (keepProcessing) {
+            this._ProcessIncludes(returnValue.toString(), options, callback);
+        } else {
+            callback(returnValue);
+        }
     }
 
     /**

+ 2 - 2
src/Engines/thinEngine.ts

@@ -2012,8 +2012,8 @@ export class ThinEngine {
     public createEffect(baseName: any, attributesNamesOrOptions: string[] | IEffectCreationOptions, uniformsNamesOrEngine: string[] | ThinEngine, samplers?: string[], defines?: string,
         fallbacks?: IEffectFallbacks,
         onCompiled?: Nullable<(effect: Effect) => void>, onError?: Nullable<(effect: Effect, errors: string) => void>, indexParameters?: any): Effect {
-        var vertex = baseName.vertexElement || baseName.vertex || baseName;
-        var fragment = baseName.fragmentElement || baseName.fragment || baseName;
+        var vertex = baseName.vertexElement || baseName.vertex || baseName.vertexToken || baseName;
+        var fragment = baseName.fragmentElement || baseName.fragment || baseName.fragmentToken || baseName;
 
         var name = vertex + "+" + fragment + "@" + (defines ? defines : (<IEffectCreationOptions>attributesNamesOrOptions).defines);
         if (this._compiledEffects[name]) {

+ 13 - 5
src/Lights/Shadows/cascadedShadowGenerator.ts

@@ -797,6 +797,12 @@ export class CascadedShadowGenerator extends ShadowGenerator {
 
         this._shadowMap.onBeforeRenderObservable.add((layer: number) => {
             this._currentLayer = layer;
+            if (this._scene.getSceneUniformBuffer().useUbo) {
+                const sceneUBO = this._scene.getSceneUniformBuffer();
+                sceneUBO.updateMatrix("viewProjection", this.getCascadeTransformMatrix(layer)!);
+                sceneUBO.updateMatrix("view", this.getCascadeViewMatrix(layer)!);
+                sceneUBO.update();
+            }
         });
 
         this._shadowMap.onBeforeBindObservable.add(() => {
@@ -809,14 +815,16 @@ export class CascadedShadowGenerator extends ShadowGenerator {
         this._splitFrustum();
     }
 
-    protected _bindCustomEffectForRenderSubMeshForShadowMap(subMesh: SubMesh, effect: Effect): void {
-        effect.setMatrix("viewProjection", this.getCascadeTransformMatrix(this._currentLayer)!);
+    protected _bindCustomEffectForRenderSubMeshForShadowMap(subMesh: SubMesh, effect: Effect, matriceNames: any): void {
+        effect.setMatrix(matriceNames?.viewProjection ?? "viewProjection", this.getCascadeTransformMatrix(this._currentLayer)!);
+
+        effect.setMatrix(matriceNames?.view ?? "view", this.getCascadeViewMatrix(this._currentLayer)!);
+
+        effect.setMatrix(matriceNames?.projection ?? "projection", this.getCascadeProjectionMatrix(this._currentLayer)!);
     }
 
     protected _isReadyCustomDefines(defines: any, subMesh: SubMesh, useInstances: boolean): void {
-        if (this._depthClamp && this._filter !== ShadowGenerator.FILTER_PCSS) {
-            defines.push("#define DEPTHCLAMP");
-        }
+        defines.push("#define SM_DEPTHCLAMP " + (this._depthClamp && this._filter !== ShadowGenerator.FILTER_PCSS ? "1" : "0"));
     }
 
     /**

+ 218 - 180
src/Lights/Shadows/shadowGenerator.ts

@@ -885,10 +885,23 @@ export class ShadowGenerator implements IShadowGenerator {
             if (this._filter === ShadowGenerator.FILTER_PCF) {
                 engine.setColorWrite(false);
             }
+            if (this._scene.getSceneUniformBuffer().useUbo) {
+                const sceneUBO = this._scene.getSceneUniformBuffer();
+                sceneUBO.updateMatrix("viewProjection", this.getTransformMatrix());
+                sceneUBO.updateMatrix("view", this._viewMatrix);
+                sceneUBO.update();
+            }
         });
 
         // Blur if required afer render.
         this._shadowMap.onAfterUnbindObservable.add(() => {
+            if (this._scene.getSceneUniformBuffer().useUbo) {
+                const sceneUBO = this._scene.getSceneUniformBuffer();
+                sceneUBO.updateMatrix("viewProjection", this._scene.getTransformMatrix());
+                sceneUBO.updateMatrix("view", this._scene.getViewMatrix());
+                sceneUBO.update();
+            }
+
             if (this._filter === ShadowGenerator.FILTER_PCF) {
                 engine.setColorWrite(true);
             }
@@ -1004,7 +1017,12 @@ export class ShadowGenerator implements IShadowGenerator {
         }
     }
 
-    protected _bindCustomEffectForRenderSubMeshForShadowMap(subMesh: SubMesh, effect: Effect): void {
+    protected _bindCustomEffectForRenderSubMeshForShadowMap(subMesh: SubMesh, effect: Effect, matriceNames: any): void {
+        effect.setMatrix(matriceNames?.viewProjection ?? "viewProjection", this.getTransformMatrix());
+
+        effect.setMatrix(matriceNames?.view ?? "view", this._viewMatrix);
+
+        effect.setMatrix(matriceNames?.projection ?? "projection", this._projectionMatrix);
     }
 
     protected _renderSubMeshForShadowMap(subMesh: SubMesh): void {
@@ -1033,57 +1051,68 @@ export class ShadowGenerator implements IShadowGenerator {
 
         var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
         if (this.isReady(subMesh, hardwareInstancedRendering)) {
-            engine.enableEffect(this._effect);
-            renderingMesh._bind(subMesh, this._effect, material.fillMode);
+            const shadowDepthWrapper = renderingMesh.material?.shadowDepthWrapper;
+
+            let effect = shadowDepthWrapper?.getEffect(subMesh, this) ?? this._effect;
+
+            engine.enableEffect(effect);
 
-            this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
+            renderingMesh._bind(subMesh, effect, material.fillMode);
+
+            effect.setFloat3("biasAndScaleSM", this.bias, this.normalBias, this.depthScale);
 
-            this._effect.setMatrix("viewProjection", this.getTransformMatrix());
             if (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
-                this._effect.setVector3("lightData", this._cachedDirection);
+                effect.setVector3("lightDataSM", this._cachedDirection);
             }
             else {
-                this._effect.setVector3("lightData", this._cachedPosition);
+                effect.setVector3("lightDataSM", this._cachedPosition);
             }
 
             if (scene.activeCamera) {
-                this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
+                effect.setFloat2("depthValuesSM", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
             }
 
-            // Alpha test
-            if (material && material.needAlphaTesting()) {
-                var alphaTexture = material.getAlphaTestTexture();
-                if (alphaTexture) {
-                    this._effect.setTexture("diffuseSampler", alphaTexture);
-                    this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
+            if (shadowDepthWrapper) {
+                subMesh._effectOverride = effect;
+                material.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh);
+                subMesh._effectOverride = null;
+            } else {
+                effect.setMatrix("viewProjection", this.getTransformMatrix());
+                // Alpha test
+                if (material && material.needAlphaTesting()) {
+                    var alphaTexture = material.getAlphaTestTexture();
+                    if (alphaTexture) {
+                        effect.setTexture("diffuseSampler", alphaTexture);
+                        effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
+                    }
                 }
-            }
 
-            // Bones
-            if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {
-                const skeleton = renderingMesh.skeleton;
+                // Bones
+                if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {
+                    const skeleton = renderingMesh.skeleton;
 
-                if (skeleton.isUsingTextureForMatrices) {
-                    const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh);
+                    if (skeleton.isUsingTextureForMatrices) {
+                        const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh);
 
-                    if (!boneTexture) {
-                        return;
-                    }
+                        if (!boneTexture) {
+                            return;
+                        }
 
-                    this._effect.setTexture("boneSampler", boneTexture);
-                    this._effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
-                } else {
-                    this._effect.setMatrices("mBones", skeleton.getTransformMatrices((renderingMesh)));
+                        effect.setTexture("boneSampler", boneTexture);
+                        effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
+                    } else {
+                        effect.setMatrices("mBones", skeleton.getTransformMatrices((renderingMesh)));
+                    }
                 }
-            }
 
-            // Morph targets
-            MaterialHelper.BindMorphTargetParameters(renderingMesh, this._effect);
+                // Morph targets
+                MaterialHelper.BindMorphTargetParameters(renderingMesh, effect);
 
-            // Clip planes
-            MaterialHelper.BindClipPlane(this._effect, scene);
+                // Clip planes
+                MaterialHelper.BindClipPlane(effect, scene);
+            }
 
-            this._bindCustomEffectForRenderSubMeshForShadowMap(subMesh, this._effect);
+            this._bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, shadowDepthWrapper?._matriceNames);
 
             if (this.forceBackFacesOnly) {
                 engine.setState(true, 0, false, true);
@@ -1091,20 +1120,19 @@ export class ShadowGenerator implements IShadowGenerator {
 
             // Observables
             this.onBeforeShadowMapRenderMeshObservable.notifyObservers(renderingMesh);
-            this.onBeforeShadowMapRenderObservable.notifyObservers(this._effect);
+            this.onBeforeShadowMapRenderObservable.notifyObservers(effect);
 
             // Draw
-            renderingMesh._processRendering(effectiveMesh, subMesh, this._effect, material.fillMode, batch, hardwareInstancedRendering,
-                (isInstance, world) => this._effect.setMatrix("world", world));
+            renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering,
+                (isInstance, world) => effect.setMatrix("world", world));
 
             if (this.forceBackFacesOnly) {
                 engine.setState(true, 0, false, false);
             }
 
             // Observables
-            this.onAfterShadowMapRenderObservable.notifyObservers(this._effect);
+            this.onAfterShadowMapRenderObservable.notifyObservers(effect);
             this.onAfterShadowMapRenderMeshObservable.notifyObservers(renderingMesh);
-
         } else {
             // Need to reset refresh rate of the shadowMap
             if (this._shadowMap) {
@@ -1201,6 +1229,27 @@ export class ShadowGenerator implements IShadowGenerator {
     protected _isReadyCustomDefines(defines: any, subMesh: SubMesh, useInstances: boolean): void {
     }
 
+    private _prepareShadowDefines(subMesh: SubMesh, useInstances: boolean, defines: string[]): string[] {
+        defines.push("#define SM_FLOAT " + (this._textureType !== Constants.TEXTURETYPE_UNSIGNED_INT ? "1" : "0"));
+
+        defines.push("#define SM_ESM " + (this.useExponentialShadowMap || this.useBlurExponentialShadowMap ? "1" : "0"));
+
+        defines.push("#define SM_DEPTHTEXTURE " + (this.usePercentageCloserFiltering || this.useContactHardeningShadow ? "1" : "0"));
+
+        var mesh = subMesh.getMesh();
+
+        // Normal bias.
+        defines.push("#define SM_NORMALBIAS " + (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind) ? "1" : "0"));
+        defines.push("#define SM_DIRECTIONINLIGHTDATA " + (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT ? "1" : "0"));
+
+        // Point light
+        defines.push("#define SM_USEDISTANCE " + (this._light.needCube() ? "1" : "0"));
+
+        this._isReadyCustomDefines(defines, subMesh, useInstances);
+
+        return defines;
+    }
+
     /**
      * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
      * @param subMesh The submesh we want to render in the shadow map
@@ -1208,182 +1257,171 @@ export class ShadowGenerator implements IShadowGenerator {
      * @returns true if ready otherwise, false
      */
     public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
-        var defines = [];
+        const material = subMesh.getMaterial(),
+              shadowDepthWrapper = material?.shadowDepthWrapper;
 
-        if (this._textureType !== Constants.TEXTURETYPE_UNSIGNED_INT) {
-            defines.push("#define FLOAT");
-        }
+        const defines: string[] = [];
 
-        if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
-            defines.push("#define ESM");
-        }
-        else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
-            defines.push("#define DEPTHTEXTURE");
-        }
+        this._prepareShadowDefines(subMesh, useInstances, defines);
 
-        var attribs = [VertexBuffer.PositionKind];
+        if (shadowDepthWrapper) {
+            if (!shadowDepthWrapper.isReadyForSubMesh(subMesh, defines, this, useInstances)) {
+                return false;
+            }
+        } else {
+            var attribs = [VertexBuffer.PositionKind];
 
-        var mesh = subMesh.getMesh();
-        var material = subMesh.getMaterial();
+            var mesh = subMesh.getMesh();
 
-        // Normal bias.
-        if (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
-            attribs.push(VertexBuffer.NormalKind);
-            defines.push("#define NORMAL");
-            if (mesh.nonUniformScaling) {
-                defines.push("#define NONUNIFORMSCALING");
-            }
-            if (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
-                defines.push("#define DIRECTIONINLIGHTDATA");
+            // Normal bias.
+            if (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
+                attribs.push(VertexBuffer.NormalKind);
+                defines.push("#define NORMAL");
+                if (mesh.nonUniformScaling) {
+                    defines.push("#define NONUNIFORMSCALING");
+                }
             }
-        }
 
-        // Alpha test
-        if (material && material.needAlphaTesting()) {
-            var alphaTexture = material.getAlphaTestTexture();
-            if (alphaTexture) {
-                defines.push("#define ALPHATEST");
-                if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
-                    attribs.push(VertexBuffer.UVKind);
-                    defines.push("#define UV1");
-                }
-                if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
-                    if (alphaTexture.coordinatesIndex === 1) {
-                        attribs.push(VertexBuffer.UV2Kind);
-                        defines.push("#define UV2");
+            // Alpha test
+            if (material && material.needAlphaTesting()) {
+                var alphaTexture = material.getAlphaTestTexture();
+                if (alphaTexture) {
+                    defines.push("#define ALPHATEST");
+                    if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
+                        attribs.push(VertexBuffer.UVKind);
+                        defines.push("#define UV1");
+                    }
+                    if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
+                        if (alphaTexture.coordinatesIndex === 1) {
+                            attribs.push(VertexBuffer.UV2Kind);
+                            defines.push("#define UV2");
+                        }
                     }
                 }
             }
-        }
 
-        // Bones
-        const fallbacks = new EffectFallbacks();
-        if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
-            attribs.push(VertexBuffer.MatricesIndicesKind);
-            attribs.push(VertexBuffer.MatricesWeightsKind);
-            if (mesh.numBoneInfluencers > 4) {
-                attribs.push(VertexBuffer.MatricesIndicesExtraKind);
-                attribs.push(VertexBuffer.MatricesWeightsExtraKind);
-            }
-            const skeleton = mesh.skeleton;
-            defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
-            if (mesh.numBoneInfluencers > 0) {
-                fallbacks.addCPUSkinningFallback(0, mesh);
-            }
+            // Bones
+            const fallbacks = new EffectFallbacks();
+            if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
+                attribs.push(VertexBuffer.MatricesIndicesKind);
+                attribs.push(VertexBuffer.MatricesWeightsKind);
+                if (mesh.numBoneInfluencers > 4) {
+                    attribs.push(VertexBuffer.MatricesIndicesExtraKind);
+                    attribs.push(VertexBuffer.MatricesWeightsExtraKind);
+                }
+                const skeleton = mesh.skeleton;
+                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
+                if (mesh.numBoneInfluencers > 0) {
+                    fallbacks.addCPUSkinningFallback(0, mesh);
+                }
+
+                if (skeleton.isUsingTextureForMatrices) {
+                    defines.push("#define BONETEXTURE");
+                } else {
+                    defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
+                }
 
-            if (skeleton.isUsingTextureForMatrices) {
-                defines.push("#define BONETEXTURE");
             } else {
-                defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
+                defines.push("#define NUM_BONE_INFLUENCERS 0");
             }
 
-        } else {
-            defines.push("#define NUM_BONE_INFLUENCERS 0");
-        }
-
-        // Morph targets
-        var manager = (<Mesh>mesh).morphTargetManager;
-        let morphInfluencers = 0;
-        if (manager) {
-            if (manager.numInfluencers > 0) {
-                defines.push("#define MORPHTARGETS");
-                morphInfluencers = manager.numInfluencers;
-                defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
-                MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, morphInfluencers);
+            // Morph targets
+            var manager = (<Mesh>mesh).morphTargetManager;
+            let morphInfluencers = 0;
+            if (manager) {
+                if (manager.numInfluencers > 0) {
+                    defines.push("#define MORPHTARGETS");
+                    morphInfluencers = manager.numInfluencers;
+                    defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
+                    MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, morphInfluencers);
+                }
             }
-        }
 
-        // ClipPlanes
-        const scene = this._scene;
-        if (scene.clipPlane) {
-            defines.push("#define CLIPPLANE");
-        }
-        if (scene.clipPlane2) {
-            defines.push("#define CLIPPLANE2");
-        }
-        if (scene.clipPlane3) {
-            defines.push("#define CLIPPLANE3");
-        }
-        if (scene.clipPlane4) {
-            defines.push("#define CLIPPLANE4");
-        }
-        if (scene.clipPlane5) {
-            defines.push("#define CLIPPLANE5");
-        }
-        if (scene.clipPlane6) {
-            defines.push("#define CLIPPLANE6");
-        }
+            // ClipPlanes
+            const scene = this._scene;
+            if (scene.clipPlane) {
+                defines.push("#define CLIPPLANE");
+            }
+            if (scene.clipPlane2) {
+                defines.push("#define CLIPPLANE2");
+            }
+            if (scene.clipPlane3) {
+                defines.push("#define CLIPPLANE3");
+            }
+            if (scene.clipPlane4) {
+                defines.push("#define CLIPPLANE4");
+            }
+            if (scene.clipPlane5) {
+                defines.push("#define CLIPPLANE5");
+            }
+            if (scene.clipPlane6) {
+                defines.push("#define CLIPPLANE6");
+            }
 
-        // Instances
-        if (useInstances) {
-            defines.push("#define INSTANCES");
-            MaterialHelper.PushAttributesForInstances(attribs);
-        }
+            // Instances
+            if (useInstances) {
+                defines.push("#define INSTANCES");
+                MaterialHelper.PushAttributesForInstances(attribs);
+            }
 
-        if (this.customShaderOptions) {
-            if (this.customShaderOptions.defines) {
-                for (var define of this.customShaderOptions.defines) {
-                    if (defines.indexOf(define) === -1) {
-                        defines.push(define);
+            if (this.customShaderOptions) {
+                if (this.customShaderOptions.defines) {
+                    for (var define of this.customShaderOptions.defines) {
+                        if (defines.indexOf(define) === -1) {
+                            defines.push(define);
+                        }
                     }
                 }
             }
-        }
-
-        // Point light
-        if (this._light.needCube()) {
-            defines.push("#define USEDISTANCE");
-        }
 
-        this._isReadyCustomDefines(defines, subMesh, useInstances);
-
-        // Get correct effect
-        var join = defines.join("\n");
-        if (this._cachedDefines !== join) {
-            this._cachedDefines = join;
-
-            let shaderName = "shadowMap";
-            let uniforms = ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences", "boneTextureWidth",
-                            "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6"];
-            let samplers = ["diffuseSampler", "boneSampler"];
-
-            // Custom shader?
-            if (this.customShaderOptions) {
-                shaderName = this.customShaderOptions.shaderName;
-
-                if (this.customShaderOptions.attributes) {
-                    for (var attrib of this.customShaderOptions.attributes) {
-                        if (attribs.indexOf(attrib) === -1) {
-                            attribs.push(attrib);
+            // Get correct effect
+            var join = defines.join("\n");
+            if (this._cachedDefines !== join) {
+                this._cachedDefines = join;
+
+                let shaderName = "shadowMap";
+                let uniforms = ["world", "mBones", "viewProjection", "diffuseMatrix", "lightDataSM", "depthValuesSM", "biasAndScaleSM", "morphTargetInfluences", "boneTextureWidth",
+                                "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6"];
+                let samplers = ["diffuseSampler", "boneSampler"];
+
+                // Custom shader?
+                if (this.customShaderOptions) {
+                    shaderName = this.customShaderOptions.shaderName;
+
+                    if (this.customShaderOptions.attributes) {
+                        for (var attrib of this.customShaderOptions.attributes) {
+                            if (attribs.indexOf(attrib) === -1) {
+                                attribs.push(attrib);
+                            }
                         }
                     }
-                }
 
-                if (this.customShaderOptions.uniforms) {
-                    for (var uniform of this.customShaderOptions.uniforms) {
-                        if (uniforms.indexOf(uniform) === -1) {
-                            uniforms.push(uniform);
+                    if (this.customShaderOptions.uniforms) {
+                        for (var uniform of this.customShaderOptions.uniforms) {
+                            if (uniforms.indexOf(uniform) === -1) {
+                                uniforms.push(uniform);
+                            }
                         }
                     }
-                }
 
-                if (this.customShaderOptions.samplers) {
-                    for (var sampler of this.customShaderOptions.samplers) {
-                        if (samplers.indexOf(sampler) === -1) {
-                            samplers.push(sampler);
+                    if (this.customShaderOptions.samplers) {
+                        for (var sampler of this.customShaderOptions.samplers) {
+                            if (samplers.indexOf(sampler) === -1) {
+                                samplers.push(sampler);
+                            }
                         }
                     }
                 }
-            }
 
-            this._effect = this._scene.getEngine().createEffect(shaderName,
-                attribs, uniforms,
-                samplers, join,
-                fallbacks, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
-        }
+                this._effect = this._scene.getEngine().createEffect(shaderName,
+                    attribs, uniforms,
+                    samplers, join,
+                    fallbacks, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
+            }
 
-        if (!this._effect.isReady()) {
-            return false;
+            if (!this._effect.isReady()) {
+                return false;
+            }
         }
 
         if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {

+ 9 - 0
src/Materials/Node/nodeMaterial.ts

@@ -29,6 +29,9 @@ import { TextureBlock } from './Blocks/Dual/textureBlock';
 import { ReflectionTextureBlock } from './Blocks/Dual/reflectionTextureBlock';
 import { EffectFallbacks } from '../effectFallbacks';
 import { WebRequest } from '../../Misc/webRequest';
+import { Effect } from '../effect';
+
+const onCreatedEffectParameters = { effect: null as unknown as Effect, subMesh: null as unknown as Nullable<SubMesh> };
 
 // declare NODEEDITOR namespace for compilation issue
 declare var NODEEDITOR: any;
@@ -818,6 +821,12 @@ export class NodeMaterial extends PushMaterial {
             }, engine);
 
             if (effect) {
+                if (this._onEffectCreatedObservable) {
+                    onCreatedEffectParameters.effect = effect;
+                    onCreatedEffectParameters.subMesh = subMesh;
+                    this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);
+                }
+
                 // Use previous effect while new one is compiling
                 if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
                     effect = previousEffect;

+ 13 - 5
src/Materials/PBR/pbrBaseMaterial.ts

@@ -39,6 +39,8 @@ import "../../Shaders/pbr.fragment";
 import "../../Shaders/pbr.vertex";
 import { EffectFallbacks } from '../effectFallbacks';
 
+const onCreatedEffectParameters = { effect: null as unknown as Effect, subMesh: null as unknown as Nullable<SubMesh> };
+
 /**
  * Manages the defines for the PBR Material.
  * @hidden
@@ -745,11 +747,6 @@ export abstract class PBRBaseMaterial extends PushMaterial {
      */
     public readonly subSurface = new PBRSubSurfaceConfiguration(this._markAllSubMeshesAsTexturesDirty.bind(this));
 
-    /**
-     * Custom callback helping to override the default shader used in the material.
-     */
-    public customShaderNameResolve: (shaderName: string, uniforms: string[], uniformBuffers: string[], samplers: string[], defines: PBRMaterialDefines, attributes?: string[]) => string;
-
     protected _rebuildInParallel = false;
 
     /**
@@ -987,6 +984,12 @@ export abstract class PBRBaseMaterial extends PushMaterial {
         let effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
 
         if (effect) {
+            if (this._onEffectCreatedObservable) {
+                onCreatedEffectParameters.effect = effect;
+                onCreatedEffectParameters.subMesh = subMesh;
+                this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);
+            }
+
             // Use previous effect while new one is compiling
             if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
                 effect = previousEffect;
@@ -1513,6 +1516,11 @@ export abstract class PBRBaseMaterial extends PushMaterial {
 
         const defines = new PBRMaterialDefines();
         const effect = this._prepareEffect(mesh, defines, undefined, undefined, localOptions.useInstances, localOptions.clipPlane)!;
+        if (this._onEffectCreatedObservable) {
+            onCreatedEffectParameters.effect = effect;
+            onCreatedEffectParameters.subMesh = null;
+            this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);
+        }
         if (effect.isReady()) {
             if (onCompiled) {
                 onCompiled(this);

+ 42 - 1
src/Materials/effect.ts

@@ -139,6 +139,7 @@ export class Effect implements IDisposable {
     private static _uniqueIdSeed = 0;
     private _engine: Engine;
     private _uniformBuffersNames: { [key: string]: number } = {};
+    private _uniformBuffersNamesList: string[];
     private _uniformsNames: string[];
     private _samplerList: string[];
     private _samplers: { [key: string]: number } = {};
@@ -203,6 +204,7 @@ export class Effect implements IDisposable {
             this._transformFeedbackVaryings = options.transformFeedbackVaryings || null;
 
             if (options.uniformBuffersNames) {
+                this._uniformBuffersNamesList = options.uniformBuffersNames.slice();
                 for (var i = 0; i < options.uniformBuffersNames.length; i++) {
                     this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
                 }
@@ -213,6 +215,7 @@ export class Effect implements IDisposable {
             this._uniformsNames = (<string[]>uniformsNamesOrEngine).concat(<string[]>samplers);
             this._samplerList = samplers ? <string[]>samplers.slice() : [];
             this._attributesNames = (<string[]>attributesNamesOrOptions);
+            this._uniformBuffersNamesList = [];
 
             this.onError = onError;
             this.onCompiled = onCompiled;
@@ -393,13 +396,37 @@ export class Effect implements IDisposable {
 
     /**
      * Returns an array of sampler variable names
-     * @returns The array of sampler variable neames.
+     * @returns The array of sampler variable names.
      */
     public getSamplers(): string[] {
         return this._samplerList;
     }
 
     /**
+     * Returns an array of uniform variable names
+     * @returns The array of uniform variable names.
+     */
+    public getUniformNames(): string[] {
+        return this._uniformsNames;
+    }
+
+    /**
+     * Returns an array of uniform buffer variable names
+     * @returns The array of uniform buffer variable names.
+     */
+    public getUniformBuffersNames(): string[] {
+        return this._uniformBuffersNamesList;
+    }
+
+    /**
+     * Returns the index parameters used to create the effect
+     * @returns The index parameters object
+     */
+    public getIndexParameters(): any {
+        return this._indexParameters;
+    }
+
+    /**
      * The error from the last compilation.
      * @returns the error string.
      */
@@ -498,6 +525,20 @@ export class Effect implements IDisposable {
     }
 
     /**
+     * Gets the vertex shader source code of this effect
+     */
+    public get vertexSourceCode(): string {
+        return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? this._vertexSourceCodeOverride : this._vertexSourceCode;
+    }
+
+    /**
+     * Gets the fragment shader source code of this effect
+     */
+    public get fragmentSourceCode(): string {
+        return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? this._fragmentSourceCodeOverride : this._fragmentSourceCode;
+    }
+
+    /**
      * Recompiles the webGL program
      * @param vertexSourceCode The source code for the vertex shader.
      * @param fragmentSourceCode The source code for the fragment shader.

+ 2 - 1
src/Materials/index.ts

@@ -17,4 +17,5 @@ export * from "./Textures/index";
 export * from "./uniformBuffer";
 export * from "./materialFlags";
 export * from "./Node/index";
-export * from "./effectRenderer";
+export * from "./effectRenderer";
+export * from "./shadowDepthWrapper";

+ 28 - 0
src/Materials/material.ts

@@ -19,6 +19,7 @@ import { Constants } from "../Engines/constants";
 import { Logger } from "../Misc/logger";
 import { IInspectable } from '../Misc/iInspectable';
 import { Plane } from '../Maths/math.plane';
+import { ShadowDepthWrapper } from './shadowDepthWrapper';
 
 declare type Mesh = import("../Meshes/mesh").Mesh;
 declare type Animation = import("../Animations/animation").Animation;
@@ -144,6 +145,16 @@ export class Material implements IAnimatable {
     public static readonly MATERIAL_ALPHATESTANDBLEND = 3;
 
     /**
+     * Custom callback helping to override the default shader used in the material.
+     */
+    public customShaderNameResolve: (shaderName: string, uniforms: string[], uniformBuffers: string[], samplers: string[], defines: MaterialDefines | string[], attributes?: string[]) => string;
+
+    /**
+     * Custom shadow depth material to use for shadow rendering instead of the in-built one
+     */
+    public shadowDepthWrapper: Nullable<ShadowDepthWrapper> = null;
+
+    /**
      * The ID of the material
      */
     @serialize()
@@ -346,6 +357,19 @@ export class Material implements IAnimatable {
         return this._onUnBindObservable;
     }
 
+    protected _onEffectCreatedObservable: Nullable<Observable<{ effect: Effect, subMesh: Nullable<SubMesh>}>>;
+
+    /**
+    * An event triggered when the effect is (re)created
+    */
+    public get onEffectCreatedObservable(): Observable<{ effect: Effect, subMesh: Nullable<SubMesh>}> {
+        if (!this._onEffectCreatedObservable) {
+            this._onEffectCreatedObservable = new Observable<{effect: Effect, subMesh: Nullable<SubMesh>}>();
+        }
+
+        return this._onEffectCreatedObservable;
+    }
+
     /**
      * Stores the value of the alpha mode
      */
@@ -1273,6 +1297,10 @@ export class Material implements IAnimatable {
         if (this._onUnBindObservable) {
             this._onUnBindObservable.clear();
         }
+
+        if (this._onEffectCreatedObservable) {
+            this._onEffectCreatedObservable.clear();
+        }
     }
 
     /** @hidden */

+ 88 - 48
src/Materials/shaderMaterial.ts

@@ -1,19 +1,22 @@
 import { SerializationHelper } from "../Misc/decorators";
+import { Nullable } from "../types";
 import { Scene } from "../scene";
 import { Matrix, Vector3, Vector2, Vector4 } from "../Maths/math.vector";
 import { AbstractMesh } from "../Meshes/abstractMesh";
 import { Mesh } from "../Meshes/mesh";
-import { BaseSubMesh } from "../Meshes/subMesh";
+import { SubMesh, BaseSubMesh } from "../Meshes/subMesh";
 import { VertexBuffer } from "../Meshes/buffer";
 import { BaseTexture } from "../Materials/Textures/baseTexture";
 import { Texture } from "../Materials/Textures/texture";
 import { MaterialHelper } from "./materialHelper";
-import { IEffectCreationOptions } from "./effect";
+import { Effect, IEffectCreationOptions } from "./effect";
 import { Material } from "./material";
 import { _TypeStore } from '../Misc/typeStore';
 import { Color3, Color4 } from '../Maths/math.color';
 import { EffectFallbacks } from './effectFallbacks';
 
+const onCreatedEffectParameters = { effect: null as unknown as Effect, subMesh: null as unknown as Nullable<SubMesh> };
+
 /**
  * Defines the options associated with the creation of a shader material.
  */
@@ -87,6 +90,7 @@ export class ShaderMaterial extends Material {
     private _cachedWorldViewProjectionMatrix = new Matrix();
     private _renderId: number;
     private _multiview: boolean = false;
+    private _cachedDefines: string;
 
     /**
      * Instantiate a new shader material.
@@ -571,21 +575,42 @@ export class ShaderMaterial extends Material {
             defines.push("#define ALPHATEST");
         }
 
+        let shaderName = this._shaderPath,
+            uniforms = this._options.uniforms,
+            uniformBuffers = this._options.uniformBuffers,
+            samplers = this._options.samplers;
+
+        if (this.customShaderNameResolve) {
+            uniforms = uniforms.slice();
+            uniformBuffers = uniformBuffers.slice();
+            samplers = samplers.slice();
+            shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs);
+        }
+
         var previousEffect = this._effect;
         var join = defines.join("\n");
 
-        this._effect = engine.createEffect(this._shaderPath, <IEffectCreationOptions>{
-            attributes: attribs,
-            uniformsNames: this._options.uniforms,
-            uniformBuffersNames: this._options.uniformBuffers,
-            samplers: this._options.samplers,
-            defines: join,
-            fallbacks: fallbacks,
-            onCompiled: this.onCompiled,
-            onError: this.onError
-        }, engine);
-
-        if (!this._effect.isReady()) {
+        if (this._cachedDefines !== join) {
+            this._cachedDefines = join;
+
+            this._effect = engine.createEffect(shaderName, <IEffectCreationOptions>{
+                attributes: attribs,
+                uniformsNames: uniforms,
+                uniformBuffersNames: uniformBuffers,
+                samplers: samplers,
+                defines: join,
+                fallbacks: fallbacks,
+                onCompiled: this.onCompiled,
+                onError: this.onError
+            }, engine);
+
+            if (this._onEffectCreatedObservable) {
+                onCreatedEffectParameters.effect = this._effect;
+                this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);
+            }
+        }
+
+        if (!this._effect?.isReady() ?? true) {
             return false;
         }
 
@@ -602,157 +627,172 @@ export class ShaderMaterial extends Material {
     /**
      * Binds the world matrix to the material
      * @param world defines the world transformation matrix
+     * @param effectOverride - If provided, use this effect instead of internal effect
      */
-    public bindOnlyWorldMatrix(world: Matrix): void {
+    public bindOnlyWorldMatrix(world: Matrix, effectOverride?: Nullable<Effect>): void {
         var scene = this.getScene();
 
-        if (!this._effect) {
+        const effect = effectOverride ?? this._effect;
+
+        if (!effect) {
             return;
         }
 
         if (this._options.uniforms.indexOf("world") !== -1) {
-            this._effect.setMatrix("world", world);
+            effect.setMatrix("world", world);
         }
 
         if (this._options.uniforms.indexOf("worldView") !== -1) {
             world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
-            this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
+            effect.setMatrix("worldView", this._cachedWorldViewMatrix);
         }
 
         if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
             world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);
-            this._effect.setMatrix("worldViewProjection", this._cachedWorldViewProjectionMatrix);
-
+            effect.setMatrix("worldViewProjection", this._cachedWorldViewProjectionMatrix);
         }
     }
 
     /**
+     * Binds the submesh to this material by preparing the effect and shader to draw
+     * @param world defines the world transformation matrix
+     * @param mesh defines the mesh containing the submesh
+     * @param subMesh defines the submesh to bind the material to
+     */
+    public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
+        this.bind(world, mesh, subMesh._effectOverride);
+    }
+
+    /**
      * Binds the material to the mesh
      * @param world defines the world transformation matrix
      * @param mesh defines the mesh to bind the material to
+     * @param effectOverride - If provided, use this effect instead of internal effect
      */
-    public bind(world: Matrix, mesh?: Mesh): void {
+    public bind(world: Matrix, mesh?: Mesh, effectOverride?: Nullable<Effect>): void {
         // Std values
-        this.bindOnlyWorldMatrix(world);
+        this.bindOnlyWorldMatrix(world, effectOverride);
+
+        const effect = effectOverride ?? this._effect;
 
-        if (this._effect && this.getScene().getCachedMaterial() !== this) {
+        if (effect && this.getScene().getCachedMaterial() !== this) {
             if (this._options.uniforms.indexOf("view") !== -1) {
-                this._effect.setMatrix("view", this.getScene().getViewMatrix());
+                effect.setMatrix("view", this.getScene().getViewMatrix());
             }
 
             if (this._options.uniforms.indexOf("projection") !== -1) {
-                this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
+                effect.setMatrix("projection", this.getScene().getProjectionMatrix());
             }
 
             if (this._options.uniforms.indexOf("viewProjection") !== -1) {
-                this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
+                effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
                 if (this._multiview) {
-                    this._effect.setMatrix("viewProjectionR", this.getScene()._transformMatrixR);
+                    effect.setMatrix("viewProjectionR", this.getScene()._transformMatrixR);
                 }
             }
 
             if (this.getScene().activeCamera && this._options.uniforms.indexOf("cameraPosition") !== -1) {
-                this._effect.setVector3("cameraPosition", this.getScene().activeCamera!.globalPosition);
+                effect.setVector3("cameraPosition", this.getScene().activeCamera!.globalPosition);
             }
 
             // Bones
-            MaterialHelper.BindBonesParameters(mesh, this._effect);
+            MaterialHelper.BindBonesParameters(mesh, effect);
 
             var name: string;
             // Texture
             for (name in this._textures) {
-                this._effect.setTexture(name, this._textures[name]);
+                effect.setTexture(name, this._textures[name]);
             }
 
             // Texture arrays
             for (name in this._textureArrays) {
-                this._effect.setTextureArray(name, this._textureArrays[name]);
+                effect.setTextureArray(name, this._textureArrays[name]);
             }
 
             // Int
             for (name in this._ints) {
-                this._effect.setInt(name, this._ints[name]);
+                effect.setInt(name, this._ints[name]);
             }
 
             // Float
             for (name in this._floats) {
-                this._effect.setFloat(name, this._floats[name]);
+                effect.setFloat(name, this._floats[name]);
             }
 
             // Floats
             for (name in this._floatsArrays) {
-                this._effect.setArray(name, this._floatsArrays[name]);
+                effect.setArray(name, this._floatsArrays[name]);
             }
 
             // Color3
             for (name in this._colors3) {
-                this._effect.setColor3(name, this._colors3[name]);
+                effect.setColor3(name, this._colors3[name]);
             }
 
             // Color3Array
             for (name in this._colors3Arrays) {
-                this._effect.setArray3(name, this._colors3Arrays[name]);
+                effect.setArray3(name, this._colors3Arrays[name]);
             }
 
             // Color4
             for (name in this._colors4) {
                 var color = this._colors4[name];
-                this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
+                effect.setFloat4(name, color.r, color.g, color.b, color.a);
             }
 
             // Color4Array
             for (name in this._colors4Arrays) {
-                this._effect.setArray4(name, this._colors4Arrays[name]);
+                effect.setArray4(name, this._colors4Arrays[name]);
             }
 
             // Vector2
             for (name in this._vectors2) {
-                this._effect.setVector2(name, this._vectors2[name]);
+                effect.setVector2(name, this._vectors2[name]);
             }
 
             // Vector3
             for (name in this._vectors3) {
-                this._effect.setVector3(name, this._vectors3[name]);
+                effect.setVector3(name, this._vectors3[name]);
             }
 
             // Vector4
             for (name in this._vectors4) {
-                this._effect.setVector4(name, this._vectors4[name]);
+                effect.setVector4(name, this._vectors4[name]);
             }
 
             // Matrix
             for (name in this._matrices) {
-                this._effect.setMatrix(name, this._matrices[name]);
+                effect.setMatrix(name, this._matrices[name]);
             }
 
             // MatrixArray
             for (name in this._matrixArrays) {
-                this._effect.setMatrices(name, this._matrixArrays[name]);
+                effect.setMatrices(name, this._matrixArrays[name]);
             }
 
             // Matrix 3x3
             for (name in this._matrices3x3) {
-                this._effect.setMatrix3x3(name, this._matrices3x3[name]);
+                effect.setMatrix3x3(name, this._matrices3x3[name]);
             }
 
             // Matrix 2x2
             for (name in this._matrices2x2) {
-                this._effect.setMatrix2x2(name, this._matrices2x2[name]);
+                effect.setMatrix2x2(name, this._matrices2x2[name]);
             }
 
             // Vector2Array
             for (name in this._vectors2Arrays) {
-                this._effect.setArray2(name, this._vectors2Arrays[name]);
+                effect.setArray2(name, this._vectors2Arrays[name]);
             }
 
             // Vector3Array
             for (name in this._vectors3Arrays) {
-                this._effect.setArray3(name, this._vectors3Arrays[name]);
+                effect.setArray3(name, this._vectors3Arrays[name]);
             }
 
             // Vector4Array
             for (name in this._vectors4Arrays) {
-                this._effect.setArray4(name, this._vectors4Arrays[name]);
+                effect.setArray4(name, this._vectors4Arrays[name]);
             }
         }
 

+ 234 - 0
src/Materials/shadowDepthWrapper.ts

@@ -0,0 +1,234 @@
+import { Observer } from "../Misc/observable";
+import { Nullable } from "../types";
+import { Scene } from "../scene";
+import { SubMesh } from "../Meshes/subMesh";
+import { Material } from "./material";
+import { _TypeStore } from "../Misc/typeStore";
+import { Effect, IEffectCreationOptions } from './effect';
+import { AbstractMesh } from '../Meshes/abstractMesh';
+import { Node } from '../node';
+import { ShadowGenerator } from '../Lights/Shadows/shadowGenerator';
+import { GUID } from '../Misc/guid';
+
+/**
+ * Options to be used when creating a shadow depth material
+ */
+export interface IIOptionShadowDepthMaterial {
+    /** Variables in the vertex shader code that need to have their names remapped.
+     * The format is: ["var_name", "var_remapped_name", "var_name", "var_remapped_name", ...]
+     * "var_name" should be either: worldPos or vNormalW
+     * So, if the variable holding the world position in your vertex shader is not named worldPos, you must tell the system
+     * the name to use instead by using: ["worldPos", "myWorldPosVar"] assuming the variable is named myWorldPosVar in your code.
+     * If the normal must also be remapped: ["worldPos", "myWorldPosVar", "vNormalW", "myWorldNormal"]
+    */
+    remappedVariables?: string[];
+
+    /** Set standalone to true if the base material wrapped by ShadowDepthMaterial is not used for a regular object but for depth shadow generation only */
+    standalone?: boolean;
+}
+
+class MapMap<Ka, Kb, V> {
+    readonly mm = new Map<Ka, Map<Kb, V>>();
+
+    get(a: Ka, b: Kb): V | undefined {
+        const m = this.mm.get(a);
+        if (m !== undefined) {
+            return m.get(b);
+        }
+        return undefined;
+    }
+
+    set(a: Ka, b: Kb, v: V): void {
+        let m = this.mm.get(a);
+        if (m === undefined) {
+            this.mm.set(a, (m = new Map()));
+        }
+        m.set(b, v);
+    }
+}
+
+/**
+ * Class that can be used to wrap a base material to generate accurate shadows when using custom vertex/fragment code in the base material
+ */
+export class ShadowDepthWrapper {
+
+    private _scene: Scene;
+    private _options?: IIOptionShadowDepthMaterial;
+    private _baseMaterial: Material;
+    private _onEffectCreatedObserver: Nullable<Observer<{ effect: Effect, subMesh: Nullable<SubMesh>}>>;
+    private _subMeshToEffect: Map<Nullable<SubMesh>, Effect>;
+    private _subMeshToDepthEffect: MapMap<Nullable<SubMesh>, ShadowGenerator, { depthEffect: Nullable<Effect>, depthDefines: string, token: string }>; // key is (subMesh + shadowGenerator)
+    private _meshes: Map<AbstractMesh, Nullable<Observer<Node>>>;
+
+    /** @hidden */
+    public _matriceNames: any;
+
+    /**
+     * Instantiate a new shadow depth wrapper.
+     * It works by injecting some specific code in the vertex/fragment shaders of the base material and is used by a shadow generator to
+     * generate the shadow depth map. For more information, please refer to the documentation:
+     * https://doc.babylonjs.com/babylon101/shadows
+     * @param baseMaterial Material to wrap
+     * @param scene Define the scene the material belongs to
+     * @param options Options used to create the wrapper
+     */
+    constructor(baseMaterial: Material, scene: Scene, options?: IIOptionShadowDepthMaterial) {
+        this._baseMaterial = baseMaterial;
+        this._scene = scene;
+        this._options = options;
+
+        this._subMeshToEffect = new Map();
+        this._subMeshToDepthEffect = new MapMap();
+        this._meshes = new Map();
+
+        const prefix = baseMaterial.getClassName() === "NodeMaterial" ? "u_" : "";
+
+        this._matriceNames = {
+            "view": prefix + "view",
+            "projection": prefix + "projection",
+            "viewProjection": prefix + "viewProjection",
+        };
+
+        // Register for onEffectCreated to store the effect of the base material when it is (re)generated. This effect will be used
+        // to create the depth effect later on
+        this._onEffectCreatedObserver = this._baseMaterial.onEffectCreatedObservable.add((params: { effect: Effect, subMesh: Nullable<SubMesh> }) => {
+            const mesh = params.subMesh?.getMesh();
+
+            if (mesh && !this._meshes.has(mesh)) {
+                // Register for mesh onDispose to clean up our internal maps when a mesh is disposed
+                this._meshes.set(mesh,
+                    mesh.onDisposeObservable.add((mesh: Node) => {
+                        const iterator = this._subMeshToEffect.keys();
+                        for (let key = iterator.next(); key.done !== true; key = iterator.next()) {
+                            const subMesh = key.value;
+                            if (subMesh?.getMesh() === mesh as AbstractMesh) {
+                                this._subMeshToEffect.delete(subMesh);
+                                this._subMeshToDepthEffect.mm.delete(subMesh);
+                            }
+                        }
+                    })
+                );
+            }
+
+            this._subMeshToEffect.set(params.subMesh, params.effect);
+            this._subMeshToDepthEffect.mm.delete(params.subMesh); // trigger a depth effect recreation
+        });
+    }
+
+    /**
+     * Gets the effect to use to generate the depth map
+     * @param subMesh subMesh to get the effect for
+     * @param shadowGenerator shadow generator to get the effect for
+     * @returns the effect to use to generate the depth map for the subMesh + shadow generator specified
+     */
+    public getEffect(subMesh: Nullable<SubMesh>, shadowGenerator: ShadowGenerator): Nullable<Effect> {
+        return this._subMeshToDepthEffect.mm.get(subMesh)?.get(shadowGenerator)?.depthEffect ?? this._subMeshToDepthEffect.mm.get(null)?.get(shadowGenerator)?.depthEffect ?? null;
+    }
+
+    /**
+     * Specifies that the submesh is ready to be used for depth rendering
+     * @param subMesh submesh to check
+     * @param defines the list of defines to take into account when checking the effect
+     * @param shadowGenerator combined with subMesh, it defines the effect to check
+     * @param useInstances specifies that instances should be used
+     * @returns a boolean indicating that the submesh is ready or not
+     */
+    public isReadyForSubMesh(subMesh: SubMesh, defines: string[], shadowGenerator: ShadowGenerator, useInstances: boolean): boolean {
+        if (this._options?.standalone) {
+            // will ensure the effect is (re)created for the base material
+            this._baseMaterial.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances);
+        }
+
+        return this._makeEffect(subMesh, defines, shadowGenerator)?.isReady() ?? false;
+    }
+
+    /**
+     * Disposes the resources
+     */
+    public dispose(): void {
+        this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver);
+        this._onEffectCreatedObserver = null;
+
+        const iterator = this._meshes.entries();
+        for (let entry = iterator.next(); entry.done !== true; entry = iterator.next()) {
+            const [mesh, observer] = entry.value;
+
+            mesh.onDisposeObservable.remove(observer);
+        }
+    }
+
+    private _makeEffect(subMesh: Nullable<SubMesh>, defines: string[], shadowGenerator: ShadowGenerator): Nullable<Effect> {
+        const origEffect = this._subMeshToEffect.get(subMesh) ?? this._subMeshToEffect.get(null);
+
+        if (!origEffect) {
+            return null;
+        }
+
+        let params = this._subMeshToDepthEffect.get(subMesh, shadowGenerator);
+        if (!params) {
+            params = {
+                depthEffect: null,
+                depthDefines: "",
+                token: GUID.RandomId()
+            };
+            this._subMeshToDepthEffect.set(subMesh, shadowGenerator, params);
+        }
+
+        let join = defines.join("\n");
+
+        if (params.depthEffect) {
+            if (join === params.depthDefines) {
+                // we already created the depth effect and it is still up to date for this submesh + shadow generator
+                return params.depthEffect;
+            }
+        }
+
+        params.depthDefines = join;
+
+        // the depth effect is either out of date or has not been created yet
+        let vertexCode = origEffect.vertexSourceCode,
+            fragmentCode = origEffect.fragmentSourceCode;
+
+        const vertexNormalBiasCode = this._options && this._options.remappedVariables ? `#include<shadowMapVertexNormalBias>(${this._options.remappedVariables.join(",")})` : Effect.IncludesShadersStore["shadowMapVertexNormalBias"],
+              vertexMetricCode = this._options && this._options.remappedVariables ? `#include<shadowMapVertexMetric>(${this._options.remappedVariables.join(",")})` : Effect.IncludesShadersStore["shadowMapVertexMetric"],
+              fragmentBlockCode = Effect.IncludesShadersStore["shadowMapFragment"];
+
+        vertexCode = vertexCode.replace(/void\s+?main/g, Effect.IncludesShadersStore["shadowMapVertexDeclaration"] + "\r\nvoid main");
+        vertexCode = vertexCode.replace(/#define SHADOWDEPTH_NORMALBIAS/g, vertexNormalBiasCode);
+
+        if (vertexCode.indexOf("#define SHADOWDEPTH_METRIC") !== -1) {
+            vertexCode = vertexCode.replace(/#define SHADOWDEPTH_METRIC/g, vertexMetricCode);
+        } else {
+            vertexCode = vertexCode.replace(/}\s*$/g, vertexMetricCode + "\r\n}");
+        }
+        vertexCode = vertexCode.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g, "");
+
+        fragmentCode = fragmentCode.replace(/void\s+?main/g, Effect.IncludesShadersStore["shadowMapFragmentDeclaration"] + "\r\nvoid main");
+        if (fragmentCode.indexOf("#define SHADOWDEPTH_FRAGMENT") !== -1) {
+            fragmentCode = vertexCode.replace(/#define SHADOWDEPTH_FRAGMENT/g, fragmentBlockCode);
+        } else {
+            fragmentCode = fragmentCode.replace(/}\s*$/g, fragmentBlockCode + "\r\n}");
+        }
+        fragmentCode = fragmentCode.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g, "");
+
+        const uniforms = origEffect.getUniformNames().slice();
+
+        uniforms.push("biasAndScaleSM", "depthValuesSM", "lightDataSM");
+
+        params.depthEffect = this._scene.getEngine().createEffect({
+            vertexSource: vertexCode,
+            fragmentSource: fragmentCode,
+            vertexToken: params.token,
+            fragmentToken: params.token,
+        }, <IEffectCreationOptions>{
+            attributes: origEffect.getAttributesNames(),
+            uniformsNames: uniforms,
+            uniformBuffersNames: origEffect.getUniformBuffersNames(),
+            samplers: origEffect.getSamplers(),
+            defines: join + "\n" + origEffect.defines,
+            indexParameters: origEffect.getIndexParameters(),
+        }, this._scene.getEngine());
+
+        return params.depthEffect;
+    }
+}

+ 9 - 6
src/Materials/standardMaterial.ts

@@ -31,7 +31,9 @@ import "../Shaders/default.fragment";
 import "../Shaders/default.vertex";
 import { Constants } from "../Engines/constants";
 import { EffectFallbacks } from './effectFallbacks';
-import { IEffectCreationOptions } from './effect';
+import { Effect, IEffectCreationOptions } from './effect';
+
+const onCreatedEffectParameters = { effect: null as unknown as Effect, subMesh: null as unknown as Nullable<SubMesh> };
 
 /** @hidden */
 export class StandardMaterialDefines extends MaterialDefines implements IImageProcessingConfigurationDefines {
@@ -662,11 +664,6 @@ export class StandardMaterial extends PushMaterial {
         this._imageProcessingConfiguration.colorCurves = value;
     }
 
-    /**
-     * Custom callback helping to override the default shader used in the material.
-     */
-    public customShaderNameResolve: (shaderName: string, uniforms: string[], uniformBuffers: string[], samplers: string[], defines: StandardMaterialDefines, attributes?: string[]) => string;
-
     protected _renderTargets = new SmartArray<RenderTargetTexture>(16);
     protected _worldViewProjectionMatrix = Matrix.Zero();
     protected _globalAmbientColor = new Color3(0, 0, 0);
@@ -1180,6 +1177,12 @@ export class StandardMaterial extends PushMaterial {
             }, engine);
 
             if (effect) {
+                if (this._onEffectCreatedObservable) {
+                    onCreatedEffectParameters.effect = effect;
+                    onCreatedEffectParameters.subMesh = subMesh;
+                    this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);
+                }
+
                 // Use previous effect while new one is compiling
                 if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
                     effect = previousEffect;

+ 3 - 1
src/Meshes/subMesh.ts

@@ -27,6 +27,8 @@ export class BaseSubMesh {
     public _materialDefines: Nullable<MaterialDefines> = null;
     /** @hidden */
     public _materialEffect: Nullable<Effect> = null;
+    /** @hidden */
+    public _effectOverride: Nullable<Effect> = null;
 
     /**
      * Gets material defines used by the effect associated to the sub mesh
@@ -46,7 +48,7 @@ export class BaseSubMesh {
      * Gets associated effect
      */
     public get effect(): Nullable<Effect> {
-        return this._materialEffect;
+        return this._effectOverride ?? this._materialEffect;
     }
 
     /**

+ 22 - 0
src/Shaders/ShadersInclude/shadowMapFragment.fx

@@ -0,0 +1,22 @@
+    float depthSM = vDepthMetricSM;
+
+#if SM_DEPTHCLAMP == 1
+    #if SM_USEDISTANCE == 1
+        depthSM = clamp(((length(vPositionWSM - lightDataSM) + depthValuesSM.x) / (depthValuesSM.y)) + biasAndScaleSM.x, 0.0, 1.0);
+    #else
+        depthSM = clamp(((zSM + depthValuesSM.x) / (depthValuesSM.y)) + biasAndScaleSM.x, 0.0, 1.0);
+    #endif
+    gl_FragDepth = depthSM;
+#elif SM_USEDISTANCE == 1
+    depthSM = (length(vPositionWSM - lightDataSM) + depthValuesSM.x) / (depthValuesSM.y) + biasAndScaleSM.x;
+#endif
+
+#if SM_ESM == 1
+    depthSM = clamp(exp(-min(87., biasAndScaleSM.z * depthSM)), 0., 1.);
+#endif
+
+#if SM_FLOAT == 1
+    gl_FragColor = vec4(depthSM, 1.0, 1.0, 1.0);
+#else
+    gl_FragColor = pack(depthSM);
+#endif

+ 17 - 0
src/Shaders/ShadersInclude/shadowMapFragmentDeclaration.fx

@@ -0,0 +1,17 @@
+#if SM_FLOAT == 0
+	#include<packingFunctions>
+#endif
+
+varying float vDepthMetricSM;
+
+#if SM_USEDISTANCE == 1
+    uniform vec3 lightDataSM;
+    varying vec3 vPositionWSM;
+#endif
+
+uniform vec3 biasAndScaleSM;
+uniform vec2 depthValuesSM;
+
+#if SM_DEPTHCLAMP == 1
+    varying float zSM;
+#endif

+ 16 - 0
src/Shaders/ShadersInclude/shadowMapVertexDeclaration.fx

@@ -0,0 +1,16 @@
+#if SM_NORMALBIAS == 1
+    uniform vec3 lightDataSM;
+#endif
+
+uniform vec3 biasAndScaleSM;
+uniform vec2 depthValuesSM;
+
+varying float vDepthMetricSM;
+
+#if SM_USEDISTANCE == 1
+    varying vec3 vPositionWSM;
+#endif
+
+#if SM_DEPTHCLAMP == 1
+    varying float zSM;
+#endif

+ 16 - 0
src/Shaders/ShadersInclude/shadowMapVertexMetric.fx

@@ -0,0 +1,16 @@
+#if SM_USEDISTANCE == 1
+    vPositionWSM = worldPos.xyz;
+#endif
+
+#if SM_DEPTHTEXTURE == 1
+    // Depth texture Linear bias.
+    gl_Position.z += biasAndScaleSM.x * gl_Position.w;
+#endif
+
+#if SM_DEPTHCLAMP == 1
+    zSM = gl_Position.z;
+    gl_Position.z = 0.0;
+#elif SM_USEDISTANCE == 0
+    // Color Texture Linear bias.
+    vDepthMetricSM = ((gl_Position.z + depthValuesSM.x) / (depthValuesSM.y)) + biasAndScaleSM.x;
+#endif

+ 15 - 0
src/Shaders/ShadersInclude/shadowMapVertexNormalBias.fx

@@ -0,0 +1,15 @@
+// Normal inset Bias.
+#if SM_NORMALBIAS == 1
+    #if SM_DIRECTIONINLIGHTDATA == 1
+        vec3 worldLightDirSM = normalize(-lightDataSM.xyz);
+    #else
+        vec3 directionToLightSM = lightDataSM.xyz - worldPos.xyz;
+        vec3 worldLightDirSM = normalize(directionToLightSM);
+    #endif
+
+    float ndlSM = dot(vNormalW, worldLightDirSM);
+    float sinNLSM = sqrt(1.0 - ndlSM * ndlSM);
+    float normalBiasSM = biasAndScaleSM.y * sinNLSM;
+
+    worldPos.xyz -= vNormalW * normalBiasSM;
+#endif

+ 12 - 10
src/Shaders/default.vertex.fx

@@ -124,6 +124,18 @@ void main(void) {
 
 	vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);
 
+#ifdef NORMAL
+	mat3 normalWorld = mat3(finalWorld);
+
+	#ifdef NONUNIFORMSCALING
+		normalWorld = transposeMat3(inverseMat3(normalWorld));
+	#endif
+
+	vNormalW = normalize(normalWorld * normalUpdated);
+#endif
+
+#define CUSTOM_VERTEX_UPDATE_WORLDPOS
+
 #ifdef MULTIVIEW
 	if (gl_ViewID_OVR == 0u) {
 		gl_Position = viewProjection * worldPos;
@@ -136,16 +148,6 @@ void main(void) {
 
 	vPositionW = vec3(worldPos);
 
-#ifdef NORMAL
-	mat3 normalWorld = mat3(finalWorld);
-
-	#ifdef NONUNIFORMSCALING
-		normalWorld = transposeMat3(inverseMat3(normalWorld));
-	#endif
-
-	vNormalW = normalize(normalWorld * normalUpdated);
-#endif
-
 #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
 	vDirectionW = normalize(vec3(finalWorld * vec4(positionUpdated, 0.0)));
 #endif

+ 12 - 10
src/Shaders/pbr.vertex.fx

@@ -163,16 +163,6 @@ void main(void) {
 #include<instancesVertex>
 #include<bonesVertex>
 
-#ifdef MULTIVIEW
-	if (gl_ViewID_OVR == 0u) {
-		gl_Position = viewProjection * finalWorld * vec4(positionUpdated, 1.0);
-	} else {
-		gl_Position = viewProjectionR * finalWorld * vec4(positionUpdated, 1.0);
-	}
-#else
-	gl_Position = viewProjection * finalWorld * vec4(positionUpdated, 1.0);
-#endif
-
 #if DEBUGMODE > 0
     vClipSpacePosition = gl_Position;
 #endif
@@ -198,6 +188,18 @@ void main(void) {
     #endif
 #endif
 
+#define CUSTOM_VERTEX_UPDATE_WORLDPOS
+
+#ifdef MULTIVIEW
+	if (gl_ViewID_OVR == 0u) {
+		gl_Position = viewProjection * worldPos;
+	} else {
+		gl_Position = viewProjectionR * worldPos;
+	}
+#else
+	gl_Position = viewProjection * worldPos;
+#endif
+
 #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
     vDirectionW = normalize(vec3(finalWorld * vec4(positionUpdated, 0.0)));
 #endif

+ 2 - 39
src/Shaders/shadowMap.fragment.fx

@@ -1,26 +1,10 @@
-#ifndef FLOAT
-	#include<packingFunctions>
-#endif
-
-varying float vDepthMetric;
-
-#ifdef USEDISTANCE
-uniform vec3 lightData;
-varying vec3 vPositionW;
-#endif
+#include<shadowMapFragmentDeclaration>
 
 #ifdef ALPHATEST
 varying vec2 vUV;
 uniform sampler2D diffuseSampler;
 #endif
 
-uniform vec3 biasAndScale;
-uniform vec2 depthValues;
-
-#ifdef DEPTHCLAMP
-varying float z;
-#endif
-
 #include<clipPlaneFragmentDeclaration>
 
 void main(void)
@@ -32,26 +16,5 @@ void main(void)
         discard;
 #endif
 
-    float depth = vDepthMetric;
-
-#ifdef DEPTHCLAMP
-    #ifdef USEDISTANCE
-        depth = clamp(((length(vPositionW - lightData) + depthValues.x) / (depthValues.y)) + biasAndScale.x, 0.0, 1.0);
-    #else
-        depth = clamp(((z + depthValues.x) / (depthValues.y)) + biasAndScale.x, 0.0, 1.0);
-    #endif
-    gl_FragDepth = depth;
-#elif defined(USEDISTANCE)
-    depth = (length(vPositionW - lightData) + depthValues.x) / (depthValues.y) + biasAndScale.x;
-#endif
-
-#ifdef ESM
-    depth = clamp(exp(-min(87., biasAndScale.z * depth)), 0., 1.);
-#endif
-
-#ifdef FLOAT
-    gl_FragColor = vec4(depth, 1.0, 1.0, 1.0);
-#else
-    gl_FragColor = pack(depth);
-#endif
+#include<shadowMapFragment>
 }

+ 9 - 45
src/Shaders/shadowMap.vertex.fx

@@ -3,7 +3,6 @@ attribute vec3 position;
 
 #ifdef NORMAL
     attribute vec3 normal;
-    uniform vec3 lightData;
 #endif
 
 #include<bonesDeclaration>
@@ -16,14 +15,6 @@ attribute vec3 position;
 #include<helperFunctions>
 
 uniform mat4 viewProjection;
-uniform vec3 biasAndScale;
-uniform vec2 depthValues;
-
-varying float vDepthMetric;
-
-#ifdef USEDISTANCE
-varying vec3 vPositionW;
-#endif
 
 #ifdef ALPHATEST
 varying vec2 vUV;
@@ -36,9 +27,7 @@ attribute vec2 uv2;
 #endif
 #endif
 
-#ifdef DEPTHCLAMP
-varying float z;
-#endif
+#include<shadowMapVertexDeclaration>
 
 #include<clipPlaneVertexDeclaration>
 
@@ -48,6 +37,9 @@ vec3 positionUpdated = position;
 #ifdef UV1
     vec2 uvUpdated = uv;
 #endif  
+#ifdef NORMAL	
+	vec3 normalUpdated = normal;
+#endif
 
 #include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
 
@@ -56,50 +48,22 @@ vec3 positionUpdated = position;
 
 vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);
 
-// Normal inset Bias.
 #ifdef NORMAL
-    mat3 normalWorld = mat3(finalWorld);
+    mat3 normWorldSM = mat3(finalWorld);
 
     #ifdef NONUNIFORMSCALING
-        normalWorld = transposeMat3(inverseMat3(normalWorld));
-    #endif
-
-    vec3 worldNor = normalize(normalWorld * normal);
-
-    #ifdef DIRECTIONINLIGHTDATA
-        vec3 worldLightDir = normalize(-lightData.xyz);
-    #else
-        vec3 directionToLight = lightData.xyz - worldPos.xyz;
-        vec3 worldLightDir = normalize(directionToLight);
+        normWorldSM = transposeMat3(inverseMat3(normWorldSM));
     #endif
 
-    float ndl = dot(worldNor, worldLightDir);
-    float sinNL = sqrt(1.0 - ndl * ndl);
-    float normalBias = biasAndScale.y * sinNL;
-
-    worldPos.xyz -= worldNor * normalBias;
+    vec3 vNormalW = normalize(normWorldSM * normalUpdated);
 #endif
 
-#ifdef USEDISTANCE
-vPositionW = worldPos.xyz;
-#endif
+#include<shadowMapVertexNormalBias>
 
 // Projection.
 gl_Position = viewProjection * worldPos;
 
-
-#ifdef DEPTHTEXTURE
-    // Depth texture Linear bias.
-    gl_Position.z += biasAndScale.x * gl_Position.w;
-#endif
-
-#ifdef DEPTHCLAMP
-    z = gl_Position.z;
-    gl_Position.z = 0.0;
-#elif !defined(USEDISTANCE)
-    // Color Texture Linear bias.
-    vDepthMetric = ((gl_Position.z + depthValues.x) / (depthValues.y)) + biasAndScale.x;
-#endif
+#include<shadowMapVertexMetric>
 
 #ifdef ALPHATEST
     #ifdef UV1