@arcgis/core 5.1.0-next.56 → 5.1.0-next.58

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.
Files changed (46) hide show
  1. package/applications/Components/SelectionOperation.d.ts +2 -2
  2. package/assets/esri/core/workers/RemoteClient.js +1 -1
  3. package/assets/esri/core/workers/chunks/{278eecd729bed2832702.js → 45b7266580f9ce4fab6c.js} +1 -1
  4. package/assets/esri/core/workers/chunks/{992e74570b76f3f9e52e.js → 666e1e79fcb309b0b9b1.js} +1 -1
  5. package/assets/esri/core/workers/chunks/{4afddb66242438b38df0.js → 6c571008bee8376ea50a.js} +1 -1
  6. package/assets/esri/core/workers/chunks/{ea068f75397c3b3337ec.js → 92fb6519b01d110ee947.js} +136 -129
  7. package/chunks/ScreenSpaceShadowHighlight.glsl.js +6 -0
  8. package/chunks/ShadowCastAccumulate.glsl.js +1 -1
  9. package/chunks/ShadowHighlight.glsl.js +15 -8
  10. package/config.js +1 -1
  11. package/kernel.js +1 -1
  12. package/networks/support/jsonTypes.d.ts +6 -0
  13. package/package.json +1 -1
  14. package/rest/networks/support/FunctionResult.d.ts +6 -0
  15. package/rest/networks/support/FunctionResult.js +1 -1
  16. package/support/revision.js +1 -1
  17. package/views/2d/engine/webgl/shaders/sources/shaderRepository.js +1 -1
  18. package/views/3d/terrain/TerrainRenderer.js +1 -1
  19. package/views/3d/terrain/TerrainSurface.js +1 -1
  20. package/views/3d/webgl/RenderNode.js +1 -1
  21. package/views/3d/webgl-engine/collections/Component/Material/ComponentMaterial.js +1 -1
  22. package/views/3d/webgl-engine/collections/Component/Material/ComponentTechniqueConfiguration.js +1 -1
  23. package/views/3d/webgl-engine/core/shaderLibrary/shading/EvaluateSceneLighting.glsl.js +28 -50
  24. package/views/3d/webgl-engine/core/shaderLibrary/shading/PhysicallyBasedRendering.glsl.js +46 -22
  25. package/views/3d/webgl-engine/core/shaderLibrary/shading/ReadShadowMap.glsl.js +18 -13
  26. package/views/3d/webgl-engine/effects/highlight/ScreenSpaceShadowHighlight.glsl.js +2 -0
  27. package/views/3d/webgl-engine/effects/highlight/ScreenSpaceShadowHighlightRenderNode.js +2 -0
  28. package/views/3d/webgl-engine/effects/highlight/ScreenSpaceShadowHighlightTechnique.js +2 -0
  29. package/views/3d/webgl-engine/effects/highlight/ShadowHighlight.js +1 -1
  30. package/views/3d/webgl-engine/effects/laserlines/LaserLineRenderer.js +1 -1
  31. package/views/3d/webgl-engine/lib/BindParameters.js +1 -1
  32. package/views/3d/webgl-engine/lib/Renderer.js +1 -1
  33. package/views/3d/webgl-engine/materials/DefaultMaterial.js +1 -1
  34. package/views/3d/webgl-engine/materials/PathMaterial.js +1 -1
  35. package/views/3d/webgl-engine/materials/PathTechniqueConfiguration.js +1 -1
  36. package/views/3d/webgl-engine/materials/WaterMaterial.js +1 -1
  37. package/views/3d/webgl-engine/materials/WaterTechniqueConfiguration.js +1 -1
  38. package/views/3d/webgl-engine/parts/RenderView.js +1 -1
  39. package/views/3d/webgl-engine/shaders/DefaultMaterialTechniqueConfiguration.js +1 -1
  40. package/views/3d/webgl-engine/shaders/ReceiveShadowsConfiguration.js +1 -1
  41. package/views/3d/webgl-engine/shaders/TerrainTechniqueConfiguration.js +1 -1
  42. package/views/3d/webgl.js +1 -1
  43. package/views/selection/types.d.ts +9 -0
  44. package/widgets/support/Selector2D/SelectionOperation.d.ts +191 -0
  45. package/widgets/support/Selector2D/SelectionOperation.js +1 -1
  46. package/widgets/support/Selector2D/types.d.ts +139 -0
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import has from"../../../core/has.js";import{disposeMaybe as t}from"../../../core/maybe.js";import{MemCachePool as i}from"../../../core/MemCachePool.js";import r from"../../../core/ObjectPool.js";import{watch as s,sync as n}from"../../../core/reactiveUtils.js";import{property as a,subclass as l}from"../../../core/accessorSupport/decorators.js";import{subtract as o,set as c,dot as d}from"../../../core/libs/gl-matrix-2/math/vec3.js";import{ZEROS as h,fromValues as u,create as _}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{fromValues as g,ZEROS as f}from"../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{create as p,set as m}from"../../../geometry/support/aaBoundingBox.js";import{BufferViewVec3f as y}from"../../../geometry/support/buffer/BufferView.js";import{overlayRenderOccludedFlag as b}from"./OverlayRenderer.js";import{PatchRenderData as x}from"./PatchRenderData.js";import{TerrainAttributesCache as T}from"./TerrainAttributesCache.js";import{enableTerrainInternalChecks as R}from"./terrainUtils.js";import{TileRenderer as v}from"./TileRenderer.js";import{IteratorPreorder as P,fallsWithinLayerView as O,sortTiles as w,compareTiles as S}from"./tileUtils.js";import{getOverlayContentForOutputTerrain as D}from"../webgl-engine/core/shaderLibrary/terrain/Overlay.glsl.js";import{SyncRenderPlugin as B}from"../webgl-engine/effects/RenderPlugin.js";import{Vertices as E}from"../webgl-engine/lib/Attribute.js";import{IntersectorResult as F}from"../webgl-engine/lib/IntersectorResult.js";import{intersectAabbInvDirBefore as j,MeshIntersectionOptions as q,intersectTriangles as C}from"../webgl-engine/lib/RayIntersections.js";import{TriangleIntersectionData as A}from"../webgl-engine/lib/TriangleIntersectionData.js";import{terrainId as M,getVerticalOffsetTerrain as G}from"../webgl-engine/lib/verticalOffsetUtils.js";import{DrawParameters as U}from"../webgl-engine/materials/DrawParameters.js";import{T as k}from"../../../chunks/Terrain.glsl.js";import{TerrainTechnique as I}from"../webgl-engine/shaders/TerrainTechnique.js";import{TerrainTechniqueConfiguration as N}from"../webgl-engine/shaders/TerrainTechniqueConfiguration.js";import{PrimitiveType as L}from"../../webgl/enums.js";const V=7,z=10,H=200,Q=p();let W=class extends B{get visibleTiles(){return Array.from(this._visiblePatchesByOrigin.values()).flat()}get _isGlobal(){return 1===this._stage.viewingMode}get _techniques(){return this._context.techniques}get _rctx(){return this._context.renderContext.rctx}get renderOccludedFlags(){return this._overlayRenderer.renderOccludedFlags}constructor(e,t,s,n,a){super({}),this._overlayRenderer=e,this._stage=t,this._allTiles=s,this._compressionTracker=n,this.type=7,this.isGround=!0,this._passParameters=new k,this._drawParameters=new U,this._renderDataPool=new r(()=>new x),this._visiblePatchesByOrigin=new Map,this._allPatchesByOrigin=new Map,this._patchesByOriginDirty=!0,this._patchSortingDirty=!0,this._tileIterator=new P,this._castShadows=!1,this._inViewshed=!1,this._cutFillEnabled=!1,this._tileRenderer=null,this._stencilEnabledLayerExtents=new Array,this._numTilesRendered=0,this._numTilesCulled=0,this._numOriginsRendered=0,this.produces=new Map([[1,()=>1===this._desiredSlot],[6,()=>6===this._desiredSlot],[8,()=>8===this._desiredSlot],[10,()=>this._produces()&&this.renderOccludedFlags===b]]),this._tileSize=256,this._configuration=new N(1===t.viewingMode),this._tileTextureCache=new i((e,t)=>a.newCache(e,t),"TileTexture"),this.tileGeometryCache=new T(a)}normalizeCtorArgs(){return{}}initialize(){this._stage.addRenderPlugin(this),this.addHandles(s(()=>this._overlayRenderer.renderOccludedFlags,()=>this.setNeedsRender(),n))}destroy(){this._stage.removeRenderPlugin(this),this._tileTextureCache.destroy(),this.tileGeometryCache.destroy(),this._allTiles.prune(),this._tileRenderer=null}get _oitEnabled(){return this._stage.renderer.oitEnabled}_produces(){return this.visible&&!!this._rootTiles&&!this.renderingDisabled}set renderingDisabled(e){this._set("renderingDisabled",!!e),this.setDirty()}set visible(e){this._set("visible",!!e),this.setDirty()}updateHeading(e){this._tileRenderer?.updateHeading(e)}set transparency(e){this._configuration.transparencyMode!==e&&(this._configuration.transparencyMode=e,this.setNeedsRender())}get transparency(){return this._configuration.transparencyMode}get renderPatchBorders(){return this._configuration.tileBorders}set renderPatchBorders(e){this._configuration.tileBorders!==e&&(this._configuration.tileBorders=e,this.setNeedsRender(),this.notifyChange("renderPatchBorders"))}get layerViewUid(){return M}get slicePlaneEnabled(){return this._configuration.hasSlicePlane}set slicePlaneEnabled(e){this._configuration.hasSlicePlane!==e&&(this._configuration.hasSlicePlane=e,this.setNeedsRender())}set textureFadingEnabled(e){this._configuration.textureFadingEnabled!==e&&(this._configuration.textureFadingEnabled=e,this.setNeedsRender())}set pbrMode(e){this._configuration.pbrMode!==e&&(this._configuration.pbrMode=e,this.setNeedsRender())}setRootTiles(e){this._rootTiles=e,this.setDirty()}setStencilEnabledLayerExtents(e){this._stencilEnabledLayerExtents=e,this._setSortingDirty()}set tileSize(e){this._tileSize=e,null!=this._tileRenderer&&(this._tileRenderer.tileSize=e),this.setDirty()}get tileSize(){return this._tileSize}_ensureRenderData(e){e.renderData||(e.renderData=this._renderDataPool.acquire(),e.renderData.init(e,this._getLocalOriginOfTile(e)))}loadTile(e){this._ensureRenderData(e),this.updateTileGeometryState(e),this.reuseTextureFromParent(e)||this.updateTileTexture(e,32)}reuseTextureFromParent(e){const{parent:t}=e;if(!this._canReuseTextureFromParent(t,e))return!1;const i=g(1&e.lij[2]?.5:0,1&e.lij[1]?0:.5,.5,.5);return t.renderData?.reuseTexture(e.renderData,i)??!1}_canReuseTextureFromParent(e,t){if(!e)return!1;const{layerInfo:i,surface:r}=t;for(let s=0;s<i[1].length;s++){const i=r.layerViewByIndex(s,1);if(O(e,i)!==O(t,i))return!1}return!0}updateTileTexture(e,t){null!=this._tileRenderer&&(this._tileRenderer.updateTileTexture(e,32===t?0:2),this.setNeedsRender(),e.resetPendingUpdate(t))}updateTileGeometryState(e){for(const i of e.layerInfo[0])i.pendingUpdates&=-9;e.resetPendingUpdate(8);const t=e.renderData.updateGeometryState();return t&&this.setDirty(),t}updateGeometryIfNeeded(e){e.loaded&&e.renderData.updateGeometryIfNeeded(this._rctx)}unloadTile(e){const t=e.renderData;t&&(t.releaseGeometry(),this._renderDataPool.release(t),t.clear(),e.renderData=null,e.setMemoryDirty(),this.setDirty())}_getLocalOriginOfTile(e){const t=z-V,i=Math.max(0,Math.floor((e.level-t)/V)*V);if(this._isGlobal&&0===i)return h;for(;e.parent&&e.level>i;)e=e.parent;return e.centerAtSeaLevel}getStats(){return{numTilesRendered:this._numTilesRendered,numTilesCulled:this._numTilesCulled,numOriginsRendered:this._numOriginsRendered}}set wireframe(e){this._get("wireframe")!==e&&(this._set("wireframe",e),this.setNeedsRender())}setDirty(e=1){this._patchesByOriginDirty=!0,this._context.requestRender(e)}_setSortingDirty(e=1){this._patchSortingDirty=!0,this._context.requestRender(e)}setNeedsRender(e=1){this._context.requestRender(e)}initializeRenderContext(e){this._context=e,this._tileRenderer=new v(this._rctx,this._tileSize,this._techniques,this._tileTextureCache,this._compressionTracker),this.updateTileBackground()}uninitializeRenderContext(){this._tileRenderer=t(this._tileRenderer)}intersect(e,t,i,r){if(!this._rootTiles||e.options.selectOpaqueTerrainOnly&&e.options.selectionMode&&0!==this.transparency)return;const s=Z,n=J;o(s,r,i),c(n,1/s[0],1/s[1],1/s[2]);const a=e.results.min,l=e.results.max,h=e.results.ground,u=0===e.options.store,_=!!e.results.ground.target,g=G(e.verticalOffset),f=e.tolerance;let p,b=u&&null!=a.distance?a.distance:1/0;const x=e.options,T=x.normalRequired||!x.backfacesTerrain,R=new q(f,!1,T),v=c=>{const _=c.renderData;if(!_?.vao)return;const v=_.geometry;m(Q,v.boundingBox);const P=_.localOrigin;null!=g&&(g.localOrigin=P,g.applyToAabb(Q));const O=Q;if(K[0]=i[0]-P[0],K[1]=i[1]-P[1],K[2]=i[2]-P[2],!j(O,K,n,f,b))return;const w=(e,t,i)=>{e.set(this.type,c,t,i),b=u&&null!=a.distance?a.distance:1/0},S=(n,o,c)=>{if((!T||null!=o)&&n>=0&&(x.backfacesTerrain||d(o,s)<0)&&(x.invisibleTerrain||!x.selectionMode||null==t||t(i,r,n))){if((null==h.distance||n<h.distance)&&w(h,n,o),x.isFiltered)return;2===x.store&&(null==p?(p=new F(e.ray),w(p,n,o),e.results.all.push(p)):n<p.distance&&w(p,n,o)),(null==a.distance||n<a.distance)&&w(a,n,o),0!==x.store&&(null==l.distance||n>l.distance)&&w(l,n,o)}},D=X;o(D,r,P);const{indices:B,indexCount:q}=v,M=v.vertexAttributes,G=M.getField("position",y),U=new E(G.typedBuffer,3,M.stride/4),k=q/3;if(!g&&k>H){const e=c.renderData;e.intersectionData??=new A(B,k,U),e.intersectionData.intersectRay(K,D,R,S)}else C(K,D,0,k,B,U,g,R,S)},P=this._rootTiles;if(null!=P){(()=>{const t=this._tileIterator;t.reset(P);const r=e.options.invisibleTerrain;for(let e=t.next();e;e=t.next())!(e.visible||r&&e.intersectsClippingArea)||null==g&&!e.intersectsRay(i,s,f,b)||_&&this._useStencilForTile(e)?t.skipSubtree():v(e)})()}}processScaleRangeQueries(e,t){if(!t.done&&e)for(this._updatePatchGroups();e.updating&&!t.done;){e.prepare();for(const t of this._visiblePatchesByOrigin.values())for(const i of t)null!=i.renderData?.textureReference&&e.queriesForTile(i);e.process(),t.madeProgress()}}get _desiredSlot(){if(!this._produces())return null;switch(this.transparency){case 0:return 1;case 1:case 2:return this._oitEnabled?8:6;case 3:case 4:return null}}acquireTechniques(e){const{shadowMap:t,viewshedEnabled:i,cutFillComputationEnabled:r,slot:s,hasEmission:n,useFloatBlend:a}=e.bind,l=!!has("enable-feature:terrain-shadows")&&t.enabled;if(l!==this._castShadows&&(this._castShadows=l,this._patchesByOriginDirty=!0),this._inViewshed!==i&&(this._inViewshed=i,this._patchesByOriginDirty=!0),this._cutFillEnabled!==r&&(this._cutFillEnabled=r,this._patchesByOriginDirty=!0),3===this.transparency)return null;if(10===s){if(0===(e.renderOccludedMask&b))return null}else if(s!==this._desiredSlot)return null;const o=this._configuration;switch(o.screenSpaceReflections=o.cloudReflections=o.receiveShadows=o.receiveAmbientOcclusion=o.renderOccluded=o.hasHighlightMixTexture=o.hasEmission=!1,o.overlayMode=this._overlayRenderer.mode,o.useFloatBlend=a.value,e.output){case 0:case 1:case 2:{const i=e.bind;o.screenSpaceReflections=i.hasScreenSpaceReflections,o.cloudReflections=null!=i.clouds.data;const r=10===s;return o.receiveShadows=t.ready&&!r,o.renderOccluded=r,o.receiveAmbientOcclusion=!r&&null!=i.ssao,o.hasEmission=n,this._acquireTechnique(e.output)}case 5:case 7:return this._castShadows?this._acquireTechnique(5):null;case 8:return this._inViewshed?this._acquireTechnique(8):null;case 9:return this._cutFillEnabled?this._acquireTechnique(9):null;case 3:case 4:return this._acquireTechnique(e.output);case 11:return this._acquireTechnique(11);case 10:return o.hasHighlightMixTexture=null!=e.bind.highlightMixTexture,this._overlayRenderer.hasHighlights?this._acquireTechnique(10):null}return null}render(e,t){switch(this._updatePatchGroups(),t.useStencil=!1,this._passParameters.overlayContent=D(e.output,e.bind),e.output){case 0:case 1:case 2:return this._renderMaterialPass(e,t);case 3:case 4:case 11:return this._renderAuxiliaryPass(e,t,this._visiblePatchesByOrigin);case 10:{const i=e.bind.highlight?.name;i&&this._overlayRenderer.hasHighlights&&this._overlayRenderer.renders(2)&&this._overlayRenderer.hasHighlight(i)&&this._renderAuxiliaryPass(e,t,this._visiblePatchesByOrigin);break}case 5:case 7:case 8:case 9:return this._renderAuxiliaryPass(e,t,this._allPatchesByOrigin)}}updateTileBackground(e){if(null==this._tileRenderer)return;const t=this._tileRenderer;let i;if(null!=e){const t=e.toUnitRGBA();i=u(t[0]||0,t[1]||0,t[2]||0)}t.setBackground(i),this._allTiles.forAll(e=>t.updateTileTexture(e,0)),this._configuration.tileBlendInput=t.backgroundIsGrid?2:null!=t.backgroundColor?1:0,this.setNeedsRender()}_updatePatchGroups(){if(this._patchesByOriginDirty&&(this._rebuildPatchGroups(),this._patchesByOriginDirty=!1,this._patchSortingDirty=!0),this._patchSortingDirty){const e=Array.from(this._visiblePatchesByOrigin.values()),t=this._stencilEnabledLayerExtents;for(const i of e)w(i,t);e.sort((e,t)=>S(e[0],t[0])),this._visiblePatchesByOrigin=new Map(e.map(e=>[e[0].renderData.localOrigin,e])),this.notifyChange("visibleTiles"),this._patchSortingDirty=!1}}_rebuildPatchGroups(){const e=this._rootTiles;if(null!=e){e[0]?.surface.checkAllTilesWaterproofness(),this._visiblePatchesByOrigin.clear(),this._allPatchesByOrigin.clear();for(const t of e)this._rebuildPatchGroupsForRootTile(t)}}_rebuildPatchGroupsForRootTile(e){const t=this._tileIterator;for(t.resetOne(e);!t.done;){const e=t.next(),i=e.renderData;if(!i){this._numTilesCulled++;continue}const r=i.localOrigin;if(this._castShadows||this._inViewshed||this._cutFillEnabled){let t=this._allPatchesByOrigin.get(r);t||(t=[],this._allPatchesByOrigin.set(r,t)),t.push(e)}if(!e.visible){this._numTilesCulled++,t.skipSubtree();continue}let s=this._visiblePatchesByOrigin.get(r);s||(s=[],this._visiblePatchesByOrigin.set(r,s)),s.push(e),t.skipSubtree()}}_useStencilForTile(e){for(const t of this._stencilEnabledLayerExtents)if(e.intersectsExtent(t))return!0;return!1}_renderAuxiliaryPass(e,t,i){const{rctx:r,bind:s}=e;r.bindTechnique(t,s,this._passParameters);const n=this._stencilEnabledLayerExtents.length>0;i.forEach(i=>{this._drawParameters.origin=i[0].renderData.localOrigin,t.program.bindDraw(s,this._passParameters,this._drawParameters);for(let r=0;r<i.length;r++)this._renderPatch(e,t,i[r],L.TRIANGLES,n,null===this._passParameters.overlayContent)}),r.bindVAO(null)}_renderMaterialPass(e,t){const{rctx:i,bind:r}=e,s=i.bindTechnique(t,r,this._passParameters);this._numTilesRendered=0,this._numTilesCulled=0,this._numOriginsRendered=0;const n=10===r.slot;n&&(s.bindTexture("tex",i.emptyTexture),s.setUniform3fv("textureOpacities",h),s.setUniform4fv("texOffsetAndScale",f));const a=null!=this._tileRenderer?.backgroundColor?this._tileRenderer.backgroundColor:h;1===this._configuration.tileBlendInput&&s.setUniform3fv("backgroundColor",a);const l=this._stencilEnabledLayerExtents.length>0,o=this.wireframe?L.LINES:L.TRIANGLES;this._configuration.textureFadingEnabled&&s.bindTexture("texNext",i.emptyTexture);const c=this._visiblePatchesByOrigin;for(const d of c.values()){const i=d[0].renderData.localOrigin;this._drawParameters.origin=i,t.program.bindDraw(r,this._passParameters,this._drawParameters),this._numOriginsRendered++;for(const r of d){const i=r.renderData,a=i.textureReference;if(null!=a){if(!n){s.setUniform4fv("texOffsetAndScale",a.offsetAndScale),s.bindTexture("tex",a.texture.texture);const e=i.textureFadeFactor,t=e<1?i.nextTextureReference:null;this._configuration.textureFadingEnabled&&t&&e<1?(s.setUniform1f("fadeFactor",e),s.setUniform4fv("nextTexOffsetAndScale",t.offsetAndScale),s.setUniform3fv("nextTexOpacities",t.opacities),s.bindTexture("texNext",t.texture.texture)):s.setUniform1f("fadeFactor",1),i.textureIsFading&&this.setNeedsRender(2),s.setUniform3fv("textureOpacities",a.opacities)}this._renderPatch(e,t,r,o,l),r.renderOrder=this._numTilesRendered,this._numTilesRendered++}}}i.bindVAO(null)}_renderPatch(e,t,i,r,s,n=!1){const a=i.renderData,l=a.vao,o=l?.indexBuffer;if(!l||null==o)return void(R&&console.error("Rendered tile with no indices: ",i.lij," : ",a));const c=t.program;n||this._overlayRenderer.isEmpty||this._bindOverlayPatchData(c,a.overlay);const{rctx:d,bind:h}=e;s&&(t.useStencil=this._useStencilForTile(i),d.setPipelineState(t.getPipeline(h)));const u=a.geometry.indexCount;d.bindVAO(l),c.assertCompatibleVertexAttributeLocations(l),d.drawElements(r,u,o.indexType,0)}_bindOverlayPatchData(e,t){e.setUniform4fv("overlayTexOffset",t.offsets),e.setUniform4fv("overlayTexScale",t.scales)}_acquireTechnique(e){return this._configuration.output=e,this._techniques.get(I,this._configuration)}get test(){}hasHighlight(e){return this._overlayRenderer.hasHighlight(e)}};e([a({readOnly:!0})],W.prototype,"visibleTiles",null),e([a({readOnly:!0})],W.prototype,"_isGlobal",null),e([a()],W.prototype,"renderOccludedFlags",null),e([a({value:!1})],W.prototype,"renderingDisabled",null),e([a({value:!0})],W.prototype,"visible",null),e([a()],W.prototype,"renderPatchBorders",null),e([a()],W.prototype,"wireframe",null),W=e([l("esri.views.3d.terrain.TerrainRenderer")],W);const Z=_(),J=_(),K=_(),X=_();export{W as TerrainRenderer};
2
+ import{__decorate as e}from"tslib";import has from"../../../core/has.js";import{disposeMaybe as t}from"../../../core/maybe.js";import{MemCachePool as i}from"../../../core/MemCachePool.js";import r from"../../../core/ObjectPool.js";import{watch as s,sync as n}from"../../../core/reactiveUtils.js";import{property as a,subclass as l}from"../../../core/accessorSupport/decorators.js";import{subtract as o,set as c,dot as d}from"../../../core/libs/gl-matrix-2/math/vec3.js";import{ZEROS as h,fromValues as u,create as _}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{fromValues as g,ZEROS as f}from"../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{create as p,set as m}from"../../../geometry/support/aaBoundingBox.js";import{BufferViewVec3f as y}from"../../../geometry/support/buffer/BufferView.js";import{overlayRenderOccludedFlag as b}from"./OverlayRenderer.js";import{PatchRenderData as x}from"./PatchRenderData.js";import{TerrainAttributesCache as T}from"./TerrainAttributesCache.js";import{enableTerrainInternalChecks as R}from"./terrainUtils.js";import{TileRenderer as v}from"./TileRenderer.js";import{IteratorPreorder as P,fallsWithinLayerView as w,sortTiles as O,compareTiles as S}from"./tileUtils.js";import{getOverlayContentForOutputTerrain as D}from"../webgl-engine/core/shaderLibrary/terrain/Overlay.glsl.js";import{SyncRenderPlugin as B}from"../webgl-engine/effects/RenderPlugin.js";import{Vertices as E}from"../webgl-engine/lib/Attribute.js";import{IntersectorResult as F}from"../webgl-engine/lib/IntersectorResult.js";import{intersectAabbInvDirBefore as j,MeshIntersectionOptions as q,intersectTriangles as C}from"../webgl-engine/lib/RayIntersections.js";import{TriangleIntersectionData as A}from"../webgl-engine/lib/TriangleIntersectionData.js";import{terrainId as M,getVerticalOffsetTerrain as G}from"../webgl-engine/lib/verticalOffsetUtils.js";import{DrawParameters as U}from"../webgl-engine/materials/DrawParameters.js";import{hasShadowHighlights as k}from"../webgl-engine/shaders/ReceiveShadowsConfiguration.js";import{T as I}from"../../../chunks/Terrain.glsl.js";import{TerrainTechnique as N}from"../webgl-engine/shaders/TerrainTechnique.js";import{TerrainTechniqueConfiguration as L}from"../webgl-engine/shaders/TerrainTechniqueConfiguration.js";import{PrimitiveType as V}from"../../webgl/enums.js";const H=7,z=10,Q=200,W=p();let Z=class extends B{get visibleTiles(){return Array.from(this._visiblePatchesByOrigin.values()).flat()}get _isGlobal(){return 1===this._stage.viewingMode}get _techniques(){return this._context.techniques}get _rctx(){return this._context.renderContext.rctx}get renderOccludedFlags(){return this._overlayRenderer.renderOccludedFlags}constructor(e,t,s,n,a){super({}),this._overlayRenderer=e,this._stage=t,this._allTiles=s,this._compressionTracker=n,this.type=7,this.isGround=!0,this._passParameters=new I,this._drawParameters=new U,this._renderDataPool=new r(()=>new x),this._visiblePatchesByOrigin=new Map,this._allPatchesByOrigin=new Map,this._patchesByOriginDirty=!0,this._patchSortingDirty=!0,this._tileIterator=new P,this._castShadows=!1,this._inViewshed=!1,this._cutFillEnabled=!1,this._tileRenderer=null,this._stencilEnabledLayerExtents=new Array,this._numTilesRendered=0,this._numTilesCulled=0,this._numOriginsRendered=0,this.produces=new Map([[1,()=>1===this._desiredSlot],[6,()=>6===this._desiredSlot],[8,()=>8===this._desiredSlot],[10,()=>this._produces()&&this.renderOccludedFlags===b]]),this._tileSize=256,this._configuration=new L(1===t.viewingMode),this._tileTextureCache=new i((e,t)=>a.newCache(e,t),"TileTexture"),this.tileGeometryCache=new T(a)}normalizeCtorArgs(){return{}}initialize(){this._stage.addRenderPlugin(this),this.addHandles(s(()=>this._overlayRenderer.renderOccludedFlags,()=>this.setNeedsRender(),n))}destroy(){this._stage.removeRenderPlugin(this),this._tileTextureCache.destroy(),this.tileGeometryCache.destroy(),this._allTiles.prune(),this._tileRenderer=null}get _oitEnabled(){return this._stage.renderer.oitEnabled}_produces(){return this.visible&&!!this._rootTiles&&!this.renderingDisabled}set renderingDisabled(e){this._set("renderingDisabled",!!e),this.setDirty()}set visible(e){this._set("visible",!!e),this.setDirty()}updateHeading(e){this._tileRenderer?.updateHeading(e)}set transparency(e){this._configuration.transparencyMode!==e&&(this._configuration.transparencyMode=e,this.setNeedsRender())}get transparency(){return this._configuration.transparencyMode}get renderPatchBorders(){return this._configuration.tileBorders}set renderPatchBorders(e){this._configuration.tileBorders!==e&&(this._configuration.tileBorders=e,this.setNeedsRender(),this.notifyChange("renderPatchBorders"))}get layerViewUid(){return M}get slicePlaneEnabled(){return this._configuration.hasSlicePlane}set slicePlaneEnabled(e){this._configuration.hasSlicePlane!==e&&(this._configuration.hasSlicePlane=e,this.setNeedsRender())}set textureFadingEnabled(e){this._configuration.textureFadingEnabled!==e&&(this._configuration.textureFadingEnabled=e,this.setNeedsRender())}set pbrMode(e){this._configuration.pbrMode!==e&&(this._configuration.pbrMode=e,this.setNeedsRender())}setRootTiles(e){this._rootTiles=e,this.setDirty()}setStencilEnabledLayerExtents(e){this._stencilEnabledLayerExtents=e,this._setSortingDirty()}set tileSize(e){this._tileSize=e,null!=this._tileRenderer&&(this._tileRenderer.tileSize=e),this.setDirty()}get tileSize(){return this._tileSize}_ensureRenderData(e){e.renderData||(e.renderData=this._renderDataPool.acquire(),e.renderData.init(e,this._getLocalOriginOfTile(e)))}loadTile(e){this._ensureRenderData(e),this.updateTileGeometryState(e),this.reuseTextureFromParent(e)||this.updateTileTexture(e,32)}reuseTextureFromParent(e){const{parent:t}=e;if(!this._canReuseTextureFromParent(t,e))return!1;const i=g(1&e.lij[2]?.5:0,1&e.lij[1]?0:.5,.5,.5);return t.renderData?.reuseTexture(e.renderData,i)??!1}_canReuseTextureFromParent(e,t){if(!e)return!1;const{layerInfo:i,surface:r}=t;for(let s=0;s<i[1].length;s++){const i=r.layerViewByIndex(s,1);if(w(e,i)!==w(t,i))return!1}return!0}updateTileTexture(e,t){null!=this._tileRenderer&&(this._tileRenderer.updateTileTexture(e,32===t?0:2),this.setNeedsRender(),e.resetPendingUpdate(t))}updateTileGeometryState(e){for(const i of e.layerInfo[0])i.pendingUpdates&=-9;e.resetPendingUpdate(8);const t=e.renderData.updateGeometryState();return t&&this.setDirty(),t}updateGeometryIfNeeded(e){e.loaded&&e.renderData.updateGeometryIfNeeded(this._rctx)}unloadTile(e){const t=e.renderData;t&&(t.releaseGeometry(),this._renderDataPool.release(t),t.clear(),e.renderData=null,e.setMemoryDirty(),this.setDirty())}_getLocalOriginOfTile(e){const t=z-H,i=Math.max(0,Math.floor((e.level-t)/H)*H);if(this._isGlobal&&0===i)return h;for(;e.parent&&e.level>i;)e=e.parent;return e.centerAtSeaLevel}getStats(){return{numTilesRendered:this._numTilesRendered,numTilesCulled:this._numTilesCulled,numOriginsRendered:this._numOriginsRendered}}set wireframe(e){this._get("wireframe")!==e&&(this._set("wireframe",e),this.setNeedsRender())}setDirty(e=1){this._patchesByOriginDirty=!0,this._context.requestRender(e)}_setSortingDirty(e=1){this._patchSortingDirty=!0,this._context.requestRender(e)}setNeedsRender(e=1){this._context.requestRender(e)}initializeRenderContext(e){this._context=e,this._tileRenderer=new v(this._rctx,this._tileSize,this._techniques,this._tileTextureCache,this._compressionTracker),this.updateTileBackground()}uninitializeRenderContext(){this._tileRenderer=t(this._tileRenderer)}intersect(e,t,i,r){if(!this._rootTiles||e.options.selectOpaqueTerrainOnly&&e.options.selectionMode&&0!==this.transparency)return;const s=J,n=K;o(s,r,i),c(n,1/s[0],1/s[1],1/s[2]);const a=e.results.min,l=e.results.max,h=e.results.ground,u=0===e.options.store,_=!!e.results.ground.target,g=G(e.verticalOffset),f=e.tolerance;let p,b=u&&null!=a.distance?a.distance:1/0;const x=e.options,T=x.normalRequired||!x.backfacesTerrain,R=new q(f,!1,T),v=c=>{const _=c.renderData;if(!_?.vao)return;const v=_.geometry;m(W,v.boundingBox);const P=_.localOrigin;null!=g&&(g.localOrigin=P,g.applyToAabb(W));const w=W;if(X[0]=i[0]-P[0],X[1]=i[1]-P[1],X[2]=i[2]-P[2],!j(w,X,n,f,b))return;const O=(e,t,i)=>{e.set(this.type,c,t,i),b=u&&null!=a.distance?a.distance:1/0},S=(n,o,c)=>{if((!T||null!=o)&&n>=0&&(x.backfacesTerrain||d(o,s)<0)&&(x.invisibleTerrain||!x.selectionMode||null==t||t(i,r,n))){if((null==h.distance||n<h.distance)&&O(h,n,o),x.isFiltered)return;2===x.store&&(null==p?(p=new F(e.ray),O(p,n,o),e.results.all.push(p)):n<p.distance&&O(p,n,o)),(null==a.distance||n<a.distance)&&O(a,n,o),0!==x.store&&(null==l.distance||n>l.distance)&&O(l,n,o)}},D=Y;o(D,r,P);const{indices:B,indexCount:q}=v,M=v.vertexAttributes,G=M.getField("position",y),U=new E(G.typedBuffer,3,M.stride/4),k=q/3;if(!g&&k>Q){const e=c.renderData;e.intersectionData??=new A(B,k,U),e.intersectionData.intersectRay(X,D,R,S)}else C(X,D,0,k,B,U,g,R,S)},P=this._rootTiles;if(null!=P){(()=>{const t=this._tileIterator;t.reset(P);const r=e.options.invisibleTerrain;for(let e=t.next();e;e=t.next())!(e.visible||r&&e.intersectsClippingArea)||null==g&&!e.intersectsRay(i,s,f,b)||_&&this._useStencilForTile(e)?t.skipSubtree():v(e)})()}}processScaleRangeQueries(e,t){if(!t.done&&e)for(this._updatePatchGroups();e.updating&&!t.done;){e.prepare();for(const t of this._visiblePatchesByOrigin.values())for(const i of t)null!=i.renderData?.textureReference&&e.queriesForTile(i);e.process(),t.madeProgress()}}get _desiredSlot(){if(!this._produces())return null;switch(this.transparency){case 0:return 1;case 1:case 2:return this._oitEnabled?8:6;case 3:case 4:return null}}acquireTechniques(e){const{shadowMap:t,viewshedEnabled:i,cutFillComputationEnabled:r,slot:s,hasEmission:n,useFloatBlend:a}=e.bind,l=!!has("enable-feature:terrain-shadows")&&t.enabled;if(l!==this._castShadows&&(this._castShadows=l,this._patchesByOriginDirty=!0),this._inViewshed!==i&&(this._inViewshed=i,this._patchesByOriginDirty=!0),this._cutFillEnabled!==r&&(this._cutFillEnabled=r,this._patchesByOriginDirty=!0),3===this.transparency)return null;if(10===s){if(0===(e.renderOccludedMask&b))return null}else if(s!==this._desiredSlot)return null;const o=this._configuration;switch(o.screenSpaceReflections=o.cloudReflections=o.receiveShadows=o.hasShadowHighlights=o.receiveAmbientOcclusion=o.renderOccluded=o.hasHighlightMixTexture=o.hasEmission=!1,o.overlayMode=this._overlayRenderer.mode,o.useFloatBlend=a.value,e.output){case 0:case 1:case 2:{const i=e.bind;o.screenSpaceReflections=i.hasScreenSpaceReflections,o.cloudReflections=null!=i.clouds.data;const r=10===s;return o.receiveShadows=t.ready&&!r,o.hasShadowHighlights=k(o,e.bind),o.renderOccluded=r,o.receiveAmbientOcclusion=!r&&null!=i.ssao,o.hasEmission=n,this._acquireTechnique(e.output)}case 5:case 7:return this._castShadows?this._acquireTechnique(5):null;case 8:return this._inViewshed?this._acquireTechnique(8):null;case 9:return this._cutFillEnabled?this._acquireTechnique(9):null;case 3:case 4:return this._acquireTechnique(e.output);case 11:return this._acquireTechnique(11);case 10:return o.hasHighlightMixTexture=null!=e.bind.highlightMixTexture,this._overlayRenderer.hasHighlights?this._acquireTechnique(10):null}return null}render(e,t){switch(this._updatePatchGroups(),t.useStencil=!1,this._passParameters.overlayContent=D(e.output,e.bind),e.output){case 0:case 1:case 2:return this._renderMaterialPass(e,t);case 3:case 4:case 11:return this._renderAuxiliaryPass(e,t,this._visiblePatchesByOrigin);case 10:{const i=e.bind.highlight?.name;i&&this._overlayRenderer.hasHighlights&&this._overlayRenderer.renders(2)&&this._overlayRenderer.hasHighlight(i)&&this._renderAuxiliaryPass(e,t,this._visiblePatchesByOrigin);break}case 5:case 7:case 8:case 9:return this._renderAuxiliaryPass(e,t,this._allPatchesByOrigin)}}updateTileBackground(e){if(null==this._tileRenderer)return;const t=this._tileRenderer;let i;if(null!=e){const t=e.toUnitRGBA();i=u(t[0]||0,t[1]||0,t[2]||0)}t.setBackground(i),this._allTiles.forAll(e=>t.updateTileTexture(e,0)),this._configuration.tileBlendInput=t.backgroundIsGrid?2:null!=t.backgroundColor?1:0,this.setNeedsRender()}_updatePatchGroups(){if(this._patchesByOriginDirty&&(this._rebuildPatchGroups(),this._patchesByOriginDirty=!1,this._patchSortingDirty=!0),this._patchSortingDirty){const e=Array.from(this._visiblePatchesByOrigin.values()),t=this._stencilEnabledLayerExtents;for(const i of e)O(i,t);e.sort((e,t)=>S(e[0],t[0])),this._visiblePatchesByOrigin=new Map(e.map(e=>[e[0].renderData.localOrigin,e])),this.notifyChange("visibleTiles"),this._patchSortingDirty=!1}}_rebuildPatchGroups(){const e=this._rootTiles;if(null!=e){e[0]?.surface.checkAllTilesWaterproofness(),this._visiblePatchesByOrigin.clear(),this._allPatchesByOrigin.clear();for(const t of e)this._rebuildPatchGroupsForRootTile(t)}}_rebuildPatchGroupsForRootTile(e){const t=this._tileIterator;for(t.resetOne(e);!t.done;){const e=t.next(),i=e.renderData;if(!i){this._numTilesCulled++;continue}const r=i.localOrigin;if(this._castShadows||this._inViewshed||this._cutFillEnabled){let t=this._allPatchesByOrigin.get(r);t||(t=[],this._allPatchesByOrigin.set(r,t)),t.push(e)}if(!e.visible){this._numTilesCulled++,t.skipSubtree();continue}let s=this._visiblePatchesByOrigin.get(r);s||(s=[],this._visiblePatchesByOrigin.set(r,s)),s.push(e),t.skipSubtree()}}_useStencilForTile(e){for(const t of this._stencilEnabledLayerExtents)if(e.intersectsExtent(t))return!0;return!1}_renderAuxiliaryPass(e,t,i){const{rctx:r,bind:s}=e;r.bindTechnique(t,s,this._passParameters);const n=this._stencilEnabledLayerExtents.length>0;i.forEach(i=>{this._drawParameters.origin=i[0].renderData.localOrigin,t.program.bindDraw(s,this._passParameters,this._drawParameters);for(let r=0;r<i.length;r++)this._renderPatch(e,t,i[r],V.TRIANGLES,n,null===this._passParameters.overlayContent)}),r.bindVAO(null)}_renderMaterialPass(e,t){const{rctx:i,bind:r}=e,s=i.bindTechnique(t,r,this._passParameters);this._numTilesRendered=0,this._numTilesCulled=0,this._numOriginsRendered=0;const n=10===r.slot;n&&(s.bindTexture("tex",i.emptyTexture),s.setUniform3fv("textureOpacities",h),s.setUniform4fv("texOffsetAndScale",f));const a=null!=this._tileRenderer?.backgroundColor?this._tileRenderer.backgroundColor:h;1===this._configuration.tileBlendInput&&s.setUniform3fv("backgroundColor",a);const l=this._stencilEnabledLayerExtents.length>0,o=this.wireframe?V.LINES:V.TRIANGLES;this._configuration.textureFadingEnabled&&s.bindTexture("texNext",i.emptyTexture);const c=this._visiblePatchesByOrigin;for(const d of c.values()){const i=d[0].renderData.localOrigin;this._drawParameters.origin=i,t.program.bindDraw(r,this._passParameters,this._drawParameters),this._numOriginsRendered++;for(const r of d){const i=r.renderData,a=i.textureReference;if(null!=a){if(!n){s.setUniform4fv("texOffsetAndScale",a.offsetAndScale),s.bindTexture("tex",a.texture.texture);const e=i.textureFadeFactor,t=e<1?i.nextTextureReference:null;this._configuration.textureFadingEnabled&&t&&e<1?(s.setUniform1f("fadeFactor",e),s.setUniform4fv("nextTexOffsetAndScale",t.offsetAndScale),s.setUniform3fv("nextTexOpacities",t.opacities),s.bindTexture("texNext",t.texture.texture)):s.setUniform1f("fadeFactor",1),i.textureIsFading&&this.setNeedsRender(2),s.setUniform3fv("textureOpacities",a.opacities)}this._renderPatch(e,t,r,o,l),r.renderOrder=this._numTilesRendered,this._numTilesRendered++}}}i.bindVAO(null)}_renderPatch(e,t,i,r,s,n=!1){const a=i.renderData,l=a.vao,o=l?.indexBuffer;if(!l||null==o)return void(R&&console.error("Rendered tile with no indices: ",i.lij," : ",a));const c=t.program;n||this._overlayRenderer.isEmpty||this._bindOverlayPatchData(c,a.overlay);const{rctx:d,bind:h}=e;s&&(t.useStencil=this._useStencilForTile(i),d.setPipelineState(t.getPipeline(h)));const u=a.geometry.indexCount;d.bindVAO(l),c.assertCompatibleVertexAttributeLocations(l),d.drawElements(r,u,o.indexType,0)}_bindOverlayPatchData(e,t){e.setUniform4fv("overlayTexOffset",t.offsets),e.setUniform4fv("overlayTexScale",t.scales)}_acquireTechnique(e){return this._configuration.output=e,this._techniques.get(N,this._configuration)}get test(){}hasHighlight(e){return this._overlayRenderer.hasHighlight(e)}};e([a({readOnly:!0})],Z.prototype,"visibleTiles",null),e([a({readOnly:!0})],Z.prototype,"_isGlobal",null),e([a()],Z.prototype,"renderOccludedFlags",null),e([a({value:!1})],Z.prototype,"renderingDisabled",null),e([a({value:!0})],Z.prototype,"visible",null),e([a()],Z.prototype,"renderPatchBorders",null),e([a()],Z.prototype,"wireframe",null),Z=e([l("esri.views.3d.terrain.TerrainRenderer")],Z);const J=_(),K=_(),X=_(),Y=_();export{Z as TerrainRenderer};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../../../Color.js";import{filterInPlace as i,difference as r}from"../../../core/arrayUtils.js";import s from"../../../core/CollectionFlattener.js";import{toConst as a}from"../../../core/compilerUtils.js";import{EventedAccessor as n}from"../../../core/Evented.js";import"../../../core/has.js";import l from"../../../core/Logger.js";import{clamp as o}from"../../../core/mathUtils.js";import{destroyMaybe as h}from"../../../core/maybe.js";import{MemCachePool as d}from"../../../core/MemCachePool.js";import p from"../../../core/ObjectPool.js";import u from"../../../core/PooledArray.js";import{throwIfAborted as c,isAbortError as g,isAborted as m}from"../../../core/promiseUtils.js";import{watch as _,syncAndInitial as y,sync as f,initial as T}from"../../../core/reactiveUtils.js";import{getMetersPerUnitForSR as v}from"../../../core/units.js";import{property as w,subclass as C}from"../../../core/accessorSupport/decorators.js";import{exactEquals as S,set as b,copy as E}from"../../../core/libs/gl-matrix-2/math/vec3.js";import{create as x}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{UpdatingHandles as L}from"../../../core/support/UpdatingHandles.js";import{getReferenceEllipsoid as P,radiusModifier as R}from"../../../geometry/ellipsoidUtils.js";import U from"../../../geometry/SpatialReference.js";import{getProjector as M}from"../../../geometry/projection/projectors.js";import{projectPointToVector as D}from"../../../geometry/projection/projectPointToVector.js";import{projectVectorToVector as j}from"../../../geometry/projection/projectVectorToVector.js";import{create as I,equals as k,intersection as V,intersectsSphere as A,empty as B,expand as O}from"../../../geometry/support/aaBoundingRect.js";import{copy as G,create as N}from"../../../geometry/support/frustum.js";import{createSpatialReferenceCyclical as q}from"../../../geometry/support/normalizeUtils.js";import{isPlateCarree as F}from"../../../geometry/support/spatialReferenceUtils.js";import{Sphere as W}from"../../../geometry/support/sphere.js";import{ElevationQueryTileCache as H}from"../../../layers/support/ElevationQueryTileCache.js";import{isBaseLayer as $}from"../../../layers/support/layerUtils.js";import{debugFlags as Q}from"../support/debugFlags.js";import{ElevationRange as z}from"../support/ElevationRange.js";import{toBoundingRect as Y}from"../support/extentUtils.js";import{updatingProgress as X}from"../support/updatingProperties.js";import{ElevationBounds as K}from"./ElevationBounds.js";import{ElevationData as J,sampleElevation as Z}from"./ElevationData.js";import{ElevationUpdateEvent as ee}from"./ElevationUpdateEvent.js";import{create as te}from"./ExtentHelper.js";import{LayerClasses as ie}from"./LayerClass.js";import{OverlayManager as re}from"./OverlayManager.js";import{PlanarPatch as se}from"./PlanarPatch.js";import{Queue as ae}from"./Queue.js";import{ScaleRangeQueries as ne}from"./ScaleRangeQueries.js";import{SphericalPatch as le}from"./SphericalPatch.js";import{SplitLimits as oe}from"./SplitLimits.js";import{maxRootTiles as he,tooManyRootTilesAfterChangeError as de,tooManyRootTilesForLayerError as pe,maxTileNeighborLevelDelta as ue,maxMemoryLodBias as ce}from"./TerrainConst.js";import{TerrainRenderer as ge}from"./TerrainRenderer.js";import me from"./TerrainSurfacePerformanceInfo.js";import{weakAssert as _e,isVectorTileLayerView as ye,neighborEdgeIndices as fe,internalAssert as Te,oppositeEdge as ve,isSurfaceLayerView as we,isGroupLayerView as Ce,isMapTileLayerView as Se,isBlendableLayerView as be,isElevationLayerView as Ee,releaseTerrainData as xe,enableTerrainInternalChecks as Le,oppositeCorner as Pe,enableWaterproofTests as Re,enableInternalTerrainChecks as Ue,enableTerrainWaterproofChecks as Me,neighborCornerIndices as De}from"./terrainUtils.js";import{Tile as je,lijEquals as Ie}from"./Tile.js";import{printAllocations as ke}from"./TilePerLayerInfo.js";import{sortTiles as Ve,IteratorPreorder as Ae,IteratorPostorder as Be,compareTilesByLij as Oe,hasLoadableSiblings as Ge,sortTilesByPOI as Ne,traverseTilesPreorder as qe}from"./tileUtils.js";import{TilingSchemeLogic as Fe}from"./TilingSchemeLogic.js";import{UpsampleInfo as We}from"./UpsampleInfo.js";import{isCompositeBlendMode as He,blendModeFromString as $e}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{hasLayerBasedScaleVisibility as Qe}from"../../support/layerViewUtils.js";import{ImmediateTask as ze,TaskPriority as Ye,noBudget as Xe}from"../../support/Scheduler.js";import{TextureCompressionTracker as Ke}from"../../support/TextureCompressionTracker.js";import{Yield as Je}from"../../support/Yield.js";var Ze;let et=class extends n{static{Ze=this}get allTilesCreated(){return this._allTilesCreated}get allTiles(){return a(this._allTiles)}get renderedTiles(){return Ve(i(this._allTiles.toArray(),e=>e.visible&&e.rendered))}get demResolution(){const{_allTiles:e,tilingScheme:t}=this;if(0===e.length)return{min:1,max:1};const i=v(t.spatialReference);let r=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(const a of e){const e=t.resolutionAtLevel(a.level)*i;r=Math.min(r,e),s=Math.max(s,e)}return{min:r,max:s}}constructor(e){super(e),this.terrainTextureCompressionTracker=new Ke,this._iteratorPool=new p(()=>new Ae,e=>e.remove=()=>this._iteratorPool.release(e)),this._postorderIterator=new Be,this._hasPendingUpdates=!1,this._pendingUpdates=0,this._asyncWorkItems=0,this._allTilesDirty=!0,this._allTilesSorted=!0,this._allTilesCreated=!1,this._usedMemory=null,this._performanceInfo=new me,this._viewChanged=!1,this.heading=0,this._inFrameTask=!1,this._viewChangeUpdateDirty=!1,this._eyePosRenderSR=x(),this._eyePosSurfaceSR=x(),this._splitLimits=new oe,this._layerViews=[new Array,new Array],this._layerIndexByUid=[new Map,new Map],this._basemapLayerViewHandles=new Map,this._watchUpdatingTracking=new L,this._frameTask=ze,this._allTiles=new u,this._upsampleInfoPool=new p(()=>new We),this._shouldEmitChangeEvent=!1,this._rootTilesExtent=I(),this.updatingProgress=.5,this._maxNumUpdating=1,this.maxTextureScale=1.2,this._spatialReference=U.WebMercator,this._elevationProjectorCache=new Map,this.visibleElevationRange=new z(1/0,-1/0),this._rootTileElevationRange=new z(1/0,-1/0),this._projectorCache=new Map,this._tilingSchemeSpatialReference=null,this._updatingRootTiles=!1,this._pendingTilesForElevationUpdateEvent=new Set,this._pendingTilesToUpdate=new Set,this.totalGeometryUpdates=0,this.totalTileUpdates=0,this._oneBatchPerFrameTask=!0,this._layerViewsDirty=!1,this.unloadedMemory=0,this.ignoresMemoryFactor=!1,this._isWebMercator=!1,this._isWebMercatorOnPlateCarree=!1,this.enabled=!0;const{view:t}=e;this.overlayManager=new re({...e,terrainSurface:this}),this._isGlobal=!t.state?.isLocal,this._isGeographic=this._spatialReference?.isGeographic??!1,this._tileConstructor=this._isGlobal?le:se,this._ellipsoid=P(t.spatialReference),this._renderer=new ge(this.overlayManager.renderer,t.stage,this._allTiles,this.terrainTextureCompressionTracker,t.resourceController.memoryController),Qe()||(this._scaleRangeQueries=new ne)}initialize(){const{view:e}=this,{resourceController:t}=e,{memoryController:i}=t;this._tileCache=new d((e,t)=>i.newCache(e,t),"terrain-tile"),this._upsampleMapCache=i.newCache("terrain-upsample",({tile:e})=>e.unloadMapData()),this._elevationQueryCache=new H(i.newCache("elevation-query"));const r=this.overlayManager;this.addHandles([_(()=>r.renderer.isEmpty,()=>this._evaluateTransparency()),_(()=>this.renderer.visible,e=>this.suspended=!e),_(()=>this.heading,e=>{this._renderer.updateHeading(e),this._updateTileTextures(0)},y),_(()=>({heading:e.camera?.heading,state:e.state?.mode}),({heading:e,state:t})=>{if(null==e)return;if(this.isGlobal&&this.isGeographic||this.isWebMercatorOnPlateCarree)return void(this.heading=90*Math.round(e/90)%360);const i=Math.round(e)%360,r=Math.abs(i-this.heading);(2===t||Math.min(r,360-r)>=30)&&(this.heading=i)})],"overlayManager"),this.addHandles([_(()=>this.baseOpacity,()=>{this._handleLayerViewChanges(),this._updateTileTextures(this._evaluateTransparency()?1:2)},y),_(()=>this.hasCompositeBlendMode,()=>this._updateTileTextures(this._evaluateTransparency()?1:2),y),_(()=>this.backgroundColor,(e,t)=>{e?.equals(t)||(this._handleLayerViewChanges(),this._renderer.updateTileBackground(e))},f),_(()=>this.snapLevel,()=>this._viewChanged=!0,f),_(()=>this.view.pointsOfInterest,e=>{this._renderer.pointsOfInterest=e,this._watchUpdatingTracking.removeAll(),e&&this._watchUpdatingTracking.add(()=>e.focus?.renderLocation,()=>this._allTilesSorted=!1,{equals:S})}),_(()=>Q.TERRAIN_TILE_TREE_SHOW_TILES,t=>{t&&!this._treeDebugger?import("../layers/support/TerrainTileTree3DDebugger.js").then(({TerrainTileTree3DDebugger:t})=>{!this._treeDebugger&&Q.TERRAIN_TILE_TREE_SHOW_TILES&&(this._treeDebugger=new t({view:e}))}):t||(this._treeDebugger=h(this._treeDebugger))},T)]);const{spatialReference:a}=e;this._extentHelper=te(this.viewingMode,{layers:e.map.allLayers,layerViews:e.allLayerViews,viewSpatialReference:a});const n=new s({getCollections:()=>e.defaultsFromMap?.mapCollections?.map(({layers:e})=>e),getChildrenFunction:e=>e&&"layers"in e?e.layers:null}),l=new Fe({layers:n,extentHelper:this._extentHelper,viewingMode:this.viewingMode,viewSpatialReference:a});this._set("tilingSchemeLogic",l),this._updateTilingScheme();const o=t.scheduler;this._frameTask=o.registerTask(Ye.TERRAIN_SURFACE,this),this.addHandles([_(()=>this._extentHelper.stencilEnabledExtents,e=>this._renderer.setStencilEnabledLayerExtents(e),T),_(()=>this.tilingSchemeLogic.tilingScheme,()=>this._updateTilingScheme(),f),_(()=>this.groundExtent,()=>this._updateRootTiles(),T),e.on("resize",()=>this._viewChangeUpdate()),_(()=>{const t=e.state;return[this._lodBias,this.lodSnappingEnabled,e.quality,t.camera,t.contentCamera,t.fixedContentCamera]},()=>this._viewChangeUpdate(),y),_(()=>e.qualitySettings?.fadeDuration,e=>this._renderer.textureFadingEnabled=e>0,T),_(()=>e.qualitySettings?.physicallyBasedRenderingEnabled,e=>this._renderer.pbrMode=e?5:0,T),_(()=>e.qualitySettings?.tiledSurface.elevationLevelDelta,()=>this._updateAllTileGeometries()),_(()=>this.userClippingExtent,()=>this._updateClippingExtent(),f)]),this.addHandles(e.allLayerViews.on("after-changes",()=>this._layerViewsDirty=!0)),this._layerViewsDirty=!0,this._handleLayerViewChanges(),this._renderer.updateTileBackground(this.backgroundColor)}clearHandles(){this._watchUpdatingTracking?.removeAll(),this.removeAllHandles(),this._basemapLayerViewHandles.forEach((e,t)=>this._unregisterTiledLayerView(t)),this._basemapLayerViewHandles.clear()}destroy(){this._frameTask.remove(),this._frameTask=ze,this._watchUpdatingTracking?.destroy(),this._removeAllTiles(),this._set("tilingSchemeLogic",h(this.tilingSchemeLogic)),this._basemapLayerViewHandles.forEach((e,t)=>this._unregisterTiledLayerView(t)),this._basemapLayerViewHandles.clear(),this._set("overlayManager",h(this.overlayManager)),this._tileCache=h(this._tileCache),this._allTiles.prune(),je.prune(),this._treeDebugger=h(this._treeDebugger),this._renderer.destroyed||this._renderer.destroy(),this._renderer=null,this._iteratorPool=h(this._iteratorPool),this._upsampleMapCache=h(this._upsampleMapCache),this._elevationQueryCache=h(this._elevationQueryCache),this._set("view",null),this._extentHelper=h(this._extentHelper),this._upsampleInfoPool=h(this._upsampleInfoPool),ke(),this._layerViews.forEach(e=>e.length=0),this._performanceInfo=null}get renderer(){return this._renderer}get frustum(){return this.view.state.camera.frustum}get snapLevel(){return this.lodSnappingEnabled?this.view.terrainLevel:null}get lodSnappingEnabled(){return this.view.qualitySettings.tiledSurface.reduceTileLevelDifferences}get upsampleInfoPool(){return this._upsampleInfoPool}get upsampleMapCache(){return this._upsampleMapCache}get elevationQueryCache(){return this._elevationQueryCache}get hasStencilEnabledExtents(){return this._extentHelper.stencilEnabledExtents.length>0}get userClippingExtent(){const{spatialReference:e}=this,t=this.view?.clippingArea;if(null==t||null==e)return null;const i=I(),r=Y(t,i,e)?i:null,s=this._get("userClippingExtent");return k(r,s)?s:r}get rootTilesExtent(){return this._rootTilesExtent}get groundExtent(){const e=V(this.fullGroundExtent,this.userClippingExtent,I()),t=this._get("groundExtent");return k(e,t)?t:e}get fullGroundExtent(){return null!=this._tilingSchemeExtent?this._tilingSchemeExtent:this._rootTilesExtent}get _tilingSchemeExtent(){return this.tilingSchemeLogic?.extent}get updating(){return this._hasPendingUpdates||(this._maxNumUpdating=1),this.enabled&&!!((this.readyToRun||this._watchUpdatingTracking?.updating||this._asyncWorkItems>0)&&this.ready&&!this.suspended||this.overlayManager?.updating||this.terrainTextureCompressionTracker.compressing)}get readyToRun(){return this.enabled&&(this._hasPendingUpdates||this._viewChanged||this._allTilesDirty||!this._allTilesSorted||this._layerViewsDirty||this._scaleRangeQueries?.updating||this._frameTask.updating)&&this.ready&&!this.suspended}get updatingProgressValue(){return this._maxNumUpdating=Math.max(this._pendingUpdates,this._maxNumUpdating),1-this._pendingUpdates/this._maxNumUpdating}get baseOpacity(){return this.view?.map?.ground?.opacity??1}set baseOpacity(e){this.view.map.ground.opacity=e}get viewingMode(){return this.view.state.viewingMode}get ready(){return!this.enabled||null!=this._rootTiles}get rootTiles(){return this._rootTiles}get spatialReference(){return this.tilingScheme?.spatialReference??null}get backgroundColor(){return this.view?.map?.ground?.surfaceColor}set backgroundColor(e){this.view.map.ground.surfaceColor=e}set slicePlaneEnabled(e){this._renderer.slicePlaneEnabled=e,this._set("slicePlaneEnabled",e),this._evaluateTransparency()}get tilingSchemeLocked(){return this.tilingSchemeLogic?.tilingSchemeLocked??!1}get wireframe(){return this._renderer?.wireframe}set wireframe(e){e!==this._renderer.wireframe&&(this._renderer.wireframe=e,this._updateAllTileGeometries())}get opaque(){return 0===this._renderer.transparency}get invisible(){return 3===this._renderer.transparency}set suspended(e){this._set("suspended",e),this._viewChangeUpdate()}get fadeDuration(){return this.view.qualitySettings.fadeDuration??0}intersect(e,t,i,r){this._renderer.intersect(e,t,i,r)}getElevationLevelDelta(e){return e<4?3:this.view.qualitySettings.tiledSurface.elevationLevelDelta}get _xNormalizer(){return q(this._spatialReference)}getElevation(e,t,i,r){const s=this._rootTiles;if(!s?.length||!this.enabled)return null;if(0===s[0].layerInfo[0].length)return null;let a=this._elevationProjectorCache.get(r);if(void 0===a&&(a=M(r,this._spatialReference)??null,this._elevationProjectorCache.set(r,a)),null==a)return l.getLogger(this).error("TerrainSurface.getElevation(): could not project given point to tiling scheme coordinate system"),null;const n=b(it,e,t,i);a(n,0,n,0);return ot(s,this._xNormalizer?.normalize(n[0])??n[0],n[1])}getElevations(e,t,i){const r=this._rootTiles,s=r?r[0].layerInfo[0].length:0;if(r?.length&&0!==s&&this.enabled)for(let a=0;a<t;++a){const t=3*a;i(a,ot(r,e[t],e[t+1]))}else for(let a=0;a<t;++a)i(a,null)}getLayerIndexByUID(e,t){return this._layerIndexByUid[e].get(t)}getScale(e){if(!this.tilingScheme)return null;if(!D(e,it,this.spatialReference))return l.getLogger(this).error("TerrainSurface.getScale(): could not project given point to tiling scheme coordinate system"),null;const t=this._rootTiles;if(null!=t)for(const i of t)if(i?.containsPoint(it)){let e=i;for(;e.children[0]&&!e.rendered;){const t=e.children[0].extent;let i=0;it[0]>t[2]&&(i+=1),it[1]<t[1]&&(i+=2),e=e.children[i]}return this._getLodBiasCorrectedScale(e.level)}return 1/0}_ensureProjector(e){const t=this._projectorCache.get(e);if(t)return t;const i=M(e,this._tilingSchemeSpatialReference)??null;return this._projectorCache.set(e,i),i}getSphereElevationRange(e,t){if(!this.enabled||null==this._rootTiles)return null;const i=this._ensureProjector(t);if(null==i)return l.getLogger(this).error("TerrainSurface.getSphereElevationRange(): could not project given point to tiling scheme coordinate system"),null;rt.copyFrom(e),i(rt.center,0,rt.center,0);const r=new z,s=this._rootTiles;if(null!=s){const e=[];for(const i of s)e.push(i);let t=0;for(;t<e.length;){const i=e[t];if(++t,!A(i.extent,rt))continue;const s=i.children;if(null==s[0]||i.rendered)r.expandElevationRangeValues(i.elevationBoundsMin,i.elevationBoundsMax);else for(const t of s)e.push(t)}}return r}getRootElevationRange(){return this.enabled&&null!=this._rootTiles?new z(this._rootTileElevationRange.minElevation,this._rootTileElevationRange.maxElevation):null}getLowerBoundRadius(){const e=(this._ellipsoid.radius+this.visibleElevationRange.minElevation)*R;return Math.min(e,this._ellipsoid.radius)}getSphereScale(e,t){if(!this.tilingScheme)return null;if(!D(e,rt.center,this.spatialReference))return l.getLogger(this).error("TerrainSurface.getSphereScale(): could not project given point to tiling scheme coordinate system"),null;rt.radius=t;let i=null;const r=e=>{if(e&&A(e.extent,rt)){const t=e.children;if(t[0]&&!e.rendered)for(const e of t)r(e);else{const t=this._getLodBiasCorrectedScale(e.level);i=null==i?t:Math.min(i,t)}}},s=this._rootTiles;if(null!=s)for(const a of s)r(a);return i}queryVisibleScaleRange(e,t,i,r){if(!this._scaleRangeQueries)return;const s=t?this.tilingScheme.levelAtScale(t):0,a=i?this.tilingScheme.levelAtScale(i):1/0,n=this._lodBias;this._scaleRangeQueries.queryVisibleLevelRange(e,s+n,a+n,r)}_evaluateTransparency(){const e=this.baseOpacity,t=this.overlayManager.renderer.isEmpty,i=this._renderer.transparency,r=this._isFullyTransparent?t?3:2:e>=1&&!this.hasCompositeBlendMode&&!this._renderer.slicePlaneEnabled?0:1;return this._renderer.transparency=r,i!==r&&(this.notifyChange("opaque"),this.notifyChange("invisible"),!0)}_updateTilingScheme(){const{tilingScheme:e}=this.tilingSchemeLogic;if(!(e!==this.tilingScheme))return;_e(!!e,"tiling scheme cannot be reset to undefined"),this._isGlobal=!this.view?.state?.isLocal,this.tilingScheme&&this._removeAllTiles();const t=e?.spatialReference??U.WebMercator;this._spatialReference=t,this._isWebMercator=!!t?.isWebMercator,this._isWebMercatorOnPlateCarree=this._isWebMercator&&F(this.view?.renderSpatialReference),this._isGeographic=t?.isGeographic??!1,this._set("tilingScheme",e),this._tilingSchemeSpatialReference=this.tilingScheme?.spatialReference,this._projectorCache.clear(),this._updateClippingExtent(),e&&(this._updateTiledLayers(),this._renderer.tileSize=e.pixelSize,this.overlayManager.spatialReference=e.spatialReference,this._updateRootTiles())}static{this._tileMemcacheKey="TerrainTileMemcache"}_acquireTile(e,t,i,r){const s=this._tileCache.pop(Ze._tileMemcacheKey);return s?(s.init(e,t,i,r,this),s):new this._tileConstructor(e,t,i,r,this)}get updatingRootTiles(){return this._updatingRootTiles}_updateRootTiles(){const{groundExtent:e,tilingScheme:t}=this;if(!t)return;if(!this.enabled)return void this._setRootTiles(null);const i=st;let s=t.rootTilesInExtent(e,i,5*he);if(null!=this._rootTiles){if(s.length>he)return void l.getLogger(this).warn(de);const e=this._rootTiles.map(e=>e.lij),t=r(e,s,Ie);if(this._updatingRootTiles=!0,t.removed.length>0||t.added.length>0){const e=this._rootTiles.filter(e=>!(t.removed.findIndex(t=>Ie(t,e.lij))>-1)||(this._purgeTile(e),!1));t.added.forEach(t=>e.push(this._newRootTile(t))),this._setRootTiles(e)}}else this._updatingRootTiles=!0,s.length>he&&(l.getLogger(this).warn(pe),s=t.rootTilesInExtent(e,i,he)),this._setRootTiles(s.map(e=>this._newRootTile(e)));k(i,this._rootTilesExtent)||(this._rootTilesExtent=I(i)),this.renderer.visible=!0,this._viewChangeUpdate(),this.overlayManager.setPlacementDirty(),this.notifyChange("ready"),this._updateAllTileGeometries(),this._updatingRootTiles=!1,this.checkAllTilesWaterproofness()}_updateAllTileGeometries(){const e=this._allTiles.filter(e=>e.loaded&&e.intersectsClippingArea);e.sort(Oe),e.forEach(e=>this._renderer.updateTileGeometryState(e)),e.forEach(e=>e.renderData.updateNeighborData()),this._updateTilesGeometries(e),this._pendingTilesToUpdate.clear()}_updateTilesGeometries(e){if(0===e.length)return;e.sort(Oe);const t=this.renderer;e.forEach(e=>t.updateGeometryIfNeeded(e)),e.forEach(e=>this._pendingTilesForElevationUpdateEvent.add(e))}_shouldSplit(e){return 1===e.shouldSplit(this._splitLimits,this._eyePosRenderSR,this.snapLevel)}_newRootTile(e){const t=this._acquireTile(0,e[1],e[2],null);return this._shouldSplit(t)&&t.setPendingUpdate(1),this._loadTile(t),this._markTileToUpdate(t),this._updateRootTileElevationRange(),t}_setRootTiles(e){if(this._rootTiles=e,this._allTiles.clear(),null!=e){const t=this._iteratorPool.acquire();for(t.reset(e);!t.done;)this._allTiles.push(t.next());t.remove()}this._renderer.setRootTiles(this._rootTiles),this._updateTilesVisibility(e),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles})}_runViewChangeUpdateIfDirty(){this._viewChangeUpdateDirty&&(this._viewChangeUpdateDirty=!1,this._viewChangeUpdate())}_viewChangeUpdate(){this.view&&!this.suspended&&this.tilingScheme&&this.renderer.visible&&(this._inFrameTask?this._viewChangeUpdateDirty=!0:(this._viewChangeUpdateDirty=!1,this._updateViewDependentParameters(),this._updateTilesVisibility(this._rootTiles)))}_updateClippingStatus(e){e.updateClippingStatus(this.groundExtent)&&e.resetPendingUpdate(8)&&this._updateTileGeometryState(e)}_updateTilesVisibility(e){if(null==e)return;const t=Ge(e),i=this.visibleElevationRange;let r=t?i.minElevation:1/0,s=t?i.maxElevation:-1/0;const a=this.groundExtent,n=this.view.state.contentCamera.viewProjectionMatrix;this.setTileTreeDirty(!1);const l=this._iteratorPool.acquire();for(l.reset(e);!l.done;){const e=l.next();e.updateClippingStatus(a)&&e.resetPendingUpdate(8)&&this._updateTileGeometryState(e),e.computeVisibility(),e.updateScreenDepth(n),e.renderData&&(r=Math.min(e.elevationBoundsMin,r),s=Math.max(e.elevationBoundsMax,s))}l.remove(),this._viewChanged=!0,this._allTilesDirty=!0,this._updatePendingTileGeometries(),isFinite(r)&&isFinite(s)&&(i.minElevation!==r||i.maxElevation!==s)&&(this.visibleElevationRange=new K(r,s))}_updateRootTileElevationRange(){let e=1/0,t=-1/0;const i=this._rootTiles;null!=i&&i.forEach(({elevationBoundsMin:i,elevationBoundsMax:r})=>{e=Math.min(e,i),t=Math.max(t,r)});const r=this._rootTileElevationRange;r.minElevation===e&&r.maxElevation===t||(this._rootTileElevationRange=new K(e,t))}_updateViewDependentParameters(){const{camera:e,contentCamera:t}=this.view.state,i=Math.tan(.5*t.fovX),r=Math.tan(.5*t.fovY),s=this.tilingScheme.pixelSize,a=2**-this._lodBias*e.pixelRatio;this._splitLimits.aboveGround=e.aboveGround,this._splitLimits.fovX=i,this._splitLimits.fovY=r,this._splitLimits.relativeWidthLimit=s/e.width*this.maxTextureScale*a,this._splitLimits.relativeHeightLimit=s/e.height*this.maxTextureScale*a,this._splitLimits.maxLod=this.tilingScheme.getMaxLod(),this._splitLimits.angledSplitBias=this.view.qualitySettings.tiledSurface.angledSplitBias,this.view.state.fixedContentCamera?this._splitLimits.frustum=G(this._splitLimits.frustum??N(),t.frustum):this._splitLimits.frustum=null,E(this._eyePosRenderSR,t.eye),j(e.eye,this.view.renderSpatialReference,this._eyePosSurfaceSR,this.spatialReference)}_updateTileGeometryState(e){e.updateVisibility();this._renderer.updateTileGeometryState(e)&&this._markTileToUpdate(e),this.setMemoryDirty()}_markAllTileNeighborsForUpdate(e){e.forEachLoadedNeighbor(e=>{this._layerViews[1].some(ye)&&e.setPendingUpdate(32),this._pendingTilesToUpdate.add(e)})}_updateTileTexture(e,t){const i=e.resetPendingUpdate(32)?32:!!e.resetPendingUpdate(16)&&16;i&&(this._renderer.updateTileTexture(e,i),this._usedMemory=null,t.madeProgress())}_emitElevationUpdateEventForTiles(){if(!this._shouldEmitChangeEvent)return;const e=nt.extent;B(e),this._pendingTilesForElevationUpdateEvent.forEach(t=>O(e,t.extent,e)),this._pendingTilesForElevationUpdateEvent.clear(),nt.spatialReference=this.spatialReference,this.emit("elevation-change",nt),this._shouldEmitChangeEvent=!1}runTask(e){this._handleLayerViewChanges(e),this._frameTask.processQueue(e),this.renderer.processScaleRangeQueries(this._scaleRangeQueries,e),this._inFrameTask=!0,this._pendingUpdates=0,this._hasPendingUpdates=!1,this._updateAllTilesStatus(e),this._sortTiles(e);const t=!this.view.state.fixedContentCamera;if(this._mergeAndSplit(e,t),this._updateElevation(e),this._updateTextures(e),t||this._mergeAndSplit(e,!0),this._inFrameTask=!1,this._runViewChangeUpdateIfDirty(),this._updatePendingTileGeometries(),this._emitElevationUpdateEventForTiles(),e.done&&e.hasProgressed&&this.requestUpdate(),this.notifyChange("updatingProgressValue"),Le&&this._checkTileInvariant(),!e.hasProgressed)return Je}_checkTileInvariant(){const e=new Map;this._allTiles.forAll(t=>e.set(t,new Set)),this._allTiles.forAll(t=>{if(_e(t.rendered===t.leaf,` rendered ${t.rendered} != ${t.leaf} leaf`),!t.leaf){const e=e=>0===e.unmergableChildCount&&0===e.maxLevelDeltaNeighborCount,i=t.children.reduce((t,i)=>t+(e(i)?0:1),0);if(_e(t.unmergableChildCount===i,` Tile[${t.lij.toString()}] unmergeable child count mismatch: actual ${t.unmergableChildCount} vs ${i}`),t.hasPendingUpdate(4)){_e(!t.hasPendingUpdate(1),"Tile can be both split and merge at the same time");for(const e of t.children)_e(e.leaf||e.hasPendingUpdate(4),"Child of tile to merge must also merge")}}for(let i=0;i<4;++i){if(t.rendered){const e=t.renderData?.geometryState.edgePeerNeighbors[i];if(null!=e){{const r=t.level-e.level<=ue;r||(console.log(`tile level delta [${t.lij.toString()}] vs [${e.lij.toString()}] > ${ue} (edge[${i}])`),_e(r,`tile level delta [${t.level}] vs [${e.level}] > ${ue}`))}_e(t.level-e.level<=ue,`Max tile lod delta exceeded: [${t.lij.toString()}] vs [${e.lij.toString()}]`)}}const r=t.level-ue,s=e=>e.leaf||e.level===t.level,a=t.findNeighborTile(fe[i],s);if(null!=a){if(t.leaf&&t.level>=ue){let i=a;for(;t.level-i.level<ue;)i=i.parent;const s=[r,t.lij[1]>>ue,t.lij[2]>>ue];if(!Ie(s,i.lij)){const r=e.get(i);_e(!r.has(t),"Cannot already have neighbor"),r.add(t)}}_e(a.rendered||a.level===t.level,"Non-same-level-neighbor of rendered must be rendered"),_e(t.level-a.level<=ue,`Tile level delta [${t.level}] vs [${a.level}] > ${ue}`)}}}),this._allTiles.forAll(t=>{const i=t.maxLevelDeltaNeighborCount,r=e.get(t);_e(i===r.size,`Tile[${t.lij.toString()}] merge-blocker mismatch: actual ${i} vs ${r.size}`)})}_updateAllTilesStatus(e){if(!this._viewChanged||!this._rootTiles||e.done)return;this._viewChanged=!1;const t=new ae(this._allTiles.length);t.pushAll(this._rootTiles);const i=this.snapLevel,r=this._splitLimits,s=this._eyePosRenderSR;this._allTiles.forAll(e=>{e.maxLevelDeltaNeighborCount=0,e.unmergableChildCount=0});const a=this.view.state.contentCamera.viewProjectionMatrix;for(;!t.empty;){const e=t.pop(),n=e.parent,l=n?.hasPendingUpdate(4),o=l?4:e.shouldSplit(r,s,i),h=1===o;e.leaf?ht(e,h):t.pushAll(e.children),l?(e.resetPendingUpdate(1),e.leaf||e.setPendingUpdate(4),this._updateClippingStatus(e),e.updateVisibility(),e.updateScreenDepth(a)):h?(e.resetPendingUpdate(4),e.leaf&&e.setPendingUpdate(1)):(e.resetPendingUpdate(1)&&e.updateAgentSuspension(),2===o&&e.updateAgents(0),e.leaf||(e.setPendingUpdate(4),e.resetPendingUpdate(1)))}this.requestUpdate(),(this._shortBatches||!this._oneBatchPerFrameTask)&&this._updatePendingTileGeometries(),e.madeProgress()}_sortTiles(e){e.done||this._allTilesSorted||!this.view.pointsOfInterest?.focus||(Ne(this._allTiles,this.view.pointsOfInterest.focus.renderLocation),this._allTilesSorted=!0,this._treeDebugger?.update(),e.madeProgress())}_markTileToUpdate(e){Te(e.loaded),e.intersectsClippingArea&&(this._pendingTilesToUpdate.add(e),this._markAllTileNeighborsForUpdate(e))}_updatePendingTileGeometries(){const e=this._pendingTilesToUpdate,t=Array.from(e.keys()).filter(e=>e.loaded&&e.intersectsClippingArea);if(0===t.length)return void e.clear();const i=(i,r)=>{!r?.loaded||!r.intersectsClippingArea||r.level<i.level||e.has(r)||(e.add(r),t.push(r),r.renderData.updateNeighborData())};t.sort(Oe);const r=t.length;for(let s=0;s<r;++s){const r=t[s];Te(r.loaded),Te(r.intersectsClippingArea);const a=r.renderData;a.updateNeighborData();const n=a.dirtyEdgeResolutions,l=a.geometryState,o=e=>{const t=De[e];i(r,l.cornerPeerNeighbors[e]?.findCorner(Pe(t),e=>e.loaded))};for(let t=0;t<4;++t)if(n&1<<t){const s=a.geometryState.edgePeerNeighbors[t];s&&s?.level>=r.level&&s.forAllSubtreeOnSide(ve(fe[t]),t=>!(!t.loaded||!t.intersectsClippingArea)&&(Te(e.has(t)||Oe(r,t)<0),i(r,t),!0)),o((t+1)%4),o(t)}}e.clear(),this._updateTilesGeometries(t),this._shouldEmitChangeEvent=!0,Le&&Re&&this.checkAllTilesWaterproofness()}_mergeAndSplit(e,t){if(this.suspended||e.done||!this._allTilesDirty)return;this._allTilesDirty=!1,this.requestUpdate();let i=!1;const r=this.view.state.fixedContentCamera;let s=!1;for(;!e.done;){s=!0;let a=!1;const n=!this._allTiles.some(s=>{if(!i&&!r&&!s.visible)return e.done;let n=s;if(s.hasPendingUpdate(4)){if(!t||s.unmergableChildCount>0)return e.done;for(s.resetPendingUpdate(4);null!=n.parent&&0===n.parent.unmergableChildCount&&n.parent.resetPendingUpdate(4);)n=n.parent;this._mergeTile(n),a=!0,e.madeProgress()}else if(s.resetPendingUpdate(1)){let t=!0;const i=s.level;if(i>=ue){const e=e=>e.leaf||i-e.level<ue;for(let r=0;r<4;++r){const a=s.findNeighborTile(fe[r],e);null!=a&&i-a.level===ue&&(t=!1,Le&&(Te(a.leaf),Te(a.hasPendingUpdate(1))))}}t?(this._splitTile(s),e.madeProgress(),a=!0):s.setPendingUpdate(1)}return e.done});if(a&&(this._allTilesSorted=!1,this._allTilesDirty=!0,!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries()),n){if(!i){i=!0;continue}if(!a)break}else this._allTilesDirty=!0}s?e.madeProgress():this._allTilesDirty=!0,!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries(),this._allTilesCreated=!this.allTiles.some(e=>e.hasPendingUpdate(1)||e.hasPendingUpdate(4)),this._sortTiles(e)}_updateElevation(e){e.done||(this._allTiles.some(t=>(t.resetPendingUpdate(8)&&(this._updateTileGeometryState(t),this._shortBatches&&this._updatePendingTileGeometries(),e.madeProgress()),e.done)),!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries())}_updateTextures(e){e.done||this._allTiles.some(t=>(this._updateTileTexture(t,e),e.done))}_updateClippingExtent(){this.spatialReference&&(this.updateOverlayParameters(),this.requestRender(1),this.overlayManager.setPlacementDirty(),this._updateRootTiles())}get _lodBias(){return this.view.qualitySettings.tiledSurface.lodBias-(1-this.view.quality)*ce}_getLodBiasCorrectedScale(e){const t=this.tilingScheme.levels,i=o(e-this._lodBias,0,t.length-1),r=i-Math.floor(i);return t[Math.floor(i)].scale*(1-r)+t[Math.ceil(i)].scale*r}_removeAllTiles(){null!=this._rootTiles&&(this._rootTiles.forEach(e=>this._purgeTile(e)),this._setRootTiles(null),this.notifyChange("ready")),this._allTiles.clear(),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles}),this.renderer.visible=!1}_purgeSubtree(e){const t=e.children;t[0]&&(this._purgeTile(t[0]),this._purgeTile(t[1]),this._purgeTile(t[2]),this._purgeTile(t[3]),e.clearChildren())}_purgeTile(e){e.leaf?pt(e):this._purgeSubtree(e),this._allTiles.removeUnordered(e),this._unloadTile(e),e.dispose(),this._tileCache.put(Ze._tileMemcacheKey,e),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles})}_unloadTile(e){this._pendingTilesToUpdate.delete(e),this._pendingTilesForElevationUpdateEvent.delete(e),e.unload()}_splitTile(e){_e(e.leaf,"Tile that is already split should not be split again!"),_e(e.rendered,"Tile marked to split is not rendered"),pt(e);const t=e.createChildren();this._allTiles.pushArray(t),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles}),e.updateAgentSuspension(),_e(e.rendered,"parent should be rendered"),t.forEach(e=>this._loadTile(e)),t.forEach(e=>this._pendingTilesToUpdate.add(e)),this._unloadTile(e),this._markAllTileNeighborsForUpdate(e),this._emitTileScaleChange(e,e.level+1),this._allTilesDirty=!0,this._shortBatches&&this._updatePendingTileGeometries(),t.forEach(e=>ht(e,e.hasPendingUpdate(1))),++this._performanceInfo.numSplit}_emitTileScaleChange(e,t=e.level){lt.spatialReference=this.spatialReference,lt.extent=e.extent,lt.scale=this._getLodBiasCorrectedScale(t),this.emit("scale-change",lt)}createTile(e,t,i,r){_e(!!r,"createTile sanity check");const s=this._acquireTile(e,t,i,r);return s.updateClippingStatus(this.groundExtent),s.updateScreenDepth(this.view.state.contentCamera.viewProjectionMatrix),this._shouldSplit(s)&&s.setPendingUpdate(1),s}get _shortBatches(){return 2!==this.view.state.mode}_mergeTile(e){_e(!e.hasPendingUpdate(1),"_mergeTile sanity check"),_e(!e.leaf,"Cannot merge a leaf"),e.leaf||(this._purgeSubtree(e),_e(!e.renderData,"Merging tile with existing render data?"),this._loadTile(e),this._markTileToUpdate(e),this._emitTileScaleChange(e),this._shortBatches&&this._updatePendingTileGeometries(),ht(e,!1),this._allTilesDirty=!0,++this._performanceInfo.numMerged)}_loadTile(e){e.load(),this.requestUpdate(),this._allTilesDirty=!0,this.overlayManager?.hasOverlays&&e.updateOverlayParameters(this.overlayManager)}_handleLayerViewChanges(e=Xe){if(!this._layerViewsDirty)return;this._layerViewsDirty=!1;let t=!1;const i=new Set;let r=-1;for(let s=this.view.allLayerViews.length-1;s>=0;s--){const e=this.view.allLayerViews.items[s];if(i.add(e.uid),we(e)||Ce(e))if(this._basemapLayerViewHandles.has(e.uid)&&!Ce(e)){const i=this._layerClassFromLayerView(e),s=this.getLayerIndexByUID(i,e.uid);null!=s&&((s<r||null==r)&&(t=!0),r=s)}else this._registerTiledLayerView(e),e.layer.loaded&&(t=!0)}this._basemapLayerViewHandles.forEach((e,r)=>{i.has(r)||(this._unregisterTiledLayerView(r),t=!0)}),t&&this._updateTiledLayers(),this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._evaluateTransparency(),e.madeProgress()}get _isFullyTransparent(){if(this.view.map?.ground?.opacity>0)return!1;for(const e of this.view.allLayerViews.items)if(Se(e)&&!$(e.layer)&&0!==e.fullOpacity)return!1;return!0}_hasCompositeBlendMode(){for(const e of this.view.allLayerViews.items)if((be(e)||Ce(e))&&He($e[e.layer.blendMode]))return!0;return!1}_layerClassFromLayerView(e){return Ee(e)?0:1}_registerTiledLayerView(e){const t=[];if((be(e)||Ce(e))&&t.push(_(()=>e.layer.blendMode,()=>{this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._updateTileTextures(2)})),!Ce(e)){const i=this._layerClassFromLayerView(e);t.push(_(()=>!e.destroyed&&e.suspended,()=>this._updateTiledLayers())),t.push(_(()=>!e.destroyed&&e.fullOpacity,()=>this._updateTileTextures(2)));const{layer:r}=e;"effectiveScaleRange"in r&&t.push(_(()=>!e.destroyed&&r.effectiveScaleRange,()=>this._restartAllAgents(i))),t.push(e.on("data-changed",()=>{const t=this.getLayerIndexByUID(i,e.uid);null!=t&&this._invalidateLayerData(t,i)}))}this._unregisterTiledLayerView(e.uid),this._basemapLayerViewHandles.set(e.uid,t)}_unregisterTiledLayerView(e){const t=this._basemapLayerViewHandles.get(e);if(t){for(const e of t)e.remove();this._basemapLayerViewHandles.delete(e)}}_updateTiledLayers(){if(!this.tilingScheme||this.view.suspended)return;const e=this.view.allLayerViews,t=[[],[]];let i=null;e.forEach(e=>{if(!e.layer||e.suspended||!we(e)||!e.fullExtent)return;const r=this._layerClassFromLayerView(e);if(1===r){const t=e.displayLevelRange.maxLevel;t!==1/0&&(null===i||t>i)&&(i=t)}t[r].push(e)});for(const r of ie){const e=this._layerViews[r],i=t[r];i.reverse();const s=i.length;let a=e.length!==s;const n=new Array(s),l=new Array(e.length);this._layerIndexByUid[r].clear();for(let t=0;t<s;t++){const s=i[t].uid;this._layerIndexByUid[r].set(s,t);const o=e.indexOf(i[t]);n[t]=o,t!==o&&(a=!0),o>-1&&(l[o]=t)}if(a){const e=this._postorderIterator;for(e.reset(this._rootTiles);!e.done;)e.next().modifyLayers(l,n,r);this._layerViews[r]=i,this._restartAllAgents(r),this._updateTilesVisibility(this._rootTiles)}}this.tilingScheme.ensureMaxLod(i)&&(this._viewChangeUpdate(),this.notifyChange("tilingScheme"))}_restartAllAgents(e){const t=this._postorderIterator;for(t.reset(this._rootTiles);!t.done;){const i=t.next();i.restartAgents(e),0===e&&i.computeElevationBounds()}this._updateRootTileElevationRange()}layerViewByIndex(e,t){return this._layerViews[t][e]}numLayers(e){return this._layerViews[e].length}_updateTileTextures(e){this._allTiles.forAll(t=>{t.updateAgents(1),1===e?this.renderer.updateTileTexture(t,16):t.updateRenderData(1,e)}),this._evaluateTransparency()}_invalidateLayerData(e,t){null!=this._rootTiles&&(qe(this._rootTiles,i=>i.removeLayerAgent(e,t)),qe(this._rootTiles,i=>{i.invalidateLayerData(e,t),i.restartAgents(t)}))}setTileTreeDirty(e){this._allTilesDirty=!0,e&&(this._allTilesCreated=!1)}requestRender(e=1){this.renderer.setNeedsRender(e)}requestUpdate(){1===++this._pendingUpdates&&(this._hasPendingUpdates=!0)}requestTileData(e,t,i,r){const s=this.layerViewByIndex(t,i),a=s.layer;return!a.tilemapCache||ye(s)?this._requestTileData(e,i,s,r):(++this._asyncWorkItems,a.tilemapCache.fetchAvailability(e.level,e.lij[1],e.lij[2],{...r,timeout:6e3}).then(()=>--this._asyncWorkItems).catch(t=>{throw--this._asyncWorkItems,c(r),g(t)||this._dataMissing(e,i,s),t}).then(()=>this._frameTask.schedule(()=>this._requestTileData(e,i,s,r),r.signal)))}_requestTileData(e,t,i,r){if(this.destroying)return Promise.resolve();return 0===t?Ee(i)?this._requestElevationTileData(e,i,r):Promise.reject():Se(i)?this._requestMapTileData(e,i,r):Promise.reject()}_requestElevationTileData(e,t,i){++this._asyncWorkItems;const r=r=>{!m(i)&&r&&(this.setMemoryDirty(),this.requestUpdate(),this._elevationDataArrived(e,t,r))},s=i=>{g(i)||(l.getLogger(this).error(`Tile ${e.lij.toString()} layer 0/${t.uid} error ${i}`),this._dataMissing(e,0,t),this.requestUpdate())};return t.fetchElevationTile(e,i).then(e=>this._frameTask.schedule(()=>r(e)),s).finally(()=>--this._asyncWorkItems)}_elevationDataArrived(e,t,i){const r=this._layerIndexByUid[0].get(t.uid);if(null==r)return void l.getLogger(this).warn("TerrainSurface: received data from unknown layer %d %s",0,e.lij.toString());const s=new J(e.lij,e.extent,i);e.dataArrived(r,0,s),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:0});const a=[e],n=e.level,o=this._iteratorPool.acquire();for(o.reset(a);!o.done;){const e=o.next();e.findElevationBoundsForLayer(r,n),e.computeElevationBounds()}0===n&&this._updateRootTileElevationRange(),o.remove(),this._updateTilesVisibility(a)}_requestMapTileData(e,t,i){++this._asyncWorkItems;const r=(r,s)=>{xe(s),m(i)||(console.error(`Tile ${e.lij.toString()} layer 1/${t.uid} error ${r}`),this._dataMissing(e,1,t),this.requestUpdate())},s=e=>t=>r(t,e),a=r=>this._frameTask.schedule(()=>{this.requestUpdate(),m(i)?xe(r):this._mapTileDataArrived(e,t,r)},i.signal,s(r)).catch(s(r)),n=(e,t=null)=>this._frameTask.schedule(()=>r(e,t));return t.fetchTile(e.lij,i).then(a,n).finally(()=>--this._asyncWorkItems)}_mapTileDataArrived(e,t,i){const r=this.getLayerIndexByUID(1,t.uid);if(null==r)return xe(i),void l.getLogger(this).warn("TerrainSurface: received data from unknown layer");e.dataArrived(r,1,i),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:1})}_dataMissing(e,t,i){const r=this.getLayerIndexByUID(t,i.uid);null!=r?(e.dataMissing(r,t),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:t})):l.getLogger(this).warn("TerrainSurface: received data from unknown layer")}get performanceInfo(){const e=this._performanceInfo;return e.numNodes=this._allTiles.length,e.numLeaves=e.numVisible=e.numRendered=e.numLoadedPerLevel.length=e.numRenderedPerLevel.length=0,this._allTiles.forAll(t=>{t.leaf&&e.numLeaves++;const i=t.level;t.renderData&&(e.numLoadedPerLevel[i]=(e.numLoadedPerLevel[i]||0)+1),t.visible&&(e.numVisible++,t.rendered&&(e.numRenderedPerLevel[i]=(e.numRenderedPerLevel[i]||0)+1,e.numRendered++))}),e}setMemoryDirty(){this._usedMemory=null}get usedMemory(){return this.tilingScheme?(null==this._usedMemory&&(this._usedMemory=this._recalculateUsedMemory()),this._usedMemory??0):0}_recalculateUsedMemory(){return this.tilingScheme?Math.round(this._allTiles.reduce((e,t)=>e+t.usedMemory,0)):null}getUsedMemoryForLayerView(e){let t=0;const i=this._layerClassFromLayerView(e),r=this.getLayerIndexByUID(i,e.uid);return null!=r&&this._allTiles.forAll(e=>t+=e.getUsedMemoryForLayer(i,r)),t}get renderPatchBorders(){return this._renderer.renderPatchBorders}set renderPatchBorders(e){this._renderer.renderPatchBorders=e}get renderingDisabled(){return this._renderer.renderingDisabled}set renderingDisabled(e){this._renderer.renderingDisabled=e}get test(){}checkAllTilesWaterproofness(){if(!Re)return;const e=this._rootTiles;if(null==e)return;const t=e=>e?.renderData?.geometry?.indices?.length>0,i=(e,i)=>{t(e)&&console.error("Tile[",e.lij,"] has geometry although parent[",i.lij,"] has geom")},r=e=>{if(e.intersectsClippingArea)if(e.renderData&&!e.renderData.geometryState&&console.error("Tile[",e.lij,"] has renderData but not geometryState"),e.renderData&&!e.renderData.geometry&&console.error("Tile[",e.lij,"] has renderData but not geometryInfo"),!e.renderData?.geometry||(e.renderData.geometry.indices?.length??0)>0||console.error("Tile[",e.lij,"] has renderData but no indices - geometryInfo: ",e.renderData.geometry),t(e)){e.checkGeometryWaterproofness();for(const t of e.children)i(t,e)}else if(e.leaf)console.error("Tile[",e.lij,"] has no geometry and no children, from root to leaf");else for(const t of e.children)r(t)},s=e=>{const t=e.parent?.visible??!0,i=e.visible;e.computeVisibility();const r=e.visible;if(i!==r&&t&&console.error(" Tile[",e.lij,"] has out of date visibility: ",i," instead of ",r),!e.leaf)for(const a of e.children)s(a)};for(const a of e)r(a),s(a)}get isGlobal(){return this._isGlobal}get isGeographic(){return this._isGeographic}get isWebMercator(){return this._isWebMercator}get isWebMercatorOnPlateCarree(){return this._isWebMercatorOnPlateCarree}isEastEndWrap(e){return this._isGlobal&&e[2]===this.lijEastEnd(e[0])-1}isWestEndWrap(e){return this._isGlobal&&0===e[2]}lijEastEnd(e){return 1<<e+(this._isGeographic?1:0)}wrapEastWest(e){const t=this.lijEastEnd(e[0]),i=e[2];if(0<=i&&i<t)return e;if(!this._isGlobal)return null;const r=(i+(i<0?t:0))%t;return[e[0],e[1],r]}enableInternalChecks(e){Ue(e)}enableWaterproofnessChecks(e){Me(e)}static cleanupTerrainSurface(){at.prune()}enable(e){e!==this.enabled&&(this._set("enabled",e),e?(this._updateRootTiles(),this.suspended=!1,this.view.elevationProvider.register(0,this)):(this.view.elevationProvider.unregister(this),this.suspended=!0,this._removeAllTiles(),this._setRootTiles(null)),this.notifyChange("ready"))}updateOverlayParameters(){const{overlayManager:e}=this;this.allTiles.forAll(t=>t.updateOverlayParameters(e))}};e([w()],et.prototype,"_renderer",void 0),e([w({constructOnly:!0})],et.prototype,"_scaleRangeQueries",void 0),e([w({constructOnly:!0})],et.prototype,"view",void 0),e([w({constructOnly:!0})],et.prototype,"overlayManager",void 0),e([w({constructOnly:!0})],et.prototype,"terrainTextureCompressionTracker",void 0),e([w()],et.prototype,"_hasPendingUpdates",void 0),e([w()],et.prototype,"_asyncWorkItems",void 0),e([w()],et.prototype,"_allTilesDirty",void 0),e([w()],et.prototype,"_allTilesSorted",void 0),e([w()],et.prototype,"allTilesCreated",null),e([w()],et.prototype,"_allTilesCreated",void 0),e([w()],et.prototype,"_viewChanged",void 0),e([w({type:Number})],et.prototype,"heading",void 0),e([w()],et.prototype,"_splitLimits",void 0),e([w({readOnly:!0})],et.prototype,"_watchUpdatingTracking",void 0),e([w()],et.prototype,"_frameTask",void 0),e([w()],et.prototype,"demResolution",null),e([w({readOnly:!0})],et.prototype,"snapLevel",null),e([w({readOnly:!0})],et.prototype,"lodSnappingEnabled",null),e([w({readOnly:!0})],et.prototype,"userClippingExtent",null),e([w()],et.prototype,"_rootTilesExtent",void 0),e([w({readOnly:!0})],et.prototype,"groundExtent",null),e([w({readOnly:!0})],et.prototype,"fullGroundExtent",null),e([w({readOnly:!0})],et.prototype,"_tilingSchemeExtent",null),e([w({readOnly:!0})],et.prototype,"updating",null),e([w({readOnly:!0})],et.prototype,"readyToRun",null),e([w(X)],et.prototype,"updatingProgress",void 0),e([w({readOnly:!0})],et.prototype,"updatingProgressValue",null),e([w()],et.prototype,"_maxNumUpdating",void 0),e([w()],et.prototype,"baseOpacity",null),e([w()],et.prototype,"hasCompositeBlendMode",void 0),e([w({readOnly:!0})],et.prototype,"viewingMode",null),e([w()],et.prototype,"maxTextureScale",void 0),e([w({readOnly:!0})],et.prototype,"ready",null),e([w({readOnly:!0})],et.prototype,"rootTiles",null),e([w()],et.prototype,"_rootTiles",void 0),e([w({readOnly:!0})],et.prototype,"spatialReference",null),e([w({type:t})],et.prototype,"backgroundColor",null),e([w({value:!1})],et.prototype,"slicePlaneEnabled",null),e([w({readOnly:!0})],et.prototype,"tilingScheme",void 0),e([w({readOnly:!0})],et.prototype,"tilingSchemeLocked",null),e([w({readOnly:!0})],et.prototype,"tilingSchemeLogic",void 0),e([w()],et.prototype,"wireframe",null),e([w()],et.prototype,"opaque",null),e([w()],et.prototype,"invisible",null),e([w({value:!1})],et.prototype,"suspended",null),e([w()],et.prototype,"fadeDuration",null),e([w()],et.prototype,"_xNormalizer",null),e([w()],et.prototype,"visibleElevationRange",void 0),e([w()],et.prototype,"_rootTileElevationRange",void 0),e([w()],et.prototype,"_layerViewsDirty",void 0),e([w()],et.prototype,"renderPatchBorders",null),e([w()],et.prototype,"renderingDisabled",null),e([w({readOnly:!0})],et.prototype,"enabled",void 0),et=Ze=e([C("esri.views.3d.terrain.TerrainSurface")],et);const tt=et,it=x(),rt=new W,st=I(),at=new u,nt=new ee("ground"),lt={spatialReference:null,extent:null,scale:0};function ot(e,t,i){for(const r of e){if(!r.containsPointXY(t,i))continue;let e=r;for(;e&&!e.renderData;){const r=(t>e.extentMidX?1:0)+(i<e.extentMidY?2:0);e=e.children[r]}const s=e?.renderData?.geometryState.samplerData??null;return Z(t,i,s)}return null}function ht(e,t){!e.leaf||e.level<ue||ct(e,e=>{t&&dt(e);const i=ut(e);if(e.maxLevelDeltaNeighborCount++,i){let t=e.parent;for(;t;){const e=ut(t);if(t.unmergableChildCount++,!e)break;t=t.parent}}})}function dt(e){if(e.hasPendingUpdate(1))return;let t=e.parent;for(;t?.resetPendingUpdate(4);)t=t.parent;e.resetPendingUpdate(4),e.leaf&&e.setPendingUpdate(1),e.level<ue||ct(e,e=>{dt(e)})}function pt(e){e.level<ue||ct(e,e=>{if(e.maxLevelDeltaNeighborCount--,0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount){let t=e.parent;for(;t&&(t.unmergableChildCount--,ut(t));)t=t.parent}})}function ut(e){return 0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount}function ct(e,t){if(e.level<ue)return;const i=e.level-ue,r=e.lij[1]>>ue,s=e.lij[2]>>ue,a=e=>e.leaf||e.level===i;for(let n=0;n<4;++n){const l=e.findNeighborTile(fe[n],a);if(!l||l.level!==i)continue;const o=l.lij;o[1]===r&&o[2]===s||t(l)}}export{tt as default};
2
+ import{__decorate as e}from"tslib";import t from"../../../Color.js";import{filterInPlace as i,difference as r}from"../../../core/arrayUtils.js";import s from"../../../core/CollectionFlattener.js";import{toConst as a}from"../../../core/compilerUtils.js";import{EventedAccessor as n}from"../../../core/Evented.js";import"../../../core/has.js";import l from"../../../core/Logger.js";import{clamp as o}from"../../../core/mathUtils.js";import{destroyMaybe as h}from"../../../core/maybe.js";import{MemCachePool as d}from"../../../core/MemCachePool.js";import p from"../../../core/ObjectPool.js";import u from"../../../core/PooledArray.js";import{throwIfAborted as c,isAbortError as g,isAborted as m}from"../../../core/promiseUtils.js";import{watch as _,syncAndInitial as y,sync as f,initial as T}from"../../../core/reactiveUtils.js";import{getMetersPerUnitForSR as v}from"../../../core/units.js";import{property as w,subclass as C}from"../../../core/accessorSupport/decorators.js";import{exactEquals as S,set as b,copy as E}from"../../../core/libs/gl-matrix-2/math/vec3.js";import{create as x}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{UpdatingHandles as L}from"../../../core/support/UpdatingHandles.js";import{getReferenceEllipsoid as P,radiusModifier as R}from"../../../geometry/ellipsoidUtils.js";import U from"../../../geometry/SpatialReference.js";import{getProjector as M}from"../../../geometry/projection/projectors.js";import{projectPointToVector as D}from"../../../geometry/projection/projectPointToVector.js";import{projectVectorToVector as j}from"../../../geometry/projection/projectVectorToVector.js";import{create as I,equals as k,intersection as V,intersectsSphere as A,empty as B,expand as O}from"../../../geometry/support/aaBoundingRect.js";import{copy as G,create as N}from"../../../geometry/support/frustum.js";import{createSpatialReferenceCyclical as q}from"../../../geometry/support/normalizeUtils.js";import{isPlateCarree as F}from"../../../geometry/support/spatialReferenceUtils.js";import{Sphere as W}from"../../../geometry/support/sphere.js";import{ElevationQueryTileCache as H}from"../../../layers/support/ElevationQueryTileCache.js";import{isBaseLayer as $}from"../../../layers/support/layerUtils.js";import{debugFlags as Q}from"../support/debugFlags.js";import{ElevationRange as z}from"../support/ElevationRange.js";import{toBoundingRect as Y}from"../support/extentUtils.js";import{updatingProgress as X}from"../support/updatingProperties.js";import{ElevationBounds as K}from"./ElevationBounds.js";import{ElevationData as J,sampleElevation as Z}from"./ElevationData.js";import{ElevationUpdateEvent as ee}from"./ElevationUpdateEvent.js";import{create as te}from"./ExtentHelper.js";import{LayerClasses as ie}from"./LayerClass.js";import{OverlayManager as re}from"./OverlayManager.js";import{PlanarPatch as se}from"./PlanarPatch.js";import{Queue as ae}from"./Queue.js";import{ScaleRangeQueries as ne}from"./ScaleRangeQueries.js";import{SphericalPatch as le}from"./SphericalPatch.js";import{SplitLimits as oe}from"./SplitLimits.js";import{maxRootTiles as he,tooManyRootTilesAfterChangeError as de,tooManyRootTilesForLayerError as pe,maxTileNeighborLevelDelta as ue,maxMemoryLodBias as ce}from"./TerrainConst.js";import{TerrainRenderer as ge}from"./TerrainRenderer.js";import me from"./TerrainSurfacePerformanceInfo.js";import{weakAssert as _e,isVectorTileLayerView as ye,neighborEdgeIndices as fe,internalAssert as Te,oppositeEdge as ve,isSurfaceLayerView as we,isGroupLayerView as Ce,isMapTileLayerView as Se,isBlendableLayerView as be,isElevationLayerView as Ee,releaseTerrainData as xe,enableTerrainInternalChecks as Le,oppositeCorner as Pe,enableWaterproofTests as Re,enableInternalTerrainChecks as Ue,enableTerrainWaterproofChecks as Me,neighborCornerIndices as De}from"./terrainUtils.js";import{Tile as je,lijEquals as Ie}from"./Tile.js";import{printAllocations as ke}from"./TilePerLayerInfo.js";import{sortTiles as Ve,IteratorPreorder as Ae,IteratorPostorder as Be,compareTilesByLij as Oe,hasLoadableSiblings as Ge,sortTilesByPOI as Ne,traverseTilesPreorder as qe}from"./tileUtils.js";import{TilingSchemeLogic as Fe}from"./TilingSchemeLogic.js";import{UpsampleInfo as We}from"./UpsampleInfo.js";import{isCompositeBlendMode as He,blendModeFromString as $e}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{hasLayerBasedScaleVisibility as Qe}from"../../support/layerViewUtils.js";import{ImmediateTask as ze,TaskPriority as Ye,noBudget as Xe}from"../../support/Scheduler.js";import{TextureCompressionTracker as Ke}from"../../support/TextureCompressionTracker.js";import{Yield as Je}from"../../support/Yield.js";var Ze;let et=class extends n{static{Ze=this}get allTilesCreated(){return this._allTilesCreated}get allTiles(){return a(this._allTiles)}get renderedTiles(){return Ve(i(this._allTiles.toArray(),e=>e.visible&&e.rendered))}get demResolution(){const{_allTiles:e,tilingScheme:t}=this;if(0===e.length)return{min:1,max:1};const i=v(t.spatialReference);let r=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(const a of e){const e=t.resolutionAtLevel(a.level)*i;r=Math.min(r,e),s=Math.max(s,e)}return{min:r,max:s}}constructor(e){super(e),this.terrainTextureCompressionTracker=new Ke,this._iteratorPool=new p(()=>new Ae,e=>e.remove=()=>this._iteratorPool.release(e)),this._postorderIterator=new Be,this._hasPendingUpdates=!1,this._pendingUpdates=0,this._asyncWorkItems=0,this._allTilesDirty=!0,this._allTilesSorted=!0,this._allTilesCreated=!1,this._usedMemory=null,this._performanceInfo=new me,this._viewChanged=!1,this.heading=0,this._inFrameTask=!1,this._viewChangeUpdateDirty=!1,this._eyePosRenderSR=x(),this._eyePosSurfaceSR=x(),this._splitLimits=new oe,this._layerViews=[new Array,new Array],this._layerIndexByUid=[new Map,new Map],this._basemapLayerViewHandles=new Map,this._watchUpdatingTracking=new L,this._frameTask=ze,this._allTiles=new u,this._upsampleInfoPool=new p(()=>new We),this._shouldEmitChangeEvent=!1,this._rootTilesExtent=I(),this.updatingProgress=.5,this._maxNumUpdating=1,this.maxTextureScale=1.2,this._spatialReference=U.WebMercator,this._elevationProjectorCache=new Map,this.visibleElevationRange=new z(1/0,-1/0),this._rootTileElevationRange=new z(1/0,-1/0),this._projectorCache=new Map,this._tilingSchemeSpatialReference=null,this._updatingRootTiles=!1,this._pendingTilesForElevationUpdateEvent=new Set,this._pendingTilesToUpdate=new Set,this.totalGeometryUpdates=0,this.totalTileUpdates=0,this._oneBatchPerFrameTask=!0,this._layerViewsDirty=!1,this.unloadedMemory=0,this.ignoresMemoryFactor=!1,this._isWebMercator=!1,this._isWebMercatorOnPlateCarree=!1,this.enabled=!0;const{view:t}=e;this.overlayManager=new re({...e,terrainSurface:this}),this._isGlobal=!t.state?.isLocal,this._isGeographic=this._spatialReference?.isGeographic??!1,this._tileConstructor=this._isGlobal?le:se,this._ellipsoid=P(t.spatialReference),this._renderer=new ge(this.overlayManager.renderer,t.stage,this._allTiles,this.terrainTextureCompressionTracker,t.resourceController.memoryController),Qe()||(this._scaleRangeQueries=new ne)}initialize(){const{view:e}=this,{resourceController:t}=e,{memoryController:i}=t;this._tileCache=new d((e,t)=>i.newCache(e,t),"terrain-tile"),this._upsampleMapCache=i.newCache("terrain-upsample",({tile:e})=>e.unloadMapData()),this._elevationQueryCache=new H(i.newCache("elevation-query"));const r=this.overlayManager;this.addHandles([_(()=>r.renderer.isEmpty,()=>this._evaluateTransparency()),_(()=>this.renderer.visible,e=>this.suspended=!e),_(()=>this.heading,e=>{this._renderer.updateHeading(e),this._updateTileTextures(0)},y),_(()=>({heading:e.camera?.heading,state:e.state?.mode}),({heading:e,state:t})=>{if(null==e)return;if(this.isGlobal&&this.isGeographic||this.isWebMercatorOnPlateCarree)return void(this.heading=90*Math.round(e/90)%360);const i=Math.round(e)%360,r=Math.abs(i-this.heading);(2===t||Math.min(r,360-r)>=30)&&(this.heading=i)})],"overlayManager"),this.addHandles([_(()=>this.baseOpacity,()=>{this._handleLayerViewChanges(),this._updateTileTextures(this._evaluateTransparency()?1:2)},y),_(()=>this.hasCompositeBlendMode,()=>this._updateTileTextures(this._evaluateTransparency()?1:2),y),_(()=>this.backgroundColor,(e,t)=>{e?.equals(t)||(this._handleLayerViewChanges(),this._renderer.updateTileBackground(e))},f),_(()=>this.snapLevel,()=>this._viewChanged=!0,f),_(()=>this.view.pointsOfInterest,e=>{this._renderer.pointsOfInterest=e,this._watchUpdatingTracking.removeAll(),e&&this._watchUpdatingTracking.add(()=>e.focus?.renderLocation,()=>this._allTilesSorted=!1,{equals:S})}),_(()=>Q.TERRAIN_TILE_TREE_SHOW_TILES,t=>{t&&!this._treeDebugger?import("../layers/support/TerrainTileTree3DDebugger.js").then(({TerrainTileTree3DDebugger:t})=>{!this._treeDebugger&&Q.TERRAIN_TILE_TREE_SHOW_TILES&&(this._treeDebugger=new t({view:e}))}):t||(this._treeDebugger=h(this._treeDebugger))},T)]);const{spatialReference:a}=e;this._extentHelper=te(this.viewingMode,{layers:e.map.allLayers,layerViews:e.allLayerViews,viewSpatialReference:a});const n=new s({getCollections:()=>e.defaultsFromMap?.mapCollections?.map(({layers:e})=>e),getChildrenFunction:e=>e&&"layers"in e?e.layers:null}),l=new Fe({layers:n,extentHelper:this._extentHelper,viewingMode:this.viewingMode,viewSpatialReference:a});this._set("tilingSchemeLogic",l),this._updateTilingScheme();const o=t.scheduler;this._frameTask=o.registerTask(Ye.TERRAIN_SURFACE,this),this.addHandles([_(()=>this._extentHelper.stencilEnabledExtents,e=>this._renderer.setStencilEnabledLayerExtents(e),T),_(()=>this.tilingSchemeLogic.tilingScheme,()=>this._updateTilingScheme(),f),_(()=>this.groundExtent,()=>this._updateRootTiles(),T),e.on("resize",()=>this._viewChangeUpdate()),_(()=>{const t=e.state;return[this._lodBias,this.lodSnappingEnabled,e.quality,t.camera,t.contentCamera,t.fixedContentCamera]},()=>this._viewChangeUpdate(),y),_(()=>e.qualitySettings?.fadeDuration,e=>this._renderer.textureFadingEnabled=e>0,T),_(()=>e.qualitySettings?.physicallyBasedRenderingEnabled,e=>this._renderer.pbrMode=e?5:0,T),_(()=>e.qualitySettings?.tiledSurface.elevationLevelDelta,()=>this._updateAllTileGeometries()),_(()=>this.userClippingExtent,()=>this._updateClippingExtent(),f)]),this.addHandles(e.allLayerViews.on("after-changes",()=>this._layerViewsDirty=!0)),this._layerViewsDirty=!0,this._handleLayerViewChanges(),this._renderer.updateTileBackground(this.backgroundColor)}clearHandles(){this._watchUpdatingTracking?.removeAll(),this.removeAllHandles(),this._basemapLayerViewHandles.forEach((e,t)=>this._unregisterTiledLayerView(t)),this._basemapLayerViewHandles.clear()}destroy(){this._frameTask.remove(),this._frameTask=ze,this._watchUpdatingTracking?.destroy(),this._removeAllTiles(),this._set("tilingSchemeLogic",h(this.tilingSchemeLogic)),this._basemapLayerViewHandles.forEach((e,t)=>this._unregisterTiledLayerView(t)),this._basemapLayerViewHandles.clear(),this._set("overlayManager",h(this.overlayManager)),this._tileCache=h(this._tileCache),this._allTiles.prune(),je.prune(),this._treeDebugger=h(this._treeDebugger),this._renderer.destroyed||this._renderer.destroy(),this._renderer=null,this._iteratorPool=h(this._iteratorPool),this._upsampleMapCache=h(this._upsampleMapCache),this._elevationQueryCache=h(this._elevationQueryCache),this._set("view",null),this._extentHelper=h(this._extentHelper),this._upsampleInfoPool=h(this._upsampleInfoPool),ke(),this._layerViews.forEach(e=>e.length=0),this._performanceInfo=null}get renderer(){return this._renderer}get frustum(){return this.view.state.camera.frustum}get snapLevel(){return this.lodSnappingEnabled?this.view.terrainLevel:null}get lodSnappingEnabled(){return this.view.qualitySettings.tiledSurface.reduceTileLevelDifferences}get upsampleInfoPool(){return this._upsampleInfoPool}get upsampleMapCache(){return this._upsampleMapCache}get elevationQueryCache(){return this._elevationQueryCache}get hasStencilEnabledExtents(){return this._extentHelper.stencilEnabledExtents.length>0}get userClippingExtent(){const{spatialReference:e}=this,t=this.view?.clippingArea;if(null==t||null==e)return null;const i=I(),r=Y(t,i,e)?i:null,s=this._get("userClippingExtent");return k(r,s)?s:r}get rootTilesExtent(){return this._rootTilesExtent}get groundExtent(){const e=V(this.fullGroundExtent,this.userClippingExtent,I()),t=this._get("groundExtent");return k(e,t)?t:e}get fullGroundExtent(){return null!=this._tilingSchemeExtent?this._tilingSchemeExtent:this._rootTilesExtent}get _tilingSchemeExtent(){return this.tilingSchemeLogic?.extent}get updating(){return this._hasPendingUpdates||(this._maxNumUpdating=1),this.enabled&&!!((this.readyToRun||this._watchUpdatingTracking?.updating||this._asyncWorkItems>0)&&this.ready&&!this.suspended||this.overlayManager?.updating||this.terrainTextureCompressionTracker.compressing)}get readyToRun(){return this.enabled&&(this._hasPendingUpdates||this._viewChanged||this._allTilesDirty||!this._allTilesSorted||this._layerViewsDirty||this._scaleRangeQueries?.updating||this._frameTask.updating)&&this.ready&&!this.suspended}get updatingProgressValue(){return this._maxNumUpdating=Math.max(this._pendingUpdates,this._maxNumUpdating),1-this._pendingUpdates/this._maxNumUpdating}get baseOpacity(){return this.view?.map?.ground?.opacity??1}set baseOpacity(e){this.view.map.ground.opacity=e}get viewingMode(){return this.view.state.viewingMode}get ready(){return!this.enabled||null!=this._rootTiles}get rootTiles(){return this._rootTiles}get spatialReference(){return this.tilingScheme?.spatialReference??null}get backgroundColor(){return this.view?.map?.ground?.surfaceColor}set backgroundColor(e){this.view.map.ground.surfaceColor=e}set slicePlaneEnabled(e){this._renderer.slicePlaneEnabled=e,this._set("slicePlaneEnabled",e),this._evaluateTransparency()}get tilingSchemeLocked(){return this.tilingSchemeLogic?.tilingSchemeLocked??!1}get wireframe(){return this._renderer?.wireframe}set wireframe(e){e!==this._renderer.wireframe&&(this._renderer.wireframe=e,this._updateAllTileGeometries())}get opaque(){return 0===this._renderer.transparency}get invisible(){return 3===this._renderer.transparency}set suspended(e){this._set("suspended",e),this._viewChangeUpdate()}get fadeDuration(){return this.view.qualitySettings.fadeDuration??0}intersect(e,t,i,r){this._renderer.intersect(e,t,i,r)}getElevationLevelDelta(e){return e<4?3:this.view.qualitySettings.tiledSurface.elevationLevelDelta}get _xNormalizer(){return q(this._spatialReference)}getElevation(e,t,i,r){const s=this._rootTiles;if(!s?.length||!this.enabled)return null;if(0===s[0].layerInfo[0].length)return null;let a=this._elevationProjectorCache.get(r);if(void 0===a&&(a=M(r,this._spatialReference)??null,this._elevationProjectorCache.set(r,a)),null==a)return l.getLogger(this).error("TerrainSurface.getElevation(): could not project given point to tiling scheme coordinate system"),null;const n=b(it,e,t,i);a(n,0,n,0);return ot(s,this._xNormalizer?.normalize(n[0])??n[0],n[1])}getElevations(e,t,i){const r=this._rootTiles,s=r?r[0].layerInfo[0].length:0;if(r?.length&&0!==s&&this.enabled)for(let a=0;a<t;++a){const t=3*a;i(a,ot(r,e[t],e[t+1]))}else for(let a=0;a<t;++a)i(a,null)}getLayerIndexByUID(e,t){return this._layerIndexByUid[e].get(t)}getScale(e){if(!this.tilingScheme)return null;if(!D(e,it,this.spatialReference))return l.getLogger(this).error("TerrainSurface.getScale(): could not project given point to tiling scheme coordinate system"),null;const t=this._rootTiles;if(null!=t)for(const i of t)if(i?.containsPoint(it)){let e=i;for(;e.children[0]&&!e.rendered;){const t=e.children[0].extent;let i=0;it[0]>t[2]&&(i+=1),it[1]<t[1]&&(i+=2),e=e.children[i]}return this._getLodBiasCorrectedScale(e.level)}return 1/0}_ensureProjector(e){const t=this._projectorCache.get(e);if(t)return t;const i=M(e,this._tilingSchemeSpatialReference)??null;return this._projectorCache.set(e,i),i}getSphereElevationRange(e,t){if(!this.enabled||null==this._rootTiles)return null;const i=this._ensureProjector(t);if(null==i)return l.getLogger(this).error("TerrainSurface.getSphereElevationRange(): could not project given point to tiling scheme coordinate system"),null;rt.copyFrom(e),i(rt.center,0,rt.center,0);const r=new z,s=this._rootTiles;if(null!=s){const e=[];for(const i of s)e.push(i);let t=0;for(;t<e.length;){const i=e[t];if(++t,!A(i.extent,rt))continue;const s=i.children;if(null==s[0]||i.rendered)r.expandElevationRangeValues(i.elevationBoundsMin,i.elevationBoundsMax);else for(const t of s)e.push(t)}}return r}getRootElevationRange(){return this.enabled&&null!=this._rootTiles?new z(this._rootTileElevationRange.minElevation,this._rootTileElevationRange.maxElevation):null}getLowerBoundRadius(){const e=(this._ellipsoid.radius+this.visibleElevationRange.minElevation)*R;return Math.min(e,this._ellipsoid.radius)}getSphereScale(e,t){if(!this.tilingScheme)return null;if(!D(e,rt.center,this.spatialReference))return l.getLogger(this).error("TerrainSurface.getSphereScale(): could not project given point to tiling scheme coordinate system"),null;rt.radius=t;let i=null;const r=e=>{if(e&&A(e.extent,rt)){const t=e.children;if(t[0]&&!e.rendered)for(const e of t)r(e);else{const t=this._getLodBiasCorrectedScale(e.level);i=null==i?t:Math.min(i,t)}}},s=this._rootTiles;if(null!=s)for(const a of s)r(a);return i}queryVisibleScaleRange(e,t,i,r){if(!this._scaleRangeQueries)return;const s=t?this.tilingScheme.levelAtScale(t):0,a=i?this.tilingScheme.levelAtScale(i):1/0,n=this._lodBias;this._scaleRangeQueries.queryVisibleLevelRange(e,s+n,a+n,r)}_evaluateTransparency(){const e=this.baseOpacity,t=this.overlayManager.renderer.isEmpty,i=this._renderer.transparency,r=this._isFullyTransparent?t?3:2:e>=1&&!this.hasCompositeBlendMode&&!this._renderer.slicePlaneEnabled?0:1;return this._renderer.transparency=r,i!==r&&(this.notifyChange("opaque"),this.notifyChange("invisible"),!0)}_updateTilingScheme(){const{tilingScheme:e}=this.tilingSchemeLogic;if(!(e!==this.tilingScheme))return;_e(!!e,"tiling scheme cannot be reset to undefined"),this._isGlobal=!this.view?.state?.isLocal,this.tilingScheme&&this._removeAllTiles();const t=e?.spatialReference??U.WebMercator;this._spatialReference=t,this._isWebMercator=!!t?.isWebMercator,this._isWebMercatorOnPlateCarree=this._isWebMercator&&F(this.view?.renderSpatialReference),this._isGeographic=t?.isGeographic??!1,this._set("tilingScheme",e),this._tilingSchemeSpatialReference=this.tilingScheme?.spatialReference,this._projectorCache.clear(),this._updateClippingExtent(),e&&(this._updateTiledLayers(),this._renderer.tileSize=e.pixelSize,this.overlayManager.spatialReference=e.spatialReference,this._updateRootTiles())}static{this._tileMemcacheKey="TerrainTileMemcache"}_acquireTile(e,t,i,r){const s=this._tileCache.pop(Ze._tileMemcacheKey);return s?(s.init(e,t,i,r,this),s):new this._tileConstructor(e,t,i,r,this)}get updatingRootTiles(){return this._updatingRootTiles}_updateRootTiles(){const{groundExtent:e,tilingScheme:t}=this;if(!t)return;if(!this.enabled)return void this._setRootTiles(null);const i=st;let s=t.rootTilesInExtent(e,i,5*he);if(null!=this._rootTiles){if(s.length>he)return void l.getLogger(this).warn(de);const e=this._rootTiles.map(e=>e.lij),t=r(e,s,Ie);if(this._updatingRootTiles=!0,t.removed.length>0||t.added.length>0){const e=this._rootTiles.filter(e=>!(t.removed.findIndex(t=>Ie(t,e.lij))>-1)||(this._purgeTile(e),!1));t.added.forEach(t=>e.push(this._newRootTile(t))),this._setRootTiles(e)}}else this._updatingRootTiles=!0,s.length>he&&(l.getLogger(this).warn(pe),s=t.rootTilesInExtent(e,i,he)),this._setRootTiles(s.map(e=>this._newRootTile(e)));k(i,this._rootTilesExtent)||(this._rootTilesExtent=I(i)),this.renderer.visible=!0,this._viewChangeUpdate(),this.overlayManager.setPlacementDirty(),this.notifyChange("ready"),this._updateAllTileGeometries(),this._updatingRootTiles=!1,this.checkAllTilesWaterproofness()}_updateAllTileGeometries(){const e=this._allTiles.filter(e=>e.loaded&&e.intersectsClippingArea);e.sort(Oe),e.forEach(e=>this._renderer.updateTileGeometryState(e)),e.forEach(e=>e.renderData.updateNeighborData()),this._updateTilesGeometries(e),this._pendingTilesToUpdate.clear()}_updateTilesGeometries(e){if(0===e.length)return;e.sort(Oe);const t=this.renderer;e.forEach(e=>t.updateGeometryIfNeeded(e)),e.forEach(e=>this._pendingTilesForElevationUpdateEvent.add(e))}_shouldSplit(e){return 1===e.shouldSplit(this._splitLimits,this._eyePosRenderSR,this.snapLevel)}_newRootTile(e){const t=this._acquireTile(0,e[1],e[2],null);return this._shouldSplit(t)&&t.setPendingUpdate(1),this._loadTile(t),this._markTileToUpdate(t),this._updateRootTileElevationRange(),t}_setRootTiles(e){if(this._rootTiles=e,this._allTiles.clear(),null!=e){const t=this._iteratorPool.acquire();for(t.reset(e);!t.done;)this._allTiles.push(t.next());t.remove()}this._renderer.setRootTiles(this._rootTiles),this._updateTilesVisibility(e),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles})}_runViewChangeUpdateIfDirty(){this._viewChangeUpdateDirty&&(this._viewChangeUpdateDirty=!1,this._viewChangeUpdate())}_viewChangeUpdate(){this.view&&!this.suspended&&this.tilingScheme&&this.renderer.visible&&(this._inFrameTask?this._viewChangeUpdateDirty=!0:(this._viewChangeUpdateDirty=!1,this._updateViewDependentParameters(),this._updateTilesVisibility(this._rootTiles)))}_updateClippingStatus(e){e.updateClippingStatus(this.groundExtent)&&e.resetPendingUpdate(8)&&this._updateTileGeometryState(e)}_updateTilesVisibility(e){if(null==e)return;const t=Ge(e),i=this.visibleElevationRange;let r=t?i.minElevation:1/0,s=t?i.maxElevation:-1/0;const a=this.groundExtent,n=this.view.state.contentCamera.viewProjectionMatrix;this.setTileTreeDirty(!1);const l=this._iteratorPool.acquire();for(l.reset(e);!l.done;){const e=l.next();e.updateClippingStatus(a)&&e.resetPendingUpdate(8)&&this._updateTileGeometryState(e),e.computeVisibility(),e.updateScreenDepth(n),e.renderData&&(r=Math.min(e.elevationBoundsMin,r),s=Math.max(e.elevationBoundsMax,s))}l.remove(),this._viewChanged=!0,this._allTilesDirty=!0,this._updatePendingTileGeometries(),isFinite(r)&&isFinite(s)&&(i.minElevation!==r||i.maxElevation!==s)&&(this.visibleElevationRange=new K(r,s))}_updateRootTileElevationRange(){let e=1/0,t=-1/0;const i=this._rootTiles;null!=i&&i.forEach(({elevationBoundsMin:i,elevationBoundsMax:r})=>{e=Math.min(e,i),t=Math.max(t,r)});const r=this._rootTileElevationRange;r.minElevation===e&&r.maxElevation===t||(this._rootTileElevationRange=new K(e,t))}_updateViewDependentParameters(){const{camera:e,contentCamera:t}=this.view.state,i=Math.tan(.5*t.fovX),r=Math.tan(.5*t.fovY),s=this.tilingScheme.pixelSize,a=2**-this._lodBias*e.pixelRatio;this._splitLimits.aboveGround=e.aboveGround,this._splitLimits.fovX=i,this._splitLimits.fovY=r,this._splitLimits.relativeWidthLimit=s/e.width*this.maxTextureScale*a,this._splitLimits.relativeHeightLimit=s/e.height*this.maxTextureScale*a,this._splitLimits.maxLod=this.tilingScheme.getMaxLod(),this._splitLimits.angledSplitBias=this.view.qualitySettings.tiledSurface.angledSplitBias,this.view.state.fixedContentCamera?this._splitLimits.frustum=G(this._splitLimits.frustum??N(),t.frustum):this._splitLimits.frustum=null,E(this._eyePosRenderSR,t.eye),j(e.eye,this.view.renderSpatialReference,this._eyePosSurfaceSR,this.spatialReference)}_updateTileGeometryState(e){e.updateVisibility();this._renderer.updateTileGeometryState(e)&&this._markTileToUpdate(e),this.setMemoryDirty()}_markAllTileNeighborsForUpdate(e){e.forEachLoadedNeighbor(e=>{this._layerViews[1].some(ye)&&e.setPendingUpdate(32),this._pendingTilesToUpdate.add(e)})}_updateTileTexture(e,t){const i=e.resetPendingUpdate(32)?32:!!e.resetPendingUpdate(16)&&16;i&&(this._renderer.updateTileTexture(e,i),this._usedMemory=null,t.madeProgress())}_emitElevationUpdateEventForTiles(){if(!this._shouldEmitChangeEvent)return;const e=nt.extent;B(e),this._pendingTilesForElevationUpdateEvent.forEach(t=>O(e,t.extent,e)),this._pendingTilesForElevationUpdateEvent.clear(),nt.spatialReference=this.spatialReference,this.emit("elevation-change",nt),this._shouldEmitChangeEvent=!1}runTask(e){this._handleLayerViewChanges(e),this._frameTask.processQueue(e),this.renderer.processScaleRangeQueries(this._scaleRangeQueries,e),this._inFrameTask=!0,this._pendingUpdates=0,this._hasPendingUpdates=!1,this._updateAllTilesStatus(e),this._sortTiles(e);const t=!this.view.state.fixedContentCamera;if(this._mergeAndSplit(e,t),this._updateElevation(e),this._updateTextures(e),t||this._mergeAndSplit(e,!0),this._inFrameTask=!1,this._runViewChangeUpdateIfDirty(),this._updatePendingTileGeometries(),this._emitElevationUpdateEventForTiles(),e.done&&e.hasProgressed&&this.requestUpdate(),this.notifyChange("updatingProgressValue"),Le&&this._checkTileInvariant(),!e.hasProgressed)return Je}_checkTileInvariant(){const e=new Map;this._allTiles.forAll(t=>e.set(t,new Set)),this._allTiles.forAll(t=>{if(_e(t.rendered===t.leaf,` rendered ${t.rendered} != ${t.leaf} leaf`),!t.leaf){const e=e=>0===e.unmergableChildCount&&0===e.maxLevelDeltaNeighborCount,i=t.children.reduce((t,i)=>t+(e(i)?0:1),0);if(_e(t.unmergableChildCount===i,` Tile[${t.lij.toString()}] unmergeable child count mismatch: actual ${t.unmergableChildCount} vs ${i}`),t.hasPendingUpdate(4)){_e(!t.hasPendingUpdate(1),"Tile can be both split and merge at the same time");for(const e of t.children)_e(e.leaf||e.hasPendingUpdate(4),"Child of tile to merge must also merge")}}for(let i=0;i<4;++i){if(t.rendered){const e=t.renderData?.geometryState.edgePeerNeighbors[i];if(null!=e){{const r=t.level-e.level<=ue;r||(console.log(`tile level delta [${t.lij.toString()}] vs [${e.lij.toString()}] > ${ue} (edge[${i}])`),_e(r,`tile level delta [${t.level}] vs [${e.level}] > ${ue}`))}_e(t.level-e.level<=ue,`Max tile lod delta exceeded: [${t.lij.toString()}] vs [${e.lij.toString()}]`)}}const r=t.level-ue,s=e=>e.leaf||e.level===t.level,a=t.findNeighborTile(fe[i],s);if(null!=a){if(t.leaf&&t.level>=ue){let i=a;for(;t.level-i.level<ue;)i=i.parent;const s=[r,t.lij[1]>>ue,t.lij[2]>>ue];if(!Ie(s,i.lij)){const r=e.get(i);_e(!r.has(t),"Cannot already have neighbor"),r.add(t)}}_e(a.rendered||a.level===t.level,"Non-same-level-neighbor of rendered must be rendered"),_e(t.level-a.level<=ue,`Tile level delta [${t.level}] vs [${a.level}] > ${ue}`)}}}),this._allTiles.forAll(t=>{const i=t.maxLevelDeltaNeighborCount,r=e.get(t);_e(i===r.size,`Tile[${t.lij.toString()}] merge-blocker mismatch: actual ${i} vs ${r.size}`)})}_updateAllTilesStatus(e){if(!this._viewChanged||!this._rootTiles||e.done)return;this._viewChanged=!1;const t=new ae(this._allTiles.length);t.pushAll(this._rootTiles);const i=this.snapLevel,r=this._splitLimits,s=this._eyePosRenderSR;this._allTiles.forAll(e=>{e.maxLevelDeltaNeighborCount=0,e.unmergableChildCount=0});const a=this.view.state.contentCamera.viewProjectionMatrix;for(;!t.empty;){const e=t.pop(),n=e.parent,l=n?.hasPendingUpdate(4),o=l?4:e.shouldSplit(r,s,i),h=1===o;e.leaf?ht(e,h):t.pushAll(e.children),l?(e.resetPendingUpdate(1),e.leaf||e.setPendingUpdate(4),this._updateClippingStatus(e),e.updateVisibility(),e.updateScreenDepth(a)):h?(e.resetPendingUpdate(4),e.leaf&&e.setPendingUpdate(1)):(e.resetPendingUpdate(1)&&e.updateAgentSuspension(),2===o&&e.updateAgents(0),e.leaf||(e.setPendingUpdate(4),e.resetPendingUpdate(1)))}this.requestUpdate(),(this._shortBatches||!this._oneBatchPerFrameTask)&&this._updatePendingTileGeometries(),e.madeProgress()}_sortTiles(e){e.done||this._allTilesSorted||!this.view.pointsOfInterest?.focus||(Ne(this._allTiles,this.view.pointsOfInterest.focus.renderLocation),this._allTilesSorted=!0,this._treeDebugger?.update(),e.madeProgress())}_markTileToUpdate(e){Te(e.loaded),e.intersectsClippingArea&&(this._pendingTilesToUpdate.add(e),this._markAllTileNeighborsForUpdate(e))}_updatePendingTileGeometries(){const e=this._pendingTilesToUpdate,t=Array.from(e.keys()).filter(e=>e.loaded&&e.intersectsClippingArea);if(0===t.length)return void e.clear();const i=(i,r)=>{!r?.loaded||!r.intersectsClippingArea||r.level<i.level||e.has(r)||(e.add(r),t.push(r),r.renderData.updateNeighborData())};t.sort(Oe);const r=t.length;for(let s=0;s<r;++s){const r=t[s];Te(r.loaded),Te(r.intersectsClippingArea);const a=r.renderData;a.updateNeighborData();const n=a.dirtyEdgeResolutions,l=a.geometryState,o=e=>{const t=De[e];i(r,l.cornerPeerNeighbors[e]?.findCorner(Pe(t),e=>e.loaded))};for(let t=0;t<4;++t)if(n&1<<t){const s=a.geometryState.edgePeerNeighbors[t];s&&s?.level>=r.level&&s.forAllSubtreeOnSide(ve(fe[t]),t=>!(!t.loaded||!t.intersectsClippingArea)&&(Te(e.has(t)||Oe(r,t)<0),i(r,t),!0)),o((t+1)%4),o(t)}}e.clear(),this._updateTilesGeometries(t),this._shouldEmitChangeEvent=!0,Le&&Re&&this.checkAllTilesWaterproofness()}_mergeAndSplit(e,t){if(this.suspended||e.done||!this._allTilesDirty)return;this._allTilesDirty=!1,this.requestUpdate();let i=!1;const r=this.view.state.fixedContentCamera;let s=!1;for(;!e.done;){s=!0;let a=!1;const n=!this._allTiles.some(s=>{if(!i&&!r&&!s.visible)return e.done;let n=s;if(s.hasPendingUpdate(4)){if(!t||s.unmergableChildCount>0)return e.done;for(s.resetPendingUpdate(4);null!=n.parent&&0===n.parent.unmergableChildCount&&n.parent.resetPendingUpdate(4);)n=n.parent;this._mergeTile(n),a=!0,e.madeProgress()}else if(s.resetPendingUpdate(1)){let t=!0;const i=s.level;if(i>=ue){const e=e=>e.leaf||i-e.level<ue;for(let r=0;r<4;++r){const a=s.findNeighborTile(fe[r],e);null!=a&&i-a.level===ue&&(t=!1,Le&&(Te(a.leaf),Te(a.hasPendingUpdate(1))))}}t?(this._splitTile(s),e.madeProgress(),a=!0):s.setPendingUpdate(1)}return e.done});if(a&&(this._allTilesSorted=!1,this._allTilesDirty=!0,!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries()),n){if(!i){i=!0;continue}if(!a)break}else this._allTilesDirty=!0}s?e.madeProgress():this._allTilesDirty=!0,!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries(),this._allTilesCreated=!this.allTiles.some(e=>e.hasPendingUpdate(1)||e.hasPendingUpdate(4)&&0===e.unmergableChildCount),this._sortTiles(e)}_updateElevation(e){e.done||(this._allTiles.some(t=>(t.resetPendingUpdate(8)&&(this._updateTileGeometryState(t),this._shortBatches&&this._updatePendingTileGeometries(),e.madeProgress()),e.done)),!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries())}_updateTextures(e){e.done||this._allTiles.some(t=>(this._updateTileTexture(t,e),e.done))}_updateClippingExtent(){this.spatialReference&&(this.updateOverlayParameters(),this.requestRender(1),this.overlayManager.setPlacementDirty(),this._updateRootTiles())}get _lodBias(){return this.view.qualitySettings.tiledSurface.lodBias-(1-this.view.quality)*ce}_getLodBiasCorrectedScale(e){const t=this.tilingScheme.levels,i=o(e-this._lodBias,0,t.length-1),r=i-Math.floor(i);return t[Math.floor(i)].scale*(1-r)+t[Math.ceil(i)].scale*r}_removeAllTiles(){null!=this._rootTiles&&(this._rootTiles.forEach(e=>this._purgeTile(e)),this._setRootTiles(null),this.notifyChange("ready")),this._allTiles.clear(),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles}),this.renderer.visible=!1}_purgeSubtree(e){const t=e.children;t[0]&&(this._purgeTile(t[0]),this._purgeTile(t[1]),this._purgeTile(t[2]),this._purgeTile(t[3]),e.clearChildren())}_purgeTile(e){e.leaf?pt(e):this._purgeSubtree(e),this._allTiles.removeUnordered(e),this._unloadTile(e),e.dispose(),this._tileCache.put(Ze._tileMemcacheKey,e),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles})}_unloadTile(e){this._pendingTilesToUpdate.delete(e),this._pendingTilesForElevationUpdateEvent.delete(e),e.unload()}_splitTile(e){_e(e.leaf,"Tile that is already split should not be split again!"),_e(e.rendered,"Tile marked to split is not rendered"),pt(e);const t=e.createChildren();this._allTiles.pushArray(t),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles}),e.updateAgentSuspension(),_e(e.rendered,"parent should be rendered"),t.forEach(e=>this._loadTile(e)),t.forEach(e=>this._pendingTilesToUpdate.add(e)),this._unloadTile(e),this._markAllTileNeighborsForUpdate(e),this._emitTileScaleChange(e,e.level+1),this._allTilesDirty=!0,this._shortBatches&&this._updatePendingTileGeometries(),t.forEach(e=>ht(e,e.hasPendingUpdate(1))),++this._performanceInfo.numSplit}_emitTileScaleChange(e,t=e.level){lt.spatialReference=this.spatialReference,lt.extent=e.extent,lt.scale=this._getLodBiasCorrectedScale(t),this.emit("scale-change",lt)}createTile(e,t,i,r){_e(!!r,"createTile sanity check");const s=this._acquireTile(e,t,i,r);return s.updateClippingStatus(this.groundExtent),s.updateScreenDepth(this.view.state.contentCamera.viewProjectionMatrix),this._shouldSplit(s)&&s.setPendingUpdate(1),s}get _shortBatches(){return 2!==this.view.state.mode}_mergeTile(e){_e(!e.hasPendingUpdate(1),"_mergeTile sanity check"),_e(!e.leaf,"Cannot merge a leaf"),e.leaf||(this._purgeSubtree(e),_e(!e.renderData,"Merging tile with existing render data?"),this._loadTile(e),this._markTileToUpdate(e),this._emitTileScaleChange(e),this._shortBatches&&this._updatePendingTileGeometries(),ht(e,!1),this._allTilesDirty=!0,++this._performanceInfo.numMerged)}_loadTile(e){e.load(),this.requestUpdate(),this._allTilesDirty=!0,this.overlayManager?.hasOverlays&&e.updateOverlayParameters(this.overlayManager)}_handleLayerViewChanges(e=Xe){if(!this._layerViewsDirty)return;this._layerViewsDirty=!1;let t=!1;const i=new Set;let r=-1;for(let s=this.view.allLayerViews.length-1;s>=0;s--){const e=this.view.allLayerViews.items[s];if(i.add(e.uid),we(e)||Ce(e))if(this._basemapLayerViewHandles.has(e.uid)&&!Ce(e)){const i=this._layerClassFromLayerView(e),s=this.getLayerIndexByUID(i,e.uid);null!=s&&((s<r||null==r)&&(t=!0),r=s)}else this._registerTiledLayerView(e),e.layer.loaded&&(t=!0)}this._basemapLayerViewHandles.forEach((e,r)=>{i.has(r)||(this._unregisterTiledLayerView(r),t=!0)}),t&&this._updateTiledLayers(),this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._evaluateTransparency(),e.madeProgress()}get _isFullyTransparent(){if(this.view.map?.ground?.opacity>0)return!1;for(const e of this.view.allLayerViews.items)if(Se(e)&&!$(e.layer)&&0!==e.fullOpacity)return!1;return!0}_hasCompositeBlendMode(){for(const e of this.view.allLayerViews.items)if((be(e)||Ce(e))&&He($e[e.layer.blendMode]))return!0;return!1}_layerClassFromLayerView(e){return Ee(e)?0:1}_registerTiledLayerView(e){const t=[];if((be(e)||Ce(e))&&t.push(_(()=>e.layer.blendMode,()=>{this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._updateTileTextures(2)})),!Ce(e)){const i=this._layerClassFromLayerView(e);t.push(_(()=>!e.destroyed&&e.suspended,()=>this._updateTiledLayers())),t.push(_(()=>!e.destroyed&&e.fullOpacity,()=>this._updateTileTextures(2)));const{layer:r}=e;"effectiveScaleRange"in r&&t.push(_(()=>!e.destroyed&&r.effectiveScaleRange,()=>this._restartAllAgents(i))),t.push(e.on("data-changed",()=>{const t=this.getLayerIndexByUID(i,e.uid);null!=t&&this._invalidateLayerData(t,i)}))}this._unregisterTiledLayerView(e.uid),this._basemapLayerViewHandles.set(e.uid,t)}_unregisterTiledLayerView(e){const t=this._basemapLayerViewHandles.get(e);if(t){for(const e of t)e.remove();this._basemapLayerViewHandles.delete(e)}}_updateTiledLayers(){if(!this.tilingScheme||this.view.suspended)return;const e=this.view.allLayerViews,t=[[],[]];let i=null;e.forEach(e=>{if(!e.layer||e.suspended||!we(e)||!e.fullExtent)return;const r=this._layerClassFromLayerView(e);if(1===r){const t=e.displayLevelRange.maxLevel;t!==1/0&&(null===i||t>i)&&(i=t)}t[r].push(e)});for(const r of ie){const e=this._layerViews[r],i=t[r];i.reverse();const s=i.length;let a=e.length!==s;const n=new Array(s),l=new Array(e.length);this._layerIndexByUid[r].clear();for(let t=0;t<s;t++){const s=i[t].uid;this._layerIndexByUid[r].set(s,t);const o=e.indexOf(i[t]);n[t]=o,t!==o&&(a=!0),o>-1&&(l[o]=t)}if(a){const e=this._postorderIterator;for(e.reset(this._rootTiles);!e.done;)e.next().modifyLayers(l,n,r);this._layerViews[r]=i,this._restartAllAgents(r),this._updateTilesVisibility(this._rootTiles)}}this.tilingScheme.ensureMaxLod(i)&&(this._viewChangeUpdate(),this.notifyChange("tilingScheme"))}_restartAllAgents(e){const t=this._postorderIterator;for(t.reset(this._rootTiles);!t.done;){const i=t.next();i.restartAgents(e),0===e&&i.computeElevationBounds()}this._updateRootTileElevationRange()}layerViewByIndex(e,t){return this._layerViews[t][e]}numLayers(e){return this._layerViews[e].length}_updateTileTextures(e){this._allTiles.forAll(t=>{t.updateAgents(1),1===e?this.renderer.updateTileTexture(t,16):t.updateRenderData(1,e)}),this._evaluateTransparency()}_invalidateLayerData(e,t){null!=this._rootTiles&&(qe(this._rootTiles,i=>i.removeLayerAgent(e,t)),qe(this._rootTiles,i=>{i.invalidateLayerData(e,t),i.restartAgents(t)}))}setTileTreeDirty(e){this._allTilesDirty=!0,e&&(this._allTilesCreated=!1)}requestRender(e=1){this.renderer.setNeedsRender(e)}requestUpdate(){1===++this._pendingUpdates&&(this._hasPendingUpdates=!0)}requestTileData(e,t,i,r){const s=this.layerViewByIndex(t,i),a=s.layer;return!a.tilemapCache||ye(s)?this._requestTileData(e,i,s,r):(++this._asyncWorkItems,a.tilemapCache.fetchAvailability(e.level,e.lij[1],e.lij[2],{...r,timeout:6e3}).then(()=>--this._asyncWorkItems).catch(t=>{throw--this._asyncWorkItems,c(r),g(t)||this._dataMissing(e,i,s),t}).then(()=>this._frameTask.schedule(()=>this._requestTileData(e,i,s,r),r.signal)))}_requestTileData(e,t,i,r){if(this.destroying)return Promise.resolve();return 0===t?Ee(i)?this._requestElevationTileData(e,i,r):Promise.reject():Se(i)?this._requestMapTileData(e,i,r):Promise.reject()}_requestElevationTileData(e,t,i){++this._asyncWorkItems;const r=r=>{!m(i)&&r&&(this.setMemoryDirty(),this.requestUpdate(),this._elevationDataArrived(e,t,r))},s=i=>{g(i)||(l.getLogger(this).error(`Tile ${e.lij.toString()} layer 0/${t.uid} error ${i}`),this._dataMissing(e,0,t),this.requestUpdate())};return t.fetchElevationTile(e,i).then(e=>this._frameTask.schedule(()=>r(e)),s).finally(()=>--this._asyncWorkItems)}_elevationDataArrived(e,t,i){const r=this._layerIndexByUid[0].get(t.uid);if(null==r)return void l.getLogger(this).warn("TerrainSurface: received data from unknown layer %d %s",0,e.lij.toString());const s=new J(e.lij,e.extent,i);e.dataArrived(r,0,s),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:0});const a=[e],n=e.level,o=this._iteratorPool.acquire();for(o.reset(a);!o.done;){const e=o.next();e.findElevationBoundsForLayer(r,n),e.computeElevationBounds()}0===n&&this._updateRootTileElevationRange(),o.remove(),this._updateTilesVisibility(a)}_requestMapTileData(e,t,i){++this._asyncWorkItems;const r=(r,s)=>{xe(s),m(i)||(console.error(`Tile ${e.lij.toString()} layer 1/${t.uid} error ${r}`),this._dataMissing(e,1,t),this.requestUpdate())},s=e=>t=>r(t,e),a=r=>this._frameTask.schedule(()=>{this.requestUpdate(),m(i)?xe(r):this._mapTileDataArrived(e,t,r)},i.signal,s(r)).catch(s(r)),n=(e,t=null)=>this._frameTask.schedule(()=>r(e,t));return t.fetchTile(e.lij,i).then(a,n).finally(()=>--this._asyncWorkItems)}_mapTileDataArrived(e,t,i){const r=this.getLayerIndexByUID(1,t.uid);if(null==r)return xe(i),void l.getLogger(this).warn("TerrainSurface: received data from unknown layer");e.dataArrived(r,1,i),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:1})}_dataMissing(e,t,i){const r=this.getLayerIndexByUID(t,i.uid);null!=r?(e.dataMissing(r,t),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:t})):l.getLogger(this).warn("TerrainSurface: received data from unknown layer")}get performanceInfo(){const e=this._performanceInfo;return e.numNodes=this._allTiles.length,e.numLeaves=e.numVisible=e.numRendered=e.numLoadedPerLevel.length=e.numRenderedPerLevel.length=0,this._allTiles.forAll(t=>{t.leaf&&e.numLeaves++;const i=t.level;t.renderData&&(e.numLoadedPerLevel[i]=(e.numLoadedPerLevel[i]||0)+1),t.visible&&(e.numVisible++,t.rendered&&(e.numRenderedPerLevel[i]=(e.numRenderedPerLevel[i]||0)+1,e.numRendered++))}),e}setMemoryDirty(){this._usedMemory=null}get usedMemory(){return this.tilingScheme?(null==this._usedMemory&&(this._usedMemory=this._recalculateUsedMemory()),this._usedMemory??0):0}_recalculateUsedMemory(){return this.tilingScheme?Math.round(this._allTiles.reduce((e,t)=>e+t.usedMemory,0)):null}getUsedMemoryForLayerView(e){let t=0;const i=this._layerClassFromLayerView(e),r=this.getLayerIndexByUID(i,e.uid);return null!=r&&this._allTiles.forAll(e=>t+=e.getUsedMemoryForLayer(i,r)),t}get renderPatchBorders(){return this._renderer.renderPatchBorders}set renderPatchBorders(e){this._renderer.renderPatchBorders=e}get renderingDisabled(){return this._renderer.renderingDisabled}set renderingDisabled(e){this._renderer.renderingDisabled=e}get test(){}checkAllTilesWaterproofness(){if(!Re)return;const e=this._rootTiles;if(null==e)return;const t=e=>e?.renderData?.geometry?.indices?.length>0,i=(e,i)=>{t(e)&&console.error("Tile[",e.lij,"] has geometry although parent[",i.lij,"] has geom")},r=e=>{if(e.intersectsClippingArea)if(e.renderData&&!e.renderData.geometryState&&console.error("Tile[",e.lij,"] has renderData but not geometryState"),e.renderData&&!e.renderData.geometry&&console.error("Tile[",e.lij,"] has renderData but not geometryInfo"),!e.renderData?.geometry||(e.renderData.geometry.indices?.length??0)>0||console.error("Tile[",e.lij,"] has renderData but no indices - geometryInfo: ",e.renderData.geometry),t(e)){e.checkGeometryWaterproofness();for(const t of e.children)i(t,e)}else if(e.leaf)console.error("Tile[",e.lij,"] has no geometry and no children, from root to leaf");else for(const t of e.children)r(t)},s=e=>{const t=e.parent?.visible??!0,i=e.visible;e.computeVisibility();const r=e.visible;if(i!==r&&t&&console.error(" Tile[",e.lij,"] has out of date visibility: ",i," instead of ",r),!e.leaf)for(const a of e.children)s(a)};for(const a of e)r(a),s(a)}get isGlobal(){return this._isGlobal}get isGeographic(){return this._isGeographic}get isWebMercator(){return this._isWebMercator}get isWebMercatorOnPlateCarree(){return this._isWebMercatorOnPlateCarree}isEastEndWrap(e){return this._isGlobal&&e[2]===this.lijEastEnd(e[0])-1}isWestEndWrap(e){return this._isGlobal&&0===e[2]}lijEastEnd(e){return 1<<e+(this._isGeographic?1:0)}wrapEastWest(e){const t=this.lijEastEnd(e[0]),i=e[2];if(0<=i&&i<t)return e;if(!this._isGlobal)return null;const r=(i+(i<0?t:0))%t;return[e[0],e[1],r]}enableInternalChecks(e){Ue(e)}enableWaterproofnessChecks(e){Me(e)}static cleanupTerrainSurface(){at.prune()}enable(e){e!==this.enabled&&(this._set("enabled",e),e?(this._updateRootTiles(),this.suspended=!1,this.view.elevationProvider.register(0,this)):(this.view.elevationProvider.unregister(this),this.suspended=!0,this._removeAllTiles(),this._setRootTiles(null)),this.notifyChange("ready"))}updateOverlayParameters(){const{overlayManager:e}=this;this.allTiles.forAll(t=>t.updateOverlayParameters(e))}};e([w()],et.prototype,"_renderer",void 0),e([w({constructOnly:!0})],et.prototype,"_scaleRangeQueries",void 0),e([w({constructOnly:!0})],et.prototype,"view",void 0),e([w({constructOnly:!0})],et.prototype,"overlayManager",void 0),e([w({constructOnly:!0})],et.prototype,"terrainTextureCompressionTracker",void 0),e([w()],et.prototype,"_hasPendingUpdates",void 0),e([w()],et.prototype,"_asyncWorkItems",void 0),e([w()],et.prototype,"_allTilesDirty",void 0),e([w()],et.prototype,"_allTilesSorted",void 0),e([w()],et.prototype,"allTilesCreated",null),e([w()],et.prototype,"_allTilesCreated",void 0),e([w()],et.prototype,"_viewChanged",void 0),e([w({type:Number})],et.prototype,"heading",void 0),e([w()],et.prototype,"_splitLimits",void 0),e([w({readOnly:!0})],et.prototype,"_watchUpdatingTracking",void 0),e([w()],et.prototype,"_frameTask",void 0),e([w()],et.prototype,"demResolution",null),e([w({readOnly:!0})],et.prototype,"snapLevel",null),e([w({readOnly:!0})],et.prototype,"lodSnappingEnabled",null),e([w({readOnly:!0})],et.prototype,"userClippingExtent",null),e([w()],et.prototype,"_rootTilesExtent",void 0),e([w({readOnly:!0})],et.prototype,"groundExtent",null),e([w({readOnly:!0})],et.prototype,"fullGroundExtent",null),e([w({readOnly:!0})],et.prototype,"_tilingSchemeExtent",null),e([w({readOnly:!0})],et.prototype,"updating",null),e([w({readOnly:!0})],et.prototype,"readyToRun",null),e([w(X)],et.prototype,"updatingProgress",void 0),e([w({readOnly:!0})],et.prototype,"updatingProgressValue",null),e([w()],et.prototype,"_maxNumUpdating",void 0),e([w()],et.prototype,"baseOpacity",null),e([w()],et.prototype,"hasCompositeBlendMode",void 0),e([w({readOnly:!0})],et.prototype,"viewingMode",null),e([w()],et.prototype,"maxTextureScale",void 0),e([w({readOnly:!0})],et.prototype,"ready",null),e([w({readOnly:!0})],et.prototype,"rootTiles",null),e([w()],et.prototype,"_rootTiles",void 0),e([w({readOnly:!0})],et.prototype,"spatialReference",null),e([w({type:t})],et.prototype,"backgroundColor",null),e([w({value:!1})],et.prototype,"slicePlaneEnabled",null),e([w({readOnly:!0})],et.prototype,"tilingScheme",void 0),e([w({readOnly:!0})],et.prototype,"tilingSchemeLocked",null),e([w({readOnly:!0})],et.prototype,"tilingSchemeLogic",void 0),e([w()],et.prototype,"wireframe",null),e([w()],et.prototype,"opaque",null),e([w()],et.prototype,"invisible",null),e([w({value:!1})],et.prototype,"suspended",null),e([w()],et.prototype,"fadeDuration",null),e([w()],et.prototype,"_xNormalizer",null),e([w()],et.prototype,"visibleElevationRange",void 0),e([w()],et.prototype,"_rootTileElevationRange",void 0),e([w()],et.prototype,"_layerViewsDirty",void 0),e([w()],et.prototype,"renderPatchBorders",null),e([w()],et.prototype,"renderingDisabled",null),e([w({readOnly:!0})],et.prototype,"enabled",void 0),et=Ze=e([C("esri.views.3d.terrain.TerrainSurface")],et);const tt=et,it=x(),rt=new W,st=I(),at=new u,nt=new ee("ground"),lt={spatialReference:null,extent:null,scale:0};function ot(e,t,i){for(const r of e){if(!r.containsPointXY(t,i))continue;let e=r;for(;e&&!e.renderData;){const r=(t>e.extentMidX?1:0)+(i<e.extentMidY?2:0);e=e.children[r]}const s=e?.renderData?.geometryState.samplerData??null;return Z(t,i,s)}return null}function ht(e,t){!e.leaf||e.level<ue||ct(e,e=>{t&&dt(e);const i=ut(e);if(e.maxLevelDeltaNeighborCount++,i){let t=e.parent;for(;t;){const e=ut(t);if(t.unmergableChildCount++,!e)break;t=t.parent}}})}function dt(e){if(e.hasPendingUpdate(1))return;let t=e.parent;for(;t?.resetPendingUpdate(4);)t=t.parent;e.resetPendingUpdate(4),e.leaf&&e.setPendingUpdate(1),e.level<ue||ct(e,e=>{dt(e)})}function pt(e){e.level<ue||ct(e,e=>{if(e.maxLevelDeltaNeighborCount--,0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount){let t=e.parent;for(;t&&(t.unmergableChildCount--,ut(t));)t=t.parent}})}function ut(e){return 0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount}function ct(e,t){if(e.level<ue)return;const i=e.level-ue,r=e.lij[1]>>ue,s=e.lij[2]>>ue,a=e=>e.leaf||e.level===i;for(let n=0;n<4;++n){const l=e.findNeighborTile(fe[n],a);if(!l||l.level!==i)continue;const o=l.lij;o[1]===r&&o[2]===s||t(l)}}export{tt as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import r from"../../../core/Accessor.js";import t from"../../../core/Error.js";import{watch as i,initial as s}from"../../../core/reactiveUtils.js";import{property as n}from"../../../core/accessorSupport/decorators/property.js";import{subclass as o}from"../../../core/accessorSupport/decorators/subclass.js";import{RenderNodeOutput as d}from"../webgl.js";import{getFramebufferDrawBuffers as a}from"../../webgl/RenderingContext.js";let h=class extends r{constructor(e){super(e),this.view=null,this.consumes={required:[]},this.produces=d.COMPOSITE,this.requireGeometryDepth=!1,this._dirty=!0}initialize(){this.addHandles([i(()=>this.view.ready,e=>{e&&this.view.stage?.renderer.addRenderNode(this)},s)])}destroy(){this.view.stage?.renderer?.removeRenderNode(this)}precompile(){}render(){throw new t("RenderNode:render-function-not-implemented","render() is not implemented.")}get camera(){return this.view.state.camera.clone()}get sunLight(){return this.bindParameters.lighting.legacy}get gl(){return this.view.stage.renderView.renderingContext.gl}get techniques(){return this.view.stage.renderView.techniques}acquireOutputFramebuffer(){const e=this._frameBuffer?.getTexture()?.descriptor,r=this.view.stage.renderer.fboCache.acquire(e?.width??640,e?.height??480,this.produces);return this._bind(r),r}bindRenderTarget(){return this._bind(this._frameBuffer),this._frameBuffer}_bind({fbo:e}){e.initializeAndBind(),this.gl.drawBuffers(a(e))}requestRender(e){switch(e){case 2:this.view.state.fading=!0;case 1:this.view.stage?.renderView.requestRender(e);case 0:case void 0:this._dirty=!0}}resetWebGLState(){this.renderingContext.resetState(),this.renderingContext.bindFramebuffer(this._frameBuffer?.fbo)}get fboCache(){return this.view.stage.renderer.fboCache}get bindParameters(){return this.renderContext.bind}get renderingContext(){return this.view.stage.renderView.renderingContext}get renderContext(){return this.view.stage?.renderer.renderContext}updateAnimation(e){return!!this._dirty&&(this._dirty=!1,!0)}doRender(e){this._frameBuffer=e.find(({name:e})=>e===this.produces);try{return this.render(e)}finally{this._frameBuffer=null}}};e([n({constructOnly:!0})],h.prototype,"view",void 0),e([n({constructOnly:!0})],h.prototype,"consumes",void 0),e([n()],h.prototype,"produces",void 0),e([n({readOnly:!0})],h.prototype,"techniques",null),h=e([o("esri.views.3d.webgl.RenderNode")],h);const u=h;export{u as default};
2
+ import{__decorate as e}from"tslib";import r from"../../../core/Accessor.js";import t from"../../../core/Error.js";import{watch as i,initial as s}from"../../../core/reactiveUtils.js";import{property as n}from"../../../core/accessorSupport/decorators/property.js";import{subclass as o}from"../../../core/accessorSupport/decorators/subclass.js";import{RenderNodeOutput as d}from"../webgl.js";import{getFramebufferDrawBuffers as a}from"../../webgl/RenderingContext.js";let u=class extends r{constructor(e){super(e),this.view=null,this.consumes={required:[]},this.produces=d.COMPOSITE,this._dirty=!0}initialize(){this.addHandles([i(()=>this.view.ready,e=>{e&&this.view.stage?.renderer.addRenderNode(this)},s)])}destroy(){this.view.stage?.renderer?.removeRenderNode(this)}precompile(){}render(){throw new t("RenderNode:render-function-not-implemented","render() is not implemented.")}get camera(){return this.view.state.camera.clone()}get sunLight(){return this.bindParameters.lighting.legacy}get gl(){return this.view.stage.renderView.renderingContext.gl}get techniques(){return this.view.stage.renderView.techniques}acquireOutputFramebuffer(){const e=this._frameBuffer?.getTexture()?.descriptor,r=this.view.stage.renderer.fboCache.acquire(e?.width??640,e?.height??480,this.produces);return this._bind(r),r}bindRenderTarget(){return this._bind(this._frameBuffer),this._frameBuffer}_bind({fbo:e}){e.initializeAndBind(),this.gl.drawBuffers(a(e))}requestRender(e){switch(e){case 2:this.view.state.fading=!0;case 1:this.view.stage?.renderView.requestRender(e);case 0:case void 0:this._dirty=!0}}resetWebGLState(){this.renderingContext.resetState(),this.renderingContext.bindFramebuffer(this._frameBuffer?.fbo)}get fboCache(){return this.view.stage.renderer.fboCache}get bindParameters(){return this.renderContext.bind}get renderingContext(){return this.view.stage.renderView.renderingContext}get renderContext(){return this.view.stage?.renderer.renderContext}updateAnimation(e){return!!this._dirty&&(this._dirty=!1,!0)}doRender(e){this._frameBuffer=e.find(({name:e})=>e===this.produces);try{return this.render(e)}finally{this._frameBuffer=null}}get requireGeometryDepth(){return!1}};e([n({constructOnly:!0})],u.prototype,"view",void 0),e([n({constructOnly:!0})],u.prototype,"consumes",void 0),e([n()],u.prototype,"produces",void 0),e([n({readOnly:!0})],u.prototype,"techniques",null),u=e([o("esri.views.3d.webgl.RenderNode")],u);const h=u;export{h as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{exactEquals as e}from"../../../../../../core/libs/gl-matrix-2/math/vec3.js";import{ZEROS as t}from"../../../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{ComponentTechnique as r}from"./ComponentTechnique.js";import{ComponentTechniqueConfiguration as s}from"./ComponentTechniqueConfiguration.js";import{MaterialBase as i}from"../../../core/material/MaterialBase.js";import{isColor as o}from"../../../core/shaderLibrary/ShaderOutput.js";class a extends i{constructor(e,t,r,i,o){super(),this.parameters=e,this.key=o,this.usePBR=e.usePBR,this.hasParametersFromSource=e.hasParametersFromSource,this.isGround=e.isGround,this.slicePlaneEnabled=e.slicePlaneEnabled,this.isIntegratedMesh=e.isIntegratedMesh,this.applySSAO=e.applySSAO,this.hasEmissions=u(e,r,i),this.materialPass=n(e,r),this._configuration=new s(i),this._initializeMaterialConfiguration(e,t,r,i)}destroy(){}acquireTechnique(e,t,s,i){const o=this._updateConfiguration(t,s);return e.get(r,o,i.layout)}_initializeMaterialConfiguration(e,t,r,s){const i=this._configuration;i.hasMetallicRoughnessTexture=null!=e.metallicRoughnessTexture,i.hasOcclusionTexture=null!=e.occlusionTexture,i.hasNormalTexture=null!=e.normalTexture,i.sphereDepthInterpolate=e.sphereDepthInterpolate&&i.spherical,i.ellipsoidMode=e.ellipsoidMode,i.doubleSidedMode=e.doubleSided?1:0,i.hasColorTexture=null!=e.baseColorTexture,i.cullFace=e.cullFace,i.alphaDiscardMode=e.alphaDiscardMode,i.hasVertexColors=t.hasVertexColors,i.textureCoordinateType=t.textureCoordinateType,i.shadeNormals=t.shadeNormals,i.normalType=t.hasNormals?1:2,i.polygonOffset=e.polygonOffset,i.vertexPositionRotationType=t.vertexPositionRotationType,i.vertexNormalRotationType=t.vertexNormalRotationType,i.componentDataType=r.componentDataType,i.emissionSource=c(e,r,s)}_updateConfiguration(e,t){const r=this._configuration,{identifier:s}=e,i=0===s;r.output=t.output,r.enableOITOffset=t.enableOITOffset,r.hasEmission=t.hasEmission&&i,r.renderOccluded=10===t.slot,r.terrainDepthTest=i&&t.terrainDepthTest,r.cullAboveTerrain=!!i&&t.cullAboveTerrain;const a=this.isIntegratedMesh?d(t)?h(t)?3:2:1:0;r.integratedMeshMode=a,r.pbrMode=3===a?4:this.usePBR?this.hasParametersFromSource?0!==r.shadeNormals&&this.isIntegratedMesh?0:2:1:0,r.hasSlicePlane=null!=t.slicePlane&&this.slicePlaneEnabled,r.isGroundSlice=r.hasSlicePlane&&this.isGround;const{materialPass:n}=this;r.transparent=i&&(1===n||2===n&&e.transparent||4===n)||r.isGroundSlice,r.hasHighlightMixTexture=2===s&&null!=t.highlightMixTexture,r.snowCover=i&&t.snowCover>0,r.vertexDiscardMode=i&&2===n?e.transparent?2:1:0;const l=o(t.output);return r.receiveAmbientOcclusion=l&&this.applySSAO&&!r.renderOccluded&&null!=t.ssao?.getTexture(),r.hasOccludees=l&&t.hasOccludees,r.receiveShadows=l&&t.shadowMap.ready,r.screenSpaceReflections=t.hasScreenSpaceReflections,r.cloudReflections=l&&null!=t.clouds.data?.cubeMap?.colorTexture,r}}function n(e,t){const{alphaDiscardMode:r,isIntegratedMesh:s,slicePlaneEnabled:i}=e,{transparent:o,opaqueOverride:a}=t,n=e.opacity<1,l=e.baseColor[3]<1;if(s)return n||i?4:3;if(n)return 1;if(0===a)return 0;if(l||0===r||3===r)return 1;switch(o){case 2:return 0;case 0:return 1;case 1:return 2}}function l(r){return null!=r.emissionTexture||!e(r.emissiveBaseColor,t)}function u(e,t,r){const s=l(e);return r.hasEmissionSupport&&2!==t.emissiveOverride&&(s||2!==t.emissiveSourceOverride)}function c(e,t,r){const s=null!=e.emissionTexture,{emissiveSourceOverride:i}=t,o=1===i,a=2===i,n=u(e,t,r),c=l(e);return n?c?a?s?4:2:o?s?5:7:6:o?7:6:0}function h(e){return null!=e.overlay?.getTexture(3)}function d(e){return null!=e.overlay?.getTexture(1)}export{a as ComponentMaterial,c as calculateEmissionSource,u as calculateHasEmissions,l as calculateHasEmissiveBase,n as computeMaterialPass};
2
+ import{exactEquals as e}from"../../../../../../core/libs/gl-matrix-2/math/vec3.js";import{ZEROS as t}from"../../../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{ComponentTechnique as r}from"./ComponentTechnique.js";import{ComponentTechniqueConfiguration as s}from"./ComponentTechniqueConfiguration.js";import{MaterialBase as i}from"../../../core/material/MaterialBase.js";import{isColor as o}from"../../../core/shaderLibrary/ShaderOutput.js";import{hasShadowHighlights as a}from"../../../shaders/ReceiveShadowsConfiguration.js";class n extends i{constructor(e,t,r,i,o){super(),this.parameters=e,this.key=o,this.usePBR=e.usePBR,this.hasParametersFromSource=e.hasParametersFromSource,this.isGround=e.isGround,this.slicePlaneEnabled=e.slicePlaneEnabled,this.isIntegratedMesh=e.isIntegratedMesh,this.applySSAO=e.applySSAO,this.hasEmissions=c(e,r,i),this.materialPass=l(e,r),this._configuration=new s(i),this._initializeMaterialConfiguration(e,t,r,i)}destroy(){}acquireTechnique(e,t,s,i){const o=this._updateConfiguration(t,s);return e.get(r,o,i.layout)}_initializeMaterialConfiguration(e,t,r,s){const i=this._configuration;i.hasMetallicRoughnessTexture=null!=e.metallicRoughnessTexture,i.hasOcclusionTexture=null!=e.occlusionTexture,i.hasNormalTexture=null!=e.normalTexture,i.sphereDepthInterpolate=e.sphereDepthInterpolate&&i.spherical,i.ellipsoidMode=e.ellipsoidMode,i.doubleSidedMode=e.doubleSided?1:0,i.hasColorTexture=null!=e.baseColorTexture,i.cullFace=e.cullFace,i.alphaDiscardMode=e.alphaDiscardMode,i.hasVertexColors=t.hasVertexColors,i.textureCoordinateType=t.textureCoordinateType,i.shadeNormals=t.shadeNormals,i.normalType=t.hasNormals?1:2,i.polygonOffset=e.polygonOffset,i.vertexPositionRotationType=t.vertexPositionRotationType,i.vertexNormalRotationType=t.vertexNormalRotationType,i.componentDataType=r.componentDataType,i.emissionSource=h(e,r,s)}_updateConfiguration(e,t){const r=this._configuration,{identifier:s}=e,i=0===s;r.output=t.output,r.enableOITOffset=t.enableOITOffset,r.hasEmission=t.hasEmission&&i,r.renderOccluded=10===t.slot,r.terrainDepthTest=i&&t.terrainDepthTest,r.cullAboveTerrain=!!i&&t.cullAboveTerrain;const n=this.isIntegratedMesh?p(t)?d(t)?3:2:1:0;r.integratedMeshMode=n,r.pbrMode=3===n?4:this.usePBR?this.hasParametersFromSource?0!==r.shadeNormals&&this.isIntegratedMesh?0:2:1:0,r.hasSlicePlane=null!=t.slicePlane&&this.slicePlaneEnabled,r.isGroundSlice=r.hasSlicePlane&&this.isGround;const{materialPass:l}=this;r.transparent=i&&(1===l||2===l&&e.transparent||4===l)||r.isGroundSlice,r.hasHighlightMixTexture=2===s&&null!=t.highlightMixTexture,r.snowCover=i&&t.snowCover>0,r.vertexDiscardMode=i&&2===l?e.transparent?2:1:0;const u=o(t.output);return r.receiveAmbientOcclusion=u&&this.applySSAO&&!r.renderOccluded&&null!=t.ssao?.getTexture(),r.hasOccludees=u&&t.hasOccludees,r.receiveShadows=u&&t.shadowMap.ready,r.hasShadowHighlights=a(r,t),r.screenSpaceReflections=t.hasScreenSpaceReflections,r.cloudReflections=u&&null!=t.clouds.data?.cubeMap?.colorTexture,r}}function l(e,t){const{alphaDiscardMode:r,isIntegratedMesh:s,slicePlaneEnabled:i}=e,{transparent:o,opaqueOverride:a}=t,n=e.opacity<1,l=e.baseColor[3]<1;if(s)return n||i?4:3;if(n)return 1;if(0===a)return 0;if(l||0===r||3===r)return 1;switch(o){case 2:return 0;case 0:return 1;case 1:return 2}}function u(r){return null!=r.emissionTexture||!e(r.emissiveBaseColor,t)}function c(e,t,r){const s=u(e);return r.hasEmissionSupport&&2!==t.emissiveOverride&&(s||2!==t.emissiveSourceOverride)}function h(e,t,r){const s=null!=e.emissionTexture,{emissiveSourceOverride:i}=t,o=1===i,a=2===i,n=c(e,t,r),l=u(e);return n?l?a?s?4:2:o?s?5:7:6:o?7:6:0}function d(e){return null!=e.overlay?.getTexture(3)}function p(e){return null!=e.overlay?.getTexture(1)}export{n as ComponentMaterial,h as calculateEmissionSource,c as calculateHasEmissions,u as calculateHasEmissiveBase,l as computeMaterialPass};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import{isColorHighlightOrOLID as t}from"../../../core/shaderLibrary/ShaderOutput.js";import{parameter as o}from"../../../core/shaderTechnique/ShaderTechniqueConfiguration.js";import{SphereDepthInterpolateConfiguration as i}from"../../../shaders/SphereDepthInterpolate.glsl.js";class s extends i{constructor(e){super(),this.output=0,this.textureCoordinateType=0,this.componentDataType=0,this.cullFace=2,this.vertexDiscardMode=0,this.doubleSidedMode=2,this.alphaDiscardMode=1,this.integratedMeshMode=0,this.pbrMode=0,this.normalType=0,this.emissionSource=0,this.shadeNormals=1,this.polygonOffset=0,this.vertexPositionRotationType=1,this.vertexNormalRotationType=0,this.hasEmission=!1,this.hasVertexColors=!1,this.hasSlicePlane=!1,this.isGroundSlice=!1,this.hasColorTexture=!1,this.hasHighlightMixTexture=!1,this.receiveAmbientOcclusion=!0,this.receiveShadows=!0,this.transparent=!0,this.screenSpaceReflections=!1,this.hasMetallicRoughnessTexture=!1,this.hasOcclusionTexture=!1,this.hasNormalTexture=!1,this.hasOccludees=!1,this.terrainDepthTest=!1,this.cullAboveTerrain=!1,this.hasNormalTextureTransform=!1,this.cloudReflections=!0,this.snowCover=!1,this.renderOccluded=!1,this.enableOITOffset=!1,this.sphereDepthInterpolate=!1,this.writeDepth=!0,this.discardInvisibleFragments=!1,this.oitPremultipliedAlpha=!1,this.occlusionPass=!1,this.bindType=2,this.useCustomDTRExponentForWater=!1,this.hasVertexTangents=!1,this.hasSliceTranslatedView=!1,this.highStepCount=!1,this.instanced=!1,this.instancedDoublePrecision=!1,this.hasModelTransformation=!1,this.useFillLights=!0,this.draped=!1,this.useTransformationTexture=!0,this.sphericalSR=e.sphericalSR,this.useFloatBlend=e.useFloatBlend}get spherical(){return 0!==this.sphericalSR}get overlayEnabled(){return(2===this.integratedMeshMode||3===this.integratedMeshMode)&&t(this.output)}get hasWater(){return 3===this.pbrMode||4===this.pbrMode||6===this.pbrMode}}e([o()],s.prototype,"useFloatBlend",void 0),e([o({count:12})],s.prototype,"output",void 0),e([o({count:3})],s.prototype,"textureCoordinateType",void 0),e([o({count:2})],s.prototype,"componentDataType",void 0),e([o({count:3})],s.prototype,"cullFace",void 0),e([o({count:3})],s.prototype,"vertexDiscardMode",void 0),e([o({count:3})],s.prototype,"doubleSidedMode",void 0),e([o({count:4})],s.prototype,"alphaDiscardMode",void 0),e([o({count:4})],s.prototype,"integratedMeshMode",void 0),e([o({count:7})],s.prototype,"pbrMode",void 0),e([o({count:3})],s.prototype,"normalType",void 0),e([o({count:8})],s.prototype,"emissionSource",void 0),e([o({count:3})],s.prototype,"shadeNormals",void 0),e([o({count:5})],s.prototype,"polygonOffset",void 0),e([o({count:2})],s.prototype,"vertexPositionRotationType",void 0),e([o({count:2})],s.prototype,"vertexNormalRotationType",void 0),e([o()],s.prototype,"hasEmission",void 0),e([o()],s.prototype,"hasVertexColors",void 0),e([o()],s.prototype,"hasSlicePlane",void 0),e([o()],s.prototype,"isGroundSlice",void 0),e([o()],s.prototype,"hasColorTexture",void 0),e([o()],s.prototype,"hasHighlightMixTexture",void 0),e([o()],s.prototype,"receiveAmbientOcclusion",void 0),e([o()],s.prototype,"receiveShadows",void 0),e([o()],s.prototype,"transparent",void 0),e([o()],s.prototype,"screenSpaceReflections",void 0),e([o()],s.prototype,"hasMetallicRoughnessTexture",void 0),e([o()],s.prototype,"hasOcclusionTexture",void 0),e([o()],s.prototype,"hasNormalTexture",void 0),e([o()],s.prototype,"hasOccludees",void 0),e([o()],s.prototype,"terrainDepthTest",void 0),e([o()],s.prototype,"cullAboveTerrain",void 0),e([o()],s.prototype,"hasNormalTextureTransform",void 0),e([o()],s.prototype,"cloudReflections",void 0),e([o()],s.prototype,"snowCover",void 0),e([o()],s.prototype,"renderOccluded",void 0),e([o()],s.prototype,"enableOITOffset",void 0),e([o()],s.prototype,"sphereDepthInterpolate",void 0);export{s as ComponentTechniqueConfiguration};
2
+ import{__decorate as t}from"tslib";import{isColorHighlightOrOLID as e}from"../../../core/shaderLibrary/ShaderOutput.js";import{parameter as o}from"../../../core/shaderTechnique/ShaderTechniqueConfiguration.js";import{SphereDepthInterpolateConfiguration as i}from"../../../shaders/SphereDepthInterpolate.glsl.js";class s extends i{constructor(t){super(),this.output=0,this.textureCoordinateType=0,this.componentDataType=0,this.cullFace=2,this.vertexDiscardMode=0,this.doubleSidedMode=2,this.alphaDiscardMode=1,this.integratedMeshMode=0,this.pbrMode=0,this.normalType=0,this.emissionSource=0,this.shadeNormals=1,this.polygonOffset=0,this.vertexPositionRotationType=1,this.vertexNormalRotationType=0,this.hasEmission=!1,this.hasVertexColors=!1,this.hasSlicePlane=!1,this.isGroundSlice=!1,this.hasColorTexture=!1,this.hasHighlightMixTexture=!1,this.receiveAmbientOcclusion=!0,this.receiveShadows=!0,this.hasShadowHighlights=!1,this.transparent=!0,this.screenSpaceReflections=!1,this.hasMetallicRoughnessTexture=!1,this.hasOcclusionTexture=!1,this.hasNormalTexture=!1,this.hasOccludees=!1,this.terrainDepthTest=!1,this.cullAboveTerrain=!1,this.hasNormalTextureTransform=!1,this.cloudReflections=!0,this.snowCover=!1,this.renderOccluded=!1,this.enableOITOffset=!1,this.sphereDepthInterpolate=!1,this.writeDepth=!0,this.discardInvisibleFragments=!1,this.oitPremultipliedAlpha=!1,this.occlusionPass=!1,this.bindType=2,this.useCustomDTRExponentForWater=!1,this.hasVertexTangents=!1,this.hasSliceTranslatedView=!1,this.highStepCount=!1,this.instanced=!1,this.instancedDoublePrecision=!1,this.hasModelTransformation=!1,this.useFillLights=!0,this.draped=!1,this.useTransformationTexture=!0,this.sphericalSR=t.sphericalSR,this.useFloatBlend=t.useFloatBlend}get spherical(){return 0!==this.sphericalSR}get overlayEnabled(){return(2===this.integratedMeshMode||3===this.integratedMeshMode)&&e(this.output)}get hasWater(){return 3===this.pbrMode||4===this.pbrMode||6===this.pbrMode}}t([o()],s.prototype,"useFloatBlend",void 0),t([o({count:12})],s.prototype,"output",void 0),t([o({count:3})],s.prototype,"textureCoordinateType",void 0),t([o({count:2})],s.prototype,"componentDataType",void 0),t([o({count:3})],s.prototype,"cullFace",void 0),t([o({count:3})],s.prototype,"vertexDiscardMode",void 0),t([o({count:3})],s.prototype,"doubleSidedMode",void 0),t([o({count:4})],s.prototype,"alphaDiscardMode",void 0),t([o({count:4})],s.prototype,"integratedMeshMode",void 0),t([o({count:7})],s.prototype,"pbrMode",void 0),t([o({count:3})],s.prototype,"normalType",void 0),t([o({count:8})],s.prototype,"emissionSource",void 0),t([o({count:3})],s.prototype,"shadeNormals",void 0),t([o({count:5})],s.prototype,"polygonOffset",void 0),t([o({count:2})],s.prototype,"vertexPositionRotationType",void 0),t([o({count:2})],s.prototype,"vertexNormalRotationType",void 0),t([o()],s.prototype,"hasEmission",void 0),t([o()],s.prototype,"hasVertexColors",void 0),t([o()],s.prototype,"hasSlicePlane",void 0),t([o()],s.prototype,"isGroundSlice",void 0),t([o()],s.prototype,"hasColorTexture",void 0),t([o()],s.prototype,"hasHighlightMixTexture",void 0),t([o()],s.prototype,"receiveAmbientOcclusion",void 0),t([o()],s.prototype,"receiveShadows",void 0),t([o()],s.prototype,"hasShadowHighlights",void 0),t([o()],s.prototype,"transparent",void 0),t([o()],s.prototype,"screenSpaceReflections",void 0),t([o()],s.prototype,"hasMetallicRoughnessTexture",void 0),t([o()],s.prototype,"hasOcclusionTexture",void 0),t([o()],s.prototype,"hasNormalTexture",void 0),t([o()],s.prototype,"hasOccludees",void 0),t([o()],s.prototype,"terrainDepthTest",void 0),t([o()],s.prototype,"cullAboveTerrain",void 0),t([o()],s.prototype,"hasNormalTextureTransform",void 0),t([o()],s.prototype,"cloudReflections",void 0),t([o()],s.prototype,"snowCover",void 0),t([o()],s.prototype,"renderOccluded",void 0),t([o()],s.prototype,"enableOITOffset",void 0),t([o()],s.prototype,"sphereDepthInterpolate",void 0);export{s as ComponentTechniqueConfiguration};
@@ -1,19 +1,19 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{EvaluateAmbientLighting as i}from"./EvaluateAmbientLighting.glsl.js";import{EvaluateAmbientOcclusion as n}from"./EvaluateAmbientOcclusion.glsl.js";import{Gamma as e}from"./Gamma.glsl.js";import{addMainLightDirection as o,addMainLightIntensity as t,applyShading as a}from"./MainLighting.glsl.js";import{PhysicallyBasedRendering as r}from"./PhysicallyBasedRendering.glsl.js";import{PiUtils as l}from"./PiUtils.glsl.js";import{BooleanBindUniform as c}from"../../shaderModules/BooleanBindUniform.js";import{FloatBindUniform as d}from"../../shaderModules/FloatBindUniform.js";import{If as m,glsl as s}from"../../shaderModules/glsl.js";import{ambientBoost as g}from"../../../lighting/SceneLighting.js";import{BlackLevelLightSoftCompression as h}from"../../../shaders/BlackLevelLightSoftCompression.glsl.js";import{ToneMapping as u}from"../../../shaders/ToneMapping.glsl.js";function p(i){i.constants.add("ambientBoostFactor","float",g)}function f(i){i.uniforms.add(new d("lightingGlobalFactor",i=>i.lighting.globalFactor))}function v(g,v){const{pbrMode:L,spherical:b,hasColorTexture:C}=v;g.include(n,v),0!==L&&g.include(r,v),g.include(i,v),g.include(l),g.include(u,v),g.include(e);const N=!(2===L&&!C);switch(N&&g.include(h),g.code.add(s`
3
- ${m(0!==L,"const float GROUND_REFLECTANCE = 0.2;")}
4
- `),p(g),f(g),o(g),g.code.add(s`
2
+ import{EvaluateAmbientLighting as i}from"./EvaluateAmbientLighting.glsl.js";import{EvaluateAmbientOcclusion as n}from"./EvaluateAmbientOcclusion.glsl.js";import{Gamma as t}from"./Gamma.glsl.js";import{addMainLightDirection as e,addMainLightIntensity as o,applyShading as a}from"./MainLighting.glsl.js";import{PhysicallyBasedRendering as r}from"./PhysicallyBasedRendering.glsl.js";import{PiUtils as l}from"./PiUtils.glsl.js";import{BooleanBindUniform as c}from"../../shaderModules/BooleanBindUniform.js";import{FloatBindUniform as d}from"../../shaderModules/FloatBindUniform.js";import{If as s,glsl as m}from"../../shaderModules/glsl.js";import{ambientBoost as g}from"../../../lighting/SceneLighting.js";import{BlackLevelLightSoftCompression as u}from"../../../shaders/BlackLevelLightSoftCompression.glsl.js";import{ToneMapping as h}from"../../../shaders/ToneMapping.glsl.js";function p(i){i.constants.add("ambientBoostFactor","float",g)}function L(i){i.uniforms.add(new d("lightingGlobalFactor",i=>i.lighting.globalFactor))}function f(g,f){const{pbrMode:v,spherical:b,hasColorTexture:C}=f;g.include(n,f),0!==v&&g.include(r,f),g.include(i,f),g.include(l),g.include(h,f),g.include(t);const D=!(2===v&&!C);switch(D&&g.include(u),g.code.add(m`
3
+ ${s(0!==v,"const float GROUND_REFLECTANCE = 0.2;")}
4
+ `),p(g),L(g),e(g),g.code.add(m`
5
5
  float additionalDirectedAmbientLight(float lightAlignment) {
6
6
  return smoothstep(0.0, 1.0, clamp(lightAlignment * 2.5, 0.0, 1.0));
7
7
  }
8
8
 
9
9
  float additionalDirectedAmbientLight(vec3 vPosWorld) {
10
- float lightAlignment = dot(${b?s`normalize(vPosWorld)`:s`vec3(0.0, 0.0, 1.0)`}, mainLightDirection);
10
+ float lightAlignment = dot(${b?m`normalize(vPosWorld)`:m`vec3(0.0, 0.0, 1.0)`}, mainLightDirection);
11
11
  return smoothstep(0.0, 1.0, clamp(lightAlignment * 2.5, 0.0, 1.0));
12
12
  }
13
- `),t(g),g.code.add(s`vec3 evaluateAdditionalLighting(float ambientOcclusion, vec3 vPosWorld) {
13
+ `),o(g),g.code.add(m`vec3 evaluateAdditionalLighting(float ambientOcclusion, vec3 vPosWorld) {
14
14
  float additionalAmbientScale = additionalDirectedAmbientLight(vPosWorld);
15
15
  return (1.0 - ambientOcclusion) * additionalAmbientScale * ambientBoostFactor * lightingGlobalFactor * mainLightIntensity;
16
- }`),L){case 0:case 4:case 3:g.include(a),g.code.add(s`vec3 evaluateSceneLighting(vec3 normalWorld, vec3 albedo, float shadow, float ssao, vec3 additionalLight) {
16
+ }`),v){case 0:case 4:case 3:g.include(a),g.code.add(m`vec3 evaluateSceneLighting(vec3 normalWorld, vec3 albedo, float shadow, float ssao, vec3 additionalLight) {
17
17
  vec3 mainLighting = applyShading(normalWorld, shadow);
18
18
  vec3 ambientLighting = calculateAmbientIrradiance(normalWorld, ssao);
19
19
  vec3 albedoLinear = linearizeGamma(albedo);
@@ -21,72 +21,50 @@ vec3 totalLight = mainLighting + ambientLighting + additionalLight;
21
21
  totalLight = min(totalLight, vec3(PI));
22
22
  vec3 outColor = vec3((albedoLinear / PI) * totalLight);
23
23
  return delinearizeGamma(outColor);
24
- }`);break;case 1:case 2:g.code.add(s`const float fillLightIntensity = 0.25;
24
+ }`);break;case 1:case 2:g.code.add(m`const float fillLightIntensity = 0.25;
25
25
  const float horizonLightDiffusion = 0.4;
26
26
  const float additionalAmbientIrradianceFactor = 0.02;
27
27
  vec3 evaluateSceneLightingPBR(vec3 normal, vec3 albedo, float shadow, float ssao, vec3 additionalLight,
28
- vec3 viewDir, vec3 groundNormal, vec3 mrr, float additionalAmbientIrradiance) {
29
- vec3 viewDirection = -viewDir;
30
- vec3 h = normalize(viewDirection + mainLightDirection);
28
+ vec3 viewDirection, vec3 upDirection, vec3 mrr, float additionalAmbientIrradiance) {
31
29
  PBRShadingInfo inputs;
32
- inputs.NdotV = clamp(abs(dot(normal, viewDirection)), 0.001, 1.0);
33
- inputs.NdotNG = clamp(dot(normal, groundNormal), -1.0, 1.0);
34
- vec3 reflectedView = normalize(reflect(viewDirection, normal));
35
- inputs.RdotNG = clamp(dot(reflectedView, groundNormal), -1.0, 1.0);
36
- inputs.albedoLinear = linearizeGamma(albedo);
37
- inputs.ssao = ssao;
38
- inputs.metalness = mrr[0];
39
- inputs.roughness = clamp(mrr[1] * mrr[1], 0.001, 0.99);`),g.code.add(s`inputs.f0 = (0.16 * mrr[2] * mrr[2]) * (1.0 - inputs.metalness) + inputs.albedoLinear * inputs.metalness;
40
- inputs.f90 = vec3(clamp(dot(inputs.f0, vec3(50.0 * 0.33)), 0.0, 1.0));
41
- inputs.diffuseColor = inputs.albedoLinear * (vec3(1.0) - inputs.f0) * (1.0 - inputs.metalness);`),v.useFillLights?g.uniforms.add(new c("hasFillLights",i=>i.enableFillLights)):g.constants.add("hasFillLights","bool",!1),g.code.add(s`vec3 ambientDir = vec3(5.0 * groundNormal[1] - groundNormal[0] * groundNormal[2], - 5.0 * groundNormal[0] - groundNormal[2] * groundNormal[1], groundNormal[1] * groundNormal[1] + groundNormal[0] * groundNormal[0]);
30
+ calculatePBRInputs(inputs, normal, viewDirection, upDirection, albedo, mrr);`),f.useFillLights?g.uniforms.add(new c("hasFillLights",i=>i.enableFillLights)):g.constants.add("hasFillLights","bool",!1),g.code.add(m`vec3 ambientDir = vec3(5.0 * upDirection[1] - upDirection[0] * upDirection[2], - 5.0 * upDirection[0] - upDirection[2] * upDirection[1], upDirection[1] * upDirection[1] + upDirection[0] * upDirection[0]);
42
31
  ambientDir = ambientDir != vec3(0.0) ? normalize(ambientDir) : normalize(vec3(5.0, -1.0, 0.0));
43
32
  inputs.NdotAmbDir = hasFillLights ? abs(dot(normal, ambientDir)) : 1.0;
44
- float NdotL = clamp(dot(normal, mainLightDirection), 0.001, 1.0);
45
- vec3 mainLightIrradianceComponent = NdotL * (1.0 - shadow) * mainLightIntensity;
33
+ vec3 mainLightIrradianceComponent = inputs.NdotL * (1.0 - shadow) * mainLightIntensity;
46
34
  vec3 fillLightsIrradianceComponent = inputs.NdotAmbDir * mainLightIntensity * fillLightIntensity;
47
35
  vec3 ambientLightIrradianceComponent = calculateAmbientIrradiance(normal, ssao) + additionalLight;
48
36
  inputs.skyIrradianceToSurface = ambientLightIrradianceComponent + mainLightIrradianceComponent + fillLightsIrradianceComponent ;
49
- inputs.groundIrradianceToSurface = GROUND_REFLECTANCE * ambientLightIrradianceComponent + mainLightIrradianceComponent + fillLightsIrradianceComponent ;`),g.uniforms.add(new d("lightingSpecularStrength",i=>i.lighting.mainLight.specularStrength),new d("lightingEnvironmentStrength",i=>i.lighting.mainLight.environmentStrength)).code.add(s`vec3 horizonRingDir = inputs.RdotNG * groundNormal - reflectedView;
50
- vec3 horizonRingH = normalize(viewDirection + horizonRingDir);
37
+ inputs.groundIrradianceToSurface = GROUND_REFLECTANCE * ambientLightIrradianceComponent + mainLightIrradianceComponent + fillLightsIrradianceComponent ;`),g.uniforms.add(new d("lightingSpecularStrength",i=>i.lighting.mainLight.specularStrength),new d("lightingEnvironmentStrength",i=>i.lighting.mainLight.environmentStrength)).code.add(m`vec3 horizonRingDir = inputs.RdotUP * upDirection - inputs.reflectedView;
38
+ vec3 horizonRingH = normalize(horizonRingDir - viewDirection);
51
39
  inputs.NdotH_Horizon = dot(normal, horizonRingH);
52
- float NdotH = clamp(dot(normal, h), 0.0, 1.0);
53
- vec3 mainLightRadianceComponent = lightingSpecularStrength * normalDistribution(NdotH, inputs.roughness) * mainLightIntensity * (1.0 - shadow);
40
+ vec3 mainLightRadianceComponent = lightingSpecularStrength * normalDistribution(inputs.NdotH, inputs.roughness) * mainLightIntensity * (1.0 - shadow);
54
41
  vec3 horizonLightRadianceComponent = lightingEnvironmentStrength * normalDistribution(inputs.NdotH_Horizon, min(inputs.roughness + horizonLightDiffusion, 1.0)) * mainLightIntensity * fillLightIntensity;
55
42
  vec3 ambientLightRadianceComponent = lightingEnvironmentStrength * calculateAmbientRadiance(ssao) + additionalLight;
56
- float normalDirectionModifier = mix(1., min(mix(0.1, 2.0, (inputs.NdotNG + 1.) * 0.5), 1.0), clamp(inputs.roughness * 5.0, 0.0 , 1.0));
43
+ float normalDirectionModifier = mix(1., min(mix(0.1, 2.0, (inputs.NdotUP + 1.) * 0.5), 1.0), clamp(inputs.roughness * 5.0, 0.0 , 1.0));
57
44
  inputs.skyRadianceToSurface = (ambientLightRadianceComponent + horizonLightRadianceComponent) * normalDirectionModifier + mainLightRadianceComponent;
58
45
  inputs.groundRadianceToSurface = 0.5 * GROUND_REFLECTANCE * (ambientLightRadianceComponent + horizonLightRadianceComponent) * normalDirectionModifier + mainLightRadianceComponent;
59
- inputs.averageAmbientRadiance = ambientLightIrradianceComponent[1] * (1.0 + GROUND_REFLECTANCE);`),g.code.add(s`
46
+ inputs.averageAmbientRadiance = ambientLightIrradianceComponent[1] * (1.0 + GROUND_REFLECTANCE);`),g.code.add(m`
60
47
  vec3 reflectedColorComponent = evaluateEnvironmentIllumination(inputs);
61
48
  vec3 additionalMaterialReflectanceComponent = inputs.albedoLinear * additionalAmbientIrradiance;
62
49
  vec3 outColorLinear = reflectedColorComponent + additionalMaterialReflectanceComponent;
63
- ${N?s`vec3 outColor = blackLevelSoftCompression(outColorLinear, inputs.averageAmbientRadiance);`:s`vec3 outColor = max(vec3(0.0), outColorLinear - 0.005 * inputs.averageAmbientRadiance);`}
50
+ ${D?m`vec3 outColor = blackLevelSoftCompression(outColorLinear, inputs.averageAmbientRadiance);`:m`vec3 outColor = max(vec3(0.0), outColorLinear - 0.005 * inputs.averageAmbientRadiance);`}
64
51
  return delinearizeGamma(outColor);
65
52
  }
66
- `);break;case 5:case 6:o(g),t(g),g.code.add(s`const float roughnessTerrain = 0.5;
53
+ `);break;case 5:case 6:e(g),o(g),g.code.add(m`const float roughnessTerrain = 0.5;
67
54
  const float specularityTerrain = 0.5;
68
- const vec3 fresnelReflectionTerrain = vec3(0.04);
69
- vec3 evaluatePBRSimplifiedLighting(vec3 n, vec3 c, float shadow, float ssao, vec3 al, vec3 vd, vec3 nup) {
70
- vec3 viewDirection = -vd;
71
- vec3 h = normalize(viewDirection + mainLightDirection);
72
- float NdotL = clamp(dot(n, mainLightDirection), 0.001, 1.0);
73
- float NdotV = clamp(abs(dot(n, viewDirection)), 0.001, 1.0);
74
- float NdotH = clamp(dot(n, h), 0.0, 1.0);
75
- float NdotNG = clamp(dot(n, nup), -1.0, 1.0);
76
- vec3 albedoLinear = linearizeGamma(c);
77
- float lightness = 0.3 * albedoLinear[0] + 0.5 * albedoLinear[1] + 0.2 * albedoLinear[2];
78
- vec3 f0 = (0.85 * lightness + 0.15) * fresnelReflectionTerrain;
79
- vec3 f90 = vec3(clamp(dot(f0, vec3(50.0 * 0.33)), 0.0, 1.0));
80
- vec3 mainLightIrradianceComponent = (1. - shadow) * NdotL * mainLightIntensity;
81
- vec3 ambientLightIrradianceComponent = calculateAmbientIrradiance(n, ssao) + al;
55
+ vec3 evaluatePBRSimplifiedLighting(vec3 normal, vec3 albedo, float shadow, float ssao, vec3 additionalLight, vec3 viewDirection, vec3 upDirection) {
56
+ PBRShadingInfo inputs;
57
+ calculateSimplifiedInputs(inputs, normal, viewDirection, upDirection, albedo);
58
+ vec3 mainLightIrradianceComponent = (1. - shadow) * inputs.NdotL * mainLightIntensity;
59
+ vec3 ambientLightIrradianceComponent = calculateAmbientIrradiance(normal, ssao) + additionalLight;
82
60
  vec3 ambientSky = ambientLightIrradianceComponent + mainLightIrradianceComponent;
83
- vec3 indirectDiffuse = ((1.0 - NdotNG) * mainLightIrradianceComponent + (1.0 + NdotNG ) * ambientSky) * 0.5;
84
- vec3 outDiffColor = albedoLinear * (1.0 - f0) * indirectDiffuse / PI;
85
- vec3 mainLightRadianceComponent = normalDistribution(NdotH, roughnessTerrain) * mainLightIntensity;
86
- vec2 dfg = prefilteredDFGAnalytical(roughnessTerrain, NdotV);
87
- vec3 specularColor = f0 * dfg.x + f90 * dfg.y;
61
+ vec3 indirectDiffuse = ((1.0 - inputs.NdotUP) * mainLightIrradianceComponent + (1.0 + inputs.NdotUP ) * ambientSky) * 0.5;
62
+ vec3 outDiffColor = inputs.albedoLinear * (1.0 - inputs.f0) * indirectDiffuse / PI;
63
+ vec3 mainLightRadianceComponent = normalDistribution(inputs.NdotH, roughnessTerrain) * mainLightIntensity;
64
+ vec2 dfg = prefilteredDFGAnalytical(roughnessTerrain, inputs.NdotV);
65
+ vec3 specularColor = inputs.f0 * dfg.x + inputs.f90 * dfg.y;
88
66
  vec3 specularComponent = specularityTerrain * specularColor * mainLightRadianceComponent;
89
67
  vec3 outColorLinear = outDiffColor + specularComponent;
90
68
  vec3 outColor = delinearizeGamma(outColorLinear);
91
69
  return outColor;
92
- }`)}}export{v as EvaluateSceneLighting,p as addAmbientBoostFactor,f as addLightingGlobalFactor};
70
+ }`)}}export{f as EvaluateSceneLighting,p as addAmbientBoostFactor,L as addLightingGlobalFactor};