Bladeren bron

Merge branch 'master' of https://github.com/BabylonJS/Babylon.js

David Catuhe 9 jaren geleden
bovenliggende
commit
7498489877

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

@@ -3,6 +3,7 @@
     - New refraction channel for Standard material (including fresnel support). Refraction texture can be provided by a reflection probe or a refraction texture. [See demo here](http://www.babylonjs.com/Demos/refraction/) ([deltakosh](https://github.com/deltakosh))
     - Added support for HDR cubemaps ([sebavan](https://github.com/sebavan))
     - Support for shaders includes ([deltakosh](https://github.com/deltakosh))
+    - new mesh type : `LineSystem` ([jerome](https://github.com/jbousquie))
   - **Updates**
     - New OnPickTrigger support for spritesManager ([deltakosh](https://github.com/deltakosh))
     - New SPS method `digest()` ([jerome](https://github.com/jbousquie))    

File diff suppressed because it is too large
+ 14 - 157
materialsLibrary/dist/babylon.gradientMaterial.js


File diff suppressed because it is too large
+ 1 - 1
materialsLibrary/dist/babylon.gradientMaterial.min.js


File diff suppressed because it is too large
+ 11 - 157
materialsLibrary/dist/babylon.lavaMaterial.js


File diff suppressed because it is too large
+ 1 - 1
materialsLibrary/dist/babylon.lavaMaterial.min.js


File diff suppressed because it is too large
+ 1 - 1
materialsLibrary/dist/babylon.normalMaterial.js


File diff suppressed because it is too large
+ 1 - 1
materialsLibrary/dist/babylon.normalMaterial.min.js


File diff suppressed because it is too large
+ 23 - 7
materialsLibrary/dist/babylon.pbrMaterial.js


File diff suppressed because it is too large
+ 2 - 2
materialsLibrary/dist/babylon.pbrMaterial.min.js


+ 10 - 8
materialsLibrary/dist/dts/babylon.pbrMaterial.d.ts

@@ -41,22 +41,24 @@ declare module BABYLON {
         albedoColor: Color3;
         reflectivityColor: Color3;
         reflectionColor: Color3;
-        microSurface: number;
         emissiveColor: Color3;
-        useAlphaFromAlbedoTexture: boolean;
-        useEmissiveAsIllumination: boolean;
-        linkEmissiveWithAlbedo: boolean;
-        useSpecularOverAlpha: boolean;
-        disableLighting: boolean;
+        microSurface: number;
         indexOfRefraction: number;
         invertRefractionY: boolean;
-        linkRefractionWithTransparency: boolean;
-        useLightmapAsShadowmap: boolean;
         opacityFresnelParameters: FresnelParameters;
         emissiveFresnelParameters: FresnelParameters;
+        linkRefractionWithTransparency: boolean;
+        linkEmissiveWithAlbedo: boolean;
+        useLightmapAsShadowmap: boolean;
+        useEmissiveAsIllumination: boolean;
+        useAlphaFromAlbedoTexture: boolean;
+        useSpecularOverAlpha: boolean;
         useMicroSurfaceFromReflectivityMapAlpha: boolean;
         useAutoMicroSurfaceFromReflectivityMap: boolean;
         useScalarInLinearSpace: boolean;
+        usePhysicalLightFalloff: boolean;
+        useRadianceOverAlpha: boolean;
+        disableLighting: boolean;
         private _renderTargets;
         private _worldViewProjectionMatrix;
         private _globalAmbientColor;

+ 14 - 174
materialsLibrary/materials/gradient/babylon.gradientMaterial.ts

@@ -47,8 +47,7 @@ module BABYLON {
         public UV2 = false;
         public VERTEXCOLOR = false;
         public VERTEXALPHA = false;
-        public BONES = false;
-        public BONES4 = false;
+        public NUM_BONE_INFLUENCERS = 0;
         public BonesPerMesh = 0;
         public INSTANCES = false;
 
@@ -162,80 +161,7 @@ module BABYLON {
 
             var lightIndex = 0;
             if (scene.lightsEnabled && !this.disableLighting) {
-                for (var index = 0; index < scene.lights.length; index++) {
-                    var light = scene.lights[index];
-
-                    if (!light.isEnabled()) {
-                        continue;
-                    }
-
-                    // Excluded check
-                    if (light._excludedMeshesIds.length > 0) {
-                        for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
-                            var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
-
-                            if (excludedMesh) {
-                                light.excludedMeshes.push(excludedMesh);
-                            }
-                        }
-
-                        light._excludedMeshesIds = [];
-                    }
-
-                    // Included check
-                    if (light._includedOnlyMeshesIds.length > 0) {
-                        for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
-                            var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
-
-                            if (includedOnlyMesh) {
-                                light.includedOnlyMeshes.push(includedOnlyMesh);
-                            }
-                        }
-
-                        light._includedOnlyMeshesIds = [];
-                    }
-
-                    if (!light.canAffectMesh(mesh)) {
-                        continue;
-                    }
-                    needNormals = true;
-                    this._defines["LIGHT" + lightIndex] = true;
-
-                    var type;
-                    if (light instanceof SpotLight) {
-                        type = "SPOTLIGHT" + lightIndex;
-                    } else if (light instanceof HemisphericLight) {
-                        type = "HEMILIGHT" + lightIndex;
-                    } else if (light instanceof PointLight) {
-                        type = "POINTLIGHT" + lightIndex;
-                    } else {
-                        type = "DIRLIGHT" + lightIndex;
-                    }
-
-                    this._defines[type] = true;
-
-                    // Shadows
-                    if (scene.shadowsEnabled) {
-                        var shadowGenerator = light.getShadowGenerator();
-                        if (mesh && mesh.receiveShadows && shadowGenerator) {
-                            this._defines["SHADOW" + lightIndex] = true;
-
-                            this._defines.SHADOWS = true;
-
-                            if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
-                                this._defines["SHADOWVSM" + lightIndex] = true;
-                            }
-
-                            if (shadowGenerator.usePoissonSampling) {
-                                this._defines["SHADOWPCF" + lightIndex] = true;
-                            }
-                        }
-                    }
-
-                    lightIndex++;
-                    if (lightIndex === maxSimultaneousLights)
-                        break;
-                }
+                needNormals = MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
             }
 
             // Attribs
@@ -259,9 +185,8 @@ module BABYLON {
                     }
                 }
                 if (mesh.useBones && mesh.computeBonesUsingShaders) {
-                    this._defines.BONES = true;
+                    this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;                    
                     this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
-                    this._defines.BONES4 = true;
                 }
 
                 // Instances
@@ -282,30 +207,10 @@ module BABYLON {
                     fallbacks.addFallback(1, "FOG");
                 }
 
-                for (lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
-                    if (!this._defines["LIGHT" + lightIndex]) {
-                        continue;
-                    }
-
-                    if (lightIndex > 0) {
-                        fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
-                    }
-
-                    if (this._defines["SHADOW" + lightIndex]) {
-                        fallbacks.addFallback(0, "SHADOW" + lightIndex);
-                    }
-
-                    if (this._defines["SHADOWPCF" + lightIndex]) {
-                        fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
-                    }
-
-                    if (this._defines["SHADOWVSM" + lightIndex]) {
-                        fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
-                    }
-                }
+                MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
              
-                if (this._defines.BONES4) {
-                    fallbacks.addFallback(0, "BONES4");
+                if (this._defines.NUM_BONE_INFLUENCERS > 0) {
+                    fallbacks.addCPUSkinningFallback(0, mesh);
                 }
 
                 //Attributes
@@ -327,17 +232,9 @@ module BABYLON {
                     attribs.push(VertexBuffer.ColorKind);
                 }
 
-                if (this._defines.BONES) {
-                    attribs.push(VertexBuffer.MatricesIndicesKind);
-                    attribs.push(VertexBuffer.MatricesWeightsKind);
-                }
+                MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
+                MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
 
-                if (this._defines.INSTANCES) {
-                    attribs.push("world0");
-                    attribs.push("world1");
-                    attribs.push("world2");
-                    attribs.push("world3");
-                }
 
                 // Legacy browser patch
                 var shaderName = "gradient";
@@ -390,16 +287,13 @@ module BABYLON {
             this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
 
             // Bones
-            if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
-                this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
-            }
+            MaterialHelper.BindBonesParameters(mesh, this._effect);
+
 
             if (scene.getCachedMaterial() !== this) {
                 // Clip plane
-                if (scene.clipPlane) {
-                    var clipPlane = scene.clipPlane;
-                    this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
-                }
+                MaterialHelper.BindClipPlane(this._effect, scene);
+
 
                 // Point size
                 if (this.pointsCloud) {
@@ -412,58 +306,7 @@ module BABYLON {
             this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
 
             if (scene.lightsEnabled && !this.disableLighting) {
-                var lightIndex = 0;
-                var depthValuesAlreadySet = false;
-                for (var index = 0; index < scene.lights.length; index++) {
-                    var light = scene.lights[index];
-
-                    if (!light.isEnabled()) {
-                        continue;
-                    }
-
-                    if (!light.canAffectMesh(mesh)) {
-                        continue;
-                    }
-
-                    if (light instanceof PointLight) {
-                        // Point Light
-                        light.transferToEffect(this._effect, "vLightData" + lightIndex);
-                    } else if (light instanceof DirectionalLight) {
-                        // Directional Light
-                        light.transferToEffect(this._effect, "vLightData" + lightIndex);
-                    } else if (light instanceof SpotLight) {
-                        // Spot Light
-                        light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
-                    } else if (light instanceof HemisphericLight) {
-                        // Hemispheric Light
-                        light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
-                    }
-
-                    light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
-                    this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
-
-                    // Shadows
-                    if (scene.shadowsEnabled) {
-                        var shadowGenerator = light.getShadowGenerator();
-                        if (mesh.receiveShadows && shadowGenerator) {
-                            if (!(<any>light).needCube()) {
-                                this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
-                            } else {
-                                if (!depthValuesAlreadySet) {
-                                    depthValuesAlreadySet = true;
-                                    this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
-                                }
-                            }
-                            this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
-                            this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
-                        }
-                    }
-
-                    lightIndex++;
-
-                    if (lightIndex === maxSimultaneousLights)
-                        break;
-                }
+                MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
             }
 
             // View
@@ -472,10 +315,7 @@ module BABYLON {
             }
 
             // Fog
-            if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
-                this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
-                this._effect.setColor3("vFogColor", scene.fogColor);
-            }
+            MaterialHelper.BindFogParameters(scene, mesh, this._effect);
 
             this._effect.setColor4("topColor", this.topColor, this.topColorAlpha);
             this._effect.setColor4("bottomColor", this.bottomColor, this.bottomColorAlpha);

+ 17 - 481
materialsLibrary/materials/gradient/gradient.fragment.fx

@@ -22,85 +22,15 @@ varying vec4 vColor;
 #endif
 
 // Lights
-#ifdef LIGHT0
-uniform vec4 vLightData0;
-uniform vec4 vLightDiffuse0;
-#ifdef SHADOW0
-#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)
-varying vec4 vPositionFromLight0;
-uniform sampler2D shadowSampler0;
-#else
-uniform samplerCube shadowSampler0;
-#endif
-uniform vec3 shadowsInfo0;
-#endif
-#ifdef SPOTLIGHT0
-uniform vec4 vLightDirection0;
-#endif
-#ifdef HEMILIGHT0
-uniform vec3 vLightGround0;
-#endif
-#endif
 
-#ifdef LIGHT1
-uniform vec4 vLightData1;
-uniform vec4 vLightDiffuse1;
-#ifdef SHADOW1
-#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)
-varying vec4 vPositionFromLight1;
-uniform sampler2D shadowSampler1;
-#else
-uniform samplerCube shadowSampler1;
-#endif
-uniform vec3 shadowsInfo1;
-#endif
-#ifdef SPOTLIGHT1
-uniform vec4 vLightDirection1;
-#endif
-#ifdef HEMILIGHT1
-uniform vec3 vLightGround1;
-#endif
-#endif
+#include<light0FragmentDeclaration>
+#include<light1FragmentDeclaration>
+#include<light2FragmentDeclaration>
+#include<light3FragmentDeclaration>
 
-#ifdef LIGHT2
-uniform vec4 vLightData2;
-uniform vec4 vLightDiffuse2;
-#ifdef SHADOW2
-#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)
-varying vec4 vPositionFromLight2;
-uniform sampler2D shadowSampler2;
-#else
-uniform samplerCube shadowSampler2;
-#endif
-uniform vec3 shadowsInfo2;
-#endif
-#ifdef SPOTLIGHT2
-uniform vec4 vLightDirection2;
-#endif
-#ifdef HEMILIGHT2
-uniform vec3 vLightGround2;
-#endif
-#endif
 
-#ifdef LIGHT3
-uniform vec4 vLightData3;
-uniform vec4 vLightDiffuse3;
-#ifdef SHADOW3
-#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)
-varying vec4 vPositionFromLight3;
-uniform sampler2D shadowSampler3;
-#else
-uniform samplerCube shadowSampler3;
-#endif
-uniform vec3 shadowsInfo3;
-#endif
-#ifdef SPOTLIGHT3
-uniform vec4 vLightDirection3;
-#endif
-#ifdef HEMILIGHT3
-uniform vec3 vLightGround3;
-#endif
-#endif
+#include<lightsFragmentFunctions>
+#include<shadowsFragmentFunctions>
 
 // Samplers
 #ifdef DIFFUSE
@@ -109,274 +39,13 @@ uniform sampler2D diffuseSampler;
 uniform vec2 vDiffuseInfos;
 #endif
 
-// Shadows
-#ifdef SHADOWS
-
-float unpack(vec4 color)
-{
-	const vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
-	return dot(color, bit_shift);
-}
-
-#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)
-uniform vec2 depthValues;
-
-float computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)
-{
-	vec3 directionToLight = vPositionW - lightPosition;
-	float depth = length(directionToLight);
-	
-	depth = clamp(depth, 0., 1.0);
-
-	directionToLight = normalize(directionToLight);
-	directionToLight.y = - directionToLight.y;
-
-	float shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;
-
-	if (depth > shadow)
-	{
-		return darkness;
-	}
-	return 1.0;
-}
-
-float computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float bias, float darkness, float mapSize)
-{
-	vec3 directionToLight = vPositionW - lightPosition;
-	float depth = length(directionToLight);
-
-	depth = clamp(depth, 0., 1.0);
-	float diskScale = 2.0 / mapSize;
-
-	directionToLight = normalize(directionToLight);
-	directionToLight.y = -directionToLight.y;
-
-	float visibility = 1.;
-
-	vec3 poissonDisk[4];
-	poissonDisk[0] = vec3(-0.094201624, 0.04, -0.039906216);
-	poissonDisk[1] = vec3(0.094558609, -0.04, -0.076890725);
-	poissonDisk[2] = vec3(-0.094184101, 0.01, -0.092938870);
-	poissonDisk[3] = vec3(0.034495938, -0.01, 0.029387760);
-
-	// Poisson Sampling
-	float biasedDepth = depth - bias;
-
-	if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0])) < biasedDepth) visibility -= 0.25;
-	if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1])) < biasedDepth) visibility -= 0.25;
-	if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2])) < biasedDepth) visibility -= 0.25;
-	if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3])) < biasedDepth) visibility -= 0.25;
-
-	return  min(1.0, visibility + darkness);
-}
-#endif
-
-#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) ||  defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)
-float computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)
-{
-	vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;
-	depth = 0.5 * depth + vec3(0.5);
-	vec2 uv = depth.xy;
-
-	if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)
-	{
-		return 1.0;
-	}
-
-	float shadow = unpack(texture2D(shadowSampler, uv)) + bias;
-
-	if (depth.z > shadow)
-	{
-		return darkness;
-	}
-	return 1.;
-}
-
-float computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)
-{
-	vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;
-	depth = 0.5 * depth + vec3(0.5);
-	vec2 uv = depth.xy;
-
-	if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)
-	{
-		return 1.0;
-	}
-
-	float visibility = 1.;
-
-	vec2 poissonDisk[4];
-	poissonDisk[0] = vec2(-0.94201624, -0.39906216);
-	poissonDisk[1] = vec2(0.94558609, -0.76890725);
-	poissonDisk[2] = vec2(-0.094184101, -0.92938870);
-	poissonDisk[3] = vec2(0.34495938, 0.29387760);
-
-	// Poisson Sampling
-	float biasedDepth = depth.z - bias;
-
-	if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;
-	if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;
-	if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;
-	if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;
-
-	return  min(1.0, visibility + darkness);
-}
-
-// Thanks to http://devmaster.net/
-float unpackHalf(vec2 color)
-{
-	return color.x + (color.y / 255.0);
-}
-
-float linstep(float low, float high, float v) {
-	return clamp((v - low) / (high - low), 0.0, 1.0);
-}
-
-float ChebychevInequality(vec2 moments, float compare, float bias)
-{
-	float p = smoothstep(compare - bias, compare, moments.x);
-	float variance = max(moments.y - moments.x * moments.x, 0.02);
-	float d = compare - moments.x;
-	float p_max = linstep(0.2, 1.0, variance / (variance + d * d));
-
-	return clamp(max(p, p_max), 0.0, 1.0);
-}
-
-float computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)
-{
-	vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;
-	depth = 0.5 * depth + vec3(0.5);
-	vec2 uv = depth.xy;
-
-	if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)
-	{
-		return 1.0;
-	}
-
-	vec4 texel = texture2D(shadowSampler, uv);
-
-	vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));
-	return min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);
-}
-#endif
-#endif
-
-
-#ifdef CLIPPLANE
-varying float fClipDistance;
-#endif
+#include<clipPlaneFragmentDeclaration>
 
 // Fog
