/*
All material copyright Esri, All Rights Reserved, unless otherwise specified.
See https://js.arcgis.com/5.0/esri/copyright.txt for details.
*/
import{copy as e,set as o}from"../core/libs/gl-matrix-2/math/vec2.js";import{create as i}from"../core/libs/gl-matrix-2/factories/vec2f64.js";import{ZEROS as r,fromValues as t}from"../core/libs/gl-matrix-2/factories/vec4f64.js";import{earth as l}from"../geometry/support/Ellipsoid.js";import{RejectBySlice as a}from"../views/3d/webgl-engine/core/shaderLibrary/Slice.glsl.js";import{ObjectAndLayerIdColor as s}from"../views/3d/webgl-engine/core/shaderLibrary/attributes/ObjectAndLayerIdColor.glsl.js";import{AlignPixel as n}from"../views/3d/webgl-engine/core/shaderLibrary/hud/AlignPixel.glsl.js";import{HUD as c}from"../views/3d/webgl-engine/core/shaderLibrary/hud/HUD.glsl.js";import{HUDOcclusionPass as d}from"../views/3d/webgl-engine/core/shaderLibrary/hud/HUDOcclusionPass.glsl.js";import{HUDVisibility as u}from"../views/3d/webgl-engine/core/shaderLibrary/hud/HUDVisibility.glsl.js";import{OutputHighlight as f}from"../views/3d/webgl-engine/core/shaderLibrary/output/OutputHighlight.glsl.js";import{positionOutsideClipSpace as p}from"../views/3d/webgl-engine/core/shaderLibrary/shading/PositionOutsideClipSpace.js";import{VisualVariables as m}from"../views/3d/webgl-engine/core/shaderLibrary/shading/VisualVariables.glsl.js";import{ColorConversion as g}from"../views/3d/webgl-engine/core/shaderLibrary/util/ColorConversion.glsl.js";import{ScreenSizePerspective as v,addScreenSizePerspective as b,addScreenSizePerspectiveAlignment as x}from"../views/3d/webgl-engine/core/shaderLibrary/util/ScreenSizePerspective.glsl.js";import{addPixelRatio as h}from"../views/3d/webgl-engine/core/shaderLibrary/util/View.glsl.js";import{Float2PassUniform as w}from"../views/3d/webgl-engine/core/shaderModules/Float2PassUniform.js";import{Float4BindUniform as C}from"../views/3d/webgl-engine/core/shaderModules/Float4BindUniform.js";import{Float4DrawUniform as z}from"../views/3d/webgl-engine/core/shaderModules/Float4DrawUniform.js";import{Float4PassUniform as P}from"../views/3d/webgl-engine/core/shaderModules/Float4PassUniform.js";import{FloatBindUniform as S}from"../views/3d/webgl-engine/core/shaderModules/FloatBindUniform.js";import{FloatPassUniform as j}from"../views/3d/webgl-engine/core/shaderModules/FloatPassUniform.js";import{glsl as y,If as A}from"../views/3d/webgl-engine/core/shaderModules/glsl.js";import{Texture2DBindUniform as $}from"../views/3d/webgl-engine/core/shaderModules/Texture2DBindUniform.js";import{Texture2DPassUniform as O}from"../views/3d/webgl-engine/core/shaderModules/Texture2DPassUniform.js";import{ShaderBuilder as D}from"../views/webgl/ShaderBuilder.js";import{alphaCutoff as F}from"../webscene/support/AlphaCutoff.js";function T(e){const i=new D;if(i.include(c,e),i.vertex.include(a,e),e.occlusionPass)return i.include(d,e),i;const{output:T,oitPass:L,signedDistanceFieldEnabled:V,visibilityPixelEnabled:H,horizonCullingEnabled:_,pixelSnappingEnabled:q,hasEmission:R,hasScreenSizePerspective:k,debugDrawLabelBorder:I,hasVVSize:G,hasVVColor:J,hasRotation:K,occludedFragmentFade:N,sampleSignedDistanceFieldTexelCenter:Q}=e;i.include(v),i.include(m,e),i.include(s,e),H&&i.include(u);const{vertex:W,fragment:X}=i;X.include(g),i.varyings.add("vcolor","vec4"),i.varyings.add("vtc","vec2"),i.varyings.add("vsize","vec2");const Y=8===T,Z=Y&&H;Z&&i.varyings.add("voccluded","float"),W.uniforms.add(new C("viewport",e=>e.camera.fullViewport),new w("screenOffset",(e,i)=>o(U,2*e.screenOffset[0]*i.camera.pixelRatio,2*e.screenOffset[1]*i.camera.pixelRatio)),new w("anchorPosition",e=>M(e)),new P("materialColor",e=>e.color),new j("materialRotation",e=>e.rotation),new O("tex",e=>e.texture)),h(W),V&&(W.uniforms.add(new P("outlineColor",e=>e.outlineColor)),X.uniforms.add(new P("outlineColor",e=>B(e)?e.outlineColor:r),new j("outlineSize",e=>B(e)?e.outlineSize:0))),_&&W.uniforms.add(new z("pointDistanceSphere",(e,o)=>{const i=o.camera.eye,r=e.origin;return t(r[0]-i[0],r[1]-i[1],r[2]-i[2],l.radius)})),q&&W.include(n),k&&(b(W),x(W)),I&&i.varyings.add("debugBorderCoords","vec4"),i.attributes.add("uv0","vec2"),i.attributes.add("uvi","vec4"),i.attributes.add("color","vec4"),i.attributes.add("size","vec2"),i.attributes.add("rotation","float"),(G||J)&&i.attributes.add("featureAttribute","vec4"),W.code.add(_?y`bool behindHorizon(vec3 posModel) {
vec3 camToEarthCenter = pointDistanceSphere.xyz - localOrigin;
vec3 camToPos = pointDistanceSphere.xyz + posModel;
float earthRadius = pointDistanceSphere.w;
float a = dot(camToPos, camToPos);
float b = dot(camToPos, camToEarthCenter);
float c = dot(camToEarthCenter, camToEarthCenter) - earthRadius * earthRadius;
return b > 0.0 && b < a && b * b  > a * c;
}`:y`bool behindHorizon(vec3 posModel) { return false; }`),W.main.add(y`
    ProjectHUDAux projectAux;
    vec4 posProj = projectPositionHUD(projectAux);
    forwardObjectAndLayerIdColor();

    if (rejectBySlice(projectAux.posModel)) {
      gl_Position = ${p};
      return;
    }

    if (behindHorizon(projectAux.posModel)) {
      gl_Position = ${p};
      return;
    }

    vec2 inputSize;
    ${A(k,y`
        inputSize = screenSizePerspectiveScaleVec2(size, projectAux.absCosAngle, projectAux.distanceToCamera, screenSizePerspective);
        vec2 screenOffsetScaled = screenSizePerspectiveScaleVec2(screenOffset, projectAux.absCosAngle, projectAux.distanceToCamera, screenSizePerspectiveAlignment);`,y`
        inputSize = size;
        vec2 screenOffsetScaled = screenOffset;`)}
    ${A(G,y`inputSize *= vvScale(featureAttribute).xx;`)}

    vec2 combinedSize = inputSize * pixelRatio;
    vec4 quadOffset = vec4(0.0);

    ${A(H,y`
    bool visible = testHUDVisibility(posProj);
    if (!visible) {
      vtc = vec2(0.0);
      ${A(I,"debugBorderCoords = vec4(0.5, 0.5, 1.5 / combinedSize);")}
      return;
    }`)}
    ${A(Z,y`voccluded = visible ? 0.0 : 1.0;`)}
  `);const ee=y`
      vec2 uv = mix(uvi.xy, uvi.zw, bvec2(uv0));
      vec2 texSize = vec2(textureSize(tex, 0));
      uv = mix(vec2(1.0), uv / texSize, lessThan(uv, vec2(${E})));
      quadOffset.xy = (uv0 - anchorPosition) * 2.0 * combinedSize;

      ${A(K,y`
          float angle = radians(materialRotation + rotation);
          float cosAngle = cos(angle);
          float sinAngle = sin(angle);
          mat2 rotate = mat2(cosAngle, -sinAngle, sinAngle,  cosAngle);

          quadOffset.xy = rotate * quadOffset.xy;
        `)}

      quadOffset.xy = (quadOffset.xy + screenOffsetScaled) / viewport.zw * posProj.w;
  `,oe=q?V?y`posProj = alignToPixelOrigin(posProj, viewport.zw) + quadOffset;`:y`posProj += quadOffset;
if (inputSize.x == size.x) {
posProj = alignToPixelOrigin(posProj, viewport.zw);
}`:y`posProj += quadOffset;`;W.main.add(y`
    ${ee}
    ${J?"vcolor = interpolateVVColor(featureAttribute.y) * materialColor;":"vcolor = color / 255.0 * materialColor;"}

    ${A(9===T,y`vcolor.a = 1.0;`)}

    bool alphaDiscard = vcolor.a < ${y.float(F)};
    ${A(V,`alphaDiscard = alphaDiscard && outlineColor.a < ${y.float(F)};`)}
    if (alphaDiscard) {
      // "early discard" if both symbol color (= fill) and outline color (if applicable) are transparent
      gl_Position = vec4(1e38, 1e38, 1e38, 1.0);
      return;
    } else {
      ${oe}
      gl_Position = posProj;
    }

    vtc = uv;

    ${A(I,y`debugBorderCoords = vec4(uv01, 1.5 / combinedSize);`)}
    vsize = inputSize;
  `),X.uniforms.add(new O("tex",e=>e.texture)),N&&!Y&&X.uniforms.add(new $("depthMap",e=>e.mainDepth),new S("occludedOpacity",e=>e.hudOccludedFragmentOpacity));const ie=I?y`(isBorder > 0.0 ? 0.0 : ${y.float(F)})`:y.float(F),re=y`
    ${A(I,y`float isBorder = float(any(lessThan(debugBorderCoords.xy, debugBorderCoords.zw)) || any(greaterThan(debugBorderCoords.xy, 1.0 - debugBorderCoords.zw)));`)}

    vec2 samplePos = vtc;

    ${A(Q,y`
      float txSize = float(textureSize(tex, 0).x);
      float texelSize = 1.0 / txSize;

      // Calculate how much we have to add/subtract to/from each texel to reach the size of an onscreen pixel
      vec2 scaleFactor = (vsize - txSize) * texelSize;
      samplePos += (vec2(1.0, -1.0) * texelSize) * scaleFactor;`)}

    ${V?y`
      vec4 fillPixelColor = vcolor;

      // Get distance in output units (i.e. pixels)

      float sdf = texture(tex, samplePos).r;
      float pixelDistance = sdf * vsize.x;

      // Create smooth transition from the icon into its outline
      float fillAlphaFactor = clamp(0.5 - pixelDistance, 0.0, 1.0);
      fillPixelColor.a *= fillAlphaFactor;

      if (outlineSize > 0.25) {
        vec4 outlinePixelColor = outlineColor;
        float clampedOutlineSize = min(outlineSize, 0.5*vsize.x);

        // Create smooth transition around outline
        float outlineAlphaFactor = clamp(0.5 - (abs(pixelDistance) - 0.5*clampedOutlineSize), 0.0, 1.0);
        outlinePixelColor.a *= outlineAlphaFactor;

        if (
          outlineAlphaFactor + fillAlphaFactor < ${ie} ||
          fillPixelColor.a + outlinePixelColor.a < ${y.float(F)}
        ) {
          discard;
        }

        // perform un-premultiplied over operator (see https://en.wikipedia.org/wiki/Alpha_compositing#Description)
        float compositeAlpha = outlinePixelColor.a + fillPixelColor.a * (1.0 - outlinePixelColor.a);
        vec3 compositeColor = vec3(outlinePixelColor) * outlinePixelColor.a +
          vec3(fillPixelColor) * fillPixelColor.a * (1.0 - outlinePixelColor.a);

        ${A(!Y,y`fragColor = vec4(compositeColor, compositeAlpha);`)}
      } else {
        if (fillAlphaFactor < ${ie}) {
          discard;
        }

        ${A(!Y,y`fragColor = premultiplyAlpha(fillPixelColor);`)}
      }

      // visualize SDF:
      // fragColor = vec4(clamp(-pixelDistance/vsize.x*2.0, 0.0, 1.0), clamp(pixelDistance/vsize.x*2.0, 0.0, 1.0), 0.0, 1.0);
      `:y`
          vec4 texColor = texture(tex, samplePos, -0.5);
          if (texColor.a < ${ie}) {
            discard;
          }
          ${A(!Y,y`fragColor = texColor * premultiplyAlpha(vcolor);`)}
          `}

    ${A(N&&!Y,y`
        float zSample = texelFetch(depthMap, ivec2(gl_FragCoord.xy), 0).x;
        if (zSample < gl_FragCoord.z) {
          fragColor *= occludedOpacity;
        }
        `)}

    ${A(!Y&&I,y`fragColor = mix(fragColor, vec4(1.0, 0.0, 1.0, 1.0), isBorder * 0.5);`)}
  `;switch(T){case 0:i.outputs.add("fragColor","vec4",0),R&&i.outputs.add("fragEmission","vec4",1),1===L&&i.outputs.add("fragAlpha","float",R?2:1),X.main.add(y`
        ${re}
        ${A(2===L,y`fragColor.rgb /= fragColor.a;`)}
        ${A(R,y`fragEmission = vec4(0.0);`)}
        ${A(1===L,y`fragAlpha = fragColor.a;`)}`);break;case 9:X.main.add(y`
        ${re}
        outputObjectAndLayerIdColor();`);break;case 8:i.include(f,e),X.main.add(y`
        ${re}
        outputHighlight(${A(Z,y`voccluded == 1.0`,y`false`)});`)}return i}function B(e){return e.outlineColor[3]>0&&e.outlineSize>0}function M(o){return o.textureIsSignedDistanceField?L(o.anchorPosition,o.distanceFieldBoundingBox,U):e(U,o.anchorPosition),U}function L(e,i,r){o(r,e[0]*(i[2]-i[0])+i[0],e[1]*(i[3]-i[1])+i[1])}const U=i(),V=32e3,E=y.float(V),H=Object.freeze(Object.defineProperty({__proto__:null,build:T,calculateAnchorPosition:M,fullUV:V},Symbol.toStringTag,{value:"Module"}));export{H,T as b,M as c,V as f};
