@galacean/engine 2.0.0-alpha.24 → 2.0.0-alpha.26

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/browser.js CHANGED
@@ -6414,6 +6414,12 @@
6414
6414
  case TextureFormat.ETC2_RGB:
6415
6415
  case TextureFormat.ETC2_RGBA8:
6416
6416
  case TextureFormat.ASTC_4x4:
6417
+ case TextureFormat.ASTC_5x5:
6418
+ case TextureFormat.ASTC_6x6:
6419
+ case TextureFormat.ASTC_8x8:
6420
+ case TextureFormat.ASTC_10x10:
6421
+ case TextureFormat.ASTC_12x12:
6422
+ case TextureFormat.ETC2_RGBA5:
6417
6423
  return true;
6418
6424
  default:
6419
6425
  return false;
@@ -6947,7 +6953,7 @@
6947
6953
  _this = ReferResource.call(this, engine) || this, _this._charInfoMap = {}, _this._space = 1, _this._curX = 1, _this._curY = 1, _this._nextY = 1;
6948
6954
  _this.isGCIgnored = true;
6949
6955
  var format = engine._hardwareRenderer.isWebGL2 ? TextureFormat.R8 : TextureFormat.Alpha8;
6950
- var texture = new Texture2D(engine, 512, 512, format, false);
6956
+ var texture = new Texture2D(engine, 512, 512, format, false, false);
6951
6957
  texture.filterMode = TextureFilterMode.Bilinear;
6952
6958
  texture.isGCIgnored = true;
6953
6959
  _this.texture = texture;
@@ -9854,7 +9860,7 @@
9854
9860
  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
9855
9861
  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
9856
9862
  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
9857
- var ibl_frag_define = "// ------------------------Diffuse------------------------\n\n// sh need be pre-scaled in CPU.\nvec3 getLightProbeIrradiance(vec3 sh[9], vec3 normal){\n normal.x = -normal.x;\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 reflectVec.x = -reflectVec.x; // TextureCube is left-hand,so x need inverse\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
9863
+ 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
9858
9864
  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
9859
9865
  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
9860
9866
  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
@@ -9888,7 +9894,8 @@
9888
9894
  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
9889
9895
  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
9890
9896
  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
9891
- 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\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 // Only VOL overlay needs to be added here.\n vec3 totalVelocity;\n if (renderer_SimulationSpace == 0) {\n // Local: integrate in local space\n totalVelocity = localVelocity + volLocal\n + rotationByQuaternions(volWorld, invWorldRotation);\n } else {\n // World: integrate in world space\n totalVelocity = rotationByQuaternions(localVelocity + volLocal, worldRotation) + volWorld;\n }\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
9897
+ var noise_module = "#ifdef RENDERER_NOISE_MODULE_ENABLED\n\n#include <noise_common>\n#include <noise_simplex_3D>\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 sampleSimplexNoise3D(vec3 coord) {\n float axisOffset = 100.0;\n return vec3(\n simplex(vec3(coord.z, coord.y, coord.x)),\n simplex(vec3(coord.x + axisOffset, coord.z, coord.y)),\n simplex(vec3(coord.y, coord.x + axisOffset, coord.z))\n );\n}\n\nvec3 computeNoiseDisplacement(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 = sampleSimplexNoise3D(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 * sampleSimplexNoise3D(coord * octaveFrequencyMultiplier);\n\n if (octaveCount >= 3) {\n amplitude *= octaveIntensityMultiplier;\n totalAmplitude += amplitude;\n noiseValue += amplitude * sampleSimplexNoise3D(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
9898
+ 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 // Noise velocity overlay (not persisted)\n // computeNoiseDisplacement returns noise * strength (position-scale)\n // Dividing by lifetime converts to velocity so that integration over lifetime\n // recovers the original displacement magnitude\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 += computeNoiseDisplacement(noiseBasePos, normalizedAge) / lifetime;\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
9892
9899
  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
9893
9900
  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
9894
9901
  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
@@ -9903,6 +9910,7 @@
9903
9910
  texture_sheet_animation_module: texture_sheet_animation_module,
9904
9911
  force_over_lifetime_module: force_over_lifetime_module,
9905
9912
  limit_velocity_over_lifetime_module: limit_velocity_over_lifetime_module,
9913
+ noise_module: noise_module,
9906
9914
  particle_feedback_simulation: particle_feedback_simulation,
9907
9915
  sphere_billboard: sphere_billboard,
9908
9916
  stretched_billboard: stretched_billboard,
@@ -10742,26 +10750,483 @@
10742
10750
  return ShaderProgram;
10743
10751
  }();
10744
10752
  ShaderProgram._counter = 0;
10753
+ function _array_like_to_array$2(arr, len) {
10754
+ if (len == null || len > arr.length) len = arr.length;
10755
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
10756
+ return arr2;
10757
+ }
10758
+ function _unsupported_iterable_to_array$2(o, minLen) {
10759
+ if (!o) return;
10760
+ if (typeof o === "string") return _array_like_to_array$2(o, minLen);
10761
+ var n = Object.prototype.toString.call(o).slice(8, -1);
10762
+ if (n === "Object" && o.constructor) n = o.constructor.name;
10763
+ if (n === "Map" || n === "Set") return Array.from(n);
10764
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$2(o, minLen);
10765
+ }
10766
+ function _create_for_of_iterator_helper_loose$2(o, allowArrayLike) {
10767
+ var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
10768
+ if (it) return (it = it.call(o)).next.bind(it);
10769
+ // Fallback for engines without symbol support
10770
+ if (Array.isArray(o) || (it = _unsupported_iterable_to_array$2(o)) || allowArrayLike && o && typeof o.length === "number") {
10771
+ if (it) o = it;
10772
+ var i = 0;
10773
+ return function() {
10774
+ if (i >= o.length) return {
10775
+ done: true
10776
+ };
10777
+ return {
10778
+ done: false,
10779
+ value: o[i++]
10780
+ };
10781
+ };
10782
+ }
10783
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
10784
+ }
10785
+ /**
10786
+ * Directive types for shader preprocessor instructions.
10787
+ */ var ShaderPreprocessorDirective = /*#__PURE__*/ function(ShaderPreprocessorDirective) {
10788
+ ShaderPreprocessorDirective[ShaderPreprocessorDirective["Text"] = 0] = "Text";
10789
+ ShaderPreprocessorDirective[ShaderPreprocessorDirective["IfDef"] = 1] = "IfDef";
10790
+ ShaderPreprocessorDirective[ShaderPreprocessorDirective["IfNdef"] = 2] = "IfNdef";
10791
+ ShaderPreprocessorDirective[ShaderPreprocessorDirective["IfCmp"] = 3] = "IfCmp";
10792
+ ShaderPreprocessorDirective[ShaderPreprocessorDirective["IfExpr"] = 4] = "IfExpr";
10793
+ ShaderPreprocessorDirective[ShaderPreprocessorDirective["Else"] = 5] = "Else";
10794
+ ShaderPreprocessorDirective[ShaderPreprocessorDirective["Endif"] = 6] = "Endif";
10795
+ ShaderPreprocessorDirective[ShaderPreprocessorDirective["Define"] = 7] = "Define";
10796
+ ShaderPreprocessorDirective[ShaderPreprocessorDirective["DefineVal"] = 8] = "DefineVal";
10797
+ ShaderPreprocessorDirective[ShaderPreprocessorDirective["DefineFunc"] = 9] = "DefineFunc";
10798
+ ShaderPreprocessorDirective[ShaderPreprocessorDirective["Undef"] = 10] = "Undef";
10799
+ return ShaderPreprocessorDirective;
10800
+ }({});
10801
+ /**
10802
+ * @internal
10803
+ */ var ShaderMacroProcessor = /*#__PURE__*/ function() {
10804
+ function ShaderMacroProcessor() {}
10805
+ /**
10806
+ * Evaluate a flat instruction array with active macros.
10807
+ * Macros are expanded immediately when text chunks are collected,
10808
+ * using the current macro state at that point (conforming to GLSL/C99 §6.10 standard).
10809
+ * @param instructions - Pre-parsed instruction array
10810
+ * @param macros - Active runtime macros
10811
+ * @returns Pure GLSL string with all conditionals resolved and macros expanded
10812
+ */ ShaderMacroProcessor.evaluate = function evaluate(instructions, macros) {
10813
+ var valueMacros = ShaderMacroProcessor._valueMacros;
10814
+ var funcMacros = ShaderMacroProcessor._funcMacros;
10815
+ var shaderChunks = ShaderMacroProcessor._shaderChunks;
10816
+ valueMacros.clear();
10817
+ funcMacros.clear();
10818
+ shaderChunks.length = 0;
10819
+ for(var _iterator = _create_for_of_iterator_helper_loose$2(macros), _step; !(_step = _iterator()).done;){
10820
+ var _step_value = _step.value, name = _step_value[0], value = _step_value[1];
10821
+ valueMacros.set(name, value);
10822
+ }
10823
+ ShaderMacroProcessor._macroFirstCharsDirty = true;
10824
+ var index = 0;
10825
+ var length = instructions.length;
10826
+ while(index < length){
10827
+ var instruction = instructions[index];
10828
+ switch(instruction[0]){
10829
+ case ShaderPreprocessorDirective.Text:
10830
+ // Immediately expand macros using current macro state (GLSL/C99 conformant)
10831
+ shaderChunks.push(ShaderMacroProcessor._expandChunk(instruction[1], valueMacros, funcMacros));
10832
+ index++;
10833
+ break;
10834
+ case ShaderPreprocessorDirective.IfDef:
10835
+ {
10836
+ var name1 = instruction[1];
10837
+ index = valueMacros.has(name1) || funcMacros.has(name1) ? index + 1 : instruction[2];
10838
+ break;
10839
+ }
10840
+ case ShaderPreprocessorDirective.IfNdef:
10841
+ {
10842
+ var name2 = instruction[1];
10843
+ index = !valueMacros.has(name2) && !funcMacros.has(name2) ? index + 1 : instruction[2];
10844
+ break;
10845
+ }
10846
+ case ShaderPreprocessorDirective.IfCmp:
10847
+ {
10848
+ var name3 = instruction[1];
10849
+ var val = valueMacros.get(name3);
10850
+ var matched = val !== undefined && ShaderMacroProcessor._compareValues(Number(val) || 0, instruction[2], instruction[3]);
10851
+ index = matched ? index + 1 : instruction[4];
10852
+ break;
10853
+ }
10854
+ case ShaderPreprocessorDirective.IfExpr:
10855
+ index = ShaderMacroProcessor._evalCondition(instruction[1], valueMacros, funcMacros) ? index + 1 : instruction[2];
10856
+ break;
10857
+ case ShaderPreprocessorDirective.Else:
10858
+ index = instruction[1];
10859
+ break;
10860
+ case ShaderPreprocessorDirective.Endif:
10861
+ index++;
10862
+ break;
10863
+ case ShaderPreprocessorDirective.Define:
10864
+ valueMacros.set(instruction[1], "");
10865
+ index++;
10866
+ break;
10867
+ case ShaderPreprocessorDirective.DefineVal:
10868
+ valueMacros.set(instruction[1], instruction[2]);
10869
+ ShaderMacroProcessor._macroFirstCharsDirty = true;
10870
+ index++;
10871
+ break;
10872
+ case ShaderPreprocessorDirective.DefineFunc:
10873
+ funcMacros.set(instruction[1], {
10874
+ params: instruction[2],
10875
+ body: instruction[3]
10876
+ });
10877
+ ShaderMacroProcessor._macroFirstCharsDirty = true;
10878
+ index++;
10879
+ break;
10880
+ case ShaderPreprocessorDirective.Undef:
10881
+ valueMacros.delete(instruction[1]);
10882
+ funcMacros.delete(instruction[1]);
10883
+ index++;
10884
+ break;
10885
+ default:
10886
+ index++;
10887
+ break;
10888
+ }
10889
+ }
10890
+ return ShaderMacroProcessor._concatChunks(shaderChunks);
10891
+ };
10892
+ /**
10893
+ * Expand macros in a single text chunk using the current macro state.
10894
+ * Returns the chunk as-is if no expandable macros exist.
10895
+ */ ShaderMacroProcessor._expandChunk = function _expandChunk(chunk, valueMacros, funcMacros) {
10896
+ // Fast path: no expandable macros at this point
10897
+ if (funcMacros.size === 0) {
10898
+ var hasExpandable = false;
10899
+ for(var _iterator = _create_for_of_iterator_helper_loose$2(valueMacros), _step; !(_step = _iterator()).done;){
10900
+ var _step_value = _step.value, val = _step_value[1];
10901
+ if (val !== "") {
10902
+ hasExpandable = true;
10903
+ break;
10904
+ }
10905
+ }
10906
+ if (!hasExpandable) return chunk;
10907
+ }
10908
+ // Rebuild first-char filter if macros changed
10909
+ if (ShaderMacroProcessor._macroFirstCharsDirty) {
10910
+ var macroFirstChars = ShaderMacroProcessor._macroFirstChars;
10911
+ macroFirstChars.clear();
10912
+ for(var _iterator1 = _create_for_of_iterator_helper_loose$2(valueMacros.keys()), _step1; !(_step1 = _iterator1()).done;){
10913
+ var name = _step1.value;
10914
+ macroFirstChars.add(name.charCodeAt(0));
10915
+ }
10916
+ for(var _iterator2 = _create_for_of_iterator_helper_loose$2(funcMacros.keys()), _step2; !(_step2 = _iterator2()).done;){
10917
+ var name1 = _step2.value;
10918
+ macroFirstChars.add(name1.charCodeAt(0));
10919
+ }
10920
+ ShaderMacroProcessor._macroFirstCharsDirty = false;
10921
+ }
10922
+ var macroFirstChars1 = ShaderMacroProcessor._macroFirstChars;
10923
+ var expandedNames = ShaderMacroProcessor._expandedNames;
10924
+ var out = ShaderMacroProcessor._out;
10925
+ out.length = 0;
10926
+ var len = chunk.length;
10927
+ var i = 0;
10928
+ while(i < len){
10929
+ var cc = chunk.charCodeAt(i);
10930
+ if (ShaderMacroProcessor._isIdentifierStart(cc)) {
10931
+ var start = i;
10932
+ i++;
10933
+ while(i < len && ShaderMacroProcessor._isIdentifierPart(chunk.charCodeAt(i)))i++;
10934
+ // Fast path: first char not in any macro name
10935
+ if (!macroFirstChars1.has(chunk.charCodeAt(start))) {
10936
+ out.push(chunk.substring(start, i));
10937
+ continue;
10938
+ }
10939
+ var name2 = chunk.substring(start, i);
10940
+ // Try function macro
10941
+ var func = funcMacros.get(name2);
10942
+ if (func) {
10943
+ var lookAhead = i;
10944
+ while(lookAhead < len && (chunk.charCodeAt(lookAhead) === 32 /* space */ || chunk.charCodeAt(lookAhead) === 9))lookAhead++;
10945
+ if (lookAhead < len && chunk.charCodeAt(lookAhead) === 40 /* '(' */ ) {
10946
+ var args = ShaderMacroProcessor._parseFuncArgs(chunk, lookAhead);
10947
+ if (args) {
10948
+ i = args.end;
10949
+ var expanded = ShaderMacroProcessor._expandFuncBody(func, args.values);
10950
+ expandedNames.clear();
10951
+ expandedNames.add(name2);
10952
+ out.push(ShaderMacroProcessor._recursiveExpandMacro(expanded, valueMacros, funcMacros, expandedNames));
10953
+ continue;
10954
+ }
10955
+ }
10956
+ }
10957
+ // Try value macro
10958
+ var val1 = valueMacros.get(name2);
10959
+ if (val1 !== undefined && val1 !== "") {
10960
+ expandedNames.clear();
10961
+ expandedNames.add(name2);
10962
+ out.push(ShaderMacroProcessor._recursiveExpandMacro(val1, valueMacros, funcMacros, expandedNames));
10963
+ continue;
10964
+ }
10965
+ out.push(name2);
10966
+ continue;
10967
+ }
10968
+ // Batch collect non-identifier characters
10969
+ var batchStart = i;
10970
+ while(i < len && !ShaderMacroProcessor._isIdentifierStart(chunk.charCodeAt(i)))i++;
10971
+ out.push(chunk.substring(batchStart, i));
10972
+ }
10973
+ return out.join("");
10974
+ };
10975
+ /**
10976
+ * Recursively expand macro substitution results until no more macros remain.
10977
+ * @param macroExpansion - Intermediate text from a macro substitution that may contain further macro references
10978
+ * @param valueMacros - Current value macro definitions
10979
+ * @param funcMacros - Current function macro definitions
10980
+ * @param expandedNames - Macro names already on the expansion chain, prevents circular references (C99 §6.10.3.4)
10981
+ */ ShaderMacroProcessor._recursiveExpandMacro = function _recursiveExpandMacro(macroExpansion, valueMacros, funcMacros, expandedNames) {
10982
+ if (macroExpansion.length === 0) return macroExpansion;
10983
+ var len = macroExpansion.length;
10984
+ var out = [];
10985
+ var i = 0;
10986
+ while(i < len){
10987
+ var cc = macroExpansion.charCodeAt(i);
10988
+ if (ShaderMacroProcessor._isIdentifierStart(cc)) {
10989
+ var start = i;
10990
+ i++;
10991
+ while(i < len && ShaderMacroProcessor._isIdentifierPart(macroExpansion.charCodeAt(i)))i++;
10992
+ var name = macroExpansion.substring(start, i);
10993
+ // Skip already-expanded names (circular reference prevention)
10994
+ // Skip GL_ prefixed names (reserved GLSL built-ins, charCodes: G=71, L=76, _=95)
10995
+ if (expandedNames.has(name) || name.charCodeAt(0) === 71 && name.charCodeAt(1) === 76 && name.charCodeAt(2) === 95) {
10996
+ out.push(name);
10997
+ continue;
10998
+ }
10999
+ var func = funcMacros.get(name);
11000
+ if (func) {
11001
+ var lookAhead = i;
11002
+ while(lookAhead < len && (macroExpansion.charCodeAt(lookAhead) === 32 /* space */ || macroExpansion.charCodeAt(lookAhead) === 9))lookAhead++;
11003
+ if (lookAhead < len && macroExpansion.charCodeAt(lookAhead) === 40 /* '(' */ ) {
11004
+ var args = ShaderMacroProcessor._parseFuncArgs(macroExpansion, lookAhead);
11005
+ if (args) {
11006
+ i = args.end;
11007
+ expandedNames.add(name);
11008
+ out.push(ShaderMacroProcessor._recursiveExpandMacro(ShaderMacroProcessor._expandFuncBody(func, args.values), valueMacros, funcMacros, expandedNames));
11009
+ expandedNames.delete(name);
11010
+ continue;
11011
+ }
11012
+ }
11013
+ }
11014
+ var val = valueMacros.get(name);
11015
+ if (val !== undefined && val !== "") {
11016
+ expandedNames.add(name);
11017
+ out.push(ShaderMacroProcessor._recursiveExpandMacro(val, valueMacros, funcMacros, expandedNames));
11018
+ expandedNames.delete(name);
11019
+ continue;
11020
+ }
11021
+ out.push(name);
11022
+ continue;
11023
+ }
11024
+ // Batch collect non-identifier characters
11025
+ var batchStart = i;
11026
+ while(i < len && !ShaderMacroProcessor._isIdentifierStart(macroExpansion.charCodeAt(i)))i++;
11027
+ out.push(macroExpansion.substring(batchStart, i));
11028
+ }
11029
+ return out.join("");
11030
+ };
11031
+ /**
11032
+ * Substitute function macro params in body.
11033
+ */ ShaderMacroProcessor._expandFuncBody = function _expandFuncBody(func, args) {
11034
+ if (func.params.length === 0 || args.length !== func.params.length) return func.body;
11035
+ var result = func.body;
11036
+ for(var i = 0; i < func.params.length; i++){
11037
+ result = ShaderMacroProcessor._replaceWord(result, func.params[i], args[i]);
11038
+ }
11039
+ return result;
11040
+ };
11041
+ /**
11042
+ * Evaluate a compound condition tree.
11043
+ */ ShaderMacroProcessor._evalCondition = function _evalCondition(cond, valueMacros, funcMacros) {
11044
+ switch(cond.t){
11045
+ case "def":
11046
+ return valueMacros.has(cond.m) || funcMacros.has(cond.m);
11047
+ case "ndef":
11048
+ return !valueMacros.has(cond.m) && !funcMacros.has(cond.m);
11049
+ case "cmp":
11050
+ {
11051
+ var val = valueMacros.get(cond.m);
11052
+ if (val === undefined) return false;
11053
+ return ShaderMacroProcessor._compareValues(Number(val) || 0, cond.op, cond.v);
11054
+ }
11055
+ case "and":
11056
+ return ShaderMacroProcessor._evalCondition(cond.l, valueMacros, funcMacros) && ShaderMacroProcessor._evalCondition(cond.r, valueMacros, funcMacros);
11057
+ case "or":
11058
+ return ShaderMacroProcessor._evalCondition(cond.l, valueMacros, funcMacros) || ShaderMacroProcessor._evalCondition(cond.r, valueMacros, funcMacros);
11059
+ case "not":
11060
+ return !ShaderMacroProcessor._evalCondition(cond.c, valueMacros, funcMacros);
11061
+ case "bool":
11062
+ return cond.v;
11063
+ }
11064
+ };
11065
+ /**
11066
+ * Evaluate a comparison operator.
11067
+ */ ShaderMacroProcessor._compareValues = function _compareValues(numVal, op, value) {
11068
+ switch(op){
11069
+ case "==":
11070
+ return numVal === value;
11071
+ case "!=":
11072
+ return numVal !== value;
11073
+ case ">":
11074
+ return numVal > value;
11075
+ case "<":
11076
+ return numVal < value;
11077
+ case ">=":
11078
+ return numVal >= value;
11079
+ case "<=":
11080
+ return numVal <= value;
11081
+ default:
11082
+ return false;
11083
+ }
11084
+ };
11085
+ /**
11086
+ * Parse function macro call arguments.
11087
+ * Returns reusable static result object to avoid allocation.
11088
+ */ ShaderMacroProcessor._parseFuncArgs = function _parseFuncArgs(text, openParen) {
11089
+ var result = ShaderMacroProcessor._parsedFuncArgs;
11090
+ result.values.length = 0;
11091
+ var level = 1;
11092
+ var argStart = openParen + 1;
11093
+ var k = argStart;
11094
+ var len = text.length;
11095
+ while(k < len && level > 0){
11096
+ var cc = text.charCodeAt(k);
11097
+ if (cc === 40 /* '(' */ ) {
11098
+ level++;
11099
+ } else if (cc === 41 /* ')' */ ) {
11100
+ if (--level === 0) {
11101
+ var arg = text.substring(argStart, k).trim();
11102
+ if (arg.length > 0 || result.values.length > 0) result.values.push(arg);
11103
+ result.end = k + 1;
11104
+ return result;
11105
+ }
11106
+ } else if (cc === 44 /* ',' */ && level === 1) {
11107
+ result.values.push(text.substring(argStart, k).trim());
11108
+ argStart = k + 1;
11109
+ }
11110
+ k++;
11111
+ }
11112
+ return null;
11113
+ };
11114
+ /**
11115
+ * Replace all whole-word occurrences of `word` in `text` with `replacement`.
11116
+ */ ShaderMacroProcessor._replaceWord = function _replaceWord(text, word, replacement) {
11117
+ var wLen = word.length;
11118
+ var parts = ShaderMacroProcessor._replaceWordParts;
11119
+ parts.length = 0;
11120
+ var start = 0;
11121
+ var idx = text.indexOf(word, start);
11122
+ while(idx !== -1){
11123
+ if (idx > 0 && ShaderMacroProcessor._isIdentifierPart(text.charCodeAt(idx - 1))) {
11124
+ idx = text.indexOf(word, idx + 1);
11125
+ continue;
11126
+ }
11127
+ var afterIdx = idx + wLen;
11128
+ if (afterIdx < text.length && ShaderMacroProcessor._isIdentifierPart(text.charCodeAt(afterIdx))) {
11129
+ idx = text.indexOf(word, idx + 1);
11130
+ continue;
11131
+ }
11132
+ parts.push(text.substring(start, idx));
11133
+ parts.push(replacement);
11134
+ start = afterIdx;
11135
+ idx = text.indexOf(word, start);
11136
+ }
11137
+ if (start === 0) return text;
11138
+ parts.push(text.substring(start));
11139
+ return parts.join("");
11140
+ };
11141
+ /**
11142
+ * Concatenate shader chunks with consecutive blank lines collapsed to a single newline.
11143
+ */ ShaderMacroProcessor._concatChunks = function _concatChunks(shaderChunks) {
11144
+ var out = ShaderMacroProcessor._out;
11145
+ out.length = 0;
11146
+ var lastNewline = false;
11147
+ for(var p = 0; p < shaderChunks.length; p++){
11148
+ var text = shaderChunks[p];
11149
+ var len = text.length;
11150
+ var i = 0;
11151
+ while(i < len){
11152
+ if (text.charCodeAt(i) === 10 /* \n */ ) {
11153
+ if (!lastNewline) {
11154
+ out.push("\n");
11155
+ lastNewline = true;
11156
+ }
11157
+ i++;
11158
+ while(i < len){
11159
+ var c = text.charCodeAt(i);
11160
+ if (c === 32 /* space */ || c === 9 /* tab */ || c === 10 /* \n */ ) i++;
11161
+ else break;
11162
+ }
11163
+ } else {
11164
+ var batchStart = i;
11165
+ while(i < len && text.charCodeAt(i) !== 10 /* \n */ )i++;
11166
+ out.push(text.substring(batchStart, i));
11167
+ lastNewline = false;
11168
+ }
11169
+ }
11170
+ }
11171
+ return out.join("");
11172
+ };
11173
+ /**
11174
+ * Check if char code is a valid identifier start.
11175
+ * Matches: [A-Z] | [a-z] | _
11176
+ */ ShaderMacroProcessor._isIdentifierStart = function _isIdentifierStart(charCode) {
11177
+ return charCode >= 65 && charCode <= 90 || charCode >= 97 && charCode <= 122 || charCode === 95;
11178
+ };
11179
+ /**
11180
+ * Check if char code is a valid identifier part.
11181
+ * Matches: [A-Z] | [a-z] | [0-9] | _
11182
+ */ ShaderMacroProcessor._isIdentifierPart = function _isIdentifierPart(charCode) {
11183
+ return charCode >= 65 && charCode <= 90 || charCode >= 97 && charCode <= 122 || charCode >= 48 && charCode <= 57 || charCode === 95;
11184
+ };
11185
+ return ShaderMacroProcessor;
11186
+ }();
11187
+ ShaderMacroProcessor._valueMacros = new Map();
11188
+ ShaderMacroProcessor._funcMacros = new Map();
11189
+ ShaderMacroProcessor._shaderChunks = [];
11190
+ ShaderMacroProcessor._out = [];
11191
+ ShaderMacroProcessor._expandedNames = new Set();
11192
+ ShaderMacroProcessor._macroFirstChars = new Set();
11193
+ ShaderMacroProcessor._macroFirstCharsDirty = true;
11194
+ ShaderMacroProcessor._replaceWordParts = [];
11195
+ ShaderMacroProcessor._parsedFuncArgs = {
11196
+ values: [],
11197
+ end: 0
11198
+ };
10745
11199
  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 ";