-#ifdef FOG
-
-#define FOGMODE_NONE    0.
-#define FOGMODE_EXP     1.
-#define FOGMODE_EXP2    2.
-#define FOGMODE_LINEAR  3.
-#define E 2.71828
-
-uniform vec4 vFogInfos;
-uniform vec3 vFogColor;
-varying float fFogDistance;
-
-float CalcFogFactor()
-{
-	float fogCoeff = 1.0;
-	float fogStart = vFogInfos.y;
-	float fogEnd = vFogInfos.z;
-	float fogDensity = vFogInfos.w;
-
-	if (FOGMODE_LINEAR == vFogInfos.x)
-	{
-		fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);
-	}
-	else if (FOGMODE_EXP == vFogInfos.x)
-	{
-		fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);
-	}
-	else if (FOGMODE_EXP2 == vFogInfos.x)
-	{
-		fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);
-	}
-
-	return clamp(fogCoeff, 0.0, 1.0);
-}
-#endif
-
-// Light Computing
-struct lightingInfo
-{
-	vec3 diffuse;
-};
-
-lightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, float range) {
-	lightingInfo result;
-
-	vec3 lightVectorW;
-	float attenuation = 1.0;
-	if (lightData.w == 0.)
-	{
-		vec3 direction = lightData.xyz - vPositionW;
-
-		attenuation = max(0., 1.0 - length(direction) / range);
-		lightVectorW = normalize(direction);
-	}
-	else
-	{
-		lightVectorW = normalize(-lightData.xyz);
-	}
-
-	// diffuse
-	float ndl = max(0., dot(vNormal, lightVectorW));
-	result.diffuse = ndl * diffuseColor * attenuation;
-
-	return result;
-}
-
-lightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, float range) {
-	lightingInfo result;
-
-	vec3 direction = lightData.xyz - vPositionW;
-	vec3 lightVectorW = normalize(direction);
-	float attenuation = max(0., 1.0 - length(direction) / range);
-
-	// diffuse
-	float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));
-	float spotAtten = 0.0;
-
-	if (cosAngle >= lightDirection.w)
-	{
-		cosAngle = max(0., pow(cosAngle, lightData.w));
-		spotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);
-
-		// Diffuse
-		float ndl = max(0., dot(vNormal, -lightDirection.xyz));
-		result.diffuse = ndl * spotAtten * diffuseColor * attenuation;
-
-		return result;
-	}
-
-	result.diffuse = vec3(0.);
-
-	return result;
-}
-
-lightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 groundColor) {
-	lightingInfo result;
-
-	// Diffuse
-	float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;
-	result.diffuse = mix(groundColor, diffuseColor, ndl);
-
-	return result;
-}
+#include<fogFragmentDeclaration>
 
 void main(void) {
-	// Clip plane
-#ifdef CLIPPLANE
-	if (fClipDistance > 0.0)
-		discard;
-#endif
+#include<clipPlaneFragment>
 
 	vec3 viewDirectionW = normalize(vEyePosition - vPositionW);
 
@@ -386,7 +55,7 @@ void main(void) {
     vec4 baseColor = mix(bottomColor, topColor, max(pow(max(h, 0.0), mysmoothness), 0.0));
 
 	// Base color
-	vec3 diffuseColor = vDiffuseColor.rgb;
+	vec3 diffuseColor = baseColor.rgb;
 
 	// Alpha
 	float alpha = baseColor.a;
@@ -411,142 +80,12 @@ void main(void) {
 	// Lighting
 	vec3 diffuseBase = vec3(0., 0., 0.);
 	float shadow = 1.;
-
-#ifdef LIGHT0
-#ifdef SPOTLIGHT0
-	lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightDiffuse0.a);
-#endif
-#ifdef HEMILIGHT0
-	lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightGround0);
-#endif
-#if defined(POINTLIGHT0) || defined(DIRLIGHT0)
-	lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightDiffuse0.a);
-#endif
-#ifdef SHADOW0
-#ifdef SHADOWVSM0
-	shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);
-#else
-#ifdef SHADOWPCF0
-	#if defined(POINTLIGHT0)
-	shadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x, shadowsInfo0.y);
-	#else
-	shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);
-	#endif
-#else
-	#if defined(POINTLIGHT0)
-	shadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);
-	#else
-	shadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);
-	#endif
-#endif
-#endif
-#else
-	shadow = 1.;
-#endif
-	diffuseBase += info.diffuse * shadow;
-#endif
-
-#ifdef LIGHT1
-#ifdef SPOTLIGHT1
-	info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightDiffuse1.a);
-#endif
-#ifdef HEMILIGHT1
-	info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightGround1.a);
-#endif
-#if defined(POINTLIGHT1) || defined(DIRLIGHT1)
-	info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightDiffuse1.a);
-#endif
-#ifdef SHADOW1
-#ifdef SHADOWVSM1
-	shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);
-#else
-#ifdef SHADOWPCF1
-#if defined(POINTLIGHT1)
-	shadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x, shadowsInfo1.y);
-#else
-	shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);
-#endif
-#else
-	#if defined(POINTLIGHT1)
-	shadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);
-	#else
-	shadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);
-	#endif
-#endif
-#endif
-#else
-	shadow = 1.;
-#endif
-	diffuseBase += info.diffuse * shadow;
-#endif
-
-#ifdef LIGHT2
-#ifdef SPOTLIGHT2
-	info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightDiffuse2.a);
-#endif
-#ifdef HEMILIGHT2
-	info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightGround2);
-#endif
-#if defined(POINTLIGHT2) || defined(DIRLIGHT2)
-	info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightDiffuse2.a);
-#endif
-#ifdef SHADOW2
-#ifdef SHADOWVSM2
-	shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);
-#else
-#ifdef SHADOWPCF2
-#if defined(POINTLIGHT2)
-	shadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x, shadowsInfo2.y);
-#else
-	shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);
-#endif
-#else
-	#if defined(POINTLIGHT2)
-	shadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);
-	#else
-	shadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);
-	#endif
-#endif	
-#endif	
-#else
-	shadow = 1.;
-#endif
-	diffuseBase += info.diffuse * shadow;
-#endif
-
-#ifdef LIGHT3
-#ifdef SPOTLIGHT3
-	info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightDiffuse3.a);
-#endif
-#ifdef HEMILIGHT3
-	info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightGround3);
-#endif
-#if defined(POINTLIGHT3) || defined(DIRLIGHT3)
-	info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightDiffuse3.a);
-#endif
-#ifdef SHADOW3
-#ifdef SHADOWVSM3
-		shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);
-#else
-#ifdef SHADOWPCF3
-#if defined(POINTLIGHT3)
-	shadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x, shadowsInfo3.y);
-#else
-	shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);
-#endif
-#else
-	#if defined(POINTLIGHT3)
-	shadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);
-	#else
-	shadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);
-	#endif
-#endif	
-#endif	
-#else
-	shadow = 1.;
-#endif
-	diffuseBase += info.diffuse * shadow;
-#endif
+    float glossiness = 0.;
+    
+#include<light0Fragment>
+#include<light1Fragment>
+#include<light2Fragment>
+#include<light3Fragment>
 
 #ifdef VERTEXALPHA
 	alpha *= vColor.a;
