@arcgis/core 4.29.1 → 4.29.2

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 (36) hide show
  1. package/assets/esri/core/workers/RemoteClient.js +1 -1
  2. package/assets/esri/core/workers/chunks/7427d03e693f32a81377.js +1 -0
  3. package/assets/esri/core/workers/chunks/8a9387483b19a5ec5b86.js +1 -0
  4. package/geohash/geohashUtils.js +1 -1
  5. package/interfaces.d.ts +14 -8
  6. package/kernel.js +1 -1
  7. package/layers/graphics/data/StreamFeatureManager.js +1 -1
  8. package/package.json +1 -1
  9. package/support/revision.js +1 -1
  10. package/views/2d/engine/webgl/collisions/CollisionEngine.js +1 -1
  11. package/views/2d/engine/webgl/shaderGraph/techniques/createTestMeshData.js +1 -1
  12. package/views/2d/layers/FeatureLayerView2D.js +1 -1
  13. package/views/2d/layers/features/Processor.js +1 -1
  14. package/views/2d/layers/features/layerAdapters/CatalogFootprintLayerAdapter.js +1 -1
  15. package/views/2d/layers/features/layerAdapters/FeatureLayerAdapter.js +1 -1
  16. package/views/2d/layers/features/layerAdapters/InMemoryLayerAdapter.js +1 -1
  17. package/views/2d/layers/features/layerAdapters/KnowledgeGraphSublayerAdapter.js +1 -1
  18. package/views/2d/layers/features/layerAdapters/OGCFeatureLayerAdapter.js +1 -1
  19. package/views/2d/layers/features/layerAdapters/OrientedImageryLayerAdapter.js +1 -1
  20. package/views/2d/layers/features/layerAdapters/StreamLayerAdapter.js +1 -1
  21. package/views/2d/layers/features/layerAdapters/SubtypeGroupLayerAdapter.js +1 -1
  22. package/views/2d/layers/features/processor/BinningStrategy.js +1 -1
  23. package/views/2d/layers/features/processor/ClusterStrategy.js +1 -1
  24. package/views/2d/layers/features/processor/FeatureUpdateStrategy.js +1 -1
  25. package/views/2d/layers/features/schema/processor/SimpleProcessorSchema.js +1 -1
  26. package/views/2d/layers/features/schema/processor/SubtypeProcessorSchema.js +1 -1
  27. package/views/2d/layers/features/sources/strategies/StreamLoadStrategy.js +1 -1
  28. package/views/2d/layers/features/support/FeatureMetadata.js +1 -1
  29. package/views/2d/layers/features/support/Tile.js +1 -1
  30. package/views/2d/layers/graphics/GraphicsView2D.js +1 -1
  31. package/views/3d/webgl-engine/effects/RenderNodes.js +1 -1
  32. package/views/3d/webgl-engine/lib/Renderer.js +1 -1
  33. package/widgets/Editor/EditorViewModel.js +1 -1
  34. package/widgets/UtilityNetworkTrace/UtilityNetworkTraceViewModel.js +1 -1
  35. package/assets/esri/core/workers/chunks/58723274ef657fe212eb.js +0 -1
  36. package/assets/esri/core/workers/chunks/8c360923cd1850767d3e.js +0 -1
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../../chunks/tslib.es6.js";import{update as r}from"../../../../core/arrayUtils.js";import{unitRGBAFromColor as t}from"../../../../core/colorUtils.js";import has from"../../../../core/has.js";import{removeMaybe as s,destroyMaybe as i,releaseMaybe as a}from"../../../../core/maybe.js";import n from"../../../../core/PooledArray.js";import{watch as h,syncAndInitial as o,initial as d,sync as l}from"../../../../core/reactiveUtils.js";import{signal as _}from"../../../../core/signal.js";import{property as p}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/Logger.js";import"../../../../core/accessorSupport/interfaces.js";import"../../../../core/accessorSupport/tracking/Flags.js";import"../../../../core/Warning.js";import"../../../../core/Error.js";import{equals as u,invert as c,multiply as m}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{IDENTITY as g,create as f}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{s as T}from"../../../../chunks/vec42.js";import{fromValues as A,ZEROS as E}from"../../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{a as b}from"../../../../chunks/boundedPlane.js";import{debugFlags as R}from"../../support/debugFlags.js";import{TransparencyMode as P}from"../../terrain/TerrainRenderer.js";import{DepthFormat as S,ColorFormat as C}from"../../webgl/formats.js";import{FBOCache as I}from"../core/FBOCache.js";import{RenderPassManager as O}from"../core/renderPasses/RenderPassManager.js";import{ShaderOutput as w}from"../core/shaderLibrary/ShaderOutput.js";import{HUDRenderStyle as y}from"../core/shaderLibrary/hud/HUDRenderStyle.js";import{RenderNodes as D}from"../effects/RenderNodes.js";import{isPrepareRenderPlugin as N}from"../effects/RenderPlugin.js";import{RenderPluginManager as L}from"../effects/RenderPluginManager.js";import{Blit as H}from"../effects/blit/Blit.js";import{Highlight as M}from"../effects/highlight/Highlight.js";import{ShadowHighlight as x}from"../effects/highlight/ShadowHighlight.js";import{SMAA as v}from"../effects/smaa/SMAA.js";import{SSAO as F}from"../effects/ssao/SSAO.js";import{AnimationTimeStep as U}from"./AnimationTimeStep.js";import{Decorations as q,RenderRequestType as j,StencilBits as G}from"./basicInterfaces.js";import{BoundingInfo as B}from"./BoundingInfo.js";import{zero as V,union as Q}from"./depthRange.js";import{depthRangeFromScene as k}from"./depthRangeUtils.js";import{RenderOccludedFlag as W}from"./Material.js";import{OffscreenRendering as X}from"./OffscreenRendering.js";import{RenderContext as Y,defaultRenderOccludedMask as z}from"./RenderContext.js";import{splitRenderGeometryChangeSetByMaterial as J,RendererTarget as K}from"./rendererUtils.js";import{setupFeatureDefaults as Z,RenderFeature as $}from"./RenderFeature.js";import{RenderSlot as ee}from"./RenderSlot.js";import{ShadowAccumulator as re}from"./ShadowAccumulator.js";import{ShadowMap as te,SnapshotSlot as se}from"./ShadowMap.js";import ie from"./SliceHelper.js";import{TransparencyPassType as ae}from"./TransparencyPassType.js";import{EdgeView as ne}from"./edgeRendering/EdgeView.js";import{Transparency as he}from"./edgeRendering/interfaces.js";import{MergedRenderer as oe}from"../materials/renderers/MergedRenderer.js";import{AlphaMode as de}from"../shaders/CompositingTechniqueConfiguration.js";import{RendererPerformanceInfo as le,PerformanceCategory as _e}from"../statistics/RendererPerformanceInfo.js";import{RenderState as pe}from"../../../support/RenderState.js";import{PixelFormat as ue,PixelType as ce,ClearBufferBit as me,DepthStencilAttachment as ge}from"../../../webgl/enums.js";class fe{constructor(e,r,s,i,a,n,l,p){this._stage=e,this._techniqueRepository=i,this._rctx=a,this._compositingHelper=n,this._magnifierHelper=l,this._requestRender=p,this._pluginsHas={hudElements:!1,water:!1},this._hasOverlayWater=!1,this.renderOverlay=e=>{},this._isRendering=!1,this._backgroundColor=A(0,0,0,1),this._sliceHelper=new ie,this._state=_(pe.IDLE),this._highQualityTransparencyEnabled=!0,this._terrainTransparency=P.Opaque,this._ssrEnabled=!1,this._hasAnimations=!1,this._animationTimestep=new U,this._reprojectionMatrixVersion=_(0),this._renderHiddenTransparentEdges=()=>{},this._pluginInput=new Map,this._releaseNormals=e=>{e.find((({name:e})=>"normals"===e))?.release()&&this._pluginInput.delete("normals")},this._debugLinearDepth=!1,this.fboCache=new I(a),this._renderStateFeatures=_(Z(!has("disable-feature:high-quality-idle"),e.view.qualityProfile)),this._offscreen=new X(this.fboCache,this._compositingHelper),this.performanceInfo=new le(this._rctx),this._shadowMap=new te(this.fboCache,e.viewingMode),this._highlight=new M({view:e.view}),this._shadowHighlight=new x({view:e.view,viewingMode:e.viewingMode}),this._shadowAccumulator=new re(this.fboCache,i,e,(e=>{const r=this.shadowsEnabled;this._shadowMap.enabled=!0,this._ensureBindParametersCamera(e.camera,e.contentCamera),this._plugins.prepareRender(),this._shadowMap.enabled=r}),((e,r,t)=>{const s=this._stage.view.qualitySettings.maximumPixelRatio;e.shadowMap.start(e.camera,r,t,!0,s),this._renderShadowCascades(w.Shadow,e.shadowMap),e.shadowMap.finish(),e.camera.setGLViewport(this._rctx),this._ensureBindParametersCamera(e.camera,e.contentCamera)}),p),this._ssao=new F({view:this._stage.view}),this._renderContext=new Y(this._rctx,this._offscreen,this._shadowMap,this._sliceHelper),this._nodes=new D(this._renderContext),this._plugins=new L({renderContext:this._renderContext,techniqueRepository:i,textureRepository:s,materialRepository:r,requestRender:p,controller:e,fbos:this.fboCache,isFeatureEnabled:e=>this.isFeatureEnabled(e)}),this.renderPassManager=new O,this._plugins.add(this.renderPassManager),this._smaa=new v({view:this._stage.view}),this._plugins.add(this._smaa),this._blit=new H({opacity:1,alphaMode:de.None}),this._plugins.add(this._blit),this._plugins.add(this._ssao),this._plugins.add(this._highlight),this._plugins.add(this._shadowHighlight),this._handles=[h((()=>this._stage.view.state.camera),(()=>p()),o),h((()=>R.EDGES_SHOW_HIDDEN_TRANSPARENT_EDGES),(e=>{this._renderHiddenTransparentEdges=e?()=>this._renderEdges(he.TRANSPARENT):()=>{},p()}),d),h((()=>this._stage.view.environment.background?.color),(e=>{const r=e?t(e):E;T(this._backgroundColor,r[0]*r[3],r[1]*r[3],r[2]*r[3],r[3]),p()}),o)]}destroy(){this._handles.forEach((e=>e.remove())),this._gpuTimerHandle=s(this._gpuTimerHandle),this._nodes.destroy(),this._offscreen.dispose(),this._shadowMap.dispose(),this._highlight.dispose(),this._shadowAccumulator.dispose(),this._edgeView=i(this._edgeView),this.renderPassManager.dispose(),this._releaseFBOs(),this._disposeOffscreenBuffers(),this.fboCache.destroy(),this._plugins.destroy(),B.prune()}get _bindParameters(){return this._renderContext.bindParameters}updateRenderFeatures(e=null,r=!has("disable-feature:high-quality-idle")){this._renderStateFeatures.value=Z(r,e),this._plugins.renderFeatureChanged(),this._requestRender()}isFeatureEnabled(e,r=this._state.value){return this._renderStateFeatures.value.get(r,e)??!1}setFeatureEnabled(e,r,t){this._renderStateFeatures.mutate((s=>s.set(r,e,t))),this._requestRender()}get _highQualityTransparency(){return this._highQualityTransparencyEnabled||this.isFeatureEnabled($.HighQualityTransparency)}get hasReflections(){return(this._pluginsHas.water||this._hasOverlayWater)&&(this._ssrEnabled||this.isFeatureEnabled($.WaterReflection))}get hasDecorations(){return this._plugins.hasDecorations}get hasHighlights(){return this._plugins.produces(ee.OPAQUE_MATERIAL,w.Highlight)||this._plugins.produces(ee.TRANSPARENT_MATERIAL,w.Highlight)||this._plugins.produces(ee.DRAPED_MATERIAL,w.Highlight)}get _magnifierEnabled(){return this._bindParameters.decorations===q.ON&&this._magnifierHelper.enabled}get fullResolutionAtmosphere(){return this._stage.view.qualitySettings.highResolutionAtmosphere||this.isFeatureEnabled($.HighResolutionAtmosphere)}_releaseFBOs(){this._bindParameters.ssr.lastFrameColor=a(this._bindParameters.ssr.lastFrameColor),this._bindParameters.multipassTerrain.linearDepth=a(this._bindParameters.multipassTerrain.linearDepth),this._bindParameters.multipassGeometry.linearDepth=a(this._bindParameters.multipassGeometry.linearDepth)}_disposeOffscreenBuffers(){this._offscreen.dispose(),this._disposeBindBuffers()}_disposeBindBuffers(){this._shadowMap.disposeOffscreenBuffers(),this._bindParameters.linearDepth=a(this._bindParameters.linearDepth),this._bindParameters.hudVisibility=a(this._bindParameters.hudVisibility)}get updating(){return this._smaa.updating||null!=this._edgeView&&this._edgeView.updating||this._shadowAccumulator.running||this._plugins.updating||!this.isCameraFinal}ensureEdgeView(){if(null==this._edgeView){const e=this._stage.view.resourceController;this._edgeView=new ne({rctx:this._rctx,renderSR:this._stage.view.renderSpatialReference,viewingMode:this._stage.viewingMode,techniqueRepository:this._techniqueRepository,setNeedsRender:()=>this._requestRender(),schedule:Ce(e)}),this._handles.push(h((()=>this._edgeView?.updating),(()=>this._requestRender()),l)),this._requestRender()}return this._edgeView}get edgeView(){return this._edgeView}get isCameraFinal(){return this._reprojectionMatrixVersion.value>=0&&u(this._bindParameters.ssr.reprojectionMatrix,g)}set _reprojectionMatrix(e){r(this._bindParameters.ssr.reprojectionMatrix,e)&&this._reprojectionMatrixVersion.value++}get shadowsEnabled(){return!!this._shadowMap?.enabled}setParameters(e){const{_shadowMap:r,_bindParameters:t}=this;if(void 0!==e.qualitySettings?.reflections&&this._ssrEnabled!==e.qualitySettings.reflections&&(this._ssrEnabled=e.qualitySettings.reflections,this._requestRender()),void 0!==e.shadowMap&&this._shadowMap.enabled!==e.shadowMap&&(this._shadowMap.enabled=e.shadowMap,this._requestRender()),void 0!==e.shadowMapMaxCascades&&r.maxCascades!==e.shadowMapMaxCascades&&(r.maxCascades=e.shadowMapMaxCascades,this._requestRender()),null!=e.environment){null!=e.environment.weather&&(this._bindParameters.weather=e.environment.weather,this._bindParameters.weatherVisible=!!e.weatherVisible);const r="virtual"!==e.environment.lighting.type;t.enableFillLights!==r&&(t.enableFillLights=r,this._requestRender())}void 0!==e.highQualityTransparency&&this._highQualityTransparencyEnabled!==e.highQualityTransparency&&(this._highQualityTransparencyEnabled=e.highQualityTransparency,this._requestRender()),void 0!==e.hasOverlayWater&&this._hasOverlayWater!==e.hasOverlayWater&&(this._hasOverlayWater=e.hasOverlayWater,this._requestRender()),void 0!==e.slicePlane&&this._sliceHelper.plane!==e.slicePlane&&(this._sliceHelper.plane=e.slicePlane,this._requestRender()),void 0!==e.terrainTransparency&&this._terrainTransparency!==e.terrainTransparency&&(this._terrainTransparency=e.terrainTransparency,this._requestRender()),void 0!==e.shadowCastOptions&&this._shadowAccumulator.setOptions(e.shadowCastOptions)}get hasSlicePlane(){return!!this._sliceHelper.plane}get plugins(){return this._plugins}get _hasOITSupport(){return this._rctx.driverTest.floatBufferBlend.result}get _oitEnabled(){return this._highQualityTransparency&&this._hasOITSupport}modify(e,r){this._isRendering&&console.warn("Renderer.modify called while rendering");const{adds:t,removes:s,updates:i}=e;if(0===t.length&&0===s.length&&0===i.length)return;const a=J(e);let n=!1;a.forEach(((t,s)=>{if(r.done)return;let i=this._plugins.getMaterialRenderer(s);if(null==i&&t.adds.length>0){const e=new oe({material:s});e.initializeRenderContext(this._plugins._context),i=e,this._plugins.add(i)}i&&(i.modify(t),0===i.numGeometries&&(n=!0)),t.removes.forEach((r=>e.removes.removeUnordered(r))),t.adds.forEach((r=>e.adds.removeUnordered(r))),t.updates.forEach((r=>e.updates.removeUnordered(r))),r.madeProgress()})),n&&this._plugins.removeEmptyMaterialRenderers(),this._updateHasFlags(),this._requestRender()}_updateHasFlags(){const has=this._pluginsHas;has.hudElements=this._plugins.produces(ee.LINE_CALLOUTS_HUD_DEPTH)||this._plugins.produces(ee.HUD_MATERIAL)||this._plugins.produces(ee.LABEL_MATERIAL),has.water=this._plugins.produces(ee.DRAPED_WATER,w.Normal),this._bindParameters.hasOccludees=this._plugins.hasOccludees}updateAnimation(e){const r=this._hasAnimations;return this._hasAnimations=this._plugins.updateAnimation(e),this._hasAnimations=this._nodes.updateAnimation()||this._hasAnimations,this._hasAnimations!==r&&(this._gpuTimerHandle=r?s(this._gpuTimerHandle):this.performanceInfo.enableGPUPerformanceInfo()),this._hasAnimations}get animationTimestep(){return this._animationTimestep.value}get animationTimeDilation(){return this._animationTimestep.timeDilation}resetAnimation(){this._animationTimestep.clear()}tick(){this.fboCache.clean()}render(e,r,t=K.Default,s=q.ON){this._isRendering=!0,this.performanceInfo.startFrame(),this.fboCache.frameStart(),this._disposeBindBuffers();const i=this._offscreen,{camera:n,contentCamera:h,mode:o,alignPixelEnabled:d}=e;this._state.value=o,this._bindParameters.overlay=this.renderOverlay(r),this.performanceInfo.advance(_e.OVERLAY),this._renderContext.time=r,this._bindParameters.transparencyPassType=ae.NONE,this._bindParameters.alignPixelEnabled=d,this._bindParameters.decorations=s,this._bindParameters.mainColor=this._bindParameters.mainDepth=null;const l=b(this._sliceHelper.plane);s===q.OFF&&(this._sliceHelper.plane=null),n.setGLViewport(this._rctx);const _=i.initializeFrame(n,this._backgroundColor,t);this.hasReflections?this._bindParameters.ssr.lastFrameColor=_:_?.release(),this._ensureBindParametersCamera(n,h),this._plugins.prepareRender(),this.performanceInfo.advance(_e.PREPARE);const p=this._computeDepthRange(n);this._renderShadowMap(n,this._bindParameters.lighting.mainLight.direction,p),this.performanceInfo.advance(_e.SHADOW_MAP),this._ensureBindParametersCamera(n,h);const u=this._plugins.produces(ee.OPAQUE_TERRAIN)&&(this._terrainTransparency===P.Semitransparent||this._terrainTransparency===P.TransparentWithDraped),c=this._highQualityTransparency&&u,m=this._plugins.produces(ee.TRANSPARENT_MATERIAL,w.Color);this._prepareShaders(c,m),this._pluginInput.set("normals",this._renderNormals()),this.performanceInfo.advance(_e.NORMALS),this._renderSSAO(),this.performanceInfo.advance(_e.SSAO),this._renderLinearDepth(),this.performanceInfo.advance(_e.LINEAR_DEPTH),this._renderShadowAccumulation(p,n,h),this.performanceInfo.advance(_e.ACCUMULATED_SHADOWS),this._ensureBindParametersSSR(r),this._renderContext.output=w.Color,i.bindFbo(),this._bindParameters.mainColor=i.colorTexture,this._bindParameters.mainDepth=i.depthTexture,this._renderOpaqueGeometry(),this._offscreen.updateColor((e=>this._invokeRenderNodes(e)),"opaque-color"),this._plugins.render(ee.ENVIRONMENT_OPAQUE),this.performanceInfo.advance(_e.OPAQUE),this.fboCache.debugCallback&&this.fboCache.debugCallback("opaque-color",this._offscreen.color.fbo),this._renderTerrainLinearDepth(c),this._setMultipassTerrain(c),this._renderEdges(he.OPAQUE),this.performanceInfo.advance(_e.OPAQUE_EDGES),i.bindFbo(),this._plugins.render(ee.VOXEL),this.performanceInfo.advance(_e.VOXEL),this._renderHiddenTransparentEdges(),m&&(this._oitEnabled?this._renderOITPass(Te.Geometry):this._renderTransparentMaterial()),this._offscreen.updateColor((e=>this._invokeRenderNodes(e)),"transparent-color"),this.performanceInfo.advance(_e.TRANSPARENT);const g=this._renderGeometryLinearDepth(c);this._renderHUDVisibility(g),c||this._plugins.render(ee.LINE_CALLOUTS),this.performanceInfo.advance(_e.HUD_VISIBILITY);const f=t===K.ObjectAndLayerID?this._renderObjectAndLayerIdColor():null;this.performanceInfo.advance(_e.OBJECT_AND_LAYER_ID_COLOR),this._renderEdges(he.TRANSPARENT,g),g?.release(),this.performanceInfo.advance(_e.TRANSPARENT_EDGES);const T=u?this._renderTransparentTerrain():null;T&&this._bindParameters.hudVisibility&&(c?this._renderLineCallouts(y.Occluded):i.compositeToHUDVisibility(this._bindParameters,T.getTexture()),this._renderHUD(y.Occluded,i.color),this.performanceInfo.advance(_e.HUD_OCCLUDED)),this.performanceInfo.advance(_e.TRANSPARENT_TERRAIN),this._setTerrainCulling(!1),T&&(i.compositeToFramebuffer(this._bindParameters,T.getTexture(),de.PremultipliedAlpha,1),T.release(),c&&(this._renderEdges(he.OPAQUE),this.performanceInfo.advance(_e.OPAQUE_EDGES),m&&(this._oitEnabled?this._renderOITPass(Te.Geometry):this._renderTransparentMaterial()),this.performanceInfo.advance(_e.TRANSPARENT),this._renderEdges(he.TRANSPARENT),this.performanceInfo.advance(_e.TRANSPARENT_EDGES))),this._bindParameters.ssao=a(this._bindParameters.ssao),c&&this._renderLineCallouts(y.NotOccluded),this._setMultipassEnabled(!1),this._shadowAccumulator.render(this._bindParameters),i.bindFbo(),this._plugins.render(ee.TRANSPARENT_DEPTH_WRITE_DISABLED_MATERIAL),this._plugins.render(ee.ENVIRONMENT_TRANSPARENT),this.performanceInfo.advance(_e.ENVIRONMENT),this._renderLaserlines(),this.performanceInfo.advance(_e.LASER_LINES),this._renderOccluded(),this.performanceInfo.advance(_e.OCCLUDED);let A=this._renderHighlightPrepass();A&&this._renderShadowHighlights(A,this._bindParameters);const E=this._magnifierEnabled&&t===K.Default?this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"magnifier"):null,R=t!==K.Default?this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"screenshot"):null,S=this._renderComposite(E??R,A)??R;return this.performanceInfo.advance(_e.ANTIALIASING),this._renderHUD(y.NotOccluded,S),this.performanceInfo.advance(_e.HUD),A&&(this._renderHighlights(S,A,this._bindParameters),A=a(A)),this.performanceInfo.advance(_e.HIGHLIGHTS),this._magnifierEnabled&&this._magnifierHelper.render(this._rctx,this._bindParameters),S!==R&&(this._rctx.bindFramebuffer(R?.fbo),this._compositingHelper.composite(this._bindParameters,E?.getTexture(),de.None)),t===K.Default&&E?.release(),this.onPostRender&&this.onPostRender(),this._releaseFBOs(),this._offscreen.releaseBuffers(),this._renderContext.lastFrameCamera.copyFrom(this._bindParameters.camera),this._sliceHelper.plane=l,this._isRendering=!1,this.fboCache.frameEnd(),this.performanceInfo.finishFrame(),t!==K.Default&&(this._releaseFBOs(),this._disposeOffscreenBuffers()),{screen:R,oid:f}}_prepareShaders(e,r){this._renderContext.output=w.Color,this._prepareOpaqueGeometry(),this._setMultipassTerrain(e),this._plugins.prepare(ee.TRANSPARENT_TERRAIN),this._setMultipassTerrain(!1),e||this._plugins.prepare(ee.LINE_CALLOUTS),r&&this._prepareTransparencySlots(),this._plugins.prepare(ee.TRANSPARENT_DEPTH_WRITE_DISABLED_MATERIAL),this._plugins.prepare(ee.ENVIRONMENT_TRANSPARENT),this._plugins.prepare(ee.LASERLINES),this._rctx.gl.flush()}_renderObjectAndLayerIdColor(){if(!has("enable-feature:objectAndLayerId-rendering"))return;const e=this._renderContext.output,r=this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"oid");return r.acquireDepth(S.DEPTH_STENCIL_TEXTURE),this._rctx.bindFramebuffer(r.fbo),this.fboCache.rctx.clearFramebuffer([0,0,0,0],!0,!0),this._renderAllGeometry(w.ObjectAndLayerIdColor),this._rctx.bindFramebuffer(r.fbo),this.fboCache.rctx.clearFramebuffer(void 0,!0,!0),this._bindParameters.hudRenderStyle=y.NotOccluded,this._plugins.render(ee.HUD_MATERIAL),this._renderContext.output=e,r}finish(e){this._hasAnimations||this._animationTimestep.clear();const r=this.performanceInfo.gpuSamplingEnabled,t=e===j.BACKGROUND;if(t||r){const e=t?this.performanceInfo.elapsedTime:0,s=r?this.performanceInfo.totalGPUTimeSampler.last:this._rctx.gl.getError(),i=Math.max(e,s);this._animationTimestep.frame(i,t)}}readDepthPixels(e,r,t){const s=this._bindParameters.linearDepth?.fbo;if(s?.colorTexture)return void s.readPixels(r[0],r[1],r[2],r[3],ue.RGBA,ce.UNSIGNED_BYTE,t);const i=this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"depth").acquireDepth(S.DEPTH16_BUFFER);this._rctx.bindFramebuffer(i.fbo),this._ensureBindParametersCamera(e,e),this._bindParameters.camera.setGLViewport(this._rctx),this._rctx.setClearColor(0,0,0,0);const a=me.COLOR_BUFFER_BIT|me.DEPTH_BUFFER_BIT|me.STENCIL_BUFFER_BIT;this._rctx.clearSafe(a),this._renderAllGeometry(w.LinearDepth),i.fbo.readPixels(r[0],r[1],r[2],r[3],ue.RGBA,ce.UNSIGNED_BYTE,t),i.release()}readHUDVisibility(e,r,t,s,i){this._bindParameters.hudVisibility?.fbo.readPixels(e,r,t,s,ue.RGBA,ce.UNSIGNED_BYTE,i)}readAccumulatedShadow(e){return this._shadowAccumulator.readAccumulatedShadow(e[0],e[1])}_setMultipassTerrain(e){this._setMultipassEnabled(e),this._setTerrainCulling(e)}_setMultipassEnabled(e){this._bindParameters.multipassEnabled=e}_setTerrainCulling(e){this._bindParameters.multipassTerrain.cullAboveGround=e}_renderEdges(e,r){const t=this._edgeView;if(t?.shouldRender()){const{width:s,height:i,depth:a}=this._offscreen,n=this.fboCache.acquire(s,i,"edges"),h=()=>t.render(this._bindParameters,e);this._offscreen.renderToTargets(h,n,r??a,Ee),this._offscreen.compositeToFramebuffer(this._bindParameters,n.getTexture(),de.Alpha,1),n.release()}}_renderShadowMap(e,r,t){const s=this._shadowMap;s.enabled&&(s.start(e,r,t,this.isFeatureEnabled($.HighResolutionShadows),this._stage.view.qualitySettings.maximumPixelRatio),this._shadowHighlight.updateParameters(e,r),this._needsShadowHighlight?(this._renderShadowCascades(w.ShadowHighlight,this._shadowMap),s.moveSnapshot(se.Highlight),this._renderShadowCascades(w.ShadowExcludeHighlight,this._shadowMap),s.copySnapshot(se.ExcludeHighlight),this._renderShadowCascades(w.ShadowHighlight,this._shadowMap)):this._renderShadowCascades(w.Shadow),s.finish(),e.setGLViewport(this._rctx))}_renderShadowCascades(e,r=this._shadowMap){for(const t of r.cascades)t.camera.setGLViewport(this._rctx),this._ensureBindParametersCamera(t.camera,t.camera),this._renderAllGeometry(e)}get _needsLinearDepth(){return this._plugins.consumes(w.LinearDepth)||this.hasReflections||this._needsShadowHighlight||this._needsShadowCast||this._debugLinearDepth}_renderLinearDepth(){this._needsLinearDepth?(this._bindParameters.linearDepth=this._offscreen.renderToCachedFBO(this._bindParameters.linearDepth,"linear-depth",(()=>this._renderAllGeometry(w.LinearDepth)),[0,0,0,0],C.RGBA,S.DEPTH_STENCIL_TEXTURE),this._bindParameters.linearDepth.detachDepth()):this._bindParameters.linearDepth=a(this._bindParameters.linearDepth)}_renderTerrainLinearDepth(e){if(e){const e=this._renderContext.output;this._renderContext.output=w.LinearDepth,this._bindParameters.multipassTerrain.linearDepth=this._offscreen.renderToCachedFBO(this._bindParameters.multipassTerrain.linearDepth,"terrain depth",(()=>this._renderTransparentTerrain()),[-1e10,-1e10,-1e10,1]),this._bindParameters.multipassTerrain.linearDepth.detachDepth(),this._renderContext.output=e}else this._bindParameters.multipassTerrain.linearDepth=a(this._bindParameters.multipassTerrain.linearDepth)}_renderGeometryLinearDepth(e){if(!e)return void(this._bindParameters.multipassGeometry.linearDepth=a(this._bindParameters.multipassGeometry.linearDepth));const r=this._renderContext.output;this._bindParameters.multipassGeometry.linearDepth=this._offscreen.renderToCachedFBO(this._bindParameters.multipassGeometry.linearDepth,"geometry depth",(()=>this._renderOpaqueGeometryAndTransparentMaterial(w.LinearDepth)),[1,1,1,1]),this._renderContext.output=r;const t=this._bindParameters.multipassGeometry.linearDepth.getAttachment(ge);return t?.retain(),this._bindParameters.multipassGeometry.linearDepth.detachDepth(),t}get _needsDepthRange(){return this._shadowMap.enabled||this._needsShadowCast}_computeDepthRange(e){if(!this._needsDepthRange)return V;const r=k(e,this._plugins.plugins,this._stage.layers);return Q(r,this._plugins.queryDepthRange(e)),r.near=Math.max(e.near,r.near),r.far=Math.min(e.far,r.far),r}_renderNormals(){const e=this._plugins.produces(ee.SSAO),r=this._nodes.require("normals");let t=(e?1:0)+r+(e||r?this._nodes.optional("normals"):0);if(0===t)return;const s=this._offscreen.renderToCachedFBO(null,"normals",(()=>this._renderGeometryForSSAO(w.Normal)),[0,0,0,0],C.RGBA,S.DEPTH_STENCIL_TEXTURE);for(;--t>0;)s.retain();return s}_renderSSAO(){const e=this._pluginInput.get("normals");this._plugins.produces(ee.SSAO)&&e&&(this._bindParameters.ssao=this._plugins.render(ee.SSAO,this._pluginInput),e.detachDepth(),e.release()&&this._pluginInput.delete("normals"))}_renderAllGeometry(e){this._renderContext.output=e,this._plugins.prepare(ee.TRANSPARENT_TERRAIN),this._renderOpaqueGeometryAndTransparentMaterial(e),this._renderTransparentTerrain()}_renderOpaqueGeometryAndTransparentMaterial(e){this._renderContext.output=e,this._plugins.prepare(ee.TRANSPARENT_MATERIAL),this._plugins.prepare(ee.TRANSPARENT_NO_SSAO_DEPTH),this._renderOpaqueGeometry(),this._renderTransparentMaterial()}_renderGeometryForSSAO(e){this._renderContext.output=e,this._plugins.render(ee.INTEGRATED_MESH),this._plugins.render(ee.OPAQUE_TERRAIN),this._plugins.render(ee.OPAQUE_MATERIAL),this._plugins.render(ee.TRANSPARENT_MATERIAL),this._renderTransparentTerrain()}_prepareOpaqueGeometry(){this._plugins.prepare(ee.INTEGRATED_MESH),this._plugins.prepare(ee.OPAQUE_TERRAIN),this._plugins.prepare(ee.OPAQUE_MATERIAL),this._plugins.prepare(ee.OPAQUE_NO_SSAO_DEPTH),this._plugins.prepare(ee.ENVIRONMENT_OPAQUE)}_renderOpaqueGeometry(){this._plugins.render(ee.INTEGRATED_MESH),this._plugins.render(ee.OPAQUE_TERRAIN),this._plugins.render(ee.OPAQUE_MATERIAL),this._plugins.render(ee.OPAQUE_NO_SSAO_DEPTH)}_renderTransparentMaterial(){this._plugins.render(ee.TRANSPARENT_MATERIAL),this._plugins.render(ee.TRANSPARENT_NO_SSAO_DEPTH)}_renderTransparentTerrain(){if(!this._plugins.produces(ee.TRANSPARENT_TERRAIN))return;const e=()=>this._plugins.render(ee.TRANSPARENT_TERRAIN,null);if(this._renderContext.output!==w.Color)return void e();const{width:r,height:t,depth:s}=this._offscreen,i=this.fboCache.acquire(r,t,"transparent terrain");return this._offscreen.renderToTargets(e,i,s,[0,0,0,0]),i}_renderHUDVisibility(e){this._plugins.produces(ee.OCCLUSION_PIXELS)?(this._bindParameters.hudVisibility=this._offscreen.renderHUDVisibility(this._bindParameters.hudVisibility,(()=>this._plugins.render(ee.OCCLUSION_PIXELS)),e),this._offscreen.bindFbo()):this._bindParameters.hudVisibility=a(this._bindParameters.hudVisibility)}_renderLineCallouts(e){if(this._bindParameters.hudRenderStyle=e,e===y.Occluded){const e=()=>{this._plugins.render(ee.LINE_CALLOUTS)},{width:r,height:t,color:s}=this._offscreen,i=this.fboCache.acquireDepth(S.DEPTH16_BUFFER,r,t,"line callouts");this._offscreen.renderToTargets(e,s,i,void 0,!0,!0),i.release()}else this._plugins.render(ee.LINE_CALLOUTS)}_renderLaserlines(){if(this._plugins.render(ee.LASERLINES),this._plugins.produces(ee.LASERLINES_CONTRAST_CONTROL)){const e=this._offscreen,{width:r,height:t,depth:s}=e,i=this.fboCache.acquire(r,t,"laser lines"),a=()=>this._plugins.render(ee.LASERLINES_CONTRAST_CONTROL);e.renderToTargets(a,i,s,Ee),e.compositeToFramebuffer(this._bindParameters,i.getTexture(),de.PremultipliedAlpha,1),i.release()}}_renderHUD(e,r){if(this._pluginsHas.hudElements)if(this._oitEnabled){const t=this._renderOITPass(Te.HUD,e);this._rctx.bindFramebuffer(r?.fbo),this._compositingHelper.composite(this._bindParameters,t.getTexture(),de.PremultipliedAlpha),t.release()}else if(e===y.Occluded){this._renderContext.output=w.Color;const r=()=>this._renderHUDElements(e),{width:t,height:s,color:i}=this._offscreen,a=this.fboCache.acquireDepth(S.DEPTH16_BUFFER,t,s,"hud");this._offscreen.renderToTargets(r,i,a,void 0,!0,!0),a.release()}else this._renderContext.output=w.Color,this._rctx.bindFramebuffer(null),r?.acquireDepth(S.DEPTH16_BUFFER),this._rctx.bindFramebuffer(r?.fbo),this._renderHUDElements(e),r?.detachDepth()}_renderHUDElements(e){this._bindParameters.hudRenderStyle=e,this._plugins.prepare(ee.LINE_CALLOUTS_HUD_DEPTH),this._plugins.prepare(ee.HUD_MATERIAL),this._plugins.prepare(ee.LABEL_MATERIAL),this._plugins.render(ee.LINE_CALLOUTS_HUD_DEPTH),this._plugins.render(ee.HUD_MATERIAL),this._plugins.render(ee.LABEL_MATERIAL)}get _needsShadowHighlight(){return this._shadowMap.enabled&&this._plugins.produces(ee.SHADOW_HIGHLIGHT)&&this._plugins.produces(ee.OPAQUE_MATERIAL,w.ShadowHighlight)}_renderHighlightPrepass(){if(!this.hasHighlights)return;const e=()=>{this._renderAllGeometry(w.Highlight),this._rctx.clearSafe(me.DEPTH_BUFFER_BIT),this._renderHUDElements(y.Both)},r=this._offscreen.renderToCachedFBO(null,"highlights",e,[0,0,0,0],C.RGBA4,S.DEPTH_STENCIL_TEXTURE);return r.detachDepth(),r}_renderShadowHighlights(e,r){this.hasHighlights&&r.decorations!==q.OFF&&this._needsShadowHighlight&&this._offscreen.updateColor((r=>(this._pluginInput.set("highlights",e),this._plugins.render(ee.SHADOW_HIGHLIGHT,this._pluginInput,r),r)),"transparent-color")}_renderHighlights(e,r,t){this.hasHighlights&&t.decorations!==q.OFF&&this._plugins.produces(ee.HIGHLIGHT)&&(this._pluginInput.set("highlights",r),this._plugins.render(ee.HIGHLIGHT,this._pluginInput,e))}get _needsShadowCast(){return this._shadowAccumulator.isAccumulating}_renderShadowAccumulation(e,r,t){this._needsShadowCast&&this._bindParameters.linearDepth?.getTexture()&&this._shadowAccumulator.renderAccumulation(this._bindParameters.linearDepth,e,r,t)}_prepareTransparencySlots(){this._renderContext.output=w.Alpha,this._bindParameters.transparencyPassType=ae.Alpha,this._plugins.prepare(ee.TRANSPARENT_MATERIAL),this._renderContext.output=w.Color,this._bindParameters.transparencyPassType=ae.Color,this._plugins.prepare(ee.TRANSPARENT_MATERIAL),this._bindParameters.transparencyPassType=ae.FrontFace,this._plugins.prepare(ee.TRANSPARENT_MATERIAL),this._bindParameters.transparencyPassType=ae.NONE}_renderOITPass(e,r=y.Both){const t=e===Te.HUD,s=t?this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"oit hud composite"):null,i=t?()=>this._renderHUDElements(r):()=>this._renderTransparentMaterial(),a=this._renderContext.output;this._renderContext.output=w.Alpha,this._bindParameters.transparencyPassType=ae.Alpha;const n=this._offscreen.renderOITPass(i,ae.Alpha,t);this._renderContext.output=w.Color,this._bindParameters.transparencyPassType=ae.Color;const h=this._offscreen.renderOITPass(i,ae.Color,t);this._bindParameters.transparencyPassType=ae.FrontFace;const o=this._offscreen.renderOITPass(i,ae.FrontFace,t);return this._offscreen.compositeTransparentOntoOpaque(this._bindParameters,h,n,o,s),s?.detachDepth(),o.release(),h.release(),n.release(),this._bindParameters.transparencyPassType=ae.NONE,this._renderContext.output=a,s}_renderOccluded(){let e=0;be.clear(),this._plugins.plugins.forAll((r=>{if(!r.materialReference)return;r.queryRenderOccludedState(W.OccludeAndTransparentStencil)&&(e|=W.OccludeAndTransparentStencil,be.push(r))}));const r=this._offscreen,t=(t,s,i,a,n)=>{if(0==(e&s))return;const{width:h,height:o,depth:d}=r,l=this.fboCache.acquire(h,o,"tmp color");r.renderToTargets(i,l,d,[0,0,0,0],a,n),r.compositeToFramebuffer(this._bindParameters,l.getTexture(),de.PremultipliedAlpha,t),l.release()},s=(e,r)=>{this._bindParameters.slot=e,r.forAll((e=>{if(N(e)){const r=e.prepareTechnique(this._renderContext);r&&e.renderNode(this._renderContext,r)}}))};0!==be.length&&(s(ee.OCCLUDER_MATERIAL,be),t(.5,W.OccludeAndTransparentStencil,(()=>s(ee.TRANSPARENT_OCCLUDER_MATERIAL,be)),!1,!1)),be.clear(),this._plugins.plugins.forAll((r=>{if(!r.materialReference)return;const t=r.queryRenderOccludedState(W.OccludeAndTransparent),s=r.queryRenderOccludedState(W.Transparent),i=r.queryRenderOccludedState(W.Opaque);(t||s||i)&&(e|=t?W.OccludeAndTransparent:s?W.Transparent:W.Opaque,be.push(r))}));const i=this._plugins.renderOccludedFlags;if(e|=i,!e)return;const a=e=>{this._renderContext.renderOccludedMask=e,i>W.Occlude&&this._plugins.render(ee.OCCLUDED_TERRAIN),s(ee.OPAQUE_MATERIAL,be),s(ee.TRANSPARENT_MATERIAL,be),s(ee.TRANSPARENT_DEPTH_WRITE_DISABLED_MATERIAL,be),this._renderContext.renderOccludedMask=z};this._renderContext.output=w.Color,t(.5,W.OccludeAndTransparent,(()=>a(W.OccludeAndTransparent)),!0,G.OutlineVisualElementMask),t(.5,W.Transparent,(()=>a(W.Transparent)),!0,G.OutlineVisualElementMask),t(1,W.Opaque,(()=>a(W.Opaque)),!0,G.OutlineVisualElementMask),be.clear()}_invokeRenderNodes(e){return this._nodes.render(e,this._pluginInput,this._releaseNormals)}_renderComposite(e,r){this._offscreen.updateColor((e=>(this._pluginInput.set("highlights",r),e=this._nodes.render(e,this._pluginInput,this._releaseNormals),this._pluginInput.set(e.name,e),this._pluginInput.delete("highlights"),e)),"composite-color");const t=this._plugins.produces(ee.ANTIALIASING);return this._plugins.render(t?ee.ANTIALIASING:ee.BLIT,this._pluginInput,e)}_ensureBindParametersCamera(e,r){this._bindParameters.camera=e,this._bindParameters.contentCamera=r}_ensureBindParametersSSR(e){if(this._bindParameters.ssr.lastFrameColor){null==this._ssrEnableTime&&(this._ssrEnableTime=e),this._renderContext.lastFrameCamera.equals(this._bindParameters.camera)?this._reprojectionMatrix=g:(c(Pe,this._bindParameters.camera.viewMatrix),c(Re,this._bindParameters.camera.projectionMatrix),m(Se,Pe,Re),m(Se,this._renderContext.lastFrameCamera.viewMatrix,Se),m(Se,this._renderContext.lastFrameCamera.projectionMatrix,Se),this._reprojectionMatrix=Se);const r=this._stage.view.qualitySettings.fadeDuration;this._bindParameters.ssr.fadeFactor=r>0?Math.min(r,e-this._ssrEnableTime)/r:1,this._bindParameters.ssr.fadeFactor<1&&this._requestRender()}else this._reprojectionMatrix=g,this._ssrEnableTime=null}addRenderNode(e){this._nodes.add(e),this._requestRender()}removeRenderNode(e){this._nodes.remove(e),this._requestRender()}get usedMemory(){return{fbos:this.fboCache.usedMemory,plugins:this._plugins.usedMemory,edges:this.edgeView?.usedMemory??0}}get test(){return{offscreen:this._offscreen,shadowMap:this._shadowMap,highlight:this._highlight,lighting:this._bindParameters.lighting,renderPlugins:this._plugins,shadowAccumulator:this._shadowAccumulator,weatherIsFading:this._bindParameters.cloudsFade.isFading,resetRenderStateFeatures:()=>{this._renderStateFeatures.value=Z(),this._plugins.renderFeatureChanged(),this._requestRender()},getFramebufferTexture:e=>{switch(e){case Ae.Color:return this._offscreen.colorTexture;case Ae.LinearDepth:return this._bindParameters.linearDepth?.getTexture();case Ae.ShadowMap:return this._shadowMap.depthTexture;case Ae.HudVisibility:return this._bindParameters.hudVisibility?.getTexture()}},debugLinearDepth:e=>{this._debugLinearDepth=e,this._requestRender()}}}}var Te,Ae;e([p({readOnly:!0})],fe.prototype,"fullResolutionAtmosphere",null),e([p()],fe.prototype,"_smaa",void 0),e([p()],fe.prototype,"_blit",void 0),e([p()],fe.prototype,"_edgeView",void 0),e([p()],fe.prototype,"updating",null),function(e){e[e.Geometry=0]="Geometry",e[e.HUD=1]="HUD"}(Te||(Te={})),function(e){e[e.Color=0]="Color",e[e.LinearDepth=1]="LinearDepth",e[e.ShadowMap=2]="ShadowMap",e[e.HudVisibility=3]="HudVisibility"}(Ae||(Ae={}));const Ee=[0,0,0,0],be=new n,Re=f(),Pe=f(),Se=f();function Ce(e){return r=>e.immediate.schedule(r)}export{Ae as FramebufferId,fe as Renderer};
5
+ import{_ as e}from"../../../../chunks/tslib.es6.js";import{update as r}from"../../../../core/arrayUtils.js";import{unitRGBAFromColor as t}from"../../../../core/colorUtils.js";import has from"../../../../core/has.js";import{removeMaybe as s,destroyMaybe as i,releaseMaybe as a}from"../../../../core/maybe.js";import n from"../../../../core/PooledArray.js";import{watch as h,syncAndInitial as o,initial as d,sync as l}from"../../../../core/reactiveUtils.js";import{signal as _}from"../../../../core/signal.js";import{property as p}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/Logger.js";import"../../../../core/accessorSupport/interfaces.js";import"../../../../core/accessorSupport/tracking/Flags.js";import"../../../../core/Warning.js";import"../../../../core/Error.js";import{equals as u,invert as c,multiply as m}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{IDENTITY as g,create as f}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{s as T}from"../../../../chunks/vec42.js";import{fromValues as A,ZEROS as E}from"../../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{a as b}from"../../../../chunks/boundedPlane.js";import{debugFlags as R}from"../../support/debugFlags.js";import{TransparencyMode as P}from"../../terrain/TerrainRenderer.js";import{DepthFormat as S,ColorFormat as C}from"../../webgl/formats.js";import{FBOCache as I}from"../core/FBOCache.js";import{RenderPassManager as O}from"../core/renderPasses/RenderPassManager.js";import{ShaderOutput as w}from"../core/shaderLibrary/ShaderOutput.js";import{HUDRenderStyle as y}from"../core/shaderLibrary/hud/HUDRenderStyle.js";import{RenderNodes as D}from"../effects/RenderNodes.js";import{isPrepareRenderPlugin as N}from"../effects/RenderPlugin.js";import{RenderPluginManager as L}from"../effects/RenderPluginManager.js";import{Blit as H}from"../effects/blit/Blit.js";import{Highlight as M}from"../effects/highlight/Highlight.js";import{ShadowHighlight as x}from"../effects/highlight/ShadowHighlight.js";import{SMAA as v}from"../effects/smaa/SMAA.js";import{SSAO as F}from"../effects/ssao/SSAO.js";import{AnimationTimeStep as U}from"./AnimationTimeStep.js";import{Decorations as q,RenderRequestType as j,StencilBits as G}from"./basicInterfaces.js";import{BoundingInfo as B}from"./BoundingInfo.js";import{zero as V,union as Q}from"./depthRange.js";import{depthRangeFromScene as k}from"./depthRangeUtils.js";import{RenderOccludedFlag as W}from"./Material.js";import{OffscreenRendering as X}from"./OffscreenRendering.js";import{RenderContext as Y,defaultRenderOccludedMask as z}from"./RenderContext.js";import{splitRenderGeometryChangeSetByMaterial as J,RendererTarget as K}from"./rendererUtils.js";import{setupFeatureDefaults as Z,RenderFeature as $}from"./RenderFeature.js";import{RenderSlot as ee}from"./RenderSlot.js";import{ShadowAccumulator as re}from"./ShadowAccumulator.js";import{ShadowMap as te,SnapshotSlot as se}from"./ShadowMap.js";import ie from"./SliceHelper.js";import{TransparencyPassType as ae}from"./TransparencyPassType.js";import{EdgeView as ne}from"./edgeRendering/EdgeView.js";import{Transparency as he}from"./edgeRendering/interfaces.js";import{MergedRenderer as oe}from"../materials/renderers/MergedRenderer.js";import{AlphaMode as de}from"../shaders/CompositingTechniqueConfiguration.js";import{RendererPerformanceInfo as le,PerformanceCategory as _e}from"../statistics/RendererPerformanceInfo.js";import{RenderState as pe}from"../../../support/RenderState.js";import{PixelFormat as ue,PixelType as ce,ClearBufferBit as me,DepthStencilAttachment as ge}from"../../../webgl/enums.js";class fe{constructor(e,r,s,i,a,n,l,p){this._stage=e,this._techniqueRepository=i,this._rctx=a,this._compositingHelper=n,this._magnifierHelper=l,this._requestRender=p,this._pluginsHas={hudElements:!1,water:!1},this._hasOverlayWater=!1,this.renderOverlay=e=>{},this._isRendering=!1,this._backgroundColor=A(0,0,0,1),this._sliceHelper=new ie,this._state=_(pe.IDLE),this._highQualityTransparencyEnabled=!0,this._terrainTransparency=P.Opaque,this._ssrEnabled=!1,this._hasAnimations=!1,this._animationTimestep=new U,this._reprojectionMatrixVersion=_(0),this._renderHiddenTransparentEdges=()=>{},this._pluginInput=new Map,this._releaseNormals=e=>{e.find((({name:e})=>"normals"===e))?.release()&&this._pluginInput.delete("normals")},this._debugLinearDepth=!1,this.fboCache=new I(a),this._renderStateFeatures=_(Z(!has("disable-feature:high-quality-idle"),e.view.qualityProfile)),this._offscreen=new X(this.fboCache,this._compositingHelper),this.performanceInfo=new le(this._rctx),this._shadowMap=new te(this.fboCache,e.viewingMode),this._highlight=new M({view:e.view}),this._shadowHighlight=new x({view:e.view,viewingMode:e.viewingMode}),this._shadowAccumulator=new re(this.fboCache,i,e,(e=>{const r=this.shadowsEnabled;this._shadowMap.enabled=!0,this._ensureBindParametersCamera(e.camera,e.contentCamera),this._plugins.prepareRender(),this._shadowMap.enabled=r}),((e,r,t)=>{const s=this._stage.view.qualitySettings.maximumPixelRatio;e.shadowMap.start(e.camera,r,t,!0,s),this._renderShadowCascades(w.Shadow,e.shadowMap),e.shadowMap.finish(),e.camera.setGLViewport(this._rctx),this._ensureBindParametersCamera(e.camera,e.contentCamera)}),p),this._ssao=new F({view:this._stage.view}),this._renderContext=new Y(this._rctx,this._offscreen,this._shadowMap,this._sliceHelper),this._nodes=new D(this._renderContext),this._plugins=new L({renderContext:this._renderContext,techniqueRepository:i,textureRepository:s,materialRepository:r,requestRender:p,controller:e,fbos:this.fboCache,isFeatureEnabled:e=>this.isFeatureEnabled(e)}),this.renderPassManager=new O,this._plugins.add(this.renderPassManager),this._smaa=new v({view:this._stage.view}),this._plugins.add(this._smaa),this._blit=new H({opacity:1,alphaMode:de.None}),this._plugins.add(this._blit),this._plugins.add(this._ssao),this._plugins.add(this._highlight),this._plugins.add(this._shadowHighlight),this._handles=[h((()=>this._stage.view.state.camera),(()=>p()),o),h((()=>R.EDGES_SHOW_HIDDEN_TRANSPARENT_EDGES),(e=>{this._renderHiddenTransparentEdges=e?()=>this._renderEdges(he.TRANSPARENT):()=>{},p()}),d),h((()=>this._stage.view.environment.background?.color),(e=>{const r=e?t(e):E;T(this._backgroundColor,r[0]*r[3],r[1]*r[3],r[2]*r[3],r[3]),p()}),o)]}destroy(){this._handles.forEach((e=>e.remove())),this._gpuTimerHandle=s(this._gpuTimerHandle),this._nodes.destroy(),this._offscreen.dispose(),this._shadowMap.dispose(),this._highlight.dispose(),this._shadowAccumulator.dispose(),this._edgeView=i(this._edgeView),this.renderPassManager.dispose(),this._releaseFBOs(),this._disposeOffscreenBuffers(),this.fboCache.destroy(),this._plugins.destroy(),B.prune()}get _bindParameters(){return this._renderContext.bindParameters}updateRenderFeatures(e=null,r=!has("disable-feature:high-quality-idle")){this._renderStateFeatures.value=Z(r,e),this._plugins.renderFeatureChanged(),this._requestRender()}isFeatureEnabled(e,r=this._state.value){return this._renderStateFeatures.value.get(r,e)??!1}setFeatureEnabled(e,r,t){this._renderStateFeatures.mutate((s=>s.set(r,e,t))),this._requestRender()}get _highQualityTransparency(){return this._highQualityTransparencyEnabled||this.isFeatureEnabled($.HighQualityTransparency)}get hasReflections(){return(this._pluginsHas.water||this._hasOverlayWater)&&(this._ssrEnabled||this.isFeatureEnabled($.WaterReflection))}get hasDecorations(){return this._plugins.hasDecorations}get hasHighlights(){return this._plugins.produces(ee.OPAQUE_MATERIAL,w.Highlight)||this._plugins.produces(ee.TRANSPARENT_MATERIAL,w.Highlight)||this._plugins.produces(ee.DRAPED_MATERIAL,w.Highlight)}get _magnifierEnabled(){return this._bindParameters.decorations===q.ON&&this._magnifierHelper.enabled}get fullResolutionAtmosphere(){return this._stage.view.qualitySettings.highResolutionAtmosphere||this.isFeatureEnabled($.HighResolutionAtmosphere)}_releaseFBOs(){this._bindParameters.ssr.lastFrameColor=a(this._bindParameters.ssr.lastFrameColor),this._bindParameters.multipassTerrain.linearDepth=a(this._bindParameters.multipassTerrain.linearDepth),this._bindParameters.multipassGeometry.linearDepth=a(this._bindParameters.multipassGeometry.linearDepth)}_disposeOffscreenBuffers(){this._offscreen.dispose(),this._disposeBindBuffers()}_disposeBindBuffers(){this._shadowMap.disposeOffscreenBuffers(),this._bindParameters.linearDepth=a(this._bindParameters.linearDepth),this._bindParameters.hudVisibility=a(this._bindParameters.hudVisibility)}get updating(){return this._smaa.updating||null!=this._edgeView&&this._edgeView.updating||this._shadowAccumulator.running||this._plugins.updating||!this.isCameraFinal}ensureEdgeView(){if(null==this._edgeView){const e=this._stage.view.resourceController;this._edgeView=new ne({rctx:this._rctx,renderSR:this._stage.view.renderSpatialReference,viewingMode:this._stage.viewingMode,techniqueRepository:this._techniqueRepository,setNeedsRender:()=>this._requestRender(),schedule:Ce(e)}),this._handles.push(h((()=>this._edgeView?.updating),(()=>this._requestRender()),l)),this._requestRender()}return this._edgeView}get edgeView(){return this._edgeView}get isCameraFinal(){return this._reprojectionMatrixVersion.value>=0&&u(this._bindParameters.ssr.reprojectionMatrix,g)}set _reprojectionMatrix(e){r(this._bindParameters.ssr.reprojectionMatrix,e)&&this._reprojectionMatrixVersion.value++}get shadowsEnabled(){return!!this._shadowMap?.enabled}setParameters(e){const{_shadowMap:r,_bindParameters:t}=this;if(void 0!==e.qualitySettings?.reflections&&this._ssrEnabled!==e.qualitySettings.reflections&&(this._ssrEnabled=e.qualitySettings.reflections,this._requestRender()),void 0!==e.shadowMap&&this._shadowMap.enabled!==e.shadowMap&&(this._shadowMap.enabled=e.shadowMap,this._requestRender()),void 0!==e.shadowMapMaxCascades&&r.maxCascades!==e.shadowMapMaxCascades&&(r.maxCascades=e.shadowMapMaxCascades,this._requestRender()),null!=e.environment){null!=e.environment.weather&&(this._bindParameters.weather=e.environment.weather,this._bindParameters.weatherVisible=!!e.weatherVisible);const r="virtual"!==e.environment.lighting.type;t.enableFillLights!==r&&(t.enableFillLights=r,this._requestRender())}void 0!==e.highQualityTransparency&&this._highQualityTransparencyEnabled!==e.highQualityTransparency&&(this._highQualityTransparencyEnabled=e.highQualityTransparency,this._requestRender()),void 0!==e.hasOverlayWater&&this._hasOverlayWater!==e.hasOverlayWater&&(this._hasOverlayWater=e.hasOverlayWater,this._requestRender()),void 0!==e.slicePlane&&this._sliceHelper.plane!==e.slicePlane&&(this._sliceHelper.plane=e.slicePlane,this._requestRender()),void 0!==e.terrainTransparency&&this._terrainTransparency!==e.terrainTransparency&&(this._terrainTransparency=e.terrainTransparency,this._requestRender()),void 0!==e.shadowCastOptions&&this._shadowAccumulator.setOptions(e.shadowCastOptions)}get hasSlicePlane(){return!!this._sliceHelper.plane}get plugins(){return this._plugins}get _hasOITSupport(){return this._rctx.driverTest.floatBufferBlend.result}get _oitEnabled(){return this._highQualityTransparency&&this._hasOITSupport}modify(e,r){this._isRendering&&console.warn("Renderer.modify called while rendering");const{adds:t,removes:s,updates:i}=e;if(0===t.length&&0===s.length&&0===i.length)return;const a=J(e);let n=!1;a.forEach(((t,s)=>{if(r.done)return;let i=this._plugins.getMaterialRenderer(s);if(null==i&&t.adds.length>0){const e=new oe({material:s});e.initializeRenderContext(this._plugins._context),i=e,this._plugins.add(i)}i&&(i.modify(t),0===i.numGeometries&&(n=!0)),t.removes.forEach((r=>e.removes.removeUnordered(r))),t.adds.forEach((r=>e.adds.removeUnordered(r))),t.updates.forEach((r=>e.updates.removeUnordered(r))),r.madeProgress()})),n&&this._plugins.removeEmptyMaterialRenderers(),this._updateHasFlags(),this._requestRender()}_updateHasFlags(){const has=this._pluginsHas;has.hudElements=this._plugins.produces(ee.LINE_CALLOUTS_HUD_DEPTH)||this._plugins.produces(ee.HUD_MATERIAL)||this._plugins.produces(ee.LABEL_MATERIAL),has.water=this._plugins.produces(ee.DRAPED_WATER,w.Normal),this._bindParameters.hasOccludees=this._plugins.hasOccludees}updateAnimation(e){const r=this._hasAnimations;return this._hasAnimations=this._plugins.updateAnimation(e),this._hasAnimations=this._nodes.updateAnimation()||this._hasAnimations,this._hasAnimations!==r&&(this._gpuTimerHandle=r?s(this._gpuTimerHandle):this.performanceInfo.enableGPUPerformanceInfo()),this._hasAnimations}get animationTimestep(){return this._animationTimestep.value}get animationTimeDilation(){return this._animationTimestep.timeDilation}resetAnimation(){this._animationTimestep.clear()}tick(){this.fboCache.clean()}render(e,r,t=K.Default,s=q.ON){this._isRendering=!0,this.performanceInfo.startFrame(),this.fboCache.frameStart(),this._disposeBindBuffers();const i=this._offscreen,{camera:n,contentCamera:h,mode:o,alignPixelEnabled:d}=e;this._state.value=o,this._bindParameters.overlay=this.renderOverlay(r),this.performanceInfo.advance(_e.OVERLAY),this._renderContext.time=r,this._bindParameters.transparencyPassType=ae.NONE,this._bindParameters.alignPixelEnabled=d,this._bindParameters.decorations=s,this._bindParameters.mainColor=this._bindParameters.mainDepth=null;const l=b(this._sliceHelper.plane);s===q.OFF&&(this._sliceHelper.plane=null),n.setGLViewport(this._rctx);const _=i.initializeFrame(n,this._backgroundColor,t);this.hasReflections?this._bindParameters.ssr.lastFrameColor=_:_?.release(),this._ensureBindParametersCamera(n,h),this._plugins.prepareRender(),this.performanceInfo.advance(_e.PREPARE);const p=this._computeDepthRange(n);this._renderShadowMap(n,this._bindParameters.lighting.mainLight.direction,p),this.performanceInfo.advance(_e.SHADOW_MAP),this._ensureBindParametersCamera(n,h);const u=this._plugins.produces(ee.OPAQUE_TERRAIN)&&(this._terrainTransparency===P.Semitransparent||this._terrainTransparency===P.TransparentWithDraped),c=this._highQualityTransparency&&u,m=this._plugins.produces(ee.TRANSPARENT_MATERIAL,w.Color);this._prepareShaders(c,m),this._pluginInput.set("normals",this._renderNormals()),this.performanceInfo.advance(_e.NORMALS),this._renderSSAO(),this.performanceInfo.advance(_e.SSAO),this._renderLinearDepth(),this.performanceInfo.advance(_e.LINEAR_DEPTH),this._renderShadowAccumulation(p,n,h),this.performanceInfo.advance(_e.ACCUMULATED_SHADOWS),this._ensureBindParametersSSR(r),this._renderContext.output=w.Color,i.bindFbo(),this._bindParameters.mainColor=i.colorTexture,this._bindParameters.mainDepth=i.depthTexture,this._renderOpaqueGeometry(),this._offscreen.updateColor((e=>this._invokeRenderNodes(e)),"opaque-color"),this._plugins.render(ee.ENVIRONMENT_OPAQUE),this.performanceInfo.advance(_e.OPAQUE),this.fboCache.debugCallback&&this.fboCache.debugCallback("opaque-color",this._offscreen.color.fbo),this._renderTerrainLinearDepth(c),this._setMultipassTerrain(c),this._renderEdges(he.OPAQUE),this.performanceInfo.advance(_e.OPAQUE_EDGES),i.bindFbo(),this._plugins.render(ee.VOXEL),this.performanceInfo.advance(_e.VOXEL),this._renderHiddenTransparentEdges(),m&&(this._oitEnabled?this._renderOITPass(Te.Geometry):this._renderTransparentMaterial()),this._offscreen.updateColor((e=>this._invokeRenderNodes(e)),"transparent-color"),this.performanceInfo.advance(_e.TRANSPARENT);const g=this._renderGeometryLinearDepth(c);this._renderHUDVisibility(g),c||this._plugins.render(ee.LINE_CALLOUTS),this.performanceInfo.advance(_e.HUD_VISIBILITY);const f=t===K.ObjectAndLayerID?this._renderObjectAndLayerIdColor():null;this.performanceInfo.advance(_e.OBJECT_AND_LAYER_ID_COLOR),this._renderEdges(he.TRANSPARENT,g),g?.release(),this.performanceInfo.advance(_e.TRANSPARENT_EDGES);const T=u?this._renderTransparentTerrain():null;T&&this._bindParameters.hudVisibility&&(c?this._renderLineCallouts(y.Occluded):i.compositeToHUDVisibility(this._bindParameters,T.getTexture()),this._renderHUD(y.Occluded,i.color),this.performanceInfo.advance(_e.HUD_OCCLUDED)),this.performanceInfo.advance(_e.TRANSPARENT_TERRAIN),this._setTerrainCulling(!1),T&&(i.compositeToFramebuffer(this._bindParameters,T.getTexture(),de.PremultipliedAlpha,1),T.release(),c&&(this._renderEdges(he.OPAQUE),this.performanceInfo.advance(_e.OPAQUE_EDGES),m&&(this._oitEnabled?this._renderOITPass(Te.Geometry):this._renderTransparentMaterial()),this.performanceInfo.advance(_e.TRANSPARENT),this._renderEdges(he.TRANSPARENT),this.performanceInfo.advance(_e.TRANSPARENT_EDGES))),this._bindParameters.ssao=a(this._bindParameters.ssao),c&&this._renderLineCallouts(y.NotOccluded),this._setMultipassEnabled(!1),this._shadowAccumulator.render(this._bindParameters),i.bindFbo(),this._plugins.render(ee.TRANSPARENT_DEPTH_WRITE_DISABLED_MATERIAL),this._plugins.render(ee.ENVIRONMENT_TRANSPARENT),this.performanceInfo.advance(_e.ENVIRONMENT),this._renderLaserlines(),this.performanceInfo.advance(_e.LASER_LINES),this._renderOccluded(),this.performanceInfo.advance(_e.OCCLUDED);let A=this._renderHighlightPrepass();A&&this._renderShadowHighlights(A,this._bindParameters);const E=this._magnifierEnabled&&t===K.Default?this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"magnifier"):null,R=t!==K.Default?this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"screenshot"):null,S=this._renderComposite(E??R,A)??R;return this.performanceInfo.advance(_e.ANTIALIASING),this._renderHUD(y.NotOccluded,S),this.performanceInfo.advance(_e.HUD),A&&(this._renderHighlights(S,A,this._bindParameters),A=a(A)),this.performanceInfo.advance(_e.HIGHLIGHTS),this._magnifierEnabled&&this._magnifierHelper.render(this._rctx,this._bindParameters),S!==R&&(this._rctx.bindFramebuffer(R?.fbo),this._compositingHelper.composite(this._bindParameters,E?.getTexture(),de.None)),t===K.Default&&E?.release(),this.onPostRender&&this.onPostRender(),this._releaseFBOs(),this._offscreen.releaseBuffers(),this._renderContext.lastFrameCamera.copyFrom(this._bindParameters.camera),this._sliceHelper.plane=l,this._isRendering=!1,this.fboCache.frameEnd(),this.performanceInfo.finishFrame(),t!==K.Default&&(this._releaseFBOs(),this._disposeOffscreenBuffers()),{screen:R,oid:f}}_prepareShaders(e,r){this._renderContext.output=w.Color,this._prepareOpaqueGeometry(),this._setMultipassTerrain(e),this._plugins.prepare(ee.TRANSPARENT_TERRAIN),this._setMultipassTerrain(!1),e||this._plugins.prepare(ee.LINE_CALLOUTS),r&&this._prepareTransparencySlots(),this._plugins.prepare(ee.TRANSPARENT_DEPTH_WRITE_DISABLED_MATERIAL),this._plugins.prepare(ee.ENVIRONMENT_TRANSPARENT),this._plugins.prepare(ee.LASERLINES),this._rctx.gl.flush()}_renderObjectAndLayerIdColor(){if(!has("enable-feature:objectAndLayerId-rendering"))return;const e=this._renderContext.output,r=this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"oid");return r.acquireDepth(S.DEPTH_STENCIL_TEXTURE),this._rctx.bindFramebuffer(r.fbo),this.fboCache.rctx.clearFramebuffer([0,0,0,0],!0,!0),this._renderAllGeometry(w.ObjectAndLayerIdColor),this._rctx.bindFramebuffer(r.fbo),this.fboCache.rctx.clearFramebuffer(void 0,!0,!0),this._bindParameters.hudRenderStyle=y.NotOccluded,this._plugins.render(ee.HUD_MATERIAL),this._renderContext.output=e,r}finish(e){this._hasAnimations||this._animationTimestep.clear();const r=this.performanceInfo.gpuSamplingEnabled,t=e===j.BACKGROUND;if(t||r){const e=t?this.performanceInfo.elapsedTime:0,s=r?this.performanceInfo.totalGPUTimeSampler.last:this._rctx.gl.getError(),i=Math.max(e,s);this._animationTimestep.frame(i,t)}}readDepthPixels(e,r,t){const s=this._bindParameters.linearDepth?.fbo;if(s?.colorTexture)return void s.readPixels(r[0],r[1],r[2],r[3],ue.RGBA,ce.UNSIGNED_BYTE,t);const i=this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"depth").acquireDepth(S.DEPTH16_BUFFER);this._rctx.bindFramebuffer(i.fbo),this._ensureBindParametersCamera(e,e),this._bindParameters.camera.setGLViewport(this._rctx),this._rctx.setClearColor(0,0,0,0);const a=me.COLOR_BUFFER_BIT|me.DEPTH_BUFFER_BIT|me.STENCIL_BUFFER_BIT;this._rctx.clearSafe(a),this._renderAllGeometry(w.LinearDepth),i.fbo.readPixels(r[0],r[1],r[2],r[3],ue.RGBA,ce.UNSIGNED_BYTE,t),i.release()}readHUDVisibility(e,r,t,s,i){this._bindParameters.hudVisibility?.fbo.readPixels(e,r,t,s,ue.RGBA,ce.UNSIGNED_BYTE,i)}readAccumulatedShadow(e){return this._shadowAccumulator.readAccumulatedShadow(e[0],e[1])}_setMultipassTerrain(e){this._setMultipassEnabled(e),this._setTerrainCulling(e)}_setMultipassEnabled(e){this._bindParameters.multipassEnabled=e}_setTerrainCulling(e){this._bindParameters.multipassTerrain.cullAboveGround=e}_renderEdges(e,r){const t=this._edgeView;if(t?.shouldRender()){const{width:s,height:i,depth:a}=this._offscreen,n=this.fboCache.acquire(s,i,"edges"),h=()=>t.render(this._bindParameters,e);this._offscreen.renderToTargets(h,n,r??a,Ee),this._offscreen.compositeToFramebuffer(this._bindParameters,n.getTexture(),de.Alpha,1),n.release()}}_renderShadowMap(e,r,t){const s=this._shadowMap;s.enabled&&(s.start(e,r,t,this.isFeatureEnabled($.HighResolutionShadows),this._stage.view.qualitySettings.maximumPixelRatio),this._shadowHighlight.updateParameters(e,r),this._needsShadowHighlight?(this._renderShadowCascades(w.ShadowHighlight,this._shadowMap),s.moveSnapshot(se.Highlight),this._renderShadowCascades(w.ShadowExcludeHighlight,this._shadowMap),s.copySnapshot(se.ExcludeHighlight),this._renderShadowCascades(w.ShadowHighlight,this._shadowMap)):this._renderShadowCascades(w.Shadow),s.finish(),e.setGLViewport(this._rctx))}_renderShadowCascades(e,r=this._shadowMap){for(const t of r.cascades)t.camera.setGLViewport(this._rctx),this._ensureBindParametersCamera(t.camera,t.camera),this._renderAllGeometry(e)}get _needsLinearDepth(){return this._plugins.consumes(w.LinearDepth)||this.hasReflections||this._needsShadowHighlight||this._needsShadowCast||this._debugLinearDepth}_renderLinearDepth(){this._needsLinearDepth?(this._bindParameters.linearDepth=this._offscreen.renderToCachedFBO(this._bindParameters.linearDepth,"linear-depth",(()=>this._renderAllGeometry(w.LinearDepth)),[0,0,0,0],C.RGBA,S.DEPTH_STENCIL_TEXTURE),this._bindParameters.linearDepth.detachDepth()):this._bindParameters.linearDepth=a(this._bindParameters.linearDepth)}_renderTerrainLinearDepth(e){if(e){const e=this._renderContext.output;this._renderContext.output=w.LinearDepth,this._bindParameters.multipassTerrain.linearDepth=this._offscreen.renderToCachedFBO(this._bindParameters.multipassTerrain.linearDepth,"terrain depth",(()=>this._renderTransparentTerrain()),[-1e10,-1e10,-1e10,1]),this._bindParameters.multipassTerrain.linearDepth.detachDepth(),this._renderContext.output=e}else this._bindParameters.multipassTerrain.linearDepth=a(this._bindParameters.multipassTerrain.linearDepth)}_renderGeometryLinearDepth(e){if(!e)return void(this._bindParameters.multipassGeometry.linearDepth=a(this._bindParameters.multipassGeometry.linearDepth));const r=this._renderContext.output;this._bindParameters.multipassGeometry.linearDepth=this._offscreen.renderToCachedFBO(this._bindParameters.multipassGeometry.linearDepth,"geometry depth",(()=>this._renderOpaqueGeometryAndTransparentMaterial(w.LinearDepth)),[1,1,1,1]),this._renderContext.output=r;const t=this._bindParameters.multipassGeometry.linearDepth.getAttachment(ge);return t?.retain(),this._bindParameters.multipassGeometry.linearDepth.detachDepth(),t}get _needsDepthRange(){return this._shadowMap.enabled||this._needsShadowCast}_computeDepthRange(e){if(!this._needsDepthRange)return V;const r=k(e,this._plugins.plugins,this._stage.layers);return Q(r,this._plugins.queryDepthRange(e)),r.near=Math.max(e.near,r.near),r.far=Math.min(e.far,r.far),r}_renderNormals(){const e=this._plugins.produces(ee.SSAO),r=this._nodes.require("normals","composite-color")+this._nodes.require("normals","opaque-color")+this._nodes.require("normals","transparent-color");let t=(e?1:0)+r+(e||r>0?this._nodes.optional("normals","composite-color")+this._nodes.optional("normals","opaque-color")+this._nodes.optional("normals","transparent-color"):0);if(0===t)return;const s=this._offscreen.renderToCachedFBO(null,"normals",(()=>this._renderGeometryForSSAO(w.Normal)),[0,0,0,0],C.RGBA,S.DEPTH_STENCIL_TEXTURE);for(;--t>0;)s.retain();return s}_renderSSAO(){const e=this._pluginInput.get("normals");this._plugins.produces(ee.SSAO)&&e&&(this._bindParameters.ssao=this._plugins.render(ee.SSAO,this._pluginInput),e.detachDepth(),e.release()&&this._pluginInput.delete("normals"))}_renderAllGeometry(e){this._renderContext.output=e,this._plugins.prepare(ee.TRANSPARENT_TERRAIN),this._renderOpaqueGeometryAndTransparentMaterial(e),this._renderTransparentTerrain()}_renderOpaqueGeometryAndTransparentMaterial(e){this._renderContext.output=e,this._plugins.prepare(ee.TRANSPARENT_MATERIAL),this._plugins.prepare(ee.TRANSPARENT_NO_SSAO_DEPTH),this._renderOpaqueGeometry(),this._renderTransparentMaterial()}_renderGeometryForSSAO(e){this._renderContext.output=e,this._plugins.render(ee.INTEGRATED_MESH),this._plugins.render(ee.OPAQUE_TERRAIN),this._plugins.render(ee.OPAQUE_MATERIAL),this._plugins.render(ee.TRANSPARENT_MATERIAL),this._renderTransparentTerrain()}_prepareOpaqueGeometry(){this._plugins.prepare(ee.INTEGRATED_MESH),this._plugins.prepare(ee.OPAQUE_TERRAIN),this._plugins.prepare(ee.OPAQUE_MATERIAL),this._plugins.prepare(ee.OPAQUE_NO_SSAO_DEPTH),this._plugins.prepare(ee.ENVIRONMENT_OPAQUE)}_renderOpaqueGeometry(){this._plugins.render(ee.INTEGRATED_MESH),this._plugins.render(ee.OPAQUE_TERRAIN),this._plugins.render(ee.OPAQUE_MATERIAL),this._plugins.render(ee.OPAQUE_NO_SSAO_DEPTH)}_renderTransparentMaterial(){this._plugins.render(ee.TRANSPARENT_MATERIAL),this._plugins.render(ee.TRANSPARENT_NO_SSAO_DEPTH)}_renderTransparentTerrain(){if(!this._plugins.produces(ee.TRANSPARENT_TERRAIN))return;const e=()=>this._plugins.render(ee.TRANSPARENT_TERRAIN,null);if(this._renderContext.output!==w.Color)return void e();const{width:r,height:t,depth:s}=this._offscreen,i=this.fboCache.acquire(r,t,"transparent terrain");return this._offscreen.renderToTargets(e,i,s,[0,0,0,0]),i}_renderHUDVisibility(e){this._plugins.produces(ee.OCCLUSION_PIXELS)?(this._bindParameters.hudVisibility=this._offscreen.renderHUDVisibility(this._bindParameters.hudVisibility,(()=>this._plugins.render(ee.OCCLUSION_PIXELS)),e),this._offscreen.bindFbo()):this._bindParameters.hudVisibility=a(this._bindParameters.hudVisibility)}_renderLineCallouts(e){if(this._bindParameters.hudRenderStyle=e,e===y.Occluded){const e=()=>{this._plugins.render(ee.LINE_CALLOUTS)},{width:r,height:t,color:s}=this._offscreen,i=this.fboCache.acquireDepth(S.DEPTH16_BUFFER,r,t,"line callouts");this._offscreen.renderToTargets(e,s,i,void 0,!0,!0),i.release()}else this._plugins.render(ee.LINE_CALLOUTS)}_renderLaserlines(){if(this._plugins.render(ee.LASERLINES),this._plugins.produces(ee.LASERLINES_CONTRAST_CONTROL)){const e=this._offscreen,{width:r,height:t,depth:s}=e,i=this.fboCache.acquire(r,t,"laser lines"),a=()=>this._plugins.render(ee.LASERLINES_CONTRAST_CONTROL);e.renderToTargets(a,i,s,Ee),e.compositeToFramebuffer(this._bindParameters,i.getTexture(),de.PremultipliedAlpha,1),i.release()}}_renderHUD(e,r){if(this._pluginsHas.hudElements)if(this._oitEnabled){const t=this._renderOITPass(Te.HUD,e);this._rctx.bindFramebuffer(r?.fbo),this._compositingHelper.composite(this._bindParameters,t.getTexture(),de.PremultipliedAlpha),t.release()}else if(e===y.Occluded){this._renderContext.output=w.Color;const r=()=>this._renderHUDElements(e),{width:t,height:s,color:i}=this._offscreen,a=this.fboCache.acquireDepth(S.DEPTH16_BUFFER,t,s,"hud");this._offscreen.renderToTargets(r,i,a,void 0,!0,!0),a.release()}else this._renderContext.output=w.Color,this._rctx.bindFramebuffer(null),r?.acquireDepth(S.DEPTH16_BUFFER),this._rctx.bindFramebuffer(r?.fbo),this._renderHUDElements(e),r?.detachDepth()}_renderHUDElements(e){this._bindParameters.hudRenderStyle=e,this._plugins.prepare(ee.LINE_CALLOUTS_HUD_DEPTH),this._plugins.prepare(ee.HUD_MATERIAL),this._plugins.prepare(ee.LABEL_MATERIAL),this._plugins.render(ee.LINE_CALLOUTS_HUD_DEPTH),this._plugins.render(ee.HUD_MATERIAL),this._plugins.render(ee.LABEL_MATERIAL)}get _needsShadowHighlight(){return this._shadowMap.enabled&&this._plugins.produces(ee.SHADOW_HIGHLIGHT)&&this._plugins.produces(ee.OPAQUE_MATERIAL,w.ShadowHighlight)}_renderHighlightPrepass(){if(!this.hasHighlights)return;const e=()=>{this._renderAllGeometry(w.Highlight),this._rctx.clearSafe(me.DEPTH_BUFFER_BIT),this._renderHUDElements(y.Both)},r=this._offscreen.renderToCachedFBO(null,"highlights",e,[0,0,0,0],C.RGBA4,S.DEPTH_STENCIL_TEXTURE);return r.detachDepth(),r}_renderShadowHighlights(e,r){this.hasHighlights&&r.decorations!==q.OFF&&this._needsShadowHighlight&&this._offscreen.updateColor((r=>(this._pluginInput.set("highlights",e),this._plugins.render(ee.SHADOW_HIGHLIGHT,this._pluginInput,r),r)),"transparent-color")}_renderHighlights(e,r,t){this.hasHighlights&&t.decorations!==q.OFF&&this._plugins.produces(ee.HIGHLIGHT)&&(this._pluginInput.set("highlights",r),this._plugins.render(ee.HIGHLIGHT,this._pluginInput,e))}get _needsShadowCast(){return this._shadowAccumulator.isAccumulating}_renderShadowAccumulation(e,r,t){this._needsShadowCast&&this._bindParameters.linearDepth?.getTexture()&&this._shadowAccumulator.renderAccumulation(this._bindParameters.linearDepth,e,r,t)}_prepareTransparencySlots(){this._renderContext.output=w.Alpha,this._bindParameters.transparencyPassType=ae.Alpha,this._plugins.prepare(ee.TRANSPARENT_MATERIAL),this._renderContext.output=w.Color,this._bindParameters.transparencyPassType=ae.Color,this._plugins.prepare(ee.TRANSPARENT_MATERIAL),this._bindParameters.transparencyPassType=ae.FrontFace,this._plugins.prepare(ee.TRANSPARENT_MATERIAL),this._bindParameters.transparencyPassType=ae.NONE}_renderOITPass(e,r=y.Both){const t=e===Te.HUD,s=t?this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"oit hud composite"):null,i=t?()=>this._renderHUDElements(r):()=>this._renderTransparentMaterial(),a=this._renderContext.output;this._renderContext.output=w.Alpha,this._bindParameters.transparencyPassType=ae.Alpha;const n=this._offscreen.renderOITPass(i,ae.Alpha,t);this._renderContext.output=w.Color,this._bindParameters.transparencyPassType=ae.Color;const h=this._offscreen.renderOITPass(i,ae.Color,t);this._bindParameters.transparencyPassType=ae.FrontFace;const o=this._offscreen.renderOITPass(i,ae.FrontFace,t);return this._offscreen.compositeTransparentOntoOpaque(this._bindParameters,h,n,o,s),s?.detachDepth(),o.release(),h.release(),n.release(),this._bindParameters.transparencyPassType=ae.NONE,this._renderContext.output=a,s}_renderOccluded(){let e=0;be.clear(),this._plugins.plugins.forAll((r=>{if(!r.materialReference)return;r.queryRenderOccludedState(W.OccludeAndTransparentStencil)&&(e|=W.OccludeAndTransparentStencil,be.push(r))}));const r=this._offscreen,t=(t,s,i,a,n)=>{if(0==(e&s))return;const{width:h,height:o,depth:d}=r,l=this.fboCache.acquire(h,o,"tmp color");r.renderToTargets(i,l,d,[0,0,0,0],a,n),r.compositeToFramebuffer(this._bindParameters,l.getTexture(),de.PremultipliedAlpha,t),l.release()},s=(e,r)=>{this._bindParameters.slot=e,r.forAll((e=>{if(N(e)){const r=e.prepareTechnique(this._renderContext);r&&e.renderNode(this._renderContext,r)}}))};0!==be.length&&(s(ee.OCCLUDER_MATERIAL,be),t(.5,W.OccludeAndTransparentStencil,(()=>s(ee.TRANSPARENT_OCCLUDER_MATERIAL,be)),!1,!1)),be.clear(),this._plugins.plugins.forAll((r=>{if(!r.materialReference)return;const t=r.queryRenderOccludedState(W.OccludeAndTransparent),s=r.queryRenderOccludedState(W.Transparent),i=r.queryRenderOccludedState(W.Opaque);(t||s||i)&&(e|=t?W.OccludeAndTransparent:s?W.Transparent:W.Opaque,be.push(r))}));const i=this._plugins.renderOccludedFlags;if(e|=i,!e)return;const a=e=>{this._renderContext.renderOccludedMask=e,i>W.Occlude&&this._plugins.render(ee.OCCLUDED_TERRAIN),s(ee.OPAQUE_MATERIAL,be),s(ee.TRANSPARENT_MATERIAL,be),s(ee.TRANSPARENT_DEPTH_WRITE_DISABLED_MATERIAL,be),this._renderContext.renderOccludedMask=z};this._renderContext.output=w.Color,t(.5,W.OccludeAndTransparent,(()=>a(W.OccludeAndTransparent)),!0,G.OutlineVisualElementMask),t(.5,W.Transparent,(()=>a(W.Transparent)),!0,G.OutlineVisualElementMask),t(1,W.Opaque,(()=>a(W.Opaque)),!0,G.OutlineVisualElementMask),be.clear()}_invokeRenderNodes(e){return this._nodes.render(e,this._pluginInput,this._releaseNormals)}_renderComposite(e,r){this._offscreen.updateColor((e=>(this._pluginInput.set("highlights",r),e=this._nodes.render(e,this._pluginInput,this._releaseNormals),this._pluginInput.set(e.name,e),this._pluginInput.delete("highlights"),e)),"composite-color");const t=this._plugins.produces(ee.ANTIALIASING);return this._plugins.render(t?ee.ANTIALIASING:ee.BLIT,this._pluginInput,e)}_ensureBindParametersCamera(e,r){this._bindParameters.camera=e,this._bindParameters.contentCamera=r}_ensureBindParametersSSR(e){if(this._bindParameters.ssr.lastFrameColor){null==this._ssrEnableTime&&(this._ssrEnableTime=e),this._renderContext.lastFrameCamera.equals(this._bindParameters.camera)?this._reprojectionMatrix=g:(c(Pe,this._bindParameters.camera.viewMatrix),c(Re,this._bindParameters.camera.projectionMatrix),m(Se,Pe,Re),m(Se,this._renderContext.lastFrameCamera.viewMatrix,Se),m(Se,this._renderContext.lastFrameCamera.projectionMatrix,Se),this._reprojectionMatrix=Se);const r=this._stage.view.qualitySettings.fadeDuration;this._bindParameters.ssr.fadeFactor=r>0?Math.min(r,e-this._ssrEnableTime)/r:1,this._bindParameters.ssr.fadeFactor<1&&this._requestRender()}else this._reprojectionMatrix=g,this._ssrEnableTime=null}addRenderNode(e){this._nodes.add(e),this._requestRender()}removeRenderNode(e){this._nodes.remove(e),this._requestRender()}get usedMemory(){return{fbos:this.fboCache.usedMemory,plugins:this._plugins.usedMemory,edges:this.edgeView?.usedMemory??0}}get test(){return{offscreen:this._offscreen,shadowMap:this._shadowMap,highlight:this._highlight,lighting:this._bindParameters.lighting,renderPlugins:this._plugins,shadowAccumulator:this._shadowAccumulator,weatherIsFading:this._bindParameters.cloudsFade.isFading,resetRenderStateFeatures:()=>{this._renderStateFeatures.value=Z(),this._plugins.renderFeatureChanged(),this._requestRender()},getFramebufferTexture:e=>{switch(e){case Ae.Color:return this._offscreen.colorTexture;case Ae.LinearDepth:return this._bindParameters.linearDepth?.getTexture();case Ae.ShadowMap:return this._shadowMap.depthTexture;case Ae.HudVisibility:return this._bindParameters.hudVisibility?.getTexture()}},debugLinearDepth:e=>{this._debugLinearDepth=e,this._requestRender()}}}}var Te,Ae;e([p({readOnly:!0})],fe.prototype,"fullResolutionAtmosphere",null),e([p()],fe.prototype,"_smaa",void 0),e([p()],fe.prototype,"_blit",void 0),e([p()],fe.prototype,"_edgeView",void 0),e([p()],fe.prototype,"updating",null),function(e){e[e.Geometry=0]="Geometry",e[e.HUD=1]="HUD"}(Te||(Te={})),function(e){e[e.Color=0]="Color",e[e.LinearDepth=1]="LinearDepth",e[e.ShadowMap=2]="ShadowMap",e[e.HudVisibility=3]="HudVisibility"}(Ae||(Ae={}));const Ee=[0,0,0,0],be=new n,Re=f(),Pe=f(),Se=f();function Ce(e){return r=>e.immediate.schedule(r)}export{Ae as FramebufferId,fe as Renderer};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
4
  */
