@galacean/engine-core 2.0.0-alpha.30 → 2.0.0-alpha.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/module.js CHANGED
@@ -1083,7 +1083,6 @@ var AssetPromise = /*#__PURE__*/ function() {
1083
1083
  /** @internal */ SystemInfo._isBrowser = true;
1084
1084
  /** Whether the system support SIMD. */ SystemInfo._simdSupported = null;
1085
1085
  SystemInfo._webpSupported = null;
1086
- SystemInfo._initialize();
1087
1086
 
1088
1087
  /**
1089
1088
  * The base class of texture, contains some common functions of texture-related classes.
@@ -4769,270 +4768,33 @@ function _extends() {
4769
4768
  return PipelineStage;
4770
4769
  }({});
4771
4770
 
4772
- var camera_declare = "uniform vec3 camera_Position;\nuniform vec3 camera_Forward; "; // eslint-disable-line
4773
-
4774
- var common = "#define PI 3.14159265359\n#define RECIPROCAL_PI 0.31830988618\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define HALF_MIN 6.103515625e-5 // 2^-14, the same value for 10, 11 and 16-bit: https://www.khronos.org/opengl/wiki/Small_Float_Formats\n#define HALF_EPS 4.8828125e-4 // 2^-11, machine epsilon: 1 + EPS = 1 (half of the ULP for 1.0f)\n\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n\nfloat pow2(float x ) {\n return x * x;\n}\n\nvec4 gammaToLinear(vec4 value){\n return vec4( pow(value.rgb, vec3(2.2)), value.a);\n}\n\nvec4 linearToGamma(vec4 value){\n\tvalue = max(value, 0.0);\n return vec4( pow(value.rgb, vec3(1.0 / 2.2)), value.a);\n}\n\n\n// https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_framebuffer_sRGB.txt\n// https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_texture_sRGB_decode.txt\nfloat sRGBToLinear(float value){\n float linearRGBLo = value / 12.92;\n float linearRGBHi = pow((value + 0.055) / 1.055, 2.4);\n float linearRGB = (value <= 0.04045) ? linearRGBLo : linearRGBHi;\n return linearRGB;\n}\n\nvec4 sRGBToLinear(vec4 value){\n return vec4(sRGBToLinear(value.r), sRGBToLinear(value.g), sRGBToLinear(value.b), value.a);\n}\n\nfloat linearToSRGB(float value){\n\tvalue = max(value, 0.0);\n return (value <= 0.0031308) ? (value * 12.9232102) : 1.055 * pow(value, 1.0 / 2.4) - 0.055;\n}\n\nvec4 linearToSRGB(vec4 value){\n return vec4(linearToSRGB(value.r), linearToSRGB(value.g), linearToSRGB(value.b), value.a);\n}\n\n// Compatible with devices that do not even support EXT_sRGB in WebGL1.0.\nvec4 texture2DSRGB(sampler2D tex, vec2 uv) {\n\tvec4 color = texture2D(tex, uv);\n\t#ifdef ENGINE_NO_SRGB\n\t\tcolor = sRGBToLinear(color);\n\t#endif\n\treturn color;\n}\n\nvec4 outputSRGBCorrection(vec4 linearIn){\n #ifdef ENGINE_OUTPUT_SRGB_CORRECT\n \treturn linearToSRGB(linearIn);\n #else \n \treturn linearIn;\n #endif\n}\n\n\nuniform vec4 camera_DepthBufferParams;\nuniform vec4 camera_ProjectionParams;\n\nfloat remapDepthBufferLinear01(float depth){\n\treturn 1.0 / (camera_DepthBufferParams.x * depth + camera_DepthBufferParams.y);\n}\n\nfloat remapDepthBufferEyeDepth(float depth){\n\t#ifdef CAMERA_ORTHOGRAPHIC\n\t\treturn camera_ProjectionParams.y + (camera_ProjectionParams.z - camera_ProjectionParams.y) * depth;\n\t#else\n\t\treturn 1.0 / (camera_DepthBufferParams.z * depth + camera_DepthBufferParams.w);\n\t#endif\n}\n\n// From Next Generation Post Processing in Call of Duty: Advanced Warfare [Jimenez 2014]\n// http://advances.realtimerendering.com/s2014/index.html\n// sampleCoord must not be normalized (e.g. window coordinates)\nfloat interleavedGradientNoise(vec2 sampleCoord)\n{\n\tconst vec3 magic = vec3(0.06711056, 0.00583715, 52.9829189);\n\treturn fract(magic.z * fract(dot(sampleCoord, magic.xy)));\n}\n\n#ifdef GRAPHICS_API_WEBGL2\n\t#define INVERSE_MAT(mat) inverse(mat)\n#else\n\tmat2 inverseMat(mat2 m) {\n\t\treturn mat2(m[1][1],-m[0][1],\n\t\t\t\t-m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n\t}\n\tmat3 inverseMat(mat3 m) {\n\t\tfloat a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n\t\tfloat a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n\t\tfloat a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n\t\tfloat b01 = a22 * a11 - a12 * a21;\n\t\tfloat b11 = -a22 * a10 + a12 * a20;\n\t\tfloat b21 = a21 * a10 - a11 * a20;\n\n\t\tfloat det = a00 * b01 + a01 * b11 + a02 * b21;\n\n\t\treturn mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n\t\t\t\t\tb11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n\t\t\t\t\tb21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n\t}\n\tmat4 inverseMat(mat4 m) {\n\t\tfloat a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n\t\t\ta10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n\t\t\ta20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n\t\t\ta30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n\t\t\tb00 = a00 * a11 - a01 * a10,\n\t\t\tb01 = a00 * a12 - a02 * a10,\n\t\t\tb02 = a00 * a13 - a03 * a10,\n\t\t\tb03 = a01 * a12 - a02 * a11,\n\t\t\tb04 = a01 * a13 - a03 * a11,\n\t\t\tb05 = a02 * a13 - a03 * a12,\n\t\t\tb06 = a20 * a31 - a21 * a30,\n\t\t\tb07 = a20 * a32 - a22 * a30,\n\t\t\tb08 = a20 * a33 - a23 * a30,\n\t\t\tb09 = a21 * a32 - a22 * a31,\n\t\t\tb10 = a21 * a33 - a23 * a31,\n\t\t\tb11 = a22 * a33 - a23 * a32,\n\n\t\t\tdet = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n\t\treturn mat4(\n\t\t\ta11 * b11 - a12 * b10 + a13 * b09,\n\t\t\ta02 * b10 - a01 * b11 - a03 * b09,\n\t\t\ta31 * b05 - a32 * b04 + a33 * b03,\n\t\t\ta22 * b04 - a21 * b05 - a23 * b03,\n\t\t\ta12 * b08 - a10 * b11 - a13 * b07,\n\t\t\ta00 * b11 - a02 * b08 + a03 * b07,\n\t\t\ta32 * b02 - a30 * b05 - a33 * b01,\n\t\t\ta20 * b05 - a22 * b02 + a23 * b01,\n\t\t\ta10 * b10 - a11 * b08 + a13 * b06,\n\t\t\ta01 * b08 - a00 * b10 - a03 * b06,\n\t\t\ta30 * b04 - a31 * b02 + a33 * b00,\n\t\t\ta21 * b02 - a20 * b04 - a23 * b00,\n\t\t\ta11 * b07 - a10 * b09 - a12 * b06,\n\t\t\ta00 * b09 - a01 * b07 + a02 * b06,\n\t\t\ta31 * b01 - a30 * b03 - a32 * b00,\n\t\t\ta20 * b03 - a21 * b01 + a22 * b00) / det;\n\t}\n\n\t#define INVERSE_MAT(mat) inverseMat(mat)\n#endif\n\n\nvec3 safeNormalize(vec3 inVec) {\n float dp3 = max(float(HALF_MIN), dot(inVec, inVec));\n return inVec * inversesqrt(dp3);\n}\n"; // eslint-disable-line
4775
-
4776
- var common_vert = "attribute vec3 POSITION;\n\n#ifdef RENDERER_HAS_UV\n attribute vec2 TEXCOORD_0;\n#endif\n\n#ifdef RENDERER_HAS_UV1\n attribute vec2 TEXCOORD_1;\n#endif\n\n#ifdef RENDERER_HAS_SKIN\n attribute vec4 JOINTS_0;\n attribute vec4 WEIGHTS_0;\n\n #ifdef RENDERER_USE_JOINT_TEXTURE\n uniform sampler2D renderer_JointSampler;\n uniform float renderer_JointCount;\n\n mat4 getJointMatrix(sampler2D smp, float index)\n {\n float base = index / renderer_JointCount;\n float hf = 0.5 / renderer_JointCount;\n float v = base + hf;\n\n vec4 m0 = texture2D(smp, vec2(0.125, v ));\n vec4 m1 = texture2D(smp, vec2(0.375, v ));\n vec4 m2 = texture2D(smp, vec2(0.625, v ));\n vec4 m3 = texture2D(smp, vec2(0.875, v ));\n\n return mat4(m0, m1, m2, m3);\n\n }\n\n #else\n uniform mat4 renderer_JointMatrix[ RENDERER_JOINTS_NUM ];\n #endif\n#endif\n\n#ifdef RENDERER_ENABLE_VERTEXCOLOR\n attribute vec4 COLOR_0;\n#endif\n\n\n#include <transform_declare>\n#include <camera_declare>\n\nuniform vec4 material_TilingOffset;\n\n\n#ifndef MATERIAL_OMIT_NORMAL\n #ifdef RENDERER_HAS_NORMAL\n attribute vec3 NORMAL;\n #endif\n\n #ifdef RENDERER_HAS_TANGENT\n attribute vec4 TANGENT;\n #endif\n#endif"; // eslint-disable-line
4777
-
4778
- var transform_declare = "uniform mat4 renderer_LocalMat;\nuniform mat4 renderer_ModelMat;\nuniform mat4 camera_ViewMat;\nuniform mat4 camera_ProjMat;\nuniform mat4 renderer_MVMat;\nuniform mat4 renderer_MVPMat;\nuniform mat4 renderer_NormalMat;"; // eslint-disable-line
4779
-
4780
- var color_share = "#ifdef RENDERER_ENABLE_VERTEXCOLOR\n\nvarying vec4 v_color;\n\n#endif\n"; // eslint-disable-line
4781
-
4782
- var FogFragmentDeclaration = "#if SCENE_FOG_MODE != 0\n varying vec3 v_positionVS;\n\n uniform vec4 scene_FogColor;\n uniform vec4 scene_FogParams;// (-1/(end-start), end/(end-start), density/ln(2),density/sprt(ln(2)));\n\n float ComputeFogIntensity(float fogDepth){\n #if SCENE_FOG_MODE == 1\n // (end-z) / (end-start) = z * (-1/(end-start)) + (end/(end-start))\n return clamp(fogDepth * scene_FogParams.x + scene_FogParams.y, 0.0, 1.0);\n #elif SCENE_FOG_MODE == 2\n // exp(-z * density) = exp2((-z * density)/ln(2)) = exp2(-z * density/ln(2))\n return clamp(exp2(-fogDepth * scene_FogParams.z), 0.0, 1.0);\n #elif SCENE_FOG_MODE == 3\n // exp(-(z * density)^2) = exp2(-(z * density)^2/ln(2)) = exp2(-(z * density/sprt(ln(2)))^2)\n float factor = fogDepth * scene_FogParams.w;\n return clamp(exp2(-factor * factor), 0.0, 1.0);\n #endif\n }\n#endif\n"; // eslint-disable-line
4783
-
4784
- var FogVertexDeclaration = "#if SCENE_FOG_MODE != 0\n varying vec3 v_positionVS;\n#endif\n"; // eslint-disable-line
4785
-
4786
- var PositionClipSpaceDeclaration = "#ifdef SCENE_ENABLE_AMBIENT_OCCLUSION\n varying vec4 v_PositionCS;\n#endif"; // eslint-disable-line
4787
-
4788
- var normal_share = "#ifndef MATERIAL_OMIT_NORMAL\n #ifdef RENDERER_HAS_NORMAL\n varying vec3 v_normal;\n #if defined(RENDERER_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) || defined(MATERIAL_ENABLE_ANISOTROPY) )\n varying mat3 v_TBN;\n #endif\n #endif\n#endif"; // eslint-disable-line
4789
-
4790
- var uv_share = "varying vec2 v_uv;\n\n#ifdef RENDERER_HAS_UV1\n varying vec2 v_uv1;\n#endif"; // eslint-disable-line
4791
-
4792
- var worldpos_share = "#ifdef MATERIAL_NEED_WORLD_POS\n varying vec3 v_pos;\n#endif\n"; // eslint-disable-line
4793
-
4794
- var begin_normal_vert = "#ifndef MATERIAL_OMIT_NORMAL\n #ifdef RENDERER_HAS_NORMAL\n vec3 normal = vec3( NORMAL );\n #endif\n\n #ifdef RENDERER_HAS_TANGENT\n vec4 tangent = vec4( TANGENT );\n #endif\n#endif"; // eslint-disable-line
4795
-
4796
- var begin_position_vert = " vec4 position = vec4( POSITION , 1.0 );\n"; // eslint-disable-line
4797
-
4798
- var blendShape_input = "#ifdef RENDERER_HAS_BLENDSHAPE\n\t#ifdef RENDERER_BLENDSHAPE_USE_TEXTURE\n\t\tuniform mediump sampler2DArray renderer_BlendShapeTexture;\n\t\tuniform ivec3 renderer_BlendShapeTextureInfo;\n\t\tuniform float renderer_BlendShapeWeights[RENDERER_BLENDSHAPE_COUNT];\n\t#else\n\t\tattribute vec3 POSITION_BS0;\n\t\tattribute vec3 POSITION_BS1;\n\t\t#if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) && defined( RENDERER_BLENDSHAPE_HAS_TANGENT )\n\t\t\tattribute vec3 NORMAL_BS0;\n\t\t\tattribute vec3 NORMAL_BS1;\n\t\t\tattribute vec3 TANGENT_BS0;\n\t\t\tattribute vec3 TANGENT_BS1;\n\t\t\tuniform float renderer_BlendShapeWeights[2];\n\t\t#else\n\t\t\t#if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) || defined( RENDERER_BLENDSHAPE_HAS_TANGENT )\n\t\t\t\tattribute vec3 POSITION_BS2;\n\t\t\t\tattribute vec3 POSITION_BS3;\n\t\t\t\t#ifdef RENDERER_BLENDSHAPE_HAS_NORMAL\n\t\t\t\t\tattribute vec3 NORMAL_BS0;\n\t\t\t\t\tattribute vec3 NORMAL_BS1;\n\t\t\t\t\tattribute vec3 NORMAL_BS2;\n\t\t\t\t\tattribute vec3 NORMAL_BS3;\n\t\t\t\t#endif\n\n\t\t\t\t#ifdef RENDERER_BLENDSHAPE_HAS_TANGENT\n\t\t\t\t\tattribute vec3 TANGENT_BS0;\n\t\t\t\t\tattribute vec3 TANGENT_BS1;\n\t\t\t\t\tattribute vec3 TANGENT_BS2;\n\t\t\t\t\tattribute vec3 TANGENT_BS3;\n\t\t\t\t#endif\n\n\t\t\t\tuniform float renderer_BlendShapeWeights[4];\n\t\t\t#else\n\t\t\t\tattribute vec3 POSITION_BS2;\n\t\t\t\tattribute vec3 POSITION_BS3;\n\t\t\t\tattribute vec3 POSITION_BS4;\n\t\t\t\tattribute vec3 POSITION_BS5;\n\t\t\t\tattribute vec3 POSITION_BS6;\n\t\t\t\tattribute vec3 POSITION_BS7;\n\t\t\t\tuniform float renderer_BlendShapeWeights[8];\n\t\t\t#endif\n\t\t#endif\n\t#endif\n\n\t#ifdef RENDERER_BLENDSHAPE_USE_TEXTURE\n\t\tvec3 getBlendShapeVertexElement(int blendShapeIndex, int vertexElementIndex)\n\t\t{\t\t\t\n\t\t\tint y = vertexElementIndex / renderer_BlendShapeTextureInfo.y;\n\t\t\tint x = vertexElementIndex - y * renderer_BlendShapeTextureInfo.y;\n\t\t\tivec3 uv = ivec3(x, y , blendShapeIndex);\n\t\t\treturn texelFetch(renderer_BlendShapeTexture, uv, 0).xyz;\n\t\t}\n\t#endif\n#endif\n"; // eslint-disable-line
4799
-
4800
- var blendShape_vert = "#ifdef RENDERER_HAS_BLENDSHAPE\n\t#ifdef RENDERER_BLENDSHAPE_USE_TEXTURE\t\n\t\tint vertexOffset = gl_VertexID * renderer_BlendShapeTextureInfo.x;\n\t\tfor(int i = 0; i < RENDERER_BLENDSHAPE_COUNT; i++){\n\t\t\tint vertexElementOffset = vertexOffset;\n\t\t\tfloat weight = renderer_BlendShapeWeights[i];\n\t\t\t// Warnning: Multiplying by 0 creates weird precision issues, causing rendering anomalies in Ace2 Android13\n\t\t\tif(weight != 0.0){\n\t\t\t\tposition.xyz += getBlendShapeVertexElement(i, vertexElementOffset) * weight;\n\t\n\t\t\t\t#ifndef MATERIAL_OMIT_NORMAL\n\t\t\t\t\t#if defined( RENDERER_HAS_NORMAL ) && defined( RENDERER_BLENDSHAPE_HAS_NORMAL )\n\t\t\t\t\t\tvertexElementOffset += 1;\n\t\t\t\t\t\tnormal += getBlendShapeVertexElement(i, vertexElementOffset) * weight;\n\t\t\t\t\t#endif\n\t\n\t\t\t\t\t#if defined( RENDERER_HAS_TANGENT ) && defined(RENDERER_BLENDSHAPE_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) )\n\t\t\t\t\t\tvertexElementOffset += 1;\n\t\t\t\t\t\ttangent.xyz += getBlendShapeVertexElement(i, vertexElementOffset) * weight;\n\t\t\t\t\t#endif\n\t\t\t\t#endif\n\t\t\t}\n\t\t\t\n\t\t}\n\t#else\n\t\tposition.xyz += POSITION_BS0 * renderer_BlendShapeWeights[0];\n\t\tposition.xyz += POSITION_BS1 * renderer_BlendShapeWeights[1];\n\n\t\t#if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) && defined( RENDERER_BLENDSHAPE_HAS_TANGENT )\n\t\t\t#ifndef MATERIAL_OMIT_NORMAL\n\t\t\t\t#ifdef RENDERER_HAS_NORMAL\n\t\t\t\t\tnormal += NORMAL_BS0 * renderer_BlendShapeWeights[0];\n\t\t\t\t\tnormal += NORMAL_BS1 * renderer_BlendShapeWeights[1];\n\t\t\t\t#endif\n\t\t\t\t#if defined( RENDERER_HAS_TANGENT ) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) )\n\t\t\t\t\ttangent.xyz += TANGENT_BS0 * renderer_BlendShapeWeights[0];\n\t\t\t\t\ttangent.xyz += TANGENT_BS1 * renderer_BlendShapeWeights[1];\n\t\t\t\t#endif\t\t\t\t\n\t\t\t#endif\n\t\t#else\n\t\t\t#if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) || defined( RENDERER_BLENDSHAPE_HAS_TANGENT )\n\t\t\t\t#ifndef MATERIAL_OMIT_NORMAL\n\t\t\t\t\tposition.xyz += POSITION_BS2 * renderer_BlendShapeWeights[2];\n\t\t\t\t\tposition.xyz += POSITION_BS3 * renderer_BlendShapeWeights[3];\n\n\t\t\t\t\t#if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) && defined( RENDERER_HAS_NORMAL )\n\t\t\t\t\t\tnormal += NORMAL_BS0 * renderer_BlendShapeWeights[0];\n\t\t\t\t\t\tnormal += NORMAL_BS1 * renderer_BlendShapeWeights[1];\n\t\t\t\t\t\tnormal += NORMAL_BS2 * renderer_BlendShapeWeights[2];\n\t\t\t\t\t\tnormal += NORMAL_BS3 * renderer_BlendShapeWeights[3];\n\t\t\t\t\t#endif\n\n\t\t\t\t\t#if defined(RENDERER_BLENDSHAPE_HAS_TANGENT) && defined( RENDERER_HAS_TANGENT ) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) )\n\t\t\t\t\t\ttangent.xyz += TANGENT_BS0 * renderer_BlendShapeWeights[0];\n\t\t\t\t\t\ttangent.xyz += TANGENT_BS1 * renderer_BlendShapeWeights[1];\n\t\t\t\t\t\ttangent.xyz += TANGENT_BS2 * renderer_BlendShapeWeights[2];\n\t\t\t\t\t\ttangent.xyz += TANGENT_BS3 * renderer_BlendShapeWeights[3];\n\t\t\t\t\t#endif\n\t\t\t\t#endif\n\t\t\t#else\n\t\t\t\tposition.xyz += POSITION_BS2 * renderer_BlendShapeWeights[2];\n\t\t\t\tposition.xyz += POSITION_BS3 * renderer_BlendShapeWeights[3];\n\t\t\t\tposition.xyz += POSITION_BS4 * renderer_BlendShapeWeights[4];\n\t\t\t\tposition.xyz += POSITION_BS5 * renderer_BlendShapeWeights[5];\n\t\t\t\tposition.xyz += POSITION_BS6 * renderer_BlendShapeWeights[6];\n\t\t\t\tposition.xyz += POSITION_BS7 * renderer_BlendShapeWeights[7];\n\t\t\t#endif\n\t\t#endif\n\t#endif\n#endif\n\n\n"; // eslint-disable-line
4801
-
4802
- var color_vert = " #ifdef RENDERER_ENABLE_VERTEXCOLOR\n\n v_color = COLOR_0;\n\n #endif\n"; // eslint-disable-line
4803
-
4804
- var FogVertex = "#if SCENE_FOG_MODE != 0\n vec4 positionVS = renderer_MVMat * position;\n v_positionVS = positionVS.xyz / positionVS.w;\n#endif\n"; // eslint-disable-line
4805
-
4806
- var normal_vert = "#ifndef MATERIAL_OMIT_NORMAL\n #ifdef RENDERER_HAS_NORMAL\n v_normal = normalize( mat3(renderer_NormalMat) * normal );\n\n #if defined(RENDERER_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) || defined(MATERIAL_ENABLE_ANISOTROPY) )\n vec3 tangentW = normalize( mat3(renderer_NormalMat) * tangent.xyz );\n vec3 bitangentW = cross( v_normal, tangentW ) * tangent.w;\n\n v_TBN = mat3( tangentW, bitangentW, v_normal );\n #endif\n #endif\n#endif"; // eslint-disable-line
4807
-
4808
- var position_vert = " gl_Position = renderer_MVPMat * position;"; // eslint-disable-line
4809
-
4810
- var skinning_vert = "#ifdef RENDERER_HAS_SKIN\n\n #ifdef RENDERER_USE_JOINT_TEXTURE\n mat4 skinMatrix =\n WEIGHTS_0.x * getJointMatrix(renderer_JointSampler, JOINTS_0.x ) +\n WEIGHTS_0.y * getJointMatrix(renderer_JointSampler, JOINTS_0.y ) +\n WEIGHTS_0.z * getJointMatrix(renderer_JointSampler, JOINTS_0.z ) +\n WEIGHTS_0.w * getJointMatrix(renderer_JointSampler, JOINTS_0.w );\n\n #else\n mat4 skinMatrix =\n WEIGHTS_0.x * renderer_JointMatrix[ int( JOINTS_0.x ) ] +\n WEIGHTS_0.y * renderer_JointMatrix[ int( JOINTS_0.y ) ] +\n WEIGHTS_0.z * renderer_JointMatrix[ int( JOINTS_0.z ) ] +\n WEIGHTS_0.w * renderer_JointMatrix[ int( JOINTS_0.w ) ];\n #endif\n\n position = skinMatrix * position;\n\n #if defined(RENDERER_HAS_NORMAL) && !defined(MATERIAL_OMIT_NORMAL)\n mat3 skinNormalMatrix = INVERSE_MAT(mat3(skinMatrix));\n normal = normal * skinNormalMatrix;\n #if defined(RENDERER_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) )\n tangent.xyz = tangent.xyz * skinNormalMatrix;\n #endif\n\n #endif\n\n#endif\n"; // eslint-disable-line
4811
-
4812
- var uv_vert = "#ifdef RENDERER_HAS_UV\n v_uv = TEXCOORD_0;\n#else\n // may need this calculate normal\n v_uv = vec2( 0., 0. );\n#endif\n\n#ifdef RENDERER_HAS_UV1\n v_uv1 = TEXCOORD_1;\n#endif\n\n#ifdef MATERIAL_NEED_TILING_OFFSET\n v_uv = v_uv * material_TilingOffset.xy + material_TilingOffset.zw;\n#endif"; // eslint-disable-line
4813
-
4814
- var worldpos_vert = "#ifdef MATERIAL_NEED_WORLD_POS\n vec4 temp_pos = renderer_ModelMat * position;\n v_pos = temp_pos.xyz / temp_pos.w;\n#endif\n"; // eslint-disable-line
4815
-
4816
- var FogFragment = "#if SCENE_FOG_MODE != 0\n float fogIntensity = ComputeFogIntensity(length(v_positionVS));\n gl_FragColor.rgb = mix(scene_FogColor.rgb, gl_FragColor.rgb, fogIntensity);\n#endif\n"; // eslint-disable-line
4817
-
4818
- var PositionClipSpaceVertex = "#ifdef SCENE_ENABLE_AMBIENT_OCCLUSION\n v_PositionCS = gl_Position;\n#endif\n"; // eslint-disable-line
4819
-
4820
- var light_frag_define = "// Directional light\n#ifdef SCENE_DIRECT_LIGHT_COUNT\n\n struct DirectLight {\n vec3 color;\n vec3 direction;\n };\n\n uniform ivec2 scene_DirectLightCullingMask[SCENE_DIRECT_LIGHT_COUNT];\n uniform vec3 scene_DirectLightColor[SCENE_DIRECT_LIGHT_COUNT];\n uniform vec3 scene_DirectLightDirection[SCENE_DIRECT_LIGHT_COUNT];\n\n#endif\n\n\n// Point light\n#ifdef SCENE_POINT_LIGHT_COUNT\n\n struct PointLight {\n vec3 color;\n vec3 position;\n float distance;\n };\n\n uniform ivec2 scene_PointLightCullingMask[ SCENE_POINT_LIGHT_COUNT ];\n uniform vec3 scene_PointLightColor[ SCENE_POINT_LIGHT_COUNT ];\n uniform vec3 scene_PointLightPosition[ SCENE_POINT_LIGHT_COUNT ];\n uniform float scene_PointLightDistance[ SCENE_POINT_LIGHT_COUNT ];\n\n#endif\n\n\n// Spot light\n#ifdef SCENE_SPOT_LIGHT_COUNT\n\n struct SpotLight {\n vec3 color;\n vec3 position;\n vec3 direction;\n float distance;\n float angleCos;\n float penumbraCos;\n };\n\n uniform ivec2 scene_SpotLightCullingMask[ SCENE_SPOT_LIGHT_COUNT ];\n uniform vec3 scene_SpotLightColor[ SCENE_SPOT_LIGHT_COUNT ];\n uniform vec3 scene_SpotLightPosition[ SCENE_SPOT_LIGHT_COUNT ];\n uniform vec3 scene_SpotLightDirection[ SCENE_SPOT_LIGHT_COUNT ];\n uniform float scene_SpotLightDistance[ SCENE_SPOT_LIGHT_COUNT ];\n uniform float scene_SpotLightAngleCos[ SCENE_SPOT_LIGHT_COUNT ];\n uniform float scene_SpotLightPenumbraCos[ SCENE_SPOT_LIGHT_COUNT ];\n\n#endif\n\n// Ambient light\nstruct EnvMapLight {\n vec3 diffuse;\n float mipMapLevel;\n float diffuseIntensity;\n float specularIntensity;\n};\n\n\nuniform EnvMapLight scene_EnvMapLight;\nuniform ivec4 renderer_Layer;\n\n#ifdef SCENE_USE_SH\n uniform vec3 scene_EnvSH[9];\n#endif\n\n#ifdef SCENE_USE_SPECULAR_ENV\n uniform samplerCube scene_EnvSpecularSampler;\n#endif\n\n#ifndef GRAPHICS_API_WEBGL2\nbool isBitSet(float value, float mask, float bitIndex)\n{\n return mod(floor(value / pow(2.0, bitIndex)), 2.0) == 1.0 && mod(floor(mask / pow(2.0, bitIndex)), 2.0) == 1.0;\n}\n#endif\n\nbool isRendererCulledByLight(ivec2 rendererLayer, ivec2 lightCullingMask)\n{\n #ifdef GRAPHICS_API_WEBGL2\n return !((rendererLayer.x & lightCullingMask.x) != 0 || (rendererLayer.y & lightCullingMask.y) != 0);\n #else\n for (int i = 0; i < 16; i++) {\n if (isBitSet( float(rendererLayer.x), float(lightCullingMask.x), float(i)) || isBitSet( float(rendererLayer.y), float(lightCullingMask.y), float(i))) {\n return false;\n }\n }\n return true;\n #endif\n}\n"; // eslint-disable-line
4821
-
4822
- var mobile_material_frag = "uniform vec4 material_EmissiveColor;\nuniform vec4 material_BaseColor;\nuniform vec4 material_SpecularColor;\nuniform float material_Shininess;\nuniform float material_NormalIntensity;\nuniform float material_AlphaCutoff;\n\n#ifdef MATERIAL_HAS_EMISSIVETEXTURE\n uniform sampler2D material_EmissiveTexture;\n#endif\n\n#ifdef MATERIAL_HAS_BASETEXTURE\n uniform sampler2D material_BaseTexture;\n#endif\n\n#ifdef MATERIAL_HAS_SPECULAR_TEXTURE\n uniform sampler2D material_SpecularTexture;\n#endif\n\n#ifdef MATERIAL_HAS_NORMALTEXTURE\n uniform sampler2D material_NormalTexture;\n#endif\n"; // eslint-disable-line
4823
-
4824
- var begin_mobile_frag = " vec4 ambient = vec4(0.0);\n vec4 emission = material_EmissiveColor;\n vec4 diffuse = material_BaseColor;\n vec4 specular = material_SpecularColor;\n\n \n\n #ifdef MATERIAL_HAS_EMISSIVETEXTURE\n emission *= texture2DSRGB(material_EmissiveTexture, v_uv);\n #endif\n\n #ifdef MATERIAL_HAS_BASETEXTURE\n diffuse *= texture2DSRGB(material_BaseTexture, v_uv);\n #endif\n\n #ifdef RENDERER_ENABLE_VERTEXCOLOR\n diffuse *= v_color;\n #endif\n\n #ifdef MATERIAL_HAS_SPECULAR_TEXTURE\n specular *= texture2DSRGB(material_SpecularTexture, v_uv);\n #endif\n\n ambient = vec4(scene_EnvMapLight.diffuse * scene_EnvMapLight.diffuseIntensity, 1.0) * diffuse;"; // eslint-disable-line
4825
-
4826
- var begin_viewdir_frag = "#ifdef CAMERA_ORTHOGRAPHIC\n vec3 V = -camera_Forward;\n#else\n #ifdef MATERIAL_NEED_WORLD_POS\n vec3 V = normalize( camera_Position - v_pos );\n #endif\n#endif"; // eslint-disable-line
4827
-
4828
- var mobile_blinnphong_frag = " #ifdef MATERIAL_HAS_NORMALTEXTURE\n mat3 tbn = getTBN(gl_FrontFacing);\n vec3 N = getNormalByNormalTexture(tbn, material_NormalTexture, material_NormalIntensity, v_uv, gl_FrontFacing);\n #else\n vec3 N = getNormal(gl_FrontFacing);\n #endif\n\n vec3 lightDiffuse = vec3( 0.0, 0.0, 0.0 );\n vec3 lightSpecular = vec3( 0.0, 0.0, 0.0 );\n float shadowAttenuation = 1.0;\n\n #ifdef SCENE_DIRECT_LIGHT_COUNT\n shadowAttenuation = 1.0;\n #ifdef SCENE_IS_CALCULATE_SHADOWS\n shadowAttenuation *= sampleShadowMap();\n #endif\n\n DirectLight directionalLight;\n for( int i = 0; i < SCENE_DIRECT_LIGHT_COUNT; i++ ) {\n if(!isRendererCulledByLight(renderer_Layer.xy, scene_DirectLightCullingMask[i])){\n directionalLight.color = scene_DirectLightColor[i];\n #ifdef SCENE_IS_CALCULATE_SHADOWS\n if (i == 0) { // Sun light index is always 0\n directionalLight.color *= shadowAttenuation;\n }\n #endif\n directionalLight.direction = scene_DirectLightDirection[i];\n \n float d = max(dot(N, -directionalLight.direction), 0.0);\n lightDiffuse += directionalLight.color * d;\n \n vec3 halfDir = normalize( V - directionalLight.direction );\n float s = pow( clamp( dot( N, halfDir ), 0.0, 1.0 ), material_Shininess );\n lightSpecular += directionalLight.color * s;\n }\n }\n\n #endif\n\n #ifdef SCENE_POINT_LIGHT_COUNT\n PointLight pointLight;\n for( int i = 0; i < SCENE_POINT_LIGHT_COUNT; i++ ) {\n if(!isRendererCulledByLight(renderer_Layer.xy, scene_PointLightCullingMask[i])){\n pointLight.color = scene_PointLightColor[i];\n pointLight.position = scene_PointLightPosition[i];\n pointLight.distance = scene_PointLightDistance[i];\n\n vec3 direction = v_pos - pointLight.position;\n float dist = length( direction );\n direction /= dist;\n float decay = clamp(1.0 - pow(dist / pointLight.distance, 4.0), 0.0, 1.0);\n\n float d = max( dot( N, -direction ), 0.0 ) * decay;\n lightDiffuse += pointLight.color * d;\n\n vec3 halfDir = normalize( V - direction );\n float s = pow( clamp( dot( N, halfDir ), 0.0, 1.0 ), material_Shininess ) * decay;\n lightSpecular += pointLight.color * s;\n }\n }\n\n #endif\n\n #ifdef SCENE_SPOT_LIGHT_COUNT\n SpotLight spotLight;\n for( int i = 0; i < SCENE_SPOT_LIGHT_COUNT; i++) {\n if(!isRendererCulledByLight(renderer_Layer.xy, scene_SpotLightCullingMask[i])){\n spotLight.color = scene_SpotLightColor[i];\n spotLight.position = scene_SpotLightPosition[i];\n spotLight.direction = scene_SpotLightDirection[i];\n spotLight.distance = scene_SpotLightDistance[i];\n spotLight.angleCos = scene_SpotLightAngleCos[i];\n spotLight.penumbraCos = scene_SpotLightPenumbraCos[i];\n\n vec3 direction = spotLight.position - v_pos;\n float lightDistance = length( direction );\n direction /= lightDistance;\n float angleCos = dot( direction, -spotLight.direction );\n float decay = clamp(1.0 - pow(lightDistance/spotLight.distance, 4.0), 0.0, 1.0);\n float spotEffect = smoothstep( spotLight.penumbraCos, spotLight.angleCos, angleCos );\n float decayTotal = decay * spotEffect;\n float d = max( dot( N, direction ), 0.0 ) * decayTotal;\n lightDiffuse += spotLight.color * d;\n\n vec3 halfDir = normalize( V + direction );\n float s = pow( clamp( dot( N, halfDir ), 0.0, 1.0 ), material_Shininess ) * decayTotal;\n lightSpecular += spotLight.color * s;\n }\n }\n\n #endif\n\n diffuse *= vec4( lightDiffuse, 1.0 );\n specular *= vec4( lightSpecular, 1.0 );\n\n #ifdef MATERIAL_IS_ALPHA_CUTOFF\n if( diffuse.a < material_AlphaCutoff ) {\n discard;\n }\n #endif\n"; // eslint-disable-line
4829
-
4830
- var noise_common = "// Common helper functions for simplex noise.\n// Algorithm: Ken Perlin, \"Noise hardware\" (2001) — simplex lattice improvement over classic Perlin noise (1985).\n// GLSL implementation: Ian McEwan, Ashima Arts (MIT License) — https://github.com/ashima/webgl-noise\n\n// Modulo 289 without a division (only multiplications)\nvec4 mod289( vec4 x ) {\n\n return x - floor( x * ( 1.0 / 289.0 ) ) * 289.0;\n\n}\n\nvec3 mod289( vec3 x ) {\n\n return x - floor( x * ( 1.0 / 289.0 ) ) * 289.0;\n\n}\n\nvec2 mod289( vec2 x ) {\n\n return x - floor( x * ( 1.0 / 289.0 ) ) * 289.0;\n\n}\n\nfloat mod289( float x ) {\n\n return x - floor( x * ( 1.0 / 289.0 ) ) * 289.0;\n\n}\n\n// Modulo 7 without a division\nvec4 mod7( vec4 x ) {\n\n return x - floor( x * ( 1.0 / 7.0 ) ) * 7.0;\n\n}\n\nvec3 mod7( vec3 x ) {\n\n return x - floor( x * ( 1.0 / 7.0 ) ) * 7.0;\n\n}\n\n// Permutation polynomial: (34x^2 + x) mod 289\nvec4 permute( vec4 x ) {\n\n return mod289( ( 34.0 * x + 1.0 ) * x);\n\n}\n\nvec3 permute( vec3 x ) {\n\n return mod289( ( 34.0 * x + 1.0 ) * x );\n\n}\n\nfloat permute( float x ) {\n\n return mod289( ( ( x * 34.0 ) + 1.0 ) * x );\n\n}\n\nvec4 taylorInvSqrt( vec4 r ) {\n\n return 1.79284291400159 - 0.85373472095314 * r;\n\n}\n\nfloat taylorInvSqrt( float r ) {\n\n return 1.79284291400159 - 0.85373472095314 * r;\n\n}\n\nvec4 fade( vec4 t ) {\n\n return t * t * t * ( t * ( t * 6.0 - 15.0 ) + 10.0 );\n\n}\n\nvec3 fade( vec3 t ) {\n\n return t * t * t * ( t * ( t * 6.0 - 15.0 ) + 10.0 );\n\n}\n\nvec2 fade( vec2 t ) {\n\n return t * t * t * ( t * ( t * 6.0 - 15.0 ) + 10.0 );\n\n}\n\n#define K 0.142857142857 // 1/7\n#define Ko 0.428571428571 // 1/2-K/2\n#define K2 0.020408163265306 // 1/(7*7)\n#define Kd2 0.0714285714285 // K/2\n#define Kz 0.166666666667 // 1/6\n#define Kzo 0.416666666667 // 1/2-1/6*2\n#define jitter 1.0 // smaller jitter gives more regular pattern\n#define jitter1 0.8 // smaller jitter gives less errors in F1 F2\n"; // eslint-disable-line
4831
-
4832
- var noise_simplex_3D_grad = "// 3D simplex noise analytical gradient.\n// Algorithm: Ken Perlin, \"Noise hardware\" (2001) — simplex lattice improvement over classic Perlin noise (1985).\n// Curl noise: Robert Bridson et al., \"Curl-noise for procedural fluid flow\" (2007).\n// GLSL implementation: Ian McEwan, Ashima Arts (MIT License) — https://github.com/ashima/webgl-noise\n\nvec3 simplexGrad( vec3 v ) {\n\n const vec2 C = vec2( 1.0 / 6.0, 1.0 / 3.0 );\n const vec4 D = vec4( 0.0, 0.5, 1.0, 2.0 );\n\n // First corner\n vec3 i = floor( v + dot( v, C.yyy ) );\n vec3 x0 = v - i + dot( i, C.xxx ) ;\n\n // Other corners\n vec3 g = step( x0.yzx, x0.xyz );\n vec3 l = 1.0 - g;\n vec3 i1 = min( g.xyz, l.zxy );\n vec3 i2 = max( g.xyz, l.zxy );\n\n vec3 x1 = x0 - i1 + C.xxx;\n vec3 x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y\n vec3 x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y\n\n // Permutations\n i = mod289( i );\n vec4 p = permute( permute( permute(\n i.z + vec4( 0.0, i1.z, i2.z, 1.0 ) )\n + i.y + vec4( 0.0, i1.y, i2.y, 1.0 ) )\n + i.x + vec4( 0.0, i1.x, i2.x, 1.0 ) );\n\n // Gradients: 7x7 points over a square, mapped onto an octahedron.\n // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)\n float n_ = 0.142857142857; // 1.0/7.0\n vec3 ns = n_ * D.wyz - D.xzx;\n\n vec4 j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p,7*7)\n\n vec4 x_ = floor(j * ns.z);\n vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N)\n\n vec4 x = x_ * ns.x + ns.yyyy;\n vec4 y = y_ * ns.x + ns.yyyy;\n vec4 h = 1.0 - abs( x ) - abs( y );\n\n vec4 b0 = vec4( x.xy, y.xy );\n vec4 b1 = vec4( x.zw, y.zw );\n\n vec4 s0 = floor( b0 ) * 2.0 + 1.0;\n vec4 s1 = floor( b1 ) * 2.0 + 1.0;\n vec4 sh = - step( h, vec4( 0.0 ) );\n\n vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy ;\n vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww ;\n\n vec3 p0 = vec3( a0.xy, h.x );\n vec3 p1 = vec3( a0.zw, h.y );\n vec3 p2 = vec3( a1.xy, h.z );\n vec3 p3 = vec3( a1.zw, h.w );\n\n //Normalise gradients\n vec4 norm = taylorInvSqrt( vec4( dot( p0, p0 ), dot( p1, p1 ), dot( p2, p2 ), dot( p3, p3 ) ) );\n p0 *= norm.x;\n p1 *= norm.y;\n p2 *= norm.z;\n p3 *= norm.w;\n\n // Mix final noise value\n vec4 m = max( 0.6 - vec4( dot( x0, x0 ), dot( x1, x1 ), dot( x2, x2 ), dot( x3, x3 ) ), 0.0 );\n vec4 m2 = m * m;\n vec4 m4 = m2 * m2;\n vec4 pdotx = vec4( dot( p0, x0 ), dot( p1, x1 ), dot( p2, x2 ), dot( p3, x3 ) );\n\n // Compute and return noise gradient\n vec4 temp = m2 * m * pdotx;\n vec3 grad = - 8.0 * ( temp.x * x0 + temp.y * x1 + temp.z * x2 + temp.w * x3 );\n grad += m4.x * p0 + m4.y * p1 + m4.z * p2 + m4.w * p3;\n return grad * 42.0;\n\n}\n"; // eslint-disable-line
4833
-
4834
- var pbr_frag_define = "#define MIN_PERCEPTUAL_ROUGHNESS 0.045\n#define MIN_ROUGHNESS 0.002025\n\nuniform float material_AlphaCutoff;\nuniform vec4 material_BaseColor;\nuniform float material_Metal;\nuniform float material_Roughness;\nuniform float material_IOR;\nuniform vec3 material_EmissiveColor;\nuniform float material_NormalIntensity;\nuniform float material_OcclusionIntensity;\nuniform float material_OcclusionTextureCoord;\nuniform float material_SpecularIntensity;\nuniform vec3 material_SpecularColor;\n\n#ifdef MATERIAL_ENABLE_CLEAR_COAT\n uniform float material_ClearCoat;\n uniform float material_ClearCoatRoughness;\n\n #ifdef MATERIAL_HAS_CLEAR_COAT_TEXTURE\n uniform sampler2D material_ClearCoatTexture;\n #endif\n\n #ifdef MATERIAL_HAS_CLEAR_COAT_ROUGHNESS_TEXTURE\n uniform sampler2D material_ClearCoatRoughnessTexture;\n #endif\n\n #ifdef MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE\n uniform sampler2D material_ClearCoatNormalTexture;\n #endif\n#endif\n\n#ifdef MATERIAL_ENABLE_ANISOTROPY\n uniform vec3 material_AnisotropyInfo;\n #ifdef MATERIAL_HAS_ANISOTROPY_TEXTURE\n uniform sampler2D material_AnisotropyTexture;\n #endif\n#endif\n\n// Texture\n#ifdef MATERIAL_HAS_BASETEXTURE\n uniform sampler2D material_BaseTexture;\n#endif\n\n#ifdef MATERIAL_HAS_NORMALTEXTURE\n uniform sampler2D material_NormalTexture;\n#endif\n\n#ifdef MATERIAL_HAS_EMISSIVETEXTURE\n uniform sampler2D material_EmissiveTexture;\n#endif\n\n#ifdef MATERIAL_HAS_ROUGHNESS_METALLIC_TEXTURE\n uniform sampler2D material_RoughnessMetallicTexture;\n#endif\n\n#ifdef MATERIAL_HAS_SPECULAR_TEXTURE\n uniform sampler2D material_SpecularIntensityTexture;\n#endif\n\n#ifdef MATERIAL_HAS_SPECULAR_COLOR_TEXTURE\n uniform sampler2D material_SpecularColorTexture;\n#endif\n\n#ifdef MATERIAL_HAS_OCCLUSION_TEXTURE\n uniform sampler2D material_OcclusionTexture;\n#endif\n\n\n#ifdef MATERIAL_ENABLE_SHEEN\n uniform float material_SheenRoughness;\n uniform vec3 material_SheenColor;\n #ifdef MATERIAL_HAS_SHEEN_TEXTURE\n uniform sampler2D material_SheenTexture;\n #endif\n\n #ifdef MATERIAL_HAS_SHEEN_ROUGHNESS_TEXTURE\n uniform sampler2D material_SheenRoughnessTexture;\n #endif\n#endif\n\n\n#ifdef MATERIAL_ENABLE_IRIDESCENCE\n uniform vec4 material_IridescenceInfo;\n #ifdef MATERIAL_HAS_IRIDESCENCE_THICKNESS_TEXTURE\n uniform sampler2D material_IridescenceThicknessTexture;\n #endif\n\n #ifdef MATERIAL_HAS_IRIDESCENCE_TEXTURE\n uniform sampler2D material_IridescenceTexture;\n #endif\n#endif\n\n#ifdef MATERIAL_ENABLE_TRANSMISSION\n uniform float material_Transmission;\n #ifdef MATERIAL_HAS_TRANSMISSION_TEXTURE\n uniform sampler2D material_TransmissionTexture;\n #endif\n\n #ifdef MATERIAL_HAS_THICKNESS\n uniform vec3 material_AttenuationColor;\n uniform float material_AttenuationDistance;\n uniform float material_Thickness;\n\n #ifdef MATERIAL_HAS_THICKNESS_TEXTURE\n uniform sampler2D material_ThicknessTexture;\n #endif\n #endif\n#endif\n\n// Runtime\nstruct ReflectedLight {\n vec3 directDiffuse;\n vec3 directSpecular;\n vec3 indirectDiffuse;\n vec3 indirectSpecular;\n};\n\nstruct Geometry {\n vec3 position;\n vec3 normal;\n vec3 viewDir;\n float dotNV;\n \n #ifdef MATERIAL_ENABLE_CLEAR_COAT\n vec3 clearCoatNormal;\n float clearCoatDotNV;\n #endif\n\n #ifdef MATERIAL_ENABLE_ANISOTROPY\n vec3 anisotropicT;\n vec3 anisotropicB;\n vec3 anisotropicN;\n float anisotropy;\n #endif\n};\n\nstruct Material {\n vec3 diffuseColor;\n float roughness;\n vec3 specularF0;\n vec3 resolvedSpecularF0;\n float specularF90;\n float specularIntensity;\n vec3 specularColor;\n float opacity;\n float diffuseAO;\n float specularAO;\n vec3 envSpecularDFG;\n vec3 energyCompensation; // Multi-scattering energy compensation factor\n float IOR;\n\n #ifdef MATERIAL_ENABLE_CLEAR_COAT\n float clearCoat;\n float clearCoatRoughness;\n #endif\n\n #ifdef MATERIAL_ENABLE_IRIDESCENCE\n float iridescenceIOR;\n float iridescenceFactor;\n float iridescenceThickness;\n vec3 iridescenceSpecularColor;\n #endif\n\n #ifdef MATERIAL_ENABLE_SHEEN\n float sheenRoughness;\n vec3 sheenColor;\n float sheenScaling;\n float approxIBLSheenDG;\n #endif\n\n #ifdef MATERIAL_ENABLE_TRANSMISSION \n vec3 absorptionCoefficient;\n float transmission;\n float thickness;\n #endif\n};\n"; // eslint-disable-line
4835
-
4836
- var pbr_helper = "#include <normal_get>\n#include <brdf>\n#include <btdf>\n\n// direct + indirect\n#include <direct_irradiance_frag_define>\n#include <ibl_frag_define>\n\nuniform sampler2D camera_AOTexture;\n\nfloat evaluateAmbientOcclusion(vec2 uv)\n{\n #ifdef MATERIAL_IS_TRANSPARENT\n return 1.0;\n #else\n return texture2D(camera_AOTexture, uv).r;\n #endif\n}\n\n\nfloat computeSpecularOcclusion(float ambientOcclusion, float roughness, float dotNV ) {\n return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n\nfloat getAARoughnessFactor(vec3 normal) {\n // Kaplanyan 2016, \"Stable specular highlights\"\n // Tokuyoshi 2017, \"Error Reduction and Simplification for Shading Anti-Aliasing\"\n // Tokuyoshi and Kaplanyan 2019, \"Improved Geometric Specular Antialiasing\"\n #ifdef HAS_DERIVATIVES\n vec3 dxy = max( abs(dFdx(normal)), abs(dFdy(normal)) );\n return max( max(dxy.x, dxy.y), dxy.z );\n #else\n return 0.0;\n #endif\n}\n\n#ifdef MATERIAL_ENABLE_ANISOTROPY\n // Aniso Bent Normals\n // Mc Alley https://www.gdcvault.com/play/1022235/Rendering-the-World-of-Far \n vec3 getAnisotropicBentNormal(Geometry geometry, vec3 n, float roughness) {\n vec3 anisotropyDirection = geometry.anisotropy >= 0.0 ? geometry.anisotropicB : geometry.anisotropicT;\n vec3 anisotropicTangent = cross(anisotropyDirection, geometry.viewDir);\n vec3 anisotropicNormal = cross(anisotropicTangent, anisotropyDirection);\n // reduce stretching for (roughness < 0.2), refer to https://advances.realtimerendering.com/s2018/Siggraph%202018%20HDRP%20talk_with%20notes.pdf 80\n vec3 bentNormal = normalize( mix(n, anisotropicNormal, abs(geometry.anisotropy) * saturate( 5.0 * roughness)) );\n\n return bentNormal;\n }\n#endif\n\nvoid initGeometry(out Geometry geometry, bool isFrontFacing){\n geometry.position = v_pos;\n #ifdef CAMERA_ORTHOGRAPHIC\n geometry.viewDir = -camera_Forward;\n #else\n geometry.viewDir = normalize(camera_Position - v_pos);\n #endif\n #if defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) || defined(MATERIAL_ENABLE_ANISOTROPY)\n mat3 tbn = getTBN(isFrontFacing);\n #endif\n\n #ifdef MATERIAL_HAS_NORMALTEXTURE\n geometry.normal = getNormalByNormalTexture(tbn, material_NormalTexture, material_NormalIntensity, v_uv, isFrontFacing);\n #else\n geometry.normal = getNormal(isFrontFacing);\n #endif\n\n geometry.dotNV = saturate( dot(geometry.normal, geometry.viewDir) );\n\n\n #ifdef MATERIAL_ENABLE_CLEAR_COAT\n #ifdef MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE\n geometry.clearCoatNormal = getNormalByNormalTexture(tbn, material_ClearCoatNormalTexture, material_NormalIntensity, v_uv, isFrontFacing);\n #else\n geometry.clearCoatNormal = getNormal(isFrontFacing);\n #endif\n geometry.clearCoatDotNV = saturate( dot(geometry.clearCoatNormal, geometry.viewDir) );\n #endif\n\n #ifdef MATERIAL_ENABLE_ANISOTROPY\n float anisotropy = material_AnisotropyInfo.z;\n vec3 anisotropicDirection = vec3(material_AnisotropyInfo.xy, 0.0);\n #ifdef MATERIAL_HAS_ANISOTROPY_TEXTURE\n vec3 anisotropyTextureInfo = texture2D( material_AnisotropyTexture, v_uv ).rgb;\n anisotropy *= anisotropyTextureInfo.b;\n anisotropicDirection.xy *= anisotropyTextureInfo.rg * 2.0 - 1.0;\n #endif\n\n geometry.anisotropy = anisotropy;\n geometry.anisotropicT = normalize(tbn * anisotropicDirection);\n geometry.anisotropicB = normalize(cross(geometry.normal, geometry.anisotropicT));\n #endif\n}\n\nvoid initMaterial(out Material material, inout Geometry geometry){\n vec4 baseColor = material_BaseColor;\n float metal = material_Metal;\n float roughness = material_Roughness;\n float alphaCutoff = material_AlphaCutoff;\n material.IOR = material_IOR;\n\n #ifdef MATERIAL_HAS_BASETEXTURE\n baseColor *= texture2DSRGB(material_BaseTexture, v_uv);\n #endif\n\n #ifdef RENDERER_ENABLE_VERTEXCOLOR\n baseColor *= v_color;\n #endif\n\n\n #ifdef MATERIAL_IS_ALPHA_CUTOFF\n if( baseColor.a < alphaCutoff ) {\n discard;\n }\n #endif\n\n #ifdef MATERIAL_HAS_ROUGHNESS_METALLIC_TEXTURE\n vec4 metalRoughMapColor = texture2D( material_RoughnessMetallicTexture, v_uv );\n roughness *= metalRoughMapColor.g;\n metal *= metalRoughMapColor.b;\n #endif\n\n // Specular\n material.specularIntensity = material_SpecularIntensity;\n material.specularColor = material_SpecularColor;\n #ifdef MATERIAL_HAS_SPECULAR_TEXTURE\n material.specularIntensity *= texture2D( material_SpecularIntensityTexture, v_uv ).a;\n #endif\n\n #ifdef MATERIAL_ENABLE_CLEAR_COAT\n material.clearCoat = material_ClearCoat;\n material.clearCoatRoughness = material_ClearCoatRoughness;\n #ifdef MATERIAL_HAS_CLEAR_COAT_TEXTURE\n material.clearCoat *= texture2D( material_ClearCoatTexture, v_uv ).r;\n #endif\n #ifdef MATERIAL_HAS_CLEAR_COAT_ROUGHNESS_TEXTURE\n material.clearCoatRoughness *= texture2D( material_ClearCoatRoughnessTexture, v_uv ).g;\n #endif\n material.clearCoat = saturate( material.clearCoat );\n material.clearCoatRoughness = max(MIN_PERCEPTUAL_ROUGHNESS, min(material.clearCoatRoughness + getAARoughnessFactor(geometry.clearCoatNormal), 1.0));\n #endif\n\n #ifdef MATERIAL_IS_TRANSPARENT\n material.opacity = baseColor.a;\n #else\n material.opacity = 1.0;\n #endif\n\n material.roughness = max(MIN_PERCEPTUAL_ROUGHNESS, min(roughness + getAARoughnessFactor(geometry.normal), 1.0));\n\n #ifdef MATERIAL_ENABLE_ANISOTROPY\n geometry.anisotropicN = getAnisotropicBentNormal(geometry, geometry.normal, material.roughness);\n #endif\n\n vec3 dielectricBaseF0 = vec3(pow2( (material.IOR - 1.0) / (material.IOR + 1.0) ));\n vec3 dielectricF0 = min(dielectricBaseF0 * material.specularColor , vec3(1.0)) * material.specularIntensity;\n float dielectricF90 = material.specularIntensity; \n\n material.specularF0 = mix(dielectricF0, baseColor.rgb, metal);\n material.specularF90 = mix(dielectricF90, 1.0, metal);\n material.resolvedSpecularF0 = material.specularF0;\n\n // Simplify: albedoColor * mix((1.0 - max(max(dielectricF0.r,dielectricF0.g),dielectricF0.b)), 0.0, metallic);\n material.diffuseColor = baseColor.rgb * (1.0 - metal) * (1.0 - max(max(dielectricF0.r,dielectricF0.g),dielectricF0.b));\n // Environment BRDF\n vec2 dfg = envDFGApprox(material.roughness, geometry.dotNV);\n\n // AO\n float diffuseAO = 1.0;\n float specularAO = 1.0;\n\n #ifdef MATERIAL_HAS_OCCLUSION_TEXTURE\n vec2 aoUV = v_uv;\n #ifdef RENDERER_HAS_UV1\n if(material_OcclusionTextureCoord == 1.0){\n aoUV = v_uv1;\n }\n #endif\n diffuseAO = ((texture2D(material_OcclusionTexture, aoUV)).r - 1.0) * material_OcclusionIntensity + 1.0;\n #endif\n\n #ifdef SCENE_ENABLE_AMBIENT_OCCLUSION\n float ambientAO = evaluateAmbientOcclusion((v_PositionCS.xy / v_PositionCS.w) * 0.5 + 0.5);\n diffuseAO = min(diffuseAO, ambientAO);\n #endif\n\n #if (defined(MATERIAL_HAS_OCCLUSION_TEXTURE) || defined(SCENE_ENABLE_AMBIENT_OCCLUSION))&& defined(SCENE_USE_SPECULAR_ENV) \n specularAO = saturate( pow( geometry.dotNV + diffuseAO, exp2( - 16.0 * material.roughness - 1.0 ) ) - 1.0 + diffuseAO );\n #endif\n\n material.diffuseAO = diffuseAO;\n material.specularAO = specularAO;\n\n // Sheen\n #ifdef MATERIAL_ENABLE_SHEEN\n vec3 sheenColor = material_SheenColor;\n #ifdef MATERIAL_HAS_SHEEN_TEXTURE\n sheenColor *= texture2DSRGB(material_SheenTexture, v_uv).rgb;\n #endif\n material.sheenColor = sheenColor;\n\n material.sheenRoughness = material_SheenRoughness;\n #ifdef MATERIAL_HAS_SHEEN_ROUGHNESS_TEXTURE\n material.sheenRoughness *= texture2D(material_SheenRoughnessTexture, v_uv).a;\n #endif\n\n material.sheenRoughness = max(MIN_PERCEPTUAL_ROUGHNESS, min(material.sheenRoughness + getAARoughnessFactor(geometry.normal), 1.0));\n material.approxIBLSheenDG = prefilteredSheenDFG(geometry.dotNV, material.sheenRoughness);\n material.sheenScaling = 1.0 - material.approxIBLSheenDG * max(max(material.sheenColor.r, material.sheenColor.g), material.sheenColor.b);\n #endif\n\n // Iridescence\n #ifdef MATERIAL_ENABLE_IRIDESCENCE\n material.iridescenceFactor = material_IridescenceInfo.x;\n material.iridescenceIOR = material_IridescenceInfo.y;\n\n #ifdef MATERIAL_HAS_IRIDESCENCE_THICKNESS_TEXTURE\n float iridescenceThicknessWeight = texture2D( material_IridescenceThicknessTexture, v_uv).g;\n material.iridescenceThickness = mix(material_IridescenceInfo.z, material_IridescenceInfo.w, iridescenceThicknessWeight);\n #else\n material.iridescenceThickness = material_IridescenceInfo.w;\n #endif\n\n #ifdef MATERIAL_HAS_IRIDESCENCE_TEXTURE\n material.iridescenceFactor *= texture2D( material_IridescenceTexture, v_uv).r;\n #endif\n \n #ifdef MATERIAL_ENABLE_IRIDESCENCE\n float topIOR = 1.0;\n material.iridescenceSpecularColor = evalIridescenceSpecular(topIOR, geometry.dotNV, material.iridescenceIOR, material.specularF0, material.specularF90, material.iridescenceThickness);\n material.resolvedSpecularF0 = mix(material.resolvedSpecularF0, material.iridescenceSpecularColor, material.iridescenceFactor);\n #endif\n #endif\n\n material.envSpecularDFG = material.resolvedSpecularF0 * dfg.x + material.specularF90 * dfg.y;\n\n // Multi-scattering energy compensation\n // Ref: Kulla & Conty 2017, \"Revisiting Physically Based Shading at Imageworks\"\n // Ref: Lagarde & Golubev 2018, simplified multiplier approach\n material.energyCompensation = 1.0 + material.resolvedSpecularF0 * (1.0 / max(dfg.x + dfg.y, EPSILON) - 1.0);\n\n // Transmission\n #ifdef MATERIAL_ENABLE_TRANSMISSION \n material.transmission = material_Transmission;\n #ifdef MATERIAL_HAS_TRANSMISSION_TEXTURE\n material.transmission *= texture2D(material_TransmissionTexture, v_uv).r;\n #endif\n\n #ifdef MATERIAL_HAS_THICKNESS\n material.absorptionCoefficient = -log(material_AttenuationColor + HALF_EPS) / max(HALF_EPS, material_AttenuationDistance);\n material.thickness = max(material_Thickness, 0.0001);\n #ifdef MATERIAL_HAS_THICKNESS_TEXTURE\n material.thickness *= texture2D( material_ThicknessTexture, v_uv).g;\n #endif\n #endif \n #endif\n}\n\n"; // eslint-disable-line
4837
-
4838
- var brdf = "\n#ifdef MATERIAL_ENABLE_SHEEN\n uniform sampler2D scene_PrefilteredDFG;\n#endif\n\nfloat F_Schlick(float f0, float f90, float dotLH) {\n\treturn f0 + (f90 - f0) * (pow(1.0 - dotLH, 5.0));\n}\n\nvec3 F_Schlick(vec3 f0, float f90, float dotLH ) {\n\n\t// Original approximation by Christophe Schlick '94\n\t// float fresnel = pow( 1.0 - dotLH, 5.0 );\n\n\t// Optimized variant (presented by Epic at SIGGRAPH '13)\n\t// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\n\treturn (f90 - f0 ) * fresnel + f0;\n\n}\n\n// Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2\n// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\nfloat G_GGX_SmithCorrelated(float alpha, float dotNL, float dotNV ) {\n\n\tfloat a2 = pow2( alpha );\n\n\t// dotNL and dotNV are explicitly swapped. This is not a mistake.\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\n\treturn 0.5 / max( gv + gl, EPSILON );\n\n}\n\n#ifdef MATERIAL_ENABLE_ANISOTROPY\n // Heitz 2014, \"Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs\"\n // Heitz http://jcgt.org/published/0003/02/03/paper.pdf\n float G_GGX_SmithCorrelated_Anisotropic(float at, float ab, float ToV, float BoV, float ToL, float BoL, float NoV, float NoL) {\n float lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV));\n float lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL));\n return 0.5 / max(lambdaV + lambdaL, EPSILON);\n }\n#endif\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (33)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney’s reparameterization\nfloat D_GGX(float alpha, float dotNH ) {\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1\n\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n\n}\n\n#ifdef MATERIAL_ENABLE_SHEEN\n // http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf\n float D_Charlie(float roughness, float dotNH) {\n float invAlpha = 1.0 / roughness;\n float cos2h = dotNH * dotNH;\n float sin2h = max(1.0 - cos2h, 0.0078125); // 2^(-14/2), so sin2h^2 > 0 in fp16\n return (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n }\n\n // Neubelt and Pettineo 2013, \"Crafting a Next-gen Material Pipeline for The Order: 1886\".\n float V_Neubelt(float NoV, float NoL) {\n return saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n }\n\n vec3 sheenBRDF(vec3 incidentDirection, Geometry geometry, vec3 sheenColor, float sheenRoughness) {\n vec3 halfDir = normalize(incidentDirection + geometry.viewDir);\n float dotNL = saturate(dot(geometry.normal, incidentDirection));\n float dotNH = saturate(dot(geometry.normal, halfDir));\n float D = D_Charlie(sheenRoughness, dotNH);\n float V = V_Neubelt(geometry.dotNV, dotNL);\n vec3 F = sheenColor;\n return D * V * F;\n }\n\n float prefilteredSheenDFG(float dotNV, float sheenRoughness) {\n #ifdef HAS_TEX_LOD\n return texture2DLodEXT(scene_PrefilteredDFG, vec2(dotNV, sheenRoughness), 0.0).b;\n #else\n return texture2D(scene_PrefilteredDFG, vec2(dotNV, sheenRoughness),0.0).b;\n #endif \n }\n#endif\n\n#ifdef MATERIAL_ENABLE_ANISOTROPY\n // GGX Distribution Anisotropic\n // https://blog.selfshadow.com/publications/s2012-shading-course/burley/s2012_pbs_disney_brdf_notes_v3.pdf Addenda\n float D_GGX_Anisotropic(float at, float ab, float ToH, float BoH, float NoH) {\n float a2 = at * ab;\n vec3 d = vec3(ab * ToH, at * BoH, a2 * NoH);\n float d2 = dot(d, d);\n float b2 = a2 / d2;\n return a2 * b2 * b2 * RECIPROCAL_PI;\n }\n#endif\n\nfloat DG_GGX(float alpha, float dotNV, float dotNL, float dotNH) {\n\tfloat D = D_GGX( alpha, dotNH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n return G * D;\n}\n\n#ifdef MATERIAL_ENABLE_ANISOTROPY\n float DG_GGX_anisotropic(vec3 h, vec3 l, Geometry geometry, float alpha, float dotNV, float dotNL, float dotNH) {\n vec3 t = geometry.anisotropicT;\n vec3 b = geometry.anisotropicB;\n vec3 v = geometry.viewDir;\n\n float dotTV = dot(t, v);\n float dotBV = dot(b, v);\n float dotTL = dot(t, l);\n float dotBL = dot(b, l);\n float dotTH = dot(t, h);\n float dotBH = dot(b, h);\n\n // Aniso parameter remapping\n // https://blog.selfshadow.com/publications/s2017-shading-course/imageworks/s2017_pbs_imageworks_slides_v2.pdf page 24\n float at = max(alpha * (1.0 + geometry.anisotropy), MIN_ROUGHNESS);\n float ab = max(alpha * (1.0 - geometry.anisotropy), MIN_ROUGHNESS);\n\n // specular anisotropic BRDF\n float D = D_GGX_Anisotropic(at, ab, dotTH, dotBH, dotNH);\n float G = G_GGX_SmithCorrelated_Anisotropic(at, ab, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL);\n\n return G * D;\n }\n#endif\n\n#ifdef MATERIAL_ENABLE_IRIDESCENCE\n vec3 iorToFresnel0(vec3 transmittedIOR, float incidentIOR) {\n return pow((transmittedIOR - incidentIOR) / (transmittedIOR + incidentIOR),vec3(2.0));\n } \n\n float iorToFresnel0(float transmittedIOR, float incidentIOR) {\n return pow((transmittedIOR - incidentIOR) / (transmittedIOR + incidentIOR),2.0);\n } \n\n // Assume air interface for top\n // Note: We don't handle the case fresnel0 == 1\n vec3 fresnelToIOR(vec3 f0){\n vec3 sqrtF0 = sqrt(f0);\n return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0);\n }\n\n // Fresnel equations for dielectric/dielectric interfaces.\n // Ref: https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html\n // Evaluation XYZ sensitivity curves in Fourier space\n vec3 evalSensitivity(float opd, vec3 shift){\n // Use Gaussian fits, given by 3 parameters: val, pos and var\n float phase = 2.0 * PI * opd * 1.0e-9;\n const vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13);\n const vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06);\n const vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09);\n vec3 xyz = val * sqrt(2.0 * PI * var) * cos(pos * phase + shift) * exp(-var * pow2(phase));\n xyz.x += 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift[0]) * exp(-4.5282e+09 * pow2(phase));\n xyz /= 1.0685e-7;\n // XYZ to RGB color space\n const mat3 XYZ_TO_RGB = mat3( 3.2404542, -0.9692660, 0.0556434,\n -1.5371385, 1.8760108, -0.2040259,\n -0.4985314, 0.0415560, 1.0572252);\n vec3 rgb = XYZ_TO_RGB * xyz;\n return rgb;\n }\n\n vec3 evalIridescenceSpecular(float outsideIOR, float dotNV, float thinIOR, vec3 baseF0, float baseF90, float iridescenceThickness){ \n vec3 iridescence = vec3(1.0);\n // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0\n float iridescenceIOR = mix( outsideIOR, thinIOR, smoothstep( 0.0, 0.03, iridescenceThickness ) );\n // Evaluate the cosTheta on the base layer (Snell law)\n float sinTheta2Sq = pow( outsideIOR / iridescenceIOR, 2.0) * (1.0 - pow( dotNV, 2.0));\n float cosTheta2Sq = 1.0 - sinTheta2Sq;\n // Handle total internal reflection\n if (cosTheta2Sq < 0.0) {\n return iridescence;\n }\n float cosTheta2 = sqrt(cosTheta2Sq);\n \n // First interface\n float f0 = iorToFresnel0(iridescenceIOR, outsideIOR);\n float reflectance = F_Schlick(f0, baseF90, dotNV);\n float t121 = 1.0 - reflectance;\n float phi12 = 0.0;\n // iridescenceIOR has limited greater than 1.0\n // if (iridescenceIOR < outsideIOR) {phi12 = PI;} \n float phi21 = PI - phi12;\n \n // Second interface\n vec3 baseIOR = fresnelToIOR(clamp(baseF0, 0.0, 0.9999)); // guard against 1.0\n vec3 r1 = iorToFresnel0(baseIOR, iridescenceIOR);\n vec3 r23 = F_Schlick(r1, baseF90, cosTheta2);\n vec3 phi23 =vec3(0.0);\n if (baseIOR[0] < iridescenceIOR) {phi23[0] = PI;}\n if (baseIOR[1] < iridescenceIOR) {phi23[1] = PI;}\n if (baseIOR[2] < iridescenceIOR) {phi23[2] = PI;}\n \n // Phase shift\n float opd = 2.0 * iridescenceIOR * iridescenceThickness * cosTheta2;\n vec3 phi = vec3(phi21) + phi23;\n \n // Compound terms\n vec3 r123 = clamp(reflectance * r23, 1e-5, 0.9999);\n vec3 sr123 = sqrt(r123);\n vec3 rs = pow2(t121) * r23 / (vec3(1.0) - r123);\n // Reflectance term for m = 0 (DC term amplitude)\n vec3 c0 = reflectance + rs;\n iridescence = c0;\n // Reflectance term for m > 0 (pairs of diracs)\n vec3 cm = rs - t121;\n for (int m = 1; m <= 2; ++m) {\n cm *= sr123;\n vec3 sm = 2.0 * evalSensitivity(float(m) * opd, float(m) * phi);\n iridescence += cm * sm;\n }\n return iridescence = max(iridescence, vec3(0.0)); \n }\n#endif\n\n// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility\nvec3 BRDF_Specular_GGX(vec3 incidentDirection, Geometry geometry, Material material, vec3 normal, vec3 specularColor, float roughness ) {\n\n\tfloat alpha = pow2( roughness ); // UE4's roughness\n\n\tvec3 halfDir = normalize( incidentDirection + geometry.viewDir );\n\n\tfloat dotNL = saturate( dot( normal, incidentDirection ) );\n\tfloat dotNV = saturate( dot( normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentDirection, halfDir ) );\n\n vec3 F = F_Schlick( specularColor, material.specularF90, dotLH );\n #ifdef MATERIAL_ENABLE_IRIDESCENCE\n F = mix(F, material.iridescenceSpecularColor, material.iridescenceFactor);\n #endif\n\n #ifdef MATERIAL_ENABLE_ANISOTROPY\n float GD = DG_GGX_anisotropic(halfDir, incidentDirection, geometry, alpha, dotNV, dotNL, dotNH);\n #else\n float GD = DG_GGX(alpha, dotNV, dotNL, dotNH);\n #endif\n\n return F * GD;\n}\n\nvec3 BRDF_Diffuse_Lambert(vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\n"; // eslint-disable-line
4839
-
4840
- var direct_irradiance_frag_define = "#include <ShadowFragmentDeclaration>\n\nvoid sheenLobe(Geometry geometry, Material material, vec3 incidentDirection, vec3 attenuationIrradiance, inout vec3 diffuseColor, inout vec3 specularColor){\n #ifdef MATERIAL_ENABLE_SHEEN\n diffuseColor *= material.sheenScaling;\n specularColor *= material.sheenScaling;\n\n specularColor += attenuationIrradiance * sheenBRDF(incidentDirection, geometry, material.sheenColor, material.sheenRoughness);\n #endif\n}\n\nvoid addDirectRadiance(vec3 incidentDirection, vec3 color, Geometry geometry, Material material, inout ReflectedLight reflectedLight) {\n float attenuation = 1.0;\n\n #ifdef MATERIAL_ENABLE_CLEAR_COAT\n float clearCoatDotNL = saturate( dot( geometry.clearCoatNormal, incidentDirection ) );\n vec3 clearCoatIrradiance = clearCoatDotNL * color;\n\n reflectedLight.directSpecular += material.clearCoat * clearCoatIrradiance * BRDF_Specular_GGX( incidentDirection, geometry, material, geometry.clearCoatNormal, vec3( 0.04 ), material.clearCoatRoughness );\n attenuation -= material.clearCoat * F_Schlick(0.04, 1.0, geometry.clearCoatDotNV);\n #endif\n\n float dotNL = saturate( dot( geometry.normal, incidentDirection ) );\n vec3 irradiance = dotNL * color * PI;\n\n reflectedLight.directSpecular += attenuation * irradiance * BRDF_Specular_GGX( incidentDirection, geometry, material, geometry.normal, material.specularF0, material.roughness) * material.energyCompensation;\n reflectedLight.directDiffuse += attenuation * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n // Sheen Lobe\n sheenLobe(geometry, material, incidentDirection, attenuation * irradiance, reflectedLight.directDiffuse, reflectedLight.directSpecular);\n\n}\n\n#ifdef SCENE_DIRECT_LIGHT_COUNT\n\n void addDirectionalDirectLightRadiance(DirectLight directionalLight, Geometry geometry, Material material, inout ReflectedLight reflectedLight) {\n vec3 color = directionalLight.color;\n vec3 direction = -directionalLight.direction;\n\n\t\taddDirectRadiance( direction, color, geometry, material, reflectedLight );\n\n }\n\n#endif\n\n#ifdef SCENE_POINT_LIGHT_COUNT\n\n\tvoid addPointDirectLightRadiance(PointLight pointLight, Geometry geometry, Material material, inout ReflectedLight reflectedLight) {\n\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tvec3 direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\n\t\tvec3 color = pointLight.color;\n\t\tcolor *= clamp(1.0 - pow(lightDistance/pointLight.distance, 4.0), 0.0, 1.0);\n\n\t\taddDirectRadiance( direction, color, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#ifdef SCENE_SPOT_LIGHT_COUNT\n\n\tvoid addSpotDirectLightRadiance(SpotLight spotLight, Geometry geometry, Material material, inout ReflectedLight reflectedLight) {\n\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tvec3 direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( direction, -spotLight.direction );\n\n\t\tfloat spotEffect = smoothstep( spotLight.penumbraCos, spotLight.angleCos, angleCos );\n\t\tfloat decayEffect = clamp(1.0 - pow(lightDistance/spotLight.distance, 4.0), 0.0, 1.0);\n\n\t\tvec3 color = spotLight.color;\n\t\tcolor *= spotEffect * decayEffect;\n\n\t\taddDirectRadiance( direction, color, geometry, material, reflectedLight );\n\n\t}\n\n\n#endif\n\nvoid addTotalDirectRadiance(Geometry geometry, Material material, inout ReflectedLight reflectedLight){\n float shadowAttenuation = 1.0;\n\n #ifdef SCENE_DIRECT_LIGHT_COUNT\n shadowAttenuation = 1.0;\n #ifdef SCENE_IS_CALCULATE_SHADOWS\n shadowAttenuation *= sampleShadowMap();\n #endif\n\n DirectLight directionalLight;\n for ( int i = 0; i < SCENE_DIRECT_LIGHT_COUNT; i ++ ) {\n // warning: use `continue` syntax may trigger flickering bug in safri 16.1.\n if(!isRendererCulledByLight(renderer_Layer.xy, scene_DirectLightCullingMask[i])){\n directionalLight.color = scene_DirectLightColor[i];\n #ifdef SCENE_IS_CALCULATE_SHADOWS\n if (i == 0) { // Sun light index is always 0\n directionalLight.color *= shadowAttenuation;\n }\n #endif\n directionalLight.direction = scene_DirectLightDirection[i];\n addDirectionalDirectLightRadiance( directionalLight, geometry, material, reflectedLight );\n }\n }\n\n #endif\n\n #ifdef SCENE_POINT_LIGHT_COUNT\n\n PointLight pointLight;\n\n for ( int i = 0; i < SCENE_POINT_LIGHT_COUNT; i ++ ) {\n if(!isRendererCulledByLight(renderer_Layer.xy, scene_PointLightCullingMask[i])){\n pointLight.color = scene_PointLightColor[i];\n pointLight.position = scene_PointLightPosition[i];\n pointLight.distance = scene_PointLightDistance[i];\n\n addPointDirectLightRadiance( pointLight, geometry, material, reflectedLight );\n } \n }\n\n #endif\n\n #ifdef SCENE_SPOT_LIGHT_COUNT\n\n SpotLight spotLight;\n\n for ( int i = 0; i < SCENE_SPOT_LIGHT_COUNT; i ++ ) {\n if(!isRendererCulledByLight(renderer_Layer.xy, scene_SpotLightCullingMask[i])){\n spotLight.color = scene_SpotLightColor[i];\n spotLight.position = scene_SpotLightPosition[i];\n spotLight.direction = scene_SpotLightDirection[i];\n spotLight.distance = scene_SpotLightDistance[i];\n spotLight.angleCos = scene_SpotLightAngleCos[i];\n spotLight.penumbraCos = scene_SpotLightPenumbraCos[i];\n\n addSpotDirectLightRadiance( spotLight, geometry, material, reflectedLight );\n } \n }\n\n #endif\n}"; // eslint-disable-line
4841
-
4842
- var ibl_frag_define = "// ------------------------Diffuse------------------------\n\n// sh need be pre-scaled in CPU.\nvec3 getLightProbeIrradiance(vec3 sh[9], vec3 normal){\n vec3 result = sh[0] +\n\n sh[1] * (normal.y) +\n sh[2] * (normal.z) +\n sh[3] * (normal.x) +\n\n sh[4] * (normal.y * normal.x) +\n sh[5] * (normal.y * normal.z) +\n sh[6] * (3.0 * normal.z * normal.z - 1.0) +\n sh[7] * (normal.z * normal.x) +\n sh[8] * (normal.x * normal.x - normal.y * normal.y);\n \n return max(result, vec3(0.0));\n\n}\n\n// ------------------------Specular------------------------\n\n// Returns raw DFG approximation coefficients (split-sum LUT approximation)\nvec2 envDFGApprox(float roughness, float dotNV) {\n const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n return vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\n\n// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\nvec3 envBRDFApprox(vec3 f0, float f90, float roughness, float dotNV ) {\n vec2 AB = envDFGApprox(roughness, dotNV);\n return f0 * AB.x + f90 * AB.y;\n}\n\n\nfloat getSpecularMIPLevel(float roughness, int maxMIPLevel ) {\n return roughness * float(maxMIPLevel);\n}\n\nvec3 getReflectedVector(Geometry geometry, vec3 n) {\n #ifdef MATERIAL_ENABLE_ANISOTROPY\n vec3 r = reflect(-geometry.viewDir, geometry.anisotropicN);\n #else\n vec3 r = reflect(-geometry.viewDir, n);\n #endif\n\n return r;\n}\n\nvec3 getLightProbeRadiance(Geometry geometry, vec3 normal, float roughness, int maxMIPLevel, float specularIntensity) {\n\n #ifndef SCENE_USE_SPECULAR_ENV\n return vec3(0);\n #else\n vec3 reflectVec = getReflectedVector(geometry, normal);\n\n float specularMIPLevel = getSpecularMIPLevel(roughness, maxMIPLevel );\n\n #ifdef HAS_TEX_LOD\n vec4 envMapColor = textureCubeLodEXT( scene_EnvSpecularSampler, reflectVec, specularMIPLevel );\n #else\n vec4 envMapColor = textureCube( scene_EnvSpecularSampler, reflectVec, specularMIPLevel );\n #endif\n\n #ifdef ENGINE_NO_SRGB\n envMapColor = sRGBToLinear(envMapColor);\n #endif\n \n return envMapColor.rgb * specularIntensity;\n\n #endif\n\n}\n\n\nvoid evaluateSheenIBL(Geometry geometry, Material material, float radianceAttenuation, inout vec3 diffuseColor, inout vec3 specularColor){\n #ifdef MATERIAL_ENABLE_SHEEN\n diffuseColor *= material.sheenScaling;\n specularColor *= material.sheenScaling;\n\n vec3 reflectance = material.specularAO * radianceAttenuation * material.approxIBLSheenDG * material.sheenColor;\n specularColor += reflectance;\n #endif\n}"; // eslint-disable-line
4843
-
4844
- var pbr_frag = "Geometry geometry;\nMaterial material;\nReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\ninitGeometry(geometry, gl_FrontFacing);\ninitMaterial(material, geometry);\n\n// Direct Light\naddTotalDirectRadiance(geometry, material, reflectedLight);\n\n// IBL diffuse\n#ifdef SCENE_USE_SH\n vec3 irradiance = getLightProbeIrradiance(scene_EnvSH, geometry.normal);\n irradiance *= scene_EnvMapLight.diffuseIntensity;\n#else\n vec3 irradiance = scene_EnvMapLight.diffuse * scene_EnvMapLight.diffuseIntensity;\n irradiance *= PI;\n#endif\n\nreflectedLight.indirectDiffuse += material.diffuseAO * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n// IBL specular\nvec3 radiance = getLightProbeRadiance(geometry, geometry.normal, material.roughness, int(scene_EnvMapLight.mipMapLevel), scene_EnvMapLight.specularIntensity);\nfloat radianceAttenuation = 1.0;\n\n// IBL Clear Coat\n#ifdef MATERIAL_ENABLE_CLEAR_COAT\n vec3 clearCoatRadiance = getLightProbeRadiance( geometry, geometry.clearCoatNormal, material.clearCoatRoughness, int(scene_EnvMapLight.mipMapLevel), scene_EnvMapLight.specularIntensity );\n\n reflectedLight.indirectSpecular += material.specularAO * clearCoatRadiance * material.clearCoat * envBRDFApprox(vec3( 0.04 ), 1.0, material.clearCoatRoughness, geometry.clearCoatDotNV);\n radianceAttenuation -= material.clearCoat * F_Schlick(0.04, 1.0, geometry.clearCoatDotNV);\n#endif\n\nreflectedLight.indirectSpecular += material.specularAO * radianceAttenuation * radiance * envBRDFApprox(material.resolvedSpecularF0, material.specularF90, material.roughness, geometry.dotNV) * material.energyCompensation;\n\n\n// IBL Sheen\nevaluateSheenIBL(geometry, material, radianceAttenuation, reflectedLight.indirectDiffuse, reflectedLight.indirectSpecular);\n\n\n// Final color\nvec3 totalDiffuseColor = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\nvec3 totalSpecularColor = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\n#ifdef MATERIAL_ENABLE_TRANSMISSION \n vec3 refractionTransmitted = evaluateTransmission(geometry, material);\n totalDiffuseColor = mix(totalDiffuseColor, refractionTransmitted, material.transmission);\n#endif\n\nvec4 finalColor = vec4(totalDiffuseColor + totalSpecularColor, material.opacity);\n\n\n// Emissive\nvec3 emissiveRadiance = material_EmissiveColor;\n#ifdef MATERIAL_HAS_EMISSIVETEXTURE\n emissiveRadiance *= texture2DSRGB(material_EmissiveTexture, v_uv).rgb;\n#endif\n\nfinalColor.rgb += emissiveRadiance;\n\n\ngl_FragColor = finalColor;\n"; // eslint-disable-line
4845
-
4846
- var btdf = "#include <refraction>\n\n#ifdef MATERIAL_ENABLE_TRANSMISSION \n uniform sampler2D camera_OpaqueTexture;\n vec3 evaluateTransmission(Geometry geometry, Material material) {\n RefractionModelResult ray;\n #if REFRACTION_MODE == 0 \n // RefractionMode.Sphere\n refractionModelSphere(-geometry.viewDir, geometry.position, geometry.normal, material.IOR, material.thickness, ray);\n #elif REFRACTION_MODE == 1\n // RefractionMode.Planar\n refractionModelPlanar(-geometry.viewDir, geometry.position, geometry.normal, material.IOR, material.thickness, ray);\n #endif\n\n vec3 refractedRayExit = ray.positionExit;\n\n // We calculate the screen space position of the refracted point\n vec4 samplingPositionNDC = camera_ProjMat * camera_ViewMat * vec4( refractedRayExit, 1.0 );\n vec2 refractionCoords = (samplingPositionNDC.xy / samplingPositionNDC.w) * 0.5 + 0.5;\n\n // Sample the opaque texture to get the transmitted light\n vec3 refractionTransmitted = texture2DSRGB(camera_OpaqueTexture, refractionCoords).rgb;\n refractionTransmitted *= material.diffuseColor;\n \n // Use specularFGD as an approximation of the fresnel effect\n // https://blog.selfshadow.com/publications/s2017-shading-course/imageworks/s2017_pbs_imageworks_slides_v2.pdf\n refractionTransmitted *= (1.0 - material.envSpecularDFG);\n\n #ifdef MATERIAL_HAS_THICKNESS\n // Absorption coefficient from Disney: http://blog.selfshadow.com/publications/s2015-shading-course/burley/s2015_pbs_disney_bsdf_notes.pdf\n vec3 transmittance = min(vec3(1.0), exp(-material.absorptionCoefficient * ray.transmissionLength));\n refractionTransmitted *= transmittance;\n #endif\n \n return refractionTransmitted;\n }\n#endif"; // eslint-disable-line
4847
-
4848
- var refraction = "#ifdef MATERIAL_ENABLE_TRANSMISSION \n\tstruct RefractionModelResult {\n\t float transmissionLength; // length of the transmission during refraction through the shape\n\t vec3 positionExit; // out ray position\n\t // vec3 directionExit; // out ray direction\n\t};\n\n\t//https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@15.0/manual/refraction-models.html\n\t void refractionModelSphere(vec3 V, vec3 positionWS, vec3 normalWS, float ior, float thickness, out RefractionModelResult ray) {\n\t // Refracted ray\n\t vec3 R1 = refract(V, normalWS, 1.0 / ior);\n\t // Center of the tangent sphere\n\t // vec3 C = positionWS - normalWS * thickness * 0.5;\n\n\t // Second refraction (tangent sphere out)\n\t float dist = dot(-normalWS, R1) * thickness;\n\t // Out hit point in the tangent sphere\n\t vec3 P1 = positionWS + R1 * dist;\n\t // Out normal\n\t // vec3 N1 = safeNormalize(C - P1);\n\t // Out refracted ray\n\t // vec3 R2 = refract(R1, N1, ior);\n\n\t ray.transmissionLength = dist;\n\t ray.positionExit = P1;\n\t // ray.directionExit = R2; \n\t}\n\n\tvoid refractionModelPlanar(vec3 V, vec3 positionWS, vec3 normalWS, float ior, float thickness, out RefractionModelResult ray) {\n\t // Refracted ray\n\t vec3 R = refract(V, normalWS, 1.0 / ior);\n\t // Optical depth within the thin plane\n\t float dist = thickness / max(dot(-normalWS, R), 1e-5f);\n\n\t ray.transmissionLength = dist;\n\t ray.positionExit = vec3(positionWS + R * dist);\n\t // ray.directionExit = V;\n\t}\n\n#endif"; // eslint-disable-line
4849
-
4850
- var PBRShaderLib = {
4851
- pbr_frag_define: pbr_frag_define,
4852
- pbr_helper: pbr_helper,
4853
- brdf: brdf,
4854
- direct_irradiance_frag_define: direct_irradiance_frag_define,
4855
- ibl_frag_define: ibl_frag_define,
4856
- pbr_frag: pbr_frag,
4857
- btdf: btdf,
4858
- refraction: refraction
4859
- };
4860
-
4861
- var ShadowCoord = "\nuniform mat4 scene_ShadowMatrices[SCENE_SHADOW_CASCADED_COUNT + 1];\nuniform vec4 scene_ShadowSplitSpheres[4];\n\nmediump int computeCascadeIndex(vec3 positionWS) {\n vec3 fromCenter0 = positionWS - scene_ShadowSplitSpheres[0].xyz;\n vec3 fromCenter1 = positionWS - scene_ShadowSplitSpheres[1].xyz;\n vec3 fromCenter2 = positionWS - scene_ShadowSplitSpheres[2].xyz;\n vec3 fromCenter3 = positionWS - scene_ShadowSplitSpheres[3].xyz;\n\n mediump vec4 comparison = vec4(\n dot(fromCenter0, fromCenter0) < scene_ShadowSplitSpheres[0].w,\n dot(fromCenter1, fromCenter1) < scene_ShadowSplitSpheres[1].w,\n dot(fromCenter2, fromCenter2) < scene_ShadowSplitSpheres[2].w,\n dot(fromCenter3, fromCenter3) < scene_ShadowSplitSpheres[3].w);\n comparison.yzw = clamp(comparison.yzw - comparison.xyz,0.0,1.0);//keep the nearest\n mediump vec4 indexCoefficient = vec4(4.0,3.0,2.0,1.0);\n mediump int index = 4 - int(dot(comparison, indexCoefficient));\n return index;\n}\n\nvec3 getShadowCoord() {\n #if SCENE_SHADOW_CASCADED_COUNT == 1\n mediump int cascadeIndex = 0;\n #else\n mediump int cascadeIndex = computeCascadeIndex(v_pos);\n #endif\n\n #ifdef GRAPHICS_API_WEBGL2\n mat4 shadowMatrix = scene_ShadowMatrices[cascadeIndex];\n #else\n mat4 shadowMatrix;\n #if SCENE_SHADOW_CASCADED_COUNT == 4\n if (cascadeIndex == 0) {\n shadowMatrix = scene_ShadowMatrices[0];\n } else if (cascadeIndex == 1) {\n shadowMatrix = scene_ShadowMatrices[1];\n } else if (cascadeIndex == 2) {\n shadowMatrix = scene_ShadowMatrices[2];\n } else if (cascadeIndex == 3) {\n shadowMatrix = scene_ShadowMatrices[3];\n } else {\n shadowMatrix = scene_ShadowMatrices[4];\n }\n #endif\n #if SCENE_SHADOW_CASCADED_COUNT == 2\n if (cascadeIndex == 0) {\n shadowMatrix = scene_ShadowMatrices[0];\n } else if (cascadeIndex == 1) {\n shadowMatrix = scene_ShadowMatrices[1];\n } else {\n shadowMatrix = scene_ShadowMatrices[2];\n } \n #endif\n #if SCENE_SHADOW_CASCADED_COUNT == 1\n if (cascadeIndex == 0) {\n shadowMatrix = scene_ShadowMatrices[0];\n } else {\n shadowMatrix = scene_ShadowMatrices[1];\n } \n #endif\n #endif\n\n vec4 shadowCoord = shadowMatrix * vec4(v_pos, 1.0);\n return shadowCoord.xyz;\n}\n"; // eslint-disable-line
4862
-
4863
- var ShadowFragmentDeclaration = "#if defined(SCENE_SHADOW_TYPE) && defined(RENDERER_IS_RECEIVE_SHADOWS)\n #define SCENE_IS_CALCULATE_SHADOWS\n#endif\n\n#ifdef SCENE_IS_CALCULATE_SHADOWS\n #if SCENE_SHADOW_CASCADED_COUNT == 1\n varying vec3 v_shadowCoord;\n #else\n #include <ShadowCoord>\n #endif\n \n // intensity, null, fadeScale, fadeBias\n uniform vec4 scene_ShadowInfo;\n uniform vec4 scene_ShadowMapSize;\n\n #ifdef GRAPHICS_API_WEBGL2\n uniform mediump sampler2DShadow scene_ShadowMap;\n #define SAMPLE_TEXTURE2D_SHADOW(textureName, coord3) textureLod(textureName, coord3 , 0.0)\n #define TEXTURE2D_SHADOW_PARAM(shadowMap) mediump sampler2DShadow shadowMap\n #else\n uniform sampler2D scene_ShadowMap;\n #ifdef ENGINE_NO_DEPTH_TEXTURE\n const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0*256.0), 1.0/(256.0*256.0*256.0));\n /**\n * Unpack depth value.\n */\n float unpack(const in vec4 rgbaDepth) {\n return dot(rgbaDepth, bitShift);\n }\n #define SAMPLE_TEXTURE2D_SHADOW(textureName, coord3) (unpack(texture2D(textureName, coord3.xy)) < coord3.z ? 0.0 : 1.0)\n #else\n #define SAMPLE_TEXTURE2D_SHADOW(textureName, coord3) (texture2D(textureName, coord3.xy).r < coord3.z ? 0.0 : 1.0)\n #endif\n #define TEXTURE2D_SHADOW_PARAM(shadowMap) mediump sampler2D shadowMap\n #endif\n\n #if SCENE_SHADOW_TYPE == 2\n float sampleShadowMapFiltered4(TEXTURE2D_SHADOW_PARAM(shadowMap), vec3 shadowCoord, vec4 shadowMapSize) {\n float attenuation;\n vec4 attenuation4;\n vec2 offset=shadowMapSize.xy/2.0;\n vec3 shadowCoord0=shadowCoord + vec3(-offset,0.0);\n vec3 shadowCoord1=shadowCoord + vec3(offset.x,-offset.y,0.0);\n vec3 shadowCoord2=shadowCoord + vec3(-offset.x,offset.y,0.0);\n vec3 shadowCoord3=shadowCoord + vec3(offset,0.0);\n attenuation4.x = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord0);\n attenuation4.y = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord1);\n attenuation4.z = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord2);\n attenuation4.w = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord3);\n attenuation = dot(attenuation4, vec4(0.25));\n return attenuation;\n }\n #endif\n\n #if SCENE_SHADOW_TYPE == 3\n #include <shadow_sample_tent>\n\n float sampleShadowMapFiltered9(TEXTURE2D_SHADOW_PARAM(shadowMap), vec3 shadowCoord, vec4 shadowmapSize) {\n float attenuation;\n float fetchesWeights[9];\n vec2 fetchesUV[9];\n sampleShadowComputeSamplesTent5x5(shadowmapSize, shadowCoord.xy, fetchesWeights, fetchesUV);\n attenuation = fetchesWeights[0] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[0].xy, shadowCoord.z));\n attenuation += fetchesWeights[1] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[1].xy, shadowCoord.z));\n attenuation += fetchesWeights[2] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[2].xy, shadowCoord.z));\n attenuation += fetchesWeights[3] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[3].xy, shadowCoord.z));\n attenuation += fetchesWeights[4] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[4].xy, shadowCoord.z));\n attenuation += fetchesWeights[5] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[5].xy, shadowCoord.z));\n attenuation += fetchesWeights[6] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[6].xy, shadowCoord.z));\n attenuation += fetchesWeights[7] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[7].xy, shadowCoord.z));\n attenuation += fetchesWeights[8] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[8].xy, shadowCoord.z));\n return attenuation;\n }\n #endif\n\n\n float getShadowFade(vec3 positionWS){\n vec3 camToPixel = positionWS - camera_Position;\n float distanceCamToPixel2 = dot(camToPixel, camToPixel);\n return saturate( distanceCamToPixel2 * scene_ShadowInfo.z + scene_ShadowInfo.w );\n }\n\n float sampleShadowMap() {\n #if SCENE_SHADOW_CASCADED_COUNT == 1\n vec3 shadowCoord = v_shadowCoord;\n #else\n vec3 shadowCoord = getShadowCoord();\n #endif\n \n float attenuation = 1.0;\n if(shadowCoord.z > 0.0 && shadowCoord.z < 1.0) {\n #if SCENE_SHADOW_TYPE == 1\n attenuation = SAMPLE_TEXTURE2D_SHADOW(scene_ShadowMap, shadowCoord);\n #endif\n\n #if SCENE_SHADOW_TYPE == 2\n attenuation = sampleShadowMapFiltered4(scene_ShadowMap, shadowCoord, scene_ShadowMapSize);\n #endif\n\n #if SCENE_SHADOW_TYPE == 3\n attenuation = sampleShadowMapFiltered9(scene_ShadowMap, shadowCoord, scene_ShadowMapSize);\n #endif\n\n float shadowFade = getShadowFade(v_pos);\n attenuation = mix(1.0, mix(attenuation, 1.0, shadowFade), scene_ShadowInfo.x);\n }\n return attenuation;\n }\n#endif"; // eslint-disable-line
4864
-
4865
- var shadow_sample_tent = "// ------------------------------------------------------------------\n// PCF Filtering Tent Functions\n// ------------------------------------------------------------------\n\n// Assuming a isoceles right angled triangle of height \"triangleHeight\" (as drawn below).\n// This function return the area of the triangle above the first texel(in Y the first texel).\n//\n// |\\ <-- 45 degree slop isosceles right angled triangle\n// | \\\n// ---- <-- length of this side is \"triangleHeight\"\n// _ _ _ _ <-- texels\nfloat sampleShadowGetIRTriangleTexelArea(float triangleHeight) {\n return triangleHeight - 0.5;\n}\n\n// Assuming a isoceles triangle of 1.5 texels height and 3 texels wide lying on 4 texels.\n// This function return the area of the triangle above each of those texels.\n// | <-- offset from -0.5 to 0.5, 0 meaning triangle is exactly in the center\n// / \\ <-- 45 degree slop isosceles triangle (ie tent projected in 2D)\n// / \\\n// _ _ _ _ <-- texels\n// X Y Z W <-- result indices (in computedArea.xyzw and computedAreaUncut.xyzw)\n// Top point at (right,top) in a texel,left bottom point at (middle,middle) in a texel,right bottom point at (middle,middle) in a texel.\nvoid sampleShadowGetTexelAreasTent3x3(float offset, out vec4 computedArea, out vec4 computedAreaUncut) {\n // Compute the exterior areas,a and h is same.\n float a = offset + 0.5;\n float offsetSquaredHalved = a * a * 0.5;\n computedAreaUncut.x = computedArea.x = offsetSquaredHalved - offset;\n computedAreaUncut.w = computedArea.w = offsetSquaredHalved;\n\n // Compute the middle areas\n // For Y : We find the area in Y of as if the left section of the isoceles triangle would\n // intersect the axis between Y and Z (ie where offset = 0).\n computedAreaUncut.y = sampleShadowGetIRTriangleTexelArea(1.5 - offset);\n // This area is superior to the one we are looking for if (offset < 0) thus we need to\n // subtract the area of the triangle defined by (0,1.5-offset), (0,1.5+offset), (-offset,1.5).\n float clampedOffsetLeft = min(offset,0.0);\n float areaOfSmallLeftTriangle = clampedOffsetLeft * clampedOffsetLeft;\n computedArea.y = computedAreaUncut.y - areaOfSmallLeftTriangle;\n\n // We do the same for the Z but with the right part of the isoceles triangle\n computedAreaUncut.z = sampleShadowGetIRTriangleTexelArea(1.5 + offset);\n float clampedOffsetRight = max(offset,0.0);\n float areaOfSmallRightTriangle = clampedOffsetRight * clampedOffsetRight;\n computedArea.z = computedAreaUncut.z - areaOfSmallRightTriangle;\n}\n\n// Assuming a isoceles triangle of 2.5 texel height and 5 texels wide lying on 6 texels.\n// This function return the weight of each texels area relative to the full triangle area.\n// / \\\n// _ _ _ _ _ _ <-- texels\n// 0 1 2 3 4 5 <-- computed area indices (in texelsWeights[])\n// Top point at (right,top) in a texel,left bottom point at (middle,middle) in a texel,right bottom point at (middle,middle) in a texel.\nvoid sampleShadowGetTexelWeightsTent5x5(float offset, out vec3 texelsWeightsA, out vec3 texelsWeightsB) {\n vec4 areaFrom3texelTriangle;\n vec4 areaUncutFrom3texelTriangle;\n sampleShadowGetTexelAreasTent3x3(offset, areaFrom3texelTriangle, areaUncutFrom3texelTriangle);\n\n // Triangle slope is 45 degree thus we can almost reuse the result of the 3 texel wide computation.\n // the 5 texel wide triangle can be seen as the 3 texel wide one but shifted up by one unit/texel.\n // 0.16 is 1/(the triangle area)\n texelsWeightsA.x = 0.16 * (areaFrom3texelTriangle.x);\n texelsWeightsA.y = 0.16 * (areaUncutFrom3texelTriangle.y);\n texelsWeightsA.z = 0.16 * (areaFrom3texelTriangle.y + 1.0);\n texelsWeightsB.x = 0.16 * (areaFrom3texelTriangle.z + 1.0);\n texelsWeightsB.y = 0.16 * (areaUncutFrom3texelTriangle.z);\n texelsWeightsB.z = 0.16 * (areaFrom3texelTriangle.w);\n}\n\n// 5x5 Tent filter (45 degree sloped triangles in U and V)\nvoid sampleShadowComputeSamplesTent5x5(vec4 shadowMapTextureTexelSize, vec2 coord, out float fetchesWeights[9], out vec2 fetchesUV[9])\n{\n // tent base is 5x5 base thus covering from 25 to 36 texels, thus we need 9 bilinear PCF fetches\n vec2 tentCenterInTexelSpace = coord.xy * shadowMapTextureTexelSize.zw;\n vec2 centerOfFetchesInTexelSpace = floor(tentCenterInTexelSpace + 0.5);\n vec2 offsetFromTentCenterToCenterOfFetches = tentCenterInTexelSpace - centerOfFetchesInTexelSpace;\n\n // find the weight of each texel based on the area of a 45 degree slop tent above each of them.\n vec3 texelsWeightsUA, texelsWeightsUB;\n vec3 texelsWeightsVA, texelsWeightsVB;\n sampleShadowGetTexelWeightsTent5x5(offsetFromTentCenterToCenterOfFetches.x, texelsWeightsUA, texelsWeightsUB);\n sampleShadowGetTexelWeightsTent5x5(offsetFromTentCenterToCenterOfFetches.y, texelsWeightsVA, texelsWeightsVB);\n\n // each fetch will cover a group of 2x2 texels, the weight of each group is the sum of the weights of the texels\n vec3 fetchesWeightsU = vec3(texelsWeightsUA.xz, texelsWeightsUB.y) + vec3(texelsWeightsUA.y, texelsWeightsUB.xz);\n vec3 fetchesWeightsV = vec3(texelsWeightsVA.xz, texelsWeightsVB.y) + vec3(texelsWeightsVA.y, texelsWeightsVB.xz);\n\n // move the PCF bilinear fetches to respect texels weights\n vec3 fetchesOffsetsU = vec3(texelsWeightsUA.y, texelsWeightsUB.xz) / fetchesWeightsU.xyz + vec3(-2.5,-0.5,1.5);\n vec3 fetchesOffsetsV = vec3(texelsWeightsVA.y, texelsWeightsVB.xz) / fetchesWeightsV.xyz + vec3(-2.5,-0.5,1.5);\n fetchesOffsetsU *= shadowMapTextureTexelSize.xxx;\n fetchesOffsetsV *= shadowMapTextureTexelSize.yyy;\n\n vec2 bilinearFetchOrigin = centerOfFetchesInTexelSpace * shadowMapTextureTexelSize.xy;\n fetchesUV[0] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.x);\n fetchesUV[1] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.x);\n fetchesUV[2] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.x);\n fetchesUV[3] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.y);\n fetchesUV[4] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.y);\n fetchesUV[5] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.y);\n fetchesUV[6] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.z);\n fetchesUV[7] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.z);\n fetchesUV[8] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.z);\n\n fetchesWeights[0] = fetchesWeightsU.x * fetchesWeightsV.x;\n fetchesWeights[1] = fetchesWeightsU.y * fetchesWeightsV.x;\n fetchesWeights[2] = fetchesWeightsU.z * fetchesWeightsV.x;\n fetchesWeights[3] = fetchesWeightsU.x * fetchesWeightsV.y;\n fetchesWeights[4] = fetchesWeightsU.y * fetchesWeightsV.y;\n fetchesWeights[5] = fetchesWeightsU.z * fetchesWeightsV.y;\n fetchesWeights[6] = fetchesWeightsU.x * fetchesWeightsV.z;\n fetchesWeights[7] = fetchesWeightsU.y * fetchesWeightsV.z;\n fetchesWeights[8] = fetchesWeightsU.z * fetchesWeightsV.z;\n}"; // eslint-disable-line
4866
-
4867
- var ShadowVertexDeclaration = "#if defined(SCENE_SHADOW_TYPE) && defined(RENDERER_IS_RECEIVE_SHADOWS)\n #define SCENE_IS_CALCULATE_SHADOWS\n#endif\n\n#ifdef SCENE_IS_CALCULATE_SHADOWS\n #if SCENE_SHADOW_CASCADED_COUNT==1\n #include <ShadowCoord>\n varying vec3 v_shadowCoord;\n #endif\n#endif"; // eslint-disable-line
4868
-
4869
- var ShadowVertex = "#ifdef SCENE_IS_CALCULATE_SHADOWS\n #if SCENE_SHADOW_CASCADED_COUNT == 1\n v_shadowCoord = getShadowCoord();\n #endif\n#endif"; // eslint-disable-line
4870
-
4871
- var ShadowLib = {
4872
- ShadowCoord: ShadowCoord,
4873
- ShadowFragmentDeclaration: ShadowFragmentDeclaration,
4874
- shadow_sample_tent: shadow_sample_tent,
4875
- ShadowVertexDeclaration: ShadowVertexDeclaration,
4876
- ShadowVertex: ShadowVertex
4877
- };
4878
-
4879
- var particle_common = "vec3 rotationByQuaternions(in vec3 v, in vec4 q) {\n return v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v);\n}\n\nvec4 quaternionConjugate(in vec4 q) {\n return vec4(-q.xyz, q.w);\n}\n\nvec3 rotationByEuler(in vec3 vector, in vec3 rot) {\n float halfRoll = rot.z * 0.5;\n float halfPitch = rot.x * 0.5;\n float halfYaw = rot.y * 0.5;\n\n float sinRoll = sin(halfRoll);\n float cosRoll = cos(halfRoll);\n float sinPitch = sin(halfPitch);\n float cosPitch = cos(halfPitch);\n float sinYaw = sin(halfYaw);\n float cosYaw = cos(halfYaw);\n\n float cosYawPitch = cosYaw * cosPitch;\n float sinYawPitch = sinYaw * sinPitch;\n\n float quaX = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);\n float quaY = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);\n float quaZ = (cosYawPitch * sinRoll) - (sinYawPitch * cosRoll);\n float quaW = (cosYawPitch * cosRoll) + (sinYawPitch * sinRoll);\n\n return rotationByQuaternions(vector, vec4(quaX, quaY, quaZ, quaW));\n}\n\n// Assume axis is normalized\nvec3 rotationByAxis(in vec3 vector, in vec3 axis, in float angle) {\n float halfAngle = angle * 0.5;\n float s = sin(halfAngle);\n\n return rotationByQuaternions(vector, vec4(axis * s, cos(halfAngle)));\n}\n\n\nfloat evaluateParticleCurve(in vec2 keys[4], in float normalizedAge) {\n float value;\n for (int i = 1; i < 4; i++) {\n vec2 key = keys[i];\n float time = key.x;\n if (time >= normalizedAge) {\n vec2 lastKey = keys[i - 1];\n float lastTime = lastKey.x;\n float age = (normalizedAge - lastTime) / (time - lastTime);\n value = mix(lastKey.y, key.y, age);\n break;\n }\n }\n return value;\n}\n\nfloat evaluateParticleCurveCumulative(in vec2 keys[4], in float normalizedAge, out float currentValue){\n float cumulativeValue = 0.0;\n for (int i = 1; i < 4; i++){\n\t vec2 key = keys[i];\n\t float time = key.x;\n\t vec2 lastKey = keys[i - 1];\n\t float lastValue = lastKey.y;\n\n\t if (time >= normalizedAge){\n\t\t float lastTime = lastKey.x;\n float offsetTime = normalizedAge - lastTime;\n\t\t float age = offsetTime / (time - lastTime);\n currentValue = mix(lastValue, key.y, age);\n\t\t cumulativeValue += (lastValue + currentValue) * 0.5 * offsetTime;\n\t\t break;\n\t\t}\n\t else{\n\t\t cumulativeValue += (lastValue + key.y) * 0.5 * (time - lastKey.x);\n\t\t}\n\t}\n return cumulativeValue;\n}\n\nvec4 evaluateParticleGradient(in vec4 colorKeys[4], in float colorMaxTime, in vec2 alphaKeys[4], in float alphaMaxTime, in float t) {\n vec4 value;\n\n float alphaT = min(t, alphaMaxTime);\n for (int i = 0; i < 4; i++) {\n vec2 key = alphaKeys[i];\n if (alphaT <= key.x) {\n if (i == 0) {\n value.a = alphaKeys[0].y;\n } else {\n vec2 lastKey = alphaKeys[i - 1];\n float age = (alphaT - lastKey.x) / (key.x - lastKey.x);\n value.a = mix(lastKey.y, key.y, age);\n }\n break;\n }\n }\n\n float colorT = min(t, colorMaxTime);\n for (int i = 0; i < 4; i++) {\n vec4 key = colorKeys[i];\n if (colorT <= key.x) {\n if (i == 0) {\n value.rgb = colorKeys[0].yzw;\n } else {\n vec4 lastKey = colorKeys[i - 1];\n float age = (colorT - lastKey.x) / (key.x - lastKey.x);\n value.rgb = mix(lastKey.yzw, key.yzw, age);\n }\n break;\n }\n }\n\n return value;\n}"; // eslint-disable-line
4880
-
4881
- var velocity_over_lifetime_module = "#if defined(RENDERER_VOL_CONSTANT_MODE) || defined(RENDERER_VOL_CURVE_MODE)\n #define _VOL_MODULE_ENABLED\n#endif\n\n#ifdef _VOL_MODULE_ENABLED\n uniform int renderer_VOLSpace;\n\n #ifdef RENDERER_VOL_CONSTANT_MODE\n uniform vec3 renderer_VOLMaxConst;\n\n #ifdef RENDERER_VOL_IS_RANDOM_TWO\n uniform vec3 renderer_VOLMinConst;\n #endif\n #endif\n\n #ifdef RENDERER_VOL_CURVE_MODE\n uniform vec2 renderer_VOLMaxGradientX[4]; // x:time y:value\n uniform vec2 renderer_VOLMaxGradientY[4]; // x:time y:value\n uniform vec2 renderer_VOLMaxGradientZ[4]; // x:time y:value\n\n #ifdef RENDERER_VOL_IS_RANDOM_TWO\n uniform vec2 renderer_VOLMinGradientX[4]; // x:time y:value\n uniform vec2 renderer_VOLMinGradientY[4]; // x:time y:value\n uniform vec2 renderer_VOLMinGradientZ[4]; // x:time y:value\n #endif\n #endif\n\n\n vec3 computeVelocityPositionOffset(in float normalizedAge, in float age, out vec3 currentVelocity) {\n vec3 velocityPosition;\n\n #ifdef RENDERER_VOL_CONSTANT_MODE\n currentVelocity = renderer_VOLMaxConst;\n #ifdef RENDERER_VOL_IS_RANDOM_TWO\n currentVelocity = mix(renderer_VOLMinConst, currentVelocity, a_Random1.yzw);\n #endif\n\n velocityPosition = currentVelocity * age;\n #endif\n\n #ifdef RENDERER_VOL_CURVE_MODE\n velocityPosition = vec3(\n evaluateParticleCurveCumulative(renderer_VOLMaxGradientX, normalizedAge, currentVelocity.x),\n evaluateParticleCurveCumulative(renderer_VOLMaxGradientY, normalizedAge, currentVelocity.y),\n evaluateParticleCurveCumulative(renderer_VOLMaxGradientZ, normalizedAge, currentVelocity.z));\n\n #ifdef RENDERER_VOL_IS_RANDOM_TWO\n vec3 minCurrentVelocity;\n vec3 minVelocityPosition = vec3(\n evaluateParticleCurveCumulative(renderer_VOLMinGradientX, normalizedAge, minCurrentVelocity.x),\n evaluateParticleCurveCumulative(renderer_VOLMinGradientY, normalizedAge, minCurrentVelocity.y),\n evaluateParticleCurveCumulative(renderer_VOLMinGradientZ, normalizedAge, minCurrentVelocity.z));\n\n currentVelocity = mix(minCurrentVelocity, currentVelocity, a_Random1.yzw);\n velocityPosition = mix(minVelocityPosition, velocityPosition, a_Random1.yzw);\n #endif\n\n velocityPosition *= vec3(a_ShapePositionStartLifeTime.w);\n #endif\n return velocityPosition;\n }\n#endif\n"; // eslint-disable-line
4882
-
4883
- var rotation_over_lifetime_module = "#if defined(RENDERER_ROL_CONSTANT_MODE) || defined(RENDERER_ROL_CURVE_MODE)\n #ifdef RENDERER_ROL_CURVE_MODE\n uniform vec2 renderer_ROLMaxCurveZ[4];\n #ifdef RENDERER_ROL_IS_SEPARATE\n uniform vec2 renderer_ROLMaxCurveX[4];\n uniform vec2 renderer_ROLMaxCurveY[4];\n #endif\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n uniform vec2 renderer_ROLMinCurveZ[4];\n #ifdef RENDERER_ROL_IS_SEPARATE\n uniform vec2 renderer_ROLMinCurveX[4];\n uniform vec2 renderer_ROLMinCurveY[4];\n #endif\n #endif\n #else\n uniform vec3 renderer_ROLMaxConst;\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n uniform vec3 renderer_ROLMinConst;\n #endif\n #endif\n#endif\n\nfloat computeParticleRotationFloat(in float rotation, in float age, in float normalizedAge) {\n #if defined(RENDERER_ROL_CONSTANT_MODE) || defined(RENDERER_ROL_CURVE_MODE)\n #ifdef RENDERER_ROL_CURVE_MODE\n float currentValue;\n float lifeRotation = evaluateParticleCurveCumulative(renderer_ROLMaxCurveZ, normalizedAge, currentValue);\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n lifeRotation = mix(evaluateParticleCurveCumulative(renderer_ROLMinCurveZ, normalizedAge, currentValue), lifeRotation, a_Random0.w);\n #endif\n rotation += lifeRotation * a_ShapePositionStartLifeTime.w;\n #else\n float lifeRotation = renderer_ROLMaxConst.z;\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n lifeRotation = mix(renderer_ROLMinConst.z, lifeRotation, a_Random0.w);\n #endif\n rotation += lifeRotation * age;\n #endif\n #endif\n return rotation;\n}\n\n\n#if defined(RENDERER_MODE_MESH) && (defined(RENDERER_ROL_CONSTANT_MODE) || defined(RENDERER_ROL_CURVE_MODE))\nvec3 computeParticleRotationVec3(in vec3 rotation, in float age, in float normalizedAge) {\n #ifdef RENDERER_ROL_IS_SEPARATE\n #ifdef RENDERER_ROL_CONSTANT_MODE\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n vec3 ageRot = mix(renderer_ROLMinConst, renderer_ROLMaxConst, a_Random0.w) * age;\n #else\n vec3 ageRot = renderer_ROLMaxConst * age;\n #endif\n rotation += ageRot;\n #endif\n #ifdef RENDERER_ROL_CURVE_MODE\n float currentValue;\n float lifetime = a_ShapePositionStartLifeTime.w;\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n rotation += vec3(\n mix(evaluateParticleCurveCumulative(renderer_ROLMinCurveX, normalizedAge, currentValue),\n evaluateParticleCurveCumulative(renderer_ROLMaxCurveX, normalizedAge, currentValue), a_Random0.w),\n mix(evaluateParticleCurveCumulative(renderer_ROLMinCurveY, normalizedAge, currentValue),\n evaluateParticleCurveCumulative(renderer_ROLMaxCurveY, normalizedAge, currentValue), a_Random0.w),\n mix(evaluateParticleCurveCumulative(renderer_ROLMinCurveZ, normalizedAge, currentValue),\n evaluateParticleCurveCumulative(renderer_ROLMaxCurveZ, normalizedAge, currentValue), a_Random0.w)) * lifetime;\n #else\n rotation += vec3(\n evaluateParticleCurveCumulative(renderer_ROLMaxCurveX, normalizedAge, currentValue),\n evaluateParticleCurveCumulative(renderer_ROLMaxCurveY, normalizedAge, currentValue),\n evaluateParticleCurveCumulative(renderer_ROLMaxCurveZ, normalizedAge, currentValue)) * lifetime;\n #endif\n #endif\n #else\n #ifdef RENDERER_ROL_CONSTANT_MODE\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n float ageRot = mix(renderer_ROLMinConst.z, renderer_ROLMaxConst.z, a_Random0.w) * age;\n #else\n float ageRot = renderer_ROLMaxConst.z * age;\n #endif\n rotation += ageRot;\n #endif\n\n #ifdef RENDERER_ROL_CURVE_MODE\n float currentValue;\n float lifeRotation = evaluateParticleCurveCumulative(renderer_ROLMaxCurveZ, normalizedAge, currentValue);\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n lifeRotation = mix(evaluateParticleCurveCumulative(renderer_ROLMinCurveZ, normalizedAge, currentValue), lifeRotation, a_Random0.w);\n #endif\n rotation += lifeRotation * a_ShapePositionStartLifeTime.w;\n #endif\n #endif\n return rotation;\n}\n#endif\n"; // eslint-disable-line
4884
-
4885
- var size_over_lifetime_module = "#ifdef RENDERER_SOL_CURVE_MODE\n uniform vec2 renderer_SOLMaxCurveX[4]; // x:time y:value\n #ifdef RENDERER_SOL_IS_SEPARATE\n uniform vec2 renderer_SOLMaxCurveY[4]; // x:time y:value\n uniform vec2 renderer_SOLMaxCurveZ[4]; // x:time y:value\n #endif\n\n #ifdef RENDERER_SOL_IS_RANDOM_TWO\n uniform vec2 renderer_SOLMinCurveX[4]; // x:time y:value\n #ifdef RENDERER_SOL_IS_SEPARATE\n uniform vec2 renderer_SOLMinCurveY[4]; // x:time y:value\n uniform vec2 renderer_SOLMinCurveZ[4]; // x:time y:value\n #endif\n #endif\n#endif\n\nvec2 computeParticleSizeBillboard(in vec2 size, in float normalizedAge) {\n #ifdef RENDERER_SOL_CURVE_MODE\n float lifeSizeX = evaluateParticleCurve(renderer_SOLMaxCurveX, normalizedAge);\n #ifdef RENDERER_SOL_IS_RANDOM_TWO\n lifeSizeX = mix(evaluateParticleCurve(renderer_SOLMinCurveX, normalizedAge), lifeSizeX, a_Random0.z);\n #endif\n\n #ifdef RENDERER_SOL_IS_SEPARATE\n float lifeSizeY = evaluateParticleCurve(renderer_SOLMaxCurveY, normalizedAge);\n #ifdef RENDERER_SOL_IS_RANDOM_TWO\n lifeSizeY = mix(evaluateParticleCurve(renderer_SOLMinCurveY, normalizedAge), lifeSizeY, a_Random0.z);\n #endif\n size *= vec2(lifeSizeX, lifeSizeY);\n #else\n size *= lifeSizeX;\n #endif\n #endif\n return size;\n}\n\n#ifdef RENDERER_MODE_MESH\n vec3 computeParticleSizeMesh(in vec3 size, in float normalizedAge) {\n #ifdef RENDERER_SOL_CURVE\n size *= evaluateParticleCurve(renderer_SOLMaxCurveX, normalizedAge);\n #endif\n #ifdef RENDERER_SOL_RANDOM_CURVES\n size *= mix(evaluateParticleCurve(renderer_SOLMaxCurveX, normalizedAge),\n evaluateParticleCurve(u_SOLSizeGradientMax, normalizedAge),\n a_Random0.z);\n #endif\n #ifdef RENDERER_SOL_CURVE_SEPARATE\n size *= vec3(evaluateParticleCurve(renderer_SOLMinCurveX, normalizedAge),\n evaluateParticleCurve(renderer_SOLMinCurveY, normalizedAge),\n evaluateParticleCurve(renderer_SOLMinCurveZ, normalizedAge));\n #endif\n #ifdef RENDERER_SOL_RANDOM_CURVES_SEPARATE\n size *= vec3(mix(evaluateParticleCurve(renderer_SOLMinCurveX, normalizedAge),\n evaluateParticleCurve(renderer_SOLMaxCurveX, normalizedAge),\n a_Random0.z),\n mix(evaluateParticleCurve(renderer_SOLMinCurveY, normalizedAge),\n evaluateParticleCurve(renderer_SOLMaxCurveY, normalizedAge),\n a_Random0.z),\n mix(evaluateParticleCurve(renderer_SOLMinCurveZ, normalizedAge),\n evaluateParticleCurve(renderer_SOLMaxCurveZ, normalizedAge),\n a_Random0.z));\n #endif\n return size;\n }\n#endif"; // eslint-disable-line
4886
-
4887
- var color_over_lifetime_module = "#if defined(RENDERER_COL_GRADIENT) || defined(RENDERER_COL_RANDOM_GRADIENTS)\n uniform vec4 renderer_COLMaxGradientColor[4]; // x:time y:r z:g w:b\n uniform vec2 renderer_COLMaxGradientAlpha[4]; // x:time y:alpha\n\n #ifdef RENDERER_COL_RANDOM_GRADIENTS\n uniform vec4 renderer_COLMinGradientColor[4]; // x:time y:r z:g w:b\n uniform vec2 renderer_COLMinGradientAlpha[4]; // x:time y:alpha\n #endif\n\n uniform vec4 renderer_COLGradientKeysMaxTime; // x: minColorKeysMaxTime, y: minAlphaKeysMaxTime, z: maxColorKeysMaxTime, w: maxAlphaKeysMaxTime\n#endif\n\n\nvec4 computeParticleColor(in vec4 color, in float normalizedAge) {\n #if defined(RENDERER_COL_GRADIENT) || defined(RENDERER_COL_RANDOM_GRADIENTS)\n vec4 gradientColor = evaluateParticleGradient(renderer_COLMaxGradientColor, renderer_COLGradientKeysMaxTime.z, renderer_COLMaxGradientAlpha, renderer_COLGradientKeysMaxTime.w, normalizedAge);\n #endif\n\n #ifdef RENDERER_COL_RANDOM_GRADIENTS\n gradientColor = mix(evaluateParticleGradient(renderer_COLMinGradientColor,renderer_COLGradientKeysMaxTime.x, renderer_COLMinGradientAlpha, renderer_COLGradientKeysMaxTime.y, normalizedAge), gradientColor, a_Random0.y);\n #endif\n\n #if defined(RENDERER_COL_GRADIENT) || defined(RENDERER_COL_RANDOM_GRADIENTS)\n color *= gradientColor;\n #endif\n\n return color;\n}\n"; // eslint-disable-line
4888
-
4889
- var texture_sheet_animation_module = "#if defined(RENDERER_TSA_FRAME_CURVE) || defined(RENDERER_TSA_FRAME_RANDOM_CURVES)\n uniform float renderer_TSACycles;\n uniform vec3 renderer_TSATillingParams; // x:subU y:subV z:tileCount\n uniform vec2 renderer_TSAFrameMaxCurve[4]; // x:time y:value\n\n #ifdef RENDERER_TSA_FRAME_RANDOM_CURVES\n uniform vec2 renderer_TSAFrameMinCurve[4]; // x:time y:value\n #endif\n#endif\n\nvec2 computeParticleUV(in vec2 uv, in float normalizedAge) {\n #if defined(RENDERER_TSA_FRAME_CURVE) || defined(RENDERER_TSA_FRAME_RANDOM_CURVES)\n float scaledNormalizedAge = normalizedAge * renderer_TSACycles;\n float cycleNormalizedAge = scaledNormalizedAge - floor(scaledNormalizedAge);\n float normalizedFrame = evaluateParticleCurve(renderer_TSAFrameMaxCurve, cycleNormalizedAge);\n #ifdef RENDERER_TSA_FRAME_RANDOM_CURVES\n normalizedFrame = mix(evaluateParticleCurve(renderer_TSAFrameMinCurve, cycleNormalizedAge), normalizedFrame, a_Random1.x);\n #endif\n\n float frame = floor(normalizedFrame * renderer_TSATillingParams.z);\n\n float tileRow = frame * renderer_TSATillingParams.x;\n float tileRowIndex = floor(tileRow);\n uv.x += tileRow - tileRowIndex;\n uv.y += tileRowIndex * renderer_TSATillingParams.y;\n #endif\n \n return uv;\n}\n"; // eslint-disable-line
4890
-
4891
- var force_over_lifetime_module = "#if defined(RENDERER_FOL_CONSTANT_MODE) || defined(RENDERER_FOL_CURVE_MODE)\n #define _FOL_MODULE_ENABLED\n#endif\n\n#ifdef _FOL_MODULE_ENABLED\n uniform int renderer_FOLSpace;\n\n #ifdef RENDERER_FOL_CONSTANT_MODE\n uniform vec3 renderer_FOLMaxConst;\n\n #ifdef RENDERER_FOL_IS_RANDOM_TWO\n uniform vec3 renderer_FOLMinConst;\n #endif\n\n #endif\n\n #ifdef RENDERER_FOL_CURVE_MODE\n uniform vec2 renderer_FOLMaxGradientX[4];\n uniform vec2 renderer_FOLMaxGradientY[4];\n uniform vec2 renderer_FOLMaxGradientZ[4];\n\n #ifdef RENDERER_FOL_IS_RANDOM_TWO\n uniform vec2 renderer_FOLMinGradientX[4];\n uniform vec2 renderer_FOLMinGradientY[4];\n uniform vec2 renderer_FOLMinGradientZ[4];\n #endif\n #endif\n\n // (tHat - t1) * (tHat - t1) * (tHat - t1) * (a2 - a1) / ((t2 - t1) * 6.0) + a1 * (tHat - t1) * (tHat - t1) * 0.5 + v1 * (tHat - t1);\n // to = tHat - t1; tr = t2 - t1\n float computeDisplacementIntegral(in float to, in float tr, in float a1, in float a2, in float v1) {\n return to * to * to * (a2 - a1) / (tr * 6.0) + a1 * to * to * 0.5 + v1 * to;\n }\n\n float evaluateForceParticleCurveCumulative(in vec2 keys[4], in float normalizedAge, out float velocityCumulative) {\n float cumulativeValue = 0.0;\n velocityCumulative = 0.0;\n\n for (int i = 1; i < 4; i++){\n vec2 key = keys[i];\n vec2 lastKey = keys[i - 1];\n float timeRange = (key.x - lastKey.x) * a_ShapePositionStartLifeTime.w;\n\n if (key.x >= normalizedAge){\n float timeOffset = (normalizedAge - lastKey.x) * a_ShapePositionStartLifeTime.w;\n cumulativeValue += computeDisplacementIntegral(timeOffset, timeRange, lastKey.y, key.y, velocityCumulative);\n\n float finalAcceleration = mix(lastKey.y, key.y, timeOffset / timeRange);\n velocityCumulative += 0.5 * timeOffset * (finalAcceleration + lastKey.y);\n break;\n } else { \n cumulativeValue += computeDisplacementIntegral(timeRange, timeRange, lastKey.y, key.y, velocityCumulative);\n velocityCumulative += 0.5 * timeRange * (lastKey.y + key.y);\n }\n }\n return cumulativeValue;\n }\n\n vec3 computeForcePositionOffset(in float normalizedAge, in float age, out vec3 velocityOffset) {\n vec3 forcePosition;\n\n #if defined(RENDERER_FOL_CONSTANT_MODE)\n vec3 forceAcceleration = renderer_FOLMaxConst;\n\n #ifdef RENDERER_FOL_IS_RANDOM_TWO\n forceAcceleration = mix(renderer_FOLMinConst, forceAcceleration, vec3(a_Random2.x, a_Random2.y, a_Random2.z));\n #endif\n\n velocityOffset = forceAcceleration * age;\n\n forcePosition = 0.5 * forceAcceleration * age * age;\n #elif defined(RENDERER_FOL_CURVE_MODE)\n forcePosition = vec3(\n evaluateForceParticleCurveCumulative(renderer_FOLMaxGradientX, normalizedAge, velocityOffset.x),\n evaluateForceParticleCurveCumulative(renderer_FOLMaxGradientY, normalizedAge, velocityOffset.y),\n evaluateForceParticleCurveCumulative(renderer_FOLMaxGradientZ, normalizedAge, velocityOffset.z)\n );\n #ifdef RENDERER_FOL_IS_RANDOM_TWO\n vec3 minVelocityOffset;\n\n forcePosition = vec3(\n mix(evaluateForceParticleCurveCumulative(renderer_FOLMinGradientX, normalizedAge, minVelocityOffset.x), forcePosition.x, a_Random2.x),\n mix(evaluateForceParticleCurveCumulative(renderer_FOLMinGradientY, normalizedAge, minVelocityOffset.y), forcePosition.y, a_Random2.y),\n mix(evaluateForceParticleCurveCumulative(renderer_FOLMinGradientZ, normalizedAge, minVelocityOffset.z), forcePosition.z, a_Random2.z)\n );\n\n velocityOffset = mix(minVelocityOffset, velocityOffset, vec3(a_Random2.x, a_Random2.y, a_Random2.z));\n #endif\n #endif\n return forcePosition;\n }\n#endif"; // eslint-disable-line
4892
-
4893
- var limit_velocity_over_lifetime_module = "#ifdef RENDERER_LVL_MODULE_ENABLED\n uniform int renderer_LVLSpace;\n uniform float renderer_LVLDampen;\n\n // Scalar limit\n #ifndef RENDERER_LVL_SEPARATE_AXES\n #ifdef RENDERER_LVL_SPEED_CONSTANT_MODE\n uniform float renderer_LVLSpeedMaxConst;\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n uniform float renderer_LVLSpeedMinConst;\n #endif\n #endif\n #ifdef RENDERER_LVL_SPEED_CURVE_MODE\n uniform vec2 renderer_LVLSpeedMaxCurve[4];\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n uniform vec2 renderer_LVLSpeedMinCurve[4];\n #endif\n #endif\n #endif\n\n // Per-axis limit\n #ifdef RENDERER_LVL_SEPARATE_AXES\n #ifdef RENDERER_LVL_SPEED_CONSTANT_MODE\n uniform vec3 renderer_LVLSpeedMaxConstVector;\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n uniform vec3 renderer_LVLSpeedMinConstVector;\n #endif\n #endif\n #ifdef RENDERER_LVL_SPEED_CURVE_MODE\n uniform vec2 renderer_LVLSpeedXMaxCurve[4];\n uniform vec2 renderer_LVLSpeedYMaxCurve[4];\n uniform vec2 renderer_LVLSpeedZMaxCurve[4];\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n uniform vec2 renderer_LVLSpeedXMinCurve[4];\n uniform vec2 renderer_LVLSpeedYMinCurve[4];\n uniform vec2 renderer_LVLSpeedZMinCurve[4];\n #endif\n #endif\n #endif\n\n // Drag curve\n #ifdef RENDERER_LVL_DRAG_CURVE_MODE\n uniform vec2 renderer_LVLDragMaxCurve[4];\n #ifdef RENDERER_LVL_DRAG_IS_RANDOM_TWO\n uniform vec2 renderer_LVLDragMinCurve[4];\n #endif\n #endif\n\n float evaluateLVLDrag(float normalizedAge, float dragRand) {\n #ifdef RENDERER_LVL_DRAG_CURVE_MODE\n float dragMax = evaluateParticleCurve(renderer_LVLDragMaxCurve, normalizedAge);\n #ifdef RENDERER_LVL_DRAG_IS_RANDOM_TWO\n float dragMin = evaluateParticleCurve(renderer_LVLDragMinCurve, normalizedAge);\n return mix(dragMin, dragMax, dragRand);\n #else\n return dragMax;\n #endif\n #else\n return mix(renderer_LVLDragConstant.x, renderer_LVLDragConstant.y, dragRand);\n #endif\n }\n\n vec3 applyLVLSpeedLimitTF(vec3 velocity, float normalizedAge, float limitRand, float effectiveDampen) {\n #ifdef RENDERER_LVL_SEPARATE_AXES\n vec3 limitSpeed;\n #ifdef RENDERER_LVL_SPEED_CONSTANT_MODE\n limitSpeed = renderer_LVLSpeedMaxConstVector;\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n limitSpeed = mix(renderer_LVLSpeedMinConstVector, limitSpeed, limitRand);\n #endif\n #endif\n #ifdef RENDERER_LVL_SPEED_CURVE_MODE\n limitSpeed = vec3(\n evaluateParticleCurve(renderer_LVLSpeedXMaxCurve, normalizedAge),\n evaluateParticleCurve(renderer_LVLSpeedYMaxCurve, normalizedAge),\n evaluateParticleCurve(renderer_LVLSpeedZMaxCurve, normalizedAge)\n );\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n vec3 minLimitSpeed = vec3(\n evaluateParticleCurve(renderer_LVLSpeedXMinCurve, normalizedAge),\n evaluateParticleCurve(renderer_LVLSpeedYMinCurve, normalizedAge),\n evaluateParticleCurve(renderer_LVLSpeedZMinCurve, normalizedAge)\n );\n limitSpeed = mix(minLimitSpeed, limitSpeed, limitRand);\n #endif\n #endif\n\n vec3 absVel = abs(velocity);\n vec3 excess = max(absVel - limitSpeed, vec3(0.0));\n velocity = sign(velocity) * (absVel - excess * effectiveDampen);\n #else\n float limitSpeed;\n #ifdef RENDERER_LVL_SPEED_CONSTANT_MODE\n limitSpeed = renderer_LVLSpeedMaxConst;\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n limitSpeed = mix(renderer_LVLSpeedMinConst, limitSpeed, limitRand);\n #endif\n #endif\n #ifdef RENDERER_LVL_SPEED_CURVE_MODE\n limitSpeed = evaluateParticleCurve(renderer_LVLSpeedMaxCurve, normalizedAge);\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n float minLimitSpeed = evaluateParticleCurve(renderer_LVLSpeedMinCurve, normalizedAge);\n limitSpeed = mix(minLimitSpeed, limitSpeed, limitRand);\n #endif\n #endif\n\n float speed = length(velocity);\n if (speed > limitSpeed && speed > 0.0) {\n float excess = speed - limitSpeed;\n velocity = velocity * ((speed - excess * effectiveDampen) / speed);\n }\n #endif\n return velocity;\n }\n\n#endif\n"; // eslint-disable-line
4894
-
4895
- var noise_module = "#ifdef RENDERER_NOISE_MODULE_ENABLED\n\n#include <noise_common>\n#include <noise_simplex_3D_grad>\n\nuniform vec4 renderer_NoiseParams; // xyz = strength (constant mode only), w = frequency\nuniform vec4 renderer_NoiseOctaveParams; // x = scrollSpeed, y = octaveCount, z = octaveIntensityMultiplier, w = octaveFrequencyMultiplier\n\n#ifdef RENDERER_NOISE_STRENGTH_CURVE\n uniform vec2 renderer_NoiseStrengthMaxCurveX[4];\n #ifdef RENDERER_NOISE_IS_SEPARATE\n uniform vec2 renderer_NoiseStrengthMaxCurveY[4];\n uniform vec2 renderer_NoiseStrengthMaxCurveZ[4];\n #endif\n #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO\n uniform vec2 renderer_NoiseStrengthMinCurveX[4];\n #ifdef RENDERER_NOISE_IS_SEPARATE\n uniform vec2 renderer_NoiseStrengthMinCurveY[4];\n uniform vec2 renderer_NoiseStrengthMinCurveZ[4];\n #endif\n #endif\n#else\n #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO\n uniform vec3 renderer_NoiseStrengthMinConst;\n #endif\n#endif\n\nvec3 sampleCurlNoise3D(vec3 coord) {\n float axisOffset = 100.0;\n vec3 gradX = simplexGrad(vec3(coord.z, coord.y, coord.x));\n vec3 gradY = simplexGrad(vec3(coord.x + axisOffset, coord.z, coord.y));\n vec3 gradZ = simplexGrad(vec3(coord.y, coord.x + axisOffset, coord.z));\n return vec3(\n gradZ.x - gradY.y,\n gradX.x - gradZ.y,\n gradY.x - gradX.y\n );\n}\n\nvec3 computeNoiseVelocity(vec3 currentPosition, float normalizedAge) {\n vec3 coord = currentPosition * renderer_NoiseParams.w\n + vec3(renderer_CurrentTime * renderer_NoiseOctaveParams.x);\n\n int octaveCount = int(renderer_NoiseOctaveParams.y);\n float octaveIntensityMultiplier = renderer_NoiseOctaveParams.z;\n float octaveFrequencyMultiplier = renderer_NoiseOctaveParams.w;\n\n vec3 noiseValue = sampleCurlNoise3D(coord);\n float totalAmplitude = 1.0;\n\n // Unrolled octave loop (GLSL ES 1.0 requires constant loop bounds)\n if (octaveCount >= 2) {\n float amplitude = octaveIntensityMultiplier;\n totalAmplitude += amplitude;\n noiseValue += amplitude * sampleCurlNoise3D(coord * octaveFrequencyMultiplier);\n\n if (octaveCount >= 3) {\n amplitude *= octaveIntensityMultiplier;\n totalAmplitude += amplitude;\n noiseValue += amplitude * sampleCurlNoise3D(coord * octaveFrequencyMultiplier * octaveFrequencyMultiplier);\n }\n }\n\n // Evaluate strength (supports Constant, TwoConstants, Curve, TwoCurves).\n vec3 strength;\n #ifdef RENDERER_NOISE_STRENGTH_CURVE\n float sx = evaluateParticleCurve(renderer_NoiseStrengthMaxCurveX, normalizedAge);\n #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO\n sx = mix(evaluateParticleCurve(renderer_NoiseStrengthMinCurveX, normalizedAge), sx, a_Random0.z);\n #endif\n #ifdef RENDERER_NOISE_IS_SEPARATE\n float sy = evaluateParticleCurve(renderer_NoiseStrengthMaxCurveY, normalizedAge);\n float sz = evaluateParticleCurve(renderer_NoiseStrengthMaxCurveZ, normalizedAge);\n #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO\n sy = mix(evaluateParticleCurve(renderer_NoiseStrengthMinCurveY, normalizedAge), sy, a_Random0.z);\n sz = mix(evaluateParticleCurve(renderer_NoiseStrengthMinCurveZ, normalizedAge), sz, a_Random0.z);\n #endif\n strength = vec3(sx, sy, sz);\n #else\n strength = vec3(sx);\n #endif\n #else\n strength = renderer_NoiseParams.xyz;\n #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO\n strength = mix(renderer_NoiseStrengthMinConst, strength, a_Random0.z);\n #endif\n #endif\n\n return (noiseValue / totalAmplitude) * strength;\n}\n\n#endif\n"; // eslint-disable-line
4896
-
4897
- var particle_feedback_simulation = "// Transform Feedback update shader for particle simulation.\n// Update order: VOL/FOL → Dampen → Drag → Position.\n// Runs once per particle per frame (no rasterization).\n\n// Previous frame TF data\nattribute vec3 a_FeedbackPosition;\nattribute vec3 a_FeedbackVelocity;\n\n// Per-particle instance data\nattribute vec4 a_ShapePositionStartLifeTime;\nattribute vec4 a_DirectionTime;\nattribute vec3 a_StartSize;\nattribute float a_StartSpeed;\nattribute vec4 a_Random0;\nattribute vec4 a_Random1;\nattribute vec3 a_SimulationWorldPosition;\nattribute vec4 a_SimulationWorldRotation;\nattribute vec4 a_Random2;\n\n// Uniforms\nuniform float renderer_CurrentTime;\nuniform float renderer_DeltaTime;\nuniform vec3 renderer_Gravity;\nuniform vec2 renderer_LVLDragConstant;\nuniform vec3 renderer_WorldPosition;\nuniform vec4 renderer_WorldRotation;\nuniform int renderer_SimulationSpace;\n\n// TF outputs\nvarying vec3 v_FeedbackPosition;\nvarying vec3 v_FeedbackVelocity;\n\n#include <particle_common>\n#include <velocity_over_lifetime_module>\n#include <force_over_lifetime_module>\n#include <limit_velocity_over_lifetime_module>\n#include <noise_module>\n\n// Get VOL instantaneous velocity at normalizedAge\nvec3 getVOLVelocity(float normalizedAge) {\n vec3 vel = vec3(0.0);\n #ifdef _VOL_MODULE_ENABLED\n #ifdef RENDERER_VOL_CONSTANT_MODE\n vel = renderer_VOLMaxConst;\n #ifdef RENDERER_VOL_IS_RANDOM_TWO\n vel = mix(renderer_VOLMinConst, vel, a_Random1.yzw);\n #endif\n #endif\n #ifdef RENDERER_VOL_CURVE_MODE\n vel = vec3(\n evaluateParticleCurve(renderer_VOLMaxGradientX, normalizedAge),\n evaluateParticleCurve(renderer_VOLMaxGradientY, normalizedAge),\n evaluateParticleCurve(renderer_VOLMaxGradientZ, normalizedAge)\n );\n #ifdef RENDERER_VOL_IS_RANDOM_TWO\n vec3 minVel = vec3(\n evaluateParticleCurve(renderer_VOLMinGradientX, normalizedAge),\n evaluateParticleCurve(renderer_VOLMinGradientY, normalizedAge),\n evaluateParticleCurve(renderer_VOLMinGradientZ, normalizedAge)\n );\n vel = mix(minVel, vel, a_Random1.yzw);\n #endif\n #endif\n #endif\n return vel;\n}\n\n// Get FOL instantaneous acceleration at normalizedAge\nvec3 getFOLAcceleration(float normalizedAge) {\n vec3 acc = vec3(0.0);\n #ifdef _FOL_MODULE_ENABLED\n #ifdef RENDERER_FOL_CONSTANT_MODE\n acc = renderer_FOLMaxConst;\n #ifdef RENDERER_FOL_IS_RANDOM_TWO\n acc = mix(renderer_FOLMinConst, acc, vec3(a_Random2.x, a_Random2.y, a_Random2.z));\n #endif\n #endif\n #ifdef RENDERER_FOL_CURVE_MODE\n acc = vec3(\n evaluateParticleCurve(renderer_FOLMaxGradientX, normalizedAge),\n evaluateParticleCurve(renderer_FOLMaxGradientY, normalizedAge),\n evaluateParticleCurve(renderer_FOLMaxGradientZ, normalizedAge)\n );\n #ifdef RENDERER_FOL_IS_RANDOM_TWO\n vec3 minAcc = vec3(\n evaluateParticleCurve(renderer_FOLMinGradientX, normalizedAge),\n evaluateParticleCurve(renderer_FOLMinGradientY, normalizedAge),\n evaluateParticleCurve(renderer_FOLMinGradientZ, normalizedAge)\n );\n acc = mix(minAcc, acc, vec3(a_Random2.x, a_Random2.y, a_Random2.z));\n #endif\n #endif\n #endif\n return acc;\n}\n\nvoid main() {\n float age = renderer_CurrentTime - a_DirectionTime.w;\n float lifetime = a_ShapePositionStartLifeTime.w;\n float normalizedAge = age / lifetime;\n // Clamp to age on the first TF pass: particles emitted mid-frame have age < dt,\n // so using the full dt would over-integrate. Subsequent passes are unaffected (age >= dt).\n float dt = min(renderer_DeltaTime, age);\n\n // normalizedAge < 0.0: stale TF slot whose startTime is from a previous playback (e.g. after StopEmittingAndClear).\n if (normalizedAge >= 1.0 || normalizedAge < 0.0) {\n v_FeedbackPosition = a_FeedbackPosition;\n v_FeedbackVelocity = a_FeedbackVelocity;\n gl_Position = vec4(0.0);\n return;\n }\n\n vec4 worldRotation;\n if (renderer_SimulationSpace == 0) {\n worldRotation = renderer_WorldRotation;\n } else {\n worldRotation = a_SimulationWorldRotation;\n }\n vec4 invWorldRotation = quaternionConjugate(worldRotation);\n\n // Read previous frame state (initialized by CPU on particle birth)\n vec3 localVelocity = a_FeedbackVelocity;\n\n // =====================================================\n // Step 1: Apply velocity module deltas (VOL + FOL + Gravity)\n // =====================================================\n\n // Gravity (world space)\n vec3 gravityDelta = renderer_Gravity * a_Random0.x * dt;\n\n // VOL instantaneous velocity (animated velocity, not persisted)\n vec3 volLocal = vec3(0.0);\n vec3 volWorld = vec3(0.0);\n #ifdef _VOL_MODULE_ENABLED\n vec3 vol = getVOLVelocity(normalizedAge);\n if (renderer_VOLSpace == 0) {\n volLocal = vol;\n } else {\n volWorld = vol;\n }\n #endif\n\n // FOL acceleration → velocity delta (always persisted, like gravity)\n vec3 folDeltaLocal = vec3(0.0);\n #ifdef _FOL_MODULE_ENABLED\n vec3 folAcc = getFOLAcceleration(normalizedAge);\n vec3 folVelDelta = folAcc * dt;\n if (renderer_FOLSpace == 0) {\n folDeltaLocal = folVelDelta;\n } else {\n // World FOL: convert to local and persist, same as gravity\n folDeltaLocal = rotationByQuaternions(folVelDelta, invWorldRotation);\n }\n #endif\n\n // Gravity and FOL contribute to base velocity (persisted, subject to dampen/drag).\n vec3 gravityLocal = rotationByQuaternions(gravityDelta, invWorldRotation);\n localVelocity += folDeltaLocal + gravityLocal;\n\n // =====================================================\n // Step 2 & 3: Dampen (Limit Velocity) + Drag\n // VOL must be projected into the LVL target space so that\n // limit/drag see the full velocity regardless of VOL.space vs LVL.space.\n // =====================================================\n #ifdef RENDERER_LVL_MODULE_ENABLED\n // Precompute VOL in both spaces\n vec3 volAsLocal = volLocal + rotationByQuaternions(volWorld, invWorldRotation);\n vec3 volAsWorld = rotationByQuaternions(volLocal, worldRotation) + volWorld;\n\n float limitRand = a_Random2.w;\n float dampen = renderer_LVLDampen;\n // Frame-rate independent dampen (30fps as reference)\n float effectiveDampen = 1.0 - pow(1.0 - dampen, dt * 30.0);\n\n if (renderer_LVLSpace == 0) {\n // Local space: total = base + all VOL projected to local\n vec3 totalLocal = localVelocity + volAsLocal;\n vec3 dampenedTotal = applyLVLSpeedLimitTF(totalLocal, normalizedAge, limitRand, effectiveDampen);\n localVelocity = dampenedTotal - volAsLocal;\n } else {\n // World space: total = rotated base + all VOL projected to world\n vec3 totalWorld = rotationByQuaternions(localVelocity, worldRotation) + volAsWorld;\n vec3 dampenedTotal = applyLVLSpeedLimitTF(totalWorld, normalizedAge, limitRand, effectiveDampen);\n localVelocity = rotationByQuaternions(dampenedTotal - volAsWorld, invWorldRotation);\n }\n\n // Drag: same space as dampen\n {\n float dragCoeff = evaluateLVLDrag(normalizedAge, a_Random2.w);\n if (dragCoeff > 0.0) {\n vec3 totalVel;\n if (renderer_LVLSpace == 0) {\n totalVel = localVelocity + volAsLocal;\n } else {\n totalVel = rotationByQuaternions(localVelocity, worldRotation) + volAsWorld;\n }\n float velMagSqr = dot(totalVel, totalVel);\n float velMag = sqrt(velMagSqr);\n\n float drag = dragCoeff;\n\n #ifdef RENDERER_LVL_DRAG_MULTIPLY_SIZE\n float maxDim = max(a_StartSize.x, max(a_StartSize.y, a_StartSize.z));\n float radius = maxDim * 0.5;\n drag *= 3.14159265 * radius * radius;\n #endif\n\n #ifdef RENDERER_LVL_DRAG_MULTIPLY_VELOCITY\n drag *= velMagSqr;\n #endif\n\n if (velMag > 0.0) {\n float newVelMag = max(0.0, velMag - drag * dt);\n vec3 draggedTotal = totalVel * (newVelMag / velMag);\n if (renderer_LVLSpace == 0) {\n localVelocity = draggedTotal - volAsLocal;\n } else {\n localVelocity = rotationByQuaternions(draggedTotal - volAsWorld, invWorldRotation);\n }\n }\n }\n }\n #endif\n\n // =====================================================\n // Step 4: Integrate position in simulation space\n // Local mode: position in local space, velocity rotated to local\n // World mode: position in world space, velocity rotated to world\n // =====================================================\n // FOL is now fully in localVelocity (both local and world-space FOL).\n // VOL and Noise overlays are added here (not persisted).\n\n vec3 totalVelocity;\n if (renderer_SimulationSpace == 0) {\n totalVelocity = localVelocity + volLocal + rotationByQuaternions(volWorld, invWorldRotation);\n } else {\n totalVelocity = rotationByQuaternions(localVelocity + volLocal, worldRotation) + volWorld;\n }\n #ifdef RENDERER_NOISE_MODULE_ENABLED\n // Use analytical base position (birth + initial velocity * age) instead of\n // a_FeedbackPosition to avoid feedback loop: position → noise → velocity → position\n vec3 noiseBasePos;\n if (renderer_SimulationSpace == 0) {\n noiseBasePos = a_ShapePositionStartLifeTime.xyz + a_DirectionTime.xyz * a_StartSpeed * age;\n } else {\n noiseBasePos = rotationByQuaternions(\n a_ShapePositionStartLifeTime.xyz + a_DirectionTime.xyz * a_StartSpeed * age,\n worldRotation) + a_SimulationWorldPosition;\n }\n totalVelocity += computeNoiseVelocity(noiseBasePos, normalizedAge);\n #endif\n vec3 position = a_FeedbackPosition + totalVelocity * dt;\n\n v_FeedbackPosition = position;\n v_FeedbackVelocity = localVelocity;\n gl_Position = vec4(0.0);\n}\n"; // eslint-disable-line
4898
-
4899
- var sphere_billboard = "#ifdef RENDERER_MODE_SPHERE_BILLBOARD\n\tvec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy;\n\tvec3 sideVector = normalize(cross(camera_Forward, camera_Up));\n\tvec3 upVector = normalize(cross(sideVector, camera_Forward));\n\tcorner *= computeParticleSizeBillboard(a_StartSize.xy, normalizedAge);\n #if defined(RENDERER_ROL_CONSTANT_MODE) || defined(RENDERER_ROL_CURVE_MODE)\n if (renderer_ThreeDStartRotation) {\n vec3 rotation = radians(vec3(a_StartRotation0.xy, computeParticleRotationFloat(a_StartRotation0.z, age, normalizedAge)));\n center += renderer_SizeScale.xzy * rotationByEuler(corner.x * sideVector + corner.y * upVector, rotation);\n } else {\n float rot = radians(computeParticleRotationFloat(a_StartRotation0.x, age, normalizedAge));\n float c = cos(rot);\n float s = sin(rot);\n mat2 rotation = mat2(c, -s, s, c);\n corner = rotation * corner;\n center += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * upVector);\n }\n #else\n if (renderer_ThreeDStartRotation) {\n center += renderer_SizeScale.xzy * rotationByEuler(corner.x * sideVector + corner.y * upVector, radians(a_StartRotation0));\n } else {\n float c = cos(radians(a_StartRotation0.x));\n float s = sin(radians(a_StartRotation0.x));\n mat2 rotation = mat2(c, -s, s, c);\n corner = rotation * corner;\n center += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * upVector);\n }\n #endif\n#endif"; // eslint-disable-line
4900
-
4901
- var stretched_billboard = "#ifdef RENDERER_MODE_STRETCHED_BILLBOARD\n\tvec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy;\n\tvec3 velocity = rotationByQuaternions(renderer_SizeScale * localVelocity, worldRotation) + worldVelocity;\n\tvec3 cameraUpVector = normalize(velocity);\n\tvec3 direction = normalize(center - camera_Position);\n\tvec3 sideVector = normalize(cross(direction, normalize(velocity)));\n\n\tsideVector = renderer_SizeScale.xzy * sideVector;\n\tcameraUpVector = length(vec3(renderer_SizeScale.x, 0.0, 0.0)) * cameraUpVector;\n\n\tvec2 size = computeParticleSizeBillboard(a_StartSize.xy, normalizedAge);\n\n\tconst mat2 rotationZHalfPI = mat2(0.0, -1.0, 1.0, 0.0);\n\tcorner = rotationZHalfPI * corner;\n\tcorner.y = corner.y - abs(corner.y);\n\n\tfloat speed = length(velocity); // TODO:\n\tcenter += sign(renderer_SizeScale.x) * (sign(renderer_StretchedBillboardLengthScale) * size.x * corner.x * sideVector\n\t + (speed * renderer_StretchedBillboardSpeedScale + size.y * renderer_StretchedBillboardLengthScale) * corner.y * cameraUpVector);\n#endif"; // eslint-disable-line
4902
-
4903
- var vertical_billboard = "#ifdef RENDERER_MODE_VERTICAL_BILLBOARD\n\tvec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy; // Billboard模式z轴无效\n\tconst vec3 cameraUpVector = vec3(0.0, 1.0, 0.0);\n\tvec3 sideVector = normalize(cross(camera_Forward, cameraUpVector));\n\n\tfloat rot = radians(computeParticleRotationFloat(a_StartRotation0.x, age, normalizedAge));\n\tfloat c = cos(rot);\n\tfloat s = sin(rot);\n\tmat2 rotation = mat2(c, -s, s, c);\n\tcorner = rotation * corner * cos(0.78539816339744830961566084581988); // TODO:临时缩小cos45,不确定U3D原因\n\tcorner *= computeParticleSizeBillboard(a_StartSize.xy, normalizedAge);\n\tcenter += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * cameraUpVector);\n#endif"; // eslint-disable-line
4904
-
4905
- var horizontal_billboard = "#ifdef RENDERER_MODE_HORIZONTAL_BILLBOARD\n\tvec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy;\n\tconst vec3 sideVector = vec3(1.0, 0.0, 0.0);\n\tconst vec3 upVector = vec3(0.0, 0.0, -1.0);\n\tcorner *= computeParticleSizeBillboard(a_StartSize.xy, normalizedAge);\n\n\t// HorizontalBillboard rotates in XZ plane (around Y-axis normal).\n\t// Uses Z-axis rotation data to match Unity behavior.\n\tfloat rot;\n\tif (renderer_ThreeDStartRotation) {\n\t\trot = radians(computeParticleRotationFloat(a_StartRotation0.z, age, normalizedAge));\n\t} else {\n\t\trot = radians(computeParticleRotationFloat(a_StartRotation0.x, age, normalizedAge));\n\t}\n\n\tfloat c = cos(rot);\n\tfloat s = sin(rot);\n\tmat2 rotation = mat2(c, -s, s, c);\n\tcorner = rotation * corner;\n\tcenter += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * upVector);\n#endif"; // eslint-disable-line
4906
-
4907
- var particle_mesh = "// Only support local alignment mode\n#ifdef RENDERER_MODE_MESH\n #if defined(RENDERER_ROL_CONSTANT_MODE) || defined(RENDERER_ROL_CURVE_MODE)\n #define RENDERER_ROL_ENABLED\n #endif\n\n\tvec3 size = computeParticleSizeMesh(a_StartSize, normalizedAge);\n\n bool is3DRotation = renderer_ThreeDStartRotation;\n #if defined(RENDERER_ROL_ENABLED) && defined(RENDERER_ROL_IS_SEPARATE)\n is3DRotation = true;\n #endif\n\n if (is3DRotation) {\n #ifdef RENDERER_ROL_ENABLED\n vec3 startRotation = renderer_ThreeDStartRotation ? a_StartRotation0 : vec3(0.0, 0.0, a_StartRotation0.x);\n vec3 rotation = radians(computeParticleRotationVec3(startRotation, age, normalizedAge));\n #else\n vec3 rotation = radians(a_StartRotation0);\n #endif\n // 3D Start Rotation is same in local and world simulation space\n center += rotationByQuaternions(renderer_SizeScale * rotationByEuler(POSITION * size, rotation), worldRotation);\n } else {\n #ifdef RENDERER_ROL_ENABLED\n float angle = radians(computeParticleRotationFloat(a_StartRotation0.x, age, normalizedAge));\n #else\n float angle = radians(a_StartRotation0.x);\n #endif\n #ifdef RENDERER_EMISSION_SHAPE\n // Axis is side vector of emit position look at zero\n vec3 axis = vec3(a_ShapePositionStartLifeTime.xy, 0.0);\n if (renderer_SimulationSpace == 1){\n axis = rotationByQuaternions(axis, worldRotation);\n }\n vec3 crossResult = cross(axis, vec3(0.0, 0.0, -1.0));\n float crossLen = length(crossResult);\n vec3 rotateAxis = crossLen > 0.0001 ? crossResult / crossLen : vec3(0.0, 1.0, 0.0);\n #else\n // Axis is negative z\n vec3 rotateAxis = vec3(0.0, 0.0, -1.0);\n #endif\n center += rotationByQuaternions(renderer_SizeScale *rotationByAxis(POSITION * size, rotateAxis, angle), worldRotation);\n }\n #ifdef RENDERER_ENABLE_VERTEXCOLOR\n\t\tv_MeshColor = COLOR_0;\n\t#endif\n#endif"; // eslint-disable-line
4908
-
4909
- var ParticleShaderLib = {
4910
- particle_common: particle_common,
4911
- velocity_over_lifetime_module: velocity_over_lifetime_module,
4912
- rotation_over_lifetime_module: rotation_over_lifetime_module,
4913
- size_over_lifetime_module: size_over_lifetime_module,
4914
- color_over_lifetime_module: color_over_lifetime_module,
4915
- texture_sheet_animation_module: texture_sheet_animation_module,
4916
- force_over_lifetime_module: force_over_lifetime_module,
4917
- limit_velocity_over_lifetime_module: limit_velocity_over_lifetime_module,
4918
- noise_module: noise_module,
4919
- particle_feedback_simulation: particle_feedback_simulation,
4920
- sphere_billboard: sphere_billboard,
4921
- stretched_billboard: stretched_billboard,
4922
- vertical_billboard: vertical_billboard,
4923
- horizontal_billboard: horizontal_billboard,
4924
- particle_mesh: particle_mesh
4925
- };
4926
-
4927
- var normal_get = "// gl_FrontFacing has random value on Adreno GPUs\n// the Adreno bug is only when gl_FrontFacing is inside a function\n// https://bugs.chromium.org/p/chromium/issues/detail?id=1154842\nvec3 getNormal(bool isFrontFacing){\n #ifdef RENDERER_HAS_NORMAL\n vec3 normal = normalize(v_normal);\n #elif defined(HAS_DERIVATIVES)\n vec3 pos_dx = dFdx(v_pos);\n vec3 pos_dy = dFdy(v_pos);\n vec3 normal = normalize( cross(pos_dx, pos_dy) );\n normal *= camera_ProjectionParams.x;\n #else\n vec3 normal = vec3(0, 0, 1);\n #endif\n\n normal *= float( isFrontFacing ) * 2.0 - 1.0;\n return normal;\n}\n\nvec3 getNormalByNormalTexture(mat3 tbn, sampler2D normalTexture, float normalIntensity, vec2 uv, bool isFrontFacing){\n vec3 normal = texture2D(normalTexture, uv).rgb;\n normal = normalize(tbn * ((2.0 * normal - 1.0) * vec3(normalIntensity, normalIntensity, 1.0)));\n normal *= float( isFrontFacing ) * 2.0 - 1.0;\n\n return normal;\n}\n\nmat3 getTBN(bool isFrontFacing){\n #if defined(RENDERER_HAS_NORMAL) && defined(RENDERER_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) || defined(MATERIAL_ENABLE_ANISOTROPY) )\n mat3 tbn = v_TBN;\n #else\n vec3 normal = getNormal(isFrontFacing);\n vec3 position = v_pos;\n vec2 uv = isFrontFacing? v_uv: -v_uv;\n\n #ifdef HAS_DERIVATIVES\n // ref: http://www.thetenthplanet.de/archives/1180\n // get edge vectors of the pixel triangle\n\t vec3 dp1 = dFdx(position);\n\t vec3 dp2 = dFdy(position);\n\t vec2 duv1 = dFdx(uv);\n\t vec2 duv2 = dFdy(uv);\n\n\t // solve the linear system\n\t vec3 dp2perp = cross(dp2, normal);\n\t vec3 dp1perp = cross(normal, dp1);\n\t vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n\t vec3 bitangent = dp2perp * duv1.y + dp1perp * duv2.y;\n\n\t // construct a scale-invariant frame \n float denom = max( dot(tangent, tangent), dot(bitangent, bitangent) );\n float invmax = (denom == 0.0) ? 0.0 : camera_ProjectionParams.x / sqrt( denom );\n\t mat3 tbn = mat3(tangent * invmax, bitangent * invmax, normal);\n #else\n mat3 tbn = mat3(vec3(0.0), vec3(0.0), normal);\n #endif\n #endif\n\t\n return tbn;\n}"; // eslint-disable-line
4928
-
4929
- var ShaderLib = _extends({
4930
- common: common,
4931
- common_vert: common_vert,
4932
- transform_declare: transform_declare,
4933
- camera_declare: camera_declare,
4934
- color_share: color_share,
4935
- normal_share: normal_share,
4936
- uv_share: uv_share,
4937
- worldpos_share: worldpos_share,
4938
- FogVertexDeclaration: FogVertexDeclaration,
4939
- FogFragmentDeclaration: FogFragmentDeclaration,
4940
- PositionClipSpaceDeclaration: PositionClipSpaceDeclaration,
4941
- begin_normal_vert: begin_normal_vert,
4942
- begin_position_vert: begin_position_vert,
4943
- position_vert: position_vert,
4944
- color_vert: color_vert,
4945
- normal_vert: normal_vert,
4946
- skinning_vert: skinning_vert,
4947
- blendShape_input: blendShape_input,
4948
- blendShape_vert: blendShape_vert,
4949
- uv_vert: uv_vert,
4950
- worldpos_vert: worldpos_vert,
4951
- FogVertex: FogVertex,
4952
- light_frag_define: light_frag_define,
4953
- mobile_material_frag: mobile_material_frag,
4954
- FogFragment: FogFragment,
4955
- PositionClipSpaceVertex: PositionClipSpaceVertex,
4956
- begin_mobile_frag: begin_mobile_frag,
4957
- begin_viewdir_frag: begin_viewdir_frag,
4958
- mobile_blinnphong_frag: mobile_blinnphong_frag,
4959
- noise_common: noise_common,
4960
- noise_simplex_3D_grad: noise_simplex_3D_grad
4961
- }, ShadowLib, PBRShaderLib, {
4962
- normal_get: normal_get
4963
- }, ParticleShaderLib);
4964
-
4965
- var ShaderFactory = /*#__PURE__*/ function() {
4771
+ /**
4772
+ * Shader registry and GLSL utilities. Holds the `#include` lookup table
4773
+ * the runtime preprocessor reads, and the GLSL ES 100 300 syntax
4774
+ * converter the WebGL2 path uses.
4775
+ */ var ShaderFactory = /*#__PURE__*/ function() {
4966
4776
  function ShaderFactory() {}
4967
- ShaderFactory.parseCustomMacros = function parseCustomMacros(macros) {
4968
- return macros.map(function(m) {
4969
- return "#define " + (m.value ? m.name + " " + m.value : m.name) + "\n";
4970
- }).join("");
4971
- };
4972
4777
  /**
4973
- * @internal
4974
- * Compile vertex and fragment source with standard macros, includes, and version header.
4975
- * @param engine - Engine instance
4976
- * @param macroCollection - Current macro collection
4977
- * @param vertexSource - Raw vertex shader source (may contain #include)
4978
- * @param fragmentSource - Raw fragment shader source
4979
- * @returns Compiled { vertexSource, fragmentSource } ready for ShaderProgram
4980
- */ ShaderFactory.compilePlatformSource = function compilePlatformSource(engine, macroCollection, vertexSource, fragmentSource) {
4981
- var isWebGL2 = engine._hardwareRenderer.isWebGL2;
4982
- var shaderMacroList = new Array();
4983
- ShaderMacro._getMacrosElements(macroCollection, shaderMacroList);
4984
- shaderMacroList.push(ShaderMacro.getByName(isWebGL2 ? "GRAPHICS_API_WEBGL2" : "GRAPHICS_API_WEBGL1"));
4985
- if (engine._hardwareRenderer.canIUse(GLCapabilityType.shaderTextureLod)) {
4986
- shaderMacroList.push(ShaderMacro.getByName("HAS_TEX_LOD"));
4987
- }
4988
- if (engine._hardwareRenderer.canIUse(GLCapabilityType.standardDerivatives)) {
4989
- shaderMacroList.push(ShaderMacro.getByName("HAS_DERIVATIVES"));
4990
- }
4991
- var noIncludeVertex = ShaderFactory.parseIncludes(vertexSource);
4992
- var noIncludeFrag = ShaderFactory.parseIncludes(fragmentSource);
4993
- var macroStr = ShaderFactory.parseCustomMacros(shaderMacroList);
4994
- noIncludeVertex = macroStr + noIncludeVertex;
4995
- noIncludeFrag = macroStr + noIncludeFrag;
4996
- if (isWebGL2) {
4997
- noIncludeVertex = ShaderFactory.convertTo300(noIncludeVertex);
4998
- noIncludeFrag = ShaderFactory.convertTo300(noIncludeFrag, true);
4999
- }
5000
- var versionStr = isWebGL2 ? "#version 300 es" : "#version 100";
5001
- var precisionStr = "\n#ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n precision highp int;\n#else\n precision mediump float;\n precision mediump int;\n#endif\n";
5002
- return {
5003
- vertexSource: versionStr + "\nprecision highp float;\n" + noIncludeVertex,
5004
- fragmentSource: versionStr + "\n" + (isWebGL2 ? "" : ShaderFactory._shaderExtension) + precisionStr + noIncludeFrag
5005
- };
5006
- };
5007
- ShaderFactory.registerInclude = function registerInclude(includeName, includeSource) {
5008
- if (ShaderLib[includeName]) {
4778
+ * Register a chunk source so `#include` resolves it.
4779
+ * @param includeName - The path key referenced in `#include "..."`.
4780
+ * @param includeSource - GLSL chunk source text.
4781
+ */ ShaderFactory.registerInclude = function registerInclude(includeName, includeSource) {
4782
+ if (ShaderFactory.includeMap[includeName]) {
5009
4783
  throw 'The "' + includeName + '" shader include already exist';
5010
4784
  }
5011
- ShaderLib[includeName] = includeSource;
5012
- };
5013
- ShaderFactory.unRegisterInclude = function unRegisterInclude(includeName) {
5014
- delete ShaderLib[includeName];
4785
+ ShaderFactory.includeMap[includeName] = includeSource;
5015
4786
  };
5016
4787
  /**
5017
- * @param regex The default regex is for engine's builtin glsl `#include` syntax,
5018
- * since `ShaderLab` use the same parsing function but different syntax for `#include` --- `/^[ \t]*#include +"([\w\d.]+)"/gm`
5019
- */ ShaderFactory.parseIncludes = function parseIncludes(src, regex) {
5020
- if (regex === void 0) regex = /^[ \t]*#include +<([\w\d.]+)>/gm;
5021
- function replace(match, slice) {
5022
- var _$replace = ShaderLib[slice];
5023
- if (_$replace === undefined) {
5024
- Logger.error('Shader slice "' + match.trim() + '" not founded.');
5025
- return "";
5026
- }
5027
- return ShaderFactory.parseIncludes(_$replace, regex);
5028
- }
5029
- return src.replace(regex, replace);
4788
+ * Remove a registered shader chunk.
4789
+ * @param includeName - The path key passed to `registerInclude`.
4790
+ */ ShaderFactory.unRegisterInclude = function unRegisterInclude(includeName) {
4791
+ delete ShaderFactory.includeMap[includeName];
5030
4792
  };
5031
4793
  /**
5032
4794
  * Convert lower GLSL version to GLSL 300 es.
5033
4795
  * @param shader - code
5034
4796
  * @param isFrag - Whether it is a fragment shader.
5035
- * */ ShaderFactory.convertTo300 = function convertTo300(shader, isFrag) {
4797
+ */ ShaderFactory.convertTo300 = function convertTo300(shader, isFrag) {
5036
4798
  shader = shader.replace(/\bvarying\b/g, isFrag ? "in" : "out");
5037
4799
  shader = shader.replace(/\btexture(2D|Cube)\b/g, "texture");
5038
4800
  shader = shader.replace(/\btexture2DProj\b/g, "textureProj");
@@ -5042,12 +4804,12 @@ var ShaderFactory = /*#__PURE__*/ function() {
5042
4804
  shader = shader.replace(/\btexture2DProjGradEXT\b/g, "textureProjGrad");
5043
4805
  if (isFrag) {
5044
4806
  shader = shader.replace(/\bgl_FragDepthEXT\b/g, "gl_FragDepth");
5045
- if (!ShaderFactory._has300Output(shader)) {
4807
+ if (!ShaderFactory._has300OutInFragReg.test(shader)) {
5046
4808
  var isMRT = /\bgl_FragData\[.+?\]/g.test(shader);
5047
4809
  if (isMRT) {
5048
4810
  shader = shader.replace(/\bgl_FragColor\b/g, "gl_FragData[0]");
5049
4811
  var result = shader.match(/\bgl_FragData\[.+?\]/g);
5050
- shader = this._replaceMRTShader(shader, result);
4812
+ shader = ShaderFactory._replaceMRTShader(shader, result);
5051
4813
  } else {
5052
4814
  shader = "out vec4 glFragColor;\n" + shader;
5053
4815
  shader = shader.replace(/\bgl_FragColor\b/g, "glFragColor");
@@ -5058,9 +4820,6 @@ var ShaderFactory = /*#__PURE__*/ function() {
5058
4820
  }
5059
4821
  return shader;
5060
4822
  };
5061
- ShaderFactory._has300Output = function _has300Output(fragmentShader) {
5062
- return ShaderFactory._has300OutInFragReg.test(fragmentShader);
5063
- };
5064
4823
  ShaderFactory._replaceMRTShader = function _replaceMRTShader(shader, result) {
5065
4824
  var declaration = "";
5066
4825
  var mrtIndexSet = new Set();
@@ -5078,7 +4837,8 @@ var ShaderFactory = /*#__PURE__*/ function() {
5078
4837
  };
5079
4838
  return ShaderFactory;
5080
4839
  }();
5081
- /** @internal */ ShaderFactory._shaderExtension = [
4840
+ ShaderFactory.includeMap = {};
4841
+ ShaderFactory.shaderExtension = [
5082
4842
  "GL_EXT_shader_texture_lod",
5083
4843
  "GL_OES_standard_derivatives",
5084
4844
  "GL_EXT_draw_buffers",
@@ -5086,8 +4846,8 @@ var ShaderFactory = /*#__PURE__*/ function() {
5086
4846
  ].map(function(e) {
5087
4847
  return "#extension " + e + " : enable\n";
5088
4848
  }).join("");
5089
- ShaderFactory._has300OutInFragReg = /\bout\s+(?:\w+\s+)?(?:vec4)\s+(?:\w+)\s*;/ // [layout(location = 0)] out [highp] vec4 [color];
5090
- ;
4849
+ // [layout(location = 0)] out [highp] vec4 [color];
4850
+ ShaderFactory._has300OutInFragReg = /\bout\s+(?:\w+\s+)?(?:vec4)\s+(?:\w+)\s*;/;
5091
4851
 
5092
4852
  /**
5093
4853
  * Shader tag key.
@@ -6205,147 +5965,6 @@ ShaderMacroProcessor._parsedFuncArgs = {
6205
5965
  end: 0
6206
5966
  };
6207
5967
 
6208
- var precisionStr = "\n #ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n precision highp int;\n #else\n precision mediump float;\n precision mediump int;\n #endif\n ";
6209
- /**
6210
- * Shader pass containing vertex and fragment source.
6211
- */ var ShaderPass = /*#__PURE__*/ function(ShaderPart) {
6212
- _inherits(ShaderPass, ShaderPart);
6213
- function ShaderPass(nameOrVertexSource, vertexSourceOrFragmentSourceOrInstructions, fragmentSourceOrTags, tagsOrPlatformTarget, tags) {
6214
- var _this;
6215
- _this = ShaderPart.call(this) || this, /** @internal */ _this._shaderPassId = 0, /** @internal */ _this._renderStateDataMap = {}, /** @internal */ _this._shaderProgramPools = [];
6216
- _this._shaderPassId = ShaderPass._shaderPassCounter++;
6217
- if (Array.isArray(vertexSourceOrFragmentSourceOrInstructions)) {
6218
- // Instructions overload: (name, vertexInst, fragInst, platformTarget, tags?)
6219
- _this._name = nameOrVertexSource;
6220
- _this._vertexShaderInstructions = vertexSourceOrFragmentSourceOrInstructions;
6221
- _this._fragmentShaderInstructions = fragmentSourceOrTags;
6222
- _this._platformTarget = tagsOrPlatformTarget;
6223
- tags = _extends({
6224
- pipelineStage: PipelineStage.Forward
6225
- }, tags);
6226
- } else if (typeof fragmentSourceOrTags === "string") {
6227
- // Named overload: (name, vertexSource, fragmentSource, tags?)
6228
- _this._name = nameOrVertexSource;
6229
- _this._vertexSource = vertexSourceOrFragmentSourceOrInstructions;
6230
- _this._fragmentSource = fragmentSourceOrTags;
6231
- tags = _extends({
6232
- pipelineStage: PipelineStage.Forward
6233
- }, tagsOrPlatformTarget);
6234
- } else {
6235
- // Unnamed overload: (vertexSource, fragmentSource, tags?)
6236
- _this._name = "Default";
6237
- _this._vertexSource = nameOrVertexSource;
6238
- _this._fragmentSource = vertexSourceOrFragmentSourceOrInstructions;
6239
- tags = _extends({
6240
- pipelineStage: PipelineStage.Forward
6241
- }, fragmentSourceOrTags);
6242
- }
6243
- for(var key in tags){
6244
- _this.setTag(key, tags[key]);
6245
- }
6246
- return _this;
6247
- }
6248
- var _proto = ShaderPass.prototype;
6249
- /**
6250
- * @internal
6251
- */ _proto._getShaderProgram = function _getShaderProgram(engine, macroCollection) {
6252
- var shaderProgramPool = engine._getShaderProgramPool(this._shaderPassId, this._shaderProgramPools);
6253
- var shaderProgram = shaderProgramPool.get(macroCollection);
6254
- if (shaderProgram) {
6255
- return shaderProgram;
6256
- }
6257
- shaderProgram = this._getCanonicalShaderProgram(engine, macroCollection);
6258
- shaderProgramPool.cache(shaderProgram);
6259
- return shaderProgram;
6260
- };
6261
- /**
6262
- * @internal
6263
- */ _proto._destroy = function _destroy() {
6264
- var shaderProgramPools = this._shaderProgramPools;
6265
- for(var i = 0, n = shaderProgramPools.length; i < n; i++){
6266
- var shaderProgramPool = shaderProgramPools[i];
6267
- shaderProgramPool._destroy();
6268
- delete shaderProgramPool.engine._shaderProgramPools[this._shaderPassId];
6269
- }
6270
- // Clear array storing multiple engine shader program pools
6271
- shaderProgramPools.length = 0;
6272
- };
6273
- _proto._getCanonicalShaderProgram = function _getCanonicalShaderProgram(engine, macroCollection) {
6274
- var _ref = this._platformTarget != undefined ? this._compileShaderLabSource(engine, macroCollection) : this._compilePlatformSource(engine, macroCollection), vertexSource = _ref.vertexSource, fragmentSource = _ref.fragmentSource;
6275
- return new ShaderProgram(engine, vertexSource, fragmentSource);
6276
- };
6277
- _proto._compilePlatformSource = function _compilePlatformSource(engine, macroCollection) {
6278
- return ShaderFactory.compilePlatformSource(engine, macroCollection, this._vertexSource, this._fragmentSource);
6279
- };
6280
- _proto._compileShaderLabSource = function _compileShaderLabSource(engine, macroCollection) {
6281
- var isWebGL2 = engine._hardwareRenderer.isWebGL2;
6282
- var shaderMacroList = ShaderPass._shaderMacroList;
6283
- shaderMacroList.length = 0;
6284
- ShaderMacro._getMacrosElements(macroCollection, shaderMacroList);
6285
- shaderMacroList.push(ShaderMacro.getByName(isWebGL2 ? "GRAPHICS_API_WEBGL2" : "GRAPHICS_API_WEBGL1"));
6286
- if (engine._hardwareRenderer.canIUse(GLCapabilityType.shaderTextureLod)) {
6287
- shaderMacroList.push(ShaderMacro.getByName("HAS_TEX_LOD"));
6288
- }
6289
- if (engine._hardwareRenderer.canIUse(GLCapabilityType.standardDerivatives)) {
6290
- shaderMacroList.push(ShaderMacro.getByName("HAS_DERIVATIVES"));
6291
- }
6292
- var macroMap = ShaderPass._macroMap;
6293
- macroMap.clear();
6294
- for(var i = 0, n = shaderMacroList.length; i < n; i++){
6295
- var macro = shaderMacroList[i];
6296
- var _macro_value;
6297
- macroMap.set(macro.name, (_macro_value = macro.value) != null ? _macro_value : "");
6298
- }
6299
- var vertexSource = ShaderMacroProcessor.evaluate(this._vertexShaderInstructions, macroMap);
6300
- var fragmentSource = ShaderMacroProcessor.evaluate(this._fragmentShaderInstructions, macroMap);
6301
- if (isWebGL2 && this._platformTarget === ShaderLanguage.GLSLES100) {
6302
- vertexSource = ShaderFactory.convertTo300(vertexSource);
6303
- fragmentSource = ShaderFactory.convertTo300(fragmentSource, true);
6304
- }
6305
- var versionStr = isWebGL2 ? "#version 300 es" : "#version 100";
6306
- return {
6307
- vertexSource: " " + versionStr + "\n " + vertexSource + "\n ",
6308
- fragmentSource: " " + versionStr + "\n " + (isWebGL2 ? "" : ShaderFactory._shaderExtension) + "\n " + precisionStr + "\n " + fragmentSource + "\n "
6309
- };
6310
- };
6311
- return ShaderPass;
6312
- }(ShaderPart);
6313
- /** @internal */ ShaderPass._shaderPassCounter = 0;
6314
- /** @internal */ ShaderPass._shaderRootPath = "shaders://root/";
6315
- ShaderPass._shaderMacroList = [];
6316
- ShaderPass._macroMap = new Map();
6317
-
6318
- /**
6319
- * Sub shader.
6320
- */ var SubShader = /*#__PURE__*/ function(ShaderPart) {
6321
- _inherits(SubShader, ShaderPart);
6322
- function SubShader(name, passes, tags) {
6323
- var _this;
6324
- _this = ShaderPart.call(this) || this;
6325
- _this._name = name;
6326
- var passCount = passes.length;
6327
- if (passCount < 1) {
6328
- throw " count must large than 0.";
6329
- }
6330
- _this._passes = passes.slice();
6331
- for(var key in tags){
6332
- _this.setTag(key, tags[key]);
6333
- }
6334
- return _this;
6335
- }
6336
- _create_class(SubShader, [
6337
- {
6338
- key: "passes",
6339
- get: /**
6340
- * Sub shader passes.
6341
- */ function get() {
6342
- return this._passes;
6343
- }
6344
- }
6345
- ]);
6346
- return SubShader;
6347
- }(ShaderPart);
6348
-
6349
5968
  /**
6350
5969
  * The blend state of the render target.
6351
5970
  */ var RenderTargetBlendState = function RenderTargetBlendState() {
@@ -6371,55 +5990,59 @@ ShaderPass._macroMap = new Map();
6371
5990
  /**
6372
5991
  * @internal
6373
5992
  */ _proto._applyShaderDataValue = function _applyShaderDataValue(renderStateDataMap, shaderData) {
6374
- var blendState = this.targetBlendState;
6375
- var enable0Property = renderStateDataMap[RenderStateElementKey.BlendStateEnabled0];
6376
- if (enable0Property !== undefined) {
6377
- var enabled = shaderData.getFloat(enable0Property);
6378
- blendState.enabled = enabled !== undefined ? !!enabled : false;
6379
- }
6380
- var colorBlendOperation0Property = renderStateDataMap[RenderStateElementKey.BlendStateColorBlendOperation0];
6381
- if (colorBlendOperation0Property !== undefined) {
5993
+ var target = this.targetBlendState;
5994
+ var enabledProp = renderStateDataMap[RenderStateElementKey.BlendStateEnabled0];
5995
+ if (enabledProp !== undefined) {
5996
+ var enabled = shaderData.getFloat(enabledProp);
5997
+ target.enabled = enabled !== undefined ? !!enabled : false;
5998
+ }
5999
+ var colorBlendOperationProp = renderStateDataMap[RenderStateElementKey.BlendStateColorBlendOperation0];
6000
+ if (colorBlendOperationProp !== undefined) {
6382
6001
  var _shaderData_getFloat;
6383
- blendState.colorBlendOperation = (_shaderData_getFloat = shaderData.getFloat(colorBlendOperation0Property)) != null ? _shaderData_getFloat : BlendOperation.Add;
6002
+ target.colorBlendOperation = (_shaderData_getFloat = shaderData.getFloat(colorBlendOperationProp)) != null ? _shaderData_getFloat : BlendOperation.Add;
6384
6003
  }
6385
- var alphaBlendOperation0Property = renderStateDataMap[RenderStateElementKey.BlendStateAlphaBlendOperation0];
6386
- if (alphaBlendOperation0Property !== undefined) {
6004
+ var alphaBlendOperationProp = renderStateDataMap[RenderStateElementKey.BlendStateAlphaBlendOperation0];
6005
+ if (alphaBlendOperationProp !== undefined) {
6387
6006
  var _shaderData_getFloat1;
6388
- blendState.alphaBlendOperation = (_shaderData_getFloat1 = shaderData.getFloat(alphaBlendOperation0Property)) != null ? _shaderData_getFloat1 : BlendOperation.Add;
6007
+ target.alphaBlendOperation = (_shaderData_getFloat1 = shaderData.getFloat(alphaBlendOperationProp)) != null ? _shaderData_getFloat1 : BlendOperation.Add;
6389
6008
  }
6390
- var sourceColorBlendFactor0Property = renderStateDataMap[RenderStateElementKey.BlendStateSourceColorBlendFactor0];
6391
- if (sourceColorBlendFactor0Property !== undefined) {
6009
+ var sourceColorBlendFactorProp = renderStateDataMap[RenderStateElementKey.BlendStateSourceColorBlendFactor0];
6010
+ if (sourceColorBlendFactorProp !== undefined) {
6392
6011
  var _shaderData_getFloat2;
6393
- blendState.sourceColorBlendFactor = (_shaderData_getFloat2 = shaderData.getFloat(sourceColorBlendFactor0Property)) != null ? _shaderData_getFloat2 : BlendFactor.One;
6012
+ target.sourceColorBlendFactor = (_shaderData_getFloat2 = shaderData.getFloat(sourceColorBlendFactorProp)) != null ? _shaderData_getFloat2 : BlendFactor.One;
6394
6013
  }
6395
- var sourceAlphaBlendFactor0Property = renderStateDataMap[RenderStateElementKey.BlendStateSourceAlphaBlendFactor0];
6396
- if (sourceAlphaBlendFactor0Property !== undefined) {
6014
+ var sourceAlphaBlendFactorProp = renderStateDataMap[RenderStateElementKey.BlendStateSourceAlphaBlendFactor0];
6015
+ if (sourceAlphaBlendFactorProp !== undefined) {
6397
6016
  var _shaderData_getFloat3;
6398
- blendState.sourceAlphaBlendFactor = (_shaderData_getFloat3 = shaderData.getFloat(sourceAlphaBlendFactor0Property)) != null ? _shaderData_getFloat3 : BlendFactor.One;
6017
+ target.sourceAlphaBlendFactor = (_shaderData_getFloat3 = shaderData.getFloat(sourceAlphaBlendFactorProp)) != null ? _shaderData_getFloat3 : BlendFactor.One;
6399
6018
  }
6400
- var destinationColorBlendFactor0Property = renderStateDataMap[RenderStateElementKey.BlendStateDestinationColorBlendFactor0];
6401
- if (destinationColorBlendFactor0Property !== undefined) {
6019
+ var destinationColorBlendFactorProp = renderStateDataMap[RenderStateElementKey.BlendStateDestinationColorBlendFactor0];
6020
+ if (destinationColorBlendFactorProp !== undefined) {
6402
6021
  var _shaderData_getFloat4;
6403
- blendState.destinationColorBlendFactor = (_shaderData_getFloat4 = shaderData.getFloat(destinationColorBlendFactor0Property)) != null ? _shaderData_getFloat4 : BlendFactor.Zero;
6022
+ target.destinationColorBlendFactor = (_shaderData_getFloat4 = shaderData.getFloat(destinationColorBlendFactorProp)) != null ? _shaderData_getFloat4 : BlendFactor.Zero;
6404
6023
  }
6405
- var destinationAlphaBlendFactor0Property = renderStateDataMap[RenderStateElementKey.BlendStateDestinationAlphaBlendFactor0];
6406
- if (destinationAlphaBlendFactor0Property !== undefined) {
6024
+ var destinationAlphaBlendFactorProp = renderStateDataMap[RenderStateElementKey.BlendStateDestinationAlphaBlendFactor0];
6025
+ if (destinationAlphaBlendFactorProp !== undefined) {
6407
6026
  var _shaderData_getFloat5;
6408
- blendState.destinationAlphaBlendFactor = (_shaderData_getFloat5 = shaderData.getFloat(destinationAlphaBlendFactor0Property)) != null ? _shaderData_getFloat5 : BlendFactor.Zero;
6027
+ target.destinationAlphaBlendFactor = (_shaderData_getFloat5 = shaderData.getFloat(destinationAlphaBlendFactorProp)) != null ? _shaderData_getFloat5 : BlendFactor.Zero;
6409
6028
  }
6410
- var colorWriteMask0Property = renderStateDataMap[RenderStateElementKey.BlendStateColorWriteMask0];
6411
- if (colorWriteMask0Property !== undefined) {
6029
+ var colorWriteMaskProp = renderStateDataMap[RenderStateElementKey.BlendStateColorWriteMask0];
6030
+ if (colorWriteMaskProp !== undefined) {
6412
6031
  var _shaderData_getFloat6;
6413
- blendState.colorWriteMask = (_shaderData_getFloat6 = shaderData.getFloat(colorWriteMask0Property)) != null ? _shaderData_getFloat6 : ColorWriteMask.All;
6032
+ target.colorWriteMask = (_shaderData_getFloat6 = shaderData.getFloat(colorWriteMaskProp)) != null ? _shaderData_getFloat6 : ColorWriteMask.All;
6414
6033
  }
6415
- var blendColorProperty = renderStateDataMap[RenderStateElementKey.BlendStateBlendColor];
6416
- if (blendColorProperty !== undefined) {
6417
- var blendColor = shaderData.getColor(blendColorProperty);
6418
- blendColor !== undefined && this.blendColor.copyFrom(blendColor);
6034
+ var blendColorProp = renderStateDataMap[RenderStateElementKey.BlendStateBlendColor];
6035
+ if (blendColorProp !== undefined) {
6036
+ var blendColor = shaderData.getColor(blendColorProp);
6037
+ if (blendColor) {
6038
+ this.blendColor.copyFrom(blendColor);
6039
+ } else {
6040
+ this.blendColor.set(0, 0, 0, 0);
6041
+ }
6419
6042
  }
6420
- var alphaToCoverageProperty = renderStateDataMap[RenderStateElementKey.BlendStateAlphaToCoverage];
6421
- if (alphaToCoverageProperty !== undefined) {
6422
- var alphaToCoverage = shaderData.getFloat(alphaToCoverageProperty);
6043
+ var alphaToCoverageProp = renderStateDataMap[RenderStateElementKey.BlendStateAlphaToCoverage];
6044
+ if (alphaToCoverageProp !== undefined) {
6045
+ var alphaToCoverage = shaderData.getFloat(alphaToCoverageProp);
6423
6046
  this.alphaToCoverage = alphaToCoverage !== undefined ? !!alphaToCoverage : false;
6424
6047
  }
6425
6048
  };
@@ -6556,20 +6179,20 @@ __decorate([
6556
6179
  /**
6557
6180
  * @internal
6558
6181
  */ _proto._applyShaderDataValue = function _applyShaderDataValue(renderStateDataMap, shaderData) {
6559
- var enableProperty = renderStateDataMap[RenderStateElementKey.DepthStateEnabled];
6560
- if (enableProperty !== undefined) {
6561
- var enabled = shaderData.getFloat(enableProperty);
6562
- this.enabled = enabled !== undefined ? !!enabled : false;
6563
- }
6564
- var writeEnabledProperty = renderStateDataMap[RenderStateElementKey.DepthStateWriteEnabled];
6565
- if (writeEnabledProperty !== undefined) {
6566
- var writeEnabled = shaderData.getFloat(writeEnabledProperty);
6567
- this.writeEnabled = writeEnabled !== undefined ? !!writeEnabled : false;
6568
- }
6569
- var compareFunctionProperty = renderStateDataMap[RenderStateElementKey.DepthStateCompareFunction];
6570
- if (compareFunctionProperty !== undefined) {
6182
+ var enabledProp = renderStateDataMap[RenderStateElementKey.DepthStateEnabled];
6183
+ if (enabledProp !== undefined) {
6184
+ var enabled = shaderData.getFloat(enabledProp);
6185
+ this.enabled = enabled !== undefined ? !!enabled : true;
6186
+ }
6187
+ var writeEnabledProp = renderStateDataMap[RenderStateElementKey.DepthStateWriteEnabled];
6188
+ if (writeEnabledProp !== undefined) {
6189
+ var writeEnabled = shaderData.getFloat(writeEnabledProp);
6190
+ this.writeEnabled = writeEnabled !== undefined ? !!writeEnabled : true;
6191
+ }
6192
+ var compareFunctionProp = renderStateDataMap[RenderStateElementKey.DepthStateCompareFunction];
6193
+ if (compareFunctionProp !== undefined) {
6571
6194
  var _shaderData_getFloat;
6572
- this.compareFunction = (_shaderData_getFloat = shaderData.getFloat(compareFunctionProperty)) != null ? _shaderData_getFloat : CompareFunction.Less;
6195
+ this.compareFunction = (_shaderData_getFloat = shaderData.getFloat(compareFunctionProp)) != null ? _shaderData_getFloat : CompareFunction.Less;
6573
6196
  }
6574
6197
  };
6575
6198
  /**
@@ -6644,20 +6267,20 @@ __decorate([
6644
6267
  /**
6645
6268
  * @internal
6646
6269
  */ _proto._applyShaderDataValue = function _applyShaderDataValue(renderStateDataMap, shaderData) {
6647
- var cullModeProperty = renderStateDataMap[RenderStateElementKey.RasterStateCullMode];
6648
- if (cullModeProperty !== undefined) {
6270
+ var cullModeProp = renderStateDataMap[RenderStateElementKey.RasterStateCullMode];
6271
+ if (cullModeProp !== undefined) {
6649
6272
  var _shaderData_getFloat;
6650
- this.cullMode = (_shaderData_getFloat = shaderData.getFloat(cullModeProperty)) != null ? _shaderData_getFloat : CullMode.Back;
6273
+ this.cullMode = (_shaderData_getFloat = shaderData.getFloat(cullModeProp)) != null ? _shaderData_getFloat : CullMode.Back;
6651
6274
  }
6652
- var depthBiasProperty = renderStateDataMap[RenderStateElementKey.RasterStateDepthBias];
6653
- if (depthBiasProperty !== undefined) {
6275
+ var depthBiasProp = renderStateDataMap[RenderStateElementKey.RasterStateDepthBias];
6276
+ if (depthBiasProp !== undefined) {
6654
6277
  var _shaderData_getFloat1;
6655
- this.depthBias = (_shaderData_getFloat1 = shaderData.getFloat(depthBiasProperty)) != null ? _shaderData_getFloat1 : 0;
6278
+ this.depthBias = (_shaderData_getFloat1 = shaderData.getFloat(depthBiasProp)) != null ? _shaderData_getFloat1 : 0;
6656
6279
  }
6657
- var slopeScaledDepthBiasProperty = renderStateDataMap[RenderStateElementKey.RasterStateSlopeScaledDepthBias];
6658
- if (slopeScaledDepthBiasProperty !== undefined) {
6280
+ var slopeScaledDepthBiasProp = renderStateDataMap[RenderStateElementKey.RasterStateSlopeScaledDepthBias];
6281
+ if (slopeScaledDepthBiasProp !== undefined) {
6659
6282
  var _shaderData_getFloat2;
6660
- this.slopeScaledDepthBias = (_shaderData_getFloat2 = shaderData.getFloat(slopeScaledDepthBiasProperty)) != null ? _shaderData_getFloat2 : 0;
6283
+ this.slopeScaledDepthBias = (_shaderData_getFloat2 = shaderData.getFloat(slopeScaledDepthBiasProp)) != null ? _shaderData_getFloat2 : 0;
6661
6284
  }
6662
6285
  };
6663
6286
  /**
@@ -6738,65 +6361,65 @@ __decorate([
6738
6361
  /**
6739
6362
  * @internal
6740
6363
  */ _proto._applyShaderDataValue = function _applyShaderDataValue(renderStateDataMap, shaderData) {
6741
- var enableProperty = renderStateDataMap[RenderStateElementKey.StencilStateEnabled];
6742
- if (enableProperty !== undefined) {
6743
- var enabled = shaderData.getFloat(enableProperty);
6364
+ var enabledProp = renderStateDataMap[RenderStateElementKey.StencilStateEnabled];
6365
+ if (enabledProp !== undefined) {
6366
+ var enabled = shaderData.getFloat(enabledProp);
6744
6367
  this.enabled = enabled !== undefined ? !!enabled : false;
6745
6368
  }
6746
- var referenceValueProperty = renderStateDataMap[RenderStateElementKey.StencilStateReferenceValue];
6747
- if (referenceValueProperty !== undefined) {
6369
+ var referenceValueProp = renderStateDataMap[RenderStateElementKey.StencilStateReferenceValue];
6370
+ if (referenceValueProp !== undefined) {
6748
6371
  var _shaderData_getFloat;
6749
- this.referenceValue = (_shaderData_getFloat = shaderData.getFloat(referenceValueProperty)) != null ? _shaderData_getFloat : 0;
6372
+ this.referenceValue = (_shaderData_getFloat = shaderData.getFloat(referenceValueProp)) != null ? _shaderData_getFloat : 0;
6750
6373
  }
6751
- var maskProperty = renderStateDataMap[RenderStateElementKey.StencilStateMask];
6752
- if (maskProperty !== undefined) {
6374
+ var maskProp = renderStateDataMap[RenderStateElementKey.StencilStateMask];
6375
+ if (maskProp !== undefined) {
6753
6376
  var _shaderData_getFloat1;
6754
- this.mask = (_shaderData_getFloat1 = shaderData.getFloat(maskProperty)) != null ? _shaderData_getFloat1 : 0xff;
6377
+ this.mask = (_shaderData_getFloat1 = shaderData.getFloat(maskProp)) != null ? _shaderData_getFloat1 : 0xff;
6755
6378
  }
6756
- var writeMaskProperty = renderStateDataMap[RenderStateElementKey.StencilStateWriteMask];
6757
- if (writeMaskProperty !== undefined) {
6379
+ var writeMaskProp = renderStateDataMap[RenderStateElementKey.StencilStateWriteMask];
6380
+ if (writeMaskProp !== undefined) {
6758
6381
  var _shaderData_getFloat2;
6759
- this.writeMask = (_shaderData_getFloat2 = shaderData.getFloat(writeMaskProperty)) != null ? _shaderData_getFloat2 : 0xff;
6382
+ this.writeMask = (_shaderData_getFloat2 = shaderData.getFloat(writeMaskProp)) != null ? _shaderData_getFloat2 : 0xff;
6760
6383
  }
6761
- var compareFunctionFrontProperty = renderStateDataMap[RenderStateElementKey.StencilStateCompareFunctionFront];
6762
- if (compareFunctionFrontProperty !== undefined) {
6384
+ var compareFunctionFrontProp = renderStateDataMap[RenderStateElementKey.StencilStateCompareFunctionFront];
6385
+ if (compareFunctionFrontProp !== undefined) {
6763
6386
  var _shaderData_getFloat3;
6764
- this.compareFunctionFront = (_shaderData_getFloat3 = shaderData.getFloat(compareFunctionFrontProperty)) != null ? _shaderData_getFloat3 : CompareFunction.Always;
6387
+ this.compareFunctionFront = (_shaderData_getFloat3 = shaderData.getFloat(compareFunctionFrontProp)) != null ? _shaderData_getFloat3 : CompareFunction.Always;
6765
6388
  }
6766
- var compareFunctionBackProperty = renderStateDataMap[RenderStateElementKey.StencilStateCompareFunctionBack];
6767
- if (compareFunctionBackProperty !== undefined) {
6389
+ var compareFunctionBackProp = renderStateDataMap[RenderStateElementKey.StencilStateCompareFunctionBack];
6390
+ if (compareFunctionBackProp !== undefined) {
6768
6391
  var _shaderData_getFloat4;
6769
- this.compareFunctionBack = (_shaderData_getFloat4 = shaderData.getFloat(compareFunctionBackProperty)) != null ? _shaderData_getFloat4 : CompareFunction.Always;
6392
+ this.compareFunctionBack = (_shaderData_getFloat4 = shaderData.getFloat(compareFunctionBackProp)) != null ? _shaderData_getFloat4 : CompareFunction.Always;
6770
6393
  }
6771
- var passOperationFrontProperty = renderStateDataMap[RenderStateElementKey.StencilStatePassOperationFront];
6772
- if (passOperationFrontProperty !== undefined) {
6394
+ var passOperationFrontProp = renderStateDataMap[RenderStateElementKey.StencilStatePassOperationFront];
6395
+ if (passOperationFrontProp !== undefined) {
6773
6396
  var _shaderData_getFloat5;
6774
- this.passOperationFront = (_shaderData_getFloat5 = shaderData.getFloat(passOperationFrontProperty)) != null ? _shaderData_getFloat5 : StencilOperation.Keep;
6397
+ this.passOperationFront = (_shaderData_getFloat5 = shaderData.getFloat(passOperationFrontProp)) != null ? _shaderData_getFloat5 : StencilOperation.Keep;
6775
6398
  }
6776
- var passOperationBackProperty = renderStateDataMap[RenderStateElementKey.StencilStatePassOperationBack];
6777
- if (passOperationBackProperty !== undefined) {
6399
+ var passOperationBackProp = renderStateDataMap[RenderStateElementKey.StencilStatePassOperationBack];
6400
+ if (passOperationBackProp !== undefined) {
6778
6401
  var _shaderData_getFloat6;
6779
- this.passOperationBack = (_shaderData_getFloat6 = shaderData.getFloat(passOperationBackProperty)) != null ? _shaderData_getFloat6 : StencilOperation.Keep;
6402
+ this.passOperationBack = (_shaderData_getFloat6 = shaderData.getFloat(passOperationBackProp)) != null ? _shaderData_getFloat6 : StencilOperation.Keep;
6780
6403
  }
6781
- var failOperationFrontProperty = renderStateDataMap[RenderStateElementKey.StencilStateFailOperationFront];
6782
- if (failOperationFrontProperty !== undefined) {
6404
+ var failOperationFrontProp = renderStateDataMap[RenderStateElementKey.StencilStateFailOperationFront];
6405
+ if (failOperationFrontProp !== undefined) {
6783
6406
  var _shaderData_getFloat7;
6784
- this.failOperationFront = (_shaderData_getFloat7 = shaderData.getFloat(failOperationFrontProperty)) != null ? _shaderData_getFloat7 : StencilOperation.Keep;
6407
+ this.failOperationFront = (_shaderData_getFloat7 = shaderData.getFloat(failOperationFrontProp)) != null ? _shaderData_getFloat7 : StencilOperation.Keep;
6785
6408
  }
6786
- var failOperationBackProperty = renderStateDataMap[RenderStateElementKey.StencilStateFailOperationBack];
6787
- if (failOperationBackProperty !== undefined) {
6409
+ var failOperationBackProp = renderStateDataMap[RenderStateElementKey.StencilStateFailOperationBack];
6410
+ if (failOperationBackProp !== undefined) {
6788
6411
  var _shaderData_getFloat8;
6789
- this.failOperationBack = (_shaderData_getFloat8 = shaderData.getFloat(failOperationBackProperty)) != null ? _shaderData_getFloat8 : StencilOperation.Keep;
6412
+ this.failOperationBack = (_shaderData_getFloat8 = shaderData.getFloat(failOperationBackProp)) != null ? _shaderData_getFloat8 : StencilOperation.Keep;
6790
6413
  }
6791
- var zFailOperationFrontProperty = renderStateDataMap[RenderStateElementKey.StencilStateZFailOperationFront];
6792
- if (zFailOperationFrontProperty !== undefined) {
6414
+ var zFailOperationFrontProp = renderStateDataMap[RenderStateElementKey.StencilStateZFailOperationFront];
6415
+ if (zFailOperationFrontProp !== undefined) {
6793
6416
  var _shaderData_getFloat9;
6794
- this.zFailOperationFront = (_shaderData_getFloat9 = shaderData.getFloat(zFailOperationFrontProperty)) != null ? _shaderData_getFloat9 : StencilOperation.Keep;
6417
+ this.zFailOperationFront = (_shaderData_getFloat9 = shaderData.getFloat(zFailOperationFrontProp)) != null ? _shaderData_getFloat9 : StencilOperation.Keep;
6795
6418
  }
6796
- var zFailOperationBackProperty = renderStateDataMap[RenderStateElementKey.StencilStateZFailOperationBack];
6797
- if (zFailOperationBackProperty !== undefined) {
6419
+ var zFailOperationBackProp = renderStateDataMap[RenderStateElementKey.StencilStateZFailOperationBack];
6420
+ if (zFailOperationBackProp !== undefined) {
6798
6421
  var _shaderData_getFloat10;
6799
- this.zFailOperationBack = (_shaderData_getFloat10 = shaderData.getFloat(zFailOperationBackProperty)) != null ? _shaderData_getFloat10 : StencilOperation.Keep;
6422
+ this.zFailOperationBack = (_shaderData_getFloat10 = shaderData.getFloat(zFailOperationBackProp)) != null ? _shaderData_getFloat10 : StencilOperation.Keep;
6800
6423
  }
6801
6424
  };
6802
6425
  /**
@@ -6933,8 +6556,10 @@ __decorate([
6933
6556
  /**
6934
6557
  * @internal
6935
6558
  */ _proto._applyStates = function _applyStates(engine, frontFaceInvert, renderStateDataMap, shaderData, customRenderStates) {
6936
- // @todo: Should merge when we can delete material render state
6937
- renderStateDataMap && this._applyStatesByShaderData(renderStateDataMap, shaderData);
6559
+ this.blendState._applyShaderDataValue(renderStateDataMap, shaderData);
6560
+ this.depthState._applyShaderDataValue(renderStateDataMap, shaderData);
6561
+ this.stencilState._applyShaderDataValue(renderStateDataMap, shaderData);
6562
+ this.rasterState._applyShaderDataValue(renderStateDataMap, shaderData);
6938
6563
  var hardwareRenderer = engine._hardwareRenderer;
6939
6564
  var lastRenderState = engine._lastRenderState;
6940
6565
  var context = engine._renderContext;
@@ -6945,21 +6570,13 @@ __decorate([
6945
6570
  };
6946
6571
  /**
6947
6572
  * @internal
6948
- * @todo Should merge when we can delete material render state
6949
6573
  */ _proto._getRenderQueueByShaderData = function _getRenderQueueByShaderData(renderStateDataMap, shaderData) {
6950
- var renderQueueType = renderStateDataMap[RenderStateElementKey.RenderQueueType];
6951
- if (renderQueueType === undefined) {
6952
- return this.renderQueueType;
6953
- } else {
6954
- var _shaderData_getFloat;
6955
- return (_shaderData_getFloat = shaderData.getFloat(renderQueueType)) != null ? _shaderData_getFloat : RenderQueueType.Opaque;
6574
+ var renderQueueTypeProp = renderStateDataMap[RenderStateElementKey.RenderQueueType];
6575
+ if (renderQueueTypeProp !== undefined) {
6576
+ var renderQueueType = shaderData.getFloat(renderQueueTypeProp);
6577
+ if (renderQueueType !== undefined) return renderQueueType;
6956
6578
  }
6957
- };
6958
- _proto._applyStatesByShaderData = function _applyStatesByShaderData(renderStateDataMap, shaderData) {
6959
- this.blendState._applyShaderDataValue(renderStateDataMap, shaderData);
6960
- this.depthState._applyShaderDataValue(renderStateDataMap, shaderData);
6961
- this.stencilState._applyShaderDataValue(renderStateDataMap, shaderData);
6962
- this.rasterState._applyShaderDataValue(renderStateDataMap, shaderData);
6579
+ return this.renderQueueType;
6963
6580
  };
6964
6581
  return RenderState;
6965
6582
  }();
@@ -6976,6 +6593,125 @@ __decorate([
6976
6593
  deepClone
6977
6594
  ], RenderState.prototype, "rasterState", void 0);
6978
6595
 
6596
+ var precisionStr = "\n #ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n precision highp int;\n #else\n precision mediump float;\n precision mediump int;\n #endif\n ";
6597
+ /**
6598
+ * Shader pass containing vertex and fragment source.
6599
+ */ var ShaderPass = /*#__PURE__*/ function(ShaderPart) {
6600
+ _inherits(ShaderPass, ShaderPart);
6601
+ function ShaderPass(name, vertexShaderInstructions, fragmentShaderInstructions, platformTarget, tags) {
6602
+ var _this;
6603
+ _this = ShaderPart.call(this) || this, /** @internal */ _this._shaderPassId = 0, /** @internal Pass-level render state — always present, populated from ShaderLab declarations. */ _this._renderState = new RenderState(), /** @internal */ _this._renderStateDataMap = {}, /** @internal */ _this._shaderProgramPools = [];
6604
+ _this._shaderPassId = ShaderPass._shaderPassCounter++;
6605
+ _this._name = name;
6606
+ _this._vertexShaderInstructions = vertexShaderInstructions;
6607
+ _this._fragmentShaderInstructions = fragmentShaderInstructions;
6608
+ _this._platformTarget = platformTarget;
6609
+ var mergedTags = _extends({
6610
+ pipelineStage: PipelineStage.Forward
6611
+ }, tags);
6612
+ for(var key in mergedTags){
6613
+ _this.setTag(key, mergedTags[key]);
6614
+ }
6615
+ return _this;
6616
+ }
6617
+ var _proto = ShaderPass.prototype;
6618
+ /**
6619
+ * @internal
6620
+ */ _proto._getShaderProgram = function _getShaderProgram(engine, macroCollection) {
6621
+ var shaderProgramPool = engine._getShaderProgramPool(this._shaderPassId, this._shaderProgramPools);
6622
+ var shaderProgram = shaderProgramPool.get(macroCollection);
6623
+ if (shaderProgram) {
6624
+ return shaderProgram;
6625
+ }
6626
+ shaderProgram = this._getCanonicalShaderProgram(engine, macroCollection);
6627
+ shaderProgramPool.cache(shaderProgram);
6628
+ return shaderProgram;
6629
+ };
6630
+ /**
6631
+ * @internal
6632
+ */ _proto._destroy = function _destroy() {
6633
+ var shaderProgramPools = this._shaderProgramPools;
6634
+ for(var i = 0, n = shaderProgramPools.length; i < n; i++){
6635
+ var shaderProgramPool = shaderProgramPools[i];
6636
+ shaderProgramPool._destroy();
6637
+ delete shaderProgramPool.engine._shaderProgramPools[this._shaderPassId];
6638
+ }
6639
+ // Clear array storing multiple engine shader program pools
6640
+ shaderProgramPools.length = 0;
6641
+ };
6642
+ _proto._getCanonicalShaderProgram = function _getCanonicalShaderProgram(engine, macroCollection) {
6643
+ var _this__compileShaderSource = this._compileShaderSource(engine, macroCollection), vertexSource = _this__compileShaderSource.vertexSource, fragmentSource = _this__compileShaderSource.fragmentSource;
6644
+ return new ShaderProgram(engine, vertexSource, fragmentSource, this._feedbackVaryings);
6645
+ };
6646
+ _proto._compileShaderSource = function _compileShaderSource(engine, macroCollection) {
6647
+ var isWebGL2 = engine._hardwareRenderer.isWebGL2;
6648
+ var shaderMacroList = ShaderPass._shaderMacroList;
6649
+ shaderMacroList.length = 0;
6650
+ ShaderMacro._getMacrosElements(macroCollection, shaderMacroList);
6651
+ shaderMacroList.push(ShaderMacro.getByName(isWebGL2 ? "GRAPHICS_API_WEBGL2" : "GRAPHICS_API_WEBGL1"));
6652
+ if (engine._hardwareRenderer.canIUse(GLCapabilityType.shaderTextureLod)) {
6653
+ shaderMacroList.push(ShaderMacro.getByName("HAS_TEX_LOD"));
6654
+ }
6655
+ if (engine._hardwareRenderer.canIUse(GLCapabilityType.standardDerivatives)) {
6656
+ shaderMacroList.push(ShaderMacro.getByName("HAS_DERIVATIVES"));
6657
+ }
6658
+ var macroMap = ShaderPass._macroMap;
6659
+ macroMap.clear();
6660
+ for(var i = 0, n = shaderMacroList.length; i < n; i++){
6661
+ var macro = shaderMacroList[i];
6662
+ var _macro_value;
6663
+ macroMap.set(macro.name, (_macro_value = macro.value) != null ? _macro_value : "");
6664
+ }
6665
+ var vertexSource = ShaderMacroProcessor.evaluate(this._vertexShaderInstructions, macroMap);
6666
+ var fragmentSource = ShaderMacroProcessor.evaluate(this._fragmentShaderInstructions, macroMap);
6667
+ if (isWebGL2 && this._platformTarget === ShaderLanguage.GLSLES100) {
6668
+ vertexSource = ShaderFactory.convertTo300(vertexSource);
6669
+ fragmentSource = ShaderFactory.convertTo300(fragmentSource, true);
6670
+ }
6671
+ var versionStr = isWebGL2 ? "#version 300 es" : "#version 100";
6672
+ return {
6673
+ vertexSource: " " + versionStr + "\n " + vertexSource + "\n ",
6674
+ fragmentSource: " " + versionStr + "\n " + (isWebGL2 ? "" : ShaderFactory.shaderExtension) + "\n " + precisionStr + "\n " + fragmentSource + "\n "
6675
+ };
6676
+ };
6677
+ return ShaderPass;
6678
+ }(ShaderPart);
6679
+ /** @internal */ ShaderPass._shaderPassCounter = 0;
6680
+ /** @internal */ ShaderPass._shaderRootPath = "shaders://root/";
6681
+ ShaderPass._shaderMacroList = [];
6682
+ ShaderPass._macroMap = new Map();
6683
+
6684
+ /**
6685
+ * Sub shader.
6686
+ */ var SubShader = /*#__PURE__*/ function(ShaderPart) {
6687
+ _inherits(SubShader, ShaderPart);
6688
+ function SubShader(name, passes, tags) {
6689
+ var _this;
6690
+ _this = ShaderPart.call(this) || this;
6691
+ _this._name = name;
6692
+ var passCount = passes.length;
6693
+ if (passCount < 1) {
6694
+ throw " count must large than 0.";
6695
+ }
6696
+ _this._passes = passes.slice();
6697
+ for(var key in tags){
6698
+ _this.setTag(key, tags[key]);
6699
+ }
6700
+ return _this;
6701
+ }
6702
+ _create_class(SubShader, [
6703
+ {
6704
+ key: "passes",
6705
+ get: /**
6706
+ * Sub shader passes.
6707
+ */ function get() {
6708
+ return this._passes;
6709
+ }
6710
+ }
6711
+ ]);
6712
+ return SubShader;
6713
+ }(ShaderPart);
6714
+
6979
6715
  /**
6980
6716
  * Shader for rendering.
6981
6717
  */ var Shader = /*#__PURE__*/ function() {
@@ -7043,32 +6779,33 @@ __decorate([
7043
6779
  */ _proto._addReferCount = function _addReferCount(value) {
7044
6780
  this._refCount += value;
7045
6781
  };
7046
- Shader.create = function create(nameOrShaderSource, vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget, fragmentSourceOrPath) {
6782
+ Shader.create = function create(nameOrShaderSource, shaderPassesOrSubShadersOrPlatformTarget, path) {
7047
6783
  var shader;
7048
6784
  var shaderMap = Shader._shaderMap;
7049
- if (vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget == undefined) {
7050
- vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget = ShaderLanguage.GLSLES100;
6785
+ if (shaderPassesOrSubShadersOrPlatformTarget == undefined) {
6786
+ shaderPassesOrSubShadersOrPlatformTarget = ShaderLanguage.GLSLES100;
7051
6787
  }
7052
- if (typeof vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget === "number") {
7053
- var shaderLab = Shader._shaderLab;
7054
- if (!shaderLab) {
7055
- throw "ShaderLab has not been set up yet.";
6788
+ if (typeof shaderPassesOrSubShadersOrPlatformTarget === "number") {
6789
+ var shaderCompiler = Shader._shaderCompiler;
6790
+ if (!shaderCompiler) {
6791
+ throw "ShaderCompiler has not been set up yet.";
7056
6792
  }
7057
- var shaderSource = shaderLab._parseShaderSource(nameOrShaderSource);
6793
+ var shaderSource = shaderCompiler._parseShaderSource(nameOrShaderSource);
7058
6794
  if (shaderMap[shaderSource.name]) {
7059
6795
  console.error('Shader named "' + shaderSource.name + '" already exists.');
7060
6796
  return;
7061
6797
  }
6798
+ var basePathForIncludeKey = new URL(path != null ? path : "", ShaderPass._shaderRootPath).href;
7062
6799
  var subShaderList = shaderSource.subShaders.map(function(subShaderSource) {
7063
6800
  var passList = subShaderSource.passes.map(function(passSource) {
7064
6801
  if (passSource.isUsePass) {
7065
6802
  return Shader._resolveUsePass(passSource.name);
7066
6803
  }
7067
- var shaderPassSource = Shader._shaderLab._parseShaderPass(passSource.contents, passSource.vertexEntry, passSource.fragmentEntry, vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget, new URL(fragmentSourceOrPath != null ? fragmentSourceOrPath : "", ShaderPass._shaderRootPath).href);
6804
+ var shaderPassSource = Shader._shaderCompiler._parseShaderPass(passSource.contents, passSource.vertexEntry, passSource.fragmentEntry, shaderPassesOrSubShadersOrPlatformTarget, basePathForIncludeKey);
7068
6805
  if (!shaderPassSource) {
7069
6806
  throw 'Shader pass "' + shaderSource.name + "." + subShaderSource.name + "." + passSource.name + '" parse failed, please check the shader source code.';
7070
6807
  }
7071
- var shaderPass = new ShaderPass(passSource.name, shaderPassSource.vertexShaderInstructions, shaderPassSource.fragmentShaderInstructions, vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget, passSource.tags);
6808
+ var shaderPass = new ShaderPass(passSource.name, shaderPassSource.vertexShaderInstructions, shaderPassSource.fragmentShaderInstructions, shaderPassesOrSubShadersOrPlatformTarget, passSource.tags);
7072
6809
  Shader._applyRenderStates(shaderPass, passSource.renderStates.constantMap, passSource.renderStates.variableMap, false);
7073
6810
  return shaderPass;
7074
6811
  });
@@ -7082,25 +6819,16 @@ __decorate([
7082
6819
  console.error('Shader named "' + nameOrShaderSource + '" already exists.');
7083
6820
  return;
7084
6821
  }
7085
- if (typeof vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget === "string") {
7086
- var shaderPass = new ShaderPass(vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget, fragmentSourceOrPath);
7087
- shader = new Shader(nameOrShaderSource, [
7088
- new SubShader("Default", [
7089
- shaderPass
7090
- ])
7091
- ]);
7092
- } else {
7093
- if (vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget.length > 0) {
7094
- if (vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget[0].constructor === ShaderPass) {
7095
- shader = new Shader(nameOrShaderSource, [
7096
- new SubShader("Default", vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget)
7097
- ]);
7098
- } else {
7099
- shader = new Shader(nameOrShaderSource, vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget.slice());
7100
- }
6822
+ if (shaderPassesOrSubShadersOrPlatformTarget.length > 0) {
6823
+ if (shaderPassesOrSubShadersOrPlatformTarget[0].constructor === ShaderPass) {
6824
+ shader = new Shader(nameOrShaderSource, [
6825
+ new SubShader("Default", shaderPassesOrSubShadersOrPlatformTarget)
6826
+ ]);
7101
6827
  } else {
7102
- throw "SubShader or ShaderPass count must large than 0.";
6828
+ shader = new Shader(nameOrShaderSource, shaderPassesOrSubShadersOrPlatformTarget.slice());
7103
6829
  }
6830
+ } else {
6831
+ throw "SubShader or ShaderPass count must large than 0.";
7104
6832
  }
7105
6833
  }
7106
6834
  shaderMap[nameOrShaderSource] = shader;
@@ -7158,32 +6886,48 @@ __decorate([
7158
6886
  }
7159
6887
  };
7160
6888
  Shader._resolveUsePass = function _resolveUsePass(passName) {
7161
- var _Shader_find_subShaders_find, _Shader_find;
7162
- var _passName_split = passName.split("/"), shaderName = _passName_split[0], subShaderName = _passName_split[1], passNamePart = _passName_split[2];
7163
- return (_Shader_find = Shader.find(shaderName)) == null ? void 0 : (_Shader_find_subShaders_find = _Shader_find.subShaders.find(function(subShader) {
7164
- return subShader.name === subShaderName;
7165
- })) == null ? void 0 : _Shader_find_subShaders_find.passes.find(function(pass) {
7166
- return pass.name === passNamePart;
6889
+ var lastSlash = passName.lastIndexOf("/");
6890
+ var secondLastSlash = passName.lastIndexOf("/", lastSlash - 1);
6891
+ if (secondLastSlash <= 0) {
6892
+ throw new Error('UsePass "' + passName + '" must be formatted as "shaderName/subShaderName/passName".');
6893
+ }
6894
+ var shaderName = passName.substring(0, secondLastSlash);
6895
+ var subShaderName = passName.substring(secondLastSlash + 1, lastSlash);
6896
+ var passNamePart = passName.substring(lastSlash + 1);
6897
+ var shader = Shader.find(shaderName);
6898
+ if (!shader) {
6899
+ throw new Error('UsePass "' + passName + '": shader "' + shaderName + '" not found.');
6900
+ }
6901
+ var subShader = shader.subShaders.find(function(s) {
6902
+ return s.name === subShaderName;
6903
+ });
6904
+ if (!subShader) {
6905
+ throw new Error('UsePass "' + passName + '": subShader "' + subShaderName + '" not found in shader "' + shaderName + '".');
6906
+ }
6907
+ var pass = subShader.passes.find(function(p) {
6908
+ return p.name === passNamePart;
7167
6909
  });
6910
+ if (!pass) {
6911
+ throw new Error('UsePass "' + passName + '": pass "' + passNamePart + '" not found in subShader "' + subShaderName + '".');
6912
+ }
6913
+ return pass;
7168
6914
  };
7169
6915
  Shader._applyRenderStates = function _applyRenderStates(shaderPass, constantMap, variableMap, deserializeColor) {
7170
- if (Object.keys(constantMap).length > 0 || Object.keys(variableMap).length > 0) {
7171
- var renderState = new RenderState();
7172
- for(var k in constantMap){
7173
- var value = constantMap[k];
7174
- if (deserializeColor && Array.isArray(value)) {
7175
- Shader._applyConstRenderStates(renderState, +k, new Color(value[0], value[1], value[2], value[3]));
7176
- } else {
7177
- Shader._applyConstRenderStates(renderState, +k, value);
7178
- }
7179
- }
7180
- shaderPass._renderState = renderState;
7181
- var renderStateDataMap = {};
7182
- for(var k1 in variableMap){
7183
- renderStateDataMap[k1] = ShaderProperty.getByName(variableMap[k1]);
6916
+ var renderState = new RenderState();
6917
+ for(var k in constantMap){
6918
+ var value = constantMap[k];
6919
+ if (deserializeColor && Array.isArray(value)) {
6920
+ Shader._applyConstRenderStates(renderState, +k, new Color(value[0], value[1], value[2], value[3]));
6921
+ } else {
6922
+ Shader._applyConstRenderStates(renderState, +k, value);
7184
6923
  }
7185
- shaderPass._renderStateDataMap = renderStateDataMap;
7186
6924
  }
6925
+ shaderPass._renderState = renderState;
6926
+ var renderStateDataMap = {};
6927
+ for(var k1 in variableMap){
6928
+ renderStateDataMap[k1] = ShaderProperty.getByName(variableMap[k1]);
6929
+ }
6930
+ shaderPass._renderStateDataMap = renderStateDataMap;
7187
6931
  };
7188
6932
  Shader._applyConstRenderStates = function _applyConstRenderStates(renderState, key, value) {
7189
6933
  switch(key){
@@ -7663,7 +7407,7 @@ RenderContext._flipYViewProjectionMatrix = new Matrix();
7663
7407
  var sceneData = scene.shaderData;
7664
7408
  var viewProjMatrix = Sky._viewProjMatrix, projectionMatrix = Sky._projectionMatrix;
7665
7409
  var rhi = engine._hardwareRenderer;
7666
- var materialShaderData = material.shaderData, shader = material.shader, renderState = material.renderState;
7410
+ var materialShaderData = material.shaderData, shader = material.shader;
7667
7411
  // no-scale view matrix
7668
7412
  viewProjMatrix.copyFrom(viewMatrix);
7669
7413
  var e = viewProjMatrix.elements;
@@ -7690,7 +7434,7 @@ RenderContext._flipYViewProjectionMatrix = new Matrix();
7690
7434
  program.uploadAll(program.cameraUniformBlock, cameraShaderData);
7691
7435
  program.uploadAll(program.materialUniformBlock, materialShaderData);
7692
7436
  program.uploadUnGroupTextures();
7693
- renderState._applyStates(engine, false, pass._renderStateDataMap, materialShaderData);
7437
+ pass._renderState._applyStates(engine, false, pass._renderStateDataMap, materialShaderData);
7694
7438
  rhi.drawPrimitive(mesh._primitive, mesh.subMesh, program);
7695
7439
  cameraShaderData.setMatrix(RenderContext.vpMatrixProperty, originViewProjMatrix);
7696
7440
  };
@@ -7815,8 +7559,7 @@ Sky._projectionMatrix = new Matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, Sky._epsilon -
7815
7559
  this._mesh._addReferCount(1);
7816
7560
  };
7817
7561
  _proto._initMaterial = function _initMaterial(engine) {
7818
- var material = this._material = new Material(engine, Shader.find("background-texture"));
7819
- material.renderState.depthState.compareFunction = CompareFunction.LessEqual;
7562
+ var material = this._material = new Material(engine, Shader.find("Sky/BackgroundTexture"));
7820
7563
  material._addReferCount(1);
7821
7564
  };
7822
7565
  _proto._createPlane = function _createPlane(engine) {
@@ -10020,8 +9763,7 @@ Camera = __decorate([
10020
9763
  _inherits(Material, ReferResource);
10021
9764
  function Material(engine, shader) {
10022
9765
  var _this;
10023
- _this = ReferResource.call(this, engine) || this, /** @internal */ _this._renderStates = [] // todo: later will as a part of shaderData when shader effect frame is OK, that is more powerful and flexible.
10024
- , _this._shaderData = new ShaderData(ShaderDataGroup.Material);
9766
+ _this = ReferResource.call(this, engine) || this, _this._shaderData = new ShaderData(ShaderDataGroup.Material);
10025
9767
  _this.shader = shader;
10026
9768
  _this.name = shader.name;
10027
9769
  return _this;
@@ -10040,7 +9782,6 @@ Camera = __decorate([
10040
9782
  */ _proto.cloneTo = function cloneTo(target) {
10041
9783
  target.shader = this.shader;
10042
9784
  this.shaderData.cloneTo(target.shaderData);
10043
- CloneManager.deepCloneObject(this.renderStates, target.renderStates, new Map());
10044
9785
  };
10045
9786
  _proto._addReferCount = function _addReferCount(value) {
10046
9787
  if (this._destroyed) return;
@@ -10058,8 +9799,6 @@ Camera = __decorate([
10058
9799
  ReferResource.prototype._onDestroy.call(this);
10059
9800
  this._shader = null;
10060
9801
  this._shaderData = null;
10061
- this._renderStates.length = 0;
10062
- this._renderStates = null;
10063
9802
  };
10064
9803
  _create_class(Material, [
10065
9804
  {
@@ -10085,36 +9824,6 @@ Camera = __decorate([
10085
9824
  value._addReferCount(refCount);
10086
9825
  }
10087
9826
  this._shader = value;
10088
- var renderStates = this._renderStates;
10089
- var lastStatesCount = renderStates.length;
10090
- var maxPassCount = 0;
10091
- var subShaders = value.subShaders;
10092
- for(var i = 0; i < subShaders.length; i++){
10093
- maxPassCount = Math.max(subShaders[i].passes.length, maxPassCount);
10094
- }
10095
- if (lastStatesCount < maxPassCount) {
10096
- for(var i1 = lastStatesCount; i1 < maxPassCount; i1++){
10097
- renderStates.push(new RenderState());
10098
- }
10099
- } else {
10100
- renderStates.length = maxPassCount;
10101
- }
10102
- }
10103
- },
10104
- {
10105
- key: "renderState",
10106
- get: /**
10107
- * First Render state.
10108
- */ function get() {
10109
- return this._renderStates[0];
10110
- }
10111
- },
10112
- {
10113
- key: "renderStates",
10114
- get: /**
10115
- * Render states.
10116
- */ function get() {
10117
- return this._renderStates;
10118
9827
  }
10119
9828
  }
10120
9829
  ]);
@@ -10130,77 +9839,63 @@ var BaseMaterial = /*#__PURE__*/ function(Material) {
10130
9839
  shaderData.setFloat(BaseMaterial._alphaCutoffProp, 0);
10131
9840
  shaderData.setFloat(BaseMaterial._shadowCasterRenderQueueProp, RenderQueueType.Opaque);
10132
9841
  shaderData.setFloat(BaseMaterial._depthOnlyRenderQueueProp, RenderQueueType.Opaque);
9842
+ _this.setIsTransparent(false);
9843
+ _this.setRenderFace(RenderFace.Front);
9844
+ _this.setBlendMode(BlendMode.Normal);
10133
9845
  return _this;
10134
9846
  }
10135
9847
  var _proto = BaseMaterial.prototype;
10136
9848
  /**
10137
9849
  * Set if is transparent of the shader pass render state.
10138
- * @param passIndex - Shader pass index
10139
9850
  * @param isTransparent - If is transparent
10140
- */ _proto.setIsTransparent = function setIsTransparent(passIndex, isTransparent) {
10141
- var renderStates = this.renderStates;
10142
- if (renderStates.length < passIndex) {
10143
- throw "Pass should less than pass count.";
10144
- }
10145
- var renderState = renderStates[passIndex];
9851
+ */ _proto.setIsTransparent = function setIsTransparent(isTransparent) {
10146
9852
  var shaderData = this.shaderData;
10147
9853
  if (isTransparent) {
10148
- renderState.blendState.targetBlendState.enabled = true;
10149
- renderState.depthState.writeEnabled = false;
10150
- renderState.renderQueueType = RenderQueueType.Transparent;
9854
+ shaderData.setInt(BaseMaterial._blendEnabledProp, 1);
9855
+ shaderData.setInt(BaseMaterial._depthWriteEnabledProp, 0);
9856
+ shaderData.setInt(BaseMaterial._renderQueueTypeProp, RenderQueueType.Transparent);
10151
9857
  shaderData.enableMacro(BaseMaterial._transparentMacro);
10152
9858
  } else {
10153
- renderState.blendState.targetBlendState.enabled = false;
10154
- renderState.depthState.writeEnabled = true;
10155
- renderState.renderQueueType = shaderData.getFloat(BaseMaterial._alphaCutoffProp) ? RenderQueueType.AlphaTest : RenderQueueType.Opaque;
9859
+ shaderData.setInt(BaseMaterial._blendEnabledProp, 0);
9860
+ shaderData.setInt(BaseMaterial._depthWriteEnabledProp, 1);
9861
+ shaderData.setInt(BaseMaterial._renderQueueTypeProp, shaderData.getFloat(BaseMaterial._alphaCutoffProp) ? RenderQueueType.AlphaTest : RenderQueueType.Opaque);
10156
9862
  shaderData.disableMacro(BaseMaterial._transparentMacro);
10157
9863
  }
10158
9864
  };
10159
9865
  /**
10160
9866
  * Set the blend mode of shader pass render state.
10161
- * @param passIndex - Shader pass index
10162
9867
  * @param blendMode - Blend mode
10163
- */ _proto.setBlendMode = function setBlendMode(passIndex, blendMode) {
10164
- var renderStates = this.renderStates;
10165
- if (renderStates.length < passIndex) {
10166
- throw "Pass should less than pass count.";
10167
- }
10168
- var _renderStates_passIndex_blendState = renderStates[passIndex].blendState, target = _renderStates_passIndex_blendState.targetBlendState;
9868
+ */ _proto.setBlendMode = function setBlendMode(blendMode) {
9869
+ var shaderData = this.shaderData;
10169
9870
  switch(blendMode){
10170
9871
  case BlendMode.Normal:
10171
- target.sourceColorBlendFactor = BlendFactor.SourceAlpha;
10172
- target.destinationColorBlendFactor = BlendFactor.OneMinusSourceAlpha;
10173
- target.sourceAlphaBlendFactor = BlendFactor.One;
10174
- target.destinationAlphaBlendFactor = BlendFactor.OneMinusSourceAlpha;
10175
- target.colorBlendOperation = target.alphaBlendOperation = BlendOperation.Add;
9872
+ shaderData.setInt(BaseMaterial._sourceColorBlendFactorProp, BlendFactor.SourceAlpha);
9873
+ shaderData.setInt(BaseMaterial._destinationColorBlendFactorProp, BlendFactor.OneMinusSourceAlpha);
9874
+ shaderData.setInt(BaseMaterial._sourceAlphaBlendFactorProp, BlendFactor.One);
9875
+ shaderData.setInt(BaseMaterial._destinationAlphaBlendFactorProp, BlendFactor.OneMinusSourceAlpha);
10176
9876
  break;
10177
9877
  case BlendMode.Additive:
10178
- target.sourceColorBlendFactor = BlendFactor.SourceAlpha;
10179
- target.destinationColorBlendFactor = BlendFactor.One;
10180
- target.sourceAlphaBlendFactor = BlendFactor.Zero;
10181
- target.destinationAlphaBlendFactor = BlendFactor.One;
10182
- target.colorBlendOperation = target.alphaBlendOperation = BlendOperation.Add;
9878
+ shaderData.setInt(BaseMaterial._sourceColorBlendFactorProp, BlendFactor.SourceAlpha);
9879
+ shaderData.setInt(BaseMaterial._destinationColorBlendFactorProp, BlendFactor.One);
9880
+ shaderData.setInt(BaseMaterial._sourceAlphaBlendFactorProp, BlendFactor.Zero);
9881
+ shaderData.setInt(BaseMaterial._destinationAlphaBlendFactorProp, BlendFactor.One);
10183
9882
  break;
10184
9883
  }
10185
9884
  };
10186
9885
  /**
10187
9886
  * Set the render face of shader pass render state.
10188
- * @param passIndex - Shader pass index
10189
9887
  * @param renderFace - Render face
10190
- */ _proto.setRenderFace = function setRenderFace(passIndex, renderFace) {
10191
- var renderStates = this.renderStates;
10192
- if (renderStates.length < passIndex) {
10193
- throw "Pass should less than pass count.";
10194
- }
9888
+ */ _proto.setRenderFace = function setRenderFace(renderFace) {
9889
+ var shaderData = this.shaderData;
10195
9890
  switch(renderFace){
10196
9891
  case RenderFace.Front:
10197
- renderStates[passIndex].rasterState.cullMode = CullMode.Back;
9892
+ shaderData.setInt(BaseMaterial._rasterStateCullModeProp, CullMode.Back);
10198
9893
  break;
10199
9894
  case RenderFace.Back:
10200
- renderStates[passIndex].rasterState.cullMode = CullMode.Front;
9895
+ shaderData.setInt(BaseMaterial._rasterStateCullModeProp, CullMode.Front);
10201
9896
  break;
10202
9897
  case RenderFace.Double:
10203
- renderStates[passIndex].rasterState.cullMode = CullMode.Off;
9898
+ shaderData.setInt(BaseMaterial._rasterStateCullModeProp, CullMode.Off);
10204
9899
  break;
10205
9900
  }
10206
9901
  };
@@ -10223,7 +9918,7 @@ var BaseMaterial = /*#__PURE__*/ function(Material) {
10223
9918
  _proto._seIsTransparent = function _seIsTransparent(value) {
10224
9919
  if (value !== this._isTransparent) {
10225
9920
  // Forward pass
10226
- this.setIsTransparent(0, value);
9921
+ this.setIsTransparent(value);
10227
9922
  // Shadow caster pass and depth only pass
10228
9923
  var shaderData = this.shaderData;
10229
9924
  if (value) {
@@ -10249,7 +9944,7 @@ var BaseMaterial = /*#__PURE__*/ function(Material) {
10249
9944
  shaderData.enableMacro(BaseMaterial._alphaCutoffMacro);
10250
9945
  // Forward render queue
10251
9946
  var forwardQueue = isTransparent ? RenderQueueType.Transparent : RenderQueueType.AlphaTest;
10252
- this.renderStates[0].renderQueueType = forwardQueue;
9947
+ shaderData.setInt(BaseMaterial._renderQueueTypeProp, forwardQueue);
10253
9948
  // Shadow caster render queue
10254
9949
  shaderData.setFloat(BaseMaterial._shadowCasterRenderQueueProp, RenderQueueType.AlphaTest);
10255
9950
  // Depth only render queue
@@ -10258,7 +9953,7 @@ var BaseMaterial = /*#__PURE__*/ function(Material) {
10258
9953
  shaderData.disableMacro(BaseMaterial._alphaCutoffMacro);
10259
9954
  // Forward render queue
10260
9955
  var forwardQueue1 = isTransparent ? RenderQueueType.Transparent : RenderQueueType.Opaque;
10261
- this.renderStates[0].renderQueueType = forwardQueue1;
9956
+ shaderData.setInt(BaseMaterial._renderQueueTypeProp, forwardQueue1);
10262
9957
  // Shadow caster render queue
10263
9958
  var shadowCasterQueue = isTransparent ? RenderQueueType.AlphaTest : RenderQueueType.Opaque;
10264
9959
  shaderData.setFloat(BaseMaterial._shadowCasterRenderQueueProp, shadowCasterQueue);
@@ -10269,38 +9964,6 @@ var BaseMaterial = /*#__PURE__*/ function(Material) {
10269
9964
  }
10270
9965
  };
10271
9966
  _create_class(BaseMaterial, [
10272
- {
10273
- key: "shader",
10274
- get: /**
10275
- * Shader used by the material.
10276
- */ function get() {
10277
- return this._shader;
10278
- },
10279
- set: function set(value) {
10280
- var refCount = this._getReferCount();
10281
- if (refCount > 0) {
10282
- var _this__shader;
10283
- (_this__shader = this._shader) == null ? void 0 : _this__shader._addReferCount(-refCount);
10284
- value._addReferCount(refCount);
10285
- }
10286
- this._shader = value;
10287
- var renderStates = this._renderStates;
10288
- var lastStatesCount = renderStates.length;
10289
- var maxPassCount = 0;
10290
- var subShaders = value.subShaders;
10291
- for(var i = 0; i < subShaders.length; i++){
10292
- maxPassCount = Math.max(subShaders[i].passes.length, maxPassCount);
10293
- }
10294
- if (lastStatesCount < maxPassCount) {
10295
- for(var i1 = lastStatesCount; i1 < maxPassCount; i1++){
10296
- renderStates.push(new RenderState());
10297
- this.setBlendMode(i1, BlendMode.Normal);
10298
- }
10299
- } else {
10300
- renderStates.length = maxPassCount;
10301
- }
10302
- }
10303
- },
10304
9967
  {
10305
9968
  key: "isTransparent",
10306
9969
  get: /**
@@ -10322,7 +9985,7 @@ var BaseMaterial = /*#__PURE__*/ function(Material) {
10322
9985
  },
10323
9986
  set: function set(value) {
10324
9987
  if (value !== this._blendMode) {
10325
- this.setBlendMode(0, value);
9988
+ this.setBlendMode(value);
10326
9989
  this._blendMode = value;
10327
9990
  }
10328
9991
  }
@@ -10350,7 +10013,7 @@ var BaseMaterial = /*#__PURE__*/ function(Material) {
10350
10013
  },
10351
10014
  set: function set(value) {
10352
10015
  if (value !== this._renderFace) {
10353
- this.setRenderFace(0, value);
10016
+ this.setRenderFace(value);
10354
10017
  this._renderFace = value;
10355
10018
  }
10356
10019
  }
@@ -10373,6 +10036,14 @@ BaseMaterial._emissiveColorProp = ShaderProperty.getByName("material_EmissiveCol
10373
10036
  BaseMaterial._emissiveTextureProp = ShaderProperty.getByName("material_EmissiveTexture");
10374
10037
  BaseMaterial._alphaCutoffProp = ShaderProperty.getByName("material_AlphaCutoff");
10375
10038
  BaseMaterial._alphaCutoffMacro = ShaderMacro.getByName("MATERIAL_IS_ALPHA_CUTOFF");
10039
+ BaseMaterial._blendEnabledProp = ShaderProperty.getByName("blendEnabled");
10040
+ BaseMaterial._depthWriteEnabledProp = ShaderProperty.getByName("depthWriteEnabled");
10041
+ BaseMaterial._renderQueueTypeProp = ShaderProperty.getByName("renderQueueType");
10042
+ BaseMaterial._sourceColorBlendFactorProp = ShaderProperty.getByName("sourceColorBlendFactor");
10043
+ BaseMaterial._destinationColorBlendFactorProp = ShaderProperty.getByName("destinationColorBlendFactor");
10044
+ BaseMaterial._sourceAlphaBlendFactorProp = ShaderProperty.getByName("sourceAlphaBlendFactor");
10045
+ BaseMaterial._destinationAlphaBlendFactorProp = ShaderProperty.getByName("destinationAlphaBlendFactor");
10046
+ BaseMaterial._rasterStateCullModeProp = ShaderProperty.getByName("rasterStateCullMode");
10376
10047
 
10377
10048
  /**
10378
10049
  * Blinn-phong Material.
@@ -10380,7 +10051,7 @@ BaseMaterial._alphaCutoffMacro = ShaderMacro.getByName("MATERIAL_IS_ALPHA_CUTOFF
10380
10051
  _inherits(BlinnPhongMaterial, BaseMaterial);
10381
10052
  function BlinnPhongMaterial(engine) {
10382
10053
  var _this;
10383
- _this = BaseMaterial.call(this, engine, Shader.find("blinn-phong")) || this;
10054
+ _this = BaseMaterial.call(this, engine, Shader.find("BlinnPhong")) || this;
10384
10055
  var shaderData = _this.shaderData;
10385
10056
  shaderData.enableMacro("MATERIAL_NEED_WORLD_POS");
10386
10057
  shaderData.enableMacro("MATERIAL_NEED_TILING_OFFSET");
@@ -10576,7 +10247,7 @@ BlinnPhongMaterial._specularTextureProp = ShaderProperty.getByName("material_Spe
10576
10247
  _inherits(PBRMaterial, BaseMaterial1);
10577
10248
  function PBRMaterial(engine) {
10578
10249
  var _this;
10579
- _this = BaseMaterial1.call(this, engine, Shader.find("pbr")) || this, _this._anisotropyRotation = 0, _this._iridescenceRange = new Vector2(100, 400), _this._sheenEnabled = false;
10250
+ _this = BaseMaterial1.call(this, engine, Shader.find("PBR")) || this, _this._anisotropyRotation = 0, _this._iridescenceRange = new Vector2(100, 400), _this._sheenEnabled = false;
10580
10251
  var shaderData = _this.shaderData;
10581
10252
  shaderData.enableMacro("MATERIAL_NEED_WORLD_POS");
10582
10253
  shaderData.enableMacro("MATERIAL_NEED_TILING_OFFSET");
@@ -11134,7 +10805,7 @@ BlinnPhongMaterial._specularTextureProp = ShaderProperty.getByName("material_Spe
11134
10805
  this._seIsTransparent(value);
11135
10806
  if (this.transmission > 0) {
11136
10807
  // If transmission enabled, always use transparent queue to ensure get correct opaque texture
11137
- this.renderState.renderQueueType = RenderQueueType.Transparent;
10808
+ this.shaderData.setInt("renderQueueType", RenderQueueType.Transparent);
11138
10809
  }
11139
10810
  }
11140
10811
  },
@@ -11149,7 +10820,7 @@ BlinnPhongMaterial._specularTextureProp = ShaderProperty.getByName("material_Spe
11149
10820
  this._setAlphaCutoff(value);
11150
10821
  if (this.transmission > 0) {
11151
10822
  // If transmission enabled, always use transparent queue to ensure get correct opaque texture
11152
- this.renderState.renderQueueType = RenderQueueType.Transparent;
10823
+ this.shaderData.setInt("renderQueueType", RenderQueueType.Transparent);
11153
10824
  }
11154
10825
  }
11155
10826
  },
@@ -11166,9 +10837,19 @@ BlinnPhongMaterial._specularTextureProp = ShaderProperty.getByName("material_Spe
11166
10837
  if (!!this.shaderData.getFloat(PBRMaterial._transmissionProp) !== !!value) {
11167
10838
  if (value > 0) {
11168
10839
  this.shaderData.enableMacro(PBRMaterial._transmissionMacro);
11169
- this.renderState.renderQueueType = RenderQueueType.Transparent;
10840
+ this.shaderData.setInt("renderQueueType", RenderQueueType.Transparent);
11170
10841
  } else {
11171
10842
  this.shaderData.disableMacro(PBRMaterial._transmissionMacro);
10843
+ // Restore renderQueueType based on isTransparent / alphaCutoff state
10844
+ var queue;
10845
+ if (this._isTransparent) {
10846
+ queue = RenderQueueType.Transparent;
10847
+ } else if (this.shaderData.getFloat(BaseMaterial._alphaCutoffProp)) {
10848
+ queue = RenderQueueType.AlphaTest;
10849
+ } else {
10850
+ queue = RenderQueueType.Opaque;
10851
+ }
10852
+ this.shaderData.setInt("renderQueueType", queue);
11172
10853
  }
11173
10854
  }
11174
10855
  this.shaderData.setFloat(PBRMaterial._transmissionProp, value);
@@ -11362,7 +11043,7 @@ PBRMaterial._specularColorTextureProp = ShaderProperty.getByName("material_Specu
11362
11043
  _inherits(UnlitMaterial, BaseMaterial);
11363
11044
  function UnlitMaterial(engine) {
11364
11045
  var _this;
11365
- _this = BaseMaterial.call(this, engine, Shader.find("unlit")) || this;
11046
+ _this = BaseMaterial.call(this, engine, Shader.find("Unlit")) || this;
11366
11047
  var shaderData = _this.shaderData;
11367
11048
  shaderData.enableMacro("MATERIAL_OMIT_NORMAL");
11368
11049
  shaderData.enableMacro("MATERIAL_NEED_TILING_OFFSET");
@@ -11530,7 +11211,8 @@ PipelineUtils.defaultViewport = new Vector4(0, 0, 1, 1);
11530
11211
  program.uploadAll(program.rendererUniformBlock, rendererShaderData);
11531
11212
  program.uploadAll(program.materialUniformBlock, blitMaterial.shaderData);
11532
11213
  program.uploadUnGroupTextures();
11533
- (pass._renderState || blitMaterial.renderState)._applyStates(engine, false, pass._renderStateDataMap, blitMaterial.shaderData);
11214
+ var renderState = pass._renderState;
11215
+ renderState._applyStates(engine, false, pass._renderStateDataMap, blitMaterial.shaderData);
11534
11216
  rhi.drawPrimitive(blitMesh._primitive, blitMesh.subMesh, program);
11535
11217
  rendererShaderData.setTexture(Blitter._blitTextureProperty, null);
11536
11218
  };
@@ -11551,8 +11233,6 @@ Blitter._defaultScaleOffset = new Vector4(1, 1, 0, 0);
11551
11233
  this.engine = engine;
11552
11234
  };
11553
11235
 
11554
- var blitVs = "attribute vec4 POSITION_UV;\nvarying vec2 v_uv;\n\nvoid main() {\t\n\tgl_Position = vec4(POSITION_UV.xy, 0.0, 1.0);\t\n\tv_uv = POSITION_UV.zw;\n}"; // eslint-disable-line
11555
-
11556
11236
  /**
11557
11237
  * Ambient occlusion quality levels that control the balance between visual quality and performance.
11558
11238
  */ var AmbientOcclusionQuality = /*#__PURE__*/ function(AmbientOcclusionQuality) {
@@ -11562,10 +11242,6 @@ var blitVs = "attribute vec4 POSITION_UV;\nvarying vec2 v_uv;\n\nvoid main() {\t
11562
11242
  return AmbientOcclusionQuality;
11563
11243
  }({});
11564
11244
 
11565
- var bilateralBlurFS = "#include <common>\n\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\nuniform vec4 renderer_SourceScaleOffset; \nuniform float material_farPlaneOverEdgeDistance;\n#if SSAO_QUALITY == 0\n #define BLUR_SAMPLE_COUNT 3\n#elif SSAO_QUALITY == 1\n #define BLUR_SAMPLE_COUNT 6\n#elif SSAO_QUALITY == 2\n #define BLUR_SAMPLE_COUNT 12\n#endif\n\nuniform float material_kernel[12]; // Sample weights for bilateral blur\n\nfloat bilateralWeight(float depth, float sampleDepth) {\n float diff = (sampleDepth - depth) * material_farPlaneOverEdgeDistance;\n return max(0.0, 1.0 - diff * diff);\n}\n\nhighp float unpack(highp vec2 depth) {\n // depth here only has 8-bits of precision, but the unpacked depth is highp\n // this is equivalent to (x8 * 256 + y8) / 65535, which gives a value between 0 and 1\n return (depth.x * (256.0 / 257.0) + depth.y * (1.0 / 257.0));\n}\n\nvoid tap(const sampler2D saoTexture,\n inout float sum, inout float totalWeight, float weight, float depth, vec2 position) {\n vec4 data = texture2D(saoTexture, position);\n // bilateral sample\n float bilateral = weight * bilateralWeight(depth, unpack(data.gb));\n sum += data.r * bilateral;\n totalWeight += bilateral;\n}\n\nvoid main(){\n mediump vec4 data = texture2D(renderer_BlitTexture, v_uv);\n float depth = unpack(data.gb);\n\n // Weight of the center pixel from the Gaussian kernel (typically 1.0)\n float totalWeight = material_kernel[0];\n float sum = data.r * totalWeight;\n \n vec2 offset = renderer_SourceScaleOffset.zw;\n for (int i = 1; i < BLUR_SAMPLE_COUNT; i++) {\n float weight = material_kernel[i];\n tap(renderer_BlitTexture, sum, totalWeight, weight, depth, v_uv + offset);\n tap(renderer_BlitTexture, sum, totalWeight, weight, depth, v_uv - offset);\n offset += renderer_SourceScaleOffset.zw;\n }\n\n float ao = sum * (1.0 / totalWeight);\n\n // simple dithering helps a lot (assumes 8 bits target)\n // this is most useful with high quality/large blurs\n ao += ((interleavedGradientNoise(gl_FragCoord.xy) - 0.5) / 255.0);\n gl_FragColor = vec4(ao, data.gb, 1.0);\n\n}\n\n"; // eslint-disable-line
11566
-
11567
- var scalableAmbientOcclusionFS = "// Ambient Occlusion, largely inspired from:\n// \"The Alchemy Screen-Space Ambient Obscurance Algorithm\" by Morgan McGuire\n// \"Scalable Ambient Obscurance\" by Morgan McGuire, Michael Mara and David Luebke\n// https://research.nvidia.com/sites/default/files/pubs/2012-06_Scalable-Ambient-Obscurance/McGuire12SAO.pdf\n\n#include <common>\n\nvarying vec2 v_uv;\nuniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height\nuniform highp sampler2D renderer_BlitTexture; // Camera_DepthTexture\n\n// float inc = (1.0f / (SAMPLE_COUNT - 0.5f)) * SPIRAL_TURNS * 2.0 * PI\n// const vec2 angleIncCosSin = vec2(cos(inc), sin(inc))\n#if SSAO_QUALITY == 0\n #define SAMPLE_COUNT 7.0\n #define SPIRAL_TURNS 3.0\n const vec2 angleIncCosSin = vec2(-0.971148, 0.238227);\n#elif SSAO_QUALITY == 1\n #define SAMPLE_COUNT 11.0\n #define SPIRAL_TURNS 6.0\n const vec2 angleIncCosSin = vec2(-0.896127, -0.443780);\n#elif SSAO_QUALITY == 2\n #define SAMPLE_COUNT 16.0\n #define SPIRAL_TURNS 7.0\n const vec2 angleIncCosSin = vec2(-0.966846, 0.255311);\n#endif\n\nuniform float material_invRadiusSquared; // Inverse of the squared radius\nuniform float material_minHorizonAngleSineSquared; // Minimum horizon angle sine squared\nuniform float material_intensity; // Intensity of the ambient occlusion\nuniform float material_projectionScaleRadius;\nuniform float material_bias; // Bias to avoid self-occlusion\nuniform float material_peak2; // Peak value to avoid singularities\nuniform float material_power; // Exponent to convert occlusion to visibility\nuniform vec2 material_invProjScaleXY; //invProjection[0][0] * 2, invProjection[1][1] * 2\n\n\nvec3 computeViewSpacePosition(vec2 uv, float linearDepth, vec2 invProjScaleXY) {\n #ifdef CAMERA_ORTHOGRAPHIC\n return vec3((vec2(0.5) - uv) * invProjScaleXY , linearDepth);\n #else\n return vec3((vec2(0.5) - uv) * invProjScaleXY * linearDepth, linearDepth);\n #endif\n}\n\nfloat depthToViewZ(float depth) {\n return -remapDepthBufferEyeDepth(depth);\n}\n\n// reconstructing normal from depth buffer\n// https://atyuwen.github.io/posts/normal-reconstruction\n// https://wickedengine.net/2019/09/22/improved-normal-reconstruction-from-depth/\nvec3 computeViewSpaceNormal(vec2 uv, highp sampler2D depthTexture, float depth, vec3 viewPos, vec2 texel, vec2 invProjScaleXY) {\n vec3 normal = vec3(0.0);\n#if SSAO_QUALITY == 0 || SSAO_QUALITY == 1\n vec2 uvdx = uv + vec2(texel.x, 0.0);\n vec2 uvdy = uv + vec2(0.0, texel.y);\n\n float depthX = texture2D(depthTexture, uvdx).r;\n float depthY = texture2D(depthTexture, uvdy).r;\n\n vec3 px = computeViewSpacePosition(uvdx, depthToViewZ(depthX), invProjScaleXY);\n vec3 py = computeViewSpacePosition(uvdy, depthToViewZ(depthY), invProjScaleXY);\n\n vec3 dpdx = px - viewPos;\n vec3 dpdy = py - viewPos;\n\n normal = normalize(cross(dpdx, dpdy));\n\n#elif SSAO_QUALITY == 2\n vec2 dx = vec2(texel.x, 0.0);\n vec2 dy = vec2(0.0, texel.y);\n \n vec4 H;\n H.x = texture2D(depthTexture, uv - dx).r; // left\n H.y = texture2D(depthTexture, uv + dx).r; // right\n H.z = texture2D(depthTexture, uv - dx * 2.0).r; // left2\n H.w = texture2D(depthTexture, uv + dx * 2.0).r; // right2\n \n // Calculate horizontal edge weights\n vec2 horizontalEdgeWeights = abs((2.0 * H.xy - H.zw) - depth);\n\n vec3 pos_l = computeViewSpacePosition(uv - dx, depthToViewZ(H.x), invProjScaleXY);\n vec3 pos_r = computeViewSpacePosition(uv + dx, depthToViewZ(H.y), invProjScaleXY);\n vec3 dpdx = (horizontalEdgeWeights.x < horizontalEdgeWeights.y) ? (viewPos - pos_l) : (pos_r - viewPos);\n\n // Sample depths for vertical edge detection\n vec4 V;\n V.x = texture2D(depthTexture, uv - dy).r; // down\n V.y = texture2D(depthTexture, uv + dy).r; // up\n V.z = texture2D(depthTexture, uv - dy * 2.0).r; // down2\n V.w = texture2D(depthTexture, uv + dy * 2.0).r; // up2\n\n // Calculate vertical edge weights\n vec2 verticalEdgeWeights = abs((2.0 * V.xy - V.zw) - depth);\n vec3 pos_d = computeViewSpacePosition(uv - dy, depthToViewZ(V.x), invProjScaleXY);\n vec3 pos_u = computeViewSpacePosition(uv + dy, depthToViewZ(V.y), invProjScaleXY);\n vec3 dpdy = (verticalEdgeWeights.x < verticalEdgeWeights.y) ? (viewPos - pos_d) : (pos_u - viewPos);\n normal = normalize(cross(dpdx, dpdy));\n #endif\n return normal;\n\n}\n\nvec3 tapLocation(float i, const float noise) {\n float offset = ((2.0 * PI) * 2.4) * noise;\n float angle = ((i / SAMPLE_COUNT) * SPIRAL_TURNS) * (2.0 * PI) + offset;\n float radius = (i + noise + 0.5) / SAMPLE_COUNT;\n return vec3(cos(angle), sin(angle), radius * radius);\n}\n\nvec2 startPosition(const float noise) {\n float angle = ((2.0 * PI) * 2.4) * noise;\n return vec2(cos(angle), sin(angle));\n}\n\nmat2 tapAngleStep() {\n vec2 t = angleIncCosSin;\n return mat2(t.x, t.y, -t.y, t.x);\n}\n\nvec3 tapLocationFast(float i, vec2 p, const float noise) {\n float radius = (i + noise + 0.5) / SAMPLE_COUNT;\n return vec3(p, radius * radius);\n}\n\nvoid computeAmbientOcclusionSAO(inout float occlusion, float i, float ssDiskRadius, vec2 uv, vec3 originPosition, vec3 normal,\n vec2 tapPosition, float noise) {\n\n vec3 tap = tapLocationFast(i, tapPosition, noise);\n\n float ssRadius = max(1.0, tap.z * ssDiskRadius); // at least 1 pixel screen-space radius\n\n vec2 uvSamplePos = uv + vec2(ssRadius * tap.xy) * renderer_texelSize.xy;\n\n float occlusionDepth = texture2D(renderer_BlitTexture, uvSamplePos).r;\n float linearOcclusionDepth = depthToViewZ(occlusionDepth);\n // “p” is the position after spiral sampling\n vec3 p = computeViewSpacePosition(uvSamplePos, linearOcclusionDepth, material_invProjScaleXY);\n\n // now we have the sample, compute AO\n vec3 v = p - originPosition; // sample vector\n float vv = dot(v, v); // squared distance\n float vn = dot(v, normal); // distance * cos(v, normal)\n\n // discard samples that are outside of the radius, preventing distant geometry to\n // cast shadows -- there are many functions that work and choosing one is an artistic\n // decision.\n float weight = pow(max(0.0, 1.0 - vv * material_invRadiusSquared), 2.0);\n\n // discard samples that are too close to the horizon to reduce shadows cast by geometry\n // not sufficently tessellated. The goal is to discard samples that form an angle 'beta'\n // smaller than 'epsilon' with the horizon. We already have dot(v,n) which is equal to the\n // sin(beta) * |v|. So the test simplifies to vn^2 < vv * sin(epsilon)^2.\n weight *= step(vv * material_minHorizonAngleSineSquared, vn * vn);\n\n // Calculate the contribution of a single sampling point to Ambient Occlusion\n float sampleOcclusion = max(0.0, vn + (originPosition.z * material_bias)) / (vv + material_peak2);\n occlusion += weight * sampleOcclusion;\n}\n\nvoid scalableAmbientObscurance(vec2 uv, vec3 origin, vec3 normal, out float obscurance) {\n float noise = interleavedGradientNoise(gl_FragCoord.xy);\n vec2 tapPosition = startPosition(noise);\n mat2 angleStep = tapAngleStep();\n\n // Choose the screen-space sample radius\n // proportional to the projected area of the sphere\n float ssDiskRadius = -(material_projectionScaleRadius / origin.z);\n\n // Accumulate the occlusion amount of all sampling points\n obscurance = 0.0;\n for (float i = 0.0; i < SAMPLE_COUNT; i += 1.0) {\n computeAmbientOcclusionSAO(obscurance, i, ssDiskRadius, uv, origin, normal, tapPosition, noise);\n tapPosition = angleStep * tapPosition;\n }\n obscurance = sqrt(obscurance * material_intensity);\n}\n\nvec2 pack(highp float normalizedDepth) {\n highp float z = clamp(normalizedDepth, 0.0, 1.0);\n highp float t = floor(256.0 * z);\n mediump float hi = t * (1.0 / 256.0);\n mediump float lo = (256.0 * z) - t;\n return vec2(hi, lo);\n}\n\n\nvoid main(){\n float depth = texture2D(renderer_BlitTexture, v_uv).r;\n float z = depthToViewZ(depth);\n\n // Reconstruct view space position from depth\n vec3 positionVS = computeViewSpacePosition(v_uv, z, material_invProjScaleXY);\n\n // Compute normal\n vec3 normal = computeViewSpaceNormal(v_uv, renderer_BlitTexture, depth, positionVS, renderer_texelSize.xy, material_invProjScaleXY);\n\n float occlusion = 0.0;\n scalableAmbientObscurance(v_uv, positionVS, normal, occlusion);\n\n // Occlusion to visibility\n float aoVisibility = pow(clamp(1.0 - occlusion, 0.0, 1.0), material_power);\n\n gl_FragColor = vec4(aoVisibility, pack(-positionVS.z/camera_ProjectionParams.z), 1.0);\n}\n\n"; // eslint-disable-line
11568
-
11569
11245
  /**
11570
11246
  * @internal
11571
11247
  * Scalable Ambient Obscurance render pass.
@@ -11695,7 +11371,7 @@ var scalableAmbientOcclusionFS = "// Ambient Occlusion, largely inspired from:\n
11695
11371
  };
11696
11372
  return ScalableAmbientObscurancePass;
11697
11373
  }(PipelinePass);
11698
- ScalableAmbientObscurancePass.SHADER_NAME = "ScalableAmbientOcclusion";
11374
+ ScalableAmbientObscurancePass.SHADER_NAME = "Lighting/ScalableAmbientOcclusion";
11699
11375
  ScalableAmbientObscurancePass._invRadiusSquaredProp = ShaderProperty.getByName("material_invRadiusSquared");
11700
11376
  ScalableAmbientObscurancePass._intensityProp = ShaderProperty.getByName("material_intensity");
11701
11377
  ScalableAmbientObscurancePass._projectionScaleRadiusProp = ShaderProperty.getByName("material_projectionScaleRadius");
@@ -11707,10 +11383,6 @@ ScalableAmbientObscurancePass._invProjScaleXYProp = ShaderProperty.getByName("ma
11707
11383
  // Shader properties for bilateral blur
11708
11384
  ScalableAmbientObscurancePass._farPlaneOverEdgeDistanceProp = ShaderProperty.getByName("material_farPlaneOverEdgeDistance");
11709
11385
  ScalableAmbientObscurancePass._kernelProp = ShaderProperty.getByName("material_kernel");
11710
- Shader.create(ScalableAmbientObscurancePass.SHADER_NAME, [
11711
- new ShaderPass("ScalableAmbientOcclusion", blitVs, scalableAmbientOcclusionFS),
11712
- new ShaderPass("BilateralBlur", blitVs, bilateralBlurFS)
11713
- ]);
11714
11386
 
11715
11387
  /**
11716
11388
  * Represents a parameter of a post process effect.
@@ -11949,14 +11621,6 @@ Shader.create(ScalableAmbientObscurancePass.SHADER_NAME, [
11949
11621
  return PostProcessEffect;
11950
11622
  }();
11951
11623
 
11952
- var fragBlurH = "#include <PostCommon>\n\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\nuniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height\n\nvoid main(){\n\tvec2 texelSize = renderer_texelSize.xy * 2.0;\n\n // 9-tap gaussian blur on the downsampled source\n mediump vec4 c0 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(texelSize.x * 4.0, 0.0));\n mediump vec4 c1 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(texelSize.x * 3.0, 0.0));\n mediump vec4 c2 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(texelSize.x * 2.0, 0.0));\n mediump vec4 c3 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(texelSize.x * 1.0, 0.0));\n mediump vec4 c4 = texture2DSRGB(renderer_BlitTexture, v_uv);\n mediump vec4 c5 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(texelSize.x * 1.0, 0.0));\n mediump vec4 c6 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(texelSize.x * 2.0, 0.0));\n mediump vec4 c7 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(texelSize.x * 3.0, 0.0));\n mediump vec4 c8 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(texelSize.x * 4.0, 0.0));\n\n gl_FragColor = c0 * 0.01621622 + c1 * 0.05405405 + c2 * 0.12162162 + c3 * 0.19459459\n + c4 * 0.22702703\n + c5 * 0.19459459 + c6 * 0.12162162 + c7 * 0.05405405 + c8 * 0.01621622;\n}"; // eslint-disable-line
11953
-
11954
- var fragBlurV = "#include <PostCommon>\n\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\nuniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height\n\nvoid main(){\n vec2 texelSize = renderer_texelSize.xy;\n\n // Optimized bilinear 5-tap gaussian on the same-sized source (9-tap equivalent)\n mediump vec4 c0 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(0.0, texelSize.y * 3.23076923));\n mediump vec4 c1 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(0.0, texelSize.y * 1.38461538));\n mediump vec4 c2 = texture2DSRGB(renderer_BlitTexture, v_uv);\n mediump vec4 c3 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(0.0, texelSize.y * 1.38461538));\n mediump vec4 c4 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(0.0, texelSize.y * 3.23076923));\n\n gl_FragColor = c0 * 0.07027027 + c1 * 0.31621622\n + c2 * 0.22702703\n + c3 * 0.31621622 + c4 * 0.07027027;\n}"; // eslint-disable-line
11955
-
11956
- var fragPrefilter = "#include <PostCommon>\n\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\nuniform vec4 material_BloomParams; // x: threshold (linear), y: threshold knee, z: scatter\nuniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height\n\nvoid main(){\n\t#ifdef BLOOM_HQ\n vec2 texelSize = renderer_texelSize.xy;\n mediump vec4 A = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-1.0, -1.0));\n mediump vec4 B = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(0.0, -1.0));\n mediump vec4 C = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(1.0, -1.0));\n mediump vec4 D = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-0.5, -0.5));\n mediump vec4 E = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(0.5, -0.5));\n mediump vec4 F = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-1.0, 0.0));\n mediump vec4 G = texture2DSRGB(renderer_BlitTexture, v_uv);\n mediump vec4 H = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(1.0, 0.0));\n mediump vec4 I = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-0.5, 0.5));\n mediump vec4 J = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(0.5, 0.5));\n mediump vec4 K = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-1.0, 1.0));\n mediump vec4 L = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(0.0, 1.0));\n mediump vec4 M = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(1.0, 1.0));\n\n mediump vec2 scale = vec2(0.5, 0.125);\n mediump vec2 div = (1.0 / 4.0) * scale;\n\n mediump vec4 samplerColor = (D + E + I + J) * div.x;\n samplerColor += (A + B + G + F) * div.y;\n samplerColor += (B + C + H + G) * div.y;\n samplerColor += (F + G + L + K) * div.y;\n samplerColor += (G + H + M + L) * div.y;\n #else\n mediump vec4 samplerColor = texture2DSRGB(renderer_BlitTexture, v_uv);\n #endif\n\n mediump vec3 color = samplerColor.rgb;\n\n // User controlled clamp to limit crazy high broken spec\n color = min(color, HALF_MAX);\n\n // Thresholding\n mediump float brightness = max3(color);\n float threshold = material_BloomParams.x;\n float thresholdKnee = material_BloomParams.y;\n mediump float softness = clamp(brightness - threshold + thresholdKnee, 0.0, 2.0 * thresholdKnee);\n softness = (softness * softness) / (4.0 * thresholdKnee + 1e-4);\n mediump float multiplier = max(brightness - threshold, softness) / max(brightness, 1e-4);\n color *= multiplier;\n\n // Clamp colors to positive once in prefilter. Encode can have a sqrt, and sqrt(-x) == NaN. Up/Downsample passes would then spread the NaN.\n color = max(color, 0.0);\n\n // Bloom is addtive blend mode, we should set alpha 0 to avoid browser background color dark when canvas alpha and premultiplyAlpha is true\n gl_FragColor = vec4(color, 0.0);\n}\n"; // eslint-disable-line
11957
-
11958
- var fragUpsample = "#include <PostCommon>\n#include <Filtering>\n\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\nuniform sampler2D material_lowMipTexture;\nuniform vec4 material_BloomParams; // x: threshold (linear), y: threshold knee, z: scatter\nuniform vec4 material_lowMipTexelSize; // x: 1/width, y: 1/height, z: width, w: height\n\nvoid main(){\n mediump vec4 highMip = texture2DSRGB(renderer_BlitTexture, v_uv);\n\n #ifdef BLOOM_HQ\n mediump vec4 lowMip = sampleTexture2DBicubic(material_lowMipTexture, v_uv, material_lowMipTexelSize);\n #else\n mediump vec4 lowMip = texture2DSRGB(material_lowMipTexture, v_uv);\n #endif\n \n gl_FragColor = mix(highMip, lowMip, material_BloomParams.z);\n}"; // eslint-disable-line
11959
-
11960
11624
  /**
11961
11625
  * This controls the size of the bloom texture.
11962
11626
  */ var BloomDownScaleMode = /*#__PURE__*/ function(BloomDownScaleMode) {
@@ -11995,7 +11659,7 @@ var BloomEffect = /*#__PURE__*/ function(PostProcessEffect) {
11995
11659
  };
11996
11660
  return BloomEffect;
11997
11661
  }(PostProcessEffect);
11998
- BloomEffect.SHADER_NAME = "PostProcessEffect Bloom";
11662
+ BloomEffect.SHADER_NAME = "PostProcess/Bloom";
11999
11663
  // Bloom shader properties
12000
11664
  /** @internal */ BloomEffect._maxIterations = 6;
12001
11665
  /** @internal */ BloomEffect._hqMacro = ShaderMacro.getByName("BLOOM_HQ");
@@ -12013,12 +11677,6 @@ BloomEffect.SHADER_NAME = "PostProcessEffect Bloom";
12013
11677
  /** @internal */ BloomEffect._bloomIntensityParams = ShaderProperty.getByName("material_BloomIntensityParams") // x: bloom intensity, y: dirt intensity
12014
11678
  ;
12015
11679
  /** @internal */ BloomEffect._dirtTilingOffsetProp = ShaderProperty.getByName("material_BloomDirtTilingOffset");
12016
- Shader.create(BloomEffect.SHADER_NAME, [
12017
- new ShaderPass("Bloom Prefilter", blitVs, fragPrefilter),
12018
- new ShaderPass("Bloom Blur Horizontal", blitVs, fragBlurH),
12019
- new ShaderPass("Bloom Blur Vertical", blitVs, fragBlurV),
12020
- new ShaderPass("Bloom Upsample", blitVs, fragUpsample)
12021
- ]);
12022
11680
 
12023
11681
  /**
12024
11682
  * Options to select a tonemapping algorithm to use.
@@ -15281,24 +14939,6 @@ PostProcessManager._tempVector3 = new Vector3();
15281
14939
  return PostProcessPass;
15282
14940
  }(EngineObject);
15283
14941
 
15284
- var Filtering = "#ifndef FILTERING\n#define FILTERING\n\nvec2 bSpline3MiddleLeft(vec2 x){\n return 0.16666667 + x * (0.5 + x * (0.5 - x * 0.5));\n}\n\nvec2 bSpline3MiddleRight(vec2 x){\n return 0.66666667 + x * (-1.0 + 0.5 * x) * x;\n}\n\nvec2 bSpline3Rightmost(vec2 x){\n return 0.16666667 + x * (-0.5 + x * (0.5 - x * 0.16666667));\n}\n\n// Compute weights & offsets for 4x bilinear taps for the bicubic B-Spline filter.\n// The fractional coordinate should be in the [0, 1] range (centered on 0.5).\n// Inspired by: http://vec3.ca/bicubic-filtering-in-fewer-taps/\nvoid bicubicFilter(vec2 fracCoord, out vec2 weights[2], out vec2 offsets[2]){\n vec2 r = bSpline3Rightmost(fracCoord);\n vec2 mr = bSpline3MiddleRight(fracCoord);\n vec2 ml = bSpline3MiddleLeft(fracCoord);\n vec2 l = 1.0 - mr - ml - r;\n\n weights[0] = r + mr;\n weights[1] = ml + l;\n offsets[0] = -1.0 + mr / weights[0];\n offsets[1] = 1.0 + l / weights[1];\n}\n\n\n// texSize: (1/width, 1/height, width, height)\nvec4 sampleTexture2DBicubic(sampler2D tex, vec2 coord, vec4 texSize){\n\tvec2 xy = coord * texSize.zw + 0.5;\n vec2 ic = floor(xy);\n vec2 fc = fract(xy);\n\n vec2 weights[2], offsets[2];\n bicubicFilter(fc, weights, offsets);\n\n return weights[0].y * (weights[0].x * texture2DSRGB(tex, (ic + vec2(offsets[0].x, offsets[0].y) - 0.5) * texSize.xy) +\n \tweights[1].x * texture2DSRGB(tex, (ic + vec2(offsets[1].x, offsets[0].y) - 0.5) * texSize.xy)) +\n weights[1].y * (weights[0].x * texture2DSRGB(tex, (ic + vec2(offsets[0].x, offsets[1].y) - 0.5) * texSize.xy) +\n weights[1].x * texture2DSRGB(tex, (ic + vec2(offsets[1].x, offsets[1].y) - 0.5) * texSize.xy));\n}\n\n\n#endif"; // eslint-disable-line
15285
-
15286
- var PostCommon = "#ifndef POST_COMMON\n#define POST_COMMON\n\n#include <common>\n#define FLT_MIN 1.175494351e-38 // Minimum normalized positive floating-point number\n#define HALF_MIN 6.103515625e-5 // 2^-14, the same value for 10, 11 and 16-bit: https://www.khronos.org/opengl/wiki/Small_Float_Formats\n#define HALF_MAX 65504.0 // (2 - 2^-10) * 2^15\n\nfloat min3(vec3 val) { return min(min(val.x, val.y), val.z); }\nfloat max3(vec3 val) { return max(max(val.x, val.y), val.z); }\n\nconst float INVERT_LOG10 = 0.43429448190325176;\n\nfloat log10(float x){\n return log(x) * INVERT_LOG10;\n}\n\n#endif"; // eslint-disable-line
15287
-
15288
- var ACESTonemapping = "#include <ColorTransform>\n#include <RRT>\n#include <ODT>\n\nvec3 ACESTonemap(vec3 color){\n vec3 aces = sRGB_2_AP0 * color;\n \n // --- Glow module --- //\n mediump float saturation = rgb_2_saturation(aces);\n mediump float ycIn = rgb_2_yc(aces);\n mediump float s = sigmoid_shaper((saturation - 0.4) / 0.2);\n float addedGlow = 1.0 + glow_fwd(ycIn, RRT_GLOW_GAIN * s, RRT_GLOW_MID);\n aces *= addedGlow;\n\n // --- Red modifier --- //\n mediump float hue = rgb_2_hue(vec3(aces));\n mediump float centeredHue = center_hue(hue, RRT_RED_HUE);\n float hueWeight = smoothstep(0.0, 1.0, 1.0 - abs(2.0 * centeredHue / RRT_RED_WIDTH));\n hueWeight *= hueWeight;\n\n aces.r += hueWeight * saturation * (RRT_RED_PIVOT - aces.r) * (1.0 - RRT_RED_SCALE);\n\n // --- ACES to RGB rendering space --- //\n vec3 acescg = max(AP0_2_AP1_MAT * aces, 0.0);\n\n // --- Global desaturation --- //\n acescg = mix(vec3(dot(acescg, AP1_RGB2Y)), acescg, RRT_SAT_FACTOR);\n\n // Apply RRT and ODT\n // https://github.com/TheRealMJP/BakingLab/blob/master/BakingLab/ACES.hlsl\n const float a = 0.0245786;\n const float b = 0.000090537;\n const float c = 0.983729;\n const float d = 0.4329510;\n const float e = 0.238081;\n\n // To reduce the likelyhood of extremely large values, we avoid using the x^2 term and therefore\n // divide numerator and denominator by it. This will lead to the constant factors of the\n // quadratic in the numerator and denominator to be divided by x; we add a tiny epsilon to avoid divide by 0.\n vec3 rcpAcesCG = 1.0 / (acescg + FLT_MIN);\n mediump vec3 rgbPost = (acescg + a - b * rcpAcesCG) /\n (acescg * c + d + e * rcpAcesCG);\n\n // Apply gamma adjustment to compensate for dim surround\n vec3 linearCV = darkSurround_to_dimSurround(rgbPost);\n\n // Apply desaturation to compensate for luminance difference\n linearCV = mix(vec3(dot(linearCV, AP1_RGB2Y)), linearCV, ODT_SAT_FACTOR);\n\n // Convert to display primary encoding\n // Rendering space RGB to XYZ\n vec3 XYZ = AP1_2_XYZ_MAT * linearCV;\n\n // Apply CAT from ACES white point to assumed observer adapted white point\n XYZ = D60_2_D65_CAT * XYZ;\n\n // CIE XYZ to display primaries\n linearCV = XYZ_2_REC709_MAT * XYZ;\n\n return linearCV;\n\n}"; // eslint-disable-line
15289
-
15290
- var ColorTransform = "#ifndef COLOR_TRANSFORM\n#define COLOR_TRANSFORM\n\n// Precomputed matrices (pre-transposed)\n// See https://github.com/ampas/aces-dev/blob/master/transforms/ctl/README-MATRIX.md\n \n const mediump mat3 sRGB_2_AP0 = mat3(\n 0.4397010, 0.0897923, 0.0175440,\n 0.3829780, 0.8134230, 0.1115440,\n 0.1773350, 0.0967616, 0.8707040\n );\n\n const mediump mat3 AP1_2_AP0_MAT = mat3(\n vec3(0.6954522414, 0.0447945634, -0.0055258826),\n vec3(0.1406786965, 0.8596711185, 0.0040252103),\n vec3(0.1638690622, 0.0955343182, 1.0015006723)\n );\n\n const mediump mat3 AP0_2_AP1_MAT = mat3(\n\tvec3(1.4514393161, -0.0765537734, 0.0083161484),\n vec3(-0.2365107469, 1.1762296998, -0.0060324498),\n vec3(-0.2149285693, -0.0996759264, 0.9977163014)\n );\n\n const mediump mat3 AP1_2_XYZ_MAT = mat3(\n vec3(0.6624541811, 0.2722287168, -0.0055746495),\n vec3(0.1340042065, 0.6740817658, 0.0040607335),\n vec3(0.1561876870, 0.0536895174, 1.0103391003)\n );\n\n const mediump mat3 XYZ_2_AP1_MAT = mat3(\n vec3(1.6410233797, -0.6636628587, 0.0117218943),\n vec3(-0.3248032942, 1.6153315917, -0.0082844420),\n vec3(-0.2364246952, 0.0167563477, 0.9883948585)\n );\n\n const mediump mat3 D60_2_D65_CAT = mat3(\n vec3(0.987224, -0.00759836, 0.00307257),\n vec3(-0.00611327, 1.00186, -0.00509595),\n vec3(0.0159533, 0.00533002, 1.08168)\n );\n\n const mediump mat3 XYZ_2_REC709_MAT = mat3(\n vec3(3.2409699419, -0.9692436363, 0.0556300797),\n vec3(-1.5373831776, 1.8759675015, -0.2039769589),\n vec3(-0.498610760, 0.0415550574, 1.0569715142)\n );\n\n const mediump vec3 AP1_RGB2Y = vec3(0.2722287168, 0.6740817658, 0.0536895174);\n\n mediump float rgb_2_saturation(mediump vec3 rgb){\n const mediump float TINY = 1e-4;\n mediump float mi = min3(rgb);\n mediump float ma = max3(rgb);\n return (max(ma, TINY) - max(mi, TINY)) / max(ma, 1e-2);\n }\n\n mediump float rgb_2_yc(mediump vec3 rgb){\n const mediump float ycRadiusWeight = 1.75;\n\n // Converts RGB to a luminance proxy, here called YC\n // YC is ~ Y + K * Chroma\n // Constant YC is a cone-shaped surface in RGB space, with the tip on the\n // neutral axis, towards white.\n // YC is normalized: RGB 1 1 1 maps to YC = 1\n //\n // ycRadiusWeight defaults to 1.75, although can be overridden in function\n // call to rgb_2_yc\n // ycRadiusWeight = 1 -> YC for pure cyan, magenta, yellow == YC for neutral\n // of same value\n // ycRadiusWeight = 2 -> YC for pure red, green, blue == YC for neutral of\n // same value.\n\n mediump float r = rgb.x;\n mediump float g = rgb.y;\n mediump float b = rgb.z;\n mediump float k = b * (b - g) + g * (g - r) + r * (r - b);\n k = max(k, 0.0); // Clamp to avoid precision issue causing k < 0, making sqrt(k) undefined\n float chroma = k == 0.0 ? 0.0 : sqrt(k); // Avoid NaN\n\n return (b + g + r + ycRadiusWeight * chroma) / 3.0;\n }\n\n mediump float rgb_2_hue(mediump vec3 rgb){\n // Returns a geometric hue angle in degrees (0-360) based on RGB values.\n // For neutral colors, hue is undefined and the function will return a quiet NaN value.\n mediump float hue;\n if (rgb.x == rgb.y && rgb.y == rgb.z){\n hue = 0.0; // RGB triplets where RGB are equal have an undefined hue\n } else{\n hue = (180.0 / PI) * atan(sqrt(3.0) * (rgb.y - rgb.z), 2.0 * rgb.x - rgb.y - rgb.z);\n }\n\n if (hue < 0.0){\n hue = hue + 360.0;\n } \n\n return hue;\n }\n\n mediump float center_hue(mediump float hue, mediump float centerH){\n mediump float hueCentered = hue - centerH;\n if (hueCentered < -180.0){\n hueCentered = hueCentered + 360.0;\n } else if (hueCentered > 180.0){\n hueCentered = hueCentered - 360.0;\n } \n\n return hueCentered;\n }\n\n\n\n#endif"; // eslint-disable-line
15291
-
15292
- var ODT = "#include <Tonescale>\n\n// Output Device Transform - RGB computer monitor\n\nconst float CINEMA_WHITE = 48.0;\nconst float CINEMA_BLACK = 0.02; // CINEMA_WHITE / 2400.0;\nconst float ODT_SAT_FACTOR = 0.93;\n\nmediump vec3 Y_2_linCV(mediump vec3 Y, mediump float Ymax, mediump float Ymin){\n return (Y - Ymin) / (Ymax - Ymin);\n}\n\nmediump vec3 XYZ_2_xyY(mediump vec3 XYZ){\n mediump float divisor = max(dot(XYZ, vec3(1.0)), 1e-4);\n return vec3(XYZ.xy / divisor, XYZ.y);\n}\n\nmediump vec3 xyY_2_XYZ(mediump vec3 xyY){\n mediump float m = xyY.z / max(xyY.y, 1e-4);\n mediump vec3 XYZ = vec3(xyY.xz, (1.0 - xyY.x - xyY.y));\n XYZ.xz *= m;\n return XYZ;\n}\n\nconst mediump float DIM_SURROUND_GAMMA = 0.9811;\n\nmediump vec3 darkSurround_to_dimSurround(mediump vec3 linearCV){\n // Extra conversions to float3/vec3 are required to avoid floating-point precision issues on some platforms.\n\n mediump vec3 XYZ = AP1_2_XYZ_MAT * linearCV;\n mediump vec3 xyY = XYZ_2_xyY(XYZ);\n xyY.z = clamp(xyY.z, 0.0, HALF_MAX);\n xyY.z = pow(xyY.z, DIM_SURROUND_GAMMA);\n XYZ = xyY_2_XYZ(xyY);\n\n return XYZ_2_AP1_MAT * XYZ;\n}\n\n//\n// Summary :\n// This transform is intended for mapping OCES onto a desktop computer monitor\n// typical of those used in motion picture visual effects production. These\n// monitors may occasionally be referred to as \"sRGB\" displays, however, the\n// monitor for which this transform is designed does not exactly match the\n// specifications in IEC 61966-2-1:1999.\n//\n// The assumed observer adapted white is D65, and the viewing environment is\n// that of a dim surround.\n//\n// The monitor specified is intended to be more typical of those found in\n// visual effects production.\n//\n// Device Primaries :\n// Primaries are those specified in Rec. ITU-R BT.709\n// CIE 1931 chromaticities: x y Y\n// Red: 0.64 0.33\n// Green: 0.3 0.6\n// Blue: 0.15 0.06\n// White: 0.3127 0.329 100 cd/m^2\n//\n// Display EOTF :\n// The reference electro-optical transfer function specified in\n// IEC 61966-2-1:1999.\n//\n// Signal Range:\n// This transform outputs full range code values.\n//\n// Assumed observer adapted white point:\n// CIE 1931 chromaticities: x y\n// 0.3127 0.329\n//\n\n// Viewing Environment:\n// This ODT has a compensation for viewing environment variables more typical\n// of those associated with video mastering.\n//\nmediump vec3 ODT_RGBmonitor_100nits_dim(mediump vec3 oces){\n // The metal compiler does not optimize structure access\n // const SegmentedSplineParams_c9 ODT_48nits = SegmentedSplineParams_c9(\n // // coefsLow[10]\n // float[10]( -1.6989700043, -1.6989700043, -1.4779000000, -1.2291000000, -0.8648000000, -0.4480000000, 0.0051800000, 0.4511080334, 0.9113744414, 0.9113744414),\n // // coefsHigh[10]\n // float[10]( 0.5154386965, 0.8470437783, 1.1358000000, 1.3802000000, 1.5197000000, 1.5985000000, 1.6467000000, 1.6746091357, 1.6878733390, 1.6878733390 ),\n // vec2(segmented_spline_c5_fwd(0.18*pow(2.,-6.5)), 0.02), // minPoint\n // vec2(segmented_spline_c5_fwd(0.18), 4.8), // midPoint\n // vec2(segmented_spline_c5_fwd(0.18*pow(2.,6.5)), 48.0), // maxPoint\n // 0.0, // slopeLow\n // 0.04 // slopeHigh\n // );\n\n // OCES to RGB rendering space\n mediump vec3 rgbPre = AP0_2_AP1_MAT * oces;\n\n // Apply the tonescale independently in rendering-space RGB\n mediump vec3 rgbPost;\n\n // rgbPost.r = segmented_spline_c9_fwd(rgbPre.r, ODT_48nits);\n // rgbPost.g = segmented_spline_c9_fwd(rgbPre.g, ODT_48nits);\n // rgbPost.b = segmented_spline_c9_fwd(rgbPre.b, ODT_48nits);\n\n rgbPost.r = segmented_spline_c9_fwd(rgbPre.r);\n rgbPost.g = segmented_spline_c9_fwd(rgbPre.g);\n rgbPost.b = segmented_spline_c9_fwd(rgbPre.b);\n\n // Scale luminance to linear code value\n mediump vec3 linearCV = Y_2_linCV(rgbPost, CINEMA_WHITE, CINEMA_BLACK);\n\n // Apply gamma adjustment to compensate for dim surround\n linearCV = darkSurround_to_dimSurround(linearCV);\n\n // Apply desaturation to compensate for luminance difference\n linearCV = mix(vec3(dot(linearCV, AP1_RGB2Y)), linearCV, ODT_SAT_FACTOR);\n\n // Convert to display primary encoding\n // Rendering space RGB to XYZ\n mediump vec3 XYZ = AP1_2_XYZ_MAT * linearCV;\n\n // Apply CAT from ACES white point to assumed observer adapted white point\n XYZ = D60_2_D65_CAT * XYZ;\n\n // CIE XYZ to display primaries\n linearCV = XYZ_2_REC709_MAT * XYZ;\n\n // Handle out-of-gamut values\n // Clip values < 0 or > 1 (i.e. projecting outside the display primaries)\n linearCV = clamp(linearCV, vec3(0), vec3(1));\n\n // Unity already draws to a sRGB target\n return linearCV;\n}"; // eslint-disable-line
15293
-
15294
- var RRT = "#include <Tonescale>\n\n// Reference Rendering Transform (RRT)\n\n// Sigmoid function in the range 0 to 1 spanning -2 to +2.\nmediump float sigmoid_shaper(mediump float x){\n mediump float t = max(1.0 - abs(x / 2.0), 0.0);\n mediump float y = 1.0 + sign(x) * (1.0 - t * t);\n\n return y * 0.5;\n}\n\nmediump float glow_fwd(mediump float ycIn, mediump float glowGainIn, mediump float glowMid){\n mediump float glowGainOut;\n\n if (ycIn <= 2.0 / 3.0 * glowMid){\n glowGainOut = glowGainIn;\n } else if (ycIn >= 2.0 * glowMid){\n glowGainOut = 0.0;\n } else{\n glowGainOut = glowGainIn * (glowMid / ycIn - 1.0 / 2.0);\n }\n\n return glowGainOut;\n}\n\n\n// \"Glow\" module constants\nconst mediump float RRT_GLOW_GAIN = 0.05;\nconst mediump float RRT_GLOW_MID = 0.08;\n\n// Red modifier constants\nconst mediump float RRT_RED_SCALE = 0.82;\nconst mediump float RRT_RED_PIVOT = 0.03;\nconst mediump float RRT_RED_HUE = 0.0;\nconst mediump float RRT_RED_WIDTH = 135.0;\n\n// Desaturation contants\nconst mediump float RRT_SAT_FACTOR = 0.96;\n\n\n// ACES to OCES\nmediump vec3 RRT(mediump vec3 aces){\n // --- Glow module --- //\n mediump float saturation = rgb_2_saturation(aces);\n mediump float ycIn = rgb_2_yc(aces);\n mediump float s = sigmoid_shaper((saturation - 0.4) / 0.2);\n mediump float addedGlow = 1.0 + glow_fwd(ycIn, RRT_GLOW_GAIN * s, RRT_GLOW_MID);\n aces *= addedGlow;\n\n // --- Red modifier --- //\n mediump float hue = rgb_2_hue(aces);\n mediump float centeredHue = center_hue(hue, RRT_RED_HUE);\n\n mediump float hueWeight = smoothstep(0.0, 1.0, 1.0 - abs(2.0 * centeredHue / RRT_RED_WIDTH));\n hueWeight *= hueWeight;\n\n aces.r += hueWeight * saturation * (RRT_RED_PIVOT - aces.r) * (1.0 - RRT_RED_SCALE);\n\n // --- ACES to RGB rendering space --- //\n aces = clamp(aces, 0.0, HALF_MAX); // avoids saturated negative colors from becoming positive in the matrix\n mediump vec3 rgbPre = AP0_2_AP1_MAT * aces;\n rgbPre = clamp(rgbPre, 0.0, HALF_MAX);\n\n // --- Global desaturation --- //\n rgbPre = mix(vec3(dot(rgbPre, AP1_RGB2Y)), rgbPre, RRT_SAT_FACTOR);\n\n // --- Apply the tonescale independently in rendering-space RGB --- //\n mediump vec3 rgbPost;\n rgbPost.x = segmented_spline_c5_fwd(rgbPre.x);\n rgbPost.y = segmented_spline_c5_fwd(rgbPre.y);\n rgbPost.z = segmented_spline_c5_fwd(rgbPre.z);\n\n // --- RGB rendering space to OCES --- //\n mediump vec3 outputVal = AP1_2_AP0_MAT * rgbPost;\n\n return outputVal;\n}"; // eslint-disable-line
15295
-
15296
- var Tonescale = " #ifndef TONE_SCALE\n #define TONE_SCALE\n \n const mediump mat3 M = mat3(\n vec3(0.5, -1.0, 0.5),\n vec3(-1.0, 1.0, 0.5),\n vec3(0.5, 0.0, 0.0)\n );\n\n mediump float segmented_spline_c5_fwd(mediump float x){\n #ifdef GRAPHICS_API_WEBGL2\n const mediump float coefsLow[6] = float[6](-4.0000000000, -4.0000000000, -3.1573765773, -0.4852499958, 1.8477324706, 1.8477324706); // coefs for B-spline between minPoint and midPoint (units of log luminance)\n const mediump float coefsHigh[6] = float[6](-0.7185482425, 2.0810307172, 3.6681241237, 4.0000000000, 4.0000000000, 4.0000000000); // coefs for B-spline between midPoint and maxPoint (units of log luminance)\n #else\n const mediump float coefsLow_0 = -4.0000000000;\n const mediump float coefsLow_1 = -4.0000000000;\n const mediump float coefsLow_2 = -3.1573765773;\n const mediump float coefsLow_3 = -0.4852499958;\n const mediump float coefsLow_4 = 1.8477324706;\n const mediump float coefsLow_5 = 1.8477324706;\n\n const mediump float coefsHigh_0 = -0.7185482425;\n const mediump float coefsHigh_1 = 2.0810307172;\n const mediump float coefsHigh_2 = 3.6681241237;\n const mediump float coefsHigh_3 = 4.0000000000;\n const mediump float coefsHigh_4 = 4.0000000000;\n const mediump float coefsHigh_5 = 4.0000000000;\n #endif\n\n // const vec2 minPoint = vec2(0.18 * exp2(-15.0), 0.0001); // {luminance, luminance} linear extension below this\n const mediump vec2 minPoint = vec2(0.0000054931640625, 0.0001); // {luminance, luminance} linear extension below this\n const mediump vec2 midPoint = vec2(0.18, 0.48); // {luminance, luminance}\n // const vec2 maxPoint = vec2(0.18 * exp2(18.0), 10000.0); // {luminance, luminance} linear extension above this\n const mediump vec2 maxPoint = vec2(47185.92, 10000.0); // {luminance, luminance} linear extension above this\n const mediump float slopeLow = 0.0; // log-log slope of low linear extension\n const mediump float slopeHigh = 0.0; // log-log slope of high linear extension\n\n const int N_KNOTS_LOW = 4;\n const int N_KNOTS_HIGH = 4;\n\n // Check for negatives or zero before taking the log. If negative or zero,\n // set to ACESMIN.1\n mediump float logx = log10(max(x, HALF_MIN));\n mediump float logy;\n\n if (logx <= log10(minPoint.x)){\n logy = logx * slopeLow + (log10(minPoint.y) - slopeLow * log10(minPoint.x));\n } else if ((logx > log10(minPoint.x)) && (logx < log10(midPoint.x))){\n mediump float knot_coord = float(N_KNOTS_LOW - 1) * (logx - log10(minPoint.x)) / (log10(midPoint.x) - log10(minPoint.x));\n int j = int(knot_coord);\n mediump float t = knot_coord - float(j);\n\n mediump vec3 cf;\n #ifdef GRAPHICS_API_WEBGL2\n cf = vec3(coefsLow[j], coefsLow[j + 1], coefsLow[j + 2]);\n #else\n if (j <= 0) {\n cf = vec3(coefsLow_0, coefsLow_1, coefsLow_2);\n } else if (j == 1) {\n cf = vec3(coefsLow_1, coefsLow_2, coefsLow_3);\n } else if (j == 2) {\n cf = vec3(coefsLow_2, coefsLow_3, coefsLow_4);\n } else { // if (j == 3)\n cf = vec3(coefsLow_3, coefsLow_4, coefsLow_5);\n }\n #endif\n\n mediump vec3 monomials = vec3(t * t, t, 1.0);\n logy = dot(monomials, M * cf);\n } else if ((logx >= log10(midPoint.x)) && (logx < log10(maxPoint.x))){\n mediump float knot_coord = float(N_KNOTS_HIGH - 1) * (logx - log10(midPoint.x)) / (log10(maxPoint.x) - log10(midPoint.x));\n int j = int(knot_coord);\n mediump float t = knot_coord - float(j);\n\n mediump vec3 cf;\n #ifdef GRAPHICS_API_WEBGL2\n cf = vec3(coefsHigh[j], coefsHigh[j + 1], coefsHigh[j + 2]);\n #else\n if (j <= 0) {\n cf = vec3(coefsHigh_0, coefsHigh_1, coefsHigh_2);\n } else if (j == 1) {\n cf = vec3(coefsHigh_1, coefsHigh_2, coefsHigh_3);\n } else if (j == 2) {\n cf = vec3(coefsHigh_2, coefsHigh_3, coefsHigh_4);\n } else { // if (j == 3)\n cf = vec3(coefsHigh_3, coefsHigh_4, coefsHigh_5);\n }\n #endif\n\n mediump vec3 monomials = vec3(t * t, t, 1.0);\n logy = dot(monomials, M * cf);\n } else {\n logy = logx * slopeHigh + (log10(maxPoint.y) - slopeHigh * log10(maxPoint.x));\n }\n\n return pow(10.0, logy);\n }\n\n // The metal compiler does not optimize structure access\n // struct SegmentedSplineParams_c9{\n // float coefsLow[10]; // coefs for B-spline between minPoint and midPoint (units of log luminance)\n // float coefsHigh[10]; // coefs for B-spline between midPoint and maxPoint (units of log luminance)\n // mediump vec2 minPoint; // {luminance, luminance} linear extension below this\n // mediump vec2 midPoint; // {luminance, luminance}\n // mediump vec2 maxPoint; // {luminance, luminance} linear extension above this\n // float slopeLow; // log-log slope of low linear extension\n // float slopeHigh; // log-log slope of high linear extension\n // };\n\n\n mediump float segmented_spline_c9_fwd(mediump float x){\n // ODT_48nits\n #ifdef GRAPHICS_API_WEBGL2\n const mediump float coefsLow[10] = float[10](-1.6989700043, -1.6989700043, -1.4779000000, -1.2291000000, -0.8648000000, -0.4480000000, 0.0051800000, 0.4511080334, 0.9113744414, 0.9113744414);\n const mediump float coefsHigh[10] = float[10](0.5154386965, 0.8470437783, 1.1358000000, 1.3802000000, 1.5197000000, 1.5985000000, 1.6467000000, 1.6746091357, 1.6878733390, 1.6878733390);\n #else\n const mediump float coefsLow_0 = -1.6989700043;\n const mediump float coefsLow_1 = -1.6989700043;\n const mediump float coefsLow_2 = -1.4779000000;\n const mediump float coefsLow_3 = -1.2291000000;\n const mediump float coefsLow_4 = -0.8648000000;\n const mediump float coefsLow_5 = -0.4480000000;\n const mediump float coefsLow_6 = 0.0051800000;\n const mediump float coefsLow_7 = 0.4511080334;\n const mediump float coefsLow_8 = 0.9113744414;\n const mediump float coefsLow_9 = 0.9113744414;\n\n const mediump float coefsHigh_0 = 0.5154386965;\n const mediump float coefsHigh_1 = 0.8470437783;\n const mediump float coefsHigh_2 = 1.1358000000;\n const mediump float coefsHigh_3 = 1.3802000000;\n const mediump float coefsHigh_4 = 1.5197000000;\n const mediump float coefsHigh_5 = 1.5985000000;\n const mediump float coefsHigh_6 = 1.6467000000;\n const mediump float coefsHigh_7 = 1.6746091357;\n const mediump float coefsHigh_8 = 1.6878733390;\n const mediump float coefsHigh_9 = 1.6878733390;\n #endif\n\n // mediump vec2 minPoint = vec2(segmented_spline_c5_fwd(0.18 * pow(2.0, -6.5)), 0.02);\n // mediump vec2 midPoint = vec2(segmented_spline_c5_fwd(0.18), 4.8);\n // mediump vec2 maxPoint = vec2(segmented_spline_c5_fwd(0.18 * pow(2., 6.5)), 48.0);\n\n const mediump vec2 minPoint = vec2(0.0028799, 0.02);\n const mediump vec2 midPoint = vec2(4.799999, 4.8);\n const mediump vec2 maxPoint = vec2(1005.719, 48.0);\n\n const mediump float slopeLow = 0.0;\n const mediump float slopeHigh = 0.04;\n\n const int N_KNOTS_LOW = 8;\n const int N_KNOTS_HIGH = 8;\n\n // Check for negatives or zero before taking the log. If negative or zero,\n // set to OCESMIN.\n mediump float logx = log10(max(x, 1e-4));\n mediump float logy;\n\n if (logx <= log10(minPoint.x)) {\n logy = logx * slopeLow + (log10(minPoint.y) - slopeLow * log10(minPoint.x));\n } else if ((logx > log10(minPoint.x)) && (logx < log10(midPoint.x))) {\n mediump float knot_coord = float(N_KNOTS_LOW - 1) * (logx - log10(minPoint.x)) / (log10(midPoint.x) - log10(minPoint.x));\n int j = int(knot_coord);\n mediump float t = knot_coord - float(j);\n\n mediump vec3 cf;\n #ifdef GRAPHICS_API_WEBGL2\n cf = vec3(coefsLow[j], coefsLow[j + 1], coefsLow[j + 2]);\n #else\n if (j <= 0) {\n cf = vec3(coefsLow_0, coefsLow_1, coefsLow_2);\n } else if (j == 1) {\n cf = vec3(coefsLow_1, coefsLow_2, coefsLow_3);\n } else if (j == 2) {\n cf = vec3(coefsLow_2, coefsLow_3, coefsLow_4);\n } else if (j == 3) {\n cf = vec3(coefsLow_3, coefsLow_4, coefsLow_5);\n } else if (j == 4) {\n cf = vec3(coefsLow_4, coefsLow_5, coefsLow_6);\n } else if (j == 5) {\n cf = vec3(coefsLow_5, coefsLow_6, coefsLow_7);\n } else if (j == 6) {\n cf = vec3(coefsLow_6, coefsLow_7, coefsLow_8);\n } else { // if (j == 7)\n cf = vec3(coefsLow_7, coefsLow_8, coefsLow_9);\n }\n #endif\n\n mediump vec3 monomials = vec3(t * t, t, 1.0);\n logy = dot(monomials, M * cf);\n } else if ((logx >= log10(midPoint.x)) && (logx < log10(maxPoint.x))) {\n mediump float knot_coord = float(N_KNOTS_HIGH - 1) * (logx - log10(midPoint.x)) / (log10(maxPoint.x) - log10(midPoint.x));\n int j = int(knot_coord);\n mediump float t = knot_coord - float(j);\n\n mediump vec3 cf;\n #ifdef GRAPHICS_API_WEBGL2\n cf = vec3(coefsHigh[j], coefsHigh[j + 1], coefsHigh[j + 2]);\n #else\n if (j <= 0) {\n cf = vec3(coefsHigh_0, coefsHigh_1, coefsHigh_2);\n } else if (j == 1) {\n cf = vec3(coefsHigh_1, coefsHigh_2, coefsHigh_3);\n } else if (j == 2) {\n cf = vec3(coefsHigh_2, coefsHigh_3, coefsHigh_4);\n } else if (j == 3) {\n cf = vec3(coefsHigh_3, coefsHigh_4, coefsHigh_5);\n } else if (j == 4) {\n cf = vec3(coefsHigh_4, coefsHigh_5, coefsHigh_6);\n } else if (j == 5) {\n cf = vec3(coefsHigh_5, coefsHigh_6, coefsHigh_7);\n } else if (j == 6) {\n cf = vec3(coefsHigh_6, coefsHigh_7, coefsHigh_8);\n } else { // if (j == 7)\n cf = vec3(coefsHigh_7, coefsHigh_8, coefsHigh_9);\n }\n #endif\n\n mediump vec3 monomials = vec3(t * t, t, 1.0);\n logy = dot(monomials, M * cf);\n } else {\n logy = logx * slopeHigh + (log10(maxPoint.y) - slopeHigh * log10(maxPoint.x));\n }\n\n return pow(10.0, logy);\n }\n\n\n#endif"; // eslint-disable-line
15297
-
15298
- var NeutralTonemapping = "// Neutral tonemapping (Hable/Hejl/Frostbite)\n// Input is linear RGB\n// More accuracy to avoid NaN on extremely high values.\nvec3 neutralCurve(vec3 x, float a, float b, float c, float d, float e, float f){\n return vec3(((x * (a * x + c * b) + d * e) / (x * (a * x + b) + d * f)) - e / f);\n}\n\n#define TONEMAPPING_CLAMP_MAX 435.18712 //(-b + sqrt(b * b - 4 * a * (HALF_MAX - d * f))) / (2 * a * whiteScale)\n//Extremely high values cause NaN output when using fp16, we clamp to avoid the performace hit of switching to fp32\n//The overflow happens in (x * (a * x + b) + d * f) of the NeutralCurve, highest value that avoids fp16 precision errors is ~571.56873\n//Since whiteScale is constant (~1.31338) max input is ~435.18712\n\nvec3 neutralTonemap(vec3 color){\n const float a = 0.2;\n const float b = 0.29;\n const float c = 0.24;\n const float d = 0.272;\n const float e = 0.02;\n const float f = 0.3;\n // const float whiteLevel = 5.3;\n // const float whiteClip = 1.0;\n\n #ifndef GL_FRAGMENT_PRECISION_HIGH\n color = min(color, TONEMAPPING_CLAMP_MAX);\n #endif\n\n // 1.0 / neutralCurve(whiteLevel, a, b, c, d, e, f);\n const float whiteScale = 1.31338; \n color = neutralCurve(color * whiteScale, a, b, c, d, e, f);\n color *= whiteScale;\n\n // Post-curve white point adjustment\n // color /= whiteClip;\n\n return color;\n}"; // eslint-disable-line
15299
-
15300
- var UberPost = "#include <PostCommon>\n#include <Filtering>\n#include <NeutralTonemapping>\n#include <ACESTonemapping>\n\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\nuniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height\n#ifdef ENABLE_EFFECT_BLOOM\n\tuniform sampler2D material_BloomTexture;\n\tuniform sampler2D material_BloomDirtTexture;\n\tuniform vec4 material_BloomTint;\n\tuniform vec4 material_BloomDirtTilingOffset;\n\tuniform vec4 material_BloomIntensityParams; // x: bloom intensity, y: dirt intensity\n#endif\n\n\nvoid main(){\n\tmediump vec4 color = texture2DSRGB(renderer_BlitTexture, v_uv);\n\n\t#ifdef ENABLE_EFFECT_BLOOM\n \t#ifdef BLOOM_HQ\n \t mediump vec4 bloom = sampleTexture2DBicubic(material_BloomTexture, v_uv, renderer_texelSize);\n \t#else\n \t mediump vec4 bloom = texture2DSRGB(material_BloomTexture, v_uv);\n \t#endif\n\n \tbloom *= material_BloomIntensityParams.x;\n \tcolor += bloom * material_BloomTint;\n\n \t#ifdef BLOOM_DIRT\n \t mediump vec4 dirt = texture2DSRGB(material_BloomDirtTexture, v_uv * material_BloomDirtTilingOffset.xy + material_BloomDirtTilingOffset.zw);\n \t dirt *= material_BloomIntensityParams.y;\n \t // Additive bloom (artist friendly)\n \t color += dirt * bloom;\n \t#endif\n\t#endif\n\n\t#ifdef ENABLE_EFFECT_TONEMAPPING\n\t\t#if TONEMAPPING_MODE == 0\n \t\tcolor.rgb = neutralTonemap(color.rgb);\n \t#elif TONEMAPPING_MODE == 1\n \t\tcolor.rgb = ACESTonemap(color.rgb);\n \t#endif\n\n \tcolor.rgb = clamp(color.rgb, vec3(0), vec3(1));\n\t#endif\n\n gl_FragColor = color;\n}"; // eslint-disable-line
15301
-
15302
14942
  var PostProcessUberPass = /*#__PURE__*/ function(PostProcessPass) {
15303
14943
  _inherits(PostProcessUberPass, PostProcessPass);
15304
14944
  function PostProcessUberPass(engine) {
@@ -15307,15 +14947,9 @@ var PostProcessUberPass = /*#__PURE__*/ function(PostProcessPass) {
15307
14947
  _this.event = PostProcessPassEvent.AfterUber - 1;
15308
14948
  // Uber Material
15309
14949
  var uberMaterial = new Material(engine, Shader.find(PostProcessUberPass.UBER_SHADER_NAME));
15310
- var uberDepthState = uberMaterial.renderState.depthState;
15311
- uberDepthState.enabled = false;
15312
- uberDepthState.writeEnabled = false;
15313
14950
  _this._uberMaterial = uberMaterial;
15314
14951
  // Bloom Material
15315
14952
  var bloomMaterial = new Material(engine, Shader.find(BloomEffect.SHADER_NAME));
15316
- var bloomDepthState = bloomMaterial.renderState.depthState;
15317
- bloomDepthState.enabled = false;
15318
- bloomDepthState.writeEnabled = false;
15319
14953
  _this._bloomMaterial = bloomMaterial;
15320
14954
  // ShaderData initialization
15321
14955
  var bloomShaderData = bloomMaterial.shaderData;
@@ -15473,24 +15107,7 @@ var PostProcessUberPass = /*#__PURE__*/ function(PostProcessPass) {
15473
15107
  };
15474
15108
  return PostProcessUberPass;
15475
15109
  }(PostProcessPass);
15476
- PostProcessUberPass.UBER_SHADER_NAME = "UberPost";
15477
- Object.assign(ShaderLib, {
15478
- PostCommon: PostCommon,
15479
- Filtering: Filtering,
15480
- ODT: ODT,
15481
- RRT: RRT,
15482
- Tonescale: Tonescale,
15483
- ColorTransform: ColorTransform,
15484
- NeutralTonemapping: NeutralTonemapping,
15485
- ACESTonemapping: ACESTonemapping
15486
- });
15487
- Shader.create(PostProcessUberPass.UBER_SHADER_NAME, blitVs, UberPost);
15488
-
15489
- var FinalAntiAliasingFS = "#define FXAA_PC 1\n#define FXAA_QUALITY_PRESET 12\n#define FXAA_GREEN_AS_LUMA 0\n#if defined(GRAPHICS_API_WEBGL2)\n #define FXAA_GLSL_130 1\n#elif defined(GRAPHICS_API_WEBGL1)\n #define FXAA_GLSL_120 1\n#endif\n\n#include <common>\n#include <FXAA3_11>\n\nconst FxaaFloat FXAA_SUBPIXEL_BLEND_AMOUNT = 0.75;\nconst FxaaFloat FXAA_RELATIVE_CONTRAST_THRESHOLD = 0.166;\nconst FxaaFloat FXAA_ABSOLUTE_CONTRAST_THRESHOLD = 0.0833;\n\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\nuniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height\n\nvec4 applyFXAA(vec4 color, vec2 positionNDC, vec4 sourceSize, sampler2D blitTexture)\n{\n return FxaaPixelShader(\n positionNDC,\n color,\n blitTexture,\n sourceSize.xy,\n FXAA_SUBPIXEL_BLEND_AMOUNT,\n FXAA_RELATIVE_CONTRAST_THRESHOLD,\n FXAA_ABSOLUTE_CONTRAST_THRESHOLD\n );\n}\n\nvoid main(){\n\tmediump vec4 color = texture2D(renderer_BlitTexture, v_uv);\n\n color = applyFXAA(color, v_uv, renderer_texelSize, renderer_BlitTexture);\n\n // We have convert the color to sRGB space in sRGB pass\n // So we need to convert it back to linear space when output to render target.\n #ifndef ENGINE_OUTPUT_SRGB_CORRECT\n color.rgb /= color.a;\n color = sRGBToLinear(color);\n color.rgb *= color.a;\n #endif\n\n gl_FragColor = color;\n}"; // eslint-disable-line
15490
-
15491
- var SRGBFS = "#include <common>\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\n\nvoid main(){\n\tmediump vec4 color = texture2DSRGB(renderer_BlitTexture, v_uv);\n\n // This is final output, maybe has alpha\n // If we use premultiplied color to convert to sRGB. Since we ignored the background color, the greater the transparency, the greater the final composite color\n // But the actual transparent canvas can be composited with any color of the browser background\n\n // So we assume non-transparent SRGB conversion. Then use the Alpha value and the background canvas to do SRGB blending \n // Although it is non-linear blending, it is more scientific\n color.rgb = color.rgb / color.a;\n color = linearToSRGB(color);\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n"; // eslint-disable-line
15492
-
15493
- var FXAA3_11 = "//----------------------------------------------------------------------------------\n// This file was obatined from: https://github.com/hghdev/NVIDIAGameWorks-GraphicsSamples/blob/master/samples/es3-kepler/FXAA/FXAA3_11.h\n// NVIDIA paper: https://www.iryoku.com/aacourse/downloads/09-FXAA-3.11-in-15-Slides.pdf\n// Modifications to this file done by Galacean:\n// * Deleted HLSL-related macros\n// * Deleted the macros and function except for 'FXAA_PC == 1' \n// * Deleted the useless parameters in 'FxaaPixelShader' \n// * Webgl does not compile the double underline, so we remove the double underline for macros\n// * Changed the 'FXAA_GREEN_AS_LUMA == 0' code-path to compute luminance since we don't precompute luminance into the alpha channel\n// * Change the alpha value of the `ret` finally returned by the function from brightness to transparency when `FXAA_DISCARD == 1` code path\n//----------------------------------------------------------------------------------\n\n//----------------------------------------------------------------------------------\n// File: es3-kepler\\FXAA/FXAA3_11.h\n// SDK Version: v3.00\n// Email: gameworks@nvidia.com\n// Site: http://developer.nvidia.com/\n//\n// Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// * Neither the name of NVIDIA CORPORATION nor the names of its\n// contributors may be used to endorse or promote products derived\n// from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n//----------------------------------------------------------------------------------\n/*============================================================================\n\n\n NVIDIA FXAA 3.11 by TIMOTHY LOTTES\n\n------------------------------------------------------------------------------\n INTEGRATION CHECKLIST\n------------------------------------------------------------------------------\n(1.)\nIn the shader source, setup defines for the desired configuration.\nWhen providing multiple shaders (for different presets),\nsimply setup the defines differently in multiple files.\nExample,\n\n #define FXAA_PC 1\n #define FXAA_HLSL_5 1\n #define FXAA_QUALITY_PRESET 12\n\nOr,\n\n #define FXAA_360 1\n\nOr,\n\n #define FXAA_PS3 1\n\nEtc.\n\n(2.)\nThen include this file,\n\n #include \"Fxaa3_11.h\"\n\n(3.)\nThen call the FXAA pixel shader from within your desired shader.\nLook at the FXAA Quality FxaaPixelShader() for docs on inputs.\nAs for FXAA 3.11 all inputs for all shaders are the same\nto enable easy porting between platforms.\n\n return FxaaPixelShader(...);\n\n(4.)\nInsure pass prior to FXAA outputs RGBL (see next section).\nOr use,\n\n #define FXAA_GREEN_AS_LUMA 1\n\n(5.)\nSetup engine to provide the following constants\nwhich are used in the FxaaPixelShader() inputs,\n\n FxaaFloat2 fxaaQualityRcpFrame,\n FxaaFloat4 fxaaConsoleRcpFrameOpt,\n FxaaFloat4 fxaaConsoleRcpFrameOpt2,\n FxaaFloat4 fxaaConsole360RcpFrameOpt2,\n FxaaFloat fxaaQualitySubpix,\n FxaaFloat fxaaQualityEdgeThreshold,\n FxaaFloat fxaaQualityEdgeThresholdMin,\n FxaaFloat fxaaConsoleEdgeSharpness,\n FxaaFloat fxaaConsoleEdgeThreshold,\n FxaaFloat fxaaConsoleEdgeThresholdMin,\n FxaaFloat4 fxaaConsole360ConstDir\n\nLook at the FXAA Quality FxaaPixelShader() for docs on inputs.\n\n(6.)\nHave FXAA vertex shader run as a full screen triangle,\nand output \"pos\" and \"fxaaConsolePosPos\"\nsuch that inputs in the pixel shader provide,\n\n // {xy} = center of pixel\n FxaaFloat2 pos,\n\n // {xy_} = upper left of pixel\n // {_zw} = lower right of pixel\n FxaaFloat4 fxaaConsolePosPos,\n\n(7.)\nInsure the texture sampler(s) used by FXAA are set to bilinear filtering.\n\n\n------------------------------------------------------------------------------\n INTEGRATION - RGBL AND COLORSPACE\n------------------------------------------------------------------------------\nFXAA3 requires RGBL as input unless the following is set,\n\n #define FXAA_GREEN_AS_LUMA 1\n\nIn which case the engine uses green in place of luma,\nand requires RGB input is in a non-linear colorspace.\n\nRGB should be LDR (low dynamic range).\nSpecifically do FXAA after tonemapping.\n\nRGB data as returned by a texture fetch can be non-linear,\nor linear when FXAA_GREEN_AS_LUMA is not set.\nNote an \"sRGB format\" texture counts as linear,\nbecause the result of a texture fetch is linear data.\nRegular \"RGBA8\" textures in the sRGB colorspace are non-linear.\n\nIf FXAA_GREEN_AS_LUMA is not set,\nluma must be stored in the alpha channel prior to running FXAA.\nThis luma should be in a perceptual space (could be gamma 2.0).\nExample pass before FXAA where output is gamma 2.0 encoded,\n\n color.rgb = ToneMap(color.rgb); // linear color output\n color.rgb = sqrt(color.rgb); // gamma 2.0 color output\n return color;\n\nTo use FXAA,\n\n color.rgb = ToneMap(color.rgb); // linear color output\n color.rgb = sqrt(color.rgb); // gamma 2.0 color output\n color.a = dot(color.rgb, FxaaFloat3(0.299, 0.587, 0.114)); // compute luma\n return color;\n\nAnother example where output is linear encoded,\nsay for instance writing to an sRGB formated render target,\nwhere the render target does the conversion back to sRGB after blending,\n\n color.rgb = ToneMap(color.rgb); // linear color output\n return color;\n\nTo use FXAA,\n\n color.rgb = ToneMap(color.rgb); // linear color output\n color.a = sqrt(dot(color.rgb, FxaaFloat3(0.299, 0.587, 0.114))); // compute luma\n return color;\n\nGetting luma correct is required for the algorithm to work correctly.\n\n\n------------------------------------------------------------------------------\n BEING LINEARLY CORRECT?\n------------------------------------------------------------------------------\nApplying FXAA to a framebuffer with linear RGB color will look worse.\nThis is very counter intuitive, but happends to be true in this case.\nThe reason is because dithering artifacts will be more visiable\nin a linear colorspace.\n\n\n------------------------------------------------------------------------------\n COMPLEX INTEGRATION\n------------------------------------------------------------------------------\nQ. What if the engine is blending into RGB before wanting to run FXAA?\n\nA. In the last opaque pass prior to FXAA,\n have the pass write out luma into alpha.\n Then blend into RGB only.\n FXAA should be able to run ok\n assuming the blending pass did not any add aliasing.\n This should be the common case for particles and common blending passes.\n\nA. Or use FXAA_GREEN_AS_LUMA.\n\n============================================================================*/\n\n/*============================================================================\n\n INTEGRATION KNOBS\n\n============================================================================*/\n/*==========================================================================*/\n#ifndef FXAA_PC\n //\n // FXAA Quality\n // The high quality PC algorithm.\n //\n #define FXAA_PC 0\n#endif\n/*--------------------------------------------------------------------------*/\n#ifndef FXAA_GLSL_120\n #define FXAA_GLSL_120 0\n#endif\n/*--------------------------------------------------------------------------*/\n#ifndef FXAA_GLSL_130\n #define FXAA_GLSL_130 0\n#endif\n/*--------------------------------------------------------------------------*/\n/*==========================================================================*/\n#ifndef FXAA_GREEN_AS_LUMA\n //\n // For those using non-linear color,\n // and either not able to get luma in alpha, or not wanting to,\n // this enables FXAA to run using green as a proxy for luma.\n // So with this enabled, no need to pack luma in alpha.\n //\n // This will turn off AA on anything which lacks some amount of green.\n // Pure red and blue or combination of only R and B, will get no AA.\n //\n // Might want to lower the settings for both,\n // fxaaConsoleEdgeThresholdMin\n // fxaaQualityEdgeThresholdMin\n // In order to insure AA does not get turned off on colors \n // which contain a minor amount of green.\n //\n // 1 = On.\n // 0 = Off.\n //\n #define FXAA_GREEN_AS_LUMA 0\n#endif\n/*--------------------------------------------------------------------------*/\n#ifndef FXAA_EARLY_EXIT\n //\n // Controls algorithm's early exit path.\n // On PS3 turning this ON adds 2 cycles to the shader.\n // On 360 turning this OFF adds 10ths of a millisecond to the shader.\n // Turning this off on console will result in a more blurry image.\n // So this defaults to on.\n //\n // 1 = On.\n // 0 = Off.\n //\n #define FXAA_EARLY_EXIT 1\n#endif\n/*--------------------------------------------------------------------------*/\n#ifndef FXAA_DISCARD\n //\n // Only valid for PC OpenGL currently.\n // Probably will not work when FXAA_GREEN_AS_LUMA = 1.\n //\n // 1 = Use discard on pixels which don't need AA.\n // For APIs which enable concurrent TEX+ROP from same surface.\n // 0 = Return unchanged color on pixels which don't need AA.\n //\n #define FXAA_DISCARD 0\n#endif\n/*--------------------------------------------------------------------------*/\n#ifndef FXAA_FAST_PIXEL_OFFSET\n //\n // Used for GLSL 120 only.\n //\n // 1 = GL API supports fast pixel offsets\n // 0 = do not use fast pixel offsets\n //\n #ifdef GL_EXT_gpu_shader4\n #define FXAA_FAST_PIXEL_OFFSET 1\n #endif\n #ifdef GL_NV_gpu_shader5\n #define FXAA_FAST_PIXEL_OFFSET 1\n #endif\n #ifdef gpu_shader5\n #define FXAA_FAST_PIXEL_OFFSET 1\n #endif\n #ifndef FXAA_FAST_PIXEL_OFFSET\n #define FXAA_FAST_PIXEL_OFFSET 0\n #endif\n#endif\n/*--------------------------------------------------------------------------*/\n#ifndef FXAA_GATHER4_ALPHA\n //\n // 1 = API supports gather4 on alpha channel.\n // 0 = API does not support gather4 on alpha channel.\n //\n #ifdef gpu_shader5\n #define FXAA_GATHER4_ALPHA 1\n #endif\n #ifdef GL_NV_gpu_shader5\n #define FXAA_GATHER4_ALPHA 1\n #endif\n #ifndef FXAA_GATHER4_ALPHA\n #define FXAA_GATHER4_ALPHA 0\n #endif\n#endif\n\n/*============================================================================\n FXAA QUALITY - TUNING KNOBS\n------------------------------------------------------------------------------\nNOTE the other tuning knobs are now in the shader function inputs!\n============================================================================*/\n#ifndef FXAA_QUALITY_PRESET\n //\n // Choose the quality preset.\n // This needs to be compiled into the shader as it affects code.\n // Best option to include multiple presets is to \n // in each shader define the preset, then include this file.\n // \n // OPTIONS\n // -----------------------------------------------------------------------\n // 10 to 15 - default medium dither (10=fastest, 15=highest quality)\n // 20 to 29 - less dither, more expensive (20=fastest, 29=highest quality)\n // 39 - no dither, very expensive \n //\n // NOTES\n // -----------------------------------------------------------------------\n // 12 = slightly faster then FXAA 3.9 and higher edge quality (default)\n // 13 = about same speed as FXAA 3.9 and better than 12\n // 23 = closest to FXAA 3.9 visually and performance wise\n // _ = the lowest digit is directly related to performance\n // _ = the highest digit is directly related to style\n // \n #define FXAA_QUALITY_PRESET 12\n#endif\n\n/*============================================================================\n\n FXAA QUALITY - PRESETS\n\n============================================================================*/\n\n/*============================================================================\n FXAA QUALITY - MEDIUM DITHER PRESETS\n============================================================================*/\n#if (FXAA_QUALITY_PRESET == 10)\n #define FXAA_QUALITY_PS 3\n #define FXAA_QUALITY_P0 1.5\n #define FXAA_QUALITY_P1 3.0\n #define FXAA_QUALITY_P2 12.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 11)\n #define FXAA_QUALITY_PS 4\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 3.0\n #define FXAA_QUALITY_P3 12.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 12)\n #define FXAA_QUALITY_PS 5\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 4.0\n #define FXAA_QUALITY_P4 12.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 13)\n #define FXAA_QUALITY_PS 6\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 4.0\n #define FXAA_QUALITY_P5 12.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 14)\n #define FXAA_QUALITY_PS 7\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 4.0\n #define FXAA_QUALITY_P6 12.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 15)\n #define FXAA_QUALITY_PS 8\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 2.0\n #define FXAA_QUALITY_P6 4.0\n #define FXAA_QUALITY_P7 12.0\n#endif\n\n/*============================================================================\n FXAA QUALITY - LOW DITHER PRESETS\n============================================================================*/\n#if (FXAA_QUALITY_PRESET == 20)\n #define FXAA_QUALITY_PS 3\n #define FXAA_QUALITY_P0 1.5\n #define FXAA_QUALITY_P1 2.0\n #define FXAA_QUALITY_P2 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 21)\n #define FXAA_QUALITY_PS 4\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 22)\n #define FXAA_QUALITY_PS 5\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 23)\n #define FXAA_QUALITY_PS 6\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 24)\n #define FXAA_QUALITY_PS 7\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 3.0\n #define FXAA_QUALITY_P6 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 25)\n #define FXAA_QUALITY_PS 8\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 2.0\n #define FXAA_QUALITY_P6 4.0\n #define FXAA_QUALITY_P7 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 26)\n #define FXAA_QUALITY_PS 9\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 2.0\n #define FXAA_QUALITY_P6 2.0\n #define FXAA_QUALITY_P7 4.0\n #define FXAA_QUALITY_P8 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 27)\n #define FXAA_QUALITY_PS 10\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 2.0\n #define FXAA_QUALITY_P6 2.0\n #define FXAA_QUALITY_P7 2.0\n #define FXAA_QUALITY_P8 4.0\n #define FXAA_QUALITY_P9 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 28)\n #define FXAA_QUALITY_PS 11\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 2.0\n #define FXAA_QUALITY_P6 2.0\n #define FXAA_QUALITY_P7 2.0\n #define FXAA_QUALITY_P8 2.0\n #define FXAA_QUALITY_P9 4.0\n #define FXAA_QUALITY_P10 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 29)\n #define FXAA_QUALITY_PS 12\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 2.0\n #define FXAA_QUALITY_P6 2.0\n #define FXAA_QUALITY_P7 2.0\n #define FXAA_QUALITY_P8 2.0\n #define FXAA_QUALITY_P9 2.0\n #define FXAA_QUALITY_P10 4.0\n #define FXAA_QUALITY_P11 8.0\n#endif\n\n/*============================================================================\n FXAA QUALITY - EXTREME QUALITY\n============================================================================*/\n#if (FXAA_QUALITY_PRESET == 39)\n #define FXAA_QUALITY_PS 12\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.0\n #define FXAA_QUALITY_P2 1.0\n #define FXAA_QUALITY_P3 1.0\n #define FXAA_QUALITY_P4 1.0\n #define FXAA_QUALITY_P5 1.5\n #define FXAA_QUALITY_P6 2.0\n #define FXAA_QUALITY_P7 2.0\n #define FXAA_QUALITY_P8 2.0\n #define FXAA_QUALITY_P9 2.0\n #define FXAA_QUALITY_P10 4.0\n #define FXAA_QUALITY_P11 8.0\n#endif\n\n\n/*============================================================================\n\n API PORTING\n\n============================================================================*/\n#if (FXAA_GLSL_120 == 1) || (FXAA_GLSL_130 == 1)\n #define FxaaBool bool\n #define FxaaDiscard discard\n #define FxaaFloat float\n #define FxaaFloat2 vec2\n #define FxaaFloat3 vec3\n #define FxaaFloat4 vec4\n #define FxaaHalf float\n #define FxaaHalf2 vec2\n #define FxaaHalf3 vec3\n #define FxaaHalf4 vec4\n #define FxaaInt2 ivec2\n #define FxaaSat(x) clamp(x, 0.0, 1.0)\n #define FxaaTex sampler2D\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_GLSL_120 == 1)\n // Requires,\n // #version 120\n // And at least,\n // #extension GL_EXT_gpu_shader4 : enable\n // (or set FXAA_FAST_PIXEL_OFFSET 1 to work like DX9)\n #define FxaaTexTop(t, p) texture2DLodEXT(t, p, 0.0)\n #if (FXAA_FAST_PIXEL_OFFSET == 1)\n #define FxaaTexOff(t, p, o, r) texture2DLodOffset(t, p, 0.0, o)\n #else\n #define FxaaTexOff(t, p, o, r) texture2DLodEXT(t, p + (o * r), 0.0)\n #endif\n #if (FXAA_GATHER4_ALPHA == 1)\n // use #extension gpu_shader5 : enable\n #define FxaaTexAlpha4(t, p) textureGather(t, p, 3)\n #define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3)\n #define FxaaTexGreen4(t, p) textureGather(t, p, 1)\n #define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1)\n #endif\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_GLSL_130 == 1)\n // Requires \"#version 130\" or better\n #define FxaaTexTop(t, p) textureLod(t, p, 0.0)\n #define FxaaTexOff(t, p, o, r) textureLodOffset(t, p, 0.0, o)\n #if (FXAA_GATHER4_ALPHA == 1)\n // use #extension gpu_shader5 : enable\n #define FxaaTexAlpha4(t, p) textureGather(t, p, 3)\n #define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3)\n #define FxaaTexGreen4(t, p) textureGather(t, p, 1)\n #define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1)\n #endif\n#endif\n/*--------------------------------------------------------------------------*/\n\n\n/*============================================================================\n GREEN AS LUMA OPTION SUPPORT FUNCTION\n============================================================================*/\n#if (FXAA_GREEN_AS_LUMA == 0)\n FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return dot(rgba.xyz, FxaaFloat3(0.299, 0.587, 0.114));}\n#else\n FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.y; }\n#endif \n\n\n/*============================================================================\n\n FXAA3 QUALITY - PC\n\n============================================================================*/\n#if (FXAA_PC == 1)\n/*--------------------------------------------------------------------------*/\nFxaaFloat4 FxaaPixelShader(\n // Use noperspective interpolation here (turn off perspective interpolation).\n // {xy} = center of pixel\n FxaaFloat2 pos,\n //\n // Reuse the center sample as it's already available\n // {rgb_} = the color of the center pixel (alpha won't be used)\n FxaaFloat4 rgbyM,\n //\n // Input color texture.\n // {rgb_} = color in linear or perceptual color space\n // if (FXAA_GREEN_AS_LUMA == 0)\n // {__a} = luma in perceptual color space (not linear)\n FxaaTex tex,\n //\n // Only used on FXAA Quality.\n // This must be from a constant/uniform.\n // {x_} = 1.0/screenWidthInPixels\n // {_y} = 1.0/screenHeightInPixels\n FxaaFloat2 fxaaQualityRcpFrame,\n //\n // Only used on FXAA Quality.\n // This used to be the FXAA_QUALITY_SUBPIX define.\n // It is here now to allow easier tuning.\n // Choose the amount of sub-pixel aliasing removal.\n // This can effect sharpness.\n // 1.00 - upper limit (softer)\n // 0.75 - default amount of filtering\n // 0.50 - lower limit (sharper, less sub-pixel aliasing removal)\n // 0.25 - almost off\n // 0.00 - completely off\n FxaaFloat fxaaQualitySubpix,\n //\n // Only used on FXAA Quality.\n // This used to be the FXAA_QUALITY_EDGE_THRESHOLD define.\n // It is here now to allow easier tuning.\n // The minimum amount of local contrast required to apply algorithm.\n // 0.333 - too little (faster)\n // 0.250 - low quality\n // 0.166 - default\n // 0.125 - high quality\n // 0.063 - overkill (slower)\n FxaaFloat fxaaQualityEdgeThreshold,\n //\n // Only used on FXAA Quality.\n // This used to be the FXAA_QUALITY_EDGE_THRESHOLD_MIN define.\n // It is here now to allow easier tuning.\n // Trims the algorithm from processing darks.\n // 0.0833 - upper limit (default, the start of visible unfiltered edges)\n // 0.0625 - high quality (faster)\n // 0.0312 - visible limit (slower)\n // Special notes when using FXAA_GREEN_AS_LUMA,\n // Likely want to set this to zero.\n // As colors that are mostly not-green\n // will appear very dark in the green channel!\n // Tune by looking at mostly non-green content,\n // then start at zero and increase until aliasing is a problem.\n FxaaFloat fxaaQualityEdgeThresholdMin\n) {\n/*--------------------------------------------------------------------------*/\n FxaaFloat2 posM;\n posM.x = pos.x;\n posM.y = pos.y;\n #if (FXAA_GATHER4_ALPHA == 1)\n #if (FXAA_DISCARD == 0)\n FxaaFloat lumaM = FxaaLuma(rgbyM);\n #endif\n #if (FXAA_GREEN_AS_LUMA == 0)\n FxaaFloat4 luma4A = FxaaTexAlpha4(tex, posM);\n FxaaFloat4 luma4B = FxaaTexOffAlpha4(tex, posM, FxaaInt2(-1, -1));\n #else\n FxaaFloat4 luma4A = FxaaTexGreen4(tex, posM);\n FxaaFloat4 luma4B = FxaaTexOffGreen4(tex, posM, FxaaInt2(-1, -1));\n #endif\n #if (FXAA_DISCARD == 1)\n FxaaFloat lumaM = luma4A.w;\n #endif\n #define lumaE luma4A.z\n #define lumaS luma4A.x\n #define lumaSE luma4A.y\n #define lumaNW luma4B.w\n #define lumaN luma4B.z\n #define lumaW luma4B.x\n #else\n FxaaFloat lumaM = FxaaLuma(rgbyM);\n FxaaFloat lumaS = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0, 1), fxaaQualityRcpFrame.xy));\n FxaaFloat lumaE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 0), fxaaQualityRcpFrame.xy));\n FxaaFloat lumaN = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0,-1), fxaaQualityRcpFrame.xy));\n FxaaFloat lumaW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 0), fxaaQualityRcpFrame.xy));\n #endif\n/*--------------------------------------------------------------------------*/\n FxaaFloat maxSM = max(lumaS, lumaM);\n FxaaFloat minSM = min(lumaS, lumaM);\n FxaaFloat maxESM = max(lumaE, maxSM);\n FxaaFloat minESM = min(lumaE, minSM);\n FxaaFloat maxWN = max(lumaN, lumaW);\n FxaaFloat minWN = min(lumaN, lumaW);\n FxaaFloat rangeMax = max(maxWN, maxESM);\n FxaaFloat rangeMin = min(minWN, minESM);\n FxaaFloat rangeMaxScaled = rangeMax * fxaaQualityEdgeThreshold;\n FxaaFloat range = rangeMax - rangeMin;\n FxaaFloat rangeMaxClamped = max(fxaaQualityEdgeThresholdMin, rangeMaxScaled);\n FxaaBool earlyExit = range < rangeMaxClamped;\n/*--------------------------------------------------------------------------*/\n if(earlyExit)\n #if (FXAA_DISCARD == 1)\n FxaaDiscard;\n #else\n return rgbyM;\n #endif\n/*--------------------------------------------------------------------------*/\n #if (FXAA_GATHER4_ALPHA == 0)\n FxaaFloat lumaNW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1,-1), fxaaQualityRcpFrame.xy));\n FxaaFloat lumaSE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 1), fxaaQualityRcpFrame.xy));\n FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1,-1), fxaaQualityRcpFrame.xy));\n FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy));\n #else\n FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(1, -1), fxaaQualityRcpFrame.xy));\n FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy));\n #endif\n/*--------------------------------------------------------------------------*/\n FxaaFloat lumaNS = lumaN + lumaS;\n FxaaFloat lumaWE = lumaW + lumaE;\n FxaaFloat subpixRcpRange = 1.0/range;\n FxaaFloat subpixNSWE = lumaNS + lumaWE;\n FxaaFloat edgeHorz1 = (-2.0 * lumaM) + lumaNS;\n FxaaFloat edgeVert1 = (-2.0 * lumaM) + lumaWE;\n/*--------------------------------------------------------------------------*/\n FxaaFloat lumaNESE = lumaNE + lumaSE;\n FxaaFloat lumaNWNE = lumaNW + lumaNE;\n FxaaFloat edgeHorz2 = (-2.0 * lumaE) + lumaNESE;\n FxaaFloat edgeVert2 = (-2.0 * lumaN) + lumaNWNE;\n/*--------------------------------------------------------------------------*/\n FxaaFloat lumaNWSW = lumaNW + lumaSW;\n FxaaFloat lumaSWSE = lumaSW + lumaSE;\n FxaaFloat edgeHorz4 = (abs(edgeHorz1) * 2.0) + abs(edgeHorz2);\n FxaaFloat edgeVert4 = (abs(edgeVert1) * 2.0) + abs(edgeVert2);\n FxaaFloat edgeHorz3 = (-2.0 * lumaW) + lumaNWSW;\n FxaaFloat edgeVert3 = (-2.0 * lumaS) + lumaSWSE;\n FxaaFloat edgeHorz = abs(edgeHorz3) + edgeHorz4;\n FxaaFloat edgeVert = abs(edgeVert3) + edgeVert4;\n/*--------------------------------------------------------------------------*/\n FxaaFloat subpixNWSWNESE = lumaNWSW + lumaNESE;\n FxaaFloat lengthSign = fxaaQualityRcpFrame.x;\n FxaaBool horzSpan = edgeHorz >= edgeVert;\n FxaaFloat subpixA = subpixNSWE * 2.0 + subpixNWSWNESE;\n/*--------------------------------------------------------------------------*/\n if(!horzSpan) lumaN = lumaW;\n if(!horzSpan) lumaS = lumaE;\n if(horzSpan) lengthSign = fxaaQualityRcpFrame.y;\n FxaaFloat subpixB = (subpixA * (1.0/12.0)) - lumaM;\n/*--------------------------------------------------------------------------*/\n FxaaFloat gradientN = lumaN - lumaM;\n FxaaFloat gradientS = lumaS - lumaM;\n FxaaFloat lumaNN = lumaN + lumaM;\n FxaaFloat lumaSS = lumaS + lumaM;\n FxaaBool pairN = abs(gradientN) >= abs(gradientS);\n FxaaFloat gradient = max(abs(gradientN), abs(gradientS));\n if(pairN) lengthSign = -lengthSign;\n FxaaFloat subpixC = FxaaSat(abs(subpixB) * subpixRcpRange);\n/*--------------------------------------------------------------------------*/\n FxaaFloat2 posB;\n posB.x = posM.x;\n posB.y = posM.y;\n FxaaFloat2 offNP;\n offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x;\n offNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y;\n if(!horzSpan) posB.x += lengthSign * 0.5;\n if( horzSpan) posB.y += lengthSign * 0.5;\n/*--------------------------------------------------------------------------*/\n FxaaFloat2 posN;\n posN.x = posB.x - offNP.x * FXAA_QUALITY_P0;\n posN.y = posB.y - offNP.y * FXAA_QUALITY_P0;\n FxaaFloat2 posP;\n posP.x = posB.x + offNP.x * FXAA_QUALITY_P0;\n posP.y = posB.y + offNP.y * FXAA_QUALITY_P0;\n FxaaFloat subpixD = ((-2.0)*subpixC) + 3.0;\n FxaaFloat lumaEndN = FxaaLuma(FxaaTexTop(tex, posN));\n FxaaFloat subpixE = subpixC * subpixC;\n FxaaFloat lumaEndP = FxaaLuma(FxaaTexTop(tex, posP));\n/*--------------------------------------------------------------------------*/\n if(!pairN) lumaNN = lumaSS;\n FxaaFloat gradientScaled = gradient * 1.0/4.0;\n FxaaFloat lumaMM = lumaM - lumaNN * 0.5;\n FxaaFloat subpixF = subpixD * subpixE;\n FxaaBool lumaMLTZero = lumaMM < 0.0;\n/*--------------------------------------------------------------------------*/\n lumaEndN -= lumaNN * 0.5;\n lumaEndP -= lumaNN * 0.5;\n FxaaBool doneN = abs(lumaEndN) >= gradientScaled;\n FxaaBool doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P1;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P1;\n FxaaBool doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P1;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P1;\n/*--------------------------------------------------------------------------*/\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P2;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P2;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P2;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P2;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 3)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P3;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P3;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P3;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P3;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 4)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P4;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P4;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P4;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P4;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 5)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P5;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P5;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P5;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P5;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 6)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P6;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P6;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P6;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P6;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 7)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P7;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P7;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P7;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P7;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 8)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P8;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P8;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P8;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P8;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 9)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P9;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P9;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P9;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P9;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 10)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P10;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P10;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P10;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P10;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 11)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P11;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P11;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P11;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P11;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 12)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P12;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P12;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P12;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P12;\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n/*--------------------------------------------------------------------------*/\n FxaaFloat dstN = posM.x - posN.x;\n FxaaFloat dstP = posP.x - posM.x;\n if(!horzSpan) dstN = posM.y - posN.y;\n if(!horzSpan) dstP = posP.y - posM.y;\n/*--------------------------------------------------------------------------*/\n FxaaBool goodSpanN = (lumaEndN < 0.0) != lumaMLTZero;\n FxaaFloat spanLength = (dstP + dstN);\n FxaaBool goodSpanP = (lumaEndP < 0.0) != lumaMLTZero;\n FxaaFloat spanLengthRcp = 1.0/spanLength;\n/*--------------------------------------------------------------------------*/\n FxaaBool directionN = dstN < dstP;\n FxaaFloat dst = min(dstN, dstP);\n FxaaBool goodSpan = directionN ? goodSpanN : goodSpanP;\n FxaaFloat subpixG = subpixF * subpixF;\n FxaaFloat pixelOffset = (dst * (-spanLengthRcp)) + 0.5;\n FxaaFloat subpixH = subpixG * fxaaQualitySubpix;\n/*--------------------------------------------------------------------------*/\n FxaaFloat pixelOffsetGood = goodSpan ? pixelOffset : 0.0;\n FxaaFloat pixelOffsetSubpix = max(pixelOffsetGood, subpixH);\n if(!horzSpan) posM.x += pixelOffsetSubpix * lengthSign;\n if( horzSpan) posM.y += pixelOffsetSubpix * lengthSign;\n\n #if (FXAA_DISCARD == 1)\n return FxaaTexTop(tex, posM);\n #else\n return FxaaTexTop(tex, posM);\n #endif\n}\n/*==========================================================================*/\n#endif"; // eslint-disable-line
15110
+ PostProcessUberPass.UBER_SHADER_NAME = "PostProcess/Uber";
15494
15111
 
15495
15112
  /**
15496
15113
  * @internal
@@ -15501,17 +15118,11 @@ var FXAA3_11 = "//--------------------------------------------------------------
15501
15118
  var _this;
15502
15119
  _this = PipelinePass.call(this, engine) || this;
15503
15120
  // SRGB Material
15504
- var sRGBmaterial = new Material(engine, Shader.find("FinalSRGB"));
15505
- var sRGBdepthState = sRGBmaterial.renderState.depthState;
15506
- sRGBdepthState.enabled = false;
15507
- sRGBdepthState.writeEnabled = false;
15121
+ var sRGBmaterial = new Material(engine, Shader.find("PostProcess/FinalSRGB"));
15508
15122
  sRGBmaterial._addReferCount(1);
15509
15123
  _this._sRGBmaterial = sRGBmaterial;
15510
15124
  // FXAA Material
15511
- var antiAliasingMaterial = new Material(engine, Shader.find("FinalAntiAliasing"));
15512
- var antiAliasingDepthState = antiAliasingMaterial.renderState.depthState;
15513
- antiAliasingDepthState.enabled = false;
15514
- antiAliasingDepthState.writeEnabled = false;
15125
+ var antiAliasingMaterial = new Material(engine, Shader.find("PostProcess/FinalAntiAliasing"));
15515
15126
  antiAliasingMaterial._addReferCount(1);
15516
15127
  _this._antiAliasingMaterial = antiAliasingMaterial;
15517
15128
  return _this;
@@ -15549,11 +15160,6 @@ var FXAA3_11 = "//--------------------------------------------------------------
15549
15160
  };
15550
15161
  return FinalPass;
15551
15162
  }(PipelinePass);
15552
- Object.assign(ShaderLib, {
15553
- FXAA3_11: FXAA3_11
15554
- });
15555
- Shader.create("FinalSRGB", blitVs, SRGBFS);
15556
- Shader.create("FinalAntiAliasing", blitVs, FinalAntiAliasingFS);
15557
15163
 
15558
15164
  /**
15559
15165
  * @internal
@@ -15628,7 +15234,7 @@ Shader.create("FinalAntiAliasing", blitVs, FinalAntiAliasingFS);
15628
15234
  var compileMacros = Shader._compileMacros;
15629
15235
  var primitive = subElement.primitive, shaderPasses = subElement.shaderPasses, renderElementShaderData = subElement.shaderData;
15630
15236
  var rendererData = renderer.shaderData, rendererId = renderer.instanceId;
15631
- var materialData = material.shaderData, materialId = material.instanceId, renderStates = material.renderStates;
15237
+ var materialData = material.shaderData, materialId = material.instanceId;
15632
15238
  // Union render global macro and material self macro
15633
15239
  ShaderMacroCollection.unionCollection(renderer._globalShaderMacro, materialData._macroCollection, compileMacros);
15634
15240
  ShaderMacroCollection.unionCollection(compileMacros, engine._macroCollection, compileMacros);
@@ -15638,19 +15244,8 @@ Shader.create("FinalAntiAliasing", blitVs, FinalAntiAliasingFS);
15638
15244
  continue;
15639
15245
  }
15640
15246
  var renderState = shaderPass._renderState;
15641
- if (needMaskType) {
15642
- // Mask don't care render queue type
15643
- if (!renderState) {
15644
- renderState = renderStates[j];
15645
- }
15646
- } else {
15647
- var passQueueType = void 0;
15648
- if (renderState) {
15649
- passQueueType = renderState._getRenderQueueByShaderData(shaderPass._renderStateDataMap, materialData);
15650
- } else {
15651
- renderState = renderStates[j];
15652
- passQueueType = renderState.renderQueueType;
15653
- }
15247
+ if (!needMaskType) {
15248
+ var passQueueType = renderState._getRenderQueueByShaderData(shaderPass._renderStateDataMap, materialData);
15654
15249
  if (passQueueType !== renderQueueType) {
15655
15250
  continue;
15656
15251
  }
@@ -16872,7 +16467,6 @@ CascadedShadowCasterPass._tempMatrix0 = new Matrix();
16872
16467
  for(var i = 0, n = subRenderElements.length; i < n; ++i){
16873
16468
  var subRenderElement = subRenderElements[i];
16874
16469
  var material = subRenderElement.material;
16875
- var renderStates = material.renderStates;
16876
16470
  var materialSubShader = material.shader.subShaders[0];
16877
16471
  var replacementShader = context.replacementShader;
16878
16472
  if (replacementShader) {
@@ -16883,33 +16477,28 @@ CascadedShadowCasterPass._tempMatrix0 = new Matrix();
16883
16477
  for(var j = 0, m = replacementSubShaders.length; j < m; j++){
16884
16478
  var subShader = replacementSubShaders[j];
16885
16479
  if (subShader.getTagValue(replacementTag) === materialSubShader.getTagValue(replacementTag)) {
16886
- this.pushRenderElementByType(renderElement, subRenderElement, subShader.passes, renderStates);
16480
+ this.pushRenderElementByType(renderElement, subRenderElement, subShader.passes);
16887
16481
  replacementSuccess = true;
16888
16482
  }
16889
16483
  }
16890
16484
  if (!replacementSuccess && context.replacementFailureStrategy === ReplacementFailureStrategy.KeepOriginalShader) {
16891
- this.pushRenderElementByType(renderElement, subRenderElement, materialSubShader.passes, renderStates);
16485
+ this.pushRenderElementByType(renderElement, subRenderElement, materialSubShader.passes);
16892
16486
  }
16893
16487
  } else {
16894
- this.pushRenderElementByType(renderElement, subRenderElement, replacementSubShaders[0].passes, renderStates);
16488
+ this.pushRenderElementByType(renderElement, subRenderElement, replacementSubShaders[0].passes);
16895
16489
  }
16896
16490
  } else {
16897
- this.pushRenderElementByType(renderElement, subRenderElement, materialSubShader.passes, renderStates);
16491
+ this.pushRenderElementByType(renderElement, subRenderElement, materialSubShader.passes);
16898
16492
  }
16899
16493
  }
16900
16494
  };
16901
- _proto.pushRenderElementByType = function pushRenderElementByType(renderElement, subRenderElement, shaderPasses, renderStates) {
16495
+ _proto.pushRenderElementByType = function pushRenderElementByType(renderElement, subRenderElement, shaderPasses) {
16902
16496
  var cullingResults = this._cullingResults;
16903
16497
  for(var i = 0, n = shaderPasses.length; i < n; i++){
16904
16498
  // Get render queue type
16905
- var renderQueueType = void 0;
16906
16499
  var shaderPass = shaderPasses[i];
16907
16500
  var renderState = shaderPass._renderState;
16908
- if (renderState) {
16909
- renderQueueType = renderState._getRenderQueueByShaderData(shaderPass._renderStateDataMap, subRenderElement.material.shaderData);
16910
- } else {
16911
- renderQueueType = renderStates[i].renderQueueType;
16912
- }
16501
+ var renderQueueType = renderState._getRenderQueueByShaderData(shaderPass._renderStateDataMap, subRenderElement.material.shaderData);
16913
16502
  var flag = 1 << renderQueueType;
16914
16503
  subRenderElement.shaderPasses = shaderPasses;
16915
16504
  subRenderElement.renderQueueFlags |= flag;
@@ -16947,7 +16536,8 @@ CascadedShadowCasterPass._tempMatrix0 = new Matrix();
16947
16536
  program.uploadAll(program.materialUniformBlock, material.shaderData);
16948
16537
  program.uploadAll(program.cameraUniformBlock, camera.shaderData);
16949
16538
  program.uploadUnGroupTextures();
16950
- (pass._renderState || material.renderState)._applyStates(engine, false, pass._renderStateDataMap, material.shaderData);
16539
+ var renderState = pass._renderState;
16540
+ renderState._applyStates(engine, false, pass._renderStateDataMap, material.shaderData);
16951
16541
  rhi.drawPrimitive(mesh._primitive, mesh.subMesh, program);
16952
16542
  };
16953
16543
  _proto._prepareRender = function _prepareRender(context) {
@@ -23248,14 +22838,10 @@ __decorate([
23248
22838
  0,
23249
22839
  2
23250
22840
  ]); // left-top
23251
- var blitMaterial = new Material(engine, Shader.find("blit"));
22841
+ var blitMaterial = new Material(engine, Shader.find("Blit/Blit"));
23252
22842
  blitMaterial._addReferCount(1);
23253
- blitMaterial.renderState.depthState.enabled = false;
23254
- blitMaterial.renderState.depthState.writeEnabled = false;
23255
- var blitScreenMaterial = new Material(engine, Shader.find("blit-screen"));
22843
+ var blitScreenMaterial = new Material(engine, Shader.find("Blit/BlitScreen"));
23256
22844
  blitScreenMaterial._addReferCount(1);
23257
- blitScreenMaterial.renderState.depthState.enabled = false;
23258
- blitScreenMaterial.renderState.depthState.writeEnabled = false;
23259
22845
  this.blitMaterial = blitMaterial;
23260
22846
  this.blitScreenMaterial = blitScreenMaterial;
23261
22847
  this.blitMesh = this._createBlitMesh(engine, vertices);
@@ -23280,11 +22866,11 @@ __decorate([
23280
22866
  ]);
23281
22867
  this.uintWhiteTexture2D = this._create1x1Texture(engine, 0, TextureFormat.R32G32B32A32_UInt, whitePixel32, false);
23282
22868
  }
23283
- this.spriteDefaultMaterial = this._create2DMaterial(engine, Shader.find("Sprite"));
23284
- this.textDefaultMaterial = this._create2DMaterial(engine, Shader.find("Text"));
22869
+ this.spriteDefaultMaterial = this._create2DMaterial(engine, Shader.find("2D/Sprite"));
22870
+ this.textDefaultMaterial = this._create2DMaterial(engine, Shader.find("2D/Text"));
23285
22871
  this.spriteMaskDefaultMaterial = this._createSpriteMaskMaterial(engine);
23286
- this.meshMagentaMaterial = this._createMagentaMaterial(engine, "unlit");
23287
- this.particleMagentaMaterial = this._createMagentaMaterial(engine, "particle-shader");
22872
+ this.meshMagentaMaterial = this._createMagentaMaterial(engine, "Unlit");
22873
+ this.particleMagentaMaterial = this._createMagentaMaterial(engine, "Effect/Particle");
23288
22874
  }
23289
22875
  var _proto = BasicResources.prototype;
23290
22876
  /**
@@ -23376,28 +22962,17 @@ __decorate([
23376
22962
  };
23377
22963
  _proto._create2DMaterial = function _create2DMaterial(engine, shader) {
23378
22964
  var material = new Material(engine, shader);
23379
- var renderState = material.renderState;
23380
- var target = renderState.blendState.targetBlendState;
23381
- target.enabled = true;
23382
- target.sourceColorBlendFactor = BlendFactor.SourceAlpha;
23383
- target.destinationColorBlendFactor = BlendFactor.OneMinusSourceAlpha;
23384
- target.sourceAlphaBlendFactor = BlendFactor.One;
23385
- target.destinationAlphaBlendFactor = BlendFactor.OneMinusSourceAlpha;
23386
- target.colorBlendOperation = target.alphaBlendOperation = BlendOperation.Add;
23387
- renderState.depthState.writeEnabled = false;
23388
- renderState.rasterState.cullMode = CullMode.Off;
23389
- renderState.renderQueueType = RenderQueueType.Transparent;
23390
22965
  material.isGCIgnored = true;
23391
22966
  return material;
23392
22967
  };
23393
22968
  _proto._createMagentaMaterial = function _createMagentaMaterial(engine, shaderName) {
23394
- var material = new Material(engine, Shader.find(shaderName));
22969
+ var material = new BaseMaterial(engine, Shader.find(shaderName));
23395
22970
  material.isGCIgnored = true;
23396
22971
  material.shaderData.setColor("material_BaseColor", new Color(1.0, 0.0, 1.01, 1.0));
23397
22972
  return material;
23398
22973
  };
23399
22974
  _proto._createSpriteMaskMaterial = function _createSpriteMaskMaterial(engine) {
23400
- var material = new Material(engine, Shader.find("SpriteMask"));
22975
+ var material = new Material(engine, Shader.find("2D/SpriteMask"));
23401
22976
  material.isGCIgnored = true;
23402
22977
  return material;
23403
22978
  };
@@ -26847,167 +26422,6 @@ ParticleBufferUtils.boundsFloatStride = 8;
26847
26422
  ParticleBufferUtils.boundsTimeOffset = 6;
26848
26423
  ParticleBufferUtils.boundsMaxLifetimeOffset = 7;
26849
26424
 
26850
- var blitFs = "#include <common>\n\nuniform mediump sampler2D renderer_BlitTexture;\n#ifdef HAS_TEX_LOD\n\tuniform float renderer_BlitMipLevel;\n#endif\n\nuniform vec4 renderer_SourceScaleOffset;\n\nvarying vec2 v_uv;\n\n#ifdef HAS_TEX_LOD\n\tvec4 texture2DLodSRGB(sampler2D tex, vec2 uv, float lod) {\n\t\tvec4 color = texture2DLodEXT(tex, uv, lod);\n\t\t#ifdef ENGINE_NO_SRGB\n\t\t\tcolor = sRGBToLinear(color);\n\t\t#endif\n\t\treturn color;\n\t}\n#endif\n\nvoid main() {\n\tvec2 uv = v_uv;\n\tuv = uv * renderer_SourceScaleOffset.xy + renderer_SourceScaleOffset.zw;\n\n\t#ifdef HAS_TEX_LOD\n\t\tgl_FragColor = texture2DLodSRGB( renderer_BlitTexture, uv, renderer_BlitMipLevel );\n\t#else\n\t\tgl_FragColor = texture2DSRGB( renderer_BlitTexture, uv );\n\t#endif\n}\n\n"; // eslint-disable-line
26851
-
26852
- var blitScreenFs = "#include <common>\n\nuniform mediump sampler2D renderer_BlitTexture;\n#ifdef HAS_TEX_LOD\n\tuniform float renderer_BlitMipLevel;\n#endif\n\nvarying vec2 v_uv;\n\n#ifdef HAS_TEX_LOD\n\tvec4 texture2DLodSRGB(sampler2D tex, vec2 uv, float lod) {\n\t\tvec4 color = texture2DLodEXT(tex, uv, lod);\n\t\t#ifdef ENGINE_NO_SRGB\n\t\t\tcolor = sRGBToLinear(color);\n\t\t#endif\n\t\treturn color;\n\t}\n#endif\n\nvoid main() {\n\tvec2 uv = v_uv;\n\t// Screen uv is flipped\n\tuv.y = 1.0 - uv.y;\n\n\t#ifdef HAS_TEX_LOD\n\t\tgl_FragColor = texture2DLodSRGB( renderer_BlitTexture, uv, renderer_BlitMipLevel );\n\t#else\n\t\tgl_FragColor = texture2D( renderer_BlitTexture, uv );\n\t#endif\n\n\t// Color space in screen is in gamma space but without sRGB texture, so we need to convert it to linear space manually\n\tgl_FragColor = sRGBToLinear(gl_FragColor);\n}\n\n"; // eslint-disable-line
26853
-
26854
- var skyProceduralFs = "// This code uses the Unity skybox-Procedural shader algorithm, developed by Unity and licensed under the Unity Companion License. \n// The original implementation can be found at unity build-in shader(DefaultResourcesExtra/Skybox-Procedural.shader)\n\n#include <common>\n\nconst float MIE_G = -0.990;\nconst float MIE_G2 = 0.9801;\nconst float SKY_GROUND_THRESHOLD = 0.02;\n\nuniform float material_SunSize;\nuniform float material_SunSizeConvergence;\nuniform vec4 scene_SunlightColor;\nuniform vec3 scene_SunlightDirection;\n\nvarying vec3 v_GroundColor;\nvarying vec3 v_SkyColor;\n\n#ifdef MATERIAL_SUN_HIGH_QUALITY\n\tvarying vec3 v_Vertex;\n#elif defined(MATERIAL_SUN_SIMPLE)\n\tvarying vec3 v_RayDir;\n#else\n\tvarying float v_SkyGroundFactor;\n#endif\n\n#if defined(MATERIAL_SUN_HIGH_QUALITY)||defined(MATERIAL_SUN_SIMPLE)\n\tvarying vec3 v_SunColor;\n#endif\n\n// Calculates the Mie phase function\nfloat getMiePhase(float eyeCos, float eyeCos2) {\n\tfloat temp = 1.0 + MIE_G2 - 2.0 * MIE_G * eyeCos;\n\ttemp = pow(temp, pow(material_SunSize,0.65) * 10.0);\n\ttemp = max(temp,1.0e-4); // prevent division by zero, esp. in half precision\n\ttemp = 1.5 * ((1.0 - MIE_G2) / (2.0 + MIE_G2)) * (1.0 + eyeCos2) / temp;\n\treturn temp;\n}\n\n// Calculates the sun shape\nfloat calcSunAttenuation(vec3 lightPos, vec3 ray) {\n\t#ifdef MATERIAL_SUN_HIGH_QUALITY\n\t\tfloat focusedEyeCos = pow(clamp(dot(lightPos, ray),0.0,1.0), material_SunSizeConvergence);\n\t\treturn getMiePhase(-focusedEyeCos, focusedEyeCos * focusedEyeCos);\n\t#else //MATERIAL_SUN_SIMPLE\n\t\tvec3 delta = lightPos - ray;\n\t\tfloat dist = length(delta);\n\t\tfloat spot = 1.0 - smoothstep(0.0, material_SunSize, dist);\n\t\treturn spot * spot;\n\t#endif\n}\n\nvoid main() {\n\t// if y > 1 [eyeRay.y < -SKY_GROUND_THRESHOLD] - ground\n\t// if y >= 0 and < 1 [eyeRay.y <= 0 and > -SKY_GROUND_THRESHOLD] - horizon\n\t// if y < 0 [eyeRay.y > 0] - sky\n\tvec3 col = vec3(0.0, 0.0, 0.0);\n\n\t#ifdef MATERIAL_SUN_HIGH_QUALITY\n\t\tvec3 ray = normalize(v_Vertex);\n\t\tfloat y = ray.y / SKY_GROUND_THRESHOLD;\n\t#elif defined(MATERIAL_SUN_SIMPLE) \n\t\tvec3 ray = v_RayDir;\n\t\tfloat y = ray.y / SKY_GROUND_THRESHOLD;\t\n\t#else\n\t\tfloat y = v_SkyGroundFactor;\n\t#endif\n\n\t// if we did precalculate color in vprog: just do lerp between them\n\tcol = mix(v_SkyColor, v_GroundColor, clamp(y,0.0,1.0));\n\n\t#if defined(MATERIAL_SUN_HIGH_QUALITY)||defined(MATERIAL_SUN_SIMPLE)\n\t\tif (y < 0.0)\n\t\t\tcol += v_SunColor * calcSunAttenuation(-scene_SunlightDirection, -ray);\n\t#endif\n\n\n\tgl_FragColor = vec4(col, 1.0);\n}\n\n"; // eslint-disable-line
26855
-
26856
- var skyProceduralVs = "// This code uses the Unity skybox-Procedural shader algorithm, developed by Unity and licensed under the Unity Companion License. \n// The original implementation can be found at unity build-in shader(DefaultResourcesExtra/Skybox-Procedural.shader)\n\n#define OUTER_RADIUS 1.025\n#define RAYLEIGH (mix(0.0, 0.0025, pow(material_AtmosphereThickness,2.5)))\t// Rayleigh constant\n#define MIE 0.0010\t// Mie constant\n#define SUN_BRIGHTNESS 20.0\t// Sun brightness\n#define MAX_SCATTER 50.0 // Maximum scattering value, to prevent math overflows on Adrenos\n\nconst float SKY_GROUND_THRESHOLD = 0.02;\nconst float outerRadius = OUTER_RADIUS;\nconst float outerRadius2 = OUTER_RADIUS*OUTER_RADIUS;\nconst float innerRadius = 1.0;\nconst float innerRadius2 = 1.0;\nconst float cameraHeight = 0.0001;\n\nconst float HDSundiskIntensityFactor = 15.0;\nconst float simpleSundiskIntensityFactor = 27.0;\n\nconst float sunScale = 400.0 * SUN_BRIGHTNESS;\nconst float kmESun = MIE * SUN_BRIGHTNESS;\nconst float km4PI = MIE * 4.0 * 3.14159265;\nconst float scale = 1.0 / (OUTER_RADIUS - 1.0);\nconst float scaleDepth = 0.25;\nconst float scaleOverScaleDepth = (1.0 / (OUTER_RADIUS - 1.0)) / 0.25;\nconst float samples = 2.0; // THIS IS UNROLLED MANUALLY, DON'T TOUCH\n\n// RGB wavelengths .35 (.62=158), .43 (.68=174), .525 (.75=190)\nconst vec3 c_DefaultScatteringWavelength = vec3(0.65, 0.57, 0.475);\nconst vec3 c_VariableRangeForScatteringWavelength = vec3(0.15, 0.15, 0.15);\n\nattribute vec4 POSITION;\n\nuniform mat4 camera_VPMat;\nuniform vec3 material_SkyTint;\nuniform vec3 material_GroundTint;\nuniform float material_Exposure;\nuniform float material_AtmosphereThickness;\nuniform vec4 scene_SunlightColor;\nuniform vec3 scene_SunlightDirection;\n\nvarying vec3 v_GroundColor;\nvarying vec3 v_SkyColor;\n\n#ifdef MATERIAL_SUN_HIGH_QUALITY\n\tvarying vec3 v_Vertex;\n#elif defined(MATERIAL_SUN_SIMPLE)\n\tvarying vec3 v_RayDir;\n#else\n\tvarying float v_SkyGroundFactor;\n#endif\n\n#if defined(MATERIAL_SUN_HIGH_QUALITY)||defined(MATERIAL_SUN_SIMPLE)\n\tvarying vec3 v_SunColor;\n#endif\n\n#define GAMMA 2.2\n#define COLOR_2_GAMMA(color) pow(color,vec3(1.0/GAMMA))\n#define COLOR_2_LINEAR(color) color\n\n// Calculates the Rayleigh phase function\nfloat getRayleighPhase(vec3 light, vec3 ray) \n{\n\tfloat eyeCos = dot(light, ray);\n\treturn 0.75 + 0.75 * eyeCos * eyeCos;\n}\n\nfloat scaleAngle(float inCos)\n{\n\tfloat x = 1.0 - inCos;\n\treturn 0.25 * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25))));\n}\n\nvoid main () {\n\tgl_Position = camera_VPMat*vec4(POSITION.xyz,1.0);\n\n \tvec3 skyTintInGammaSpace = COLOR_2_GAMMA(material_SkyTint);\n\tvec3 scatteringWavelength = mix(c_DefaultScatteringWavelength-c_VariableRangeForScatteringWavelength,c_DefaultScatteringWavelength+c_VariableRangeForScatteringWavelength,vec3(1.0) - skyTintInGammaSpace); // using Tint in sRGB+ gamma allows for more visually linear interpolation and to keep (0.5) at (128, gray in sRGB) point\n\tvec3 invWavelength = 1.0 / pow(scatteringWavelength, vec3(4.0));\n\n\tfloat krESun = RAYLEIGH * SUN_BRIGHTNESS;\n\tfloat kr4PI = RAYLEIGH * 4.0 * 3.14159265;\n\n\tvec3 cameraPos = vec3(0.0,innerRadius + cameraHeight,0.0); // The camera's current position\n\n\t// Get the ray from the camera to the vertex and its length (which is the far point of the ray passing through the atmosphere)\n\tvec3 eyeRay = normalize(POSITION.xyz);\n\n\tfloat far = 0.0;\n\tvec3 cIn, cOut;\n\tif (eyeRay.y >= 0.0) {\n\t\t// Sky \n\t\t// Calculate the length of the \"atmosphere\"\n\t\tfar = sqrt(outerRadius2 + innerRadius2 * eyeRay.y * eyeRay.y - innerRadius2) - innerRadius * eyeRay.y;\n\n\t\t// Calculate the ray's starting position, then calculate its scattering offset\n\t\tfloat height = innerRadius + cameraHeight;\n\t\tfloat depth = exp(scaleOverScaleDepth * -cameraHeight);\n\t\tfloat startAngle = dot(eyeRay, cameraPos) / height;\n\t\tfloat startOffset = depth*scaleAngle(startAngle);\n\n\t\t// Initialize the scattering loop variables\n\t\tfloat sampleLength = far / samples;\n\t\tfloat scaledLength = sampleLength * scale;\n\t\tvec3 sampleRay = eyeRay * sampleLength;\n\t\tvec3 samplePoint = cameraPos + sampleRay * 0.5;\n\n\t\tvec3 frontColor = vec3(0.0);\n\t\t//unrolling this manually to avoid some platform for loop slow\n\t\t{\n\t\t\tfloat height = length(samplePoint);\n\t\t\tfloat depth = exp(scaleOverScaleDepth * (innerRadius - height));\n\t\t\tfloat lightAngle = dot(-scene_SunlightDirection, samplePoint) / height;\n\t\t\tfloat cameraAngle = dot(eyeRay, samplePoint) / height;\n\t\t\tfloat scatter = (startOffset + depth*(scaleAngle(lightAngle) - scaleAngle(cameraAngle)));\n\t\t\tvec3 attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI));\n\n\t\t\tfrontColor += attenuate * (depth * scaledLength);\n\t\t\tsamplePoint += sampleRay;\n\t\t}\n\t\t{\n\t\t\tfloat height = length(samplePoint);\n\t\t\tfloat depth = exp(scaleOverScaleDepth * (innerRadius - height));\n\t\t\tfloat lightAngle = dot(-scene_SunlightDirection, samplePoint) / height;\n\t\t\tfloat cameraAngle = dot(eyeRay, samplePoint) / height;\n\t\t\tfloat scatter = (startOffset + depth*(scaleAngle(lightAngle) - scaleAngle(cameraAngle)));\n\t\t\tvec3 attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI));\n\n\t\t\tfrontColor += attenuate * (depth * scaledLength);\n\t\t\tsamplePoint += sampleRay;\n\t\t}\n\n\t\t// Finally, scale the Mie and Rayleigh colors and set up the varying variables for the pixel shader\n\t\tcIn = frontColor * (invWavelength * krESun);\n\t\tcOut = frontColor * kmESun;\n\t} else {\n\t\t// Ground\n\t\tfar = (-cameraHeight) / (min(-0.001, eyeRay.y));\n\t\tvec3 pos = cameraPos + far * eyeRay;\n\n\t\t// Calculate the ray's starting position, then calculate its scattering offset\n\t\tfloat depth = exp((-cameraHeight) * (1.0/scaleDepth));\n\t\tfloat cameraAngle = dot(-eyeRay, pos);\n\t\tfloat lightAngle = dot(-scene_SunlightDirection, pos);\n\t\tfloat cameraScale = scaleAngle(cameraAngle);\n\t\tfloat lightScale = scaleAngle(lightAngle);\n\t\tfloat cameraOffset = depth*cameraScale;\n\t\tfloat temp = lightScale + cameraScale;\n\n\t\t// Initialize the scattering loop variables\n\t\tfloat sampleLength = far / samples;\n\t\tfloat scaledLength = sampleLength * scale;\n\t\tvec3 sampleRay = eyeRay * sampleLength;\n\t\tvec3 samplePoint = cameraPos + sampleRay * 0.5;\n\n\t\t// Now loop through the sample rays\n\t\tvec3 frontColor = vec3(0.0, 0.0, 0.0);\n\t\tvec3 attenuate;\n\n\t\t// Loop removed because we kept hitting SM2.0 temp variable limits. Doesn't affect the image too much\n\t\t{\n\t\t\tfloat height = length(samplePoint);\n\t\t\tfloat depth = exp(scaleOverScaleDepth * (innerRadius - height));\n\t\t\tfloat scatter = depth*temp - cameraOffset;\n\t\t\tattenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI));\n\t\t\tfrontColor += attenuate * (depth * scaledLength);\n\t\t\tsamplePoint += sampleRay;\n\t\t}\n\n\t\tcIn = frontColor * (invWavelength * krESun + kmESun);\n\t\tcOut = clamp(attenuate, 0.0, 1.0);\n\t}\n\n\t#ifdef MATERIAL_SUN_HIGH_QUALITY\n\t\tv_Vertex = -POSITION.xyz;\n\t#elif defined(MATERIAL_SUN_SIMPLE) \n\t\tv_RayDir = -eyeRay;\n\t#else\n\t\tv_SkyGroundFactor = -eyeRay.y / SKY_GROUND_THRESHOLD;\n\t#endif\n\n\t// if we want to calculate color in vprog:\n\t// 1. in case of linear: multiply by _Exposure in here (even in case of lerp it will be common multiplier, so we can skip mul in fshader)\n\t// 2. in case of gamma: do sqrt right away instead of doing that in fshader\n\t\n\tv_GroundColor = material_Exposure * (cIn + COLOR_2_LINEAR(material_GroundTint) * cOut);\n\tv_SkyColor = material_Exposure * (cIn * getRayleighPhase(-scene_SunlightDirection, -eyeRay));\n\n\t\n\t// The sun should have a stable intensity in its course in the sky. Moreover it should match the highlight of a purely specular material.\n\t// This matching was done using the standard shader BRDF1 on the 5/31/2017\n\t// Finally we want the sun to be always bright even in LDR thus the normalization of the lightColor for low intensity.\n\tfloat lightColorIntensity = clamp(length(scene_SunlightColor.xyz), 0.25, 1.0);\n\n\t#ifdef MATERIAL_SUN_HIGH_QUALITY \n\t\tv_SunColor = HDSundiskIntensityFactor * clamp(cOut,0.0,1.0) * scene_SunlightColor.xyz / lightColorIntensity;\n\t#elif defined(MATERIAL_SUN_SIMPLE) \n\t\tv_SunColor = simpleSundiskIntensityFactor * clamp(cOut * sunScale,0.0,1.0) * scene_SunlightColor.xyz / lightColorIntensity;\n\t#endif\n}\n"; // eslint-disable-line
26857
-
26858
- var backgroundTextureFs = "#include <common>\nuniform sampler2D material_BaseTexture;\n\nvarying vec2 v_uv;\n\nvoid main() {\n gl_FragColor = texture2DSRGB(material_BaseTexture, v_uv);\n}"; // eslint-disable-line
26859
-
26860
- var backgroundTextureVs = "attribute vec3 POSITION;\nattribute vec2 TEXCOORD_0;\nvarying vec2 v_uv;\nuniform vec4 camera_ProjectionParams;\n\nvoid main() {\n gl_Position = vec4(POSITION, 1.0);\n gl_Position.y *= camera_ProjectionParams.x;\n \n v_uv = TEXCOORD_0;\n}"; // eslint-disable-line
26861
-
26862
- var blinnPhongFs = "#include <common>\n#include <camera_declare>\n\n#include <uv_share>\n#include <normal_share>\n#include <color_share>\n#include <worldpos_share>\n\n#include <light_frag_define>\n#include <ShadowFragmentDeclaration>\n#include <mobile_material_frag>\n\n#include <FogFragmentDeclaration>\n#include <normal_get>\n\nvoid main() {\n\n #include <begin_mobile_frag>\n #include <begin_viewdir_frag>\n #include <mobile_blinnphong_frag>\n\n gl_FragColor = emission + ambient + diffuse + specular;\n\n #ifdef MATERIAL_IS_TRANSPARENT\n gl_FragColor.a = diffuse.a;\n #else\n gl_FragColor.a = 1.0;\n #endif\n\n #include <FogFragment>\n}\n"; // eslint-disable-line
26863
-
26864
- var blinnPhongVs = "#include <common>\n#include <common_vert>\n#include <blendShape_input>\n#include <uv_share>\n#include <color_share>\n#include <normal_share>\n#include <worldpos_share>\n\n#include <ShadowVertexDeclaration>\n#include <FogVertexDeclaration>\n\nvoid main() {\n\n #include <begin_position_vert>\n #include <begin_normal_vert>\n #include <blendShape_vert>\n #include <skinning_vert>\n #include <uv_vert>\n #include <color_vert>\n #include <normal_vert>\n #include <worldpos_vert>\n #include <position_vert>\n\n #include <ShadowVertex>\n #include <FogVertex>\n}\n"; // eslint-disable-line
26865
-
26866
- var depthOnlyFs = "void main() {\n}"; // eslint-disable-line
26867
-
26868
- var depthOnlyVs = "#define MATERIAL_OMIT_NORMAL\n#include <common>\n#include <common_vert>\n#include <blendShape_input>\nuniform mat4 camera_VPMat;\n\n\nvoid main() {\n\n #include <begin_position_vert>\n #include <blendShape_vert>\n #include <skinning_vert>\n #include <position_vert>\n\n}\n"; // eslint-disable-line
26869
-
26870
- var particleFs = "#include <common>\n\nvarying vec4 v_Color;\nvarying vec2 v_TextureCoordinate;\nuniform sampler2D material_BaseTexture;\nuniform vec4 material_BaseColor;\n \nuniform mediump vec3 material_EmissiveColor;\n#ifdef MATERIAL_HAS_EMISSIVETEXTURE\n uniform sampler2D material_EmissiveTexture;\n#endif\n\n#ifdef RENDERER_MODE_MESH\n\tvarying vec4 v_MeshColor;\n#endif\n\nvoid main() {\n\tvec4 color = material_BaseColor * v_Color;\n\n\t#if defined(RENDERER_MODE_MESH) && defined(RENDERER_ENABLE_VERTEXCOLOR)\n\t\tcolor *= v_MeshColor;\n\t#endif\n\n\t#ifdef MATERIAL_HAS_BASETEXTURE\n\t\tcolor *= texture2DSRGB(material_BaseTexture, v_TextureCoordinate);\n\t#endif\n\t\n\t// Emissive\n\tvec3 emissiveRadiance = material_EmissiveColor;\n\t#ifdef MATERIAL_HAS_EMISSIVETEXTURE\n\t\temissiveRadiance *= texture2DSRGB(material_EmissiveTexture, v_TextureCoordinate).rgb;\n\t#endif\n\n\tcolor.rgb += emissiveRadiance;\n\n\tgl_FragColor = color;\n}"; // eslint-disable-line
26871
-
26872
- var particleVs = "#if defined(RENDERER_MODE_SPHERE_BILLBOARD) || defined(RENDERER_MODE_STRETCHED_BILLBOARD) || defined(RENDERER_MODE_HORIZONTAL_BILLBOARD) || defined(RENDERER_MODE_VERTICAL_BILLBOARD)\n attribute vec4 a_CornerTextureCoordinate;\n#endif\n\n#ifdef RENDERER_MODE_MESH\n attribute vec3 POSITION;\n #ifdef RENDERER_ENABLE_VERTEXCOLOR\n attribute vec4 COLOR_0;\n #endif\n attribute vec2 TEXCOORD_0;\n varying vec4 v_MeshColor;\n#endif\n\nattribute vec4 a_ShapePositionStartLifeTime;\nattribute vec4 a_DirectionTime;\nattribute vec4 a_StartColor;\nattribute vec3 a_StartSize;\nattribute vec3 a_StartRotation0;\nattribute float a_StartSpeed;\n\n//#if defined(COLOR_OVER_LIFETIME) || defined(RENDERER_COL_RANDOM_GRADIENTS) || defined(RENDERER_SOL_RANDOM_CURVES) || defined(RENDERER_SOL_RANDOM_CURVES_SEPARATE) || defined(ROTATION_OVER_LIFE_TIME_RANDOM_CONSTANTS) || defined(ROTATION_OVER_LIFETIME_RANDOM_CURVES)\n attribute vec4 a_Random0;\n//#endif\n\n#if defined(RENDERER_TSA_FRAME_RANDOM_CURVES) || defined(RENDERER_VOL_IS_RANDOM_TWO)\n attribute vec4 a_Random1; // x:texture sheet animation random\n#endif\n\n#if defined(RENDERER_FOL_CONSTANT_MODE) || defined(RENDERER_FOL_CURVE_MODE) || defined(RENDERER_LVL_MODULE_ENABLED)\n attribute vec4 a_Random2;\n#endif\n\nattribute vec3 a_SimulationWorldPosition;\nattribute vec4 a_SimulationWorldRotation;\n\n#ifdef RENDERER_TRANSFORM_FEEDBACK\n attribute vec3 a_FeedbackPosition;\n attribute vec3 a_FeedbackVelocity;\n#endif\n\nvarying vec4 v_Color;\n#ifdef MATERIAL_HAS_BASETEXTURE\n attribute vec4 a_SimulationUV;\n varying vec2 v_TextureCoordinate;\n#endif\n\nuniform float renderer_CurrentTime;\nuniform vec3 renderer_Gravity;\nuniform vec3 renderer_WorldPosition;\nuniform vec4 renderer_WorldRotation;\nuniform bool renderer_ThreeDStartRotation;\nuniform int renderer_ScalingMode;\nuniform vec3 renderer_PositionScale;\nuniform vec3 renderer_SizeScale;\nuniform vec3 renderer_PivotOffset;\n\nuniform mat4 camera_ViewMat;\nuniform mat4 camera_ProjMat;\n\n#ifdef RENDERER_MODE_STRETCHED_BILLBOARD\n uniform vec3 camera_Position;\n#endif\nuniform vec3 camera_Forward; // TODO:只有几种广告牌模式需要用\nuniform vec3 camera_Up;\n\nuniform float renderer_StretchedBillboardLengthScale;\nuniform float renderer_StretchedBillboardSpeedScale;\nuniform int renderer_SimulationSpace;\n\n#include <particle_common>\n#include <velocity_over_lifetime_module>\n#include <force_over_lifetime_module>\n#include <color_over_lifetime_module>\n#include <size_over_lifetime_module>\n#include <rotation_over_lifetime_module>\n#include <texture_sheet_animation_module>\n#include <noise_module>\n\nvec3 computeParticlePosition(in vec3 startVelocity, in float age, in float normalizedAge, vec3 gravityVelocity, vec4 worldRotation, inout vec3 localVelocity, inout vec3 worldVelocity) {\n vec3 startPosition = startVelocity * age;\n\n vec3 finalPosition;\n vec3 localPositionOffset = startPosition;\n vec3 worldPositionOffset;\n\n #ifdef _VOL_MODULE_ENABLED\n vec3 lifeVelocity; \n vec3 velocityPositionOffset = computeVelocityPositionOffset(normalizedAge, age, lifeVelocity);\n if (renderer_VOLSpace == 0) {\n localVelocity += lifeVelocity;\n localPositionOffset += velocityPositionOffset;\n } else {\n worldVelocity += lifeVelocity;\n worldPositionOffset += velocityPositionOffset;\n }\n #endif\n\n #ifdef _FOL_MODULE_ENABLED\n vec3 forceVelocity;\n vec3 forcePositionOffset = computeForcePositionOffset(normalizedAge, age, forceVelocity);\n if (renderer_FOLSpace == 0) {\n localVelocity += forceVelocity;\n localPositionOffset += forcePositionOffset;\n } else {\n worldVelocity += forceVelocity;\n worldPositionOffset += forcePositionOffset;\n }\n #endif\n\n finalPosition = rotationByQuaternions(a_ShapePositionStartLifeTime.xyz + localPositionOffset, worldRotation) + worldPositionOffset;\n\n if (renderer_SimulationSpace == 0) {\n finalPosition = finalPosition + renderer_WorldPosition;\n } else if (renderer_SimulationSpace == 1) {\n\t finalPosition = finalPosition + a_SimulationWorldPosition;\n\t}\n\n finalPosition += 0.5 * gravityVelocity * age;\n\n return finalPosition;\n}\n\nvoid main() {\n float age = renderer_CurrentTime - a_DirectionTime.w;\n float normalizedAge = age / a_ShapePositionStartLifeTime.w;\n // normalizedAge >= 0.0: skip stale TF slots whose startTime is from a previous playback (e.g. after StopEmittingAndClear).\n if (normalizedAge >= 0.0 && normalizedAge < 1.0) {\n vec4 worldRotation;\n if (renderer_SimulationSpace == 0) {\n worldRotation = renderer_WorldRotation;\n } else {\n worldRotation = a_SimulationWorldRotation;\n }\n\n vec3 localVelocity;\n vec3 worldVelocity;\n\n #ifdef RENDERER_TRANSFORM_FEEDBACK\n // Transform Feedback mode: position in simulation space (local or world).\n // Local: transform to world; World: use directly.\n vec3 center;\n if (renderer_SimulationSpace == 0) {\n center = rotationByQuaternions(a_FeedbackPosition, worldRotation) + renderer_WorldPosition;\n } else if (renderer_SimulationSpace == 1) {\n center = a_FeedbackPosition;\n }\n localVelocity = a_FeedbackVelocity;\n worldVelocity = vec3(0.0);\n\n #ifdef _VOL_MODULE_ENABLED\n vec3 instantVOLVelocity;\n computeVelocityPositionOffset(normalizedAge, age, instantVOLVelocity);\n if (renderer_VOLSpace == 0) {\n localVelocity += instantVOLVelocity;\n } else {\n worldVelocity += instantVOLVelocity;\n }\n #endif\n #else\n // Original analytical path\n vec3 startVelocity = a_DirectionTime.xyz * a_StartSpeed;\n vec3 gravityVelocity = renderer_Gravity * a_Random0.x * age;\n localVelocity = startVelocity;\n worldVelocity = gravityVelocity;\n vec3 center = computeParticlePosition(startVelocity, age, normalizedAge, gravityVelocity, worldRotation, localVelocity, worldVelocity);\n #endif\n\n #include <sphere_billboard>\n #include <stretched_billboard>\n #include <horizontal_billboard>\n #include <vertical_billboard>\n #include <particle_mesh>\n\n gl_Position = camera_ProjMat * camera_ViewMat * vec4(center, 1.0);\n v_Color = computeParticleColor(a_StartColor, normalizedAge);\n\n #ifdef MATERIAL_HAS_BASETEXTURE\n vec2 simulateUV;\n #if defined(RENDERER_MODE_SPHERE_BILLBOARD) || defined(RENDERER_MODE_STRETCHED_BILLBOARD) || defined(RENDERER_MODE_HORIZONTAL_BILLBOARD) || defined(RENDERER_MODE_VERTICAL_BILLBOARD)\n simulateUV = a_CornerTextureCoordinate.zw * a_SimulationUV.xy + a_SimulationUV.zw;\n v_TextureCoordinate = computeParticleUV(simulateUV, normalizedAge);\n #endif\n #ifdef RENDERER_MODE_MESH\n simulateUV = a_SimulationUV.zw + TEXCOORD_0 * a_SimulationUV.xy;\n v_TextureCoordinate = computeParticleUV(simulateUV, normalizedAge);\n #endif\n #endif\n } else {\n\t gl_Position = vec4(2.0, 2.0, 2.0, 1.0); // Discard use out of X(-1,1),Y(-1,1),Z(0,1)\n }\n}"; // eslint-disable-line
26873
-
26874
- var pbrSpecularFs = "#include <common>\n#include <camera_declare>\n\n#include <FogFragmentDeclaration>\n\n#include <uv_share>\n#include <normal_share>\n#include <color_share>\n#include <worldpos_share>\n\n#include <light_frag_define>\n\n\n#include <pbr_frag_define>\n#include <pbr_helper>\n\nvoid main() {\n #include <pbr_frag>\n #include <FogFragment>\n}\n"; // eslint-disable-line
26875
-
26876
- var pbrFs = "#include <common>\n#include <camera_declare>\n#include <transform_declare>\n\n#include <FogFragmentDeclaration>\n#include <PositionClipSpaceDeclaration>\n\n#include <uv_share>\n#include <normal_share>\n#include <color_share>\n#include <worldpos_share>\n\n#include <light_frag_define>\n\n#include <pbr_frag_define>\n#include <pbr_helper>\n\nvoid main() {\n #include <pbr_frag>\n #include <FogFragment>\n}\n"; // eslint-disable-line
26877
-
26878
- var pbrVs = "#include <common>\n#include <common_vert>\n#include <blendShape_input>\n#include <uv_share>\n#include <color_share>\n#include <normal_share>\n#include <worldpos_share>\n\n#include <ShadowVertexDeclaration>\n#include <FogVertexDeclaration>\n#include <PositionClipSpaceDeclaration>\n\nvoid main() {\n\n #include <begin_position_vert>\n #include <begin_normal_vert>\n #include <blendShape_vert>\n #include <skinning_vert>\n #include <uv_vert>\n #include <color_vert>\n #include <normal_vert>\n #include <worldpos_vert>\n #include <position_vert>\n\n #include <ShadowVertex>\n #include <FogVertex>\n #include <PositionClipSpaceVertex>\n}\n"; // eslint-disable-line
26879
-
26880
- var shadowMapFs = "#ifdef ENGINE_NO_DEPTH_TEXTURE\n /**\n * Decompose and save depth value.\n */\n vec4 pack (float depth) {\n // Use rgba 4 bytes with a total of 32 bits to store the z value, and the accuracy of 1 byte is 1/256.\n const vec4 bitShift = vec4(1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0);\n const vec4 bitMask = vec4(1.0/256.0, 1.0/256.0, 1.0/256.0, 0.0);\n\n vec4 rgbaDepth = fract(depth * bitShift); // Calculate the z value of each point\n\n // Cut off the value which do not fit in 8 bits\n rgbaDepth -= rgbaDepth.gbaa * bitMask;\n\n return rgbaDepth;\n }\n#endif\n\n\nuniform vec4 material_BaseColor;\nuniform sampler2D material_BaseTexture;\nuniform float material_AlphaCutoff;\nvarying vec2 v_uv;\n\nvoid main() {\n #if defined(MATERIAL_IS_ALPHA_CUTOFF) || (defined(SCENE_ENABLE_TRANSPARENT_SHADOW) && defined(MATERIAL_IS_TRANSPARENT))\n float alpha = material_BaseColor.a;\n #ifdef MATERIAL_HAS_BASETEXTURE\n alpha *= texture2D(material_BaseTexture, v_uv).a;\n #endif\n \n #ifdef MATERIAL_IS_ALPHA_CUTOFF\n if(alpha < material_AlphaCutoff){\n discard;\n }\n #endif\n \n #if defined(SCENE_ENABLE_TRANSPARENT_SHADOW) && defined(MATERIAL_IS_TRANSPARENT)\n // Interleaved gradient noise\n float noise = fract(52.982919 * fract(dot(vec2(0.06711, 0.00584), gl_FragCoord.xy)));\n if (alpha <= noise) {\n discard;\n };\n #endif\n #endif\n\n #ifdef ENGINE_NO_DEPTH_TEXTURE\n gl_FragColor = pack(gl_FragCoord.z);\n #else\n gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);\n #endif\n}"; // eslint-disable-line
26881
-
26882
- var shadowMapVs = "#include <common>\n#include <common_vert>\n#include <blendShape_input>\n#include <normal_share>\n#include <uv_share>\nuniform mat4 camera_VPMat;\nuniform vec2 scene_ShadowBias; // x: depth bias, y: normal bias\nuniform vec3 scene_LightDirection;\n\nvec3 applyShadowBias(vec3 positionWS) {\n positionWS -= scene_LightDirection * scene_ShadowBias.x;\n return positionWS;\n}\n\nvec3 applyShadowNormalBias(vec3 positionWS, vec3 normalWS) {\n float invNdotL = 1.0 - clamp(dot(-scene_LightDirection, normalWS), 0.0, 1.0);\n float scale = invNdotL * scene_ShadowBias.y;\n positionWS += normalWS * vec3(scale);\n return positionWS;\n}\n\nvoid main() {\n\n #include <begin_position_vert>\n #include <begin_normal_vert>\n #include <blendShape_vert>\n #include <skinning_vert>\n #include <uv_vert>\n \n vec4 positionWS = renderer_ModelMat * position;\n\n positionWS.xyz = applyShadowBias(positionWS.xyz);\n #ifndef MATERIAL_OMIT_NORMAL\n #ifdef RENDERER_HAS_NORMAL\n vec3 normalWS = normalize( mat3(renderer_NormalMat) * normal );\n positionWS.xyz = applyShadowNormalBias(positionWS.xyz, normalWS);\n #endif\n #endif\n\n\n vec4 positionCS = camera_VPMat * positionWS;\n positionCS.z = max(positionCS.z, -1.0);// clamp to min ndc z\n\n gl_Position = positionCS;\n\n}\n"; // eslint-disable-line
26883
-
26884
- var skyboxFs = "#include <common>\nuniform samplerCube material_CubeTexture;\n\nvarying vec3 v_cubeUV;\nuniform float material_Exposure;\nuniform vec4 material_TintColor;\n\nvoid main() {\n vec4 textureColor = textureCube( material_CubeTexture, v_cubeUV );\n\n #ifdef ENGINE_NO_SRGB\n textureColor = sRGBToLinear(textureColor);\n #endif\n\n textureColor.rgb *= material_Exposure * material_TintColor.rgb;\n \n gl_FragColor = textureColor;\n}\n"; // eslint-disable-line
26885
-
26886
- var skyboxVs = "#include <common_vert>\n\nuniform mat4 camera_VPMat;\n\nvarying vec3 v_cubeUV;\nuniform float material_Rotation;\n\nvec4 rotateY(vec4 v, float angle) {\n\tconst float deg2rad = 3.1415926 / 180.0;\n\tfloat radian = angle * deg2rad;\n\tfloat sina = sin(radian);\n\tfloat cosa = cos(radian);\n\tmat2 m = mat2(cosa, -sina, sina, cosa);\n\treturn vec4(m * v.xz, v.yw).xzyw;\n}\n\nvoid main() {\n v_cubeUV = POSITION;\n gl_Position = camera_VPMat * rotateY(vec4(POSITION, 1.0), material_Rotation);\n}\n"; // eslint-disable-line
26887
-
26888
- var spriteMaskFs = "uniform sampler2D renderer_MaskTexture;\nuniform float renderer_MaskAlphaCutoff;\nvarying vec2 v_uv;\n\nvoid main()\n{\n vec4 color = texture2D(renderer_MaskTexture, v_uv);\n if (color.a < renderer_MaskAlphaCutoff) {\n discard;\n }\n\n gl_FragColor = color;\n}\n"; // eslint-disable-line
26889
-
26890
- var spriteMaskVs = "uniform mat4 camera_VPMat;\n\nattribute vec3 POSITION;\nattribute vec2 TEXCOORD_0;\n\nvarying vec2 v_uv;\n\nvoid main()\n{\n gl_Position = camera_VPMat * vec4(POSITION, 1.0);\n v_uv = TEXCOORD_0;\n}\n"; // eslint-disable-line
26891
-
26892
- var spriteFs = "#include <common>\nuniform sampler2D renderer_SpriteTexture;\n\nvarying vec2 v_uv;\nvarying vec4 v_color;\n\nvoid main()\n{\n vec4 baseColor = texture2DSRGB(renderer_SpriteTexture, v_uv);\n gl_FragColor = baseColor * v_color;\n}\n"; // eslint-disable-line
26893
-
26894
- var spriteVs = "uniform mat4 renderer_MVPMat;\n\nattribute vec3 POSITION;\nattribute vec2 TEXCOORD_0;\nattribute vec4 COLOR_0;\n\nvarying vec2 v_uv;\nvarying vec4 v_color;\n\nvoid main()\n{\n gl_Position = renderer_MVPMat * vec4(POSITION, 1.0);\n\n v_uv = TEXCOORD_0;\n v_color = COLOR_0;\n}\n"; // eslint-disable-line
26895
-
26896
- var textFs = "uniform sampler2D renderElement_TextTexture;\n\nvarying vec2 v_uv;\nvarying vec4 v_color;\n\nvoid main()\n{\n vec4 texColor = texture2D(renderElement_TextTexture, v_uv);\n #ifdef GRAPHICS_API_WEBGL2\n float coverage = texColor.r;\n #else\n float coverage = texColor.a;\n #endif\n gl_FragColor = vec4(v_color.rgb, v_color.a * coverage);\n}\n"; // eslint-disable-line
26897
-
26898
- var textVs = "uniform mat4 renderer_MVPMat;\n\nattribute vec3 POSITION;\nattribute vec2 TEXCOORD_0;\nattribute vec4 COLOR_0;\n\nvarying vec2 v_uv;\nvarying vec4 v_color;\n\nvoid main()\n{\n gl_Position = renderer_MVPMat * vec4(POSITION, 1.0);\n\n v_uv = TEXCOORD_0;\n v_color = COLOR_0;\n}\n"; // eslint-disable-line
26899
-
26900
- var trailFs = "#include <common>\n\nvarying vec2 v_uv;\nvarying vec4 v_color;\n\nuniform vec4 material_BaseColor;\n\n#ifdef MATERIAL_HAS_BASETEXTURE\n uniform sampler2D material_BaseTexture;\n#endif\n\nuniform mediump vec3 material_EmissiveColor;\n#ifdef MATERIAL_HAS_EMISSIVETEXTURE\n uniform sampler2D material_EmissiveTexture;\n#endif\n\nvoid main() {\n vec4 color = material_BaseColor * v_color;\n\n #ifdef MATERIAL_HAS_BASETEXTURE\n color *= texture2DSRGB(material_BaseTexture, v_uv);\n #endif\n\n // Emissive\n vec3 emissiveRadiance = material_EmissiveColor;\n #ifdef MATERIAL_HAS_EMISSIVETEXTURE\n emissiveRadiance *= texture2DSRGB(material_EmissiveTexture, v_uv).rgb;\n #endif\n\n color.rgb += emissiveRadiance;\n\n gl_FragColor = color;\n}\n\n"; // eslint-disable-line
26901
-
26902
- var trailVs = "attribute vec4 a_PositionBirthTime; // xyz: World position, w: Birth time (used by CPU only)\nattribute vec4 a_CornerTangent; // x: Corner (-1 or 1), yzw: Tangent direction\nattribute float a_Distance; // Absolute cumulative distance (written once per point)\n\nuniform vec4 renderer_TrailParams; // x: TextureMode (0: Stretch, 1: Tile), y: TextureScaleX, z: TextureScaleY\nuniform vec2 renderer_DistanceParams; // x: HeadDistance, y: TailDistance\nuniform vec3 camera_Position;\nuniform mat4 camera_ViewMat;\nuniform mat4 camera_ProjMat;\nuniform vec2 renderer_WidthCurve[4]; // Width curve (4 keyframes max: x=time, y=value)\nuniform vec4 renderer_ColorKeys[4]; // Color gradient (x=time, yzw=rgb)\nuniform vec2 renderer_AlphaKeys[4]; // Alpha gradient (x=time, y=alpha)\nuniform vec4 renderer_CurveMaxTime; // x: colorMaxTime, y: alphaMaxTime, z: widthMaxTime\n\nvarying vec2 v_uv;\nvarying vec4 v_color;\n\n#include <particle_common>\n\nvoid main() {\n vec3 position = a_PositionBirthTime.xyz;\n float corner = a_CornerTangent.x;\n vec3 tangent = a_CornerTangent.yzw;\n\n // Distance-based relative position: 0=head(newest), 1=tail(oldest)\n float distFromHead = renderer_DistanceParams.x - a_Distance;\n float totalDist = renderer_DistanceParams.x - renderer_DistanceParams.y;\n float relativePos = totalDist > 0.0 ? distFromHead / totalDist : 0.0;\n\n // Billboard: expand perpendicular to tangent and view direction\n vec3 toCamera = normalize(camera_Position - position);\n vec3 right = cross(tangent, toCamera);\n float rightLenSq = dot(right, right);\n if (rightLenSq < 0.000001) {\n right = cross(tangent, vec3(0.0, 1.0, 0.0));\n rightLenSq = dot(right, right);\n if (rightLenSq < 0.000001) {\n right = cross(tangent, vec3(1.0, 0.0, 0.0));\n rightLenSq = dot(right, right);\n }\n }\n right = right * inversesqrt(rightLenSq);\n\n float width = evaluateParticleCurve(renderer_WidthCurve, min(relativePos, renderer_CurveMaxTime.z));\n vec3 worldPosition = position + right * width * 0.5 * corner;\n\n gl_Position = camera_ProjMat * camera_ViewMat * vec4(worldPosition, 1.0);\n\n // u = position along trail (affected by textureMode), v = corner side.\n float u = renderer_TrailParams.x == 0.0 ? relativePos : distFromHead;\n float v = corner * 0.5 + 0.5;\n v_uv = vec2(u * renderer_TrailParams.y, v * renderer_TrailParams.z);\n\n v_color = evaluateParticleGradient(renderer_ColorKeys, renderer_CurveMaxTime.x, renderer_AlphaKeys, renderer_CurveMaxTime.y, relativePos);\n}\n"; // eslint-disable-line
26903
-
26904
- var unlitFs = "#include <common>\n#include <uv_share>\n#include <FogFragmentDeclaration>\n\nuniform vec4 material_BaseColor;\nuniform float material_AlphaCutoff;\n\n#ifdef MATERIAL_HAS_BASETEXTURE\n uniform sampler2D material_BaseTexture;\n#endif\n\nvoid main() {\n vec4 baseColor = material_BaseColor;\n\n #ifdef MATERIAL_HAS_BASETEXTURE\n baseColor *= texture2DSRGB(material_BaseTexture, v_uv);\n #endif\n\n #ifdef MATERIAL_IS_ALPHA_CUTOFF\n if( baseColor.a < material_AlphaCutoff ) {\n discard;\n }\n #endif\n\n gl_FragColor = baseColor;\n\n #ifndef MATERIAL_IS_TRANSPARENT\n gl_FragColor.a = 1.0;\n #endif\n\n #include <FogFragment>\n}\n"; // eslint-disable-line
26905
-
26906
- var unlitVs = "#include <common>\n#include <common_vert>\n#include <blendShape_input>\n#include <uv_share>\n#include <FogVertexDeclaration>\n\nvoid main() {\n\n #include <begin_position_vert>\n #include <blendShape_vert>\n #include <skinning_vert>\n #include <uv_vert>\n #include <position_vert>\n\n #include <FogVertex>\n}\n"; // eslint-disable-line
26907
-
26908
- /**
26909
- * @internal
26910
- * Shared shader definition for Transform Feedback simulation.
26911
- * Multiple simulators using the same shader share a single program pool per engine.
26912
- */ var TransformFeedbackShader = /*#__PURE__*/ function() {
26913
- function TransformFeedbackShader(vertexSource, fragmentSource, feedbackVaryings) {
26914
- this._id = ShaderPass._shaderPassCounter++;
26915
- this.vertexSource = vertexSource;
26916
- this.fragmentSource = fragmentSource;
26917
- this.feedbackVaryings = feedbackVaryings;
26918
- }
26919
- var _proto = TransformFeedbackShader.prototype;
26920
- /**
26921
- * Get or compile a shader program for the given engine and macro combination.
26922
- */ _proto.getProgram = function getProgram(engine, macroCollection) {
26923
- var pool = engine._getShaderProgramPool(this._id);
26924
- var program = pool.get(macroCollection);
26925
- if (program) return program;
26926
- var _ShaderFactory_compilePlatformSource = ShaderFactory.compilePlatformSource(engine, macroCollection, this.vertexSource, this.fragmentSource), vertexSource = _ShaderFactory_compilePlatformSource.vertexSource, fragmentSource = _ShaderFactory_compilePlatformSource.fragmentSource;
26927
- program = new ShaderProgram(engine, vertexSource, fragmentSource, this.feedbackVaryings);
26928
- if (!program.isValid) {
26929
- Logger.error("TransformFeedbackShader: Failed to compile shader program.");
26930
- return null;
26931
- }
26932
- pool.cache(program);
26933
- return program;
26934
- };
26935
- return TransformFeedbackShader;
26936
- }();
26937
-
26938
- /**
26939
- * Internal shader pool.
26940
- * @internal
26941
- */ var ShaderPool = /*#__PURE__*/ function() {
26942
- function ShaderPool() {}
26943
- ShaderPool.init = function init() {
26944
- ShaderPool.particleFeedbackShader = new TransformFeedbackShader("#include <particle_feedback_simulation>", "void main() { discard; }", [
26945
- "v_FeedbackPosition",
26946
- "v_FeedbackVelocity"
26947
- ]);
26948
- var shadowCasterPass = new ShaderPass("ShadowCaster", shadowMapVs, shadowMapFs, {
26949
- pipelineStage: PipelineStage.ShadowCaster
26950
- });
26951
- shadowCasterPass._renderState = new RenderState();
26952
- shadowCasterPass._renderStateDataMap[RenderStateElementKey.RenderQueueType] = BaseMaterial._shadowCasterRenderQueueProp;
26953
- var depthOnlyPass = new ShaderPass("DepthOnly", depthOnlyVs, depthOnlyFs, {
26954
- pipelineStage: PipelineStage.DepthOnly
26955
- });
26956
- depthOnlyPass._renderState = new RenderState();
26957
- depthOnlyPass._renderStateDataMap[RenderStateElementKey.RenderQueueType] = BaseMaterial._depthOnlyRenderQueueProp;
26958
- var basePasses = [
26959
- shadowCasterPass,
26960
- depthOnlyPass
26961
- ];
26962
- var forwardPassTags = {
26963
- pipelineStage: PipelineStage.Forward
26964
- };
26965
- Shader.create("blinn-phong", [].concat([
26966
- new ShaderPass("Forward", blinnPhongVs, blinnPhongFs, forwardPassTags)
26967
- ], basePasses));
26968
- Shader.create("pbr", [].concat([
26969
- new ShaderPass("Forward", pbrVs, pbrFs, forwardPassTags)
26970
- ], basePasses));
26971
- Shader.create("pbr-specular", [].concat([
26972
- new ShaderPass("Forward", pbrVs, pbrSpecularFs, forwardPassTags)
26973
- ], basePasses));
26974
- Shader.create("unlit", [].concat([
26975
- new ShaderPass("Forward", unlitVs, unlitFs, forwardPassTags)
26976
- ], basePasses));
26977
- Shader.create("blit", [
26978
- new ShaderPass("Forward", blitVs, blitFs, forwardPassTags)
26979
- ]);
26980
- Shader.create("blit-screen", [
26981
- new ShaderPass("Forward", blitVs, blitScreenFs, forwardPassTags)
26982
- ]);
26983
- Shader.create("skybox", [
26984
- new ShaderPass("Forward", skyboxVs, skyboxFs, forwardPassTags)
26985
- ]);
26986
- Shader.create("SkyProcedural", [
26987
- new ShaderPass("Forward", skyProceduralVs, skyProceduralFs, forwardPassTags)
26988
- ]);
26989
- Shader.create("particle-shader", [
26990
- new ShaderPass("Forward", particleVs, particleFs, forwardPassTags)
26991
- ]);
26992
- Shader.create("trail", [
26993
- new ShaderPass("Forward", trailVs, trailFs, forwardPassTags)
26994
- ]);
26995
- Shader.create("SpriteMask", [
26996
- new ShaderPass("Forward", spriteMaskVs, spriteMaskFs, forwardPassTags)
26997
- ]);
26998
- Shader.create("Sprite", [
26999
- new ShaderPass("Forward", spriteVs, spriteFs, forwardPassTags)
27000
- ]);
27001
- Shader.create("Text", [
27002
- new ShaderPass("Forward", textVs, textFs, forwardPassTags)
27003
- ]);
27004
- Shader.create("background-texture", [
27005
- new ShaderPass("Forward", backgroundTextureVs, backgroundTextureFs, forwardPassTags)
27006
- ]);
27007
- };
27008
- return ShaderPool;
27009
- }();
27010
-
27011
26425
  /**
27012
26426
  * Shader program pool.
27013
26427
  * @internal
@@ -27177,7 +26591,6 @@ var OverlayCamera = function OverlayCamera() {
27177
26591
  return XRManager;
27178
26592
  }();
27179
26593
 
27180
- ShaderPool.init();
27181
26594
  /**
27182
26595
  * Engine.
27183
26596
  */ var Engine = /*#__PURE__*/ function(EventDispatcher) {
@@ -27512,9 +26925,17 @@ ShaderPool.init();
27512
26925
  * @internal
27513
26926
  */ _proto._initialize = function _initialize(configuration) {
27514
26927
  var _this = this;
27515
- var shaderLab = configuration.shaderLab, physics = configuration.physics;
27516
- if (shaderLab && !Shader._shaderLab) {
27517
- Shader._shaderLab = shaderLab;
26928
+ var shaderCompiler = configuration.shaderCompiler, physics = configuration.physics;
26929
+ if (shaderCompiler && !Shader._shaderCompiler) {
26930
+ // Bind the runtime include map so the preprocessor sees every chunk
26931
+ // the umbrella package's ShaderPool registered into ShaderFactory.
26932
+ // shader-compiler defaults to an empty map and stays free of any direct
26933
+ // ShaderFactory dependency, so the binding has to be wired here at the
26934
+ // runtime boundary.
26935
+ // @ts-ignore — `_setIncludeMap` is shader-compiler @internal; `includeMap`
26936
+ // is `ShaderFactory` @internal. Both intentionally cross-package wired.
26937
+ shaderCompiler._setIncludeMap(ShaderFactory.includeMap);
26938
+ Shader._shaderCompiler = shaderCompiler;
27518
26939
  }
27519
26940
  var initializePromises = new Array();
27520
26941
  if (physics) {
@@ -28024,18 +27445,36 @@ ShaderPool.init();
28024
27445
  }
28025
27446
  };
28026
27447
  _proto.isStencilWritten = function isStencilWritten(material) {
28027
- var stencilState = material.renderState.stencilState;
28028
- var stencilOperation = StencilOperation.Keep;
28029
- if (stencilState.enabled && stencilState.writeMask !== 0x00 && (stencilState.passOperationFront !== stencilOperation || stencilState.passOperationBack !== stencilOperation || stencilState.failOperationFront !== stencilOperation || stencilState.failOperationBack !== stencilOperation || stencilState.zFailOperationFront !== stencilOperation || stencilState.zFailOperationBack !== stencilOperation)) {
28030
- return true;
28031
- }
27448
+ var data = material.shaderData;
27449
+ if (!data.getFloat(MaskManager._stencilEnabledProp)) return false;
27450
+ var _data_getFloat;
27451
+ if (((_data_getFloat = data.getFloat(MaskManager._stencilWriteMaskProp)) != null ? _data_getFloat : 0xff) === 0) return false;
27452
+ var keep = StencilOperation.Keep;
27453
+ var passFront = data.getFloat(MaskManager._stencilPassOperationFrontProp);
27454
+ if (passFront !== undefined && passFront !== keep) return true;
27455
+ var passBack = data.getFloat(MaskManager._stencilPassOperationBackProp);
27456
+ if (passBack !== undefined && passBack !== keep) return true;
27457
+ var failFront = data.getFloat(MaskManager._stencilFailOperationFrontProp);
27458
+ if (failFront !== undefined && failFront !== keep) return true;
27459
+ var failBack = data.getFloat(MaskManager._stencilFailOperationBackProp);
27460
+ if (failBack !== undefined && failBack !== keep) return true;
27461
+ var zFailFront = data.getFloat(MaskManager._stencilZFailOperationFrontProp);
27462
+ if (zFailFront !== undefined && zFailFront !== keep) return true;
27463
+ var zFailBack = data.getFloat(MaskManager._stencilZFailOperationBackProp);
27464
+ if (zFailBack !== undefined && zFailBack !== keep) return true;
28032
27465
  return false;
28033
27466
  };
28034
27467
  _proto.isReadStencil = function isReadStencil(material) {
28035
- var _material_renderState_stencilState = material.renderState.stencilState, enabled = _material_renderState_stencilState.enabled, mask = _material_renderState_stencilState.mask, compareFunctionFront = _material_renderState_stencilState.compareFunctionFront, compareFunctionBack = _material_renderState_stencilState.compareFunctionBack;
28036
- if (enabled && mask !== 0x00 && (compareFunctionFront !== CompareFunction.Always && compareFunctionFront !== CompareFunction.Never || compareFunctionBack !== CompareFunction.Always && compareFunctionBack !== CompareFunction.Never)) {
28037
- return true;
28038
- }
27468
+ var data = material.shaderData;
27469
+ if (!data.getFloat(MaskManager._stencilEnabledProp)) return false;
27470
+ var _data_getFloat;
27471
+ if (((_data_getFloat = data.getFloat(MaskManager._stencilMaskProp)) != null ? _data_getFloat : 0xff) === 0) return false;
27472
+ var always = CompareFunction.Always;
27473
+ var never = CompareFunction.Never;
27474
+ var cmpFront = data.getFloat(MaskManager._stencilCompareFunctionFrontProp);
27475
+ if (cmpFront !== undefined && cmpFront !== always && cmpFront !== never) return true;
27476
+ var cmpBack = data.getFloat(MaskManager._stencilCompareFunctionBackProp);
27477
+ if (cmpBack !== undefined && cmpBack !== always && cmpBack !== never) return true;
28039
27478
  return false;
28040
27479
  };
28041
27480
  _proto.destroy = function destroy() {
@@ -28075,6 +27514,17 @@ ShaderPool.init();
28075
27514
  };
28076
27515
  return MaskManager;
28077
27516
  }();
27517
+ MaskManager._stencilEnabledProp = ShaderProperty.getByName("stencilEnabled");
27518
+ MaskManager._stencilWriteMaskProp = ShaderProperty.getByName("stencilWriteMask");
27519
+ MaskManager._stencilMaskProp = ShaderProperty.getByName("stencilMask");
27520
+ MaskManager._stencilCompareFunctionFrontProp = ShaderProperty.getByName("stencilCompareFunctionFront");
27521
+ MaskManager._stencilCompareFunctionBackProp = ShaderProperty.getByName("stencilCompareFunctionBack");
27522
+ MaskManager._stencilPassOperationFrontProp = ShaderProperty.getByName("stencilPassOperationFront");
27523
+ MaskManager._stencilPassOperationBackProp = ShaderProperty.getByName("stencilPassOperationBack");
27524
+ MaskManager._stencilFailOperationFrontProp = ShaderProperty.getByName("stencilFailOperationFront");
27525
+ MaskManager._stencilFailOperationBackProp = ShaderProperty.getByName("stencilFailOperationBack");
27526
+ MaskManager._stencilZFailOperationFrontProp = ShaderProperty.getByName("stencilZFailOperationFront");
27527
+ MaskManager._stencilZFailOperationBackProp = ShaderProperty.getByName("stencilZFailOperationBack");
28078
27528
 
28079
27529
  /**
28080
27530
  * Fog Mode.
@@ -33491,9 +32941,7 @@ function _assert_this_initialized(self) {
33491
32941
  _inherits(SkyBoxMaterial, Material);
33492
32942
  function SkyBoxMaterial(engine) {
33493
32943
  var _this;
33494
- _this = Material.call(this, engine, Shader.find("skybox")) || this, _this._tintColor = new Color(1, 1, 1, 1);
33495
- _this.renderState.rasterState.cullMode = CullMode.Off;
33496
- _this.renderState.depthState.compareFunction = CompareFunction.LessEqual;
32944
+ _this = Material.call(this, engine, Shader.find("Sky/Skybox")) || this, _this._tintColor = new Color(1, 1, 1, 1);
33497
32945
  _this.shaderData.setFloat(SkyBoxMaterial._rotationProp, 0);
33498
32946
  _this.shaderData.setFloat(SkyBoxMaterial._exposureProp, 1);
33499
32947
  _this.shaderData.setColor(SkyBoxMaterial._tintColorProp, _this._tintColor);
@@ -33574,7 +33022,7 @@ SkyBoxMaterial._exposureProp = ShaderProperty.getByName("material_Exposure");
33574
33022
  _inherits(SkyProceduralMaterial, Material);
33575
33023
  function SkyProceduralMaterial(engine) {
33576
33024
  var _this;
33577
- _this = Material.call(this, engine, Shader.find("SkyProcedural")) || this;
33025
+ _this = Material.call(this, engine, Shader.find("Sky/SkyProcedural")) || this;
33578
33026
  _this.sunMode = 2;
33579
33027
  _this.sunSize = 0.04;
33580
33028
  _this.sunSizeConvergence = 5;
@@ -33582,8 +33030,6 @@ SkyBoxMaterial._exposureProp = ShaderProperty.getByName("material_Exposure");
33582
33030
  _this.skyTint = new Color(0.21404114048223255, 0.21404114048223255, 0.21404114048223255, 1.0);
33583
33031
  _this.groundTint = new Color(0.11216882039252905, 0.09988709277986121, 0.09520561068319185, 1.0);
33584
33032
  _this.exposure = 1.3;
33585
- _this.renderState.rasterState.cullMode = CullMode.Off;
33586
- _this.renderState.depthState.compareFunction = CompareFunction.LessEqual;
33587
33033
  return _this;
33588
33034
  }
33589
33035
  var _proto = SkyProceduralMaterial.prototype;
@@ -34141,10 +33587,10 @@ __decorate([
34141
33587
  * General-purpose Transform Feedback simulator.
34142
33588
  * Manages per-frame simulation with shared shader program caching.
34143
33589
  */ var TransformFeedbackSimulator = /*#__PURE__*/ function() {
34144
- function TransformFeedbackSimulator(engine, byteStride, shader) {
33590
+ function TransformFeedbackSimulator(engine, byteStride, shaderPass) {
34145
33591
  this._engine = engine;
34146
33592
  this._primitive = new TransformFeedbackPrimitive(engine, byteStride);
34147
- this._shader = shader;
33593
+ this._shaderPass = shaderPass;
34148
33594
  }
34149
33595
  var _proto = TransformFeedbackSimulator.prototype;
34150
33596
  /**
@@ -34160,8 +33606,8 @@ __decorate([
34160
33606
  * @param inputBinding - Input buffer binding
34161
33607
  * @param inputElements - Vertex elements for the input buffer
34162
33608
  */ _proto.beginUpdate = function beginUpdate(shaderData, feedbackElements, inputBinding, inputElements) {
34163
- var program = this._shader.getProgram(this._engine, shaderData._macroCollection);
34164
- if (!program) return false;
33609
+ var program = this._shaderPass._getShaderProgram(this._engine, shaderData._macroCollection);
33610
+ if (!(program == null ? void 0 : program.isValid)) return false;
34165
33611
  program.bind();
34166
33612
  program.uploadUniforms(program.rendererUniformBlock, shaderData);
34167
33613
  program.uploadUniforms(program.otherUniformBlock, shaderData);
@@ -34208,13 +33654,23 @@ __decorate([
34208
33654
  return TransformFeedbackSimulator;
34209
33655
  }();
34210
33656
 
33657
+ var FEEDBACK_SHADER_NAME = "Effect/ParticleFeedback";
34211
33658
  /**
34212
33659
  * @internal
34213
33660
  * Particle-specific Transform Feedback simulation.
34214
33661
  */ var ParticleTransformFeedbackSimulator = /*#__PURE__*/ function() {
34215
33662
  function ParticleTransformFeedbackSimulator(engine) {
34216
33663
  this._particleInitData = new Float32Array(6);
34217
- this._simulator = new TransformFeedbackSimulator(engine, ParticleBufferUtils.feedbackVertexStride, ShaderPool.particleFeedbackShader);
33664
+ // Look up the feedback pass dynamically rather than caching it on a
33665
+ // built-in pool — `engine-core` no longer ships the built-in shader set
33666
+ // itself; the umbrella `@galacean/engine` package registers
33667
+ // `Effect/ParticleFeedback` (and configures its transform-feedback
33668
+ // varyings) at module load time.
33669
+ var feedbackShader = Shader.find(FEEDBACK_SHADER_NAME);
33670
+ if (!feedbackShader) {
33671
+ throw new Error("" + FEEDBACK_SHADER_NAME + ' shader is not registered. Import "@galacean/engine" before constructing the engine, ' + "or register the shader manually if you build a custom engine flavor.");
33672
+ }
33673
+ this._simulator = new TransformFeedbackSimulator(engine, ParticleBufferUtils.feedbackVertexStride, feedbackShader.subShaders[0].passes[0]);
34218
33674
  }
34219
33675
  var _proto = ParticleTransformFeedbackSimulator.prototype;
34220
33676
  /**
@@ -38308,7 +37764,7 @@ __decorate([
38308
37764
  */ var ParticleMaterial = /*#__PURE__*/ function(EffectMaterial) {
38309
37765
  _inherits(ParticleMaterial, EffectMaterial);
38310
37766
  function ParticleMaterial(engine) {
38311
- return EffectMaterial.call(this, engine, Shader.find("particle-shader")) || this;
37767
+ return EffectMaterial.call(this, engine, Shader.find("Effect/Particle")) || this;
38312
37768
  }
38313
37769
  var _proto = ParticleMaterial.prototype;
38314
37770
  /**
@@ -39699,7 +39155,7 @@ __decorate([
39699
39155
  */ var TrailMaterial = /*#__PURE__*/ function(EffectMaterial) {
39700
39156
  _inherits(TrailMaterial, EffectMaterial);
39701
39157
  function TrailMaterial(engine) {
39702
- return EffectMaterial.call(this, engine, Shader.find("trail")) || this;
39158
+ return EffectMaterial.call(this, engine, Shader.find("Effect/Trail")) || this;
39703
39159
  }
39704
39160
  var _proto = TrailMaterial.prototype;
39705
39161
  /**
@@ -40385,7 +39841,5 @@ __decorate([
40385
39841
  return Polyfill;
40386
39842
  }();
40387
39843
 
40388
- Polyfill.registerPolyfill();
40389
-
40390
- export { AmbientLight, AmbientOcclusion, AmbientOcclusionQuality, AnimationArrayCurve, AnimationBoolCurve, AnimationClip, AnimationClipCurveBinding, AnimationColorCurve, AnimationCurve, AnimationEvent, AnimationFloatArrayCurve, AnimationFloatCurve, AnimationQuaternionCurve, AnimationRectCurve, AnimationRefCurve, AnimationStringCurve, AnimationVector2Curve, AnimationVector3Curve, AnimationVector4Curve, Animator, AnimatorCondition, AnimatorConditionMode, AnimatorController, AnimatorControllerLayer, AnimatorControllerParameter, AnimatorCullingMode, AnimatorLayerBlendingMode, AnimatorLayerMask, AnimatorState, AnimatorStateMachine, AnimatorStateTransition, AntiAliasing, AssetPromise, AssetType, AudioClip, AudioManager, AudioSource, Background, BackgroundMode, BackgroundTextureFillMode, BaseMaterial, BasicRenderPipeline, BatchUtils, BlendFactor, BlendMode, BlendOperation, BlendShape, BlendShapeFrame, BlendState, BlinnPhongMaterial, Blitter, BloomDownScaleMode, BloomEffect, BoolUpdateFlag, BoxColliderShape, BoxShape, Buffer, BufferAsset, BufferBindFlag, BufferMesh, BufferUsage, BufferUtil, Burst, Camera, CameraClearFlags, CameraModifyFlags, CameraType, Canvas, CapsuleColliderShape, CharRenderInfo, CharacterController, CircleShape, ClearableObjectPool, CloneManager, CloneUtils, Collider, ColliderShape, ColliderShapeUpAxis, Collision, CollisionDetectionMode, ColorOverLifetimeModule, ColorWriteMask, CompareFunction, Component, ConeEmitType, ConeShape, ContactPoint, ContentRestorer, ControllerCollisionFlag, ControllerNonWalkableMode, CubeProbe, CullMode, CurveKey, DataType, DependentMode, DepthState, DepthTextureMode, DiffuseMode, DirectLight, DisorderedArray, Downsampling, DynamicCollider, DynamicColliderConstraints, EmissionModule, Engine, EngineObject, Entity, EntityModifyFlags, EventDispatcher, FinalPass, FixedJoint, FogMode, Font, FontStyle, GLCapabilityType, GradientAlphaKey, GradientColorKey, HemisphereShape, HingeJoint, HitResult, IndexBufferBinding, IndexFormat, InputManager, InterpolationType, JSONAsset, Joint, JointLimits, JointMotor, Keyframe, Keys, Layer, LayerPathMask, Light, LimitVelocityOverLifetimeModule, Loader, Logger, MSAASamples, MainModule, Material, Mesh, MeshColliderShape, MeshColliderShapeCookingFlag, MeshRenderer, MeshShape, MeshTopology, ModelMesh, NoiseModule, OverflowMode, PBRMaterial, ParticleCompositeCurve, ParticleCompositeGradient, ParticleCurve, ParticleCurveMode, ParticleGenerator, ParticleGradient, ParticleGradientMode, ParticleMaterial, ParticleRenderMode, ParticleRenderer, ParticleScaleMode, ParticleShapeArcMode, ParticleShapeType, ParticleSimulationSpace, ParticleStopMode, PhysicsMaterial, PhysicsMaterialCombineMode, PhysicsScene, PipelineStage, PlaneColliderShape, Platform, PointLight, Pointer, PointerButton, PointerEventData, PointerEventEmitter, PointerPhase, PostProcess, PostProcessEffect, PostProcessEffectBoolParameter, PostProcessEffectColorParameter, PostProcessEffectEnumParameter, PostProcessEffectFloatParameter, PostProcessEffectParameter, PostProcessEffectTextureParameter, PostProcessEffectVector2Parameter, PostProcessEffectVector3Parameter, PostProcessEffectVector4Parameter, PostProcessManager, PostProcessPass, PostProcessPassEvent, PostProcessUberPass, Primitive, PrimitiveMesh, Probe, RasterState, ReferResource, RefractionMode, RenderBufferDepthFormat, RenderFace, RenderQueue, RenderQueueFlags, RenderQueueType, RenderState, RenderStateElementKey, RenderTarget, RenderTargetBlendState, Renderer, RendererUpdateFlags, RenderingStatistics, ReplacementFailureStrategy, ResourceManager, ReturnableObjectPool, RotationOverLifetimeModule, SafeLoopArray, Scene, SceneManager, Script, SetDataOptions, Shader, ShaderData, ShaderDataGroup, ShaderFactory, ShaderLanguage, ShaderLib, ShaderMacro, ShaderMacroCollection, ShaderPass, ShaderProperty, ShaderPropertyType, ShaderTagKey, ShadowCascadesMode, ShadowResolution, ShadowType, Signal, SimpleSpriteAssembler, SizeOverLifetimeModule, Skin, SkinnedMeshRenderer, Sky, SkyBoxMaterial, SkyProceduralMaterial, SlicedSpriteAssembler, SphereColliderShape, SphereShape, SpotLight, SpringJoint, Sprite, SpriteAtlas, SpriteDrawMode, SpriteMask, SpriteMaskInteraction, SpriteMaskLayer, SpriteModifyFlags, SpriteRenderer, SpriteTileMode, StateMachineScript, StaticCollider, StencilOperation, StencilState, SubFont, SubMesh, SubPrimitive, SubShader, SunMode, SystemInfo, TextAsset, TextHorizontalAlignment, TextRenderer, TextUtils, TextVerticalAlignment, Texture, Texture2D, Texture2DArray, TextureCoordinate, TextureCube, TextureCubeFace, TextureDepthCompareFunction, TextureFilterMode, TextureFormat, TextureSheetAnimationModule, TextureUsage, TextureUtils, TextureWrapMode, TiledSpriteAssembler, Time, TonemappingEffect, TonemappingMode, TrailMaterial, TrailRenderer, TrailTextureMode, Transform, TransformModifyFlags, UnlitMaterial, Utils, VelocityOverLifetimeModule, VertexAttribute, VertexBufferBinding, VertexElement, VertexElementFormat, WrapMode, XRManager, assignmentClone, deepClone, dependentComponents, ignoreClone, registerPointerEventEmitter, request, resourceLoader, shallowClone };
39844
+ export { AmbientLight, AmbientOcclusion, AmbientOcclusionQuality, AnimationArrayCurve, AnimationBoolCurve, AnimationClip, AnimationClipCurveBinding, AnimationColorCurve, AnimationCurve, AnimationEvent, AnimationFloatArrayCurve, AnimationFloatCurve, AnimationQuaternionCurve, AnimationRectCurve, AnimationRefCurve, AnimationStringCurve, AnimationVector2Curve, AnimationVector3Curve, AnimationVector4Curve, Animator, AnimatorCondition, AnimatorConditionMode, AnimatorController, AnimatorControllerLayer, AnimatorControllerParameter, AnimatorCullingMode, AnimatorLayerBlendingMode, AnimatorLayerMask, AnimatorState, AnimatorStateMachine, AnimatorStateTransition, AntiAliasing, AssetPromise, AssetType, AudioClip, AudioManager, AudioSource, Background, BackgroundMode, BackgroundTextureFillMode, BaseMaterial, BasicRenderPipeline, BatchUtils, BlendFactor, BlendMode, BlendOperation, BlendShape, BlendShapeFrame, BlinnPhongMaterial, Blitter, BloomDownScaleMode, BloomEffect, BoolUpdateFlag, BoxColliderShape, BoxShape, Buffer, BufferAsset, BufferBindFlag, BufferMesh, BufferUsage, BufferUtil, Burst, Camera, CameraClearFlags, CameraModifyFlags, CameraType, Canvas, CapsuleColliderShape, CharRenderInfo, CharacterController, CircleShape, ClearableObjectPool, CloneManager, CloneUtils, Collider, ColliderShape, ColliderShapeUpAxis, Collision, CollisionDetectionMode, ColorOverLifetimeModule, ColorWriteMask, CompareFunction, Component, ConeEmitType, ConeShape, ContactPoint, ContentRestorer, ControllerCollisionFlag, ControllerNonWalkableMode, CubeProbe, CullMode, CurveKey, DataType, DependentMode, DepthTextureMode, DiffuseMode, DirectLight, DisorderedArray, Downsampling, DynamicCollider, DynamicColliderConstraints, EmissionModule, Engine, EngineObject, Entity, EntityModifyFlags, EventDispatcher, FinalPass, FixedJoint, FogMode, Font, FontStyle, GLCapabilityType, GradientAlphaKey, GradientColorKey, HemisphereShape, HingeJoint, HitResult, IndexBufferBinding, IndexFormat, InputManager, InterpolationType, JSONAsset, Joint, JointLimits, JointMotor, Keyframe, Keys, Layer, LayerPathMask, Light, LimitVelocityOverLifetimeModule, Loader, Logger, MSAASamples, MainModule, Material, Mesh, MeshColliderShape, MeshColliderShapeCookingFlag, MeshRenderer, MeshShape, MeshTopology, ModelMesh, NoiseModule, OverflowMode, PBRMaterial, ParticleCompositeCurve, ParticleCompositeGradient, ParticleCurve, ParticleCurveMode, ParticleGenerator, ParticleGradient, ParticleGradientMode, ParticleMaterial, ParticleRenderMode, ParticleRenderer, ParticleScaleMode, ParticleShapeArcMode, ParticleShapeType, ParticleSimulationSpace, ParticleStopMode, PhysicsMaterial, PhysicsMaterialCombineMode, PhysicsScene, PipelineStage, PlaneColliderShape, Platform, PointLight, Pointer, PointerButton, PointerEventData, PointerEventEmitter, PointerPhase, Polyfill, PostProcess, PostProcessEffect, PostProcessEffectBoolParameter, PostProcessEffectColorParameter, PostProcessEffectEnumParameter, PostProcessEffectFloatParameter, PostProcessEffectParameter, PostProcessEffectTextureParameter, PostProcessEffectVector2Parameter, PostProcessEffectVector3Parameter, PostProcessEffectVector4Parameter, PostProcessManager, PostProcessPass, PostProcessPassEvent, PostProcessUberPass, Primitive, PrimitiveMesh, Probe, ReferResource, RefractionMode, RenderBufferDepthFormat, RenderFace, RenderQueue, RenderQueueFlags, RenderQueueType, RenderStateElementKey, RenderTarget, Renderer, RendererUpdateFlags, RenderingStatistics, ReplacementFailureStrategy, ResourceManager, ReturnableObjectPool, RotationOverLifetimeModule, SafeLoopArray, Scene, SceneManager, Script, SetDataOptions, Shader, ShaderData, ShaderDataGroup, ShaderFactory, ShaderLanguage, ShaderMacro, ShaderMacroCollection, ShaderPass, ShaderProperty, ShaderPropertyType, ShaderTagKey, ShadowCascadesMode, ShadowResolution, ShadowType, Signal, SimpleSpriteAssembler, SizeOverLifetimeModule, Skin, SkinnedMeshRenderer, Sky, SkyBoxMaterial, SkyProceduralMaterial, SlicedSpriteAssembler, SphereColliderShape, SphereShape, SpotLight, SpringJoint, Sprite, SpriteAtlas, SpriteDrawMode, SpriteMask, SpriteMaskInteraction, SpriteMaskLayer, SpriteModifyFlags, SpriteRenderer, SpriteTileMode, StateMachineScript, StaticCollider, StencilOperation, SubFont, SubMesh, SubPrimitive, SubShader, SunMode, SystemInfo, TextAsset, TextHorizontalAlignment, TextRenderer, TextUtils, TextVerticalAlignment, Texture, Texture2D, Texture2DArray, TextureCoordinate, TextureCube, TextureCubeFace, TextureDepthCompareFunction, TextureFilterMode, TextureFormat, TextureSheetAnimationModule, TextureUsage, TextureUtils, TextureWrapMode, TiledSpriteAssembler, Time, TonemappingEffect, TonemappingMode, TrailMaterial, TrailRenderer, TrailTextureMode, Transform, TransformModifyFlags, UnlitMaterial, Utils, VelocityOverLifetimeModule, VertexAttribute, VertexBufferBinding, VertexElement, VertexElementFormat, WrapMode, XRManager, assignmentClone, deepClone, dependentComponents, ignoreClone, registerPointerEventEmitter, request, resourceLoader, shallowClone };
40391
39845
  //# sourceMappingURL=module.js.map