@@ -557,10 +96,7 @@ void main(void) {
 	// Composition
 	vec4 color = vec4(finalDiffuse, alpha);
 
-#ifdef FOG
-	float fog = CalcFogFactor();
-	color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;
-#endif
+#include<fogFragment>
 
 	gl_FragColor = color;
 }

+ 11 - 86
materialsLibrary/materials/gradient/gradient.vertex.fx

@@ -15,21 +15,10 @@ attribute vec2 uv2;
 #ifdef VERTEXCOLOR
 attribute vec4 color;
 #endif
-#ifdef BONES
-attribute vec4 matricesIndices;
-attribute vec4 matricesWeights;
-#endif
+#include<bonesDeclaration>
 
 // Uniforms
-
-#ifdef INSTANCES
-attribute vec4 world0;
-attribute vec4 world1;
-attribute vec4 world2;
-attribute vec4 world3;
-#else
-uniform mat4 world;
-#endif
+#include<instancesDeclaration>
 
 uniform mat4 view;
 uniform mat4 viewProjection;
@@ -40,10 +29,6 @@ uniform mat4 diffuseMatrix;
 uniform vec2 vDiffuseInfos;
 #endif
 
-#ifdef BONES
-uniform mat4 mBones[BonesPerMesh];
-#endif
-
 #ifdef POINTSIZE
 uniform float pointSize;
 #endif
