/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import{translate as e}from"../core/libs/gl-matrix-2/math/mat4.js";import{create as o}from"../core/libs/gl-matrix-2/factories/mat4f64.js";import{normalize as r,set as i}from"../core/libs/gl-matrix-2/math/vec3.js";import{create as a}from"../core/libs/gl-matrix-2/factories/vec3f64.js";import{addLinearDepth as l}from"../views/3d/webgl-engine/core/shaderLibrary/ForwardLinearDepth.glsl.js";import{addNearFar as t}from"../views/3d/webgl-engine/core/shaderLibrary/ForwardLinearDepthToWriteShadowMap.glsl.js";import{SliceDraw as n}from"../views/3d/webgl-engine/core/shaderLibrary/Slice.glsl.js";import{Transform as s}from"../views/3d/webgl-engine/core/shaderLibrary/Transform.glsl.js";import{NormalAttribute as d}from"../views/3d/webgl-engine/core/shaderLibrary/attributes/NormalAttribute.glsl.js";import{TextureCoordinateAttribute as c}from"../views/3d/webgl-engine/core/shaderLibrary/attributes/TextureCoordinateAttribute.glsl.js";import{VertexTangent as m}from"../views/3d/webgl-engine/core/shaderLibrary/attributes/VertexTangent.glsl.js";import{OutputDepth as v}from"../views/3d/webgl-engine/core/shaderLibrary/output/OutputDepth.glsl.js";import{OutputHighlight as g}from"../views/3d/webgl-engine/core/shaderLibrary/output/OutputHighlight.glsl.js";import{OutputHighlightOverlay as u}from"../views/3d/webgl-engine/core/shaderLibrary/output/OutputHighlightOverlay.js";import{EvaluateAmbientOcclusion as p}from"../views/3d/webgl-engine/core/shaderLibrary/shading/EvaluateAmbientOcclusion.glsl.js";import{EvaluateSceneLighting as w,addAmbientBoostFactor as f,addLightingGlobalFactor as b}from"../views/3d/webgl-engine/core/shaderLibrary/shading/EvaluateSceneLighting.glsl.js";import{addMainLightDirection as h,addMainLightIntensity as y}from"../views/3d/webgl-engine/core/shaderLibrary/shading/MainLighting.glsl.js";import{NormalUtils as C}from"../views/3d/webgl-engine/core/shaderLibrary/shading/NormalUtils.glsl.js";import{ReadShadowMapDraw as O}from"../views/3d/webgl-engine/core/shaderLibrary/shading/ReadShadowMap.glsl.js";import{OverlayTerrain as L}from"../views/3d/webgl-engine/core/shaderLibrary/terrain/Overlay.glsl.js";import{OverlayTerrainPassParameters as j,TerrainTexture as x}from"../views/3d/webgl-engine/core/shaderLibrary/terrain/TerrainTexture.glsl.js";import{addProjViewLocalOrigin as T,addViewNormal as M,addCameraPosition as P}from"../views/3d/webgl-engine/core/shaderLibrary/util/View.glsl.js";import{Float3BindUniform as $}from"../views/3d/webgl-engine/core/shaderModules/Float3BindUniform.js";import{glsl as S,If as z}from"../views/3d/webgl-engine/core/shaderModules/glsl.js";import{Matrix4DrawUniform as D}from"../views/3d/webgl-engine/core/shaderModules/Matrix4DrawUniform.js";import{Texture2DBindUniform as A}from"../views/3d/webgl-engine/core/shaderModules/Texture2DBindUniform.js";import{outputColorHighlightOLID as F}from"../views/3d/webgl-engine/shaders/OutputColorHighlightOLID.glsl.js";import{ShaderBuilder as _}from"../views/webgl/ShaderBuilder.js";import{alphaCutoff as V}from"../webscene/support/AlphaCutoff.js";class N extends j{}function W(o){const a=new _,{attributes:j,vertex:N,fragment:W,varyings:H}=a;j.add("position","vec3"),a.include(d,o),a.include(c,o);const U=()=>{a.include(C,o),N.code.add(S`vec3 getNormal() {
float z = 1.0 - abs(normalCompressed.x) - abs(normalCompressed.y);
vec3 n = vec3(normalCompressed + vec2(normalCompressed.x >= 0.0 ? 1.0 : -1.0,
normalCompressed.y >= 0.0 ? 1.0 : -1.0) * min(z, 0.0), z);
return normalize(n);
}`)};T(N,o),a.include(s);const{output:E,overlayMode:I,tileBorders:q,transparencyMode:R,overlayEnabled:G}=o,J=2===R||3===R,K=0!==o.pbrMode,Q=G&&J;switch(E){case 0:{a.include(x,o),W.include(w,o),G&&a.include(L,o);const l=2===I;l&&a.include(m,o),H.add("vnormal","vec3"),H.add("vpos","vec3",{invariant:!0}),H.add("vup","vec3"),U(),N.main.add(S`
          vpos = position;
          vec3 positionWorld = position + localOrigin;
          gl_Position = transformPosition(proj, view, vpos);
          vnormal = getNormal();
          vup = getLocalUp(position, localOrigin);
          ${z(l,S`forwardVertexTangent(vnormal);`)}

          forwardTextureCoordinatesWithTransform(uv0);
          ${z(G,"setOverlayVTC(uv0);")}
          ${z(q,"forwardTextureCoordinates();")}
          forwardLinearDepthToReadShadowMap();`),a.include(O,o),W.include(n,o),W.include(w,o),W.include(p,o),a.include(F,o),P(W,o),f(W),b(W),W.uniforms.add(N.uniforms.get("localOrigin"),new $("viewDirection",({camera:e})=>r(B,i(B,e.viewMatrix[12],e.viewMatrix[13],e.viewMatrix[14])))),l&&W.uniforms.add(new A("ovWaterTex",e=>e.overlay?.getTexture(3)),new D("view",({origin:o},{camera:r})=>e(k,r.viewMatrix,o))),h(W),y(W),W.main.add(S`
          vec3 normal = normalize(vnormal);
          float lightAlignment = dot(normal, mainLightDirection);

          float additionalAmbientScale = additionalDirectedAmbientLight(lightAlignment);
          float shadow = readShadow(additionalAmbientScale, vpos);
          float ssao = evaluateAmbientOcclusionInverse();
          vec4 tileColor = getTileColor();

          ${z(G,S`vec4 overlayColorOpaque = getOverlayColor(ovColorTex, vtcOverlay);
                   vec4 overlayColor = overlayOpacity * overlayColorOpaque;
                   ${z(J,`if (overlayColor.a < ${S.float(V)}) { discard; }`)}
                   vec4 groundColor = tileColor;
                   tileColor = tileColor * (1.0 - overlayColor.a) + overlayColor;`)}

          if(tileColor.a < ${S.float(V)}) {
            discard;
          }

          bool sliced = rejectBySlice(vpos);
          if (sliced) {
            tileColor *= groundSliceOpacity;
          }

          vec3 albedo = tileColor.rgb;

          // heuristic shading function used in the old terrain, now used to add ambient lighting
          vec3 additionalLight = ssao * mainLightIntensity * additionalAmbientScale * ambientBoostFactor * lightingGlobalFactor;

          ${K?S`vec4 finalColor = vec4(evaluatePBRSimplifiedLighting(normal, albedo, shadow, 1.0 - ssao, additionalLight, normalize(vpos - cameraPosition), vup), tileColor.a);`:S`vec4 finalColor = vec4(evaluateSceneLighting(normal, albedo, shadow, 1.0 - ssao, additionalLight), tileColor.a);`}
          ${z(l,S`vec4 overlayWaterMask = getOverlayColor(ovWaterTex, vtcOverlay);
                 float waterNormalLength = length(overlayWaterMask);
                 if (waterNormalLength > 0.95) {
                   mat3 tbnMatrix = mat3(tbnTangent, tbnBiTangent, vnormal);
                   vec4 waterOverlayColor = vec4(overlayColor.w > 0.0 ? overlayColorOpaque.xyz/overlayColor.w : vec3(1.0), overlayColor.w);
                   vec4 viewPosition = view * vec4(vpos, 1.0);
                   vec4 waterColorLinear = getOverlayWaterColor(overlayWaterMask, waterOverlayColor, -normalize(vpos - cameraPosition), shadow, vnormal, tbnMatrix, viewPosition.xyz,  vpos + localOrigin);
                   vec4 waterColorNonLinear = delinearizeGamma(vec4(waterColorLinear.xyz, 1.0));
                   float opacity = sliced ? groundSliceOpacity : 1.0;
                   // un-gamma the ground color to mix in linear space
                   finalColor = mix(groundColor, waterColorNonLinear, waterColorLinear.w) * opacity;
                 }`)}
          ${z(q,S`vec2 dVuv = fwidth(vuv0);
                 vec2 edgeFactors = smoothstep(vec2(0.0), 1.5 * dVuv, min(vuv0, 1.0 - vuv0));
                 float edgeFactor = 1.0 - min(edgeFactors.x, edgeFactors.y);
                 finalColor = mix(finalColor, vec4(1.0, 0.0, 0.0, 1.0), edgeFactor);`)}
          outputColorHighlightOLID(applySlice(finalColor, vpos), finalColor.rgb);`)}break;case 1:Q&&a.include(L,o),N.main.add(S`
        ${z(Q,"setOverlayVTC(uv0);")}
        gl_Position = transformPosition(proj, view, position);`),W.main.add(`${z(Q,`if (getCombinedOverlayColor().a < ${S.float(V)}) discard;`)}`);break;case 3:case 4:case 5:case 6:case 7:a.include(v,o),l(a),t(a),N.main.add(S`gl_Position = transformPositionWithDepth(proj, view, position, nearFar, linearDepth);`),W.main.add(S`outputDepth(linearDepth);`);break;case 2:Q&&a.include(L,o),H.add("vnormal","vec3"),M(N),U(),N.main.add(S`
        ${z(Q,"setOverlayVTC(uv0);")}
        gl_Position = transformPosition(proj, view, position);
        vnormal = normalize((viewNormal * vec4(getNormal(), 1.0)).xyz);`),W.main.add(S`
        ${z(Q,`if (getCombinedOverlayColor().a < ${S.float(V)}) discard;`)}
        vec3 normal = normalize(vnormal);
        if (gl_FrontFacing == false) {
          normal = -normal;
        }
        fragColor = vec4(vec3(0.5) + 0.5 * normal, 1.0);`);break;case 8:G&&(a.include(L,o),a.include(u,o)),N.main.add(S`
        ${z(G,"setOverlayVTC(uv0);")}
        gl_Position = transformPosition(proj, view, position);`),a.include(g,o),W.main.add(S`
        ${z(G,S`
           calculateOcclusionAndOutputHighlight(getAllOverlayHighlightValuesEncoded());`,"calculateOcclusionAndOutputHighlight();")}
      `);break;case 9:if(G)a.include(L,o),N.main.add(S`gl_Position = transformPosition(proj, view, position);
setOverlayVTC(uv0);`),W.main.add(S`fragColor = getOverlayColorTexel();`);else{const e=0===R;N.main.add(S`${z(e,"gl_Position = transformPosition(proj, view, position);")}`),W.main.add(S`fragColor = vec4(0.0);`)}}return a}const k=o(),B=a(),H=Object.freeze(Object.defineProperty({__proto__:null,TerrainPassParameters:N,build:W},Symbol.toStringTag,{value:"Module"}));export{N as T,H as a,W as b};
