@arcgis/core 4.34.0-next.80 → 4.34.0-next.82

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 (111) hide show
  1. package/analysis/VolumeMeasurement/VolumeMeasurementDisplayUnits.d.ts +4 -0
  2. package/analysis/VolumeMeasurement/VolumeMeasurementDisplayUnits.js +5 -0
  3. package/analysis/VolumeMeasurement/VolumeMeasurementInputUnits.d.ts +4 -0
  4. package/analysis/VolumeMeasurement/VolumeMeasurementInputUnits.js +5 -0
  5. package/analysis/VolumeMeasurementAnalysis.js +1 -1
  6. package/assets/esri/core/workers/RemoteClient.js +1 -1
  7. package/assets/esri/core/workers/chunks/{c90571063bd2bb57a5a7.js → 1d491447b13f2f2b4399.js} +1 -1
  8. package/assets/esri/core/workers/chunks/264a9a916e1e972b69d7.js +1 -0
  9. package/assets/esri/core/workers/chunks/30c85a1a4f118cc45a25.js +1 -0
  10. package/assets/esri/core/workers/chunks/3192b68675ff2afcb1d6.js +1 -0
  11. package/assets/esri/core/workers/chunks/365d63c2aed3a49918f2.js +1 -0
  12. package/assets/esri/core/workers/chunks/3ef8a7468d7e3b2f0b69.js +351 -0
  13. package/assets/esri/core/workers/chunks/a1196637268b89281780.js +1 -0
  14. package/assets/esri/core/workers/chunks/a1b08aab73747f4e7e25.js +1 -0
  15. package/assets/esri/core/workers/chunks/{b815c2f61fb9c58a2956.js → b6c4712e00fce87bd0f4.js} +1 -1
  16. package/assets/esri/core/workers/chunks/{db2396bf062468ee8b60.js → b8810711d058300395cd.js} +1 -1
  17. package/assets/esri/core/workers/chunks/{22bd4255b6b511a43b66.js → c2bc70b65f5c2a2c9671.js} +1 -1
  18. package/assets/esri/core/workers/chunks/cc579c94438f48a0dbab.js +1 -0
  19. package/assets/esri/core/workers/chunks/e1b3ae6426886e2fab07.js +1 -0
  20. package/assets/esri/core/workers/chunks/e4acc3c2b6d865ed1940.js +1 -0
  21. package/assets/esri/core/workers/chunks/f6513ec888a7d927d948.js +1 -0
  22. package/assets/esri/core/workers/chunks/{ede479faa4e6920fe673.js → f8f85207b382c1ea038c.js} +17 -9
  23. package/assets/esri/core/workers/chunks/{23a13fbab9984953a7c6.js → fc06014fb484fc8c697e.js} +1 -1
  24. package/assets/esri/libs/dracoMeshDecoder/draco_mesh_decoder.wasm +0 -0
  25. package/chunks/CutFillComposition.glsl.js +8 -0
  26. package/chunks/CutFillMask.glsl.js +6 -0
  27. package/chunks/GaussianSplat.glsl.js +2 -2
  28. package/chunks/HUDMaterial.glsl.js +4 -6
  29. package/chunks/draco_mesh_decoder.js +5 -0
  30. package/config.js +1 -1
  31. package/core/unitUtils.js +1 -1
  32. package/interfaces.d.ts +147 -13
  33. package/kernel.js +1 -1
  34. package/layers/CSVLayer.js +1 -1
  35. package/layers/FeatureLayer.js +1 -1
  36. package/layers/IntegratedMesh3DTilesLayer.js +1 -1
  37. package/layers/OrientedImageryLayer.js +1 -1
  38. package/layers/support/ElevationSampler.js +1 -1
  39. package/layers/support/FieldConfiguration.js +1 -1
  40. package/layers/support/rasterDatasets/BaseRaster.js +1 -1
  41. package/layers/support/rasterDatasets/datasetUtils.js +1 -1
  42. package/libs/dracoMeshDecoder/dracoMeshDecoder.js +5 -0
  43. package/package.json +1 -1
  44. package/portal/schemas/definitions.js +1 -1
  45. package/rest/featureService/FeatureService.js +1 -1
  46. package/support/revision.js +1 -1
  47. package/views/2d/engine/Stage.js +1 -1
  48. package/views/2d/engine/webgl/shaderGraph/techniques/TextureStatisticsTechnique.js +1 -1
  49. package/views/2d/engine/webgl/shaderGraph/techniques/shaders/TextureStatisticsDiffShader.js +1 -1
  50. package/views/2d/engine/webgl/shaderGraph/techniques/shaders/TextureStatisticsMinMaxSumShader.js +1 -1
  51. package/views/2d/engine/webgl/shaderGraph/techniques/shaders/TextureStatisticsStdDevShader.js +1 -1
  52. package/views/2d/engine/webgl/shaderGraph/techniques/shaders/TextureStatisticsSumOfSquaredDiffShader.js +1 -1
  53. package/views/3d/analysis/VolumeMeasurement/VolumeMeasurementCutFillComputation.js +1 -1
  54. package/views/3d/analysis/VolumeMeasurement/VolumeMeasurementCutFillController.js +1 -1
  55. package/views/3d/analysis/VolumeMeasurement/VolumeMeasurementShiftTool.js +1 -1
  56. package/views/3d/analysis/VolumeMeasurementAnalysisView3D.js +1 -1
  57. package/views/3d/glTF/internal/Resource.js +1 -1
  58. package/views/3d/glTF/loader.js +1 -1
  59. package/views/3d/layers/FlowSubView3D.js +1 -1
  60. package/views/3d/layers/GaussianSplatLayerView3D.js +1 -1
  61. package/views/3d/layers/graphics/pipeline/Feature3DPipelineWorker.js +1 -1
  62. package/views/3d/layers/graphics/pipeline/Feature3DPipelineWorkerHandle.js +1 -1
  63. package/views/3d/layers/graphics/pipeline/rendering/DirectRenderer.js +1 -1
  64. package/views/3d/layers/graphics/pipeline/rendering/FeaturePipelineRenderManager.js +1 -1
  65. package/views/3d/layers/graphics/pipeline/rendering/RenderCommandContext.js +1 -1
  66. package/views/3d/layers/graphics/pipeline/symbolization/IconSymbolLayerRenderer.js +1 -1
  67. package/views/3d/layers/support/HeatmapFeatureProcessor.js +1 -1
  68. package/views/3d/support/buffer/InterleavedLayout.js +1 -1
  69. package/views/3d/support/engineContent/line.js +1 -1
  70. package/views/3d/support/flow/FlowSubViewTiles3D.js +1 -1
  71. package/views/3d/support/flow/constants.js +1 -1
  72. package/views/3d/support/flow/geometryUtils.js +1 -1
  73. package/views/3d/support/gaussianSplatting/GaussianSplatDataStore.js +1 -1
  74. package/views/3d/support/gaussianSplatting/GaussianSplatQualitySettings.js +5 -0
  75. package/views/3d/support/gaussianSplatting/GaussianSplatTextureAtlas.js +1 -1
  76. package/views/3d/webgl-engine/core/shaderLibrary/attributes/MaskedColor.glsl.js +15 -7
  77. package/views/3d/webgl-engine/lib/CutFillColor.js +5 -0
  78. package/views/3d/webgl-engine/lib/GaussianSplatRenderNode.js +1 -1
  79. package/views/3d/webgl-engine/lib/GeometryUtil.js +1 -1
  80. package/views/3d/webgl-engine/lib/OrderIndependentTransparency.js +1 -1
  81. package/views/3d/webgl-engine/lib/Renderer.js +1 -1
  82. package/views/3d/webgl-engine/materials/HUDMaterial.js +1 -1
  83. package/views/3d/webgl-engine/materials/HUDMaterialBaseInstance.js +5 -0
  84. package/views/3d/webgl-engine/materials/HeatmapDensityMaterial.js +1 -1
  85. package/views/3d/webgl-engine/materials/RibbonLineMaterial.js +1 -1
  86. package/views/3d/webgl-engine/materials/renderers/VaoWriter.js +1 -1
  87. package/views/3d/webgl-engine/shaders/CutFillComposition.glsl.js +5 -0
  88. package/views/3d/webgl-engine/shaders/CutFillCompositionTechnique.js +5 -0
  89. package/views/3d/webgl-engine/shaders/CutFillMask.glsl.js +5 -0
  90. package/views/3d/webgl-engine/shaders/CutFillMaskTechnique.js +5 -0
  91. package/views/3d/webgl-engine/shaders/HUDMaterialTechnique.js +1 -1
  92. package/views/3d/webgl-engine/shaders/HeatmapDensityTechnique.js +1 -1
  93. package/views/3d/webgl-engine/shaders/ImageMaterialTechnique.js +1 -1
  94. package/views/3d/webgl.js +1 -1
  95. package/views/webgl/VertexArrayObject.js +1 -1
  96. package/widgets/Attribution/AttributionViewModel.js +1 -1
  97. package/widgets/Feature/FeatureMedia/FeatureMediaViewModel.js +1 -1
  98. package/widgets/Legend/LegendViewModel.js +1 -1
  99. package/widgets/Legend/support/ActiveLayerInfo.js +1 -1
  100. package/widgets/Search/SearchViewModel.js +1 -1
  101. package/widgets/Search.js +1 -1
  102. package/assets/esri/core/workers/chunks/07a355a9c95154971aab.js +0 -1
  103. package/assets/esri/core/workers/chunks/22a66db7d73e733917e3.js +0 -1
  104. package/assets/esri/core/workers/chunks/49486c2e12e768b347ed.js +0 -1
  105. package/assets/esri/core/workers/chunks/66e0bc4acb18f00a433d.js +0 -1
  106. package/assets/esri/core/workers/chunks/76db75337044de8218c9.js +0 -353
  107. package/assets/esri/core/workers/chunks/978fab0f0b10edde4ff8.js +0 -1
  108. package/assets/esri/core/workers/chunks/a07321a901d6847d1a6b.js +0 -1
  109. package/assets/esri/core/workers/chunks/ae8dce1a43ca7019f81d.js +0 -1
  110. package/assets/esri/core/workers/chunks/cb3b88959b2f048e54a5.js +0 -1
  111. package/assets/esri/core/workers/chunks/da1a5537e2f2ca6cc247.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.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import t from"../../config.js";import{id as s}from"../../kernel.js";import r from"../../request.js";import{isSome as i}from"../../core/arrayUtils.js";import a from"../../core/Error.js";import{IdentifiableMixin as o}from"../../core/Identifiable.js";import{JSONSupportMixin as n}from"../../core/JSONSupport.js";import{clone as l}from"../../core/lang.js";import{Loadable as d}from"../../core/Loadable.js";import{throwIfAborted as u,throwIfAbortError as p}from"../../core/promiseUtils.js";import{property as c}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/Logger.js";import{reader as m}from"../../core/accessorSupport/decorators/reader.js";import{subclass as y}from"../../core/accessorSupport/decorators/subclass.js";import h from"../../geometry/SpatialReference.js";import{getFeatureJSON as f,getFeatureIds as b,getAttachmentEditsJSON as g,isProtectedOrPrivateVersionError as v,unpackEditResultData as j,createEditedFeatures as S}from"../../layers/graphics/applyEditsUtils.js";import{checkEditingCapabilities as E,normalizeEdits as I,normalizeGeometries as O}from"../../layers/graphics/editingSupport.js";import{emitApplyEditsEvent as F}from"../../layers/mixins/EditBusLayer.js";import{ensureCredentialIfSignedIn as R}from"../../layers/support/featureLayerUtils.js";import{getOwningPortalUrl as A}from"../../layers/support/layerUtils.js";import{getFeatureLayerCapabilities as w}from"../../layers/support/serviceCapabilitiesUtils.js";import T from"../../portal/PortalItem.js";import{getUserPrivileges as U}from"../../portal/support/portalItemUtils.js";import{isSecureProxyService as C}from"../../portal/support/urlUtils.js";import{parseUrl as D,asValidOptions as P,encode as V}from"../utils.js";import{unapplyEditsZUnitScaling as G}from"../query/operations/editsZScale.js";import{readBoolean as k,readNumber as _}from"../support/jsonUtils.js";import{isSafeToEditVersion as x,isVersionInEditSession as L,currentSessionId as M}from"../../versionManagement/support/versionManagementUtils.js";function N(e,t){const s=t.id;return{id:s,name:t.name,url:`${e}/${s}`,type:t.type||"Table"}}function Q(e){return{data:J(e),sync:B(e),operations:q(e.capabilities,e),query:W(e),editing:H(e)}}function J(e){return{isDataVersioned:k(e,"hasVersionedData",!1),isDataBranchVersioned:k(e,"hasBranchVersionedData",!1)}}function q(e,t){const s=e?e.toLowerCase().split(",").map(e=>e.trim()):[],r=s.includes("query"),i=s.includes("editing")&&!t.datesInUnknownTimezone;let a=i&&s.includes("create"),o=i&&s.includes("delete"),n=i&&s.includes("update");return i&&!(a||o||n)&&(a=o=n=!0),{supportsAdd:a,supportsDelete:o,supportsEditing:i,supportsChangeTracking:s.includes("changetracking"),supportsQuery:r,supportsQueryDataElements:k(t,"supportsQueryDataElements",!1),supportsQueryDomains:k(t,"supportsQueryDomains",!1),supportsQueryContingentValues:k(t,"supportsQueryContingentValues",!1),supportsSync:s.includes("sync"),supportsUpdate:n}}function W(e){return{maxRecordCountFactor:_(e,"maxRecordCountFactor",void 0),maxRecordCount:_(e,"maxRecordCount",void 0)}}function H(e){const t=e?.advancedEditingCapabilities;return{supportsAsyncApplyEdits:k(t,"supportsAsyncApplyEdits",!1),supportsGlobalId:k(e,"supportsApplyEditsWithGlobalIds",!1),supportsReturnServiceEditsInSourceSpatialReference:k(t,"supportsReturnServiceEditsInSourceSR",!1),supportsSharedTemplates:k(e,"supportsSharedTemplates",!1)||k(e,"hasSharedTemplates",!1),supportsSplit:k(t,"supportsSplit",!1)}}function B(e){const t=e?.syncCapabilities,s=t?.supportedSyncDataOptions;return{supportsAsync:k(t,"supportsAsync",!1),supportedSyncDataOptions:{annotations:!(1&~s),dimensions:!(2&~s),contingentValues:!(4&~s),attributeRules:!(8&~s),utilityNetworkSystem:!(16&~s),annotationFullModel:!(32&~s),include3DObjects:!(64&~s),utilityNetworkMissingLayers:!(128&~s),preserveTrueCurves:!(256&~s)}}}let $=class extends(n(o(d))){constructor(e){super(e),this.url=null,this.sourceJSON=null,this.userHasFullEditingPrivileges=!1,this.userHasUpdateItemPrivileges=!1,this.userTypeExtensions=[],this.layerInfos=null,this.tableInfos=null,this.capabilities=null,this._layerTableIndex=new Map}read(e,t){this.sourceJSON=e,super.read(e,t)}get utilityNetworkUrl(){if(this.sourceJSON)for(const e of this.sourceJSON.layers)if("Utility Network Layer"===e.type)return`${this.url}/${e.id}`;return null}get versionManagementServiceUrl(){return this.sourceJSON?.hasBranchVersionedData&&!C(this.url)?this.url.replace(/\/FeatureServer/i,"/VersionManagementServer"):null}readLayerInfos(e,t){return(t.layers||[]).map(e=>{const{type:t,geometryType:s}=e;return{...N(this.url,e),type:t||"Feature Layer",geometryType:s}})}readTableInfos(e,t){return(t.tables||[]).map(e=>N(this.url,e))}readCapabilities(e,t){return Q(t)}get effectiveCapabilities(){const e=this.capabilities;if(!e)return null;const t=l(e),{operations:s}=t;return this.userHasUpdateItemPrivileges?(s.supportsAdd=s.supportsDelete=s.supportsEditing=s.supportsQuery=s.supportsUpdate=!0,t):(this.userHasFullEditingPrivileges&&s.supportsEditing&&(s.supportsAdd=s.supportsDelete=s.supportsUpdate=!0),t)}get loaded(){return super.loaded}load(e){return this.addResolvingPromise(this._fetchService(this.url,e).then(()=>this._setUserPrivileges(e))),Promise.resolve(this)}async fetchAllLayersAndTables(e){return await this.load(e),this._fetchLayersAndTablesPromise||=this._fetchLayersAndTables(this.url),u(e),this._fetchLayersAndTablesPromise}async applyEdits(e,t){let s=null;try{const{results:r,edits:i,editedFeatures:a}=await this._internalApplyEdits(e,t),o=e=>e.filter(e=>!e.error).map(l);let n=0;return r.map(e=>{s=F(this.url,e.id,t?.gdbVersion,!0);const r={edits:i[n],addedFeatures:o(e.addFeatureResults),updatedFeatures:o(e.updateFeatureResults),deletedFeatures:o(e.deleteFeatureResults),addedAttachments:o(e.addAttachmentResults),updatedAttachments:o(e.updateAttachmentResults),deletedAttachments:o(e.deleteAttachmentResults),exceededTransferLimit:!1,historicMoment:e.editMoment?new Date(e.editMoment):null};n+=1,a.length>0&&(r.editedFeatures=a),s.resolve(r),s=null}),r}catch(r){throw s&&s.reject(r),r}}async _setUserPrivileges(e){if(t.userPrivilegesApplied)try{const{features:{fullEdit:t},content:{updateItem:s}}=await this._fetchUserPrivileges(this.sourceJSON.serviceItemId,e);this._set("userHasFullEditingPrivileges",t),this._set("userHasUpdateItemPrivileges",s)}catch(s){p(s)}}async _fetchUserPrivileges(e,t){const r=!0,i=!1,a=!1;if(!e)return{features:{edit:r,fullEdit:i},content:{updateItem:a}};let o,n,l;try{o=await A(this.url,t)}catch(d){p(d)}try{const e=null!=t?t.signal:null;n=await(s?.getCredential(`${o}/sharing`,{prompt:!1,signal:e}))}catch(d){p(d)}if(!n)return{features:{edit:r,fullEdit:i},content:{updateItem:a}};try{if(l=new T({id:e,portal:{url:o}}),await l.load(t),l.portal.user)return U(l)}catch(d){p(d)}return{features:{edit:r,fullEdit:i},content:{updateItem:a}}}async _internalApplyEdits(e,t){await R(this.url);const s=t?.globalIdUsed??!1,a=h.fromJSON(this.sourceJSON.spatialReference),{edits:o,options:n}=await this._processApplyEditsParams(e,t),l=await Promise.all(o.map(async e=>{const t=e.addFeatures?.map(e=>f({spatialReference:a},e,null))??[],r=(await Promise.all(t)).filter(i),o=r.length>0?r:null,n=e.updateFeatures?.map(e=>f({spatialReference:a},e,null))??[],l=(await Promise.all(n)).filter(i),d=l.length>0?l:null,u=b(e.identifierFields,e.deleteFeatures,s),p=u.length>0?u:null;G(o,d,a);const c=await g(e.identifierFields,e);let m=null;if(c){m={adds:c.adds.length>0?c.adds:void 0,updates:c.updates.length>0?c.updates:void 0,deletes:c.deletes.length>0?c.deletes:void 0}}const y={};return e.deleteAssociations&&(y.deleteAssociations=e.deleteAssociations),e.combineGroupedObjects&&(y.combineGroupedObjects=e.combineGroupedObjects),e.divideGroupedObjects&&(y.divideGroupedObjects=e.divideGroupedObjects),{id:e.id,adds:o,updates:d,deletes:p,attachments:m,...y}})),d={gdbVersion:n?.gdbVersion,rollbackOnFailure:!0,useGlobalIds:s,returnEditMoment:!0,honorSequenceOfEdits:n?.honorSequenceOfEdits,usePreviousEditMoment:n?.usePreviousEditMoment,returnServiceEditsInSourceSR:!1,returnServiceEditsOption:"originalAndCurrentFeatures",async:!1};await x(this.url,t?.gdbVersion,!0);const u=L(this.url,t?.gdbVersion||null);d.edits=JSON.stringify(l);const p=D(this.url),c=P(p.query,{query:V({...d,f:"json"}),method:"post"});let m;u&&(c.authMode="immediate",c.query.sessionId=M);try{m=await r(this.url+"/applyEdits",c)}catch(y){if(!v(y))throw y;c.authMode="immediate",m=await r(this.url+"/applyEdits",c)}return{...z(m),edits:o}}async _processApplyEditsParams(e,t){const s={...t,usingFeatureServiceEndpoint:!0,usingTelecomOperations:e.some(e=>e.deleteAssociations||e.combineGroupedObjects||e.divideGroupedObjects)};return{edits:await Promise.all(e.map(async e=>{const t=this.effectiveCapabilities,r=e&&(e.addFeatures||e.updateFeatures||e.deleteFeatures),i=e&&(e.addAttachments||e.updateAttachments||e.deleteAttachments);if(E(e,t,s,!!r,!!i,"feature-service"),!t.data.isDataVersioned&&s?.gdbVersion)throw new a("feature-service:invalid-parameter","'gdbVersion' is applicable only if the layer supports versioned data. See: 'capabilities.data.isDataVersioned'");const o=I(e,t,"feature-service"),n={};if(e.deleteAssociations&&(n.deleteAssociations=e.deleteAssociations),e.combineGroupedObjects&&(n.combineGroupedObjects=e.combineGroupedObjects),e.divideGroupedObjects&&(n.divideGroupedObjects=e.divideGroupedObjects),!e.identifierFields){await this.fetchAllLayersAndTables();const t=this._layerTableIndex.get(e.id);t&&(e.identifierFields={globalIdField:t.globalIdField,objectIdField:t.objectIdField})}const l=await O(o);return{id:e.id,...l,...n,identifierFields:e.identifierFields}})),options:s}}async _fetchService(e,t){if(this.sourceJSON)return void this.read(this.sourceJSON,{url:D(e)});const s=await r(e,{responseType:"json",query:{f:"json"},...t});this.read(s.data,{url:D(e)})}async _fetchLayersAndTables(e){const t=`${e}/layers`,s=await r(t,{responseType:"json",query:{f:"json"}});return{layers:s.data.layers.map(e=>{const{type:t,geometryType:s}=e,r=N(this.url,e),i=w(e,r.url);return this._layerTableIndex.set(e.id,e),{...r,type:t||"Feature Layer",geometryType:s,capabilities:i}}),tables:s.data.tables.map(e=>{const t=N(this.url,e),s=w(e,t.url);return this._layerTableIndex.set(e.id,e),{...t,capabilities:s}})}}};function z(e){const t=e.data,s=[];return{results:t.map(e=>{const t={addResults:e.addResults??[],updateResults:e.updateResults??[],deleteResults:e.deleteResults??[],attachments:e.attachments,editMoment:e.editMoment},r=j(t),i=e.editedFeatures,a=i?.spatialReference?new h({wkid:i?.spatialReference.wkid,wkt:i?.spatialReference.wkt,latestWkid:i?.spatialReference.latestWkid,latestVcsWkid:i?.spatialReference.latestVcsWkid,vcsWkid:i?.spatialReference.vcsWkid}):null,o=i?S(i,a):null;o&&s.push({layerId:e.id,editedFeatures:o});const n={};return e.divideGroupedObjectResults&&(n.divideGroupedObjectResults=e.divideGroupedObjectResults),e.combineGroupedObjectResults&&(n.combineGroupedObjectResults=e.combineGroupedObjectResults),{id:e.id,editedFeatures:o,...r,...n}}),editedFeatures:s}}e([c()],$.prototype,"url",void 0),e([c()],$.prototype,"sourceJSON",void 0),e([c()],$.prototype,"userHasFullEditingPrivileges",void 0),e([c()],$.prototype,"userHasUpdateItemPrivileges",void 0),e([c({readOnly:!0})],$.prototype,"utilityNetworkUrl",null),e([c({readOnly:!0})],$.prototype,"versionManagementServiceUrl",null),e([c()],$.prototype,"userTypeExtensions",void 0),e([c({json:{read:{source:["layers"]}}})],$.prototype,"layerInfos",void 0),e([m("layerInfos",["layers"])],$.prototype,"readLayerInfos",null),e([c({json:{read:{source:["tables"]}}})],$.prototype,"tableInfos",void 0),e([m("tableInfos",["tables"])],$.prototype,"readTableInfos",null),e([c({readOnly:!0,json:{read:{source:["hasVersionedData","hasSharedTemplates","hasBranchVersionedData","capabilities","supportsQueryDataElements","supportsQueryDomains","supportsQueryContingentValues","maxRecordCountFactor","maxRecordCount","advancedEditingCapabilities","supportsApplyEditsWithGlobalIds","syncCapabilities","datesInUnknownTimezone"]}}})],$.prototype,"capabilities",void 0),e([m("capabilities",["hasVersionedData","hasSharedTemplates","hasBranchVersionedData","capabilities","supportsQueryDataElements","supportsQueryDomains","supportsQueryContingentValues","maxRecordCountFactor","maxRecordCount","advancedEditingCapabilities","supportsApplyEditsWithGlobalIds","syncCapabilities","datesInUnknownTimezone"])],$.prototype,"readCapabilities",null),e([c({readOnly:!0})],$.prototype,"effectiveCapabilities",null),$=e([y("esri.rest.featureService.FeatureService")],$);const Z=$;export{Z as default};