@@ -58,56 +43,15 @@ varying vec3 vNormalW;
 varying vec4 vColor;
 #endif
 
-#ifdef CLIPPLANE
-uniform vec4 vClipPlane;
-varying float fClipDistance;
-#endif
+#include<clipPlaneVertexDeclaration>
 
-#ifdef FOG
-varying float fFogDistance;
-#endif
-
-#ifdef SHADOWS
-#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)
-uniform mat4 lightMatrix0;
-varying vec4 vPositionFromLight0;
-#endif
-#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)
-uniform mat4 lightMatrix1;
-varying vec4 vPositionFromLight1;
-#endif
-#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)
-uniform mat4 lightMatrix2;
-varying vec4 vPositionFromLight2;
-#endif
-#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)
-uniform mat4 lightMatrix3;
-varying vec4 vPositionFromLight3;
-#endif
-#endif
+#include<fogVertexDeclaration>
+#include<shadowsVertexDeclaration>
 
 void main(void) {
-	mat4 finalWorld;
+#include<instancesVertex>
+#include<bonesVertex> 
 
-#ifdef INSTANCES
-	finalWorld = mat4(world0, world1, world2, world3);
-#else
-	finalWorld = world;
-#endif
-
-#ifdef BONES
-	mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;
-	mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;
-	mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;
-
-#ifdef BONES4
-	mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;
-	finalWorld = finalWorld * (m0 + m1 + m2 + m3);
-#else
-	finalWorld = finalWorld * (m0 + m1 + m2);
-#endif 
-
-#endif
 	gl_Position = viewProjection * finalWorld * vec4(position, 1.0);
 
 	vec4 worldPos = finalWorld * vec4(position, 1.0);
@@ -137,30 +81,11 @@ void main(void) {
 #endif
 
 	// Clip plane
-#ifdef CLIPPLANE
-	fClipDistance = dot(worldPos, vClipPlane);
-#endif
+#include<clipPlaneVertex>
 
-	// Fog
-#ifdef FOG
-	fFogDistance = (view * worldPos).z;
-#endif
-
-	// Shadows
-#ifdef SHADOWS
-#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)
-	vPositionFromLight0 = lightMatrix0 * worldPos;
-#endif
-#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)
-	vPositionFromLight1 = lightMatrix1 * worldPos;
-#endif
-#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)
-	vPositionFromLight2 = lightMatrix2 * worldPos;
-#endif
-#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)
-	vPositionFromLight3 = lightMatrix3 * worldPos;
-#endif
-#endif
+    // Fog
+#include<fogVertex>
+#include<shadowsVertex>
 
 	// Vertex color
 #ifdef VERTEXCOLOR

+ 10 - 177
materialsLibrary/materials/lava/babylon.lavaMaterial.ts

@@ -131,7 +131,6 @@ module BABYLON {
             }
 
             var engine = scene.getEngine();
-            var needNormals = false;
             var needUVs = false;
 
             this._defines.reset();
@@ -169,85 +168,12 @@ module BABYLON {
 
             var lightIndex = 0;
             if (scene.lightsEnabled && !this.disableLighting) {
-                for (var index = 0; index < scene.lights.length; index++) {
-                    var light = scene.lights[index];
-
-                    if (!light.isEnabled()) {
-                        continue;
-                    }
-
-                    // Excluded check
-                    if (light._excludedMeshesIds.length > 0) {
-                        for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
-                            var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
-
-                            if (excludedMesh) {
-                                light.excludedMeshes.push(excludedMesh);
-                            }
-                        }
-
-                        light._excludedMeshesIds = [];
-                    }
-
-                    // Included check
-                    if (light._includedOnlyMeshesIds.length > 0) {
-                        for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
-                            var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
-
-                            if (includedOnlyMesh) {
-                                light.includedOnlyMeshes.push(includedOnlyMesh);
-                            }
-                        }
-
-                        light._includedOnlyMeshesIds = [];
-                    }
-
-                    if (!light.canAffectMesh(mesh)) {
-                        continue;
-                    }
-                    needNormals = true;
-                    this._defines["LIGHT" + lightIndex] = true;
-
-                    var type;
-                    if (light instanceof SpotLight) {
-                        type = "SPOTLIGHT" + lightIndex;
-                    } else if (light instanceof HemisphericLight) {
-                        type = "HEMILIGHT" + lightIndex;
-                    } else if (light instanceof PointLight) {
-                        type = "POINTLIGHT" + lightIndex;
-                    } else {
-                        type = "DIRLIGHT" + lightIndex;
-                    }
-
-                    this._defines[type] = true;
-
-                    // Shadows
-                    if (scene.shadowsEnabled) {
-                        var shadowGenerator = light.getShadowGenerator();
-                        if (mesh && mesh.receiveShadows && shadowGenerator) {
-                            this._defines["SHADOW" + lightIndex] = true;
-
-                            this._defines.SHADOWS = true;
-
-                            if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
-                                this._defines["SHADOWVSM" + lightIndex] = true;
-                            }
-
-                            if (shadowGenerator.usePoissonSampling) {
-                                this._defines["SHADOWPCF" + lightIndex] = true;
-                            }
-                        }
-                    }
-
-                    lightIndex++;
-                    if (lightIndex === maxSimultaneousLights)
-                        break;
-                }
+                MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
             }
 
             // Attribs
             if (mesh) {
-                if (needNormals && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
+                if (mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
                     this._defines.NORMAL = true;
                 }
                 if (needUVs) {
@@ -265,7 +191,6 @@ module BABYLON {
                         this._defines.VERTEXALPHA = true;
                     }
                 }
-
                 if (mesh.useBones && mesh.computeBonesUsingShaders) {
                     this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
                     this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
@@ -289,29 +214,9 @@ module BABYLON {
                     fallbacks.addFallback(1, "FOG");
                 }
 
-                for (lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
-                    if (!this._defines["LIGHT" + lightIndex]) {
-                        continue;
-                    }
-
-                    if (lightIndex > 0) {
-                        fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
-                    }
-
-                    if (this._defines["SHADOW" + lightIndex]) {
-                        fallbacks.addFallback(0, "SHADOW" + lightIndex);
-                    }
-
-                    if (this._defines["SHADOWPCF" + lightIndex]) {
-                        fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
-                    }
+                MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
 
-                    if (this._defines["SHADOWVSM" + lightIndex]) {
-                        fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
-                    }
-                }
-
-                if (this._defines.NUM_BONE_INFLUENCERS > 0){
+                if (this._defines.NUM_BONE_INFLUENCERS > 0) {
                     fallbacks.addCPUSkinningFallback(0, mesh);
                 }
 
@@ -334,21 +239,8 @@ module BABYLON {
                     attribs.push(VertexBuffer.ColorKind);
                 }
 
-                if (this._defines.NUM_BONE_INFLUENCERS > 0) {
-                    attribs.push(VertexBuffer.MatricesIndicesKind);
-                    attribs.push(VertexBuffer.MatricesWeightsKind);
-                    if (this._defines.NUM_BONE_INFLUENCERS > 4) {
-                        attribs.push(VertexBuffer.MatricesIndicesExtraKind);
-                        attribs.push(VertexBuffer.MatricesWeightsExtraKind);
-                    }
-                }
-
-                if (this._defines.INSTANCES) {
-                    attribs.push("world0");
-                    attribs.push("world1");
-                    attribs.push("world2");
-                    attribs.push("world3");
-                }
+                MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
+                MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
 
                 // Legacy browser patch
                 var shaderName = "lava";
@@ -403,9 +295,7 @@ module BABYLON {
             this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
 
             // Bones
-            if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
-                this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
-            }
+            MaterialHelper.BindBonesParameters(mesh, this._effect);
 
             if (scene.getCachedMaterial() !== this) {
                 // Textures        
@@ -421,10 +311,7 @@ module BABYLON {
                 }
 
                 // Clip plane
-                if (scene.clipPlane) {
-                    var clipPlane = scene.clipPlane;
-                    this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
-                }
+                MaterialHelper.BindClipPlane(this._effect, scene);
 
                 // Point size
                 if (this.pointsCloud) {
@@ -437,58 +324,7 @@ module BABYLON {
             this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
 
             if (scene.lightsEnabled && !this.disableLighting) {
-                var lightIndex = 0;
-                var depthValuesAlreadySet = false;
-                for (var index = 0; index < scene.lights.length; index++) {
-                    var light = scene.lights[index];
-
-                    if (!light.isEnabled()) {
-                        continue;
-                    }
-
-                    if (!light.canAffectMesh(mesh)) {
-                        continue;
-                    }
-
-                    if (light instanceof PointLight) {
-                        // Point Light
-                        light.transferToEffect(this._effect, "vLightData" + lightIndex);
-                    } else if (light instanceof DirectionalLight) {
-                        // Directional Light
-                        light.transferToEffect(this._effect, "vLightData" + lightIndex);
-                    } else if (light instanceof SpotLight) {
-                        // Spot Light
-                        light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
-                    } else if (light instanceof HemisphericLight) {
-                        // Hemispheric Light
-                        light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
-                    }
-
-                    light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
-                    this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
-
-                    // Shadows
-                    if (scene.shadowsEnabled) {
-                        var shadowGenerator = light.getShadowGenerator();
-                        if (mesh.receiveShadows && shadowGenerator) {
-                            if (!(<any>light).needCube()) {
-                                this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
-                            } else {
-                                if (!depthValuesAlreadySet) {
-                                    depthValuesAlreadySet = true;
-                                    this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
-                                }
-                            }
-                            this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
-                            this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
-                        }
-                    }
-
-                    lightIndex++;
-
-                    if (lightIndex === maxSimultaneousLights)
-                        break;
-                }
+                MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
             }
 
             // View
@@ -497,10 +333,7 @@ module BABYLON {
             }
 
             // Fog
-            if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
-                this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
-                this._effect.setColor3("vFogColor", scene.fogColor);
-            }
+            MaterialHelper.BindFogParameters(scene, mesh, this._effect);
 
 
             this._lastTime += scene.getEngine().getDeltaTime();

+ 17 - 481
materialsLibrary/materials/lava/lava.fragment.fx

@@ -27,85 +27,14 @@ varying vec4 vColor;
 #endif
 
 // Lights
-#ifdef LIGHT0
-uniform vec4 vLightData0;
-uniform vec4 vLightDiffuse0;
-#ifdef SHADOW0
-#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)
-varying vec4 vPositionFromLight0;
-uniform sampler2D shadowSampler0;
-#else
-uniform samplerCube shadowSampler0;
-#endif
-uniform vec3 shadowsInfo0;
-#endif
-#ifdef SPOTLIGHT0
-uniform vec4 vLightDirection0;
-#endif
-#ifdef HEMILIGHT0
-uniform vec3 vLightGround0;
-#endif
-#endif
+#include<light0FragmentDeclaration>
+#include<light1FragmentDeclaration>
+#include<light2FragmentDeclaration>
+#include<light3FragmentDeclaration>
 
-#ifdef LIGHT1
-uniform vec4 vLightData1;
-uniform vec4 vLightDiffuse1;
-#ifdef SHADOW1
-#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)
-varying vec4 vPositionFromLight1;
-uniform sampler2D shadowSampler1;
-#else
-uniform samplerCube shadowSampler1;
-#endif
-uniform vec3 shadowsInfo1;
-#endif
-#ifdef SPOTLIGHT1
-uniform vec4 vLightDirection1;
-#endif
-#ifdef HEMILIGHT1
-uniform vec3 vLightGround1;
-#endif
-#endif
 
-#ifdef LIGHT2
-uniform vec4 vLightData2;
-uniform vec4 vLightDiffuse2;
-#ifdef SHADOW2
-#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)
-varying vec4 vPositionFromLight2;
-uniform sampler2D shadowSampler2;
-#else
-uniform samplerCube shadowSampler2;
-#endif
-uniform vec3 shadowsInfo2;
-#endif
-#ifdef SPOTLIGHT2
-uniform vec4 vLightDirection2;
-#endif
-#ifdef HEMILIGHT2
-uniform vec3 vLightGround2;
-#endif
-#endif
-
-#ifdef LIGHT3
-uniform vec4 vLightData3;
-uniform vec4 vLightDiffuse3;
-#ifdef SHADOW3
-#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)
-varying vec4 vPositionFromLight3;
-uniform sampler2D shadowSampler3;
-#else
-uniform samplerCube shadowSampler3;
-#endif
-uniform vec3 shadowsInfo3;
-#endif
-#ifdef SPOTLIGHT3
-uniform vec4 vLightDirection3;
-#endif
-#ifdef HEMILIGHT3
-uniform vec3 vLightGround3;
-#endif
-#endif
+#include<lightsFragmentFunctions>
+#include<shadowsFragmentFunctions>
 
 // Samplers
 #ifdef DIFFUSE
@@ -114,266 +43,10 @@ uniform sampler2D diffuseSampler;
 uniform vec2 vDiffuseInfos;
 #endif
 
-// Shadows
-#ifdef SHADOWS
-
-float unpack(vec4 color)
-{
-	const vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
-	return dot(color, bit_shift);
-}
-
-#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)
-uniform vec2 depthValues;
-
-float computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)
-{
-	vec3 directionToLight = vPositionW - lightPosition;
-	float depth = length(directionToLight);
-	depth = clamp(depth, 0., 1.0);
-
-	directionToLight = normalize(directionToLight);
-	directionToLight.y = - directionToLight.y;
-
-	float shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;
-
-	if (depth > shadow)
-	{
-		return darkness;
-	}
-	return 1.0;
-}
-
-float computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float bias, float darkness, float mapSize)
-{
-	vec3 directionToLight = vPositionW - lightPosition;
-	float depth = length(directionToLight);
-
-	depth = clamp(depth, 0., 1.0);
-	float diskScale = 2.0 / mapSize;
-
-	directionToLight = normalize(directionToLight);
-	directionToLight.y = -directionToLight.y;
-
-	float visibility = 1.;
-
-	vec3 poissonDisk[4];
-	poissonDisk[0] = vec3(-0.094201624, 0.04, -0.039906216);
-	poissonDisk[1] = vec3(0.094558609, -0.04, -0.076890725);
-	poissonDisk[2] = vec3(-0.094184101, 0.01, -0.092938870);
-	poissonDisk[3] = vec3(0.034495938, -0.01, 0.029387760);
-
-	// Poisson Sampling
-	float biasedDepth = depth - bias;
-
-	if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0])) < biasedDepth) visibility -= 0.25;
-	if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1])) < biasedDepth) visibility -= 0.25;
-	if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2])) < biasedDepth) visibility -= 0.25;
-	if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3])) < biasedDepth) visibility -= 0.25;
-
-	return  min(1.0, visibility + darkness);
-}
-#endif
-
-#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) ||  defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)
-float computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)
-{
-	vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;
-	depth = 0.5 * depth + vec3(0.5);
-	vec2 uv = depth.xy;
-
-	if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)
-	{
-		return 1.0;
-	}
-
-	float shadow = unpack(texture2D(shadowSampler, uv)) + bias;
-
-	if (depth.z > shadow)
-	{
-		return darkness;
-	}
-	return 1.;
-}
-
-float computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)
-{
-	vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;
-	depth = 0.5 * depth + vec3(0.5);
-	vec2 uv = depth.xy;
-
-	if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)
-	{
-		return 1.0;
-	}
-
-	float visibility = 1.;
-
-	vec2 poissonDisk[4];
-	poissonDisk[0] = vec2(-0.94201624, -0.39906216);
-	poissonDisk[1] = vec2(0.94558609, -0.76890725);
-	poissonDisk[2] = vec2(-0.094184101, -0.92938870);
-	poissonDisk[3] = vec2(0.34495938, 0.29387760);
-
-	// Poisson Sampling
-	float biasedDepth = depth.z - bias;
-
-	if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;
-	if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;
-	if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;
-	if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;
-
-	return  min(1.0, visibility + darkness);
-}
-
-// Thanks to http://devmaster.net/
-float unpackHalf(vec2 color)
-{
-	return color.x + (color.y / 255.0);
-}
-
-float linstep(float low, float high, float v) {
-	return clamp((v - low) / (high - low), 0.0, 1.0);
-}
-
-float ChebychevInequality(vec2 moments, float compare, float bias)
-{
-	float p = smoothstep(compare - bias, compare, moments.x);
-	float variance = max(moments.y - moments.x * moments.x, 0.02);
-	float d = compare - moments.x;
-	float p_max = linstep(0.2, 1.0, variance / (variance + d * d));
-
-	return clamp(max(p, p_max), 0.0, 1.0);
-}
-
-float computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)
-{
-	vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;
-	depth = 0.5 * depth + vec3(0.5);
-	vec2 uv = depth.xy;
-
-	if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)
-	{
-		return 1.0;
-	}
-
-	vec4 texel = texture2D(shadowSampler, uv);
-
-	vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));
-	return min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);
-}
-#endif
-#endif
-
-
-#ifdef CLIPPLANE
-varying float fClipDistance;
-#endif
+#include<clipPlaneFragmentDeclaration>
 
 // Fog