5
- import{_ as t}from"../../chunks/tslib.es6.js";import{createTask as e}from"../../core/asyncUtils.js";import a from"../../core/Collection.js";import{deprecatedProperty as r,deprecated as i}from"../../core/deprecate.js";import s from"../../core/Error.js";import o from"../../core/Evented.js";import{makeHandle as n}from"../../core/handleUtils.js";import l from"../../core/Logger.js";import{abortMaybe as p,removeMaybe as d,destroyMaybe as c}from"../../core/maybe.js";import{throwIfAborted as u,createResolver as h}from"../../core/promiseUtils.js";import{watch as w,on as f,when as m,whenOnce as y,syncAndInitial as k,initial as g,sync as v}from"../../core/reactiveUtils.js";import{property as _}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/RandomLCG.js";import{subclass as W}from"../../core/accessorSupport/decorators/subclass.js";import{UpdatingHandles as b}from"../../core/support/UpdatingHandles.js";import I from"../../layers/GraphicsLayer.js";import{isEditableLayer as F}from"../../layers/support/editableLayers.js";import{isFeatureLayer as E,getOwningPortalUrl as M}from"../../layers/support/layerUtils.js";import{parseKnownArcGISOnlineDomain as C}from"../../portal/support/urlUtils.js";import V from"../../views/interactive/sketch/SketchOptions.js";import{SnappingManager as O}from"../../views/interactive/snapping/SnappingManager.js";import U from"../../views/interactive/snapping/SnappingOptions.js";import T from"../Attachments/AttachmentsViewModel.js";import L from"./CreateFeaturesWorkflow.js";import A from"./UpdateWorkflow.js";import{whenEditorLayerView as j}from"./workflowUtils.js";import S from"./support/EditorItem.js";import P from"../FeatureTemplates/FeatureTemplatesViewModel.js";import R from"../Sketch/SketchViewModel.js";import H from"../Spinner/SpinnerViewModel.js";const x="esri.widgets.Editor.EditorViewModel",D=()=>l.getLogger(x),G=["create-features","update"];function q(t,e,a){D().error(new s(t,e,a))}function B(t,e){return t?.find((t=>t.layer===e))}let Q=class extends o.EventedAccessor{constructor(t){super(t),this._sketchEventListenerHandle=null,this._sketchGraphicsLayer=new I({listMode:"hide",internal:!0}),this._snappingManager=null,this._updateItemsTask=null,this._updatingHandles=new b,this._featureTemplatesViewModelLocked=!1,this.activeWorkflow=null,this._activityQueue=new a,this.editorItems=new a,this.failures=[],this.hideTemplatesForInactiveLayers=!1,this.attachmentsViewModel=new T({capabilities:{editing:!0}}),this.featureTemplatesViewModel=new P({disabledItemFunction:({layer:t})=>this._itemIsSuspended(t)}),this.ownSketchViewModel=new R({layer:this._sketchGraphicsLayer}),this.sketchOptions=new V,this.snappingOptions=new U,this.spinnerViewModel=new H,this.pageStack=[],this.showDiscardEditsPrompt=()=>Promise.resolve(!0),this._candidateCommitted=!1,this.back=async()=>{this.canGoBack&&(this.activeWorkflow?.hasPreviousStep?await this.activeWorkflow.back(this.showDiscardEditsPrompt):await this._cancelWorkflow({force:!this.hasPendingEdits}))},this.saveWorkflow=async()=>{const{featureFormViewModel:t}=this;if(t){if(t.submit(),!t.submittable)return;const e=t.getValues();if(t.validateContingencyConstraints(e,{includeIncompleteViolations:!0}).length>0)return}await(this.activeWorkflow?.save())},this.selectFeature=(t,e=!1)=>{const a=this.activeWorkflow;this._candidateCommitted||"update"!==a?.type||(a.data.rootFeature=t,e&&(a.next(),this._candidateCommitted=!0))}}initialize(){this.addHandles([w((()=>{const t=this.view,e=t?.map?.editableLayers,a=t?.allLayerViews,r=a?.filter((t=>!!e?.includes(t.layer)));return[e,r,this.layerInfos,this.allowedWorkflows]}),(()=>this._updateEditorItems()),k),w((()=>this.hideTemplatesForInactiveLayers),(()=>this.syncFeatureTemplates())),f((()=>this.activeWorkflow),"cancel",(()=>this.emit("workflow-cancel"))),f((()=>this.activeWorkflow),"commit",(()=>this.emit("workflow-commit"))),f((()=>this.activeWorkflow),"complete",(()=>{this.emit("workflow-commit"),this._set("activeWorkflow",null)})),m((()=>this.view?.map),(t=>t.add(this._sketchGraphicsLayer)),g),f((()=>this.editorItems),"change",(()=>this._afterEditorItemsChange())),w((()=>[this.canCreate,this.canUpdateVisible]),(()=>this._afterEditorItemsChange())),w((()=>this.page),((t,e)=>{const a=[...this.pageStack];if(-1===a.indexOf(t))a.push(t);else for(;a.length&&a.at(-1)!==t;)a.pop();this.pageStack=a}),k),m((()=>"awaiting-update-feature-candidate"===this.state),(()=>this._candidateCommitted=!1)),f((()=>this.featureTemplatesViewModel),"select",(async({item:t,oldItem:e})=>{const{activeWorkflow:a}=this;if(a){if("update"===a.type&&"awaiting-feature-creation-info"===a.activeWorkflow?.stepId)return;try{await this.cancelWorkflow({force:!this.hasPendingEdits})}catch{return void this.featureTemplatesViewModel.select(e,{emit:!1})}}if(!t)return;const r={layer:t.layer,template:t.template};if(t.supportsUpload)return this.featureTemplatesViewModel.select(e,{emit:!1}),this.startCreateFeaturesWorkflow(r);this.startCreateFeaturesWorkflowAtFeatureCreation(r)})),f((()=>this.view),"key-down",(t=>{"Escape"===t.key&&this.activeWorkflow?.keyboardCancellationEnabled&&(t.stopPropagation(),this.back())})),f((()=>this.sketchViewModel),["create","delete","update"],(t=>{const{activeWorkflow:e}=this,a="update"===e?.type,r=a?e.activeWorkflow?.layer:e?.layer,i=a?e?.activeWorkflow?.parentLayer:void 0,s=`sketch-${t.type}`;this.emit(s,{type:s,detail:t,layer:r,parentLayer:i})}),v),w((()=>this.view),(t=>{if(this._snappingManager=c(this._snappingManager),!t)return;const e=this.snappingOptions;this._snappingManager=new O({view:t,options:e})}),k),w((()=>this.snappingOptions),(t=>{this._snappingManager&&(this._snappingManager.options=t)}),k)])}destroy(){this._cancelWorkflow({warnIfNoWorkflow:!1}).then((()=>{this.view?.map?.remove(this._sketchGraphicsLayer),this.view=null})),this._updateItemsTask=p(this._updateItemsTask),this._updatingHandles.destroy(),this._sketchEventListenerHandle=d(this._sketchEventListenerHandle)}get allowedWorkflows(){return this._get("allowedWorkflows")}set allowedWorkflows(t){r(l.getLogger(this),"allowedWorkflows",{replacement:"Editor.visibleElements",version:"4.29",warnOnce:!0}),t&&0!==t.length||(t=[...G]),this._set("allowedWorkflows",t)}get canCreate(){return this.editorItems.some((t=>t.supportsCreateFeaturesWorkflow))}get canCreateVisible(){return!!this.featureTemplatesLayers.length}get canUpdate(){return this.editorItems.some((t=>t.supportsUpdateWorkflow))}get canUpdateVisible(){return this.editorItems.some((t=>t.supportsUpdateWorkflow&&t.visible))}get featureTemplatesLayers(){const t=new a;for(const e of this.editorItems){const a=e.supportsCreateFeaturesWorkflow&&!e.isTable,r=this.hideTemplatesForInactiveLayers&&!e.visible;a&&!r&&t.push(e.layer)}return t}get editableItems(){return r(l.getLogger(this),"editableItems",{replacement:"editorItems",version:"4.29",warnOnce:!0}),this.editorItems.map((t=>{const{capabilities:e,disabled:a,hasInvalidFormTemplate:r,layer:i}=t,s=[],o=e.create,n=e.update,l=e.delete;return o.enabled&&s.push("create"),n.enabled&&s.push("update"),l.enabled&&s.push("delete"),{layer:i,supports:s,suspended:a,attributeUpdatesEnabled:n.attributes,geometryUpdatesEnabled:n.geometry,attachmentsOnCreateEnabled:o.attachments.enabled,attachmentsOnUpdateEnabled:n.attachments.enabled,hasInvalidFormTemplate:r,hasAttachments:e.attachments.enabled}}))}get featureFormViewModel(){const{activeWorkflow:t}=this;return"update"===t?.type?t.activeFeatureFormViewModel:"create-features"===t?.type?t.featureFormViewModel:null}get labelOptions(){return this.sketchOptions.labels}set labelOptions(t){this.sketchOptions.labels=t}set layerInfos(t){const e=t?.some((t=>"allowAttachments"in t));e&&i(D(),"Property: layerInfo.allowAttachments",{replacement:"layerInfo.attachmentsOnCreateEnabled or layerInfo.attachmentsOnUpdateEnabled",version:"4.26"}),this._set("layerInfos",t)}get sketchViewModel(){const{activeWorkflow:t}=this;return"update"===t?.type?t.activeSketchViewModel:"create-features"===t?.type?t.sketchViewModel:this.ownSketchViewModel}get state(){if(!this.view?.ready)return"disabled";const t=this.attachmentsViewModel.mode;if("add"===t)return"adding-attachment";if("edit"===t)return"editing-attachment";const{activeWorkflow:e}=this;return e?.stepId?"update"===e.type&&e.activeWorkflow?.stepId?e.activeWorkflow.stepId:e.stepId:"ready"}get syncing(){return this._activityQueue.length>0}get updating(){return this._updatingHandles.updating||!0===this.activeWorkflow?.updating}get tooltipOptions(){return this.sketchOptions.tooltips}set tooltipOptions(t){this.sketchOptions.tooltips=t}get valueOptions(){return this.sketchOptions.values}set valueOptions(t){this.sketchOptions.values=t}set view(t){this.ownSketchViewModel.view=t,this.spinnerViewModel.view=t,this._set("view",t)}get page(){const{activeWorkflow:t,state:e}=this;if("update"===t?.type&&"awaiting-feature-to-update"===t.stepId)return"ready";if("create-features"===t?.type&&0===t.numPendingFeatures){const e=t.data.upload;if(e)return"default"===e.state?"ready":"creating-features-upload-details"}return e??"disabled"}get featureFormDisabled(){const{activeWorkflow:t}=this;return"update"===t?.type&&!1===t.activeEditorItem?.capabilities.update.attributes}get canGoBack(){return null!=this.activeWorkflow&&!this.syncing}get shouldShowDeleteButton(){const{activeWorkflow:t}=this;return!!t&&"update"===t.type&&!!t.activeEditorItem?.capabilities.delete.enabled}get hasPendingEdits(){return this.activeWorkflow?.hasPendingEdits??!1}async startCreateFeaturesWorkflowAtFeatureTypeSelection(){return this.startCreateFeaturesWorkflow()}async startCreateFeaturesWorkflowAtFeatureCreation(t){return this.startCreateFeaturesWorkflow(t,"creating-features")}async startCreateFeaturesWorkflow(t,e="awaiting-feature-creation-info"){if(await y((()=>!this.updating)),!this.canCreate)throw new s("editing:unsupported-workflow","Creating features is unsupported or disabled.");const a=this._createUpdatingResolver();await this._cancelWorkflow();const r=this._createCreateFeaturesWorkflow(t,e);this._set("activeWorkflow",r),await r.start(),a.resolve()}async startCreateFeaturesWorkflowAtFeatureEdit(t){await y((()=>!this.updating));const e=this._createUpdatingResolver(),{initialFeature:a}=t,r=a.sourceLayer,i=r?this.findEditorItemForLayer(r):void 0;if(!i?.supportsCreateFeaturesWorkflow)throw new s("editing:unsupported-workflow","Creating features is unsupported or disabled for this layer.");await this._cancelWorkflow();const o=this._createCreateFeaturesWorkflow({initialFeature:a,layer:i.layer,maxFeatures:1},"creating-features");this._set("activeWorkflow",o),await o.start(),e.resolve()}async startUpdateWorkflowAtFeatureSelection(){if(await y((()=>!this.updating)),!this.canUpdate)return void q("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const t=this._createUpdatingResolver();await this._cancelWorkflow();const e=this._createUpdateWorkflow();this._set("activeWorkflow",e),await e.start(),t.resolve()}async startUpdateWorkflowAtMultipleFeatureSelection(t){if(await y((()=>!this.updating)),!this.canUpdate)return void q("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const e=this._createUpdatingResolver();await this._cancelWorkflow();const a=this._createUpdateWorkflow("awaiting-update-feature-candidate");a.data.candidates=t,this._set("activeWorkflow",a),await a.start(),e.resolve()}async startUpdateWorkflowAtFeatureEdit(t){if(await y((()=>!this.updating)),!this.canUpdate)return void q("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const e=this._createUpdatingResolver();await this._cancelWorkflow();const a=this._createUpdateWorkflow("editing-existing-feature");a.data.rootFeature=t,this._set("activeWorkflow",a),await a.start(),e.resolve()}async deleteFeatureFromWorkflow(){const{activeWorkflow:t}=this;t&&"update"===t.type?await t.deleteActiveFeature():q("editing:unsupported-workflow","Deleting requires an active update workflow.")}async cancelWorkflow(t){return this._cancelWorkflow({warnIfNoWorkflow:!0,...t})}findEditorItemForLayer(t){return this.editorItems.find((e=>e.layer===t))}itemHasInvalidFormTemplate(t){return null!=t&&!0===this.findEditorItemForLayer(t.layer)?.hasInvalidFormTemplate}syncFeatureTemplates(){this._featureTemplatesViewModelLocked||(this.featureTemplatesViewModel.layers=this.featureTemplatesLayers.toArray())}async toggleUpdateWorkflow(){this.canUpdate&&(this.hasPendingEdits&&!await this.showDiscardEditsPrompt()||(this.activeWorkflow&&"awaiting-feature-to-update"===this.state?await this.cancelWorkflow({force:!0}):await this.startUpdateWorkflowAtFeatureSelection()))}lockFeatureTemplatesViewModel(){return this._featureTemplatesViewModelLocked=!0,n((()=>{this._featureTemplatesViewModelLocked=!1,this.syncFeatureTemplates()}))}async _getEditorItemCandidates(t){const{view:e}=this;if(!e?.map)return[];const{map:a}=e,r=a.editableLayers.toArray()??[],i=a.allTables.toArray().filter(E)??[];return await Promise.allSettled([...r.map((t=>"subtype-group"===t.type?t.loadAll():Promise.resolve())),...i.map((t=>t.load()))]),u(t),[...r.reverse(),...i.reverse()].filter((t=>F(t)&&("mesh"!==t.geometryType||"3d"===e.type))).flatMap((t=>"subtype-group"===t.type?t.sublayers.toArray():t))}_drainEditorItems(){this.editorItems.drain((t=>t.destroy()))}async _updateEditorItems(){p(this._updateItemsTask);const{view:t}=this,a=e((async e=>{if(!t?.map||!t?.allLayerViews)return;const a=await this._getEditorItemCandidates(e);if(!a.length)return void this._drainEditorItems();const r=[],i=[],s=[],{layerInfos:o}=this;for(const l of a){const e=B(o,l),a=await j(t,l).catch((()=>null));(e?r:a?i:s).push(new S({layer:l,layerInfo:e,layerView:a}))}o?.length&&r.sort(((t,e)=>o.findIndex((({layer:e})=>e===t.layer))-o.findIndex((({layer:t})=>t===e.layer))));const n=[...r,...i,...s];e.aborted||(this._drainEditorItems(),this.editorItems.addMany(n))}));this._updatingHandles.addPromise(a.promise),this._updateItemsTask=a}_afterEditorItemsChange(){const{activeWorkflow:t}=this;if(this.syncFeatureTemplates(),!t)return;const{stepId:e}=t;"create-features"!==t.type?"update"===t.type&&("awaiting-feature-to-update"===e&&!this.canUpdateVisible||"awaiting-update-feature-candidate"===e&&!t.hasUpdatableCandidates)&&this._cancelWorkflow():"awaiting-feature-creation-info"!==e||this.canCreate||this._cancelWorkflow()}async _cancelWorkflow(t){const e=this.activeWorkflow;if(!e)return void(t?.warnIfNoWorkflow&&q("editing:no-active-workflow","There is no active workflow to cancel."));if(!t||!1!==t.force)return this.emit("workflow-cancel"),this._set("activeWorkflow",null),void await e.cancel(t);await e.cancel(t),this._set("activeWorkflow",null)}_createCreateFeaturesWorkflow(t,e){return L.create({viewModel:this,creationInfo:t,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,startAt:e,applyEditsCallback:(t,e,a)=>this._applyEdits(t,e,a),addAttachmentsCallback:(t,e)=>this._addAttachments(t,e)})}_createUpdateWorkflow(t){return A.create({viewModel:this,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,startAt:t,applyEditsCallback:(t,e,a)=>this._applyEdits(t,e,a),addAttachmentsCallback:(t,e)=>this._addAttachments(t,e)})}_addAttachments(t,e){const a=e.map((e=>this._addAttachment(t,e.feature,e.attachment)))??[];return Promise.all(a)}async _addAttachment(t,e,a){let r=null;if(!("addAttachment"in t)||null==t.capabilities?.attachment)throw new s("editor:attachments-not-supported","Adding attachments is not supported for this layer type");return await this._queueOperation((async()=>(r=await(t.addAttachment?.(e,a).catch((t=>{throw t?.error||t})))??null,r))),r}async _applyEdits(t,e,a){let r=null;const i=t.url?await M(t.url):null,s={returnServiceEditsOption:(!i||!C(i))&&!RegExp("/hosted/","i").test(t.url)?"original-and-current-features":void 0,...a};return await this._queueOperation((async()=>{const{view:a}=this;if(!a)return null;const i=await j(a,t).catch((()=>null));return r=await t.applyEdits(e,s),i&&await y((()=>!i.updating)),r})),r}_queueOperation(t){this._activityQueue.push(t);const e=(t,e)=>{const a=e.indexOf(t);a>-1&&e.splice(a,1)};return t().then((t=>{if(null!=t&&"error"in t&&null!=t.error)throw t.error;if(null!=t&&"addFeatureResults"in t){const{addFeatureResults:e,deleteFeatureResults:a,updateFeatureResults:r}=t,i=e.find((t=>!!t.error))||r.find((t=>!!t.error))||a.find((t=>!!t.error));if(i)throw i.error}return t})).catch((a=>{q("editing:operation-error","An error occurred.",{error:a});const r={error:a,retry:()=>(e(r,this.failures),this._queueOperation(t)),cancel:()=>{e(r,this.failures)}};this._set("failures",[...this.failures,r])})).then((()=>{e(t,this._activityQueue)}))}_createUpdatingResolver(){const t=h();return this._updatingHandles.addPromise(t.promise),t}_itemIsSuspended(t){const e=this.findEditorItemForLayer(t);return null!=e&&(!e.visible||e.disabled)}};t([_({readOnly:!0})],Q.prototype,"activeWorkflow",void 0),t([_({readOnly:!0})],Q.prototype,"_activityQueue",void 0),t([_({value:[...G]})],Q.prototype,"allowedWorkflows",null),t([_({readOnly:!0})],Q.prototype,"canCreate",null),t([_()],Q.prototype,"canCreateVisible",null),t([_({readOnly:!0})],Q.prototype,"canUpdate",null),t([_()],Q.prototype,"canUpdateVisible",null),t([_()],Q.prototype,"featureTemplatesLayers",null),t([_()],Q.prototype,"editableItems",null),t([_()],Q.prototype,"editorItems",void 0),t([_({readOnly:!0})],Q.prototype,"failures",void 0),t([_()],Q.prototype,"hideTemplatesForInactiveLayers",void 0),t([_()],Q.prototype,"attachmentsViewModel",void 0),t([_()],Q.prototype,"featureFormViewModel",null),t([_()],Q.prototype,"featureTemplatesViewModel",void 0),t([_()],Q.prototype,"labelOptions",null),t([_()],Q.prototype,"layerInfos",null),t([_()],Q.prototype,"ownSketchViewModel",void 0),t([_()],Q.prototype,"sketchOptions",void 0),t([_()],Q.prototype,"sketchViewModel",null),t([_({type:U,nonNullable:!0})],Q.prototype,"snappingOptions",void 0),t([_()],Q.prototype,"spinnerViewModel",void 0),t([_()],Q.prototype,"state",null),t([_({readOnly:!0})],Q.prototype,"syncing",null),t([_()],Q.prototype,"updating",null),t([_()],Q.prototype,"tooltipOptions",null),t([_()],Q.prototype,"valueOptions",null),t([_()],Q.prototype,"view",null),t([_()],Q.prototype,"pageStack",void 0),t([_()],Q.prototype,"showDiscardEditsPrompt",void 0),t([_()],Q.prototype,"_candidateCommitted",void 0),t([_()],Q.prototype,"page",null),t([_()],Q.prototype,"featureFormDisabled",null),t([_()],Q.prototype,"canGoBack",null),t([_()],Q.prototype,"shouldShowDeleteButton",null),t([_()],Q.prototype,"hasPendingEdits",null),Q=t([W(x)],Q);const N=Q;export{N as default};
5
+ import{_ as t}from"../../chunks/tslib.es6.js";import{createTask as e}from"../../core/asyncUtils.js";import a from"../../core/Collection.js";import{deprecatedProperty as r,deprecated as i}from"../../core/deprecate.js";import s from"../../core/Error.js";import o from"../../core/Evented.js";import{makeHandle as n}from"../../core/handleUtils.js";import l from"../../core/Logger.js";import{abortMaybe as p,removeMaybe as d,destroyMaybe as c}from"../../core/maybe.js";import{throwIfAborted as u,createResolver as h}from"../../core/promiseUtils.js";import{watch as w,on as f,when as m,whenOnce as y,syncAndInitial as k,initial as g,sync as v}from"../../core/reactiveUtils.js";import{property as _}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/RandomLCG.js";import{subclass as W}from"../../core/accessorSupport/decorators/subclass.js";import{UpdatingHandles as b}from"../../core/support/UpdatingHandles.js";import I from"../../layers/GraphicsLayer.js";import{isEditableLayer as F}from"../../layers/support/editableLayers.js";import{isFeatureLayer as E,getOwningPortalUrl as M}from"../../layers/support/layerUtils.js";import{parseKnownArcGISOnlineDomain as C}from"../../portal/support/urlUtils.js";import V from"../../views/interactive/sketch/SketchOptions.js";import{SnappingManager as O}from"../../views/interactive/snapping/SnappingManager.js";import U from"../../views/interactive/snapping/SnappingOptions.js";import T from"../Attachments/AttachmentsViewModel.js";import L from"./CreateFeaturesWorkflow.js";import A from"./UpdateWorkflow.js";import{whenEditorLayerView as j}from"./workflowUtils.js";import S from"./support/EditorItem.js";import P from"../FeatureTemplates/FeatureTemplatesViewModel.js";import R from"../Sketch/SketchViewModel.js";import H from"../Spinner/SpinnerViewModel.js";const x="esri.widgets.Editor.EditorViewModel",D=()=>l.getLogger(x),G=["create-features","update"];function q(t,e,a){D().error(new s(t,e,a))}function B(t,e){return t?.find((t=>t.layer===e))}let Q=class extends o.EventedAccessor{constructor(t){super(t),this._sketchEventListenerHandle=null,this._sketchGraphicsLayer=new I({listMode:"hide",internal:!0}),this._snappingManager=null,this._updateItemsTask=null,this._updatingHandles=new b,this._featureTemplatesViewModelLocked=!1,this.activeWorkflow=null,this._activityQueue=new a,this.editorItems=new a,this.failures=[],this.hideTemplatesForInactiveLayers=!1,this.attachmentsViewModel=new T({capabilities:{editing:!0}}),this.featureTemplatesViewModel=new P({disabledItemFunction:({layer:t})=>this._itemIsSuspended(t)}),this.ownSketchViewModel=new R({layer:this._sketchGraphicsLayer}),this.sketchOptions=new V,this.snappingOptions=new U,this.spinnerViewModel=new H,this.pageStack=[],this.showDiscardEditsPrompt=()=>Promise.resolve(!0),this._candidateCommitted=!1,this.back=async()=>{this.canGoBack&&(this.activeWorkflow?.hasPreviousStep?await this.activeWorkflow.back(this.showDiscardEditsPrompt):await this._cancelWorkflow({force:!this.hasPendingEdits}))},this.saveWorkflow=async()=>{const{featureFormViewModel:t}=this;if(t){if(t.submit(),!t.submittable)return;const e=t.getValues();if(t.validateContingencyConstraints(e,{includeIncompleteViolations:!0}).length>0)return}await(this.activeWorkflow?.save())},this.selectFeature=(t,e=!1)=>{const a=this.activeWorkflow;this._candidateCommitted||"update"!==a?.type||(a.data.rootFeature=t,e&&(a.next(),this._candidateCommitted=!0))}}initialize(){this.addHandles([w((()=>{const t=this.view,e=t?.map?.editableLayers,a=t?.allLayerViews,r=a?.filter((t=>!!e?.includes(t.layer)));return[e,r,this.layerInfos,this.allowedWorkflows]}),(()=>this._updateEditorItems()),k),w((()=>this.hideTemplatesForInactiveLayers),(()=>this.syncFeatureTemplates())),f((()=>this.activeWorkflow),"cancel",(()=>this.emit("workflow-cancel"))),f((()=>this.activeWorkflow),"commit",(()=>this.emit("workflow-commit"))),f((()=>this.activeWorkflow),"complete",(()=>{this.emit("workflow-commit"),this._set("activeWorkflow",null)})),m((()=>this.view?.map),(t=>t.add(this._sketchGraphicsLayer)),g),f((()=>this.editorItems),"change",(()=>this._afterEditorItemsChange())),w((()=>[this.canCreate,this.canUpdateVisible]),(()=>this._afterEditorItemsChange())),w((()=>this.page),((t,e)=>{const a=[...this.pageStack];if(-1===a.indexOf(t))a.push(t);else for(;a.length&&a.at(-1)!==t;)a.pop();this.pageStack=a}),k),m((()=>"awaiting-update-feature-candidate"===this.state),(()=>this._candidateCommitted=!1)),f((()=>this.featureTemplatesViewModel),"select",(async({item:t,oldItem:e})=>{const{activeWorkflow:a}=this;if(a){if("update"===a.type&&"awaiting-feature-creation-info"===a.activeWorkflow?.stepId)return;try{await this.cancelWorkflow({force:!this.hasPendingEdits})}catch{return void this.featureTemplatesViewModel.select(e,{emit:!1})}}if(!t)return;const r={layer:t.layer,template:t.template};if(t.supportsUpload)return this.featureTemplatesViewModel.select(e,{emit:!1}),this.startCreateFeaturesWorkflow(r);this.startCreateFeaturesWorkflowAtFeatureCreation(r)})),f((()=>this.view),"key-down",(t=>{"Escape"===t.key&&this.activeWorkflow?.keyboardCancellationEnabled&&(t.stopPropagation(),this.back())})),f((()=>this.sketchViewModel),["create","delete","update"],(t=>{const{activeWorkflow:e}=this,a="update"===e?.type,r=a?e.activeWorkflow?.layer:e?.layer,i=a?e?.activeWorkflow?.parentLayer:void 0,s=`sketch-${t.type}`;this.emit(s,{type:s,detail:t,layer:r,parentLayer:i})}),v),w((()=>this.view),(t=>{if(this._snappingManager=c(this._snappingManager),!t)return;const e=this.snappingOptions;this._snappingManager=new O({view:t,options:e})}),k),w((()=>this.snappingOptions),(t=>{this._snappingManager&&(this._snappingManager.options=t)}),k)])}destroy(){this._cancelWorkflow({warnIfNoWorkflow:!1}).then((()=>{this.view?.map?.remove(this._sketchGraphicsLayer),this.view=null})),this._updateItemsTask=p(this._updateItemsTask),this._updatingHandles.destroy(),this._sketchEventListenerHandle=d(this._sketchEventListenerHandle)}get allowedWorkflows(){return this._get("allowedWorkflows")}set allowedWorkflows(t){r(l.getLogger(this),"allowedWorkflows",{replacement:"Editor.visibleElements",version:"4.29",warnOnce:!0}),t&&0!==t.length||(t=[...G]),this._set("allowedWorkflows",t)}get canCreate(){return this.editorItems.some((t=>t.supportsCreateFeaturesWorkflow))}get canCreateVisible(){return!!this.featureTemplatesLayers.length}get canUpdate(){return this.editorItems.some((t=>t.supportsUpdateWorkflow))}get canUpdateVisible(){return this.editorItems.some((t=>t.supportsUpdateWorkflow&&t.visible))}get featureTemplatesLayers(){const t=new a;for(const e of this.editorItems){const a=e.supportsCreateFeaturesWorkflow&&!e.isTable,r=this.hideTemplatesForInactiveLayers&&!e.visible;a&&!r&&t.push(e.layer)}return t}get editableItems(){return r(l.getLogger(this),"editableItems",{replacement:"editorItems",version:"4.29",warnOnce:!0}),this.editorItems.map((t=>{const{capabilities:e,disabled:a,hasInvalidFormTemplate:r,layer:i}=t,s=[],o=e.create,n=e.update,l=e.delete;return o.enabled&&s.push("create"),n.enabled&&s.push("update"),l.enabled&&s.push("delete"),{layer:i,supports:s,suspended:a,attributeUpdatesEnabled:n.attributes,geometryUpdatesEnabled:n.geometry,attachmentsOnCreateEnabled:o.attachments.enabled,attachmentsOnUpdateEnabled:n.attachments.enabled,hasInvalidFormTemplate:r,hasAttachments:e.attachments.enabled}}))}get featureFormViewModel(){const{activeWorkflow:t}=this;return"update"===t?.type?t.activeFeatureFormViewModel:"create-features"===t?.type?t.featureFormViewModel:null}get labelOptions(){return this.sketchOptions.labels}set labelOptions(t){this.sketchOptions.labels=t}set layerInfos(t){const e=t?.some((t=>"allowAttachments"in t));e&&i(D(),"Property: layerInfo.allowAttachments",{replacement:"layerInfo.attachmentsOnCreateEnabled or layerInfo.attachmentsOnUpdateEnabled",version:"4.26"}),this._set("layerInfos",t)}get sketchViewModel(){const{activeWorkflow:t}=this;return"update"===t?.type?t.activeSketchViewModel:"create-features"===t?.type?t.sketchViewModel:this.ownSketchViewModel}get state(){if(!this.view?.ready)return"disabled";const t=this.attachmentsViewModel.mode;if("add"===t)return"adding-attachment";if("edit"===t)return"editing-attachment";const{activeWorkflow:e}=this;return e?.stepId?"update"===e.type&&e.activeWorkflow?.stepId?e.activeWorkflow.stepId:e.stepId:"ready"}get syncing(){return this._activityQueue.length>0}get updating(){return this._updatingHandles.updating||!0===this.activeWorkflow?.updating}get tooltipOptions(){return this.sketchOptions.tooltips}set tooltipOptions(t){this.sketchOptions.tooltips=t}get valueOptions(){return this.sketchOptions.values}set valueOptions(t){this.sketchOptions.values=t}set view(t){this.ownSketchViewModel.view=t,this.spinnerViewModel.view=t,this._set("view",t)}get page(){const{activeWorkflow:t,state:e}=this;if("update"===t?.type&&"awaiting-feature-to-update"===t.stepId)return"ready";if("create-features"===t?.type&&0===t.numPendingFeatures){const e=t.data.upload;if(e)return"default"===e.state?"ready":"creating-features-upload-details"}return e??"disabled"}get featureFormDisabled(){const{activeWorkflow:t}=this;return"update"===t?.type&&!1===t.activeEditorItem?.capabilities.update.attributes}get canGoBack(){return null!=this.activeWorkflow&&!this.syncing}get shouldShowDeleteButton(){const{activeWorkflow:t}=this;return!!t&&"update"===t.type&&!!t.activeEditorItem?.capabilities.delete.enabled}get hasPendingEdits(){return this.activeWorkflow?.hasPendingEdits??!1}async startCreateFeaturesWorkflowAtFeatureTypeSelection(){return this.startCreateFeaturesWorkflow()}async startCreateFeaturesWorkflowAtFeatureCreation(t){return this.startCreateFeaturesWorkflow(t,"creating-features")}async startCreateFeaturesWorkflow(t,e="awaiting-feature-creation-info"){if(await y((()=>!this.updating)),!this.canCreate)throw new s("editing:unsupported-workflow","Creating features is unsupported or disabled.");const a=this._createUpdatingResolver();await this._cancelWorkflow();const r=this._createCreateFeaturesWorkflow(t,e);this._set("activeWorkflow",r),await r.start(),a.resolve()}async startCreateFeaturesWorkflowAtFeatureEdit(t){await y((()=>!this.updating));const e=this._createUpdatingResolver(),{initialFeature:a}=t,r=a.sourceLayer=a.layer,i=r?this.findEditorItemForLayer(r):void 0;if(!i?.supportsCreateFeaturesWorkflow)throw new s("editing:unsupported-workflow","Creating features is unsupported or disabled for this layer.");await this._cancelWorkflow();const o=this._createCreateFeaturesWorkflow({initialFeature:a,layer:i.layer,maxFeatures:1},"creating-features");this._set("activeWorkflow",o),await o.start(),e.resolve()}async startUpdateWorkflowAtFeatureSelection(){if(await y((()=>!this.updating)),!this.canUpdate)return void q("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const t=this._createUpdatingResolver();await this._cancelWorkflow();const e=this._createUpdateWorkflow();this._set("activeWorkflow",e),await e.start(),t.resolve()}async startUpdateWorkflowAtMultipleFeatureSelection(t){if(await y((()=>!this.updating)),!this.canUpdate)return void q("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const e=this._createUpdatingResolver();await this._cancelWorkflow();const a=this._createUpdateWorkflow("awaiting-update-feature-candidate");a.data.candidates=t,this._set("activeWorkflow",a),await a.start(),e.resolve()}async startUpdateWorkflowAtFeatureEdit(t){if(await y((()=>!this.updating)),!this.canUpdate)return void q("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const e=this._createUpdatingResolver();await this._cancelWorkflow();const a=this._createUpdateWorkflow("editing-existing-feature");a.data.rootFeature=t,this._set("activeWorkflow",a),await a.start(),e.resolve()}async deleteFeatureFromWorkflow(){const{activeWorkflow:t}=this;t&&"update"===t.type?await t.deleteActiveFeature():q("editing:unsupported-workflow","Deleting requires an active update workflow.")}async cancelWorkflow(t){return this._cancelWorkflow({warnIfNoWorkflow:!0,...t})}findEditorItemForLayer(t){return this.editorItems.find((e=>e.layer===t))}itemHasInvalidFormTemplate(t){return null!=t&&!0===this.findEditorItemForLayer(t.layer)?.hasInvalidFormTemplate}syncFeatureTemplates(){this._featureTemplatesViewModelLocked||(this.featureTemplatesViewModel.layers=this.featureTemplatesLayers.toArray())}async toggleUpdateWorkflow(){this.canUpdate&&(this.hasPendingEdits&&!await this.showDiscardEditsPrompt()||(this.activeWorkflow&&"awaiting-feature-to-update"===this.state?await this.cancelWorkflow({force:!0}):await this.startUpdateWorkflowAtFeatureSelection()))}lockFeatureTemplatesViewModel(){return this._featureTemplatesViewModelLocked=!0,n((()=>{this._featureTemplatesViewModelLocked=!1,this.syncFeatureTemplates()}))}async _getEditorItemCandidates(t){const{view:e}=this;if(!e?.map)return[];const{map:a}=e,r=a.editableLayers.toArray()??[],i=a.allTables.toArray().filter(E)??[];return await Promise.allSettled([...r.map((t=>"subtype-group"===t.type?t.loadAll():Promise.resolve())),...i.map((t=>t.load()))]),u(t),[...r.reverse(),...i.reverse()].filter((t=>F(t)&&("mesh"!==t.geometryType||"3d"===e.type))).flatMap((t=>"subtype-group"===t.type?t.sublayers.toArray():t))}_drainEditorItems(){this.editorItems.drain((t=>t.destroy()))}async _updateEditorItems(){p(this._updateItemsTask);const{view:t}=this,a=e((async e=>{if(!t?.map||!t?.allLayerViews)return;const a=await this._getEditorItemCandidates(e);if(!a.length)return void this._drainEditorItems();const r=[],i=[],s=[],{layerInfos:o}=this;for(const l of a){const e=B(o,l),a=await j(t,l).catch((()=>null));(e?r:a?i:s).push(new S({layer:l,layerInfo:e,layerView:a}))}o?.length&&r.sort(((t,e)=>o.findIndex((({layer:e})=>e===t.layer))-o.findIndex((({layer:t})=>t===e.layer))));const n=[...r,...i,...s];e.aborted||(this._drainEditorItems(),this.editorItems.addMany(n))}));this._updatingHandles.addPromise(a.promise),this._updateItemsTask=a}_afterEditorItemsChange(){const{activeWorkflow:t}=this;if(this.syncFeatureTemplates(),!t)return;const{stepId:e}=t;"create-features"!==t.type?"update"===t.type&&("awaiting-feature-to-update"===e&&!this.canUpdateVisible||"awaiting-update-feature-candidate"===e&&!t.hasUpdatableCandidates)&&this._cancelWorkflow():"awaiting-feature-creation-info"!==e||this.canCreate||this._cancelWorkflow()}async _cancelWorkflow(t){const e=this.activeWorkflow;if(!e)return void(t?.warnIfNoWorkflow&&q("editing:no-active-workflow","There is no active workflow to cancel."));if(!t||!1!==t.force)return this.emit("workflow-cancel"),this._set("activeWorkflow",null),void await e.cancel(t);await e.cancel(t),this._set("activeWorkflow",null)}_createCreateFeaturesWorkflow(t,e){return L.create({viewModel:this,creationInfo:t,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,startAt:e,applyEditsCallback:(t,e,a)=>this._applyEdits(t,e,a),addAttachmentsCallback:(t,e)=>this._addAttachments(t,e)})}_createUpdateWorkflow(t){return A.create({viewModel:this,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,startAt:t,applyEditsCallback:(t,e,a)=>this._applyEdits(t,e,a),addAttachmentsCallback:(t,e)=>this._addAttachments(t,e)})}_addAttachments(t,e){const a=e.map((e=>this._addAttachment(t,e.feature,e.attachment)))??[];return Promise.all(a)}async _addAttachment(t,e,a){let r=null;if(!("addAttachment"in t)||null==t.capabilities?.attachment)throw new s("editor:attachments-not-supported","Adding attachments is not supported for this layer type");return await this._queueOperation((async()=>(r=await(t.addAttachment?.(e,a).catch((t=>{throw t?.error||t})))??null,r))),r}async _applyEdits(t,e,a){let r=null;const i=t.url?await M(t.url):null,s={returnServiceEditsOption:(!i||!C(i))&&!RegExp("/hosted/","i").test(t.url)?"original-and-current-features":void 0,...a};return await this._queueOperation((async()=>{const{view:a}=this;if(!a)return null;const i=await j(a,t).catch((()=>null));return r=await t.applyEdits(e,s),i&&await y((()=>!i.updating)),r})),r}_queueOperation(t){this._activityQueue.push(t);const e=(t,e)=>{const a=e.indexOf(t);a>-1&&e.splice(a,1)};return t().then((t=>{if(null!=t&&"error"in t&&null!=t.error)throw t.error;if(null!=t&&"addFeatureResults"in t){const{addFeatureResults:e,deleteFeatureResults:a,updateFeatureResults:r}=t,i=e.find((t=>!!t.error))||r.find((t=>!!t.error))||a.find((t=>!!t.error));if(i)throw i.error}return t})).catch((a=>{q("editing:operation-error","An error occurred.",{error:a});const r={error:a,retry:()=>(e(r,this.failures),this._queueOperation(t)),cancel:()=>{e(r,this.failures)}};this._set("failures",[...this.failures,r])})).then((()=>{e(t,this._activityQueue)}))}_createUpdatingResolver(){const t=h();return this._updatingHandles.addPromise(t.promise),t}_itemIsSuspended(t){const e=this.findEditorItemForLayer(t);return null!=e&&(!e.visible||e.disabled)}};t([_({readOnly:!0})],Q.prototype,"activeWorkflow",void 0),t([_({readOnly:!0})],Q.prototype,"_activityQueue",void 0),t([_({value:[...G]})],Q.prototype,"allowedWorkflows",null),t([_({readOnly:!0})],Q.prototype,"canCreate",null),t([_()],Q.prototype,"canCreateVisible",null),t([_({readOnly:!0})],Q.prototype,"canUpdate",null),t([_()],Q.prototype,"canUpdateVisible",null),t([_()],Q.prototype,"featureTemplatesLayers",null),t([_()],Q.prototype,"editableItems",null),t([_()],Q.prototype,"editorItems",void 0),t([_({readOnly:!0})],Q.prototype,"failures",void 0),t([_()],Q.prototype,"hideTemplatesForInactiveLayers",void 0),t([_()],Q.prototype,"attachmentsViewModel",void 0),t([_()],Q.prototype,"featureFormViewModel",null),t([_()],Q.prototype,"featureTemplatesViewModel",void 0),t([_()],Q.prototype,"labelOptions",null),t([_()],Q.prototype,"layerInfos",null),t([_()],Q.prototype,"ownSketchViewModel",void 0),t([_()],Q.prototype,"sketchOptions",void 0),t([_()],Q.prototype,"sketchViewModel",null),t([_({type:U,nonNullable:!0})],Q.prototype,"snappingOptions",void 0),t([_()],Q.prototype,"spinnerViewModel",void 0),t([_()],Q.prototype,"state",null),t([_({readOnly:!0})],Q.prototype,"syncing",null),t([_()],Q.prototype,"updating",null),t([_()],Q.prototype,"tooltipOptions",null),t([_()],Q.prototype,"valueOptions",null),t([_()],Q.prototype,"view",null),t([_()],Q.prototype,"pageStack",void 0),t([_()],Q.prototype,"showDiscardEditsPrompt",void 0),t([_()],Q.prototype,"_candidateCommitted",void 0),t([_()],Q.prototype,"page",null),t([_()],Q.prototype,"featureFormDisabled",null),t([_()],Q.prototype,"canGoBack",null),t([_()],Q.prototype,"shouldShowDeleteButton",null),t([_()],Q.prototype,"hasPendingEdits",null),Q=t([W(x)],Q);const N=Q;export{N as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../chunks/tslib.es6.js";import{id as t}from"../../kernel.js";import r from"../../core/Collection.js";import s from"../../core/Error.js";import i from"../../core/Evented.js";import a from"../../core/Logger.js";import{when as l}from"../../core/reactiveUtils.js";import{property as o}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/RandomLCG.js";import{subclass as n}from"../../core/accessorSupport/decorators/subclass.js";import c from"../../geometry/Point.js";import{isPoint as h,isMultipoint as u}from"../../geometry/support/jsonUtils.js";import{fetchMessageBundle as p}from"../../intl/messages.js";import d from"../../layers/FeatureLayer.js";import g from"../../layers/GraphicsLayer.js";import y from"../../layers/support/CodedValueDomain.js";import{isFeatureLayer as m}from"../../layers/support/layerUtils.js";import f from"../../networks/UtilityNetwork.js";import{getObjectIdsFromElements as w,getFeaturesFromLayers as _}from"../../networks/support/utils.js";import A from"../../portal/Portal.js";import{hasUserTypeExtension as b}from"../../portal/support/utils.js";import{trace as v}from"../../rest/networks/trace.js";import R from"../../rest/networks/support/TraceLocation.js";import I from"../../rest/networks/support/TraceParameters.js";import{GeometryHandler as k}from"./support/GeometryHandler.js";import{GraphicHandler as G}from"./support/GraphicHandler.js";import{ResultAreaHandler as F}from"./support/ResultAreaHandler.js";import{UtilityHelper as T}from"./support/UtilityHelper.js";const S=()=>p("esri/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace"),L=()=>p("esri/core/t9n/Units"),H=`utility-network-trace-flags-${Date.now()}`,P=`utility-network-trace-results-${Date.now()}`;function N(e){return e instanceof y}function U(e){return"feature"===e.layer.type||"subtype-group"===e.layer.type}function C(e){return"layer"in e}function E(e){return void 0!==e.layerViews}function B(e){return"graphics"===e.type}async function j(e){const t=new d({url:e.networkSystemLayers.dirtyAreasLayerUrl});await t.load();const r=t.version;if(Number(r)<=11.1){const t=new A({url:new URL(e.layerUrl).origin+"/portal"});await t.load();const r=t?.user?.username;return!!r&&b(t,r,"utilityNetwork")}return!0}let D=class extends i.EventedAccessor{constructor(e){super(e),this._activeProgress=!1,this._clickHandler=null,this._flags=[],this._flagId=0,this._geometryHandler=null,this._highlightHandler=[],this._resultAreaHandler=null,this._utilityHelper=new T,this._watchHandler=null,this._validUNLayers=[],this._traceTimeout=6e5,this.traces=[],this.graphicHandler=null,this.defaultGraphicColor={color:[255,255,0,.6],haloOpacity:.9,fillOpacity:.2,hex:"#FFFF00"},this.enableResultArea=!1,this.flags=[],this.gdbVersion="sde.DEFAULT",this.messages=null,this.messagesUnits=null,this.defaultResultAreaProperties={type:"convexhull",distance:10,unit:"meters",areaUnit:"square-meters",color:{color:[255,165,0,.5],haloOpacity:.9,fillOpacity:.2,hex:"#ffa500"},show:!1},this.selectedTraces=[],this.selectOnComplete=!0,this.showGraphicsOnComplete=!0,this.showSelectionAttributes=!0,this.traceResults=[],this.utilityNetwork=null}initialize(){this._geometryHandler=new k,this.graphicHandler=new G,this._resultAreaHandler=new F;(async()=>{const[e,t]=await Promise.all([S(),L()]);this.set({messages:e,messagesUnits:t})})()}destroy(){this.view=null}get resultAreaProperties(){return this.defaultResultAreaProperties}set resultAreaProperties(e){this._set("resultAreaProperties",{...this.defaultResultAreaProperties,...e}),this.graphicHandler.addCustomColor(this.resultAreaProperties.color),this.traceResults.forEach((t=>{const r=t.resultArea?.show;t.resultArea={...this.defaultResultAreaProperties,...e},this.removeResultAreaFromMap(t),this.enableResultArea&&this.createResultAreaGraphic(t).then((s=>{if(s){t.resultAreaGraphic=s;const i=e?.show??r;t.resultArea&&(t.resultArea.show=i),i&&this.addResultAreaToMap(t,s)}}))}))}get state(){return this.view?.ready?"ready":"loading"}get view(){return this._get("view")}set view(e){e&&"2d"!==e.type&&a.getLogger(this).error(new s("view:invalid-view","SceneView is not supported",{view:e})),this._set("view",e),this.utilityNetwork&&this.reset(),this.utilityNetwork=null,this.loadUtilityNetwork().then((e=>{e&&this.selectTracesOnLoad()}))}addFlagByHit(e,t){const r=e=>{this.view?.popup&&(this.view.popupEnabled=e)};return new Promise(((s,i)=>{r(!1),this._clickHandler?.remove(),this.emit("add-flag",{type:e}),this._clickHandler=this.view?.on("click",(a=>{this.queryFlagByHitTest(a,e,t).then((i=>{r(!0),this._clickHandler?.remove(),this.emit("add-flag-complete",{type:e,symbol:t}),s(i)})).catch((s=>{r(!0),this._clickHandler?.remove(),this.emit("add-flag-error",{type:e,symbol:t}),i(s)}))}))}))}async addFlagsOnLoad(){return new Promise((e=>{const t=[];this._watchHandler=l((()=>null!=this.view&&!this.view.updating),(async()=>{if(this._flags.length>0)e(t);else{const r=this.flags.map((async e=>{if(e.mapPoint){const r=new c({x:e.mapPoint.x,y:e.mapPoint.y,spatialReference:e.mapPoint.spatialReference.wkid}),s={screenPoint:this.view.toScreen(r),mapPoint:r};await this.queryFlagByHitTest(s,e.type)||("barrier"===e.type?t.push("barrier"):t.push("starting-point"))}}));await Promise.all(r),e(t)}}),{initial:!0})}))}async addResultAreaToMap(e,t){if(this.view)if(e.resultArea.show=!0,t)this._resultAreaHandler?.addResultAreaToMap(t,this.view.map),this.emit("add-result-area",{graphic:t});else if(e.results){const t=await this.createResultAreaGraphic(e);t&&(this._resultAreaHandler?.addResultAreaToMap(t,this.view.map),this.emit("add-result-area",{graphic:t}))}}async addResultGraphicToView(e,t){const{view:r}=this,{results:s}=e;if(r&&s&&this.utilityNetwork)for(const i in s.aggregatedGeometry)if("line,multipoint,polygon".includes(i)){const a=i,l=s.aggregatedGeometry[a];if(null!=l){l.spatialReference=this.utilityNetwork.spatialReference,e.graphicEnabled=!0;const s=await this._geometryHandler.projectGeometry(l,r.spatialReference),i={globalid:e.trace.globalId};if(null!==s){const e=this.graphicHandler.makeGraphic(s,t.color,i,r.spatialReference);this._getGraphicLayer(P)?.add(e)}}}}addTerminal(e,t){const r=[...this._flags];r.forEach((r=>{r.globalId===t.globalId&&(t.selectedTerminals?.includes(parseInt(e,10))||r.selectedTerminals?.push(parseInt(e,10)))})),this._flags=r}async callTrace(){const e=this.traces.filter((e=>e.selected));return e.length>0&&(this.traceResults.length>0&&this.traceResults.forEach((e=>{this.removeResultGraphicFromView(e)})),this.traceResults=[],this.removeSelection(),await Promise.all(e.map((async(e,t)=>{const r=e,s=new I({gdbVersion:this.gdbVersion,moment:null,traceType:r.traceType,traceLocations:this._flags,namedTraceConfigurationGlobalId:r.globalId,traceConfiguration:null,outSpatialReference:null,resultTypes:null});await this.executeTrace(r,this.utilityNetwork?.networkServiceUrl,s).then((e=>{if(e.hasOwnProperty("results")){const r={...e};if(null!==r.results){r.resultArea={...this.resultAreaProperties};const e=[...r.results.elements];r.results.elements.length=0;const s=new Map;for(const t of e)s.has(t.globalId)||(s.set(t.globalId,!0),r.results.elements.push(t));const i=[...this.traceResults];i.splice(t,0,r),this.traceResults=i,null!==r.results&&(this.selectOnComplete&&this.mergeSelection(!0,r.trace),this.showGraphicsOnComplete&&this.addResultGraphicToView(r,r.graphicColor),this.enableResultArea&&this.createResultAreaGraphic(r).then((e=>{e&&(r.resultAreaGraphic=e,r.resultArea?.show&&this.addResultAreaToMap(r,r.resultAreaGraphic))})))}else{const r=[...this.traceResults];r.splice(t,0,e),this.traceResults=r}this._activeProgress=!1}else{this._activeProgress=!1;const r=[...this.traceResults];r.splice(t,0,e),this.traceResults=r}})).catch((e=>{throw this._activeProgress=!1,e}))}))),!0)}changeResultAreaColor(e,t){if(!e.resultArea)return;e.resultArea.color=t;const r=this._resultAreaHandler?.changeResultAreaColor(e.trace.globalId,t,this.view.map);e.resultAreaGraphic&&(e.resultAreaGraphic.symbol=r)}changeResultGraphicColor(e,t){const r=[...this.traceResults];r.length>0&&r.forEach((r=>{r.trace.globalId===t.trace.globalId&&(r.graphicColor=e,r.graphicEnabled=!0)})),this.traceResults=r,this.removeResultGraphicFromView(t),this.addResultGraphicToView(t,e)}changeFlagSymbol(e,t){this._flags.length>0&&this._flags.forEach((r=>{r.type===e&&t&&r.mapGraphic&&(r.mapGraphic.symbol=t)}))}checkCanTrace(){const e={status:!0,issues:[]};let t=!1;const r=this._flags.some((e=>"starting-point"===e.type)),s=this._flags.filter((e=>null!==e.allTerminals));s.length>0&&(t=s.some((e=>e.selectedTerminals.length<=0)));let i=[];return r?(i=this.traces.filter((e=>e.selected)),i.length<=0?(e.status=!1,e.issues=["noTrace"],t&&(e.status=!1,e.issues=["noTrace","noTerminalSelected"])):t&&(e.status=!1,e.issues=["noTerminalSelected"])):(i=this.traces.filter((e=>!0===e.selected)),i.length>0?(e.status=!1,e.issues=["noStart"],t&&(e.status=!1,e.issues=["noStart","noTerminalSelected"])):(e.status=!1,e.issues=["noStart","noTrace"],t&&(e.status=!1,e.issues=["noStart","noTrace","noTerminalSelected"]))),e}checkSelectionExist(){return this._highlightHandler.some((e=>e))}clearResult(e){if(!this.view)return;let t=this.traceResults;if(t.length>0){const r=t.filter((t=>t.trace.globalId===e.globalId));r.length>0&&(this.removeResultGraphicFromView(r[0]),this.removeResultAreaFromMap(r[0])),t=t.filter((t=>t.trace.globalId!==e.globalId))}this.traceResults=t,0===t.length?(this.removeAllResultAreaGraphics(),this.removeSelection(),this.emit("clear-selection",{resultSet:[]})):this.mergeSelection(!1,e)}createResultAreaGeometries(e,t,r){if(!this.view||!this.resultAreaProperties)return;let s;if("convexhull"===this.resultAreaProperties?.type?s=1===t.length&&(h(t[0])||u(t[0])&&1===t[0].points.length)?this._resultAreaHandler?.createBuffer(t,r,e.resultArea?.unit,!0):this._resultAreaHandler?.createConvexHull(t,e.resultArea?.distance,e.resultArea?.unit):t&&(s=this._resultAreaHandler?.createBuffer(t,r,e.resultArea?.unit,!0)),s&&Array.isArray(s)){if(s.length>0)for(const i of s){const t=this.getResultAreaAttributes(e,i),r=this._resultAreaHandler?.createResultAreaGraphic(i,t,e.resultArea?.areaUnit,this.messages,this.messagesUnits,e.resultArea?.color);if(r)return r}}else{const t=this.getResultAreaAttributes(e,s),r=this._resultAreaHandler?.createResultAreaGraphic(s,t,e.resultArea?.areaUnit,this.messages,this.messagesUnits,e.resultArea?.color);if(r)return r}}async createResultAreaGraphic(e){if(e.results){const t=await this._createResultAreaInputGeometry(e.results);if(t.length>0){const r=Array(t.length).fill(e.resultArea?.distance),s=this.createResultAreaGeometries(e,t,r);return this.emit("create-result-area",{graphic:s}),s}}}executeTrace(e,t,r){const s=this._processFlags(r.traceLocations);return r.traceLocations=s,v(t,r,{timeout:this._traceTimeout}).then((t=>({trace:e,results:t,selectionEnabled:!1,graphicEnabled:!1,graphicColor:this.defaultGraphicColor,status:"success",date:new Date}))).catch((t=>({trace:e,results:null,selectionEnabled:!1,graphicEnabled:!1,graphicColor:this.defaultGraphicColor,status:t.message,date:new Date})))}getResultAreaAttributes(e,r){const{messages:s}=this,i=[],a=[];this._flags.forEach((e=>{const t=e.displayValue?.field+":"+e.displayValue?.value+";"+s.attributeStrings.globalid+":"+e.globalId+";"+s.attributeStrings.terminalid+":"+e.terminalId+";"+s.attributeStrings.x+":"+e.mapPoint?.x+";"+s.attributeStrings.y+":"+e.mapPoint?.y;"starting-point"===e.type?i.push(t):a.push(t)}));return{traceId:e.trace.globalId,traceName:e.trace.title,traceDescription:e.trace.description??"",startingPoints:i.toString(),barriers:a.toString(),version:this.gdbVersion,username:t.credentials[0].userId,date:e.date,elementCount:e.results?.elements.length,functionResult:JSON.stringify(e.results?.globalFunctionResults),areaStatistic:r?this._geometryHandler.calculateArea(r,e.resultArea?.areaUnit):0}}getValidSources(){let e=[];const t=this.utilityNetwork?.dataElement?.domainNetworks??[];for(const r of t)e=e.concat(r.junctionSources),e=e.concat(r.edgeSources);return e}groupResultsByNetworkSource(e){return 0===e.length?[]:this._groupBy(e,"networkSourceId")}async loadUtilityNetwork(){const{view:e}=this;if(!e)return null;if(await e.when(),this.utilityNetwork){if(this.utilityNetwork.loaded||await this.utilityNetwork.load(),this.utilityNetwork instanceof f){try{const t=e.map;await t.loadAll(),this._loadUNSupportItems()}catch(i){this._loadUNSupportItems()}return this.utilityNetwork}return null}const t=e.map,r=t.utilityNetworks?.at(0);if(r){if(await r.load(),this.utilityNetwork=r,!await j(r))throw new s("utility-network:no-user-type-extension","User type extension not found");try{await t.loadAll(),this._loadUNSupportItems()}catch(i){}finally{this._loadUNSupportItems()}return r}return null}manageFilterBarrier(e,t){const r=[...this._flags];r.forEach((r=>{r.globalId===t.globalId&&"barrier"===t.type&&r.id===t.id&&(r.isFilterBarrier=e)})),this._flags=r}mergeSelection(e,t){let r=[];const s=[...this.traceResults],i=t.globalId;s.forEach((t=>{i===t.trace.globalId&&(t.selectionEnabled=e),t.selectionEnabled&&null!==t.results?.elements&&(r=[...r,...t.results?.elements??[]])})),this.selectResults([...new Set(r)])}async queryFeaturesById(e){const{view:t}=this;if(!t||!this.utilityNetwork)return null;const s=w(this.utilityNetwork,e),i={layerUrl:s[0].layerUrl,objectIds:s[0].objectIds,outFields:["*"]},a=t.map?.allTables.toArray().filter((e=>e?.parsedUrl?.path===s[0].layerUrl)).filter(m)??[];this._getUniqueMapLayerViews(t).filter((({layer:e})=>e?.parsedUrl?.path===s[0].layerUrl)).forEach((({layer:e})=>{"feature"!==e.type&&"subtype-group"!==e.type||a.push(e)}));const l=(await Promise.all(a.map((async e=>{const s={layers:new r([e]),layerInfos:[i],returnGeometry:!0,outSpatialReference:t.spatialReference},[a]=await _(s,!1);return a})))).filter((({featureSet:e})=>e.features.length>0));return l.length>0?l:null}queryFlagByHitTest(e,t,r){return this._lookupFlagByHit(e).then((e=>{const{view:s}=this;if(!s)return!1;if(e.length>0){const s=[...this._flags],i=r;return e.forEach((e=>{const r=e.graphic,a=r.attributes.hasOwnProperty("GLOBALID")?r.attributes.GLOBALID:r.attributes.globalid;if(s.filter((e=>e.globalId===a)).length<=0){const e=this.graphicHandler.getFlagGraphic(r.mapPoint,t,r,i);this._getGraphicLayer(H)?.add(e),s.push({...r,type:t,globalId:r.attributes.globalid||r.attributes.GLOBALID,details:r,mapGraphic:e,id:this._uniqueFlagId})}else if(null!==r.percentAlong){const e=this.graphicHandler.getFlagGraphic(r.mapPoint,t,r,i);this._getGraphicLayer(H)?.add(e),s.push({...r,type:t,globalId:r.attributes.globalid||r.attributes.GLOBALID,details:r,mapGraphic:e,id:this._uniqueFlagId})}})),this._flags=s,!0}return!1}))}removeResultGraphicFromView(e){const{view:t}=this;if(!t)return;const r=this._getGraphicLayer(P)?.graphics;e.graphicEnabled=!1;const s=r?.filter((t=>t.attributes[t.attributes.hasOwnProperty("GLOBALID")?"GLOBALID":"globalid"]===e.trace.globalId));s?.forEach((e=>{this._getGraphicLayer(P)?.remove(e)}))}removeFlag(e){const t=this._flags.filter((t=>{if(t.id!==e.id)return t}));this._removeGraphic(e),this._flags=t}removeAllResultAreaGraphics(){this._resultAreaHandler?.removeAllResultAreaGraphics(this.view.map)}removeResultAreaFromMap(e){if(e.resultArea){e.resultArea.show=!1;const t=this._resultAreaHandler?.removeResultArea(e.trace.globalId,this.view?.map);t&&this.emit("remove-result-area",{graphic:t})}}removeSelection(){this._highlightHandler.forEach((e=>{e&&e.remove()})),this._highlightHandler=[]}removeTerminal(e,t){const r=[...this._flags];r.forEach((r=>{if(r.globalId===t.globalId&&t.selectedTerminals?.includes(parseInt(e,10))){const s=t.selectedTerminals.indexOf(parseInt(e,10));r.selectedTerminals?.splice(s,1)}})),this._flags=r}removeFlagsOnLoadWatcher(){this._watchHandler&&null!==this._watchHandler&&this._watchHandler.remove()}reset(){this._flags=[],this.traceResults=[];const e=[...this.traces];e.forEach((e=>{e.selected=!1})),this.traces=e,this.view&&(this._getGraphicLayer(P)?.removeAll(),this._getGraphicLayer(H)?.removeAll(),this.removeAllResultAreaGraphics(),this.removeSelection(),this.emit("clear-selection",{resultSet:[]}))}selectFeaturesById(e){const{view:t}=this;if(!t||!this.utilityNetwork)return;const r=w(this.utilityNetwork,e);this._getUniqueMapLayerViews(t).forEach((e=>{C(e)&&e.layer?.parsedUrl?.path===r[0].layerUrl&&U(e)&&this._highlightHandler.push(e.highlight(r[0].objectIds))}))}selectResults(e){if(e.length>0){this.removeSelection();const t=this.groupResultsByNetworkSource(e),r=[];for(const e in t)this.selectFeaturesById(t[e]),r.push(this.queryFeaturesById(t[e]));Promise.all(r).then((e=>{this.emit("select-features",{resultSet:e})}))}else this.removeSelection(),this.emit("clear-selection",{resultSet:[]})}selectTraces(e,t){const r=[...this.traces];r.forEach((r=>{t===r.globalId&&(r.selected=e)})),this.traces=r}selectTracesOnLoad(){this.utilityNetwork?.hasOwnProperty("sharedNamedTraceConfigurations")&&(this.traces=[...this.utilityNetwork.sharedNamedTraceConfigurations],this.traces.forEach((e=>{e.selected=!1,this.selectedTraces.includes(e.globalId)&&(e.selected=!0)})))}zoomToAsset(e){this.view?.goTo(e).catch((e=>console.error(e)))}async _createResultAreaInputGeometry(e){if(null!=e.aggregatedGeometry)return this._geometryHandler.mergeAggregatedToGeometries(e.aggregatedGeometry);const t=this.groupResultsByNetworkSource(e.elements),r=[];for(const s in t)r.push(this.queryFeaturesById(t[s]));try{const e=await Promise.all(r),t=[];for(const r of e)if(r)for(const e of r)for(const r of e.featureSet.features)t.push(r.geometry);return t}catch{return[]}}_loadUNSupportItems(){if(!this.utilityNetwork)return;const{map:e}=this.view,{messages:t}=this;this._populateOutfields(),this._createGraphicLayer(H),this._createGraphicLayer(P),this._resultAreaHandler?.createGraphicLayer(e,t?.alertsStrings.genericResultHeader),this._validUNLayers=this._utilityHelper.getValidUtilityNetworkLayers(e,this.utilityNetwork)}_getUniqueMapLayerViews(e){const t=[];return e.layerViews.filter((({layer:{type:e}})=>"feature"===e||"group"===e||"subtype-group"===e)).toArray().forEach((e=>{switch(e.layer.type){case"group":if(E(e))for(const r of e.layerViews)t.push(r);break;case"subtype-group":t.push(e);break;default:t.some((t=>t.layer.id===e.layer.id))||t.push(e)}})),t}_processFlags(e){const t=[];return e.forEach((e=>{if(null!==e.selectedTerminals&&e.selectedTerminals.length>0)e.selectedTerminals.forEach((r=>{const s=new R({globalId:e.globalId,percentAlong:e.percentAlong,terminalId:r,type:e.type,isFilterBarrier:e.isFilterBarrier});t.push(s)}));else{const r=new R({globalId:e.globalId,percentAlong:e.percentAlong,terminalId:null,type:e.type,isFilterBarrier:e.isFilterBarrier});t.push(r)}})),t}_getDisplayField(e){return"subtype-sublayer"===e?.layer?.type?this._getDisplayFieldBySublayer(e):this._getDisplayFieldByFeatureLayer(e)}_getDisplayFieldBySublayer(e){let t="",r="";const s=e.layer;t=this._checkParentForData(s,"displayField");for(const i in e.attributes){const a=i.toLowerCase();a===t?.toLowerCase()?(r=e.attributes[i],"assetgroup"===a||"assettype"===a?r=this._checkSubtype(s,s.subtypeCode):(r=this._checkDomain(s.fields,i,r),"string"==typeof r&&(r=this._defaultDisplayField(r,s)))):(r=this._checkDomain(s.fields,i,r),"string"==typeof r&&(r=this._defaultDisplayField(r,s)))}return{field:t,value:r.toString()}}_getDisplayFieldByFeatureLayer(e){const t=e.layer;let r=t.displayField,s="";for(const i in e.attributes){const a=i.toLowerCase();if(a===r?.toLowerCase())if(s=e.attributes[i],"assetgroup"===a||"assettype"===a){let a=e.attributes[t.typeIdField.toUpperCase()];a||(a=e.attributes[t.typeIdField.toLowerCase()]),r=t.typeIdField,s=this._checkSubtype(t,a),""===r&&(t.templates&&t.templates.length>0?(r=t.templates[0]?.name,s=t.templates[0]?.name):(r=t.displayField,s=e.attributes[i]))}else s=this._checkDomain(t.fields,i,s),"string"==typeof s&&(s=this._defaultDisplayField(s,t));else s=this._checkDomain(t.fields,i,s),"string"==typeof s&&(s=this._defaultDisplayField(s,t))}return{field:r,value:s?s.toString():""}}_checkSubtype(e,t){let r=t;if("subtype-sublayer"===e.type){const s=this._checkParentForData(e,"subtypes");s?.length>0&&s.forEach((e=>{e.code===t&&(r=e.name)}))}else if(null!=e.types&&e.types.length>0){const s=e.types.filter((e=>e.id===t));s.length>0&&(r=s[0].name)}return r}_checkDomain(e,t,r){let s=r;const i=e.filter((e=>e.name.toLowerCase()===t.toLowerCase()));if(i.length>0&&N(i[0].domain)&&i[0].domain?.codedValues){const e=i[0].domain.codedValues.filter((({code:e})=>e===r));e.length>0&&(s=e[0].name)}return s}_checkParentForData(e,t){return e.parent?.[t]??null}_defaultDisplayField(e,t){return e.trim()?e:t.templates&&t.templates?.length>0?t.templates[0].name:t.title}get _uniqueFlagId(){return this._flagId++}_groupBy(e,t){return e.reduce(((e,r)=>((e[r[t]]=e[r[t]]||[]).push(r),e)),{})}async _lookupFlagByHit(e){if(null==e.mapPoint)return[];const t=await this.view.hitTest(e.screenPoint,{include:this._validUNLayers}),r=[];if(t.results.length>0){const s=t.results.find((e=>null!==e.layer));if(null!=s.graphic?.geometry)if("polyline"===s.graphic.geometry.type){const t=this._geometryHandler.getPercentageAlong(s.graphic.geometry,e.mapPoint,s.graphic.geometry.spatialReference),i=this._getDisplayField(s.graphic);s.graphic.terminalId=null,s.graphic.isFilterBarrier=!1,s.graphic.allTerminals=null,s.graphic.selectedTerminals=null,s.graphic.percentAlong=t,s.graphic.displayValue=i,s.graphic.mapPoint=s.mapPoint,r.push(s)}else if(("point"===s.graphic.geometry.type||"polygon"===s.graphic.geometry.type)&&null!==this.utilityNetwork){const e=this.utilityNetwork?.getTerminalConfiguration(s.graphic),t=this._getDisplayField(s.graphic);s.graphic.terminalId=e?e.terminals[0].id||null:1,s.graphic.isFilterBarrier=!1,s.graphic.allTerminals=e??null,s.graphic.selectedTerminals=[e?e.terminals[0].id||null:1],s.graphic.percentAlong=null,s.graphic.displayValue=t,s.graphic.mapPoint=s.mapPoint,r.push(s)}}return r}async _populateOutfields(){const e=this.view?.map,t=this.getValidSources();e?.layers.forEach((e=>{"group"===e.type?e.layers.forEach((e=>{t.some((t=>t.layerId===e.layerId))&&e.fields.some((e=>"assetgroup"===e.name.toLowerCase()))&&(e.outFields=["assetgroup","assettype","globalid","objectid"])})):t.some((t=>t.layerId===e.layerId))&&e.fields.some((e=>"assetgroup"===e.name.toLowerCase()))&&(e.outFields=["assetgroup","assettype","globalid","objectid"])}))}_removeGraphic(e){this._getGraphicLayer(H)?.remove(e.mapGraphic)}_createGraphicLayer(e){const{map:t}=this.view;if(!t.findLayerById(e)){const r=new g({title:e,listMode:"hide",id:e});t.add(r)}}_getGraphicLayer(e){const{map:t}=this.view;if(t){const r=t.findLayerById(e);if(r&&B(r))return r}return null}};e([o()],D.prototype,"_activeProgress",void 0),e([o()],D.prototype,"_flags",void 0),e([o()],D.prototype,"traces",void 0),e([o()],D.prototype,"defaultGraphicColor",void 0),e([o()],D.prototype,"enableResultArea",void 0),e([o()],D.prototype,"flags",void 0),e([o()],D.prototype,"gdbVersion",void 0),e([o()],D.prototype,"messages",void 0),e([o()],D.prototype,"messagesUnits",void 0),e([o()],D.prototype,"resultAreaProperties",null),e([o()],D.prototype,"selectedTraces",void 0),e([o()],D.prototype,"selectOnComplete",void 0),e([o()],D.prototype,"showGraphicsOnComplete",void 0),e([o()],D.prototype,"showSelectionAttributes",void 0),e([o({readOnly:!0})],D.prototype,"state",null),e([o()],D.prototype,"traceResults",void 0),e([o()],D.prototype,"utilityNetwork",void 0),e([o({value:null})],D.prototype,"view",null),D=e([n("esri.widgets.UtilityNetworkTrace.UtilityNetworkTraceViewModel")],D);const V=D;export{V as default};
5
+ import{_ as e}from"../../chunks/tslib.es6.js";import{id as t}from"../../kernel.js";import r from"../../core/Collection.js";import s from"../../core/Error.js";import i from"../../core/Evented.js";import a from"../../core/Logger.js";import{when as l}from"../../core/reactiveUtils.js";import{property as o}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/RandomLCG.js";import{subclass as n}from"../../core/accessorSupport/decorators/subclass.js";import c from"../../geometry/Point.js";import{isPoint as h,isMultipoint as u}from"../../geometry/support/jsonUtils.js";import{fetchMessageBundle as p}from"../../intl/messages.js";import d from"../../layers/FeatureLayer.js";import g from"../../layers/GraphicsLayer.js";import y from"../../layers/support/CodedValueDomain.js";import{isFeatureLayer as m}from"../../layers/support/layerUtils.js";import f from"../../networks/UtilityNetwork.js";import{getObjectIdsFromElements as w,getFeaturesFromLayers as _}from"../../networks/support/utils.js";import A from"../../portal/Portal.js";import{hasUserTypeExtension as b}from"../../portal/support/utils.js";import{trace as v}from"../../rest/networks/trace.js";import R from"../../rest/networks/support/TraceLocation.js";import I from"../../rest/networks/support/TraceParameters.js";import{GeometryHandler as k}from"./support/GeometryHandler.js";import{GraphicHandler as G}from"./support/GraphicHandler.js";import{ResultAreaHandler as F}from"./support/ResultAreaHandler.js";import{UtilityHelper as T}from"./support/UtilityHelper.js";const S=()=>p("esri/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace"),L=()=>p("esri/core/t9n/Units"),H=`utility-network-trace-flags-${Date.now()}`,P=`utility-network-trace-results-${Date.now()}`;function N(e){return e instanceof y}function U(e){return"feature"===e.layer.type||"subtype-group"===e.layer.type}function C(e){return"layer"in e}function E(e){return void 0!==e.layerViews}function B(e){return"graphics"===e.type}async function j(e){const t=new d({url:e.networkSystemLayers.dirtyAreasLayerUrl});await t.load();const r=t.version;if(Number(r)<=11.1){const t=new A({url:new URL(e.layerUrl).origin+"/portal"});await t.load();const r=t?.user?.username;return!!r&&b(t,r,"utilityNetwork")}return!0}let D=class extends i.EventedAccessor{constructor(e){super(e),this._activeProgress=!1,this._clickHandler=null,this._flags=[],this._flagId=0,this._geometryHandler=null,this._highlightHandler=[],this._resultAreaHandler=null,this._utilityHelper=new T,this._watchHandler=null,this._validUNLayers=[],this._traceTimeout=6e5,this.traces=[],this.graphicHandler=null,this.defaultGraphicColor={color:[255,255,0,.6],haloOpacity:.9,fillOpacity:.2,hex:"#FFFF00"},this.enableResultArea=!1,this.flags=[],this.gdbVersion="sde.DEFAULT",this.messages=null,this.messagesUnits=null,this.defaultResultAreaProperties={type:"convexhull",distance:10,unit:"meters",areaUnit:"square-meters",color:{color:[255,165,0,.5],haloOpacity:.9,fillOpacity:.2,hex:"#ffa500"},show:!1},this.selectedTraces=[],this.selectOnComplete=!0,this.showGraphicsOnComplete=!0,this.showSelectionAttributes=!0,this.traceResults=[],this.utilityNetwork=null}initialize(){this._geometryHandler=new k,this.graphicHandler=new G,this._resultAreaHandler=new F;(async()=>{const[e,t]=await Promise.all([S(),L()]);this.set({messages:e,messagesUnits:t})})()}destroy(){this.view=null}get resultAreaProperties(){return this.defaultResultAreaProperties}set resultAreaProperties(e){this._set("resultAreaProperties",{...this.defaultResultAreaProperties,...e}),this.graphicHandler.addCustomColor(this.resultAreaProperties.color),this.traceResults.forEach((t=>{const r=t.resultArea?.show;t.resultArea={...this.defaultResultAreaProperties,...e},this.removeResultAreaFromMap(t),this.enableResultArea&&this.createResultAreaGraphic(t).then((s=>{if(s){t.resultAreaGraphic=s;const i=e?.show??r;t.resultArea&&(t.resultArea.show=i),i&&this.addResultAreaToMap(t,s)}}))}))}get state(){return this.view?.ready?"ready":"loading"}get view(){return this._get("view")}set view(e){e&&"2d"!==e.type&&a.getLogger(this).error(new s("view:invalid-view","SceneView is not supported",{view:e})),this._set("view",e),this.utilityNetwork&&this.reset(),this.utilityNetwork=null,this.loadUtilityNetwork().then((e=>{e&&this.selectTracesOnLoad()}))}addFlagByHit(e,t){const r=e=>{this.view?.popup&&(this.view.popupEnabled=e)};return new Promise(((s,i)=>{r(!1),this._clickHandler?.remove(),this.emit("add-flag",{type:e}),this._clickHandler=this.view?.on("click",(a=>{this.queryFlagByHitTest(a,e,t).then((i=>{r(!0),this._clickHandler?.remove(),this.emit("add-flag-complete",{type:e,symbol:t}),s(i)})).catch((s=>{r(!0),this._clickHandler?.remove(),this.emit("add-flag-error",{type:e,symbol:t}),i(s)}))}))}))}async addFlagsOnLoad(){return new Promise((e=>{const t=[];this._watchHandler=l((()=>null!=this.view&&!this.view.updating),(async()=>{if(this._flags.length>0)e(t);else{const r=this.flags.map((async e=>{if(e.mapPoint){const r=new c({x:e.mapPoint.x,y:e.mapPoint.y,spatialReference:e.mapPoint.spatialReference.wkid}),s={screenPoint:this.view.toScreen(r),mapPoint:r};await this.queryFlagByHitTest(s,e.type)||("barrier"===e.type?t.push("barrier"):t.push("starting-point"))}}));await Promise.all(r),e(t)}}),{initial:!0})}))}async addResultAreaToMap(e,t){if(this.view)if(e.resultArea.show=!0,t)this._resultAreaHandler?.addResultAreaToMap(t,this.view.map),this.emit("add-result-area",{graphic:t});else if(e.results){const t=await this.createResultAreaGraphic(e);t&&(e.resultAreaGraphic=t,this._resultAreaHandler?.addResultAreaToMap(t,this.view.map),this.emit("add-result-area",{graphic:t}))}}async addResultGraphicToView(e,t){const{view:r}=this,{results:s}=e;if(r&&s&&this.utilityNetwork)for(const i in s.aggregatedGeometry)if("line,multipoint,polygon".includes(i)){const a=i,l=s.aggregatedGeometry[a];if(null!=l){l.spatialReference=this.utilityNetwork.spatialReference,e.graphicEnabled=!0;const s=await this._geometryHandler.projectGeometry(l,r.spatialReference),i={globalid:e.trace.globalId};if(null!==s){const e=this.graphicHandler.makeGraphic(s,t.color,i,r.spatialReference);this._getGraphicLayer(P)?.add(e)}}}}addTerminal(e,t){const r=[...this._flags];r.forEach((r=>{r.globalId===t.globalId&&(t.selectedTerminals?.includes(parseInt(e,10))||r.selectedTerminals?.push(parseInt(e,10)))})),this._flags=r}async callTrace(){const e=this.traces.filter((e=>e.selected));return e.length>0&&(this.traceResults.length>0&&this.traceResults.forEach((e=>{this.removeResultGraphicFromView(e)})),this.traceResults=[],this.removeSelection(),await Promise.all(e.map((async(e,t)=>{const r=e,s=new I({gdbVersion:this.gdbVersion,moment:null,traceType:r.traceType,traceLocations:this._flags,namedTraceConfigurationGlobalId:r.globalId,traceConfiguration:null,outSpatialReference:null,resultTypes:null});await this.executeTrace(r,this.utilityNetwork?.networkServiceUrl,s).then((e=>{if(e.hasOwnProperty("results")){const r={...e};if(null!==r.results){r.resultArea={...this.resultAreaProperties};const e=[...r.results.elements];r.results.elements.length=0;const s=new Map;for(const t of e)s.has(t.globalId)||(s.set(t.globalId,!0),r.results.elements.push(t));const i=[...this.traceResults];i.splice(t,0,r),this.traceResults=i,null!==r.results&&(this.selectOnComplete&&this.mergeSelection(!0,r.trace),this.showGraphicsOnComplete&&this.addResultGraphicToView(r,r.graphicColor),this.enableResultArea&&this.createResultAreaGraphic(r).then((e=>{e&&(r.resultAreaGraphic=e,r.resultArea?.show&&this.addResultAreaToMap(r,r.resultAreaGraphic))})))}else{const r=[...this.traceResults];r.splice(t,0,e),this.traceResults=r}this._activeProgress=!1}else{this._activeProgress=!1;const r=[...this.traceResults];r.splice(t,0,e),this.traceResults=r}})).catch((e=>{throw this._activeProgress=!1,e}))}))),!0)}changeResultAreaColor(e,t){if(!e.resultArea)return;e.resultArea.color=t;const r=this._resultAreaHandler?.changeResultAreaColor(e.trace.globalId,t,this.view.map);e.resultAreaGraphic&&(e.resultAreaGraphic.symbol=r)}changeResultGraphicColor(e,t){const r=[...this.traceResults];r.length>0&&r.forEach((r=>{r.trace.globalId===t.trace.globalId&&(r.graphicColor=e,r.graphicEnabled=!0)})),this.traceResults=r,this.removeResultGraphicFromView(t),this.addResultGraphicToView(t,e)}changeFlagSymbol(e,t){this._flags.length>0&&this._flags.forEach((r=>{r.type===e&&t&&r.mapGraphic&&(r.mapGraphic.symbol=t)}))}checkCanTrace(){const e={status:!0,issues:[]};let t=!1;const r=this._flags.some((e=>"starting-point"===e.type)),s=this._flags.filter((e=>null!==e.allTerminals));s.length>0&&(t=s.some((e=>e.selectedTerminals.length<=0)));let i=[];return r?(i=this.traces.filter((e=>e.selected)),i.length<=0?(e.status=!1,e.issues=["noTrace"],t&&(e.status=!1,e.issues=["noTrace","noTerminalSelected"])):t&&(e.status=!1,e.issues=["noTerminalSelected"])):(i=this.traces.filter((e=>!0===e.selected)),i.length>0?(e.status=!1,e.issues=["noStart"],t&&(e.status=!1,e.issues=["noStart","noTerminalSelected"])):(e.status=!1,e.issues=["noStart","noTrace"],t&&(e.status=!1,e.issues=["noStart","noTrace","noTerminalSelected"]))),e}checkSelectionExist(){return this._highlightHandler.some((e=>e))}clearResult(e){if(!this.view)return;let t=this.traceResults;if(t.length>0){const r=t.filter((t=>t.trace.globalId===e.globalId));r.length>0&&(this.removeResultGraphicFromView(r[0]),this.removeResultAreaFromMap(r[0])),t=t.filter((t=>t.trace.globalId!==e.globalId))}this.traceResults=t,0===t.length?(this.removeAllResultAreaGraphics(),this.removeSelection(),this.emit("clear-selection",{resultSet:[]})):this.mergeSelection(!1,e)}createResultAreaGeometries(e,t,r){if(!this.view||!this.resultAreaProperties)return;let s;if("convexhull"===this.resultAreaProperties?.type?s=1===t.length&&(h(t[0])||u(t[0])&&1===t[0].points.length)?this._resultAreaHandler?.createBuffer(t,r,e.resultArea?.unit,!0):this._resultAreaHandler?.createConvexHull(t,e.resultArea?.distance,e.resultArea?.unit):t&&(s=this._resultAreaHandler?.createBuffer(t,r,e.resultArea?.unit,!0)),s&&Array.isArray(s)){if(s.length>0)for(const i of s){const t=this.getResultAreaAttributes(e,i),r=this._resultAreaHandler?.createResultAreaGraphic(i,t,e.resultArea?.areaUnit,this.messages,this.messagesUnits,e.resultArea?.color);if(r)return r}}else{const t=this.getResultAreaAttributes(e,s),r=this._resultAreaHandler?.createResultAreaGraphic(s,t,e.resultArea?.areaUnit,this.messages,this.messagesUnits,e.resultArea?.color);if(r)return r}}async createResultAreaGraphic(e){if(e.results){const t=await this._createResultAreaInputGeometry(e.results);if(t.length>0){const r=Array(t.length).fill(e.resultArea?.distance),s=this.createResultAreaGeometries(e,t,r);return this.emit("create-result-area",{graphic:s}),s}}}executeTrace(e,t,r){const s=this._processFlags(r.traceLocations);return r.traceLocations=s,v(t,r,{timeout:this._traceTimeout}).then((t=>({trace:e,results:t,selectionEnabled:!1,graphicEnabled:!1,graphicColor:this.defaultGraphicColor,status:"success",date:new Date}))).catch((t=>({trace:e,results:null,selectionEnabled:!1,graphicEnabled:!1,graphicColor:this.defaultGraphicColor,status:t.message,date:new Date})))}getResultAreaAttributes(e,r){const{messages:s}=this,i=[],a=[];this._flags.forEach((e=>{const t=e.displayValue?.field+":"+e.displayValue?.value+";"+s.attributeStrings.globalid+":"+e.globalId+";"+s.attributeStrings.terminalid+":"+e.terminalId+";"+s.attributeStrings.x+":"+e.mapPoint?.x+";"+s.attributeStrings.y+":"+e.mapPoint?.y;"starting-point"===e.type?i.push(t):a.push(t)}));return{traceId:e.trace.globalId,traceName:e.trace.title,traceDescription:e.trace.description??"",startingPoints:i.toString(),barriers:a.toString(),version:this.gdbVersion,username:t.credentials[0].userId,date:e.date,elementCount:e.results?.elements.length,functionResult:JSON.stringify(e.results?.globalFunctionResults),areaStatistic:r?this._geometryHandler.calculateArea(r,e.resultArea?.areaUnit):0}}getValidSources(){let e=[];const t=this.utilityNetwork?.dataElement?.domainNetworks??[];for(const r of t)e=e.concat(r.junctionSources),e=e.concat(r.edgeSources);return e}groupResultsByNetworkSource(e){return 0===e.length?[]:this._groupBy(e,"networkSourceId")}async loadUtilityNetwork(){const{view:e}=this;if(!e)return null;if(await e.when(),this.utilityNetwork){if(this.utilityNetwork.loaded||await this.utilityNetwork.load(),this.utilityNetwork instanceof f){try{const t=e.map;await t.loadAll(),this._loadUNSupportItems()}catch(i){this._loadUNSupportItems()}return this.utilityNetwork}return null}const t=e.map,r=t.utilityNetworks?.at(0);if(r){if(await r.load(),this.utilityNetwork=r,!await j(r))throw new s("utility-network:no-user-type-extension","User type extension not found");try{await t.loadAll(),this._loadUNSupportItems()}catch(i){}finally{this._loadUNSupportItems()}return r}return null}manageFilterBarrier(e,t){const r=[...this._flags];r.forEach((r=>{r.globalId===t.globalId&&"barrier"===t.type&&r.id===t.id&&(r.isFilterBarrier=e)})),this._flags=r}mergeSelection(e,t){let r=[];const s=[...this.traceResults],i=t.globalId;s.forEach((t=>{i===t.trace.globalId&&(t.selectionEnabled=e),t.selectionEnabled&&null!==t.results?.elements&&(r=[...r,...t.results?.elements??[]])})),this.selectResults([...new Set(r)])}async queryFeaturesById(e){const{view:t}=this;if(!t||!this.utilityNetwork)return null;const s=w(this.utilityNetwork,e),i={layerUrl:s[0].layerUrl,objectIds:s[0].objectIds,outFields:["*"]},a=t.map?.allTables.toArray().filter((e=>e?.parsedUrl?.path===s[0].layerUrl)).filter(m)??[];this._getUniqueMapLayerViews(t).filter((({layer:e})=>e?.parsedUrl?.path===s[0].layerUrl)).forEach((({layer:e})=>{"feature"!==e.type&&"subtype-group"!==e.type||a.push(e)}));const l=(await Promise.all(a.map((async e=>{const s={layers:new r([e]),layerInfos:[i],returnGeometry:!0,outSpatialReference:t.spatialReference},[a]=await _(s,!1);return a})))).filter((({featureSet:e})=>e.features.length>0));return l.length>0?l:null}queryFlagByHitTest(e,t,r){return this._lookupFlagByHit(e).then((e=>{const{view:s}=this;if(!s)return!1;if(e.length>0){const s=[...this._flags],i=r;return e.forEach((e=>{const r=e.graphic,a=r.attributes.hasOwnProperty("GLOBALID")?r.attributes.GLOBALID:r.attributes.globalid;if(s.filter((e=>e.globalId===a)).length<=0){const e=this.graphicHandler.getFlagGraphic(r.mapPoint,t,r,i);this._getGraphicLayer(H)?.add(e),s.push({...r,type:t,globalId:r.attributes.globalid||r.attributes.GLOBALID,details:r,mapGraphic:e,id:this._uniqueFlagId})}else if(null!==r.percentAlong){const e=this.graphicHandler.getFlagGraphic(r.mapPoint,t,r,i);this._getGraphicLayer(H)?.add(e),s.push({...r,type:t,globalId:r.attributes.globalid||r.attributes.GLOBALID,details:r,mapGraphic:e,id:this._uniqueFlagId})}})),this._flags=s,!0}return!1}))}removeResultGraphicFromView(e){const{view:t}=this;if(!t)return;const r=this._getGraphicLayer(P)?.graphics;e.graphicEnabled=!1;const s=r?.filter((t=>t.attributes[t.attributes.hasOwnProperty("GLOBALID")?"GLOBALID":"globalid"]===e.trace.globalId));s?.forEach((e=>{this._getGraphicLayer(P)?.remove(e)}))}removeFlag(e){const t=this._flags.filter((t=>{if(t.id!==e.id)return t}));this._removeGraphic(e),this._flags=t}removeAllResultAreaGraphics(){this._resultAreaHandler?.removeAllResultAreaGraphics(this.view.map)}removeResultAreaFromMap(e){if(e.resultArea){e.resultArea.show=!1;const t=this._resultAreaHandler?.removeResultArea(e.trace.globalId,this.view?.map);t&&this.emit("remove-result-area",{graphic:t})}}removeSelection(){this._highlightHandler.forEach((e=>{e&&e.remove()})),this._highlightHandler=[]}removeTerminal(e,t){const r=[...this._flags];r.forEach((r=>{if(r.globalId===t.globalId&&t.selectedTerminals?.includes(parseInt(e,10))){const s=t.selectedTerminals.indexOf(parseInt(e,10));r.selectedTerminals?.splice(s,1)}})),this._flags=r}removeFlagsOnLoadWatcher(){this._watchHandler&&null!==this._watchHandler&&this._watchHandler.remove()}reset(){this._flags=[],this.traceResults=[];const e=[...this.traces];e.forEach((e=>{e.selected=!1})),this.traces=e,this.view&&(this._getGraphicLayer(P)?.removeAll(),this._getGraphicLayer(H)?.removeAll(),this.removeAllResultAreaGraphics(),this.removeSelection(),this.emit("clear-selection",{resultSet:[]}))}selectFeaturesById(e){const{view:t}=this;if(!t||!this.utilityNetwork)return;const r=w(this.utilityNetwork,e);this._getUniqueMapLayerViews(t).forEach((e=>{C(e)&&e.layer?.parsedUrl?.path===r[0].layerUrl&&U(e)&&this._highlightHandler.push(e.highlight(r[0].objectIds))}))}selectResults(e){if(e.length>0){this.removeSelection();const t=this.groupResultsByNetworkSource(e),r=[];for(const e in t)this.selectFeaturesById(t[e]),r.push(this.queryFeaturesById(t[e]));Promise.all(r).then((e=>{this.emit("select-features",{resultSet:e})}))}else this.removeSelection(),this.emit("clear-selection",{resultSet:[]})}selectTraces(e,t){const r=[...this.traces];r.forEach((r=>{t===r.globalId&&(r.selected=e)})),this.traces=r}selectTracesOnLoad(){this.utilityNetwork?.hasOwnProperty("sharedNamedTraceConfigurations")&&(this.traces=[...this.utilityNetwork.sharedNamedTraceConfigurations],this.traces.forEach((e=>{e.selected=!1,this.selectedTraces.includes(e.globalId)&&(e.selected=!0)})))}zoomToAsset(e){this.view?.goTo(e).catch((e=>console.error(e)))}async _createResultAreaInputGeometry(e){if(null!=e.aggregatedGeometry)return this._geometryHandler.mergeAggregatedToGeometries(e.aggregatedGeometry);const t=this.groupResultsByNetworkSource(e.elements),r=[];for(const s in t)r.push(this.queryFeaturesById(t[s]));try{const e=await Promise.all(r),t=[];for(const r of e)if(r)for(const e of r)for(const r of e.featureSet.features)t.push(r.geometry);return t}catch{return[]}}_loadUNSupportItems(){if(!this.utilityNetwork)return;const{map:e}=this.view,{messages:t}=this;this._populateOutfields(),this._createGraphicLayer(H),this._createGraphicLayer(P),this._resultAreaHandler?.createGraphicLayer(e,t?.alertsStrings.genericResultHeader),this._validUNLayers=this._utilityHelper.getValidUtilityNetworkLayers(e,this.utilityNetwork)}_getUniqueMapLayerViews(e){const t=[];return e.layerViews.filter((({layer:{type:e}})=>"feature"===e||"group"===e||"subtype-group"===e)).toArray().forEach((e=>{switch(e.layer.type){case"group":if(E(e))for(const r of e.layerViews)t.push(r);break;case"subtype-group":t.push(e);break;default:t.some((t=>t.layer.id===e.layer.id))||t.push(e)}})),t}_processFlags(e){const t=[];return e.forEach((e=>{if(null!==e.selectedTerminals&&e.selectedTerminals.length>0)e.selectedTerminals.forEach((r=>{const s=new R({globalId:e.globalId,percentAlong:e.percentAlong,terminalId:r,type:e.type,isFilterBarrier:e.isFilterBarrier});t.push(s)}));else{const r=new R({globalId:e.globalId,percentAlong:e.percentAlong,terminalId:null,type:e.type,isFilterBarrier:e.isFilterBarrier});t.push(r)}})),t}_getDisplayField(e){return"subtype-sublayer"===e?.layer?.type?this._getDisplayFieldBySublayer(e):this._getDisplayFieldByFeatureLayer(e)}_getDisplayFieldBySublayer(e){let t="",r="";const s=e.layer;t=this._checkParentForData(s,"displayField");for(const i in e.attributes){const a=i.toLowerCase();a===t?.toLowerCase()?(r=e.attributes[i],"assetgroup"===a||"assettype"===a?r=this._checkSubtype(s,s.subtypeCode):(r=this._checkDomain(s.fields,i,r),"string"==typeof r&&(r=this._defaultDisplayField(r,s)))):(r=this._checkDomain(s.fields,i,r),"string"==typeof r&&(r=this._defaultDisplayField(r,s)))}return{field:t,value:r.toString()}}_getDisplayFieldByFeatureLayer(e){const t=e.layer;let r=t.displayField,s="";for(const i in e.attributes){const a=i.toLowerCase();if(a===r?.toLowerCase())if(s=e.attributes[i],"assetgroup"===a||"assettype"===a){let a=e.attributes[t.typeIdField.toUpperCase()];a||(a=e.attributes[t.typeIdField.toLowerCase()]),r=t.typeIdField,s=this._checkSubtype(t,a),""===r&&(t.templates&&t.templates.length>0?(r=t.templates[0]?.name,s=t.templates[0]?.name):(r=t.displayField,s=e.attributes[i]))}else s=this._checkDomain(t.fields,i,s),"string"==typeof s&&(s=this._defaultDisplayField(s,t));else s=this._checkDomain(t.fields,i,s),"string"==typeof s&&(s=this._defaultDisplayField(s,t))}return{field:r,value:s?s.toString():""}}_checkSubtype(e,t){let r=t;if("subtype-sublayer"===e.type){const s=this._checkParentForData(e,"subtypes");s?.length>0&&s.forEach((e=>{e.code===t&&(r=e.name)}))}else if(null!=e.types&&e.types.length>0){const s=e.types.filter((e=>e.id===t));s.length>0&&(r=s[0].name)}return r}_checkDomain(e,t,r){let s=r;const i=e.filter((e=>e.name.toLowerCase()===t.toLowerCase()));if(i.length>0&&N(i[0].domain)&&i[0].domain?.codedValues){const e=i[0].domain.codedValues.filter((({code:e})=>e===r));e.length>0&&(s=e[0].name)}return s}_checkParentForData(e,t){return e.parent?.[t]??null}_defaultDisplayField(e,t){return e.trim()?e:t.templates&&t.templates?.length>0?t.templates[0].name:t.title}get _uniqueFlagId(){return this._flagId++}_groupBy(e,t){return e.reduce(((e,r)=>((e[r[t]]=e[r[t]]||[]).push(r),e)),{})}async _lookupFlagByHit(e){if(null==e.mapPoint)return[];const t=await this.view.hitTest(e.screenPoint,{include:this._validUNLayers}),r=[];if(t.results.length>0){const s=t.results.find((e=>null!==e.layer));if(null!=s.graphic?.geometry)if("polyline"===s.graphic.geometry.type){const t=this._geometryHandler.getPercentageAlong(s.graphic.geometry,e.mapPoint,s.graphic.geometry.spatialReference),i=this._getDisplayField(s.graphic);s.graphic.terminalId=null,s.graphic.isFilterBarrier=!1,s.graphic.allTerminals=null,s.graphic.selectedTerminals=null,s.graphic.percentAlong=t,s.graphic.displayValue=i,s.graphic.mapPoint=s.mapPoint,r.push(s)}else if(("point"===s.graphic.geometry.type||"polygon"===s.graphic.geometry.type)&&null!==this.utilityNetwork){const e=this.utilityNetwork?.getTerminalConfiguration(s.graphic),t=this._getDisplayField(s.graphic);s.graphic.terminalId=e?e.terminals[0].id||null:1,s.graphic.isFilterBarrier=!1,s.graphic.allTerminals=e??null,s.graphic.selectedTerminals=[e?e.terminals[0].id||null:1],s.graphic.percentAlong=null,s.graphic.displayValue=t,s.graphic.mapPoint=s.mapPoint,r.push(s)}}return r}async _populateOutfields(){const e=this.view?.map,t=this.getValidSources();e?.layers.forEach((e=>{"group"===e.type?e.layers.forEach((e=>{t.some((t=>t.layerId===e.layerId))&&e.fields.some((e=>"assetgroup"===e.name.toLowerCase()))&&(e.outFields=["assetgroup","assettype","globalid","objectid"])})):t.some((t=>t.layerId===e.layerId))&&e.fields.some((e=>"assetgroup"===e.name.toLowerCase()))&&(e.outFields=["assetgroup","assettype","globalid","objectid"])}))}_removeGraphic(e){this._getGraphicLayer(H)?.remove(e.mapGraphic)}_createGraphicLayer(e){const{map:t}=this.view;if(!t.findLayerById(e)){const r=new g({title:e,listMode:"hide",id:e});t.add(r)}}_getGraphicLayer(e){const{map:t}=this.view;if(t){const r=t.findLayerById(e);if(r&&B(r))return r}return null}};e([o()],D.prototype,"_activeProgress",void 0),e([o()],D.prototype,"_flags",void 0),e([o()],D.prototype,"traces",void 0),e([o()],D.prototype,"defaultGraphicColor",void 0),e([o()],D.prototype,"enableResultArea",void 0),e([o()],D.prototype,"flags",void 0),e([o()],D.prototype,"gdbVersion",void 0),e([o()],D.prototype,"messages",void 0),e([o()],D.prototype,"messagesUnits",void 0),e([o()],D.prototype,"resultAreaProperties",null),e([o()],D.prototype,"selectedTraces",void 0),e([o()],D.prototype,"selectOnComplete",void 0),e([o()],D.prototype,"showGraphicsOnComplete",void 0),e([o()],D.prototype,"showSelectionAttributes",void 0),e([o({readOnly:!0})],D.prototype,"state",null),e([o()],D.prototype,"traceResults",void 0),e([o()],D.prototype,"utilityNetwork",void 0),e([o({value:null})],D.prototype,"view",null),D=e([n("esri.widgets.UtilityNetworkTrace.UtilityNetworkTraceViewModel")],D);const V=D;export{V as default};