5
+ import{__decorate as e}from"tslib";import t from"../../config.js";import{id as s}from"../../kernel.js";import r from"../../request.js";import{isSome as i}from"../../core/arrayUtils.js";import a from"../../core/Error.js";import{IdentifiableMixin as o}from"../../core/Identifiable.js";import{JSONSupportMixin as n}from"../../core/JSONSupport.js";import{clone as l}from"../../core/lang.js";import{Loadable as d}from"../../core/Loadable.js";import{throwIfAborted as u,throwIfAbortError as p}from"../../core/promiseUtils.js";import{property as c}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/Logger.js";import{reader as m}from"../../core/accessorSupport/decorators/reader.js";import{subclass as y}from"../../core/accessorSupport/decorators/subclass.js";import h from"../../geometry/SpatialReference.js";import{getFeatureJSON as f,getFeatureIds as b,getAttachmentEditsJSON as g,isProtectedOrPrivateVersionError as v,unpackEditResultData as j,createEditedFeatures as S}from"../../layers/graphics/applyEditsUtils.js";import{checkEditingCapabilities as E,normalizeEdits as I,normalizeGeometries as O}from"../../layers/graphics/editingSupport.js";import{emitApplyEditsEvent as F}from"../../layers/mixins/EditBusLayer.js";import{ensureCredentialIfSignedIn as R}from"../../layers/support/featureLayerUtils.js";import{getOwningPortalUrl as A}from"../../layers/support/layerUtils.js";import{getFeatureLayerCapabilities as w}from"../../layers/support/serviceCapabilitiesUtils.js";import C from"../../portal/PortalItem.js";import{getUserPrivileges as T}from"../../portal/support/portalItemUtils.js";import{isSecureProxyService as U}from"../../portal/support/urlUtils.js";import{parseUrl as D,asValidOptions as P,encode as V}from"../utils.js";import{unapplyEditsZUnitScaling as G}from"../query/operations/editsZScale.js";import{readBoolean as k,readNumber as _}from"../support/jsonUtils.js";import{isSafeToEditVersion as x,isVersionInEditSession as L,currentSessionId as M}from"../../versionManagement/support/versionManagementUtils.js";function N(e,t){const s=t.id;return{id:s,name:t.name,url:`${e}/${s}`,type:t.type||"Table"}}function Q(e){return{data:J(e),sync:B(e),operations:q(e.capabilities,e),query:W(e),editing:H(e)}}function J(e){return{isDataVersioned:k(e,"hasVersionedData",!1),isDataBranchVersioned:k(e,"hasBranchVersionedData",!1)}}function q(e,t){const s=e?e.toLowerCase().split(",").map(e=>e.trim()):[],r=s.includes("query"),i=s.includes("editing")&&!t.datesInUnknownTimezone;let a=i&&s.includes("create"),o=i&&s.includes("delete"),n=i&&s.includes("update");return i&&!(a||o||n)&&(a=o=n=!0),{supportsAdd:a,supportsDelete:o,supportsEditing:i,supportsChangeTracking:s.includes("changetracking"),supportsQuery:r,supportsQueryDataElements:k(t,"supportsQueryDataElements",!1),supportsQueryDomains:k(t,"supportsQueryDomains",!1),supportsQueryContingentValues:k(t,"supportsQueryContingentValues",!1),supportsSync:s.includes("sync"),supportsUpdate:n}}function W(e){return{maxRecordCountFactor:_(e,"maxRecordCountFactor",void 0),maxRecordCount:_(e,"maxRecordCount",void 0)}}function H(e){const t=e?.advancedEditingCapabilities;return{supportsAsyncApplyEdits:k(t,"supportsAsyncApplyEdits",!1),supportsGlobalId:k(e,"supportsApplyEditsWithGlobalIds",!1),supportsReturnServiceEditsInSourceSpatialReference:k(t,"supportsReturnServiceEditsInSourceSR",!1),supportsSharedTemplates:k(e,"supportsSharedTemplates",!1)||k(e,"hasSharedTemplates",!1),supportsSplit:k(t,"supportsSplit",!1)}}function B(e){const t=e?.syncCapabilities,s=t?.supportedSyncDataOptions;return{supportsAsync:k(t,"supportsAsync",!1),supportedSyncDataOptions:{annotations:!(1&~s),dimensions:!(2&~s),contingentValues:!(4&~s),attributeRules:!(8&~s),utilityNetworkSystem:!(16&~s),annotationFullModel:!(32&~s),include3DObjects:!(64&~s),utilityNetworkMissingLayers:!(128&~s),preserveTrueCurves:!(256&~s)}}}let $=class extends(n(o(d))){constructor(e){super(e),this.url=null,this.sourceJSON=null,this.userHasFullEditingPrivileges=!1,this.userHasUpdateItemPrivileges=!1,this.userTypeExtensions=[],this.layerInfos=null,this.tableInfos=null,this.capabilities=null,this._layerTableIndex=new Map}read(e,t){this.sourceJSON=e,super.read(e,t)}get utilityNetworkUrl(){if(this.sourceJSON)for(const e of this.sourceJSON.layers)if("Utility Network Layer"===e.type)return`${this.url}/${e.id}`;return null}get versionManagementServiceUrl(){return this.sourceJSON?.hasBranchVersionedData&&!U(this.url)?this.url.replace(/\/FeatureServer/i,"/VersionManagementServer"):null}readLayerInfos(e,t){return(t.layers||[]).map(e=>{const{type:t,geometryType:s}=e;return{...N(this.url,e),type:t||"Feature Layer",geometryType:s}})}readTableInfos(e,t){return(t.tables||[]).map(e=>N(this.url,e))}readCapabilities(e,t){return Q(t)}get effectiveCapabilities(){const e=this.capabilities;if(!e)return null;const t=l(e),{operations:s}=t;return this.userHasUpdateItemPrivileges?(s.supportsAdd=s.supportsDelete=s.supportsEditing=s.supportsQuery=s.supportsUpdate=!0,t):(this.userHasFullEditingPrivileges&&s.supportsEditing&&(s.supportsAdd=s.supportsDelete=s.supportsUpdate=!0),t)}get loaded(){return super.loaded}load(e){return this.addResolvingPromise(this._fetchService(this.url,e).then(()=>this._setUserPrivileges(e))),Promise.resolve(this)}async fetchAllLayersAndTables(e){return await this.load(e),this._fetchLayersAndTablesPromise||=this._fetchLayersAndTables(this.url),u(e),this._fetchLayersAndTablesPromise}async applyEdits(e,t){let s=null;try{const{results:r,edits:i,editedFeatures:a}=await this._internalApplyEdits(e,t),o=e=>e.filter(e=>!e.error).map(l);let n=0;return r.map(e=>{s=F(this.url,e.id,t?.gdbVersion,!0);const r={edits:i[n],addedFeatures:o(e.addFeatureResults),updatedFeatures:o(e.updateFeatureResults),deletedFeatures:o(e.deleteFeatureResults),addedAttachments:o(e.addAttachmentResults),updatedAttachments:o(e.updateAttachmentResults),deletedAttachments:o(e.deleteAttachmentResults),exceededTransferLimit:!1,historicMoment:e.editMoment?new Date(e.editMoment):null};n+=1,a.length>0&&(r.editedFeatures=a),s.resolve(r),s=null}),r}catch(r){throw s&&s.reject(r),r}}async _setUserPrivileges(e){if(t.userPrivilegesApplied)try{const{features:{fullEdit:t},content:{updateItem:s}}=await this._fetchUserPrivileges(this.sourceJSON.serviceItemId,e);this._set("userHasFullEditingPrivileges",t),this._set("userHasUpdateItemPrivileges",s)}catch(s){p(s)}}async _fetchUserPrivileges(e,t){const r=!0,i=!1,a=!1;if(!e)return{features:{edit:r,fullEdit:i},content:{updateItem:a}};let o,n,l;try{o=await A(this.url,t)}catch(d){p(d)}try{const e=null!=t?t.signal:null;n=await(s?.getCredential(`${o}/sharing`,{prompt:!1,signal:e}))}catch(d){p(d)}if(!n)return{features:{edit:r,fullEdit:i},content:{updateItem:a}};try{if(l=new C({id:e,portal:{url:o}}),await l.load(t),l.portal.user)return T(l)}catch(d){p(d)}return{features:{edit:r,fullEdit:i},content:{updateItem:a}}}async _internalApplyEdits(e,t){await R(this.url);const s=t?.globalIdUsed??!1,a=h.fromJSON(this.sourceJSON.spatialReference),{edits:o,options:n}=await this._processApplyEditsParams(e,t),l=await Promise.all(o.map(async e=>{const t=e.addFeatures?.map(e=>f({spatialReference:a},e,null))??[],r=(await Promise.all(t)).filter(i),o=r.length>0?r:null,n=e.updateFeatures?.map(e=>f({spatialReference:a},e,null))??[],l=(await Promise.all(n)).filter(i),d=l.length>0?l:null,u=b(e.identifierFields,e.deleteFeatures,s),p=u.length>0?u:null;G(o,d,a);const c=await g(e.identifierFields,e);let m=null;if(c){m={adds:c.adds.length>0?c.adds:void 0,updates:c.updates.length>0?c.updates:void 0,deletes:c.deletes.length>0?c.deletes:void 0}}const y={};return e.deleteAssociations&&(y.deleteAssociations=e.deleteAssociations),e.combineGroupedObjects&&(y.combineGroupedObjects=e.combineGroupedObjects),e.divideGroupedObjects&&(y.divideGroupedObjects=e.divideGroupedObjects),{id:e.id,adds:o,updates:d,deletes:p,attachments:m,...y}})),d={gdbVersion:n?.gdbVersion,rollbackOnFailure:!0,useGlobalIds:s,returnEditMoment:!0,honorSequenceOfEdits:n?.honorSequenceOfEdits,trueCurveClient:n?.trueCurveClient,usePreviousEditMoment:n?.usePreviousEditMoment,returnServiceEditsInSourceSR:!1,returnServiceEditsOption:"originalAndCurrentFeatures",async:!1};await x(this.url,t?.gdbVersion,!0);const u=L(this.url,t?.gdbVersion||null);d.edits=JSON.stringify(l);const p=D(this.url),c=P(p.query,{query:V({...d,f:"json"}),method:"post"});let m;u&&(c.authMode="immediate",c.query.sessionId=M);try{m=await r(this.url+"/applyEdits",c)}catch(y){if(!v(y))throw y;c.authMode="immediate",m=await r(this.url+"/applyEdits",c)}return{...z(m),edits:o}}async _processApplyEditsParams(e,t){const s={...t,usingFeatureServiceEndpoint:!0,usingTelecomOperations:e.some(e=>e.deleteAssociations||e.combineGroupedObjects||e.divideGroupedObjects)};return{edits:await Promise.all(e.map(async e=>{const t=this.effectiveCapabilities,r=e&&(e.addFeatures||e.updateFeatures||e.deleteFeatures),i=e&&(e.addAttachments||e.updateAttachments||e.deleteAttachments);if(E(e,t,s,!!r,!!i,"feature-service"),!t.data.isDataVersioned&&s?.gdbVersion)throw new a("feature-service:invalid-parameter","'gdbVersion' is applicable only if the layer supports versioned data. See: 'capabilities.data.isDataVersioned'");const o=I(e,t,"feature-service"),n={};if(e.deleteAssociations&&(n.deleteAssociations=e.deleteAssociations),e.combineGroupedObjects&&(n.combineGroupedObjects=e.combineGroupedObjects),e.divideGroupedObjects&&(n.divideGroupedObjects=e.divideGroupedObjects),!e.identifierFields){await this.fetchAllLayersAndTables();const t=this._layerTableIndex.get(e.id);t&&(e.identifierFields={globalIdField:t.globalIdField,objectIdField:t.objectIdField})}const l=await O(o);return{id:e.id,...l,...n,identifierFields:e.identifierFields}})),options:s}}async _fetchService(e,t){if(this.sourceJSON)return void this.read(this.sourceJSON,{url:D(e)});const s=await r(e,{responseType:"json",query:{f:"json"},...t});this.read(s.data,{url:D(e)})}async _fetchLayersAndTables(e){const t=`${e}/layers`,s=await r(t,{responseType:"json",query:{f:"json"}});return{layers:s.data.layers.map(e=>{const{type:t,geometryType:s}=e,r=N(this.url,e),i=w(e,r.url);return this._layerTableIndex.set(e.id,e),{...r,type:t||"Feature Layer",geometryType:s,capabilities:i}}),tables:s.data.tables.map(e=>{const t=N(this.url,e),s=w(e,t.url);return this._layerTableIndex.set(e.id,e),{...t,capabilities:s}})}}};function z(e){const t=e.data,s=[];return{results:t.map(e=>{const t={addResults:e.addResults??[],updateResults:e.updateResults??[],deleteResults:e.deleteResults??[],attachments:e.attachments,editMoment:e.editMoment},r=j(t),i=e.editedFeatures,a=i?.spatialReference?new h({wkid:i?.spatialReference.wkid,wkt:i?.spatialReference.wkt,latestWkid:i?.spatialReference.latestWkid,latestVcsWkid:i?.spatialReference.latestVcsWkid,vcsWkid:i?.spatialReference.vcsWkid}):null,o=i?S(i,a):null;o&&s.push({layerId:e.id,editedFeatures:o});const n={};return e.divideGroupedObjectResults&&(n.divideGroupedObjectResults=e.divideGroupedObjectResults),e.combineGroupedObjectResults&&(n.combineGroupedObjectResults=e.combineGroupedObjectResults),{id:e.id,editedFeatures:o,...r,...n}}),editedFeatures:s}}e([c()],$.prototype,"url",void 0),e([c()],$.prototype,"sourceJSON",void 0),e([c()],$.prototype,"userHasFullEditingPrivileges",void 0),e([c()],$.prototype,"userHasUpdateItemPrivileges",void 0),e([c({readOnly:!0})],$.prototype,"utilityNetworkUrl",null),e([c({readOnly:!0})],$.prototype,"versionManagementServiceUrl",null),e([c()],$.prototype,"userTypeExtensions",void 0),e([c({json:{read:{source:["layers"]}}})],$.prototype,"layerInfos",void 0),e([m("layerInfos",["layers"])],$.prototype,"readLayerInfos",null),e([c({json:{read:{source:["tables"]}}})],$.prototype,"tableInfos",void 0),e([m("tableInfos",["tables"])],$.prototype,"readTableInfos",null),e([c({readOnly:!0,json:{read:{source:["hasVersionedData","hasSharedTemplates","hasBranchVersionedData","capabilities","supportsQueryDataElements","supportsQueryDomains","supportsQueryContingentValues","maxRecordCountFactor","maxRecordCount","advancedEditingCapabilities","supportsApplyEditsWithGlobalIds","syncCapabilities","datesInUnknownTimezone"]}}})],$.prototype,"capabilities",void 0),e([m("capabilities",["hasVersionedData","hasSharedTemplates","hasBranchVersionedData","capabilities","supportsQueryDataElements","supportsQueryDomains","supportsQueryContingentValues","maxRecordCountFactor","maxRecordCount","advancedEditingCapabilities","supportsApplyEditsWithGlobalIds","syncCapabilities","datesInUnknownTimezone"])],$.prototype,"readCapabilities",null),e([c({readOnly:!0})],$.prototype,"effectiveCapabilities",null),$=e([y("esri.rest.featureService.FeatureService")],$);const Z=$;export{Z 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.34/esri/copyright.txt for details.
4
4
  */