-#ifdef FOG
-
-#define FOGMODE_NONE    0.
-#define FOGMODE_EXP     1.
-#define FOGMODE_EXP2    2.
-#define FOGMODE_LINEAR  3.
-#define E 2.71828
-
-uniform vec4 vFogInfos;
-uniform vec3 vFogColor;
-varying float fFogDistance;
-
-float CalcFogFactor()
-{
-	float fogCoeff = 1.0;
-	float fogStart = vFogInfos.y;
-	float fogEnd = vFogInfos.z;
-	float fogDensity = vFogInfos.w;
-
-	if (FOGMODE_LINEAR == vFogInfos.x)
-	{
-		fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);
-	}
-	else if (FOGMODE_EXP == vFogInfos.x)
-	{
-		fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);
-	}
-	else if (FOGMODE_EXP2 == vFogInfos.x)
-	{
-		fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);
-	}
-
-	return clamp(fogCoeff, 0.0, 1.0);
-}
-#endif
-
-// Light Computing
-struct lightingInfo
-{
-	vec3 diffuse;
-};
-
-lightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, float range) {
-	lightingInfo result;
-
-	vec3 lightVectorW;
-	float attenuation = 1.0;
-	if (lightData.w == 0.)
-	{
-		vec3 direction = lightData.xyz - vPositionW;
-
-		attenuation = max(0., 1.0 - length(direction) / range);
-		lightVectorW = normalize(direction);
-	}
-	else
-	{
-		lightVectorW = normalize(-lightData.xyz);
-	}
-
-	// diffuse
-	float ndl = max(0., dot(vNormal, lightVectorW));
-	result.diffuse = ndl * diffuseColor * attenuation;
-
-	return result;
-}
-
-lightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, float range) {
-	lightingInfo result;
-
-	vec3 direction = lightData.xyz - vPositionW;
-	vec3 lightVectorW = normalize(direction);
-	float attenuation = max(0., 1.0 - length(direction) / range);
-
-	// diffuse
-	float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));
-	float spotAtten = 0.0;
-
-	if (cosAngle >= lightDirection.w)
-	{
-		cosAngle = max(0., pow(cosAngle, lightData.w));
-		spotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);
-
-		// Diffuse
-		float ndl = max(0., dot(vNormal, -lightDirection.xyz));
-		result.diffuse = ndl * spotAtten * diffuseColor * attenuation;
-
-		return result;
-	}
-
-	result.diffuse = vec3(0.);
-
-	return result;
-}
-
-lightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 groundColor) {
-	lightingInfo result;
-
-	// Diffuse
-	float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;
-	result.diffuse = mix(groundColor, diffuseColor, ndl);
-
-	return result;
-}
+#include<fogFragmentDeclaration>
 
 
 float random( vec3 scale, float seed ){
@@ -382,11 +55,7 @@ float random( vec3 scale, float seed ){
 
 
 void main(void) {
-	// Clip plane
-#ifdef CLIPPLANE
-	if (fClipDistance > 0.0)
-		discard;
-#endif
+#include<clipPlaneFragment>
 
 	vec3 viewDirectionW = normalize(vEyePosition - vPositionW);
 
@@ -424,7 +93,7 @@ void main(void) {
     fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );
 
     baseColor = mix( baseColor, vec4( fogColor, baseColor.w ), fogFactor );
-
+    diffuseColor = baseColor.rgb;
     ///// END MAGMA ////
 
 
@@ -453,142 +122,13 @@ void main(void) {
 	// Lighting
 	vec3 diffuseBase = vec3(0., 0., 0.);
 	float shadow = 1.;
+    float glossiness = 0.;
+    
+#include<light0Fragment>
+#include<light1Fragment>
+#include<light2Fragment>
+#include<light3Fragment>
 
-#ifdef LIGHT0
-#ifdef SPOTLIGHT0
-	lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightDiffuse0.a);
-#endif
-#ifdef HEMILIGHT0
-	lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightGround0);
-#endif
-#if defined(POINTLIGHT0) || defined(DIRLIGHT0)
-	lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightDiffuse0.a);
-#endif
-#ifdef SHADOW0
-#ifdef SHADOWVSM0
-	shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);
-#else
-#ifdef SHADOWPCF0
-	#if defined(POINTLIGHT0)
-	shadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x, shadowsInfo0.y);
-	#else
-	shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);
-	#endif
-#else
-	#if defined(POINTLIGHT0)
-	shadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);
-	#else
-	shadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);
-	#endif
-#endif
-#endif
-#else
-	shadow = 1.;
-#endif
-	diffuseBase += info.diffuse * shadow;
-#endif
-
-#ifdef LIGHT1
-#ifdef SPOTLIGHT1
-	info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightDiffuse1.a);
-#endif
-#ifdef HEMILIGHT1
-	info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightGround1.a);
-#endif
-#if defined(POINTLIGHT1) || defined(DIRLIGHT1)
-	info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightDiffuse1.a);
-#endif
-#ifdef SHADOW1
-#ifdef SHADOWVSM1
-	shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);
-#else
-#ifdef SHADOWPCF1
-#if defined(POINTLIGHT1)
-	shadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x, shadowsInfo1.y);
-#else
-	shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);
-#endif
-#else
-	#if defined(POINTLIGHT1)
-	shadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);
-	#else
-	shadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);
-	#endif
-#endif
-#endif
-#else
-	shadow = 1.;
-#endif
-	diffuseBase += info.diffuse * shadow;
-#endif
-
-#ifdef LIGHT2
-#ifdef SPOTLIGHT2
-	info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightDiffuse2.a);
-#endif
-#ifdef HEMILIGHT2
-	info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightGround2);
-#endif
-#if defined(POINTLIGHT2) || defined(DIRLIGHT2)
-	info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightDiffuse2.a);
-#endif
-#ifdef SHADOW2
-#ifdef SHADOWVSM2
-	shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);
-#else
-#ifdef SHADOWPCF2
-#if defined(POINTLIGHT2)
-	shadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x, shadowsInfo2.y);
-#else
-	shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);
-#endif
-#else
-	#if defined(POINTLIGHT2)
-	shadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);
-	#else
-	shadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);
-	#endif
-#endif	
-#endif	
-#else
-	shadow = 1.;
-#endif
-	diffuseBase += info.diffuse * shadow;
-#endif
-
-#ifdef LIGHT3
-#ifdef SPOTLIGHT3
-	info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightDiffuse3.a);
-#endif
-#ifdef HEMILIGHT3
-	info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightGround3);
-#endif
-#if defined(POINTLIGHT3) || defined(DIRLIGHT3)
-	info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightDiffuse3.a);
-#endif
-#ifdef SHADOW3
-#ifdef SHADOWVSM3
-		shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);
-#else
-#ifdef SHADOWPCF3
-#if defined(POINTLIGHT3)
-	shadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x, shadowsInfo3.y);
-#else
-	shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);
-#endif
-#else
-	#if defined(POINTLIGHT3)
-	shadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);
-	#else
-	shadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);
-	#endif
-#endif	
-#endif	
-#else
-	shadow = 1.;
-#endif
-	diffuseBase += info.diffuse * shadow;
-#endif
 
 #ifdef VERTEXALPHA
 	alpha *= vColor.a;
