// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
require({cache:{"url:esri/views/3d/terrain/TerrainMaterial.xml":'\x3c?xml version\x3d"1.0" encoding\x3d"UTF-8"?\x3e\n\n\x3csnippets\x3e\n\n\x3csnippet name\x3d"getOverlayColor"\x3e\x3c![CDATA[\n  vec4 getOverlayColor(vec4 texCoords, float opacity) {\n    vec4 color \x3d vec4(0, 0, 0, 0);\n\n    if ((texCoords.x \x3e 0.0) \x26\x26 (texCoords.x \x3c 1.0) \x26\x26 (texCoords.y \x3e 0.0) \x26\x26 (texCoords.y \x3c 1.0)) {\n      // inner overlay texture coordinates are within bounds -\x3e sample from inner overlay\n      color \x3d texture2D(overlay0Tex, texCoords.xy);\n    } else if ((texCoords.z \x3e 0.0) \x26\x26 (texCoords.z \x3c 1.0) \x26\x26 (texCoords.w \x3e 0.0) \x26\x26 (texCoords.w \x3c 1.0)) {\n      // sample from outer overlay\n      color \x3d texture2D(overlay1Tex, texCoords.zw);\n    }\n\n    return color * opacity;\n  }\n]]\x3e\x3c/snippet\x3e\n\n\x3csnippet name\x3d"applySkirts"\x3e\x3c![CDATA[\n  uniform float skirtScale;\n\n  vec3 applySkirts(inout vec2 uv, vec3 vpos, vec3 vnormal) {\n    float skirtLength \x3d 0.0;\n\n    if (uv.x \x3e\x3d 2.0) {\n      skirtLength \x3d uv.y * skirtScale;\n      // decode original uv-coordinates (see `encodeSkirtPos`)\n      vec2 x \x3d vec2(uv.x) - vec2(3.5, 4.5);\n      uv \x3d clamp(vec2(1.5) - abs(x), vec2(0.0), vec2(1.0));\n    }\n\n    return vpos - vnormal * skirtLength;\n  }\n]]\x3e\x3c/snippet\x3e\n\n\x3csnippet name\x3d"vsTerrain"\x3e\x3c![CDATA[\n  $vsprecisionf\n\n  uniform mat4 proj;\n  uniform mat4 view;\n  uniform vec3 origin;\n  uniform vec4 texOffsetAndScale;\n  uniform mat4 viewNormal;\n\n  attribute vec3 $position;\n  attribute vec2 $uv0;\n  varying vec2 vtc;\n  varying vec3 vpos;\n  varying vec3 vnormal;\n\n#ifdef RECEIVE_SHADOWS\n  varying float linearDepth;\n#endif\n\n#if defined(WIREFRAME) || defined(TILE_BORDERS)\n  varying vec2 vuv;\n#endif\n\n#ifdef ATMOSPHERE\n  uniform vec3 lightDirection;\n  varying vec3 wpos;\n  varying vec3 wview;\n  varying vec3 wnormal;\n  varying vec3 wlight;\n#endif\n\n#ifdef OVERLAY\n  // these variables combine two possible overlays into one by using a vec4:\n  // components x/y are x/y of overlay 0, and components z/w are x/y of overlay 1\n  uniform vec4 overlayTexOffset;\n  uniform vec4 overlayTexScale;\n  varying vec4 vtcOverlay;\n#endif\n\n#ifdef SCREEN_SIZE_PERSPECTIVE /* debug only */\n\n  uniform vec4 screenSizePerspective;\n\n  varying float screenSizeDistanceToCamera;\n  varying float screenSizeCosAngle;\n\n#endif\n\n$applySkirts\n\n  void main(void) {\n    vpos \x3d $position;\n\n#ifdef SPHERICAL\n    vnormal \x3d normalize(vpos + origin);\n#else\n    vnormal \x3d vec3(0, 0, 1); // WARNING: up-axis dependent code\n#endif\n\n  vec2 uv \x3d $uv0;\n  vpos \x3d applySkirts(uv, vpos, vnormal);\n\n#ifdef ATMOSPHERE\n    wpos \x3d (view * vec4(vpos, 1.0)).xyz;\n    wnormal \x3d (viewNormal * vec4(normalize(vpos+origin), 1.0)).xyz;\n    wlight \x3d (view  * vec4(lightDirection, 1.0)).xyz;\n#endif\n\n#if defined(WIREFRAME) || defined(TILE_BORDERS)\n    vuv \x3d uv;\n#endif\n\n#ifdef SCREEN_SIZE_PERSPECTIVE /* debug only */\n\n    vec3 viewPos \x3d (view * vec4(vpos, 1.0)).xyz;\n\n    screenSizeDistanceToCamera \x3d length(viewPos);\n\n    vec3 viewSpaceNormal \x3d (viewNormal * vec4(normalize(vpos + origin), 1.0)).xyz;\n    screenSizeCosAngle \x3d abs(viewSpaceNormal.z);\n\n#endif\n\n    gl_Position \x3d proj * view * vec4(vpos, 1.0);\n\n#ifdef RECEIVE_SHADOWS\n    // Shadowmap\'s cascading index used to be based on \'1.0 / gl_FragCoord.w\'\n    // (i.e. the perspective interpolation of \'gl_Position.w\'). Precision\n    // issues on iPad/iPhone with the \'w\' component require the depth to be\n    // passed as varying to properly drive the cascading shadow map index.\n    linearDepth \x3d gl_Position.w;\n#endif\n\n    vtc \x3d uv * texOffsetAndScale.zw + texOffsetAndScale.xy;\n\n#ifdef OVERLAY\n    vtcOverlay \x3d vec4(uv, uv) * overlayTexScale + overlayTexOffset;\n#endif\n  }\n]]\x3e\x3c/snippet\x3e\n\n\x3csnippet name\x3d"fsTerrainCommon"\x3e\x3c![CDATA[\n  uniform vec3 lightDirection;\n  uniform vec3 viewDirection;\n  uniform sampler2D depthTex;\n  uniform int shadowMapNum;\n  uniform vec4 shadowMapDistance;\n  uniform mat4 shadowMapMatrix[4];\n  uniform float depthHalfPixelSz;\n  uniform sampler2D ssaoTex;\n  uniform vec4 viewportPixelSz;\n  uniform sampler2D tex;\n  uniform float opacity;\n\n  varying vec3 vpos;\n  varying vec3 vnormal;\n  varying vec2 vtc;\n\n#if defined(WIREFRAME) || defined(TILE_BORDERS)\n  varying vec2 vuv;\n#endif\n\n#ifdef ATMOSPHERE\n  varying vec3 wpos;\n  varying vec3 wview;\n  varying vec3 wnormal;\n  varying vec3 wlight;\n#endif\n\n  $sceneLightingDefinitions\n\n#ifdef SCREEN_SIZE_PERSPECTIVE /* debug only */\n  $screenSizePerspective\n\n  uniform vec4 screenSizePerspective;\n\n  varying float screenSizeDistanceToCamera;\n  varying float screenSizeCosAngle;\n#endif\n\n  const vec3 ambient \x3d vec3(0.2,0.2,0.2);\n  const vec3 diffuse \x3d vec3(0.8,0.8,0.8);\n  const float diffuseHardness \x3d 2.5;\n\n#ifdef OVERLAY\n  uniform sampler2D overlay0Tex;\n  uniform sampler2D overlay1Tex;\n  uniform float overlayOpacity;\n  varying vec4 vtcOverlay;\n\n  $getOverlayColor\n#endif\n\n#ifdef RECEIVE_SHADOWS\n\tvarying float linearDepth;\n\t$evalShadow\n#endif\n\n  float lum(vec3 c) {\n    float max \x3d max(max(c.r, c.g), c.b);\n    float min \x3d min(min(c.r, c.g), c.b);\n    return (min + max) * 0.5;\n  }\n\n#ifdef ATMOSPHERE\n  vec3 atmosphere(vec3 lightPos, vec3 normal, vec3 view) {\n    vec3 surfaceColor   \x3d vec3(0.0);\n    vec3 fuzzySpecColor \x3d vec3(1.0);\n    vec3 subColor       \x3d vec3(0.0);\n    float rollOff       \x3d 1.0;\n\n    vec3 Ln \x3d normalize(lightPos);\n    vec3 Nn \x3d normalize(normal);\n    vec3 Hn \x3d normalize(view + Ln);\n\n    float ldn \x3d dot(Ln, Nn);\n    float diffComp \x3d max(0.0, ldn);\n    float vdn \x3d 1.0 - dot(view, Nn);\n    float ndv \x3d dot(view, Ln);\n\n    vec3 diffContrib \x3d surfaceColor * diffComp;\n    float subLamb \x3d max(0.0, smoothstep(-rollOff, 1.0, ldn) - smoothstep(0.0, 1.0, ldn));\n\n    vec3 subContrib \x3d subLamb * subColor;\n    vec3 vecColor \x3d vec3(vdn);\n\n    vec3 diffuseContrib \x3d (subContrib + diffContrib);\n    vec3 specularContrib \x3d (vecColor * fuzzySpecColor);\n\n    return (diffContrib + specularContrib) * rollOff;\n  }\n#endif\n\n  void main() {\n    vec3 a \x3d ambient;\n\n    float shadow \x3d 0.0;\n#ifdef RECEIVE_SHADOWS\n    shadow \x3d evalShadow(vpos, linearDepth, depthTex, shadowMapNum, shadowMapDistance, shadowMapMatrix, depthHalfPixelSz);\n#endif\n    float vndl \x3d dot(normalize(vnormal), lightDirection);\n    float k \x3d smoothstep(0.0, 1.0, clamp(vndl*diffuseHardness, 0.0, 1.0));\n    vec3 d \x3d (1.0 - shadow/1.8) * diffuse * k;\n\n    float ssao \x3d viewportPixelSz.w \x3c .0 ? 1.0 : texture2D(ssaoTex, (gl_FragCoord.xy - viewportPixelSz.xy) * viewportPixelSz.zw).a;\n    vec4 texCol \x3d texture2D(tex, vtc);\n\n#ifdef OVERLAY\n    vec4 overlayColor \x3d getOverlayColor(vtcOverlay, overlayOpacity);\n\n    // texCol and overlayTexCols have pre-multiplied alpha\n    texCol \x3d texCol * (1.0 - overlayColor.a) + overlayColor;\n#endif\n\n    vec3 atm \x3d vec3(0.0);\n#ifdef ATMOSPHERE\n    float ndotl \x3d max(0.0, min(1.0, vndl));\n    atm \x3d atmosphere(wlight, wnormal, -viewDirection);\n    atm *\x3d max(0.0, min(1.0, (1.0-lum(texCol.rgb)*1.5))); //avoid atmosphere on bright base maps\n    atm *\x3d max(0.0, min(1.0, ndotl*2.0)); // avoid atmosphere on dark side of the globe\n#endif\n\n    vec3 albedo \x3d atm + texCol.rgb;\n    vec3 normal \x3d normalize(vnormal);\n\n    // heuristic shading function used in the old terrain, now used to add ambient lighting\n    float additionalAmbientScale \x3d smoothstep(0.0, 1.0, clamp(vndl*2.5, 0.0, 1.0));\n\t\tvec3 additionalLight \x3d ssao * lightingMainIntensity * additionalAmbientScale * ambientBoostFactor * lightingGlobalFactor;\n\n    gl_FragColor \x3d vec4(evaluateSceneLighting(normal, albedo, shadow, 1.0 - ssao, additionalLight), texCol.a) * opacity;\n\n#ifdef SCREEN_SIZE_PERSPECTIVE /* debug only */\n    // This is only used for debug rendering the screenSize perspective\n\n    float perspectiveScale \x3d screenSizePerspectiveScaleFloat(1.0, screenSizeCosAngle, screenSizeDistanceToCamera, screenSizePerspective);\n\n    if (perspectiveScale \x3c\x3d 0.25) {\n      gl_FragColor \x3d mix(gl_FragColor, vec4(1, 0, 0, 1), perspectiveScale * 4.0);\n    }\n    else if (perspectiveScale \x3c\x3d 0.5) {\n      gl_FragColor \x3d mix(gl_FragColor, vec4(0, 0, 1, 1), (perspectiveScale - 0.25) * 4.0);\n    }\n    else if (perspectiveScale \x3e\x3d 0.99) {\n      gl_FragColor \x3d mix(gl_FragColor, vec4(0, 1, 0, 1), 0.2);\n    }\n    else {\n      gl_FragColor \x3d mix(gl_FragColor, vec4(1, 0, 1, 1), (perspectiveScale - 0.5) * 2.0);\n    }\n\n#endif\n\n  // closing } is missing here, it\'s in the shaders using this snippet below\n\n]]\x3e\x3c/snippet\x3e\n\n\x3csnippet name\x3d"fsTerrainWireframe"\x3e\x3c![CDATA[\n#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives : enable\n#endif\n\n  $fsprecisionf\n\n  struct WireframeSettings {\n    float width;\n    float falloff;\n    float subdivision;\n    vec4 color;\n    float wireOpacity;\n    float surfaceOpacity;\n  };\n\n  uniform WireframeSettings wireframe;\n\n    $fsTerrainCommon\n\n    vec2 vuvScaled \x3d vuv * wireframe.subdivision;\n    vec2 vuvMod \x3d fract(vuvScaled);\n\n#ifdef GL_OES_standard_derivatives\n    vec2 dVuv \x3d fwidth(vuvScaled);\n    dVuv \x3d max(vec2(0.00001), dVuv); // workaround against flickering skirts, see #10245\n#else\n    // Something that reasonably works\n    vec2 dVuv \x3d vec2(0.05);\n#endif\n\n    vec2 edgeFactors \x3d smoothstep((wireframe.width - wireframe.falloff) * dVuv,\n                                  wireframe.width * dVuv, min(vuvMod, 1.0 - vuvMod));\n\n    float edgeFactor \x3d 1.0 - min(edgeFactors.x, edgeFactors.y);\n\n#ifdef WIREFRAME\n    gl_FragColor \x3d vec4(mix(gl_FragColor.rgb, wireframe.color.rgb, edgeFactor * wireframe.color.a),\n                        mix(wireframe.surfaceOpacity, wireframe.wireOpacity, edgeFactor));\n#endif\n\n\n#ifdef TILE_BORDERS\n    dVuv \x3d fwidth(vuv);\n    edgeFactors \x3d smoothstep((wireframe.width - wireframe.falloff) * dVuv,\n                              wireframe.width * dVuv, min(vuv, 1.0 - vuv));\n    edgeFactor \x3d 1.0 - min(edgeFactors.x, edgeFactors.y);\n\n    gl_FragColor \x3d mix(gl_FragColor, vec4(1.0, 0.0, 0.0, 1.0), edgeFactor);\n#endif\n  }\n]]\x3e\x3c/snippet\x3e\n\n\x3csnippet name\x3d"fsTerrain"\x3e\x3c![CDATA[\n    $fsprecisionf\n    $fsTerrainCommon\n  }\n]]\x3e\x3c/snippet\x3e\n\n\x3csnippet name\x3d"vsTerrainNormal"\x3e\x3c![CDATA[\n  $vsprecisionf\n\n  uniform vec3 origin;\n  uniform mat4 proj;\n  uniform mat4 view;\n  uniform mat4 viewNormal;\n  attribute vec3 $position;\n  attribute vec2 $uv0;\n  varying vec3 vnormal;\n\n$applySkirts\n\n  void main(void) {\n#ifdef SPHERICAL\n    vec4 normal \x3d vec4(normalize($position + origin), 1.0);\n#else\n    vec4 normal \x3d vec4(0.0, 0.0, 1.0, 1.0);\n#endif\n\n    vec2 uv \x3d $uv0;\n    vec3 vpos \x3d applySkirts(uv, $position, normal.xyz);\n\n    gl_Position \x3d proj * view * vec4(vpos, 1.0);\n    vnormal \x3d normalize((viewNormal * normal).xyz);\n  }\n]]\x3e\x3c/snippet\x3e\n\n\x3csnippet name\x3d"vsTerrainDepth"\x3e\x3c![CDATA[\n  $vsprecisionf\n\n  uniform vec3 origin;\n  uniform mat4 proj;\n  uniform mat4 view;\n  uniform vec2 nearFar;\n  attribute vec3 $position;\n  attribute vec2 $uv0;\n  varying float depth;\n\n$applySkirts\n\n  void main(void) {\n#ifdef SPHERICAL\n    vec3 normal \x3d normalize($position + origin);\n#else\n    vec3 normal \x3d vec3(0.0, 0.0, 1.0);\n#endif\n\n    vec2 uv \x3d $uv0;\n    vec3 vpos \x3d applySkirts(uv, $position, normal.xyz);\n\n    vec4 eye \x3d view * vec4(vpos, 1.0);\n    gl_Position \x3d proj * eye;\n    depth \x3d (-eye.z - nearFar[0]) / (nearFar[1] - nearFar[0]) ;\n  }\n]]\x3e\x3c/snippet\x3e\n\n\x3csnippet name\x3d"vsTerrainHighlight"\x3e\x3c![CDATA[\n  $vsprecisionf\n\n  uniform vec3 origin;\n  uniform mat4 proj;\n  uniform mat4 view;\n  uniform vec4 overlayTexScale;\n  uniform vec4 overlayTexOffset;\n\n  attribute vec3 $position;\n  attribute vec2 $uv0;\n\n  varying vec4 vtcOverlay;\n\n$applySkirts\n\n  void main() {\n    #ifdef SPHERICAL\n      vec3 vnormal \x3d normalize($position + origin);\n    #else\n      vec3 vnormal \x3d vec3(0, 0, 1); // WARNING: up-axis dependent code\n    #endif\n\n    vec2 uv \x3d $uv0;\n    vec3 vpos \x3d applySkirts(uv, $position, vnormal);\n\n    vtcOverlay \x3d vec4(uv, uv) * overlayTexScale + overlayTexOffset;\n\n    gl_Position \x3d proj * view * vec4(vpos, 1.0);\n  }\n]]\x3e\x3c/snippet\x3e\n\n\x3csnippet name\x3d"fsTerrainHighlight"\x3e\x3c![CDATA[\n  $fsprecisionf\n\n  uniform sampler2D overlay0Tex;\n  uniform sampler2D overlay1Tex;\n  uniform float overlayOpacity;\n\n  uniform sampler2D depthTex;\n  uniform vec4 highlightViewportPixelSz;\n\n  varying vec4 vtcOverlay;\n\n  $getOverlayColor\n\n  void main() {\n    vec4 overlayColor \x3d getOverlayColor(vtcOverlay, overlayOpacity);\n\n    if (overlayColor.a \x3d\x3d 0.0) {\n      // Here we have to write black, instead of discarding the fragment in order to overwrite\n      // the highlights which might have been written by skirts of other tiles.\n      // As a consequence skirts are not visible, but terrain overwrites draped highlights.\n      gl_FragColor \x3d vec4(0,0,0,0);\n      return;\n    }\n\n    $highlightWrite\n  }\n]]\x3e\x3c/snippet\x3e\n\n\x3c/snippets\x3e\n'}});
define("require exports ../../../core/tsSupport/extendsHelper dojo/text!./TerrainMaterial.xml ../../../Color ../../../core/ObjectPool ../../../core/PooledArray ../../../core/promiseUtils ../../../geometry/support/aaBoundingBox ../lib/glMatrix ../support/imageUtils ./ResourceCounter ./TerrainConst ./TileGeometryFactory ./TileRenderData ./TileRenderer ./tileUtils ../webgl-engine/lib/DefaultVertexAttributeLocations ../webgl-engine/lib/DefaultVertexBufferLayouts ../webgl-engine/lib/glUtil3D ../webgl-engine/lib/RenderPass ../webgl-engine/lib/RenderSlot ../webgl-engine/lib/screenSizePerspectiveUtils ../webgl-engine/lib/ShaderVariations ../webgl-engine/lib/tracer ../webgl-engine/lib/Util ../webgl-engine/materials/internal/MaterialUtil ../../webgl/BufferObject ../../webgl/Util ../../webgl/VertexArrayObject".split(" "),
function(J,ra,sa,V,W,K,A,D,E,k,X,Y,L,Z,aa,ba,x,ca,da,ea,n,M,fa,B,F,ga,y,N,O,ha){function P(b){return function(a,c){a=a.screenDepth;c=c.screenDepth;return a<c?-b:a>c?b:0}}function ia(b){var a=P(b);return function(c,f){return 0===c.tiles.length?-b:0===f.tiles.length?b:a(c.tiles.data[0],f.tiles.data[0])}}var ja=ga.assert,ka=k.mat4d.identity(),Q=M.OPAQUE_TERRAIN,R=M.TRANSPARENT_TERRAIN,S=k.vec3d.create(),G=k.vec2d.create(),H=E.create(),r=k.vec4d.create(),z=k.vec4d.create(),T=k.vec4d.create(),la=function(){return function(){this.extent=
k.vec4d.create();this.maxLevel=this.minLevel=0;this.callback=null}}();J=function(){function b(a,c){this.initialized=!1;this.rctx=null;this.renderDataPool=new K(aa.TileRenderData);this.perOriginTileData=new A(10,function(){return{root:null,origin:null,tiles:new A(300)}});this.perOriginTileDataDirty=!0;this.tileIterator=new x.IteratorPreorder;this.highestVisibleLODTile=null;this.visible=!0;this.debugScreenSizePerspective=!1;this.wireframe=y.copyParameters(ma);this._skirtScale=this._opacity=1;this._cullBackFaces=
this._disableRendering=this._drawBorders=!1;this._renderOrder=1;this._velvetOverground=!0;this._hasOverlays=!1;this.castShadows=!0;this.receiveShadows=!1;this.backgroundPromise=this.tileRenderer=this.emptyTex=null;this.tileBackgroundInitialized=!1;this.stencilEnabledLayerExtents=[];this.numOriginsRendered=this.numTilesCulled=this.numTilesRendered=this.numTrianglesRendered=0;this.resourceCounter=new Y;this.loaded=this.clippingExtent=null;this._loaded=!1;this.needsRender=!0;this.needsHighlight=this.didRender=
!1;this.visibleScaleRangeQueries=new A(10);this.visibleScaleRangeQueriesInvPtr=0;this.visibleScaleRangeQueryQueue=new A(30);this.visibleScaleRangeQueryPool=new K(la,!1);this.manifold=a;this.tileSize=c||256}b.prototype.destroy=function(a){this.uninstall(a);this.backgroundPromise&&(this.backgroundPromise.cancel(),this.backgroundPromise=null)};b.prototype.install=function(a){a.addExternalRenderer([Q,R],this);this.drapedRenderer=a.getDrapedTextureRenderer()};b.prototype.uninstall=function(a){a.removeExternalRenderer(this)};
Object.defineProperty(b.prototype,"disableRendering",{set:function(a){this._disableRendering=!!a;this.setNeedsRender()},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"opacity",{set:function(a){this._opacity=a;this.setNeedsRender()},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"skirtScale",{set:function(a){this._skirtScale=a;this.setNeedsRender()},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"drawBorders",{set:function(a){this._drawBorders!==
a&&(this._drawBorders=a,this._updatePrograms())},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"cullBackFaces",{set:function(a){this._cullBackFaces=a;this.setNeedsRender()},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"renderOrder",{set:function(a){this._renderOrder=a;this.setNeedsRender()},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"velvetOverground",{set:function(a){this._velvetOverground!==a&&(this._velvetOverground=a,this._updatePrograms())},
enumerable:!0,configurable:!0});b.prototype.setRootTiles=function(a){this.rootTiles=a;this.setNeedsRender()};b.prototype.setNeedsHighlight=function(a){this.needsHighlight=a;this.setNeedsRender()};b.prototype.setStencilEnabledLayerExtents=function(a){this.stencilEnabledLayerExtents=a;this.setNeedsRender()};b.prototype.setTileSize=function(a){this.tileSize=a;this.tileRenderer&&(this.tileRenderer.tileSize=a);this.setNeedsRender()};b.prototype.loadTile=function(a){ja(null===a.renderData);a.renderData=
this.renderDataPool.acquire();a.renderData.init();var c=this.getLocalOriginOfTile(a);a.createGeometry(a.renderData.updateGeometryState(a),c,"debug"===this.wireframe.mode,a.renderData.geometryInfo);a.renderData.localOrigin=c;this._updateTileGeometryBuffers(a);this.tileBackgroundInitialized&&this.tileRenderer.updateTileTexture(a)};b.prototype.queryVisibleLevelRange=function(a,c,f,d){var e=this.visibleScaleRangeQueryPool.acquire();k.vec4d.set(a,e.extent);e.minLevel=c?c:-Number.MAX_VALUE;e.maxLevel=null!=
f?f:Number.MAX_VALUE;e.callback=d;this.visibleScaleRangeQueryQueue.push(e);this.setNeedsRender()};b.prototype.updateTileTexture=function(a){this.tileRenderer&&this.tileBackgroundInitialized&&this.tileRenderer.updateTileTexture(a)};b.prototype.updateTileGeometryNeedsUpdate=function(a){return a.renderData.updateGeometryState(a).needsUpdate};b.prototype._updateTileGeometry=function(a){for(var c=a.renderData.geometryState,f=a.layerInfo[L.LayerClass.ELEVATION],d=0;d<f.length;d++)f[d].pendingUpdates&=~L.TileUpdateTypes.UPDATE_GEOMETRY;
return c.needsUpdate?(a.renderData.vao&&this._releaseTileGeometry(a),a.createGeometry(c,a.renderData.localOrigin,"debug"===this.wireframe.mode,a.renderData.geometryInfo),this._updateTileGeometryBuffers(a),!0):!1};b.prototype.updateTileGeometry=function(a){a.renderData.updateGeometryState(a);return this._updateTileGeometry(a)};b.prototype.unloadTile=function(a){this._releaseTileGeometry(a);a.renderData.texture&&a.renderData.texture.dispose();this.renderDataPool.release(a.renderData);a.renderData=null};
b.prototype.getLocalOriginOfTile=function(a){if(10<=a.lij[0]){for(;7<a.lij[0];)a=a.parent;return a.centerAtSeaLevel}if("spherical"===this.manifold)return S;for(;a.parent;)a=a.parent;return a.centerAtSeaLevel};b.prototype.setVisibility=function(a){this.visible=a;this.setNeedsRender()};b.prototype.getStats=function(){return{numTilesRendered:this.numTilesRendered,numTilesCulled:this.numTilesCulled,numTrianglesRendered:this.numTrianglesRendered,numOriginsRendered:this.numOriginsRendered}};b.prototype.getWireframeEnabled=
function(){return"shader"===this.wireframe.mode};b.prototype.setDebugScreenSizePerspective=function(a){a!==this.debugScreenSizePerspective&&(this.debugScreenSizePerspective=a,this._updatePrograms())};b.prototype.setWireframe=function(a){var c=this;if(!1===a||!0===a)a={mode:a?"shader":"none"};var f=this.wireframe;if(void 0!==a.mode&&f.mode!==a.mode){var d="debug"===f.mode,e="debug"===a.mode;f.mode=a.mode;this._updatePrograms();d!==e&&this.rootTiles&&x.traverseTilesPreorder(this.rootTiles,function(a){a.renderData&&
(a.renderData.vao&&c._releaseTileGeometry(a),a.createGeometry(a.renderData.updateGeometryState(a),a.renderData.localOrigin,e,a.renderData.geometryInfo),c._updateTileGeometryBuffers(a))})}for(var b in a)f.hasOwnProperty(b)&&(f[b]=a[b]),this.setNeedsRender();f.resolution&&(f.resolution=Math.min(f.resolution,this.tileSize),f.resolution=1<<Math.round(Math.log(f.resolution)/Math.LN2))};b.prototype.setNeedsRender=function(){this.needsRender=!0;this.didRender=!1;this.perOriginTileDataDirty=!0};b.prototype.resetNeedsRender=
function(){this.didRender&&(this.needsRender=0!==this.visibleScaleRangeQueryQueue.length,this.didRender=!1)};b.prototype.isTransparent=function(){var a=this.wireframe;return 1>this._opacity||"shader"===a.mode&&(1>a.wireOpacity||1>a.surfaceOpacity)};b.prototype.updateTileBackground=function(a){this.backgroundPromise&&this.backgroundPromise.cancel();this.backgroundPromise="string"===typeof a?X.requestImage(a).catch(function(){return null}):null!=a?D.resolve(W.toUnitRGBA(a)):D.resolve(null);this._renderTileBackground()};
b.prototype.initializeRenderContext=function(a){var c=this,f=this.rctx=a.rctx,d=function(a){D.when(a).then(function(){c.initialized=!0;c.setNeedsRender()}).catch(d)};d(this._renderTileBackground());var e=a.shaderSnippets;a=a.programRep;e.vsTerrain||e._parse(V);var b=new B("terrain",["vsTerrain","fsTerrain"],null,a,e,f);b.addDefine("Spherical","SPHERICAL");b.addDefine("Overlay","OVERLAY");b.addDefine("Atmosphere","ATMOSPHERE");b.addDefine("Wireframe","WIREFRAME");b.addDefine("TileBorders","TILE_BORDERS");
b.addBinaryShaderSnippetSuffix("Wireframe","Wireframe",[!1,!0]);b.addDefine("ReceiveShadows","RECEIVE_SHADOWS");b.addDefine("ScreenSizePerspective","SCREEN_SIZE_PERSPECTIVE");var l=new B("terrainNormal",["vsTerrainNormal","fsNormal"],null,a,e,f);l.addDefine("Spherical","SPHERICAL");l.addDefine("AlphaZero","ALPHA_ZERO");var g=new B("terrainDepth",["vsTerrainDepth","fsDepth"],null,a,e,f);g.addDefine("Spherical","SPHERICAL");g.addDefine("ShadowMap","BIAS_SHADOWMAP");e=new B("terrainHighlight",["vsTerrainHighlight",
"fsTerrainHighlight"],null,a,e,f);e.addDefine("Spherical","SPHERICAL");this.programs={color:null,normal:null,depth:null,depthShadowMap:null,highlight:null};this.programVariations={color:b,normal:l,depth:g,highlight:e};this._updatePrograms();this.tileRenderer=new ba(f,this.tileSize,a,this.resourceCounter,this.setNeedsRender.bind(this));this._renderTileBackground();this.emptyTex=ea.createEmptyTexture(f)};b.prototype.uninitializeRenderContext=function(a){null!=this.emptyTex&&(this.emptyTex.dispose(),
this.emptyTex=null);this.tileRenderer&&(this.tileRenderer.dispose(),this.tileRenderer=null)};b.prototype.render=function(a){var c=a.rctx,f=c.gl;if(this.initialized&&!this._disableRendering&&this.visible&&this.rootTiles&&this.tileBackgroundInitialized){var d=this.isTransparent()?R:Q;if(a.slot===d){F.trace("# BEGIN RENDER TERRAIN");d=a.pass;c.setFaceCullingEnabled(this._cullBackFaces);var e=1===a.lightingData.helper.globalFactor;d===n.MATERIAL?this._renderMaterialPass(a,this._updatePerOriginTileData()):
d===n.MATERIAL_DEPTH_SHADOWMAP&&this.castShadows&&e?this._renderDepthPass(a,this.programs.depthShadowMap,this._updatePerOriginTileData()):d===n.MATERIAL_DEPTH?this._renderDepthPass(a,this.programs.depth,this._updatePerOriginTileData()):d===n.MATERIAL_NORMAL?this._renderNormalPass(a,this._updatePerOriginTileData()):d===n.MATERIAL_HIGHLIGHT&&this.needsHighlight&&(this._renderHighlightPass(a,this._updatePerOriginTileData()),c.clear(f.DEPTH_BUFFER_BIT));this._cullBackFaces&&c.setFaceCullingEnabled(!1);
F.trace("# END RENDER TERRAIN");return!0}}};b.prototype.intersect=function(a,c,f,d){if(this.rootTiles){var e=this.clippingExtent;if((!a.isSelection||!this.isTransparent())&&a.enableTerrain){var b=na,l=oa;k.vec3d.subtract(f,c,b);k.vec3d.set3(1/b[0],1/b[1],1/b[2],l);var g=a.getMinResult(),C=a.getMaxResult(),p=this.tileIterator;p.reset(this.rootTiles);d=function(){var d=p.next();if(null===d.renderData)return"continue";if(a.enableInvisibleTerrain){if(!d.visible&&e&&!d.intersectsExtent(e))return"continue"}else if(!d.visible)return"continue";
var h=d.renderData,m=h.geometryInfo,q=h.localOrigin,u=pa,n=qa;k.vec3d.subtract(c,q,u);k.vec3d.subtract(f,q,n);var w=-U._skirtScale*h.geometryInfo.skirtLength;0!==w&&(h=d.tileUp,E.offset(m.boundingBox,w*h[0],w*h[1],w*h[2],H),E.expandWithBuffer(H,m.boundingBox,0,2));if(!y.intersectAabbInvDir(0!==w?H:m.boundingBox,u,l,a.tolerance))return"continue";var h=function(c,f,e){if(0<=c&&(a.enableBackfacesTerrain||0>k.vec3d.dot(f,b))){e=void 0;if(void 0===g.dist||c<g.dist)e=x.lij2str(d.lij[0],d.lij[1],d.lij[2]),
g.set(void 0,e,c,f,void 0),g.setIntersector("terrain");if(void 0===C.dist||c>C.dist)e=x.lij2str(d.lij[0],d.lij[1],d.lij[2]),C.set(void 0,e,c,f,void 0),C.setIntersector("terrain")}},q=m.indices,r={data:m.vertexAttributes,size:3,offsetIdx:0,strideIdx:5},m=m.numWithoutSkirtIndices/3;y.intersectTriangles(u,n,0,m,q,r,null,h);0!==w&&x.intersectSkirts(u,n,m,q.length/3,q,r,null,"spherical"===U.manifold?function(a){return k.vec3d.scale(a,w/k.vec3d.length(a))}:function(a){return k.vec3d.set3(0,0,w,a)},h)};
for(var U=this;!p.done;)d()}}};b.prototype._renderTileBackground=function(){var a=this;if(this.rctx&&this.backgroundPromise&&this.tileRenderer)return this.backgroundPromise.then(function(c){a.tileRenderer&&(a.tileBackgroundInitialized=!0,a.tileRenderer.setBackground(c),a.rootTiles&&x.traverseTilesPreorder(a.rootTiles,function(c){a.tileRenderer.updateTileTexture(c)}))})};b.prototype._updatePrograms=function(){var a="spherical"===this.manifold,c="shader"===this.wireframe.mode;this.programs.color=this.programVariations.color.getProgram([a,
this._hasOverlays,a&&this._velvetOverground,c,this._drawBorders,c||this._drawBorders,this.receiveShadows,this.debugScreenSizePerspective]);this.programs.normal=this.programVariations.normal.getProgram([a,!0]);this.programs.depth=this.programVariations.depth.getProgram([a,!1]);this.programs.depthShadowMap=this.programVariations.depth.getProgram([a,!0]);this.programs.highlight=this.programVariations.highlight.getProgram([a]);this.setNeedsRender()};b.prototype._renderMaterialPass=function(a,c){var f=
this,d=this.isTransparent(),e=a.shadowMap&&a.shadowMap.getEnableState(),b=a.rctx;this.receiveShadows!==e&&(this.receiveShadows=e,this._updatePrograms());e=!this.drapedRenderer.isEmpty();e!==this._hasOverlays&&(this._hasOverlays=e,this._updatePrograms());e=a.camera;b.setDepthTestEnabled(!0);var l=this.wireframe,g=this.programs.color;b.bindProgram(g);g.setUniform1f("opacity",this._opacity);if("shader"===l.mode||this._drawBorders)g.setUniform1f("wireframe.width",this.wireframe.width),g.setUniform1f("wireframe.falloff",
Math.min(l.width,l.falloff)),g.setUniform1f("wireframe.wireOpacity",l.wireOpacity*this._opacity),g.setUniform1f("wireframe.surfaceOpacity",l.surfaceOpacity*this._opacity),g.setUniform4fv("wireframe.color",l.color);a.shadowMap&&a.shadowMap.bind(g);a.ssaoHelper&&a.ssaoHelper.setUniforms(g);g.setUniform1i("tex",0);g.setUniform1i("overlay0Tex",1);g.setUniform1i("overlay1Tex",2);g.setUniformMatrix4fv("viewNormal",e.viewInverseTransposeMatrix);g.setUniformMatrix4fv("proj",e.projectionMatrix);a.lightingData.helper.setUniforms(g,
!0);b=e.viewMatrix;k.vec3d.set3(b[12],b[13],b[14],I);k.vec3d.normalize(I);g.setUniform3fv("viewDirection",I);this.numOriginsRendered=this.numTrianglesRendered=this.numTilesCulled=this.numTilesRendered=0;this._prepareScaleRangeQueries();d?a.offscreenRenderingHelper.renderSeparateAndComposite(function(){return f._renderTiles(a,g,c)},[0,0,0,0],"alpha"):this._renderTiles(a,g,c);this._processScaleRangeQueries();0<this.numTilesRendered&&!this._loaded&&(this._loaded=!0,this.loaded&&this.loaded())};b.prototype._renderDepthPass=
function(a,c,b){var d=a.rctx,f=a.camera;d.bindProgram(c);d.setBlendingEnabled(!1);d.setDepthTestEnabled(!0);c.setUniformMatrix4fv("model",ka);c.setUniformMatrix4fv("viewNormal",f.viewInverseTransposeMatrix);G[0]=f.near;G[1]=f.far;c.setUniform2fv("nearFar",G);this._renderTilesAuxiliary(a,c,b,!1)};b.prototype._renderNormalPass=function(a,c){var b=a.rctx,d=a.camera,e=this.programs.normal;b.bindProgram(e);b.setBlendingEnabled(!1);b.setDepthTestEnabled(!0);e.setUniformMatrix4fv("viewNormal",d.viewInverseTransposeMatrix);
this._renderTilesAuxiliary(a,e,c,!1)};b.prototype._renderHighlightPass=function(a,c){var b=a.rctx,d=this.programs.highlight;b.bindProgram(d);b.setBlendingEnabled(!1);b.setDepthTestEnabled(!0);var e=a.offscreenRenderingHelper;b.bindTexture(e.getDepthTexture(),3);d.setUniform1i("depthTex",3);d.setUniform4f("highlightViewportPixelSz",0,0,1/e.width,1/e.height);this._renderTilesAuxiliary(a,d,c,!0)};b.prototype._updatePerOriginTileData=function(){var a=this.perOriginTileData;if(!this.perOriginTileDataDirty)return a;
this.highestVisibleLODTile=null;this._renderCollectOrigins();if(0!==this._renderOrder){for(var c=P(this._renderOrder),b=0;b<a.length;b++)this._sortFrontToBack(a.data[b].tiles,c);c=ia(this._renderOrder);this._sortFrontToBack(a,c)}this.perOriginTileDataDirty=!1;return a};b.prototype._renderCollectOrigins=function(){var a=this.perOriginTileData,c=this.rootTiles,b="spherical"===this.manifold;a.clear();for(var d=0;d<c.length;d++){var e=c[d],h=a.pushNew();h.root=e;h.origin=b?S:e.centerAtSeaLevel;h.tiles.clear();
this._renderCollectOriginsForRoot(h)}return!0};b.prototype._renderCollectOriginsForRoot=function(a){var c=this.tileIterator,b=this.perOriginTileData;for(c.reset(a.root);!c.done;){var d=c.next(),e=d.renderData;if(e&&!d.visible)this.numTilesCulled++,c.skip();else{var h=b.back();if(7===d.lij[0]){if(h===a||0!==h.tiles.length)h=b.pushNew(),h.tiles.clear();h.root=d;h.origin=d.centerAtSeaLevel}if(e){10<=d.lij[0]?b.back().tiles.push(d):a.tiles.push(d);if(!this.highestVisibleLODTile||d.vlevel>this.highestVisibleLODTile.vlevel)this.highestVisibleLODTile=
d;c.skip()}}}};b.prototype._sortFrontToBack=function(a,c){a.sort(c)};b.prototype._scaleQueriesForTile=function(a){var c=a.extent;a=a.lij[0];for(var b=0;b<this.visibleScaleRangeQueriesInvPtr;){var d=this.visibleScaleRangeQueries.data[b],e=d.extent;a>=d.minLevel&&a<=d.maxLevel&&e[0]<=c[2]&&e[2]>=c[0]&&e[1]<=c[3]&&e[3]>=c[1]?(this.visibleScaleRangeQueries.swap(b,this.visibleScaleRangeQueriesInvPtr-1),this.visibleScaleRangeQueriesInvPtr--):b++}};b.prototype._updateStencilReadStateForTile=function(a,b){if(a.stencilRenderingHelper&&
a.stencilRenderingHelper.getEnableState()){for(var c=this.stencilEnabledLayerExtents,d=!1,e=0;e<c.length;e++)if(b.intersectsExtent(c[e])){d=!0;break}d?a.stencilRenderingHelper.enableStencilRead():a.stencilRenderingHelper.disableStencilRead()}};b.prototype._renderTilesAuxiliary=function(a,b,f,d){var c=a.rctx,h=c.gl,l=a.camera,g=l.viewMatrix;b.setUniformMatrix4fv("proj",l.projectionMatrix);b.setUniform1f("skirtScale",this._skirtScale);d&&(b.setUniform1i("overlay0Tex",1),b.setUniform1i("overlay1Tex",
2));for(l=0;l<f.length;l++){var k=f.data[l];b.setUniform3fv("origin",k.origin);y.bindView(k.origin,g,b);for(var p=0;p<k.tiles.length;p++){var n=k.tiles.data[p],t=n.renderData;d&&(this._bindOverlayTextures(b,t.overlays,!0),b.setUniform1f("overlayOpacity",t.overlayOpacity));this._updateStencilReadStateForTile(a,n);c.bindVAO(t.vao);O.assertCompatibleVertexAttributeLocations(t.vao,b);c.drawElements(h.TRIANGLES,0!==this._skirtScale?t.vao.indexBuffer.size:t.geometryInfo.numWithoutSkirtIndices,t.vao.indexBuffer.indexType,
0)}}c.bindVAO(null);a.stencilRenderingHelper&&a.stencilRenderingHelper.disableStencilRead()};b.prototype._renderTiles=function(a,b,f){var c=a.rctx,e=c.gl,h=a.camera,l=h.viewMatrix;if(this.debugScreenSizePerspective&&this.pointsOfInterest){var g=fa.getSettings("spherical"===this.manifold?"global":"local");g.update({distance:this.pointsOfInterest.centerOnSurfaceFrequent.distance,fovY:h.fovY});y.bindScreenSizePerspective(g,b,"screenSizePerspective")}b.setUniform1f("skirtScale",this._skirtScale);for(h=
0;h<f.length;h++)if(g=f.data[h],b.setUniform3fv("origin",g.origin),y.bindView(g.origin,l,b),a.shadowMap&&a.shadowMap.bindView(b,g.origin),this.numOriginsRendered++,g=g.tiles,0!==g.length){var n="debug"===this.wireframe.mode?e.LINES:e.TRIANGLES,p=this.highestVisibleLODTile,r=void 0,t=void 0;p?(r=p.vlevel,t=this.tileSize/this.wireframe.resolution):(r=16,t=this.tileSize/64);for(p=0;p<g.length;p++){var v=g.data[p],m=v.renderData;this._updateStencilReadStateForTile(a,v);F.trace("# RENDER TILE "+v.lij[0]+
"/"+v.lij[1]+"/"+v.lij[2]+", screenDepth:"+v.screenDepth);var q=m.geometryInfo.uvOffsetAndScale,u=m.texOffsetAndScale;k.vec4d.set4(q[0]*u[2]+u[0],q[1]*u[3]+u[1],q[2]*u[2],q[3]*u[3],T);b.setUniform4fv("texOffsetAndScale",T);c.bindTexture(m.textureReference||m.texture,0);this._bindOverlayTextures(b,m.overlays,!1);b.setUniform1f("overlayOpacity",m.overlayOpacity);("shader"===this.wireframe.mode||this._drawBorders)&&b.setUniform1f("wireframe.subdivision",t*(1<<r-v.vlevel));q=0!==this._skirtScale?m.vao.indexBuffer.size:
m.geometryInfo.numWithoutSkirtIndices;c.bindVAO(m.vao);O.assertCompatibleVertexAttributeLocations(m.vao,b);c.drawElements(n,q,m.vao.indexBuffer.indexType,0);v.renderOrder=this.numTilesRendered;this.numTilesRendered++;this.numTrianglesRendered+=q/3;this._scaleQueriesForTile(v)}}c.bindVAO(null);a.stencilRenderingHelper&&a.stencilRenderingHelper.disableStencilRead()};b.prototype._bindOverlayTextures=function(a,b,f){for(var c=0;2>c;c++){var e=2*c,h=b[c],k=f?h.highlightRenderTargetId:h.renderTargetId;
k?(k=this.drapedRenderer.getRenderTargetTexture(k),r[e]=h.texOffset[0],r[e+1]=h.texOffset[1],z[e]=h.texScale[0],z[e+1]=h.texScale[1],this.rctx.bindTexture(k,1+c)):(r[e]=0,r[e+1]=0,z[e]=0,z[e+1]=0,this.rctx.bindTexture(this.emptyTex,1+c))}a.setUniform4fv("overlayTexOffset",r);a.setUniform4fv("overlayTexScale",z)};b.prototype._updateTileGeometryBuffers=function(a){var b=this.rctx,f=b.gl;a=a.renderData;var d=a.geometryInfo.indices;a.vao=new ha(b,ca.Default3D,{geometry:da.Pos3Tex},{geometry:N.createVertex(b,
f.STATIC_DRAW,a.geometryInfo.vertexAttributes)},N.createIndex(b,f.STATIC_DRAW,d));this.setNeedsRender()};b.prototype._releaseTileGeometry=function(a){a=a.renderData;a.vao.dispose(!0);a.vao=null;Z.releaseGeometry(a.geometryInfo);this.setNeedsRender()};b.prototype._prepareScaleRangeQueries=function(){for(var a=this.visibleScaleRangeQueries,b=this.visibleScaleRangeQueryQueue;a.length<a.data.length&&0<b.length;){var f=b.pop();a.push(f)}this.visibleScaleRangeQueriesInvPtr=a.length};b.prototype._processScaleRangeQueries=
function(){for(var a=this.visibleScaleRangeQueries,b=this.visibleScaleRangeQueryPool,f=0;f<a.length;f++){var d=a.data[f];b.release(d);d.callback(f>=this.visibleScaleRangeQueriesInvPtr);d.callback=null}a.clear()};return b}();var ma={mode:"none",width:1.5,falloff:1.5,wireOpacity:1,surfaceOpacity:0,color:[1,1,1,0],resolution:64},I=k.vec3d.create(),na=k.vec3d.create(),oa=k.vec3d.create(),pa=k.vec3d.create(),qa=k.vec3d.create();return J});