10746
11200
  /**
10747
11201
  * Shader pass containing vertex and fragment source.
10748
11202
  */ var ShaderPass = /*#__PURE__*/ function(ShaderPart) {
10749
11203
  _inherits$2(ShaderPass, ShaderPart);
10750
- function ShaderPass(nameOrVertexSource, vertexSourceOrFragmentSource, fragmentSourceOrTags, tags) {
11204
+ function ShaderPass(nameOrVertexSource, vertexSourceOrFragmentSourceOrInstructions, fragmentSourceOrTags, tagsOrPlatformTarget, tags) {
10751
11205
  var _this;
10752
11206
  _this = ShaderPart.call(this) || this, /** @internal */ _this._shaderPassId = 0, /** @internal */ _this._renderStateDataMap = {}, /** @internal */ _this._shaderProgramPools = [];
10753
11207
  _this._shaderPassId = ShaderPass._shaderPassCounter++;
10754
- if (typeof fragmentSourceOrTags === "string") {
11208
+ if (Array.isArray(vertexSourceOrFragmentSourceOrInstructions)) {
11209
+ // Instructions overload: (name, vertexInst, fragInst, platformTarget, tags?)
10755
11210
  _this._name = nameOrVertexSource;
10756
- _this._vertexSource = vertexSourceOrFragmentSource;
10757
- _this._fragmentSource = fragmentSourceOrTags;
11211
+ _this._vertexShaderInstructions = vertexSourceOrFragmentSourceOrInstructions;
11212
+ _this._fragmentShaderInstructions = fragmentSourceOrTags;
11213
+ _this._platformTarget = tagsOrPlatformTarget;
10758
11214
  tags = _extends$2({
10759
11215
  pipelineStage: PipelineStage.Forward
10760
11216
  }, tags);
11217
+ } else if (typeof fragmentSourceOrTags === "string") {
11218
+ // Named overload: (name, vertexSource, fragmentSource, tags?)
11219
+ _this._name = nameOrVertexSource;
11220
+ _this._vertexSource = vertexSourceOrFragmentSourceOrInstructions;
11221
+ _this._fragmentSource = fragmentSourceOrTags;
11222
+ tags = _extends$2({
11223
+ pipelineStage: PipelineStage.Forward
11224
+ }, tagsOrPlatformTarget);
10761
11225
  } else {
11226
+ // Unnamed overload: (vertexSource, fragmentSource, tags?)
10762
11227
  _this._name = "Default";
10763
11228
  _this._vertexSource = nameOrVertexSource;
10764
- _this._fragmentSource = vertexSourceOrFragmentSource;
11229
+ _this._fragmentSource = vertexSourceOrFragmentSourceOrInstructions;
10765
11230
  tags = _extends$2({
10766
11231
  pipelineStage: PipelineStage.Forward
10767
11232
  }, fragmentSourceOrTags);
@@ -10797,15 +11262,16 @@
10797
11262
  shaderProgramPools.length = 0;
10798
11263
  };
10799
11264
  _proto._getCanonicalShaderProgram = function _getCanonicalShaderProgram(engine, macroCollection) {
10800
- if (this._platformTarget != undefined) {
10801
- return this._getShaderLabProgram(engine, macroCollection);
10802
- }
10803
- var _ShaderFactory_compilePlatformSource = ShaderFactory.compilePlatformSource(engine, macroCollection, this._vertexSource, this._fragmentSource), vertexSource = _ShaderFactory_compilePlatformSource.vertexSource, fragmentSource = _ShaderFactory_compilePlatformSource.fragmentSource;
11265
+ var _ref = this._platformTarget != undefined ? this._compileShaderLabSource(engine, macroCollection) : this._compilePlatformSource(engine, macroCollection), vertexSource = _ref.vertexSource, fragmentSource = _ref.fragmentSource;
10804
11266
  return new ShaderProgram(engine, vertexSource, fragmentSource);
10805
11267
  };
10806
- _proto._getShaderLabProgram = function _getShaderLabProgram(engine, macroCollection) {
11268
+ _proto._compilePlatformSource = function _compilePlatformSource(engine, macroCollection) {
11269
+ return ShaderFactory.compilePlatformSource(engine, macroCollection, this._vertexSource, this._fragmentSource);
11270
+ };
11271
+ _proto._compileShaderLabSource = function _compileShaderLabSource(engine, macroCollection) {
10807
11272
  var isWebGL2 = engine._hardwareRenderer.isWebGL2;
10808
- var shaderMacroList = new Array();
11273
+ var shaderMacroList = ShaderPass._shaderMacroList;
11274
+ shaderMacroList.length = 0;
10809
11275
  ShaderMacro._getMacrosElements(macroCollection, shaderMacroList);
10810
11276
  shaderMacroList.push(ShaderMacro.getByName(isWebGL2 ? "GRAPHICS_API_WEBGL2" : "GRAPHICS_API_WEBGL1"));
10811
11277
  if (engine._hardwareRenderer.canIUse(GLCapabilityType.shaderTextureLod)) {
@@ -10814,23 +11280,31 @@
10814
11280
  if (engine._hardwareRenderer.canIUse(GLCapabilityType.standardDerivatives)) {
10815
11281
  shaderMacroList.push(ShaderMacro.getByName("HAS_DERIVATIVES"));
10816
11282
  }
10817
- var noIncludeVertex = ShaderFactory.parseIncludes(this._vertexSource);
10818
- var noIncludeFrag = ShaderFactory.parseIncludes(this._fragmentSource);
10819
- noIncludeVertex = Shader._shaderLab._parseMacros(noIncludeVertex, shaderMacroList);
10820
- noIncludeFrag = Shader._shaderLab._parseMacros(noIncludeFrag, shaderMacroList);
11283
+ var macroMap = ShaderPass._macroMap;
11284
+ macroMap.clear();
11285
+ for(var i = 0, n = shaderMacroList.length; i < n; i++){
11286
+ var macro = shaderMacroList[i];
11287
+ var _macro_value;
11288
+ macroMap.set(macro.name, (_macro_value = macro.value) != null ? _macro_value : "");
11289
+ }
11290
+ var vertexSource = ShaderMacroProcessor.evaluate(this._vertexShaderInstructions, macroMap);
11291
+ var fragmentSource = ShaderMacroProcessor.evaluate(this._fragmentShaderInstructions, macroMap);
10821
11292
  if (isWebGL2 && this._platformTarget === ShaderLanguage.GLSLES100) {
10822
- noIncludeVertex = ShaderFactory.convertTo300(noIncludeVertex);
10823
- noIncludeFrag = ShaderFactory.convertTo300(noIncludeFrag, true);
11293
+ vertexSource = ShaderFactory.convertTo300(vertexSource);
11294
+ fragmentSource = ShaderFactory.convertTo300(fragmentSource, true);
10824
11295
  }
10825
11296
  var versionStr = isWebGL2 ? "#version 300 es" : "#version 100";
10826
- var vertexSource = " " + versionStr + "\n " + noIncludeVertex + "\n ";
10827
- var fragmentSource = " " + versionStr + "\n " + (isWebGL2 ? "" : ShaderFactory._shaderExtension) + "\n " + precisionStr + "\n " + noIncludeFrag + "\n ";
10828
- return new ShaderProgram(engine, vertexSource, fragmentSource);
11297
+ return {
11298
+ vertexSource: " " + versionStr + "\n " + vertexSource + "\n ",
11299
+ fragmentSource: " " + versionStr + "\n " + (isWebGL2 ? "" : ShaderFactory._shaderExtension) + "\n " + precisionStr + "\n " + fragmentSource + "\n "
11300
+ };
10829
11301
  };
10830
11302
  return ShaderPass;
10831
11303
  }(ShaderPart);
10832
11304
  /** @internal */ ShaderPass._shaderPassCounter = 0;
10833
11305
  /** @internal */ ShaderPass._shaderRootPath = "shaders://root/";
11306
+ ShaderPass._shaderMacroList = [];
11307
+ ShaderPass._macroMap = new Map();
10834
11308
  /**
10835
11309
  * Sub shader.
10836
11310
  */ var SubShader = /*#__PURE__*/ function(ShaderPart) {
@@ -11571,36 +12045,14 @@
11571
12045
  var subShaderList = shaderSource.subShaders.map(function(subShaderSource) {
11572
12046
  var passList = subShaderSource.passes.map(function(passSource) {
11573
12047
  if (passSource.isUsePass) {
11574
- var _Shader_find_subShaders_find, _Shader_find;
11575
- var _passSource_name_split = passSource.name.split("/"), shaderName = _passSource_name_split[0], subShaderName = _passSource_name_split[1], passName = _passSource_name_split[2];
11576
- return (_Shader_find = Shader.find(shaderName)) == null ? void 0 : (_Shader_find_subShaders_find = _Shader_find.subShaders.find(function(subShader) {
11577
- return subShader.name === subShaderName;
11578
- })) == null ? void 0 : _Shader_find_subShaders_find.passes.find(function(pass) {
11579
- return pass.name === passName;
11580
- });
12048
+ return Shader._resolveUsePass(passSource.name);
11581
12049
  }
11582
12050
  var shaderPassSource = Shader._shaderLab._parseShaderPass(passSource.contents, passSource.vertexEntry, passSource.fragmentEntry, vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget, new URL(fragmentSourceOrPath != null ? fragmentSourceOrPath : "", ShaderPass._shaderRootPath).href);
11583
12051
  if (!shaderPassSource) {
11584
12052
  throw 'Shader pass "' + shaderSource.name + "." + subShaderSource.name + "." + passSource.name + '" parse failed, please check the shader source code.';
11585
12053
  }
11586
- var shaderPass = new ShaderPass(passSource.name, shaderPassSource.vertex, shaderPassSource.fragment, passSource.tags);
11587
- shaderPass._platformTarget = vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget;
11588
- var _passSource_renderStates = passSource.renderStates, constantMap = _passSource_renderStates.constantMap, variableMap = _passSource_renderStates.variableMap;
11589
- // Compatible shader lab no render state use material `renderState` to modify render state
11590
- if (Object.keys(constantMap).length > 0 || Object.keys(variableMap).length > 0) {
11591
- // Parse const render state
11592
- var renderState = new RenderState();
11593
- for(var k in constantMap){
11594
- Shader._applyConstRenderStates(renderState, +k, constantMap[k]);
11595
- }
11596
- shaderPass._renderState = renderState;
11597
- // Parse variable render state
11598
- var renderStateDataMap = {};
11599
- for(var k1 in variableMap){
11600
- renderStateDataMap[k1] = ShaderProperty.getByName(variableMap[k1]);
11601
- }
11602
- shaderPass._renderStateDataMap = renderStateDataMap;
11603
- }
12054
+ var shaderPass = new ShaderPass(passSource.name, shaderPassSource.vertexShaderInstructions, shaderPassSource.fragmentShaderInstructions, vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget, passSource.tags);
12055
+ Shader._applyRenderStates(shaderPass, passSource.renderStates.constantMap, passSource.renderStates.variableMap, false);
11604
12056
  return shaderPass;
11605
12057
  });
11606
12058
  return new SubShader(subShaderSource.name, passList, subShaderSource.tags);
@@ -11645,6 +12097,29 @@
11645
12097
  };
11646
12098
  /**
11647
12099
  * @internal
12100
+ */ Shader._createFromPrecompiled = function _createFromPrecompiled(data) {
12101
+ var shaderMap = Shader._shaderMap;
12102
+ if (shaderMap[data.name]) {
12103
+ console.error('Shader named "' + data.name + '" already exists.');
12104
+ return;
12105
+ }
12106
+ var subShaderList = data.subShaders.map(function(subData) {
12107
+ var passList = subData.passes.map(function(passData) {
12108
+ if (passData.isUsePass) {
12109
+ return Shader._resolveUsePass(passData.name);
12110
+ }
12111
+ var shaderPass = new ShaderPass(passData.name, passData.vertexShaderInstructions, passData.fragmentShaderInstructions, data.platformTarget, passData.tags);
12112
+ Shader._applyRenderStates(shaderPass, passData.renderStates.constantMap, passData.renderStates.variableMap, true);
12113
+ return shaderPass;
12114
+ });
12115
+ return new SubShader(subData.name, passList, subData.tags);
12116
+ });
12117
+ var shader = new Shader(data.name, subShaderList);
12118
+ shaderMap[data.name] = shader;
12119
+ return shader;
12120
+ };
12121
+ /**
12122
+ * @internal
11648
12123
  */ Shader._clear = function _clear(engine) {
11649
12124
  var shaderMap = Shader._shaderMap;
11650
12125
  for(var key in shaderMap){
@@ -11665,6 +12140,34 @@
11665
12140
  }
11666
12141
  }
11667
12142
  };
12143
+ Shader._resolveUsePass = function _resolveUsePass(passName) {
12144
+ var _Shader_find_subShaders_find, _Shader_find;
12145
+ var _passName_split = passName.split("/"), shaderName = _passName_split[0], subShaderName = _passName_split[1], passNamePart = _passName_split[2];
12146
+ return (_Shader_find = Shader.find(shaderName)) == null ? void 0 : (_Shader_find_subShaders_find = _Shader_find.subShaders.find(function(subShader) {
12147
+ return subShader.name === subShaderName;
12148
+ })) == null ? void 0 : _Shader_find_subShaders_find.passes.find(function(pass) {
12149
+ return pass.name === passNamePart;
12150
+ });
12151
+ };
12152
+ Shader._applyRenderStates = function _applyRenderStates(shaderPass, constantMap, variableMap, deserializeColor) {
12153
+ if (Object.keys(constantMap).length > 0 || Object.keys(variableMap).length > 0) {
12154
+ var renderState = new RenderState();
12155
+ for(var k in constantMap){
12156
+ var value = constantMap[k];
12157
+ if (deserializeColor && Array.isArray(value)) {
12158
+ Shader._applyConstRenderStates(renderState, +k, new Color(value[0], value[1], value[2], value[3]));
12159
+ } else {
12160
+ Shader._applyConstRenderStates(renderState, +k, value);
12161
+ }
12162
+ }
12163
+ shaderPass._renderState = renderState;
12164
+ var renderStateDataMap = {};
12165
+ for(var k1 in variableMap){
12166
+ renderStateDataMap[k1] = ShaderProperty.getByName(variableMap[k1]);
12167
+ }
12168
+ shaderPass._renderStateDataMap = renderStateDataMap;
12169
+ }
12170
+ };
11668
12171
  Shader._applyConstRenderStates = function _applyConstRenderStates(renderState, key, value) {
11669
12172
  switch(key){
11670
12173
  case RenderStateElementKey.BlendStateEnabled0:
@@ -14082,7 +14585,15 @@
14082
14585
  */ _proto._getInvViewProjMat = function _getInvViewProjMat() {
14083
14586
  if (this._isInvViewProjDirty.flag) {
14084
14587
  this._isInvViewProjDirty.flag = false;
14085
- Matrix.multiply(this._entity.transform.worldMatrix, this._getInverseProjectionMatrix(), this._invViewProjMat);
14588
+ var matrix = this._invViewProjMat;
14589
+ if (this._isCustomViewMatrix) {
14590
+ Matrix.invert(this.viewMatrix, matrix);
14591
+ } else {
14592
+ // Ignore scale, consistent with viewMatrix getter
14593
+ var transform = this._entity.transform;
14594
+ Matrix.rotationTranslation(transform.worldRotationQuaternion, transform.worldPosition, matrix);
14595
+ }
14596
+ matrix.multiply(this._getInverseProjectionMatrix());
14086
14597
  }
14087
14598
  return this._invViewProjMat;
14088
14599
  };
@@ -27250,7 +27761,7 @@
27250
27761
  deepClone
27251
27762
  ], Skin.prototype, "inverseBindMatrices", void 0);
27252
27763
  __decorate$1([
27253
- ignoreClone
27764
+ deepClone
27254
27765
  ], Skin.prototype, "_skinMatrices", void 0);
27255
27766
  __decorate$1([
27256
27767
  ignoreClone
@@ -28241,7 +28752,10 @@
28241
28752
  _proto._setActiveComponents = function _setActiveComponents(isActive, activeChangeFlag) {
28242
28753
  var activeChangedComponents = this._activeChangedComponents;
28243
28754
  for(var i = 0, length = activeChangedComponents.length; i < length; ++i){
28244
- activeChangedComponents[i]._setActive(isActive, activeChangeFlag);
28755
+ var component = activeChangedComponents[i];
28756
+ // Skip components whose scene was already cleared by an earlier callback's removeChild
28757
+ if (!isActive && !component._entity._scene) continue;
28758
+ component._setActive(isActive, activeChangeFlag);
28245
28759
  }
28246
28760
  this._scene._componentsManager.putActiveChangedTempList(activeChangedComponents);
28247
28761
  this._activeChangedComponents = null;
@@ -28261,18 +28775,19 @@
28261
28775
  }
28262
28776
  };
28263
28777
  _proto._setInActiveInHierarchy = function _setInActiveInHierarchy(activeChangedComponents, activeChangeFlag) {
28778
+ // Children-first, reverse traversal for safe removeChild during callbacks
28779
+ var children = this._children;
28780
+ for(var i = children.length - 1; i >= 0; i--){
28781
+ var child = children[i];
28782
+ child.isActive && child._setInActiveInHierarchy(activeChangedComponents, activeChangeFlag);
28783
+ }
28264
28784
  activeChangeFlag & ActiveChangeFlag.Hierarchy && (this._isActiveInHierarchy = false);
28265
28785
  activeChangeFlag & ActiveChangeFlag.Scene && (this._isActiveInScene = false);
28266
28786
  var components = this._components;
28267
- for(var i = 0, n = components.length; i < n; i++){
28268
- var component = components[i];
28787
+ for(var i1 = 0, n = components.length; i1 < n; i1++){
28788
+ var component = components[i1];
28269
28789
  component.enabled && activeChangedComponents.push(component);
28270
28790
  }
28271
- var children = this._children;
28272
- for(var i1 = 0, n1 = children.length; i1 < n1; i1++){
28273
- var child = children[i1];
28274
- child.isActive && child._setInActiveInHierarchy(activeChangedComponents, activeChangeFlag);
28275
- }
28276
28791
  };
28277
28792
  _proto._setSiblingIndex = function _setSiblingIndex(sibling, target) {
28278
28793
  target = Math.min(target, sibling.length - 1);
@@ -28943,8 +29458,7 @@
28943
29458
  /** Plain text. */ AssetType["Text"] = "Text";
28944
29459
  /** JSON. */ AssetType["JSON"] = "JSON";
28945
29460
  /** ArrayBuffer. */ AssetType["Buffer"] = "Buffer";
28946
- /** 2D Texture. */ AssetType["Texture2D"] = "Texture2D";
28947
- /** Cube Texture. */ AssetType["TextureCube"] = "TextureCube";
29461
+ /** Texture. */ AssetType["Texture"] = "Texture";
28948
29462
  /** Material. */ AssetType["Material"] = "Material";
28949
29463
  /** Shader. */ AssetType["Shader"] = "Shader";
28950
29464
  /** Mesh. */ AssetType["Mesh"] = "Mesh";
@@ -31138,14 +31652,14 @@
31138
31652
  var depthOnlyFs = "void main() {\n}"; // eslint-disable-line
31139
31653
  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
31140
31654
  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
31141
- 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\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
31655
+ 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
31142
31656
  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
31143
31657
  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
31144
31658
  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
31145
31659
  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
31146
31660
  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
31147
31661
  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
31148
- 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 = vec3( -POSITION.x, POSITION.yz ); // TextureCube is left-hand,so x need inverse\n gl_Position = camera_VPMat * rotateY(vec4(POSITION, 1.0), material_Rotation);\n}\n"; // eslint-disable-line
31662
+ 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
31149
31663
  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
31150
31664
  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
31151
31665
  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
@@ -33573,38 +34087,6 @@
33573
34087
  Scene._fogColorProperty = ShaderProperty.getByName("scene_FogColor");
33574
34088
  Scene._fogParamsProperty = ShaderProperty.getByName("scene_FogParams");
33575
34089
  Scene._prefilterdDFGProperty = ShaderProperty.getByName("scene_PrefilteredDFG");
33576
- function _array_like_to_array$2(arr, len) {
33577
- if (len == null || len > arr.length) len = arr.length;
33578
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
33579
- return arr2;
33580
- }
33581
- function _unsupported_iterable_to_array$2(o, minLen) {
33582
- if (!o) return;
33583
- if (typeof o === "string") return _array_like_to_array$2(o, minLen);
33584
- var n = Object.prototype.toString.call(o).slice(8, -1);
33585
- if (n === "Object" && o.constructor) n = o.constructor.name;
33586
- if (n === "Map" || n === "Set") return Array.from(n);
33587
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$2(o, minLen);
33588
- }
33589
- function _create_for_of_iterator_helper_loose$2(o, allowArrayLike) {
33590
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
33591
- if (it) return (it = it.call(o)).next.bind(it);
33592
- // Fallback for engines without symbol support
33593
- if (Array.isArray(o) || (it = _unsupported_iterable_to_array$2(o)) || allowArrayLike && o && typeof o.length === "number") {
33594
- if (it) o = it;
33595
- var i = 0;
33596
- return function() {
33597
- if (i >= o.length) return {
33598
- done: true
33599
- };
33600
- return {
33601
- done: false,
33602
- value: o[i++]
33603
- };
33604
- };
33605
- }
33606
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
33607
- }
33608
34090
  /**
33609
34091
  * Script class, used for logic writing.
33610
34092
  */ var Script = /*#__PURE__*/ function(Component) {
@@ -37929,7 +38411,7 @@
37929
38411
  _inherits$2(ParticleRenderer, Renderer);
37930
38412
  function ParticleRenderer(entity) {
37931
38413
  var _this;
37932
- _this = Renderer.call(this, entity) || this, /** Specifies how much particles stretch depending on their velocity. */ _this.velocityScale = 0, /** How much are the particles stretched in their direction of motion, defined as the length of the particle compared to its width. */ _this.lengthScale = 2, /** The pivot of particle. */ _this.pivot = new Vector3(), /** @internal */ _this._generatorBounds = new BoundingBox(), /** @internal */ _this._transformedBounds = new BoundingBox();
38414
+ _this = Renderer.call(this, entity) || this, /** Specifies how much particles stretch depending on their velocity. */ _this.velocityScale = 0, /** How much are the particles stretched in their direction of motion, defined as the length of the particle compared to its width. */ _this.lengthScale = 2, /** The pivot of particle. */ _this.pivot = new Vector3(), /** @internal */ _this._generatorBounds = new BoundingBox(), /** @internal */ _this._transformedBounds = new BoundingBox(), _this._renderMode = ParticleRenderMode.Billboard;
37933
38415
  _this._onGeneratorParamsChanged = _this._onGeneratorParamsChanged.bind(_this);
37934
38416
  _this.generator = new ParticleGenerator(_this);
37935
38417
  _this._currentRenderModeMacro = ParticleRenderer._billboardModeMacro;
@@ -38528,6 +39010,7 @@
38528
39010
  ParticleRandomSubSeeds[ParticleRandomSubSeeds["GravityModifier"] = 2759560269] = "GravityModifier";
38529
39011
  ParticleRandomSubSeeds[ParticleRandomSubSeeds["ForceOverLifetime"] = 3875246972] = "ForceOverLifetime";
38530
39012
  ParticleRandomSubSeeds[ParticleRandomSubSeeds["LimitVelocityOverLifetime"] = 3047300990] = "LimitVelocityOverLifetime";
39013
+ ParticleRandomSubSeeds[ParticleRandomSubSeeds["Noise"] = 4105357473] = "Noise";
38531
39014
  return ParticleRandomSubSeeds;
38532
39015
  }({});
38533
39016
  /**
@@ -39903,7 +40386,7 @@
39903
40386
  return;
39904
40387
  }
39905
40388
  this._enabled = value;
39906
- this._generator._setTransformFeedback(value);
40389
+ this._generator._setTransformFeedback();
39907
40390
  this._generator._renderer._onGeneratorParamsChanged();
39908
40391
  }
39909
40392
  }
@@ -40842,6 +41325,297 @@
40842
41325
  __decorate$1([
40843
41326
  ignoreClone
40844
41327
  ], TextureSheetAnimationModule.prototype, "_onTilingChanged", null);
41328
+ /**
41329
+ * Noise module for particle system.
41330
+ * Adds simplex noise-based turbulence displacement to particles.
41331
+ */ var NoiseModule = /*#__PURE__*/ function(ParticleGeneratorModule) {
41332
+ _inherits$2(NoiseModule, ParticleGeneratorModule);
41333
+ function NoiseModule(generator) {
41334
+ var _this;
41335
+ _this = ParticleGeneratorModule.call(this, generator) || this, /** @internal */ _this._noiseRand = new Rand(0, ParticleRandomSubSeeds.Noise), _this._noiseParams = new Vector4(), _this._noiseOctaveParams = new Vector4(), _this._strengthMinConst = new Vector3(), _this._scrollSpeed = 0, _this._separateAxes = false, _this._frequency = 0.5, _this._octaveCount = 1, _this._octaveIntensityMultiplier = 0.5, _this._octaveFrequencyMultiplier = 2.0;
41336
+ _this.strengthX = new ParticleCompositeCurve(1);
41337
+ _this.strengthY = new ParticleCompositeCurve(1);
41338
+ _this.strengthZ = new ParticleCompositeCurve(1);
41339
+ return _this;
41340
+ }
41341
+ var _proto = NoiseModule.prototype;
41342
+ /**
41343
+ * @internal
41344
+ */ _proto._updateShaderData = function _updateShaderData(shaderData) {
41345
+ var enabledMacro = null;
41346
+ var strengthCurveMacro = null;
41347
+ var strengthIsRandomTwoMacro = null;
41348
+ var separateAxesMacro = null;
41349
+ if (this.enabled) {
41350
+ enabledMacro = NoiseModule._enabledMacro;
41351
+ var strengthX = this._strengthX;
41352
+ var strengthY = this._strengthY;
41353
+ var strengthZ = this._strengthZ;
41354
+ var separateAxes = this._separateAxes;
41355
+ // Determine strength curve mode (following SOL pattern)
41356
+ var isRandomCurveMode = separateAxes ? strengthX.mode === ParticleCurveMode.TwoCurves && strengthY.mode === ParticleCurveMode.TwoCurves && strengthZ.mode === ParticleCurveMode.TwoCurves : strengthX.mode === ParticleCurveMode.TwoCurves;
41357
+ var isCurveMode = isRandomCurveMode || (separateAxes ? strengthX.mode === ParticleCurveMode.Curve && strengthY.mode === ParticleCurveMode.Curve && strengthZ.mode === ParticleCurveMode.Curve : strengthX.mode === ParticleCurveMode.Curve);
41358
+ var isRandomConstMode = separateAxes ? strengthX.mode === ParticleCurveMode.TwoConstants && strengthY.mode === ParticleCurveMode.TwoConstants && strengthZ.mode === ParticleCurveMode.TwoConstants : strengthX.mode === ParticleCurveMode.TwoConstants;
41359
+ // noiseParams.w = frequency (always needed)
41360
+ var noiseParams = this._noiseParams;
41361
+ if (isCurveMode) {
41362
+ // Curve/TwoCurves: encode curve data as float arrays
41363
+ shaderData.setFloatArray(NoiseModule._strengthMaxCurveXProperty, strengthX.curveMax._getTypeArray());
41364
+ if (separateAxes) {
41365
+ shaderData.setFloatArray(NoiseModule._strengthMaxCurveYProperty, strengthY.curveMax._getTypeArray());
41366
+ shaderData.setFloatArray(NoiseModule._strengthMaxCurveZProperty, strengthZ.curveMax._getTypeArray());
41367
+ }
41368
+ if (isRandomCurveMode) {
41369
+ shaderData.setFloatArray(NoiseModule._strengthMinCurveXProperty, strengthX.curveMin._getTypeArray());
41370
+ if (separateAxes) {
41371
+ shaderData.setFloatArray(NoiseModule._strengthMinCurveYProperty, strengthY.curveMin._getTypeArray());
41372
+ shaderData.setFloatArray(NoiseModule._strengthMinCurveZProperty, strengthZ.curveMin._getTypeArray());
41373
+ }
41374
+ strengthIsRandomTwoMacro = NoiseModule._strengthIsRandomTwoMacro;
41375
+ }
41376
+ strengthCurveMacro = NoiseModule._strengthCurveMacro;
41377
+ // xyz unused in curve mode, just set frequency
41378
+ noiseParams.set(0, 0, 0, this._frequency);
41379
+ } else {
41380
+ // Constant/TwoConstants: pack strength into noiseParams.xyz
41381
+ if (separateAxes) {
41382
+ noiseParams.set(strengthX.constantMax, strengthY.constantMax, strengthZ.constantMax, this._frequency);
41383
+ } else {
41384
+ var s = strengthX.constantMax;
41385
+ noiseParams.set(s, s, s, this._frequency);
41386
+ }
41387
+ if (isRandomConstMode) {
41388
+ var minConst = this._strengthMinConst;
41389
+ if (separateAxes) {
41390
+ minConst.set(strengthX.constantMin, strengthY.constantMin, strengthZ.constantMin);
41391
+ } else {
41392
+ var sMin = strengthX.constantMin;
41393
+ minConst.set(sMin, sMin, sMin);
41394
+ }
41395
+ shaderData.setVector3(NoiseModule._strengthMinConstProperty, minConst);
41396
+ strengthIsRandomTwoMacro = NoiseModule._strengthIsRandomTwoMacro;
41397
+ }
41398
+ }
41399
+ shaderData.setVector4(NoiseModule._noiseProperty, noiseParams);
41400
+ if (separateAxes) {
41401
+ separateAxesMacro = NoiseModule._separateAxesMacro;
41402
+ }
41403
+ var noiseOctaveParams = this._noiseOctaveParams;
41404
+ noiseOctaveParams.set(this._scrollSpeed, this._octaveCount, this._octaveIntensityMultiplier, this._octaveFrequencyMultiplier);
41405
+ shaderData.setVector4(NoiseModule._noiseOctaveProperty, noiseOctaveParams);
41406
+ }
41407
+ this._enabledModuleMacro = this._enableMacro(shaderData, this._enabledModuleMacro, enabledMacro);
41408
+ this._strengthCurveModeMacro = this._enableMacro(shaderData, this._strengthCurveModeMacro, strengthCurveMacro);
41409
+ this._strengthIsRandomTwoModeMacro = this._enableMacro(shaderData, this._strengthIsRandomTwoModeMacro, strengthIsRandomTwoMacro);
41410
+ this._separateAxesModeMacro = this._enableMacro(shaderData, this._separateAxesModeMacro, separateAxesMacro);
41411
+ };
41412
+ /**
41413
+ * @internal
41414
+ */ _proto._resetRandomSeed = function _resetRandomSeed(seed) {
41415
+ this._noiseRand.reset(seed, ParticleRandomSubSeeds.Noise);
41416
+ };
41417
+ _create_class$2(NoiseModule, [
41418
+ {
41419
+ key: "separateAxes",
41420
+ get: /**
41421
+ * Specifies whether the strength is separate on each axis, when disabled, only `strength` is used.
41422
+ */ function get() {
41423
+ return this._separateAxes;
41424
+ },
41425
+ set: function set(value) {
41426
+ if (value !== this._separateAxes) {
41427
+ this._separateAxes = value;
41428
+ this._generator._renderer._onGeneratorParamsChanged();
41429
+ }
41430
+ }
41431
+ },
41432
+ {
41433
+ key: "strengthX",
41434
+ get: /**
41435
+ * Noise strength. When `separateAxes` is disabled, applies to all axes.
41436
+ * When `separateAxes` is enabled, applies only to x axis.
41437
+ */ function get() {
41438
+ return this._strengthX;
41439
+ },
41440
+ set: function set(value) {
41441
+ var lastValue = this._strengthX;
41442
+ if (value !== lastValue) {
41443
+ this._strengthX = value;
41444
+ this._onCompositeCurveChange(lastValue, value);
41445
+ }
41446
+ }
41447
+ },
41448
+ {
41449
+ key: "strengthY",
41450
+ get: /**
41451
+ * Noise strength for y axis, used when `separateAxes` is enabled.
41452
+ */ function get() {
41453
+ return this._strengthY;
41454
+ },
41455
+ set: function set(value) {
41456
+ var lastValue = this._strengthY;
41457
+ if (value !== lastValue) {
41458
+ this._strengthY = value;
41459
+ this._onCompositeCurveChange(lastValue, value);
41460
+ }
41461
+ }
41462
+ },
41463
+ {
41464
+ key: "strengthZ",
41465
+ get: /**
41466
+ * Noise strength for z axis, used when `separateAxes` is enabled.
41467
+ */ function get() {
41468
+ return this._strengthZ;
41469
+ },
41470
+ set: function set(value) {
41471
+ var lastValue = this._strengthZ;
41472
+ if (value !== lastValue) {
41473
+ this._strengthZ = value;
41474
+ this._onCompositeCurveChange(lastValue, value);
41475
+ }
41476
+ }
41477
+ },
41478
+ {
41479
+ key: "frequency",
41480
+ get: /**
41481
+ * Noise spatial frequency.
41482
+ */ function get() {
41483
+ return this._frequency;
41484
+ },
41485
+ set: function set(value) {
41486
+ value = Math.max(1e-6, value);
41487
+ if (value !== this._frequency) {
41488
+ this._frequency = value;
41489
+ this._generator._renderer._onGeneratorParamsChanged();
41490
+ }
41491
+ }
41492
+ },
41493
+ {
41494
+ key: "scrollSpeed",
41495
+ get: /**
41496
+ * Noise field scroll speed over time.
41497
+ */ function get() {
41498
+ return this._scrollSpeed;
41499
+ },
41500
+ set: function set(value) {
41501
+ if (value !== this._scrollSpeed) {
41502
+ this._scrollSpeed = value;
41503
+ this._generator._renderer._onGeneratorParamsChanged();
41504
+ }
41505
+ }
41506
+ },
41507
+ {
41508
+ key: "octaveCount",
41509
+ get: /**
41510
+ * Number of noise octave layers (1-3).
41511
+ */ function get() {
41512
+ return this._octaveCount;
41513
+ },
41514
+ set: function set(value) {
41515
+ value = Math.max(1, Math.min(3, Math.floor(value)));
41516
+ if (value !== this._octaveCount) {
41517
+ this._octaveCount = value;
41518
+ this._generator._renderer._onGeneratorParamsChanged();
41519
+ }
41520
+ }
41521
+ },
41522
+ {
41523
+ key: "octaveIntensityMultiplier",
41524
+ get: /**
41525
+ * Intensity multiplier for each successive octave, only effective when `octaveCount` > 1.
41526
+ * Each layer's contribution is scaled by this factor relative to the previous layer, range [0, 1].
41527
+ */ function get() {
41528
+ return this._octaveIntensityMultiplier;
41529
+ },
41530
+ set: function set(value) {
41531
+ value = Math.max(0, Math.min(1, value));
41532
+ if (value !== this._octaveIntensityMultiplier) {
41533
+ this._octaveIntensityMultiplier = value;
41534
+ this._generator._renderer._onGeneratorParamsChanged();
41535
+ }
41536
+ }
41537
+ },
41538
+ {
41539
+ key: "octaveFrequencyMultiplier",
41540
+ get: /**
41541
+ * Frequency multiplier for each successive octave, only effective when `octaveCount` > 1.
41542
+ * Each layer samples at this multiple of the previous layer's frequency, range [1, 4].
41543
+ */ function get() {
41544
+ return this._octaveFrequencyMultiplier;
41545
+ },
41546
+ set: function set(value) {
41547
+ value = Math.max(1, Math.min(4, value));
41548
+ if (value !== this._octaveFrequencyMultiplier) {
41549
+ this._octaveFrequencyMultiplier = value;
41550
+ this._generator._renderer._onGeneratorParamsChanged();
41551
+ }
41552
+ }
41553
+ },
41554
+ {
41555
+ key: "enabled",
41556
+ get: function get() {
41557
+ return this._enabled;
41558
+ },
41559
+ set: function set(value) {
41560
+ if (value !== this._enabled) {
41561
+ if (value && !this._generator._renderer.engine._hardwareRenderer.isWebGL2) {
41562
+ return;
41563
+ }
41564
+ this._enabled = value;
41565
+ this._generator._setTransformFeedback();
41566
+ this._generator._renderer._onGeneratorParamsChanged();
41567
+ }
41568
+ }
41569
+ }
41570
+ ]);
41571
+ return NoiseModule;
41572
+ }(ParticleGeneratorModule);
41573
+ NoiseModule._enabledMacro = ShaderMacro.getByName("RENDERER_NOISE_MODULE_ENABLED");
41574
+ NoiseModule._strengthCurveMacro = ShaderMacro.getByName("RENDERER_NOISE_STRENGTH_CURVE");
41575
+ NoiseModule._strengthIsRandomTwoMacro = ShaderMacro.getByName("RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO");
41576
+ NoiseModule._separateAxesMacro = ShaderMacro.getByName("RENDERER_NOISE_IS_SEPARATE");
41577
+ NoiseModule._noiseProperty = ShaderProperty.getByName("renderer_NoiseParams");
41578
+ NoiseModule._noiseOctaveProperty = ShaderProperty.getByName("renderer_NoiseOctaveParams");
41579
+ NoiseModule._strengthMinConstProperty = ShaderProperty.getByName("renderer_NoiseStrengthMinConst");
41580
+ NoiseModule._strengthMaxCurveXProperty = ShaderProperty.getByName("renderer_NoiseStrengthMaxCurveX");
41581
+ NoiseModule._strengthMaxCurveYProperty = ShaderProperty.getByName("renderer_NoiseStrengthMaxCurveY");
41582
+ NoiseModule._strengthMaxCurveZProperty = ShaderProperty.getByName("renderer_NoiseStrengthMaxCurveZ");
41583
+ NoiseModule._strengthMinCurveXProperty = ShaderProperty.getByName("renderer_NoiseStrengthMinCurveX");
41584
+ NoiseModule._strengthMinCurveYProperty = ShaderProperty.getByName("renderer_NoiseStrengthMinCurveY");
41585
+ NoiseModule._strengthMinCurveZProperty = ShaderProperty.getByName("renderer_NoiseStrengthMinCurveZ");
41586
+ __decorate$1([
41587
+ ignoreClone
41588
+ ], NoiseModule.prototype, "_enabledModuleMacro", void 0);
41589
+ __decorate$1([
41590
+ ignoreClone
41591
+ ], NoiseModule.prototype, "_strengthCurveModeMacro", void 0);
41592
+ __decorate$1([
41593
+ ignoreClone
41594
+ ], NoiseModule.prototype, "_strengthIsRandomTwoModeMacro", void 0);
41595
+ __decorate$1([
41596
+ ignoreClone
41597
+ ], NoiseModule.prototype, "_separateAxesModeMacro", void 0);
41598
+ __decorate$1([
41599
+ ignoreClone
41600
+ ], NoiseModule.prototype, "_noiseRand", void 0);
41601
+ __decorate$1([
41602
+ ignoreClone
41603
+ ], NoiseModule.prototype, "_noiseParams", void 0);
41604
+ __decorate$1([
41605
+ ignoreClone
41606
+ ], NoiseModule.prototype, "_noiseOctaveParams", void 0);
41607
+ __decorate$1([
41608
+ ignoreClone
41609
+ ], NoiseModule.prototype, "_strengthMinConst", void 0);
41610
+ __decorate$1([
41611
+ deepClone
41612
+ ], NoiseModule.prototype, "_strengthX", void 0);
41613
+ __decorate$1([
41614
+ deepClone
41615
+ ], NoiseModule.prototype, "_strengthY", void 0);
41616
+ __decorate$1([
41617
+ deepClone
41618
+ ], NoiseModule.prototype, "_strengthZ", void 0);
40845
41619
  /**
40846
41620
  * Velocity over lifetime module.
40847
41621
  */ var VelocityOverLifetimeModule = /*#__PURE__*/ function(ParticleGeneratorModule) {
@@ -41047,6 +41821,7 @@
41047
41821
  this.forceOverLifetime = new ForceOverLifetimeModule(this);
41048
41822
  this.sizeOverLifetime = new SizeOverLifetimeModule(this);
41049
41823
  this.limitVelocityOverLifetime = new LimitVelocityOverLifetimeModule(this);
41824
+ this.noise = new NoiseModule(this);
41050
41825
  this.emission.enabled = true;
41051
41826
  }
41052
41827
  var _proto = ParticleGenerator.prototype;
@@ -41354,6 +42129,7 @@
41354
42129
  this.sizeOverLifetime._updateShaderData(shaderData);
41355
42130
  this.rotationOverLifetime._updateShaderData(shaderData);
41356
42131
  this.colorOverLifetime._updateShaderData(shaderData);
42132
+ this.noise._updateShaderData(shaderData);
41357
42133
  };
41358
42134
  /**
41359
42135
  * @internal
@@ -41367,16 +42143,19 @@
41367
42143
  this.limitVelocityOverLifetime._resetRandomSeed(seed);
41368
42144
  this.rotationOverLifetime._resetRandomSeed(seed);
41369
42145
  this.colorOverLifetime._resetRandomSeed(seed);
42146
+ this.noise._resetRandomSeed(seed);
41370
42147
  };
41371
42148
  /**
41372
42149
  * @internal
41373
- */ _proto._setTransformFeedback = function _setTransformFeedback(enabled) {
41374
- this._useTransformFeedback = enabled;
42150
+ */ _proto._setTransformFeedback = function _setTransformFeedback() {
42151
+ var needed = this.limitVelocityOverLifetime.enabled || this.noise.enabled;
42152
+ if (needed === this._useTransformFeedback) return;
42153
+ this._useTransformFeedback = needed;
41375
42154
  // Switching TF mode invalidates all active particle state: feedback buffers and instance
41376
42155
  // buffer layout are incompatible between the two paths. Clear rather than show a one-frame
41377
42156
  // jump; new particles will fill in naturally from the next emit cycle.
41378
42157
  this._clearActiveParticles();
41379
- if (enabled) {
42158
+ if (needed) {
41380
42159
  if (!this._feedbackSimulator) {
41381
42160
  this._feedbackSimulator = new ParticleTransformFeedbackSimulator(this._renderer.engine);
41382
42161
  }
@@ -41426,9 +42205,7 @@
41426
42205
  /**
41427
42206
  * @internal
41428
42207
  */ _proto._cloneTo = function _cloneTo(target) {
41429
- if (target.limitVelocityOverLifetime.enabled) {
41430
- target._setTransformFeedback(true);
41431
- }
42208
+ target._setTransformFeedback();
41432
42209
  };
41433
42210
  /**
41434
42211
  * @internal
@@ -41590,10 +42367,6 @@
41590
42367
  // Start rotation
41591
42368
  var startRotationRand = main._startRotationRand, flipRotation = main.flipRotation;
41592
42369
  var isFlip = flipRotation > startRotationRand.random();
41593
- // @todo:None-Mesh mode should inverse the rotation, maybe should unify it
41594
- if (this._renderer.renderMode !== ParticleRenderMode.Mesh) {
41595
- isFlip = !isFlip;
41596
- }
41597
42370
  var rotationZ = main.startRotationZ.evaluate(undefined, startRotationRand.random());
41598
42371
  if (main.startRotation3D) {
41599
42372
  var rotationX = main.startRotationX.evaluate(undefined, startRotationRand.random());
@@ -41619,7 +42392,9 @@
41619
42392
  if (colorOverLifetime.enabled && colorOverLifetime.color.mode === ParticleGradientMode.TwoGradients) {
41620
42393
  instanceVertices[offset + 20] = colorOverLifetime._colorGradientRand.random();
41621
42394
  }
41622
- // instanceVertices[offset + 21] = rand.random();
42395
+ if (this.noise.enabled) {
42396
+ instanceVertices[offset + 21] = this.noise._noiseRand.random();
42397
+ }
41623
42398
  var rotationOverLifetime = this.rotationOverLifetime;
41624
42399
  if (rotationOverLifetime.enabled && rotationOverLifetime.rotationZ.mode === ParticleCurveMode.TwoConstants) {
41625
42400
  instanceVertices[offset + 22] = rotationOverLifetime._rotationRand.random();
@@ -41907,6 +42682,21 @@
41907
42682
  out.transform(rotateMat);
41908
42683
  min.add(worldOffsetMin);
41909
42684
  max.add(worldOffsetMax);
42685
+ // Noise module impact: noise output is normalized to [-1, 1],
42686
+ // max displacement = |strength_max|
42687
+ var noise = this.noise;
42688
+ if (noise.enabled) {
42689
+ var noiseMaxX, noiseMaxY, noiseMaxZ;
42690
+ if (noise.separateAxes) {
42691
+ noiseMaxX = Math.abs(noise.strengthX._getMax());
42692
+ noiseMaxY = Math.abs(noise.strengthY._getMax());
42693
+ noiseMaxZ = Math.abs(noise.strengthZ._getMax());
42694
+ } else {
42695
+ noiseMaxX = noiseMaxY = noiseMaxZ = Math.abs(noise.strengthX._getMax());
42696
+ }
42697
+ min.set(min.x - noiseMaxX, min.y - noiseMaxY, min.z - noiseMaxZ);
42698
+ max.set(max.x + noiseMaxX, max.y + noiseMaxY, max.z + noiseMaxZ);
42699
+ }
41910
42700
  min.add(worldPosition);
41911
42701
  max.add(worldPosition);
41912
42702
  };
@@ -42004,6 +42794,9 @@
42004
42794
  __decorate$1([
42005
42795
  deepClone
42006
42796
  ], ParticleGenerator.prototype, "textureSheetAnimation", void 0);
42797
+ __decorate$1([
42798
+ deepClone
42799
+ ], ParticleGenerator.prototype, "noise", void 0);
42007
42800
  __decorate$1([
42008
42801
  ignoreClone
42009
42802
  ], ParticleGenerator.prototype, "_playTime", void 0);
@@ -44197,6 +44990,7 @@
44197
44990
  MeshShape: MeshShape,
44198
44991
  MeshTopology: MeshTopology,
44199
44992
  ModelMesh: ModelMesh,
44993
+ NoiseModule: NoiseModule,
44200
44994
  OverflowMode: OverflowMode,
44201
44995
  PBRMaterial: PBRMaterial,
44202
44996
  ParticleCompositeCurve: ParticleCompositeCurve,
@@ -45387,7 +46181,7 @@
45387
46181
  };
45388
46182
  case TextureFormat.ETC2_RGBA5:
45389
46183
  return {
45390
- internalFormat: GLCompressedTextureInternalFormat.RGB8_PUNCHTHROUGH_ALPHA1_ETC2,
46184
+ internalFormat: isSRGBColorSpace ? GLCompressedTextureInternalFormat.SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 : GLCompressedTextureInternalFormat.RGB8_PUNCHTHROUGH_ALPHA1_ETC2,
45391
46185
  isCompressed: true
45392
46186
  };
45393
46187
  case TextureFormat.ETC2_RGBA8:
@@ -45422,27 +46216,27 @@
45422
46216
  };
45423
46217
  case TextureFormat.ASTC_5x5:
45424
46218
  return {
45425
- internalFormat: GLCompressedTextureInternalFormat.RGBA_ASTC_5X5_KHR,
46219
+ internalFormat: isSRGBColorSpace ? GLCompressedTextureInternalFormat.SRGB8_ALPHA8_ASTC_5X5_KHR : GLCompressedTextureInternalFormat.RGBA_ASTC_5X5_KHR,
45426
46220
  isCompressed: true
45427
46221
  };
45428
46222
  case TextureFormat.ASTC_6x6:
45429
46223
  return {
45430
- internalFormat: GLCompressedTextureInternalFormat.RGBA_ASTC_6X6_KHR,
46224
+ internalFormat: isSRGBColorSpace ? GLCompressedTextureInternalFormat.SRGB8_ALPHA8_ASTC_6X6_KHR : GLCompressedTextureInternalFormat.RGBA_ASTC_6X6_KHR,
45431
46225
  isCompressed: true
45432
46226
  };
45433
46227
  case TextureFormat.ASTC_8x8:
45434
46228
  return {
45435
- internalFormat: GLCompressedTextureInternalFormat.RGBA_ASTC_8X8_KHR,
46229
+ internalFormat: isSRGBColorSpace ? GLCompressedTextureInternalFormat.SRGB8_ALPHA8_ASTC_8X8_KHR : GLCompressedTextureInternalFormat.RGBA_ASTC_8X8_KHR,
45436
46230
  isCompressed: true
45437
46231
  };
45438
46232
  case TextureFormat.ASTC_10x10:
45439
46233
  return {
45440
- internalFormat: GLCompressedTextureInternalFormat.RGBA_ASTC_10X10_KHR,
46234
+ internalFormat: isSRGBColorSpace ? GLCompressedTextureInternalFormat.SRGB8_ALPHA8_ASTC_10X10_KHR : GLCompressedTextureInternalFormat.RGBA_ASTC_10X10_KHR,
45441
46235
  isCompressed: true
45442
46236
  };
45443
46237
  case TextureFormat.ASTC_12x12:
45444
46238
  return {
45445
- internalFormat: GLCompressedTextureInternalFormat.RGBA_ASTC_12X12_KHR,
46239
+ internalFormat: isSRGBColorSpace ? GLCompressedTextureInternalFormat.SRGB8_ALPHA8_ASTC_12X12_KHR : GLCompressedTextureInternalFormat.RGBA_ASTC_12X12_KHR,
45446
46240
  isCompressed: true
45447
46241
  };
45448
46242
  case TextureFormat.Depth:
@@ -47717,11 +48511,189 @@
47717
48511
  };
47718
48512
  return ReflectionParser;
47719
48513
  }();
47720
- exports.Texture2DDecoder = /*#__PURE__*/ function() {
48514
+ /**
48515
+ * HDR (Radiance RGBE) image decoder.
48516
+ *
48517
+ * Decodes .hdr files into pixel data. Supports parsing the header
48518
+ * and decoding RLE-compressed RGBE scanlines into R16G16B16A16 half-float pixels.
48519
+ */ var HDRDecoder = /*#__PURE__*/ function() {
48520
+ function HDRDecoder() {}
48521
+ /**
48522
+ * Parse the header of an HDR file.
48523
+ * @returns Header info including width, height, and data start position.
48524
+ */ HDRDecoder.parseHeader = function parseHeader(uint8array) {
48525
+ var line = this._readStringLine(uint8array, 0);
48526
+ if (line[0] !== "#" || line[1] !== "?") {
48527
+ throw "HDRDecoder: invalid file header";
48528
+ }
48529
+ var endOfHeader = false;
48530
+ var findFormat = false;
48531
+ var lineIndex = 0;
48532
+ do {
48533
+ lineIndex += line.length + 1;
48534
+ line = this._readStringLine(uint8array, lineIndex);
48535
+ if (line === "FORMAT=32-bit_rle_rgbe") findFormat = true;
48536
+ else if (line.length === 0) endOfHeader = true;
48537
+ }while (!endOfHeader);
48538
+ if (!findFormat) {
48539
+ throw "HDRDecoder: unsupported format, expected 32-bit_rle_rgbe";
48540
+ }
48541
+ lineIndex += line.length + 1;
48542
+ line = this._readStringLine(uint8array, lineIndex);
48543
+ var match = /^\-Y (.*) \+X (.*)$/g.exec(line);
48544
+ if (!match || match.length < 3) {
48545
+ throw "HDRDecoder: missing image size, only -Y +X layout is supported";
48546
+ }
48547
+ var width = parseInt(match[2]);
48548
+ var height = parseInt(match[1]);
48549
+ if (width < 8 || width > 0x7fff) {
48550
+ throw "HDRDecoder: unsupported image width, must be between 8 and 32767";
48551
+ }
48552
+ return {
48553
+ height: height,
48554
+ width: width,
48555
+ dataPosition: lineIndex + line.length + 1
48556
+ };
48557
+ };
48558
+ /**
48559
+ * Decode an HDR file buffer into R16G16B16A16 half-float pixel data.
48560
+ * @param buffer - The full HDR file as Uint8Array.
48561
+ * @returns Object with width, height, and half-float pixel data.
48562
+ */ HDRDecoder.decode = function decode(buffer) {
48563
+ var header = this.parseHeader(buffer);
48564
+ var width = header.width, height = header.height, dataPosition = header.dataPosition;
48565
+ var rgbe = this._readPixels(buffer.subarray(dataPosition), width, height);
48566
+ var pixels = this._rgbeToHalfFloat(rgbe, width, height);
48567
+ return {
48568
+ width: width,
48569
+ height: height,
48570
+ pixels: pixels
48571
+ };
48572
+ };
48573
+ /**
48574
+ * Convert RGBE pixel data to R16G16B16A16 half-float.
48575
+ */ HDRDecoder._rgbeToHalfFloat = function _rgbeToHalfFloat(rgbe, width, height) {
48576
+ var floatView = this._floatView;
48577
+ var uint32View = this._uint32View;
48578
+ var _this__float2HalfTables = this._float2HalfTables, baseTable = _this__float2HalfTables.baseTable, shiftTable = _this__float2HalfTables.shiftTable;
48579
+ var one = 0x3c00; // Half float 1.0
48580
+ var pixelCount = width * height;
48581
+ var result = new Uint16Array(pixelCount * 4);
48582
+ for(var i = 0; i < pixelCount; i++){
48583
+ var srcIdx = i * 4;
48584
+ var dstIdx = i * 4;
48585
+ var scaleFactor = Math.pow(2, rgbe[srcIdx + 3] - 128 - 8);
48586
+ for(var c = 0; c < 3; c++){
48587
+ floatView[0] = Math.min(rgbe[srcIdx + c] * scaleFactor, 65504);
48588
+ var f = uint32View[0];
48589
+ var e = f >> 23 & 0x1ff;
48590
+ result[dstIdx + c] = baseTable[e] + ((f & 0x007fffff) >> shiftTable[e]);
48591
+ }
48592
+ result[dstIdx + 3] = one;
48593
+ }
48594
+ return result;
48595
+ };
48596
+ /**
48597
+ * Decode RLE-compressed RGBE scanlines into raw RGBE pixel data.
48598
+ */ HDRDecoder._readPixels = function _readPixels(buffer, width, height) {
48599
+ var byteLength = buffer.byteLength;
48600
+ var dataRGBA = new Uint8Array(4 * width * height);
48601
+ var offset = 0;
48602
+ var pos = 0;
48603
+ var ptrEnd = 4 * width;
48604
+ var scanLineBuffer = new Uint8Array(ptrEnd);
48605
+ var numScanLines = height;
48606
+ while(numScanLines > 0 && pos < byteLength){
48607
+ var a = buffer[pos++];
48608
+ var b = buffer[pos++];
48609
+ var c = buffer[pos++];
48610
+ var d = buffer[pos++];
48611
+ if (a !== 2 || b !== 2 || c & 0x80 || width < 8 || width > 32767) return buffer;
48612
+ if ((c << 8 | d) !== width) throw "HDRDecoder: wrong scanline width";
48613
+ var ptr = 0;
48614
+ while(ptr < ptrEnd && pos < byteLength){
48615
+ var count = buffer[pos++];
48616
+ var isEncodedRun = count > 128;
48617
+ if (isEncodedRun) count -= 128;
48618
+ if (count === 0 || ptr + count > ptrEnd) throw "HDRDecoder: bad scanline data";
48619
+ if (isEncodedRun) {
48620
+ var byteValue = buffer[pos++];
48621
+ for(var i = 0; i < count; i++)scanLineBuffer[ptr++] = byteValue;
48622
+ } else {
48623
+ scanLineBuffer.set(buffer.subarray(pos, pos + count), ptr);
48624
+ ptr += count;
48625
+ pos += count;
48626
+ }
48627
+ }
48628
+ for(var i1 = 0; i1 < width; i1++, offset += 4){
48629
+ dataRGBA[offset] = scanLineBuffer[i1];
48630
+ dataRGBA[offset + 1] = scanLineBuffer[i1 + width];
48631
+ dataRGBA[offset + 2] = scanLineBuffer[i1 + width * 2];
48632
+ dataRGBA[offset + 3] = scanLineBuffer[i1 + width * 3];
48633
+ }
48634
+ numScanLines--;
48635
+ }
48636
+ return dataRGBA;
48637
+ };
48638
+ HDRDecoder._generateFloat2HalfTables = function _generateFloat2HalfTables() {
48639
+ var baseTable = new Uint32Array(512);
48640
+ var shiftTable = new Uint32Array(512);
48641
+ for(var i = 0; i < 256; ++i){
48642
+ var e = i - 127;
48643
+ if (e < -27) {
48644
+ baseTable[i] = 0x0000;
48645
+ baseTable[i | 0x100] = 0x8000;
48646
+ shiftTable[i] = 24;
48647
+ shiftTable[i | 0x100] = 24;
48648
+ } else if (e < -14) {
48649
+ baseTable[i] = 0x0400 >> -e - 14;
48650
+ baseTable[i | 0x100] = 0x0400 >> -e - 14 | 0x8000;
48651
+ shiftTable[i] = -e - 1;
48652
+ shiftTable[i | 0x100] = -e - 1;
48653
+ } else if (e <= 15) {
48654
+ baseTable[i] = e + 15 << 10;
48655
+ baseTable[i | 0x100] = e + 15 << 10 | 0x8000;
48656
+ shiftTable[i] = 13;
48657
+ shiftTable[i | 0x100] = 13;
48658
+ } else if (e < 128) {
48659
+ baseTable[i] = 0x7c00;
48660
+ baseTable[i | 0x100] = 0xfc00;
48661
+ shiftTable[i] = 24;
48662
+ shiftTable[i | 0x100] = 24;
48663
+ } else {
48664
+ baseTable[i] = 0x7c00;
48665
+ baseTable[i | 0x100] = 0xfc00;
48666
+ shiftTable[i] = 13;
48667
+ shiftTable[i | 0x100] = 13;
48668
+ }
48669
+ }
48670
+ return {
48671
+ baseTable: baseTable,
48672
+ shiftTable: shiftTable
48673
+ };
48674
+ };
48675
+ HDRDecoder._readStringLine = function _readStringLine(uint8array, startIndex) {
48676
+ var line = "";
48677
+ for(var i = startIndex, n = uint8array.length; i < n; i++){
48678
+ var character = String.fromCharCode(uint8array[i]);
48679
+ if (character === "\n") break;
48680
+ line += character;
48681
+ }
48682
+ return line;
48683
+ };
48684
+ return HDRDecoder;
48685
+ }();
48686
+ HDRDecoder._float2HalfTables = HDRDecoder._generateFloat2HalfTables();
48687
+ HDRDecoder._floatView = new Float32Array(1);
48688
+ HDRDecoder._uint32View = new Uint32Array(HDRDecoder._floatView.buffer);
48689
+ /**
48690
+ * Data format: [url] [mipmap(1B)] [filterMode(1B)] [anisoLevel(1B)] [wrapModeU(1B)] [wrapModeV(1B)]
48691
+ * [format(1B)] [width(2B)] [height(2B)] [isSRGBColorSpace(1B)] [Uint32(imageSize) + imageBytes]
48692
+ */ var Texture2DDecoder = /*#__PURE__*/ function() {
47721
48693
  function Texture2DDecoder() {}
47722
48694
  Texture2DDecoder.decode = function decode(engine, bufferReader, restoredTexture) {
47723
48695
  return new AssetPromise(function(resolve, reject) {
47724
- var url = bufferReader.nextStr();
48696
+ bufferReader.nextStr();
47725
48697
  var mipmap = !!bufferReader.nextUint8();
47726
48698
  var filterMode = bufferReader.nextUint8();
47727
48699
  var anisoLevel = bufferReader.nextUint8();
@@ -47730,58 +48702,34 @@
47730
48702
  var format = bufferReader.nextUint8();
47731
48703
  var width = bufferReader.nextUint16();
47732
48704
  var height = bufferReader.nextUint16();
47733
- var isPixelBuffer = bufferReader.nextUint8();
47734
48705
  var isSRGBColorSpace = !!bufferReader.nextUint8();
47735
- var mipCount = bufferReader.nextUint8();
47736
- var imagesData = bufferReader.nextImagesData(mipCount);
47737
- var texture2D = restoredTexture || new Texture2D(engine, width, height, format, mipmap, isSRGBColorSpace);
47738
- texture2D.filterMode = filterMode;
47739
- texture2D.anisoLevel = anisoLevel;
47740
- texture2D.wrapModeU = wrapModeU;
47741
- texture2D.wrapModeV = wrapModeV;
47742
- if (isPixelBuffer) {
47743
- var pixelBuffer = imagesData[0];
47744
- texture2D.setPixelBuffer(pixelBuffer);
47745
- if (mipmap) {
47746
- texture2D.generateMipmaps();
47747
- for(var i = 1; i < mipCount; i++){
47748
- var pixelBuffer1 = imagesData[i];
47749
- texture2D.setPixelBuffer(pixelBuffer1, i);
47750
- }
47751
- }
47752
- // @ts-ignore
47753
- engine.resourceManager._objectPool[url] = texture2D;
47754
- resolve(texture2D);
48706
+ var imageData = bufferReader.nextImagesData(1)[0];
48707
+ var isHDR = imageData[0] === 0x23 && imageData[1] === 0x3f;
48708
+ var textureFormat = isHDR ? TextureFormat.R16G16B16A16 : format;
48709
+ var texture = restoredTexture || new Texture2D(engine, width, height, textureFormat, mipmap, isHDR ? false : isSRGBColorSpace);
48710
+ texture.filterMode = filterMode;
48711
+ texture.anisoLevel = anisoLevel;
48712
+ texture.wrapModeU = wrapModeU;
48713
+ texture.wrapModeV = wrapModeV;
48714
+ if (isHDR) {
48715
+ var pixels = HDRDecoder.decode(imageData).pixels;
48716
+ texture.setPixelBuffer(pixels);
48717
+ mipmap && texture.generateMipmaps();
48718
+ resolve(texture);
47755
48719
  } else {
47756
- var blob = new window.Blob([
47757
- imagesData[0]
48720
+ var blob = new Blob([
48721
+ imageData
47758
48722
  ]);
47759
48723
  var img = new Image();
47760
48724
  img.onload = function() {
47761
- texture2D.setImageSource(img);
47762
- var completedCount = 0;
47763
- var onComplete = function onComplete() {
47764
- completedCount++;
47765
- if (completedCount >= mipCount) {
47766
- resolve(texture2D);
47767
- }
47768
- };
47769
- onComplete();
47770
- if (mipmap) {
47771
- var _loop = function _loop(i) {
47772
- var blob = new window.Blob([
47773
- imagesData[i]
47774
- ]);
47775
- var img = new Image();
47776
- img.onload = function() {
47777
- texture2D.setImageSource(img, i);
47778
- onComplete();
47779
- };
47780
- img.src = URL.createObjectURL(blob);
47781
- };
47782
- texture2D.generateMipmaps();
47783
- for(var i = 1; i < mipCount; i++)_loop(i);
47784
- }
48725
+ URL.revokeObjectURL(img.src);
48726
+ texture.setImageSource(img);
48727
+ mipmap && texture.generateMipmaps();
48728
+ resolve(texture);
48729
+ };
48730
+ img.onerror = function(e) {
48731
+ URL.revokeObjectURL(img.src);
48732
+ reject(e);
47785
48733
  };
47786
48734
  img.src = URL.createObjectURL(blob);
47787
48735
  }
@@ -47789,9 +48737,71 @@
47789
48737
  };
47790
48738
  return Texture2DDecoder;
47791
48739
  }();
47792
- exports.Texture2DDecoder = __decorate([
48740
+ Texture2DDecoder = __decorate([
47793
48741
  decoder("Texture2D")
47794
- ], exports.Texture2DDecoder);
48742
+ ], Texture2DDecoder);
48743
+ /**
48744
+ * Data format: [url] [mipmap(1B)] [filterMode(1B)] [anisoLevel(1B)] [wrapModeU(1B)] [wrapModeV(1B)]
48745
+ * [format(1B)] [faceSize(2B)] [isSRGBColorSpace(1B)] [Uint32(size) + faceBytes] × 6
48746
+ */ var TextureCubeDecoder = /*#__PURE__*/ function() {
48747
+ function TextureCubeDecoder() {}
48748
+ TextureCubeDecoder.decode = function decode(engine, bufferReader, restoredTexture) {
48749
+ return new AssetPromise(function(resolve, reject) {
48750
+ bufferReader.nextStr();
48751
+ var mipmap = !!bufferReader.nextUint8();
48752
+ var filterMode = bufferReader.nextUint8();
48753
+ var anisoLevel = bufferReader.nextUint8();
48754
+ var wrapModeU = bufferReader.nextUint8();
48755
+ var wrapModeV = bufferReader.nextUint8();
48756
+ var format = bufferReader.nextUint8();
48757
+ var faceSize = bufferReader.nextUint16();
48758
+ var isSRGBColorSpace = !!bufferReader.nextUint8();
48759
+ var facesData = bufferReader.nextImagesData(6);
48760
+ // Detect format by first face's magic bytes
48761
+ var isHDR = facesData[0][0] === 0x23 && facesData[0][1] === 0x3f;
48762
+ var textureFormat = isHDR ? TextureFormat.R16G16B16A16 : format;
48763
+ var texture = restoredTexture || new TextureCube(engine, faceSize, textureFormat, mipmap, isSRGBColorSpace);
48764
+ texture.filterMode = filterMode;
48765
+ texture.anisoLevel = anisoLevel;
48766
+ texture.wrapModeU = wrapModeU;
48767
+ texture.wrapModeV = wrapModeV;
48768
+ if (isHDR) {
48769
+ for(var i = 0; i < 6; i++){
48770
+ var pixels = HDRDecoder.decode(facesData[i]).pixels;
48771
+ texture.setPixelBuffer(TextureCubeFace.PositiveX + i, pixels, 0);
48772
+ }
48773
+ mipmap && texture.generateMipmaps();
48774
+ resolve(texture);
48775
+ } else {
48776
+ var _loop = function _loop(i1) {
48777
+ var blob = new Blob([
48778
+ facesData[i1]
48779
+ ]);
48780
+ var img = new Image();
48781
+ img.onload = function() {
48782
+ URL.revokeObjectURL(img.src);
48783
+ texture.setImageSource(TextureCubeFace.PositiveX + i1, img);
48784
+ if (++loadedCount === 6) {
48785
+ mipmap && texture.generateMipmaps();
48786
+ resolve(texture);
48787
+ }
48788
+ };
48789
+ img.onerror = function(e) {
48790
+ URL.revokeObjectURL(img.src);
48791
+ reject(e);
48792
+ };
48793
+ img.src = URL.createObjectURL(blob);
48794
+ };
48795
+ var loadedCount = 0;
48796
+ for(var i1 = 0; i1 < 6; i1++)_loop(i1);
48797
+ }
48798
+ });
48799
+ };
48800
+ return TextureCubeDecoder;
48801
+ }();
48802
+ TextureCubeDecoder = __decorate([
48803
+ decoder("TextureCube")
48804
+ ], TextureCubeDecoder);
47795
48805
  function _instanceof1(left, right) {
47796
48806
  if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
47797
48807
  return !!right[Symbol.hasInstance](left);
@@ -50362,11 +51372,13 @@
50362
51372
  });
50363
51373
  var img = new Image();
50364
51374
  img.onerror = function() {
51375
+ URL.revokeObjectURL(img.src);
50365
51376
  reject(new Error("Failed to load image buffer"));
50366
51377
  };
50367
51378
  img.onload = function() {
50368
51379
  // Call requestAnimationFrame to avoid iOS's bug.
50369
51380
  requestAnimationFrame(function() {
51381
+ URL.revokeObjectURL(img.src);
50370
51382
  resolve(img);
50371
51383
  img.onload = null;
50372
51384
  img.onerror = null;
@@ -51484,16 +52496,11 @@
51484
52496
  var isDefaultScene = scene === index;
51485
52497
  var sceneNodes = sceneInfo.nodes || [];
51486
52498
  var sceneRoot;
51487
- if (sceneNodes.length === 1) {
51488
- sceneRoot = context.get(GLTFParserType.Entity, sceneNodes[0]);
51489
- } else {
51490
- sceneRoot = new Entity(engine, "GLTF_ROOT");
51491
- // @ts-ignore
51492
- sceneRoot._markAsTemplate(glTFResource);
51493
- for(var i = 0; i < sceneNodes.length; i++){
51494
- var childEntity = context.get(GLTFParserType.Entity, sceneNodes[i]);
51495
- sceneRoot.addChild(childEntity);
51496
- }
52499
+ sceneRoot = new Entity(engine, "GLTF_ROOT");
52500
+ // @ts-ignore
52501
+ sceneRoot._markAsTemplate(glTFResource);
52502
+ for(var i = 0; i < sceneNodes.length; i++){
52503
+ sceneRoot.addChild(context.get(GLTFParserType.Entity, sceneNodes[i]));
51497
52504
  }
51498
52505
  if (isDefaultScene) {
51499
52506
  glTFResource._defaultSceneRoot = sceneRoot;
@@ -51784,7 +52791,7 @@
51784
52791
  if (uri) {
51785
52792
  var extIndex = uri.lastIndexOf(".");
51786
52793
  var ext = uri.substring(extIndex + 1);
51787
- var type = ext.startsWith("ktx") ? AssetType.KTX : AssetType.Texture2D;
52794
+ var type = ext.startsWith("ktx") ? AssetType.KTX : AssetType.Texture;
51788
52795
  texture = engine.resourceManager.load({
51789
52796
  url: Utils.resolveAbsoluteUrl(url, uri),
51790
52797
  type: type,
@@ -52641,7 +53648,7 @@
52641
53648
  var _atlasItem_type;
52642
53649
  chainPromises.push(resourceManager.load({
52643
53650
  url: Utils.resolveAbsoluteUrl(item.url, atlasItem.img),
52644
- type: (_atlasItem_type = atlasItem.type) != null ? _atlasItem_type : AssetType.Texture2D,
53651
+ type: (_atlasItem_type = atlasItem.type) != null ? _atlasItem_type : AssetType.Texture,
52645
53652
  params: {
52646
53653
  format: format,
52647
53654
  mipmap: mipmap
@@ -52776,26 +53783,12 @@
52776
53783
  "txt"
52777
53784
  ])
52778
53785
  ], TextLoader);
52779
- function loadImageFromBuffer(buffer) {
52780
- return new AssetPromise(function(resolve, reject) {
52781
- var blob = new Blob([
52782
- buffer
52783
- ]);
52784
- var img = new Image();
52785
- img.onload = function() {
52786
- URL.revokeObjectURL(img.src);
52787
- resolve(img);
52788
- };
52789
- img.onerror = reject;
52790
- img.src = URL.createObjectURL(blob);
52791
- });
52792
- }
52793
- var Texture2DLoader = /*#__PURE__*/ function(Loader) {
52794
- _inherits(Texture2DLoader, Loader);
52795
- function Texture2DLoader() {
53786
+ var TextureLoader = /*#__PURE__*/ function(Loader) {
53787
+ _inherits(TextureLoader, Loader);
53788
+ function TextureLoader() {
52796
53789
  return Loader.apply(this, arguments) || this;
52797
53790
  }
52798
- var _proto = Texture2DLoader.prototype;
53791
+ var _proto = TextureLoader.prototype;
52799
53792
  _proto.load = function load(item, resourceManager) {
52800
53793
  var _this = this;
52801
53794
  var url = item.url;
@@ -52805,427 +53798,136 @@
52805
53798
  return new AssetPromise(function(resolve, reject, setTaskCompleteProgress, setTaskDetailProgress) {
52806
53799
  resourceManager // @ts-ignore
52807
53800
  ._request(url, requestConfig).onProgress(setTaskCompleteProgress, setTaskDetailProgress).then(function(buffer) {
52808
- if (FileHeader.checkMagic(buffer)) {
52809
- decode(buffer, resourceManager.engine).then(function(texture) {
52810
- resourceManager.addContentRestorer(new Texture2DContentRestorer(texture, url, requestConfig));
52811
- resolve(texture);
52812
- }, reject);
52813
- } else {
52814
- loadImageFromBuffer(buffer).then(function(img) {
52815
- var texture = _this._createTexture(img, item, resourceManager);
52816
- resourceManager.addContentRestorer(new Texture2DContentRestorer(texture, url, requestConfig));
52817
- resolve(texture);
52818
- }, reject);
52819
- }
53801
+ _this._decode(buffer, item, resourceManager).then(function(texture) {
53802
+ resourceManager.addContentRestorer(new TextureContentRestorer(texture, url, requestConfig));
53803
+ resolve(texture);
53804
+ }, reject);
52820
53805
  }).catch(reject);
52821
53806
  });
52822
53807
  };
52823
- _proto._createTexture = function _createTexture(img, item, resourceManager) {
53808
+ _proto._decode = function _decode(buffer, item, resourceManager) {
53809
+ if (FileHeader.checkMagic(buffer)) {
53810
+ return decode(buffer, resourceManager.engine);
53811
+ }
53812
+ var bufferView = new Uint8Array(buffer);
53813
+ var isHDR = bufferView[0] === 0x23 && bufferView[1] === 0x3f;
53814
+ if (isHDR) {
53815
+ return this._decodeHDR(bufferView, item, resourceManager);
53816
+ }
53817
+ return this._decodeImage(buffer, item, resourceManager);
53818
+ };
53819
+ _proto._decodeHDR = function _decodeHDR(buffer, item, resourceManager) {
53820
+ var _this = this;
53821
+ return new AssetPromise(function(resolve, reject) {
53822
+ var engine = resourceManager.engine;
53823
+ if (!SystemInfo.supportsTextureFormat(engine, TextureFormat.R16G16B16A16)) {
53824
+ reject(new Error("TextureLoader: HDR texture requires half float support."));
53825
+ return;
53826
+ }
53827
+ var _HDRDecoder_decode = HDRDecoder.decode(buffer), width = _HDRDecoder_decode.width, height = _HDRDecoder_decode.height, pixels = _HDRDecoder_decode.pixels;
53828
+ var _item_params;
53829
+ var _ref = (_item_params = item.params) != null ? _item_params : {}, _ref_mipmap = _ref.mipmap, mipmap = _ref_mipmap === void 0 ? true : _ref_mipmap;
53830
+ var texture = new Texture2D(engine, width, height, TextureFormat.R16G16B16A16, mipmap, false);
53831
+ texture.setPixelBuffer(pixels);
53832
+ mipmap && texture.generateMipmaps();
53833
+ _this._applyParams(texture, item);
53834
+ resolve(texture);
53835
+ });
53836
+ };
53837
+ _proto._decodeImage = function _decodeImage(buffer, item, resourceManager) {
53838
+ var _this = this;
53839
+ return new AssetPromise(function(resolve, reject) {
53840
+ var blob = new Blob([
53841
+ buffer
53842
+ ]);
53843
+ var img = new Image();
53844
+ img.onload = function() {
53845
+ URL.revokeObjectURL(img.src);
53846
+ var _item_params;
53847
+ var _ref = (_item_params = item.params) != null ? _item_params : {}, _ref_format = _ref.format, format = _ref_format === void 0 ? TextureFormat.R8G8B8A8 : _ref_format, _ref_isSRGBColorSpace = _ref.isSRGBColorSpace, isSRGBColorSpace = _ref_isSRGBColorSpace === void 0 ? true : _ref_isSRGBColorSpace, _ref_mipmap = _ref.mipmap, mipmap = _ref_mipmap === void 0 ? true : _ref_mipmap;
53848
+ var engine = resourceManager.engine;
53849
+ var width = img.width, height = img.height;
53850
+ var generateMipmap = TextureUtils.supportGenerateMipmapsWithCorrection(engine, width, height, format, mipmap, isSRGBColorSpace);
53851
+ var texture = new Texture2D(engine, width, height, format, generateMipmap, isSRGBColorSpace);
53852
+ texture.setImageSource(img);
53853
+ generateMipmap && texture.generateMipmaps();
53854
+ _this._applyParams(texture, item);
53855
+ resolve(texture);
53856
+ };
53857
+ img.onerror = function(e) {
53858
+ URL.revokeObjectURL(img.src);
53859
+ reject(e);
53860
+ };
53861
+ img.src = URL.createObjectURL(blob);
53862
+ });
53863
+ };
53864
+ _proto._applyParams = function _applyParams(texture, item) {
52824
53865
  var _item_params;
52825
- var _ref = (_item_params = item.params) != null ? _item_params : {}, _ref_format = _ref.format, format = _ref_format === void 0 ? TextureFormat.R8G8B8A8 : _ref_format, anisoLevel = _ref.anisoLevel, wrapModeU = _ref.wrapModeU, wrapModeV = _ref.wrapModeV, filterMode = _ref.filterMode, _ref_isSRGBColorSpace = _ref.isSRGBColorSpace, isSRGBColorSpace = _ref_isSRGBColorSpace === void 0 ? true : _ref_isSRGBColorSpace, _ref_mipmap = _ref.mipmap, mipmap = _ref_mipmap === void 0 ? true : _ref_mipmap;
52826
- var width = img.width, height = img.height;
52827
- var engine = resourceManager.engine;
52828
- var generateMipmap = TextureUtils.supportGenerateMipmapsWithCorrection(engine, width, height, format, mipmap, isSRGBColorSpace);
52829
- var texture = new Texture2D(engine, width, height, format, generateMipmap, isSRGBColorSpace);
53866
+ var _ref = (_item_params = item.params) != null ? _item_params : {}, anisoLevel = _ref.anisoLevel, wrapModeU = _ref.wrapModeU, wrapModeV = _ref.wrapModeV, filterMode = _ref.filterMode;
52830
53867
  texture.anisoLevel = anisoLevel != null ? anisoLevel : texture.anisoLevel;
52831
53868
  texture.filterMode = filterMode != null ? filterMode : texture.filterMode;
52832
53869
  texture.wrapModeU = wrapModeU != null ? wrapModeU : texture.wrapModeU;
52833
53870
  texture.wrapModeV = wrapModeV != null ? wrapModeV : texture.wrapModeV;
52834
- texture.setImageSource(img);
52835
- generateMipmap && texture.generateMipmaps();
52836
53871
  var url = item.url;
52837
53872
  if (url.indexOf("data:") !== 0) {
52838
53873
  texture.name = url.substring(url.lastIndexOf("/") + 1);
52839
53874
  }
52840
- return texture;
52841
53875
  };
52842
- return Texture2DLoader;
53876
+ return TextureLoader;
52843
53877
  }(Loader);
52844
- Texture2DLoader = __decorate([
52845
- resourceLoader(AssetType.Texture2D, [
53878
+ TextureLoader = __decorate([
53879
+ resourceLoader(AssetType.Texture, [
53880
+ "tex",
52846
53881
  "png",
52847
53882
  "jpg",
52848
53883
  "webp",
52849
53884
  "jpeg",
52850
- "tex"
53885
+ "hdr"
52851
53886
  ])
52852
- ], Texture2DLoader);
52853
- var Texture2DContentRestorer = /*#__PURE__*/ function(ContentRestorer) {
52854
- _inherits(Texture2DContentRestorer, ContentRestorer);
52855
- function Texture2DContentRestorer(resource, url, requestConfig) {
53887
+ ], TextureLoader);
53888
+ var TextureContentRestorer = /*#__PURE__*/ function(ContentRestorer) {
53889
+ _inherits(TextureContentRestorer, ContentRestorer);
53890
+ function TextureContentRestorer(resource, url, requestConfig) {
52856
53891
  var _this;
52857
53892
  _this = ContentRestorer.call(this, resource) || this, _this.url = url, _this.requestConfig = requestConfig;
52858
53893
  return _this;
52859
53894
  }
52860
- var _proto = Texture2DContentRestorer.prototype;
53895
+ var _proto = TextureContentRestorer.prototype;
52861
53896
  _proto.restoreContent = function restoreContent() {
52862
- var texture = this.resource;
52863
- var engine = texture.engine;
52864
- return engine.resourceManager // @ts-ignore
53897
+ var _this = this;
53898
+ return this.resource.engine.resourceManager // @ts-ignore
52865
53899
  ._request(this.url, this.requestConfig).then(function(buffer) {
52866
53900
  if (FileHeader.checkMagic(buffer)) {
52867
- return decode(buffer, engine, texture);
52868
- } else {
52869
- return loadImageFromBuffer(buffer).then(function(img) {
52870
- texture.setImageSource(img);
52871
- texture.generateMipmaps();
52872
- return texture;
52873
- });
52874
- }
52875
- });
52876
- };
52877
- return Texture2DContentRestorer;
52878
- }(ContentRestorer);
52879
- /**
52880
- * HDR panorama to cubemap decoder.
52881
- */ var HDRDecoder = /*#__PURE__*/ function() {
52882
- function HDRDecoder() {}
52883
- HDRDecoder.parseHeader = function parseHeader(uint8array) {
52884
- var line = this._readStringLine(uint8array, 0);
52885
- if (line[0] !== "#" || line[1] !== "?") {
52886
- throw "HDRDecoder: invalid file header";
52887
- }
52888
- var endOfHeader = false;
52889
- var findFormat = false;
52890
- var lineIndex = 0;
52891
- do {
52892
- lineIndex += line.length + 1;
52893
- line = this._readStringLine(uint8array, lineIndex);
52894
- if (line === "FORMAT=32-bit_rle_rgbe") findFormat = true;
52895
- else if (line.length === 0) endOfHeader = true;
52896
- }while (!endOfHeader);
52897
- if (!findFormat) {
52898
- throw "HDRDecoder: unsupported format, expected 32-bit_rle_rgbe";
52899
- }
52900
- lineIndex += line.length + 1;
52901
- line = this._readStringLine(uint8array, lineIndex);
52902
- var match = /^\-Y (.*) \+X (.*)$/g.exec(line);
52903
- if (!match || match.length < 3) {
52904
- throw "HDRDecoder: missing image size, only -Y +X layout is supported";
52905
- }
52906
- var width = parseInt(match[2]);
52907
- var height = parseInt(match[1]);
52908
- if (width < 8 || width > 0x7fff) {
52909
- throw "HDRDecoder: unsupported image width, must be between 8 and 32767";
52910
- }
52911
- return {
52912
- height: height,
52913
- width: width,
52914
- dataPosition: lineIndex + line.length + 1
52915
- };
52916
- };
52917
- HDRDecoder.decodeFaces = function decodeFaces(bufferArray, header, onFace) {
52918
- var width = header.width, height = header.height, dataPosition = header.dataPosition;
52919
- var cubeSize = height >> 1;
52920
- var pixels = HDRDecoder._readPixels(bufferArray.subarray(dataPosition), width, height);
52921
- var faces = HDRDecoder._faces;
52922
- var faceBuffer = new Uint16Array(cubeSize * cubeSize * 4);
52923
- for(var faceIndex = 0; faceIndex < 6; faceIndex++){
52924
- HDRDecoder._createCubemapData(cubeSize, faces[faceIndex], pixels, width, height, faceBuffer);
52925
- onFace(faceIndex, faceBuffer);
52926
- }
52927
- };
52928
- HDRDecoder._generateFloat2HalfTables = function _generateFloat2HalfTables() {
52929
- var baseTable = new Uint32Array(512);
52930
- var shiftTable = new Uint32Array(512);
52931
- for(var i = 0; i < 256; ++i){
52932
- var e = i - 127;
52933
- if (e < -27) {
52934
- baseTable[i] = 0x0000;
52935
- baseTable[i | 0x100] = 0x8000;
52936
- shiftTable[i] = 24;
52937
- shiftTable[i | 0x100] = 24;
52938
- } else if (e < -14) {
52939
- baseTable[i] = 0x0400 >> -e - 14;
52940
- baseTable[i | 0x100] = 0x0400 >> -e - 14 | 0x8000;
52941
- shiftTable[i] = -e - 1;
52942
- shiftTable[i | 0x100] = -e - 1;
52943
- } else if (e <= 15) {
52944
- baseTable[i] = e + 15 << 10;
52945
- baseTable[i | 0x100] = e + 15 << 10 | 0x8000;
52946
- shiftTable[i] = 13;
52947
- shiftTable[i | 0x100] = 13;
52948
- } else if (e < 128) {
52949
- baseTable[i] = 0x7c00;
52950
- baseTable[i | 0x100] = 0xfc00;
52951
- shiftTable[i] = 24;
52952
- shiftTable[i | 0x100] = 24;
52953
- } else {
52954
- baseTable[i] = 0x7c00;
52955
- baseTable[i | 0x100] = 0xfc00;
52956
- shiftTable[i] = 13;
52957
- shiftTable[i | 0x100] = 13;
52958
- }
52959
- }
52960
- return {
52961
- baseTable: baseTable,
52962
- shiftTable: shiftTable
52963
- };
52964
- };
52965
- HDRDecoder._createCubemapData = function _createCubemapData(texSize, face, pixels, inputWidth, inputHeight, facePixels) {
52966
- var invSize = 1 / texSize;
52967
- var rotDX1X = (face[3] - face[0]) * invSize;
52968
- var rotDX1Y = (face[4] - face[1]) * invSize;
52969
- var rotDX1Z = (face[5] - face[2]) * invSize;
52970
- var rotDX2X = (face[9] - face[6]) * invSize;
52971
- var rotDX2Y = (face[10] - face[7]) * invSize;
52972
- var rotDX2Z = (face[11] - face[8]) * invSize;
52973
- var floatView = HDRDecoder._floatView;
52974
- var uint32View = HDRDecoder._uint32View;
52975
- var _HDRDecoder__float2HalfTables = HDRDecoder._float2HalfTables, baseTable = _HDRDecoder__float2HalfTables.baseTable, shiftTable = _HDRDecoder__float2HalfTables.shiftTable;
52976
- var one = HDRDecoder._one;
52977
- var fy = 0;
52978
- for(var y = 0; y < texSize; y++){
52979
- var xv1X = face[0], xv1Y = face[1], xv1Z = face[2];
52980
- var xv2X = face[6], xv2Y = face[7], xv2Z = face[8];
52981
- for(var x = 0; x < texSize; x++){
52982
- var dirX = xv1X + (xv2X - xv1X) * fy;
52983
- var dirY = xv1Y + (xv2Y - xv1Y) * fy;
52984
- var dirZ = xv1Z + (xv2Z - xv1Z) * fy;
52985
- var invLen = 1 / Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ);
52986
- dirX *= invLen;
52987
- dirY *= invLen;
52988
- dirZ *= invLen;
52989
- var px = Math.round((Math.atan2(dirZ, dirX) / Math.PI * 0.5 + 0.5) * inputWidth);
52990
- if (px < 0) px = 0;
52991
- else if (px >= inputWidth) px = inputWidth - 1;
52992
- var py = Math.round(Math.acos(dirY) / Math.PI * inputHeight);
52993
- if (py < 0) py = 0;
52994
- else if (py >= inputHeight) py = inputHeight - 1;
52995
- var srcIndex = (inputHeight - py - 1) * inputWidth * 4 + px * 4;
52996
- var scaleFactor = Math.pow(2, pixels[srcIndex + 3] - 128) / 255;
52997
- var dstIndex = y * texSize * 4 + x * 4;
52998
- for(var c = 0; c < 3; c++){
52999
- // Clamp to half-float max (65504) to prevent Infinity in R16G16B16A16
53000
- floatView[0] = Math.min(pixels[srcIndex + c] * scaleFactor, 65504);
53001
- var f = uint32View[0];
53002
- var e = f >> 23 & 0x1ff;
53003
- facePixels[dstIndex + c] = baseTable[e] + ((f & 0x007fffff) >> shiftTable[e]);
53004
- }
53005
- facePixels[dstIndex + 3] = one;
53006
- xv1X += rotDX1X;
53007
- xv1Y += rotDX1Y;
53008
- xv1Z += rotDX1Z;
53009
- xv2X += rotDX2X;
53010
- xv2Y += rotDX2Y;
53011
- xv2Z += rotDX2Z;
53012
- }
53013
- fy += invSize;
53014
- }
53015
- };
53016
- HDRDecoder._readStringLine = function _readStringLine(uint8array, startIndex) {
53017
- var line = "";
53018
- for(var i = startIndex, n = uint8array.length; i < n; i++){
53019
- var character = String.fromCharCode(uint8array[i]);
53020
- if (character === "\n") break;
53021
- line += character;
53022
- }
53023
- return line;
53024
- };
53025
- HDRDecoder._readPixels = function _readPixels(buffer, width, height) {
53026
- var byteLength = buffer.byteLength;
53027
- var dataRGBA = new Uint8Array(4 * width * height);
53028
- var offset = 0;
53029
- var pos = 0;
53030
- var ptrEnd = 4 * width;
53031
- var scanLineBuffer = new Uint8Array(ptrEnd);
53032
- var numScanLines = height;
53033
- while(numScanLines > 0 && pos < byteLength){
53034
- var a = buffer[pos++];
53035
- var b = buffer[pos++];
53036
- var c = buffer[pos++];
53037
- var d = buffer[pos++];
53038
- if (a !== 2 || b !== 2 || c & 0x80 || width < 8 || width > 32767) return buffer;
53039
- if ((c << 8 | d) !== width) throw "HDRDecoder: wrong scanline width";
53040
- var ptr = 0;
53041
- while(ptr < ptrEnd && pos < byteLength){
53042
- var count = buffer[pos++];
53043
- var isEncodedRun = count > 128;
53044
- if (isEncodedRun) count -= 128;
53045
- if (count === 0 || ptr + count > ptrEnd) throw "HDRDecoder: bad scanline data";
53046
- if (isEncodedRun) {
53047
- var byteValue = buffer[pos++];
53048
- for(var i = 0; i < count; i++)scanLineBuffer[ptr++] = byteValue;
53049
- } else {
53050
- scanLineBuffer.set(buffer.subarray(pos, pos + count), ptr);
53051
- ptr += count;
53052
- pos += count;
53053
- }
53054
- }
53055
- for(var i1 = 0; i1 < width; i1++, offset += 4){
53056
- dataRGBA[offset] = scanLineBuffer[i1];
53057
- dataRGBA[offset + 1] = scanLineBuffer[i1 + width];
53058
- dataRGBA[offset + 2] = scanLineBuffer[i1 + width * 2];
53059
- dataRGBA[offset + 3] = scanLineBuffer[i1 + width * 3];
53901
+ return decode(buffer, _this.resource.engine, _this.resource);
53902
+ }
53903
+ var bufferView = new Uint8Array(buffer);
53904
+ var texture = _this.resource;
53905
+ if (bufferView[0] === 0x23 && bufferView[1] === 0x3f) {
53906
+ var pixels = HDRDecoder.decode(bufferView).pixels;
53907
+ texture.setPixelBuffer(pixels);
53908
+ texture.mipmapCount > 1 && texture.generateMipmaps();
53909
+ return texture;
53060
53910
  }
53061
- numScanLines--;
53062
- }
53063
- return dataRGBA;
53064
- };
53065
- return HDRDecoder;
53066
- }();
53067
- // Float32 to Float16 lookup tables (http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf)
53068
- HDRDecoder._float2HalfTables = HDRDecoder._generateFloat2HalfTables();
53069
- HDRDecoder._floatView = new Float32Array(1);
53070
- HDRDecoder._uint32View = new Uint32Array(HDRDecoder._floatView.buffer);
53071
- HDRDecoder._one = 0x3c00 // Half float for 1.0
53072
- ;
53073
- // prettier-ignore
53074
- HDRDecoder._faces = [
53075
- /* +X */ [
53076
- 1,
53077
- -1,
53078
- -1,
53079
- 1,
53080
- -1,
53081
- 1,
53082
- 1,
53083
- 1,
53084
- -1,
53085
- 1,
53086
- 1,
53087
- 1
53088
- ],
53089
- /* -X */ [
53090
- -1,
53091
- -1,
53092
- 1,
53093
- -1,
53094
- -1,
53095
- -1,
53096
- -1,
53097
- 1,
53098
- 1,
53099
- -1,
53100
- 1,
53101
- -1
53102
- ],
53103
- /* +Y */ [
53104
- -1,
53105
- -1,
53106
- 1,
53107
- 1,
53108
- -1,
53109
- 1,
53110
- -1,
53111
- -1,
53112
- -1,
53113
- 1,
53114
- -1,
53115
- -1
53116
- ],
53117
- /* -Y */ [
53118
- -1,
53119
- 1,
53120
- -1,
53121
- 1,
53122
- 1,
53123
- -1,
53124
- -1,
53125
- 1,
53126
- 1,
53127
- 1,
53128
- 1,
53129
- 1
53130
- ],
53131
- /* +Z */ [
53132
- -1,
53133
- -1,
53134
- -1,
53135
- 1,
53136
- -1,
53137
- -1,
53138
- -1,
53139
- 1,
53140
- -1,
53141
- 1,
53142
- 1,
53143
- -1
53144
- ],
53145
- /* -Z */ [
53146
- 1,
53147
- -1,
53148
- 1,
53149
- -1,
53150
- -1,
53151
- 1,
53152
- 1,
53153
- 1,
53154
- 1,
53155
- -1,
53156
- 1,
53157
- 1
53158
- ]
53159
- ];
53160
- var TextureCubeLoader = /*#__PURE__*/ function(Loader) {
53161
- _inherits(TextureCubeLoader, Loader);
53162
- function TextureCubeLoader() {
53163
- return Loader.apply(this, arguments) || this;
53164
- }
53165
- var _proto = TextureCubeLoader.prototype;
53166
- _proto.load = function load(item, resourceManager) {
53167
- return new AssetPromise(function(resolve, reject) {
53168
- var engine = resourceManager.engine;
53169
- var url = item.url;
53170
- var requestConfig = _extends({}, item, {
53171
- type: "arraybuffer"
53911
+ return new AssetPromise(function(resolve, reject) {
53912
+ var blob = new Blob([
53913
+ buffer
53914
+ ]);
53915
+ var img = new Image();
53916
+ img.onload = function() {
53917
+ URL.revokeObjectURL(img.src);
53918
+ texture.setImageSource(img);
53919
+ texture.mipmapCount > 1 && texture.generateMipmaps();
53920
+ resolve(texture);
53921
+ };
53922
+ img.onerror = function(e) {
53923
+ URL.revokeObjectURL(img.src);
53924
+ reject(e);
53925
+ };
53926
+ img.src = URL.createObjectURL(blob);
53172
53927
  });
53173
- resourceManager // @ts-ignore
53174
- ._request(url, requestConfig).then(function(buffer) {
53175
- if (!SystemInfo.supportsTextureFormat(engine, TextureFormat.R16G16B16A16)) {
53176
- reject(new Error("TextureCubeLoader: HDR texture requires half float support."));
53177
- return;
53178
- }
53179
- var _item_params;
53180
- var _ref = (_item_params = item.params) != null ? _item_params : {}, _ref_mipmap = _ref.mipmap, mipmap = _ref_mipmap === void 0 ? true : _ref_mipmap, anisoLevel = _ref.anisoLevel, wrapModeU = _ref.wrapModeU, wrapModeV = _ref.wrapModeV, filterMode = _ref.filterMode;
53181
- var bufferArray = new Uint8Array(buffer);
53182
- var header = HDRDecoder.parseHeader(bufferArray);
53183
- var texture = new TextureCube(engine, header.height >> 1, TextureFormat.R16G16B16A16, mipmap, false);
53184
- HDRDecoder.decodeFaces(bufferArray, header, function(faceIndex, data) {
53185
- texture.setPixelBuffer(TextureCubeFace.PositiveX + faceIndex, data, 0);
53186
- });
53187
- texture.generateMipmaps();
53188
- texture.anisoLevel = anisoLevel != null ? anisoLevel : texture.anisoLevel;
53189
- texture.filterMode = filterMode != null ? filterMode : texture.filterMode;
53190
- texture.wrapModeU = wrapModeU != null ? wrapModeU : texture.wrapModeU;
53191
- texture.wrapModeV = wrapModeV != null ? wrapModeV : texture.wrapModeV;
53192
- resourceManager.addContentRestorer(new HDRContentRestorer(texture, url, requestConfig));
53193
- resolve(texture);
53194
- }).catch(reject);
53195
- });
53196
- };
53197
- return TextureCubeLoader;
53198
- }(Loader);
53199
- TextureCubeLoader = __decorate([
53200
- resourceLoader(AssetType.TextureCube, [
53201
- "texCube",
53202
- "hdr"
53203
- ])
53204
- ], TextureCubeLoader);
53205
- var HDRContentRestorer = /*#__PURE__*/ function(ContentRestorer) {
53206
- _inherits(HDRContentRestorer, ContentRestorer);
53207
- function HDRContentRestorer(resource, url, requestConfig) {
53208
- var _this;
53209
- _this = ContentRestorer.call(this, resource) || this, _this.url = url, _this.requestConfig = requestConfig;
53210
- return _this;
53211
- }
53212
- var _proto = HDRContentRestorer.prototype;
53213
- _proto.restoreContent = function restoreContent() {
53214
- var _this = this;
53215
- return new AssetPromise(function(resolve, reject) {
53216
- var resource = _this.resource;
53217
- resource.engine.resourceManager // @ts-ignore
53218
- ._request(_this.url, _this.requestConfig).then(function(buffer) {
53219
- var bufferArray = new Uint8Array(buffer);
53220
- HDRDecoder.decodeFaces(bufferArray, HDRDecoder.parseHeader(bufferArray), function(faceIndex, data) {
53221
- resource.setPixelBuffer(TextureCubeFace.PositiveX + faceIndex, data, 0);
53222
- });
53223
- resource.generateMipmaps();
53224
- resolve(resource);
53225
- }).catch(reject);
53226
53928
  });
53227
53929
  };
53228
- return HDRContentRestorer;
53930
+ return TextureContentRestorer;
53229
53931
  }(ContentRestorer);
53230
53932
  var AudioLoader = /*#__PURE__*/ function(Loader) {
53231
53933
  _inherits(AudioLoader, Loader);
@@ -53321,6 +54023,15 @@
53321
54023
  _proto.load = function load(item, resourceManager) {
53322
54024
  var _this = this;
53323
54025
  var url = item.url;
54026
+ if (url.endsWith(".gsp")) {
54027
+ // @ts-ignore
54028
+ return resourceManager._request(url, _extends({}, item, {
54029
+ type: "json"
54030
+ })).then(function(data) {
54031
+ // @ts-ignore - _createFromPrecompiled is @internal
54032
+ return Shader._createFromPrecompiled(data);
54033
+ });
54034
+ }
53324
54035
  // @ts-ignore
53325
54036
  return resourceManager._request(url, _extends({}, item, {
53326
54037
  type: "text"
@@ -53344,8 +54055,7 @@
53344
54055
  ShaderLoader._builtinRegex = /^\s*\/\/\s*@builtin\s+(\w+)/;
53345
54056
  ShaderLoader = __decorate([
53346
54057
  resourceLoader(AssetType.Shader, [
53347
- "gs",
53348
- "gsl"
54058
+ "shader"
53349
54059
  ])
53350
54060
  ], ShaderLoader);
53351
54061
  var PhysicsMaterialLoader = /*#__PURE__*/ function(Loader) {
@@ -54056,7 +54766,7 @@
54056
54766
  ], EXT_texture_webp);
54057
54767
 
54058
54768
  //@ts-ignore
54059
- var version = "2.0.0-alpha.24";
54769
+ var version = "2.0.0-alpha.26";
54060
54770
  console.log("Galacean Engine Version: " + version);
54061
54771
  for(var key in CoreObjects){
54062
54772
  Loader.registerClass(key, CoreObjects[key]);
@@ -54220,6 +54930,7 @@
54220
54930
  exports.MeshShape = MeshShape;
54221
54931
  exports.MeshTopology = MeshTopology;
54222
54932
  exports.ModelMesh = ModelMesh;
54933
+ exports.NoiseModule = NoiseModule;
54223
54934
  exports.OverflowMode = OverflowMode;
54224
54935
  exports.PBRMaterial = PBRMaterial;
54225
54936
  exports.ParserContext = ParserContext;