@@ -599,11 +139,7 @@ void main(void) {
 	// Composition
 	vec4 color = vec4(finalDiffuse, alpha);
 
-#ifdef FOG
-	float fog = CalcFogFactor();
-	color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;
-#endif
-
+#include<fogFragment>
 
 	gl_FragColor = color;
 }

+ 12 - 105
materialsLibrary/materials/lava/lava.vertex.fx

@@ -20,16 +20,10 @@ attribute vec2 uv2;
 attribute vec4 color;
 #endif
 
-// Uniforms
+#include<bonesDeclaration>
 
-#ifdef INSTANCES
-attribute vec4 world0;
-attribute vec4 world1;
-attribute vec4 world2;
-attribute vec4 world3;
-#else
-uniform mat4 world;
-#endif
+// Uniforms
+#include<instancesDeclaration>
 
 uniform mat4 view;
 uniform mat4 viewProjection;
@@ -40,17 +34,6 @@ uniform mat4 diffuseMatrix;
 uniform vec2 vDiffuseInfos;
 #endif
 
-#if NUM_BONE_INFLUENCERS > 0
-	uniform mat4 mBones[BonesPerMesh];
-
-	attribute vec4 matricesIndices;
-	attribute vec4 matricesWeights;
-	#if NUM_BONE_INFLUENCERS > 4
-		attribute vec4 matricesIndicesExtra;
-		attribute vec4 matricesWeightsExtra;
-	#endif
-#endif
-
 #ifdef POINTSIZE
 uniform float pointSize;
 #endif