5
- const a="20250910",e="737aa7ea5627033d3384eded76f6055f379ab349";export{a as buildDate,e as commitHash};
5
+ const b="20250912",f="147367af05f28541a6b3dbfeb3ecbe206f4514bf";export{b as buildDate,f as commitHash};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../../core/Error.js";import has from"../../../core/has.js";import{removeMaybe as t}from"../../../core/maybe.js";import{addFrameTask as r}from"../../../core/scheduling.js";import{signal as s}from"../../../core/signal.js";import{create as i}from"../../../core/libs/gl-matrix-2/factories/mat3f32.js";import{CIMAnalyzer as n}from"../../../symbols/cim/cimAnalyzer.js";import{Container as a}from"./Container.js";import{MAX_TILE_RESHUFFLES_PER_FRAME as o}from"./webgl/definitions.js";import h from"./webgl/Painter.js";import{ArrayBufferPool as d}from"./webgl/PooledUint32Array.js";import{Profiler as l}from"./webgl/Profiler.js";import{TileReshuffleManager as m}from"./webgl/TileReshuffleManager.js";import{startup as u,shutdown as c}from"./webgl/shaderGraph/techniques/TechniqueRegistry.js";import{MeshWriterRegistry as p}from"./webgl/shaderGraph/techniques/mesh/MeshWriterRegistry.js";import{Timeline as g}from"../support/Timeline.js";import{SizedPixelFormat as f,SizedDepthStencilFormat as _,PixelType as b}from"../../webgl/enums.js";import{FramebufferObject as w}from"../../webgl/FramebufferObject.js";import{RenderbufferDescriptor as R}from"../../webgl/RenderbufferDescriptor.js";import{RenderingContext as y}from"../../webgl/RenderingContext.js";import{RenderingContextOptions as x}from"../../webgl/RenderingContextOptions.js";import{TextureDescriptor as C}from"../../webgl/TextureDescriptor.js";const P=2e3;class j extends a{constructor(t,i,a){super(),this.meshWriterRegistry=new p,this._trash=new Set,this._renderRemainingTime=0,this._lastFrameRenderTime=0,this._renderRequested=s(!1),this.stage=this,this._stationary=!0,this._reshuffleManager=new m,this._managedCanvas=a,this.context=new y(this._managedCanvas.gl,i.contextOptions??new x),this.painter=new h(this.context,this),this._cimAnalyzer=new n(this.painter.textureManager.resourceManager),has("esri-2d-profiler")&&null!=t&&(this._debugOutput=document.createElement("div"),this._debugOutput.setAttribute("style","margin: 24px 64px; position: absolute; color: red;"),t.appendChild(this._debugOutput));const o=()=>this.highlightGradient;this._renderParameters={drawPhase:0,state:this.state,pixelRatio:window.devicePixelRatio,stationary:!1,globalOpacity:1,blendMode:null,deltaTime:-1,time:0,inFadeTransition:!1,effects:null,context:this.context,painter:this.painter,timeline:i.timeline||new g,renderingOptions:i.renderingOptions,requestRender:()=>this.requestRender(),allowDelayedRender:!1,requireFBO:!1,profiler:new l(this.context,this._debugOutput),dataUploadCounter:0,get highlightGradient(){return o()},reshuffleManager:this._reshuffleManager,backgroundColor:i.backgroundColor};let c=e=>this.renderFrame(e);null!=i.renderFrame&&(c=i.renderFrame),this._taskHandle=r({render:e=>c(e)}),this._taskHandle.pause(),this._lostWebGLContextHandle=this._managedCanvas.events.on("webgl-context-lost",t=>this.emit("webgl-error",{error:new e("webgl-context-lost",t.statusMessage)})),this._bufferPool=new d,u()}destroy(){super.destroy(),c(this.context),this.removeAllChildren(),this._emptyTrash(),this._taskHandle=t(this._taskHandle),this._lostWebGLContextHandle=t(this._lostWebGLContextHandle),this._managedCanvas.destroy(),this._debugOutput?.parentNode?.removeChild(this._debugOutput),this._bufferPool.destroy(),this.painter.dispose(),this.context.dispose(),this._managedCanvas=null}get textureManager(){return this.painter.textureManager}get profiler(){return this._renderParameters.profiler}get backgroundColor(){return this._renderParameters.backgroundColor}set backgroundColor(e){this._renderParameters.backgroundColor=e,this.requestRender()}get canvas(){return this._managedCanvas.canvas}get bufferPool(){return this._bufferPool}get cimAnalyzer(){return this._cimAnalyzer}get renderingOptions(){return this._renderingOptions}set renderingOptions(e){this._renderingOptions=e,this.requestRender()}get renderRequested(){return this._renderRequested.value}get state(){return this._state}set state(e){this._state=e,this.requestRender()}get stationary(){return this._stationary}set stationary(e){this._stationary!==e&&(this._stationary=e,this.requestRender())}trashDisplayObject(e){this._trash.add(e),this.requestRender()}untrashDisplayObject(e){return this._trash.delete(e)}requestRender(){this._renderRemainingTime=P,this.renderRequested||(this._renderRequested.value=!0,this._taskHandle.resume())}renderFrame(e){const t=this._lastFrameRenderTime?e.time-this._lastFrameRenderTime:0;this._renderRemainingTime-=t,this._renderRemainingTime<=0&&this._taskHandle.pause(),this._lastFrameRenderTime=e.time,this._renderRequested.value=!1,this._renderParameters.state=this._state,this._renderParameters.stationary=this.stationary,this._renderParameters.pixelRatio=window.devicePixelRatio,this._renderParameters.globalOpacity=1,this._renderParameters.time=e.time,this._renderParameters.deltaTime=e.deltaTime,this._renderParameters.effects=null,this.processRender(this._renderParameters),this._emptyTrash()}_createTransforms(){return{displayViewScreenMat3:i()}}renderChildren(e){for(const t of this.children)t.beforeRender(e);this._reshuffleManager.reshuffle(o),this._managedCanvas.render(e,()=>this._renderChildren(this.children,e));for(const t of this.children)t.afterRender(e)}_renderChildren(e,t){const r=this.context;this.painter.textureUploadManager.upload(),r.resetInfo(),t.profiler.recordStart("drawLayers"),t.dataUploadCounter=0,this.painter.beforeRenderPhases(t,t.backgroundColor,this.state.padding),t.drawPhase=1;for(const s of e)s.processRender(t);if(this.children.some(e=>e.hasHighlight)){t.drawPhase=16;for(const r of e)r.processRender(t)}if(this.children.some(e=>e.hasLabels)){t.drawPhase=2;for(const r of e)r.processRender(t)}if(has("esri-tiles-debug")){t.drawPhase=64;for(const r of e)r.processRender(t)}this.painter.afterRenderPhases(t),t.profiler.recordEnd("drawLayers"),r.logInfo()}doRender(e){const t=this.context,{state:r,pixelRatio:s}=e;this._managedCanvas.resize(e),t.setViewport(0,0,s*r.size[0],s*r.size[1]),t.setDepthWriteEnabled(!0),t.setStencilWriteMask(255),this.renderChildren(e)}async takeScreenshot(e,t,r,s){const i=Math.round(this.state.size[0]*e.resolutionScale),n=Math.round(this.state.size[1]*e.resolutionScale),a=e.resolutionScale,o=this.context,h=this._state.clone();if(null!=s){const e=h.viewpoint;h.viewpoint.rotation=s,h.viewpoint=e}const d={...this._renderParameters,drawPhase:null,globalOpacity:1,stationary:!0,state:h,pixelRatio:a,time:performance.now(),deltaTime:0,blendMode:null,effects:null,inFadeTransition:!1,backgroundColor:r},l=new C(i,n);l.wrapMode=33071,l.internalFormat=f.RGBA8,l.isImmutable=!0;const m=new w(o,l,new R(_.DEPTH24_STENCIL8,i,n)),u=o.getBoundFramebufferObject(),c=o.getViewport();o.bindFramebuffer(m),o.setViewport(0,0,i,n),this._renderChildren(t??this.children,d);const p=this._readbackScreenshot(m,{...e.cropArea,y:n-(e.cropArea.y+e.cropArea.height)});o.bindFramebuffer(u),o.setViewport(c.x,c.y,c.width,c.height),this.requestRender();const g=await p;let b;return 1===e.outputScale?b=g:(b=new ImageData(Math.round(g.width*e.outputScale),Math.round(g.height*e.outputScale)),(await import("../../support/screenshotUtils.js")).resampleHermite(g,b,!0)),m.dispose(),b}async _readbackScreenshot(e,t){const r=(await import("../../support/screenshotUtils.js")).createEmptyImageData(t.width,t.height,document.createElement("canvas"));return await e.readPixelsAsync(t.x,t.y,t.width,t.height,6408,b.UNSIGNED_BYTE,new Uint8Array(r.data.buffer)),r}_emptyTrash(){for(;this._trash.size>0;){const e=Array.from(this._trash);this._trash.clear();for(const t of e)t.processDetach()}}}export{j as Stage,P as extraRenderTime};
5
+ import e from"../../../core/Error.js";import has from"../../../core/has.js";import{removeMaybe as t}from"../../../core/maybe.js";import{addFrameTask as r}from"../../../core/scheduling.js";import{signal as s}from"../../../core/signal.js";import{create as i}from"../../../core/libs/gl-matrix-2/factories/mat3f32.js";import{CIMAnalyzer as n}from"../../../symbols/cim/cimAnalyzer.js";import{Container as a}from"./Container.js";import{MAX_TILE_RESHUFFLES_PER_FRAME as o}from"./webgl/definitions.js";import h from"./webgl/Painter.js";import{ArrayBufferPool as d}from"./webgl/PooledUint32Array.js";import{Profiler as l}from"./webgl/Profiler.js";import{TileReshuffleManager as m}from"./webgl/TileReshuffleManager.js";import{startup as u,shutdown as c}from"./webgl/shaderGraph/techniques/TechniqueRegistry.js";import{MeshWriterRegistry as p}from"./webgl/shaderGraph/techniques/mesh/MeshWriterRegistry.js";import{Timeline as g}from"../support/Timeline.js";import{SizedPixelFormat as f,SizedDepthStencilFormat as _,PixelType as b}from"../../webgl/enums.js";import{FramebufferObject as w}from"../../webgl/FramebufferObject.js";import{RenderbufferDescriptor as R}from"../../webgl/RenderbufferDescriptor.js";import{RenderingContext as y}from"../../webgl/RenderingContext.js";import{RenderingContextOptions as x}from"../../webgl/RenderingContextOptions.js";import{TextureDescriptor as C}from"../../webgl/TextureDescriptor.js";const P=2e3;class j extends a{constructor(t,i,a){super(),this.meshWriterRegistry=new p,this._trash=new Set,this._renderRemainingTime=0,this._lastFrameRenderTime=0,this._renderRequested=s(!1),this.stage=this,this._stationary=!0,this._reshuffleManager=new m,this._managedCanvas=a,this.context=new y(this._managedCanvas.gl,i.contextOptions??new x),this.painter=new h(this.context,this),this._cimAnalyzer=new n(this.painter.textureManager.resourceManager),has("esri-2d-profiler")&&null!=t&&(this._debugOutput=document.createElement("div"),this._debugOutput.setAttribute("style","margin: 24px 64px; position: absolute; color: red;"),t.appendChild(this._debugOutput));const o=()=>this.highlightGradient;this._renderParameters={drawPhase:0,state:this.state,pixelRatio:window.devicePixelRatio,stationary:!1,globalOpacity:1,blendMode:null,deltaTime:-1,time:0,inFadeTransition:!1,effects:null,context:this.context,painter:this.painter,timeline:i.timeline||new g,renderingOptions:i.renderingOptions,requestRender:()=>this.requestRender(),allowDelayedRender:!1,requireFBO:!1,profiler:new l(this.context,this._debugOutput),dataUploadCounter:0,get highlightGradient(){return o()},reshuffleManager:this._reshuffleManager,backgroundColor:i.backgroundColor};let c=e=>this.renderFrame(e);null!=i.renderFrame&&(c=i.renderFrame),this._taskHandle=r({render:e=>c(e)}),this._taskHandle.pause(),this._lostWebGLContextHandle=this._managedCanvas.events.on("webgl-context-lost",t=>this.emit("webgl-error",{error:new e("webgl-context-lost",t.statusMessage)})),this._bufferPool=new d,u()}destroy(){super.destroy(),c(this.context),this.removeAllChildren(),this._emptyTrash(),this._taskHandle=t(this._taskHandle),this._lostWebGLContextHandle=t(this._lostWebGLContextHandle),this._managedCanvas.destroy(),this._debugOutput?.parentNode?.removeChild(this._debugOutput),this._bufferPool.destroy(),this.painter.dispose(),this.context.dispose(),this._managedCanvas=null}get textureManager(){return this.painter.textureManager}get profiler(){return this._renderParameters.profiler}get backgroundColor(){return this._renderParameters.backgroundColor}set backgroundColor(e){this._renderParameters.backgroundColor=e,this.requestRender()}get canvas(){return this._managedCanvas.canvas}get bufferPool(){return this._bufferPool}get cimAnalyzer(){return this._cimAnalyzer}get renderingOptions(){return this._renderingOptions}set renderingOptions(e){this._renderingOptions=e,this.requestRender()}get renderRequested(){return this._renderRequested.value}get state(){return this._state}set state(e){this._state=e,this.requestRender()}get stationary(){return this._stationary}set stationary(e){this._stationary!==e&&(this._stationary=e,this.requestRender())}trashDisplayObject(e){this._trash.add(e),this.requestRender()}untrashDisplayObject(e){return this._trash.delete(e)}requestRender(){this._renderRemainingTime=P,this.renderRequested||(this._renderRequested.value=!0,this._taskHandle.resume())}renderFrame(e){const t=this._lastFrameRenderTime?e.time-this._lastFrameRenderTime:0;this._renderRemainingTime-=t,this._renderRemainingTime<=0&&this._taskHandle.pause(),this._lastFrameRenderTime=e.time,this._renderRequested.value=!1,this._renderParameters.state=this._state,this._renderParameters.stationary=this.stationary,this._renderParameters.pixelRatio=window.devicePixelRatio,this._renderParameters.globalOpacity=1,this._renderParameters.time=e.time,this._renderParameters.deltaTime=e.deltaTime,this._renderParameters.effects=null,this.processRender(this._renderParameters),this._emptyTrash()}_createTransforms(){return{displayViewScreenMat3:i()}}renderChildren(e){this._reshuffleManager.reshuffle(o),this._managedCanvas.render(e,()=>this._renderChildren(this.children,e))}_renderChildren(e,t){for(const s of e)s.beforeRender(t);const r=this.context;this.painter.textureUploadManager.upload(),r.resetInfo(),t.profiler.recordStart("drawLayers"),t.dataUploadCounter=0,this.painter.beforeRenderPhases(t,t.backgroundColor,this.state.padding),t.drawPhase=1;for(const s of e)s.processRender(t);if(this.children.some(e=>e.hasHighlight)){t.drawPhase=16;for(const r of e)r.processRender(t)}if(this.children.some(e=>e.hasLabels)){t.drawPhase=2;for(const r of e)r.processRender(t)}if(has("esri-tiles-debug")){t.drawPhase=64;for(const r of e)r.processRender(t)}this.painter.afterRenderPhases(t),t.profiler.recordEnd("drawLayers"),r.logInfo();for(const s of e)s.afterRender(t)}doRender(e){const t=this.context,{state:r,pixelRatio:s}=e;this._managedCanvas.resize(e),t.setViewport(0,0,s*r.size[0],s*r.size[1]),t.setDepthWriteEnabled(!0),t.setStencilWriteMask(255),this.renderChildren(e)}async takeScreenshot(e,t,r,s){const i=Math.round(this.state.size[0]*e.resolutionScale),n=Math.round(this.state.size[1]*e.resolutionScale),a=e.resolutionScale,o=this.context,h=this._state.clone();if(null!=s){const e=h.viewpoint;h.viewpoint.rotation=s,h.viewpoint=e}const d={...this._renderParameters,drawPhase:null,globalOpacity:1,stationary:!0,state:h,pixelRatio:a,time:performance.now(),deltaTime:0,blendMode:null,effects:null,inFadeTransition:!1,backgroundColor:r},l=new C(i,n);l.wrapMode=33071,l.internalFormat=f.RGBA8,l.isImmutable=!0;const m=new w(o,l,new R(_.DEPTH24_STENCIL8,i,n)),u=o.getBoundFramebufferObject(),c=o.getViewport();o.bindFramebuffer(m),o.setViewport(0,0,i,n),this._renderChildren(t??this.children,d);const p=this._readbackScreenshot(m,{...e.cropArea,y:n-(e.cropArea.y+e.cropArea.height)});o.bindFramebuffer(u),o.setViewport(c.x,c.y,c.width,c.height),this.requestRender();const g=await p;let b;return 1===e.outputScale?b=g:(b=new ImageData(Math.round(g.width*e.outputScale),Math.round(g.height*e.outputScale)),(await import("../../support/screenshotUtils.js")).resampleHermite(g,b,!0)),m.dispose(),b}async _readbackScreenshot(e,t){const r=(await import("../../support/screenshotUtils.js")).createEmptyImageData(t.width,t.height,document.createElement("canvas"));return await e.readPixelsAsync(t.x,t.y,t.width,t.height,6408,b.UNSIGNED_BYTE,new Uint8Array(r.data.buffer)),r}_emptyTrash(){for(;this._trash.size>0;){const e=Array.from(this._trash);this._trash.clear();for(const t of e)t.processDetach()}}}export{j as Stage,P as extraRenderTime};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import"../../../../../../core/has.js";import{isPowerOfTwo as e,nextPowerOfTwo as t}from"../../../../../../core/mathUtils.js";import{disposeMaybe as r}from"../../../../../../core/maybe.js";import{simplePipelineState as s}from"../utils.js";import{Technique as u}from"./Technique.js";import{TextureStatisticsDiffShader as i}from"./shaders/TextureStatisticsDiffShader.js";import{TextureStatisticsMinMaxSumShader as o}from"./shaders/TextureStatisticsMinMaxSumShader.js";import{TextureStatisticsStdDevShader as a}from"./shaders/TextureStatisticsStdDevShader.js";import{TextureStatisticsSumOfSquaredDiffShader as f}from"./shaders/TextureStatisticsSumOfSquaredDiffShader.js";import{getWebGLCapabilities as n}from"../../../../../webgl/capabilities.js";import{ColorAttachment2 as h,ColorAttachment3 as l,SizedPixelFormat as m,PixelType as c,ColorAttachment0 as x,ColorAttachment1 as T}from"../../../../../webgl/enums.js";import{FramebufferObject as b}from"../../../../../webgl/FramebufferObject.js";import{Texture as d}from"../../../../../webgl/Texture.js";import{TextureDescriptor as p}from"../../../../../webgl/TextureDescriptor.js";const _=1048576;class F extends u{constructor(){super(...arguments),this.type=32,this._width=0,this._height=0,this._framebuffers=null,this._minTexture=null,this._maxTexture=null,this._sumTexture=null,this._resultsFramebuffer=null,this._startFramebuffer=null,this._diffFramebuffer=null,this._scaleFbo=null,this.shaders={textureStatisticsMinMaxSum:new o,textureStatisticsSum:new f,textureStatisticsDiff:new i,textureStatisticsStdDev:new a}}dispose(){this.shaders.textureStatisticsMinMaxSum=null,this._framebuffers&&(this._framebuffers.forEach(e=>r(e)),this._framebuffers=null),r(this._resultsFramebuffer),r(this._startFramebuffer),r(this._diffFramebuffer),r(this._scaleFbo),r(this._minTexture),r(this._maxTexture),r(this._sumTexture)}get minValuesTexture(){return this._minTexture||null}get maxValuesTexture(){return this._maxTexture||null}get meanValuesTexture(){return this._resultsFramebuffer?.getColorTexture(h)||null}get stdDevValuesTexture(){return this._resultsFramebuffer?.getColorTexture(l)||null}get statsFbo(){return this._resultsFramebuffer}render(t,r){const{context:u,painter:i}=t;let o=r.fbo.width,a=r.fbo.height,f=r.fbo;const n=u.gl,h=u.getBoundFramebufferObject();if(o*a>_||!e(o)||!e(a)){const t=o/a;if(o*a>_){const e=Math.max(Math.floor(Math.sqrt(_/t)),1);o=Math.max(Math.floor(t*e),1),a=e}e(o)||(o=S(o)),e(a)||(a=S(a)),this._scaleFbo?this._scaleFbo.resize(o,a):this._scaleFbo=g(u,o,a,c.UNSIGNED_BYTE,m.RGBA8),u.bindFramebuffer(this._scaleFbo),u.setViewport(0,0,o,a),i.blitTexture(u,f.getColorTexture(x),9728),f=this._scaleFbo}this._updateResources(t,f),i.setPipelineState({...s,color:{write:[!0,!0,!0,!0],blendMode:"none"}});const l=this._applyReductionPass(t);n.readBuffer(n.COLOR_ATTACHMENT2),l.copyToTexture(0,0,1,1,0,0,this._sumTexture),n.readBuffer(n.COLOR_ATTACHMENT1),l.copyToTexture(0,0,1,1,0,0,this._maxTexture),n.readBuffer(n.COLOR_ATTACHMENT0),l.copyToTexture(0,0,1,1,0,0,this._minTexture);const T=r.fbo.getColorTexture(x);if(!T)throw new Error("Start buffer color texture is not available, cannot compute diff.");this._computeDiff(t,T,this._sumTexture,o,a);const b=this._applySecondReductionPass(t,o,a).getColorTexture(x);this._computeSdtDev(t,this._minTexture,this._maxTexture,this._sumTexture,b,o,a),u.bindFramebuffer(h),u.setViewport(0,0,o,a),u.setDrawBuffers([x]),i.setPipelineState(s)}_applyReductionPass(e){const{context:t,painter:r}=e,s=this.shaders.textureStatisticsMinMaxSum,u=this._framebuffers;if(null===u)throw new Error("Framebuffers are not initialized, cannot apply reduction pass.");t.setDrawBuffers([x,T,h]);const i=this._startFramebuffer;let o=i.getColorTexture(x),a=i.getColorTexture(T),f=i.getColorTexture(h);const n=u;for(const l of n){t.setViewport(0,0,l.width,l.height),t.bindFramebuffer(l),t.setClearColor(0,0,0,0),t.clear(16384);const e={shader:s,uniforms:{config:{minTexture:{texture:o,unit:1},maxTexture:{texture:a,unit:2},sumTexture:{texture:f,unit:3},width:l.width,height:l.height}},defines:null,optionalAttributes:null,useComputeBuffer:!1};r.submitDrawMesh(t,e,r.quadMesh),o=l.getColorTexture(x),a=l.getColorTexture(T),f=l.getColorTexture(h)}return u.at(-1)}_applySecondReductionPass(e,t,r){const{context:s,painter:u}=e,i=this.shaders.textureStatisticsSum,o=this._framebuffers;if(null===o||null==this._diffFramebuffer)throw new Error("Framebuffers are not initialized, cannot apply reduction pass.");s.setDrawBuffers([x]);let a=this._diffFramebuffer.getColorTexture(x);const f=o;for(const n of f){s.setViewport(0,0,n.width,n.height),s.bindFramebuffer(n),s.setClearColor(0,0,0,0),s.clear(16384);const e={shader:i,uniforms:{config:{sumTexture:{texture:a,unit:2},width:n.width,height:n.height}},defines:null,optionalAttributes:null,useComputeBuffer:!1};u.submitDrawMesh(s,e,u.quadMesh),a=n.getColorTexture(x)}return o.at(-1)}_updateResources(e,t){const{context:r}=e,s=t.width,u=t.height;if(null===this._startFramebuffer){if(!n().supportsColorBufferFloat)throw new Error("WebGL does not support color buffer float, cannot compute texture statistics.");const e=g(r,s,u,c.UNSIGNED_BYTE,m.RGBA8,3),i=e.getColorTexture(x),o=e.getColorTexture(T),a=e.getColorTexture(h);t.copyToTexture(0,0,s,u,0,0,i),t.copyToTexture(0,0,s,u,0,0,o),t.copyToTexture(0,0,s,u,0,0,a),this._startFramebuffer=e,this._diffFramebuffer=g(r,s,u,c.FLOAT,m.RGBA32F),this._resultsFramebuffer=g(r,1,1,c.FLOAT,m.RGBA32F,4),this._minTexture=C(r,1,1,c.FLOAT,m.RGBA32F),this._maxTexture=C(r,1,1,c.FLOAT,m.RGBA32F),this._sumTexture=C(r,1,1,c.FLOAT,m.RGBA32F)}else{const e=this._startFramebuffer;e.resize(s,u);const r=e.getColorTexture(x),i=e.getColorTexture(T),o=e.getColorTexture(h);t.copyToTexture(0,0,s,u,0,0,r),t.copyToTexture(0,0,s,u,0,0,i),t.copyToTexture(0,0,s,u,0,0,o),this._diffFramebuffer.resize(s,u)}if(this._width===s&&this._height===u&&null!==this._framebuffers)return;const i=(this._framebuffers||[]).reverse();this._framebuffers=null,this._width=s,this._height=u,this._framebuffers=this._updateFramebuffers(r,s,u,i,3)}_updateFramebuffers(e,t,s,u,i=1){const o=[];let a=t,f=s;for(;a>1||f>1;){const t=Math.max(1,Math.floor(a/2)),r=Math.max(1,Math.floor(f/2)),s=w(e,t,r,u,i);o.push(s),a=t,f=r}return o.at(-1),u.forEach(e=>r(e)),u.length=0,o}_computeDiff(e,t,r,s,u){const{context:i,painter:o}=e;i.bindFramebuffer(this._diffFramebuffer),i.setDrawBuffers([x]),i.setViewport(0,0,s,u),i.setClearColor(0,0,0,0),i.clear(16384);const a={shader:this.shaders.textureStatisticsDiff,uniforms:{config:{inputTexture:{texture:t,unit:1},sumTexture:{texture:r,unit:2},numTexels:s*u}},defines:null,optionalAttributes:null,useComputeBuffer:!1};o.submitDrawMesh(i,a,o.quadMesh)}_computeSdtDev(e,t,r,s,u,i,o){const{context:a,painter:f}=e;a.bindFramebuffer(this._resultsFramebuffer),a.setDrawBuffers([x,T,h,l]),a.setViewport(0,0,1,1),a.setClearColor(0,0,0,0),a.clear(16384);const n={shader:this.shaders.textureStatisticsStdDev,uniforms:{config:{minTexture:{texture:t,unit:1},maxTexture:{texture:r,unit:2},sumTexture:{texture:s,unit:3},diffSqTexture:{texture:u,unit:4},numTexels:i*o}},defines:null,optionalAttributes:null,useComputeBuffer:!1};f.submitDrawMesh(a,n,f.quadMesh)}}function w(e,t,r,s,u=1){let i=s.pop();return void 0!==i?i.resize(t,r):i=g(e,t,r,c.FLOAT,m.RGBA32F,u),i}function g(e,t,r,s,u,i=1){if(i<1||i>4)throw new Error("Number of color attachments must be between 1 and 4.");const o=new b(e,C(e,t,r,s,u));for(let a=1;a<i;a++){const i=C(e,t,r,s,u);o.attachColorTexture(i,x+a)}return o}function C(e,t,r,s,u){const i=new p(t,r);return i.samplingMode=9728,i.wrapMode=33071,i.pixelFormat=6408,i.dataType=s,i.internalFormat=u,new d(e,i)}function S(e){const r=t(e),s=r/2;return Math.abs(r-e)<Math.abs(s-e)?r:s}export{F as TextureStatisticsTechnique};
5
+ import"../../../../../../core/has.js";import{isPowerOfTwo as e,nextPowerOfTwo as t}from"../../../../../../core/mathUtils.js";import{disposeMaybe as r}from"../../../../../../core/maybe.js";import{simplePipelineState as s}from"../utils.js";import{Technique as u}from"./Technique.js";import{TextureStatisticsDiffShader as o}from"./shaders/TextureStatisticsDiffShader.js";import{TextureStatisticsMinMaxSumShader as i}from"./shaders/TextureStatisticsMinMaxSumShader.js";import{TextureStatisticsStdDevShader as a}from"./shaders/TextureStatisticsStdDevShader.js";import{TextureStatisticsSumOfSquaredDiffShader as f}from"./shaders/TextureStatisticsSumOfSquaredDiffShader.js";import{getWebGLCapabilities as n}from"../../../../../webgl/capabilities.js";import{ColorAttachment2 as l,ColorAttachment3 as h,SizedPixelFormat as m,PixelType as x,ColorAttachment0 as c,ColorAttachment1 as T}from"../../../../../webgl/enums.js";import{FramebufferObject as p}from"../../../../../webgl/FramebufferObject.js";import{Texture as d}from"../../../../../webgl/Texture.js";import{TextureDescriptor as b}from"../../../../../webgl/TextureDescriptor.js";const _=1048576;class F extends u{constructor(){super(...arguments),this.type=32,this._width=0,this._height=0,this._framebuffers=null,this._minTexture=null,this._maxTexture=null,this._sumTexture=null,this._numOfNoDataTexture=null,this._resultsFramebuffer=null,this._startFramebuffer=null,this._diffFramebuffer=null,this._scaleFbo=null,this.shaders={textureStatisticsMinMaxSum:new i,textureStatisticsSum:new f,textureStatisticsDiff:new o,textureStatisticsStdDev:new a}}dispose(){this.shaders.textureStatisticsMinMaxSum=null,this._framebuffers&&(this._framebuffers.forEach(e=>r(e)),this._framebuffers=null),r(this._resultsFramebuffer),r(this._startFramebuffer),r(this._diffFramebuffer),r(this._scaleFbo),r(this._minTexture),r(this._maxTexture),r(this._sumTexture),r(this._numOfNoDataTexture)}get minValuesTexture(){return this._minTexture||null}get maxValuesTexture(){return this._maxTexture||null}get meanValuesTexture(){return this._resultsFramebuffer?.getColorTexture(l)||null}get stdDevValuesTexture(){return this._resultsFramebuffer?.getColorTexture(h)||null}get statsFbo(){return this._resultsFramebuffer}render(t,r){const{context:u,painter:o}=t;let i=r.fbo.width,a=r.fbo.height,f=r.fbo;const n=u.gl,l=u.getBoundFramebufferObject();if(i*a>_||!e(i)||!e(a)){const t=i/a;if(i*a>_){const e=Math.max(Math.floor(Math.sqrt(_/t)),1);i=Math.max(Math.floor(t*e),1),a=e}e(i)||(i=S(i)),e(a)||(a=S(a)),this._scaleFbo?this._scaleFbo.resize(i,a):this._scaleFbo=w(u,i,a,x.UNSIGNED_BYTE,m.RGBA8),u.bindFramebuffer(this._scaleFbo),u.setViewport(0,0,i,a),o.blitTexture(u,f.getColorTexture(c),9728),f=this._scaleFbo}this._updateResources(t,f),o.setPipelineState({...s,color:{write:[!0,!0,!0,!0],blendMode:"none"}});const h=this._applyReductionPass(t);n.readBuffer(n.COLOR_ATTACHMENT3),h.copyToTexture(0,0,1,1,0,0,this._numOfNoDataTexture),n.readBuffer(n.COLOR_ATTACHMENT2),h.copyToTexture(0,0,1,1,0,0,this._sumTexture),n.readBuffer(n.COLOR_ATTACHMENT1),h.copyToTexture(0,0,1,1,0,0,this._maxTexture),n.readBuffer(n.COLOR_ATTACHMENT0),h.copyToTexture(0,0,1,1,0,0,this._minTexture);const T=r.fbo.getColorTexture(c);if(!T)throw new Error("Start buffer color texture is not available, cannot compute diff.");this._computeDiff(t,T,this._sumTexture,this._numOfNoDataTexture,i,a);const p=this._applySecondReductionPass(t,i,a).getColorTexture(c);this._computeSdtDev(t,this._minTexture,this._maxTexture,this._sumTexture,this._numOfNoDataTexture,p,i,a),u.bindFramebuffer(l),u.setViewport(0,0,i,a),u.setDrawBuffers([c]),o.setPipelineState(s)}_applyReductionPass(e){const{context:t,painter:r}=e,s=this.shaders.textureStatisticsMinMaxSum,u=this._framebuffers;if(null===u)throw new Error("Framebuffers are not initialized, cannot apply reduction pass.");t.setDrawBuffers([c,T,l]);const o=this._startFramebuffer;let i=o.getColorTexture(c),a=o.getColorTexture(T),f=o.getColorTexture(l),n=o.getColorTexture(h);const m=u;let x=0;for(const p of m){t.setViewport(0,0,p.width,p.height),t.bindFramebuffer(p),t.setClearColor(0,0,0,0),t.clear(16384);const e={shader:s,uniforms:{config:{minTexture:{texture:i,unit:1},maxTexture:{texture:a,unit:2},sumTexture:{texture:f,unit:3},numOfNoDataTexture:{texture:n,unit:4},width:p.width,height:p.height,isFirstPass:0===x?1:0}},defines:null,optionalAttributes:null,useComputeBuffer:!1};r.submitDrawMesh(t,e,r.quadMesh),i=p.getColorTexture(c),a=p.getColorTexture(T),f=p.getColorTexture(l),n=p.getColorTexture(h),x++}return u.at(-1)}_applySecondReductionPass(e,t,r){const{context:s,painter:u}=e,o=this.shaders.textureStatisticsSum,i=this._framebuffers;if(null===i||null==this._diffFramebuffer)throw new Error("Framebuffers are not initialized, cannot apply reduction pass.");s.setDrawBuffers([c]);let a=this._diffFramebuffer.getColorTexture(c);const f=i;for(const n of f){s.setViewport(0,0,n.width,n.height),s.bindFramebuffer(n),s.setClearColor(0,0,0,0),s.clear(16384);const e={shader:o,uniforms:{config:{sumTexture:{texture:a,unit:2},width:n.width,height:n.height}},defines:null,optionalAttributes:null,useComputeBuffer:!1};u.submitDrawMesh(s,e,u.quadMesh),a=n.getColorTexture(c)}return i.at(-1)}_updateResources(e,t){const{context:r}=e,s=t.width,u=t.height;if(null===this._startFramebuffer){if(!n().supportsColorBufferFloat)throw new Error("WebGL does not support color buffer float, cannot compute texture statistics.");const e=t.getColorTexture(c);if(!e)throw new Error("Input FBO does not have a color attachment 0, cannot compute texture statistics.");const o=e.descriptor,{dataType:i,internalFormat:a}=o,f=w(r,s,u,i,a??m.RGBA8,4),p=f.getColorTexture(c),d=f.getColorTexture(T),b=f.getColorTexture(l),_=f.getColorTexture(h);t.copyToTexture(0,0,s,u,0,0,p),t.copyToTexture(0,0,s,u,0,0,d),t.copyToTexture(0,0,s,u,0,0,b),t.copyToTexture(0,0,s,u,0,0,_),this._startFramebuffer=f,this._diffFramebuffer=w(r,s,u,x.FLOAT,m.RGBA32F),this._resultsFramebuffer=w(r,1,1,x.FLOAT,m.RGBA32F,4),this._minTexture=C(r,1,1,x.FLOAT,m.RGBA32F),this._maxTexture=C(r,1,1,x.FLOAT,m.RGBA32F),this._sumTexture=C(r,1,1,x.FLOAT,m.RGBA32F),this._numOfNoDataTexture=C(r,1,1,x.FLOAT,m.R32F)}else{const e=this._startFramebuffer;e.resize(s,u);const r=e.getColorTexture(c),o=e.getColorTexture(T),i=e.getColorTexture(l),a=e.getColorTexture(h);t.copyToTexture(0,0,s,u,0,0,r),t.copyToTexture(0,0,s,u,0,0,o),t.copyToTexture(0,0,s,u,0,0,i),t.copyToTexture(0,0,s,u,0,0,a),this._diffFramebuffer.resize(s,u)}if(this._width===s&&this._height===u&&null!==this._framebuffers)return;const o=(this._framebuffers||[]).reverse();this._framebuffers=null,this._width=s,this._height=u,this._framebuffers=this._updateFramebuffers(r,s,u,o,4)}_updateFramebuffers(e,t,s,u,o=1){const i=[];let a=t,f=s;for(;a>1||f>1;){const t=Math.max(1,Math.floor(a/2)),r=Math.max(1,Math.floor(f/2)),s=g(e,t,r,u,o);i.push(s),a=t,f=r}return i.at(-1),u.forEach(e=>r(e)),u.length=0,i}_computeDiff(e,t,r,s,u,o){const{context:i,painter:a}=e;i.bindFramebuffer(this._diffFramebuffer),i.setDrawBuffers([c]),i.setViewport(0,0,u,o),i.setClearColor(0,0,0,0),i.clear(16384);const f={shader:this.shaders.textureStatisticsDiff,uniforms:{config:{inputTexture:{texture:t,unit:1},sumTexture:{texture:r,unit:2},numOfNoDataTexture:{texture:s,unit:3},numTexels:u*o}},defines:null,optionalAttributes:null,useComputeBuffer:!1};a.submitDrawMesh(i,f,a.quadMesh)}_computeSdtDev(e,t,r,s,u,o,i,a){const{context:f,painter:n}=e;f.bindFramebuffer(this._resultsFramebuffer),f.setDrawBuffers([c,T,l,h]),f.setViewport(0,0,1,1),f.setClearColor(0,0,0,0),f.clear(16384);const m={shader:this.shaders.textureStatisticsStdDev,uniforms:{config:{minTexture:{texture:t,unit:1},maxTexture:{texture:r,unit:2},sumTexture:{texture:s,unit:3},numOfNoDataTexture:{texture:u,unit:4},diffSqTexture:{texture:o,unit:5},numTexels:i*a}},defines:null,optionalAttributes:null,useComputeBuffer:!1};n.submitDrawMesh(f,m,n.quadMesh)}}function g(e,t,r,s,u=1){let o=s.pop();return void 0!==o?o.resize(t,r):o=w(e,t,r,x.FLOAT,m.RGBA32F,u),o}function w(e,t,r,s,u,o=1){if(o<1||o>4)throw new Error("Number of color attachments must be between 1 and 4.");const i=new p(e,C(e,t,r,s,u));for(let a=1;a<o;a++){const o=C(e,t,r,s,u);i.attachColorTexture(o,c+a)}return i}function C(e,t,r,s,u){const o=new b(t,r);return o.samplingMode=9728,o.wrapMode=33071,o.pixelFormat=6408,o.dataType=s,o.internalFormat=u,new d(e,o)}function S(e){const r=t(e),s=r/2;return Math.abs(r-e)<Math.abs(s-e)?r:s}export{F as TextureStatisticsTechnique};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as t,__param as e}from"tslib";import{location as o,uniform as r,input as s,VertexInput as i,UniformGroup as p,GraphShaderModule as n,FragmentOutput as u,FragmentInput as l}from"../../GraphShaderModule.js";import{Vec2 as m,Sampler2D as d,Float as x,Vec4 as a,texture2D as c,texelFetch as f,Int as v,IVec2 as g}from"../../graph/glsl.js";import{uvToClip as y}from"./utils.js";class h extends i{}t([o(0,m)],h.prototype,"position",void 0);class T extends l{}class w extends p{}t([r(d)],w.prototype,"inputTexture",void 0),t([r(d)],w.prototype,"sumTexture",void 0),t([r(x)],w.prototype,"numTexels",void 0);class j extends n{constructor(){super(...arguments),this.type="TextureStatisticsDiffShader"}vertex(t){const e=t.position;return{uv:e,glPosition:new a(y(e),0,1)}}fragment(t){const{inputTexture:e,sumTexture:o}=this.config,r=new u,s=c(e,t.uv),i=f(o,new g(0,0),new v(0)),p=this.config.numTexels,n=i.divide(p),l=s.subtract(n);return r.fragColor=l.multiply(l),r}}t([r(w)],j.prototype,"config",void 0),t([e(0,s(h))],j.prototype,"vertex",null),t([e(0,s(T))],j.prototype,"fragment",null);export{j as TextureStatisticsDiffShader};
5
+ import{__decorate as t,__param as e}from"tslib";import{location as o,uniform as r,input as s,VertexInput as i,UniformGroup as n,GraphShaderModule as p,FragmentOutput as u,FragmentInput as l}from"../../GraphShaderModule.js";import{Vec2 as a,Sampler2D as m,Float as x,Vec4 as c,texture2D as d,texelFetch as f,Int as v,IVec2 as y,step as g}from"../../graph/glsl.js";import{uvToClip as T}from"./utils.js";class w extends i{}t([o(0,a)],w.prototype,"position",void 0);class h extends l{}class b extends n{}t([r(m)],b.prototype,"inputTexture",void 0),t([r(m)],b.prototype,"sumTexture",void 0),t([r(m)],b.prototype,"numOfNoDataTexture",void 0),t([r(x)],b.prototype,"numTexels",void 0);class j extends p{constructor(){super(...arguments),this.type="TextureStatisticsDiffShader"}vertex(t){const e=t.position;return{uv:e,glPosition:new c(T(e),0,1)}}fragment(t){const{inputTexture:e,numOfNoDataTexture:o,sumTexture:r}=this.config,s=new u,i=d(e,t.uv),n=f(r,new y(0,0),new v(0)),p=f(o,new y(0,0),new v(0)).r,l=this.config.numTexels.subtract(p),a=n.divide(l),m=g(i.a,new x(0)),c=new x(1).subtract(m).multiply(i.subtract(a));return s.fragColor=c.multiply(c),s}}t([r(b)],j.prototype,"config",void 0),t([e(0,s(w))],j.prototype,"vertex",null),t([e(0,s(h))],j.prototype,"fragment",null);export{j as TextureStatisticsDiffShader};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as t,__param as e}from"tslib";import{location as o,uniform as r,input as d,VertexInput as n,UniformGroup as a,GraphShaderModule as i,FragmentOutput as s,FragmentInput as p}from"../../GraphShaderModule.js";import{Vec2 as u,Sampler2D as m,Int as x,Vec4 as l,IVec2 as w,texelFetch as g,min as y,max as c}from"../../graph/glsl.js";import{uvToClip as f,sum4 as v}from"./utils.js";class h extends n{}t([o(0,u)],h.prototype,"position",void 0);class T extends p{}class S extends a{}t([r(m)],S.prototype,"minTexture",void 0),t([r(m)],S.prototype,"maxTexture",void 0),t([r(m)],S.prototype,"sumTexture",void 0),t([r(x)],S.prototype,"width",void 0),t([r(x)],S.prototype,"height",void 0);class j extends i{constructor(){super(...arguments),this.type="TextureStatisticsMinMaxSumShader"}vertex(t){const e=t.position;return{uv:e,glPosition:new l(f(e),0,1)}}fragment(t){const e=new s,{minTexture:o,maxTexture:r,sumTexture:d}=this.config,n=t.glFragCoord.xy,a=new w(n.multiply(2)),i=new x(0),p=g(o,a,i),u=g(o,a.add(new w(-1,0)),i),m=g(o,a.add(new w(0,-1)),i),l=g(o,a.add(new w(-1,-1)),i),f=y(y(p,u),y(m,l)),h=g(r,a,i),T=g(r,a.add(new w(-1,0)),i),S=g(r,a.add(new w(0,-1)),i),j=g(r,a.add(new w(-1,-1)),i),D=c(c(h,T),c(S,j)),M=g(d,a,i),b=g(d,a.add(new w(-1,0)),i),C=g(d,a.add(new w(0,-1)),i),F=g(d,a.add(new w(-1,-1)),i),G=v(M,b,C,F);return e.fragData0=f,e.fragData1=D,e.fragData2=G,e}}t([r(S)],j.prototype,"config",void 0),t([e(0,d(h))],j.prototype,"vertex",null),t([e(0,d(T))],j.prototype,"fragment",null);export{j as TextureStatisticsMinMaxSumShader};
5
+ import{__decorate as t,__param as e}from"tslib";import{location as n,uniform as o,input as r,VertexInput as a,UniformGroup as i,GraphShaderModule as s,FragmentOutput as d,FragmentInput as u}from"../../GraphShaderModule.js";import{Vec2 as p,Sampler2D as l,Int as w,Vec4 as m,IVec2 as c,texelFetch as y,Float as f,step as x,min as g,max as v}from"../../graph/glsl.js";import{maxRepresentableInt as h}from"./constants.js";import{uvToClip as T,sum4 as D}from"./utils.js";class b extends a{}t([n(0,p)],b.prototype,"position",void 0);class j extends u{}class S extends i{}t([o(l)],S.prototype,"minTexture",void 0),t([o(l)],S.prototype,"maxTexture",void 0),t([o(l)],S.prototype,"sumTexture",void 0),t([o(l)],S.prototype,"numOfNoDataTexture",void 0),t([o(w)],S.prototype,"width",void 0),t([o(w)],S.prototype,"height",void 0),t([o(w)],S.prototype,"isFirstPass",void 0);class F extends s{constructor(){super(...arguments),this.type="TextureStatisticsMinMaxSumShader"}vertex(t){const e=t.position;return{uv:e,glPosition:new m(T(e),0,1)}}fragment(t){const e=new d,{minTexture:n,maxTexture:o,sumTexture:r,numOfNoDataTexture:a}=this.config,i=t.glFragCoord.xy,s=new c(i.multiply(2)),u=new w(0),p=y(n,s,u),l=y(n,s.add(new c(-1,0)),u),x=y(n,s.add(new c(0,-1)),u),g=y(n,s.add(new c(-1,-1)),u),v=M(M(p,M(l,new m(h))),M(x,M(g,new m(h)))),T=y(o,s,u),b=y(o,s.add(new c(-1,0)),u),j=y(o,s.add(new c(0,-1)),u),S=y(o,s.add(new c(-1,-1)),u),F=P(P(T,P(b,new m(-h))),P(j,P(S,new m(-h)))),C=y(r,s,u),G=y(r,s.add(new c(-1,0)),u),k=y(r,s.add(new c(0,-1)),u),q=y(r,s.add(new c(-1,-1)),u),z=D(N(C),N(G),N(k),N(q)),A=y(a,s,u),B=y(a,s.add(new c(-1,0)),u),E=y(a,s.add(new c(0,-1)),u),H=y(a,s.add(new c(-1,-1)),u),I=new f(this.config.isFirstPass),J=D(O(A,I),O(B,I),O(E,I),O(H,I));return e.fragData0=v,e.fragData1=F,e.fragData2=z,e.fragData3=J,e}}function M(t,e){const n=x(t.a,new f(0));return g(t,e).multiply(new f(1).subtract(n)).add(e.multiply(n))}function P(t,e){const n=x(t.a,new f(0));return v(t,e).multiply(new f(1).subtract(n)).add(e.multiply(n))}function N(t){const e=x(t.a,new f(0)),n=new f(1).subtract(e);return t.multiply(n)}function O(t,e){const n=x(t.a,new f(0)),o=new f(1).subtract(e);return e.multiply(n).multiply(new m(1)).add(o.multiply(t))}t([o(S)],F.prototype,"config",void 0),t([e(0,r(b))],F.prototype,"vertex",null),t([e(0,r(j))],F.prototype,"fragment",null);export{F as TextureStatisticsMinMaxSumShader};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as t,__param as e}from"tslib";import{location as o,uniform as r,input as i,VertexInput as s,UniformGroup as p,GraphShaderModule as n,FragmentOutput as a,FragmentInput as d}from"../../GraphShaderModule.js";import{Vec2 as u,Sampler2D as x,Float as m,Vec4 as f,IVec2 as l,Int as g,texelFetch as v,sqrt as c}from"../../graph/glsl.js";import{uvToClip as y}from"./utils.js";class T extends s{}t([o(0,u)],T.prototype,"position",void 0);class h extends d{}class S extends p{}t([r(x)],S.prototype,"minTexture",void 0),t([r(x)],S.prototype,"maxTexture",void 0),t([r(x)],S.prototype,"sumTexture",void 0),t([r(x)],S.prototype,"diffSqTexture",void 0),t([r(m)],S.prototype,"numTexels",void 0);class w extends n{constructor(){super(...arguments),this.type="TextureStatisticsStdDevShader"}vertex(t){const e=t.position;return{uv:e,glPosition:new f(y(e),0,1)}}fragment(t){const e=new a,{minTexture:o,maxTexture:r,sumTexture:i,diffSqTexture:s}=this.config,p=t.glFragCoord.xy,n=new l(p),d=new g(0),u=v(o,n,d),x=v(r,n,d),m=v(i,n,d),y=v(s,n,d),T=this.config.numTexels,h=m.divide(T),S=new f(y.divide(T)),w=c(S);return e.fragData0=u,e.fragData1=x,e.fragData2=h,e.fragData3=w,e}}t([r(S)],w.prototype,"config",void 0),t([e(0,i(T))],w.prototype,"vertex",null),t([e(0,i(h))],w.prototype,"fragment",null);export{w as TextureStatisticsStdDevShader};
5
+ import{__decorate as t,__param as e}from"tslib";import{location as o,uniform as r,input as i,VertexInput as s,UniformGroup as a,GraphShaderModule as p,FragmentOutput as n,FragmentInput as u}from"../../GraphShaderModule.js";import{Vec2 as d,Sampler2D as x,Float as m,Vec4 as f,IVec2 as l,Int as g,texelFetch as v,sqrt as c}from"../../graph/glsl.js";import{uvToClip as T}from"./utils.js";class y extends s{}t([o(0,d)],y.prototype,"position",void 0);class h extends u{}class D extends a{}t([r(x)],D.prototype,"minTexture",void 0),t([r(x)],D.prototype,"maxTexture",void 0),t([r(x)],D.prototype,"sumTexture",void 0),t([r(x)],D.prototype,"numOfNoDataTexture",void 0),t([r(x)],D.prototype,"diffSqTexture",void 0),t([r(m)],D.prototype,"numTexels",void 0);class S extends p{constructor(){super(...arguments),this.type="TextureStatisticsStdDevShader"}vertex(t){const e=t.position;return{uv:e,glPosition:new f(T(e),0,1)}}fragment(t){const e=new n,{minTexture:o,maxTexture:r,numOfNoDataTexture:i,sumTexture:s,diffSqTexture:a}=this.config,p=t.glFragCoord.xy,u=new l(p),d=new g(0),x=v(o,u,d),m=v(r,u,d),f=v(s,u,d),T=v(i,u,d).r,y=v(a,u,d),h=this.config.numTexels.subtract(T),D=f.divide(h),S=y.divide(h),w=c(S);return e.fragData0=x,e.fragData1=m,e.fragData2=D,e.fragData3=w,e}}t([r(D)],S.prototype,"config",void 0),t([e(0,i(y))],S.prototype,"vertex",null),t([e(0,i(h))],S.prototype,"fragment",null);export{S as TextureStatisticsStdDevShader};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as t,__param as e}from"tslib";import{location as o,uniform as r,input as s,VertexInput as i,UniformGroup as n,GraphShaderModule as p,FragmentOutput as a,FragmentInput as d}from"../../GraphShaderModule.js";import{Vec2 as l,Sampler2D as u,Int as f,Vec4 as m,IVec2 as g,texelFetch as c}from"../../graph/glsl.js";import{uvToClip as x,sum4 as w}from"./utils.js";class y extends i{}t([o(0,l)],y.prototype,"position",void 0);class h extends d{}class v extends n{}t([r(u)],v.prototype,"sumTexture",void 0),t([r(f)],v.prototype,"width",void 0),t([r(f)],v.prototype,"height",void 0);class S extends p{constructor(){super(...arguments),this.type="TextureStatisticsSumOfSquaredDiffShader"}vertex(t){const e=t.position;return{uv:e,glPosition:new m(x(e),0,1)}}fragment(t){const e=new a,{sumTexture:o}=this.config,r=t.glFragCoord.xy,s=new g(r.multiply(2)),i=new f(0),n=c(o,s,i),p=c(o,s.add(new g(-1,0)),i),d=c(o,s.add(new g(0,-1)),i),l=c(o,s.add(new g(-1,-1)),i),u=w(n,p,d,l);return e.fragData0=u,e.fragData1=new m(0),e.fragData2=new m(0),e}}t([r(v)],S.prototype,"config",void 0),t([e(0,s(y))],S.prototype,"vertex",null),t([e(0,s(h))],S.prototype,"fragment",null);export{S as TextureStatisticsSumOfSquaredDiffShader};
5
+ import{__decorate as t,__param as e}from"tslib";import{location as o,uniform as r,input as s,VertexInput as a,UniformGroup as n,GraphShaderModule as i,FragmentOutput as p,FragmentInput as d}from"../../GraphShaderModule.js";import{Vec2 as l,Sampler2D as u,Int as f,Vec4 as g,IVec2 as m,texelFetch as c}from"../../graph/glsl.js";import{uvToClip as w,sum4 as x}from"./utils.js";class y extends a{}t([o(0,l)],y.prototype,"position",void 0);class h extends d{}class v extends n{}t([r(u)],v.prototype,"sumTexture",void 0),t([r(f)],v.prototype,"width",void 0),t([r(f)],v.prototype,"height",void 0);class D extends i{constructor(){super(...arguments),this.type="TextureStatisticsSumOfSquaredDiffShader"}vertex(t){const e=t.position;return{uv:e,glPosition:new g(w(e),0,1)}}fragment(t){const e=new p,{sumTexture:o}=this.config,r=t.glFragCoord.xy,s=new m(r.multiply(2)),a=new f(0),n=c(o,s,a),i=c(o,s.add(new m(-1,0)),a),d=c(o,s.add(new m(0,-1)),a),l=c(o,s.add(new m(-1,-1)),a),u=x(n,i,d,l);return e.fragData0=u,e.fragData1=new g(0),e.fragData2=new g(0),e.fragData3=new g(0),e}}t([r(v)],D.prototype,"config",void 0),t([e(0,s(y))],D.prototype,"vertex",null),t([e(0,s(h))],D.prototype,"fragment",null);export{D as TextureStatisticsSumOfSquaredDiffShader};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import r from"../../../../core/Accessor.js";import{property as t}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/has.js";import"../../../../core/Logger.js";import"../../../../core/RandomLCG.js";import{subclass as o}from"../../../../core/accessorSupport/decorators/subclass.js";import{i as n}from"../../../../chunks/vec32.js";import{fromValues as s,create as i}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{create as a,width as c,height as p,expand as d}from"../../../../geometry/support/aaBoundingRect.js";import{vectorCoordinates as l}from"../../../../geometry/support/coordinateSystem.js";let m=class extends r{constructor(e){super(e),this.rawResult=null}get localOrigin(){const{extent:e}=this;return s(e.center.x,e.center.y,0)}get localOriginRenderSpace(){const{extent:e,localOrigin:r,renderCoordsHelper:t}=this,o=i();return t.toRenderCoords(r,e.spatialReference,o),o}get cameraPositionRenderSpace(){const{localOriginRenderSpace:e,renderCoordsHelper:r}=this,t=i();return r.setAltitude(t,g,e),t}get cameraDimensions(){const{extent:e,renderCoordsHelper:r}=this;if(2===r.viewingMode)return{width:e.width,height:e.height};const t=a();this._expandBoundingRect(e.xmin,e.ymin,t),this._expandBoundingRect(e.xmax,e.ymin,t),this._expandBoundingRect(e.xmin,e.ymax,t),this._expandBoundingRect(e.xmax,e.ymax,t);return{width:c(t),height:p(t)}}get cameraNearFar(){return{near:x,far:R}}get upVector(){return this.renderCoordsHelper.worldBasisAtPosition(this.cameraPositionRenderSpace,2,i())}get northVector(){return this.renderCoordsHelper.worldBasisAtPosition(this.cameraPositionRenderSpace,1,i())}get eastVector(){return this.renderCoordsHelper.worldBasisAtPosition(this.cameraPositionRenderSpace,0,i())}_expandBoundingRect(e,r,t){const{extent:o,eastVector:s,northVector:i,upVector:a,renderCoordsHelper:c}=this,p=o.center.z??0;n(u,e,r,p),c.toRenderCoords(u,o.spatialReference,u),l(u,s,i,a,h),d(t,h,t)}};e([t()],m.prototype,"renderCoordsHelper",void 0),e([t()],m.prototype,"extent",void 0),e([t()],m.prototype,"localOrigin",null),e([t()],m.prototype,"localOriginRenderSpace",null),e([t()],m.prototype,"cameraPositionRenderSpace",null),e([t()],m.prototype,"cameraDimensions",null),e([t()],m.prototype,"upVector",null),e([t()],m.prototype,"northVector",null),e([t()],m.prototype,"eastVector",null),e([t()],m.prototype,"rawResult",void 0),m=e([o("esri.views.3d.analysis.VolumeMeasurement.VolumeMeasurementCutFillComputation")],m);const u=i(),h=i(),g=9e3,x=0,R=2e4;export{m as VolumeMeasurementCutFillComputation};
5
+ import{__decorate as e}from"tslib";import r from"../../../../core/Accessor.js";import{property as t}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/has.js";import"../../../../core/Logger.js";import"../../../../core/RandomLCG.js";import{subclass as o}from"../../../../core/accessorSupport/decorators/subclass.js";import{i as n}from"../../../../chunks/vec32.js";import{fromValues as s,create as i}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{create as c,fromExtent as a,width as p,height as d,expand as l}from"../../../../geometry/support/aaBoundingRect.js";import{vectorCoordinates as m}from"../../../../geometry/support/coordinateSystem.js";let u=class extends r{constructor(e){super(e),this.rawResult=null}get localOrigin(){const{extent:e}=this;return s(e.center.x,e.center.y,0)}get localOriginRenderSpace(){const{extent:e,localOrigin:r,renderCoordsHelper:t}=this,o=i();return t.toRenderCoords(r,e.spatialReference,o),o}get cameraPositionRenderSpace(){const{localOriginRenderSpace:e,renderCoordsHelper:r}=this,t=i();return r.setAltitude(t,R,e),t}get boundingRect(){const{extent:e,renderCoordsHelper:r}=this,t=c();return 2===r.viewingMode?a(e,t):(this._expandBoundingRect(e.xmin,e.ymin,t),this._expandBoundingRect(e.xmax,e.ymin,t),this._expandBoundingRect(e.xmin,e.ymax,t),this._expandBoundingRect(e.xmax,e.ymax,t)),t}get cameraDimensions(){const{boundingRect:e}=this;return{width:p(e),height:d(e)}}get cameraNearFar(){return{near:x,far:y}}get upVector(){return this.renderCoordsHelper.worldBasisAtPosition(this.cameraPositionRenderSpace,2,i())}get northVector(){return this.renderCoordsHelper.worldBasisAtPosition(this.cameraPositionRenderSpace,1,i())}get eastVector(){return this.renderCoordsHelper.worldBasisAtPosition(this.cameraPositionRenderSpace,0,i())}_expandBoundingRect(e,r,t){const{extent:o,eastVector:s,northVector:i,upVector:c,renderCoordsHelper:a}=this,p=o.center.z??0;n(g,e,r,p),a.toRenderCoords(g,o.spatialReference,g),m(g,s,i,c,h),l(t,h,t)}};e([t()],u.prototype,"renderCoordsHelper",void 0),e([t()],u.prototype,"extent",void 0),e([t()],u.prototype,"localOrigin",null),e([t()],u.prototype,"localOriginRenderSpace",null),e([t()],u.prototype,"cameraPositionRenderSpace",null),e([t()],u.prototype,"boundingRect",null),e([t()],u.prototype,"cameraDimensions",null),e([t()],u.prototype,"upVector",null),e([t()],u.prototype,"northVector",null),e([t()],u.prototype,"eastVector",null),e([t()],u.prototype,"rawResult",void 0),u=e([o("esri.views.3d.analysis.VolumeMeasurement.VolumeMeasurementCutFillComputation")],u);const g=i(),h=i(),R=9e3,x=0,y=2e4;export{u as VolumeMeasurementCutFillComputation};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import t from"../../../../core/Accessor.js";import o from"../../../../core/Logger.js";import{syncAndInitial as i,watch as r,when as s,initial as n}from"../../../../core/reactiveUtils.js";import{property as a}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/has.js";import"../../../../core/RandomLCG.js";import{subclass as l}from"../../../../core/accessorSupport/decorators/subclass.js";import{e as p}from"../../../../chunks/earcut.js";import{create as m}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{UpdatingHandles as u}from"../../../../core/support/UpdatingHandles.js";import{projectOrLoad as d}from"../../../../geometry/projectionUtils.js";import{computeTranslationToOriginAndRotation as c}from"../../../../geometry/projection/computeTranslationToOriginAndRotation.js";import{projectBoundingRect as h}from"../../../../geometry/projection/projectBoundingRect.js";import{empty as y,fromExtent as g,intersects as f}from"../../../../geometry/support/aaBoundingRect.js";import{newDoubleArray as v}from"../../../../geometry/support/DoubleArray.js";import{t as _}from"../../../../chunks/vec3.js";import w from"../../../../symbols/support/ElevationInfo.js";import{logFailedGeometryProjectionError as j}from"../support/projectionUtils.js";import{VolumeMeasurementCutFillComputation as C}from"./VolumeMeasurementCutFillComputation.js";import G from"./VolumeMeasurementResult.js";import{getRawResult as R}from"./volumeMeasurementUtils.js";import{ElevationContext as D}from"../../layers/graphics/ElevationContext.js";import{getElevationAtPoint as V}from"../../support/ElevationProvider.js";import{geometryToRenderInfo as H}from"../../support/renderInfoUtils/polygon.js";import{CutFillDepth as x,TargetGeometry as b}from"../../webgl-engine/lib/CutFillDepth.js";let A=class extends t{constructor(e){super(e),this._computation=null,this._updatingHandles=new u}initialize(){const e=this.view;this._renderer=new x({view:e}),this._updatingHandles.add(()=>({geometry:this.analysis.geometry,projectedGeometry:d(this.analysis.geometry,this.view.spatialReference)}),({geometry:e,projectedGeometry:t})=>{null==t.pending?this._onGeometryChange(e,t.geometry):this._updatingHandles.addPromise(t.pending)},i),this.addHandles([this._createElevationUpdateHandle(),r(()=>[this.analysis.measureType,this.analysisViewData.elevationAlignedGeometry,this.analysisViewData.effectiveTargetElevation],()=>this._updateTargetGeometry(),n),r(()=>this.analysisViewData.targetGeometry,e=>{if(!e||!this._computation)return;const t=this._getGeometryAttributes(e,this._computation.extent,this._computation.localOrigin);this._renderer.setup(this._computation,t),this._renderer.start()},n),s(()=>this._renderer.done,()=>this._updateResult())])}destroy(){this._updatingHandles.destroy(),this._renderer.destroy()}get updating(){return this._renderer.updating||this._updatingHandles.updating}get result(){const e=this._computation?.rawResult;return e?new G({measureType:this.analysis.measureType,rawResult:e,unit:this.analysisViewData.unit}):null}_createComputation(e){const{renderCoordsHelper:t}=this.view;this._computation=new C({extent:e,renderCoordsHelper:t})}_updateComputation(e){this._computation?this._computation.extent=e:this._createComputation(e)}_removeComputation(){this._computation=null}_createElevationUpdateHandle(){const e=t=>{const o=this.analysis.geometry;if(null==o||"ground"!==t.context)return;const i=d(o,this.view.spatialReference);if(null!=i.pending)return this._updatingHandles.addPromise(i.pending),void i.pending.finally(()=>e(t));const r=i.geometry;null!=r&&null!=r.extent&&(h(t.extent,t.spatialReference,T,this.view.spatialReference),g(r.extent,U),f(T,U)&&this._onGeometryChange(o,r))};return this.view.elevationProvider.on("elevation-change",t=>e(t))}_onGeometryChange(e,t){const{elevationProvider:i}=this.view,{valid:r}=this.analysis;if(null==e||!r)return this.analysisViewData.elevationAlignedGeometry=null,void this._removeComputation();if(null==t)return j(this.analysis,e.spatialReference,o.getLogger(this)),void(this.analysisViewData.elevationAlignedGeometry=null);this._updateComputation(t.extent);const s=t.clone();E(i,s),this.analysisViewData.elevationAlignedGeometry=s}_updateTargetGeometry(){const{measureType:e}=this.analysis,{elevationAlignedGeometry:t,effectiveTargetElevation:o}=this.analysisViewData;if(!t)return void(this.analysisViewData.targetGeometry=null);if("stockpile"===e||null==o)return void(this.analysisViewData.targetGeometry=t);const i=t.clone();i.rings[0].forEach(e=>{e[2]=o}),this.analysisViewData.targetGeometry=i}_updateResult(){if(!this._computation)return;const{cameraDimensions:e,cameraNearFar:{near:t,far:o}}=this._computation,{width:i,height:r}=this._renderer,s=e.width/i*(e.height/r),n=this._renderer.getDepth(),a=e=>e*(o-t)+t,l=a(n.cut)*s,p=a(n.fill)*s;this._computation.rawResult=R(Math.abs(l),p)}_getGeometryAttributes(e,t,o){const{elevationProvider:i,renderCoordsHelper:r}=this.view,s=H(e,i,r,D.fromElevationInfo(new w({mode:"absolute-height"}))),{polygons:n}=s,a=n[0],l=p(a.position,a.holeIndices,3),u=v(3*a.count),d=m(),h=m();return c(t.spatialReference,o,d,r.spatialReference),h[12]=-d[12],h[13]=-d[13],h[14]=-d[14],_(u,a.position,h),new b(u,l)}};function E(e,t){t.rings[0].forEach(t=>{t[2]=V(e,t,"ground")??0})}e([a({constructOnly:!0})],A.prototype,"analysis",void 0),e([a({constructOnly:!0})],A.prototype,"analysisViewData",void 0),e([a({constructOnly:!0})],A.prototype,"view",void 0),e([a()],A.prototype,"updating",null),e([a()],A.prototype,"result",null),e([a()],A.prototype,"_renderer",void 0),e([a()],A.prototype,"_computation",void 0),e([a({readOnly:!0})],A.prototype,"_updatingHandles",void 0),A=e([l("esri.views.3d.analysis.VolumeMeasurement.VolumeMeasurementCutFillController")],A);const T=y(),U=y();export{A as VolumeMeasurementCutFillController};
5
+ import{__decorate as e}from"tslib";import t from"../../../../core/Accessor.js";import i from"../../../../core/Logger.js";import{syncAndInitial as o,watch as r,when as n,initial as s}from"../../../../core/reactiveUtils.js";import{property as a}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/has.js";import"../../../../core/RandomLCG.js";import{subclass as l}from"../../../../core/accessorSupport/decorators/subclass.js";import{e as p}from"../../../../chunks/earcut.js";import{create as m}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{UpdatingHandles as u}from"../../../../core/support/UpdatingHandles.js";import{projectOrLoad as c}from"../../../../geometry/projectionUtils.js";import{computeTranslationToOriginAndRotation as d}from"../../../../geometry/projection/computeTranslationToOriginAndRotation.js";import{projectBoundingRect as h}from"../../../../geometry/projection/projectBoundingRect.js";import{width as y,height as g,empty as f,fromExtent as v,intersects as _}from"../../../../geometry/support/aaBoundingRect.js";import{newDoubleArray as w}from"../../../../geometry/support/DoubleArray.js";import{t as j}from"../../../../chunks/vec3.js";import R from"../../../../symbols/support/ElevationInfo.js";import{logFailedGeometryProjectionError as x}from"../support/projectionUtils.js";import{VolumeMeasurementCutFillComputation as C}from"./VolumeMeasurementCutFillComputation.js";import G from"./VolumeMeasurementResult.js";import{getRawResult as D}from"./volumeMeasurementUtils.js";import{ElevationContext as V}from"../../layers/graphics/ElevationContext.js";import{getElevationAtPoint as H}from"../../support/ElevationProvider.js";import{geometryToRenderInfo as b}from"../../support/renderInfoUtils/polygon.js";import{CutFillDepth as A,TargetGeometry as E}from"../../webgl-engine/lib/CutFillDepth.js";import{euclideanDirectDistance as T}from"../../../support/euclideanLengthMeasurementUtils.js";let U=class extends t{constructor(e){super(e),this._computation=null,this._updatingHandles=new u}initialize(){const e=this.view;this._renderer=new A({view:e}),this._updatingHandles.add(()=>({geometry:this.analysis.geometry,projectedGeometry:c(this.analysis.geometry,this.view.spatialReference)}),({geometry:e,projectedGeometry:t})=>{null==t.pending?this._onGeometryChange(e,t.geometry):this._updatingHandles.addPromise(t.pending)},o),this.addHandles([this._createElevationUpdateHandle(),r(()=>[this.analysis.measureType,this.analysisViewData.elevationAlignedGeometry,this.analysisViewData.effectiveTargetElevation],()=>this._updateTargetGeometry(),s),r(()=>this.analysisViewData.targetGeometry,e=>{if(!e||!this._computation)return;const t=this._getGeometryAttributes(e,this._computation.extent,this._computation.localOrigin);this._renderer.setup(this._computation,t),this._renderer.start()},s),n(()=>this._renderer.done,()=>this._updateResult())])}destroy(){this._updatingHandles.destroy(),this._renderer.destroy()}get updating(){return this._renderer.updating||this._updatingHandles.updating}get result(){const e=this._computation?.rawResult;return e?new G({measureType:this.analysis.measureType,rawResult:e,unit:this.analysisViewData.effectiveDisplayUnits.volume}):null}_createComputation(e){const{renderCoordsHelper:t}=this.view;this._computation=new C({extent:e,renderCoordsHelper:t})}_updateComputation(e){this._computation?this._computation.extent=e:this._createComputation(e)}_removeComputation(){this._computation=null}_createElevationUpdateHandle(){const e=t=>{const i=this.analysis.geometry;if(null==i||"ground"!==t.context)return;const o=c(i,this.view.spatialReference);if(null!=o.pending)return this._updatingHandles.addPromise(o.pending),void o.pending.finally(()=>e(t));const r=o.geometry;null!=r&&null!=r.extent&&(h(t.extent,t.spatialReference,P,this.view.spatialReference),v(r.extent,F),_(P,F)&&this._onGeometryChange(i,r))};return this.view.elevationProvider.on("elevation-change",t=>e(t))}_onGeometryChange(e,t){const{elevationProvider:o}=this.view,{valid:r}=this.analysis;if(null==e||!r)return this.analysisViewData.elevationAlignedGeometry=null,void this._removeComputation();if(null==t)return x(this.analysis,e.spatialReference,i.getLogger(this)),void(this.analysisViewData.elevationAlignedGeometry=null);this._updateComputation(t.extent);const n=t.clone();M(o,n),this.analysisViewData.elevationAlignedGeometry=n}_updateTargetGeometry(){const{measureType:e}=this.analysis,{elevationAlignedGeometry:t,effectiveTargetElevation:i}=this.analysisViewData;if(!t)return void(this.analysisViewData.targetGeometry=null);if("stockpile"===e||null==i)return void(this.analysisViewData.targetGeometry=t);const o=t.clone();o.rings[0].forEach(e=>{e[2]=i}),this.analysisViewData.targetGeometry=o}_updateResult(){if(!this._computation)return;const{spatialReference:e,viewingMode:t}=this.view,{extent:i,boundingRect:o,cameraNearFar:{near:r,far:n}}=this._computation,{width:s,height:a}=this._renderer;let l,p;"local"===t&&e.isWebMercator?({width:l,height:p}=O(i)):(l=y(o),p=g(o));const m=l/s*(p/a),u=this._renderer.getDepth(),c=e=>e*(n-r)+r,d=c(u.cut)*m,h=c(u.fill)*m;this._computation.rawResult=D(Math.abs(d),h)}_getGeometryAttributes(e,t,i){const{elevationProvider:o,renderCoordsHelper:r}=this.view,n=b(e,o,r,V.fromElevationInfo(new R({mode:"absolute-height"}))),{polygons:s}=n,a=s[0],l=p(a.position,a.holeIndices,3),u=w(3*a.count),c=m(),h=m();return d(t.spatialReference,i,c,r.spatialReference),h[12]=-c[12],h[13]=-c[13],h[14]=-c[14],j(u,a.position,h),new E(u,l)}};function M(e,t){t.rings[0].forEach(t=>{t[2]=H(e,t,"ground")??0})}function O(e){const t=T([e.xmin,e.ymin,0],[e.xmax,e.ymin,0],e.spatialReference),i=T([e.xmin,e.ymin,0],[e.xmin,e.ymax,0],e.spatialReference);return{width:t?.value??0,height:i?.value??0}}e([a({constructOnly:!0})],U.prototype,"analysis",void 0),e([a({constructOnly:!0})],U.prototype,"analysisViewData",void 0),e([a({constructOnly:!0})],U.prototype,"view",void 0),e([a()],U.prototype,"updating",null),e([a()],U.prototype,"result",null),e([a()],U.prototype,"_renderer",void 0),e([a()],U.prototype,"_computation",void 0),e([a({readOnly:!0})],U.prototype,"_updatingHandles",void 0),U=e([l("esri.views.3d.analysis.VolumeMeasurement.VolumeMeasurementCutFillController")],U);const P=f(),F=f();export{U as VolumeMeasurementCutFillController};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as t}from"tslib";import{deg2rad as i}from"../../../../core/mathUtils.js";import{createLength as o}from"../../../../core/quantityUtils.js";import{watch as e,sync as s,syncAndInitial as a}from"../../../../core/reactiveUtils.js";import{verticalLengthUnitFromSpatialReference as r}from"../../../../core/unitUtils.js";import{property as n}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/has.js";import"../../../../core/Logger.js";import"../../../../core/RandomLCG.js";import{subclass as l}from"../../../../core/accessorSupport/decorators/subclass.js";import{rotateZ as p}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{d as h,m as c}from"../../../../chunks/vec32.js";import{fromArray as u,clone as m}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{sv3d as d,sm4d as f}from"../../../../geometry/support/vectorStacks.js";import{ShiftManipulator as v}from"../Slice/ShiftManipulator.js";import{IsShiftEdgeOnScreenFlag as y}from"../Slice/sliceToolUtils.js";import{calculateTranslateRotateFromBases as _}from"../../interactive/manipulatorUtils.js";import{screenToZConstrained as g}from"../../interactive/editingTools/dragEventPipeline3D.js";import{createManipulatorDragEventPipeline as w}from"../../../interactive/dragEventPipeline.js";import{InteractiveToolBase as T}from"../../../interactive/InteractiveToolBase.js";import j from"../../../interactive/sketch/SketchOptions.js";import{makeTooltip as M,enterInputModeIfAvailable as V}from"../../../interactive/tooltip/tooltipCommonUtils.js";import{ElevationTooltipInfo as O}from"../../../interactive/tooltip/infos/ElevationTooltipInfo.js";let S=class extends T{constructor(t){super(t),this.sketchOptions=new j,this._tooltipInfo=null}initialize(){const{view:t}=this;this._shiftManipulator=new v(t,0),this._shiftManipulator.state|=y,this.manipulators.add(this._shiftManipulator),this.addHandles([this._createDragPipeline(),e(()=>this.analysisViewData.targetGeometry,()=>this._updateManipulatorPosition(),s),e(()=>[this.analysisViewData.interactive,this.analysisViewData.targetGeometry,this.analysis.measureType],()=>this._updateManipulatorVisibility(),a)]),this._initializeTooltip(),this.finishToolCreation()}_initializeTooltip(){const{view:t}=this;this.tooltip=M(()=>({view:t,options:this.sketchOptions.tooltips})),this.sketchOptions.tooltips.placement="trailing",this.addHandles([e(()=>this.analysisViewData.effectiveTargetElevation,()=>this._updateTooltip()),e(()=>this._shouldShowTooltip,t=>{t?this._showTooltip():this._hideTooltip()}),this.tooltip.on("commit",()=>{const t=this._tooltipInfo?.elevation.actual?.value;this._updateValue(t)})])}destroy(){this._shiftManipulator.destroy(),this.tooltip.destroy()}onInputEvent(t){if(!this.destroyed&&!V(t,this.tooltip))return super.onInputEvent(t)}get _shouldShowTooltip(){return this.hasFocusedManipulators||"input"===this.tooltip.mode}_createDragPipeline(){const{cutFillOptions:t}=this.analysis;return w(this._shiftManipulator,(i,o,e)=>{const s=m(i.renderLocation),a=t.targetElevation;o.next(g(this.view,s,this.view.spatialReference)).next(t=>(this._updateValue(t.mapEnd.z),t)),e.next(()=>{this._updateValue(a)})})}_updateManipulatorPosition(){const{targetGeometry:t}=this.analysisViewData,{renderCoordsHelper:o}=this.view;if(!t)return;const e=.5,s=t.rings[0],a=u(s[0]),r=u(s[1]);o.toRenderCoords(a,t.spatialReference,a),o.toRenderCoords(r,t.spatialReference,r);const n=d.get();h(n,r,a);const l=d.get();c(l,a,r,e);const v=o.worldBasisAtPosition(l,1,d.get()),y=o.worldBasisAtPosition(l,0,d.get()),g=_(v,y,l,f.get()),w=o.headingAtPosition(l,n),T=t.isClockwise(t.rings[0])?-Math.PI/2:Math.PI/2;p(g,g,i(w)+T),g[12]=0,g[13]=0,g[14]=0,this._shiftManipulator.renderLocation=m(l),this._shiftManipulator.modelTransform=g}_updateManipulatorVisibility(){const{interactive:t,targetGeometry:i}=this.analysisViewData,{measureType:o}=this.analysis,e=t&&null!=i&&"cut-fill"===o;this._shiftManipulator.available=e}_updateValue(t){this.analysis.cutFillOptions.targetElevation=t}_getUpdatedTooltipInfo(){const{effectiveTargetElevation:t}=this.analysisViewData,i=this._tooltipInfo??=new O({sketchOptions:this.sketchOptions}),e=r(this.view.spatialReference);return t&&e?(i.elevation.actual=o(t,e),i):null}_updateTooltip(){this._shouldShowTooltip&&(this.tooltip.info=this._getUpdatedTooltipInfo())}_showTooltip(){this._updateTooltip()}_hideTooltip(){this.tooltip?.clear()}};t([n({constructOnly:!0})],S.prototype,"analysis",void 0),t([n({constructOnly:!0})],S.prototype,"view",void 0),t([n({constructOnly:!0})],S.prototype,"analysisViewData",void 0),t([n({constructOnly:!0,type:j})],S.prototype,"sketchOptions",void 0),t([n()],S.prototype,"_shouldShowTooltip",null),S=t([l("esri.views.3d.analysis.VolumeMeasurement.VolumeMeasurementShiftTool")],S);export{S as VolumeMeasurementShiftTool};
5
+ import{__decorate as t}from"tslib";import{deg2rad as i}from"../../../../core/mathUtils.js";import{valueInUnit as o}from"../../../../core/quantityUtils.js";import{watch as e,sync as s,syncAndInitial as a}from"../../../../core/reactiveUtils.js";import{verticalLengthUnitFromSpatialReference as n,convertUnit as r}from"../../../../core/unitUtils.js";import{property as l}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/has.js";import"../../../../core/Logger.js";import"../../../../core/RandomLCG.js";import{subclass as p}from"../../../../core/accessorSupport/decorators/subclass.js";import{rotateZ as h}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{d as c,m as u}from"../../../../chunks/vec32.js";import{fromArray as m,clone as d}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{sv3d as f,sm4d as v}from"../../../../geometry/support/vectorStacks.js";import{ShiftManipulator as y}from"../Slice/ShiftManipulator.js";import{IsShiftEdgeOnScreenFlag as _}from"../Slice/sliceToolUtils.js";import{calculateTranslateRotateFromBases as w}from"../../interactive/manipulatorUtils.js";import{screenToZConstrained as g}from"../../interactive/editingTools/dragEventPipeline3D.js";import{createManipulatorDragEventPipeline as T}from"../../../interactive/dragEventPipeline.js";import{InteractiveToolBase as j}from"../../../interactive/InteractiveToolBase.js";import M from"../../../interactive/sketch/SketchOptions.js";import U from"../../../interactive/sketch/Units.js";import{makeTooltip as O,enterInputModeIfAvailable as k}from"../../../interactive/tooltip/tooltipCommonUtils.js";import{ElevationTooltipInfo as V}from"../../../interactive/tooltip/infos/ElevationTooltipInfo.js";import{elevationFromZ as S}from"../../../support/euclideanLengthMeasurementUtils.js";let I=class extends j{constructor(t){super(t),this.sketchOptions=new M}initialize(){const{view:t}=this;this._shiftManipulator=new y(t,0),this._shiftManipulator.state|=_,this.manipulators.add(this._shiftManipulator),this.addHandles([this._createDragPipeline(),e(()=>this.analysisViewData.targetGeometry,()=>this._updateManipulatorPosition(),s),e(()=>[this.analysisViewData.interactive,this.analysisViewData.targetGeometry,this.analysis.measureType],()=>this._updateManipulatorVisibility(),a)]),this._initializeTooltip(),this.finishToolCreation()}_initializeTooltip(){const{view:t}=this;this.tooltip=O(()=>({view:t,options:this.sketchOptions.tooltips})),this._tooltipInfo=new V({sketchOptions:this.sketchOptions}),this.sketchOptions.tooltips.placement="trailing",this._updateSketchOptions(),this.addHandles([e(()=>this.analysisViewData.effectiveTargetElevation,()=>this._updateTooltip()),e(()=>this._shouldShowTooltip,t=>{t?this._showTooltip():this._hideTooltip()}),this.tooltip.on("commit",()=>{const t=this._tooltipInfo.elevation.actual,i=n(this.view.spatialReference);if(null==t||null==i)return;const e=o(t,i);this._updateValue(e)}),e(()=>[this.analysis.displayUnits.elevation,this.analysis.inputUnits.elevation],()=>this._updateSketchOptions(),a)])}destroy(){this._shiftManipulator.destroy(),this.tooltip.destroy()}onInputEvent(t){if(!this.destroyed&&!k(t,this.tooltip))return super.onInputEvent(t)}get _shouldShowTooltip(){return this.hasFocusedManipulators||"input"===this.tooltip.mode}_createDragPipeline(){const{targetElevation:t}=this.analysis.cutFillOptions;return T(this._shiftManipulator,(i,o,e)=>{const s=d(i.renderLocation),a=this.analysis.inputUnits.elevation??"meters",l=n(this.view.spatialReference),p=t&&l?r(t,a,l):null;o.next(g(this.view,s,this.view.spatialReference)).next(t=>(this._updateValue(t.mapEnd.z),t)),e.next(()=>{this._updateValue(p)})})}_updateManipulatorPosition(){const{targetGeometry:t}=this.analysisViewData,{renderCoordsHelper:o}=this.view;if(!t)return;const e=.5,s=t.rings[0],a=m(s[0]),n=m(s[1]);o.toRenderCoords(a,t.spatialReference,a),o.toRenderCoords(n,t.spatialReference,n);const r=f.get();c(r,n,a);const l=f.get();u(l,a,n,e);const p=o.worldBasisAtPosition(l,1,f.get()),y=o.worldBasisAtPosition(l,0,f.get()),_=w(p,y,l,v.get()),g=o.headingAtPosition(l,r),T=t.isClockwise(t.rings[0])?-Math.PI/2:Math.PI/2;h(_,_,i(g)+T),_[12]=0,_[13]=0,_[14]=0,this._shiftManipulator.renderLocation=d(l),this._shiftManipulator.modelTransform=_}_updateManipulatorVisibility(){const{interactive:t,targetGeometry:i}=this.analysisViewData,{measureType:o}=this.analysis,e=t&&null!=i&&"cut-fill"===o;this._shiftManipulator.available=e}_updateValue(t){const i=S(t,this.view.spatialReference);if(null==i)return;const o=this.analysis.inputUnits.elevation??"meters";this.analysis.cutFillOptions.targetElevation=r(i.value,i.unit,o)}_getUpdatedTooltipInfo(){const{effectiveTargetElevation:t}=this.analysisViewData;return t?(this._tooltipInfo.elevation.actual=S(t,this.view.spatialReference),this._tooltipInfo):this._tooltipInfo}_updateTooltip(){this._shouldShowTooltip&&(this.tooltip.info=this._getUpdatedTooltipInfo())}_showTooltip(){this._updateTooltip()}_hideTooltip(){this.tooltip?.clear()}_updateSketchOptions(){const{analysis:t}=this,{displayUnits:i,inputUnits:o}=t;this.sketchOptions.values.inputUnits=new U({verticalLength:o.elevation}),this.sketchOptions.values.displayUnits=new U({verticalLength:i.elevation})}};t([l({constructOnly:!0})],I.prototype,"analysis",void 0),t([l({constructOnly:!0})],I.prototype,"view",void 0),t([l({constructOnly:!0})],I.prototype,"analysisViewData",void 0),t([l({constructOnly:!0,type:M})],I.prototype,"sketchOptions",void 0),t([l()],I.prototype,"_shouldShowTooltip",null),I=t([p("esri.views.3d.analysis.VolumeMeasurement.VolumeMeasurementShiftTool")],I);export{I as VolumeMeasurementShiftTool};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import"../../../core/has.js";import{destroyMaybe as t}from"../../../core/maybe.js";import{property as s}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/Logger.js";import"../../../core/RandomLCG.js";import{subclass as i}from"../../../core/accessorSupport/decorators/subclass.js";import{getDefaultUnitForView as o}from"../../../support/getDefaultUnitForView.js";import{AnalysisView3D as r}from"./AnalysisView3D.js";import{VolumeMeasurementCutFillController as l}from"./VolumeMeasurement/VolumeMeasurementCutFillController.js";import{VolumeMeasurementCutFillVisualization as a}from"./VolumeMeasurement/VolumeMeasurementCutFillVisualization.js";import n from"./VolumeMeasurement/VolumeMeasurementTool.js";let u=class extends r{constructor(e){super(e),this.type="volume-measurement-view-3d",this.analysis=null,this.elevationAlignedGeometry=null,this.targetGeometry=null}initialize(){const{analysis:e,view:t}=this;this._analysisController=new l({view:t,analysis:e,analysisViewData:this}),this._analysisTool=new n({analysis:e,view:t,analysisViewData:this}),this._analysisVisualization=new a({view:t,analysisViewData:this})}destroy(){this._analysisController=t(this._analysisController),this._analysisVisualization=t(this._analysisVisualization),this._analysisTool.destroy()}get result(){return this._analysisController.result}get interactive(){return super.interactive}set interactive(e){super.interactive=e}get visible(){return super.visible}set visible(e){super.visible=e}get effectiveTargetElevation(){const{targetElevation:e}=this.analysis.cutFillOptions;if(null!=e)return e;const t=this.elevationAlignedGeometry?.extent;return t&&t.zmin&&t.zmax?(t.zmax+t.zmin)/2:null}get unit(){return this.analysis.unit??o(this.view)}get updating(){return null!=this._analysisController&&this._analysisController.updating||this._analysisTool.updating}place(e){return this._analysisTool.place(e)}get test(){}};e([s({readOnly:!0})],u.prototype,"type",void 0),e([s({constructOnly:!0,nonNullable:!0})],u.prototype,"analysis",void 0),e([s({readOnly:!0})],u.prototype,"result",null),e([s()],u.prototype,"elevationAlignedGeometry",void 0),e([s({type:Number})],u.prototype,"effectiveTargetElevation",null),e([s()],u.prototype,"targetGeometry",void 0),e([s()],u.prototype,"unit",null),e([s()],u.prototype,"updating",null),u=e([i("esri.views.3d.analysis.VolumeMeasurementAnalysisView3D")],u);const p=u;export{p as default};
5
+ import{__decorate as e}from"tslib";import"../../../core/has.js";import{destroyMaybe as t}from"../../../core/maybe.js";import{verticalLengthUnitFromSpatialReference as i,convertUnit as s}from"../../../core/unitUtils.js";import{property as l}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/Logger.js";import"../../../core/RandomLCG.js";import{subclass as o}from"../../../core/accessorSupport/decorators/subclass.js";import{getDefaultUnitForView as r}from"../../../support/getDefaultUnitForView.js";import{AnalysisView3D as a}from"./AnalysisView3D.js";import{VolumeMeasurementCutFillController as n}from"./VolumeMeasurement/VolumeMeasurementCutFillController.js";import{VolumeMeasurementCutFillVisualization as u}from"./VolumeMeasurement/VolumeMeasurementCutFillVisualization.js";import p from"./VolumeMeasurement/VolumeMeasurementTool.js";let m=class extends a{constructor(e){super(e),this.type="volume-measurement-view-3d",this.analysis=null,this.elevationAlignedGeometry=null,this.targetGeometry=null}initialize(){const{analysis:e,view:t}=this;this._analysisController=new n({view:t,analysis:e,analysisViewData:this}),this._analysisTool=new p({analysis:e,view:t,analysisViewData:this}),this._analysisVisualization=new u({view:t,analysisViewData:this})}destroy(){this._analysisController=t(this._analysisController),this._analysisVisualization=t(this._analysisVisualization),this._analysisTool.destroy()}get result(){return this._analysisController?.result}get interactive(){return super.interactive}set interactive(e){super.interactive=e}get visible(){return super.visible}set visible(e){super.visible=e}get effectiveTargetElevation(){const{cutFillOptions:e,inputUnits:t}=this.analysis,{targetElevation:l}=e,o=t?.elevation??"meters",r=i(this.view.spatialReference);if(null!=l&&null!=r)return s(l,o,r);const a=this.elevationAlignedGeometry?.extent;return null==a?.zmin||null==a?.zmax?null:(a.zmax+a.zmin)/2}get effectiveDisplayUnits(){const{displayUnits:e}=this.analysis,t=r(this.view);return{elevation:e.elevation??t,volume:e.volume??t}}get updating(){return null!=this._analysisController&&this._analysisController.updating||this._analysisTool.updating}place(e){return this._analysisTool.place(e)}get test(){}};e([l({readOnly:!0})],m.prototype,"type",void 0),e([l({constructOnly:!0,nonNullable:!0})],m.prototype,"analysis",void 0),e([l({readOnly:!0})],m.prototype,"result",null),e([l()],m.prototype,"elevationAlignedGeometry",void 0),e([l({type:Number})],m.prototype,"effectiveTargetElevation",null),e([l()],m.prototype,"targetGeometry",void 0),e([l()],m.prototype,"effectiveDisplayUnits",null),e([l()],m.prototype,"updating",null),m=e([o("esri.views.3d.analysis.VolumeMeasurementAnalysisView3D")],m);const y=m;export{y 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.34/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../../../core/Error.js";import t from"../../../../core/Logger.js";import{getOrCreateMapValue as r}from"../../../../core/MapUtils.js";import{getKey as o}from"../../../../core/object.js";import{allSettledValues as n}from"../../../../core/promiseUtils.js";import{isDataProtocol as s,dataComponents as a,dataToArrayBuffer as i,makeAbsolute as u}from"../../../../core/urlUtils.js";import{Version as f}from"../../../../core/Version.js";import{fromXRotation as l,multiply as c,translate as d,rotate as p,scale as m}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{create as h,clone as w}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{getAxisAngle as b}from"../../../../core/libs/gl-matrix-2/math/quat.js";import{create as T}from"../../../../core/libs/gl-matrix-2/factories/quatf64.js";import{BufferViewVec2f as y,BufferViewVec2u32 as g,BufferViewVec2u16 as x,BufferViewVec2i16 as _,BufferViewVec2u8 as O,BufferViewVec2i8 as N,BufferViewUint32 as S,BufferViewUint16 as C,BufferViewUint8 as A,BufferViewVec3f as E,BufferViewVec4f as L,BufferViewVec4u8 as R,BufferViewVec4u16 as v,BufferViewVec3u8 as I,BufferViewVec3u16 as U}from"../../../../geometry/support/buffer/BufferView.js";import{m as B}from"../../../../chunks/scalar.js";import"../../../../core/has.js";import{BinaryStreamReader as D}from"./BinaryStreamReader.js";import{material as j,textureSampler as M}from"./fillDefaults.js";import{splitURI as G}from"./pathUtils.js";import{jsonFromBinaryData as F,EncodedMeshTexture as H,imageFromBinaryData as P,isEncodedMeshTexture as V}from"./resourceUtils.js";import{DataType as K}from"../../../webgl/enums.js";const k={MAGIC:1179937895,CHUNK_TYPE_JSON:1313821514,CHUNK_TYPE_BIN:5130562};class Y{constructor(t,r,o,n){if(this._context=t,this.uri=r,this.json=o,this._glbBuffer=n,this._bufferLoaders=new Map,this._textureLoaders=new Map,this._textureCache=new Map,this._materialCache=new Map,this._nodeParentMap=new Map,this._nodeTransformCache=new Map,this._supportedExtensions=["KHR_texture_basisu","KHR_texture_transform"],this._baseUri=G(this.uri).dirPart,this._checkVersionSupported(),this._checkRequiredExtensionsSupported(),null==o.scenes)throw new e("gltf-loader-unsupported-feature","Scenes must be defined.");if(null==o.meshes)throw new e("gltf-loader-unsupported-feature","Meshes must be defined");if(null==o.nodes)throw new e("gltf-loader-unsupported-feature","Nodes must be defined.");this._computeNodeParents()}static async load(t,r,o){if(s(r)){const e=a(r);if(e&&"model/gltf-binary"!==e.mediaType)try{const o=JSON.parse(e.isBase64?atob(e.data):e.data);return new Y(t,r,o)}catch{}const o=i(r);if(Y._isGLBData(o))return this._fromGLBData(t,r,o)}if(ee.test(r)||"gltf"===o?.expectedType){const e=await t.loadJSON(r,o);return new Y(t,r,e)}const n=await t.loadBinary(r,o);if(Y._isGLBData(n))return this._fromGLBData(t,r,n);if(te.test(r)||"glb"===o?.expectedType)throw new e("gltf-loader-invalid-glb","This is not a valid glb file.");const u=await t.loadJSON(r,o);return new Y(t,r,u)}static _isGLBData(e){if(null==e)return!1;const t=new D(e);return t.remainingBytes()>=4&&t.readUint32()===k.MAGIC}static async _fromGLBData(e,t,r){const o=await Y._parseGLBData(r);return new Y(e,t,o.json,o.binaryData)}static async _parseGLBData(r){const o=new D(r);if(o.remainingBytes()<12)throw new e("gltf-loader-error","glb binary data is insufficiently large.");const n=o.readUint32(),s=o.readUint32(),a=o.readUint32();if(n!==k.MAGIC)throw new e("gltf-loader-error","Magic first 4 bytes do not fit to expected glb value.");if(r.byteLength<a)throw new e("gltf-loader-error","glb binary data is smaller than header specifies.");if(2!==s)throw new e("gltf-loader-unsupported-feature","An unsupported glb container version was detected. Only version 2 is supported.");let i,u,f=0;for(;o.remainingBytes()>=8;){const r=o.readUint32(),n=o.readUint32();if(0===f){if(n!==k.CHUNK_TYPE_JSON)throw new e("gltf-loader-error","First glb chunk must be JSON.");if(r<0)throw new e("gltf-loader-error","No JSON data found.");i=await F(o.readUint8Array(r))}else if(1===f){if(n!==k.CHUNK_TYPE_BIN)throw new e("gltf-loader-unsupported-feature","Second glb chunk expected to be BIN.");u=o.readUint8Array(r)}else t.getLogger("esri.views.3d.glTF").warn("[Unsupported Feature] More than 2 glb chunks detected. Skipping.");f+=1}if(!i)throw new e("gltf-loader-error","No glb JSON chunk detected.");return{json:i,binaryData:u}}async getBuffer(t,r){const o=this.json.buffers[t];if(null==o.uri){if(null==this._glbBuffer)throw new e("gltf-loader-error","glb buffer not present");return this._glbBuffer}const n=await this._getBufferLoader(t,r);if(n.byteLength!==o.byteLength)throw new e("gltf-loader-error","Buffer byte lengths should match.");return n}async _getBufferLoader(e,t){const r=this._bufferLoaders.get(e);if(r)return r;const o=this.json.buffers[e].uri,n=this._context.loadBinary(this._resolveUri(o),t).then(e=>new Uint8Array(e));return this._bufferLoaders.set(e,n),n}async getAccessor(t,r){if(!this.json.accessors)throw new e("gltf-loader-unsupported-feature","Accessors missing.");const o=this.json.accessors[t];if(null==o?.bufferView)throw new e("gltf-loader-unsupported-feature","Some accessor does not specify a bufferView.");if(o.type in["MAT2","MAT3","MAT4"])throw new e("gltf-loader-unsupported-feature",`AttributeType ${o.type} is not supported`);const n=this.json.bufferViews[o.bufferView],s=await this.getBuffer(n.buffer,r),a=X[o.type],i=$[o.componentType],u=a*i,f=n.byteStride||u;return{raw:s.buffer,byteStride:f,byteOffset:s.byteOffset+(n.byteOffset||0)+(o.byteOffset||0),entryCount:o.count,isDenselyPacked:f===u,componentCount:a,componentByteSize:i,componentType:o.componentType,min:o.min,max:o.max,normalized:!!o.normalized}}async getIndexData(e,t){if(null==e.indices)return;const r=await this.getAccessor(e.indices,t);if(r.isDenselyPacked)switch(r.componentType){case K.UNSIGNED_BYTE:return new Uint8Array(r.raw,r.byteOffset,r.entryCount);case K.UNSIGNED_SHORT:return new Uint16Array(r.raw,r.byteOffset,r.entryCount);case K.UNSIGNED_INT:return new Uint32Array(r.raw,r.byteOffset,r.entryCount)}else switch(r.componentType){case K.UNSIGNED_BYTE:return B(Q(A,r));case K.UNSIGNED_SHORT:return B(Q(C,r));case K.UNSIGNED_INT:return B(Q(S,r))}}async getPositionData(t,r){if(null==t.attributes.POSITION)throw new e("gltf-loader-unsupported-feature","No POSITION vertex data found.");const n=await this.getAccessor(t.attributes.POSITION,r);if(n.componentType!==K.FLOAT)throw new e("gltf-loader-unsupported-feature","Expected type FLOAT for POSITION vertex attribute, but found "+o(K,n.componentType));if(3!==n.componentCount)throw new e("gltf-loader-unsupported-feature","POSITION vertex attribute must have 3 components, but found "+n.componentCount.toFixed());return Q(E,n)}async getNormalData(t,r){if(null==t.attributes.NORMAL)throw new e("gltf-loader-error","No NORMAL vertex data found.");const n=await this.getAccessor(t.attributes.NORMAL,r);if(n.componentType!==K.FLOAT)throw new e("gltf-loader-unsupported-feature","Expected type FLOAT for NORMAL vertex attribute, but found "+o(K,n.componentType));if(3!==n.componentCount)throw new e("gltf-loader-unsupported-feature","NORMAL vertex attribute must have 3 components, but found "+n.componentCount.toFixed());return Q(E,n)}async getTangentData(t,r){if(null==t.attributes.TANGENT)throw new e("gltf-loader-error","No TANGENT vertex data found.");const n=await this.getAccessor(t.attributes.TANGENT,r);if(n.componentType!==K.FLOAT)throw new e("gltf-loader-unsupported-feature","Expected type FLOAT for TANGENT vertex attribute, but found "+o(K,n.componentType));if(4!==n.componentCount)throw new e("gltf-loader-unsupported-feature","TANGENT vertex attribute must have 4 components, but found "+n.componentCount.toFixed());return Q(L,n)}async getTextureCoordinates(t,r){if(null==t.attributes.TEXCOORD_0)throw new e("gltf-loader-error","No TEXCOORD_0 vertex data found.");const o=await this.getAccessor(t.attributes.TEXCOORD_0,r);if(2!==o.componentCount)throw new e("gltf-loader-unsupported-feature","TEXCOORD_0 vertex attribute must have 2 components, but found "+o.componentCount.toFixed());if(o.componentType===K.FLOAT)return Q(y,o);if(!o.normalized)throw new e("gltf-loader-unsupported-feature","Integer component types are only supported for a normalized accessor for TEXCOORD_0.");return W(o)}async getVertexColors(t,r){if(null==t.attributes.COLOR_0)throw new e("gltf-loader-error","No COLOR_0 vertex data found.");const n=await this.getAccessor(t.attributes.COLOR_0,r);if(4!==n.componentCount&&3!==n.componentCount)throw new e("gltf-loader-unsupported-feature","COLOR_0 attribute must have 3 or 4 components, but found "+n.componentCount.toFixed());if(4===n.componentCount){if(n.componentType===K.FLOAT)return Q(L,n);if(n.componentType===K.UNSIGNED_BYTE)return Q(R,n);if(n.componentType===K.UNSIGNED_SHORT)return Q(v,n)}else if(3===n.componentCount){if(n.componentType===K.FLOAT)return Q(E,n);if(n.componentType===K.UNSIGNED_BYTE)return Q(I,n);if(n.componentType===K.UNSIGNED_SHORT)return Q(U,n)}throw new e("gltf-loader-unsupported-feature","Unsupported component type for COLOR_0 attribute: "+o(K,n.componentType))}hasPositions(e){return void 0!==e.attributes.POSITION}hasNormals(e){return void 0!==e.attributes.NORMAL}hasVertexColors(e){return void 0!==e.attributes.COLOR_0}hasTextureCoordinates(e){return void 0!==e.attributes.TEXCOORD_0}hasTangents(e){return void 0!==e.attributes.TANGENT}async getMaterial(e,t,r){let o=e.material?this._materialCache.get(e.material):void 0;if(!o){const n=null!=e.material?j(this.json.materials[e.material]):j(),s=n.pbrMetallicRoughness,a=this.hasVertexColors(e),i=this.getTexture(s.baseColorTexture,t),u=this.getTexture(n.normalTexture,t),f=r?this.getTexture(n.occlusionTexture,t):void 0,l=r?this.getTexture(n.emissiveTexture,t):void 0,c=r?this.getTexture(s.metallicRoughnessTexture,t):void 0,d=null!=e.material?e.material:-1;o={alphaMode:n.alphaMode,alphaCutoff:n.alphaCutoff,color:s.baseColorFactor,doubleSided:!!n.doubleSided,colorTexture:await i,normalTexture:await u,name:n.name,id:d,occlusionTexture:await f,emissiveTexture:await l,emissiveFactor:n.emissiveFactor,metallicFactor:s.metallicFactor,roughnessFactor:s.roughnessFactor,metallicRoughnessTexture:await c,hasVertexColors:a,ESRI_externalColorMixMode:n.extras.ESRI_externalColorMixMode,colorTextureTransform:s?.baseColorTexture?.extensions?.KHR_texture_transform,normalTextureTransform:n.normalTexture?.extensions?.KHR_texture_transform,occlusionTextureTransform:n.occlusionTexture?.extensions?.KHR_texture_transform,emissiveTextureTransform:n.emissiveTexture?.extensions?.KHR_texture_transform,metallicRoughnessTextureTransform:s?.metallicRoughnessTexture?.extensions?.KHR_texture_transform,receiveAmbientOcclusion:n.extras.ESRI_receiveAmbientOcclusion,receiveShadows:n.extras.ESRI_receiveShadows}}return o}async getTexture(t,o){if(!t)return;if(0!==(t.texCoord||0))throw new e("gltf-loader-unsupported-feature","Only TEXCOORD with index 0 is supported.");const n=t.index,s=this.json.textures[n],a=M(null!=s.sampler?this.json.samplers[s.sampler]:{}),i=Z(s),u=this.json.images[i],f=await this._loadTextureImageData(n,s,o);return r(this._textureCache,n,()=>{const t=e=>33071===e||33648===e||10497===e,r=t=>{throw new e("gltf-loader-error",`Unexpected TextureSampler WrapMode: ${t}`)};return{data:f,wrapS:t(a.wrapS)?a.wrapS:r(a.wrapS),wrapT:t(a.wrapT)?a.wrapT:r(a.wrapT),minFilter:a.minFilter,name:u.name,id:n}})}getNodeTransform(e){if(void 0===e)return q;let t=this._nodeTransformCache.get(e);if(!t){const r=this.getNodeTransform(this._getNodeParent(e)),o=this.json.nodes[e];o.matrix?t=c(h(),r,o.matrix):o.translation||o.rotation||o.scale?(t=w(r),o.translation&&d(t,t,o.translation),o.rotation&&(z[3]=b(z,o.rotation),p(t,t,z[3],z)),o.scale&&m(t,t,o.scale)):t=w(r),this._nodeTransformCache.set(e,t)}return t}_resolveUri(e){return u(e,this._baseUri)}_getNodeParent(e){return this._nodeParentMap.get(e)}_checkVersionSupported(){const e=f.parse(this.json.asset.version,"glTF");J.validate(e)}_checkRequiredExtensionsSupported(){const t=this.json;if(t.extensionsRequired){if(!t.extensionsRequired.every(e=>this._supportedExtensions.includes(e)))throw new e("gltf-loader-unsupported-feature","gltf loader was not able to load unsupported feature. Required extensions: "+t.extensionsRequired.join(", "))}}_computeNodeParents(){this.json.nodes.forEach((e,t)=>{e.children&&e.children.forEach(e=>{this._nodeParentMap.set(e,t)})})}async _loadTextureImageData(e,t,r){const o=this._textureLoaders.get(e);if(o)return o;const n=this._createTextureLoader(t,r);return this._textureLoaders.set(e,n),n}async _createTextureLoader(t,r){const o=Z(t),n=this.json.images[o];if(n.uri){if(n.uri.endsWith(".ktx2")){const e=await this._context.loadBinary(this._resolveUri(n.uri),r);return new H(new Uint8Array(e))}return this._context.loadImage(this._resolveUri(n.uri),r)}if(null==n.bufferView)throw new e("gltf-loader-unsupported-feature","Image bufferView must be defined.");if(null==n.mimeType)throw new e("gltf-loader-unsupported-feature","Image mimeType must be defined.");const s=this.json.bufferViews[n.bufferView],a=await this.getBuffer(s.buffer,r);if(null!=s.byteStride)throw new e("gltf-loader-unsupported-feature","byteStride not supported for image buffer");const i=a.byteOffset+(s.byteOffset||0);return P(new Uint8Array(a.buffer,i,s.byteLength),n.mimeType)}async getLoadedBuffersSize(){if(this._glbBuffer)return this._glbBuffer.byteLength;const e=await n(Array.from(this._bufferLoaders.values())),t=await n(Array.from(this._textureLoaders.values()));return e.reduce((e,t)=>e+(t?.byteLength??0),0)+t.reduce((e,t)=>e+(t?V(t)?t.data.byteLength:t.width*t.height*4:0),0)}}const q=l(h(),Math.PI/2),J=new f(2,0,"glTF"),z=T(),X={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},$={[K.BYTE]:1,[K.UNSIGNED_BYTE]:1,[K.SHORT]:2,[K.UNSIGNED_SHORT]:2,[K.HALF_FLOAT]:2,[K.FLOAT]:4,[K.INT]:4,[K.UNSIGNED_INT]:4};function W(e){switch(e.componentType){case K.BYTE:return new N(e.raw,e.byteOffset,e.byteStride,e.byteOffset+e.byteStride*e.entryCount);case K.UNSIGNED_BYTE:return new O(e.raw,e.byteOffset,e.byteStride,e.byteOffset+e.byteStride*e.entryCount);case K.SHORT:return new _(e.raw,e.byteOffset,e.byteStride,e.byteOffset+e.byteStride*e.entryCount);case K.UNSIGNED_SHORT:return new x(e.raw,e.byteOffset,e.byteStride,e.byteOffset+e.byteStride*e.entryCount);case K.UNSIGNED_INT:return new g(e.raw,e.byteOffset,e.byteStride,e.byteOffset+e.byteStride*e.entryCount);case K.FLOAT:return new y(e.raw,e.byteOffset,e.byteStride,e.byteOffset+e.byteStride*e.entryCount)}}function Q(e,t){return new e(t.raw,t.byteOffset,t.byteStride,t.byteOffset+t.byteStride*(t.entryCount-1)+t.componentByteSize*t.componentCount)}function Z(t){if(null!=t.extensions?.KHR_texture_basisu)return t.extensions.KHR_texture_basisu.source;if(null!==t.source)return t.source;throw new e("gltf-loader-unsupported-feature","Source is expected to be defined for a texture. It can also be omitted in favour of an KHR_texture_basisu extension tag.")}const ee=/\.gltf$/i,te=/\.glb$/i;export{Y as GLTFResource,q as transformGltfToEngine};
5
+ import e from"../../../../core/Error.js";import t from"../../../../core/Logger.js";import{getOrCreateMapValue as r}from"../../../../core/MapUtils.js";import{getKey as o}from"../../../../core/object.js";import{allSettledValues as n}from"../../../../core/promiseUtils.js";import{isDataProtocol as s,dataComponents as a,dataToArrayBuffer as i,makeAbsolute as u}from"../../../../core/urlUtils.js";import{Version as f}from"../../../../core/Version.js";import{fromXRotation as c,multiply as d,translate as l,rotate as p,scale as m}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{create as h,clone as b}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{getAxisAngle as w}from"../../../../core/libs/gl-matrix-2/math/quat.js";import{create as y}from"../../../../core/libs/gl-matrix-2/factories/quatf64.js";import{BufferViewVec2f as g,BufferViewVec2u32 as T,BufferViewVec2u16 as _,BufferViewVec2i16 as x,BufferViewVec2u8 as O,BufferViewVec2i8 as N,BufferViewUint32 as S,BufferViewUint16 as C,BufferViewUint8 as A,BufferViewVec3f as L,BufferViewVec4f as E,BufferViewVec4u8 as R,BufferViewVec4u16 as v,BufferViewVec3u8 as I,BufferViewVec3u16 as D}from"../../../../geometry/support/buffer/BufferView.js";import{m as B}from"../../../../chunks/scalar.js";import"../../../../core/has.js";import{getDracoMeshDecoder as U}from"../../../../libs/dracoMeshDecoder/dracoMeshDecoder.js";import{BinaryStreamReader as M}from"./BinaryStreamReader.js";import{material as j,textureSampler as G}from"./fillDefaults.js";import{splitURI as F}from"./pathUtils.js";import{jsonFromBinaryData as H,EncodedMeshTexture as P,imageFromBinaryData as V,isEncodedMeshTexture as z}from"./resourceUtils.js";import{DataType as K}from"../../../webgl/enums.js";const k={MAGIC:1179937895,CHUNK_TYPE_JSON:1313821514,CHUNK_TYPE_BIN:5130562};class Y{constructor(t,r,o,n){if(this._context=t,this.uri=r,this.json=o,this._glbBuffer=n,this._bufferLoaders=new Map,this._textureLoaders=new Map,this._dracoBuffersSize=0,this._textureCache=new Map,this._materialCache=new Map,this._nodeParentMap=new Map,this._nodeTransformCache=new Map,this._supportedExtensions=["KHR_texture_basisu","KHR_texture_transform","KHR_draco_mesh_compression"],this._baseUri=F(this.uri).dirPart,this._checkVersionSupported(),this._checkRequiredExtensionsSupported(),null==o.scenes)throw new e("gltf-loader-unsupported-feature","Scenes must be defined.");if(null==o.meshes)throw new e("gltf-loader-unsupported-feature","Meshes must be defined");if(null==o.nodes)throw new e("gltf-loader-unsupported-feature","Nodes must be defined.");this._computeNodeParents()}static async load(t,r,o){if(s(r)){const e=a(r);if(e&&"model/gltf-binary"!==e.mediaType)try{const o=JSON.parse(e.isBase64?atob(e.data):e.data);return new Y(t,r,o)}catch{}const o=i(r);if(Y._isGLBData(o))return this._fromGLBData(t,r,o)}if(te.test(r)||"gltf"===o?.expectedType){const e=await t.loadJSON(r,o);return new Y(t,r,e)}const n=await t.loadBinary(r,o);if(Y._isGLBData(n))return this._fromGLBData(t,r,n);if(re.test(r)||"glb"===o?.expectedType)throw new e("gltf-loader-invalid-glb","This is not a valid glb file.");const u=await t.loadJSON(r,o);return new Y(t,r,u)}static _isGLBData(e){if(null==e)return!1;const t=new M(e);return t.remainingBytes()>=4&&t.readUint32()===k.MAGIC}static async _fromGLBData(e,t,r){const o=await Y._parseGLBData(r);return new Y(e,t,o.json,o.binaryData)}static async _parseGLBData(r){const o=new M(r);if(o.remainingBytes()<12)throw new e("gltf-loader-error","glb binary data is insufficiently large.");const n=o.readUint32(),s=o.readUint32(),a=o.readUint32();if(n!==k.MAGIC)throw new e("gltf-loader-error","Magic first 4 bytes do not fit to expected glb value.");if(r.byteLength<a)throw new e("gltf-loader-error","glb binary data is smaller than header specifies.");if(2!==s)throw new e("gltf-loader-unsupported-feature","An unsupported glb container version was detected. Only version 2 is supported.");let i,u,f=0;for(;o.remainingBytes()>=8;){const r=o.readUint32(),n=o.readUint32();if(0===f){if(n!==k.CHUNK_TYPE_JSON)throw new e("gltf-loader-error","First glb chunk must be JSON.");if(r<0)throw new e("gltf-loader-error","No JSON data found.");i=await H(o.readUint8Array(r))}else if(1===f){if(n!==k.CHUNK_TYPE_BIN)throw new e("gltf-loader-unsupported-feature","Second glb chunk expected to be BIN.");u=o.readUint8Array(r)}else t.getLogger("esri.views.3d.glTF").warn("[Unsupported Feature] More than 2 glb chunks detected. Skipping.");f+=1}if(!i)throw new e("gltf-loader-error","No glb JSON chunk detected.");return{json:i,binaryData:u}}async getBuffer(t,r){const o=this.json.buffers[t];if(null==o.uri){if(null==this._glbBuffer)throw new e("gltf-loader-error","glb buffer not present");return this._glbBuffer}const n=await this._getBufferLoader(t,r);if(n.byteLength!==o.byteLength)throw new e("gltf-loader-error","Buffer byte lengths should match.");return n}async _getBufferLoader(e,t){const r=this._bufferLoaders.get(e);if(r)return r;const o=this.json.buffers[e].uri,n=this._context.loadBinary(this._resolveUri(o),t).then(e=>new Uint8Array(e));return this._bufferLoaders.set(e,n),n}_validateAccessor(t){if(!this.json.accessors)throw new e("gltf-loader-unsupported-feature","Accessors missing.");const r=this.json.accessors[t];if(r.type in["MAT2","MAT3","MAT4"])throw new e("gltf-loader-unsupported-feature",`AttributeType ${r.type} is not supported`);return r}_getComponentInfo(e){const t=$[e.type],r=W[e.componentType];return{componentCount:t,componentByteSize:r,denseByteStride:t*r}}getDracoAccessor(e,t,r=!1){const o=this._validateAccessor(e),{componentCount:n,componentByteSize:s,denseByteStride:a}=this._getComponentInfo(o),i=t.offsets.get(e);return{raw:t.buffer.buffer,byteStride:a,byteOffset:t.buffer.byteOffset+(i||0),entryCount:o.count,isDenselyPacked:!0,componentCount:n,componentByteSize:s,componentType:r?t.indexComponentType:o.componentType,min:o.min,max:o.max,normalized:!!o.normalized}}async getAccessor(t,r){const o=this._validateAccessor(t);if(null==o?.bufferView)throw new e("gltf-loader-unsupported-feature","Some accessor does not specify a bufferView.");const{componentCount:n,componentByteSize:s,denseByteStride:a}=this._getComponentInfo(o),i=this.json.bufferViews[o.bufferView],u=await this.getBuffer(i.buffer,r),f=i.byteStride||a;return{raw:u.buffer,byteStride:f,byteOffset:u.byteOffset+(i.byteOffset||0)+(o.byteOffset||0),entryCount:o.count,isDenselyPacked:f===a,componentCount:n,componentByteSize:s,componentType:o.componentType,min:o.min,max:o.max,normalized:!!o.normalized}}async getIndexData(e,t,r){if(null==e.indices)return;const o=e.indices,n=r?this.getDracoAccessor(o,r,!0):await this.getAccessor(o,t);if(n.isDenselyPacked)switch(n.componentType){case K.UNSIGNED_BYTE:return new Uint8Array(n.raw,n.byteOffset,n.entryCount);case K.UNSIGNED_SHORT:return new Uint16Array(n.raw,n.byteOffset,n.entryCount);case K.UNSIGNED_INT:return new Uint32Array(n.raw,n.byteOffset,n.entryCount)}else switch(n.componentType){case K.UNSIGNED_BYTE:return B(Z(A,n));case K.UNSIGNED_SHORT:return B(Z(C,n));case K.UNSIGNED_INT:return B(Z(S,n))}}async getPositionData(t,r,n){if(null==t.attributes.POSITION)throw new e("gltf-loader-unsupported-feature","No POSITION vertex data found.");const s=t.attributes.POSITION,a=n?this.getDracoAccessor(s,n):await this.getAccessor(s,r);if(a.componentType!==K.FLOAT)throw new e("gltf-loader-unsupported-feature","Expected type FLOAT for POSITION vertex attribute, but found "+o(K,a.componentType));if(3!==a.componentCount)throw new e("gltf-loader-unsupported-feature","POSITION vertex attribute must have 3 components, but found "+a.componentCount.toFixed());return Z(L,a)}async getNormalData(t,r,n){if(null==t.attributes.NORMAL)throw new e("gltf-loader-error","No NORMAL vertex data found.");const s=t.attributes.NORMAL,a=n?this.getDracoAccessor(s,n):await this.getAccessor(s,r);if(a.componentType!==K.FLOAT)throw new e("gltf-loader-unsupported-feature","Expected type FLOAT for NORMAL vertex attribute, but found "+o(K,a.componentType));if(3!==a.componentCount)throw new e("gltf-loader-unsupported-feature","NORMAL vertex attribute must have 3 components, but found "+a.componentCount.toFixed());return Z(L,a)}async getTangentData(t,r,n){if(null==t.attributes.TANGENT)throw new e("gltf-loader-error","No TANGENT vertex data found.");const s=t.attributes.TANGENT,a=n?this.getDracoAccessor(s,n):await this.getAccessor(s,r);if(a.componentType!==K.FLOAT)throw new e("gltf-loader-unsupported-feature","Expected type FLOAT for TANGENT vertex attribute, but found "+o(K,a.componentType));if(4!==a.componentCount)throw new e("gltf-loader-unsupported-feature","TANGENT vertex attribute must have 4 components, but found "+a.componentCount.toFixed());return Z(E,a)}async getTextureCoordinates(t,r,o){if(null==t.attributes.TEXCOORD_0)throw new e("gltf-loader-error","No TEXCOORD_0 vertex data found.");const n=t.attributes.TEXCOORD_0,s=o?this.getDracoAccessor(n,o):await this.getAccessor(n,r);if(2!==s.componentCount)throw new e("gltf-loader-unsupported-feature","TEXCOORD_0 vertex attribute must have 2 components, but found "+s.componentCount.toFixed());if(s.componentType===K.FLOAT)return Z(g,s);if(!s.normalized)throw new e("gltf-loader-unsupported-feature","Integer component types are only supported for a normalized accessor for TEXCOORD_0.");return Q(s)}async getVertexColors(t,r,n){if(null==t.attributes.COLOR_0)throw new e("gltf-loader-error","No COLOR_0 vertex data found.");const s=t.attributes.COLOR_0,a=n?this.getDracoAccessor(s,n):await this.getAccessor(s,r);if(4!==a.componentCount&&3!==a.componentCount)throw new e("gltf-loader-unsupported-feature","COLOR_0 attribute must have 3 or 4 components, but found "+a.componentCount.toFixed());if(4===a.componentCount){if(a.componentType===K.FLOAT)return Z(E,a);if(a.componentType===K.UNSIGNED_BYTE)return Z(R,a);if(a.componentType===K.UNSIGNED_SHORT)return Z(v,a)}else if(3===a.componentCount){if(a.componentType===K.FLOAT)return Z(L,a);if(a.componentType===K.UNSIGNED_BYTE)return Z(I,a);if(a.componentType===K.UNSIGNED_SHORT)return Z(D,a)}throw new e("gltf-loader-unsupported-feature","Unsupported component type for COLOR_0 attribute: "+o(K,a.componentType))}hasPositions(e){return void 0!==e.attributes.POSITION}hasNormals(e){return void 0!==e.attributes.NORMAL}hasVertexColors(e){return void 0!==e.attributes.COLOR_0}hasTextureCoordinates(e){return void 0!==e.attributes.TEXCOORD_0}hasTangents(e){return void 0!==e.attributes.TANGENT}async getMaterial(e,t,r){let o=e.material?this._materialCache.get(e.material):void 0;if(!o){const n=null!=e.material?j(this.json.materials[e.material]):j(),s=n.pbrMetallicRoughness,a=this.hasVertexColors(e),i=this.getTexture(s.baseColorTexture,t),u=this.getTexture(n.normalTexture,t),f=r?this.getTexture(n.occlusionTexture,t):void 0,c=r?this.getTexture(n.emissiveTexture,t):void 0,d=r?this.getTexture(s.metallicRoughnessTexture,t):void 0,l=null!=e.material?e.material:-1;o={alphaMode:n.alphaMode,alphaCutoff:n.alphaCutoff,color:s.baseColorFactor,doubleSided:!!n.doubleSided,colorTexture:await i,normalTexture:await u,name:n.name,id:l,occlusionTexture:await f,emissiveTexture:await c,emissiveFactor:n.emissiveFactor,metallicFactor:s.metallicFactor,roughnessFactor:s.roughnessFactor,metallicRoughnessTexture:await d,hasVertexColors:a,ESRI_externalColorMixMode:n.extras.ESRI_externalColorMixMode,colorTextureTransform:s?.baseColorTexture?.extensions?.KHR_texture_transform,normalTextureTransform:n.normalTexture?.extensions?.KHR_texture_transform,occlusionTextureTransform:n.occlusionTexture?.extensions?.KHR_texture_transform,emissiveTextureTransform:n.emissiveTexture?.extensions?.KHR_texture_transform,metallicRoughnessTextureTransform:s?.metallicRoughnessTexture?.extensions?.KHR_texture_transform,receiveAmbientOcclusion:n.extras.ESRI_receiveAmbientOcclusion,receiveShadows:n.extras.ESRI_receiveShadows}}return o}async decode(t,r){const o=t.extensions?.KHR_draco_mesh_compression;if(!o)return;if(null==t.indices)throw new e("gltf-loader-error","Found Draco compressed primitive without indices.");const n=this.json.bufferViews[o.bufferView],s=await this.getBuffer(n.buffer,r),a=(await U()).decode(new Uint8Array(s.buffer,n.byteOffset,n.byteLength));this._bufferLoaders.delete(n.buffer);const i=new Map([[t.indices,a.indexOffset],[t.attributes.POSITION,a.positionOffset]]);return t.attributes.TEXCOORD_0&&i.set(t.attributes.TEXCOORD_0,a.uvOffset),t.attributes.NORMAL&&i.set(t.attributes.NORMAL,a.normalOffset),t.attributes.COLOR_0&&i.set(t.attributes.COLOR_0,a.colorOffset),t.attributes.TANGENT&&i.set(t.attributes.TANGENT,a.tangentOffset),this._dracoBuffersSize+=a.buffer.byteLength,{buffer:a.buffer,indexComponentType:a.indexComponentType,offsets:i}}async getTexture(t,o){if(!t)return;if(0!==(t.texCoord||0))throw new e("gltf-loader-unsupported-feature","Only TEXCOORD with index 0 is supported.");const n=t.index,s=this.json.textures[n],a=G(null!=s.sampler?this.json.samplers[s.sampler]:{}),i=ee(s),u=this.json.images[i],f=await this._loadTextureImageData(n,s,o);return r(this._textureCache,n,()=>{const t=e=>33071===e||33648===e||10497===e,r=t=>{throw new e("gltf-loader-error",`Unexpected TextureSampler WrapMode: ${t}`)};return{data:f,wrapS:t(a.wrapS)?a.wrapS:r(a.wrapS),wrapT:t(a.wrapT)?a.wrapT:r(a.wrapT),minFilter:a.minFilter,name:u.name,id:n}})}getNodeTransform(e){if(void 0===e)return X;let t=this._nodeTransformCache.get(e);if(!t){const r=this.getNodeTransform(this._getNodeParent(e)),o=this.json.nodes[e];o.matrix?t=d(h(),r,o.matrix):o.translation||o.rotation||o.scale?(t=b(r),o.translation&&l(t,t,o.translation),o.rotation&&(J[3]=w(J,o.rotation),p(t,t,J[3],J)),o.scale&&m(t,t,o.scale)):t=b(r),this._nodeTransformCache.set(e,t)}return t}_resolveUri(e){return u(e,this._baseUri)}_getNodeParent(e){return this._nodeParentMap.get(e)}_checkVersionSupported(){const e=f.parse(this.json.asset.version,"glTF");q.validate(e)}_checkRequiredExtensionsSupported(){const t=this.json;if(t.extensionsRequired){if(!t.extensionsRequired.every(e=>this._supportedExtensions.includes(e)))throw new e("gltf-loader-unsupported-feature","gltf loader was not able to load unsupported feature. Required extensions: "+t.extensionsRequired.join(", "))}}_computeNodeParents(){this.json.nodes.forEach((e,t)=>{e.children&&e.children.forEach(e=>{this._nodeParentMap.set(e,t)})})}async _loadTextureImageData(e,t,r){const o=this._textureLoaders.get(e);if(o)return o;const n=this._createTextureLoader(t,r);return this._textureLoaders.set(e,n),n}async _createTextureLoader(t,r){const o=ee(t),n=this.json.images[o];if(n.uri){if(n.uri.endsWith(".ktx2")){const e=await this._context.loadBinary(this._resolveUri(n.uri),r);return new P(new Uint8Array(e))}return this._context.loadImage(this._resolveUri(n.uri),r)}if(null==n.bufferView)throw new e("gltf-loader-unsupported-feature","Image bufferView must be defined.");if(null==n.mimeType)throw new e("gltf-loader-unsupported-feature","Image mimeType must be defined.");const s=this.json.bufferViews[n.bufferView],a=await this.getBuffer(s.buffer,r);if(null!=s.byteStride)throw new e("gltf-loader-unsupported-feature","byteStride not supported for image buffer");const i=a.byteOffset+(s.byteOffset||0);return V(new Uint8Array(a.buffer,i,s.byteLength),n.mimeType)}async getLoadedBuffersSize(){if(this._glbBuffer)return this._glbBuffer.byteLength;const e=await n(Array.from(this._bufferLoaders.values())),t=await n(Array.from(this._textureLoaders.values()));return e.reduce((e,t)=>e+(t?.byteLength??0),0)+this._dracoBuffersSize+t.reduce((e,t)=>e+(t?z(t)?t.data.byteLength:t.width*t.height*4:0),0)}}const X=c(h(),Math.PI/2),q=new f(2,0,"glTF"),J=y(),$={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},W={[K.BYTE]:1,[K.UNSIGNED_BYTE]:1,[K.SHORT]:2,[K.UNSIGNED_SHORT]:2,[K.HALF_FLOAT]:2,[K.FLOAT]:4,[K.INT]:4,[K.UNSIGNED_INT]:4};function Q(e){switch(e.componentType){case K.BYTE:return new N(e.raw,e.byteOffset,e.byteStride,e.byteOffset+e.byteStride*e.entryCount);case K.UNSIGNED_BYTE:return new O(e.raw,e.byteOffset,e.byteStride,e.byteOffset+e.byteStride*e.entryCount);case K.SHORT:return new x(e.raw,e.byteOffset,e.byteStride,e.byteOffset+e.byteStride*e.entryCount);case K.UNSIGNED_SHORT:return new _(e.raw,e.byteOffset,e.byteStride,e.byteOffset+e.byteStride*e.entryCount);case K.UNSIGNED_INT:return new T(e.raw,e.byteOffset,e.byteStride,e.byteOffset+e.byteStride*e.entryCount);case K.FLOAT:return new g(e.raw,e.byteOffset,e.byteStride,e.byteOffset+e.byteStride*e.entryCount)}}function Z(e,t){return new e(t.raw,t.byteOffset,t.byteStride,t.byteOffset+t.byteStride*(t.entryCount-1)+t.componentByteSize*t.componentCount)}function ee(t){if(null!=t.extensions?.KHR_texture_basisu)return t.extensions.KHR_texture_basisu.source;if(null!==t.source)return t.source;throw new e("gltf-loader-unsupported-feature","Source is expected to be defined for a texture. It can also be omitted in favour of an KHR_texture_basisu extension tag.")}const te=/\.gltf$/i,re=/\.glb$/i;export{Y as GLTFResource,X as transformGltfToEngine};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../../core/Logger.js";import{getKey as o}from"../../../core/object.js";import{clone as t}from"../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{makeMaterialParameters as r,makeTextureSource as s}from"./LoaderResult.js";import{GLTFResource as a}from"./internal/Resource.js";import{PrimitiveType as i}from"../../webgl/enums.js";let n=0;async function l(r,s,l={},m=!0){const T=await a.load(r,s,l),p="gltf_"+n++,f={lods:[],materials:new Map,textures:new Map,meta:u(T)},x=!(!T.json.asset.extras||"symbolResource"!==T.json.asset.extras.ESRI_type),g=T.json.asset.extras?.ESRI_webstyleSymbol?.webstyle,h=new Map;await c(T,async(r,s,a,n)=>{const u=h.get(a)??0;h.set(a,u+1);const c=void 0!==r.mode?r.mode:i.TRIANGLES,x=c===i.TRIANGLES||c===i.TRIANGLE_STRIP||c===i.TRIANGLE_FAN?c:null;if(null==x)return void e.getLogger("esri.views.3d.glTF").warn("[Unsupported Feature] Unsupported primitive mode ("+o(i,c)+"). Skipping primitive.");if(!T.hasPositions(r))return void e.getLogger("esri.views.3d.glTF").warn("Skipping primitive without POSITION vertex attribute.");const g=T.getPositionData(r,l),w=T.getMaterial(r,l,m),v=T.hasNormals(r)?T.getNormalData(r,l):null,S=T.hasTangents(r)?T.getTangentData(r,l):null,R=T.hasTextureCoordinates(r)?T.getTextureCoordinates(r,l):null,_=T.hasVertexColors(r)?T.getVertexColors(r,l):null,F=T.getIndexData(r,l),y={name:n,transform:t(s),attributes:{position:await g,normal:v?await v:null,texCoord0:R?await R:null,color:_?await _:null,tangent:S?await S:null},indices:await F,primitiveType:x,material:d(f,await w,p)};let E=null;null!=f.meta?.ESRI_lod&&"screenSpaceRadius"===f.meta.ESRI_lod.metric&&(E=f.meta.ESRI_lod.thresholds[a]),f.lods[a]=f.lods[a]||{parts:[],name:n,lodThreshold:E},f.lods[a].parts[u]=y});for(const e of f.lods)e.parts=e.parts.filter(e=>!!e);const w=await T.getLoadedBuffersSize();return{model:f,meta:{isEsriSymbolResource:x,uri:T.uri,ESRI_webstyle:g},customMeta:{},usedMemory:w}}function u(e){const o=e.json;let t=null;return o.nodes.forEach(e=>{const o=e.extras;null!=o&&(o.ESRI_proxyEllipsoid||o.ESRI_lod)&&(t=o)}),t}async function c(o,t){const r=o.json,s=r.scenes[r.scene||0].nodes,a=s.length>1,i=[];for(const e of s){const o=r.nodes[e];if(i.push(n(e,0)),m(o)&&!a){o.extensions.MSFT_lod.ids.forEach((e,o)=>n(e,o+1))}}async function n(s,a){const l=r.nodes[s],u=o.getNodeTransform(s);if(null!=l.weights&&e.getLogger("esri.views.3d.glTF").warn("[Unsupported Feature] Morph targets are not supported."),null!=l.mesh){const e=r.meshes[l.mesh];for(const o of e.primitives)i.push(t(o,u,a,e.name))}for(const e of l.children||[])i.push(n(e,a))}await Promise.all(i)}function m(e){return e.extensions?.MSFT_lod&&Array.isArray(e.extensions.MSFT_lod.ids)}function d(e,o,t){const a=o=>{const r=`${t}_tex_${o&&o.id}${o?.name?"_"+o.name:""}`;if(o&&!e.textures.has(r)){const t=s(o.data,{wrap:{s:o.wrapS,t:o.wrapT},mipmap:T.has(o.minFilter),noUnpackFlip:!0});e.textures.set(r,t)}return r},i=`${t}_mat_${o.id}_${o.name}`;if(!e.materials.has(i)){const t=r({color:[o.color[0],o.color[1],o.color[2]],opacity:o.color[3],alphaMode:o.alphaMode,alphaCutoff:o.alphaCutoff,doubleSided:o.doubleSided,colorMixMode:o.ESRI_externalColorMixMode,colorTexture:o.colorTexture?a(o.colorTexture):void 0,normalTexture:o.normalTexture?a(o.normalTexture):void 0,occlusionTexture:o.occlusionTexture?a(o.occlusionTexture):void 0,emissiveTexture:o.emissiveTexture?a(o.emissiveTexture):void 0,metallicRoughnessTexture:o.metallicRoughnessTexture?a(o.metallicRoughnessTexture):void 0,emissiveFactor:[o.emissiveFactor[0],o.emissiveFactor[1],o.emissiveFactor[2]],colorTextureTransform:o.colorTextureTransform,normalTextureTransform:o.normalTextureTransform,occlusionTextureTransform:o.occlusionTextureTransform,emissiveTextureTransform:o.emissiveTextureTransform,metallicRoughnessTextureTransform:o.metallicRoughnessTextureTransform,metallicFactor:o.metallicFactor,roughnessFactor:o.roughnessFactor,receiveShadows:o.receiveShadows,receiveAmbientOcclusion:o.receiveAmbientOcclusion});e.materials.set(i,t)}return i}const T=new Set([9987,9985]);export{l as loadGLTF};
5
+ import e from"../../../core/Logger.js";import{getKey as o}from"../../../core/object.js";import{clone as t}from"../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{makeMaterialParameters as r,makeTextureSource as s}from"./LoaderResult.js";import{GLTFResource as a}from"./internal/Resource.js";import{PrimitiveType as i}from"../../webgl/enums.js";let n=0;async function l(r,s,l={},m=!0){const T=await a.load(r,s,l),p="gltf_"+n++,f={lods:[],materials:new Map,textures:new Map,meta:u(T)},x=!(!T.json.asset.extras||"symbolResource"!==T.json.asset.extras.ESRI_type),g=T.json.asset.extras?.ESRI_webstyleSymbol?.webstyle,h=new Map;await c(T,async(r,s,a,n)=>{const u=h.get(a)??0;h.set(a,u+1);const c=void 0!==r.mode?r.mode:i.TRIANGLES,x=c===i.TRIANGLES||c===i.TRIANGLE_STRIP||c===i.TRIANGLE_FAN?c:null;if(null==x)return void e.getLogger("esri.views.3d.glTF").warn("[Unsupported Feature] Unsupported primitive mode ("+o(i,c)+"). Skipping primitive.");if(!T.hasPositions(r))return void e.getLogger("esri.views.3d.glTF").warn("Skipping primitive without POSITION vertex attribute.");const g=await T.decode(r,l),w=T.getPositionData(r,l,g),v=T.getMaterial(r,l,m),S=T.hasNormals(r)?T.getNormalData(r,l,g):null,R=T.hasTangents(r)?T.getTangentData(r,l,g):null,_=T.hasTextureCoordinates(r)?T.getTextureCoordinates(r,l,g):null,F=T.hasVertexColors(r)?T.getVertexColors(r,l,g):null,y=T.getIndexData(r,l,g),E={name:n,transform:t(s),attributes:{position:await w,normal:S?await S:null,texCoord0:_?await _:null,color:F?await F:null,tangent:R?await R:null},indices:await y,primitiveType:x,material:d(f,await v,p)};let I=null;null!=f.meta?.ESRI_lod&&"screenSpaceRadius"===f.meta.ESRI_lod.metric&&(I=f.meta.ESRI_lod.thresholds[a]),f.lods[a]=f.lods[a]||{parts:[],name:n,lodThreshold:I},f.lods[a].parts[u]=E});for(const e of f.lods)e.parts=e.parts.filter(e=>!!e);const w=await T.getLoadedBuffersSize();return{model:f,meta:{isEsriSymbolResource:x,uri:T.uri,ESRI_webstyle:g},customMeta:{},usedMemory:w}}function u(e){const o=e.json;let t=null;return o.nodes.forEach(e=>{const o=e.extras;null!=o&&(o.ESRI_proxyEllipsoid||o.ESRI_lod)&&(t=o)}),t}async function c(o,t){const r=o.json,s=r.scenes[r.scene||0].nodes,a=s.length>1,i=[];for(const e of s){const o=r.nodes[e];if(i.push(n(e,0)),m(o)&&!a){o.extensions.MSFT_lod.ids.forEach((e,o)=>n(e,o+1))}}async function n(s,a){const l=r.nodes[s],u=o.getNodeTransform(s);if(null!=l.weights&&e.getLogger("esri.views.3d.glTF").warn("[Unsupported Feature] Morph targets are not supported."),null!=l.mesh){const e=r.meshes[l.mesh];for(const o of e.primitives)i.push(t(o,u,a,e.name))}for(const e of l.children||[])i.push(n(e,a))}await Promise.all(i)}function m(e){return e.extensions?.MSFT_lod&&Array.isArray(e.extensions.MSFT_lod.ids)}function d(e,o,t){const a=o=>{const r=`${t}_tex_${o&&o.id}${o?.name?"_"+o.name:""}`;if(o&&!e.textures.has(r)){const t=s(o.data,{wrap:{s:o.wrapS,t:o.wrapT},mipmap:T.has(o.minFilter),noUnpackFlip:!0});e.textures.set(r,t)}return r},i=`${t}_mat_${o.id}_${o.name}`;if(!e.materials.has(i)){const t=r({color:[o.color[0],o.color[1],o.color[2]],opacity:o.color[3],alphaMode:o.alphaMode,alphaCutoff:o.alphaCutoff,doubleSided:o.doubleSided,colorMixMode:o.ESRI_externalColorMixMode,colorTexture:o.colorTexture?a(o.colorTexture):void 0,normalTexture:o.normalTexture?a(o.normalTexture):void 0,occlusionTexture:o.occlusionTexture?a(o.occlusionTexture):void 0,emissiveTexture:o.emissiveTexture?a(o.emissiveTexture):void 0,metallicRoughnessTexture:o.metallicRoughnessTexture?a(o.metallicRoughnessTexture):void 0,emissiveFactor:[o.emissiveFactor[0],o.emissiveFactor[1],o.emissiveFactor[2]],colorTextureTransform:o.colorTextureTransform,normalTextureTransform:o.normalTextureTransform,occlusionTextureTransform:o.occlusionTextureTransform,emissiveTextureTransform:o.emissiveTextureTransform,metallicRoughnessTextureTransform:o.metallicRoughnessTextureTransform,metallicFactor:o.metallicFactor,roughnessFactor:o.roughnessFactor,receiveShadows:o.receiveShadows,receiveAmbientOcclusion:o.receiveAmbientOcclusion});e.materials.set(i,t)}return i}const T=new Set([9987,9985]);export{l as loadGLTF};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import{equals as t}from"../../../core/arrayUtils.js";import"../../../core/has.js";import{removeMaybe as r,abortMaybe as i}from"../../../core/maybe.js";import{debounce as s,ignoreAbortErrors as o,throwIfAborted as n}from"../../../core/promiseUtils.js";import{watch as a,when as l,sync as u,whenOnce as d}from"../../../core/reactiveUtils.js";import{addFrameTask as p}from"../../../core/scheduling.js";import{Seconds as h,secondsFromMilliseconds as c}from"../../../core/time.js";import{property as m}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/Logger.js";import{subclass as _}from"../../../core/accessorSupport/decorators/subclass.js";import{projectOrLoad as f}from"../../../geometry/projectionUtils.js";import{fromExtent as g,intersection as y,toExtent as w,intersects as v}from"../../../geometry/support/aaBoundingRect.js";import b from"../../../symbols/support/ElevationInfo.js";import{simulationSettingsEqual as T,getPositions as S,getFlowSimulationSettings as R}from"../../2d/engine/flow/utils.js";import j from"./SubView3D.js";import{makeScheduleFunction as L}from"./support/makeScheduleFunction.js";import{fadeOutTime as U,fadeInTime as A,defaultTransitionDuration as P,transitionDurationFactor as E,averageLoadingTimeSmoothingFactor as x}from"../support/flow/constants.js";import{FlowWorkerHandle as I}from"../support/flow/FlowWorkerHandle.js";import{materialParametersFromRenderer as k,createStreamlineGeometry as C}from"../support/flow/geometryUtils.js";import{boundingRectOfTiles as q}from"../support/flow/loadUtils.js";import{StreamlineResources3DOverlay as M}from"../support/flow/StreamlineResources3DOverlay.js";import{StreamlineResources3DShape as z}from"../support/flow/StreamlineResources3DShape.js";import D from"../support/flow/VisualQuery3D.js";import{tilesAreRelated as V}from"../terrain/tileUtils.js";import{isScreenSizePerspectiveEnabled as B}from"../webgl-engine/lib/screenSizePerspectiveUtils.js";import{RibbonLineMaterial as W}from"../webgl-engine/materials/RibbonLineMaterial.js";import{isInEffectiveScaleRange as G,hasLayerBasedScaleVisibility as H}from"../../support/layerViewUtils.js";import{TaskPriority as F}from"../../support/Scheduler.js";let O=class extends j{constructor(e){super(e),this.type="flow",this.renderedTiles=null,this.requireLoad=!1,this.workerHandle=null,this._averageLoadingTime=h(0),this._abortController=null,this._frameTask=null,this._tilesUpdateIsWaiting=!1,this._transitionEnabled=!0,this._debugAllowAutoLoading=!0,this.emissiveStrength=0,this._overrideMaterialParameters=null,this._overrideSimulationSettings=null,this._updateTask=null,this._debouncedTileUpdate=s(async()=>{const{allTiles:e}=this.surface,{featureTiles:r}=this.view,{_dataBounds:i,_featureTilesBounds:s}=this,o=e=>e.rendered&&e.visible&&Q(i,e.extent);if(null==r)return void(this.renderedTiles=new Set(e.filter(e=>o(e))));const n=r.tiles.filter(e=>e.measures.visible),a=new Set;function*l(r){for(let i=0;i<e.length;++i){const l=e.at(i);if(!o(l))continue;if(!Q(s,l.extent))continue;n.some(({lij:e})=>t(e,l.lij)||V(e,l.lij))&&a.add(l),r.madeProgress(),r.done&&(r=yield)}}await this._frameTask.scheduleGenerator(l),this.renderedTiles=a}),this._transitionEnabled=!0}initialize(){const{surface:e,view:t}=this,{resourceController:r}=t;this.workerHandle=new I(L(r)),this._frameTask=r.scheduler.registerTask(F.FLOW_GENERATOR),this._updateTask=p({update:this._update.bind(this)}),this.addHandles([a(()=>this.simulationSettings,()=>this.triggerLoad(),{sync:!0,equals:(e,t)=>null==e&&null==t||null!=e&&null!=t&&T(e,t)}),a(()=>{const{elevationInfo:e}=this;return[this._clippingArea,this._visible,this._draped,e?.mode,e?.offset,e?.unit]},()=>this.triggerLoad(),u),a(()=>this._materialParameters,e=>{this._resources?.setMaterialParameters(e),this._lastResources?.setMaterialParameters(e)}),e.on("tiles-changed",()=>this._triggerTilesUpdate()),t.enableFeatureTiles(),a(()=>[this._dataBounds,this._featureTilesBounds],()=>this._triggerTilesUpdate()),l(()=>!t.featureTiles?.updating,()=>this._triggerTilesUpdate())]),this._triggerTilesUpdate()}destroy(){this._updateTask=r(this._updateTask),this.abort(),this.clear()}abort(){this._abortController=i(this._abortController),this.requireLoad=!1}get _clippingArea(){const e=f(this.view.clippingArea,this.surface.spatialReference).geometry;return null==e?null:g(e)}get _dataBounds(){const e=f(this.layer.fullExtent,this.surface.spatialReference).geometry;return null==e?null:g(e)}get _draped(){return"on-the-ground"===this.elevationInfo.mode}get _featureTilesBounds(){const e=this.view.featureTiles?.filterExtent,t=f(e,this.surface.spatialReference).geometry;return null==t?null:g(t)}get _flowRenderer(){const e=this.layer.renderer;return"flow"!==e?.type?null:e}get _materialParameters(){return{...k(this._flowRenderer,this.layerView.fullOpacity,this.emissiveStrength),fadeInTime:A,fadeOutTime:U,...this._overrideMaterialParameters,screenSizePerspective:!this._draped&&B(this.layer.screenSizePerspectiveEnabled)?this.view.screenSizePerspective.parameters:null}}get _opacity(){return this.layerView.fullOpacity}get _transitionDuration(){const{_averageLoadingTime:e}=this;return h(0===e?P:this._averageLoadingTime*E)}get _visible(){const e=this._flowRenderer?.color;return this.visibleAtCurrentScale&&this.layer.effectiveVisible&&this._opacity>0&&(null==e||e.a>0)}get elevationInfo(){return this.layer.elevationInfo??N}startPositions(e){if(!this._transitionEnabled)return[];const{_flowRenderer:t,_resources:r}=this;return null==t||null==r?[]:S(r.streamlines,r.query,e,t.flowSpeed)}get needsMagnitude(){return this._flowRenderer?.hasVisualVariables()??!1}get layer(){return this.layerView.layer}get updating(){return this.updatingHandles.updating||this.requireLoad}get visibleAtCurrentScale(){return!H()||G(this.layer.effectiveScaleRange,this.view.scale)}get simulationSettings(){const{_flowRenderer:e,_overrideSimulationSettings:t}=this;if(null==e)return null;let r=R(e);return r.segmentLength=r.lineCollisionWidth/2,r.onlyForwardTracing=!1,null!=t&&(r={...r,...t}),r}get surface(){return this.view.basemapTerrain}doRefresh(){this.triggerLoad()}clear(){this._resources?.detach(),this._resources=null,this._lastResources?.detach(),this._lastResources=null}_update(e){if(!this.requireLoad||this.updatingHandles.updating)return;const t=c(e.time);if(this._transitionEnabled&&!this._lastResourceIsTransitioned(t))return;const{renderedTiles:r}=this;if(null==r||0===r.size)return;const i=async()=>{const e=performance.now();await this._load(r,t,this._transitionDuration);const i=h((performance.now()-e)/1e3);this._updateAverageLoadingTime(i)};this.updatingHandles.addPromise(o(i())),this.requireLoad=!1}_updateAverageLoadingTime(e){const t=x;this._averageLoadingTime=h(t*e+(1-t)*this._averageLoadingTime)}triggerLoad(){this._debugAllowAutoLoading&&(this.requireLoad=!0)}async _load(e,t,r){const{view:i}=this;if(!this._visible)return void this.clear();if(0===e.size)return;const s=this._computeExtent(e);if(null==s)return;const o=this._transitionEnabled&&null!=this._resources?h(t+r):t,a=new D(s,this.layer.timeExtent,this._viewSizeWithEqualRatio(s),i.state.contentPixelRatio,o);null==this._abortController&&(this._abortController=new AbortController);const l=this._abortController,u=await this._loadStreamlines(a,l.signal);if(n(l.signal),this._visible&&null!=u){u.attach(),this._lastResources?.detach(),this._transitionEnabled?this._lastResources=this._resources:this._resources?.detach(),this._resources=u;const e=performance.now()/1e3,t=this._transitionEnabled&&e>o?e:o;null!=this._lastResources&&(this._lastResources.endTime=t),this._resources.startTime=t}}async _loadStreamlines(e,t){const r=await this.fetchDataAndGenerateStreamlines(e,t);if(null==r||0===r.length)return null;const i=await this._createGeometry(e,r);return this._draped?new M(e,r,i,this.surface.overlayManager):new z(e,r,i,this.view.stage)}async fetchDataAndGenerateStreamlines(e,t){return null}async _createGeometry(e,t){const r=new W(this._materialParameters,this.view.state.isGlobal),i=new Array,{elevationInfo:s,_draped:o,view:n}=this;function*a(a){for(let l=0;l<t.length;++l)i.push(C(n,e,t[l],s,r,o)),a.madeProgress(),a.done&&(a=yield)}return await this._frameTask.scheduleGenerator(a),i}_computeExtent(e){const{spatialReference:t}=this.surface;if(null==t)return null;const r=q(e);return null==r?null:(y(r,this._clippingArea,r),w(r,t))}_triggerTilesUpdate(){if(this._tilesUpdateIsWaiting)return;this._tilesUpdateIsWaiting=!0;const e=async()=>{await d(()=>this.view.stationary),this._tilesUpdateIsWaiting=!1,await this._debouncedTileUpdate()};this.updatingHandles.addPromise(o(e()))}_viewSizeWithEqualRatio(e){const t=(e.xmax-e.xmin)/(e.ymax-e.ymin),[r,i]=this.view.size;return r<i?[r,Math.floor(r/t)]:[Math.floor(i*t),i]}_lastResourceIsTransitioned(e){const{_lastResources:t,_resources:r,_flowRenderer:i}=this;if(null==t||null==r||null==i)return!0;return r.startTime+U<e}get test(){}};e([m()],O.prototype,"type",void 0),e([m()],O.prototype,"renderedTiles",void 0),e([m()],O.prototype,"_resources",void 0),e([m()],O.prototype,"_lastResources",void 0),e([m()],O.prototype,"requireLoad",void 0),e([m()],O.prototype,"_averageLoadingTime",void 0),e([m()],O.prototype,"emissiveStrength",void 0),e([m()],O.prototype,"_clippingArea",null),e([m()],O.prototype,"_dataBounds",null),e([m()],O.prototype,"_draped",null),e([m()],O.prototype,"_featureTilesBounds",null),e([m()],O.prototype,"_flowRenderer",null),e([m()],O.prototype,"_materialParameters",null),e([m()],O.prototype,"_opacity",null),e([m()],O.prototype,"_transitionDuration",null),e([m()],O.prototype,"_visible",null),e([m()],O.prototype,"elevationInfo",null),e([m()],O.prototype,"needsMagnitude",null),e([m()],O.prototype,"layer",null),e([m()],O.prototype,"updating",null),e([m()],O.prototype,"visibleAtCurrentScale",null),e([m()],O.prototype,"_overrideMaterialParameters",void 0),e([m()],O.prototype,"_overrideSimulationSettings",void 0),e([m()],O.prototype,"simulationSettings",null),e([m()],O.prototype,"surface",null),O=e([_("esri.views.3d.layers.FlowSubView3D")],O);const N=new b({mode:"on-the-ground"});function Q(e,t){return null==e||null==t||v(e,t)}export{O as default};
5
+ import{__decorate as e}from"tslib";import{equals as t}from"../../../core/arrayUtils.js";import"../../../core/has.js";import{removeMaybe as i,abortMaybe as r}from"../../../core/maybe.js";import{debounce as s,ignoreAbortErrors as o,throwIfAborted as l}from"../../../core/promiseUtils.js";import{watch as a,when as n,sync as u,whenOnce as d}from"../../../core/reactiveUtils.js";import{addFrameTask as p}from"../../../core/scheduling.js";import{Seconds as h,secondsFromMilliseconds as c}from"../../../core/time.js";import{getMetersPerVerticalUnitForSR as m}from"../../../core/unitUtils.js";import{property as _}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/Logger.js";import{subclass as f}from"../../../core/accessorSupport/decorators/subclass.js";import{getReferenceEllipsoid as g}from"../../../geometry/ellipsoidUtils.js";import{projectOrLoad as y}from"../../../geometry/projectionUtils.js";import{fromExtent as v,intersection as w,toExtent as T,intersects as b}from"../../../geometry/support/aaBoundingRect.js";import R from"../../../symbols/support/ElevationInfo.js";import{simulationSettingsEqual as S,getPositions as j,getFlowSimulationSettings as L}from"../../2d/engine/flow/utils.js";import A from"./SubView3D.js";import{makeScheduleFunction as U}from"./support/makeScheduleFunction.js";import{thresholdForLoadingAllTiles as P,fadeOutTime as E,fadeInTime as x,defaultTransitionDuration as I,transitionDurationFactor as k,averageLoadingTimeSmoothingFactor as V}from"../support/flow/constants.js";import{FlowWorkerHandle as C}from"../support/flow/FlowWorkerHandle.js";import{materialParametersFromRenderer as q,createStreamlineGeometry as z}from"../support/flow/geometryUtils.js";import{boundingRectOfTiles as M}from"../support/flow/loadUtils.js";import{StreamlineResources3DOverlay as D}from"../support/flow/StreamlineResources3DOverlay.js";import{StreamlineResources3DShape as F}from"../support/flow/StreamlineResources3DShape.js";import B from"../support/flow/VisualQuery3D.js";import{tilesAreRelated as W}from"../terrain/tileUtils.js";import{isScreenSizePerspectiveEnabled as G}from"../webgl-engine/lib/screenSizePerspectiveUtils.js";import{RibbonLineMaterial as H}from"../webgl-engine/materials/RibbonLineMaterial.js";import{isInEffectiveScaleRange as O,hasLayerBasedScaleVisibility as N}from"../../support/layerViewUtils.js";import{TaskPriority as Q}from"../../support/Scheduler.js";let J=class extends A{constructor(e){super(e),this.type="flow",this.renderedTiles=null,this.requireLoad=!1,this.workerHandle=null,this._averageLoadingTime=h(0),this._abortController=null,this._frameTask=null,this._tilesUpdateIsWaiting=!1,this._transitionEnabled=!0,this._debugAllowAutoLoading=!0,this.emissiveStrength=0,this._overrideMaterialParameters=null,this._overrideSimulationSettings=null,this._updateTask=null,this._debouncedTileUpdate=s(async()=>{const{allTiles:e}=this.surface,t=this._getTileFilterFunction(),i=new Set;function*r(r){for(let s=0;s<e.length;++s){const o=e.at(s);t(o)&&i.add(o),r.madeProgress(),r.done&&(r=yield)}}await this._frameTask.scheduleGenerator(r),this.renderedTiles=i}),this._transitionEnabled=!0}initialize(){const{surface:e,view:t}=this,{resourceController:i}=t;this.workerHandle=new C(U(i)),this._frameTask=i.scheduler.registerTask(Q.FLOW_GENERATOR),this._updateTask=p({update:this._update.bind(this)}),this.addHandles([a(()=>this.simulationSettings,()=>this.triggerLoad(),{sync:!0,equals:(e,t)=>null==e&&null==t||null!=e&&null!=t&&S(e,t)}),a(()=>{const{elevationInfo:e}=this;return[this._clippingArea,this._visible,this._draped,this.view.state.contentPixelRatio,e?.mode,e?.offset,e?.unit]},()=>this.triggerLoad(),u),a(()=>this._materialParameters,e=>{this._resources?.setMaterialParameters(e),this._lastResources?.setMaterialParameters(e)}),e.on("tiles-changed",()=>this._triggerTilesUpdate()),t.enableFeatureTiles(),a(()=>[this._dataBounds,this._featureTilesBounds,this._loadAllTiles],()=>this._triggerTilesUpdate()),a(()=>this._flowRenderer,(e,t)=>{const i=t?.visualVariables??[],r=e?.visualVariables??[];r.length===i.length&&r.every((e,t)=>e.type===i[t].type)||this.clear()}),n(()=>!t.featureTiles?.updating,()=>this._triggerTilesUpdate())]),this._triggerTilesUpdate()}destroy(){this._updateTask=i(this._updateTask),this.abort(),this.clear()}abort(){this._abortController=r(this._abortController),this.requireLoad=!1}get _clippingArea(){const e=y(this.view.clippingArea,this.surface.spatialReference).geometry;return null==e?null:v(e)}get _dataBounds(){const e=y(this.layer.fullExtent,this.surface.spatialReference).geometry;return null==e?null:v(e)}get _draped(){return"on-the-ground"===this.elevationInfo.mode}get _ellipsoidRadius(){return g(this.view.spatialReference).radius}get _loadAllTiles(){const{position:e}=this.view.camera,t=e.z;if(null==t)return!1;return t*m(e.spatialReference)/this._ellipsoidRadius>=P}get _featureTilesBounds(){const e=this.view.featureTiles?.filterExtent,t=y(e,this.surface.spatialReference).geometry;return null==t?null:v(t)}get _flowRenderer(){const e=this.layer.renderer;return"flow"!==e?.type?null:e}get _materialParameters(){return{...q(this._flowRenderer,this.layerView.fullOpacity,this.emissiveStrength),fadeInTime:x,fadeOutTime:E,...this._overrideMaterialParameters,screenSizePerspective:!this._draped&&G(this.layer.screenSizePerspectiveEnabled)?this.view.screenSizePerspective.parameters:null}}get _opacity(){return this.layerView.fullOpacity}get _transitionDuration(){const{_averageLoadingTime:e}=this;return h(0===e?I:this._averageLoadingTime*k)}get _visible(){const e=this._flowRenderer?.color;return this.visibleAtCurrentScale&&this.layer.effectiveVisible&&this._opacity>0&&(null==e||e.a>0)}get elevationInfo(){return this.layer.elevationInfo??K}startPositions(e){if(!this._transitionEnabled)return[];const{_flowRenderer:t,_resources:i}=this;return null==t||null==i?[]:j(i.streamlines,i.query,e,t.flowSpeed)}get needsMagnitude(){return this._flowRenderer?.hasVisualVariables()??!1}get layer(){return this.layerView.layer}get updating(){return this.updatingHandles.updating||this.requireLoad}get visibleAtCurrentScale(){return!N()||O(this.layer.effectiveScaleRange,this.view.scale)}get simulationSettings(){const{_flowRenderer:e,_overrideSimulationSettings:t}=this;if(null==e)return null;let i=L(e);return i.segmentLength=i.lineCollisionWidth/2,i.onlyForwardTracing=!1,null!=t&&(i={...i,...t}),i}get surface(){return this.view.basemapTerrain}doRefresh(){this.triggerLoad()}clear(){this._resources?.detach(),this._resources=null,this._lastResources?.detach(),this._lastResources=null}_update(e){if(!this.requireLoad||this.updatingHandles.updating)return;const t=c(e.time);if(this._transitionEnabled&&!this._lastResourceIsTransitioned(t))return;const{renderedTiles:i}=this;if(null==i||0===i.size)return;const r=async()=>{const e=performance.now();await this._load(i,t,this._transitionDuration);const r=h((performance.now()-e)/1e3);this._updateAverageLoadingTime(r)};this.updatingHandles.addPromise(o(r())),this.requireLoad=!1}_updateAverageLoadingTime(e){const t=V;this._averageLoadingTime=h(t*e+(1-t)*this._averageLoadingTime)}triggerLoad(){this._debugAllowAutoLoading&&(this.requireLoad=!0)}async _load(e,t,i){const{view:r}=this;if(!this._visible)return void this.clear();if(0===e.size)return;const s=this._computeExtent(e);if(null==s)return;const o=this._transitionEnabled&&null!=this._resources?h(t+i):t,a=new B(s,this.layerView.timeExtent,this._viewSizeWithEqualRatio(s),r.state.contentPixelRatio,o);null==this._abortController&&(this._abortController=new AbortController);const n=this._abortController,u=await this._loadStreamlines(a,n.signal);if(l(n.signal),this._visible&&null!=u){u.attach(),this._lastResources?.detach(),this._transitionEnabled?this._lastResources=this._resources:this._resources?.detach(),this._resources=u;const e=performance.now()/1e3,t=this._transitionEnabled&&e>o?e:o;null!=this._lastResources&&(this._lastResources.endTime=t),this._resources.startTime=t}}async _loadStreamlines(e,t){const i=await this.fetchDataAndGenerateStreamlines(e,t);if(null==i||0===i.length)return null;const r=await this._createGeometry(e,i);return this._draped?new D(e,i,r,this.surface.overlayManager):new F(e,i,r,this.view.stage)}async fetchDataAndGenerateStreamlines(e,t){return null}async _createGeometry(e,t){const i=new H(this._materialParameters,this.view.state.isGlobal),r=new Array,{elevationInfo:s,_draped:o,view:l}=this;function*a(a){for(let n=0;n<t.length;++n)r.push(z(l,e,t[n],s,i,o)),a.madeProgress(),a.done&&(a=yield)}return await this._frameTask.scheduleGenerator(a),r}_computeExtent(e){const{spatialReference:t}=this.surface;if(null==t)return null;const i=M(e);return null==i?null:(w(i,this._clippingArea,i),T(i,t))}_triggerTilesUpdate(){if(this._tilesUpdateIsWaiting)return;this._tilesUpdateIsWaiting=!0;const e=async()=>{await d(()=>this.view.stationary),this._tilesUpdateIsWaiting=!1,await this._debouncedTileUpdate()};this.updatingHandles.addPromise(o(e()))}_getTileFilterFunction(){const{_dataBounds:e,view:i,_featureTilesBounds:r}=this;if(this._loadAllTiles)return t=>t.leaf&&X(e,t.extent);const s=t=>t.rendered&&t.visible&&X(e,t.extent),{featureTiles:o}=i;if(!o)return s;const l=o.tiles.filter(e=>e.measures.visible);return e=>s(e)&&X(r,e.extent)&&l.some(({lij:i})=>t(i,e.lij)||W(i,e.lij))}_viewSizeWithEqualRatio(e){const t=(e.xmax-e.xmin)/(e.ymax-e.ymin),[i,r]=this.view.size;return i<r?[i,Math.floor(i/t)]:[Math.floor(r*t),r]}_lastResourceIsTransitioned(e){const{_lastResources:t,_resources:i,_flowRenderer:r}=this;if(null==t||null==i||null==r)return!0;return i.startTime+E<e}get test(){}};e([_()],J.prototype,"type",void 0),e([_()],J.prototype,"renderedTiles",void 0),e([_()],J.prototype,"_resources",void 0),e([_()],J.prototype,"_lastResources",void 0),e([_()],J.prototype,"requireLoad",void 0),e([_()],J.prototype,"_averageLoadingTime",void 0),e([_()],J.prototype,"emissiveStrength",void 0),e([_()],J.prototype,"_clippingArea",null),e([_()],J.prototype,"_dataBounds",null),e([_()],J.prototype,"_draped",null),e([_()],J.prototype,"_ellipsoidRadius",null),e([_()],J.prototype,"_loadAllTiles",null),e([_()],J.prototype,"_featureTilesBounds",null),e([_()],J.prototype,"_flowRenderer",null),e([_()],J.prototype,"_materialParameters",null),e([_()],J.prototype,"_opacity",null),e([_()],J.prototype,"_transitionDuration",null),e([_()],J.prototype,"_visible",null),e([_()],J.prototype,"elevationInfo",null),e([_()],J.prototype,"needsMagnitude",null),e([_()],J.prototype,"layer",null),e([_()],J.prototype,"updating",null),e([_()],J.prototype,"visibleAtCurrentScale",null),e([_()],J.prototype,"_overrideMaterialParameters",void 0),e([_()],J.prototype,"_overrideSimulationSettings",void 0),e([_()],J.prototype,"simulationSettings",null),e([_()],J.prototype,"surface",null),J=e([f("esri.views.3d.layers.FlowSubView3D")],J);const K=new R({mode:"on-the-ground"});function X(e,t){return null==e||null==t||b(e,t)}export{J as default};