/*
All material copyright Esri, All Rights Reserved, unless otherwise specified.
See https://js.arcgis.com/5.0/esri/copyright.txt for details.
*/
import{SliceDraw as e}from"../views/3d/webgl-engine/core/shaderLibrary/Slice.glsl.js";import{Transform as o}from"../views/3d/webgl-engine/core/shaderLibrary/Transform.glsl.js";import{ObjectAndLayerIdColor as r}from"../views/3d/webgl-engine/core/shaderLibrary/attributes/ObjectAndLayerIdColor.glsl.js";import{VertexColor as t}from"../views/3d/webgl-engine/core/shaderLibrary/attributes/VertexColor.glsl.js";import{terrainDepthTest as a}from"../views/3d/webgl-engine/core/shaderLibrary/shading/TerrainDepthTest.glsl.js";import{VisualVariables as i}from"../views/3d/webgl-engine/core/shaderLibrary/shading/VisualVariables.glsl.js";import{ColorConversion as n}from"../views/3d/webgl-engine/core/shaderLibrary/util/ColorConversion.glsl.js";import{addProjViewLocalOrigin as l,addCameraPosition as c}from"../views/3d/webgl-engine/core/shaderLibrary/util/View.glsl.js";import{Float4PassUniform as d}from"../views/3d/webgl-engine/core/shaderModules/Float4PassUniform.js";import{FloatBindUniform as s}from"../views/3d/webgl-engine/core/shaderModules/FloatBindUniform.js";import{glsl as v,If as p}from"../views/3d/webgl-engine/core/shaderModules/glsl.js";import{outputColorHighlightOLID as m}from"../views/3d/webgl-engine/shaders/OutputColorHighlightOLID.glsl.js";import{ShaderBuilder as g}from"../views/webgl/ShaderBuilder.js";const u=.70710678118,f=u,w=.08715574274,b=10,h=1;function y(y){const x=new g,{vertex:j,fragment:C,attributes:V,varyings:R}=x,P=8===y.output;l(j,y),x.include(o),x.include(t,y),x.include(i,y),x.include(r,y),x.fragment.include(e,y),x.include(m,y),x.include(a,y),y.draped?j.uniforms.add(new s("worldToScreenRatio",e=>1/e.screenToPCSRatio)):V.add("boundingRect","mat3"),V.add("position","vec3"),V.add("uvMapSpace","vec4"),y.hasVVColor&&V.add("colorFeatureAttribute","float"),y.hasVertexColors||R.add("vColor","vec4"),R.add("vpos","vec3",{invariant:!0}),R.add("vuv","vec2"),j.uniforms.add(new d("uColor",e=>e.color));const T=3===y.style||4===y.style||5===y.style;return T&&j.code.add(v`
      const mat2 rotate45 = mat2(${v.float(u)}, ${v.float(-f)},
                                 ${v.float(f)}, ${v.float(u)});
    `),y.draped||(c(j,y),j.uniforms.add(new s("worldToScreenPerDistanceRatio",e=>1/e.camera.perScreenPixelRatio)),j.code.add(v`vec3 projectPointToLineSegment(vec3 center, vec3 halfVector, vec3 point) {
float projectedLength = dot(halfVector, point - center) / dot(halfVector, halfVector);
return center + halfVector * clamp(projectedLength, -1.0, 1.0);
}`),j.code.add(v`vec3 intersectRayPlane(vec3 rayDir, vec3 rayOrigin, vec3 planeNormal, vec3 planePoint) {
float d = dot(planeNormal, planePoint);
float t = (d - dot(planeNormal, rayOrigin)) / dot(planeNormal, rayDir);
return rayOrigin + t * rayDir;
}`),j.code.add(v`
      float boundingRectDistanceToCamera() {
        vec3 center = vec3(boundingRect[0][0], boundingRect[0][1], boundingRect[0][2]);
        vec3 halfU = vec3(boundingRect[1][0], boundingRect[1][1], boundingRect[1][2]);
        vec3 halfV = vec3(boundingRect[2][0], boundingRect[2][1], boundingRect[2][2]);
        vec3 n = normalize(cross(halfU, halfV));

        vec3 viewDir = - vec3(view[0][2], view[1][2], view[2][2]);

        float viewAngle = dot(viewDir, n);
        float minViewAngle = ${v.float(w)};

        if (abs(viewAngle) < minViewAngle) {
          // view direction is (almost) parallel to plane -> clamp it to min angle
          float normalComponent = sign(viewAngle) * minViewAngle - viewAngle;
          viewDir = normalize(viewDir + normalComponent * n);
        }

        // intersect view direction with infinite plane that contains bounding rect
        vec3 planeProjected = intersectRayPlane(viewDir, cameraPosition, n, center);

        // clip to bounds by projecting to u and v line segments individually
        vec3 uProjected = projectPointToLineSegment(center, halfU, planeProjected);
        vec3 vProjected = projectPointToLineSegment(center, halfV, planeProjected);

        // use to calculate the closest point to camera on bounding rect
        vec3 closestPoint = uProjected + vProjected - center;

        return length(closestPoint - cameraPosition);
      }
    `)),j.code.add(v`
    vec2 scaledUV() {
      vec2 uv = uvMapSpace.xy ${p(T," * rotate45")};
      vec2 uvCellOrigin = uvMapSpace.zw ${p(T," * rotate45")};

      ${p(!y.draped,v`float distanceToCamera = boundingRectDistanceToCamera();
               float worldToScreenRatio = worldToScreenPerDistanceRatio / distanceToCamera;`)}

      // Logarithmically discretize ratio to avoid jittering
      float step = 0.1;
      float discreteWorldToScreenRatio = log(worldToScreenRatio);
      discreteWorldToScreenRatio = ceil(discreteWorldToScreenRatio / step) * step;
      discreteWorldToScreenRatio = exp(discreteWorldToScreenRatio);

      vec2 uvOffset = mod(uvCellOrigin * discreteWorldToScreenRatio, ${v.float(b)});
      return uvOffset + (uv * discreteWorldToScreenRatio);
    }
  `),j.main.add(v`
    vuv = scaledUV();
    vpos = position;
    forwardViewPosDepth((view * vec4(vpos, 1.0)).xyz);
    forwardNormalizedVertexColor();
    forwardObjectAndLayerIdColor();
    ${y.hasVertexColors?"vColor *= uColor;":y.hasVVColor?"vColor = uColor * interpolateVVColor(colorFeatureAttribute);":"vColor = uColor;"}
    gl_Position = transformPosition(proj, view, vpos);
  `),C.include(n),y.draped&&C.uniforms.add(new s("texelSize",e=>1/e.camera.pixelRatio)),P||(C.code.add(v`
      const float lineWidth = ${v.float(h)};
      const float spacing = ${v.float(b)};
      const float spacingINV = ${v.float(1/b)};

      float coverage(float p, float txlSize) {
        p = mod(p, spacing);

        float halfTxlSize = txlSize / 2.0;

        float start = p - halfTxlSize;
        float end = p + halfTxlSize;

        float coverage = (ceil(end * spacingINV) - floor(start * spacingINV)) * lineWidth;
        coverage -= min(lineWidth, mod(start, spacing));
        coverage -= max(lineWidth - mod(end, spacing), 0.0);

        return coverage / txlSize;
      }
    `),y.draped||C.code.add(v`const int maxSamples = 5;
float sampleAA(float p) {
vec2 dxdy = abs(vec2(dFdx(p), dFdy(p)));
float fwidth = dxdy.x + dxdy.y;
ivec2 samples = 1 + ivec2(clamp(dxdy, 0.0, float(maxSamples - 1)));
vec2 invSamples = 1.0 / vec2(samples);
float accumulator = 0.0;
for (int j = 0; j < maxSamples; j++) {
if(j >= samples.y) {
break;
}
for (int i = 0; i < maxSamples; i++) {
if(i >= samples.x) {
break;
}
vec2 step = vec2(i,j) * invSamples - 0.5;
accumulator += coverage(p + step.x * dxdy.x + step.y * dxdy.y, fwidth);
}
}
accumulator /= float(samples.x * samples.y);
return accumulator;
}`)),C.main.add(v`
    discardBySlice(vpos);
    discardByTerrainDepth();
    vec4 color = vColor;
    ${p(!P,v`color.a *= ${S(y)};`)}
    outputColorHighlightOLID(color, vpos, color.rgb);
  `),x}function S(e){function o(o){return e.draped?v`coverage(vuv.${o}, texelSize)`:v`sampleAA(vuv.${o})`}switch(e.style){case 3:case 0:return o("y");case 4:case 1:return o("x");case 5:case 2:return v`1.0 - (1.0 - ${o("x")}) * (1.0 - ${o("y")})`;default:return"0.0"}}const x=Object.freeze(Object.defineProperty({__proto__:null,build:y},Symbol.toStringTag,{value:"Module"}));export{x as P,y as b};