@@ -65,33 +48,11 @@ varying vec3 vNormalW;
 varying vec4 vColor;
 #endif
 
-#ifdef CLIPPLANE
-uniform vec4 vClipPlane;
-varying float fClipDistance;
-#endif
 
-#ifdef FOG
-varying float fFogDistance;
-#endif
+#include<clipPlaneVertexDeclaration>
 
-#ifdef SHADOWS
-#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)
-uniform mat4 lightMatrix0;
-varying vec4 vPositionFromLight0;
-#endif
-#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)
-uniform mat4 lightMatrix1;
-varying vec4 vPositionFromLight1;
-#endif
-#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)
-uniform mat4 lightMatrix2;
-varying vec4 vPositionFromLight2;
-#endif
-#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)
-uniform mat4 lightMatrix3;
-varying vec4 vPositionFromLight3;
-#endif
-#endif
+#include<fogVertexDeclaration>
+#include<shadowsVertexDeclaration>
 
 /* NOISE FUNCTIONS */
 ////// ASHIMA webgl noise
@@ -202,45 +163,11 @@ float turbulence( vec3 p ) {
 }
 
 void main(void) {
-	mat4 finalWorld;
-
-#ifdef INSTANCES
-	finalWorld = mat4(world0, world1, world2, world3);
-#else
-	finalWorld = world;
-#endif
-
-#if NUM_BONE_INFLUENCERS > 0
-	mat4 influence;
-	influence = mBones[int(matricesIndices[0])] * matricesWeights[0];
-
-	#if NUM_BONE_INFLUENCERS > 1
-		influence += mBones[int(matricesIndices[1])] * matricesWeights[1];
-	#endif 
-	#if NUM_BONE_INFLUENCERS > 2
-		influence += mBones[int(matricesIndices[2])] * matricesWeights[2];
-	#endif	
-	#if NUM_BONE_INFLUENCERS > 3
-		influence += mBones[int(matricesIndices[3])] * matricesWeights[3];
-	#endif	
-
-	#if NUM_BONE_INFLUENCERS > 4
-		influence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];
-	#endif
-	#if NUM_BONE_INFLUENCERS > 5
-		influence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];
-	#endif	
-	#if NUM_BONE_INFLUENCERS > 6
-		influence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];
-	#endif	
-	#if NUM_BONE_INFLUENCERS > 7
-		influence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];
-	#endif	
-
-	finalWorld = finalWorld * influence;
-#endif
 
+#include<instancesVertex>
+#include<bonesVertex>
 
+#ifdef NORMAL
     // get a turbulent 3d noise using the normal, normal to high freq
     noise = 10.0 *  -.10 * turbulence( .5 * normal + time*1.15 );
     // get a 3d noise using the position, low frequency
@@ -256,7 +183,6 @@ void main(void) {
 	vec4 worldPos = finalWorld * vec4(newPosition, 1.0);
 	vPositionW = vec3(worldPos);
 
-#ifdef NORMAL
 	vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));
 #endif
 
