Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #version 450 core
- /*Copyright 2009-2016 DIVIDE-Studio*/
- #extension GL_ARB_shader_draw_parameters : require
- #extension GL_ARB_gpu_shader5 : require
- #define GPU_VENDOR_AMD 1
- #define GPU_VENDOR_NVIDIA 0
- #define GPU_VENDOR_INTEL 2
- #define GPU_VENDOR_OTHER 3
- #define GPU_VENDOR 0
- #define _DEBUG
- #define FRAG_SHADER
- #define SKIP_TEXTURES
- #define USE_DOUBLE_SIDED
- #define USE_SHADING_PHONG
- //#pragma optionNV(fastmath on)
- //#pragma optionNV(fastprecision on)
- //#pragma optionNV(inline all)
- //#pragma optionNV(ifcvt none)
- //#pragma optionNV(strict on)
- //#pragma optionNV(unroll all)
- #define USE_HIZ_CULLING
- const uint MAX_SPLITS_PER_LIGHT = 6;
- const uint MAX_POSSIBLE_LIGHTS = 1024;
- const int MAX_VISIBLE_NODES = 1024;
- const float Z_TEST_SIGMA = 0.0001;
- const float ALPHA_DISCARD_THRESHOLD = 0.05;
- const uint DEPTH_EXP_WARP = 32;
- #define USE_HIZ_CULLING
- #define MAX_CLIP_PLANES 6
- #define MAX_SHADOW_CASTING_LIGHTS 5
- #define MAX_LIGHT_TYPES 3
- #define BUFFER_GPU_BLOCK 0
- #define BUFFER_GPU_COMMANDS 1
- #define BUFFER_LIGHT_NORMAL 2
- #define BUFFER_LIGHT_SHADOW 3
- #define BUFFER_LIGHT_INDICES 4
- #define BUFFER_NODE_INFO 5
- #define BUFFER_SCENE_DATA 7
- #define FORWARD_PLUS_TILE_RES 16
- #define MAX_NUM_LIGHTS_PER_TILE 544
- #define LIGHT_INDEX_BUFFER_SENTINEL 2147483647
- #define MAX_TEXTURE_SLOTS 32
- #define MAX_TEXTURE_SLOTS 32
- #define MAX_TEXTURE_SLOTS 32
- #define TEXTURE_UNIT0 0
- #define TEXTURE_UNIT1 1
- #define TEXTURE_NORMALMAP 2
- #define TEXTURE_OPACITY 3
- #define TEXTURE_SPECULAR 4
- #define TEXTURE_PROJECTION 5
- #define TEXTURE_DEPTH_MAP 6
- #define TEXTURE_REFLECTION 7
- #define TEXTURE_REFRACTION 8
- #define SHADOW_CUBE_MAP_ARRAY 10
- #define SHADOW_SINGLE_MAP_ARRAY 11
- #define SHADOW_LAYERED_MAP_ARRAY 12
- in PerVertexData{
- flat uint dvd_drawID;
- vec2 _texCoord;
- vec4 _vertexW;
- vec4 _vertexWV;
- vec3 _normalWV;
- vec3 _tangentWV;
- vec3 _bitangentWV;
- } f_in;
- #define VAR f_in
- #ifndef _NODE_DATA_INPUT_CMN_
- #define _NODE_DATA_INPUT_CMN_
- #if defined(COMPUTE_SHADER)
- struct IndirectDrawCommand {
- uint count;
- uint instanceCount;
- uint firstIndex;
- uint baseVertex;
- uint baseInstance;
- };
- layout(binding = BUFFER_GPU_COMMANDS, std430) coherent buffer dvd_GPUCmds
- {
- IndirectDrawCommand dvd_drawCommands[MAX_VISIBLE_NODES];
- };
- #endif
- layout(binding = BUFFER_GPU_BLOCK, std140) uniform dvd_GPUBlock
- {
- mat4 dvd_ProjectionMatrix;
- mat4 dvd_ViewMatrix;
- mat4 dvd_ViewProjectionMatrix;
- vec4 dvd_cameraPosition; ///xyz - position, w - aspect ratio
- vec4 dvd_ViewPort;
- vec4 dvd_ZPlanesCombined; //xy - current, zw - main scene
- vec4 dvd_invScreenDimensions;
- vec4 dvd_renderProperties;
- vec4 dvd_frustumPlanes[6];
- vec4 dvd_clip_plane[MAX_CLIP_PLANES];
- };
- #define dvd_shadowArrayOffset int(dvd_renderProperties.x)
- #define dvd_GSInvocationLimit int(dvd_renderProperties.y)
- #define dvd_aspectRatio dvd_cameraPosition.w
- #define dvd_fieldOfView dvd_renderProperties.z
- #define dvd_tanHalfFieldOfView dvd_renderProperties.w
- layout(binding = BUFFER_SCENE_DATA, std140) uniform dvd_SceneData
- {
- vec4 dvd_fogDetails;
- vec4 dvd_windDetails;
- vec4 dvd_shadowingSettings;
- vec4 dvd_otherData;
- vec4 dvd_otherData2;
- uvec4 dvd_lightCountPerType;
- //uint dvd_lightCountPerType[MAX_LIGHT_TYPES];
- };
- #define dvd_fogColour dvd_fogDetails.xyz
- #define dvd_fogDensity dvd_fogDetails.w
- #define dvd_time int(dvd_otherData.x)
- #define dvd_showDebugInfo int(dvd_otherData.y)
- int dvd_deltaTime() {
- return int(dvd_otherData2.x);
- }
- bool dvd_shadowsEnabled() {
- return int(dvd_otherData.z) == 1;
- }
- #if defined(VERT_SHADER)
- invariant gl_Position;
- //out float gl_ClipDistance[MAX_CLIP_PLANES];
- void setClipPlanes(in vec4 worldSpaceVertex) {
- #if MAX_CLIP_PLANES > 0
- gl_ClipDistance[0] = dot(worldSpaceVertex, dvd_clip_plane[0]);
- # if MAX_CLIP_PLANES > 1
- gl_ClipDistance[1] = dot(worldSpaceVertex, dvd_clip_plane[1]);
- # if MAX_CLIP_PLANES > 2
- gl_ClipDistance[2] = dot(worldSpaceVertex, dvd_clip_plane[2]);
- # if MAX_CLIP_PLANES > 3
- gl_ClipDistance[3] = dot(worldSpaceVertex, dvd_clip_plane[3]);
- # if MAX_CLIP_PLANES > 4
- gl_ClipDistance[4] = dot(worldSpaceVertex, dvd_clip_plane[4]);
- # if MAX_CLIP_PLANES > 5
- gl_ClipDistance[5] = dot(worldSpaceVertex, dvd_clip_plane[5]);
- # endif
- # endif
- # endif
- # endif
- # endif
- #endif
- }
- #endif
- //mix(false, true, condition);
- #endif //_NODE_DATA_INPUT_CMN_
- #line 127
- #if !defined(HAS_TRANSPARENCY)
- layout(early_fragment_tests) in;
- #endif
- #ifndef _BRDF_FRAG_
- #define _BRDF_FRAG_
- #ifndef _LIGHTING_DEFAULTS_FRAG_
- #define _LIGHTING_DEFAULTS_FRAG_
- #ifndef _NODE_BUFFERED_INPUT_CMN_
- #define _NODE_BUFFERED_INPUT_CMN_
- struct NodeData {
- mat4 _worldMatrix;
- // [0][0] ... [2][2] = normal matrix
- // [0][3] = bone count
- // [3][0] ... [3][3] = bounding sphere
- mat4 _normalMatrixWV;
- // [0][0] ... [0][3] = albedo
- // [1][0] ... [1][3] = specular
- // [2][0] ... [2][3] = emissive
- // [3][0] = is translucent
- // [3][1] = texture operation
- // [3][2] = texture count
- // [3][3] = parallax factor
- mat4 _colourMatrix;
- // x = selection flag
- // y = is shadow received
- // z = lod level
- // w = reserved
- vec4 _properties;
- };
- layout(binding = BUFFER_NODE_INFO, std430) coherent readonly buffer dvd_MatrixBlock
- {
- NodeData dvd_Matrices[MAX_VISIBLE_NODES];
- };
- mat4 dvd_WorldMatrix() {
- return dvd_Matrices[VAR.dvd_drawID]._worldMatrix;
- }
- mat3 dvd_NormalMatrixWV() {
- return mat3(dvd_Matrices[VAR.dvd_drawID]._normalMatrixWV);
- }
- ivec4 dvd_BufferIntegerValues() {
- return ivec4(dvd_Matrices[VAR.dvd_drawID]._properties);
- }
- #if defined(VERT_SHADER)
- #define dvd_boneCount uint(dvd_Matrices[VAR.dvd_drawID]._normalMatrixWV[0][3])
- #endif
- // x - isSelected/isHighlighted; y - isShadowMapped; z - lodLevel, w - occlusion cull data
- #define dvd_lodLevel dvd_BufferIntegerValues().z
- #define dvd_customData dvd_Matrices[VAR.dvd_drawID]._properties.w
- #if defined(FRAG_SHADER)
- // x - useAlphaTest; y - textureOperation; z - textureCount, w - parallax/relief mapping factor
- #define buffer_matProperties dvd_Matrices[VAR.dvd_drawID]._colourMatrix[3]
- #define dvd_isSelected (dvd_BufferIntegerValues().x < -0.5)
- #define dvd_isHighlighted (dvd_BufferIntegerValues().x > 0.5)
- #define dvd_shadowMapping (dvd_BufferIntegerValues().y > 0.0)
- #define dvd_useAlphaTest (buffer_matProperties.x > 0.0)
- #define dvd_texOperation uint(buffer_matProperties.y)
- #define dvd_textureCount uint(buffer_matProperties.z)
- #define dvd_parallaxFactor buffer_matProperties.w
- #define dvd_reliefFactor dvd_parallaxFactor
- #endif
- #endif //_NODE_BUFFERED_INPUT_CMN_
- uniform float projectedTextureMixWeight;
- layout(binding = TEXTURE_PROJECTION) uniform sampler2D texDiffuseProjected;
- #define PRECISION 0.000001
- float DIST_TO_ZERO(float val) {
- return 1.0 - (step(-PRECISION, val) * (1.0 - step(PRECISION, val)));
- }
- float saturate(float v) { return clamp(v, 0.0, 1.0); }
- vec3 saturate(vec3 v) { return clamp(v, 0.0, 1.0); }
- vec4 saturate(vec4 v) { return clamp(v, 0.0, 1.0); }
- void projectTexture(in vec3 PoxPosInMap, inout vec4 targetTexture){
- vec4 projectedTex = texture(texDiffuseProjected, vec2(PoxPosInMap.s, 1.0-PoxPosInMap.t));
- targetTexture.xyz = mix(targetTexture.xyz, projectedTex.xyz, projectedTextureMixWeight);
- }
- vec3 applyFogColour(in vec3 colour){
- const float LOG2 = 1.442695;
- float zDepth = gl_FragCoord.z / gl_FragCoord.w;
- return mix(dvd_fogColour, colour, clamp(exp2(-dvd_fogDensity * dvd_fogDensity * zDepth * zDepth * LOG2), 0.0, 1.0));
- }
- vec4 applyFog(in vec4 colour) {
- return vec4(mix(applyFogColour(colour.rgb), colour.rgb, dvd_fogDensity), colour.a);
- }
- float ToLinearDepth(in float depthIn) {
- #if defined(USE_SCENE_ZPLANES)
- float n = dvd_ZPlanesCombined.z;
- float f = dvd_ZPlanesCombined.w * 0.5;
- #else
- float n = dvd_ZPlanesCombined.x;
- float f = dvd_ZPlanesCombined.y * 0.5;
- #endif
- return (2 * n) / (f + n - (depthIn) * (f - n));
- }
- float ToLinearDepth(in float depthIn, in mat4 projMatrix) {
- return projMatrix[3][2] / (depthIn - projMatrix[2][2]);
- }
- bool InRangeExclusive(in float value, in float min, in float max) {
- return value > min && value < max;
- }
- vec4 positionFromDepth(in float depth,
- in mat4 invProjectionMatrix,
- in vec2 uv) {
- vec4 pos = vec4(2.0 * uv.x - 1.0,
- 2.0 * uv.y - 1.0,
- 2.0 * depth - 1.0,
- 1.0);
- pos = invProjectionMatrix * pos;
- pos /= pos.w;
- return pos;
- }
- float luminance(in vec3 rgb) {
- const vec3 kLum = vec3(0.299, 0.587, 0.114);
- return max(dot(rgb, kLum), 0.0001); // prevent zero result
- }
- const float gamma = 2.2;
- const float invGamma = 1.0 / gamma;
- const vec3 invGammaVec = vec3(invGamma);
- const vec3 gammaVec = vec3(gamma);
- float ToLinear(float v) { return pow(v, gamma); }
- vec3 ToLinear(vec3 v) { return pow(v, gammaVec); }
- vec4 ToLinear(vec4 v) { return vec4(pow(v.rgb, gammaVec), v.a); }
- float ToSRGB(float v) { return pow(v, invGamma); }
- vec3 ToSRGB(vec3 v) { return pow(v, invGammaVec); }
- vec4 ToSRGB(vec4 v) { return vec4(pow(v.rgb, invGammaVec), v.a);}
- float Gloss(vec3 bump)
- {
- float gloss = 1.0;
- /*if (do_toksvig)
- {
- // Compute the "Toksvig Factor"
- float rlen = 1.0 / saturate(length(bump));
- gloss = 1.0 / (1.0 + power*(rlen - 1.0));
- }
- if (do_toksmap)
- {
- // Fetch pre-computed "Toksvig Factor"
- // and adjust for specified power
- gloss = texture2D(gloss_map, texcoord).r;
- gloss /= mix(power / baked_power, 1.0, gloss);
- }
- */
- return gloss;
- }
- #endif //_LIGHTING_DEFAULTS_FRAG_
- #ifndef _LIGHT_INPUT_CMN_
- #define _LIGHT_INPUT_CMN_
- #if defined(COMPUTE_SHADER)
- # define ACCESS
- #else
- # define ACCESS readonly
- #endif
- const int LIGHT_DIRECTIONAL = 0;
- const int LIGHT_OMNIDIRECTIONAL = 1;
- const int LIGHT_SPOT = 2;
- struct Light {
- /// rgb = colour
- /// w = reserved
- vec4 _colour;
- /// xyz = light positon (or direction for Directional lights)
- /// w = range
- vec4 _positionWV;
- /// xyz = spot direction
- /// w = spot angle
- vec4 _directionWV;
- /// x = light type: 0.0 - directional, 1.0 - point, 2.0 - spot
- /// y = casts shadows
- /// z = shadow block index
- /// w = if directional light : csm split count else : reserved
- ivec4 _options;
- };
- layout(binding = BUFFER_LIGHT_NORMAL, std430) coherent ACCESS buffer dvd_LightBlock
- {
- Light dvd_LightSource[MAX_POSSIBLE_LIGHTS];
- };
- layout(binding = BUFFER_LIGHT_INDICES, std430) coherent ACCESS buffer perTileLightIndexBuffer
- {
- uint perTileLightIndices[];
- };
- #if defined(FRAG_SHADER)
- struct Shadow {
- uvec4 _arrayOffset;
- mat4 _lightVP[MAX_SPLITS_PER_LIGHT];
- vec4 _lightPosition[MAX_SPLITS_PER_LIGHT];
- vec4 _floatValues[MAX_SPLITS_PER_LIGHT];
- };
- layout(binding = BUFFER_LIGHT_SHADOW, std430) coherent ACCESS buffer dvd_ShadowBlock
- {
- Shadow dvd_ShadowSource[MAX_SHADOW_CASTING_LIGHTS];
- };
- #endif
- #define windowWidth int(dvd_ViewPort.z)
- #define windowHeight int(dvd_ViewPort.w)
- // calculate the number of tiles in the horizontal direction
- uint GetNumTilesX()
- {
- return uint((windowWidth + FORWARD_PLUS_TILE_RES - 1) / float(FORWARD_PLUS_TILE_RES));
- }
- // calculate the number of tiles in the vertical direction
- uint GetNumTilesY()
- {
- return uint((windowHeight + FORWARD_PLUS_TILE_RES - 1) / float(FORWARD_PLUS_TILE_RES));
- }
- uint GetTileIndex(in vec2 ScreenPos)
- {
- float fTileRes = float(FORWARD_PLUS_TILE_RES);
- return uint(floor(ScreenPos.x / fTileRes) + floor(ScreenPos.y / fTileRes) * GetNumTilesX());
- }
- #endif //_LIGHT_INPUT_CMN_
- #ifndef _LIGHT_DATA_FRAG_
- #define _LIGHT_DATA_FRAG_
- #define M_PIDIV180 0.01745329251994329576923690768488
- // Light direction is NOT normalized
- float getLightAttenuation(const in int lightIndex,
- const in vec3 lightDirection){
- int lightType = dvd_LightSource[lightIndex]._options.x;
- if (lightType == LIGHT_DIRECTIONAL) {
- return 1.0;
- }
- float dis = length(lightDirection);
- float r = dvd_LightSource[lightIndex]._positionWV.w;
- float att = clamp(1.0 - (dis*dis) / (r*r), 0.0, 1.0);
- att *= att;
- if (lightType == LIGHT_SPOT) {
- vec4 dirIn = dvd_LightSource[lightIndex]._directionWV;
- float cosOutterConeAngle = dvd_LightSource[lightIndex]._colour.w;
- float cosInnerMinusOuterAngle = dirIn.w - cosOutterConeAngle;
- att *= clamp((dot(-normalize(lightDirection), normalize(dirIn.xyz)) - cosOutterConeAngle) /
- cosInnerMinusOuterAngle, 0.0, 1.0);
- }
- return att;
- }
- //non-normalized light direction!
- vec3 getLightDirection(const in int lightIndex) {
- if (dvd_LightSource[lightIndex]._options.x == LIGHT_DIRECTIONAL) {
- return -dvd_LightSource[lightIndex]._positionWV.xyz;
- }
- return dvd_LightSource[lightIndex]._positionWV.xyz - VAR._vertexWV.xyz;
- }
- #endif
- #ifndef _MATERIAL_DATA_FRAG_
- #define _MATERIAL_DATA_FRAG_
- #if defined(USE_OPACITY_DIFFUSE) || defined(USE_OPACITY_MAP)
- #define HAS_TRANSPARENCY
- #endif
- #if !defined(SKIP_TEXTURES)
- layout(binding = TEXTURE_UNIT0) uniform sampler2D texDiffuse0;
- layout(binding = TEXTURE_UNIT1) uniform sampler2D texDiffuse1;
- #endif
- layout(binding = TEXTURE_REFLECTION) uniform samplerCubeArray texEnvironmentCube;
- //Normal or BumpMap
- #if defined(COMPUTE_TBN)
- layout(binding = TEXTURE_NORMALMAP) uniform sampler2D texNormalMap;
- #endif
- //Specular and opacity maps are available even for non-textured geometry
- #if defined(USE_OPACITY_MAP)
- layout(binding = TEXTURE_OPACITY) uniform sampler2D texOpacityMap;
- #endif
- #if defined(USE_SPECULAR_MAP)
- layout(binding = TEXTURE_SPECULAR) uniform sampler2D texSpecularMap;
- #endif
- float Gloss(in vec3 bump, in vec2 texCoord)
- {
- #if defined(USE_TOKSVIG)
- // Compute the "Toksvig Factor"
- float rlen = 1.0/saturate(length(bump));
- return 1.0/(1.0 + power*(rlen - 1.0));
- #elif defined(USE_TOKSVIG_MAP)
- float baked_power = 100.0;
- // Fetch pre-computed "Toksvig Factor"
- // and adjust for specified power
- float gloss = texture2D(texSpecularMap, texCoord).r;
- gloss /= mix(power/baked_power, 1.0, gloss);
- return gloss;
- #else
- return 1.0;
- #endif
- }
- #if !defined(SKIP_TEXTURES)
- vec4 getTextureColour(in vec2 uv) {
- #define TEX_MODULATE 0
- #define TEX_ADD 1
- #define TEX_SUBTRACT 2
- #define TEX_DIVIDE 3
- #define TEX_SMOOTH_ADD 4
- #define TEX_SIGNED_ADD 5
- #define TEX_DECAL 6
- #define TEX_REPLACE 7
- vec4 colour = texture(texDiffuse0, uv);
- if (dvd_textureCount == 1) {
- return colour;
- }
- vec4 colour2 = texture(texDiffuse1, uv);
- // Read from the texture
- switch (dvd_texOperation) {
- default : colour = vec4(0.7743, 0.3188, 0.5465, 1.0); break; // <hot pink to easily spot it in a crowd
- case TEX_MODULATE : colour *= colour2; break;
- case TEX_REPLACE : colour = colour2; break;
- case TEX_SIGNED_ADD : colour += colour2 - 0.5; break;
- case TEX_DIVIDE : colour /= colour2; break;
- case TEX_SUBTRACT : colour -= colour2; break;
- case TEX_DECAL : colour = vec4(mix(colour.rgb, colour2.rgb, colour2.a), colour.a); break;
- case TEX_ADD : {
- colour.rgb += colour2.rgb;
- colour.a *= colour2.a;
- }break;
- case TEX_SMOOTH_ADD : {
- colour = (colour + colour2) - (colour * colour2);
- }break;
- }
- return saturate(colour);
- }
- #endif
- vec4 dvd_MatDiffuse;
- vec3 dvd_MatSpecular;
- vec3 dvd_MatEmissive;
- float dvd_MatShininess;
- void parseMaterial() {
- dvd_MatEmissive = dvd_Matrices[VAR.dvd_drawID]._colourMatrix[2].rgb;
- dvd_MatShininess = dvd_Matrices[VAR.dvd_drawID]._colourMatrix[2].w;
- #if !defined(USE_CUSTOM_ALBEDO)
- #if defined(SKIP_TEXTURES)
- dvd_MatDiffuse = dvd_Matrices[VAR.dvd_drawID]._colourMatrix[0];
- #else
- dvd_MatDiffuse = getTextureColour(VAR._texCoord);
- #endif
- #endif
- #if defined(USE_SPECULAR_MAP)
- dvd_MatSpecular = texture(texSpecularMap, VAR._texCoord).rgb;
- #else
- dvd_MatSpecular = dvd_Matrices[VAR.dvd_drawID]._colourMatrix[1].rgb;
- #endif
- }
- #endif //_MATERIAL_DATA_FRAG_
- #ifndef _SHADOW_MAPPING_FRAG_
- #define _SHADOW_MAPPING_FRAG_
- layout(binding = SHADOW_SINGLE_MAP_ARRAY) uniform sampler2DArrayShadow texDepthMapFromLight;
- layout(binding = SHADOW_CUBE_MAP_ARRAY) uniform samplerCubeArrayShadow texDepthMapFromLightCube;
- layout(binding = SHADOW_LAYERED_MAP_ARRAY) uniform sampler2DArray texDepthMapFromLightArray;
- #if defined(_DEBUG)
- #define DEBUG_SHADOWMAPPING
- //#define DEBUG_SHADOWSPLITS
- // set this to whatever (current cascade, current depth comparison result, anything)
- int _shadowTempInt = -2;
- #endif
- #ifndef _SHADOW_DIRECTIONAL_FRAG_
- #define _SHADOW_DIRECTIONAL_FRAG_
- #define LT(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n
- float linstep(float min, float max, float v) {
- return clamp((v - min) / (max - min), 0.0, 1.0);
- }
- // Reduces VSM light bleeding (remove the [0, amount] tail and linearly rescale (amount, 1])
- float reduceLightBleeding(float pMax, float amount) {
- return linstep(amount, 1.0f, pMax);
- }
- float chebyshevUpperBound(vec2 moments, float depth, float minVariance) {
- if (depth <= moments.x + dvd_shadowingSettings.x) {
- return 1.0;
- }
- float variance = max(moments.y - (moments.x * moments.x), minVariance);
- float d = (depth - moments.x);
- float p_max = variance / (variance + d*d);
- return max(1.0 - p_max, 0.0);
- }
- float applyShadowDirectional(int shadowIndex, int splitCount, in float fragDepth) {
- Shadow currentShadowSource = dvd_ShadowSource[shadowIndex];
- # if !defined(_DEBUG)
- int _shadowTempInt = -2;
- # endif
- // find the appropriate depth map to look up in based on the depth of this fragment
- _shadowTempInt = 0;
- for (int i = 0; i < splitCount; ++i) {
- if (fragDepth > currentShadowSource._floatValues[i].x) {
- _shadowTempInt = i + 1;
- }
- }
- // GLOBAL
- const int SplitPowLookup[] = { 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
- LT(4), LT(5), LT(5), LT(6), LT(6), LT(6), LT(6),
- LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7)};
- // Ensure that every fragment in the quad choses the same split so that derivatives
- // will be meaningful for proper texture filtering and LOD selection.
- int SplitPow = 1 << _shadowTempInt;
- int SplitX = int(abs(dFdx(SplitPow)));
- int SplitY = int(abs(dFdy(SplitPow)));
- int SplitXY = int(abs(dFdx(SplitY)));
- int SplitMax = max(SplitXY, max(SplitX, SplitY));
- _shadowTempInt = SplitMax > 0 ? SplitPowLookup[SplitMax - 1] : _shadowTempInt;
- if (_shadowTempInt < 0 || _shadowTempInt > splitCount) {
- return 1.0;
- }
- vec4 sc = currentShadowSource._lightVP[_shadowTempInt] * VAR._vertexW;
- vec3 scPostW = sc.xyz / sc.w;
- if (!(sc.w <= 0.0f || (scPostW.x < 0 || scPostW.y < 0) || (scPostW.x >= 1 || scPostW.y >= 1))){
- float layer = float(_shadowTempInt + currentShadowSource._arrayOffset.x);
- vec2 moments = texture(texDepthMapFromLightArray, vec3(scPostW.xy, layer)).rg;
- //float shadowBias = DEPTH_EXP_WARP * exp(DEPTH_EXP_WARP * dvd_shadowingSettings.y);
- //float shadowWarpedz1 = exp(scPostW.z * DEPTH_EXP_WARP);
- //return mix(chebyshevUpperBound(moments, shadowWarpedz1, dvd_shadowingSettings.y),
- // 1.0,
- // clamp(((gl_FragCoord.z + dvd_shadowingSettings.z) - dvd_shadowingSettings.w) / dvd_shadowingSettings.z, 0.0, 1.0));
- return reduceLightBleeding(chebyshevUpperBound(moments, scPostW.z, dvd_shadowingSettings.y), 0.1);
- }
- return 1.0;
- }
- #endif //_SHADOW_DIRECTIONAL_FRAG_
- #ifndef _SHADOW_POINT_FRAG_
- #define _SHADOW_POINT_FRAG_
- float applyShadowPoint(int shadowIndex) {
- Shadow currentShadowSource = dvd_ShadowSource[shadowIndex];
- // SHADOW MAPS
- vec3 position_ls = currentShadowSource._lightPosition[0].xyz;
- vec3 abs_position = abs(position_ls);
- float fs_z = -max(abs_position.x, max(abs_position.y, abs_position.z));
- vec4 clip = (currentShadowSource._lightVP[0] * VAR._vertexW) * vec4(0.0, 0.0, fs_z, 1.0);
- float depth = (clip.z / clip.w) * 0.5 + 0.5;
- return texture(texDepthMapFromLightCube, vec4(position_ls.xyz, currentShadowSource._arrayOffset.x), depth).r;
- }
- #endif //_SHADOW_POINT_FRAG_
- #ifndef _SHADOW_SPOT_FRAG_
- #define _SHADOW_SPOT_FRAG_
- float filterFinalShadow(in sampler2DArrayShadow depthMap, in vec4 vPosInDM){
- // Gaussian 3x3 filter
- float vDepthMapColour = texture(depthMap, vPosInDM);
- float fShadow = 0.0;
- if((vDepthMapColour+Z_TEST_SIGMA) < vPosInDM.w){
- #if GPU_VENDOR == GPU_VENDOR_AMD
- fShadow = vDepthMapColour;
- #else
- fShadow = vDepthMapColour * 0.25;
- fShadow += textureOffset(depthMap, vPosInDM, ivec2( -1, -1)) * 0.0625;
- fShadow += textureOffset(depthMap, vPosInDM, ivec2( -1, 0)) * 0.125;
- fShadow += textureOffset(depthMap, vPosInDM, ivec2( -1, 1)) * 0.0625;
- fShadow += textureOffset(depthMap, vPosInDM, ivec2( 0, -1)) * 0.125;
- fShadow += textureOffset(depthMap, vPosInDM, ivec2( 0, 1)) * 0.125;
- fShadow += textureOffset(depthMap, vPosInDM, ivec2( 1, -1)) * 0.0625;
- fShadow += textureOffset(depthMap, vPosInDM, ivec2( 1, 0)) * 0.125;
- fShadow += textureOffset(depthMap, vPosInDM, ivec2( 1, 1)) * 0.0625;
- #endif
- fShadow = clamp(fShadow, 0.0, 1.0);
- }else{
- fShadow = 1.0;
- }
- return fShadow;
- }
- float applyShadowSpot(int shadowIndex) {
- Shadow currentShadowSource = dvd_ShadowSource[shadowIndex];
- vec4 shadow_coord = currentShadowSource._lightVP[0] * VAR._vertexW;
- shadow_coord = shadow_coord / shadow_coord.w;
- shadow_coord = 0.5 + shadow_coord * 0.5;
- shadow_coord.xyw = shadow_coord.xyz;
- shadow_coord.z = currentShadowSource._arrayOffset.x;
- return filterFinalShadow(texDepthMapFromLight, shadow_coord);
- }
- #endif //_SHADOW_SPOT_FRAG_
- float getShadowFactor(in int lightIndex, in float fragDepth) {
- Light light = dvd_LightSource[lightIndex];
- switch (light._options.x) {
- case LIGHT_DIRECTIONAL : return applyShadowDirectional(light._options.z, light._options.w, fragDepth);
- //case LIGHT_OMNIDIRECTIONAL : return applyShadowPoint(light._options.z);
- //case LIGHT_SPOT : return applyShadowSpot(light._options.z);
- }
- return 1.0;
- }
- float shadow_loop(){
- if (!dvd_shadowsEnabled()) {
- return 1.0;
- }
- float fragDepth = gl_FragCoord.z;
- float shadow = 1.0;
- int offset = 0;
- int shadowLights = 0;
- for (int i = 0; i < MAX_LIGHT_TYPES; ++i) {
- for (int j = 0; j < int(dvd_lightCountPerType[i]); ++j) {
- int lightIndex = j + offset;
- if (shadowLights < MAX_SHADOW_CASTING_LIGHTS &&
- dvd_LightSource[lightIndex]._options.y == 1) {
- shadow *= getShadowFactor(lightIndex, fragDepth);
- shadowLights++;
- }
- }
- offset += int(dvd_lightCountPerType[i]);
- }
- return saturate(shadow);
- }
- #endif //_SHADOW_MAPPING_FRAG_
- #ifndef _PHONG_LIGHTING_FRAG_
- #define _PHONG_LIGHTING_FRAG_
- void Phong(in int lightIndex, in vec3 normalWV, inout vec3 colourInOut) {
- // direction is NOT normalized
- vec3 lightDirection = getLightDirection(lightIndex);
- float att = getLightAttenuation(lightIndex, lightDirection);
- vec3 lightColour = dvd_LightSource[lightIndex]._colour.rgb;
- float NDotL = max(dot(normalize(lightDirection), normalWV), 0.0);
- colourInOut += clamp(lightColour * dvd_MatDiffuse.rgb * NDotL * att, 0.0, 1.0);
- if (NDotL > 0.0) {
- vec3 dvd_ViewDirNorm = normalize(-VAR._vertexWV.xyz);
- #if defined(USE_SHADING_BLINN_PHONG)
- vec3 halfDir = normalize(normalize(lightDirection) + dvd_ViewDirNorm);
- float specAngle = max(dot(halfDir, normalWV), 0.0);
- #else
- vec3 reflectDir = reflect(normalize(-lightDirection), normalWV);
- float specAngle = max(dot(reflectDir, dvd_ViewDirNorm), 0.0);
- #endif
- float shininess = pow(specAngle, dvd_MatShininess) * att;
- colourInOut += clamp(lightColour * dvd_MatSpecular.rgb * shininess, 0.0, 1.0);
- }
- }
- #endif //_PHONG_LIGHTING_FRAG_
- vec3 processedNormal = vec3(0.0, 0.0, 1.0);
- //TEMP PBR
- /// Smith GGX Visibility
- /// nDotL: dot-prod of surface normal and light direction
- /// nDotV: dot-prod of surface normal and view direction
- /// roughness: surface roughness
- float SmithGGXVisibility(in float nDotL, in float nDotV, in float roughness)
- {
- float rough2 = roughness * roughness;
- float gSmithV = nDotV + sqrt(nDotV * (nDotV - nDotV * rough2) + rough2);
- float gSmithL = nDotL + sqrt(nDotL * (nDotL - nDotL * rough2) + rough2);
- return 1.0 / (gSmithV * gSmithL);
- }
- float SchlickG1(in float factor, in float rough2)
- {
- return 1.0 / (factor * (1.0 - rough2) + rough2);
- }
- /// Schlick approximation of Smith GGX
- /// nDotL: dot product of surface normal and light direction
- /// nDotV: dot product of surface normal and view direction
- /// roughness: surface roughness
- float SchlickVisibility(float nDotL, float nDotV, float roughness)
- {
- const float rough2 = roughness * roughness;
- return (SchlickG1(nDotL, rough2) * SchlickG1(nDotV, rough2)) * 0.25;
- }
- void PBR(in int lightIndex, in vec3 normalWV, inout vec4 colourInOut) {
- vec3 lightDirection = getLightDirection(lightIndex);
- vec3 lightDir = normalize(lightDirection);
- float roughness = dvd_MatShininess;
- colourInOut = vec4(1.0);
- }
- //TEMP PBR
- void getBRDFFactors(in int lightIndex,
- in vec3 normalWV,
- inout vec3 colourInOut)
- {
- #if defined(USE_SHADING_PHONG) || defined (USE_SHADING_BLINN_PHONG)
- Phong(lightIndex, normalWV, colourInOut);
- #elif defined(USE_SHADING_TOON)
- #elif defined(USE_SHADING_OREN_NAYAR)
- #else //if defined(USE_SHADING_COOK_TORRANCE)
- PBR(lightIndex, normalWV, colourInOut);
- #endif
- }
- uint GetNumLightsInThisTile(uint nTileIndex)
- {
- uint nNumLightsInThisTile = 0;
- uint nIndex = uint(dvd_otherData.w) * nTileIndex;
- uint nNextLightIndex = perTileLightIndices[nIndex];
- while (nNextLightIndex != LIGHT_INDEX_BUFFER_SENTINEL)
- {
- nIndex++;
- nNextLightIndex = perTileLightIndices[nIndex];
- nNumLightsInThisTile++;
- }
- return nNumLightsInThisTile;
- }
- vec4 getPixelColour(const in vec2 texCoord, in vec3 normalWV) {
- //Occlusion culling visibility debug code
- #if defined(USE_HIZ_CULLING) && defined(DEBUG_HIZ_CULLING)
- if (dvd_customData > 2.0) {
- return vec4(1.0, 0.0, 0.0, 1.0);
- }
- #endif
- parseMaterial();
- processedNormal = normalWV;
- #if defined(HAS_TRANSPARENCY)
- # if defined(USE_OPACITY_DIFFUSE)
- float alpha = dvd_MatDiffuse.a;
- # endif
- # if defined(USE_OPACITY_MAP)
- vec4 opacityMap = texture(texOpacityMap, texCoord);
- float alpha = max(min(opacityMap.r, opacityMap.g), min(opacityMap.b, opacityMap.a));
- # endif
- # else
- const float alpha = 1.0;
- # endif
- # if defined (USE_DOUBLE_SIDED)
- processedNormal = gl_FrontFacing ? processedNormal : -processedNormal;
- # endif
- # if defined(USE_SHADING_FLAT)
- vec3 colour = dvd_MatDiffuse.rgb;
- # else
- vec3 lightColour = vec3(0.0);
- // Apply all lighting contributions
- uint lightIdx;
- // Directional lights
- for (lightIdx = 0; lightIdx < dvd_lightCountPerType[0]; ++lightIdx) {
- getBRDFFactors(int(lightIdx), processedNormal, lightColour);
- }
- uint offset = dvd_lightCountPerType[0];
- // Point lights
- uint nIndex = uint(dvd_otherData.w) * GetTileIndex(gl_FragCoord.xy);
- uint nNextLightIndex = perTileLightIndices[nIndex];
- while (nNextLightIndex != LIGHT_INDEX_BUFFER_SENTINEL)
- {
- uint nLightIndex = nNextLightIndex;
- nNextLightIndex = perTileLightIndices[++nIndex];
- getBRDFFactors(int(nLightIndex - 1 + offset), processedNormal, lightColour);
- }
- offset = dvd_lightCountPerType[1];
- // Spot lights
- // Moves past the first sentinel to get to the spot lights.
- nNextLightIndex = perTileLightIndices[++nIndex];
- while (nNextLightIndex != LIGHT_INDEX_BUFFER_SENTINEL)
- {
- uint nLightIndex = nNextLightIndex;
- nNextLightIndex = perTileLightIndices[++nIndex];
- getBRDFFactors(int(nLightIndex - 1 + offset), processedNormal, lightColour);
- }
- vec3 colour = mix(dvd_MatEmissive, lightColour, DIST_TO_ZERO(length(lightColour)));
- #endif
- float reflectance = saturate(dvd_MatShininess / 255.0);
- if (reflectance > 0.75 && dvd_lodLevel < 1) {
- vec3 reflectDirection = reflect(normalize(VAR._vertexWV.xyz), processedNormal);
- reflectDirection = vec3(inverse(dvd_ViewMatrix) * vec4(reflectDirection, 0.0));
- colour = mix(texture(texEnvironmentCube, vec4(reflectDirection, 0.0)).rgb,
- colour,
- vec3(reflectance));
- }
- colour *= mix(mix(1.0, 2.0, dvd_isHighlighted), 3.0, dvd_isSelected);
- // Apply shadowing
- colour *= mix(1.0, shadow_loop(), dvd_shadowMapping);
- #if defined(_DEBUG) && defined(DEBUG_SHADOWMAPPING)
- if (dvd_showDebugInfo == 1) {
- switch (_shadowTempInt){
- #if defined(DEBUG_SHADOWSPLITS)
- case -1: colour = vec3(1.0); break;
- case 0: colour = vec3(1.0, 0.0, 0.0); break;
- case 1: colour = vec3(0.0, 1.0, 0.0); break;
- case 2: colour = vec3(0.0, 0.0, 1.0); break;
- case 3: colour = vec3(1.0, 0.25, 0.40); break;
- #else
- case -1: colour = vec3(1.0); break;
- case 0: colour.r += 0.15; break;
- case 1: colour.g += 0.25; break;
- case 2: colour.b += 0.40; break;
- case 3: colour += vec3(0.15, 0.25, 0.40); break;
- #endif
- };
- }
- #endif
- return vec4(colour, alpha);
- }
- #endif
- #if defined(COMPUTE_TBN)
- #ifndef _BUMP_MAPPING_FRAG_
- #define _BUMP_MAPPING_FRAG_
- uniform int bumpMapLightID = 0;
- vec3 getTBNNormal(in vec3 bump) {
- mat3 TBN = mat3(VAR._tangentWV, VAR._bitangentWV, VAR._normalWV);
- return TBN * bump;
- }
- vec3 getBump(in vec2 uv) {
- return normalize(2.0 * texture(texNormalMap, uv).rgb - 1.0);
- }
- float ReliefMapping_RayIntersection(in vec2 A, in vec2 AB){
- const int num_steps_lin = 10;
- const int num_steps_bin = 15;
- float linear_step = 1.0 / (float(num_steps_lin));
- //Current depth position
- float depth = 0.0;
- //Best match found (starts with last position 1.0)
- float best_depth = 1.0;
- float step = linear_step;
- //Search from front to back for first point inside the object
- for(int i=0; i<num_steps_lin-1; i++){
- depth += step;
- if (depth >= 1.0 - texture(texNormalMap, A+AB*depth).a) {
- best_depth = depth; //Store best depth
- i = num_steps_lin-1;
- }
- }
- //The point of intersection is found between (depth) and (depth-step)
- //so start from (depth - step/2)
- step = linear_step * 0.5;
- depth = best_depth - step;
- // binary search
- for(int i = 0; i < num_steps_bin; ++i){
- step *= 0.5;
- best_depth = depth;
- if (depth >= 1.0 - texture(texNormalMap, A + AB * depth).a) {
- depth -= step;
- }else {
- depth += step;
- }
- }
- return best_depth;
- }
- vec4 ParallaxMapping(in int bumpMapLightID, in vec2 uv){
- vec3 lightVecTBN = vec3(0.0);
- switch (dvd_LightSource[bumpMapLightID]._options.x){
- case LIGHT_DIRECTIONAL :
- lightVecTBN = -normalize(dvd_LightSource[bumpMapLightID]._positionWV.xyz);
- break;
- case LIGHT_OMNIDIRECTIONAL :
- case LIGHT_SPOT :
- lightVecTBN = normalize(-VAR._vertexWV.xyz + dvd_LightSource[bumpMapLightID]._positionWV.xyz);
- break;
- };
- vec3 viewVecTBN = normalize(-VAR._vertexWV.xyz);
- //Offset, scale and bias
- vec2 vTexCoord = uv +
- ((texture(texNormalMap, uv).a - 0.5) *
- dvd_parallaxFactor *
- (vec2(viewVecTBN.x, -viewVecTBN.y) /
- viewVecTBN.z));
- return getPixelColour(vTexCoord, getTBNNormal(getBump(vTexCoord)));
- }
- vec4 ReliefMapping(in int _light, in vec2 uv){
- vec3 viewVecTBN = normalize(-VAR._vertexWV.xyz);
- //Size and search starting position in texture space
- vec2 AB = dvd_reliefFactor * vec2(-viewVecTBN.x, viewVecTBN.y)/viewVecTBN.z;
- float h = ReliefMapping_RayIntersection(uv, AB);
- vec2 uv_offset = h * AB;
- vec3 p = VAR._vertexWV.xyz;
- vec3 v = normalize(p);
- //Compute light direction
- p += v*h*viewVecTBN.z;
- vec2 planes;
- planes.x = -dvd_ZPlanesCombined.y / (dvd_ZPlanesCombined.y - dvd_ZPlanesCombined.x);
- planes.y = -dvd_ZPlanesCombined.y * dvd_ZPlanesCombined.x / (dvd_ZPlanesCombined.y - dvd_ZPlanesCombined.x);
- gl_FragDepth =((planes.x * p.z + planes.y) / -p.z);
- return getPixelColour(uv + uv_offset, getTBNNormal(getBump(uv + uv_offset)));
- }
- #endif //_BUMP_MAPPING_FRAG_
- #endif
- layout(location = 0) out vec4 _colourOut;
- layout(location = 1) out vec3 _normalOut;
- //subroutine vec4 MappingRoutineType();
- //layout(location = 0) subroutine uniform MappingRoutineType MappingRoutine;
- //subroutine(MappingRoutineType)
- vec4 mappingFlat(){
- return getPixelColour(VAR._texCoord, VAR._normalWV);
- }
- #if defined(COMPUTE_TBN)
- //subroutine(MappingRoutineType)
- vec4 mappingNormal(){
- vec3 bump = getBump(VAR._texCoord);
- return mix(getPixelColour(VAR._texCoord, getTBNNormal(bump)),
- mappingFlat(),
- vec4(dvd_lodLevel > 1));
- }
- //subroutine(MappingRoutineType)
- vec4 mappingRelief(){
- return mix(ReliefMapping(bumpMapLightID, VAR._texCoord),
- mappingFlat(),
- vec4(dvd_lodLevel > 1));
- }
- //subroutine(MappingRoutineType)
- vec4 mappingParallax(){
- return mix(ParallaxMapping(bumpMapLightID, VAR._texCoord),
- mappingFlat(),
- vec4(dvd_lodLevel > 1));
- }
- #endif
- void main (void){
- //_colourOut = ToSRGB(applyFog(MappingRoutine()));
- #if defined(COMPUTE_TBN)
- # if defined(USE_PARALLAX_MAPPING)
- _colourOut = ToSRGB(applyFog(ParallaxMapping()));
- # elif defined(USE_RELIEF_MAPPING)
- _colourOut = ToSRGB(applyFog(ReliefMapping()));
- # else
- _colourOut = ToSRGB(applyFog(mappingNormal()));
- # endif
- #else
- _colourOut = ToSRGB(applyFog(mappingFlat()));
- #endif
- _normalOut = processedNormal;
- }
Advertisement
Add Comment
Please, Sign In to add comment