@arcgis/core 4.33.0-next.20250304 → 4.33.0-next.20250306

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 (60) hide show
  1. package/arcade/arcadeCompiler.js +1 -1
  2. package/assets/esri/core/workers/RemoteClient.js +1 -1
  3. package/assets/esri/core/workers/chunks/{e99d7ecb80a9df9ead6d.js → 1e7a70a1871fea29169e.js} +3 -3
  4. package/assets/esri/core/workers/chunks/{618016fc1165bcfc2b0d.js → 42b862550c96cc1be956.js} +7 -9
  5. package/assets/esri/core/workers/chunks/4403b3f08907e88d0d91.js +1 -0
  6. package/assets/esri/core/workers/chunks/{0e2d9cd4e8ee5a62b05c.js → 45eee326f7a649c5a15b.js} +7 -9
  7. package/assets/esri/core/workers/chunks/7975ada96e4540a37c83.js +1 -0
  8. package/assets/esri/core/workers/chunks/e3e049311bced533c853.js +1 -0
  9. package/assets/esri/core/workers/chunks/{b464b7800a2ddd92b9a7.js → e8a19f9144df8f155e30.js} +1 -1
  10. package/assets/esri/core/workers/chunks/f4111bb5e5a4910b684a.js +1 -0
  11. package/assets/esri/libs/parquet/pkg/arcgis_parquet_bg.wasm +0 -0
  12. package/chunks/Clouds.glsl.js +19 -23
  13. package/chunks/ImageMaterial.glsl.js +1 -1
  14. package/core/Accessor.js +1 -1
  15. package/core/accessorSupport/decorators/subclass.js +1 -1
  16. package/core/accessorSupport/interfaces.js +1 -1
  17. package/interfaces.d.ts +8 -4
  18. package/layers/mixins/ArcGISImageService.js +1 -1
  19. package/layers/support/featureLayerUtils.js +1 -1
  20. package/libs/parquet/parquet.js +1 -1
  21. package/package.json +1 -1
  22. package/request.js +1 -1
  23. package/rest/support/IdentifyParameters.js +1 -1
  24. package/support/revision.js +1 -1
  25. package/views/3d/analysis/Dimension/DimensionTool.js +1 -1
  26. package/views/3d/analysis/Dimension/LengthDimensionSubTool.js +1 -1
  27. package/views/3d/analysis/Dimension/lengthDimensionManipulatorUtils.js +1 -1
  28. package/views/3d/analysis/Slice/RotateManipulator.js +1 -1
  29. package/views/3d/environment/Clouds.glsl.js +1 -1
  30. package/views/3d/environment/CloudsParameters.js +1 -1
  31. package/views/3d/environment/CloudsRenderer.js +1 -1
  32. package/views/3d/layers/DynamicLayerView3D.js +1 -1
  33. package/views/3d/layers/MediaLayerView3D.js +1 -1
  34. package/views/3d/layers/support/FeatureTile.js +1 -1
  35. package/views/3d/layers/support/FeatureTileFetcher3D.js +1 -1
  36. package/views/3d/support/StreamTextureCollection.js +1 -1
  37. package/views/3d/support/TextureCollection.js +1 -1
  38. package/views/3d/terrain/TerrainRenderer.js +1 -1
  39. package/views/3d/terrain/TerrainSurface.js +1 -1
  40. package/views/3d/webgl-engine/core/shaderLibrary/util/CloudsParallaxShading.glsl.js +7 -7
  41. package/views/3d/webgl-engine/core/shaderLibrary/util/DoublePrecision.glsl.js +5 -7
  42. package/views/3d/webgl-engine/core/shaderLibrary/util/LookupCloudsFromTextureArray.glsl.js +51 -0
  43. package/views/3d/webgl-engine/lib/GLMaterialParameters.js +5 -0
  44. package/views/3d/webgl-engine/lib/GLMaterialRepository.js +1 -1
  45. package/views/3d/webgl-engine/lib/RenderingContext.js +1 -1
  46. package/views/3d/webgl-engine/lib/TextTextureAtlas.js +1 -1
  47. package/views/3d/webgl-engine/lib/Texture.js +1 -1
  48. package/views/3d/webgl-engine/lib/TextureRepository.js +1 -1
  49. package/views/3d/webgl-engine/materials/ImageMaterial.js +1 -1
  50. package/views/animation/pointToPoint/apex/planning.js +1 -1
  51. package/views/webgl/FramebufferObject.js +1 -1
  52. package/views/webgl/TextureDescriptor.js +1 -1
  53. package/widgets/FeatureForm/FieldInput.js +1 -1
  54. package/widgets/FeatureForm/UtilityNetworkAssociationAddAssociationViewModel.js +1 -1
  55. package/widgets/UtilityNetworkTraceAnalysis/UtilityNetworkTraceAnalysisViewModel.js +1 -1
  56. package/assets/esri/core/workers/chunks/04341d50082f864025aa.js +0 -1
  57. package/assets/esri/core/workers/chunks/10118666a5a5b141ece6.js +0 -1
  58. package/assets/esri/core/workers/chunks/64d3e683872791eb6ae9.js +0 -1
  59. package/assets/esri/core/workers/chunks/8b057b5a606ac3669a78.js +0 -1
  60. package/views/3d/webgl-engine/core/shaderLibrary/util/LookupCubemapFromTextureArray.glsl.js +0 -39
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../Color.js";import i from"../../../core/Accessor.js";import{difference as r}from"../../../core/arrayUtils.js";import s from"../../../core/CollectionFlattener.js";import a from"../../../core/Evented.js";import"../../../core/has.js";import n from"../../../core/Logger.js";import{clamp as l}from"../../../core/mathUtils.js";import{destroyMaybe as o}from"../../../core/maybe.js";import{MemCachePool as h}from"../../../core/MemCachePool.js";import d from"../../../core/ObjectPool.js";import p from"../../../core/PooledArray.js";import{throwIfAborted as u,isAbortError as c,isAborted as g}from"../../../core/promiseUtils.js";import{watch as _,syncAndInitial as m,sync as f,initial as y}from"../../../core/reactiveUtils.js";import{property as T}from"../../../core/accessorSupport/decorators/property.js";import{subclass as v}from"../../../core/accessorSupport/decorators/subclass.js";import{i as E,c as S}from"../../../chunks/vec32.js";import{create as w}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{UpdatingHandles as C}from"../../../core/support/UpdatingHandles.js";import{getReferenceEllipsoid as L}from"../../../geometry/ellipsoidUtils.js";import b from"../../../geometry/SpatialReference.js";import{getProjector as P}from"../../../geometry/projection/projectors.js";import{projectPointToVector as M}from"../../../geometry/projection/projectPointToVector.js";import{projectVectorToVector as D}from"../../../geometry/projection/projectVectorToVector.js";import{create as x,equals as U,intersection as R,intersectsSphere as j,empty as A,expand as I}from"../../../geometry/support/aaBoundingRect.js";import{create as B,copy as V}from"../../../geometry/support/frustum.js";import{isPlateCarree as k}from"../../../geometry/support/spatialReferenceUtils.js";import{e as O,a as G,c as N}from"../../../chunks/sphere.js";import{ElevationQueryTileCache as q}from"../../../layers/support/ElevationQueryTileCache.js";import{isBaseLayer as F}from"../../../layers/support/layerUtils.js";import{debugFlags as W}from"../support/debugFlags.js";import{ElevationRange as $}from"../support/ElevationRange.js";import{ElevationUpdateEvent as H}from"../support/ElevationUpdateEvent.js";import{toBoundingRect as Q}from"../support/extentUtils.js";import{ClientType as z}from"../support/index.js";import{updatingProgress as X}from"../support/updatingProperties.js";import{ElevationBounds as Y}from"./ElevationBounds.js";import{ElevationData as K,sampleElevation as J}from"./ElevationData.js";import{create as Z}from"./ExtentHelper.js";import{TextureUpdate as ee}from"./interfaces.js";import{LayerClass as te,LayerClasses as ie}from"./LayerClass.js";import{OverlayManager as re}from"./OverlayManager.js";import{PlanarPatch as se}from"./PlanarPatch.js";import{RenderOrder as ae}from"./RenderOrder.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 _e from"./TerrainSurfacePerformanceInfo.js";import{weakAssert as me,isVectorTileLayerView as fe,neighborEdgeIndices as ye,internalAssert as Te,oppositeEdge as ve,isSurfaceLayerView as Ee,isGroupLayerView as Se,isMapTileLayerView as we,isBlendableLayerView as Ce,isElevationLayerView as Le,releaseTerrainData as be,enableTerrainInternalChecks as Pe,neighborCornerIndices as Me,oppositeCorner as De,enableWaterproofTests as xe,enableInternalTerrainChecks as Ue,enableTerrainWaterproofChecks as Re}from"./terrainUtils.js";import{Tile as je,lijEquals as Ae}from"./Tile.js";import{printAllocations as Ie}from"./TilePerLayerInfo.js";import{TileUpdate as Be}from"./TileUpdate.js";import{IteratorPreorder as Ve,IteratorPostorder as ke,compareTilesByLij as Oe,hasLoadableSiblings as Ge,sortTilesByPOI as Ne}from"./tileUtils.js";import{TilingSchemeLogic as qe}from"./TilingSchemeLogic.js";import{TransparencyMode as Fe}from"./TransparencyMode.js";import{UpsampleInfo as We}from"./UpsampleInfo.js";import{isCompositeBlendMode as $e,blendModeFromString as He}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{PBRMode as Qe}from"../webgl-engine/core/shaderLibrary/shading/PhysicallyBasedRenderingParameters.glsl.js";import{RenderRequestType as ze}from"../webgl-engine/lib/basicInterfaces.js";import{RenderState as Xe}from"../../support/RenderState.js";import{ImmediateTask as Ye,TaskPriority as Ke,noBudget as Je}from"../../support/Scheduler.js";import{Yield as Ze}from"../../support/Yield.js";var et;let tt=class extends(a.EventedMixin(i)){static{et=this}get allTiles(){return this._allTiles}constructor(e){super(e),this._scaleRangeQueries=new ne,this._iteratorPool=new d(Ve,(e=>e.remove=()=>this._iteratorPool.release(e))),this._postorderIterator=new ke,this._hasPendingUpdates=!1,this._pendingUpdates=0,this._asyncWorkItems=0,this._allTilesDirty=!0,this._allTilesSorted=!0,this._usedMemory=null,this._performanceInfo=new _e,this._viewChanged=!1,this.heading=0,this._inFrameTask=!1,this._viewChangeUpdateDirty=!1,this._eyePosRenderSR=w(),this._eyePosSurfaceSR=w(),this._splitLimits=new oe,this._frustum=B(),this._layerViews=[new Array,new Array],this._layerIndexByUid=[new Map,new Map],this._basemapLayerViewHandles=new Map,this._watchUpdatingTracking=new C,this._frameTask=Ye,this._allTiles=new p,this._upsampleInfoPool=new d(We),this._shouldEmitChangeEvent=!1,this._destroying=!1,this._rootTilesExtent=x(),this.updatingProgress=.5,this._maxNumUpdating=1,this.maxTextureScale=1.2,this._spatialReference=b.WebMercator,this._elevationProjectorCache=new Map,this.visibleElevationBounds=new Y(1/0,-1/0),this.rootTileElevationBounds=new Y(1/0,-1/0),this._projectorCache=new Map,this._radiusModifier=Math.cos(Math.PI/16/16),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.overlayManager=new re({...e,surface:this}),this._isGlobal=!e.view?.state?.isLocal,this._isGeographic=this._spatialReference?.isGeographic??!1,this._tileConstructor=this._isGlobal?le:se,this._ellipsoid=L(e.view.spatialReference)}initialize(){const e=this.view,t=e.resourceController,i=t.memoryController;this._tileCache=new h(((e,t)=>i.newCache(e,t)),"terrain-tile"),this._upsampleMapCache=i.newCache("terrain-upsample",(e=>e.unloadMapData())),this._elevationQueryCache=new q(i.newCache("elevation-query"));const r=this.overlayManager;this._renderer=new ge(r.renderer,e._stage,this._allTiles,this._ellipsoid.radius,i),this.addHandles([_((()=>r.renderer.isEmpty),(()=>this._evaluateTransparency())),_((()=>this.renderer.visible),(e=>this.suspended=!e)),_((()=>this.heading),(e=>{this._renderer.updateHeading(e),this._updateTileTextures(ee.FADING)})),_((()=>({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);(t===Xe.IDLE||Math.min(r,360-r)>=30)&&(this.heading=i)}))],"overlayManager"),this.addHandles([_((()=>this.baseOpacity),(()=>{this._handleLayerViewChanges(),this._updateTileTextures(this._evaluateTransparency()?ee.UNFADED:ee.IMMEDIATE)}),m),_((()=>this.hasCompositeBlendMode),(()=>this._updateTileTextures(this._evaluateTransparency()?ee.UNFADED:ee.IMMEDIATE)),m),_((()=>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))})),_((()=>W.TERRAIN_TILE_TREE_SHOW_TILES),(t=>{t&&!this._treeDebugger?import("../layers/support/TerrainTileTree3DDebugger.js").then((({TerrainTileTree3DDebugger:t})=>{!this._treeDebugger&&W.TERRAIN_TILE_TREE_SHOW_TILES&&(this._treeDebugger=new t({view:e}))})):t||(this._treeDebugger=o(this._treeDebugger))}),y)]),this.addHandles([_((()=>this._renderer.tileRenderer?.texturesBeingCompressed),((e,t)=>{t&&e<t&&(this.setMemoryDirty(),this._allTiles.forAll((e=>e.setMemoryDirty())))}))]),this.addHandles([_((()=>this._renderer.texturesBeingCompressed),((e,t)=>{0===e&&e!==t&&this.requestRender()}))]);const{spatialReference:a}=e;this._extentHelper=Z(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 qe({layers:n,extentHelper:this._extentHelper,viewingMode:this.viewingMode,viewSpatialReference:a});this._set("tilingSchemeLogic",l),this._updateTilingScheme(),this._elevationDataRequester=t.createStreamDataRequester(z.ELEVATION),this._mapDataRequester=t.createStreamDataRequester(z.BASEMAP);const d=t.scheduler;this._frameTask=d.registerTask(Ke.TERRAIN_SURFACE,this),this.addHandles([_((()=>this._extentHelper.stencilEnabledExtents),(e=>this._renderer.setStencilEnabledLayerExtents(e)),y),_((()=>this.tilingSchemeLogic.tilingScheme),(()=>this._updateTilingScheme()),f),_((()=>this.extent),(()=>this._updateRootTiles()),y),e.on("resize",(()=>this._viewChangeUpdate())),_((()=>{const t=e.state;return[this._lodBias,this.lodSnappingEnabled,e.quality,t.camera,t.contentCamera,t.fixedContentCamera]}),(()=>this._viewChangeUpdate()),m),_((()=>e.qualitySettings?.fadeDuration),(e=>this._renderer.textureFadingEnabled=e>0),y),_((()=>e.qualitySettings?.physicallyBasedRenderingEnabled),(e=>this._renderer.pbrMode=e?Qe.Simplified:Qe.Disabled),y),_((()=>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)}destroy(){this._destroying=!0,this._frameTask.remove(),this._watchUpdatingTracking.destroy(),this._removeAllTiles(),this._set("tilingSchemeLogic",o(this.tilingSchemeLogic)),this._basemapLayerViewHandles.forEach(((e,t)=>this._unregisterTiledLayerView(t))),this._elevationDataRequester=null,this._mapDataRequester=null,this._set("overlayManager",o(this.overlayManager)),this._tileCache=o(this._tileCache),je.prune(),this._treeDebugger=o(this._treeDebugger),this._renderer=o(this._renderer),this._iteratorPool=o(this._iteratorPool),this._upsampleMapCache=o(this._upsampleMapCache),this._elevationQueryCache=o(this._elevationQueryCache),this._set("view",null),this._extentHelper=o(this._extentHelper),this._upsampleInfoPool=o(this._upsampleInfoPool),Ie()}get renderer(){return this._renderer}get frustum(){return this._frustum}get snapLevel(){if(this.lodSnappingEnabled){const{view:e,tilingScheme:t}=this,i=e.scale;if(t&&i){const r=t.levelAtScale(i)+e.qualitySettings.tiledSurface.lodBias,s=t.getMaxLod();return r<=0?null:Math.min(r,s||1/0)}}return 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,{clippingArea:t}=this.view;if(null==t||null==e)return null;const i=x(),r=Q(t,i,e)?i:null,s=this._get("extent");return U(r,s)?s:r}get rootTilesExtent(){return this._rootTilesExtent}get extent(){const e=R(this.groundExtent,this._userClippingExtent,x()),t=this._get("extent");return U(e,t)?t:e}get groundExtent(){return null!=this._tilingSchemeExtent?this._tilingSchemeExtent:this._rootTilesExtent}get _tilingSchemeExtent(){return this.tilingSchemeLogic?.extent}get updating(){return this._hasPendingUpdates||(this._maxNumUpdating=1),!!((this.running||this._watchUpdatingTracking?.updating||this._asyncWorkItems>0)&&this.ready&&!this.suspended||this.overlayManager?.updating||this.renderer.texturesBeingCompressed)}get running(){return(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 null!=this._rootTiles}set renderOrder(e){this._renderer.renderOrder=e,this._set("renderOrder",e)}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 this._renderer.transparency===Fe.Opaque}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}getElevation(e,t,i,r){const s=this._rootTiles;if(!s?.length)return null;if(0===s[0].layerInfo[te.ELEVATION].length)return null;let a=this._elevationProjectorCache.get(r);if(void 0===a&&(a=P(r,this._spatialReference)??null,this._elevationProjectorCache.set(r,a)),null==a)return n.getLogger(this).error("TerrainSurface.getElevation(): could not project given point to tiling scheme coordinate system"),null;const l=E(rt,e,t,i);a(l,0,l,0);return ot(s,l[0],l[1])}getElevations(e,t,i){const r=this._rootTiles,s=r?r[0].layerInfo[te.ELEVATION].length:0;if(r?.length&&0!==s)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)}getScale(e){if(!this.tilingScheme)return null;if(!M(e,rt,this.spatialReference))return n.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(rt)){let e=i;for(;e.children[0]&&!e.rendered;){const t=e.children[0].extent;let i=0;rt[0]>t[2]&&(i+=1),rt[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=P(e,this._tilingSchemeSpatialReference)??null;return this._projectorCache.set(e,i),i}getSphereElevationBounds(e,t){const i=this._ensureProjector(t);if(null==i)return n.getLogger(this).error("TerrainSurface.getSphereElevationBounds(): could not project given point to tiling scheme coordinate system"),null;O(e,st);const r=G(st);i(r,0,r,0);const s=new $,a=this._rootTiles;if(null!=a){const e=[];for(const i of a)e.push(i);let t=0;for(;t<e.length;){const i=e[t];if(++t,!j(i.extent,st))continue;const r=i.children;if(null==r[0]||i.rendered)s.expandElevationRangeValues(i.elevationBoundsMin,i.elevationBoundsMax);else for(const t of r)e.push(t)}}return s}getRootElevationBounds(){return new $(this.rootTileElevationBounds.min,this.rootTileElevationBounds.max)}getLowerBoundRadius(){const e=(this._ellipsoid.radius+this.visibleElevationBounds.min)*this._radiusModifier;return Math.min(e,this._ellipsoid.radius)}getSphereScale(e,t){if(!this.tilingScheme)return null;if(!M(e,G(st),this.spatialReference))return n.getLogger(this).error("TerrainSurface.getSphereScale(): could not project given point to tiling scheme coordinate system"),null;st[3]=t;let i=null;const r=e=>{if(e&&j(e.extent,st)){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){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._allSurfaceLayersTransparent()?t?Fe.Invisible:Fe.InvisibleWithDraped:e>=1&&!this.hasCompositeBlendMode&&!this._renderer.slicePlaneEnabled?Fe.Opaque:Fe.Transparent;return this._renderer.transparency=r,i!==r}_updateTilingScheme(){const e=this.tilingSchemeLogic.tilingScheme;if(!(e!==this.tilingScheme))return;me(!!e,"tiling scheme cannot be reset to undefined"),this._isGlobal=!this.view?.state?.isLocal,this.tilingScheme&&this._removeAllTiles();const t=e?.spatialReference??b.WebMercator;this._spatialReference=t,this._isWebMercator=!!t?.isWebMercator,this._isWebMercatorOnPlateCarree=this._isWebMercator&&k(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(et._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{extent:e,tilingScheme:t}=this;if(!t)return;const i=at;let s=t.rootTilesInExtent(e,i,5*he);if(null!=this._rootTiles){if(s.length>he)return void n.getLogger(this).warn(de);const e=this._rootTiles.map((e=>e.lij)),t=r(e,s,Ae);if(this._updatingRootTiles=!0,t.removed.length>0||t.added.length>0){const e=this._rootTiles.filter((e=>!(t.removed.findIndex((t=>Ae(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&&(n.getLogger(this).warn(pe),s=t.rootTilesInExtent(e,i,he)),this._setRootTiles(s.map((e=>this._newRootTile(e))));U(i,this._rootTilesExtent)||(this._rootTilesExtent=x(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 e.shouldSplit(this._splitLimits,this._eyePosRenderSR,this.snapLevel)===Be.SPLIT}_newRootTile(e){const t=this._acquireTile(0,e[1],e[2],null);return this._shouldSplit(t)&&t.setPendingUpdate(Be.SPLIT),this._loadTile(t),this._markTileToUpdate(t),this._updateRootTileElevationBounds(),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)}_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.extent)&&e.resetPendingUpdate(Be.GEOMETRY)&&this._updateTileGeometryState(e)}_updateTilesVisibility(e){if(null==e)return;const t=Ge(e),i=this.visibleElevationBounds;let r=t?i.min:1/0,s=t?i.max:-1/0;const a=this.extent,n=this.view.state.contentCamera.viewProjectionMatrix;this.setTileTreeDirty();const l=this._iteratorPool.acquire();for(l.reset(e);!l.done;){const e=l.next();e.updateClippingStatus(a)&&e.resetPendingUpdate(Be.GEOMETRY)&&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.min!==r||i.max!==s)&&(this.visibleElevationBounds=new Y(r,s))}_updateRootTileElevationBounds(){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.rootTileElevationBounds;r.min===e&&r.max===t||(this.rootTileElevationBounds=new Y(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=V(this._splitLimits.frustum??B(),t.frustum):this._splitLimits.frustum=null,V(this._frustum,e.frustum),S(this._eyePosRenderSR,t.eye),D(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[te.MAP].some(fe)&&e.setPendingUpdate(Be.TEXTURE_FADING),this._pendingTilesToUpdate.add(e)}))}_updateTileTexture(e,t){const i=e.resetPendingUpdate(Be.TEXTURE_FADING)?Be.TEXTURE_FADING:!!e.resetPendingUpdate(Be.TEXTURE_NOFADING)&&Be.TEXTURE_NOFADING;i&&(this._renderer.updateTileTexture(e,i),this._usedMemory=null,t.madeProgress())}_emitElevationUpdateEventForTiles(){if(!this._shouldEmitChangeEvent)return;const e=nt.extent;A(e),this._pendingTilesForElevationUpdateEvent.forEach((t=>I(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"),Pe&&this._checkTileInvariant(),!e.hasProgressed)return Ze}_checkTileInvariant(){const e=new Map;this._allTiles.forAll((t=>e.set(t,new Set))),this._allTiles.forAll((t=>{if(me(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(me(t.unmergableChildCount===i,` Tile[${t.lij.toString()}] unmergeable child count mismatch: actual ${t.unmergableChildCount} vs ${i}`),t.hasPendingUpdate(Be.MERGE)){me(!t.hasPendingUpdate(Be.SPLIT),"Tile can be both split and merge at the same time");for(const e of t.children)me(e.leaf||e.hasPendingUpdate(Be.MERGE),"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}])`),me(r,`tile level delta [${t.level}] vs [${e.level}] > ${ue}`))}me(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(ye[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(!Ae(s,i.lij)){const r=e.get(i);me(!r.has(t),"Cannot already have neighbor"),r.add(t)}}me(a.rendered||a.level===t.level,"Non-same-level-neighbor of rendered must be rendered"),me(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);me(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 ht(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=null!=n&&n.hasPendingUpdate(Be.MERGE),o=l?Be.MERGE:e.shouldSplit(r,s,i),h=o===Be.SPLIT;e.leaf?dt(e,h):t.pushAll(e.children),l?(e.resetPendingUpdate(Be.SPLIT),e.leaf||e.setPendingUpdate(Be.MERGE),this._updateClippingStatus(e),e.updateVisibility(),e.updateScreenDepth(a)):h?(e.resetPendingUpdate(Be.MERGE),e.leaf&&e.setPendingUpdate(Be.SPLIT)):(e.resetPendingUpdate(Be.SPLIT)&&e.updateAgentSuspension(),o===Be.ELEVATION&&e.updateAgents(te.ELEVATION),e.leaf||(e.setPendingUpdate(Be.MERGE),e.resetPendingUpdate(Be.SPLIT)))}this.requestUpdate(),(this._shortBatches||!this._oneBatchPerFrameTask)&&this._updatePendingTileGeometries(),e.madeProgress()}_sortTiles(e){e.done||this._allTilesSorted||(Ne(this._allTiles,this.view.pointsOfInterest.focus.renderLocation),this._allTilesSorted=!0,this._treeDebugger&&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=Me[e];i(r,l.cornerPeerNeighbors[e]?.findCorner(De(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(ye[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,Pe&&xe&&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(Be.MERGE)){if(!t||s.unmergableChildCount>0)return e.done;for(s.resetPendingUpdate(Be.MERGE);null!=n.parent&&0===n.parent.unmergableChildCount&&n.parent.resetPendingUpdate(Be.MERGE);)n=n.parent;this._mergeTile(n),a=!0,e.madeProgress()}else if(s.resetPendingUpdate(Be.SPLIT)){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(ye[r],e);null!=a&&i-a.level===ue&&(t=!1,Pe&&(Te(a.leaf),Te(a.hasPendingUpdate(Be.SPLIT))))}}t?(this._splitTile(s),e.madeProgress(),a=!0):s.setPendingUpdate(Be.SPLIT)}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._sortTiles(e)}_updateElevation(e){e.done||(this._allTiles.some((t=>(t.resetPendingUpdate(Be.GEOMETRY)&&(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.overlayManager?.updateOverlayParameters(ze.UPDATE),this.overlayManager.setPlacementDirty(),this._updateRootTiles())}get _lodBias(){const e=this.view.quality;return this.view.qualitySettings.tiledSurface.lodBias-(1-e)*ce}_getLodBiasCorrectedScale(e){const t=this.tilingScheme.levels,i=l(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.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?ut(e):this._purgeSubtree(e),this._allTiles.removeUnordered(e),this._unloadTile(e),e.dispose(),this._tileCache.put(et._tileMemcacheKey,e)}_unloadTile(e){this._pendingTilesToUpdate.delete(e),this._pendingTilesForElevationUpdateEvent.delete(e),e.unload()}_splitTile(e){me(e.leaf,"Tile that is already split should not be split again!"),me(e.rendered,"Tile marked to split is not rendered"),ut(e);const t=e.createChildren();this._allTiles.pushArray(t),e.updateAgentSuspension(),me(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=>dt(e,e.hasPendingUpdate(Be.SPLIT)))),++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){me(!!r,"createTile sanity check");const s=this._acquireTile(e,t,i,r);return s.updateClippingStatus(this.extent),s.updateScreenDepth(this.view.state.contentCamera.viewProjectionMatrix),this._shouldSplit(s)&&s.setPendingUpdate(Be.SPLIT),s}get _shortBatches(){return this.view.state.mode!==Xe.IDLE}_mergeTile(e){me(!e.hasPendingUpdate(Be.SPLIT),"_mergeTile sanity check"),me(!e.leaf,"Cannot merge a leaf"),e.leaf||(this._purgeSubtree(e),me(!e.renderData,"Merging tile with existing render data?"),this._loadTile(e),this._markTileToUpdate(e),this._emitTileScaleChange(e),this._shortBatches&&this._updatePendingTileGeometries(),dt(e,!1),this._allTilesDirty=!0,++this._performanceInfo.numMerged)}_loadTile(e){e.load(),this.requestUpdate(),this._allTilesDirty=!0,this.overlayManager?.hasOverlays&&this.overlayManager.updateTileOverlayParameters(e)}_handleLayerViewChanges(e=Je){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),Ee(e)||Se(e))if(this._basemapLayerViewHandles.has(e.uid)&&!Se(e)){const i=this._layerClassFromLayerView(e),s=this._getLayerIdxByUID(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()}_allSurfaceLayersTransparent(){let e=0===this.view.map?.ground?.opacity;for(const t of this.view.allLayerViews.items)if(we(t)&&!F(t.layer)&&0!==t.fullOpacity)return e=!1,e;return e}_hasCompositeBlendMode(){for(const e of this.view.allLayerViews.items)if((Ce(e)||Se(e))&&$e(He[e.layer.blendMode]))return!0;return!1}_layerClassFromLayerView(e){return Le(e)?te.ELEVATION:te.MAP}_registerTiledLayerView(e){const t=[];if((Ce(e)||Se(e))&&t.push(_((()=>e.layer.blendMode),(()=>{this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._updateTileTextures(ee.UNFADED)}))),!Se(e)){const i=this._layerClassFromLayerView(e);t.push(_((()=>e.suspended),(()=>this._updateTiledLayers()))),t.push(_((()=>e.fullOpacity),(()=>this._updateTileTextures(ee.UNFADED)))),t.push(_((()=>"effectiveScaleRange"in e.layer?e.layer.effectiveScaleRange:null),(()=>this._restartAllAgents(i)))),t.push(e.on("data-changed",(()=>{const t=this._getLayerIdxByUID(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||!Ee(e)||!e.fullExtent)return;const r=this._layerClassFromLayerView(e);if(r===te.MAP){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),e===te.ELEVATION&&i.computeElevationBounds()}this._updateRootTileElevationBounds()}layerViewByIndex(e,t){return this._layerViews[t][e]}numLayers(e){return this._layerViews[e].length}_updateTileTextures(e){this._allTiles.forAll((t=>{t.updateAgents(te.MAP),e===ee.IMMEDIATE?this.renderer.updateTileTexture(t,Be.TEXTURE_NOFADING):t.updateRenderData(te.MAP,e)})),this._evaluateTransparency()}_invalidateLayerData(e,t){this._allTiles.forAll((i=>i.removeLayerAgent(e,t))),this._allTiles.forAll((i=>i.invalidateLayerData(e,t)))}setTileTreeDirty(){this._allTilesDirty=!0}requestRender(e=ze.UPDATE){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||fe(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,u(r),c(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();const s=t===te.ELEVATION;return r.requester??=s?this._elevationDataRequester:this._mapDataRequester,s?Le(i)?this._requestElevationTileData(e,i,r):Promise.reject():we(i)?this._requestMapTileData(e,i,r):Promise.reject()}_requestElevationTileData(e,t,i){++this._asyncWorkItems;const r=r=>{!g(i)&&r&&(this.setMemoryDirty(),this.requestUpdate(),this._elevationDataArrived(e,t,r))},s=i=>{c(i)||(n.getLogger(this).error(`Tile ${e.lij.toString()} layer ${te.ELEVATION}/${t.uid} error ${i}`),this._dataMissing(e,te.ELEVATION,t),this.requestUpdate())};return t.fetchTile(e.lij,i).then((e=>this._frameTask.schedule((()=>r(e)))),s).finally((()=>--this._asyncWorkItems))}_elevationDataArrived(e,t,i){const r=this._layerIndexByUid[te.ELEVATION].get(t.uid);if(null==r)return void n.getLogger(this).warn("TerrainSurface: received data from unknown layer %d %s",te.ELEVATION,e.lij.toString());const s=new K(e.lij,e.extent,i);e.dataArrived(r,te.ELEVATION,s);const a=[e],l=e.level,o=this._iteratorPool.acquire();for(o.reset(a);!o.done;){const e=o.next();e.findElevationBoundsForLayer(r,l),e.computeElevationBounds()}0===l&&this._updateRootTileElevationBounds(),o.remove(),this._updateTilesVisibility(a)}_requestMapTileData(e,t,i){++this._asyncWorkItems;const r=(r,s)=>{be(s),g(i)||(console.error(`Tile ${e.lij.toString()} layer ${te.MAP}/${t.uid} error ${r}`),this._dataMissing(e,te.MAP,t),this.requestUpdate())},s=e=>t=>r(t,e),a=r=>this._frameTask.schedule((()=>{this.requestUpdate(),g(i)?be(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._getLayerIdxByUID(te.MAP,t.uid);if(null==r)return be(i),void n.getLogger(this).warn("TerrainSurface: received data from unknown layer");e.dataArrived(r,te.MAP,i)}_getLayerIdxByUID(e,t){return this._layerIndexByUid[e].get(t)}_dataMissing(e,t,i){const r=this._getLayerIdxByUID(t,i.uid);null!=r?e.dataMissing(r,t):n.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._getLayerIdxByUID(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 visualizeNormals(){return this._renderer.visualizeNormals}set visualizeNormals(e){this._renderer.visualizeNormals=e}get renderingDisabled(){return this._renderer.renderingDisabled}set renderingDisabled(e){this._renderer.renderingDisabled=e}get test(){}checkAllTilesWaterproofness(){if(!xe)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){Re(e)}};e([T()],tt.prototype,"_renderer",void 0),e([T({constructOnly:!0})],tt.prototype,"_scaleRangeQueries",void 0),e([T({constructOnly:!0})],tt.prototype,"view",void 0),e([T({constructOnly:!0})],tt.prototype,"overlayManager",void 0),e([T()],tt.prototype,"_hasPendingUpdates",void 0),e([T()],tt.prototype,"_asyncWorkItems",void 0),e([T()],tt.prototype,"_allTilesDirty",void 0),e([T()],tt.prototype,"_allTilesSorted",void 0),e([T()],tt.prototype,"_viewChanged",void 0),e([T({type:Number})],tt.prototype,"heading",void 0),e([T()],tt.prototype,"_splitLimits",void 0),e([T({readOnly:!0})],tt.prototype,"_watchUpdatingTracking",void 0),e([T()],tt.prototype,"_frameTask",void 0),e([T({readOnly:!0})],tt.prototype,"snapLevel",null),e([T({readOnly:!0})],tt.prototype,"lodSnappingEnabled",null),e([T()],tt.prototype,"_userClippingExtent",null),e([T()],tt.prototype,"_rootTilesExtent",void 0),e([T({readOnly:!0})],tt.prototype,"extent",null),e([T({readOnly:!0})],tt.prototype,"groundExtent",null),e([T({readOnly:!0})],tt.prototype,"_tilingSchemeExtent",null),e([T({readOnly:!0})],tt.prototype,"updating",null),e([T({readOnly:!0})],tt.prototype,"running",null),e([T(X)],tt.prototype,"updatingProgress",void 0),e([T({readOnly:!0})],tt.prototype,"updatingProgressValue",null),e([T()],tt.prototype,"_maxNumUpdating",void 0),e([T()],tt.prototype,"baseOpacity",null),e([T()],tt.prototype,"hasCompositeBlendMode",void 0),e([T({readOnly:!0})],tt.prototype,"viewingMode",null),e([T()],tt.prototype,"maxTextureScale",void 0),e([T({readOnly:!0})],tt.prototype,"ready",null),e([T({value:ae.FRONT_TO_BACK})],tt.prototype,"renderOrder",null),e([T({readOnly:!0})],tt.prototype,"rootTiles",null),e([T()],tt.prototype,"_rootTiles",void 0),e([T({readOnly:!0})],tt.prototype,"spatialReference",null),e([T({type:t})],tt.prototype,"backgroundColor",null),e([T({value:!1})],tt.prototype,"slicePlaneEnabled",null),e([T({readOnly:!0})],tt.prototype,"tilingScheme",void 0),e([T({readOnly:!0})],tt.prototype,"tilingSchemeLocked",null),e([T({readOnly:!0})],tt.prototype,"tilingSchemeLogic",void 0),e([T()],tt.prototype,"wireframe",null),e([T({value:!1})],tt.prototype,"suspended",null),e([T()],tt.prototype,"fadeDuration",null),e([T()],tt.prototype,"visibleElevationBounds",void 0),e([T()],tt.prototype,"rootTileElevationBounds",void 0),e([T()],tt.prototype,"_layerViewsDirty",void 0),e([T()],tt.prototype,"renderPatchBorders",null),e([T()],tt.prototype,"visualizeNormals",null),e([T()],tt.prototype,"renderingDisabled",null),tt=et=e([v("esri.views.3d.terrain.TerrainSurface")],tt);const it=tt,rt=w(),st=N(),at=x();new p;const nt=new H("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 J(t,i,s)}return null}class ht{constructor(e){this.capacity=e,this._head=0,this._tail=0,this._data=new Array(e)}push(e){const t=this._tail;if(!(t<this.capacity))throw new Error("Queue full");this._data[t]=e,this._tail=t+1}pushAll(e){const t=e.length;if(0===t)return;const i=this._tail;if(!(i+t<=this.capacity))throw new Error("Queue full");for(let r=0;r<t;++r)this._data[i+r]=e[r];this._tail=i+t}pop(){const e=this._head;if(e<this._tail){const t=this._data[e];return this._head=e+1,t}}get empty(){return this._head>=this._tail}get full(){return this._tail>=this._data.length}}function dt(e,t){!e.leaf||e.level<ue||gt(e,(e=>{t&&pt(e);const i=ct(e);if(e.maxLevelDeltaNeighborCount++,i){let t=e.parent;for(;t;){const e=ct(t);if(t.unmergableChildCount++,!e)break;t=t.parent}}}))}function pt(e){if(e.hasPendingUpdate(Be.SPLIT))return;let t=e.parent;for(;t?.resetPendingUpdate(Be.MERGE);)t=t.parent;e.resetPendingUpdate(Be.MERGE),e.leaf&&e.setPendingUpdate(Be.SPLIT),e.level<ue||gt(e,(e=>{pt(e)}))}function ut(e){e.level<ue||gt(e,(e=>{if(e.maxLevelDeltaNeighborCount--,0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount){let t=e.parent;for(;t&&(t.unmergableChildCount--,ct(t));)t=t.parent}}))}function ct(e){return 0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount}function gt(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(ye[n],a);if(!l||l.level!==i)continue;const o=l.lij;o[1]===r&&o[2]===s||t(l)}}export{it as default};
5
+ import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../Color.js";import i from"../../../core/Accessor.js";import{difference as r}from"../../../core/arrayUtils.js";import s from"../../../core/CollectionFlattener.js";import a from"../../../core/Evented.js";import"../../../core/has.js";import n from"../../../core/Logger.js";import{clamp as l}from"../../../core/mathUtils.js";import{destroyMaybe as o}from"../../../core/maybe.js";import{MemCachePool as h}from"../../../core/MemCachePool.js";import d from"../../../core/ObjectPool.js";import p from"../../../core/PooledArray.js";import{throwIfAborted as u,isAbortError as c,isAborted as g}from"../../../core/promiseUtils.js";import{watch as _,syncAndInitial as m,sync as f,initial as y}from"../../../core/reactiveUtils.js";import{property as T}from"../../../core/accessorSupport/decorators/property.js";import{subclass as v}from"../../../core/accessorSupport/decorators/subclass.js";import{i as E,c as S}from"../../../chunks/vec32.js";import{create as w}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{UpdatingHandles as C}from"../../../core/support/UpdatingHandles.js";import{getReferenceEllipsoid as L}from"../../../geometry/ellipsoidUtils.js";import b from"../../../geometry/SpatialReference.js";import{getProjector as P}from"../../../geometry/projection/projectors.js";import{projectPointToVector as M}from"../../../geometry/projection/projectPointToVector.js";import{projectVectorToVector as D}from"../../../geometry/projection/projectVectorToVector.js";import{create as x,equals as U,intersection as R,intersectsSphere as j,empty as A,expand as I}from"../../../geometry/support/aaBoundingRect.js";import{create as B,copy as V}from"../../../geometry/support/frustum.js";import{isPlateCarree as k}from"../../../geometry/support/spatialReferenceUtils.js";import{e as O,a as G,c as N}from"../../../chunks/sphere.js";import{ElevationQueryTileCache as q}from"../../../layers/support/ElevationQueryTileCache.js";import{isBaseLayer as F}from"../../../layers/support/layerUtils.js";import{debugFlags as W}from"../support/debugFlags.js";import{ElevationRange as $}from"../support/ElevationRange.js";import{ElevationUpdateEvent as H}from"../support/ElevationUpdateEvent.js";import{toBoundingRect as Q}from"../support/extentUtils.js";import{ClientType as z}from"../support/index.js";import{updatingProgress as X}from"../support/updatingProperties.js";import{ElevationBounds as Y}from"./ElevationBounds.js";import{ElevationData as K,sampleElevation as J}from"./ElevationData.js";import{create as Z}from"./ExtentHelper.js";import{TextureUpdate as ee}from"./interfaces.js";import{LayerClass as te,LayerClasses as ie}from"./LayerClass.js";import{OverlayManager as re}from"./OverlayManager.js";import{PlanarPatch as se}from"./PlanarPatch.js";import{RenderOrder as ae}from"./RenderOrder.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 _e from"./TerrainSurfacePerformanceInfo.js";import{weakAssert as me,isVectorTileLayerView as fe,neighborEdgeIndices as ye,internalAssert as Te,oppositeEdge as ve,isSurfaceLayerView as Ee,isGroupLayerView as Se,isMapTileLayerView as we,isBlendableLayerView as Ce,isElevationLayerView as Le,releaseTerrainData as be,enableTerrainInternalChecks as Pe,neighborCornerIndices as Me,oppositeCorner as De,enableWaterproofTests as xe,enableInternalTerrainChecks as Ue,enableTerrainWaterproofChecks as Re}from"./terrainUtils.js";import{Tile as je,lijEquals as Ae}from"./Tile.js";import{printAllocations as Ie}from"./TilePerLayerInfo.js";import{TileUpdate as Be}from"./TileUpdate.js";import{IteratorPreorder as Ve,IteratorPostorder as ke,compareTilesByLij as Oe,hasLoadableSiblings as Ge,sortTilesByPOI as Ne}from"./tileUtils.js";import{TilingSchemeLogic as qe}from"./TilingSchemeLogic.js";import{TransparencyMode as Fe}from"./TransparencyMode.js";import{UpsampleInfo as We}from"./UpsampleInfo.js";import{isCompositeBlendMode as $e,blendModeFromString as He}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{PBRMode as Qe}from"../webgl-engine/core/shaderLibrary/shading/PhysicallyBasedRenderingParameters.glsl.js";import{RenderRequestType as ze}from"../webgl-engine/lib/basicInterfaces.js";import{RenderState as Xe}from"../../support/RenderState.js";import{ImmediateTask as Ye,TaskPriority as Ke,noBudget as Je}from"../../support/Scheduler.js";import{Yield as Ze}from"../../support/Yield.js";var et;let tt=class extends(a.EventedMixin(i)){static{et=this}get allTiles(){return this._allTiles}constructor(e){super(e),this._scaleRangeQueries=new ne,this._iteratorPool=new d(Ve,(e=>e.remove=()=>this._iteratorPool.release(e))),this._postorderIterator=new ke,this._hasPendingUpdates=!1,this._pendingUpdates=0,this._asyncWorkItems=0,this._allTilesDirty=!0,this._allTilesSorted=!0,this._usedMemory=null,this._performanceInfo=new _e,this._viewChanged=!1,this.heading=0,this._inFrameTask=!1,this._viewChangeUpdateDirty=!1,this._eyePosRenderSR=w(),this._eyePosSurfaceSR=w(),this._splitLimits=new oe,this._frustum=B(),this._layerViews=[new Array,new Array],this._layerIndexByUid=[new Map,new Map],this._basemapLayerViewHandles=new Map,this._watchUpdatingTracking=new C,this._frameTask=Ye,this._allTiles=new p,this._upsampleInfoPool=new d(We),this._shouldEmitChangeEvent=!1,this._rootTilesExtent=x(),this.updatingProgress=.5,this._maxNumUpdating=1,this.maxTextureScale=1.2,this._spatialReference=b.WebMercator,this._elevationProjectorCache=new Map,this.visibleElevationBounds=new Y(1/0,-1/0),this.rootTileElevationBounds=new Y(1/0,-1/0),this._projectorCache=new Map,this._radiusModifier=Math.cos(Math.PI/16/16),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;const t=e.view;this.overlayManager=new re({...e,surface:this}),this._isGlobal=!t.state?.isLocal,this._isGeographic=this._spatialReference?.isGeographic??!1,this._tileConstructor=this._isGlobal?le:se,this._ellipsoid=L(t.spatialReference),this._renderer=new ge(this.overlayManager.renderer,t._stage,this._allTiles,this._ellipsoid.radius,t.resourceController.memoryController)}initialize(){const e=this.view,t=e.resourceController,i=t.memoryController;this._tileCache=new h(((e,t)=>i.newCache(e,t)),"terrain-tile"),this._upsampleMapCache=i.newCache("terrain-upsample",(e=>e.unloadMapData())),this._elevationQueryCache=new q(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(ee.FADING)})),_((()=>({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);(t===Xe.IDLE||Math.min(r,360-r)>=30)&&(this.heading=i)}))],"overlayManager"),this.addHandles([_((()=>this.baseOpacity),(()=>{this._handleLayerViewChanges(),this._updateTileTextures(this._evaluateTransparency()?ee.UNFADED:ee.IMMEDIATE)}),m),_((()=>this.hasCompositeBlendMode),(()=>this._updateTileTextures(this._evaluateTransparency()?ee.UNFADED:ee.IMMEDIATE)),m),_((()=>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))})),_((()=>W.TERRAIN_TILE_TREE_SHOW_TILES),(t=>{t&&!this._treeDebugger?import("../layers/support/TerrainTileTree3DDebugger.js").then((({TerrainTileTree3DDebugger:t})=>{!this._treeDebugger&&W.TERRAIN_TILE_TREE_SHOW_TILES&&(this._treeDebugger=new t({view:e}))})):t||(this._treeDebugger=o(this._treeDebugger))}),y),_((()=>this._renderer?.texturesBeingCompressed),((e,t)=>{t&&e<t&&(this.setMemoryDirty(),this._allTiles.forAll((e=>e.setMemoryDirty()))),0===e&&e!==t&&this.requestRender()}))]);const{spatialReference:a}=e;this._extentHelper=Z(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 qe({layers:n,extentHelper:this._extentHelper,viewingMode:this.viewingMode,viewSpatialReference:a});this._set("tilingSchemeLogic",l),this._updateTilingScheme(),this._elevationDataRequester=t.createStreamDataRequester(z.ELEVATION),this._mapDataRequester=t.createStreamDataRequester(z.BASEMAP);const d=t.scheduler;this._frameTask=d.registerTask(Ke.TERRAIN_SURFACE,this),this.addHandles([_((()=>this._extentHelper.stencilEnabledExtents),(e=>this._renderer.setStencilEnabledLayerExtents(e)),y),_((()=>this.tilingSchemeLogic.tilingScheme),(()=>this._updateTilingScheme()),f),_((()=>this.extent),(()=>this._updateRootTiles()),y),e.on("resize",(()=>this._viewChangeUpdate())),_((()=>{const t=e.state;return[this._lodBias,this.lodSnappingEnabled,e.quality,t.camera,t.contentCamera,t.fixedContentCamera]}),(()=>this._viewChangeUpdate()),m),_((()=>e.qualitySettings?.fadeDuration),(e=>this._renderer.textureFadingEnabled=e>0),y),_((()=>e.qualitySettings?.physicallyBasedRenderingEnabled),(e=>this._renderer.pbrMode=e?Qe.Simplified:Qe.Disabled),y),_((()=>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)}destroy(){this._frameTask.remove(),this._watchUpdatingTracking.destroy(),this._removeAllTiles(),this._set("tilingSchemeLogic",o(this.tilingSchemeLogic)),this._basemapLayerViewHandles.forEach(((e,t)=>this._unregisterTiledLayerView(t))),this._elevationDataRequester=null,this._mapDataRequester=null,this._set("overlayManager",o(this.overlayManager)),this._tileCache=o(this._tileCache),je.prune(),this._treeDebugger=o(this._treeDebugger),this._renderer.destroy(),this._iteratorPool=o(this._iteratorPool),this._upsampleMapCache=o(this._upsampleMapCache),this._elevationQueryCache=o(this._elevationQueryCache),this._set("view",null),this._extentHelper=o(this._extentHelper),this._upsampleInfoPool=o(this._upsampleInfoPool),Ie()}get renderer(){return this._renderer}get frustum(){return this._frustum}get snapLevel(){if(this.lodSnappingEnabled){const{view:e,tilingScheme:t}=this,i=e.scale;if(t&&i){const r=t.levelAtScale(i)+e.qualitySettings.tiledSurface.lodBias,s=t.getMaxLod();return r<=0?null:Math.min(r,s||1/0)}}return 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,{clippingArea:t}=this.view;if(null==t||null==e)return null;const i=x(),r=Q(t,i,e)?i:null,s=this._get("extent");return U(r,s)?s:r}get rootTilesExtent(){return this._rootTilesExtent}get extent(){const e=R(this.groundExtent,this._userClippingExtent,x()),t=this._get("extent");return U(e,t)?t:e}get groundExtent(){return null!=this._tilingSchemeExtent?this._tilingSchemeExtent:this._rootTilesExtent}get _tilingSchemeExtent(){return this.tilingSchemeLogic?.extent}get updating(){return this._hasPendingUpdates||(this._maxNumUpdating=1),!!((this.running||this._watchUpdatingTracking?.updating||this._asyncWorkItems>0)&&this.ready&&!this.suspended||this.overlayManager?.updating||this.renderer.texturesBeingCompressed)}get running(){return(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 null!=this._rootTiles}set renderOrder(e){this._renderer.renderOrder=e,this._set("renderOrder",e)}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 this._renderer.transparency===Fe.Opaque}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}getElevation(e,t,i,r){const s=this._rootTiles;if(!s?.length)return null;if(0===s[0].layerInfo[te.ELEVATION].length)return null;let a=this._elevationProjectorCache.get(r);if(void 0===a&&(a=P(r,this._spatialReference)??null,this._elevationProjectorCache.set(r,a)),null==a)return n.getLogger(this).error("TerrainSurface.getElevation(): could not project given point to tiling scheme coordinate system"),null;const l=E(rt,e,t,i);a(l,0,l,0);return ot(s,l[0],l[1])}getElevations(e,t,i){const r=this._rootTiles,s=r?r[0].layerInfo[te.ELEVATION].length:0;if(r?.length&&0!==s)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)}getScale(e){if(!this.tilingScheme)return null;if(!M(e,rt,this.spatialReference))return n.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(rt)){let e=i;for(;e.children[0]&&!e.rendered;){const t=e.children[0].extent;let i=0;rt[0]>t[2]&&(i+=1),rt[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=P(e,this._tilingSchemeSpatialReference)??null;return this._projectorCache.set(e,i),i}getSphereElevationBounds(e,t){const i=this._ensureProjector(t);if(null==i)return n.getLogger(this).error("TerrainSurface.getSphereElevationBounds(): could not project given point to tiling scheme coordinate system"),null;O(e,st);const r=G(st);i(r,0,r,0);const s=new $,a=this._rootTiles;if(null!=a){const e=[];for(const i of a)e.push(i);let t=0;for(;t<e.length;){const i=e[t];if(++t,!j(i.extent,st))continue;const r=i.children;if(null==r[0]||i.rendered)s.expandElevationRangeValues(i.elevationBoundsMin,i.elevationBoundsMax);else for(const t of r)e.push(t)}}return s}getRootElevationBounds(){return new $(this.rootTileElevationBounds.min,this.rootTileElevationBounds.max)}getLowerBoundRadius(){const e=(this._ellipsoid.radius+this.visibleElevationBounds.min)*this._radiusModifier;return Math.min(e,this._ellipsoid.radius)}getSphereScale(e,t){if(!this.tilingScheme)return null;if(!M(e,G(st),this.spatialReference))return n.getLogger(this).error("TerrainSurface.getSphereScale(): could not project given point to tiling scheme coordinate system"),null;st[3]=t;let i=null;const r=e=>{if(e&&j(e.extent,st)){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){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._allSurfaceLayersTransparent()?t?Fe.Invisible:Fe.InvisibleWithDraped:e>=1&&!this.hasCompositeBlendMode&&!this._renderer.slicePlaneEnabled?Fe.Opaque:Fe.Transparent;return this._renderer.transparency=r,i!==r}_updateTilingScheme(){const e=this.tilingSchemeLogic.tilingScheme;if(!(e!==this.tilingScheme))return;me(!!e,"tiling scheme cannot be reset to undefined"),this._isGlobal=!this.view?.state?.isLocal,this.tilingScheme&&this._removeAllTiles();const t=e?.spatialReference??b.WebMercator;this._spatialReference=t,this._isWebMercator=!!t?.isWebMercator,this._isWebMercatorOnPlateCarree=this._isWebMercator&&k(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(et._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{extent:e,tilingScheme:t}=this;if(!t)return;const i=at;let s=t.rootTilesInExtent(e,i,5*he);if(null!=this._rootTiles){if(s.length>he)return void n.getLogger(this).warn(de);const e=this._rootTiles.map((e=>e.lij)),t=r(e,s,Ae);if(this._updatingRootTiles=!0,t.removed.length>0||t.added.length>0){const e=this._rootTiles.filter((e=>!(t.removed.findIndex((t=>Ae(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&&(n.getLogger(this).warn(pe),s=t.rootTilesInExtent(e,i,he)),this._setRootTiles(s.map((e=>this._newRootTile(e))));U(i,this._rootTilesExtent)||(this._rootTilesExtent=x(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 e.shouldSplit(this._splitLimits,this._eyePosRenderSR,this.snapLevel)===Be.SPLIT}_newRootTile(e){const t=this._acquireTile(0,e[1],e[2],null);return this._shouldSplit(t)&&t.setPendingUpdate(Be.SPLIT),this._loadTile(t),this._markTileToUpdate(t),this._updateRootTileElevationBounds(),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)}_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.extent)&&e.resetPendingUpdate(Be.GEOMETRY)&&this._updateTileGeometryState(e)}_updateTilesVisibility(e){if(null==e)return;const t=Ge(e),i=this.visibleElevationBounds;let r=t?i.min:1/0,s=t?i.max:-1/0;const a=this.extent,n=this.view.state.contentCamera.viewProjectionMatrix;this.setTileTreeDirty();const l=this._iteratorPool.acquire();for(l.reset(e);!l.done;){const e=l.next();e.updateClippingStatus(a)&&e.resetPendingUpdate(Be.GEOMETRY)&&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.min!==r||i.max!==s)&&(this.visibleElevationBounds=new Y(r,s))}_updateRootTileElevationBounds(){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.rootTileElevationBounds;r.min===e&&r.max===t||(this.rootTileElevationBounds=new Y(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=V(this._splitLimits.frustum??B(),t.frustum):this._splitLimits.frustum=null,V(this._frustum,e.frustum),S(this._eyePosRenderSR,t.eye),D(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[te.MAP].some(fe)&&e.setPendingUpdate(Be.TEXTURE_FADING),this._pendingTilesToUpdate.add(e)}))}_updateTileTexture(e,t){const i=e.resetPendingUpdate(Be.TEXTURE_FADING)?Be.TEXTURE_FADING:!!e.resetPendingUpdate(Be.TEXTURE_NOFADING)&&Be.TEXTURE_NOFADING;i&&(this._renderer.updateTileTexture(e,i),this._usedMemory=null,t.madeProgress())}_emitElevationUpdateEventForTiles(){if(!this._shouldEmitChangeEvent)return;const e=nt.extent;A(e),this._pendingTilesForElevationUpdateEvent.forEach((t=>I(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"),Pe&&this._checkTileInvariant(),!e.hasProgressed)return Ze}_checkTileInvariant(){const e=new Map;this._allTiles.forAll((t=>e.set(t,new Set))),this._allTiles.forAll((t=>{if(me(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(me(t.unmergableChildCount===i,` Tile[${t.lij.toString()}] unmergeable child count mismatch: actual ${t.unmergableChildCount} vs ${i}`),t.hasPendingUpdate(Be.MERGE)){me(!t.hasPendingUpdate(Be.SPLIT),"Tile can be both split and merge at the same time");for(const e of t.children)me(e.leaf||e.hasPendingUpdate(Be.MERGE),"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}])`),me(r,`tile level delta [${t.level}] vs [${e.level}] > ${ue}`))}me(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(ye[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(!Ae(s,i.lij)){const r=e.get(i);me(!r.has(t),"Cannot already have neighbor"),r.add(t)}}me(a.rendered||a.level===t.level,"Non-same-level-neighbor of rendered must be rendered"),me(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);me(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 ht(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=null!=n&&n.hasPendingUpdate(Be.MERGE),o=l?Be.MERGE:e.shouldSplit(r,s,i),h=o===Be.SPLIT;e.leaf?dt(e,h):t.pushAll(e.children),l?(e.resetPendingUpdate(Be.SPLIT),e.leaf||e.setPendingUpdate(Be.MERGE),this._updateClippingStatus(e),e.updateVisibility(),e.updateScreenDepth(a)):h?(e.resetPendingUpdate(Be.MERGE),e.leaf&&e.setPendingUpdate(Be.SPLIT)):(e.resetPendingUpdate(Be.SPLIT)&&e.updateAgentSuspension(),o===Be.ELEVATION&&e.updateAgents(te.ELEVATION),e.leaf||(e.setPendingUpdate(Be.MERGE),e.resetPendingUpdate(Be.SPLIT)))}this.requestUpdate(),(this._shortBatches||!this._oneBatchPerFrameTask)&&this._updatePendingTileGeometries(),e.madeProgress()}_sortTiles(e){e.done||this._allTilesSorted||(Ne(this._allTiles,this.view.pointsOfInterest.focus.renderLocation),this._allTilesSorted=!0,this._treeDebugger&&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=Me[e];i(r,l.cornerPeerNeighbors[e]?.findCorner(De(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(ye[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,Pe&&xe&&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(Be.MERGE)){if(!t||s.unmergableChildCount>0)return e.done;for(s.resetPendingUpdate(Be.MERGE);null!=n.parent&&0===n.parent.unmergableChildCount&&n.parent.resetPendingUpdate(Be.MERGE);)n=n.parent;this._mergeTile(n),a=!0,e.madeProgress()}else if(s.resetPendingUpdate(Be.SPLIT)){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(ye[r],e);null!=a&&i-a.level===ue&&(t=!1,Pe&&(Te(a.leaf),Te(a.hasPendingUpdate(Be.SPLIT))))}}t?(this._splitTile(s),e.madeProgress(),a=!0):s.setPendingUpdate(Be.SPLIT)}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._sortTiles(e)}_updateElevation(e){e.done||(this._allTiles.some((t=>(t.resetPendingUpdate(Be.GEOMETRY)&&(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.overlayManager?.updateOverlayParameters(ze.UPDATE),this.overlayManager.setPlacementDirty(),this._updateRootTiles())}get _lodBias(){const e=this.view.quality;return this.view.qualitySettings.tiledSurface.lodBias-(1-e)*ce}_getLodBiasCorrectedScale(e){const t=this.tilingScheme.levels,i=l(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.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?ut(e):this._purgeSubtree(e),this._allTiles.removeUnordered(e),this._unloadTile(e),e.dispose(),this._tileCache.put(et._tileMemcacheKey,e)}_unloadTile(e){this._pendingTilesToUpdate.delete(e),this._pendingTilesForElevationUpdateEvent.delete(e),e.unload()}_splitTile(e){me(e.leaf,"Tile that is already split should not be split again!"),me(e.rendered,"Tile marked to split is not rendered"),ut(e);const t=e.createChildren();this._allTiles.pushArray(t),e.updateAgentSuspension(),me(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=>dt(e,e.hasPendingUpdate(Be.SPLIT)))),++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){me(!!r,"createTile sanity check");const s=this._acquireTile(e,t,i,r);return s.updateClippingStatus(this.extent),s.updateScreenDepth(this.view.state.contentCamera.viewProjectionMatrix),this._shouldSplit(s)&&s.setPendingUpdate(Be.SPLIT),s}get _shortBatches(){return this.view.state.mode!==Xe.IDLE}_mergeTile(e){me(!e.hasPendingUpdate(Be.SPLIT),"_mergeTile sanity check"),me(!e.leaf,"Cannot merge a leaf"),e.leaf||(this._purgeSubtree(e),me(!e.renderData,"Merging tile with existing render data?"),this._loadTile(e),this._markTileToUpdate(e),this._emitTileScaleChange(e),this._shortBatches&&this._updatePendingTileGeometries(),dt(e,!1),this._allTilesDirty=!0,++this._performanceInfo.numMerged)}_loadTile(e){e.load(),this.requestUpdate(),this._allTilesDirty=!0,this.overlayManager?.hasOverlays&&this.overlayManager.updateTileOverlayParameters(e)}_handleLayerViewChanges(e=Je){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),Ee(e)||Se(e))if(this._basemapLayerViewHandles.has(e.uid)&&!Se(e)){const i=this._layerClassFromLayerView(e),s=this._getLayerIdxByUID(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()}_allSurfaceLayersTransparent(){let e=0===this.view.map?.ground?.opacity;for(const t of this.view.allLayerViews.items)if(we(t)&&!F(t.layer)&&0!==t.fullOpacity)return e=!1,e;return e}_hasCompositeBlendMode(){for(const e of this.view.allLayerViews.items)if((Ce(e)||Se(e))&&$e(He[e.layer.blendMode]))return!0;return!1}_layerClassFromLayerView(e){return Le(e)?te.ELEVATION:te.MAP}_registerTiledLayerView(e){const t=[];if((Ce(e)||Se(e))&&t.push(_((()=>e.layer.blendMode),(()=>{this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._updateTileTextures(ee.UNFADED)}))),!Se(e)){const i=this._layerClassFromLayerView(e);t.push(_((()=>e.suspended),(()=>this._updateTiledLayers()))),t.push(_((()=>e.fullOpacity),(()=>this._updateTileTextures(ee.UNFADED)))),t.push(_((()=>"effectiveScaleRange"in e.layer?e.layer.effectiveScaleRange:null),(()=>this._restartAllAgents(i)))),t.push(e.on("data-changed",(()=>{const t=this._getLayerIdxByUID(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||!Ee(e)||!e.fullExtent)return;const r=this._layerClassFromLayerView(e);if(r===te.MAP){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),e===te.ELEVATION&&i.computeElevationBounds()}this._updateRootTileElevationBounds()}layerViewByIndex(e,t){return this._layerViews[t][e]}numLayers(e){return this._layerViews[e].length}_updateTileTextures(e){this._allTiles.forAll((t=>{t.updateAgents(te.MAP),e===ee.IMMEDIATE?this.renderer.updateTileTexture(t,Be.TEXTURE_NOFADING):t.updateRenderData(te.MAP,e)})),this._evaluateTransparency()}_invalidateLayerData(e,t){this._allTiles.forAll((i=>i.removeLayerAgent(e,t))),this._allTiles.forAll((i=>i.invalidateLayerData(e,t)))}setTileTreeDirty(){this._allTilesDirty=!0}requestRender(e=ze.UPDATE){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||fe(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,u(r),c(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();const s=t===te.ELEVATION;return r.requester??=s?this._elevationDataRequester:this._mapDataRequester,s?Le(i)?this._requestElevationTileData(e,i,r):Promise.reject():we(i)?this._requestMapTileData(e,i,r):Promise.reject()}_requestElevationTileData(e,t,i){++this._asyncWorkItems;const r=r=>{!g(i)&&r&&(this.setMemoryDirty(),this.requestUpdate(),this._elevationDataArrived(e,t,r))},s=i=>{c(i)||(n.getLogger(this).error(`Tile ${e.lij.toString()} layer ${te.ELEVATION}/${t.uid} error ${i}`),this._dataMissing(e,te.ELEVATION,t),this.requestUpdate())};return t.fetchTile(e.lij,i).then((e=>this._frameTask.schedule((()=>r(e)))),s).finally((()=>--this._asyncWorkItems))}_elevationDataArrived(e,t,i){const r=this._layerIndexByUid[te.ELEVATION].get(t.uid);if(null==r)return void n.getLogger(this).warn("TerrainSurface: received data from unknown layer %d %s",te.ELEVATION,e.lij.toString());const s=new K(e.lij,e.extent,i);e.dataArrived(r,te.ELEVATION,s);const a=[e],l=e.level,o=this._iteratorPool.acquire();for(o.reset(a);!o.done;){const e=o.next();e.findElevationBoundsForLayer(r,l),e.computeElevationBounds()}0===l&&this._updateRootTileElevationBounds(),o.remove(),this._updateTilesVisibility(a)}_requestMapTileData(e,t,i){++this._asyncWorkItems;const r=(r,s)=>{be(s),g(i)||(console.error(`Tile ${e.lij.toString()} layer ${te.MAP}/${t.uid} error ${r}`),this._dataMissing(e,te.MAP,t),this.requestUpdate())},s=e=>t=>r(t,e),a=r=>this._frameTask.schedule((()=>{this.requestUpdate(),g(i)?be(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._getLayerIdxByUID(te.MAP,t.uid);if(null==r)return be(i),void n.getLogger(this).warn("TerrainSurface: received data from unknown layer");e.dataArrived(r,te.MAP,i)}_getLayerIdxByUID(e,t){return this._layerIndexByUid[e].get(t)}_dataMissing(e,t,i){const r=this._getLayerIdxByUID(t,i.uid);null!=r?e.dataMissing(r,t):n.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._getLayerIdxByUID(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 visualizeNormals(){return this._renderer.visualizeNormals}set visualizeNormals(e){this._renderer.visualizeNormals=e}get renderingDisabled(){return this._renderer.renderingDisabled}set renderingDisabled(e){this._renderer.renderingDisabled=e}get test(){}checkAllTilesWaterproofness(){if(!xe)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){Re(e)}};e([T()],tt.prototype,"_renderer",void 0),e([T({constructOnly:!0})],tt.prototype,"_scaleRangeQueries",void 0),e([T({constructOnly:!0})],tt.prototype,"view",void 0),e([T({constructOnly:!0})],tt.prototype,"overlayManager",void 0),e([T()],tt.prototype,"_hasPendingUpdates",void 0),e([T()],tt.prototype,"_asyncWorkItems",void 0),e([T()],tt.prototype,"_allTilesDirty",void 0),e([T()],tt.prototype,"_allTilesSorted",void 0),e([T()],tt.prototype,"_viewChanged",void 0),e([T({type:Number})],tt.prototype,"heading",void 0),e([T()],tt.prototype,"_splitLimits",void 0),e([T({readOnly:!0})],tt.prototype,"_watchUpdatingTracking",void 0),e([T()],tt.prototype,"_frameTask",void 0),e([T({readOnly:!0})],tt.prototype,"snapLevel",null),e([T({readOnly:!0})],tt.prototype,"lodSnappingEnabled",null),e([T()],tt.prototype,"_userClippingExtent",null),e([T()],tt.prototype,"_rootTilesExtent",void 0),e([T({readOnly:!0})],tt.prototype,"extent",null),e([T({readOnly:!0})],tt.prototype,"groundExtent",null),e([T({readOnly:!0})],tt.prototype,"_tilingSchemeExtent",null),e([T({readOnly:!0})],tt.prototype,"updating",null),e([T({readOnly:!0})],tt.prototype,"running",null),e([T(X)],tt.prototype,"updatingProgress",void 0),e([T({readOnly:!0})],tt.prototype,"updatingProgressValue",null),e([T()],tt.prototype,"_maxNumUpdating",void 0),e([T()],tt.prototype,"baseOpacity",null),e([T()],tt.prototype,"hasCompositeBlendMode",void 0),e([T({readOnly:!0})],tt.prototype,"viewingMode",null),e([T()],tt.prototype,"maxTextureScale",void 0),e([T({readOnly:!0})],tt.prototype,"ready",null),e([T({value:ae.FRONT_TO_BACK})],tt.prototype,"renderOrder",null),e([T({readOnly:!0})],tt.prototype,"rootTiles",null),e([T()],tt.prototype,"_rootTiles",void 0),e([T({readOnly:!0})],tt.prototype,"spatialReference",null),e([T({type:t})],tt.prototype,"backgroundColor",null),e([T({value:!1})],tt.prototype,"slicePlaneEnabled",null),e([T({readOnly:!0})],tt.prototype,"tilingScheme",void 0),e([T({readOnly:!0})],tt.prototype,"tilingSchemeLocked",null),e([T({readOnly:!0})],tt.prototype,"tilingSchemeLogic",void 0),e([T()],tt.prototype,"wireframe",null),e([T({value:!1})],tt.prototype,"suspended",null),e([T()],tt.prototype,"fadeDuration",null),e([T()],tt.prototype,"visibleElevationBounds",void 0),e([T()],tt.prototype,"rootTileElevationBounds",void 0),e([T()],tt.prototype,"_layerViewsDirty",void 0),e([T()],tt.prototype,"renderPatchBorders",null),e([T()],tt.prototype,"visualizeNormals",null),e([T()],tt.prototype,"renderingDisabled",null),tt=et=e([v("esri.views.3d.terrain.TerrainSurface")],tt);const it=tt,rt=w(),st=N(),at=x();new p;const nt=new H("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 J(t,i,s)}return null}class ht{constructor(e){this.capacity=e,this._head=0,this._tail=0,this._data=new Array(e)}push(e){const t=this._tail;if(!(t<this.capacity))throw new Error("Queue full");this._data[t]=e,this._tail=t+1}pushAll(e){const t=e.length;if(0===t)return;const i=this._tail;if(!(i+t<=this.capacity))throw new Error("Queue full");for(let r=0;r<t;++r)this._data[i+r]=e[r];this._tail=i+t}pop(){const e=this._head;if(e<this._tail){const t=this._data[e];return this._head=e+1,t}}get empty(){return this._head>=this._tail}get full(){return this._tail>=this._data.length}}function dt(e,t){!e.leaf||e.level<ue||gt(e,(e=>{t&&pt(e);const i=ct(e);if(e.maxLevelDeltaNeighborCount++,i){let t=e.parent;for(;t;){const e=ct(t);if(t.unmergableChildCount++,!e)break;t=t.parent}}}))}function pt(e){if(e.hasPendingUpdate(Be.SPLIT))return;let t=e.parent;for(;t?.resetPendingUpdate(Be.MERGE);)t=t.parent;e.resetPendingUpdate(Be.MERGE),e.leaf&&e.setPendingUpdate(Be.SPLIT),e.level<ue||gt(e,(e=>{pt(e)}))}function ut(e){e.level<ue||gt(e,(e=>{if(e.maxLevelDeltaNeighborCount--,0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount){let t=e.parent;for(;t&&(t.unmergableChildCount--,ct(t));)t=t.parent}}))}function ct(e){return 0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount}function gt(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(ye[n],a);if(!l||l.level!==i)continue;const o=l.lij;o[1]===r&&o[2]===s||t(l)}}export{it as default};
@@ -2,7 +2,7 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import{fromValues as o}from"../../../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{earth as t}from"../../../../../../geometry/support/Ellipsoid.js";import{CloudsTextureChannels as e}from"../../../../environment/Clouds.js";import{FadeState as r}from"../../../../environment/CloudsParameters.js";import{cloudsHeight as a}from"../../../../environment/weather.js";import{addMainLightDirection as i,addMainLightIntensity as c}from"../shading/MainLighting.glsl.js";import{LookupCubemapFromTextureArray as d}from"./LookupCubemapFromTextureArray.glsl.js";import{BooleanBindUniform as n}from"../../shaderModules/BooleanBindUniform.js";import{Float3BindUniform as l}from"../../shaderModules/Float3BindUniform.js";import{FloatBindUniform as s}from"../../shaderModules/FloatBindUniform.js";import{glsl as u}from"../../shaderModules/glsl.js";import{Matrix4BindUniform as m}from"../../shaderModules/Matrix4BindUniform.js";import{Texture2DArrayBindUniform as h}from"../../shaderModules/Texture2DArrayBindUniform.js";function C(t){const a=t.fragment;a.constants.add("radiusCloudsSquared","float",p).code.add(u`vec3 intersectWithCloudLayer(vec3 dir, vec3 cameraPosition, vec3 spherePos) {
5
+ import{fromValues as o}from"../../../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{earth as t}from"../../../../../../geometry/support/Ellipsoid.js";import{CloudsTextureChannels as e}from"../../../../environment/Clouds.js";import{FadeState as r}from"../../../../environment/CloudsParameters.js";import{cloudsHeight as a}from"../../../../environment/weather.js";import{addMainLightDirection as i,addMainLightIntensity as d}from"../shading/MainLighting.glsl.js";import{LookupCloudsFromTextureArray as c}from"./LookupCloudsFromTextureArray.glsl.js";import{BooleanBindUniform as n}from"../../shaderModules/BooleanBindUniform.js";import{Float3BindUniform as l}from"../../shaderModules/Float3BindUniform.js";import{FloatBindUniform as s}from"../../shaderModules/FloatBindUniform.js";import{glsl as u}from"../../shaderModules/glsl.js";import{Matrix4BindUniform as m}from"../../shaderModules/Matrix4BindUniform.js";import{Texture2DArrayBindUniform as h}from"../../shaderModules/Texture2DArrayBindUniform.js";function C(t){const a=t.fragment;a.constants.add("radiusCloudsSquared","float",v).code.add(u`vec3 intersectWithCloudLayer(vec3 dir, vec3 cameraPosition, vec3 spherePos) {
6
6
  float B = 2.0 * dot(cameraPosition, dir);
7
7
  float C = dot(cameraPosition, cameraPosition) - radiusCloudsSquared;
8
8
  float det = B * B - 4.0 * C;
@@ -13,11 +13,11 @@ dir.z = dir.z * (1.0 - radiusCurvatureCorrection) + radiusCurvatureCorrection;
13
13
  return dir;
14
14
  }`),a.code.add(u`vec3 rotateDirectionToAnchorPoint(mat4 rotMat, vec3 inVec) {
15
15
  return (rotMat * vec4(inVec, 0.0)).xyz;
16
- }`),i(a),c(a);const C=o(.28,.175,.035);a.constants.add("RIM_COLOR","vec3",C);const v=.3,f=140,g=.2,w=10,P=.3;a.code.add(u`
16
+ }`),i(a),d(a);const C=o(.28,.175,.035);a.constants.add("RIM_COLOR","vec3",C);const f=.3,p=140,g=.2,w=10,P=.3;a.code.add(u`
17
17
  vec3 calculateCloudColor(vec3 cameraPosition, vec3 worldSpaceRay, vec4 clouds) {
18
18
  float upDotLight = dot(cameraPosition, mainLightDirection);
19
19
  float dirDotLight = max(dot(worldSpaceRay, mainLightDirection), 0.0);
20
- float sunsetTransition = clamp(pow(max(upDotLight, 0.0), ${u.float(v)}), 0.0, 1.0);
20
+ float sunsetTransition = clamp(pow(max(upDotLight, 0.0), ${u.float(f)}), 0.0, 1.0);
21
21
 
22
22
  // Base color of the clouds that depends on lighting of the sun and sky
23
23
  vec3 ambientLight = calculateAmbientIrradiance(cameraPosition, 0.0);
@@ -27,15 +27,15 @@ return (rotMat * vec4(inVec, 0.0)).xyz;
27
27
  // Rim light around the edge of the clouds simulating scattering of the direct lun light
28
28
  float scatteringMod = max(clouds.a < 0.5 ? clouds.a / 0.5 : - clouds.a / 0.5 + 2.0, 0.0);
29
29
  float rimLightIntensity = 0.5 + 0.5 * pow(max(upDotLight, 0.0), 0.35);
30
- vec3 directSunScattering = RIM_COLOR * rimLightIntensity * (pow(dirDotLight, ${u.float(f)})) * scatteringMod;
30
+ vec3 directSunScattering = RIM_COLOR * rimLightIntensity * (pow(dirDotLight, ${u.float(p)})) * scatteringMod;
31
31
 
32
32
  // Brighten the clouds around the sun at the sunsets
33
33
  float additionalLight = ${u.float(g)} * pow(dirDotLight, ${u.float(w)}) * (1. - pow(sunsetTransition, ${u.float(P)})) ;
34
34
 
35
35
  return vec3(baseCloudColor * (1.0 + additionalLight) + directSunScattering);
36
36
  }
37
- `),t.include(d),a.uniforms.add(new n("readChannelsRG",(o=>o.clouds.readChannels===e.RG)),new h("cubeMap",(o=>o.clouds.data?.cubeMap?.colorTexture??null))).code.add(u`vec4 sampleCloud(vec3 rayDir, bool readOtherChannel) {
38
- vec4 s = lookupCubemapFromTextureArray(cubeMap, rayDir);
37
+ `),t.include(c),a.uniforms.add(new n("readChannelsRG",(o=>o.clouds.readChannels===e.RG)),new h("cubeMap",(o=>o.clouds.data?.cubeMap?.colorTexture??null))).code.add(u`vec4 sampleCloud(vec3 rayDir, bool readOtherChannel) {
38
+ vec4 s = lookupCloudsFromTextureArray(cubeMap, rayDir);
39
39
  bool readRG = readChannelsRG ^^ readOtherChannel;
40
40
  s = readRG ? vec4(vec3(s.r), s.g) : vec4(vec3(s.b), s.a);
41
41
  return length(s) == 0.0 ? vec4(s.rgb, 1.0) : s;
@@ -58,4 +58,4 @@ float totalTransmittance = length(cloudColor.rgb) == 0.0 ?
58
58
  1.0 :
59
59
  clamp(cloudColor.a * cloudsOpacity + (1.0 - cloudsOpacity), 0.0 , 1.0);
60
60
  return vec4(cloudColor.rgb, totalTransmittance);
61
- }`)}const p=(t.radius+a)**2;export{C as CloudsParallaxShading};
61
+ }`)}const v=(t.radius+a)**2;export{C as CloudsParallaxShading};
@@ -2,10 +2,8 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import{glsl as e}from"../../shaderModules/glsl.js";function t({code:t}){t.add(e`vec3 dpAdd(vec3 hiA, vec3 loA, vec3 hiB, vec3 loB) {
6
- vec3 t1 = hiA + hiB;
7
- vec3 e = t1 - hiA;
8
- vec3 t2 = ((hiB - e) + (hiA - (t1 - e))) + loA + loB;
9
- vec3 result = t1 + t2;
10
- return result;
11
- }`)}export{t as DoublePrecision};
5
+ import{FloatBindUniform as o}from"../../shaderModules/FloatBindUniform.js";import{glsl as d}from"../../shaderModules/glsl.js";function e({code:e,uniforms:i},l){i.add(new o("dpDummy",(()=>1))),e.add(d`vec3 dpAdd(vec3 hiA, vec3 loA, vec3 hiB, vec3 loB) {
6
+ vec3 hiD = hiA + hiB;
7
+ vec3 loD = loA + loB;
8
+ return dpDummy * hiD + loD;
9
+ }`)}export{e as DoublePrecision};
@@ -0,0 +1,51 @@
1
+ /*
2
+ All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
+ See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
+ */
5
+ import{FloatBindUniform as r}from"../../shaderModules/FloatBindUniform.js";import{glsl as a}from"../../shaderModules/glsl.js";function e(e){e.fragment.uniforms.add(new r("cloudAbsorption",(r=>r.clouds.absorption)),new r("cloudCoverage",(r=>r.clouds.coverage))).code.add(a`vec4 lookupCloudsFromTextureArray(sampler2DArray cubeMap, vec3 rayDir) {
6
+ int faceIndex;
7
+ vec2 uv;
8
+ if(rayDir.z <= 0.0) {
9
+ float hazeFactor = smoothstep(-0.01, mix(0.0, 0.075, cloudCoverage), abs(dot(rayDir, vec3(0, 0, 1))));
10
+ float shading = clamp(1.0 - cloudAbsorption, 0.6, 1.0) * (1.0 - hazeFactor);
11
+ float totalTransmittance = hazeFactor;
12
+ return vec4(shading, totalTransmittance, shading, totalTransmittance);
13
+ }
14
+ if (abs(rayDir.x) >= abs(rayDir.y) && abs(rayDir.x) >= abs(rayDir.z)) {
15
+ if(rayDir.x > 0.0) {
16
+ faceIndex = 0;
17
+ uv = rayDir.yz / rayDir.x;
18
+ uv = vec2(-uv.x, uv.y);
19
+ } else {
20
+ faceIndex = 1;
21
+ uv = rayDir.yz / rayDir.x;
22
+ uv = vec2(-uv.x, -uv.y);
23
+ }
24
+ } else if (abs(rayDir.y) >= abs(rayDir.x) && abs(rayDir.y) >= abs(rayDir.z)) {
25
+ if(rayDir.y > 0.0) {
26
+ faceIndex = 2;
27
+ uv = rayDir.xz / rayDir.y;
28
+ } else {
29
+ faceIndex = 3;
30
+ uv = rayDir.xz / rayDir.y;
31
+ uv = vec2(uv.x, -uv.y);
32
+ }
33
+ } else {
34
+ if(rayDir.y < 0.0) {
35
+ faceIndex = 4;
36
+ uv = rayDir.xy / rayDir.z;
37
+ uv = vec2(uv.x, -uv.y);
38
+ } else {
39
+ faceIndex = 5;
40
+ uv = rayDir.xy / rayDir.z;
41
+ uv = vec2(uv.x, -uv.y);
42
+ }
43
+ }
44
+ uv = 0.5 * (uv + 1.0);
45
+ if(faceIndex != 5) {
46
+ uv.y = uv.y - 0.5;
47
+ }
48
+ uv.y = uv.y * 2.0;
49
+ vec4 s = texture(cubeMap, vec3(uv, float(faceIndex)));
50
+ return s;
51
+ }`)}export{e as LookupCloudsFromTextureArray};
@@ -0,0 +1,5 @@
1
+ /*
2
+ All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
+ See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
+ */
5
+ class t{constructor(t,s,e,i){this.material=t,this.output=s,this.techniques=e,this.textures=i}}export{t as GLMaterialParameters};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../../../core/Logger.js";import{disposeMaybe as t}from"../../../../core/maybe.js";import{NestedMap as r}from"../../../../core/NestedMap.js";import{assert as i}from"./Util.js";class s{constructor(e,t,i,s){this._textures=e,this._techniques=t,this.materialChanged=i,this.requestRender=s,this._id2glMaterialRef=new r}dispose(){this._textures.destroy()}acquire(e,t,r){this._ownMaterial(e);const i=e.produces.get(t);if(!i?.(r))return null;let s=this._id2glMaterialRef.get(r,e.id);if(null==s){const t=e.createGLMaterial({material:e,techniques:this._techniques,textures:this._textures,output:r});s=new a(t),this._id2glMaterialRef.set(r,e.id,s)}return s.ref(),s.glMaterial}release(e,r){const i=this._id2glMaterialRef.get(r,e.id);null!=i&&(i.unref(),i.referenced||(t(i.glMaterial),this._id2glMaterialRef.delete(r,e.id)))}_ownMaterial(t){t.repository&&t.repository!==this&&e.getLogger("esri.views.3d.webgl-engine.lib.GLMaterialRepository").error("Material is already owned by a different material repository"),t.repository=this}}class a{constructor(e){this.glMaterial=e,this._refCnt=0}ref(){++this._refCnt}unref(){--this._refCnt,i(this._refCnt>=0)}get referenced(){return this._refCnt>0}}export{s as GLMaterialRepository};
5
+ import e from"../../../../core/Logger.js";import{disposeMaybe as t}from"../../../../core/maybe.js";import{NestedMap as r}from"../../../../core/NestedMap.js";import{GLMaterialParameters as i}from"./GLMaterialParameters.js";import{assert as s}from"./Util.js";class a{constructor(e,t,i,s){this._textures=e,this._techniques=t,this.materialChanged=i,this.requestRender=s,this._id2glMaterialRef=new r}dispose(){this._textures.destroy()}acquire(e,t,r){this._ownMaterial(e);const s=e.produces.get(t);if(!s?.(r))return null;let a=this._id2glMaterialRef.get(r,e.id);if(null==a){const t=e.createGLMaterial(new i(e,r,this._techniques,this._textures));a=new o(t),this._id2glMaterialRef.set(r,e.id,a)}return a.ref(),a.glMaterial}release(e,r){const i=this._id2glMaterialRef.get(r,e.id);null!=i&&(i.unref(),i.referenced||(t(i.glMaterial),this._id2glMaterialRef.delete(r,e.id)))}_ownMaterial(t){t.repository&&t.repository!==this&&e.getLogger("esri.views.3d.webgl-engine.lib.GLMaterialRepository").error("Material is already owned by a different material repository"),t.repository=this}}class o{constructor(e){this.glMaterial=e,this._refCnt=0}ref(){++this._refCnt}unref(){--this._refCnt,s(this._refCnt>=0)}get referenced(){return this._refCnt>0}}export{a as GLMaterialRepository};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import has from"../../../../core/has.js";import{NestedMap as e}from"../../../../core/NestedMap.js";import{ScreenSpaceGeometry as r}from"../effects/ScreenSpaceGeometry.js";import{VaoCache as s}from"../materials/renderers/VaoCache.js";import{AppleAmdDriverHelper as i}from"../../../webgl/AppleAmdDriverHelper.js";import{RenderingContext as t}from"../../../webgl/RenderingContext.js";class a extends t{constructor(s,i){super(s,i),this._vaoCaches=new e,this._appleAmdDriverHelper=null,this._refCount=1,this._newCache=i.newCache,this.screen=new r(this)}configure(e){super.configure(e),this._newCache=e.newCache}destroy(){this._vaoCaches?.forAll((e=>e.dispose())),this._vaoCaches?.clear(),--this._refCount>0||this.dispose()}ref(){++this._refCount}dispose(){super.dispose(),this._appleAmdDriverHelper?.dispose(),this.screen.destroy(),this._vaoCaches.forAll((e=>e.dispose())),this._vaoCaches.clear()}get newCache(){return this._newCache}getVaoCache(e,r){const i=Array.from(e).join("."),t=JSON.stringify(r),a=this._vaoCaches.get(i,t);if(a)return a;const o=new s(this,e,r);return this._vaoCaches.set(i,t,o),o}bindTechnique(e,r,s,i){return this.useProgram(e.program),this.setPipelineState(e.getPipeline()),e.program.bind(r),s&&(e.program.bindPass(s,r),i&&e.program.bindDraw(r,s,i)),e.program}runAppleAmdDriverHelper(){this.driverTest.drawArraysRequiresIndicesTypeReset.result&&(this._appleAmdDriverHelper??=new i(this),this._appleAmdDriverHelper.run())}get isAssumedMetalDriver(){if(null==this._isAssumedMetalDriver&&(this._isAssumedMetalDriver=!!has("ios")||!!has("safari"),!this._isAssumedMetalDriver&&has("mac")&&has("chrome"))){const e=this.capabilities.rendererInfo?.getUnmaskedRenderer().toLowerCase(),r=e?.includes("apple")&&e?.includes("angle")&&e?.includes("metal");this._isAssumedMetalDriver=r??!0}return this._isAssumedMetalDriver}get test(){}}export{a as RenderingContext};
5
+ import has from"../../../../core/has.js";import{NestedMap as e}from"../../../../core/NestedMap.js";import{ScreenSpaceGeometry as s}from"../effects/ScreenSpaceGeometry.js";import{createEmptyTexture as r}from"./glUtil3D.js";import{VaoCache as i}from"../materials/renderers/VaoCache.js";import{AppleAmdDriverHelper as t}from"../../../webgl/AppleAmdDriverHelper.js";import{RenderingContext as a}from"../../../webgl/RenderingContext.js";class o extends a{constructor(i,t){super(i,t),this.emptyTexture=r(this),this._vaoCaches=new e,this._appleAmdDriverHelper=null,this._refCount=1,this._newCache=t.newCache,this.screen=new s(this)}configure(e){super.configure(e),this._newCache=e.newCache}destroy(){this._vaoCaches?.forAll((e=>e.dispose())),this._vaoCaches?.clear(),--this._refCount>0||this.dispose()}ref(){++this._refCount}dispose(){super.dispose(),this._appleAmdDriverHelper?.dispose(),this.emptyTexture.dispose(),this.screen.destroy(),this._vaoCaches.forAll((e=>e.dispose())),this._vaoCaches.clear()}get newCache(){return this._newCache}getVaoCache(e,s){const r=Array.from(e).join("."),t=JSON.stringify(s),a=this._vaoCaches.get(r,t);if(a)return a;const o=new i(this,e,s);return this._vaoCaches.set(r,t,o),o}bindTechnique(e,s,r,i){return this.useProgram(e.program),this.setPipelineState(e.getPipeline()),e.program.bind(s),r&&(e.program.bindPass(r,s),i&&e.program.bindDraw(s,r,i)),e.program}runAppleAmdDriverHelper(){this.driverTest.drawArraysRequiresIndicesTypeReset.result&&(this._appleAmdDriverHelper??=new t(this),this._appleAmdDriverHelper.run())}get isAssumedMetalDriver(){if(null==this._isAssumedMetalDriver&&(this._isAssumedMetalDriver=!!has("ios")||!!has("safari"),!this._isAssumedMetalDriver&&has("mac")&&has("chrome"))){const e=this.capabilities.rendererInfo?.getUnmaskedRenderer().toLowerCase(),s=e?.includes("apple")&&e?.includes("angle")&&e?.includes("metal");this._isAssumedMetalDriver=s??!0}return this._isAssumedMetalDriver}get test(){}}export{o as RenderingContext};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../../chunks/tslib.es6.js";import t from"../../../../core/Accessor.js";import s from"../../../../core/Evented.js";import"../../../../core/has.js";import{disposeMaybe as i,removeMaybe as r}from"../../../../core/maybe.js";import{generateUID as h}from"../../../../core/uid.js";import{property as n}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/Logger.js";import"../../../../core/RandomLCG.js";import{subclass as a}from"../../../../core/accessorSupport/decorators/subclass.js";import{a as o,s as l}from"../../../../chunks/vec42.js";import{ZEROS as _,create as c}from"../../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{ContentObjectType as d}from"./ContentObjectType.js";import{textTextureAtlas as u}from"./testUtils.js";import{applyTextureResizeModuloCeil as m}from"./textureUtils.js";import{TaskPriority as p}from"../../../support/Scheduler.js";import{Yield as g}from"../../../support/Yield.js";import{TextureWrapMode as f,TextureSamplingMode as x}from"../../../webgl/enums.js";import{Texture as v}from"../../../webgl/Texture.js";import{TextureDescriptor as w}from"../../../webgl/TextureDescriptor.js";const T=4096;let k=class extends t{constructor(e){super(e),this.type=d.Texture,this.id=h(),this.events=new s,this._glTexture=null,this._atlas=new A(256,256),this._needsRepack=!1,this._canRepack=!0,this._elementsToRender=new Map,this._elements=new Map,this._uvCallbacks=new Map,this.updating=!1}initialize(){this._canvas=document.createElement("canvas"),this._canvas.setAttribute("id","textAtlasCanvas"),this._canvas.setAttribute("style","display:none"),this._ctx=this._canvas.getContext("2d"),this._stage=this.view._stage,this._stage.add(this),this._updateCanvasElementSize(this._atlas),this._reset()}unload(){this._glTexture=i(this._glTexture),this._frameWorker=r(this._frameWorker),this.updating=!1,this.events.emit("unloaded")}get glTexture(){return this._glTexture}static get maxSize(){return j=u.stableRendering?R:0,[T-R-j,T-R-j-y]}load(e){if(this._glTexture)return this._glTexture;const t=new w;return t.wrapMode=f.CLAMP_TO_EDGE,t.samplingMode=x.LINEAR_MIPMAP_LINEAR,t.hasMipmap=!0,t.preMultiplyAlpha=!0,t.maxAnisotropy=e.parameters.maxMaxAnisotropy,this._glTexture=new v(e,t,this._canvas),this._frameWorker=this.view.resourceController.scheduler.registerTask(p.TEXT_TEXTURE_ATLAS,this),this.setDirty(),this._glTexture}dispose(){this._elements.clear(),this._elementsToRender.clear(),this._frameWorker=r(this._frameWorker),this._glTexture&&(this._stage.remove(this),this._glTexture=i(this._glTexture)),this._canvas.width=0,this._canvas.height=0,this._canvas=null,this._ctx=null}_updateCanvasElementSize(e){this._canvas.width=e.width,this._canvas.height=e.height}_resizeAtlas(e,t){const{width:s,height:i}=this._atlas;s===e&&i===t||(this._atlas.width=e,this._atlas.height=t,this._glTexture?.resize(e,t),this._glTexture?.updateData(0,0,0,s,i,this._canvas),this._updateCanvasElementSize(this._atlas),this._elements.forEach((e=>this._uvCallbacks.get(e.textRenderer.key)?.forEach((t=>t(e.uv))))),this._reset())}_reset(){this._elementsToRender.clear(),this._atlas.reset(),this._needsRepack=!0,this.setDirty()}_addAtlasElement(e,t,s,i){const r=this._atlas;if(r.width<s||r.height<i)return!1;let h=r.cursors.get(i);if(!h){if(r.height<r.nextY+i)return!1;h=[new C(r.nextY)],r.cursors.set(i,h),r.nextY+=i}let n=h.find((e=>r.width>=e.x+s));if(null==n){if(r.height<r.nextY+i)return!1;n=new C(r.nextY),r.nextY+=i,h.push(n)}return e.setNewPosition(n),this._elements.set(t,e),this._elementsToRender.set(t,e),n.x+=s,!0}_ensureCallbacks(e){const t=this._uvCallbacks.get(e);if(t)return t;const s=new Set;return this._uvCallbacks.set(e,s),s}_addCallback(e,t){this._ensureCallbacks(e).add(t)}_removeCallback(e,t){const s=this._uvCallbacks.get(e);return!(!s?.delete(t)||0!==s.size)&&(this._uvCallbacks.delete(e),!0)}_processAddition(e){const t=e.textRenderer.key;if(this._needsRepack)return void this._elements.set(t,e);const s=this._atlas,i=e.textRenderer.renderedWidth,r=e.textRenderer.renderedHeight,h=i+R,n=r+R+y;if(!this._addAtlasElement(e,t,h,n)){if(this._canRepack)this._reset();else if(s.width<h){const e=m(Math.max(h,1.5*s.width),T);this._resizeAtlas(e,s.height)}else{const e=s.nextY+n,t=m(Math.max(e,1.5*s.height),T);if(t>s.height)this._resizeAtlas(s.width,t);else if(s.width<T){const e=m(1.5*s.width,T);this._resizeAtlas(e,s.height)}}this._elements.set(t,e)}}_renderElement(e){const t=e.commitNewPosition(),s=e.textRenderer;this._ctx.clearRect(t[0]-R,t[1]-R,s.renderedWidth+2*R,s.renderedHeight+2*R),s.render(this._ctx,t[0],t[1]),this._uvCallbacks.get(s.key)?.forEach((t=>t(e.uv)))}get running(){return this.updating}runTask(e){if(null==this._glTexture)return g;for(;this._needsRepack&&(this._canRepack||this._atlas.height<T&&this._atlas.height<T);){this._canRepack=this._needsRepack=!1;const t=this._elements;this._elements=new Map,t.forEach((e=>this._processAddition(e))),e.madeProgress()}if(this._elementsToRender.size>0){for(const[t,s]of this._elementsToRender){if(e.done)break;this._renderElement(s),this._elementsToRender.delete(t),e.madeProgress()}this._glTexture.setData(this._canvas)}this.updating=this._elementsToRender.size>0}addText(e,t){const s=e.key;this._addCallback(s,t);let i=this._elements.get(s);return i?o(i.uv,_)||t(i.uv):(i=new b(this._atlas,e),this._processAddition(i),this.setDirty()),{remove:()=>this._removeText(e,t)}}_removeText(e,t){const s=e.key;this._elements.get(s)&&this._removeCallback(s,t)&&(this._elements.delete(s),this._elementsToRender.delete(s),this._canRepack=!0)}setDirty(){this._glTexture&&(this.updating=!0)}get test(){}};e([n({constructOnly:!0})],k.prototype,"view",void 0),e([n({type:Boolean})],k.prototype,"updating",void 0),k=e([a("esri.views.3d.webgl-engine.lib.TextTextureAtlas")],k);const R=2,y=2;class b{constructor(e,t){this._atlas=e,this.textRenderer=t,this._uv=c(),this._newPosition=[0,0]}get uv(){if(null==this._xOffset||null==this._yOffset)return _;const{renderedWidth:e,renderedHeight:t}=this.textRenderer;return l(this._uv,this._xOffset/this._atlas.width,(this._yOffset+t)/this._atlas.height,(this._xOffset+e)/this._atlas.width,this._yOffset/this._atlas.height)}setNewPosition(e){this._newPosition[0]=e.x,this._newPosition[1]=e.y}commitNewPosition(){return this._xOffset=this._newPosition[0],this._yOffset=this._newPosition[1],this._newPosition}get xOffset(){return this._xOffset}get yOffset(){return this._yOffset}}class A{constructor(e,t){this.width=e,this.height=t,this.cursors=new Map,this.nextY=0}reset(){this.cursors.clear(),this.nextY=j}}class C{constructor(e){this.y=e,this.x=j}}let j=0;export{k as TextTextureAtlas};
5
+ import{_ as e}from"../../../../chunks/tslib.es6.js";import t from"../../../../core/Accessor.js";import s from"../../../../core/Evented.js";import"../../../../core/has.js";import{disposeMaybe as i,removeMaybe as r}from"../../../../core/maybe.js";import{generateUID as h}from"../../../../core/uid.js";import{property as n}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/Logger.js";import"../../../../core/RandomLCG.js";import{subclass as a}from"../../../../core/accessorSupport/decorators/subclass.js";import{a as o,s as l}from"../../../../chunks/vec42.js";import{ZEROS as _,create as c}from"../../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{ContentObjectType as d}from"./ContentObjectType.js";import{textTextureAtlas as u}from"./testUtils.js";import{applyTextureResizeModuloCeil as m}from"./textureUtils.js";import{TaskPriority as p}from"../../../support/Scheduler.js";import{Yield as g}from"../../../support/Yield.js";import{TextureWrapMode as f,TextureSamplingMode as x}from"../../../webgl/enums.js";import{Texture as v}from"../../../webgl/Texture.js";import{TextureDescriptor as w}from"../../../webgl/TextureDescriptor.js";const T=4096;let k=class extends t{constructor(e){super(e),this.type=d.Texture,this.id=h(),this.events=new s,this._glTexture=null,this._atlas=new A(256,256),this._needsRepack=!1,this._canRepack=!0,this._elementsToRender=new Map,this._elements=new Map,this._uvCallbacks=new Map,this.updating=!1}initialize(){this._canvas=document.createElement("canvas"),this._canvas.setAttribute("id","textAtlasCanvas"),this._canvas.setAttribute("style","display:none"),this._ctx=this._canvas.getContext("2d"),this._stage=this.view._stage,this._stage.add(this),this._updateCanvasElementSize(this._atlas),this._reset()}unload(){this._glTexture=i(this._glTexture),this._frameWorker=r(this._frameWorker),this.updating=!1,this.events.emit("unloaded")}get loaded(){return null!=this._glTexture}get glTexture(){return this._glTexture}static get maxSize(){return j=u.stableRendering?R:0,[T-R-j,T-R-j-y]}load(e){if(this._glTexture)return this._glTexture;const t=new w;return t.wrapMode=f.CLAMP_TO_EDGE,t.samplingMode=x.LINEAR_MIPMAP_LINEAR,t.hasMipmap=!0,t.preMultiplyAlpha=!0,t.maxAnisotropy=e.parameters.maxMaxAnisotropy,this._glTexture=new v(e,t,this._canvas),this._frameWorker=this.view.resourceController.scheduler.registerTask(p.TEXT_TEXTURE_ATLAS,this),this.setDirty(),this._glTexture}dispose(){this._elements.clear(),this._elementsToRender.clear(),this._frameWorker=r(this._frameWorker),this._glTexture&&(this._stage.remove(this),this._glTexture=i(this._glTexture)),this._canvas.width=0,this._canvas.height=0,this._canvas=null,this._ctx=null}_updateCanvasElementSize(e){this._canvas.width=e.width,this._canvas.height=e.height}_resizeAtlas(e,t){const{width:s,height:i}=this._atlas;s===e&&i===t||(this._atlas.width=e,this._atlas.height=t,this._glTexture?.resize(e,t),this._glTexture?.updateData(0,0,0,s,i,this._canvas),this._updateCanvasElementSize(this._atlas),this._elements.forEach((e=>this._uvCallbacks.get(e.textRenderer.key)?.forEach((t=>t(e.uv))))),this._reset())}_reset(){this._elementsToRender.clear(),this._atlas.reset(),this._needsRepack=!0,this.setDirty()}_addAtlasElement(e,t,s,i){const r=this._atlas;if(r.width<s||r.height<i)return!1;let h=r.cursors.get(i);if(!h){if(r.height<r.nextY+i)return!1;h=[new C(r.nextY)],r.cursors.set(i,h),r.nextY+=i}let n=h.find((e=>r.width>=e.x+s));if(null==n){if(r.height<r.nextY+i)return!1;n=new C(r.nextY),r.nextY+=i,h.push(n)}return e.setNewPosition(n),this._elements.set(t,e),this._elementsToRender.set(t,e),n.x+=s,!0}_ensureCallbacks(e){const t=this._uvCallbacks.get(e);if(t)return t;const s=new Set;return this._uvCallbacks.set(e,s),s}_addCallback(e,t){this._ensureCallbacks(e).add(t)}_removeCallback(e,t){const s=this._uvCallbacks.get(e);return!(!s?.delete(t)||0!==s.size)&&(this._uvCallbacks.delete(e),!0)}_processAddition(e){const t=e.textRenderer.key;if(this._needsRepack)return void this._elements.set(t,e);const s=this._atlas,i=e.textRenderer.renderedWidth,r=e.textRenderer.renderedHeight,h=i+R,n=r+R+y;if(!this._addAtlasElement(e,t,h,n)){if(this._canRepack)this._reset();else if(s.width<h){const e=m(Math.max(h,1.5*s.width),T);this._resizeAtlas(e,s.height)}else{const e=s.nextY+n,t=m(Math.max(e,1.5*s.height),T);if(t>s.height)this._resizeAtlas(s.width,t);else if(s.width<T){const e=m(1.5*s.width,T);this._resizeAtlas(e,s.height)}}this._elements.set(t,e)}}_renderElement(e){const t=e.commitNewPosition(),s=e.textRenderer;this._ctx.clearRect(t[0]-R,t[1]-R,s.renderedWidth+2*R,s.renderedHeight+2*R),s.render(this._ctx,t[0],t[1]),this._uvCallbacks.get(s.key)?.forEach((t=>t(e.uv)))}get running(){return this.updating}runTask(e){if(null==this._glTexture)return g;for(;this._needsRepack&&(this._canRepack||this._atlas.height<T&&this._atlas.height<T);){this._canRepack=this._needsRepack=!1;const t=this._elements;this._elements=new Map,t.forEach((e=>this._processAddition(e))),e.madeProgress()}if(this._elementsToRender.size>0){for(const[t,s]of this._elementsToRender){if(e.done)break;this._renderElement(s),this._elementsToRender.delete(t),e.madeProgress()}this._glTexture.setData(this._canvas)}this.updating=this._elementsToRender.size>0}addText(e,t){const s=e.key;this._addCallback(s,t);let i=this._elements.get(s);return i?o(i.uv,_)||t(i.uv):(i=new b(this._atlas,e),this._processAddition(i),this.setDirty()),{remove:()=>this._removeText(e,t)}}_removeText(e,t){const s=e.key;this._elements.get(s)&&this._removeCallback(s,t)&&(this._elements.delete(s),this._elementsToRender.delete(s),this._canRepack=!0)}setDirty(){this._glTexture&&(this.updating=!0)}get test(){}};e([n({constructOnly:!0})],k.prototype,"view",void 0),e([n({type:Boolean})],k.prototype,"updating",void 0),k=e([a("esri.views.3d.webgl-engine.lib.TextTextureAtlas")],k);const R=2,y=2;class b{constructor(e,t){this._atlas=e,this.textRenderer=t,this._uv=c(),this._newPosition=[0,0]}get uv(){if(null==this._xOffset||null==this._yOffset)return _;const{renderedWidth:e,renderedHeight:t}=this.textRenderer;return l(this._uv,this._xOffset/this._atlas.width,(this._yOffset+t)/this._atlas.height,(this._xOffset+e)/this._atlas.width,this._yOffset/this._atlas.height)}setNewPosition(e){this._newPosition[0]=e.x,this._newPosition[1]=e.y}commitNewPosition(){return this._xOffset=this._newPosition[0],this._yOffset=this._newPosition[1],this._newPosition}get xOffset(){return this._xOffset}get yOffset(){return this._yOffset}}class A{constructor(e,t){this.width=e,this.height=t,this.cursors=new Map,this.nextY=0}reset(){this.cursors.clear(),this.nextY=j}}class C{constructor(e){this.y=e,this.x=j}}let j=0;export{k as TextTextureAtlas};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import"../../../../core/has.js";import t from"../../../../core/Error.js";import e from"../../../../core/Evented.js";import{disposeMaybe as r,removeMaybe as s}from"../../../../core/maybe.js";import{throwIfAborted as a,onAbort as i,createAbortError as o}from"../../../../core/promiseUtils.js";import{isUint8Array as n,isArrayBuffer as l}from"../../../../core/typedArrayUtil.js";import{isBlobProtocol as m,isDataProtocol as h}from"../../../../core/urlUtils.js";import{requestImage as _}from"../../../../support/requestImageUtils.js";import{loadImageAsync as p}from"../../../../support/requestUtils.js";import{TextureEncodingMimeType as d}from"./basicInterfaces.js";import{createTextureKTX2 as c,createTextureBasis as u,estimateMemoryKTX2 as g,estimateMemoryBasis as A}from"./BasisUtil.js";import{ContentObject as E}from"./ContentObject.js";import{ContentObjectType as T}from"./ContentObjectType.js";import{createDDSTexture as f}from"./DDSUtil.js";import{ensureImageMaxSize as D}from"./textureUtils.js";import{assert as x}from"./Util.js";import{TextureWrapMode as y,TextureSamplingMode as I,PixelFormat as F}from"../../../webgl/enums.js";import{Texture as U}from"../../../webgl/Texture.js";import{TextureDescriptor as C}from"../../../webgl/TextureDescriptor.js";class N extends E{constructor(t,r){super(),this._data=t,this.type=T.Texture,this.events=new e,this._glTexture=null,this._loadingPromise=null,this._loadingController=null,this._parameters={...R,...r},this._startPreload(t)}dispose(){this.unload(),this._data=this.frameUpdate=void 0}_startPreload(t){null!=t&&(t instanceof HTMLVideoElement?(this.frameUpdate=e=>this._frameUpdate(t,e),this._startPreloadVideoElement(t)):t instanceof HTMLImageElement&&this._startPreloadImageElement(t))}_startPreloadVideoElement(t){if(!(m(t.src)||"auto"===t.preload&&t.crossOrigin)){t.preload="auto",t.crossOrigin="anonymous";const e=!t.paused;if(t.src=t.src,e&&t.autoplay){const e=()=>{t.removeEventListener("canplay",e),t.play()};t.addEventListener("canplay",e)}}}_startPreloadImageElement(t){h(t.src)||m(t.src)||t.crossOrigin||(t.crossOrigin="anonymous",t.src=t.src)}_createDescriptor(t){const e=new C;return e.wrapMode=this._parameters.wrap??y.REPEAT,e.flipped=!this._parameters.noUnpackFlip,e.samplingMode=this._parameters.mipmap?I.LINEAR_MIPMAP_LINEAR:I.LINEAR,e.hasMipmap=!!this._parameters.mipmap,e.preMultiplyAlpha=!!this._parameters.preMultiplyAlpha,e.maxAnisotropy=this._parameters.maxAnisotropy??(this._parameters.mipmap?t.parameters.maxMaxAnisotropy:1),e}get glTexture(){return this._glTexture}get usedMemory(){return this._glTexture?.usedMemory||w(this._data,this._parameters)}load(t){if(this._glTexture)return this._glTexture;if(this._loadingPromise)return this._loadingPromise;const e=this._data;return null==e?(this._glTexture=new U(t,this._createDescriptor(t),null),this._glTexture):(this._parameters.reloadable||(this._data=void 0),"string"==typeof e?this._loadFromURL(t,e):e instanceof Image?this._loadFromImageElement(t,e):e instanceof HTMLVideoElement?this._loadFromVideoElement(t,e):e instanceof ImageData||e instanceof HTMLCanvasElement?this._loadFromImage(t,e):n(e)&&this._parameters.encoding===d.DDS_ENCODING?this._loadFromDDSData(t,e):l(e)&&this._parameters.encoding===d.DDS_ENCODING?this._loadFromDDSData(t,new Uint8Array(e)):(l(e)||n(e))&&this._parameters.encoding===d.KTX2_ENCODING?this._loadFromKTX2(t,e):(l(e)||n(e))&&this._parameters.encoding===d.BASIS_ENCODING?this._loadFromBasis(t,e):n(e)?this._loadFromPixelData(t,e):l(e)?this._loadFromPixelData(t,new Uint8Array(e)):null)}_frameUpdate(t,e){return null==this._glTexture||t.readyState<M.HAVE_CURRENT_DATA||e===t.currentTime?e:(this._glTexture.setData(t),this._glTexture.descriptor.hasMipmap&&this._glTexture.generateMipmap(),this._parameters.updateCallback&&this._parameters.updateCallback(),t.currentTime)}_loadFromDDSData(t,e){return this._glTexture=f(t,this._createDescriptor(t),e),this._glTexture}_loadFromKTX2(t,e){return this._loadAsync((()=>c(t,this._createDescriptor(t),e).then((t=>(this._glTexture=t,t)))))}_loadFromBasis(t,e){return this._loadAsync((()=>u(t,this._createDescriptor(t),e).then((t=>(this._glTexture=t,t)))))}_loadFromPixelData(t,e){x(this._parameters.width>0&&this._parameters.height>0);const r=this._createDescriptor(t);return r.pixelFormat=1===this._parameters.components?F.LUMINANCE:3===this._parameters.components?F.RGB:F.RGBA,r.width=this._parameters.width??0,r.height=this._parameters.height??0,this._glTexture=new U(t,r,e),this._glTexture}_loadFromURL(t,e){return this._loadAsync((async r=>{const s=await _(e,{signal:r});return a(r),this._loadFromImage(t,s)}))}_loadFromImageElement(t,e){return e.complete?this._loadFromImage(t,e):this._loadAsync((async r=>{const s=await p(e,e.src,!1,r);return a(r),this._loadFromImage(t,s)}))}_loadFromVideoElement(t,e){return e.readyState>=M.HAVE_CURRENT_DATA?this._loadFromImage(t,e):this._loadFromVideoElementAsync(t,e)}_loadFromVideoElementAsync(e,r){return this._loadAsync((a=>new Promise(((n,l)=>{const m=()=>{r.removeEventListener("loadeddata",h),r.removeEventListener("error",_),s(p)},h=()=>{r.readyState>=M.HAVE_CURRENT_DATA&&(m(),n(this._loadFromImage(e,r)))},_=e=>{m(),l(e||new t("Failed to load video"))};r.addEventListener("loadeddata",h),r.addEventListener("error",_);const p=i(a,(()=>_(o())))}))))}_loadFromImage(t,e){let r=e;r instanceof HTMLVideoElement||(r=D(r,t.parameters));const s=H(r);this._parameters.width=s.width,this._parameters.height=s.height;const a=this._createDescriptor(t);return a.pixelFormat=3===this._parameters.components?F.RGB:F.RGBA,a.width=s.width,a.height=s.height,a.shouldCompress=this._parameters.shouldCompress,this._glTexture=new U(t,a,r),this._glTexture}_loadAsync(t){const e=new AbortController;this._loadingController=e;const r=t(e.signal);this._loadingPromise=r;const s=()=>{this._loadingController===e&&(this._loadingController=null),this._loadingPromise===r&&(this._loadingPromise=null)};return r.then(s,s),r}unload(){if(this._glTexture=r(this._glTexture),null!=this._loadingController){const t=this._loadingController;this._loadingController=null,this._loadingPromise=null,t.abort()}this.events.emit("unloaded")}get parameters(){return this._parameters}}function w(t,e){if(null==t)return 0;if(l(t)||n(t))return e.encoding===d.KTX2_ENCODING?g(t,!!e.mipmap):e.encoding===d.BASIS_ENCODING?A(t,!!e.mipmap):t.byteLength;const{width:r,height:s}=t instanceof Image||t instanceof ImageData||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement?H(t):e;return(e.mipmap?4/3:1)*r*s*(e.components||4)||0}function H(t){return t instanceof HTMLVideoElement?{width:t.videoWidth,height:t.videoHeight}:t}var M;!function(t){t[t.HAVE_NOTHING=0]="HAVE_NOTHING",t[t.HAVE_METADATA=1]="HAVE_METADATA",t[t.HAVE_CURRENT_DATA=2]="HAVE_CURRENT_DATA",t[t.HAVE_FUTURE_DATA=3]="HAVE_FUTURE_DATA",t[t.HAVE_ENOUGH_DATA=4]="HAVE_ENOUGH_DATA"}(M||(M={}));const R={wrap:{s:y.REPEAT,t:y.REPEAT},mipmap:!0,noUnpackFlip:!1,preMultiplyAlpha:!1,shouldCompress:!1};export{N as Texture};
5
+ import"../../../../core/has.js";import e from"../../../../core/Error.js";import t from"../../../../core/Evented.js";import{disposeMaybe as r,removeMaybe as s}from"../../../../core/maybe.js";import{throwIfAborted as a,onAbort as i,createAbortError as o}from"../../../../core/promiseUtils.js";import{isUint8Array as n,isArrayBuffer as l}from"../../../../core/typedArrayUtil.js";import{isBlobProtocol as m,isDataProtocol as h}from"../../../../core/urlUtils.js";import{requestImage as _}from"../../../../support/requestImageUtils.js";import{loadImageAsync as p}from"../../../../support/requestUtils.js";import{TextureEncodingMimeType as d}from"./basicInterfaces.js";import{createTextureKTX2 as u,createTextureBasis as c,estimateMemoryKTX2 as g,estimateMemoryBasis as T}from"./BasisUtil.js";import{ContentObject as A}from"./ContentObject.js";import{ContentObjectType as E}from"./ContentObjectType.js";import{createDDSTexture as f}from"./DDSUtil.js";import{ensureImageMaxSize as D}from"./textureUtils.js";import{assert as x}from"./Util.js";import{TextureWrapMode as y,TextureSamplingMode as I,PixelFormat as F}from"../../../webgl/enums.js";import{Texture as U}from"../../../webgl/Texture.js";import{TextureDescriptor as C}from"../../../webgl/TextureDescriptor.js";class N extends A{constructor(e,r){super(),this._data=e,this.type=E.Texture,this.events=new t,this._parameters={...R,...r},this._startPreload(e)}dispose(){this.unload(),this._data=this.frameUpdate=void 0}_startPreload(e){e instanceof HTMLVideoElement?(this.frameUpdate=t=>this._frameUpdate(e,t),this._startPreloadVideoElement(e)):e instanceof HTMLImageElement&&this._startPreloadImageElement(e)}_startPreloadVideoElement(e){if(!(m(e.src)||"auto"===e.preload&&e.crossOrigin)){e.preload="auto",e.crossOrigin="anonymous";const t=!e.paused;if(e.src=e.src,t&&e.autoplay){const t=()=>{e.removeEventListener("canplay",t),e.play()};e.addEventListener("canplay",t)}}}_startPreloadImageElement(e){h(e.src)||m(e.src)||e.crossOrigin||(e.crossOrigin="anonymous",e.src=e.src)}_createDescriptor(e){const t=new C;return t.wrapMode=this._parameters.wrap??y.REPEAT,t.flipped=!this._parameters.noUnpackFlip,t.samplingMode=this._parameters.mipmap?I.LINEAR_MIPMAP_LINEAR:I.LINEAR,t.hasMipmap=!!this._parameters.mipmap,t.preMultiplyAlpha=!!this._parameters.preMultiplyAlpha,t.maxAnisotropy=this._parameters.maxAnisotropy??(this._parameters.mipmap?e.parameters.maxMaxAnisotropy:1),t}get glTexture(){return this._glTexture??this._emptyTexture}get loaded(){return null!=this._glTexture}get usedMemory(){return this._glTexture?.usedMemory||w(this._data,this._parameters)}load(e){if(this._loadingPromise)return this._loadingPromise;if(this._glTexture)return this._glTexture;const t=this._data;return null==t?(this._glTexture=new U(e,this._createDescriptor(e),null),this._glTexture):(this._emptyTexture=e.emptyTexture,this._parameters.reloadable||(this._data=void 0),"string"==typeof t?this._loadFromURL(e,t):t instanceof Image?this._loadFromImageElement(e,t):t instanceof HTMLVideoElement?this._loadFromVideoElement(e,t):t instanceof ImageData||t instanceof HTMLCanvasElement?this._loadFromImage(e,t):n(t)&&this._parameters.encoding===d.DDS_ENCODING?this._loadFromDDSData(e,t):l(t)&&this._parameters.encoding===d.DDS_ENCODING?this._loadFromDDSData(e,new Uint8Array(t)):(l(t)||n(t))&&this._parameters.encoding===d.KTX2_ENCODING?this._loadFromKTX2(e,t):(l(t)||n(t))&&this._parameters.encoding===d.BASIS_ENCODING?this._loadFromBasis(e,t):n(t)?this._loadFromPixelData(e,t):l(t)?this._loadFromPixelData(e,new Uint8Array(t)):null)}_frameUpdate(e,t){return null==this._glTexture||e.readyState<M.HAVE_CURRENT_DATA||t===e.currentTime?t:(this._glTexture.setData(e),this._glTexture.descriptor.hasMipmap&&this._glTexture.generateMipmap(),this._parameters.updateCallback&&this._parameters.updateCallback(),e.currentTime)}_loadFromDDSData(e,t){return this._glTexture=f(e,this._createDescriptor(e),t),this._emptyTexture=null,this._glTexture}_loadFromKTX2(e,t){return this._loadAsync((()=>u(e,this._createDescriptor(e),t).then((e=>(this._glTexture=e,e)))))}_loadFromBasis(e,t){return this._loadAsync((()=>c(e,this._createDescriptor(e),t).then((e=>(this._glTexture=e,e)))))}_loadFromPixelData(e,t){x(this._parameters.width>0&&this._parameters.height>0);const r=this._createDescriptor(e);return r.pixelFormat=1===this._parameters.components?F.LUMINANCE:3===this._parameters.components?F.RGB:F.RGBA,r.width=this._parameters.width??0,r.height=this._parameters.height??0,this._glTexture=new U(e,r,t),this._glTexture}_loadFromURL(e,t){return this._loadAsync((async r=>{const s=await _(t,{signal:r});return a(r),this._loadFromImage(e,s)}))}_loadFromImageElement(e,t){return t.complete?this._loadFromImage(e,t):this._loadAsync((async r=>{const s=await p(t,t.src,!1,r);return a(r),this._loadFromImage(e,s)}))}_loadFromVideoElement(e,t){return t.readyState>=M.HAVE_CURRENT_DATA?this._loadFromImage(e,t):this._loadFromVideoElementAsync(e,t)}_loadFromVideoElementAsync(t,r){return this._loadAsync((a=>new Promise(((n,l)=>{const m=()=>{r.removeEventListener("loadeddata",h),r.removeEventListener("error",_),s(p)},h=()=>{r.readyState>=M.HAVE_CURRENT_DATA&&(m(),n(this._loadFromImage(t,r)))},_=t=>{m(),l(t||new e("Failed to load video"))};r.addEventListener("loadeddata",h),r.addEventListener("error",_);const p=i(a,(()=>_(o())))}))))}_loadFromImage(e,t){let r=t;r instanceof HTMLVideoElement||(r=D(r,e.parameters));const s=H(r);this._parameters.width=s.width,this._parameters.height=s.height;const a=this._createDescriptor(e);return a.pixelFormat=3===this._parameters.components?F.RGB:F.RGBA,a.width=s.width,a.height=s.height,a.shouldCompress=this._parameters.shouldCompress,this._glTexture=new U(e,a,r),this._emptyTexture=null,this._glTexture}_loadAsync(e){const t=new AbortController;this._loadingController=t;const r=e(t.signal);this._loadingPromise=r;const s=()=>{this._loadingController===t&&(this._loadingController=null),this._loadingPromise===r&&(this._loadingPromise=null),this._emptyTexture=null};return r.then(s,s),r}unload(){if(this._glTexture=r(this._glTexture),this._emptyTexture=null,null!=this._loadingController){const e=this._loadingController;this._loadingController=null,this._loadingPromise=null,e.abort()}this.events.emit("unloaded")}get parameters(){return this._parameters}}function w(e,t){if(null==e)return 0;if(l(e)||n(e))return t.encoding===d.KTX2_ENCODING?g(e,!!t.mipmap):t.encoding===d.BASIS_ENCODING?T(e,!!t.mipmap):e.byteLength;const{width:r,height:s}=e instanceof Image||e instanceof ImageData||e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement?H(e):t;return(t.mipmap?4/3:1)*r*s*(t.components||4)||0}function H(e){return e instanceof HTMLVideoElement?{width:e.videoWidth,height:e.videoHeight}:e}var M;!function(e){e[e.HAVE_NOTHING=0]="HAVE_NOTHING",e[e.HAVE_METADATA=1]="HAVE_METADATA",e[e.HAVE_CURRENT_DATA=2]="HAVE_CURRENT_DATA",e[e.HAVE_FUTURE_DATA=3]="HAVE_FUTURE_DATA",e[e.HAVE_ENOUGH_DATA=4]="HAVE_ENOUGH_DATA"}(M||(M={}));const R={wrap:{s:y.REPEAT,t:y.REPEAT},mipmap:!0,noUnpackFlip:!1,preMultiplyAlpha:!1,shouldCompress:!1};export{N as Texture};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../../chunks/tslib.es6.js";import t from"../../../../core/Accessor.js";import r from"../../../../core/Evented.js";import s from"../../../../core/Logger.js";import{isPromiseLike as o,isAbortError as i}from"../../../../core/promiseUtils.js";import{property as n}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/has.js";import"../../../../core/RandomLCG.js";import{subclass as a}from"../../../../core/accessorSupport/decorators/subclass.js";import{RenderRequestType as u}from"./basicInterfaces.js";import{ContentObjectType as d}from"./ContentObjectType.js";import{isFrameUpdateTexture as l}from"./ITexture.js";import{TaskPriority as p}from"../../../support/Scheduler.js";let h=class extends t{constructor(e){super({}),this._stage=e,this._textures=new Map,this._loadingCount=0,this._frameUpdates=new Map,this.events=new r,this._frameTask=e.view.resourceController.scheduler.registerTask(p.TEXTURE_UNLOAD)}normalizeCtorArgs(){return{}}destroy(){this._frameTask.remove(),this._stage.forEachOfType(d.Texture,(e=>e.unload()))}get updating(){return this._loadingCount>0||this._frameTask.updating}acquire(e){const t=this._textures.get(e);return t?(t.ref(),t.loadingPromise??t):this._createNewRef(e)}update(){let e=!1;this._frameUpdates.forEach((t=>{const r=t.texture.frameUpdate(t.previousToken);r>=0&&r!==t.previousToken&&(t.previousToken=r,e=!0)})),e&&this.events.emit("changed",u.BACKGROUND)}_createNewRef(e){const t=this._stage.getObject(e);if(null==t)return null;const r=t.events.on("unloaded",(()=>{r.remove(),this._onTextureUnloaded(e)})),n=new c(e,(()=>{this._frameTask.schedule((()=>{n.isUnreferenced&&t.unload()}))}));return this._textures.set(e,n),n.ref(),t.glTexture?(this._updateGLTexture(n,t.glTexture),l(t)&&this._frameUpdates.set(e,{texture:t,previousToken:-1}),n):(this._loadingCount++,n.loadingPromise=this._stage.schedule((()=>{const r=t.load(this._stage.renderView.renderingContext),a=r=>(this._loadingCount--,n.loadingPromise=null,this._updateGLTexture(n,r),l(t)&&this._frameUpdates.set(e,{texture:t,previousToken:-1}),n),u=e=>(this._loadingCount--,n.loadingPromise=null,i(e)||s.getLogger(this).error(e),null);return o(r)?r.then(a,u):a(r)})),n.loadingPromise)}_updateGLTexture(e,t){e.glTexture=t,this.events.emit("changed",u.UPDATE)}_onTextureUnloaded(e){this._textures.delete(e),this._frameUpdates.delete(e)}};e([n()],h.prototype,"_loadingCount",void 0),e([n()],h.prototype,"_frameTask",void 0),e([n()],h.prototype,"updating",null),h=e([a("esri.views.3d.webgl-engine.lib.TextureRepository")],h);class c{constructor(e,t){this.id=e,this._release=t,this._refCount=0}get isUnreferenced(){return 0===this._refCount}ref(){++this._refCount}release(){--this._refCount,this._refCount>0||(0!==this._refCount?(s.getLogger("esri.views.3d.webgl-engine.lib.TextureRepository.RefCountedTextureImpl").error("Cannot dereference texture that has no references!"),this._refCount=0):this._release())}}export{h as TextureRepository};
5
+ import{_ as e}from"../../../../chunks/tslib.es6.js";import t from"../../../../core/Accessor.js";import r from"../../../../core/Evented.js";import s from"../../../../core/Logger.js";import{isPromiseLike as o,isAbortError as i}from"../../../../core/promiseUtils.js";import{property as n}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/has.js";import"../../../../core/RandomLCG.js";import{subclass as a}from"../../../../core/accessorSupport/decorators/subclass.js";import{RenderRequestType as u}from"./basicInterfaces.js";import{ContentObjectType as d}from"./ContentObjectType.js";import{isFrameUpdateTexture as l}from"./ITexture.js";import{TaskPriority as p}from"../../../support/Scheduler.js";let h=class extends t{constructor(e){super({}),this._stage=e,this._textures=new Map,this._loadingCount=0,this._frameUpdates=new Map,this.events=new r,this._frameTask=e.view.resourceController.scheduler.registerTask(p.TEXTURE_UNLOAD)}normalizeCtorArgs(){return{}}destroy(){this._frameTask.remove(),this._stage.forEachOfType(d.Texture,(e=>e.unload()))}get updating(){return this._loadingCount>0||this._frameTask.updating}acquire(e){const t=this._textures.get(e);return t?(t.ref(),t.loadingPromise??t):this._createNewRef(e)}update(){let e=!1;this._frameUpdates.forEach((t=>{const r=t.texture.frameUpdate(t.previousToken);r>=0&&r!==t.previousToken&&(t.previousToken=r,e=!0)})),e&&this.events.emit("changed",u.BACKGROUND)}_createNewRef(e){const t=this._stage.getObject(e);if(null==t)return null;const r=t.events.on("unloaded",(()=>{r.remove(),this._onTextureUnloaded(e)})),n=new c(e,(()=>{this._frameTask.schedule((()=>{n.isUnreferenced&&t.unload()}))}));return this._textures.set(e,n),n.ref(),t.loaded?(this._updateGLTexture(n,t.glTexture),l(t)&&this._frameUpdates.set(e,{texture:t,previousToken:-1}),n):(this._loadingCount++,n.loadingPromise=this._stage.schedule((()=>{const r=t.load(this._stage.renderView.renderingContext),a=r=>(this._loadingCount--,n.loadingPromise=null,this._updateGLTexture(n,r),l(t)&&this._frameUpdates.set(e,{texture:t,previousToken:-1}),n),u=e=>(this._loadingCount--,n.loadingPromise=null,i(e)||s.getLogger(this).error(e),null);return o(r)?r.then(a,u):a(r)})),n.loadingPromise)}_updateGLTexture(e,t){e.glTexture=t,this.events.emit("changed",u.UPDATE)}_onTextureUnloaded(e){this._textures.delete(e),this._frameUpdates.delete(e)}};e([n()],h.prototype,"_loadingCount",void 0),e([n()],h.prototype,"_frameTask",void 0),e([n()],h.prototype,"updating",null),h=e([a("esri.views.3d.webgl-engine.lib.TextureRepository")],h);class c{constructor(e,t){this.id=e,this._release=t,this._refCount=0}get isUnreferenced(){return 0===this._refCount}ref(){++this._refCount}release(){--this._refCount,this._refCount>0||(0!==this._refCount?(s.getLogger("esri.views.3d.webgl-engine.lib.TextureRepository.RefCountedTextureImpl").error("Cannot dereference texture that has no references!"),this._refCount=0):this._release())}}export{h as TextureRepository};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import{BufferViewFloat as e}from"../../../../geometry/support/buffer/BufferView.js";import{isHighlightOrOID as t,isColor as r}from"../core/shaderLibrary/ShaderOutput.js";import{CullFaceOptions as i}from"../lib/basicInterfaces.js";import{GLTextureMaterial as s}from"../lib/GLTextureMaterial.js";import{MaterialParameters as a}from"../lib/Material.js";import{OITPolygonOffsetLimit as o}from"../lib/OrderIndependentTransparency.js";import{RenderSlot as n}from"../lib/RenderSlot.js";import{assert as u}from"../lib/Util.js";import{VertexAttribute as l}from"../lib/VertexAttribute.js";import{DefaultBufferWriter as c}from"./DefaultBufferWriter.js";import{PositionUVLayout as p}from"./DefaultLayouts.js";import{TriangleMaterial as h}from"./TriangleMaterial.js";import{writeBufferFloat as f,writeDefaultAttribute as m}from"./internal/bufferWriterUtils.js";import{vertexAttributeLocations as g,ImageMaterialTechnique as T}from"../shaders/ImageMaterialTechnique.js";import{ImageMaterialTechniqueConfiguration as d}from"../shaders/ImageMaterialTechniqueConfiguration.js";class I extends h{constructor(e){super(e,b),this._configuration=new d,this.vertexAttributeLocations=g,this.supportsEdges=!0,this.produces=new Map([[n.OPAQUE_MATERIAL,e=>t(e)],[n.TRANSPARENT_MATERIAL,e=>r(e)&&this.parameters.writeDepth],[n.TRANSPARENT_MATERIAL_WITHOUT_DEPTH,e=>r(e)&&!this.parameters.writeDepth],[n.DRAPED_MATERIAL,e=>r(e)||t(e)]])}getConfiguration(e,t){return this._configuration.output=e,this._configuration.cullFace=this.parameters.cullFace,this._configuration.hasSlicePlane=this.parameters.hasSlicePlane,this._configuration.writeDepth=this.parameters.writeDepth,this._configuration.hasOccludees=t.hasOccludees,this._configuration.oitPass=t.oitPass,this._configuration.enableOffset=t.camera.relativeElevation<o,this._configuration.terrainDepthTest=t.terrainDepthTest,this._configuration.cullAboveTerrain=t.cullAboveTerrain,this._configuration.perspectiveInterpolation=this.parameters.perspectiveInterpolation,this._configuration}get visible(){return!0}createGLMaterial(e){return new _(e)}createBufferWriter(){const e=p.clone();return this.parameters.perspectiveInterpolation&&e.f32(l.PERSPECTIVEDIVIDE),new E(e)}}class _ extends s{constructor(e){super({...e,...e.material.parameters})}beginSlot(e){return this.updateTexture(this._material.parameters.textureId),this._material.setParameters(this.textureBindParameters),this.getTechnique(T,e)}}class E extends c{write(t,r,i,s,a,o){for(const n of this.vertexBufferLayout.fields.keys()){const s=i.get(n);if(s)if(n===l.PERSPECTIVEDIVIDE){u(1===s.size);const t=a.getField(n,e);t&&f(s,t,o)}else m(n,s,t,r,a,o)}return null}}class b extends a{constructor(e){super(),this.textureId=e,this.writeDepth=!0,this.hasSlicePlane=!1,this.cullFace=i.None,this.opacity=1,this.perspectiveInterpolation=!1}}export{I as ImageMaterial,b as Parameters};
5
+ import{BufferViewFloat as e}from"../../../../geometry/support/buffer/BufferView.js";import{isHighlightOrOID as t,isColor as r}from"../core/shaderLibrary/ShaderOutput.js";import{CullFaceOptions as i}from"../lib/basicInterfaces.js";import s from"../lib/GLMaterial.js";import{MaterialParameters as o}from"../lib/Material.js";import{OITPolygonOffsetLimit as a}from"../lib/OrderIndependentTransparency.js";import{RenderSlot as n}from"../lib/RenderSlot.js";import{assert as u}from"../lib/Util.js";import{VertexAttribute as l}from"../lib/VertexAttribute.js";import{DefaultBufferWriter as c}from"./DefaultBufferWriter.js";import{PositionUVLayout as p}from"./DefaultLayouts.js";import{TriangleMaterial as f}from"./TriangleMaterial.js";import{writeBufferFloat as h,writeDefaultAttribute as m}from"./internal/bufferWriterUtils.js";import{vertexAttributeLocations as g,ImageMaterialTechnique as T}from"../shaders/ImageMaterialTechnique.js";import{ImageMaterialTechniqueConfiguration as d}from"../shaders/ImageMaterialTechniqueConfiguration.js";class E extends f{constructor(e){super(e,A),this._configuration=new d,this.vertexAttributeLocations=g,this.supportsEdges=!0,this.produces=new Map([[n.OPAQUE_MATERIAL,e=>t(e)],[n.TRANSPARENT_MATERIAL,e=>r(e)&&this.parameters.writeDepth],[n.TRANSPARENT_MATERIAL_WITHOUT_DEPTH,e=>r(e)&&!this.parameters.writeDepth],[n.DRAPED_MATERIAL,e=>r(e)||t(e)]])}dispose(){this.setParameters({texture:void 0})}getConfiguration(e,t){return this._configuration.output=e,this._configuration.cullFace=this.parameters.cullFace,this._configuration.hasSlicePlane=this.parameters.hasSlicePlane,this._configuration.writeDepth=this.parameters.writeDepth,this._configuration.hasOccludees=t.hasOccludees,this._configuration.oitPass=t.oitPass,this._configuration.enableOffset=t.camera.relativeElevation<a,this._configuration.terrainDepthTest=t.terrainDepthTest,this._configuration.cullAboveTerrain=t.cullAboveTerrain,this._configuration.perspectiveInterpolation=this.parameters.perspectiveInterpolation,this._configuration}get visible(){return!0}createGLMaterial(e){return new I(e)}createBufferWriter(){const e=p.clone();return this.parameters.perspectiveInterpolation&&e.f32(l.PERSPECTIVEDIVIDE),new b(e)}}class I extends s{constructor(e){super({...e,...e.material.parameters})}beginSlot(e){return this.getTechnique(T,e)}}class b extends c{write(t,r,i,s,o,a){for(const n of this.vertexBufferLayout.fields.keys()){const s=i.get(n);if(s)if(n===l.PERSPECTIVEDIVIDE){u(1===s.size);const t=o.getField(n,e);t&&h(s,t,a)}else m(n,s,t,r,o,a)}return null}}class A extends o{constructor(e){super(),this.texture=e,this.writeDepth=!0,this.hasSlicePlane=!1,this.cullFace=i.None,this.opacity=1,this.perspectiveInterpolation=!1}get glTexture(){return this.texture.glTexture}}export{E as ImageMaterial,A as Parameters};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import{tBaseLine as o,tPanion as e,dtPanion as n,ddtPanion as a,tAscensionZoomOnly as t,tAscensionZoomPan as c,dtAscensionZoomOnly as s,dtAscensionZoomPan as r,ddtAscensionZoomOnly as i,ddtAscensionZoomPan as m,tDescensionZoomOnly as u,tDescensionZoomPan as l,dtDescensionZoomOnly as d,dtDescensionZoomPan as p,ddtDescensionZoomOnly as x,ddtDescensionZoomPan as F}from"./functions.js";function f(f,Z){let b=D(f,Z);const h={ascensionFactor:null!=Z.ascensionFactor?Z.ascensionFactor:.5,descensionFactor:null!=Z.descensionFactor?Z.descensionFactor:.5},M=0===h.ascensionFactor,P=0===h.descensionFactor,g=M?t:c,k=M?s:r,N=M?i:m,j=P?u:l,w=P?d:p,z=P?x:F,A=o=>g(f,o,h)+e(f,o,h)+j(f,o,h),I=o=>k(f,o,h)+n(f,o,h)+w(f,o,h),S=o=>N(f,o,h)+a(f,o,h)+z(f,o,h);let q=A(b);const v=o(f);let y;const B=Z.maximumIterations||20,C=null!=Z.maximumDistance?Z.maximumDistance:1/0;for(y=0;y<B;y++){const o=Z.desiredSlope??1e-6;let e=I(b);Math.abs(e)>o&&(e+=o);const n=e/S(b);if(isNaN(n)||b>=C&&n<0){if(!isFinite(C))return null;b=C,q=A(b);break}if(b-=n,b<f.compared.sourceZoom||b<f.compared.targetZoom)return null;const a=A(b);if(Math.abs(a-q)/q<=.005)break;q=a}return q>v*(1-.3)||b<f.compared.sourceZoom||b<f.compared.targetZoom?null:b}function D(o,e){const n=Math.max(o.compared.sourceZoom,o.compared.targetZoom),a=o.source.zoomAtPixelsPerPan(o.desiredPixelFlow/o.compared.pan)/2;return a<n?null!=e.maximumDistance?n+(e.maximumDistance-n)/2:1.5*n:e.maximumDistance?Math.min(e.maximumDistance,a):a}export{f as optimalDistance};
5
+ import{tBaseLine as o,tPanion as e,dtPanion as n,ddtPanion as a,tAscensionZoomOnly as t,tAscensionZoomPan as s,dtAscensionZoomOnly as c,dtAscensionZoomPan as i,ddtAscensionZoomOnly as r,ddtAscensionZoomPan as m,tDescensionZoomOnly as u,tDescensionZoomPan as l,dtDescensionZoomOnly as d,dtDescensionZoomPan as p,ddtDescensionZoomOnly as x,ddtDescensionZoomPan as F}from"./functions.js";function f(f,Z){let b=D(f,Z);const h={ascensionFactor:null!=Z.ascensionFactor?Z.ascensionFactor:.5,descensionFactor:null!=Z.descensionFactor?Z.descensionFactor:.5},M=0===h.ascensionFactor,N=0===h.descensionFactor,P=M?t:s,g=M?c:i,k=M?r:m,j=N?u:l,w=N?d:p,z=N?x:F,A=o=>P(f,o,h)+e(f,o,h)+j(f,o,h),I=o=>g(f,o,h)+n(f,o,h)+w(f,o,h),S=o=>k(f,o,h)+a(f,o,h)+z(f,o,h);let q=A(b);const v=o(f);let y;const B=Z.maximumIterations||20,C=null!=Z.maximumDistance?Z.maximumDistance:1/0;for(y=0;y<B;y++){const o=Z.desiredSlope??1e-6;let e=I(b);Math.abs(e)>o&&(e+=o);const n=e/S(b);if(isNaN(n)||b>=C&&n<0){if(!isFinite(C))return null;b=C,q=A(b);break}if(b-=n,b<=f.compared.sourceZoom||b<=f.compared.targetZoom)return null;const a=A(b);if(Math.abs(a-q)/q<=.005)break;q=a}const E=.3;return isNaN(q)||q>v*(1-E)||b<=f.compared.sourceZoom||b<=f.compared.targetZoom?null:b}function D(o,e){const n=Math.max(o.compared.sourceZoom,o.compared.targetZoom),a=o.source.zoomAtPixelsPerPan(o.desiredPixelFlow/o.compared.pan)/2;return a<n?null!=e.maximumDistance?n+(e.maximumDistance-n)/2:1.5*n:e.maximumDistance?Math.min(e.maximumDistance,a):a}export{f as optimalDistance};