@@ -280,30 +206,11 @@ void main(void) {
 #endif
 
 	// Clip plane
-#ifdef CLIPPLANE
-	fClipDistance = dot(worldPos, vClipPlane);
-#endif
+#include<clipPlaneVertex>
 
 	// Fog
-#ifdef FOG
-	fFogDistance = (view * worldPos).z;
-#endif
-
-	// Shadows
-#ifdef SHADOWS
-#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)
-	vPositionFromLight0 = lightMatrix0 * worldPos;
-#endif
-#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)
-	vPositionFromLight1 = lightMatrix1 * worldPos;
-#endif
-#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)
-	vPositionFromLight2 = lightMatrix2 * worldPos;
-#endif
-#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)
-	vPositionFromLight3 = lightMatrix3 * worldPos;
-#endif
-#endif
+#include<fogVertex>
+#include<shadowsVertex>
 
 	// Vertex color
 #ifdef VERTEXCOLOR

+ 4 - 1
materialsLibrary/materials/normal/normal.fragment.fx

@@ -60,7 +60,10 @@ void main(void) {
 	baseColor.rgb *= vDiffuseInfos.y;
 #endif
 
-baseColor = mix(baseColor, vec4(vNormalW, 1.0), 0.5);
+#ifdef NORMAL
+    baseColor = mix(baseColor, vec4(vNormalW, 1.0), 0.5);
+#endif
+
 #ifdef VERTEXCOLOR
 	baseColor.rgb *= vColor.rgb;
 #endif

+ 28 - 10
materialsLibrary/materials/pbr/babylon.pbrMaterial.ts

@@ -89,6 +89,8 @@ module BABYLON {
         public LINKREFRACTIONTOTRANSPARENCY = false;
         public REFRACTIONMAPINLINEARSPACE = false;
         public LODBASEDMICROSFURACE = false;
+        public USEPHYSICALLIGHTFALLOFF = false;
+        public RADIANCEOVERALPHA = false;
 
         constructor() {
             super();
@@ -148,26 +150,28 @@ module BABYLON {
         public albedoColor = new Color3(1, 1, 1);
         public reflectivityColor = new Color3(1, 1, 1);
         public reflectionColor = new Color3(0.5, 0.5, 0.5);
-        public microSurface = 0.5;
         public emissiveColor = new Color3(0, 0, 0);
-        public useAlphaFromAlbedoTexture = false;
-        public useEmissiveAsIllumination = false;
-        public linkEmissiveWithAlbedo = false;
-        public useSpecularOverAlpha = true;
-        public disableLighting = false;
-        
+        public microSurface = 0.5;
         public indexOfRefraction = 0.66;
         public invertRefractionY = false;
-        public linkRefractionWithTransparency = false;
-
-        public useLightmapAsShadowmap = false;
 
         public opacityFresnelParameters: FresnelParameters;
         public emissiveFresnelParameters: FresnelParameters;
 
+        public linkRefractionWithTransparency = false;
+        public linkEmissiveWithAlbedo = false;
+        
+        public useLightmapAsShadowmap = false;
+        public useEmissiveAsIllumination = false;
+        public useAlphaFromAlbedoTexture = false;
+        public useSpecularOverAlpha = true;
         public useMicroSurfaceFromReflectivityMapAlpha = false;
         public useAutoMicroSurfaceFromReflectivityMap = false;
         public useScalarInLinearSpace = false;
+        public usePhysicalLightFalloff = true;
+        public useRadianceOverAlpha = true;
+        
+        public disableLighting = false;
 
         private _renderTargets = new SmartArray<RenderTargetTexture>(16);
         private _worldViewProjectionMatrix = Matrix.Zero();
@@ -561,6 +565,14 @@ module BABYLON {
             if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
                 this._defines.SPECULAROVERALPHA = true;
             }
+            
+            if (this.usePhysicalLightFalloff) {
+                this._defines.USEPHYSICALLIGHTFALLOFF = true;
+            }
+            
+            if (this.useRadianceOverAlpha) {
+                this._defines.RADIANCEOVERALPHA = true;
+            }
 
             // Attribs
             if (mesh) {
@@ -1131,6 +1143,8 @@ module BABYLON {
             newPBRMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
             newPBRMaterial.indexOfRefraction = this.indexOfRefraction;
             newPBRMaterial.invertRefractionY = this.invertRefractionY;
+            newPBRMaterial.usePhysicalLightFalloff = this.usePhysicalLightFalloff;
+            newPBRMaterial.useRadianceOverAlpha = this.useRadianceOverAlpha;
 
             newPBRMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
             newPBRMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
@@ -1215,6 +1229,8 @@ module BABYLON {
             serializationObject.useSpecularOverAlpha = this.useSpecularOverAlpha;
             serializationObject.indexOfRefraction = this.indexOfRefraction;
             serializationObject.invertRefractionY = this.invertRefractionY;
+            serializationObject.usePhysicalLightFalloff = this.usePhysicalLightFalloff;
+            serializationObject.useRadianceOverAlpha = this.useRadianceOverAlpha;
 
             serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
             serializationObject.opacityFresnelParameters = this.opacityFresnelParameters.serialize();
@@ -1312,6 +1328,8 @@ module BABYLON {
             material.useSpecularOverAlpha = source.useSpecularOverAlpha;
             material.indexOfRefraction = source.indexOfRefraction;
             material.invertRefractionY = source.invertRefractionY;
+            material.usePhysicalLightFalloff = source.usePhysicalLightFalloff;
+            material.useRadianceOverAlpha = source.useRadianceOverAlpha;
 
             material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
             material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);

+ 17 - 10
materialsLibrary/materials/pbr/pbr.fragment.fx

@@ -269,6 +269,17 @@ vec3 toGammaSpace(vec3 color)
     return vec3(pow(color.r, 1.0 / 2.2), pow(color.g, 1.0 / 2.2), pow(color.b, 1.0 / 2.2));
 }
 
+float computeLightFalloff(vec3 lightOffset, float lightDistanceSquared, float range)
+{
+    #ifdef USEPHYSICALLIGHTFALLOFF
+        float lightDistanceFalloff = 1.0 / ((lightDistanceSquared + 0.0001));
+        return lightDistanceFalloff;
+    #else
+        float lightFalloff = max(0., 1.0 - length(lightOffset) / range);
+        return lightFalloff;
+    #endif
+}
+
 #ifdef CAMERATONEMAP
     vec3 toneMaps(vec3 color)
     {
@@ -620,11 +631,8 @@ lightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData,
     if (lightData.w == 0.)
     {
         vec3 lightOffset = lightData.xyz - vPositionW;
-        
-        // Inverse squared falloff.
         float lightDistanceSquared = dot(lightOffset, lightOffset);
-        float lightDistanceFalloff = 1.0 / ((lightDistanceSquared + 0.0001) * range);
-        attenuation = lightDistanceFalloff;
+        attenuation = computeLightFalloff(lightOffset, lightDistanceSquared, range);
         
         lightDistance = sqrt(lightDistanceSquared);
         lightDirection = normalize(lightOffset);
@@ -673,8 +681,7 @@ lightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightDa
         
         // Inverse squared falloff.
         float lightDistanceSquared = dot(lightOffset, lightOffset);
-        float lightDistanceFalloff = 1.0 / ((lightDistanceSquared + 0.0001) * range);
-        float attenuation = lightDistanceFalloff;
+        float attenuation = computeLightFalloff(lightOffset, lightDistanceSquared, range);
         
         // Directional falloff.
         attenuation *= cosAngle;
@@ -1273,12 +1280,12 @@ vec3 surfaceEmissiveColor = vEmissiveColor;
     vec3 finalSpecular = vec3(0.0);
 #endif
 
-#ifdef OVERLOADEDSHADOWVALUES
-    finalSpecular = mix(finalSpecular, vec3(0.0), (1.0 - vOverloadedShadowIntensity.y));
+#ifdef SPECULAROVERALPHA
+    alpha = clamp(alpha + getLuminance(finalSpecular), 0., 1.);
 #endif
 
-#ifdef SPECULAROVERALPHA
-    alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);
+#ifdef RADIANCEOVERALPHA
+    alpha = clamp(alpha + getLuminance(environmentRadiance), 0., 1.);
 #endif
 
 // Composition

+ 1 - 18
materialsLibrary/test/index.html

@@ -215,15 +215,6 @@
 					skybox.material = skyboxMaterial;
 					currentMesh.isVisible = true;
 					fur.resetFur();
-					
-                    options.lightRange = 1000;
-                    hemisphericLight.range = 1000;
-                    options.lightRange = 1000;
-                    directionalLight.range = 1000;
-                    options.lightRange = 1000;
-                    pointLight.range = 1000;
-                    options.lightRange = 1000;
-                    spotLight.range = 1000;
                     
 					switch (options.material) {
 						case "simple":
@@ -248,14 +239,6 @@
 							break;
 						case "pbr":
 							currentMaterial = pbr;
-                            options.lightRange = 1;
-                            hemisphericLight.range = 1;
-                            options.lightRange = 1;
-                            directionalLight.range = 1;
-                            options.lightRange = 1;
-                            pointLight.range = 1;
-                            options.lightRange = 1;
-                            spotLight.range = 1;
 							break;
 						case "fur":
 							currentMaterial = fur.material;
@@ -329,7 +312,7 @@
                     directionalLight.range = options.lightRange;
                     pointLight.range = options.lightRange;
                     spotLight.range = options.lightRange;
-                }).listen();
+                });
                 
                 f1.add(options, 'lightRadius').onChange(function() {
                     hemisphericLight.radius = options.lightRadius;

File diff suppressed because it is too large
+ 66 - 27
materialsLibrary/test/refs/babylon.max.js


+ 25 - 1
src/Mesh/babylon.mesh.vertexData.ts

@@ -1106,7 +1106,31 @@
 
             return vertexData;
         }
-
+        
+        public static CreateLineSystem(options: {lines: Vector3[][]}): VertexData {
+            var indices = [];
+            var positions = [];
+            var lines = options.lines;
+            var idx = 0;
+            
+            for (var l = 0; l < lines.length; l++) {
+                var points = lines[l];
+                for (var index = 0; index < points.length; index++) {
+                    positions.push(points[index].x, points[index].y, points[index].z);
+                    
+                    if (index > 0) {
+                        indices.push(idx - 1);
+                        indices.push(idx);
+                    }
+                    idx ++;
+                }               
+            }
+            var vertexData = new VertexData();
+            vertexData.indices = indices;
+            vertexData.positions = positions;
+            return vertexData;
+        }
+        
         public static CreateLines(options: { points: Vector3[] }): VertexData {
             var indices = [];
             var positions = [];

+ 28 - 0
src/Mesh/babylon.meshBuilder.ts

@@ -151,6 +151,34 @@
 
             return torusKnot;
         }
+        
+        public static CreateLineSystem(name: string, options: {lines: Vector3[][], updatable: boolean, instance?: LinesMesh}, scene: Scene): LinesMesh {
+            var instance = options.instance;
+            var lines = options.lines;
+            
+            if (instance) { // lines update
+                var positionFunction = positions => {
+                    var i = 0;
+                    for (var l = 0; l < lines.length; l++) {
+                        var points = lines[l];
+                        for (var p = 0; p < points.length; p++) {
+                            positions[i] = points[p].x;
+                            positions[i + 1] = points[p].y;
+                            positions[i + 2] = points[p].z;
+                            i += 3;
+                        }
+                    }
+                };
+                instance.updateMeshPositions(positionFunction, false);
+                return instance;
+            }
+            
+            // line system creation
+            var lineSystem = new LinesMesh(name, scene);
+            var vertexData = VertexData.CreateLineSystem(options);
+            vertexData.applyToMesh(lineSystem, options.updatable);
+            return lineSystem;
+        }
 
         public static CreateLines(name: string, options: { points: Vector3[], updatable?: boolean, instance?: LinesMesh }, scene: Scene): LinesMesh {
             var instance = options.instance;