@luma.gl/graph 10.0.0-alpha.5 → 10.0.0-alpha.6

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 (110) hide show
  1. package/LICENSE +38 -0
  2. package/README.md +7 -1
  3. package/dist/arrow/dggs/dggs-gpu-polygons.cjs +667 -0
  4. package/dist/arrow/dggs/dggs-gpu-polygons.d.ts +75 -0
  5. package/dist/arrow/dggs/dggs-gpu-polygons.d.ts.map +1 -0
  6. package/dist/arrow/dggs/dggs-gpu-polygons.js +651 -0
  7. package/dist/arrow/dggs/dggs-gpu-polygons.js.map +1 -0
  8. package/dist/arrow/geoarrow/arrow-geoarrow-adapter.cjs +411 -0
  9. package/dist/arrow/geoarrow/arrow-geoarrow-adapter.d.ts +31 -0
  10. package/dist/arrow/geoarrow/arrow-geoarrow-adapter.d.ts.map +1 -0
  11. package/dist/arrow/geoarrow/arrow-geoarrow-adapter.js +395 -0
  12. package/dist/arrow/geoarrow/arrow-geoarrow-adapter.js.map +1 -0
  13. package/dist/arrow/geoarrow/arrow-geoarrow-conversion.cjs +304 -0
  14. package/dist/arrow/geoarrow/arrow-geoarrow-conversion.d.ts +32 -0
  15. package/dist/arrow/geoarrow/arrow-geoarrow-conversion.d.ts.map +1 -0
  16. package/dist/arrow/geoarrow/arrow-geoarrow-conversion.js +293 -0
  17. package/dist/arrow/geoarrow/arrow-geoarrow-conversion.js.map +1 -0
  18. package/dist/arrow/geoarrow/arrow-polygon-tessellation.cjs +232 -0
  19. package/dist/arrow/geoarrow/arrow-polygon-tessellation.d.ts +54 -0
  20. package/dist/arrow/geoarrow/arrow-polygon-tessellation.d.ts.map +1 -0
  21. package/dist/arrow/geoarrow/arrow-polygon-tessellation.js +222 -0
  22. package/dist/arrow/geoarrow/arrow-polygon-tessellation.js.map +1 -0
  23. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.cjs +314 -0
  24. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.d.ts +42 -0
  25. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.d.ts.map +1 -0
  26. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.js +318 -0
  27. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.js.map +1 -0
  28. package/dist/arrow/gpu/arrow-gpu-analytics-readback.cjs +204 -0
  29. package/dist/arrow/gpu/arrow-gpu-analytics-readback.d.ts +30 -0
  30. package/dist/arrow/gpu/arrow-gpu-analytics-readback.d.ts.map +1 -0
  31. package/dist/arrow/gpu/arrow-gpu-analytics-readback.js +195 -0
  32. package/dist/arrow/gpu/arrow-gpu-analytics-readback.js.map +1 -0
  33. package/dist/arrow/gpu/arrow-gpu-table-adapters.cjs +257 -0
  34. package/dist/arrow/gpu/arrow-gpu-table-adapters.d.ts +45 -0
  35. package/dist/arrow/gpu/arrow-gpu-table-adapters.d.ts.map +1 -0
  36. package/dist/arrow/gpu/arrow-gpu-table-adapters.js +257 -0
  37. package/dist/arrow/gpu/arrow-gpu-table-adapters.js.map +1 -0
  38. package/dist/arrow/gpu/arrow-gpu-table-conversion.cjs +230 -0
  39. package/dist/arrow/gpu/arrow-gpu-table-conversion.d.ts +71 -0
  40. package/dist/arrow/gpu/arrow-gpu-table-conversion.d.ts.map +1 -0
  41. package/dist/arrow/gpu/arrow-gpu-table-conversion.js +215 -0
  42. package/dist/arrow/gpu/arrow-gpu-table-conversion.js.map +1 -0
  43. package/dist/arrow/gpu/arrow-input-schema.cjs +36 -0
  44. package/dist/arrow/gpu/arrow-input-schema.d.ts +41 -0
  45. package/dist/arrow/gpu/arrow-input-schema.d.ts.map +1 -0
  46. package/dist/arrow/gpu/arrow-input-schema.js +17 -0
  47. package/dist/arrow/gpu/arrow-input-schema.js.map +1 -0
  48. package/dist/arrow/index.cjs +90 -0
  49. package/dist/arrow/index.cjs.map +6 -0
  50. package/dist/arrow/index.d.ts +9 -0
  51. package/dist/arrow/index.d.ts.map +1 -0
  52. package/dist/arrow/index.js +12 -0
  53. package/dist/arrow/index.js.map +1 -0
  54. package/dist/arrow/internal.cjs +30 -0
  55. package/dist/arrow/internal.cjs.map +6 -0
  56. package/dist/arrow/internal.d.ts +19 -0
  57. package/dist/arrow/internal.d.ts.map +1 -0
  58. package/dist/arrow/internal.js +7 -0
  59. package/dist/arrow/internal.js.map +1 -0
  60. package/dist/dist.dev.js +283 -12
  61. package/dist/dist.min.js +29 -29
  62. package/dist/geospatial/geospatial-utils.cjs +12 -11
  63. package/dist/geospatial/geospatial-utils.d.ts +1 -1
  64. package/dist/geospatial/geospatial-utils.d.ts.map +1 -1
  65. package/dist/geospatial/geospatial-utils.js +3 -2
  66. package/dist/geospatial/geospatial-utils.js.map +1 -1
  67. package/dist/geospatial/index.cjs.map +2 -2
  68. package/dist/gpu-a5/index.cjs.map +1 -1
  69. package/dist/gpu-dggs/benchmarks.cjs.map +1 -1
  70. package/dist/gpu-dggs/gpu-dggs-cell-projection.cjs +2 -2
  71. package/dist/gpu-dggs/gpu-dggs-cell-projection.js +1 -1
  72. package/dist/gpu-dggs/gpu-dggs-cell-projection.js.map +1 -1
  73. package/dist/gpu-dggs/index.cjs.map +1 -1
  74. package/dist/gpu-h3/index.cjs.map +1 -1
  75. package/dist/gpu-project/benchmarks.cjs.map +2 -2
  76. package/dist/gpu-project/crs.cjs.map +2 -2
  77. package/dist/gpu-project/index.cjs.map +2 -2
  78. package/dist/gpu-project/projection-program.cjs +2 -2
  79. package/dist/gpu-project/projection-program.d.ts +1 -1
  80. package/dist/gpu-project/projection-program.d.ts.map +1 -1
  81. package/dist/gpu-project/projection-program.js +1 -1
  82. package/dist/gpu-project/projection-program.js.map +1 -1
  83. package/dist/gpu-sql/lu-sql.d.ts +1 -1
  84. package/dist/gpu-sql/lu-sql.js +1 -1
  85. package/dist/gpu-tables/engine/gpu-table-shader-bindings.d.ts +1 -1
  86. package/dist/gpu-tables/engine/gpu-table-shader-bindings.d.ts.map +1 -1
  87. package/dist/gpu-vector-search/index.cjs.map +1 -1
  88. package/dist/utils/assemble-compute-kernel.cjs +2 -2
  89. package/dist/utils/assemble-compute-kernel.d.ts +2 -1
  90. package/dist/utils/assemble-compute-kernel.d.ts.map +1 -1
  91. package/dist/utils/assemble-compute-kernel.js +2 -2
  92. package/dist/utils/assemble-compute-kernel.js.map +1 -1
  93. package/package.json +19 -7
  94. package/src/arrow/dggs/dggs-gpu-polygons.ts +820 -0
  95. package/src/arrow/geoarrow/arrow-geoarrow-adapter.ts +519 -0
  96. package/src/arrow/geoarrow/arrow-geoarrow-conversion.ts +415 -0
  97. package/src/arrow/geoarrow/arrow-polygon-tessellation.ts +369 -0
  98. package/src/arrow/gpu/arrow-gpu-analytics-adapters.ts +474 -0
  99. package/src/arrow/gpu/arrow-gpu-analytics-readback.ts +294 -0
  100. package/src/arrow/gpu/arrow-gpu-table-adapters.ts +378 -0
  101. package/src/arrow/gpu/arrow-gpu-table-conversion.ts +324 -0
  102. package/src/arrow/gpu/arrow-input-schema.ts +98 -0
  103. package/src/arrow/index.ts +79 -0
  104. package/src/arrow/internal.ts +23 -0
  105. package/src/geospatial/geospatial-utils.ts +3 -7
  106. package/src/gpu-dggs/gpu-dggs-cell-projection.ts +1 -1
  107. package/src/gpu-project/projection-program.ts +1 -1
  108. package/src/gpu-sql/lu-sql.ts +1 -1
  109. package/src/gpu-tables/engine/gpu-table-shader-bindings.ts +1 -1
  110. package/src/utils/assemble-compute-kernel.ts +3 -7
package/dist/dist.min.js CHANGED
@@ -4,7 +4,7 @@
4
4
  else if (typeof define === 'function' && define.amd) define([], factory);
5
5
  else if (typeof exports === 'object') exports['luma'] = factory();
6
6
  else root['luma'] = factory();})(globalThis, function () {
7
- "use strict";var __exports__=(()=>{var Pi=Object.create;var It=Object.defineProperty;var Si=Object.getOwnPropertyDescriptor;var Bi=Object.getOwnPropertyNames;var Ei=Object.getPrototypeOf,Li=Object.prototype.hasOwnProperty;var b=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(o){throw t=[o],o}};var Gi=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Di=(r,e)=>{for(var t in e)It(r,t,{get:e[t],enumerable:!0})},Dt=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Bi(e))!Li.call(r,n)&&n!==t&&It(r,n,{get:()=>e[n],enumerable:!(o=Si(e,n))||o.enumerable});return r},At=(r,e,t)=>(Dt(r,e,"default"),t&&Dt(t,e,"default")),ee=(r,e,t)=>(t=r!=null?Pi(Ei(r)):{},Dt(e||!r||!r.__esModule?It(t,"default",{value:r,enumerable:!0}):t,r)),Ii=r=>Dt(It({},"__esModule",{value:!0}),r);var K=Gi((Ts,Mo)=>{Mo.exports=globalThis.luma});var ot,Ai,Ut,Ui,$i,vr=b(()=>{ot=globalThis,Ai=globalThis.document||{},Ut=globalThis.process||{},Ui=globalThis.console,$i=globalThis.navigator||{}});function $t(r){if(typeof window<"u"&&window.process?.type==="renderer"||typeof process<"u"&&process.versions?.electron)return!0;let e=typeof navigator<"u"&&navigator.userAgent,t=r||e;return!!(t&&t.indexOf("Electron")>=0)}var _t=b(()=>{});function he(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||$t()}var Cr=b(()=>{_t()});var Oo=b(()=>{Cr();_t();vr()});var Fo=b(()=>{});var Pr,Rt=b(()=>{vr();Cr();Oo();_t();Fo();Pr="5.0.0"});function Fe(r,e){if(!r)throw new Error(e||"Assertion failed")}var Sr=b(()=>{});function Mt(r){if(!r)return 0;let e;switch(typeof r){case"number":e=r;break;case"object":e=r.logLevel||r.priority||0;break;default:return 0}return Fe(Number.isFinite(e)&&e>=0),e}function Br(r){let{logLevel:e,message:t}=r;r.logLevel=Mt(e);let o=r.args?Array.from(r.args):[];for(;o.length&&o.shift()!==t;);switch(typeof e){case"string":case"function":t!==void 0&&o.unshift(t),r.message=e;break;case"object":Object.assign(r,e);break;default:}typeof r.message=="function"&&(r.message=r.message());let n=typeof r.message;return Fe(n==="string"||n==="object"),Object.assign(r,{args:o},r.opts)}var kt=b(()=>{Sr()});var ge,Ee,nt=b(()=>{kt();ge=()=>{},Ee=class{constructor({level:e=0}={}){this.userData={},this._onceCache=new Set,this._level=e}set level(e){this.setLevel(e)}get level(){return this.getLevel()}setLevel(e){return this._level=e,this}getLevel(){return this._level}warn(e,...t){return this._log("warn",0,e,t,{once:!0})}error(e,...t){return this._log("error",0,e,t)}log(e,t,...o){return this._log("log",e,t,o)}info(e,t,...o){return this._log("info",e,t,o)}once(e,t,...o){return this._log("once",e,t,o,{once:!0})}_log(e,t,o,n,i={}){let a=Br({logLevel:t,message:o,args:this._buildArgs(t,o,n),opts:i});return this._createLogFunction(e,a,i)}_buildArgs(e,t,o){return[e,t,...o]}_createLogFunction(e,t,o){if(!this._shouldLog(t.logLevel))return ge;let n=this._getOnceTag(o.tag??t.tag??t.message);if((o.once||t.once)&&n!==void 0){if(this._onceCache.has(n))return ge;this._onceCache.add(n)}return this._emit(e,t)}_shouldLog(e){return this.getLevel()>=Mt(e)}_getOnceTag(e){if(e!==void 0)try{return typeof e=="string"?e:String(e)}catch{return}}}});function Ri(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,t),e.removeItem(t),e}catch{return null}}var it,Er=b(()=>{it=class{constructor(e,t,o="sessionStorage"){this.storage=Ri(o),this.id=e,this.config=t,this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){if(Object.assign(this.config,e),this.storage){let t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}}_loadConfiguration(){let e={};if(this.storage){let t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}});function No(r){let e;return r<10?e=`${r.toFixed(2)}ms`:r<100?e=`${r.toFixed(1)}ms`:r<1e3?e=`${r.toFixed(0)}ms`:e=`${(r/1e3).toFixed(2)}s`,e}function Lr(r,e=8){let t=Math.max(e-r.length,0);return`${" ".repeat(t)}${r}`}var Gr=b(()=>{});function zo(r){return typeof r!="string"?r:(r=r.toUpperCase(),at[r]||at.WHITE)}function Dr(r,e,t){return!he&&typeof r=="string"&&(e&&(r=`\x1B[${zo(e)}m${r}\x1B[39m`),t&&(r=`\x1B[${zo(t)+Mi}m${r}\x1B[49m`)),r}var at,Mi,Ot=b(()=>{Rt();(function(r){r[r.BLACK=30]="BLACK",r[r.RED=31]="RED",r[r.GREEN=32]="GREEN",r[r.YELLOW=33]="YELLOW",r[r.BLUE=34]="BLUE",r[r.MAGENTA=35]="MAGENTA",r[r.CYAN=36]="CYAN",r[r.WHITE=37]="WHITE",r[r.BRIGHT_BLACK=90]="BRIGHT_BLACK",r[r.BRIGHT_RED=91]="BRIGHT_RED",r[r.BRIGHT_GREEN=92]="BRIGHT_GREEN",r[r.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",r[r.BRIGHT_BLUE=94]="BRIGHT_BLUE",r[r.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",r[r.BRIGHT_CYAN=96]="BRIGHT_CYAN",r[r.BRIGHT_WHITE=97]="BRIGHT_WHITE"})(at||(at={}));Mi=10});function Ir(r,e=["constructor"]){let t=Object.getPrototypeOf(r),o=Object.getOwnPropertyNames(t),n=r;for(let i of o){let a=n[i];typeof a=="function"&&(e.find(s=>i===s)||(n[i]=a.bind(r)))}}var Ar=b(()=>{});var Ft,j,st=b(()=>{Rt();Ft=class{getHighResolutionTimer(){let e;if(he()&&ot.performance)e=ot?.performance?.now?.();else if("hrtime"in Ut){let t=Ut?.hrtime?.();e=t[0]*1e3+t[1]/1e6}else e=Date.now();return e}getMemoryUsageMB(){let t=ot?.performance?.memory?.usedJSHeapSize;return t==null?null:Math.trunc(t/1024/1024)}},j=new Ft;globalThis.Probe=Ft;globalThis.probe=j});function ki(r,e,t){if(typeof e=="string"){let o=t.time?Lr(No(t.total)):"";e=t.time?`${r}: ${o} ${e}`:`${r}: ${e}`,e=Dr(e,t.color,t.background)}return e}function Oi(r){for(let e in r)for(let t in r[e])return t||"untitled";return"empty"}var Ne,Ur,ae,$r=b(()=>{Rt();nt();Er();Gr();Ot();Ar();Sr();st();kt();kt();Ne={debug:he()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},Ur={enabled:!0,level:0},ae=class extends Ee{constructor({id:e}={id:""}){super({level:0}),this.VERSION=Pr,this._startTs=j.getHighResolutionTimer(),this._deltaTs=j.getHighResolutionTimer(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new it(`__probe-${this.id}__`,{[this.id]:Ur}),this.timeStamp(`${this.id} started`),Ir(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((j.getHighResolutionTimer()-this._startTs).toPrecision(10))}getDelta(){return Number((j.getHighResolutionTimer()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._updateConfiguration({enabled:e}),this}setLevel(e){return this._updateConfiguration({level:e}),this}get(e){return this._getConfiguration()[e]}set(e,t){this._updateConfiguration({[e]:t})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,t){if(!e)throw new Error(t||"Assertion failed")}warn(e,...t){return this._log("warn",0,e,t,{method:Ne.warn,once:!0})}error(e,...t){return this._log("error",0,e,t,{method:Ne.error})}deprecated(e,t){return this.warn(`\`${e}\` is deprecated and will be removed in a later version. Use \`${t}\` instead`)}removed(e,t){return this.error(`\`${e}\` has been removed. Use \`${t}\` instead`)}probe(e,t,...o){let n=j.getMemoryUsageMB();if(n!==null){let i=`${n}MB `;typeof t=="function"?t=()=>`${i}${t()}`:typeof t=="string"&&(t=`${i}${t}`)}return this._log("log",e,t,o,{method:Ne.log,time:!0,once:!0})}log(e,t,...o){return this._log("log",e,t,o,{method:Ne.debug})}info(e,t,...o){return this._log("info",e,t,o,{method:console.info})}once(e,t,...o){return this._log("once",e,t,o,{method:Ne.debug||Ne.info,once:!0})}table(e,t,o){return t?this._log("table",e,t,o&&[o]||[],{method:console.table||ge,tag:Oi(t)}):ge}time(e,t){return this._log("time",e,t,[],{method:console.time?console.time:console.info})}timeEnd(e,t){return this._log("time",e,t,[],{method:console.timeEnd?console.timeEnd:console.info})}timeStamp(e,t){return this._log("time",e,t,[],{method:console.timeStamp||ge})}group(e,t,o={collapsed:!1}){let n=(o.collapsed?console.groupCollapsed:console.group)||console.info;return this._log("group",e,t,[],{method:n})}groupCollapsed(e,t,o={}){return this.group(e,t,Object.assign({},o,{collapsed:!0}))}groupEnd(e){return this._log("groupEnd",e,"",[],{method:console.groupEnd||ge})}withGroup(e,t,o){this.group(e,t)();try{o()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&super._shouldLog(e)}_emit(e,t){let o=t.method;Fe(o),t.total=this.getTotal(),t.delta=this.getDelta(),this._deltaTs=j.getHighResolutionTimer();let n=ki(this.id,t.message,t);return o.bind(console,n,...t.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(Ur),this._storage.config[this.id]}_updateConfiguration(e){let t=this._storage.config[this.id]||{...Ur};this._storage.setConfiguration({[this.id]:{...t,...e}})}};ae.VERSION=Pr});var Vo=b(()=>{nt()});var Wo=b(()=>{nt()});var jo=b(()=>{st()});var Ho=b(()=>{st();globalThis.probe||(globalThis.probe=j)});var vu,qo=b(()=>{$r();st();$r();Vo();nt();Wo();Ot();Ot();Gr();Ar();Er();jo();Ho();vu=new ae({id:"@probe.gl/log"})});var Z,_r=b(()=>{"use strict";qo();Z=new ae({id:"luma.gl"})});function ze(r="id"){Rr[r]=Rr[r]||1;let e=Rr[r]++;return`${r}-${e}`}var Rr,Nt=b(()=>{"use strict";Rr={}});function ji(r,e){let t={...e};for(let o in r)r[o]!==void 0&&(t[o]=r[o]);return t}function Jo(r,e){let t=r.stats,o=!1;for(let u of e)t[u]||(r.get(u),o=!0);let n=Object.keys(t).length,i=Zo.get(r);if(!o&&i?.orderedStatNames===e&&i.statCount===n)return;let a={},s=Qo.get(e);s||(s=new Set(e),Qo.set(e,s));for(let u of e)t[u]&&(a[u]=t[u]);for(let[u,d]of Object.entries(t))s.has(u)||(a[u]=d);for(let u of Object.keys(t))delete t[u];Object.assign(t,a),Zo.set(r,{orderedStatNames:e,statCount:n})}function en(r){return r.type==="webgl"?Wi:Vi}function ut(r){let e=r.userData[Fi];return e?.enabled?e:null}function ye(){return globalThis.performance?.now?.()??Date.now()}function Hi(r,e){let t=ut(r);if(!(!t||!t.activeDefaultFramebufferAcquireDepth))switch(t.transientCanvasResourceCreates=(t.transientCanvasResourceCreates||0)+1,e){case"Texture":t.transientCanvasTextureCreates=(t.transientCanvasTextureCreates||0)+1;break;case"TextureView":t.transientCanvasTextureViewCreates=(t.transientCanvasTextureViewCreates||0)+1;break;case"Sampler":t.transientCanvasSamplerCreates=(t.transientCanvasSamplerCreates||0)+1;break;case"Framebuffer":t.transientCanvasFramebufferCreates=(t.transientCanvasFramebufferCreates||0)+1;break;default:break}}function qi(r){let e=Object.getPrototypeOf(r);for(;e;){let t=Object.getPrototypeOf(e);if(!t||t===H.prototype)return Yi(e)||r[Symbol.toStringTag]||r.constructor.name;e=t}return r[Symbol.toStringTag]||r.constructor.name}function Yi(r){let e=Object.getOwnPropertyDescriptor(r,Symbol.toStringTag);return typeof e?.get=="function"?e.get.call(r):typeof e?.value=="string"?e.value:null}var Fi,Yo,Xo,Ko,Ni,zi,Vi,Wi,Zo,Qo,H,zt=b(()=>{"use strict";Nt();Fi="cpu-hotspot-profiler",Yo="GPU Resource Counts",Xo="Resource Counts",Ko="GPU Time and Memory",Ni=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],zi=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","SharedRenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],Vi=Ni.flatMap(r=>[`${r} Created`,`${r} Active`]),Wi=zi.flatMap(r=>[`${r} Created`,`${r} Active`]),Zo=new WeakMap,Qo=new WeakMap,H=class{static defaultProps={id:"undefined",handle:void 0,_isHandleBorrowed:!1,userData:void 0};toString(){return`${this[Symbol.toStringTag]||this.constructor.name}:"${this.id}"`}toJSON(){return this.toString()}id;props;userData={};_device;destroyed=!1;allocatedBytes=0;allocatedBytesName=null;_attachedResources=new Set;get ownsHandle(){return(this.props.handle===void 0||this.props.handle===null)&&!this.isHandleBorrowed}get isHandleBorrowed(){return!!this.props._isHandleBorrowed}constructor(e,t,o){if(!e)throw new Error("no device");this._device=e,this.props=ji(t,o);let n=this.props.id!=="undefined"?this.props.id:ze(this[Symbol.toStringTag]);this.props.id=n,this.id=n,this.userData=this.props.userData||{},this.addStats()}destroy(){this.destroyed||this.destroyResource()}delete(){return this.destroy(),this}getProps(){return this.props}attachResource(e){this._attachedResources.add(e)}detachResource(e){this._attachedResources.delete(e)}destroyAttachedResource(e){this._attachedResources.delete(e)&&e.destroy()}destroyAttachedResources(){for(let e of this._attachedResources)e.destroy();this._attachedResources=new Set}destroyResource(){this.destroyed||(this.destroyAttachedResources(),this.removeStats(),this.destroyed=!0)}removeStats(){let e=ut(this._device),t=e?ye():0,o=[this._device.statsManager.getStats(Yo),this._device.statsManager.getStats(Xo)],n=en(this._device);for(let a of o)Jo(a,n);let i=this.getStatsName();for(let a of o)a.get("Resources Active").decrementCount(),a.get(`${i}s Active`).decrementCount();e&&(e.statsBookkeepingCalls=(e.statsBookkeepingCalls||0)+1,e.statsBookkeepingTimeMs=(e.statsBookkeepingTimeMs||0)+(ye()-t))}trackAllocatedMemory(e,t=this.getStatsName()){let o=ut(this._device),n=o?ye():0,i=this._device.statsManager.getStats(Ko);this.allocatedBytes>0&&this.allocatedBytesName&&(i.get("GPU Memory").subtractCount(this.allocatedBytes),i.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes)),i.get("GPU Memory").addCount(e),i.get(`${t} Memory`).addCount(e),o&&(o.statsBookkeepingCalls=(o.statsBookkeepingCalls||0)+1,o.statsBookkeepingTimeMs=(o.statsBookkeepingTimeMs||0)+(ye()-n)),this.allocatedBytes=e,this.allocatedBytesName=t}trackReferencedMemory(e,t=this.getStatsName()){this.trackAllocatedMemory(e,`External ${t}`)}trackDeallocatedMemory(e=this.getStatsName()){if(this.allocatedBytes===0){this.allocatedBytesName=null;return}let t=ut(this._device),o=t?ye():0,n=this._device.statsManager.getStats(Ko);n.get("GPU Memory").subtractCount(this.allocatedBytes),n.get(`${this.allocatedBytesName||e} Memory`).subtractCount(this.allocatedBytes),t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(ye()-o)),this.allocatedBytes=0,this.allocatedBytesName=null}trackDeallocatedReferencedMemory(e=this.getStatsName()){this.trackDeallocatedMemory(`Referenced ${e}`)}addStats(){let e=this.getStatsName(),t=ut(this._device),o=t?ye():0,n=[this._device.statsManager.getStats(Yo),this._device.statsManager.getStats(Xo)],i=en(this._device);for(let a of n)Jo(a,i);for(let a of n)a.get("Resources Created").incrementCount(),a.get("Resources Active").incrementCount(),a.get(`${e}s Created`).incrementCount(),a.get(`${e}s Active`).incrementCount();t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(ye()-o)),Hi(this._device,e)}getStatsName(){return qi(this)}}});var te,tn=b(()=>{"use strict";zt();te=class r extends H{static INDEX=16;static VERTEX=32;static UNIFORM=64;static STORAGE=128;static INDIRECT=256;static QUERY_RESOLVE=512;static MAP_READ=1;static MAP_WRITE=2;static COPY_SRC=4;static COPY_DST=8;get[Symbol.toStringTag](){return"Buffer"}usage;indexType;updateTimestamp;constructor(e,t){let o={...t};(t.usage||0)&r.INDEX&&!t.indexType&&(t.data instanceof Uint32Array?o.indexType="uint32":t.data instanceof Uint16Array?o.indexType="uint16":t.data instanceof Uint8Array&&(o.indexType="uint8")),delete o.data,super(e,o,r.defaultProps),this.usage=o.usage||0,this.indexType=o.indexType,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createBuffer({...this.props,...e})}static DEBUG_DATA_MAX_LENGTH=32;debugData=new ArrayBuffer(0);_setDebugData(e,t,o){if(!this.device.props.debug)return;let n=null,i;ArrayBuffer.isView(e)?(n=e,i=e.buffer):i=e;let a=Math.min(e?e.byteLength:o,r.DEBUG_DATA_MAX_LENGTH);if(i===null)this.debugData=new ArrayBuffer(a);else{let s=Math.min(n?.byteOffset||0,i.byteLength),u=Math.max(0,i.byteLength-s),d=Math.min(a,u);this.debugData=new Uint8Array(i,s,d).slice().buffer}}static defaultProps={...H.defaultProps,handle:void 0,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}}});function rn(){return Mr??Uint16Array}function on(r){return!!(Mr&&r===Mr)}var Mr,nn=b(()=>{"use strict";Mr=globalThis.Float16Array});function an(r){let e=r.includes("norm"),t=!e&&!r.startsWith("float"),o=r.startsWith("s"),n=kr[r],[i,a,s]=n||["uint8 ","i32",1];return{signedType:i,primitiveType:a,byteLength:s,normalized:e,integer:t,signed:o}}function sn(r){let e=r;switch(e){case"uint8":return"unorm8";case"sint8":return"snorm8";case"uint16":return"unorm16";case"sint16":return"snorm16";default:return e}}function un(r,e){switch(e){case 1:return r;case 2:return r+r%2;default:return r+(4-r%4)%4}}function Xi(r){let e=ArrayBuffer.isView(r)?r.constructor:r;if(on(e))return"float16";if(e===Uint8ClampedArray)return"uint8";let t=Object.values(kr).find(o=>e===o[4]);if(!t)throw new Error(e.name);return t[0]}function dn(r){return Xi(r)}function Ki(r){if(r==="float16")return rn();let e=kr[r];if(!e)throw new Error(r);let[,,,,t]=e;return t}function cn(r){return Ki(r)}var kr,mn=b(()=>{"use strict";nn();kr={uint8:["uint8","u32",1,!1,Uint8Array],sint8:["sint8","i32",1,!1,Int8Array],unorm8:["uint8","f32",1,!0,Uint8Array],snorm8:["sint8","f32",1,!0,Int8Array],uint16:["uint16","u32",2,!1,Uint16Array],sint16:["sint16","i32",2,!1,Int16Array],unorm16:["uint16","u32",2,!0,Uint16Array],snorm16:["sint16","i32",2,!0,Int16Array],float16:["float16","f16",2,!1,Uint16Array],float32:["float32","f32",4,!1,Float32Array],uint32:["uint32","u32",4,!1,Uint32Array],sint32:["sint32","i32",4,!1,Int32Array]}});var Or,ln,fn=b(()=>{"use strict";mn();Or=class{getDataTypeInfo(e){return an(e)}getNormalizedDataType(e){return sn(e)}alignTo(e,t){return un(e,t)}getDataType(e){return dn(e)}getTypedArrayConstructor(e){return cn(e)}},ln=new Or});function Yt(r){let e=na[r];if(!e)throw new Error(`Unsupported texture format ${r}`);return e}var _,v,re,Zi,Vt,Fr,Wt,Nr,Qi,zr,xe,Vr,Wr,jt,pn,dt,ct,qr,Yr,We,qt,gn,U,Ht,se,oe,Ji,Hr,hn,ea,F,Ve,ta,jr,ra,oa,na,yn=b(()=>{"use strict";_="texture-compression-bc",v="texture-compression-astc",re="texture-compression-etc2",Zi="texture-compression-etc1-webgl",Vt="texture-compression-pvrtc-webgl",Fr="texture-compression-atc-webgl",Wt="float32-renderable-webgl",Nr="float16-renderable-webgl",Qi="rgb9e5ufloat-renderable-webgl",zr="snorm8-renderable-webgl",xe="norm16-webgl",Vr="norm16-renderable-webgl",Wr="snorm16-renderable-webgl",jt="float32-filterable",pn="float16-filterable-webgl",dt=1,ct=2,qr=4,Yr=8,We=16,qt=5,gn=10,U=dt|ct,Ht=dt|qr,se=dt|ct|qr|Yr,oe=dt|ct|We,Ji=dt|qr|We,Hr=se|We,hn=(ct|Yr|We)<<qt,ea=(ct|Yr)<<qt,F=We<<qt,Ve=Hr<<qt,ta=se<<gn,jr=We<<gn;ra={r8unorm:{webgpu:se|F},rg8unorm:{webgpu:se|F},"rgb8unorm-webgl":{},rgba8unorm:{webgpu:Hr},"rgba8unorm-srgb":{webgpu:se},r8snorm:{render:zr,webgpu:Ht|hn},rg8snorm:{render:zr,webgpu:Ht|hn},"rgb8snorm-webgl":{},rgba8snorm:{render:zr,webgpu:Ji|ea},r8uint:{webgpu:U|F},rg8uint:{webgpu:U|F},rgba8uint:{webgpu:oe},r8sint:{webgpu:U|F},rg8sint:{webgpu:U|F},rgba8sint:{webgpu:oe},bgra8unorm:{webgpu:se},"bgra8unorm-srgb":{webgpu:ta},r16unorm:{f:xe,render:Vr,webgpu:Ve},rg16unorm:{f:xe,render:Vr,webgpu:Ve},"rgb16unorm-webgl":{f:xe,render:!1},rgba16unorm:{f:xe,render:Vr,webgpu:Ve},r16snorm:{f:xe,render:Wr,webgpu:Ve},rg16snorm:{f:xe,render:Wr,webgpu:Ve},"rgb16snorm-webgl":{f:xe,render:!1},rgba16snorm:{f:xe,render:Wr,webgpu:Ve},r16uint:{webgpu:U|F},rg16uint:{webgpu:U|F},rgba16uint:{webgpu:oe},r16sint:{webgpu:U|F},rg16sint:{webgpu:U|F},rgba16sint:{webgpu:oe},r16float:{render:Nr,filter:"float16-filterable-webgl",webgpu:se|F},rg16float:{render:Nr,filter:pn,webgpu:se|F},rgba16float:{render:Nr,filter:pn,webgpu:Hr},r32uint:{webgpu:oe},rg32uint:{webgpu:U|jr},rgba32uint:{webgpu:oe},r32sint:{webgpu:oe},rg32sint:{webgpu:U|jr},rgba32sint:{webgpu:oe},r32float:{render:Wt,filter:jt,webgpu:oe},rg32float:{render:!1,filter:jt,webgpu:U|jr},"rgb32float-webgl":{render:Wt,filter:jt},rgba32float:{render:Wt,filter:jt,webgpu:oe},"rgba4unorm-webgl":{channels:"rgba",bitsPerChannel:[4,4,4,4],packed:!0},"rgb565unorm-webgl":{channels:"rgb",bitsPerChannel:[5,6,5,0],packed:!0},"rgb5a1unorm-webgl":{channels:"rgba",bitsPerChannel:[5,5,5,1],packed:!0},rgb9e5ufloat:{channels:"rgb",packed:!0,render:Qi,webgpu:Ht},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:Wt,webgpu:Ht|F},rgb10a2unorm:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:se|F},rgb10a2uint:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:U|F},stencil8:{attachment:"stencil",bitsPerChannel:[8,0,0,0],dataType:"uint8",webgpu:U},depth16unorm:{attachment:"depth",bitsPerChannel:[16,0,0,0],dataType:"uint16",webgpu:U},depth24plus:{attachment:"depth",bitsPerChannel:[24,0,0,0],dataType:"uint32",webgpu:U},depth32float:{attachment:"depth",bitsPerChannel:[32,0,0,0],dataType:"float32",webgpu:U},"depth24plus-stencil8":{attachment:"depth-stencil",bitsPerChannel:[24,8,0,0],packed:!0,webgpu:U},"depth32float-stencil8":{attachment:"depth-stencil",bitsPerChannel:[32,8,0,0],packed:!0,f:"depth32float-stencil8",webgpu:U}},oa={"bc1-rgb-unorm-webgl":{f:_},"bc1-rgb-unorm-srgb-webgl":{f:_},"bc1-rgba-unorm":{f:_},"bc1-rgba-unorm-srgb":{f:_},"bc2-rgba-unorm":{f:_},"bc2-rgba-unorm-srgb":{f:_},"bc3-rgba-unorm":{f:_},"bc3-rgba-unorm-srgb":{f:_},"bc4-r-unorm":{f:_},"bc4-r-snorm":{f:_},"bc5-rg-unorm":{f:_},"bc5-rg-snorm":{f:_},"bc6h-rgb-ufloat":{f:_},"bc6h-rgb-float":{f:_},"bc7-rgba-unorm":{f:_},"bc7-rgba-unorm-srgb":{f:_},"etc2-rgb8unorm":{f:re},"etc2-rgb8unorm-srgb":{f:re},"etc2-rgb8a1unorm":{f:re},"etc2-rgb8a1unorm-srgb":{f:re},"etc2-rgba8unorm":{f:re},"etc2-rgba8unorm-srgb":{f:re},"eac-r11unorm":{f:re},"eac-r11snorm":{f:re},"eac-rg11unorm":{f:re},"eac-rg11snorm":{f:re},"astc-4x4-unorm":{f:v},"astc-4x4-unorm-srgb":{f:v},"astc-5x4-unorm":{f:v},"astc-5x4-unorm-srgb":{f:v},"astc-5x5-unorm":{f:v},"astc-5x5-unorm-srgb":{f:v},"astc-6x5-unorm":{f:v},"astc-6x5-unorm-srgb":{f:v},"astc-6x6-unorm":{f:v},"astc-6x6-unorm-srgb":{f:v},"astc-8x5-unorm":{f:v},"astc-8x5-unorm-srgb":{f:v},"astc-8x6-unorm":{f:v},"astc-8x6-unorm-srgb":{f:v},"astc-8x8-unorm":{f:v},"astc-8x8-unorm-srgb":{f:v},"astc-10x5-unorm":{f:v},"astc-10x5-unorm-srgb":{f:v},"astc-10x6-unorm":{f:v},"astc-10x6-unorm-srgb":{f:v},"astc-10x8-unorm":{f:v},"astc-10x8-unorm-srgb":{f:v},"astc-10x10-unorm":{f:v},"astc-10x10-unorm-srgb":{f:v},"astc-12x10-unorm":{f:v},"astc-12x10-unorm-srgb":{f:v},"astc-12x12-unorm":{f:v},"astc-12x12-unorm-srgb":{f:v},"pvrtc-rgb4unorm-webgl":{f:Vt},"pvrtc-rgba4unorm-webgl":{f:Vt},"pvrtc-rgb2unorm-webgl":{f:Vt},"pvrtc-rgba2unorm-webgl":{f:Vt},"etc1-rbg-unorm-webgl":{f:Zi},"atc-rgb-unorm-webgl":{f:Fr},"atc-rgba-unorm-webgl":{f:Fr},"atc-rgbai-unorm-webgl":{f:Fr}},na={...ra,...oa}});function ca({format:r,width:e,height:t,depth:o,byteAlignment:n}){let i=Le.getInfo(r),{bytesPerPixel:a,bytesPerBlock:s=a,blockWidth:u=1,blockHeight:d=1,compressed:c=!1}=i,m=c?Math.ceil(e/u):e,l=c?Math.ceil(t/d):t,f=m*s,h=Math.ceil(f/n)*n,y=l,w=h*y*o;return{bytesPerPixel:a,bytesPerRow:h,rowsPerImage:y,depthOrArrayLayers:o,bytesPerImage:h*y,byteLength:w}}function ma(r){let e=Yt(r),t={format:r,create:e.f??!0,render:e.render??!0,filter:e.filter??!0,blend:e.blend??!0,store:e.store??!0},o=xn(r),n=r.startsWith("depth")||r.startsWith("stencil"),i=o?.signed,a=o?.integer,s=o?.webgl,u=!!o?.compressed;return t.render&&=!n&&!u,t.filter&&=!n&&!i&&!a&&!s,t}function xn(r){let e=la(r);if(Le.isCompressed(r)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0,e.bytesPerBlock=pa(r);let o=fa(r);o&&(e.blockWidth=o.blockWidth,e.blockHeight=o.blockHeight)}let t=e.packed?null:ia.exec(r);if(t){let[,o,n,i,a,s]=t,u=`${i}${n}`,d=ln.getDataTypeInfo(u),c=d.byteLength*8,m=o?.length??1,l=[c,m>=2?c:0,m>=3?c:0,m>=4?c:0];e={format:r,attachment:e.attachment,dataType:d.signedType,components:m,channels:o,integer:d.integer,signed:d.signed,normalized:d.normalized,bitsPerChannel:l,bytesPerPixel:d.byteLength*m,packed:e.packed,srgb:e.srgb},s==="-webgl"&&(e.webgl=!0),a==="-srgb"&&(e.srgb=!0)}return r.endsWith("-webgl")&&(e.webgl=!0),r.endsWith("-srgb")&&(e.srgb=!0),e}function la(r){let e={...Yt(r)},t=e.bytesPerPixel||1,o=e.bitsPerChannel||[8,8,8,8];return delete e.bitsPerChannel,delete e.bytesPerPixel,delete e.f,delete e.render,delete e.filter,delete e.blend,delete e.store,delete e.webgpu,{...e,format:r,attachment:e.attachment||"color",channels:e.channels||"r",components:e.components||e.channels?.length||1,bytesPerPixel:t,bitsPerChannel:o,dataType:e.dataType||"uint8",srgb:e.srgb??!1,packed:e.packed??!1,webgl:e.webgl??!1,integer:e.integer??!1,signed:e.signed??!1,normalized:e.normalized??!1,compressed:e.compressed??!1}}function fa(r){let t=/.*-(\d+)x(\d+)-.*/.exec(r);if(t){let[,o,n]=t;return{blockWidth:Number(o),blockHeight:Number(n)}}return r.startsWith("bc")||r.startsWith("etc1")||r.startsWith("etc2")||r.startsWith("eac")||r.startsWith("atc")?{blockWidth:4,blockHeight:4}:r.startsWith("pvrtc-rgb4")||r.startsWith("pvrtc-rgba4")?{blockWidth:4,blockHeight:4}:r.startsWith("pvrtc-rgb2")||r.startsWith("pvrtc-rgba2")?{blockWidth:8,blockHeight:4}:null}function pa(r){return r.startsWith("bc1")||r.startsWith("bc4")||r.startsWith("etc1")||r.startsWith("etc2-rgb8")||r.startsWith("etc2-rgb8a1")||r.startsWith("eac-r11")||r==="atc-rgb-unorm-webgl"?8:r.startsWith("bc2")||r.startsWith("bc3")||r.startsWith("bc5")||r.startsWith("bc6h")||r.startsWith("bc7")||r.startsWith("etc2-rgba8")||r.startsWith("eac-rg11")||r.startsWith("astc")||r==="atc-rgba-unorm-webgl"||r==="atc-rgbai-unorm-webgl"?16:r.startsWith("pvrtc")?8:16}var ia,aa,sa,ua,da,Xr,Le,bn=b(()=>{"use strict";fn();yn();ia=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,aa=["rgb","rgba","bgra"],sa=["depth","stencil"],ua=5,da=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"],Xr=class{isColor(e){return aa.some(t=>e.startsWith(t))}isDepthStencil(e){return sa.some(t=>e.startsWith(t))}isCompressed(e){return da.some(t=>e.startsWith(t))}getInfo(e){return xn(e)}getCapabilities(e){return ma(e)}getWebGPUCapabilities(e){let t=Yt(e);return t.webgpu!==void 0?t.webgpu:this.isCompressed(e)&&!e.endsWith("-webgl")?ua:0}computeMemoryLayout(e){return ca(e)}},Le=new Xr});function mt(r){return typeof ImageData<"u"&&r instanceof ImageData||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement||typeof VideoFrame<"u"&&r instanceof VideoFrame||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas}function Xt(r){if(typeof ImageData<"u"&&r instanceof ImageData||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas)return{width:r.width,height:r.height};if(typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement)return{width:r.naturalWidth,height:r.naturalHeight};if(typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement)return{width:r.videoWidth,height:r.videoHeight};if(typeof VideoFrame<"u"&&r instanceof VideoFrame)return{width:r.displayWidth,height:r.displayHeight};throw new Error("Unknown image type")}var wn=b(()=>{"use strict"});var be,Kr=b(()=>{"use strict";zt();be=class r extends H{static defaultProps={...H.defaultProps,type:"color-sampler",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge",magFilter:"nearest",minFilter:"nearest",mipmapFilter:"none",lodMinClamp:0,lodMaxClamp:32,compare:"less-equal",maxAnisotropy:1};get[Symbol.toStringTag](){return"Sampler"}constructor(e,t){t=r.normalizeProps(e,t),super(e,t,r.defaultProps)}static normalizeProps(e,t){return t}}});var ha,R,Tn=b(()=>{"use strict";zt();Kr();_r();bn();ha={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"},R=class r extends H{static SAMPLE=4;static STORAGE=8;static RENDER=16;static COPY_SRC=1;static COPY_DST=2;static TEXTURE=4;static RENDER_ATTACHMENT=16;dimension;baseDimension;format;width;height;depth;mipLevels;samples;byteAlignment;ready=Promise.resolve(this);isReady=!0;updateTimestamp;get[Symbol.toStringTag](){return"Texture"}toString(){return`Texture(${this.id},${this.format},${this.width}x${this.height})`}constructor(e,t,o){if(t=r.normalizeProps(e,t),super(e,t,r.defaultProps),this.dimension=this.props.dimension,this.baseDimension=ha[this.dimension],this.format=this.props.format,this.width=this.props.width,this.height=this.props.height,this.depth=this.props.depth,this.mipLevels=this.props.mipLevels,this.samples=this.props.samples||1,this.dimension==="cube"&&(this.depth=6),this.props.width===void 0||this.props.height===void 0)if(e.isExternalImage(t.data)){let n=e.getExternalImageSize(t.data);this.width=n?.width||1,this.height=n?.height||1}else this.width=1,this.height=1,(this.props.width===void 0||this.props.height===void 0)&&Z.warn(`${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`)();this.byteAlignment=o?.byteAlignment||1,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createTexture({...this.props,...e})}setSampler(e){this.sampler=e instanceof be?e:this.device.createSampler(e)}copyImageData(e){let{data:t,depth:o,...n}=e;this.writeData(t,{...n,depthOrArrayLayers:n.depthOrArrayLayers??o})}computeMemoryLayout(e={}){let t=this._normalizeTextureReadOptions(e),{width:o=this.width,height:n=this.height,depthOrArrayLayers:i=this.depth}=t,{format:a,byteAlignment:s}=this;return Le.computeMemoryLayout({format:a,width:o,height:n,depth:i,byteAlignment:s})}readBuffer(e,t){throw new Error("readBuffer not implemented")}readDataAsync(e){throw new Error("readBuffer not implemented")}writeBuffer(e,t){throw new Error("readBuffer not implemented")}writeData(e,t){throw new Error("readBuffer not implemented")}readDataSyncWebGL(e){throw new Error("readDataSyncWebGL not available")}generateMipmapsWebGL(){throw new Error("generateMipmapsWebGL not available")}static normalizeProps(e,t){let o={...t},{width:n,height:i}=o;return typeof n=="number"&&(o.width=Math.max(1,Math.ceil(n))),typeof i=="number"&&(o.height=Math.max(1,Math.ceil(i))),o}_initializeData(e){this.device.isExternalImage(e)?this.copyExternalImage({image:e,width:this.width,height:this.height,depth:this.depth,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1}):e&&this.copyImageData({data:e,mipLevel:0,x:0,y:0,z:0,aspect:"all"})}_normalizeCopyImageDataOptions(e){let{data:t,depth:o,...n}=e,i=this._normalizeTextureWriteOptions({...n,depthOrArrayLayers:n.depthOrArrayLayers??o});return{data:t,depth:i.depthOrArrayLayers,...i}}_normalizeCopyExternalImageOptions(e){let t=r._omitUndefined(e),o=t.mipLevel??0,n=this._getMipLevelSize(o),i=this.device.getExternalImageSize(e.image),a={...r.defaultCopyExternalImageOptions,...n,...i,...t};return a.width=Math.min(a.width,n.width-a.x),a.height=Math.min(a.height,n.height-a.y),a.depth=Math.min(a.depth,n.depthOrArrayLayers-a.z),a}_normalizeCopyElementImageOptions(e){let t=r._omitUndefined(e),o=t.mipLevel??0,n=this._getMipLevelSize(o),i={...r.defaultCopyElementImageOptions,...n,...t};return i.width=Math.min(i.width,n.width-i.x),i.height=Math.min(i.height,n.height-i.y),i.depth=Math.min(i.depth,n.depthOrArrayLayers-i.z),i}_normalizeTextureReadOptions(e){let t=r._omitUndefined(e),o=t.mipLevel??0,n=this._getMipLevelSize(o),i={...r.defaultTextureReadOptions,...n,...t};return i.width=Math.min(i.width,n.width-i.x),i.height=Math.min(i.height,n.height-i.y),i.depthOrArrayLayers=Math.min(i.depthOrArrayLayers,n.depthOrArrayLayers-i.z),i}_getSupportedColorReadOptions(e){let t=this._normalizeTextureReadOptions(e),o=Le.getInfo(this.format);switch(this._validateColorReadAspect(t),this._validateColorReadFormat(o),this.dimension){case"2d":case"cube":case"cube-array":case"2d-array":case"3d":return t;default:throw new Error(`${this} color readback does not support ${this.dimension} textures`)}}_validateColorReadAspect(e){if(e.aspect!=="all")throw new Error(`${this} color readback only supports aspect 'all'`)}_validateColorReadFormat(e){if(e.compressed)throw new Error(`${this} color readback does not support compressed formats (${this.format})`);switch(e.attachment){case"color":return;case"depth":throw new Error(`${this} color readback does not support depth formats (${this.format})`);case"stencil":throw new Error(`${this} color readback does not support stencil formats (${this.format})`);case"depth-stencil":throw new Error(`${this} color readback does not support depth-stencil formats (${this.format})`);default:throw new Error(`${this} color readback does not support format ${this.format}`)}}_normalizeTextureWriteOptions(e){let t=r._omitUndefined(e),o=t.mipLevel??0,n=this._getMipLevelSize(o),i={...r.defaultTextureWriteOptions,...n,...t};i.width=Math.min(i.width,n.width-i.x),i.height=Math.min(i.height,n.height-i.y),i.depthOrArrayLayers=Math.min(i.depthOrArrayLayers,n.depthOrArrayLayers-i.z);let a=Le.computeMemoryLayout({format:this.format,width:i.width,height:i.height,depth:i.depthOrArrayLayers,byteAlignment:this.byteAlignment}),s=a.bytesPerPixel*i.width;if(i.bytesPerRow=t.bytesPerRow??a.bytesPerRow,i.rowsPerImage=t.rowsPerImage??i.height,i.bytesPerRow<s)throw new Error(`bytesPerRow (${i.bytesPerRow}) must be at least ${s} for ${this.format}`);if(i.rowsPerImage<i.height)throw new Error(`rowsPerImage (${i.rowsPerImage}) must be at least ${i.height} for ${this.format}`);let u=this.device.getTextureFormatInfo(this.format).bytesPerPixel;if(u&&i.bytesPerRow%u!==0)throw new Error(`bytesPerRow (${i.bytesPerRow}) must be a multiple of bytesPerPixel (${u}) for ${this.format}`);return i}_getMipLevelSize(e){let t=Math.max(1,this.width>>e),o=this.baseDimension==="1d"?1:Math.max(1,this.height>>e),n=this.dimension==="3d"?Math.max(1,this.depth>>e):this.depth;return{width:t,height:o,depthOrArrayLayers:n}}getAllocatedByteLength(){let e=0;for(let t=0;t<this.mipLevels;t++){let{width:o,height:n,depthOrArrayLayers:i}=this._getMipLevelSize(t);e+=Le.computeMemoryLayout({format:this.format,width:o,height:n,depth:i,byteAlignment:1}).byteLength}return e*this.samples}static _omitUndefined(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}static defaultProps={...H.defaultProps,data:null,dimension:"2d",format:"rgba8unorm",usage:r.SAMPLE|r.RENDER|r.COPY_DST,width:void 0,height:void 0,depth:1,mipLevels:1,samples:void 0,sampler:{},view:void 0};static defaultCopyDataOptions={data:void 0,byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,width:void 0,height:void 0,depthOrArrayLayers:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all"};static defaultCopyExternalImageOptions={image:void 0,sourceX:0,sourceY:0,width:void 0,height:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultCopyElementImageOptions={element:void 0,width:void 0,height:void 0,sourceX:0,sourceY:0,sourceWidth:void 0,sourceHeight:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultTextureReadOptions={x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"};static defaultTextureWriteOptions={byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"}}});var lt=b(()=>{"use strict";tn();Tn();Kr();_r()});var vn=b(()=>{"use strict";wn()});var Kt=b(()=>{"use strict";lt();lt();lt();vn();lt()});var ga,Ge,Cn=b(()=>{"use strict";Kt();Nt();ga=te.DEBUG_DATA_MAX_LENGTH,Ge=class{device;id;ready;usage;props;isReady=!0;destroyed=!1;generation=0;updateTimestamp;debugData=new ArrayBuffer(0);_debugDataEnabled;_maxDebugDataByteLength;_ownsBuffer;_buffer;get buffer(){return this._buffer}get byteLength(){return this._buffer.byteLength}get[Symbol.toStringTag](){return"DynamicBuffer"}toString(){return`DynamicBuffer:"${this.id}":${this.byteLength}B`}toJSON(){return this.toString()}constructor(e,t){let{debugData:o=!1,buffer:n,ownsBuffer:i=!0,...a}=t;if(n&&n.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(n&&(a.byteLength!==void 0||a.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let s=t.id||n?.id||ze("dynamic-buffer"),u={...a,id:s,usage:a.usage??n?.usage,indexType:a.indexType??n?.indexType};(u.usage||0)&te.INDEX&&!u.indexType&&(a.data instanceof Uint32Array?u.indexType="uint32":a.data instanceof Uint16Array?u.indexType="uint16":a.data instanceof Uint8Array&&(u.indexType="uint8")),delete u.data,delete u.byteOffset,this.device=e,this.id=s,this.props=u,this.usage=u.usage||0,this._debugDataEnabled=!!o,this._maxDebugDataByteLength=typeof o=="object"&&o.maxByteLength!==void 0?o.maxByteLength:ga,this._ownsBuffer=i,this._buffer=n??this.device.createBuffer({...a,id:s}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),a.data&&this._writeDebugData(a.data,a.byteOffset||0)}write(e,t=0){this._buffer.write(e,t),this._touch(),this._writeDebugData(e,t)}async mapAndWriteAsync(e,t=0,o=this.byteLength-t){let n=null;await this._buffer.mapAndWriteAsync(async(i,a)=>{await e(i,a),n=new Uint8Array(i.slice(0,o))},t,o),this._touch(),n&&this._writeDebugData(n,t)}async readAsync(e=0,t=this.byteLength-e){let o=await this._buffer.readAsync(e,t);return this._writeDebugData(o,e)&&this._touch(),o}async mapAndReadAsync(e,t=0,o=this.byteLength-t){let n=null,i=await this._buffer.mapAndReadAsync(async(a,s)=>(n=new Uint8Array(a.slice(0)),await e(a,s)),t,o);return n&&this._writeDebugData(n,t)&&this._touch(),i}resize(e){let{byteLength:t,preserveData:o=!1}=e;if(t===this.byteLength)return!1;let n=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),i=this._buffer,a=this.debugData.slice(0),{data:s,byteOffset:u,...d}=this.props,c=this.device.createBuffer({...d,byteLength:t});return o&&n>0&&this._copyBufferContents(i,c,n),this._buffer=c,this._resetDebugData(t),o&&a.byteLength>0&&this._writeDebugData(a,0),this._ownsBuffer&&i.destroy(),this._ownsBuffer=!0,this.generation++,this._touch(),!0}ensureSize(e,t){return e<=this.byteLength?!1:this.resize({byteLength:e,preserveData:t?.preserveData})}getBinding(e){return e?.offset===void 0&&e?.size===void 0?this._buffer:{buffer:this._buffer,offset:e?.offset,size:e?.size}}destroy(){this.destroyed||(this._ownsBuffer&&this._buffer.destroy(),this.destroyed=!0,this.debugData=new ArrayBuffer(0))}_copyBufferContents(e,t,o){let n=this.device.type==="webgpu"?Math.ceil(o/4)*4:o,i=this.device.createCommandEncoder();i.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:n}),this.device.submit(i.finish())}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_resetDebugData(e){if(!this._debugDataEnabled){this.debugData=new ArrayBuffer(0);return}this.debugData=new ArrayBuffer(Math.min(e,this._maxDebugDataByteLength))}_writeDebugData(e,t){if(!this._debugDataEnabled||this.debugData.byteLength===0||t>=this.debugData.byteLength)return!1;let o=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),n=new Uint8Array(this.debugData),i=Math.min(o.byteLength,n.byteLength-t);return n.set(o.subarray(0,i),t),i>0}}});function ft(r){return r?Array.isArray(r)?r[0]??null:r:null}function Pn(r){let{dimension:e,data:t}=r;if(!t)return null;switch(e){case"1d":{let o=ft(t);if(!o)return null;let{width:n}=pt(o);return{width:n,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let o=ft(t);return o?pt(o):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let o=ft(t[0]);return o?pt(o):null}case"cube":{let o=Object.keys(t)[0]??null;if(!o)return null;let n=t[o],i=ft(n);return i?pt(i):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let o=t[0],n=Object.keys(o)[0]??null;if(!n)return null;let i=ft(o[n]);return i?pt(i):null}default:return null}}function pt(r){if(mt(r))return Xt(r);if(typeof r=="object"&&"width"in r&&"height"in r)return{width:r.width,height:r.height};throw new Error("Unsupported mip-level data")}function ya(r){return typeof r=="object"&&r!==null&&"data"in r&&"width"in r&&"height"in r}function xa(r){return ArrayBuffer.isView(r)}function Qr(r){let{textureFormat:e,format:t}=r;if(e&&t&&e!==t)throw new Error(`Conflicting texture formats "${e}" and "${t}" provided for the same mip level`);return e??t}function Sn(r){let e=Zr[r];if(e===void 0)throw new Error(`Invalid cube face: ${r}`);return e}function ba(r,e){return 6*r+Sn(e)}function Jr(r){throw new Error("setTexture1DData not supported in WebGL.")}function wa(r){return Array.isArray(r)?r:[r]}function De(r,e,t,o){let n=wa(e),i=r,a=[];for(let s=0;s<n.length;s++){let u=n[s];if(mt(u))a.push({type:"external-image",image:u,z:i,mipLevel:s});else if(ya(u))a.push({type:"texture-data",data:u,textureFormat:Qr(u),z:i,mipLevel:s});else if(xa(u)&&t)a.push({type:"texture-data",data:{data:u,width:Math.max(1,t.width>>s),height:Math.max(1,t.height>>s),...o?{format:o}:{}},textureFormat:o,z:i,mipLevel:s});else throw new Error("Unsupported 2D mip-level payload")}return a}function eo(r){let e=[];for(let t=0;t<r.length;t++)e.push(...De(t,r[t]));return e}function to(r){let e=[];for(let t=0;t<r.length;t++)e.push(...De(t,r[t]));return e}function ro(r){let e=[];for(let[t,o]of Object.entries(r)){let n=Sn(t);e.push(...De(n,o))}return e}function oo(r){let e=[];return r.forEach((t,o)=>{for(let[n,i]of Object.entries(t)){let a=ba(o,n);e.push(...De(a,i))}}),e}var Zr,no=b(()=>{"use strict";Kt();Zr={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5}});function Ta(r){if(!r.data)return[];let e=r.width&&r.height?{width:r.width,height:r.height}:void 0,t="format"in r?r.format:void 0;switch(r.dimension){case"1d":return Jr(r.data);case"2d":return De(0,r.data,e,t);case"3d":return eo(r.data);case"2d-array":return to(r.data);case"cube":return ro(r.data);case"cube-array":return oo(r.data);default:throw new Error(`Unhandled dimension ${r.dimension}`)}}function va(r,e,t,o){if(e.length===0)return{subresources:e,mipLevels:1,format:o.format,hasExplicitMipChain:!1};let n=new Map;for(let c of e){let m=n.get(c.z)??[];m.push(c),n.set(c.z,m)}let i=e.some(c=>c.mipLevel>0),a=o.format,s=Number.POSITIVE_INFINITY,u=[];for(let[c,m]of n){let l=[...m].sort((L,P)=>L.mipLevel-P.mipLevel),f=l[0];if(!f||f.mipLevel!==0)throw new Error(`DynamicTexture: slice ${c} is missing mip level 0`);let h=En(r,f);if(h.width!==t.width||h.height!==t.height)throw new Error(`DynamicTexture: slice ${c} base level dimensions ${h.width}x${h.height} do not match expected ${t.width}x${t.height}`);let y=Bn(f);if(y){if(a&&a!==y)throw new Error(`DynamicTexture: slice ${c} base level format "${y}" does not match texture format "${a}"`);a=y}let w=a&&r.isTextureFormatCompressed(a)?Ca(r,h.width,h.height,a):r.getMipLevelCount(h.width,h.height),I=0;for(let L=0;L<l.length;L++){let P=l[L];if(!P||P.mipLevel!==L||L>=w)break;let W=En(r,P),g=Math.max(1,h.width>>L),p=Math.max(1,h.height>>L);if(W.width!==g||W.height!==p)break;let T=Bn(P);if(T&&(a||(a=T),T!==a))break;I++,u.push(P)}s=Math.min(s,I)}let d=Number.isFinite(s)?Math.max(1,s):1;return{subresources:u.filter(c=>c.mipLevel<d),mipLevels:d,format:a,hasExplicitMipChain:i}}function Bn(r){if(r.type==="texture-data")return r.textureFormat??Qr(r.data)}function En(r,e){switch(e.type){case"external-image":return r.getExternalImageSize(e.image);case"texture-data":return{width:e.data.width,height:e.data.height};default:throw new Error("Unsupported texture subresource")}}function Ca(r,e,t,o){let{blockWidth:n=1,blockHeight:i=1}=r.getTextureFormatInfo(o),a=1;for(let s=1;;s++){let u=Math.max(1,e>>s),d=Math.max(1,t>>s);if(u<n||d<i)break;a++}return a}async function io(r){if(r=await r,Array.isArray(r))return await Promise.all(r.map(io));if(r&&typeof r=="object"&&r.constructor===Object){let e=r,t=await Promise.all(Object.values(e).map(io)),o=Object.keys(e),n={};for(let i=0;i<o.length;i++)n[o[i]]=t[i];return n}return r}var Zt,Ln=b(()=>{"use strict";Kt();Nt();no();Zt=class r{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;generation=0;updateTimestamp;resolveReady=()=>{};rejectReady=()=>{};get texture(){if(!this._texture)throw new Error("Texture not initialized yet");return this._texture}get sampler(){if(!this._sampler)throw new Error("Sampler not initialized yet");return this._sampler}get view(){if(!this._view)throw new Error("View not initialized yet");return this._view}get[Symbol.toStringTag](){return"DynamicTexture"}toString(){let e=this._texture?.width??this.props.width??"?",t=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${t}px:(${this.isReady?"ready":"loading..."})`}resolveTextureBinding(e){return this.isReady?this.texture:null}constructor(e,t){this.device=e;let o=ze("dynamic-texture"),n=t;this.props={...r.defaultProps,id:o,...t,data:null},this.id=this.props.id,this.ready=new Promise((i,a)=>{this.resolveReady=i,this.rejectReady=a}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(n)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let o=t.data?Ta({...t,width:e.width,height:e.height,format:e.format}):[],n="format"in e&&e.format!==void 0,i="usage"in e&&e.usage!==void 0,s=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let y=Pn(t);return y||{width:this.props.width||1,height:this.props.height||1}})();if(!s||s.width<=0||s.height<=0)throw new Error(`${this} size could not be determined or was zero`);let u=va(this.device,o,s,{format:n?e.format:void 0}),d=u.format??this.props.format,c={...this.props,...s,format:d,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(d)&&!i&&(c.usage=R.SAMPLE|R.COPY_DST);let m=this.props.mipmaps&&!u.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(d);if(this.device.type==="webgpu"&&m){let y=this.props.dimension==="3d"?R.SAMPLE|R.STORAGE|R.COPY_DST|R.COPY_SRC:R.SAMPLE|R.RENDER|R.COPY_DST|R.COPY_SRC;c.usage|=y}let l=this.device.getMipLevelCount(c.width,c.height),f=u.hasExplicitMipChain?u.mipLevels:this.props.mipLevels==="auto"?l:Math.max(1,Math.min(l,this.props.mipLevels??1)),h={...c,mipLevels:f};this._texture=this.device.createTexture(h),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),u.subresources.length&&this._setTextureSubresources(u.subresources),this.props.mipmaps&&!u.hasExplicitMipChain&&!m&&Z.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),m&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),Z.info(1,`${this} created`)()}catch(t){let o=t instanceof Error?t:new Error(String(t));this.rejectReady(o)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.isReady=!1,this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?(this.texture.generateMipmapsWebGL(),this._touch()):this.device.type==="webgpu"?(this.device.generateMipmapsWebGPU(this.texture),this._touch()):Z.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof be?e:this.device.createSampler(e);this.texture.setSampler(t),this._sampler=t,this._touchGeneration()}async readBuffer(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,o=e.height??this.texture.height,n=e.depthOrArrayLayers??this.texture.depth,i=this.texture.computeMemoryLayout({width:t,height:o,depthOrArrayLayers:n}),a=this.device.createBuffer({byteLength:i.byteLength,usage:te.COPY_DST|te.MAP_READ});this.texture.readBuffer({...e,width:t,height:o,depthOrArrayLayers:n},a);let s=this.device.createFence();return await s.signaled,s.destroy(),a}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,o=e.height??this.texture.height,n=e.depthOrArrayLayers??this.texture.depth,i=this.texture.computeMemoryLayout({width:t,height:o,depthOrArrayLayers:n}),a=await this.readBuffer(e),s=await a.readAsync(0,i.byteLength);return a.destroy(),s.buffer instanceof ArrayBuffer?s.buffer:s.slice().buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;let t=this.texture;return this._texture=t.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,t.destroy(),this._touchGeneration(),Z.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=Zr[e];if(t===void 0)throw new Error(`Invalid cube face: ${e}`);return t}getCubeArrayFaceIndex(e,t){return 6*e+this.getCubeFaceIndex(t)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let t=Jr(e);this._setTextureSubresources(t)}setTexture2DData(e,t=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let o=De(t,e);this._setTextureSubresources(o)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=eo(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=to(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=ro(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=oo(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:o,mipLevel:n}=t;switch(t.type){case"external-image":let{image:i,flipY:a}=t;this.texture.copyExternalImage({image:i,z:o,mipLevel:n,flipY:a});break;case"texture-data":let{data:s,textureFormat:u}=t;if(u&&u!==this.texture.format)throw new Error(`${this} mip level ${n} uses format "${u}" but texture format is "${this.texture.format}"`);this.texture.writeData(s.data,{x:0,y:0,z:o,width:s.width,height:s.height,depthOrArrayLayers:1,mipLevel:n});break;default:throw new Error("Unsupported 2D mip-level payload")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await io(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&Z.warn(`${this} already destroyed`)}_checkReady(){this.isReady||Z.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...R.defaultProps,dimension:"2d",data:null,mipmaps:!1}}});var Gn=b(()=>{"use strict"});var Dn=b(()=>{"use strict";Cn();Ln();no();Gn()});function we(r){return In.test(r)}function Te(r){return An.test(r)}function Un(r){let e=In.exec(r),t=An.exec(r),n=$n(r)?.elementFormat??e?.[1]??t?.[1]??r;try{ht.vertexFormatDecoder.getVertexFormatInfo(n)}catch{throw new Error(`Unsupported GPUVector format ${r}`)}return n}function N(r){let e=Un(r),t=we(r),o=Te(r),n=$n(r),i=ht.vertexFormatDecoder.getVertexFormatInfo(e),a=i.byteLength*(n?.listSize??1);if(!Number.isSafeInteger(a))throw new Error(`Unsupported GPUVector format ${r}`);let s=i.type,u=i.normalized,d=Sa(s,u);return{format:r,elementFormat:e,vertexList:t,valueList:o,fixedSizeList:!!n,...n?{listSize:n.listSize}:{},type:s,signedDataType:Ba(e,s),primitiveType:d,components:i.components,elementByteLength:i.byteLength,byteLength:a,integer:i.integer,signed:i.signed,normalized:u,...i.webglOnly?{webglOnly:!0}:{}}}function $n(r){let e=Pa.exec(r);if(!e)return;let t=Number(e[2]);if(!Number.isSafeInteger(t))return;let o=e[1];try{let n=ht.vertexFormatDecoder.getVertexFormatInfo(o);if(!Number.isSafeInteger(t*n.components)||!Number.isSafeInteger(t*n.byteLength))return}catch{return}return{elementFormat:o,listSize:t}}function Sa(r,e){if(e)return"f32";switch(r){case"float32":return"f32";case"float16":return"f16";case"uint8":case"uint16":case"uint32":return"u32";case"sint8":case"sint16":case"sint32":return"i32";default:throw new Error(`Unsupported GPUVector component type ${r}`)}}function Ba(r,e){if(r==="unorm10-10-10-2")return"uint32";switch(e){case"unorm8":return"uint8";case"snorm8":return"sint8";case"unorm16":return"uint16";case"snorm16":return"sint16";default:return e}}var ht,In,An,Pa,_n=b(()=>{"use strict";ht=ee(K(),1),In=/^vertex-list<([^<>]+)>$/,An=/^value-list<([^<>]+)>$/,Pa=/^fixed-size-list<([^<>,]+),([1-9][0-9]*)>$/});function Ie(r){let e=0;return Object.freeze(r.map(t=>{let o=Object.freeze({offset:e,length:t.length,data:t});return e+=t.length,o}))}var Rn=b(()=>{"use strict"});var ao,Ae=b(()=>{"use strict";_n();ao=ee(K(),1);Rn()});var me,A,ai=b(()=>{"use strict";me=ee(K(),1),A=class r{static async createAsync(e,t){let o=!me.PipelineFactory.getAsyncCompilation(e),n=o?me.PipelineFactory.beginAsyncCompilation(e):me.PipelineFactory.getAsyncCompilation(e),i;try{i=new r(e,t)}finally{o&&me.PipelineFactory.endAsyncCompilation(e,n)}try{return o?await Promise.all(n):await i._pipelineInitialization,i}catch(a){throw i.destroy(),a}}device;id;source;pipelineFactory;shaderFactory;shader;pipeline;_pipelineInitialization;_destroyed=!1;constructor(e,t){if(e.type!=="webgpu")throw new Error("Kernel is only supported in WebGPU");let{source:o,pipelineFactory:n,shaderFactory:i,debugShaders:a,...s}=t;this.device=e,this.id=t.id??"kernel",this.source=o,this.pipelineFactory=n??me.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=i??me.ShaderFactory.getDefaultShaderFactory(e),this.shader=this.shaderFactory.createShader({id:`${this.id}-compute`,stage:"compute",source:this.source,debugShaders:a});let u={...s,shader:this.shader},d=me.PipelineFactory.getAsyncCompilation(e);if(d){let c=this.pipelineFactory.createComputePipelineAsync(u);this._pipelineInitialization=c,d.push(c.then(m=>(this.pipeline=m,m)))}else this.pipeline=this.pipelineFactory.createComputePipeline(u)}dispatch(e,t){this._setPipeline(e,t.bindings),e.dispatch(t.x,t.y,t.z)}dispatchIndirect(e,t){this._setPipeline(e,t.bindings),e.dispatchIndirect(t.indirectBuffer,t.indirectOffset??0)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.shader),this._destroyed=!0)}_setPipeline(e,t={}){e.setPipeline(this.pipeline),e.setBindings(t)}}});var le=b(()=>{"use strict";ai()});var Lt={};Di(Lt,{CompiledGPUCommandGraph:()=>qe,GPUCommandGraph:()=>He,GPUCommandGraphAutotuner:()=>Eo,GPUCommandGraphEncoding:()=>Ct,GPUCommandGraphExecution:()=>vt,GPUCommandGraphExecutionBudgetController:()=>Lo,GPUCommandGraphInspector:()=>Go,GPUGraph:()=>Jt,GPUGraphCompiler:()=>yr,GPUGraphScalar:()=>Ye,GPUGraphTexture:()=>Ke,GPUGraphTextureView:()=>ce,GPUGraphVector:()=>Xe,GPUOperationLoweringRegistry:()=>rt,GraphBufferHandle:()=>Ce,GraphDataView:()=>de,GraphExternalTextureHandle:()=>$e,GraphTextureHandle:()=>ne,GraphTextureView:()=>Pe,GraphVectorView:()=>B,composite:()=>oi,getGPUCommandGraphAdapterIdentity:()=>ms,getGPUCommandGraphExecutionPlan:()=>go,inspectGPUGraphCompilation:()=>hi,validateGPUGraph:()=>gr});At(Lt,ee(K(),1));var Be=ee(K(),1);async function ko(r,e){if(r.destroyed)throw new Error("Resource has been destroyed.");if(r instanceof Be.Buffer){if(!(r.usage&Be.Buffer.COPY_SRC))throw new Error("Preview requires COPY_SRC usage.");let d=e.byteOffset??0,c=Math.min(256,e.byteLength??r.byteLength-d);if(d<0||c<0||d+c>r.byteLength)throw new Error("Preview range is outside the buffer.");return{data:c?await r.readAsync(d,c):new Uint8Array,format:e.format}}let t=r.device.getTextureFormatInfo(r.format);if(t.packed)throw new Error("Packed texture previews are not supported.");if(r.device.type!=="webgpu")throw new Error("Texture previews require WebGPU.");if(!((r.props.usage??0)&Be.Texture.COPY_SRC))throw new Error("Preview requires COPY_SRC usage.");if(r.samples!==1||t.compressed||r.format.startsWith("depth")||r.format.startsWith("stencil"))throw new Error("Preview requires a single-sample, uncompressed color texture.");let o=e.baseMipLevel??0,n=Math.min(32,e.width??Math.max(1,r.width>>o)),i=Math.min(32,e.height??Math.max(1,r.height>>o)),a=r.computeMemoryLayout({width:n,height:i,depthOrArrayLayers:1}),s=r.device.createBuffer({byteLength:a.byteLength,usage:Be.Buffer.MAP_READ|Be.Buffer.COPY_DST}),u=r.device.createCommandEncoder();try{u.copyTextureToBuffer({sourceTexture:r,destinationBuffer:s,mipLevel:o,origin:[0,0,e.baseArrayLayer??0],width:n,height:i,depthOrArrayLayers:1,bytesPerRow:a.bytesPerRow}),r.device.submit(u.finish());let d=await s.readAsync(),c=n*t.bytesPerPixel,m=new Uint8Array(c*i);for(let l=0;l<i;l++)m.set(d.subarray(l*a.bytesPerRow,l*a.bytesPerRow+c),l*c);return{data:m,width:n,height:i,format:r.format}}finally{s.destroy(),u.destroy()}}var z=ee(K(),1);Dn();Ae();var gt=class{compare;values=[];constructor(e){this.compare=e}peek(){return this.values[0]}push(e){let t=this.values.length;for(this.values.push(e);t>0;){let o=Math.floor((t-1)/2);if(this.compare(this.values[o],e)<=0)break;this.values[t]=this.values[o],t=o}this.values[t]=e}pop(){let e=this.values[0],t=this.values.pop();if(this.values.length&&t!==void 0){let o=0;for(;o*2+1<this.values.length;){let n=o*2+1;if(n+1<this.values.length&&this.compare(this.values[n+1],this.values[n])<0&&n++,this.compare(t,this.values[n])<=0)break;this.values[o]=this.values[n],o=n}this.values[o]=t}return e}};var yt=ee(K(),1);function Nn(r){let e=jn(r.nodes),t=Hn(e,r.buffers.values()),o=qn(e,r.textures.values()),n=new Map,i=new Map,a=[];try{for(let s of t){s.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(s)}`,byteLength:s.byteLength,usage:s.usage});for(let u of s.handles)n.set(u,s.buffer)}for(let s of o){s.texture=r.device.createTexture({...s.descriptor,id:`${r.id}-transient-texture-${o.indexOf(s)}`});for(let u of s.handles)i.set(u,s.texture)}for(let s of e)a.push({node:s,executable:s.compile({device:r.device})})}catch(s){for(let u of a)u.executable.destroy?.();for(let u of t)u.buffer?.destroy();for(let u of o)u.texture?.destroy();throw s}return Vn(r,e,a,n,i,t,o)}async function zn(r){let e=jn(r.nodes),t=Hn(e,r.buffers.values()),o=qn(e,r.textures.values()),n=new Map,i=new Map;try{for(let f of t){f.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(f)}`,byteLength:f.byteLength,usage:f.usage});for(let h of f.handles)n.set(h,f.buffer)}for(let f of o){f.texture=r.device.createTexture({...f.descriptor,id:`${r.id}-transient-texture-${o.indexOf(f)}`});for(let h of f.handles)i.set(h,f.texture)}let a=yt.PipelineFactory.beginAsyncCompilation(r.device),s=e.map(async f=>({node:f,executable:f.compileAsync?await f.compileAsync({device:r.device}):f.compile({device:r.device})}));yt.PipelineFactory.endAsyncCompilation(r.device,a);let[u,d]=await Promise.all([Promise.allSettled(s),Promise.allSettled(a)]),c=[],m=d.find(f=>f.status==="rejected"),l=m?.status==="rejected"?m.reason:void 0;for(let f of u)f.status==="fulfilled"?c.push(f.value):l??=f.reason;if(l){for(let f of c)f.executable.destroy?.();throw l}return Vn(r,e,c,n,i,t,o)}catch(a){for(let s of t)s.buffer?.destroy();for(let s of o)s.texture?.destroy();throw a}}function Vn(r,e,t,o,n,i,a){let s=Array.from(r.buffers.values()),u=s.filter(x=>!x.transient),d=s.filter(x=>x.transient),c=je(u.map(x=>x.byteLength),"imported buffer capacities"),m=je(d.map(x=>x.byteLength),"logical transient buffer capacities"),l=Ue(c,m,"logical buffer capacities"),f=je(i.map(x=>x.byteLength),"physical transient buffer capacities"),h=Math.max(0,m-f),y=Array.from(r.textures.values()),w=y.filter(x=>!x.transient),I=y.filter(x=>x.transient),L=je(w.map(mo),"imported texture estimates"),P=je(I.map(mo),"logical transient texture estimates"),W=Ue(L,P,"logical texture estimates"),g=je(a.map(x=>x.byteLength),"physical transient texture estimates"),p=Math.max(0,P-g),T={nodeOrder:e.map(x=>x.id),importedBufferCount:u.length,importedBufferBytes:c,logicalBufferCount:s.length,logicalBufferBytes:l,logicalTransientBufferCount:d.length,physicalTransientBufferCount:i.length,logicalTransientBytes:m,physicalTransientBytes:f,reusedTransientBytes:h,reusePercentage:m>0?h/m*100:0,importedTextureCount:w.length,importedTextureBytes:L,logicalTextureCount:y.length,logicalTextureBytes:W,logicalTransientTextureCount:I.length,physicalTransientTextureCount:a.length,logicalTransientTextureBytes:P,physicalTransientTextureBytes:g,reusedTransientTextureBytes:p,textureReusePercentage:P>0?p/P*100:0,logicalResourceBytes:Ue(l,W,"logical resource estimates"),physicalTransientResourceBytes:Ue(f,g,"physical transient resource estimates")},C=La(r.device,s,e);return{device:r.device,id:r.id,buffers:new Map(r.buffers),textures:new Map(r.textures),externalTextures:new Map(r.externalTextures),compiledNodes:t,transientBuffers:o,transientTextures:n,bufferTransientAllocations:i,textureTransientAllocations:a,stats:T,preflight:C}}function Ea(r){if("buffer"in r){let t=r.buffer,o="buffer"in t?t:void 0;return Object.freeze({id:o?o.buffer.id:t.id,kind:"buffer",usage:r.usage,byteOffset:o?.byteOffset??0,byteLength:o?o.length===0?0:(o.length-1)*o.byteStride+o.rowByteLength:t.byteLength,...o?{format:o.format,length:o.length}:{}})}let e="texture"in r?r.texture:r.externalTexture;return Object.freeze({id:"texture"in e?e.texture.id:e.id,kind:"externalTexture"in r?"external-texture":"texture",usage:r.usage,width:e.width,height:e.height,..."texture"in e?{baseMipLevel:e.baseMipLevel,baseArrayLayer:e.baseArrayLayer,mipLevelCount:e.mipLevelCount,arrayLayerCount:e.arrayLayerCount,aspect:e.aspect}:{},..."format"in e?{format:e.format,depth:e.depth}:{}})}function La(r,e,t){let o=t.map(s=>{let u=s.workload??{};return Object.freeze({id:s.id,...s.description===void 0?{}:{description:s.description},type:s.type,resources:Object.freeze((s.resources??[]).map(Ea)),...u.operation?{operation:u.operation}:{},...u.variant?{variant:u.variant}:{},...s.publication?{publication:Object.freeze({...s.publication})}:{},...s.condition?{condition:Object.freeze(s.condition.source==="cpu"?{id:s.condition.id,source:"cpu",mode:"skip"}:{id:s.condition.id,source:"gpu",mode:"indirect",bufferId:s.condition.buffer.id,byteOffset:s.condition.byteOffset??0})}:{},commandCount:u.commandCount??0,maximumWorkgroupCount:u.maximumWorkgroupCount??0,maximumInvocationCount:u.maximumInvocationCount??0,readByteLength:u.readByteLength??0,writeByteLength:u.writeByteLength??0})}),n=e.reduce((s,u)=>Math.max(s,u.byteLength),0),i=t.reduce((s,u)=>{for(let d of u.resources??[])ve(d)&&(d.usage==="storage-read"||d.usage==="storage-write"||d.usage==="storage-read-write")&&(s=Math.max(s,uo(d.buffer).size));return s},0),a=s=>o.reduce((u,d)=>{let c=d[s];return typeof c=="number"?Ue(u,c,"workload estimates"):u},0);return Object.freeze({nodes:Object.freeze(o),annotatedNodeCount:t.filter(s=>s.workload!==void 0).length,conditionalNodeCount:t.filter(s=>s.condition!==void 0).length,commandCount:a("commandCount"),maximumWorkgroupCount:a("maximumWorkgroupCount"),maximumInvocationCount:a("maximumInvocationCount"),readByteLength:a("readByteLength"),writeByteLength:a("writeByteLength"),largestBufferByteLength:n,largestStorageBufferBindingByteLength:i,maxBufferByteLength:r.limits.maxBufferSize,maxStorageBufferBindingByteLength:r.limits.maxStorageBufferBindingSize,fitsDeviceLimits:n<=r.limits.maxBufferSize&&i<=r.limits.maxStorageBufferBindingSize})}function Q(r){return"buffer"in r?r.buffer:r}function ue(r){return"texture"in r?r.texture:r}function ve(r){return"buffer"in r}function xt(r){return"texture"in r}function Wn(r){if(r.type==="copy")return;let e=(r.resources??[]).filter(t=>ve(t)&&(t.usage==="storage-read"||t.usage==="storage-write"||t.usage==="storage-read-write"));for(let t=0;t<e.length;t++){let o=e[t];for(let n=t+1;n<e.length;n++){let i=e[n];if(o.buffer===i.buffer||Q(o.buffer)!==Q(i.buffer)||!co(o.usage)&&!co(i.usage))continue;let a=uo(o.buffer),s=uo(i.buffer);if(a.offset<s.offset+s.size&&s.offset<a.offset+a.size){let u=Q(o.buffer);throw new Error(`GPUCommandGraph node "${r.id}" has overlapping writable storage bindings for buffer "${u.id}" (${Mn(a)} and ${Mn(s)}). Bind the shared range once or align the views to non-overlapping storage binding ranges.`)}}}}function uo(r){if(!("buffer"in r))return{offset:0,size:r.byteLength};let e=256,t=Math.floor(r.byteOffset/e)*e,o=r.byteOffset-t,n=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:t,size:o+Math.max(n,r.rowByteLength)}}function Mn(r){return`${r.offset}\u2013${r.offset+r.size} bytes`}function Ga(r){return r==="storage-read"||r==="storage-read-write"||r==="uniform"||r==="copy-source"||r==="indirect"||r==="vertex"||r==="index"}function co(r){return r==="storage-write"||r==="storage-read-write"||r==="copy-destination"}function kn(r){return r==="sampled"||r==="storage-read"||r==="storage-read-write"||r==="render-attachment"||r==="copy-source"}function so(r){return r==="storage-write"||r==="storage-read-write"||r==="render-attachment"||r==="copy-destination"}function jn(r){let e=new Map(r.map(m=>[m.id,m])),t=new Map,o=new Map,n=new Map,i=new Map;for(let m of r){let l=new Set(m.dependsOn??[]);for(let f of l)if(!e.has(f))throw new Error(`GPUCommandGraph node "${m.id}" depends on missing node "${f}"`);for(let f of m.resources??[])if(ve(f)){let h=Q(f.buffer);if(Ga(f.usage)){let y=o.get(h);y&&l.add(y);let w=n.get(h)??new Set;w.add(m.id),n.set(h,w)}if(co(f.usage)){let y=o.get(h);y&&l.add(y);for(let w of n.get(h)??[])w!==m.id&&l.add(w);n.set(h,new Set),o.set(h,m.id)}}else if(xt(f)){let h=ue(f.texture),y=i.get(h)??[];for(let w of y)w.nodeId!==m.id&&Da(w.resource,f)&&(kn(f.usage)&&so(w.resource.usage)||so(f.usage)&&(kn(w.resource.usage)||so(w.resource.usage)))&&l.add(w.nodeId);y.push({nodeId:m.id,resource:f}),i.set(h,y)}l.delete(m.id),t.set(m.id,l)}let a=r.map(()=>[]),s=new Map(r.map((m,l)=>[m.id,l])),u=r.map(m=>t.get(m.id).size);for(let[m,l]of r.entries())for(let f of t.get(l.id))a[s.get(f)].push(m);let d=u.flatMap((m,l)=>m===0?[l]:[]),c=[];for(;d.length;){let m=[];for(let l of d){c.push(r[l]);for(let f of a[l])--u[f]===0&&m.push(f)}d=m.sort((l,f)=>l-f)}if(c.length!==r.length)throw new Error("GPUCommandGraph contains a dependency cycle");return c}function Da(r,e){let t=ue(r.texture),o=ue(e.texture);if(t!==o)return!1;let n=On(r.texture),i=On(e.texture);return Ia(n.aspect,i.aspect)&&Fn(n.baseMipLevel,n.mipLevelCount,i.baseMipLevel,i.mipLevelCount)&&Fn(n.baseArrayLayer,n.arrayLayerCount,i.baseArrayLayer,i.arrayLayerCount)}function On(r){return"texture"in r?r:{aspect:"all",baseMipLevel:0,mipLevelCount:r.mipLevels,baseArrayLayer:0,arrayLayerCount:r.dimension==="3d"?1:r.depth}}function Ia(r,e){return r==="all"||e==="all"||r===e}function Fn(r,e,t,o){return r<t+o&&t<r+e}function Hn(r,e){let t=Yn(r,s=>ve(s)?Q(s.buffer):null),o=[],n=Array.from(e).filter(s=>s.transient).map(s=>({buffer:s,lifetime:t.get(s)})).sort((s,u)=>(s.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(u.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)),i=new gt((s,u)=>s.allocation.lastUse-u.allocation.lastUse||s.index-u.index),a=new gt((s,u)=>s.allocation.byteLength-u.allocation.byteLength||s.index-u.index);for(let{buffer:s,lifetime:u}of n){if(!u)continue;for(;i.peek()&&i.peek().allocation.lastUse<u.firstUse;)a.push(i.pop());let d=a.pop();d||(d={allocation:{byteLength:0,usage:0,lastUse:-1,handles:[]},index:o.length},o.push(d.allocation));let{allocation:c}=d;c.byteLength=Math.max(c.byteLength,s.byteLength),c.usage|=s.usage,c.lastUse=u.lastUse,c.handles.push(s),i.push(d)}return o}function qn(r,e){let t=Yn(r,i=>xt(i)?ue(i.texture):null),o=[],n=Array.from(e).filter(i=>i.transient).map(i=>({texture:i,lifetime:t.get(i)})).sort((i,a)=>(i.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(a.lifetime?.firstUse??Number.MAX_SAFE_INTEGER));for(let{texture:i,lifetime:a}of n){if(!a)continue;let s=o.find(u=>u.lastUse<a.firstUse&&Ua(u.descriptor,i));s||(s={descriptor:Aa(i),byteLength:mo(i),lastUse:-1,handles:[]},o.push(s)),s.descriptor.usage|=i.usage,s.lastUse=a.lastUse,s.handles.push(i)}return o}function Yn(r,e){let t=new Map;return r.forEach((o,n)=>{for(let i of o.resources??[]){let a=e(i);if(!a||!("transient"in a)||!a.transient)continue;let s=t.get(a);s?s.lastUse=n:t.set(a,{firstUse:n,lastUse:n})}}),t}function Aa(r){return{id:r.id,format:r.format,width:r.width,height:r.height,usage:r.usage,dimension:r.dimension,depth:r.depth,mipLevels:r.mipLevels,samples:r.samples}}function Ua(r,e){return r.format===e.format&&r.width===e.width&&r.height===e.height&&r.dimension===e.dimension&&r.depth===e.depth&&r.mipLevels===e.mipLevels&&r.samples===e.samples}function mo(r){let e=0;for(let o=0;o<r.mipLevels;o++)e=Ue(e,yt.textureFormatDecoder.computeMemoryLayout({format:r.format,width:Math.max(1,r.width>>o),height:r.dimension==="1d"?1:Math.max(1,r.height>>o),depth:r.dimension==="3d"?Math.max(1,r.depth>>o):r.depth,byteAlignment:1}).byteLength,`texture "${r.id}" mip estimates`);let t=e*r.samples;if(!Number.isSafeInteger(t))throw new Error(`GPUCommandGraph texture "${r.id}" byte estimate exceeds safe integer range`);return t}function Ue(r,e,t){let o=r+e;if(!Number.isSafeInteger(o))throw new Error(`GPUCommandGraph ${t} exceed safe integer range`);return o}function je(r,e){return r.reduce((t,o)=>Ue(t,o,e),0)}Ae();var Ce=class{id;byteLength;usage;transient;graph;defaultBuffer;constructor(e,t,o,n){this.graph=e,this.id=t.id,this.byteLength=t.byteLength,this.usage=t.usage,this.transient=o,this.defaultBuffer=n}},de=class{buffer;format;length;byteOffset;byteStride;rowByteLength;constructor(e,t){this.buffer=e,this.format=t.format,this.length=t.length,this.byteOffset=t.byteOffset,this.byteStride=t.byteStride,this.rowByteLength=t.rowByteLength}},B=class{chunks;id;name;format;length;valueLength;stride;byteStride;rowByteLength;data;constructor(e){if(this.id=e.id,this.name=e.name,this.format=e.format,this.length=e.length,this.valueLength=e.valueLength,this.stride=e.stride,this.byteStride=e.byteStride,this.rowByteLength=e.rowByteLength,e.data.some(t=>t.format!==e.format)||e.data.reduce((t,o)=>t+o.length,0)!==e.length)throw new Error(`${e.id} length must equal its ordered source chunks, with matching formats`);this.data=Object.freeze([...e.data]),this.chunks=Ie(this.data)}},ne=class{id;format;width;height;usage;dimension;depth;mipLevels;samples;transient;frameScoped;graph;defaultTexture;constructor(e,t,o,n,i=!1){this.graph=e,this.id=t.id,this.format=t.format,this.width=t.width,this.height=t.height,this.usage=t.usage,this.dimension=t.dimension,this.depth=t.depth,this.mipLevels=t.mipLevels,this.samples=t.samples,this.transient=o,this.frameScoped=i,this.defaultTexture=n}},$e=class{id;width;height;graph;constructor(e,t){this.graph=e,this.id=t.id,this.width=t.width,this.height=t.height}},Pe=class{texture;format;dimension;aspect;baseMipLevel;mipLevelCount;baseArrayLayer;arrayLayerCount;width;height;depth;constructor(e,t){this.texture=e,this.format=e.format,this.dimension=t.dimension,this.aspect=t.aspect,this.baseMipLevel=t.baseMipLevel,this.mipLevelCount=t.mipLevelCount,this.baseArrayLayer=t.baseArrayLayer,this.arrayLayerCount=t.arrayLayerCount,this.width=t.width,this.height=t.height,this.depth=t.depth}};function lo(r,e){switch(e.type){case"compute":{let{type:t,...o}=e;r.addComputePass(o);return}case"render":{let{type:t,...o}=e;r.addRenderPass(o);return}case"copy":{let{type:t,...o}=e;r.addCopyPass(o);return}}}function _e(r,e){for(let t of e)lo(r,t)}function M(r){return{...r,type:"compute"}}var $a=4,vt=class{nodeCount;budget;plan;encodeNodeRange;nextStepIndex=0;currentPublishedProgress=0;constructor(e){ei(e.budget),this.plan=e.plan,this.nodeCount=e.plan.nodeCount,this.budget=Object.freeze({...e.budget}),this.encodeNodeRange=e.encodeNodeRange}get completed(){return this.nextStepIndex>=this.plan.stepCount}get progress(){return this.plan.stepCount===0?1:this.nextStepIndex/this.plan.stepCount}get publishedProgress(){return this.currentPublishedProgress}encodeNext(e,t){if(this.completed)throw new Error("GPUCommandGraph execution has already completed");let o=this.plan.steps[this.nextStepIndex],n=this.encodeNodeRange(e,t,o.firstNodeIndex,o.nextNodeIndex);return this.nextStepIndex++,o.publishable&&(this.currentPublishedProgress=this.progress),{...o,encoding:n,progress:this.progress,completed:this.completed,publishedProgress:this.publishedProgress}}};function go(r,e,t={}){ei(e);let o=t.latencyPriority??"normal",n=t.publicationPolicy??"final";if(!["interactive","normal","background"].includes(o))throw new Error(`GPUCommandGraph execution latency priority "${o}" is invalid`);if(!["final","progressive"].includes(n))throw new Error(`GPUCommandGraph execution publication policy "${n}" is invalid`);let i=r.nodes,a=[],s=0;for(;s<i.length;){let d=s,c=Xn();for(;s<i.length;){let f=Kn(c,i[s]);if(s>d&&Zn(f,e)||(c=f,s++,n==="progressive"&&i[s-1].publication)||_a(c,e))break}let m=Object.freeze(n==="progressive"?i.slice(d,s).flatMap(f=>f.publication?[f.publication]:[]):[]),l=s===i.length;a.push(Object.freeze({stepIndex:a.length,firstNodeIndex:d,nextNodeIndex:s,...c,exceedsBudget:Zn(c,e),latencyPriority:o,publications:m,publishable:l||m.length>0}))}let u=i.reduce((d,c)=>Kn(d,c),Xn());return Object.freeze({...u,annotatedNodeCount:r.annotatedNodeCount,stepCount:a.length,oversizedStepCount:a.filter(d=>d.exceedsBudget).length,latencyPriority:o,publicationPolicy:n,publicationCount:a.reduce((d,c)=>d+c.publications.length,0),steps:Object.freeze(a)})}function Xn(){return{nodeCount:0,commandCount:0,maximumInvocationCount:0,readByteLength:0,writeByteLength:0,conditionalNodeCount:0}}function Kn(r,e){return{nodeCount:r.nodeCount+1,commandCount:r.commandCount+e.commandCount,maximumInvocationCount:r.maximumInvocationCount+e.maximumInvocationCount,readByteLength:r.readByteLength+e.readByteLength,writeByteLength:r.writeByteLength+e.writeByteLength,conditionalNodeCount:r.conditionalNodeCount+(e.condition?1:0)}}function Zn(r,e){return r.maximumInvocationCount>e.maximumInvocationCount||e.maximumNodeCount!==void 0&&r.nodeCount>e.maximumNodeCount||e.maximumCommandCount!==void 0&&r.commandCount>e.maximumCommandCount||e.maximumReadByteLength!==void 0&&r.readByteLength>e.maximumReadByteLength||e.maximumWriteByteLength!==void 0&&r.writeByteLength>e.maximumWriteByteLength}function _a(r,e){return r.maximumInvocationCount>=e.maximumInvocationCount||e.maximumNodeCount!==void 0&&r.nodeCount>=e.maximumNodeCount||e.maximumCommandCount!==void 0&&r.commandCount>=e.maximumCommandCount||e.maximumReadByteLength!==void 0&&r.readByteLength>=e.maximumReadByteLength||e.maximumWriteByteLength!==void 0&&r.writeByteLength>=e.maximumWriteByteLength}function ei(r){let e=[["maximumInvocationCount",r.maximumInvocationCount],["maximumNodeCount",r.maximumNodeCount],["maximumCommandCount",r.maximumCommandCount],["maximumReadByteLength",r.maximumReadByteLength],["maximumWriteByteLength",r.maximumWriteByteLength]];for(let[t,o]of e)if(o!==void 0&&(!Number.isSafeInteger(o)||o<=0))throw new Error(`GPUCommandGraph execution ${t} must be a positive safe integer`)}function Ra(r,e,t,o){let n=0;return{computePass:new Proxy(r,{get(a,s){if(s==="dispatch")return()=>{if(n>0)throw new Error(`GPUCommandGraph GPU-conditional compute node "${o}" must encode exactly one dispatch`);n++,a.dispatchIndirect(e,t)};if(s==="dispatchIndirect")return()=>{throw new Error(`GPUCommandGraph GPU-conditional compute node "${o}" must use dispatch(); the graph supplies its indirect command`)};let u=Reflect.get(a,s,a);return typeof u=="function"?u.bind(a):u}}),assertDispatched:()=>{if(n!==1)throw new Error(`GPUCommandGraph GPU-conditional compute node "${o}" must encode exactly one dispatch`)}}}var Ct=class{readResource;stats;canReadGPUTimings;nodes;constructor(e,t,o=e.filter(s=>s.stats.type==="compute"&&s.stats.condition?.outcome!=="skipped").length,n,i,a){this.readResource=a,this.nodes=e,this.canReadGPUTimings=e.some(d=>d.timestamp!==void 0);let s=e.filter(d=>d.stats.condition?.outcome!=="skipped"),u=s.filter(d=>d.stats.type==="compute").length;this.stats={cpuEncodeTimeMilliseconds:t,cpuEncodeStartTimeMilliseconds:n,cpuEncodeEndTimeMilliseconds:i,nodeCount:s.length,skippedNodeCount:e.length-s.length,computePassCount:o,coalescedComputeNodeCount:u-o,timestampedNodeCount:e.filter(d=>d.timestamp!==void 0).length,nodes:e.map(d=>d.stats)}}async readTimings(){let e=await Promise.all(this.nodes.map(async({stats:a,timestamp:s})=>{if(!s)return{...a};let{querySet:u,snapshot:d,beginIndex:c,endIndex:m}=s;if(u.device.type!=="webgpu")return{...a,gpuTimeMilliseconds:await u.readTimestampDuration(c,m)};let l=await(d??u).readResults({firstQuery:c,queryCount:m-c+1}),f=l[0],h=l[l.length-1];return{...a,gpuStartTimeMilliseconds:Number(f)/1e6,gpuEndTimeMilliseconds:Number(h)/1e6,gpuTimeMilliseconds:Number(h-f)/1e6}})),t=e.filter(a=>a.gpuTimeMilliseconds!==void 0),o=e.filter(a=>a.gpuStartTimeMilliseconds!==void 0),i=this.nodes.flatMap(a=>a.timestamp?.snapshot?.clockCorrelation?[a.timestamp.snapshot.clockCorrelation]:[]).sort((a,s)=>a.uncertaintyMilliseconds-s.uncertaintyMilliseconds)[0];return{...i?{clockCorrelation:i}:{},cpuEncodeStartTimeMilliseconds:this.stats.cpuEncodeStartTimeMilliseconds,cpuEncodeEndTimeMilliseconds:this.stats.cpuEncodeEndTimeMilliseconds,...o.length>0?{gpuStartTimeMilliseconds:Math.min(...o.map(a=>a.gpuStartTimeMilliseconds)),gpuEndTimeMilliseconds:Math.max(...o.map(a=>a.gpuEndTimeMilliseconds))}:{},cpuEncodeTimeMilliseconds:this.stats.cpuEncodeTimeMilliseconds,...t.length>0?{gpuTimeMilliseconds:t.reduce((a,s)=>a+(s.gpuTimeMilliseconds??0),0)}:{},nodes:e}}},He=class{device;id;autotuner;buffers=new Map;textures=new Map;externalTextures=new Map;importedBufferHandles=new Map;dynamicBufferHandles=new Map;nodes=[];nodeIds=new Set;compiled=!1;constructor(e,t={}){if(e.type!=="webgpu")throw new Error("GPUCommandGraph requires a WebGPU device");Qt(e,"construction"),this.device=e,this.id=t.id??"gpu-command-graph",this.autotuner=t.autotuner}importBuffer(e,t){this.assertMutable(),Jn(e,this.device),t&&ti(t,e,this.device);let o=this.addBuffer(new Ce(this,e,!1,t));if(t){let n=Tt(t);this.importedBufferHandles.has(n)||this.importedBufferHandles.set(n,o),t instanceof Ge&&!this.dynamicBufferHandles.has(t)&&this.dynamicBufferHandles.set(t,o)}return o}createTransientBuffer(e){return this.assertMutable(),Jn(e,this.device),this.addBuffer(new Ce(this,e,!0))}createDataView(e,t){this.assertBuffer(e);let o=N(t.format),n=t.byteOffset??0,i=t.rowByteLength??o.byteLength,a=t.byteStride??i;return za(e,{length:t.length,byteOffset:n,byteStride:a,rowByteLength:i}),new de(e,{format:t.format,length:t.length,byteOffset:n,byteStride:a,rowByteLength:i})}importGPUData(e,t){return this.importGPUDataView(e,t)}importGPUVector(e,t){if(t.bufferLayout)throw new Error(`GPUCommandGraph import "${e}" does not accept interleaved GPUVector data`);let o=t.format??t.data[0]?.format;if(!o)throw new Error(`GPUCommandGraph import "${e}" requires GPUVector.format`);if(we(o)||Te(o))throw new Error(`GPUCommandGraph import "${e}" requires a fixed-width GPUVector format`);let n=N(o),i=t.data.map((a,s)=>{if(a.format!==o)throw new Error(`GPUCommandGraph import "${e}" requires matching GPUVector chunk formats`);let u=t.data.length===1?e:`${e}-chunk-${s}`;return this.importGPUDataView(u,a)});return new B({id:e,name:t.name??e,format:o,length:t.length,valueLength:t.valueLength??t.data.reduce((a,s)=>a+s.valueLength,0),stride:t.stride??t.data[0]?.stride??n.components*(n.listSize??1),byteStride:t.byteStride??i[0]?.byteStride??n.byteLength,rowByteLength:t.rowByteLength??i[0]?.rowByteLength??n.byteLength,data:i})}importTexture(e,t){this.assertMutable();let o=fo(e,this.device);return t&&ho(t,o,this.device),this.addTexture(new ne(this,o,!1,t))}importFrameTexture(e){this.assertMutable();let t=fo(e,this.device);return this.addTexture(new ne(this,t,!1,void 0,!0))}importExternalTexture(e){return this.assertMutable(),Fa(e,this.device),this.addExternalTexture(new $e(this,e))}createTransientTexture(e){this.assertMutable();let t=fo(e,this.device);return this.addTexture(new ne(this,t,!0))}createTextureView(e,t={}){this.assertTexture(e);let o=Na(e,t);return new Pe(e,o)}add(e){if(this.assertMutable(),"getNodes"in e)for(let t of e.getNodes())this.add(t);else if("getCommandNodes"in e)_e(this,e.getCommandNodes(this));else if("type"in e)lo(this,e);else for(let t of e)this.add(t)}addComputePass(e){this.addNode({...e,type:"compute"})}addRenderPass(e){e.attachments&&this.validateRenderAttachments(e.id,e.attachments);let t=e.attachments?[...e.attachments.colorAttachments.map(o=>({texture:o,usage:"render-attachment"})),...(e.attachments.resolveTargets??[]).filter(o=>o!==null).map(o=>({texture:o,usage:"render-attachment"})),...e.attachments.depthStencilAttachment?[{texture:e.attachments.depthStencilAttachment,usage:"render-attachment"}]:[]]:[];this.addNode({...e,resources:[...e.resources??[],...t],type:"render"})}addCopyPass(e){this.addNode({...e,type:"copy"})}compile(){return this.assertMutable(),Qt(this.device,"compilation"),this.compiled=!0,new qe(Nn({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes}))}async compileAsync(){return this.assertMutable(),Qt(this.device,"compilation"),this.compiled=!0,new qe(await zn({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes}))}addNode(e){if(this.assertMutable(),!e.id)throw new Error("GPUCommandGraph node id is required");if(this.nodeIds.has(e.id))throw new Error(`GPUCommandGraph node id "${e.id}" is already in use`);for(let[t,o]of Object.entries(e.workload??{}))if(t==="operation"||t==="variant"){if(typeof o!="string"||!o)throw new Error(`GPUCommandGraph node "${e.id}" workload ${t} must be nonempty`)}else if(typeof o!="number"||!Number.isSafeInteger(o)||o<0)throw new Error(`GPUCommandGraph node "${e.id}" workload ${t} must be a nonnegative safe integer`);if(e.condition){if(!e.condition.id)throw new Error(`GPUCommandGraph node "${e.id}" condition id is required`);if(e.condition.source==="cpu"){if(typeof e.condition.evaluate!="function")throw new Error(`GPUCommandGraph node "${e.id}" CPU condition requires an evaluate function`)}else{let t=e.condition;if(e.type!=="compute"||t.mode!=="indirect")throw new Error(`GPUCommandGraph node "${e.id}" GPU conditions require an indirect compute node`);if(!t.buffer)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition requires an indirect command buffer`);this.assertBuffer(t.buffer);let o=t.byteOffset??0;if(!Number.isSafeInteger(o)||o<0||o%4!==0)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition byteOffset must be a nonnegative multiple of 4`);if(o+3*$a>t.buffer.byteLength)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition indirect command exceeds buffer "${t.buffer.id}"`);(e.resources??[]).some(n=>ve(n)&&Q(n.buffer)===t.buffer&&n.usage==="indirect")||(e={...e,resources:[...e.resources??[],{buffer:t.buffer,usage:"indirect"}]})}}if(e.publication){if(e.condition)throw new Error(`GPUCommandGraph node "${e.id}" cannot combine conditional execution with a publication boundary`);if(!e.publication.id)throw new Error(`GPUCommandGraph node "${e.id}" publication id is required`);if(!["partial","complete"].includes(e.publication.completeness))throw new Error(`GPUCommandGraph node "${e.id}" publication completeness is invalid`)}for(let t of e.resources??[])if(ve(t)){let o=Q(t.buffer);this.assertBuffer(o),Wa(o,t.usage)}else if(xt(t)){let o=ue(t.texture);this.assertTexture(o),ja(o,t.usage),Ha(t.texture,t.usage)}else{if(this.assertExternalTexture(t.externalTexture),t.usage!=="sampled")throw new Error("GPUCommandGraph external textures support sampled access only");if(e.type!=="render")throw new Error("GPUCommandGraph external textures can be sampled only by render nodes")}Wn(e),this.nodeIds.add(e.id),this.nodes.push(e)}addBuffer(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.buffers.set(e.id,e),e}addTexture(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.textures.set(e.id,e),e}addExternalTexture(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.externalTextures.set(e.id,e),e}importGPUDataView(e,t){if(!t.format)throw new Error(`GPUCommandGraph import "${e}" requires GPUData.format`);let o=Tt(t.buffer),n={byteLength:Ma(t),usage:o.usage},i=t.buffer instanceof Ge?this.getDynamicBufferHandle(t.buffer,n):this.getImportedBufferHandle(o,n);return i||(i=this.importBuffer({id:e,byteLength:o.byteLength,usage:o.usage},t.buffer),t.buffer instanceof Ge?this.dynamicBufferHandles.set(t.buffer,i):this.importedBufferHandles.set(o,i)),this.createDataView(i,{format:t.format,length:t.length,byteOffset:t.byteOffset,byteStride:t.byteStride,rowByteLength:t.rowByteLength})}getDynamicBufferHandle(e,t){let o=this.dynamicBufferHandles.get(e);if(o?.defaultBuffer===e&&bt(o,t))return o;this.dynamicBufferHandles.delete(e);for(let n of this.buffers.values())if(n.defaultBuffer===e&&bt(n,t))return this.dynamicBufferHandles.set(e,n),n}getImportedBufferHandle(e,t){let o=this.importedBufferHandles.get(e);if(o?.defaultBuffer&&Tt(o.defaultBuffer)===e&&bt(o,t))return o;this.importedBufferHandles.delete(e);for(let[n,i]of this.dynamicBufferHandles)if(n.buffer===e&&bt(i,t))return this.importedBufferHandles.set(e,i),i;for(let n of this.buffers.values())if(n.defaultBuffer===e&&bt(n,t))return this.importedBufferHandles.set(e,n),n}assertBuffer(e){if(e.graph!==this||this.buffers.get(e.id)!==e)throw new Error(`Graph buffer "${e.id}" does not belong to ${this.id}`)}assertTexture(e){if(e.graph!==this||this.textures.get(e.id)!==e)throw new Error(`Graph texture "${e.id}" does not belong to ${this.id}`)}assertExternalTexture(e){if(e.graph!==this||this.externalTextures.get(e.id)!==e)throw new Error(`Graph external texture "${e.id}" does not belong to ${this.id}`)}assertMutable(){if(this.compiled)throw new Error(`GPUCommandGraph "${this.id}" has already been compiled`)}validateRenderAttachments(e,t){if(t.colorAttachments.length===0&&!t.depthStencilAttachment)throw new Error(`GPUCommandGraph render node "${e}" requires at least one attachment`);let o=[...t.colorAttachments,...t.depthStencilAttachment?[t.depthStencilAttachment]:[]];for(let a of o)if(this.assertTexture(a.texture),a.dimension!=="2d"||a.mipLevelCount!==1||a.arrayLayerCount!==1)throw new Error(`GPUCommandGraph render node "${e}" attachments must be single-mip, single-layer 2d views`);let[n,...i]=o;for(let a of i)if(a.width!==n.width||a.height!==n.height||a.texture.samples!==n.texture.samples)throw new Error(`GPUCommandGraph render node "${e}" attachments must have matching extent and samples`);this.validateResolveTargets(e,t)}validateResolveTargets(e,t){let o=t.resolveTargets;if(o){if(this.device.type!=="webgpu")throw new Error(`GPUCommandGraph render node "${e}" resolve targets require WebGPU`);if(o.length!==t.colorAttachments.length)throw new Error(`GPUCommandGraph render node "${e}" requires one resolve entry per color attachment`);for(let n=0;n<o.length;n++){let i=o[n];if(!i)continue;let a=t.colorAttachments[n];if(this.assertTexture(i.texture),a.texture.samples<=1||i.texture.samples!==1||a.format!==i.format||a.width!==i.width||a.height!==i.height)throw new Error(`GPUCommandGraph render node "${e}" resolve target ${n} must match a multisampled source and be single-sampled`);if(i.dimension!=="2d"||i.aspect!=="all"||i.mipLevelCount!==1||i.arrayLayerCount!==1)throw new Error(`GPUCommandGraph render node "${e}" resolve targets must be single-mip, single-layer 2d color views`)}}}},qe=class{device;id;stats;preflight;capabilities;buffers;textures;externalTextures;compiledNodes;activeImportedBufferHandles=new Set;writableImportedBufferHandles=new Set;activeImportedTextureHandles=new Set;writableImportedTextureHandles=new Set;transientBuffers;transientTextures;bufferTransientAllocations;textureTransientAllocations;cachedTextureViews=[];cachedFramebuffers=[];lastFrameIds=new Map;lastExternalTextureFrameIds=new Map;consumedExternalTextures=new WeakSet;destroyed=!1;get[Symbol.toStringTag](){return"CompiledGPUCommandGraph"}toString(){let e=this.destroyed?"destroyed":"active";return`${this[Symbol.toStringTag]}:"${this.id}":${this.stats.nodeOrder.length} nodes:${this.stats.physicalTransientResourceBytes}B transient:${e}`}toJSON(){return this.toString()}constructor(e){this.device=e.device,this.id=e.id,this.buffers=e.buffers,this.textures=e.textures,this.externalTextures=e.externalTextures,this.compiledNodes=e.compiledNodes;for(let{node:t}of this.compiledNodes)for(let o of t.resources??[])if(ve(o)){let n=Q(o.buffer);n.transient||(this.activeImportedBufferHandles.add(n),(o.usage==="storage-write"||o.usage==="storage-read-write"||o.usage==="copy-destination")&&this.writableImportedBufferHandles.add(n))}else if(xt(o)){let n=ue(o.texture);n.transient||(this.activeImportedTextureHandles.add(n),(o.usage==="storage-write"||o.usage==="storage-read-write"||o.usage==="render-attachment"||o.usage==="copy-destination")&&this.writableImportedTextureHandles.add(n))}this.transientBuffers=e.transientBuffers,this.transientTextures=e.transientTextures,this.bufferTransientAllocations=e.bufferTransientAllocations,this.textureTransientAllocations=e.textureTransientAllocations,this.stats=e.stats,this.preflight=e.preflight,this.capabilities=Oa(this.device)}encode(e,t){return this.encodeNodeRange(e,t,0,this.compiledNodes.length)}getExecutionPlan(e,t={}){return go(this.preflight,e,t)}createExecution(e,t={}){return new vt({plan:this.getExecutionPlan(e,t),budget:e,encodeNodeRange:(o,n,i,a)=>this.encodeNodeRange(o,n,i,a)})}encodeNodeRange(e,t,o,n){if(this.destroyed)throw new Error(`CompiledGPUCommandGraph "${this.id}" has been destroyed`);if(Qt(this.device,"encoding"),e.device!==this.device)throw new Error("GPUCommandGraph command encoder must belong to the graph device");let i=wt(),a=this.resolveImportedBuffers(t.buffers??{});ka(t.frameTextures??{},t.externalTextures??{});let s=this.resolveImportedTextures(t.textures??{},t.frameTextures??{}),u=this.resolveExternalTextures(t.externalTextures??{});for(let[g,p]of s.frameIds)this.lastFrameIds.set(g,p);for(let[g,p]of u.frameIds)this.lastExternalTextureFrameIds.set(g,p);for(let g of u.textures.values())this.consumedExternalTextures.add(g);let d=s.textures,c=g=>{let p=Q(g),T=p.transient?this.transientBuffers.get(p):a.get(p);if(!T)throw new Error(`GPUCommandGraph buffer "${p.id}" is not bound`);return T},m=g=>{let p=ue(g),T=p.transient?this.transientTextures.get(p):d.get(p);if(!T)throw new Error(`GPUCommandGraph texture "${p.id}" is not bound`);return T},l=g=>{let p=m(g);if(g instanceof ne||Xa(g))return p.view;if(g.texture.frameScoped){let x=this.lastFrameIds.get(g.texture);for(let O=this.cachedTextureViews.length-1;O>=0;O--){let S=this.cachedTextureViews[O];S.logicalView===g&&S.frameId!==x&&(this.destroyFramebuffersUsingView(S.view),S.view.destroy(),this.cachedTextureViews.splice(O,1))}}let T=this.cachedTextureViews.find(x=>x.logicalView===g&&x.texture===p&&(!g.texture.frameScoped||x.frameId===this.lastFrameIds.get(g.texture)));if(T)return T.view;let C=p.createView({format:g.format,dimension:g.dimension,aspect:g.aspect,baseMipLevel:g.baseMipLevel,mipLevelCount:g.mipLevelCount,baseArrayLayer:g.baseArrayLayer,arrayLayerCount:g.arrayLayerCount});return this.cachedTextureViews.push({logicalView:g,texture:p,view:C,...g.texture.frameScoped?{frameId:this.lastFrameIds.get(g.texture)}:{}}),C},f=g=>{let p=u.textures.get(g);if(!p)throw new Error(`GPUCommandGraph external texture "${g.id}" is not bound`);return p},h={commandEncoder:e,parameters:t.parameters,getBuffer:c,getTexture:m,getTextureView:l,getExternalTexture:f},y=[],w,I=0,L=t.coalesceComputePasses!==!1&&e.getTimeProfilingQuerySet()===null,P=()=>{let g=w;w=void 0,g?.end()};try{for(let g=o;g<n;g++){let{node:p,executable:T}=this.compiledNodes[g],C=wt();if(p.condition?.source==="cpu"){let S=!1;try{S=p.condition.evaluate(t.parameters)}catch(G){let $=G instanceof Error?G.message:String(G);throw new Error(`GPUCommandGraph CPU condition "${p.condition.id}" failed for node "${p.id}": ${$}`)}if(!S){let G=wt();y.push({stats:{id:p.id,description:p.description,resources:this.preflight.nodes[g].resources,operation:p.workload?.operation,type:p.type,cpuEncodeStartTimeMilliseconds:C,cpuEncodeEndTimeMilliseconds:G,cpuEncodeTimeMilliseconds:G-C,hasGPUTimestamps:!1,condition:{id:p.condition.id,source:"cpu",outcome:"skipped"}}});continue}}let x;switch(p.type){case"compute":{w||(w=e.beginComputePass({id:p.id}),I++);let S=w;x=Qn(S,e),x&&(L=!1),S.pushDebugGroup(p.id);try{let G=p.condition?.source==="gpu"?p.condition:void 0,$=G?Ra(S,c(G.buffer),G.byteOffset??0,p.id):void 0;T.encode({...h,computePass:$?.computePass??S}),$?.assertDispatched()}finally{S.popDebugGroup()}L||P();break}case"render":{P();let S=T,G=S.getRenderPassProps?.(h)??{id:p.id};if(p.attachments&&G.framebuffer!==void 0)throw new Error(`GPUCommandGraph render node "${p.id}" cannot supply framebuffer with graph attachments`);if(p.attachments?.resolveTargets&&G.resolveTargets!==void 0)throw new Error(`GPUCommandGraph render node "${p.id}" cannot supply resolveTargets with graph attachments`);let $=p.attachments?this.getFramebuffer(p.id,p.attachments,l):void 0,X=p.attachments?.resolveTargets?.map(pe=>pe?l(pe):null),ie=e.beginRenderPass({...G,...$?{framebuffer:$}:{},...X?{resolveTargets:X}:{}});x=Qn(ie,e),ie.pushDebugGroup(p.id);try{S.encode({...h,renderPass:ie})}finally{ie.popDebugGroup(),ie.end()}break}case"copy":P(),T.encode(h);break}let O=wt();y.push({stats:{id:p.id,description:p.description,resources:this.preflight.nodes[g].resources,operation:p.workload?.operation,type:p.type,cpuEncodeStartTimeMilliseconds:C,cpuEncodeEndTimeMilliseconds:O,cpuEncodeTimeMilliseconds:O-C,hasGPUTimestamps:x!==void 0,...p.condition?{condition:{id:p.condition.id,source:p.condition.source,outcome:p.condition.source==="gpu"?"gpu-resolved":"executed"}}:{}},timestamp:x})}}finally{P()}let W=wt();return new Ct(y,W-i,I,i,W,async(g,p)=>{if(this.destroyed)throw new Error("Graph has been destroyed.");let T=this.compiledNodes.findIndex(({node:$})=>$.id===g),C=this.compiledNodes[T]?.node.resources?.[p],x=this.preflight.nodes[T]?.resources?.[p];if(!C||!x)throw new Error("Resource is unavailable.");if("externalTexture"in C)throw new Error("External images cannot be read back.");let O="buffer"in C?Q(C.buffer):ue(C.texture);if("frameScoped"in O&&O.frameScoped)throw new Error("Frame textures expire after presentation.");let S="buffer"in C?c(C.buffer):m(C.texture),G=S instanceof z.Buffer?this.transientBuffers:this.transientTextures;if(O.transient&&[...G].some(([$,X])=>$!==O&&X===S))throw new Error("Transient allocation is reused; logical contents are no longer available.");return ko(S,x)})}destroy(){if(!this.destroyed){for(let{executable:e}of this.compiledNodes)e.destroy?.();for(let e of this.cachedFramebuffers)e.framebuffer.destroy();for(let e of this.cachedTextureViews)e.view.destroy();for(let e of this.bufferTransientAllocations)e.buffer?.destroy();for(let e of this.textureTransientAllocations)e.texture?.destroy();this.destroyed=!0}}resolveImportedBuffers(e){let t=new Map,o=new Map;for(let[n,i]of this.buffers){if(i.transient)continue;let a=e[n]??i.defaultBuffer;if(!a)throw new Error(`GPUCommandGraph imported buffer "${n}" is required`);ti(a,i,this.device);let s=Tt(a);if(this.activeImportedBufferHandles.has(i)){let u=s.handle,d=typeof u=="object"&&u!==null||typeof u=="function"?u:s,c=o.get(d);if(c&&(this.writableImportedBufferHandles.has(c)||this.writableImportedBufferHandles.has(i)))throw new Error(`GPUCommandGraph imported buffers "${c.id}" and "${n}" resolve to the same physical buffer`);c||o.set(d,i)}t.set(i,s)}for(let n of Object.keys(e)){let i=this.buffers.get(n);if(!i||i.transient)throw new Error(`GPUCommandGraph has no imported buffer named "${n}"`)}return t}resolveImportedTextures(e,t){let o=new Map,n=new Map;for(let[a,s]of this.textures){if(s.transient)continue;if(s.frameScoped){let d=t[a];if(!d)throw new Error(`GPUCommandGraph frame texture "${a}" is required`);let c=this.lastFrameIds.get(s);if(c!==void 0&&d.frameId<=c)throw new Error(`GPUCommandGraph frame texture "${a}" frameId ${d.frameId} is stale; expected greater than ${c}`);ho(d.texture,s,this.device),o.set(s,po(d.texture)),n.set(s,d.frameId);continue}let u=e[a]??s.defaultTexture;if(!u)throw new Error(`GPUCommandGraph imported texture "${a}" is required`);ho(u,s,this.device),o.set(s,po(u))}for(let a of Object.keys(e)){let s=this.textures.get(a);if(!s||s.transient||s.frameScoped)throw new Error(`GPUCommandGraph has no imported texture named "${a}"`)}for(let a of Object.keys(t))if(!this.textures.get(a)?.frameScoped)throw new Error(`GPUCommandGraph has no frame texture named "${a}"`);let i=new Map;for(let[a,s]of o){if(!this.activeImportedTextureHandles.has(a))continue;let u=s.handle,d=typeof u=="object"&&u!==null||typeof u=="function"?u:s,c=i.get(d);if(c&&(this.writableImportedTextureHandles.has(c)||this.writableImportedTextureHandles.has(a)))throw new Error(`GPUCommandGraph imported textures "${c.id}" and "${a.id}" resolve to the same physical texture`);c||i.set(d,a)}return{textures:o,frameIds:n}}resolveExternalTextures(e){let t=new Map,o=new Map;for(let[n,i]of this.externalTextures){let a=e[n];if(!a)throw new Error(`GPUCommandGraph external texture "${n}" is required`);let s=this.lastExternalTextureFrameIds.get(i);if(s!==void 0&&a.frameId<=s)throw new Error(`GPUCommandGraph external texture "${n}" frameId ${a.frameId} is stale; expected greater than ${s}`);if(this.consumedExternalTextures.has(a.texture))throw new Error(`GPUCommandGraph external texture "${n}" requires a fresh binding for each frame`);Va(a.texture,i,this.device),t.set(i,a.texture),o.set(i,a.frameId)}for(let n of Object.keys(e))if(!this.externalTextures.has(n))throw new Error(`GPUCommandGraph has no external texture named "${n}"`);return{textures:t,frameIds:o}}getFramebuffer(e,t,o){let n=t.colorAttachments.map(o),i=t.depthStencilAttachment?o(t.depthStencilAttachment):void 0,a=this.cachedFramebuffers.find(d=>d.nodeId===e&&d.depthStencilAttachment===i&&d.colorAttachments.length===n.length&&d.colorAttachments.every((c,m)=>c===n[m]));if(a)return a.framebuffer;let s=t.colorAttachments[0]??t.depthStencilAttachment,u=this.device.createFramebuffer({id:`${this.id}-${e}-framebuffer-${this.cachedFramebuffers.length}`,width:s.width,height:s.height,colorAttachments:n,depthStencilAttachment:i??null});return this.cachedFramebuffers.push({nodeId:e,colorAttachments:n,depthStencilAttachment:i,framebuffer:u}),u}destroyFramebuffersUsingView(e){for(let t=this.cachedFramebuffers.length-1;t>=0;t--){let o=this.cachedFramebuffers[t];(o.depthStencilAttachment===e||o.colorAttachments.some(n=>n===e))&&(o.framebuffer.destroy(),this.cachedFramebuffers.splice(t,1))}}};function Tt(r){return r instanceof Ge?r.buffer:r}function Ma(r){let e=r.length===0?0:(r.length-1)*r.byteStride+r.rowByteLength;return r.byteOffset+e}function bt(r,e){return r.byteLength>=e.byteLength&&(r.usage&e.usage)===e.usage}function po(r){if(r instanceof Zt){if(!r.isReady)throw new Error(`GPUCommandGraph dynamic texture "${r.id}" is not ready`);return r.texture}return r}function ka(r,e){let t;for(let[o,n]of[...Object.entries(r),...Object.entries(e)]){if(!Number.isSafeInteger(n.frameId)||n.frameId<0)throw new Error(`GPUCommandGraph frame resource "${o}" requires a valid frameId`);if(t!==void 0&&n.frameId!==t)throw new Error("GPUCommandGraph frame resources must share one frameId per encoding");t=n.frameId}}function Qn(r,e){let{timestampQuerySet:t,beginTimestampIndex:o,endTimestampIndex:n}=r.props;return t&&Number.isSafeInteger(o)&&Number.isSafeInteger(n)&&o>=0&&n>o?{querySet:t,snapshot:t.device.type==="webgpu"?e.captureTimestampQuerySet?.(t):void 0,beginIndex:o,endIndex:n}:void 0}function Oa(r){return Object.freeze({timestampQueries:r.features.has("timestamp-query"),subgroups:r.features.has("subgroups"),subgroupId:r.wgslLanguageFeatures.has("subgroup_id"),subgroupMinSize:r.info.subgroupMinSize,subgroupMaxSize:r.info.subgroupMaxSize,softwareAdapter:r.info.gpu==="software"||r.info.gpuType==="cpu"||!!r.info.fallback,maxBufferByteLength:r.limits.maxBufferSize,maxStorageBufferBindingByteLength:r.limits.maxStorageBufferBindingSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension})}function Qt(r,e){if(r.isLost)throw new Error(`GPUCommandGraph cannot perform ${e} after device loss`)}function wt(){return globalThis.performance?.now()??Date.now()}function Jn(r,e){if(!r.id)throw new Error("GPUCommandGraph buffer id is required");if(!Number.isSafeInteger(r.byteLength)||r.byteLength<0)throw new Error(`GPUCommandGraph buffer "${r.id}" requires a valid byteLength`);if(r.byteLength>e.limits.maxBufferSize)throw new Error(`GPUCommandGraph buffer "${r.id}" exceeds the device buffer limit`);if(!Number.isSafeInteger(r.usage)||r.usage<=0)throw new Error(`GPUCommandGraph buffer "${r.id}" requires buffer usage flags`)}function Fa(r,e){if(!r.id)throw new Error("GPUCommandGraph external texture id is required");for(let[t,o]of Object.entries({width:r.width,height:r.height}))if(!Number.isSafeInteger(o)||o<=0)throw new Error(`GPUCommandGraph external texture "${r.id}" ${t} must be a positive safe integer`);if(r.width>e.limits.maxTextureDimension2D||r.height>e.limits.maxTextureDimension2D)throw new Error(`GPUCommandGraph external texture "${r.id}" exceeds device dimension limits`)}function fo(r,e){if(!r.id)throw new Error("GPUCommandGraph texture id is required");let t=r.dimension??"2d",o=t==="cube"?6:r.depth??1,n=r.mipLevels??1,i=r.samples??1;for(let[d,c]of Object.entries({width:r.width,height:r.height,depth:o,mipLevels:n,samples:i}))if(!Number.isSafeInteger(c)||c<=0)throw new Error(`GPUCommandGraph texture "${r.id}" ${d} must be a positive safe integer`);if(!Number.isSafeInteger(r.usage)||r.usage<=0)throw new Error(`GPUCommandGraph texture "${r.id}" requires texture usage flags`);if(!e.isTextureFormatSupported(r.format))throw new Error(`GPUCommandGraph texture "${r.id}" format ${r.format} is unsupported`);if(t==="1d"&&(r.height!==1||o!==1))throw new Error(`GPUCommandGraph 1d texture "${r.id}" requires height and depth 1`);if(t==="cube"&&r.width!==r.height)throw new Error(`GPUCommandGraph cube texture "${r.id}" must be square`);if(t==="cube-array"&&(r.width!==r.height||o%6!==0))throw new Error(`GPUCommandGraph cube-array texture "${r.id}" must be square with depth divisible by 6`);if(n>e.getMipLevelCount(r.width,r.height,t==="3d"?o:1))throw new Error(`GPUCommandGraph texture "${r.id}" declares too many mip levels`);let a=t==="1d"?e.limits.maxTextureDimension1D:t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,s=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,u=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureArrayLayers;if(r.width>a||r.height>s||o>u)throw new Error(`GPUCommandGraph texture "${r.id}" exceeds device dimension limits`);return{id:r.id,format:r.format,width:r.width,height:r.height,usage:r.usage,dimension:t,depth:o,mipLevels:n,samples:i}}function Na(r,e){let t=e.dimension??r.dimension,o=e.aspect??"all",n=e.baseMipLevel??0,i=e.mipLevelCount??r.mipLevels-n,a=e.baseArrayLayer??0,s=r.dimension==="3d"?1:r.depth,u=e.arrayLayerCount??s-a;for(let[l,f]of Object.entries({baseMipLevel:n,mipLevelCount:i,baseArrayLayer:a,arrayLayerCount:u}))if(!Number.isSafeInteger(f)||f<0)throw new Error(`Graph texture view ${l} must be a non-negative safe integer`);if(i===0||n+i>r.mipLevels)throw new Error(`Graph texture view exceeds texture "${r.id}" mip levels`);if(u===0||a+u>s||r.dimension==="3d"&&(a!==0||u!==1))throw new Error(`Graph texture view exceeds texture "${r.id}" array layers`);let d=Math.max(1,r.width>>n),c=r.dimension==="1d"?1:Math.max(1,r.height>>n),m=r.dimension==="3d"?Math.max(1,r.depth>>n):u;return{dimension:t,aspect:o,baseMipLevel:n,mipLevelCount:i,baseArrayLayer:a,arrayLayerCount:u,width:d,height:c,depth:m}}function za(r,e){for(let[n,i]of Object.entries(e))if(!Number.isSafeInteger(i)||i<0)throw new Error(`Graph data view ${n} must be a non-negative safe integer`);if(e.length>1&&e.byteStride===0)throw new Error("Graph data view byteStride must be positive for multiple rows");if(e.rowByteLength>e.byteStride&&e.length>1)throw new Error("Graph data view rowByteLength cannot exceed byteStride");let t=e.length===0?0:(e.length-1)*e.byteStride+e.rowByteLength,o=e.byteOffset+t;if(!Number.isSafeInteger(t)||!Number.isSafeInteger(o))throw new Error("Graph data view byte range exceeds safe integer precision");if(o>r.byteLength)throw new Error(`Graph data view exceeds buffer "${r.id}" byte length`)}function ti(r,e,t){let o=Tt(r);if(o.device!==t)throw new Error(`GPUCommandGraph buffer "${e.id}" belongs to another device`);if(o.byteLength<e.byteLength)throw new Error(`GPUCommandGraph buffer "${e.id}" is smaller than compiled capacity`);if((o.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph buffer "${e.id}" has incompatible usage flags`)}function ho(r,e,t){let o=po(r);if(o.device!==t)throw new Error(`GPUCommandGraph texture "${e.id}" belongs to another device`);for(let[n,i,a]of[["format",e.format,o.format],["dimension",e.dimension,o.dimension],["width",e.width,o.width],["height",e.height,o.height],["depth",e.depth,o.depth],["mipLevels",e.mipLevels,o.mipLevels],["samples",e.samples,o.samples]])if(a!==i)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible ${n} (${a} !== ${i})`);if((o.props.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible usage flags`)}function Va(r,e,t){if(r.device!==t)throw new Error(`GPUCommandGraph external texture "${e.id}" belongs to another device`);if(r.destroyed)throw new Error(`GPUCommandGraph external texture "${e.id}" has been destroyed`);if(r.width!==e.width||r.height!==e.height)throw new Error(`GPUCommandGraph external texture "${e.id}" has incompatible dimensions (${r.width}x${r.height} !== ${e.width}x${e.height})`)}function Wa(r,e){let t=qa(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph buffer "${r.id}" does not declare usage required by ${e}`)}function ja(r,e){let t=Ya(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph texture "${r.id}" does not declare usage required by ${e}`)}function Ha(r,e){if(r instanceof Pe&&e.startsWith("storage-")&&r.mipLevelCount!==1)throw new Error("GPUCommandGraph storage texture views must contain exactly one mip level")}function qa(r){switch(r){case"storage-read":case"storage-write":case"storage-read-write":return z.Buffer.STORAGE;case"uniform":return z.Buffer.UNIFORM;case"copy-source":return z.Buffer.COPY_SRC;case"copy-destination":return z.Buffer.COPY_DST;case"indirect":return z.Buffer.INDIRECT;case"vertex":return z.Buffer.VERTEX;case"index":return z.Buffer.INDEX}}function Ya(r){switch(r){case"sampled":return z.Texture.SAMPLE;case"storage-read":case"storage-write":case"storage-read-write":return z.Texture.STORAGE;case"render-attachment":return z.Texture.RENDER;case"copy-source":return z.Texture.COPY_SRC;case"copy-destination":return z.Texture.COPY_DST}}function Xa(r){let e=r.texture;return r.dimension===e.dimension&&r.aspect==="all"&&r.baseMipLevel===0&&r.mipLevelCount===e.mipLevels&&r.baseArrayLayer===0&&r.arrayLayerCount===(e.dimension==="3d"?1:e.depth)}var q=class{id;type="composite";operations;metadata;constructor(e){let t=Array.isArray(e)?{operations:e}:e;this.id=t.id??"gpu-composite-operation",this.operations=Object.freeze([...t.operations]),this.metadata=t.metadata}};function yo(r){let e=r;return typeof e.id=="string"&&typeof e.type=="string"}function xo(r){return r instanceof q?Object.freeze({id:r.id,type:r.type,...r.metadata?{metadata:r.metadata}:{},children:Object.freeze(r.operations.map(xo))}):yo(r)?Object.freeze({id:r.id,type:r.type,...r.metadata?{metadata:r.metadata}:{}}):Object.freeze({id:r.constructor?.name??"gpu-command-node-producer",type:"command-node-producer"})}function ri(r){return typeof r.getCommandNodes=="function"}var Ye=class{id;format;constructor(e,t){if(!e)throw new Error("GPUGraphScalar id is required");this.id=e,this.format=t}},Xe=class{id;format;length;external;chunkLengths;constructor(e){if(!e.id)throw new Error("GPUGraphVector id is required");if(!Number.isSafeInteger(e.length)||e.length<0)throw new Error(`${e.id} vector length must be a non-negative safe integer`);if(this.id=e.id,this.format=e.format,this.length=e.length,this.external=e.external??!1,e.chunkLengths){if(e.chunkLengths.some(t=>!Number.isSafeInteger(t)||t<0)||e.chunkLengths.reduce((t,o)=>t+o,0)!==e.length)throw new Error(`${e.id} chunk lengths must partition its logical length`);this.chunkLengths=Object.freeze([...e.chunkLengths])}}},Ke=class{id;format;width;height;usage;dimension;depth;mipLevels;samples;external;constructor(e){this.id=e.id,this.format=e.format,this.width=e.width,this.height=e.height,this.usage=e.usage,this.dimension=e.dimension,this.depth=e.depth,this.mipLevels=e.mipLevels,this.samples=e.samples,this.external=e.external??!1}},ce=class{texture;props;constructor(e,t={}){this.texture=e,this.props=Object.freeze({...t})}};var Jt=class{id;programOperations=[];programScalars=new Map;programVectors=new Map;programTextures=new Map;constructor(e={}){this.id=e.id??"gpu-program"}add(e){return this.assertOperationLike(e),this.addOperationLike(e),this}scalar(e,t){this.assertValueId(e);let o=new Ye(e,t);return this.programScalars.set(e,o),o}vector(e,t,o,n={}){this.assertValueId(e);let i=new Xe({id:e,format:t,length:o,...n});return this.programVectors.set(e,i),i}texture(e,t){this.assertValueId(e);let o=new Ke({...t,id:e});return this.programTextures.set(e,o),o}textureView(e,t={}){if(this.programTextures.get(e.id)!==e)throw new Error(`Undeclared program texture "${e.id}"`);return new ce(e,t)}get textures(){return Object.freeze([...this.programTextures.values()])}get scalars(){return Object.freeze([...this.programScalars.values()])}get vectors(){return Object.freeze([...this.programVectors.values()])}get operations(){return Object.freeze([...this.programOperations])}get operationTree(){return Object.freeze(this.programOperations.map(xo))}assertValueId(e){if(this.programScalars.has(e)||this.programVectors.has(e)||this.programTextures.has(e))throw new Error(`${this.id} value "${e}" already exists`)}addOperationLike(e){if(Array.isArray(e)){for(let t of e)this.addOperationLike(t);return}this.programOperations.push(e)}assertOperationLike(e){if(Array.isArray(e)){for(let t of e)this.assertOperationLike(t);return}if(!e||typeof e!="object")throw new Error(`${this.id} accepts GPU operations only`)}};function oi(r,e={}){return new q({id:e.id,operations:r})}var er=class extends He{computeLowerings=[];loweringsSuspended=0;otherLowerings=[];addRenderPass(e){let t={...e,type:"render"},o=this.otherLowerings.at(-1);o&&(t=o(t)),super.addRenderPass(t)}addCopyPass(e){let t={...e,type:"copy"},o=this.otherLowerings.at(-1);o&&(t=o(t)),super.addCopyPass(t)}withOtherLowering(e,t){this.otherLowerings.push(e);try{return t()}finally{this.otherLowerings.pop()}}constructor(e,t={}){super(e,t)}addComputePass(e){let t=e;if(this.loweringsSuspended===0)for(let o=this.computeLowerings.length-1;o>=0;o--)t=this.computeLowerings[o](t);super.addComputePass(t)}withComputeLowering(e,t){this.computeLowerings.push(e);try{return t()}finally{this.computeLowerings.pop()}}withoutComputeLowering(e){this.loweringsSuspended++;try{return e()}finally{this.loweringsSuspended--}}};var bo=ee(K(),1);Ae();var wo=Uint32Array.BYTES_PER_ELEMENT,To=256;function Re(r,e,t){let o=N(r.format);if(!e.includes(r.format)||r.byteStride!==o.byteLength||r.rowByteLength!==o.byteLength||r.byteOffset%wo!==0)throw new Error(`${t} must be packed, uint32-aligned ${e.join(" or ")} GPU data`)}function ni(r,e){Re(r,["uint32"],e)}function V(r,e){let t=Pt(r),o={buffer:e(r),...t};if(o.offset+o.size>r.buffer.byteLength)throw new Error("GraphDataView storage binding exceeds its logical buffer");return o}function Pt(r){let e=Math.floor(r.byteOffset/To)*To,t=r.byteOffset-e,o=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:e,size:t+Math.max(o,r.rowByteLength)}}function E(r){if(r.byteOffset%wo!==0)throw new Error("GraphDataView storage binding must be uint32-aligned");return r.byteOffset%To/wo}function Me(r,e,t,o,n=bo.Buffer.STORAGE){if(!Number.isSafeInteger(o)||o<0)throw new Error("Transient GraphDataView length must be a non-negative safe integer");if((n&bo.Buffer.STORAGE)===0)throw new Error("Transient GraphDataView usage must include Buffer.STORAGE");if(we(t)||Te(t))throw new Error("Transient GraphDataView requires a fixed-width GPUVector format");let i=N(t),a=r.createTransientBuffer({id:e,byteLength:Math.max(o,1)*i.byteLength,usage:n});return r.createDataView(a,{format:t,length:o})}function ii(r,e,t){if(!Number.isSafeInteger(t)||t<0||t>e.length)throw new Error("Graph prefix must fit within the input");if(t===e.length)return e;let o=e instanceof B?e.data:[e],n=t,i=[];for(let a of o){let s=Math.min(n,a.length);if(i.push(s===a.length?a:r.createDataView(a.buffer,{format:a.format,length:s,byteOffset:a.byteOffset,byteStride:a.byteStride,rowByteLength:a.rowByteLength})),n-=s,n===0)break}return e instanceof B?new B({...e,length:t,valueLength:t*(N(e.format).listSize??1),data:i}):i[0]}var or=ee(K(),1);le();function k(r,e){let[t,o,n]=e;for(let[i,a]of[["x",t],["y",o],["z",n]])if(!Number.isSafeInteger(a)||a<0)throw new Error(`compute dispatch ${i} workgroup count must be a non-negative safe integer`);return{...r,dispatchWorkgroups:Object.freeze([t,o,n])}}function tr(r){return r.dispatchWorkgroups}var rr=ee(K(),1);var Ka=16*1024,si=new WeakMap;function ui(r){let e=r,t=si.get(e);return t||(t=new vo(r),si.set(e,t)),t}var vo=class{id;graph;buffer;capacityByteLength;nextByteOffset=0;slots=new Map;views=new Map;constructor(e,t="gpu-value-arena",o=Ka){if(this.id=t,this.graph=e,!Number.isSafeInteger(o)||o<=0||o%4!==0)throw new Error(`${this.id} capacityByteLength must be a positive multiple of 4`);this.capacityByteLength=o,this.buffer=e.createTransientBuffer({id:`${this.id}-buffer`,byteLength:o,usage:rr.Buffer.STORAGE|rr.Buffer.COPY_SRC|rr.Buffer.COPY_DST})}allocate(e,t){if(!e)throw new Error(`${this.id} slot id must not be empty`);if(this.slots.has(e))throw new Error(`${this.id} slot "${e}" already exists`);if(!["float32","uint32","sint32"].includes(t))throw new Error(`${this.id} unsupported slot format ${t}`);if(this.nextByteOffset+4>this.capacityByteLength)throw new Error(`${this.id} capacity exceeded while allocating "${e}"`);let o=Object.freeze({id:e,format:t,byteOffset:this.nextByteOffset});return this.nextByteOffset+=4,this.slots.set(e,o),this.views.set(e,new de(this.buffer,{format:t,length:1,byteOffset:o.byteOffset,byteStride:4,rowByteLength:4})),o}get(e){return this.slots.get(e)}getSlots(){return Object.freeze([...this.slots.values()])}getView(e){let t=this.views.get(e.id);if(!t)throw new Error(`${this.id} does not contain slot "${e.id}"`);return t}get byteLength(){return this.nextByteOffset}get size(){return this.slots.size}get availableByteLength(){return this.capacityByteLength-this.nextByteOffset}};var Co=class{id;format;arena;slot;constructor(e,t){this.id=t.id,this.format=t.format,this.arena=e,this.slot=t}get byteOffset(){return this.slot.byteOffset}get wordOffset(){return this.slot.byteOffset>>>2}get view(){return this.arena.getView(this.slot)}};function Po(r,e,t){let o=ui(r);return new Co(o,o.allocate(e,t))}function J(r,e="gpuValues"){let t=`${e}[${r.wordOffset}u]`;switch(r.format){case"float32":return`bitcast<f32>(${t})`;case"uint32":return t;case"sint32":return`bitcast<i32>(${t})`}}function Se(r,e,t="gpuValues"){let o=`${t}[${r.wordOffset}u]`;switch(r.format){case"float32":return`${o} = bitcast<u32>(${e});`;case"uint32":return`${o} = ${e};`;case"sint32":return`${o} = bitcast<u32>(${e});`}}function Y(r,e,t="gpuValues"){return`@group(${r}) @binding(${e}) var<storage, read_write> ${t}: array<u32>;`}var St=class{id;active;workgroups;dispatchBuffer;constructor(e,t){if(this.id=t.id,this.active=t.active,this.workgroups=t.workgroups,t.active.arena.graph!==e)throw new Error(`${this.id} active scalar must belong to target graph`);this.dispatchBuffer=e.createTransientBuffer({id:`${this.id}-dispatch`,byteLength:12,usage:or.Buffer.STORAGE|or.Buffer.INDIRECT|or.Buffer.COPY_SRC})}getUpdateCommandNodes(e,t=`${this.id}-update`){if(this.active.arena.graph!==e)throw new Error(`${this.id} active scalar must belong to target graph`);let o=this.active.arena.buffer,[n,i,a]=this.workgroups,s=`${Y(0,0)}
7
+ "use strict";var __exports__=(()=>{var Ri=Object.create;var Gt=Object.defineProperty;var Mi=Object.getOwnPropertyDescriptor;var ki=Object.getOwnPropertyNames;var Oi=Object.getPrototypeOf,Fi=Object.prototype.hasOwnProperty;var y=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(o){throw t=[o],o}};var Vi=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Ni=(r,e)=>{for(var t in e)Gt(r,t,{get:e[t],enumerable:!0})},At=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ki(e))!Fi.call(r,n)&&n!==t&&Gt(r,n,{get:()=>e[n],enumerable:!(o=Mi(e,n))||o.enumerable});return r},It=(r,e,t)=>(At(r,e,"default"),t&&At(t,e,"default")),ee=(r,e,t)=>(t=r!=null?Ri(Oi(r)):{},At(e||!r||!r.__esModule?Gt(t,"default",{value:r,enumerable:!0}):t,r)),zi=r=>At(Gt({},"__esModule",{value:!0}),r);var K=Vi((Vs,Oo)=>{Oo.exports=globalThis.luma});var ot,Wi,$t,ji,Hi,Sr=y(()=>{ot=globalThis,Wi=globalThis.document||{},$t=globalThis.process||{},ji=globalThis.console,Hi=globalThis.navigator||{}});function Ut(r){if(typeof window<"u"&&window.process?.type==="renderer"||typeof process<"u"&&process.versions?.electron)return!0;let e=typeof navigator<"u"&&navigator.userAgent,t=r||e;return!!(t&&t.indexOf("Electron")>=0)}var _t=y(()=>{});function he(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||Ut()}var Cr=y(()=>{_t()});var Vo=y(()=>{Cr();_t();Sr()});var No=y(()=>{});var Pr,Rt=y(()=>{Sr();Cr();Vo();_t();No();Pr="5.0.0"});function Fe(r,e){if(!r)throw new Error(e||"Assertion failed")}var Br=y(()=>{});function Mt(r){if(!r)return 0;let e;switch(typeof r){case"number":e=r;break;case"object":e=r.logLevel||r.priority||0;break;default:return 0}return Fe(Number.isFinite(e)&&e>=0),e}function Er(r){let{logLevel:e,message:t}=r;r.logLevel=Mt(e);let o=r.args?Array.from(r.args):[];for(;o.length&&o.shift()!==t;);switch(typeof e){case"string":case"function":t!==void 0&&o.unshift(t),r.message=e;break;case"object":Object.assign(r,e);break;default:}typeof r.message=="function"&&(r.message=r.message());let n=typeof r.message;return Fe(n==="string"||n==="object"),Object.assign(r,{args:o},r.opts)}var kt=y(()=>{Br()});var ge,Ee,nt=y(()=>{kt();ge=()=>{},Ee=class{constructor({level:e=0}={}){this.userData={},this._onceCache=new Set,this._level=e}set level(e){this.setLevel(e)}get level(){return this.getLevel()}setLevel(e){return this._level=e,this}getLevel(){return this._level}warn(e,...t){return this._log("warn",0,e,t,{once:!0})}error(e,...t){return this._log("error",0,e,t)}log(e,t,...o){return this._log("log",e,t,o)}info(e,t,...o){return this._log("info",e,t,o)}once(e,t,...o){return this._log("once",e,t,o,{once:!0})}_log(e,t,o,n,i={}){let a=Er({logLevel:t,message:o,args:this._buildArgs(t,o,n),opts:i});return this._createLogFunction(e,a,i)}_buildArgs(e,t,o){return[e,t,...o]}_createLogFunction(e,t,o){if(!this._shouldLog(t.logLevel))return ge;let n=this._getOnceTag(o.tag??t.tag??t.message);if((o.once||t.once)&&n!==void 0){if(this._onceCache.has(n))return ge;this._onceCache.add(n)}return this._emit(e,t)}_shouldLog(e){return this.getLevel()>=Mt(e)}_getOnceTag(e){if(e!==void 0)try{return typeof e=="string"?e:String(e)}catch{return}}}});function Yi(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,t),e.removeItem(t),e}catch{return null}}var it,Lr=y(()=>{it=class{constructor(e,t,o="sessionStorage"){this.storage=Yi(o),this.id=e,this.config=t,this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){if(Object.assign(this.config,e),this.storage){let t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}}_loadConfiguration(){let e={};if(this.storage){let t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}});function zo(r){let e;return r<10?e=`${r.toFixed(2)}ms`:r<100?e=`${r.toFixed(1)}ms`:r<1e3?e=`${r.toFixed(0)}ms`:e=`${(r/1e3).toFixed(2)}s`,e}function Dr(r,e=8){let t=Math.max(e-r.length,0);return`${" ".repeat(t)}${r}`}var Ar=y(()=>{});function Wo(r){return typeof r!="string"?r:(r=r.toUpperCase(),at[r]||at.WHITE)}function Gr(r,e,t){return!he&&typeof r=="string"&&(e&&(r=`\x1B[${Wo(e)}m${r}\x1B[39m`),t&&(r=`\x1B[${Wo(t)+Xi}m${r}\x1B[49m`)),r}var at,Xi,Ot=y(()=>{Rt();(function(r){r[r.BLACK=30]="BLACK",r[r.RED=31]="RED",r[r.GREEN=32]="GREEN",r[r.YELLOW=33]="YELLOW",r[r.BLUE=34]="BLUE",r[r.MAGENTA=35]="MAGENTA",r[r.CYAN=36]="CYAN",r[r.WHITE=37]="WHITE",r[r.BRIGHT_BLACK=90]="BRIGHT_BLACK",r[r.BRIGHT_RED=91]="BRIGHT_RED",r[r.BRIGHT_GREEN=92]="BRIGHT_GREEN",r[r.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",r[r.BRIGHT_BLUE=94]="BRIGHT_BLUE",r[r.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",r[r.BRIGHT_CYAN=96]="BRIGHT_CYAN",r[r.BRIGHT_WHITE=97]="BRIGHT_WHITE"})(at||(at={}));Xi=10});function Ir(r,e=["constructor"]){let t=Object.getPrototypeOf(r),o=Object.getOwnPropertyNames(t),n=r;for(let i of o){let a=n[i];typeof a=="function"&&(e.find(s=>i===s)||(n[i]=a.bind(r)))}}var $r=y(()=>{});var Ft,j,st=y(()=>{Rt();Ft=class{getHighResolutionTimer(){let e;if(he()&&ot.performance)e=ot?.performance?.now?.();else if("hrtime"in $t){let t=$t?.hrtime?.();e=t[0]*1e3+t[1]/1e6}else e=Date.now();return e}getMemoryUsageMB(){let t=ot?.performance?.memory?.usedJSHeapSize;return t==null?null:Math.trunc(t/1024/1024)}},j=new Ft;globalThis.Probe=Ft;globalThis.probe=j});function Ki(r,e,t){if(typeof e=="string"){let o=t.time?Dr(zo(t.total)):"";e=t.time?`${r}: ${o} ${e}`:`${r}: ${e}`,e=Gr(e,t.color,t.background)}return e}function Zi(r){for(let e in r)for(let t in r[e])return t||"untitled";return"empty"}var Ve,Ur,ae,_r=y(()=>{Rt();nt();Lr();Ar();Ot();$r();Br();st();kt();kt();Ve={debug:he()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},Ur={enabled:!0,level:0},ae=class extends Ee{constructor({id:e}={id:""}){super({level:0}),this.VERSION=Pr,this._startTs=j.getHighResolutionTimer(),this._deltaTs=j.getHighResolutionTimer(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new it(`__probe-${this.id}__`,{[this.id]:Ur}),this.timeStamp(`${this.id} started`),Ir(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((j.getHighResolutionTimer()-this._startTs).toPrecision(10))}getDelta(){return Number((j.getHighResolutionTimer()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._updateConfiguration({enabled:e}),this}setLevel(e){return this._updateConfiguration({level:e}),this}get(e){return this._getConfiguration()[e]}set(e,t){this._updateConfiguration({[e]:t})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,t){if(!e)throw new Error(t||"Assertion failed")}warn(e,...t){return this._log("warn",0,e,t,{method:Ve.warn,once:!0})}error(e,...t){return this._log("error",0,e,t,{method:Ve.error})}deprecated(e,t){return this.warn(`\`${e}\` is deprecated and will be removed in a later version. Use \`${t}\` instead`)}removed(e,t){return this.error(`\`${e}\` has been removed. Use \`${t}\` instead`)}probe(e,t,...o){let n=j.getMemoryUsageMB();if(n!==null){let i=`${n}MB `;typeof t=="function"?t=()=>`${i}${t()}`:typeof t=="string"&&(t=`${i}${t}`)}return this._log("log",e,t,o,{method:Ve.log,time:!0,once:!0})}log(e,t,...o){return this._log("log",e,t,o,{method:Ve.debug})}info(e,t,...o){return this._log("info",e,t,o,{method:console.info})}once(e,t,...o){return this._log("once",e,t,o,{method:Ve.debug||Ve.info,once:!0})}table(e,t,o){return t?this._log("table",e,t,o&&[o]||[],{method:console.table||ge,tag:Zi(t)}):ge}time(e,t){return this._log("time",e,t,[],{method:console.time?console.time:console.info})}timeEnd(e,t){return this._log("time",e,t,[],{method:console.timeEnd?console.timeEnd:console.info})}timeStamp(e,t){return this._log("time",e,t,[],{method:console.timeStamp||ge})}group(e,t,o={collapsed:!1}){let n=(o.collapsed?console.groupCollapsed:console.group)||console.info;return this._log("group",e,t,[],{method:n})}groupCollapsed(e,t,o={}){return this.group(e,t,Object.assign({},o,{collapsed:!0}))}groupEnd(e){return this._log("groupEnd",e,"",[],{method:console.groupEnd||ge})}withGroup(e,t,o){this.group(e,t)();try{o()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&super._shouldLog(e)}_emit(e,t){let o=t.method;Fe(o),t.total=this.getTotal(),t.delta=this.getDelta(),this._deltaTs=j.getHighResolutionTimer();let n=Ki(this.id,t.message,t);return o.bind(console,n,...t.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(Ur),this._storage.config[this.id]}_updateConfiguration(e){let t=this._storage.config[this.id]||{...Ur};this._storage.setConfiguration({[this.id]:{...t,...e}})}};ae.VERSION=Pr});var jo=y(()=>{nt()});var Ho=y(()=>{nt()});var qo=y(()=>{st()});var Yo=y(()=>{st();globalThis.probe||(globalThis.probe=j)});var Nu,Xo=y(()=>{_r();st();_r();jo();nt();Ho();Ot();Ot();Ar();$r();Lr();qo();Yo();Nu=new ae({id:"@probe.gl/log"})});var Z,Rr=y(()=>{"use strict";Xo();Z=new ae({id:"luma.gl"})});function Ne(r="id"){Mr[r]=Mr[r]||1;let e=Mr[r]++;return`${r}-${e}`}var Mr,Vt=y(()=>{"use strict";Mr={}});function oa(r,e){let t={...e};for(let o in r)r[o]!==void 0&&(t[o]=r[o]);return t}function tn(r,e){let t=r.stats,o=!1;for(let u of e)t[u]||(r.get(u),o=!0);let n=Object.keys(t).length,i=Jo.get(r);if(!o&&i?.orderedStatNames===e&&i.statCount===n)return;let a={},s=en.get(e);s||(s=new Set(e),en.set(e,s));for(let u of e)t[u]&&(a[u]=t[u]);for(let[u,c]of Object.entries(t))s.has(u)||(a[u]=c);for(let u of Object.keys(t))delete t[u];Object.assign(t,a),Jo.set(r,{orderedStatNames:e,statCount:n})}function rn(r){return r.type==="webgl"?ra:ta}function ut(r){let e=r.userData[Qi];return e?.enabled?e:null}function ye(){return globalThis.performance?.now?.()??Date.now()}function na(r,e){let t=ut(r);if(!(!t||!t.activeDefaultFramebufferAcquireDepth))switch(t.transientCanvasResourceCreates=(t.transientCanvasResourceCreates||0)+1,e){case"Texture":t.transientCanvasTextureCreates=(t.transientCanvasTextureCreates||0)+1;break;case"TextureView":t.transientCanvasTextureViewCreates=(t.transientCanvasTextureViewCreates||0)+1;break;case"Sampler":t.transientCanvasSamplerCreates=(t.transientCanvasSamplerCreates||0)+1;break;case"Framebuffer":t.transientCanvasFramebufferCreates=(t.transientCanvasFramebufferCreates||0)+1;break;default:break}}function ia(r){let e=Object.getPrototypeOf(r);for(;e;){let t=Object.getPrototypeOf(e);if(!t||t===H.prototype)return aa(e)||r[Symbol.toStringTag]||r.constructor.name;e=t}return r[Symbol.toStringTag]||r.constructor.name}function aa(r){let e=Object.getOwnPropertyDescriptor(r,Symbol.toStringTag);return typeof e?.get=="function"?e.get.call(r):typeof e?.value=="string"?e.value:null}var Qi,Ko,Zo,Qo,Ji,ea,ta,ra,Jo,en,H,Nt=y(()=>{"use strict";Vt();Qi="cpu-hotspot-profiler",Ko="GPU Resource Counts",Zo="Resource Counts",Qo="GPU Time and Memory",Ji=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],ea=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","SharedRenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],ta=Ji.flatMap(r=>[`${r} Created`,`${r} Active`]),ra=ea.flatMap(r=>[`${r} Created`,`${r} Active`]),Jo=new WeakMap,en=new WeakMap,H=class{static defaultProps={id:"undefined",handle:void 0,_isHandleBorrowed:!1,userData:void 0};toString(){return`${this[Symbol.toStringTag]||this.constructor.name}:"${this.id}"`}toJSON(){return this.toString()}id;props;userData={};_device;destroyed=!1;allocatedBytes=0;allocatedBytesName=null;_attachedResources=new Set;get ownsHandle(){return(this.props.handle===void 0||this.props.handle===null)&&!this.isHandleBorrowed}get isHandleBorrowed(){return!!this.props._isHandleBorrowed}constructor(e,t,o){if(!e)throw new Error("no device");this._device=e,this.props=oa(t,o);let n=this.props.id!=="undefined"?this.props.id:Ne(this[Symbol.toStringTag]);this.props.id=n,this.id=n,this.userData=this.props.userData||{},this.addStats()}destroy(){this.destroyed||this.destroyResource()}delete(){return this.destroy(),this}getProps(){return this.props}attachResource(e){this._attachedResources.add(e)}detachResource(e){this._attachedResources.delete(e)}destroyAttachedResource(e){this._attachedResources.delete(e)&&e.destroy()}destroyAttachedResources(){for(let e of this._attachedResources)e.destroy();this._attachedResources=new Set}destroyResource(){this.destroyed||(this.destroyAttachedResources(),this.removeStats(),this.destroyed=!0)}removeStats(){let e=ut(this._device),t=e?ye():0,o=[this._device.statsManager.getStats(Ko),this._device.statsManager.getStats(Zo)],n=rn(this._device);for(let a of o)tn(a,n);let i=this.getStatsName();for(let a of o)a.get("Resources Active").decrementCount(),a.get(`${i}s Active`).decrementCount();e&&(e.statsBookkeepingCalls=(e.statsBookkeepingCalls||0)+1,e.statsBookkeepingTimeMs=(e.statsBookkeepingTimeMs||0)+(ye()-t))}trackAllocatedMemory(e,t=this.getStatsName()){let o=ut(this._device),n=o?ye():0,i=this._device.statsManager.getStats(Qo);this.allocatedBytes>0&&this.allocatedBytesName&&(i.get("GPU Memory").subtractCount(this.allocatedBytes),i.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes)),i.get("GPU Memory").addCount(e),i.get(`${t} Memory`).addCount(e),o&&(o.statsBookkeepingCalls=(o.statsBookkeepingCalls||0)+1,o.statsBookkeepingTimeMs=(o.statsBookkeepingTimeMs||0)+(ye()-n)),this.allocatedBytes=e,this.allocatedBytesName=t}trackReferencedMemory(e,t=this.getStatsName()){this.trackAllocatedMemory(e,`External ${t}`)}trackDeallocatedMemory(e=this.getStatsName()){if(this.allocatedBytes===0){this.allocatedBytesName=null;return}let t=ut(this._device),o=t?ye():0,n=this._device.statsManager.getStats(Qo);n.get("GPU Memory").subtractCount(this.allocatedBytes),n.get(`${this.allocatedBytesName||e} Memory`).subtractCount(this.allocatedBytes),t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(ye()-o)),this.allocatedBytes=0,this.allocatedBytesName=null}trackDeallocatedReferencedMemory(e=this.getStatsName()){this.trackDeallocatedMemory(`Referenced ${e}`)}addStats(){let e=this.getStatsName(),t=ut(this._device),o=t?ye():0,n=[this._device.statsManager.getStats(Ko),this._device.statsManager.getStats(Zo)],i=rn(this._device);for(let a of n)tn(a,i);for(let a of n)a.get("Resources Created").incrementCount(),a.get("Resources Active").incrementCount(),a.get(`${e}s Created`).incrementCount(),a.get(`${e}s Active`).incrementCount();t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(ye()-o)),na(this._device,e)}getStatsName(){return ia(this)}}});var te,on=y(()=>{"use strict";Nt();te=class r extends H{static INDEX=16;static VERTEX=32;static UNIFORM=64;static STORAGE=128;static INDIRECT=256;static QUERY_RESOLVE=512;static MAP_READ=1;static MAP_WRITE=2;static COPY_SRC=4;static COPY_DST=8;get[Symbol.toStringTag](){return"Buffer"}usage;indexType;updateTimestamp;constructor(e,t){let o={...t};(t.usage||0)&r.INDEX&&!t.indexType&&(t.data instanceof Uint32Array?o.indexType="uint32":t.data instanceof Uint16Array?o.indexType="uint16":t.data instanceof Uint8Array&&(o.indexType="uint8")),delete o.data,super(e,o,r.defaultProps),this.usage=o.usage||0,this.indexType=o.indexType,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createBuffer({...this.props,...e})}static DEBUG_DATA_MAX_LENGTH=32;debugData=new ArrayBuffer(0);_setDebugData(e,t,o){if(!this.device.props.debug)return;let n=null,i;ArrayBuffer.isView(e)?(n=e,i=e.buffer):i=e;let a=Math.min(e?e.byteLength:o,r.DEBUG_DATA_MAX_LENGTH);if(i===null)this.debugData=new ArrayBuffer(a);else{let s=Math.min(n?.byteOffset||0,i.byteLength),u=Math.max(0,i.byteLength-s),c=Math.min(a,u);this.debugData=new Uint8Array(i,s,c).slice().buffer}}static defaultProps={...H.defaultProps,handle:void 0,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}}});function nn(){return kr??Uint16Array}function an(r){return!!(kr&&r===kr)}var kr,sn=y(()=>{"use strict";kr=globalThis.Float16Array});var un=y(()=>{"use strict"});var cn=y(()=>{"use strict"});function sa(r){let e=mn(r),t=fa[e];if(!t)throw new Error(`Unsupported variable shader type: ${r}`);return t}function ua(r){let e=dn(r),t=ma[e];if(!t)throw new Error(`Unsupported attribute shader type: ${r}`);let[o,n]=t,i=o==="i32"||o==="u32",a=o!=="u32",s=da[o]*n;return{primitiveType:o,components:n,byteLength:s,integer:i,signed:a}}function ca(r,e){return e===1?r:`vec${e}<${r}>`}function dn(r){return pa[r]||r}function mn(r){return la[r]||r}var Or,mc,da,ma,fa,pa,la,fn=y(()=>{"use strict";Or=class{getVariableShaderTypeInfo(e){return sa(e)}getAttributeShaderTypeInfo(e){return ua(e)}makeShaderAttributeType(e,t){return ca(e,t)}resolveAttributeShaderTypeAlias(e){return dn(e)}resolveVariableShaderTypeAlias(e){return mn(e)}};mc=new Or,da={f32:4,f16:2,i32:4,u32:4},ma={f32:["f32",1],"vec2<f32>":["f32",2],"vec3<f32>":["f32",3],"vec4<f32>":["f32",4],f16:["f16",1],"vec2<f16>":["f16",2],"vec3<f16>":["f16",3],"vec4<f16>":["f16",4],i32:["i32",1],"vec2<i32>":["i32",2],"vec3<i32>":["i32",3],"vec4<i32>":["i32",4],u32:["u32",1],"vec2<u32>":["u32",2],"vec3<u32>":["u32",3],"vec4<u32>":["u32",4]},fa={f32:{type:"f32",components:1},f16:{type:"f16",components:1},i32:{type:"i32",components:1},u32:{type:"u32",components:1},"vec2<f32>":{type:"f32",components:2},"vec3<f32>":{type:"f32",components:3},"vec4<f32>":{type:"f32",components:4},"vec2<f16>":{type:"f16",components:2},"vec3<f16>":{type:"f16",components:3},"vec4<f16>":{type:"f16",components:4},"vec2<i32>":{type:"i32",components:2},"vec3<i32>":{type:"i32",components:3},"vec4<i32>":{type:"i32",components:4},"vec2<u32>":{type:"u32",components:2},"vec3<u32>":{type:"u32",components:3},"vec4<u32>":{type:"u32",components:4},"mat2x2<f32>":{type:"f32",components:4},"mat2x3<f32>":{type:"f32",components:6},"mat2x4<f32>":{type:"f32",components:8},"mat3x2<f32>":{type:"f32",components:6},"mat3x3<f32>":{type:"f32",components:9},"mat3x4<f32>":{type:"f32",components:12},"mat4x2<f32>":{type:"f32",components:8},"mat4x3<f32>":{type:"f32",components:12},"mat4x4<f32>":{type:"f32",components:16},"mat2x2<f16>":{type:"f16",components:4},"mat2x3<f16>":{type:"f16",components:6},"mat2x4<f16>":{type:"f16",components:8},"mat3x2<f16>":{type:"f16",components:6},"mat3x3<f16>":{type:"f16",components:9},"mat3x4<f16>":{type:"f16",components:12},"mat4x2<f16>":{type:"f16",components:8},"mat4x3<f16>":{type:"f16",components:12},"mat4x4<f16>":{type:"f16",components:16},"mat2x2<i32>":{type:"i32",components:4},"mat2x3<i32>":{type:"i32",components:6},"mat2x4<i32>":{type:"i32",components:8},"mat3x2<i32>":{type:"i32",components:6},"mat3x3<i32>":{type:"i32",components:9},"mat3x4<i32>":{type:"i32",components:12},"mat4x2<i32>":{type:"i32",components:8},"mat4x3<i32>":{type:"i32",components:12},"mat4x4<i32>":{type:"i32",components:16},"mat2x2<u32>":{type:"u32",components:4},"mat2x3<u32>":{type:"u32",components:6},"mat2x4<u32>":{type:"u32",components:8},"mat3x2<u32>":{type:"u32",components:6},"mat3x3<u32>":{type:"u32",components:9},"mat3x4<u32>":{type:"u32",components:12},"mat4x2<u32>":{type:"u32",components:8},"mat4x3<u32>":{type:"u32",components:12},"mat4x4<u32>":{type:"u32",components:16}},pa={vec2i:"vec2<i32>",vec3i:"vec3<i32>",vec4i:"vec4<i32>",vec2u:"vec2<u32>",vec3u:"vec3<u32>",vec4u:"vec4<u32>",vec2f:"vec2<f32>",vec3f:"vec3<f32>",vec4f:"vec4<f32>",vec2h:"vec2<f16>",vec3h:"vec3<f16>",vec4h:"vec4<f16>"},la={vec2i:"vec2<i32>",vec3i:"vec3<i32>",vec4i:"vec4<i32>",vec2u:"vec2<u32>",vec3u:"vec3<u32>",vec4u:"vec4<u32>",vec2f:"vec2<f32>",vec3f:"vec3<f32>",vec4f:"vec4<f32>",vec2h:"vec2<f16>",vec3h:"vec3<f16>",vec4h:"vec4<f16>",mat2x2f:"mat2x2<f32>",mat2x3f:"mat2x3<f32>",mat2x4f:"mat2x4<f32>",mat3x2f:"mat3x2<f32>",mat3x3f:"mat3x3<f32>",mat3x4f:"mat3x4<f32>",mat4x2f:"mat4x2<f32>",mat4x3f:"mat4x3<f32>",mat4x4f:"mat4x4<f32>",mat2x2i:"mat2x2<i32>",mat2x3i:"mat2x3<i32>",mat2x4i:"mat2x4<i32>",mat3x2i:"mat3x2<i32>",mat3x3i:"mat3x3<i32>",mat3x4i:"mat3x4<i32>",mat4x2i:"mat4x2<i32>",mat4x3i:"mat4x3<i32>",mat4x4i:"mat4x4<i32>",mat2x2u:"mat2x2<u32>",mat2x3u:"mat2x3<u32>",mat2x4u:"mat2x4<u32>",mat3x2u:"mat3x2<u32>",mat3x3u:"mat3x3<u32>",mat3x4u:"mat3x4<u32>",mat4x2u:"mat4x2<u32>",mat4x3u:"mat4x3<u32>",mat4x4u:"mat4x4<u32>",mat2x2h:"mat2x2<f16>",mat2x3h:"mat2x3<f16>",mat2x4h:"mat2x4<f16>",mat3x2h:"mat3x2<f16>",mat3x3h:"mat3x3<f16>",mat3x4h:"mat3x4<f16>",mat4x2h:"mat4x2<f16>",mat4x3h:"mat4x3<f16>",mat4x4h:"mat4x4<f16>"}});function zt(r,e){switch(e){case 1:return r;case 2:return r+r%2;default:return r+(4-r%4)%4}}var pn=y(()=>{"use strict"});var ln=y(()=>{"use strict"});var hn=y(()=>{"use strict"});var gn=y(()=>{"use strict"});var yn=y(()=>{"use strict"});var xn=y(()=>{"use strict";un();cn();fn();ln();hn();gn();yn();pn()});function bn(r){let e=r.includes("norm"),t=!e&&!r.startsWith("float"),o=r.startsWith("s"),n=Fr[r],[i,a,s]=n||["uint8 ","i32",1];return{signedType:i,primitiveType:a,byteLength:s,normalized:e,integer:t,signed:o}}function wn(r){let e=r;switch(e){case"uint8":return"unorm8";case"sint8":return"snorm8";case"uint16":return"unorm16";case"sint16":return"snorm16";default:return e}}function ha(r){let e=ArrayBuffer.isView(r)?r.constructor:r;if(an(e))return"float16";if(e===Uint8ClampedArray)return"uint8";let t=Object.values(Fr).find(o=>e===o[4]);if(!t)throw new Error(e.name);return t[0]}function Tn(r){return ha(r)}function ga(r){if(r==="float16")return nn();let e=Fr[r];if(!e)throw new Error(r);let[,,,,t]=e;return t}function vn(r){return ga(r)}var Fr,Sn=y(()=>{"use strict";sn();xn();Fr={uint8:["uint8","u32",1,!1,Uint8Array],sint8:["sint8","i32",1,!1,Int8Array],unorm8:["uint8","f32",1,!0,Uint8Array],snorm8:["sint8","f32",1,!0,Int8Array],uint16:["uint16","u32",2,!1,Uint16Array],sint16:["sint16","i32",2,!1,Int16Array],unorm16:["uint16","u32",2,!0,Uint16Array],snorm16:["sint16","i32",2,!0,Int16Array],float16:["float16","f16",2,!1,Uint16Array],float32:["float32","f32",4,!1,Float32Array],uint32:["uint32","u32",4,!1,Uint32Array],sint32:["sint32","i32",4,!1,Int32Array]}});var Vr,Cn,Pn=y(()=>{"use strict";Sn();Vr=class{getDataTypeInfo(e){return bn(e)}getNormalizedDataType(e){return wn(e)}alignTo(e,t){return zt(e,t)}getDataType(e){return Tn(e)}getTypedArrayConstructor(e){return vn(e)}},Cn=new Vr});function Xt(r){let e=Ca[r];if(!e)throw new Error(`Unsupported texture format ${r}`);return e}var _,v,re,ya,Wt,Nr,jt,zr,xa,Wr,xe,jr,Hr,Ht,Bn,ct,dt,Xr,Kr,We,Yt,Ln,$,qt,se,oe,ba,Yr,En,wa,F,ze,Ta,qr,va,Sa,Ca,Dn=y(()=>{"use strict";_="texture-compression-bc",v="texture-compression-astc",re="texture-compression-etc2",ya="texture-compression-etc1-webgl",Wt="texture-compression-pvrtc-webgl",Nr="texture-compression-atc-webgl",jt="float32-renderable-webgl",zr="float16-renderable-webgl",xa="rgb9e5ufloat-renderable-webgl",Wr="snorm8-renderable-webgl",xe="norm16-webgl",jr="norm16-renderable-webgl",Hr="snorm16-renderable-webgl",Ht="float32-filterable",Bn="float16-filterable-webgl",ct=1,dt=2,Xr=4,Kr=8,We=16,Yt=5,Ln=10,$=ct|dt,qt=ct|Xr,se=ct|dt|Xr|Kr,oe=ct|dt|We,ba=ct|Xr|We,Yr=se|We,En=(dt|Kr|We)<<Yt,wa=(dt|Kr)<<Yt,F=We<<Yt,ze=Yr<<Yt,Ta=se<<Ln,qr=We<<Ln;va={r8unorm:{webgpu:se|F},rg8unorm:{webgpu:se|F},"rgb8unorm-webgl":{},rgba8unorm:{webgpu:Yr},"rgba8unorm-srgb":{webgpu:se},r8snorm:{render:Wr,webgpu:qt|En},rg8snorm:{render:Wr,webgpu:qt|En},"rgb8snorm-webgl":{},rgba8snorm:{render:Wr,webgpu:ba|wa},r8uint:{webgpu:$|F},rg8uint:{webgpu:$|F},rgba8uint:{webgpu:oe},r8sint:{webgpu:$|F},rg8sint:{webgpu:$|F},rgba8sint:{webgpu:oe},bgra8unorm:{webgpu:se},"bgra8unorm-srgb":{webgpu:Ta},r16unorm:{f:xe,render:jr,webgpu:ze},rg16unorm:{f:xe,render:jr,webgpu:ze},"rgb16unorm-webgl":{f:xe,render:!1},rgba16unorm:{f:xe,render:jr,webgpu:ze},r16snorm:{f:xe,render:Hr,webgpu:ze},rg16snorm:{f:xe,render:Hr,webgpu:ze},"rgb16snorm-webgl":{f:xe,render:!1},rgba16snorm:{f:xe,render:Hr,webgpu:ze},r16uint:{webgpu:$|F},rg16uint:{webgpu:$|F},rgba16uint:{webgpu:oe},r16sint:{webgpu:$|F},rg16sint:{webgpu:$|F},rgba16sint:{webgpu:oe},r16float:{render:zr,filter:"float16-filterable-webgl",webgpu:se|F},rg16float:{render:zr,filter:Bn,webgpu:se|F},rgba16float:{render:zr,filter:Bn,webgpu:Yr},r32uint:{webgpu:oe},rg32uint:{webgpu:$|qr},rgba32uint:{webgpu:oe},r32sint:{webgpu:oe},rg32sint:{webgpu:$|qr},rgba32sint:{webgpu:oe},r32float:{render:jt,filter:Ht,webgpu:oe},rg32float:{render:!1,filter:Ht,webgpu:$|qr},"rgb32float-webgl":{render:jt,filter:Ht},rgba32float:{render:jt,filter:Ht,webgpu:oe},"rgba4unorm-webgl":{channels:"rgba",bitsPerChannel:[4,4,4,4],packed:!0},"rgb565unorm-webgl":{channels:"rgb",bitsPerChannel:[5,6,5,0],packed:!0},"rgb5a1unorm-webgl":{channels:"rgba",bitsPerChannel:[5,5,5,1],packed:!0},rgb9e5ufloat:{channels:"rgb",packed:!0,render:xa,webgpu:qt},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:jt,webgpu:qt|F},rgb10a2unorm:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:se|F},rgb10a2uint:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:$|F},stencil8:{attachment:"stencil",bitsPerChannel:[8,0,0,0],dataType:"uint8",webgpu:$},depth16unorm:{attachment:"depth",bitsPerChannel:[16,0,0,0],dataType:"uint16",webgpu:$},depth24plus:{attachment:"depth",bitsPerChannel:[24,0,0,0],dataType:"uint32",webgpu:$},depth32float:{attachment:"depth",bitsPerChannel:[32,0,0,0],dataType:"float32",webgpu:$},"depth24plus-stencil8":{attachment:"depth-stencil",bitsPerChannel:[24,8,0,0],packed:!0,webgpu:$},"depth32float-stencil8":{attachment:"depth-stencil",bitsPerChannel:[32,8,0,0],packed:!0,f:"depth32float-stencil8",webgpu:$}},Sa={"bc1-rgb-unorm-webgl":{f:_},"bc1-rgb-unorm-srgb-webgl":{f:_},"bc1-rgba-unorm":{f:_},"bc1-rgba-unorm-srgb":{f:_},"bc2-rgba-unorm":{f:_},"bc2-rgba-unorm-srgb":{f:_},"bc3-rgba-unorm":{f:_},"bc3-rgba-unorm-srgb":{f:_},"bc4-r-unorm":{f:_},"bc4-r-snorm":{f:_},"bc5-rg-unorm":{f:_},"bc5-rg-snorm":{f:_},"bc6h-rgb-ufloat":{f:_},"bc6h-rgb-float":{f:_},"bc7-rgba-unorm":{f:_},"bc7-rgba-unorm-srgb":{f:_},"etc2-rgb8unorm":{f:re},"etc2-rgb8unorm-srgb":{f:re},"etc2-rgb8a1unorm":{f:re},"etc2-rgb8a1unorm-srgb":{f:re},"etc2-rgba8unorm":{f:re},"etc2-rgba8unorm-srgb":{f:re},"eac-r11unorm":{f:re},"eac-r11snorm":{f:re},"eac-rg11unorm":{f:re},"eac-rg11snorm":{f:re},"astc-4x4-unorm":{f:v},"astc-4x4-unorm-srgb":{f:v},"astc-5x4-unorm":{f:v},"astc-5x4-unorm-srgb":{f:v},"astc-5x5-unorm":{f:v},"astc-5x5-unorm-srgb":{f:v},"astc-6x5-unorm":{f:v},"astc-6x5-unorm-srgb":{f:v},"astc-6x6-unorm":{f:v},"astc-6x6-unorm-srgb":{f:v},"astc-8x5-unorm":{f:v},"astc-8x5-unorm-srgb":{f:v},"astc-8x6-unorm":{f:v},"astc-8x6-unorm-srgb":{f:v},"astc-8x8-unorm":{f:v},"astc-8x8-unorm-srgb":{f:v},"astc-10x5-unorm":{f:v},"astc-10x5-unorm-srgb":{f:v},"astc-10x6-unorm":{f:v},"astc-10x6-unorm-srgb":{f:v},"astc-10x8-unorm":{f:v},"astc-10x8-unorm-srgb":{f:v},"astc-10x10-unorm":{f:v},"astc-10x10-unorm-srgb":{f:v},"astc-12x10-unorm":{f:v},"astc-12x10-unorm-srgb":{f:v},"astc-12x12-unorm":{f:v},"astc-12x12-unorm-srgb":{f:v},"pvrtc-rgb4unorm-webgl":{f:Wt},"pvrtc-rgba4unorm-webgl":{f:Wt},"pvrtc-rgb2unorm-webgl":{f:Wt},"pvrtc-rgba2unorm-webgl":{f:Wt},"etc1-rbg-unorm-webgl":{f:ya},"atc-rgb-unorm-webgl":{f:Nr},"atc-rgba-unorm-webgl":{f:Nr},"atc-rgbai-unorm-webgl":{f:Nr}},Ca={...va,...Sa}});function Aa({format:r,width:e,height:t,depth:o,byteAlignment:n}){let i=Le.getInfo(r),{bytesPerPixel:a,bytesPerBlock:s=a,blockWidth:u=1,blockHeight:c=1,compressed:d=!1}=i,m=d?Math.ceil(e/u):e,f=d?Math.ceil(t/c):t,p=m*s,h=Math.ceil(p/n)*n,x=f,w=h*x*o;return{bytesPerPixel:a,bytesPerRow:h,rowsPerImage:x,depthOrArrayLayers:o,bytesPerImage:h*x,byteLength:w}}function Ga(r){let e=Xt(r),t={format:r,create:e.f??!0,render:e.render??!0,filter:e.filter??!0,blend:e.blend??!0,store:e.store??!0},o=An(r),n=r.startsWith("depth")||r.startsWith("stencil"),i=o?.signed,a=o?.integer,s=o?.webgl,u=!!o?.compressed;return t.render&&=!n&&!u,t.filter&&=!n&&!i&&!a&&!s,t}function An(r){let e=Ia(r);if(Le.isCompressed(r)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0,e.bytesPerBlock=Ua(r);let o=$a(r);o&&(e.blockWidth=o.blockWidth,e.blockHeight=o.blockHeight)}let t=e.packed?null:Pa.exec(r);if(t){let[,o,n,i,a,s]=t,u=`${i}${n}`,c=Cn.getDataTypeInfo(u),d=c.byteLength*8,m=o?.length??1,f=[d,m>=2?d:0,m>=3?d:0,m>=4?d:0];e={format:r,attachment:e.attachment,dataType:c.signedType,components:m,channels:o,integer:c.integer,signed:c.signed,normalized:c.normalized,bitsPerChannel:f,bytesPerPixel:c.byteLength*m,packed:e.packed,srgb:e.srgb},s==="-webgl"&&(e.webgl=!0),a==="-srgb"&&(e.srgb=!0)}return r.endsWith("-webgl")&&(e.webgl=!0),r.endsWith("-srgb")&&(e.srgb=!0),e}function Ia(r){let e={...Xt(r)},t=e.bytesPerPixel||1,o=e.bitsPerChannel||[8,8,8,8];return delete e.bitsPerChannel,delete e.bytesPerPixel,delete e.f,delete e.render,delete e.filter,delete e.blend,delete e.store,delete e.webgpu,{...e,format:r,attachment:e.attachment||"color",channels:e.channels||"r",components:e.components||e.channels?.length||1,bytesPerPixel:t,bitsPerChannel:o,dataType:e.dataType||"uint8",srgb:e.srgb??!1,packed:e.packed??!1,webgl:e.webgl??!1,integer:e.integer??!1,signed:e.signed??!1,normalized:e.normalized??!1,compressed:e.compressed??!1}}function $a(r){let t=/.*-(\d+)x(\d+)-.*/.exec(r);if(t){let[,o,n]=t;return{blockWidth:Number(o),blockHeight:Number(n)}}return r.startsWith("bc")||r.startsWith("etc1")||r.startsWith("etc2")||r.startsWith("eac")||r.startsWith("atc")?{blockWidth:4,blockHeight:4}:r.startsWith("pvrtc-rgb4")||r.startsWith("pvrtc-rgba4")?{blockWidth:4,blockHeight:4}:r.startsWith("pvrtc-rgb2")||r.startsWith("pvrtc-rgba2")?{blockWidth:8,blockHeight:4}:null}function Ua(r){return r.startsWith("bc1")||r.startsWith("bc4")||r.startsWith("etc1")||r.startsWith("etc2-rgb8")||r.startsWith("etc2-rgb8a1")||r.startsWith("eac-r11")||r==="atc-rgb-unorm-webgl"?8:r.startsWith("bc2")||r.startsWith("bc3")||r.startsWith("bc5")||r.startsWith("bc6h")||r.startsWith("bc7")||r.startsWith("etc2-rgba8")||r.startsWith("eac-rg11")||r.startsWith("astc")||r==="atc-rgba-unorm-webgl"||r==="atc-rgbai-unorm-webgl"?16:r.startsWith("pvrtc")?8:16}var Pa,Ba,Ea,La,Da,Zr,Le,Gn=y(()=>{"use strict";Pn();Dn();Pa=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,Ba=["rgb","rgba","bgra"],Ea=["depth","stencil"],La=5,Da=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"],Zr=class{isColor(e){return Ba.some(t=>e.startsWith(t))}isDepthStencil(e){return Ea.some(t=>e.startsWith(t))}isCompressed(e){return Da.some(t=>e.startsWith(t))}getInfo(e){return An(e)}getCapabilities(e){return Ga(e)}getWebGPUCapabilities(e){let t=Xt(e);return t.webgpu!==void 0?t.webgpu:this.isCompressed(e)&&!e.endsWith("-webgl")?La:0}computeMemoryLayout(e){return Aa(e)}},Le=new Zr});function mt(r){return typeof ImageData<"u"&&r instanceof ImageData||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement||typeof VideoFrame<"u"&&r instanceof VideoFrame||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas}function Kt(r){if(typeof ImageData<"u"&&r instanceof ImageData||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas)return{width:r.width,height:r.height};if(typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement)return{width:r.naturalWidth,height:r.naturalHeight};if(typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement)return{width:r.videoWidth,height:r.videoHeight};if(typeof VideoFrame<"u"&&r instanceof VideoFrame)return{width:r.displayWidth,height:r.displayHeight};throw new Error("Unknown image type")}var In=y(()=>{"use strict"});var be,Qr=y(()=>{"use strict";Nt();be=class r extends H{static defaultProps={...H.defaultProps,type:"color-sampler",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge",magFilter:"nearest",minFilter:"nearest",mipmapFilter:"none",lodMinClamp:0,lodMaxClamp:32,compare:"less-equal",maxAnisotropy:1};get[Symbol.toStringTag](){return"Sampler"}constructor(e,t){t=r.normalizeProps(e,t),super(e,t,r.defaultProps)}static normalizeProps(e,t){return t}}});var _a,R,$n=y(()=>{"use strict";Nt();Qr();Rr();Gn();_a={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"},R=class r extends H{static SAMPLE=4;static STORAGE=8;static RENDER=16;static COPY_SRC=1;static COPY_DST=2;static TEXTURE=4;static RENDER_ATTACHMENT=16;dimension;baseDimension;format;width;height;depth;mipLevels;samples;byteAlignment;ready=Promise.resolve(this);isReady=!0;updateTimestamp;get[Symbol.toStringTag](){return"Texture"}toString(){return`Texture(${this.id},${this.format},${this.width}x${this.height})`}constructor(e,t,o){if(t=r.normalizeProps(e,t),super(e,t,r.defaultProps),this.dimension=this.props.dimension,this.baseDimension=_a[this.dimension],this.format=this.props.format,this.width=this.props.width,this.height=this.props.height,this.depth=this.props.depth,this.mipLevels=this.props.mipLevels,this.samples=this.props.samples||1,this.dimension==="cube"&&(this.depth=6),this.props.width===void 0||this.props.height===void 0)if(e.isExternalImage(t.data)){let n=e.getExternalImageSize(t.data);this.width=n?.width||1,this.height=n?.height||1}else this.width=1,this.height=1,(this.props.width===void 0||this.props.height===void 0)&&Z.warn(`${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`)();this.byteAlignment=o?.byteAlignment||1,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createTexture({...this.props,...e})}setSampler(e){this.sampler=e instanceof be?e:this.device.createSampler(e)}copyImageData(e){let{data:t,depth:o,...n}=e;this.writeData(t,{...n,depthOrArrayLayers:n.depthOrArrayLayers??o})}computeMemoryLayout(e={}){let t=this._normalizeTextureReadOptions(e),{width:o=this.width,height:n=this.height,depthOrArrayLayers:i=this.depth}=t,{format:a,byteAlignment:s}=this;return Le.computeMemoryLayout({format:a,width:o,height:n,depth:i,byteAlignment:s})}readBuffer(e,t){throw new Error("readBuffer not implemented")}readDataAsync(e){throw new Error("readBuffer not implemented")}writeBuffer(e,t){throw new Error("readBuffer not implemented")}writeData(e,t){throw new Error("readBuffer not implemented")}readDataSyncWebGL(e){throw new Error("readDataSyncWebGL not available")}generateMipmapsWebGL(){throw new Error("generateMipmapsWebGL not available")}static normalizeProps(e,t){let o={...t},{width:n,height:i}=o;return typeof n=="number"&&(o.width=Math.max(1,Math.ceil(n))),typeof i=="number"&&(o.height=Math.max(1,Math.ceil(i))),o}_initializeData(e){this.device.isExternalImage(e)?this.copyExternalImage({image:e,width:this.width,height:this.height,depth:this.depth,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1}):e&&this.copyImageData({data:e,mipLevel:0,x:0,y:0,z:0,aspect:"all"})}_normalizeCopyImageDataOptions(e){let{data:t,depth:o,...n}=e,i=this._normalizeTextureWriteOptions({...n,depthOrArrayLayers:n.depthOrArrayLayers??o});return{data:t,depth:i.depthOrArrayLayers,...i}}_normalizeCopyExternalImageOptions(e){let t=r._omitUndefined(e),o=t.mipLevel??0,n=this._getMipLevelSize(o),i=this.device.getExternalImageSize(e.image),a={...r.defaultCopyExternalImageOptions,...n,...i,...t};return a.width=Math.min(a.width,n.width-a.x),a.height=Math.min(a.height,n.height-a.y),a.depth=Math.min(a.depth,n.depthOrArrayLayers-a.z),a}_normalizeCopyElementImageOptions(e){let t=r._omitUndefined(e),o=t.mipLevel??0,n=this._getMipLevelSize(o),i={...r.defaultCopyElementImageOptions,...n,...t};return i.width=Math.min(i.width,n.width-i.x),i.height=Math.min(i.height,n.height-i.y),i.depth=Math.min(i.depth,n.depthOrArrayLayers-i.z),i}_normalizeTextureReadOptions(e){let t=r._omitUndefined(e),o=t.mipLevel??0,n=this._getMipLevelSize(o),i={...r.defaultTextureReadOptions,...n,...t};return i.width=Math.min(i.width,n.width-i.x),i.height=Math.min(i.height,n.height-i.y),i.depthOrArrayLayers=Math.min(i.depthOrArrayLayers,n.depthOrArrayLayers-i.z),i}_getSupportedColorReadOptions(e){let t=this._normalizeTextureReadOptions(e),o=Le.getInfo(this.format);switch(this._validateColorReadAspect(t),this._validateColorReadFormat(o),this.dimension){case"2d":case"cube":case"cube-array":case"2d-array":case"3d":return t;default:throw new Error(`${this} color readback does not support ${this.dimension} textures`)}}_validateColorReadAspect(e){if(e.aspect!=="all")throw new Error(`${this} color readback only supports aspect 'all'`)}_validateColorReadFormat(e){if(e.compressed)throw new Error(`${this} color readback does not support compressed formats (${this.format})`);switch(e.attachment){case"color":return;case"depth":throw new Error(`${this} color readback does not support depth formats (${this.format})`);case"stencil":throw new Error(`${this} color readback does not support stencil formats (${this.format})`);case"depth-stencil":throw new Error(`${this} color readback does not support depth-stencil formats (${this.format})`);default:throw new Error(`${this} color readback does not support format ${this.format}`)}}_normalizeTextureWriteOptions(e){let t=r._omitUndefined(e),o=t.mipLevel??0,n=this._getMipLevelSize(o),i={...r.defaultTextureWriteOptions,...n,...t};i.width=Math.min(i.width,n.width-i.x),i.height=Math.min(i.height,n.height-i.y),i.depthOrArrayLayers=Math.min(i.depthOrArrayLayers,n.depthOrArrayLayers-i.z);let a=Le.computeMemoryLayout({format:this.format,width:i.width,height:i.height,depth:i.depthOrArrayLayers,byteAlignment:this.byteAlignment}),s=a.bytesPerPixel*i.width;if(i.bytesPerRow=t.bytesPerRow??a.bytesPerRow,i.rowsPerImage=t.rowsPerImage??i.height,i.bytesPerRow<s)throw new Error(`bytesPerRow (${i.bytesPerRow}) must be at least ${s} for ${this.format}`);if(i.rowsPerImage<i.height)throw new Error(`rowsPerImage (${i.rowsPerImage}) must be at least ${i.height} for ${this.format}`);let u=this.device.getTextureFormatInfo(this.format).bytesPerPixel;if(u&&i.bytesPerRow%u!==0)throw new Error(`bytesPerRow (${i.bytesPerRow}) must be a multiple of bytesPerPixel (${u}) for ${this.format}`);return i}_getMipLevelSize(e){let t=Math.max(1,this.width>>e),o=this.baseDimension==="1d"?1:Math.max(1,this.height>>e),n=this.dimension==="3d"?Math.max(1,this.depth>>e):this.depth;return{width:t,height:o,depthOrArrayLayers:n}}getAllocatedByteLength(){let e=0;for(let t=0;t<this.mipLevels;t++){let{width:o,height:n,depthOrArrayLayers:i}=this._getMipLevelSize(t);e+=Le.computeMemoryLayout({format:this.format,width:o,height:n,depth:i,byteAlignment:1}).byteLength}return e*this.samples}static _omitUndefined(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}static defaultProps={...H.defaultProps,data:null,dimension:"2d",format:"rgba8unorm",usage:r.SAMPLE|r.RENDER|r.COPY_DST,width:void 0,height:void 0,depth:1,mipLevels:1,samples:void 0,sampler:{},view:void 0};static defaultCopyDataOptions={data:void 0,byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,width:void 0,height:void 0,depthOrArrayLayers:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all"};static defaultCopyExternalImageOptions={image:void 0,sourceX:0,sourceY:0,width:void 0,height:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultCopyElementImageOptions={element:void 0,width:void 0,height:void 0,sourceX:0,sourceY:0,sourceWidth:void 0,sourceHeight:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultTextureReadOptions={x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"};static defaultTextureWriteOptions={byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"}}});var ft=y(()=>{"use strict";on();$n();Qr();Rr()});var Un=y(()=>{"use strict";In()});var Zt=y(()=>{"use strict";ft();ft();ft();Un();ft()});var Ra,De,_n=y(()=>{"use strict";Zt();Vt();Ra=te.DEBUG_DATA_MAX_LENGTH,De=class{device;id;ready;usage;props;isReady=!0;destroyed=!1;generation=0;updateTimestamp;debugData=new ArrayBuffer(0);_debugDataEnabled;_maxDebugDataByteLength;_ownsBuffer;_buffer;get buffer(){return this._buffer}get byteLength(){return this._buffer.byteLength}get[Symbol.toStringTag](){return"DynamicBuffer"}toString(){return`DynamicBuffer:"${this.id}":${this.byteLength}B`}toJSON(){return this.toString()}constructor(e,t){let{debugData:o=!1,buffer:n,ownsBuffer:i=!0,...a}=t;if(n&&n.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(n&&(a.byteLength!==void 0||a.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let s=t.id||n?.id||Ne("dynamic-buffer"),u={...a,id:s,usage:a.usage??n?.usage,indexType:a.indexType??n?.indexType};(u.usage||0)&te.INDEX&&!u.indexType&&(a.data instanceof Uint32Array?u.indexType="uint32":a.data instanceof Uint16Array?u.indexType="uint16":a.data instanceof Uint8Array&&(u.indexType="uint8")),delete u.data,delete u.byteOffset,this.device=e,this.id=s,this.props=u,this.usage=u.usage||0,this._debugDataEnabled=!!o,this._maxDebugDataByteLength=typeof o=="object"&&o.maxByteLength!==void 0?o.maxByteLength:Ra,this._ownsBuffer=i,this._buffer=n??this.device.createBuffer({...a,id:s}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),a.data&&this._writeDebugData(a.data,a.byteOffset||0)}write(e,t=0){this._buffer.write(e,t),this._touch(),this._writeDebugData(e,t)}async mapAndWriteAsync(e,t=0,o=this.byteLength-t){let n=null;await this._buffer.mapAndWriteAsync(async(i,a)=>{await e(i,a),n=new Uint8Array(i.slice(0,o))},t,o),this._touch(),n&&this._writeDebugData(n,t)}async readAsync(e=0,t=this.byteLength-e){let o=await this._buffer.readAsync(e,t);return this._writeDebugData(o,e)&&this._touch(),o}async mapAndReadAsync(e,t=0,o=this.byteLength-t){let n=null,i=await this._buffer.mapAndReadAsync(async(a,s)=>(n=new Uint8Array(a.slice(0)),await e(a,s)),t,o);return n&&this._writeDebugData(n,t)&&this._touch(),i}resize(e){let{byteLength:t,preserveData:o=!1}=e;if(t===this.byteLength)return!1;let n=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),i=this._buffer,a=this.debugData.slice(0),{data:s,byteOffset:u,...c}=this.props,d=this.device.createBuffer({...c,byteLength:t});return o&&n>0&&this._copyBufferContents(i,d,n),this._buffer=d,this._resetDebugData(t),o&&a.byteLength>0&&this._writeDebugData(a,0),this._ownsBuffer&&i.destroy(),this._ownsBuffer=!0,this.generation++,this._touch(),!0}ensureSize(e,t){return e<=this.byteLength?!1:this.resize({byteLength:e,preserveData:t?.preserveData})}getBinding(e){return e?.offset===void 0&&e?.size===void 0?this._buffer:{buffer:this._buffer,offset:e?.offset,size:e?.size}}destroy(){this.destroyed||(this._ownsBuffer&&this._buffer.destroy(),this.destroyed=!0,this.debugData=new ArrayBuffer(0))}_copyBufferContents(e,t,o){let n=this.device.type==="webgpu"?Math.ceil(o/4)*4:o,i=this.device.createCommandEncoder();i.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:n}),this.device.submit(i.finish())}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_resetDebugData(e){if(!this._debugDataEnabled){this.debugData=new ArrayBuffer(0);return}this.debugData=new ArrayBuffer(Math.min(e,this._maxDebugDataByteLength))}_writeDebugData(e,t){if(!this._debugDataEnabled||this.debugData.byteLength===0||t>=this.debugData.byteLength)return!1;let o=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),n=new Uint8Array(this.debugData),i=Math.min(o.byteLength,n.byteLength-t);return n.set(o.subarray(0,i),t),i>0}}});function pt(r){return r?Array.isArray(r)?r[0]??null:r:null}function Rn(r){let{dimension:e,data:t}=r;if(!t)return null;switch(e){case"1d":{let o=pt(t);if(!o)return null;let{width:n}=lt(o);return{width:n,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let o=pt(t);return o?lt(o):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let o=pt(t[0]);return o?lt(o):null}case"cube":{let o=Object.keys(t)[0]??null;if(!o)return null;let n=t[o],i=pt(n);return i?lt(i):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let o=t[0],n=Object.keys(o)[0]??null;if(!n)return null;let i=pt(o[n]);return i?lt(i):null}default:return null}}function lt(r){if(mt(r))return Kt(r);if(typeof r=="object"&&"width"in r&&"height"in r)return{width:r.width,height:r.height};throw new Error("Unsupported mip-level data")}function Ma(r){return typeof r=="object"&&r!==null&&"data"in r&&"width"in r&&"height"in r}function ka(r){return ArrayBuffer.isView(r)}function eo(r){let{textureFormat:e,format:t}=r;if(e&&t&&e!==t)throw new Error(`Conflicting texture formats "${e}" and "${t}" provided for the same mip level`);return e??t}function Mn(r){let e=Jr[r];if(e===void 0)throw new Error(`Invalid cube face: ${r}`);return e}function Oa(r,e){return 6*r+Mn(e)}function to(r){throw new Error("setTexture1DData not supported in WebGL.")}function Fa(r){return Array.isArray(r)?r:[r]}function Ae(r,e,t,o){let n=Fa(e),i=r,a=[];for(let s=0;s<n.length;s++){let u=n[s];if(mt(u))a.push({type:"external-image",image:u,z:i,mipLevel:s});else if(Ma(u))a.push({type:"texture-data",data:u,textureFormat:eo(u),z:i,mipLevel:s});else if(ka(u)&&t)a.push({type:"texture-data",data:{data:u,width:Math.max(1,t.width>>s),height:Math.max(1,t.height>>s),...o?{format:o}:{}},textureFormat:o,z:i,mipLevel:s});else throw new Error("Unsupported 2D mip-level payload")}return a}function ro(r){let e=[];for(let t=0;t<r.length;t++)e.push(...Ae(t,r[t]));return e}function oo(r){let e=[];for(let t=0;t<r.length;t++)e.push(...Ae(t,r[t]));return e}function no(r){let e=[];for(let[t,o]of Object.entries(r)){let n=Mn(t);e.push(...Ae(n,o))}return e}function io(r){let e=[];return r.forEach((t,o)=>{for(let[n,i]of Object.entries(t)){let a=Oa(o,n);e.push(...Ae(a,i))}}),e}var Jr,ao=y(()=>{"use strict";Zt();Jr={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5}});function Va(r){if(!r.data)return[];let e=r.width&&r.height?{width:r.width,height:r.height}:void 0,t="format"in r?r.format:void 0;switch(r.dimension){case"1d":return to(r.data);case"2d":return Ae(0,r.data,e,t);case"3d":return ro(r.data);case"2d-array":return oo(r.data);case"cube":return no(r.data);case"cube-array":return io(r.data);default:throw new Error(`Unhandled dimension ${r.dimension}`)}}function Na(r,e,t,o){if(e.length===0)return{subresources:e,mipLevels:1,format:o.format,hasExplicitMipChain:!1};let n=new Map;for(let d of e){let m=n.get(d.z)??[];m.push(d),n.set(d.z,m)}let i=e.some(d=>d.mipLevel>0),a=o.format,s=Number.POSITIVE_INFINITY,u=[];for(let[d,m]of n){let f=[...m].sort((L,C)=>L.mipLevel-C.mipLevel),p=f[0];if(!p||p.mipLevel!==0)throw new Error(`DynamicTexture: slice ${d} is missing mip level 0`);let h=On(r,p);if(h.width!==t.width||h.height!==t.height)throw new Error(`DynamicTexture: slice ${d} base level dimensions ${h.width}x${h.height} do not match expected ${t.width}x${t.height}`);let x=kn(p);if(x){if(a&&a!==x)throw new Error(`DynamicTexture: slice ${d} base level format "${x}" does not match texture format "${a}"`);a=x}let w=a&&r.isTextureFormatCompressed(a)?za(r,h.width,h.height,a):r.getMipLevelCount(h.width,h.height),G=0;for(let L=0;L<f.length;L++){let C=f[L];if(!C||C.mipLevel!==L||L>=w)break;let W=On(r,C),g=Math.max(1,h.width>>L),l=Math.max(1,h.height>>L);if(W.width!==g||W.height!==l)break;let T=kn(C);if(T&&(a||(a=T),T!==a))break;G++,u.push(C)}s=Math.min(s,G)}let c=Number.isFinite(s)?Math.max(1,s):1;return{subresources:u.filter(d=>d.mipLevel<c),mipLevels:c,format:a,hasExplicitMipChain:i}}function kn(r){if(r.type==="texture-data")return r.textureFormat??eo(r.data)}function On(r,e){switch(e.type){case"external-image":return r.getExternalImageSize(e.image);case"texture-data":return{width:e.data.width,height:e.data.height};default:throw new Error("Unsupported texture subresource")}}function za(r,e,t,o){let{blockWidth:n=1,blockHeight:i=1}=r.getTextureFormatInfo(o),a=1;for(let s=1;;s++){let u=Math.max(1,e>>s),c=Math.max(1,t>>s);if(u<n||c<i)break;a++}return a}async function so(r){if(r=await r,Array.isArray(r))return await Promise.all(r.map(so));if(r&&typeof r=="object"&&r.constructor===Object){let e=r,t=await Promise.all(Object.values(e).map(so)),o=Object.keys(e),n={};for(let i=0;i<o.length;i++)n[o[i]]=t[i];return n}return r}var Qt,Fn=y(()=>{"use strict";Zt();Vt();ao();Qt=class r{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;generation=0;updateTimestamp;resolveReady=()=>{};rejectReady=()=>{};get texture(){if(!this._texture)throw new Error("Texture not initialized yet");return this._texture}get sampler(){if(!this._sampler)throw new Error("Sampler not initialized yet");return this._sampler}get view(){if(!this._view)throw new Error("View not initialized yet");return this._view}get[Symbol.toStringTag](){return"DynamicTexture"}toString(){let e=this._texture?.width??this.props.width??"?",t=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${t}px:(${this.isReady?"ready":"loading..."})`}resolveTextureBinding(e){return this.isReady?this.texture:null}constructor(e,t){this.device=e;let o=Ne("dynamic-texture"),n=t;this.props={...r.defaultProps,id:o,...t,data:null},this.id=this.props.id,this.ready=new Promise((i,a)=>{this.resolveReady=i,this.rejectReady=a}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(n)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let o=t.data?Va({...t,width:e.width,height:e.height,format:e.format}):[],n="format"in e&&e.format!==void 0,i="usage"in e&&e.usage!==void 0,s=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let x=Rn(t);return x||{width:this.props.width||1,height:this.props.height||1}})();if(!s||s.width<=0||s.height<=0)throw new Error(`${this} size could not be determined or was zero`);let u=Na(this.device,o,s,{format:n?e.format:void 0}),c=u.format??this.props.format,d={...this.props,...s,format:c,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(c)&&!i&&(d.usage=R.SAMPLE|R.COPY_DST);let m=this.props.mipmaps&&!u.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(c);if(this.device.type==="webgpu"&&m){let x=this.props.dimension==="3d"?R.SAMPLE|R.STORAGE|R.COPY_DST|R.COPY_SRC:R.SAMPLE|R.RENDER|R.COPY_DST|R.COPY_SRC;d.usage|=x}let f=this.device.getMipLevelCount(d.width,d.height),p=u.hasExplicitMipChain?u.mipLevels:this.props.mipLevels==="auto"?f:Math.max(1,Math.min(f,this.props.mipLevels??1)),h={...d,mipLevels:p};this._texture=this.device.createTexture(h),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),u.subresources.length&&this._setTextureSubresources(u.subresources),this.props.mipmaps&&!u.hasExplicitMipChain&&!m&&Z.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),m&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),Z.info(1,`${this} created`)()}catch(t){let o=t instanceof Error?t:new Error(String(t));this.rejectReady(o)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.isReady=!1,this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?(this.texture.generateMipmapsWebGL(),this._touch()):this.device.type==="webgpu"?(this.device.generateMipmapsWebGPU(this.texture),this._touch()):Z.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof be?e:this.device.createSampler(e);this.texture.setSampler(t),this._sampler=t,this._touchGeneration()}async readBuffer(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,o=e.height??this.texture.height,n=e.depthOrArrayLayers??this.texture.depth,i=this.texture.computeMemoryLayout({width:t,height:o,depthOrArrayLayers:n}),a=this.device.createBuffer({byteLength:i.byteLength,usage:te.COPY_DST|te.MAP_READ});this.texture.readBuffer({...e,width:t,height:o,depthOrArrayLayers:n},a);let s=this.device.createFence();return await s.signaled,s.destroy(),a}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,o=e.height??this.texture.height,n=e.depthOrArrayLayers??this.texture.depth,i=this.texture.computeMemoryLayout({width:t,height:o,depthOrArrayLayers:n}),a=await this.readBuffer(e),s=await a.readAsync(0,i.byteLength);return a.destroy(),s.buffer instanceof ArrayBuffer?s.buffer:s.slice().buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;let t=this.texture;return this._texture=t.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,t.destroy(),this._touchGeneration(),Z.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=Jr[e];if(t===void 0)throw new Error(`Invalid cube face: ${e}`);return t}getCubeArrayFaceIndex(e,t){return 6*e+this.getCubeFaceIndex(t)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let t=to(e);this._setTextureSubresources(t)}setTexture2DData(e,t=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let o=Ae(t,e);this._setTextureSubresources(o)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=ro(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=oo(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=no(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=io(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:o,mipLevel:n}=t;switch(t.type){case"external-image":let{image:i,flipY:a}=t;this.texture.copyExternalImage({image:i,z:o,mipLevel:n,flipY:a});break;case"texture-data":let{data:s,textureFormat:u}=t;if(u&&u!==this.texture.format)throw new Error(`${this} mip level ${n} uses format "${u}" but texture format is "${this.texture.format}"`);this.texture.writeData(s.data,{x:0,y:0,z:o,width:s.width,height:s.height,depthOrArrayLayers:1,mipLevel:n});break;default:throw new Error("Unsupported 2D mip-level payload")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await so(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&Z.warn(`${this} already destroyed`)}_checkReady(){this.isReady||Z.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...R.defaultProps,dimension:"2d",data:null,mipmaps:!1}}});var Vn=y(()=>{"use strict"});var Nn=y(()=>{"use strict";_n();Fn();ao();Vn()});function we(r){return zn.test(r)}function Te(r){return Wn.test(r)}function jn(r){let e=zn.exec(r),t=Wn.exec(r),n=Hn(r)?.elementFormat??e?.[1]??t?.[1]??r;try{ht.vertexFormatDecoder.getVertexFormatInfo(n)}catch{throw new Error(`Unsupported GPUVector format ${r}`)}return n}function V(r){let e=jn(r),t=we(r),o=Te(r),n=Hn(r),i=ht.vertexFormatDecoder.getVertexFormatInfo(e),a=i.byteLength*(n?.listSize??1);if(!Number.isSafeInteger(a))throw new Error(`Unsupported GPUVector format ${r}`);let s=i.type,u=i.normalized,c=ja(s,u);return{format:r,elementFormat:e,vertexList:t,valueList:o,fixedSizeList:!!n,...n?{listSize:n.listSize}:{},type:s,signedDataType:Ha(e,s),primitiveType:c,components:i.components,elementByteLength:i.byteLength,byteLength:a,integer:i.integer,signed:i.signed,normalized:u,...i.webglOnly?{webglOnly:!0}:{}}}function Hn(r){let e=Wa.exec(r);if(!e)return;let t=Number(e[2]);if(!Number.isSafeInteger(t))return;let o=e[1];try{let n=ht.vertexFormatDecoder.getVertexFormatInfo(o);if(!Number.isSafeInteger(t*n.components)||!Number.isSafeInteger(t*n.byteLength))return}catch{return}return{elementFormat:o,listSize:t}}function ja(r,e){if(e)return"f32";switch(r){case"float32":return"f32";case"float16":return"f16";case"uint8":case"uint16":case"uint32":return"u32";case"sint8":case"sint16":case"sint32":return"i32";default:throw new Error(`Unsupported GPUVector component type ${r}`)}}function Ha(r,e){if(r==="unorm10-10-10-2")return"uint32";switch(e){case"unorm8":return"uint8";case"snorm8":return"sint8";case"unorm16":return"uint16";case"snorm16":return"sint16";default:return e}}var ht,zn,Wn,Wa,qn=y(()=>{"use strict";ht=ee(K(),1),zn=/^vertex-list<([^<>]+)>$/,Wn=/^value-list<([^<>]+)>$/,Wa=/^fixed-size-list<([^<>,]+),([1-9][0-9]*)>$/});function Ge(r){let e=0;return Object.freeze(r.map(t=>{let o=Object.freeze({offset:e,length:t.length,data:t});return e+=t.length,o}))}var Yn=y(()=>{"use strict"});var uo,Ie=y(()=>{"use strict";qn();uo=ee(K(),1);Yn()});var me,I,xi=y(()=>{"use strict";me=ee(K(),1),I=class r{static async createAsync(e,t){let o=!me.PipelineFactory.getAsyncCompilation(e),n=o?me.PipelineFactory.beginAsyncCompilation(e):me.PipelineFactory.getAsyncCompilation(e),i;try{i=new r(e,t)}finally{o&&me.PipelineFactory.endAsyncCompilation(e,n)}try{return o?await Promise.all(n):await i._pipelineInitialization,i}catch(a){throw i.destroy(),a}}device;id;source;pipelineFactory;shaderFactory;shader;pipeline;_pipelineInitialization;_destroyed=!1;constructor(e,t){if(e.type!=="webgpu")throw new Error("Kernel is only supported in WebGPU");let{source:o,pipelineFactory:n,shaderFactory:i,debugShaders:a,...s}=t;this.device=e,this.id=t.id??"kernel",this.source=o,this.pipelineFactory=n??me.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=i??me.ShaderFactory.getDefaultShaderFactory(e),this.shader=this.shaderFactory.createShader({id:`${this.id}-compute`,stage:"compute",source:this.source,debugShaders:a});let u={...s,shader:this.shader},c=me.PipelineFactory.getAsyncCompilation(e);if(c){let d=this.pipelineFactory.createComputePipelineAsync(u);this._pipelineInitialization=d,c.push(d.then(m=>(this.pipeline=m,m)))}else this.pipeline=this.pipelineFactory.createComputePipeline(u)}dispatch(e,t){this._setPipeline(e,t.bindings),e.dispatch(t.x,t.y,t.z)}dispatchIndirect(e,t){this._setPipeline(e,t.bindings),e.dispatchIndirect(t.indirectBuffer,t.indirectOffset??0)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.shader),this._destroyed=!0)}_setPipeline(e,t={}){e.setPipeline(this.pipeline),e.setBindings(t)}}});var fe=y(()=>{"use strict";xi()});var Lt={};Ni(Lt,{CompiledGPUCommandGraph:()=>qe,GPUCommandGraph:()=>He,GPUCommandGraphAutotuner:()=>Do,GPUCommandGraphEncoding:()=>St,GPUCommandGraphExecution:()=>vt,GPUCommandGraphExecutionBudgetController:()=>Ao,GPUCommandGraphInspector:()=>Go,GPUGraph:()=>er,GPUGraphCompiler:()=>xr,GPUGraphScalar:()=>Ye,GPUGraphTexture:()=>Ke,GPUGraphTextureView:()=>de,GPUGraphVector:()=>Xe,GPUOperationLoweringRegistry:()=>rt,GraphBufferHandle:()=>Se,GraphDataView:()=>ce,GraphExternalTextureHandle:()=>Ue,GraphTextureHandle:()=>ne,GraphTextureView:()=>Ce,GraphVectorView:()=>B,composite:()=>hi,getGPUCommandGraphAdapterIdentity:()=>Gs,getGPUCommandGraphExecutionPlan:()=>xo,inspectGPUGraphCompilation:()=>Ei,validateGPUGraph:()=>yr});It(Lt,ee(K(),1));var Be=ee(K(),1);async function Fo(r,e){if(r.destroyed)throw new Error("Resource has been destroyed.");if(r instanceof Be.Buffer){if(!(r.usage&Be.Buffer.COPY_SRC))throw new Error("Preview requires COPY_SRC usage.");let c=e.byteOffset??0,d=Math.min(256,e.byteLength??r.byteLength-c);if(c<0||d<0||c+d>r.byteLength)throw new Error("Preview range is outside the buffer.");return{data:d?await r.readAsync(c,d):new Uint8Array,format:e.format}}let t=r.device.getTextureFormatInfo(r.format);if(t.packed)throw new Error("Packed texture previews are not supported.");if(r.device.type!=="webgpu")throw new Error("Texture previews require WebGPU.");if(!((r.props.usage??0)&Be.Texture.COPY_SRC))throw new Error("Preview requires COPY_SRC usage.");if(r.samples!==1||t.compressed||r.format.startsWith("depth")||r.format.startsWith("stencil"))throw new Error("Preview requires a single-sample, uncompressed color texture.");let o=e.baseMipLevel??0,n=Math.min(32,e.width??Math.max(1,r.width>>o)),i=Math.min(32,e.height??Math.max(1,r.height>>o)),a=r.computeMemoryLayout({width:n,height:i,depthOrArrayLayers:1}),s=r.device.createBuffer({byteLength:a.byteLength,usage:Be.Buffer.MAP_READ|Be.Buffer.COPY_DST}),u=r.device.createCommandEncoder();try{u.copyTextureToBuffer({sourceTexture:r,destinationBuffer:s,mipLevel:o,origin:[0,0,e.baseArrayLayer??0],width:n,height:i,depthOrArrayLayers:1,bytesPerRow:a.bytesPerRow}),r.device.submit(u.finish());let c=await s.readAsync(),d=n*t.bytesPerPixel,m=new Uint8Array(d*i);for(let f=0;f<i;f++)m.set(c.subarray(f*a.bytesPerRow,f*a.bytesPerRow+d),f*d);return{data:m,width:n,height:i,format:r.format}}finally{s.destroy(),u.destroy()}}var N=ee(K(),1);Nn();Ie();var gt=class{compare;values=[];constructor(e){this.compare=e}peek(){return this.values[0]}push(e){let t=this.values.length;for(this.values.push(e);t>0;){let o=Math.floor((t-1)/2);if(this.compare(this.values[o],e)<=0)break;this.values[t]=this.values[o],t=o}this.values[t]=e}pop(){let e=this.values[0],t=this.values.pop();if(this.values.length&&t!==void 0){let o=0;for(;o*2+1<this.values.length;){let n=o*2+1;if(n+1<this.values.length&&this.compare(this.values[n+1],this.values[n])<0&&n++,this.compare(t,this.values[n])<=0)break;this.values[o]=this.values[n],o=n}this.values[o]=t}return e}};var yt=ee(K(),1);function Jn(r){let e=oi(r.nodes),t=ni(e,r.buffers.values()),o=ii(e,r.textures.values()),n=new Map,i=new Map,a=[];try{for(let s of t){s.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(s)}`,byteLength:s.byteLength,usage:s.usage});for(let u of s.handles)n.set(u,s.buffer)}for(let s of o){s.texture=r.device.createTexture({...s.descriptor,id:`${r.id}-transient-texture-${o.indexOf(s)}`});for(let u of s.handles)i.set(u,s.texture)}for(let s of e)a.push({node:s,executable:s.compile({device:r.device})})}catch(s){for(let u of a)u.executable.destroy?.();for(let u of t)u.buffer?.destroy();for(let u of o)u.texture?.destroy();throw s}return ti(r,e,a,n,i,t,o)}async function ei(r){let e=oi(r.nodes),t=ni(e,r.buffers.values()),o=ii(e,r.textures.values()),n=new Map,i=new Map;try{for(let p of t){p.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(p)}`,byteLength:p.byteLength,usage:p.usage});for(let h of p.handles)n.set(h,p.buffer)}for(let p of o){p.texture=r.device.createTexture({...p.descriptor,id:`${r.id}-transient-texture-${o.indexOf(p)}`});for(let h of p.handles)i.set(h,p.texture)}let a=yt.PipelineFactory.beginAsyncCompilation(r.device),s=e.map(async p=>({node:p,executable:p.compileAsync?await p.compileAsync({device:r.device}):p.compile({device:r.device})}));yt.PipelineFactory.endAsyncCompilation(r.device,a);let[u,c]=await Promise.all([Promise.allSettled(s),Promise.allSettled(a)]),d=[],m=c.find(p=>p.status==="rejected"),f=m?.status==="rejected"?m.reason:void 0;for(let p of u)p.status==="fulfilled"?d.push(p.value):f??=p.reason;if(f){for(let p of d)p.executable.destroy?.();throw f}return ti(r,e,d,n,i,t,o)}catch(a){for(let s of t)s.buffer?.destroy();for(let s of o)s.texture?.destroy();throw a}}function ti(r,e,t,o,n,i,a){let s=Array.from(r.buffers.values()),u=s.filter(b=>!b.transient),c=s.filter(b=>b.transient),d=je(u.map(b=>b.byteLength),"imported buffer capacities"),m=je(c.map(b=>b.byteLength),"logical transient buffer capacities"),f=$e(d,m,"logical buffer capacities"),p=je(i.map(b=>b.byteLength),"physical transient buffer capacities"),h=Math.max(0,m-p),x=Array.from(r.textures.values()),w=x.filter(b=>!b.transient),G=x.filter(b=>b.transient),L=je(w.map(po),"imported texture estimates"),C=je(G.map(po),"logical transient texture estimates"),W=$e(L,C,"logical texture estimates"),g=je(a.map(b=>b.byteLength),"physical transient texture estimates"),l=Math.max(0,C-g),T={nodeOrder:e.map(b=>b.id),importedBufferCount:u.length,importedBufferBytes:d,logicalBufferCount:s.length,logicalBufferBytes:f,logicalTransientBufferCount:c.length,physicalTransientBufferCount:i.length,logicalTransientBytes:m,physicalTransientBytes:p,reusedTransientBytes:h,reusePercentage:m>0?h/m*100:0,importedTextureCount:w.length,importedTextureBytes:L,logicalTextureCount:x.length,logicalTextureBytes:W,logicalTransientTextureCount:G.length,physicalTransientTextureCount:a.length,logicalTransientTextureBytes:C,physicalTransientTextureBytes:g,reusedTransientTextureBytes:l,textureReusePercentage:C>0?l/C*100:0,logicalResourceBytes:$e(f,W,"logical resource estimates"),physicalTransientResourceBytes:$e(p,g,"physical transient resource estimates")},S=Ya(r.device,s,e);return{device:r.device,id:r.id,buffers:new Map(r.buffers),textures:new Map(r.textures),externalTextures:new Map(r.externalTextures),compiledNodes:t,transientBuffers:o,transientTextures:n,bufferTransientAllocations:i,textureTransientAllocations:a,stats:T,preflight:S}}function qa(r){if("buffer"in r){let t=r.buffer,o="buffer"in t?t:void 0;return Object.freeze({id:o?o.buffer.id:t.id,kind:"buffer",usage:r.usage,byteOffset:o?.byteOffset??0,byteLength:o?o.length===0?0:(o.length-1)*o.byteStride+o.rowByteLength:t.byteLength,...o?{format:o.format,length:o.length}:{}})}let e="texture"in r?r.texture:r.externalTexture;return Object.freeze({id:"texture"in e?e.texture.id:e.id,kind:"externalTexture"in r?"external-texture":"texture",usage:r.usage,width:e.width,height:e.height,..."texture"in e?{baseMipLevel:e.baseMipLevel,baseArrayLayer:e.baseArrayLayer,mipLevelCount:e.mipLevelCount,arrayLayerCount:e.arrayLayerCount,aspect:e.aspect}:{},..."format"in e?{format:e.format,depth:e.depth}:{}})}function Ya(r,e,t){let o=t.map(s=>{let u=s.workload??{};return Object.freeze({id:s.id,...s.description===void 0?{}:{description:s.description},type:s.type,resources:Object.freeze((s.resources??[]).map(qa)),...u.operation?{operation:u.operation}:{},...u.variant?{variant:u.variant}:{},...s.publication?{publication:Object.freeze({...s.publication})}:{},...s.condition?{condition:Object.freeze(s.condition.source==="cpu"?{id:s.condition.id,source:"cpu",mode:"skip"}:{id:s.condition.id,source:"gpu",mode:"indirect",bufferId:s.condition.buffer.id,byteOffset:s.condition.byteOffset??0})}:{},commandCount:u.commandCount??0,maximumWorkgroupCount:u.maximumWorkgroupCount??0,maximumInvocationCount:u.maximumInvocationCount??0,readByteLength:u.readByteLength??0,writeByteLength:u.writeByteLength??0})}),n=e.reduce((s,u)=>Math.max(s,u.byteLength),0),i=t.reduce((s,u)=>{for(let c of u.resources??[])ve(c)&&(c.usage==="storage-read"||c.usage==="storage-write"||c.usage==="storage-read-write")&&(s=Math.max(s,mo(c.buffer).size));return s},0),a=s=>o.reduce((u,c)=>{let d=c[s];return typeof d=="number"?$e(u,d,"workload estimates"):u},0);return Object.freeze({nodes:Object.freeze(o),annotatedNodeCount:t.filter(s=>s.workload!==void 0).length,conditionalNodeCount:t.filter(s=>s.condition!==void 0).length,commandCount:a("commandCount"),maximumWorkgroupCount:a("maximumWorkgroupCount"),maximumInvocationCount:a("maximumInvocationCount"),readByteLength:a("readByteLength"),writeByteLength:a("writeByteLength"),largestBufferByteLength:n,largestStorageBufferBindingByteLength:i,maxBufferByteLength:r.limits.maxBufferSize,maxStorageBufferBindingByteLength:r.limits.maxStorageBufferBindingSize,fitsDeviceLimits:n<=r.limits.maxBufferSize&&i<=r.limits.maxStorageBufferBindingSize})}function Q(r){return"buffer"in r?r.buffer:r}function ue(r){return"texture"in r?r.texture:r}function ve(r){return"buffer"in r}function xt(r){return"texture"in r}function ri(r){if(r.type==="copy")return;let e=(r.resources??[]).filter(t=>ve(t)&&(t.usage==="storage-read"||t.usage==="storage-write"||t.usage==="storage-read-write"));for(let t=0;t<e.length;t++){let o=e[t];for(let n=t+1;n<e.length;n++){let i=e[n];if(o.buffer===i.buffer||Q(o.buffer)!==Q(i.buffer)||!fo(o.usage)&&!fo(i.usage))continue;let a=mo(o.buffer),s=mo(i.buffer);if(a.offset<s.offset+s.size&&s.offset<a.offset+a.size){let u=Q(o.buffer);throw new Error(`GPUCommandGraph node "${r.id}" has overlapping writable storage bindings for buffer "${u.id}" (${Xn(a)} and ${Xn(s)}). Bind the shared range once or align the views to non-overlapping storage binding ranges.`)}}}}function mo(r){if(!("buffer"in r))return{offset:0,size:r.byteLength};let e=256,t=Math.floor(r.byteOffset/e)*e,o=r.byteOffset-t,n=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:t,size:o+Math.max(n,r.rowByteLength)}}function Xn(r){return`${r.offset}\u2013${r.offset+r.size} bytes`}function Xa(r){return r==="storage-read"||r==="storage-read-write"||r==="uniform"||r==="copy-source"||r==="indirect"||r==="vertex"||r==="index"}function fo(r){return r==="storage-write"||r==="storage-read-write"||r==="copy-destination"}function Kn(r){return r==="sampled"||r==="storage-read"||r==="storage-read-write"||r==="render-attachment"||r==="copy-source"}function co(r){return r==="storage-write"||r==="storage-read-write"||r==="render-attachment"||r==="copy-destination"}function oi(r){let e=new Map(r.map(m=>[m.id,m])),t=new Map,o=new Map,n=new Map,i=new Map;for(let m of r){let f=new Set(m.dependsOn??[]);for(let p of f)if(!e.has(p))throw new Error(`GPUCommandGraph node "${m.id}" depends on missing node "${p}"`);for(let p of m.resources??[])if(ve(p)){let h=Q(p.buffer);if(Xa(p.usage)){let x=o.get(h);x&&f.add(x);let w=n.get(h)??new Set;w.add(m.id),n.set(h,w)}if(fo(p.usage)){let x=o.get(h);x&&f.add(x);for(let w of n.get(h)??[])w!==m.id&&f.add(w);n.set(h,new Set),o.set(h,m.id)}}else if(xt(p)){let h=ue(p.texture),x=i.get(h)??[];for(let w of x)w.nodeId!==m.id&&Ka(w.resource,p)&&(Kn(p.usage)&&co(w.resource.usage)||co(p.usage)&&(Kn(w.resource.usage)||co(w.resource.usage)))&&f.add(w.nodeId);x.push({nodeId:m.id,resource:p}),i.set(h,x)}f.delete(m.id),t.set(m.id,f)}let a=r.map(()=>[]),s=new Map(r.map((m,f)=>[m.id,f])),u=r.map(m=>t.get(m.id).size);for(let[m,f]of r.entries())for(let p of t.get(f.id))a[s.get(p)].push(m);let c=u.flatMap((m,f)=>m===0?[f]:[]),d=[];for(;c.length;){let m=[];for(let f of c){d.push(r[f]);for(let p of a[f])--u[p]===0&&m.push(p)}c=m.sort((f,p)=>f-p)}if(d.length!==r.length)throw new Error("GPUCommandGraph contains a dependency cycle");return d}function Ka(r,e){let t=ue(r.texture),o=ue(e.texture);if(t!==o)return!1;let n=Zn(r.texture),i=Zn(e.texture);return Za(n.aspect,i.aspect)&&Qn(n.baseMipLevel,n.mipLevelCount,i.baseMipLevel,i.mipLevelCount)&&Qn(n.baseArrayLayer,n.arrayLayerCount,i.baseArrayLayer,i.arrayLayerCount)}function Zn(r){return"texture"in r?r:{aspect:"all",baseMipLevel:0,mipLevelCount:r.mipLevels,baseArrayLayer:0,arrayLayerCount:r.dimension==="3d"?1:r.depth}}function Za(r,e){return r==="all"||e==="all"||r===e}function Qn(r,e,t,o){return r<t+o&&t<r+e}function ni(r,e){let t=ai(r,s=>ve(s)?Q(s.buffer):null),o=[],n=Array.from(e).filter(s=>s.transient).map(s=>({buffer:s,lifetime:t.get(s)})).sort((s,u)=>(s.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(u.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)),i=new gt((s,u)=>s.allocation.lastUse-u.allocation.lastUse||s.index-u.index),a=new gt((s,u)=>s.allocation.byteLength-u.allocation.byteLength||s.index-u.index);for(let{buffer:s,lifetime:u}of n){if(!u)continue;for(;i.peek()&&i.peek().allocation.lastUse<u.firstUse;)a.push(i.pop());let c=a.pop();c||(c={allocation:{byteLength:0,usage:0,lastUse:-1,handles:[]},index:o.length},o.push(c.allocation));let{allocation:d}=c;d.byteLength=Math.max(d.byteLength,s.byteLength),d.usage|=s.usage,d.lastUse=u.lastUse,d.handles.push(s),i.push(c)}return o}function ii(r,e){let t=ai(r,i=>xt(i)?ue(i.texture):null),o=[],n=Array.from(e).filter(i=>i.transient).map(i=>({texture:i,lifetime:t.get(i)})).sort((i,a)=>(i.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(a.lifetime?.firstUse??Number.MAX_SAFE_INTEGER));for(let{texture:i,lifetime:a}of n){if(!a)continue;let s=o.find(u=>u.lastUse<a.firstUse&&Ja(u.descriptor,i));s||(s={descriptor:Qa(i),byteLength:po(i),lastUse:-1,handles:[]},o.push(s)),s.descriptor.usage|=i.usage,s.lastUse=a.lastUse,s.handles.push(i)}return o}function ai(r,e){let t=new Map;return r.forEach((o,n)=>{for(let i of o.resources??[]){let a=e(i);if(!a||!("transient"in a)||!a.transient)continue;let s=t.get(a);s?s.lastUse=n:t.set(a,{firstUse:n,lastUse:n})}}),t}function Qa(r){return{id:r.id,format:r.format,width:r.width,height:r.height,usage:r.usage,dimension:r.dimension,depth:r.depth,mipLevels:r.mipLevels,samples:r.samples}}function Ja(r,e){return r.format===e.format&&r.width===e.width&&r.height===e.height&&r.dimension===e.dimension&&r.depth===e.depth&&r.mipLevels===e.mipLevels&&r.samples===e.samples}function po(r){let e=0;for(let o=0;o<r.mipLevels;o++)e=$e(e,yt.textureFormatDecoder.computeMemoryLayout({format:r.format,width:Math.max(1,r.width>>o),height:r.dimension==="1d"?1:Math.max(1,r.height>>o),depth:r.dimension==="3d"?Math.max(1,r.depth>>o):r.depth,byteAlignment:1}).byteLength,`texture "${r.id}" mip estimates`);let t=e*r.samples;if(!Number.isSafeInteger(t))throw new Error(`GPUCommandGraph texture "${r.id}" byte estimate exceeds safe integer range`);return t}function $e(r,e,t){let o=r+e;if(!Number.isSafeInteger(o))throw new Error(`GPUCommandGraph ${t} exceed safe integer range`);return o}function je(r,e){return r.reduce((t,o)=>$e(t,o,e),0)}Ie();var Se=class{id;byteLength;usage;transient;graph;defaultBuffer;constructor(e,t,o,n){this.graph=e,this.id=t.id,this.byteLength=t.byteLength,this.usage=t.usage,this.transient=o,this.defaultBuffer=n}},ce=class{buffer;format;length;byteOffset;byteStride;rowByteLength;constructor(e,t){this.buffer=e,this.format=t.format,this.length=t.length,this.byteOffset=t.byteOffset,this.byteStride=t.byteStride,this.rowByteLength=t.rowByteLength}},B=class{chunks;id;name;format;length;valueLength;stride;byteStride;rowByteLength;data;constructor(e){if(this.id=e.id,this.name=e.name,this.format=e.format,this.length=e.length,this.valueLength=e.valueLength,this.stride=e.stride,this.byteStride=e.byteStride,this.rowByteLength=e.rowByteLength,e.data.some(t=>t.format!==e.format)||e.data.reduce((t,o)=>t+o.length,0)!==e.length)throw new Error(`${e.id} length must equal its ordered source chunks, with matching formats`);this.data=Object.freeze([...e.data]),this.chunks=Ge(this.data)}},ne=class{id;format;width;height;usage;dimension;depth;mipLevels;samples;transient;frameScoped;graph;defaultTexture;constructor(e,t,o,n,i=!1){this.graph=e,this.id=t.id,this.format=t.format,this.width=t.width,this.height=t.height,this.usage=t.usage,this.dimension=t.dimension,this.depth=t.depth,this.mipLevels=t.mipLevels,this.samples=t.samples,this.transient=o,this.frameScoped=i,this.defaultTexture=n}},Ue=class{id;width;height;graph;constructor(e,t){this.graph=e,this.id=t.id,this.width=t.width,this.height=t.height}},Ce=class{texture;format;dimension;aspect;baseMipLevel;mipLevelCount;baseArrayLayer;arrayLayerCount;width;height;depth;constructor(e,t){this.texture=e,this.format=e.format,this.dimension=t.dimension,this.aspect=t.aspect,this.baseMipLevel=t.baseMipLevel,this.mipLevelCount=t.mipLevelCount,this.baseArrayLayer=t.baseArrayLayer,this.arrayLayerCount=t.arrayLayerCount,this.width=t.width,this.height=t.height,this.depth=t.depth}};function lo(r,e){switch(e.type){case"compute":{let{type:t,...o}=e;r.addComputePass(o);return}case"render":{let{type:t,...o}=e;r.addRenderPass(o);return}case"copy":{let{type:t,...o}=e;r.addCopyPass(o);return}}}function _e(r,e){for(let t of e)lo(r,t)}function M(r){return{...r,type:"compute"}}var es=4,vt=class{nodeCount;budget;plan;encodeNodeRange;nextStepIndex=0;currentPublishedProgress=0;constructor(e){fi(e.budget),this.plan=e.plan,this.nodeCount=e.plan.nodeCount,this.budget=Object.freeze({...e.budget}),this.encodeNodeRange=e.encodeNodeRange}get completed(){return this.nextStepIndex>=this.plan.stepCount}get progress(){return this.plan.stepCount===0?1:this.nextStepIndex/this.plan.stepCount}get publishedProgress(){return this.currentPublishedProgress}encodeNext(e,t){if(this.completed)throw new Error("GPUCommandGraph execution has already completed");let o=this.plan.steps[this.nextStepIndex],n=this.encodeNodeRange(e,t,o.firstNodeIndex,o.nextNodeIndex);return this.nextStepIndex++,o.publishable&&(this.currentPublishedProgress=this.progress),{...o,encoding:n,progress:this.progress,completed:this.completed,publishedProgress:this.publishedProgress}}};function xo(r,e,t={}){fi(e);let o=t.latencyPriority??"normal",n=t.publicationPolicy??"final";if(!["interactive","normal","background"].includes(o))throw new Error(`GPUCommandGraph execution latency priority "${o}" is invalid`);if(!["final","progressive"].includes(n))throw new Error(`GPUCommandGraph execution publication policy "${n}" is invalid`);let i=r.nodes,a=[],s=0;for(;s<i.length;){let c=s,d=si();for(;s<i.length;){let p=ui(d,i[s]);if(s>c&&ci(p,e)||(d=p,s++,n==="progressive"&&i[s-1].publication)||ts(d,e))break}let m=Object.freeze(n==="progressive"?i.slice(c,s).flatMap(p=>p.publication?[p.publication]:[]):[]),f=s===i.length;a.push(Object.freeze({stepIndex:a.length,firstNodeIndex:c,nextNodeIndex:s,...d,exceedsBudget:ci(d,e),latencyPriority:o,publications:m,publishable:f||m.length>0}))}let u=i.reduce((c,d)=>ui(c,d),si());return Object.freeze({...u,annotatedNodeCount:r.annotatedNodeCount,stepCount:a.length,oversizedStepCount:a.filter(c=>c.exceedsBudget).length,latencyPriority:o,publicationPolicy:n,publicationCount:a.reduce((c,d)=>c+d.publications.length,0),steps:Object.freeze(a)})}function si(){return{nodeCount:0,commandCount:0,maximumInvocationCount:0,readByteLength:0,writeByteLength:0,conditionalNodeCount:0}}function ui(r,e){return{nodeCount:r.nodeCount+1,commandCount:r.commandCount+e.commandCount,maximumInvocationCount:r.maximumInvocationCount+e.maximumInvocationCount,readByteLength:r.readByteLength+e.readByteLength,writeByteLength:r.writeByteLength+e.writeByteLength,conditionalNodeCount:r.conditionalNodeCount+(e.condition?1:0)}}function ci(r,e){return r.maximumInvocationCount>e.maximumInvocationCount||e.maximumNodeCount!==void 0&&r.nodeCount>e.maximumNodeCount||e.maximumCommandCount!==void 0&&r.commandCount>e.maximumCommandCount||e.maximumReadByteLength!==void 0&&r.readByteLength>e.maximumReadByteLength||e.maximumWriteByteLength!==void 0&&r.writeByteLength>e.maximumWriteByteLength}function ts(r,e){return r.maximumInvocationCount>=e.maximumInvocationCount||e.maximumNodeCount!==void 0&&r.nodeCount>=e.maximumNodeCount||e.maximumCommandCount!==void 0&&r.commandCount>=e.maximumCommandCount||e.maximumReadByteLength!==void 0&&r.readByteLength>=e.maximumReadByteLength||e.maximumWriteByteLength!==void 0&&r.writeByteLength>=e.maximumWriteByteLength}function fi(r){let e=[["maximumInvocationCount",r.maximumInvocationCount],["maximumNodeCount",r.maximumNodeCount],["maximumCommandCount",r.maximumCommandCount],["maximumReadByteLength",r.maximumReadByteLength],["maximumWriteByteLength",r.maximumWriteByteLength]];for(let[t,o]of e)if(o!==void 0&&(!Number.isSafeInteger(o)||o<=0))throw new Error(`GPUCommandGraph execution ${t} must be a positive safe integer`)}function rs(r,e,t,o){let n=0;return{computePass:new Proxy(r,{get(a,s){if(s==="dispatch")return()=>{if(n>0)throw new Error(`GPUCommandGraph GPU-conditional compute node "${o}" must encode exactly one dispatch`);n++,a.dispatchIndirect(e,t)};if(s==="dispatchIndirect")return()=>{throw new Error(`GPUCommandGraph GPU-conditional compute node "${o}" must use dispatch(); the graph supplies its indirect command`)};let u=Reflect.get(a,s,a);return typeof u=="function"?u.bind(a):u}}),assertDispatched:()=>{if(n!==1)throw new Error(`GPUCommandGraph GPU-conditional compute node "${o}" must encode exactly one dispatch`)}}}var St=class{readResource;stats;canReadGPUTimings;nodes;constructor(e,t,o=e.filter(s=>s.stats.type==="compute"&&s.stats.condition?.outcome!=="skipped").length,n,i,a){this.readResource=a,this.nodes=e,this.canReadGPUTimings=e.some(c=>c.timestamp!==void 0);let s=e.filter(c=>c.stats.condition?.outcome!=="skipped"),u=s.filter(c=>c.stats.type==="compute").length;this.stats={cpuEncodeTimeMilliseconds:t,cpuEncodeStartTimeMilliseconds:n,cpuEncodeEndTimeMilliseconds:i,nodeCount:s.length,skippedNodeCount:e.length-s.length,computePassCount:o,coalescedComputeNodeCount:u-o,timestampedNodeCount:e.filter(c=>c.timestamp!==void 0).length,nodes:e.map(c=>c.stats)}}async readTimings(){let e=await Promise.all(this.nodes.map(async({stats:a,timestamp:s})=>{if(!s)return{...a};let{querySet:u,snapshot:c,beginIndex:d,endIndex:m}=s;if(u.device.type!=="webgpu")return{...a,gpuTimeMilliseconds:await u.readTimestampDuration(d,m)};let f=await(c??u).readResults({firstQuery:d,queryCount:m-d+1}),p=f[0],h=f[f.length-1];return{...a,gpuStartTimeMilliseconds:Number(p)/1e6,gpuEndTimeMilliseconds:Number(h)/1e6,gpuTimeMilliseconds:Number(h-p)/1e6}})),t=e.filter(a=>a.gpuTimeMilliseconds!==void 0),o=e.filter(a=>a.gpuStartTimeMilliseconds!==void 0),i=this.nodes.flatMap(a=>a.timestamp?.snapshot?.clockCorrelation?[a.timestamp.snapshot.clockCorrelation]:[]).sort((a,s)=>a.uncertaintyMilliseconds-s.uncertaintyMilliseconds)[0];return{...i?{clockCorrelation:i}:{},cpuEncodeStartTimeMilliseconds:this.stats.cpuEncodeStartTimeMilliseconds,cpuEncodeEndTimeMilliseconds:this.stats.cpuEncodeEndTimeMilliseconds,...o.length>0?{gpuStartTimeMilliseconds:Math.min(...o.map(a=>a.gpuStartTimeMilliseconds)),gpuEndTimeMilliseconds:Math.max(...o.map(a=>a.gpuEndTimeMilliseconds))}:{},cpuEncodeTimeMilliseconds:this.stats.cpuEncodeTimeMilliseconds,...t.length>0?{gpuTimeMilliseconds:t.reduce((a,s)=>a+(s.gpuTimeMilliseconds??0),0)}:{},nodes:e}}},He=class{device;id;autotuner;buffers=new Map;textures=new Map;externalTextures=new Map;importedBufferHandles=new Map;dynamicBufferHandles=new Map;nodes=[];nodeIds=new Set;compiled=!1;constructor(e,t={}){if(e.type!=="webgpu")throw new Error("GPUCommandGraph requires a WebGPU device");Jt(e,"construction"),this.device=e,this.id=t.id??"gpu-command-graph",this.autotuner=t.autotuner}importBuffer(e,t){this.assertMutable(),mi(e,this.device),t&&pi(t,e,this.device);let o=this.addBuffer(new Se(this,e,!1,t));if(t){let n=Tt(t);this.importedBufferHandles.has(n)||this.importedBufferHandles.set(n,o),t instanceof De&&!this.dynamicBufferHandles.has(t)&&this.dynamicBufferHandles.set(t,o)}return o}createTransientBuffer(e){return this.assertMutable(),mi(e,this.device),this.addBuffer(new Se(this,e,!0))}createDataView(e,t){this.assertBuffer(e);let o=V(t.format),n=t.byteOffset??0,i=t.rowByteLength??o.byteLength,a=t.byteStride??i;return us(e,{length:t.length,byteOffset:n,byteStride:a,rowByteLength:i}),new ce(e,{format:t.format,length:t.length,byteOffset:n,byteStride:a,rowByteLength:i})}importGPUData(e,t){return this.importGPUDataView(e,t)}importGPUVector(e,t){if(t.bufferLayout)throw new Error(`GPUCommandGraph import "${e}" does not accept interleaved GPUVector data`);let o=t.format??t.data[0]?.format;if(!o)throw new Error(`GPUCommandGraph import "${e}" requires GPUVector.format`);if(we(o)||Te(o))throw new Error(`GPUCommandGraph import "${e}" requires a fixed-width GPUVector format`);let n=V(o),i=t.data.map((a,s)=>{if(a.format!==o)throw new Error(`GPUCommandGraph import "${e}" requires matching GPUVector chunk formats`);let u=t.data.length===1?e:`${e}-chunk-${s}`;return this.importGPUDataView(u,a)});return new B({id:e,name:t.name??e,format:o,length:t.length,valueLength:t.valueLength??t.data.reduce((a,s)=>a+s.valueLength,0),stride:t.stride??t.data[0]?.stride??n.components*(n.listSize??1),byteStride:t.byteStride??i[0]?.byteStride??n.byteLength,rowByteLength:t.rowByteLength??i[0]?.rowByteLength??n.byteLength,data:i})}importTexture(e,t){this.assertMutable();let o=ho(e,this.device);return t&&yo(t,o,this.device),this.addTexture(new ne(this,o,!1,t))}importFrameTexture(e){this.assertMutable();let t=ho(e,this.device);return this.addTexture(new ne(this,t,!1,void 0,!0))}importExternalTexture(e){return this.assertMutable(),as(e,this.device),this.addExternalTexture(new Ue(this,e))}createTransientTexture(e){this.assertMutable();let t=ho(e,this.device);return this.addTexture(new ne(this,t,!0))}createTextureView(e,t={}){this.assertTexture(e);let o=ss(e,t);return new Ce(e,o)}add(e){if(this.assertMutable(),"getNodes"in e)for(let t of e.getNodes())this.add(t);else if("getCommandNodes"in e)_e(this,e.getCommandNodes(this));else if("type"in e)lo(this,e);else for(let t of e)this.add(t)}addComputePass(e){this.addNode({...e,type:"compute"})}addRenderPass(e){e.attachments&&this.validateRenderAttachments(e.id,e.attachments);let t=e.attachments?[...e.attachments.colorAttachments.map(o=>({texture:o,usage:"render-attachment"})),...(e.attachments.resolveTargets??[]).filter(o=>o!==null).map(o=>({texture:o,usage:"render-attachment"})),...e.attachments.depthStencilAttachment?[{texture:e.attachments.depthStencilAttachment,usage:"render-attachment"}]:[]]:[];this.addNode({...e,resources:[...e.resources??[],...t],type:"render"})}addCopyPass(e){this.addNode({...e,type:"copy"})}compile(){return this.assertMutable(),Jt(this.device,"compilation"),this.compiled=!0,new qe(Jn({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes}))}async compileAsync(){return this.assertMutable(),Jt(this.device,"compilation"),this.compiled=!0,new qe(await ei({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes}))}addNode(e){if(this.assertMutable(),!e.id)throw new Error("GPUCommandGraph node id is required");if(this.nodeIds.has(e.id))throw new Error(`GPUCommandGraph node id "${e.id}" is already in use`);for(let[t,o]of Object.entries(e.workload??{}))if(t==="operation"||t==="variant"){if(typeof o!="string"||!o)throw new Error(`GPUCommandGraph node "${e.id}" workload ${t} must be nonempty`)}else if(typeof o!="number"||!Number.isSafeInteger(o)||o<0)throw new Error(`GPUCommandGraph node "${e.id}" workload ${t} must be a nonnegative safe integer`);if(e.condition){if(!e.condition.id)throw new Error(`GPUCommandGraph node "${e.id}" condition id is required`);if(e.condition.source==="cpu"){if(typeof e.condition.evaluate!="function")throw new Error(`GPUCommandGraph node "${e.id}" CPU condition requires an evaluate function`)}else{let t=e.condition;if(e.type!=="compute"||t.mode!=="indirect")throw new Error(`GPUCommandGraph node "${e.id}" GPU conditions require an indirect compute node`);if(!t.buffer)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition requires an indirect command buffer`);this.assertBuffer(t.buffer);let o=t.byteOffset??0;if(!Number.isSafeInteger(o)||o<0||o%4!==0)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition byteOffset must be a nonnegative multiple of 4`);if(o+3*es>t.buffer.byteLength)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition indirect command exceeds buffer "${t.buffer.id}"`);(e.resources??[]).some(n=>ve(n)&&Q(n.buffer)===t.buffer&&n.usage==="indirect")||(e={...e,resources:[...e.resources??[],{buffer:t.buffer,usage:"indirect"}]})}}if(e.publication){if(e.condition)throw new Error(`GPUCommandGraph node "${e.id}" cannot combine conditional execution with a publication boundary`);if(!e.publication.id)throw new Error(`GPUCommandGraph node "${e.id}" publication id is required`);if(!["partial","complete"].includes(e.publication.completeness))throw new Error(`GPUCommandGraph node "${e.id}" publication completeness is invalid`)}for(let t of e.resources??[])if(ve(t)){let o=Q(t.buffer);this.assertBuffer(o),ds(o,t.usage)}else if(xt(t)){let o=ue(t.texture);this.assertTexture(o),ms(o,t.usage),fs(t.texture,t.usage)}else{if(this.assertExternalTexture(t.externalTexture),t.usage!=="sampled")throw new Error("GPUCommandGraph external textures support sampled access only");if(e.type!=="render")throw new Error("GPUCommandGraph external textures can be sampled only by render nodes")}ri(e),this.nodeIds.add(e.id),this.nodes.push(e)}addBuffer(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.buffers.set(e.id,e),e}addTexture(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.textures.set(e.id,e),e}addExternalTexture(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.externalTextures.set(e.id,e),e}importGPUDataView(e,t){if(!t.format)throw new Error(`GPUCommandGraph import "${e}" requires GPUData.format`);let o=Tt(t.buffer),n={byteLength:os(t),usage:o.usage},i=t.buffer instanceof De?this.getDynamicBufferHandle(t.buffer,n):this.getImportedBufferHandle(o,n);return i||(i=this.importBuffer({id:e,byteLength:o.byteLength,usage:o.usage},t.buffer),t.buffer instanceof De?this.dynamicBufferHandles.set(t.buffer,i):this.importedBufferHandles.set(o,i)),this.createDataView(i,{format:t.format,length:t.length,byteOffset:t.byteOffset,byteStride:t.byteStride,rowByteLength:t.rowByteLength})}getDynamicBufferHandle(e,t){let o=this.dynamicBufferHandles.get(e);if(o?.defaultBuffer===e&&bt(o,t))return o;this.dynamicBufferHandles.delete(e);for(let n of this.buffers.values())if(n.defaultBuffer===e&&bt(n,t))return this.dynamicBufferHandles.set(e,n),n}getImportedBufferHandle(e,t){let o=this.importedBufferHandles.get(e);if(o?.defaultBuffer&&Tt(o.defaultBuffer)===e&&bt(o,t))return o;this.importedBufferHandles.delete(e);for(let[n,i]of this.dynamicBufferHandles)if(n.buffer===e&&bt(i,t))return this.importedBufferHandles.set(e,i),i;for(let n of this.buffers.values())if(n.defaultBuffer===e&&bt(n,t))return this.importedBufferHandles.set(e,n),n}assertBuffer(e){if(e.graph!==this||this.buffers.get(e.id)!==e)throw new Error(`Graph buffer "${e.id}" does not belong to ${this.id}`)}assertTexture(e){if(e.graph!==this||this.textures.get(e.id)!==e)throw new Error(`Graph texture "${e.id}" does not belong to ${this.id}`)}assertExternalTexture(e){if(e.graph!==this||this.externalTextures.get(e.id)!==e)throw new Error(`Graph external texture "${e.id}" does not belong to ${this.id}`)}assertMutable(){if(this.compiled)throw new Error(`GPUCommandGraph "${this.id}" has already been compiled`)}validateRenderAttachments(e,t){if(t.colorAttachments.length===0&&!t.depthStencilAttachment)throw new Error(`GPUCommandGraph render node "${e}" requires at least one attachment`);let o=[...t.colorAttachments,...t.depthStencilAttachment?[t.depthStencilAttachment]:[]];for(let a of o)if(this.assertTexture(a.texture),a.dimension!=="2d"||a.mipLevelCount!==1||a.arrayLayerCount!==1)throw new Error(`GPUCommandGraph render node "${e}" attachments must be single-mip, single-layer 2d views`);let[n,...i]=o;for(let a of i)if(a.width!==n.width||a.height!==n.height||a.texture.samples!==n.texture.samples)throw new Error(`GPUCommandGraph render node "${e}" attachments must have matching extent and samples`);this.validateResolveTargets(e,t)}validateResolveTargets(e,t){let o=t.resolveTargets;if(o){if(this.device.type!=="webgpu")throw new Error(`GPUCommandGraph render node "${e}" resolve targets require WebGPU`);if(o.length!==t.colorAttachments.length)throw new Error(`GPUCommandGraph render node "${e}" requires one resolve entry per color attachment`);for(let n=0;n<o.length;n++){let i=o[n];if(!i)continue;let a=t.colorAttachments[n];if(this.assertTexture(i.texture),a.texture.samples<=1||i.texture.samples!==1||a.format!==i.format||a.width!==i.width||a.height!==i.height)throw new Error(`GPUCommandGraph render node "${e}" resolve target ${n} must match a multisampled source and be single-sampled`);if(i.dimension!=="2d"||i.aspect!=="all"||i.mipLevelCount!==1||i.arrayLayerCount!==1)throw new Error(`GPUCommandGraph render node "${e}" resolve targets must be single-mip, single-layer 2d color views`)}}}},qe=class{device;id;stats;preflight;capabilities;buffers;textures;externalTextures;compiledNodes;activeImportedBufferHandles=new Set;writableImportedBufferHandles=new Set;activeImportedTextureHandles=new Set;writableImportedTextureHandles=new Set;transientBuffers;transientTextures;bufferTransientAllocations;textureTransientAllocations;cachedTextureViews=[];cachedFramebuffers=[];lastFrameIds=new Map;lastExternalTextureFrameIds=new Map;consumedExternalTextures=new WeakSet;destroyed=!1;get[Symbol.toStringTag](){return"CompiledGPUCommandGraph"}toString(){let e=this.destroyed?"destroyed":"active";return`${this[Symbol.toStringTag]}:"${this.id}":${this.stats.nodeOrder.length} nodes:${this.stats.physicalTransientResourceBytes}B transient:${e}`}toJSON(){return this.toString()}constructor(e){this.device=e.device,this.id=e.id,this.buffers=e.buffers,this.textures=e.textures,this.externalTextures=e.externalTextures,this.compiledNodes=e.compiledNodes;for(let{node:t}of this.compiledNodes)for(let o of t.resources??[])if(ve(o)){let n=Q(o.buffer);n.transient||(this.activeImportedBufferHandles.add(n),(o.usage==="storage-write"||o.usage==="storage-read-write"||o.usage==="copy-destination")&&this.writableImportedBufferHandles.add(n))}else if(xt(o)){let n=ue(o.texture);n.transient||(this.activeImportedTextureHandles.add(n),(o.usage==="storage-write"||o.usage==="storage-read-write"||o.usage==="render-attachment"||o.usage==="copy-destination")&&this.writableImportedTextureHandles.add(n))}this.transientBuffers=e.transientBuffers,this.transientTextures=e.transientTextures,this.bufferTransientAllocations=e.bufferTransientAllocations,this.textureTransientAllocations=e.textureTransientAllocations,this.stats=e.stats,this.preflight=e.preflight,this.capabilities=is(this.device)}encode(e,t){return this.encodeNodeRange(e,t,0,this.compiledNodes.length)}getExecutionPlan(e,t={}){return xo(this.preflight,e,t)}createExecution(e,t={}){return new vt({plan:this.getExecutionPlan(e,t),budget:e,encodeNodeRange:(o,n,i,a)=>this.encodeNodeRange(o,n,i,a)})}encodeNodeRange(e,t,o,n){if(this.destroyed)throw new Error(`CompiledGPUCommandGraph "${this.id}" has been destroyed`);if(Jt(this.device,"encoding"),e.device!==this.device)throw new Error("GPUCommandGraph command encoder must belong to the graph device");let i=wt(),a=this.resolveImportedBuffers(t.buffers??{});ns(t.frameTextures??{},t.externalTextures??{});let s=this.resolveImportedTextures(t.textures??{},t.frameTextures??{}),u=this.resolveExternalTextures(t.externalTextures??{});for(let[g,l]of s.frameIds)this.lastFrameIds.set(g,l);for(let[g,l]of u.frameIds)this.lastExternalTextureFrameIds.set(g,l);for(let g of u.textures.values())this.consumedExternalTextures.add(g);let c=s.textures,d=g=>{let l=Q(g),T=l.transient?this.transientBuffers.get(l):a.get(l);if(!T)throw new Error(`GPUCommandGraph buffer "${l.id}" is not bound`);return T},m=g=>{let l=ue(g),T=l.transient?this.transientTextures.get(l):c.get(l);if(!T)throw new Error(`GPUCommandGraph texture "${l.id}" is not bound`);return T},f=g=>{let l=m(g);if(g instanceof ne||hs(g))return l.view;if(g.texture.frameScoped){let b=this.lastFrameIds.get(g.texture);for(let O=this.cachedTextureViews.length-1;O>=0;O--){let P=this.cachedTextureViews[O];P.logicalView===g&&P.frameId!==b&&(this.destroyFramebuffersUsingView(P.view),P.view.destroy(),this.cachedTextureViews.splice(O,1))}}let T=this.cachedTextureViews.find(b=>b.logicalView===g&&b.texture===l&&(!g.texture.frameScoped||b.frameId===this.lastFrameIds.get(g.texture)));if(T)return T.view;let S=l.createView({format:g.format,dimension:g.dimension,aspect:g.aspect,baseMipLevel:g.baseMipLevel,mipLevelCount:g.mipLevelCount,baseArrayLayer:g.baseArrayLayer,arrayLayerCount:g.arrayLayerCount});return this.cachedTextureViews.push({logicalView:g,texture:l,view:S,...g.texture.frameScoped?{frameId:this.lastFrameIds.get(g.texture)}:{}}),S},p=g=>{let l=u.textures.get(g);if(!l)throw new Error(`GPUCommandGraph external texture "${g.id}" is not bound`);return l},h={commandEncoder:e,parameters:t.parameters,getBuffer:d,getTexture:m,getTextureView:f,getExternalTexture:p},x=[],w,G=0,L=t.coalesceComputePasses!==!1&&e.getTimeProfilingQuerySet()===null,C=()=>{let g=w;w=void 0,g?.end()};try{for(let g=o;g<n;g++){let{node:l,executable:T}=this.compiledNodes[g],S=wt();if(l.condition?.source==="cpu"){let P=!1;try{P=l.condition.evaluate(t.parameters)}catch(D){let U=D instanceof Error?D.message:String(D);throw new Error(`GPUCommandGraph CPU condition "${l.condition.id}" failed for node "${l.id}": ${U}`)}if(!P){let D=wt();x.push({stats:{id:l.id,description:l.description,resources:this.preflight.nodes[g].resources,operation:l.workload?.operation,type:l.type,cpuEncodeStartTimeMilliseconds:S,cpuEncodeEndTimeMilliseconds:D,cpuEncodeTimeMilliseconds:D-S,hasGPUTimestamps:!1,condition:{id:l.condition.id,source:"cpu",outcome:"skipped"}}});continue}}let b;switch(l.type){case"compute":{w||(w=e.beginComputePass({id:l.id}),G++);let P=w;b=di(P,e),b&&(L=!1),P.pushDebugGroup(l.id);try{let D=l.condition?.source==="gpu"?l.condition:void 0,U=D?rs(P,d(D.buffer),D.byteOffset??0,l.id):void 0;T.encode({...h,computePass:U?.computePass??P}),U?.assertDispatched()}finally{P.popDebugGroup()}L||C();break}case"render":{C();let P=T,D=P.getRenderPassProps?.(h)??{id:l.id};if(l.attachments&&D.framebuffer!==void 0)throw new Error(`GPUCommandGraph render node "${l.id}" cannot supply framebuffer with graph attachments`);if(l.attachments?.resolveTargets&&D.resolveTargets!==void 0)throw new Error(`GPUCommandGraph render node "${l.id}" cannot supply resolveTargets with graph attachments`);let U=l.attachments?this.getFramebuffer(l.id,l.attachments,f):void 0,X=l.attachments?.resolveTargets?.map(le=>le?f(le):null),ie=e.beginRenderPass({...D,...U?{framebuffer:U}:{},...X?{resolveTargets:X}:{}});b=di(ie,e),ie.pushDebugGroup(l.id);try{P.encode({...h,renderPass:ie})}finally{ie.popDebugGroup(),ie.end()}break}case"copy":C(),T.encode(h);break}let O=wt();x.push({stats:{id:l.id,description:l.description,resources:this.preflight.nodes[g].resources,operation:l.workload?.operation,type:l.type,cpuEncodeStartTimeMilliseconds:S,cpuEncodeEndTimeMilliseconds:O,cpuEncodeTimeMilliseconds:O-S,hasGPUTimestamps:b!==void 0,...l.condition?{condition:{id:l.condition.id,source:l.condition.source,outcome:l.condition.source==="gpu"?"gpu-resolved":"executed"}}:{}},timestamp:b})}}finally{C()}let W=wt();return new St(x,W-i,G,i,W,async(g,l)=>{if(this.destroyed)throw new Error("Graph has been destroyed.");let T=this.compiledNodes.findIndex(({node:U})=>U.id===g),S=this.compiledNodes[T]?.node.resources?.[l],b=this.preflight.nodes[T]?.resources?.[l];if(!S||!b)throw new Error("Resource is unavailable.");if("externalTexture"in S)throw new Error("External images cannot be read back.");let O="buffer"in S?Q(S.buffer):ue(S.texture);if("frameScoped"in O&&O.frameScoped)throw new Error("Frame textures expire after presentation.");let P="buffer"in S?d(S.buffer):m(S.texture),D=P instanceof N.Buffer?this.transientBuffers:this.transientTextures;if(O.transient&&[...D].some(([U,X])=>U!==O&&X===P))throw new Error("Transient allocation is reused; logical contents are no longer available.");return Fo(P,b)})}destroy(){if(!this.destroyed){for(let{executable:e}of this.compiledNodes)e.destroy?.();for(let e of this.cachedFramebuffers)e.framebuffer.destroy();for(let e of this.cachedTextureViews)e.view.destroy();for(let e of this.bufferTransientAllocations)e.buffer?.destroy();for(let e of this.textureTransientAllocations)e.texture?.destroy();this.destroyed=!0}}resolveImportedBuffers(e){let t=new Map,o=new Map;for(let[n,i]of this.buffers){if(i.transient)continue;let a=e[n]??i.defaultBuffer;if(!a)throw new Error(`GPUCommandGraph imported buffer "${n}" is required`);pi(a,i,this.device);let s=Tt(a);if(this.activeImportedBufferHandles.has(i)){let u=s.handle,c=typeof u=="object"&&u!==null||typeof u=="function"?u:s,d=o.get(c);if(d&&(this.writableImportedBufferHandles.has(d)||this.writableImportedBufferHandles.has(i)))throw new Error(`GPUCommandGraph imported buffers "${d.id}" and "${n}" resolve to the same physical buffer`);d||o.set(c,i)}t.set(i,s)}for(let n of Object.keys(e)){let i=this.buffers.get(n);if(!i||i.transient)throw new Error(`GPUCommandGraph has no imported buffer named "${n}"`)}return t}resolveImportedTextures(e,t){let o=new Map,n=new Map;for(let[a,s]of this.textures){if(s.transient)continue;if(s.frameScoped){let c=t[a];if(!c)throw new Error(`GPUCommandGraph frame texture "${a}" is required`);let d=this.lastFrameIds.get(s);if(d!==void 0&&c.frameId<=d)throw new Error(`GPUCommandGraph frame texture "${a}" frameId ${c.frameId} is stale; expected greater than ${d}`);yo(c.texture,s,this.device),o.set(s,go(c.texture)),n.set(s,c.frameId);continue}let u=e[a]??s.defaultTexture;if(!u)throw new Error(`GPUCommandGraph imported texture "${a}" is required`);yo(u,s,this.device),o.set(s,go(u))}for(let a of Object.keys(e)){let s=this.textures.get(a);if(!s||s.transient||s.frameScoped)throw new Error(`GPUCommandGraph has no imported texture named "${a}"`)}for(let a of Object.keys(t))if(!this.textures.get(a)?.frameScoped)throw new Error(`GPUCommandGraph has no frame texture named "${a}"`);let i=new Map;for(let[a,s]of o){if(!this.activeImportedTextureHandles.has(a))continue;let u=s.handle,c=typeof u=="object"&&u!==null||typeof u=="function"?u:s,d=i.get(c);if(d&&(this.writableImportedTextureHandles.has(d)||this.writableImportedTextureHandles.has(a)))throw new Error(`GPUCommandGraph imported textures "${d.id}" and "${a.id}" resolve to the same physical texture`);d||i.set(c,a)}return{textures:o,frameIds:n}}resolveExternalTextures(e){let t=new Map,o=new Map;for(let[n,i]of this.externalTextures){let a=e[n];if(!a)throw new Error(`GPUCommandGraph external texture "${n}" is required`);let s=this.lastExternalTextureFrameIds.get(i);if(s!==void 0&&a.frameId<=s)throw new Error(`GPUCommandGraph external texture "${n}" frameId ${a.frameId} is stale; expected greater than ${s}`);if(this.consumedExternalTextures.has(a.texture))throw new Error(`GPUCommandGraph external texture "${n}" requires a fresh binding for each frame`);cs(a.texture,i,this.device),t.set(i,a.texture),o.set(i,a.frameId)}for(let n of Object.keys(e))if(!this.externalTextures.has(n))throw new Error(`GPUCommandGraph has no external texture named "${n}"`);return{textures:t,frameIds:o}}getFramebuffer(e,t,o){let n=t.colorAttachments.map(o),i=t.depthStencilAttachment?o(t.depthStencilAttachment):void 0,a=this.cachedFramebuffers.find(c=>c.nodeId===e&&c.depthStencilAttachment===i&&c.colorAttachments.length===n.length&&c.colorAttachments.every((d,m)=>d===n[m]));if(a)return a.framebuffer;let s=t.colorAttachments[0]??t.depthStencilAttachment,u=this.device.createFramebuffer({id:`${this.id}-${e}-framebuffer-${this.cachedFramebuffers.length}`,width:s.width,height:s.height,colorAttachments:n,depthStencilAttachment:i??null});return this.cachedFramebuffers.push({nodeId:e,colorAttachments:n,depthStencilAttachment:i,framebuffer:u}),u}destroyFramebuffersUsingView(e){for(let t=this.cachedFramebuffers.length-1;t>=0;t--){let o=this.cachedFramebuffers[t];(o.depthStencilAttachment===e||o.colorAttachments.some(n=>n===e))&&(o.framebuffer.destroy(),this.cachedFramebuffers.splice(t,1))}}};function Tt(r){return r instanceof De?r.buffer:r}function os(r){let e=r.length===0?0:(r.length-1)*r.byteStride+r.rowByteLength;return r.byteOffset+e}function bt(r,e){return r.byteLength>=e.byteLength&&(r.usage&e.usage)===e.usage}function go(r){if(r instanceof Qt){if(!r.isReady)throw new Error(`GPUCommandGraph dynamic texture "${r.id}" is not ready`);return r.texture}return r}function ns(r,e){let t;for(let[o,n]of[...Object.entries(r),...Object.entries(e)]){if(!Number.isSafeInteger(n.frameId)||n.frameId<0)throw new Error(`GPUCommandGraph frame resource "${o}" requires a valid frameId`);if(t!==void 0&&n.frameId!==t)throw new Error("GPUCommandGraph frame resources must share one frameId per encoding");t=n.frameId}}function di(r,e){let{timestampQuerySet:t,beginTimestampIndex:o,endTimestampIndex:n}=r.props;return t&&Number.isSafeInteger(o)&&Number.isSafeInteger(n)&&o>=0&&n>o?{querySet:t,snapshot:t.device.type==="webgpu"?e.captureTimestampQuerySet?.(t):void 0,beginIndex:o,endIndex:n}:void 0}function is(r){return Object.freeze({timestampQueries:r.features.has("timestamp-query"),subgroups:r.features.has("subgroups"),subgroupId:r.wgslLanguageFeatures.has("subgroup_id"),subgroupMinSize:r.info.subgroupMinSize,subgroupMaxSize:r.info.subgroupMaxSize,softwareAdapter:r.info.gpu==="software"||r.info.gpuType==="cpu"||!!r.info.fallback,maxBufferByteLength:r.limits.maxBufferSize,maxStorageBufferBindingByteLength:r.limits.maxStorageBufferBindingSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension})}function Jt(r,e){if(r.isLost)throw new Error(`GPUCommandGraph cannot perform ${e} after device loss`)}function wt(){return globalThis.performance?.now()??Date.now()}function mi(r,e){if(!r.id)throw new Error("GPUCommandGraph buffer id is required");if(!Number.isSafeInteger(r.byteLength)||r.byteLength<0)throw new Error(`GPUCommandGraph buffer "${r.id}" requires a valid byteLength`);if(r.byteLength>e.limits.maxBufferSize)throw new Error(`GPUCommandGraph buffer "${r.id}" exceeds the device buffer limit`);if(!Number.isSafeInteger(r.usage)||r.usage<=0)throw new Error(`GPUCommandGraph buffer "${r.id}" requires buffer usage flags`)}function as(r,e){if(!r.id)throw new Error("GPUCommandGraph external texture id is required");for(let[t,o]of Object.entries({width:r.width,height:r.height}))if(!Number.isSafeInteger(o)||o<=0)throw new Error(`GPUCommandGraph external texture "${r.id}" ${t} must be a positive safe integer`);if(r.width>e.limits.maxTextureDimension2D||r.height>e.limits.maxTextureDimension2D)throw new Error(`GPUCommandGraph external texture "${r.id}" exceeds device dimension limits`)}function ho(r,e){if(!r.id)throw new Error("GPUCommandGraph texture id is required");let t=r.dimension??"2d",o=t==="cube"?6:r.depth??1,n=r.mipLevels??1,i=r.samples??1;for(let[c,d]of Object.entries({width:r.width,height:r.height,depth:o,mipLevels:n,samples:i}))if(!Number.isSafeInteger(d)||d<=0)throw new Error(`GPUCommandGraph texture "${r.id}" ${c} must be a positive safe integer`);if(!Number.isSafeInteger(r.usage)||r.usage<=0)throw new Error(`GPUCommandGraph texture "${r.id}" requires texture usage flags`);if(!e.isTextureFormatSupported(r.format))throw new Error(`GPUCommandGraph texture "${r.id}" format ${r.format} is unsupported`);if(t==="1d"&&(r.height!==1||o!==1))throw new Error(`GPUCommandGraph 1d texture "${r.id}" requires height and depth 1`);if(t==="cube"&&r.width!==r.height)throw new Error(`GPUCommandGraph cube texture "${r.id}" must be square`);if(t==="cube-array"&&(r.width!==r.height||o%6!==0))throw new Error(`GPUCommandGraph cube-array texture "${r.id}" must be square with depth divisible by 6`);if(n>e.getMipLevelCount(r.width,r.height,t==="3d"?o:1))throw new Error(`GPUCommandGraph texture "${r.id}" declares too many mip levels`);let a=t==="1d"?e.limits.maxTextureDimension1D:t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,s=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,u=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureArrayLayers;if(r.width>a||r.height>s||o>u)throw new Error(`GPUCommandGraph texture "${r.id}" exceeds device dimension limits`);return{id:r.id,format:r.format,width:r.width,height:r.height,usage:r.usage,dimension:t,depth:o,mipLevels:n,samples:i}}function ss(r,e){let t=e.dimension??r.dimension,o=e.aspect??"all",n=e.baseMipLevel??0,i=e.mipLevelCount??r.mipLevels-n,a=e.baseArrayLayer??0,s=r.dimension==="3d"?1:r.depth,u=e.arrayLayerCount??s-a;for(let[f,p]of Object.entries({baseMipLevel:n,mipLevelCount:i,baseArrayLayer:a,arrayLayerCount:u}))if(!Number.isSafeInteger(p)||p<0)throw new Error(`Graph texture view ${f} must be a non-negative safe integer`);if(i===0||n+i>r.mipLevels)throw new Error(`Graph texture view exceeds texture "${r.id}" mip levels`);if(u===0||a+u>s||r.dimension==="3d"&&(a!==0||u!==1))throw new Error(`Graph texture view exceeds texture "${r.id}" array layers`);let c=Math.max(1,r.width>>n),d=r.dimension==="1d"?1:Math.max(1,r.height>>n),m=r.dimension==="3d"?Math.max(1,r.depth>>n):u;return{dimension:t,aspect:o,baseMipLevel:n,mipLevelCount:i,baseArrayLayer:a,arrayLayerCount:u,width:c,height:d,depth:m}}function us(r,e){for(let[n,i]of Object.entries(e))if(!Number.isSafeInteger(i)||i<0)throw new Error(`Graph data view ${n} must be a non-negative safe integer`);if(e.length>1&&e.byteStride===0)throw new Error("Graph data view byteStride must be positive for multiple rows");if(e.rowByteLength>e.byteStride&&e.length>1)throw new Error("Graph data view rowByteLength cannot exceed byteStride");let t=e.length===0?0:(e.length-1)*e.byteStride+e.rowByteLength,o=e.byteOffset+t;if(!Number.isSafeInteger(t)||!Number.isSafeInteger(o))throw new Error("Graph data view byte range exceeds safe integer precision");if(o>r.byteLength)throw new Error(`Graph data view exceeds buffer "${r.id}" byte length`)}function pi(r,e,t){let o=Tt(r);if(o.device!==t)throw new Error(`GPUCommandGraph buffer "${e.id}" belongs to another device`);if(o.byteLength<e.byteLength)throw new Error(`GPUCommandGraph buffer "${e.id}" is smaller than compiled capacity`);if((o.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph buffer "${e.id}" has incompatible usage flags`)}function yo(r,e,t){let o=go(r);if(o.device!==t)throw new Error(`GPUCommandGraph texture "${e.id}" belongs to another device`);for(let[n,i,a]of[["format",e.format,o.format],["dimension",e.dimension,o.dimension],["width",e.width,o.width],["height",e.height,o.height],["depth",e.depth,o.depth],["mipLevels",e.mipLevels,o.mipLevels],["samples",e.samples,o.samples]])if(a!==i)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible ${n} (${a} !== ${i})`);if((o.props.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible usage flags`)}function cs(r,e,t){if(r.device!==t)throw new Error(`GPUCommandGraph external texture "${e.id}" belongs to another device`);if(r.destroyed)throw new Error(`GPUCommandGraph external texture "${e.id}" has been destroyed`);if(r.width!==e.width||r.height!==e.height)throw new Error(`GPUCommandGraph external texture "${e.id}" has incompatible dimensions (${r.width}x${r.height} !== ${e.width}x${e.height})`)}function ds(r,e){let t=ps(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph buffer "${r.id}" does not declare usage required by ${e}`)}function ms(r,e){let t=ls(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph texture "${r.id}" does not declare usage required by ${e}`)}function fs(r,e){if(r instanceof Ce&&e.startsWith("storage-")&&r.mipLevelCount!==1)throw new Error("GPUCommandGraph storage texture views must contain exactly one mip level")}function ps(r){switch(r){case"storage-read":case"storage-write":case"storage-read-write":return N.Buffer.STORAGE;case"uniform":return N.Buffer.UNIFORM;case"copy-source":return N.Buffer.COPY_SRC;case"copy-destination":return N.Buffer.COPY_DST;case"indirect":return N.Buffer.INDIRECT;case"vertex":return N.Buffer.VERTEX;case"index":return N.Buffer.INDEX}}function ls(r){switch(r){case"sampled":return N.Texture.SAMPLE;case"storage-read":case"storage-write":case"storage-read-write":return N.Texture.STORAGE;case"render-attachment":return N.Texture.RENDER;case"copy-source":return N.Texture.COPY_SRC;case"copy-destination":return N.Texture.COPY_DST}}function hs(r){let e=r.texture;return r.dimension===e.dimension&&r.aspect==="all"&&r.baseMipLevel===0&&r.mipLevelCount===e.mipLevels&&r.baseArrayLayer===0&&r.arrayLayerCount===(e.dimension==="3d"?1:e.depth)}var q=class{id;type="composite";operations;metadata;constructor(e){let t=Array.isArray(e)?{operations:e}:e;this.id=t.id??"gpu-composite-operation",this.operations=Object.freeze([...t.operations]),this.metadata=t.metadata}};function bo(r){let e=r;return typeof e.id=="string"&&typeof e.type=="string"}function wo(r){return r instanceof q?Object.freeze({id:r.id,type:r.type,...r.metadata?{metadata:r.metadata}:{},children:Object.freeze(r.operations.map(wo))}):bo(r)?Object.freeze({id:r.id,type:r.type,...r.metadata?{metadata:r.metadata}:{}}):Object.freeze({id:r.constructor?.name??"gpu-command-node-producer",type:"command-node-producer"})}function li(r){return typeof r.getCommandNodes=="function"}var Ye=class{id;format;constructor(e,t){if(!e)throw new Error("GPUGraphScalar id is required");this.id=e,this.format=t}},Xe=class{id;format;length;external;chunkLengths;constructor(e){if(!e.id)throw new Error("GPUGraphVector id is required");if(!Number.isSafeInteger(e.length)||e.length<0)throw new Error(`${e.id} vector length must be a non-negative safe integer`);if(this.id=e.id,this.format=e.format,this.length=e.length,this.external=e.external??!1,e.chunkLengths){if(e.chunkLengths.some(t=>!Number.isSafeInteger(t)||t<0)||e.chunkLengths.reduce((t,o)=>t+o,0)!==e.length)throw new Error(`${e.id} chunk lengths must partition its logical length`);this.chunkLengths=Object.freeze([...e.chunkLengths])}}},Ke=class{id;format;width;height;usage;dimension;depth;mipLevels;samples;external;constructor(e){this.id=e.id,this.format=e.format,this.width=e.width,this.height=e.height,this.usage=e.usage,this.dimension=e.dimension,this.depth=e.depth,this.mipLevels=e.mipLevels,this.samples=e.samples,this.external=e.external??!1}},de=class{texture;props;constructor(e,t={}){this.texture=e,this.props=Object.freeze({...t})}};var er=class{id;programOperations=[];programScalars=new Map;programVectors=new Map;programTextures=new Map;constructor(e={}){this.id=e.id??"gpu-program"}add(e){return this.assertOperationLike(e),this.addOperationLike(e),this}scalar(e,t){this.assertValueId(e);let o=new Ye(e,t);return this.programScalars.set(e,o),o}vector(e,t,o,n={}){this.assertValueId(e);let i=new Xe({id:e,format:t,length:o,...n});return this.programVectors.set(e,i),i}texture(e,t){this.assertValueId(e);let o=new Ke({...t,id:e});return this.programTextures.set(e,o),o}textureView(e,t={}){if(this.programTextures.get(e.id)!==e)throw new Error(`Undeclared program texture "${e.id}"`);return new de(e,t)}get textures(){return Object.freeze([...this.programTextures.values()])}get scalars(){return Object.freeze([...this.programScalars.values()])}get vectors(){return Object.freeze([...this.programVectors.values()])}get operations(){return Object.freeze([...this.programOperations])}get operationTree(){return Object.freeze(this.programOperations.map(wo))}assertValueId(e){if(this.programScalars.has(e)||this.programVectors.has(e)||this.programTextures.has(e))throw new Error(`${this.id} value "${e}" already exists`)}addOperationLike(e){if(Array.isArray(e)){for(let t of e)this.addOperationLike(t);return}this.programOperations.push(e)}assertOperationLike(e){if(Array.isArray(e)){for(let t of e)this.assertOperationLike(t);return}if(!e||typeof e!="object")throw new Error(`${this.id} accepts GPU operations only`)}};function hi(r,e={}){return new q({id:e.id,operations:r})}var tr=class extends He{computeLowerings=[];loweringsSuspended=0;otherLowerings=[];addRenderPass(e){let t={...e,type:"render"},o=this.otherLowerings.at(-1);o&&(t=o(t)),super.addRenderPass(t)}addCopyPass(e){let t={...e,type:"copy"},o=this.otherLowerings.at(-1);o&&(t=o(t)),super.addCopyPass(t)}withOtherLowering(e,t){this.otherLowerings.push(e);try{return t()}finally{this.otherLowerings.pop()}}constructor(e,t={}){super(e,t)}addComputePass(e){let t=e;if(this.loweringsSuspended===0)for(let o=this.computeLowerings.length-1;o>=0;o--)t=this.computeLowerings[o](t);super.addComputePass(t)}withComputeLowering(e,t){this.computeLowerings.push(e);try{return t()}finally{this.computeLowerings.pop()}}withoutComputeLowering(e){this.loweringsSuspended++;try{return e()}finally{this.loweringsSuspended--}}};var To=ee(K(),1);Ie();var vo=Uint32Array.BYTES_PER_ELEMENT,So=256;function Re(r,e,t){let o=V(r.format);if(!e.includes(r.format)||r.byteStride!==o.byteLength||r.rowByteLength!==o.byteLength||r.byteOffset%vo!==0)throw new Error(`${t} must be packed, uint32-aligned ${e.join(" or ")} GPU data`)}function gi(r,e){Re(r,["uint32"],e)}function z(r,e){let t=Ct(r),o={buffer:e(r),...t};if(o.offset+o.size>r.buffer.byteLength)throw new Error("GraphDataView storage binding exceeds its logical buffer");return o}function Ct(r){let e=Math.floor(r.byteOffset/So)*So,t=r.byteOffset-e,o=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:e,size:t+Math.max(o,r.rowByteLength)}}function E(r){if(r.byteOffset%vo!==0)throw new Error("GraphDataView storage binding must be uint32-aligned");return r.byteOffset%So/vo}function Me(r,e,t,o,n=To.Buffer.STORAGE){if(!Number.isSafeInteger(o)||o<0)throw new Error("Transient GraphDataView length must be a non-negative safe integer");if((n&To.Buffer.STORAGE)===0)throw new Error("Transient GraphDataView usage must include Buffer.STORAGE");if(we(t)||Te(t))throw new Error("Transient GraphDataView requires a fixed-width GPUVector format");let i=V(t),a=r.createTransientBuffer({id:e,byteLength:Math.max(o,1)*i.byteLength,usage:n});return r.createDataView(a,{format:t,length:o})}function yi(r,e,t){if(!Number.isSafeInteger(t)||t<0||t>e.length)throw new Error("Graph prefix must fit within the input");if(t===e.length)return e;let o=e instanceof B?e.data:[e],n=t,i=[];for(let a of o){let s=Math.min(n,a.length);if(i.push(s===a.length?a:r.createDataView(a.buffer,{format:a.format,length:s,byteOffset:a.byteOffset,byteStride:a.byteStride,rowByteLength:a.rowByteLength})),n-=s,n===0)break}return e instanceof B?new B({...e,length:t,valueLength:t*(V(e.format).listSize??1),data:i}):i[0]}var nr=ee(K(),1);fe();function k(r,e){let[t,o,n]=e;for(let[i,a]of[["x",t],["y",o],["z",n]])if(!Number.isSafeInteger(a)||a<0)throw new Error(`compute dispatch ${i} workgroup count must be a non-negative safe integer`);return{...r,dispatchWorkgroups:Object.freeze([t,o,n])}}function rr(r){return r.dispatchWorkgroups}var or=ee(K(),1);var gs=16*1024,bi=new WeakMap;function wi(r){let e=r,t=bi.get(e);return t||(t=new Co(r),bi.set(e,t)),t}var Co=class{id;graph;buffer;capacityByteLength;nextByteOffset=0;slots=new Map;views=new Map;constructor(e,t="gpu-value-arena",o=gs){if(this.id=t,this.graph=e,!Number.isSafeInteger(o)||o<=0||o%4!==0)throw new Error(`${this.id} capacityByteLength must be a positive multiple of 4`);this.capacityByteLength=o,this.buffer=e.createTransientBuffer({id:`${this.id}-buffer`,byteLength:o,usage:or.Buffer.STORAGE|or.Buffer.COPY_SRC|or.Buffer.COPY_DST})}allocate(e,t){if(!e)throw new Error(`${this.id} slot id must not be empty`);if(this.slots.has(e))throw new Error(`${this.id} slot "${e}" already exists`);if(!["float32","uint32","sint32"].includes(t))throw new Error(`${this.id} unsupported slot format ${t}`);if(this.nextByteOffset+4>this.capacityByteLength)throw new Error(`${this.id} capacity exceeded while allocating "${e}"`);let o=Object.freeze({id:e,format:t,byteOffset:this.nextByteOffset});return this.nextByteOffset+=4,this.slots.set(e,o),this.views.set(e,new ce(this.buffer,{format:t,length:1,byteOffset:o.byteOffset,byteStride:4,rowByteLength:4})),o}get(e){return this.slots.get(e)}getSlots(){return Object.freeze([...this.slots.values()])}getView(e){let t=this.views.get(e.id);if(!t)throw new Error(`${this.id} does not contain slot "${e.id}"`);return t}get byteLength(){return this.nextByteOffset}get size(){return this.slots.size}get availableByteLength(){return this.capacityByteLength-this.nextByteOffset}};var Po=class{id;format;arena;slot;constructor(e,t){this.id=t.id,this.format=t.format,this.arena=e,this.slot=t}get byteOffset(){return this.slot.byteOffset}get wordOffset(){return this.slot.byteOffset>>>2}get view(){return this.arena.getView(this.slot)}};function Bo(r,e,t){let o=wi(r);return new Po(o,o.allocate(e,t))}function J(r,e="gpuValues"){let t=`${e}[${r.wordOffset}u]`;switch(r.format){case"float32":return`bitcast<f32>(${t})`;case"uint32":return t;case"sint32":return`bitcast<i32>(${t})`}}function Pe(r,e,t="gpuValues"){let o=`${t}[${r.wordOffset}u]`;switch(r.format){case"float32":return`${o} = bitcast<u32>(${e});`;case"uint32":return`${o} = ${e};`;case"sint32":return`${o} = bitcast<u32>(${e});`}}function Y(r,e,t="gpuValues"){return`@group(${r}) @binding(${e}) var<storage, read_write> ${t}: array<u32>;`}var Pt=class{id;active;workgroups;dispatchBuffer;constructor(e,t){if(this.id=t.id,this.active=t.active,this.workgroups=t.workgroups,t.active.arena.graph!==e)throw new Error(`${this.id} active scalar must belong to target graph`);this.dispatchBuffer=e.createTransientBuffer({id:`${this.id}-dispatch`,byteLength:12,usage:nr.Buffer.STORAGE|nr.Buffer.INDIRECT|nr.Buffer.COPY_SRC})}getUpdateCommandNodes(e,t=`${this.id}-update`){if(this.active.arena.graph!==e)throw new Error(`${this.id} active scalar must belong to target graph`);let o=this.active.arena.buffer,[n,i,a]=this.workgroups,s=`${Y(0,0)}
8
8
  @group(0) @binding(1) var<storage, read_write> dispatch: array<u32>;
9
9
  @compute @workgroup_size(1)
10
10
  fn main() {
@@ -12,17 +12,17 @@ fn main() {
12
12
  dispatch[0] = select(0u, ${n}u, enabled);
13
13
  dispatch[1] = ${i}u;
14
14
  dispatch[2] = ${a}u;
15
- }`;return[M({id:t,workload:{operation:"GPUScalarDispatchGate",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:4,writeByteLength:12},resources:[{buffer:o,usage:"storage-read"},{buffer:this.dispatchBuffer,usage:"storage-write"}],compile:({device:u})=>{let d=new A(u,{id:t,source:s,shaderLayout:{bindings:[{name:"gpuValues",type:"read-only-storage",group:0,location:0},{name:"dispatch",type:"storage",group:0,location:1}]}});return{encode:({computePass:c,getBuffer:m})=>{let l={gpuValues:m(o),dispatch:m(this.dispatchBuffer)};d.dispatch(c,{bindings:l,x:1,y:1,z:1})},destroy:()=>d.destroy()}}})]}get condition(){return{id:`${this.id}-active`,source:"gpu",mode:"indirect",buffer:this.dispatchBuffer}}};function nr(r,e,t){return e.flatMap(o=>{let n=tr(o);if(o.type!=="compute"||o.condition||!n)throw new Error("Gated primitives must expose unconditional compute nodes with exact dispatch geometry");let i=new St(r,{id:`${o.id}-gate`,active:t,workgroups:n});return[...i.getUpdateCommandNodes(r).map(a=>k(a,[1,1,1])),{...o,condition:i.condition}]})}le();var ir=class{id;operation;left;right;output;constructor(e){this.id=e.id??`gpu-scalar-${e.operation}`,this.operation=e.operation,this.left=e.left,this.right=e.right,this.output=e.output,Za(this)}getCommandNodes(e){let t=this.left.arena;if(this.right&&this.right.arena!==t)throw new Error(`${this.id} operands must belong to the same GPUValueArena`);if(this.output.arena!==t)throw new Error(`${this.id} output must belong to the same GPUValueArena`);if(t.graph!==e)throw new Error(`${this.id} scalars must belong to the target graph`);let o=t.buffer,n=Qa(this);return[k(M({id:this.id,workload:{operation:"GPUScalarCompute",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:this.right?8:4,writeByteLength:4},resources:[{buffer:o,usage:"storage-write"}],compile:({device:i})=>{let a=new A(i,{id:this.id,source:n,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:s,getBuffer:u})=>{let d={gpuValues:u(o)};a.dispatch(s,{bindings:d,x:1,y:1,z:1})},destroy:()=>a.destroy()}}}),[1,1,1])]}};function Za(r){let e=r.operation==="copy"||r.operation==="sqrt",t=es(r.operation);if(!e&&!r.right)throw new Error(`${r.id} ${r.operation} requires a right operand`);if(e&&r.right)throw new Error(`${r.id} ${r.operation} does not accept a right operand`);if(r.right&&r.right.format!==r.left.format)throw new Error(`${r.id} input scalar formats must match`);if(r.operation==="sqrt"&&r.left.format!=="float32")throw new Error(`${r.id} sqrt currently requires float32 input`);if(t){if(r.output.format!=="uint32")throw new Error(`${r.id} comparison output must be uint32`)}else if(r.output.format!==r.left.format)throw new Error(`${r.id} arithmetic output format must match input format`)}function Qa(r){let e=J(r.left),t=r.right?J(r.right):void 0,o=Ja(r.operation,e,t);return`${Y(0,0)}
16
- @compute @workgroup_size(1) fn main(){${Se(r.output,o)}}`}function Ja(r,e,t){switch(r){case"copy":return e;case"add":return`(${e} + ${t})`;case"subtract":return`(${e} - ${t})`;case"multiply":return`(${e} * ${t})`;case"divide":return`(${e} / ${t})`;case"sqrt":return`sqrt(${e})`;case"min":return`min(${e}, ${t})`;case"max":return`max(${e}, ${t})`;case"equal":return`select(0u,1u,${e} == ${t})`;case"not-equal":return`select(0u,1u,${e} != ${t})`;case"less-than":return`select(0u,1u,${e} < ${t})`;case"less-than-or-equal":return`select(0u,1u,${e} <= ${t})`;case"greater-than":return`select(0u,1u,${e} > ${t})`;case"greater-than-or-equal":return`select(0u,1u,${e} >= ${t})`}}function es(r){return["equal","not-equal","less-than","less-than-or-equal","greater-than","greater-than-or-equal"].includes(r)}le();var Ze=class{props;id;constructor(e){this.props=e,this.id=e.id??`${e.output.id}-literal`}getCommandNodes(e){let{output:t,value:o}=this.props;if(t.arena.graph!==e)throw new Error(`${this.id} output must belong to target graph`);let n=t.format==="float32"?`f32(${o})`:t.format==="uint32"?`${o}u`:`${o}i`,i=`
15
+ }`;return[M({id:t,workload:{operation:"GPUScalarDispatchGate",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:4,writeByteLength:12},resources:[{buffer:o,usage:"storage-read"},{buffer:this.dispatchBuffer,usage:"storage-write"}],compile:({device:u})=>{let c=new I(u,{id:t,source:s,shaderLayout:{bindings:[{name:"gpuValues",type:"read-only-storage",group:0,location:0},{name:"dispatch",type:"storage",group:0,location:1}]}});return{encode:({computePass:d,getBuffer:m})=>{let f={gpuValues:m(o),dispatch:m(this.dispatchBuffer)};c.dispatch(d,{bindings:f,x:1,y:1,z:1})},destroy:()=>c.destroy()}}})]}get condition(){return{id:`${this.id}-active`,source:"gpu",mode:"indirect",buffer:this.dispatchBuffer}}};function ir(r,e,t){return e.flatMap(o=>{let n=rr(o);if(o.type!=="compute"||o.condition||!n)throw new Error("Gated primitives must expose unconditional compute nodes with exact dispatch geometry");let i=new Pt(r,{id:`${o.id}-gate`,active:t,workgroups:n});return[...i.getUpdateCommandNodes(r).map(a=>k(a,[1,1,1])),{...o,condition:i.condition}]})}fe();var ar=class{id;operation;left;right;output;constructor(e){this.id=e.id??`gpu-scalar-${e.operation}`,this.operation=e.operation,this.left=e.left,this.right=e.right,this.output=e.output,ys(this)}getCommandNodes(e){let t=this.left.arena;if(this.right&&this.right.arena!==t)throw new Error(`${this.id} operands must belong to the same GPUValueArena`);if(this.output.arena!==t)throw new Error(`${this.id} output must belong to the same GPUValueArena`);if(t.graph!==e)throw new Error(`${this.id} scalars must belong to the target graph`);let o=t.buffer,n=xs(this);return[k(M({id:this.id,workload:{operation:"GPUScalarCompute",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:this.right?8:4,writeByteLength:4},resources:[{buffer:o,usage:"storage-write"}],compile:({device:i})=>{let a=new I(i,{id:this.id,source:n,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:s,getBuffer:u})=>{let c={gpuValues:u(o)};a.dispatch(s,{bindings:c,x:1,y:1,z:1})},destroy:()=>a.destroy()}}}),[1,1,1])]}};function ys(r){let e=r.operation==="copy"||r.operation==="sqrt",t=ws(r.operation);if(!e&&!r.right)throw new Error(`${r.id} ${r.operation} requires a right operand`);if(e&&r.right)throw new Error(`${r.id} ${r.operation} does not accept a right operand`);if(r.right&&r.right.format!==r.left.format)throw new Error(`${r.id} input scalar formats must match`);if(r.operation==="sqrt"&&r.left.format!=="float32")throw new Error(`${r.id} sqrt currently requires float32 input`);if(t){if(r.output.format!=="uint32")throw new Error(`${r.id} comparison output must be uint32`)}else if(r.output.format!==r.left.format)throw new Error(`${r.id} arithmetic output format must match input format`)}function xs(r){let e=J(r.left),t=r.right?J(r.right):void 0,o=bs(r.operation,e,t);return`${Y(0,0)}
16
+ @compute @workgroup_size(1) fn main(){${Pe(r.output,o)}}`}function bs(r,e,t){switch(r){case"copy":return e;case"add":return`(${e} + ${t})`;case"subtract":return`(${e} - ${t})`;case"multiply":return`(${e} * ${t})`;case"divide":return`(${e} / ${t})`;case"sqrt":return`sqrt(${e})`;case"min":return`min(${e}, ${t})`;case"max":return`max(${e}, ${t})`;case"equal":return`select(0u,1u,${e} == ${t})`;case"not-equal":return`select(0u,1u,${e} != ${t})`;case"less-than":return`select(0u,1u,${e} < ${t})`;case"less-than-or-equal":return`select(0u,1u,${e} <= ${t})`;case"greater-than":return`select(0u,1u,${e} > ${t})`;case"greater-than-or-equal":return`select(0u,1u,${e} >= ${t})`}}function ws(r){return["equal","not-equal","less-than","less-than-or-equal","greater-than","greater-than-or-equal"].includes(r)}fe();var Ze=class{props;id;constructor(e){this.props=e,this.id=e.id??`${e.output.id}-literal`}getCommandNodes(e){let{output:t,value:o}=this.props;if(t.arena.graph!==e)throw new Error(`${this.id} output must belong to target graph`);let n=t.format==="float32"?`f32(${o})`:t.format==="uint32"?`${o}u`:`${o}i`,i=`
17
17
  ${Y(0,0)}
18
18
 
19
19
  @compute @workgroup_size(1)
20
20
  fn main() {
21
- ${Se(t,n)}
21
+ ${Pe(t,n)}
22
22
  }
23
- `,a=t.arena.buffer;return[k(M({id:this.id,workload:{operation:"GPUScalarLiteral",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:0,writeByteLength:4},resources:[{buffer:a,usage:"storage-write"}],compile:({device:s})=>{let u=new A(s,{id:this.id,source:i,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:d,getBuffer:c})=>{let m={gpuValues:c(a)};u.dispatch(d,{bindings:m,x:1,y:1,z:1})},destroy:()=>u.destroy()}}}),[1,1,1])]}};le();function ar(r,e,t,o){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new Error(`${r} element count must be a non-negative uint32`);di(r,t);let n=Math.floor(o);if(!Number.isSafeInteger(n)||n<1)throw new Error("maxComputeWorkgroupsPerDimension must be a positive integer");let i=Math.max(1,Math.ceil(e/t)),a=Math.min(i,n),s=Math.min(Math.ceil(i/a),n),u=Math.ceil(i/a/s);if(u>n)throw new Error(`${r} requires ${i} workgroups, exceeding the 3D dispatch limit of ${n} per dimension`);return{x:a,y:s,z:u}}function ke(r,e){di("GPU dispatch",e);let t=Math.floor(4294967295/e)+1;return`let workgroupIndex = (workgroupId.z * ${r.y}u + workgroupId.y) * ${r.x}u + workgroupId.x;
23
+ `,a=t.arena.buffer;return[k(M({id:this.id,workload:{operation:"GPUScalarLiteral",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:0,writeByteLength:4},resources:[{buffer:a,usage:"storage-write"}],compile:({device:s})=>{let u=new I(s,{id:this.id,source:i,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:c,getBuffer:d})=>{let m={gpuValues:d(a)};u.dispatch(c,{bindings:m,x:1,y:1,z:1})},destroy:()=>u.destroy()}}}),[1,1,1])]}};fe();function sr(r,e,t,o){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new Error(`${r} element count must be a non-negative uint32`);Ti(r,t);let n=Math.floor(o);if(!Number.isSafeInteger(n)||n<1)throw new Error("maxComputeWorkgroupsPerDimension must be a positive integer");let i=Math.max(1,Math.ceil(e/t)),a=Math.min(i,n),s=Math.min(Math.ceil(i/a),n),u=Math.ceil(i/a/s);if(u>n)throw new Error(`${r} requires ${i} workgroups, exceeding the 3D dispatch limit of ${n} per dimension`);return{x:a,y:s,z:u}}function ke(r,e){Ti("GPU dispatch",e);let t=Math.floor(4294967295/e)+1;return`let workgroupIndex = (workgroupId.z * ${r.y}u + workgroupId.y) * ${r.x}u + workgroupId.x;
24
24
  if (workgroupIndex >= ${t}u) { return; }
25
- let index = workgroupIndex * ${e}u + localInvocationIndex;`}function di(r,e){if(!Number.isSafeInteger(e)||e<2||e>4294967295||4294967296%e!==0)throw new Error(`${r} workgroup size must be a power of two greater than one`)}function D(r){return r instanceof B?r.data:[r]}function fe(r,e){let t=e[0]?.length??0;if(e.some(u=>u.length!==t))throw new Error("Aligned vectors must have equal logical lengths");let o=e.map(D),n=e.map(()=>0),i=e.map(()=>0),a=[],s=0;for(;s<t;){for(let m=0;m<o.length;m++)for(;o[m][n[m]]?.length===i[m];)n[m]++,i[m]=0;let u=o.map((m,l)=>m[n[l]]),d=Math.min(...u.map((m,l)=>m.length-i[l])),c=[];for(let m=0;m<u.length;m++){let l=u[m],f=u.findIndex((h,y)=>y<m&&h===l&&i[y]===i[m]);c.push(f>=0?c[f]:i[m]===0&&d===l.length?l:r.createDataView(l.buffer,{format:l.format,length:d,byteOffset:l.byteOffset+i[m]*l.byteStride,byteStride:l.byteStride,rowByteLength:l.rowByteLength}))}a.push(c);for(let m=0;m<i.length;m++)i[m]+=d;s+=d}return a}var sr=256,ur=class r{props;id;constructor(e){this.props=e,this.id=e.id??"gpu-vector-scalar-madd";for(let[t,o]of Object.entries({input:e.input,addend:e.addend,output:e.output}))for(let n of D(o))Re(n,["float32"],`${this.id} ${t}`);if(e.input.length!==e.addend.length||e.input.length!==e.output.length)throw new Error(`${this.id} vector lengths must match`)}getCommandNodes(e){let{input:t,scale:o,addend:n,output:i,gate:a}=this.props;if(t instanceof B||n instanceof B||i instanceof B)return fe(e,[t,n,i]).flatMap(([f,h,y],w)=>new r({id:`${this.id}-chunk-${w}`,input:f,addend:h,output:y,scale:o,gate:a}).getCommandNodes(e));if([t,n,i].some(f=>f.buffer.graph!==e)||o.arena.graph!==e)throw new Error(`${this.id} resources must belong to target graph`);if(i.length===0)return[];let s=o.arena.buffer,u=ar("GPUVectorScalarMADD",i.length,sr,e.device.limits.maxComputeWorkgroupsPerDimension),d=t===i?"outputValues":"inputValues",c=n===i?"outputValues":"addendValues",m=`
25
+ let index = workgroupIndex * ${e}u + localInvocationIndex;`}function Ti(r,e){if(!Number.isSafeInteger(e)||e<2||e>4294967295||4294967296%e!==0)throw new Error(`${r} workgroup size must be a power of two greater than one`)}function A(r){return r instanceof B?r.data:[r]}function pe(r,e){let t=e[0]?.length??0;if(e.some(u=>u.length!==t))throw new Error("Aligned vectors must have equal logical lengths");let o=e.map(A),n=e.map(()=>0),i=e.map(()=>0),a=[],s=0;for(;s<t;){for(let m=0;m<o.length;m++)for(;o[m][n[m]]?.length===i[m];)n[m]++,i[m]=0;let u=o.map((m,f)=>m[n[f]]),c=Math.min(...u.map((m,f)=>m.length-i[f])),d=[];for(let m=0;m<u.length;m++){let f=u[m],p=u.findIndex((h,x)=>x<m&&h===f&&i[x]===i[m]);d.push(p>=0?d[p]:i[m]===0&&c===f.length?f:r.createDataView(f.buffer,{format:f.format,length:c,byteOffset:f.byteOffset+i[m]*f.byteStride,byteStride:f.byteStride,rowByteLength:f.rowByteLength}))}a.push(d);for(let m=0;m<i.length;m++)i[m]+=c;s+=c}return a}var ur=256,cr=class r{props;id;constructor(e){this.props=e,this.id=e.id??"gpu-vector-scalar-madd";for(let[t,o]of Object.entries({input:e.input,addend:e.addend,output:e.output}))for(let n of A(o))Re(n,["float32"],`${this.id} ${t}`);if(e.input.length!==e.addend.length||e.input.length!==e.output.length)throw new Error(`${this.id} vector lengths must match`)}getCommandNodes(e){let{input:t,scale:o,addend:n,output:i,gate:a}=this.props;if(t instanceof B||n instanceof B||i instanceof B)return pe(e,[t,n,i]).flatMap(([p,h,x],w)=>new r({id:`${this.id}-chunk-${w}`,input:p,addend:h,output:x,scale:o,gate:a}).getCommandNodes(e));if([t,n,i].some(p=>p.buffer.graph!==e)||o.arena.graph!==e)throw new Error(`${this.id} resources must belong to target graph`);if(i.length===0)return[];let s=o.arena.buffer,u=sr("GPUVectorScalarMADD",i.length,ur,e.device.limits.maxComputeWorkgroupsPerDimension),c=t===i?"outputValues":"inputValues",d=n===i?"outputValues":"addendValues",m=`
26
26
  const LENGTH: u32 = ${i.length}u;
27
27
  const I: u32 = ${E(t)}u;
28
28
  const A: u32 = ${E(n)}u;
@@ -33,27 +33,27 @@ ${n===i?"":"@group(0) @binding(1) var<storage, read> addendValues: array<f32>;"}
33
33
  @group(0) @binding(2) var<storage, read_write> outputValues: array<f32>;
34
34
  ${Y(0,3)}
35
35
 
36
- @compute @workgroup_size(${sr})
36
+ @compute @workgroup_size(${ur})
37
37
  fn main(
38
38
  @builtin(workgroup_id) workgroupId: vec3u,
39
39
  @builtin(local_invocation_index) localInvocationIndex: u32
40
40
  ) {
41
- ${ke(u,sr)}
41
+ ${ke(u,ur)}
42
42
  if (index >= LENGTH) {
43
43
  return;
44
44
  }
45
45
 
46
- let x = ${d}[I + index];
47
- let y = ${c}[A + index];
46
+ let x = ${c}[I + index];
47
+ let y = ${d}[A + index];
48
48
  outputValues[O + index] = ${J(o)} * x + y;
49
49
  }
50
- `,l=[k(M({id:this.id,workload:{operation:"GPUVectorScalarMADD",commandCount:1,maximumWorkgroupCount:u.x*u.y*u.z,maximumInvocationCount:u.x*u.y*u.z*sr,readByteLength:t.length*8+4,writeByteLength:i.length*4},resources:[...t===i?[]:[{buffer:t,usage:"storage-read"}],...n===i?[]:[{buffer:n,usage:"storage-read"}],{buffer:i,usage:t===i||n===i?"storage-read-write":"storage-write"},{buffer:s,usage:"storage-read"}],compile:({device:f})=>{let h=new A(f,{id:this.id,source:m,shaderLayout:{bindings:[...t===i?[]:[{name:"inputValues",type:"read-only-storage",group:0,location:0}],...n===i?[]:[{name:"addendValues",type:"read-only-storage",group:0,location:1}],{name:"outputValues",type:"storage",group:0,location:2},{name:"gpuValues",type:"read-only-storage",group:0,location:3}]}});return{encode:({computePass:y,getBuffer:w})=>{let I={...t===i?{}:{inputValues:V(t,w)},...n===i?{}:{addendValues:V(n,w)},outputValues:V(i,w),gpuValues:w(s)};h.dispatch(y,{bindings:I,x:u.x,y:u.y,z:u.z})},destroy:()=>h.destroy()}}}),[u.x,u.y,u.z])];return a?nr(e,l,a.active):l}};le();function dr(r,e={}){let t=r.features?.has("subgroups"),o=!e.requiresSubgroupId||r.wgslLanguageFeatures?.has("subgroup_id");return t&&o?"subgroups":"portable"}le();Ae();function So(r,e,t,o){if(!Number.isSafeInteger(t)||!Number.isSafeInteger(o)||t<0||o<0||t+o>e.length)throw new Error("Graph range must fit the source");let n=[],i=e instanceof B?e.chunks:[{offset:0,length:e.length,data:e}],a=0,s=i.length;for(;a<s;){let u=Math.floor((a+s)/2);i[u].offset+i[u].length<=t?a=u+1:s=u}for(let u=a;u<i.length&&i[u].offset<t+o;u++){let{data:d,offset:c}=i[u],m=Math.max(t,c),l=Math.min(t+o,c+d.length);m<l&&n.push(m===c&&l===c+d.length?d:r.createDataView(d.buffer,{format:d.format,length:l-m,byteOffset:d.byteOffset+(m-c)*d.byteStride,byteStride:d.byteStride,rowByteLength:d.rowByteLength}))}return new B({id:`graph-range-${t}-${o}`,name:`graph-range-${t}-${o}`,stride:e instanceof B?e.stride:N(e.format).components*(N(e.format).listSize??1),format:e.format,length:o,valueLength:o*(N(e.format).listSize??1),byteStride:e.byteStride,rowByteLength:e.rowByteLength,data:n})}function ci(r,e,t){if([...e,...t].some(s=>s.length>4294967295))throw new Error("Logical lengths must fit uint32 addressing");let o=e.flatMap(D),n=t.flatMap(D);for(let s of[...o,...n])if(s.buffer.graph!==r)throw new Error("Views must belong to the target graph");let i=new Set(o.map(s=>s.buffer)),a=new Map;for(let s of n){if(i.has(s.buffer))throw new Error("Outputs must use separate buffers from inputs");if(!s.length)continue;let u=a.get(s.buffer)??[];u.push(s),a.set(s.buffer,u)}for(let s of a.values()){s.sort((d,c)=>d.byteOffset-c.byteOffset);let u=0;for(let d of s){if(d.byteOffset<u)throw new Error("Writable chunks must not overlap");u=d.byteOffset+(d.length-1)*d.byteStride+d.rowByteLength}}}function Qe(r,e){if(!Number.isSafeInteger(r)||r<1||r>4294967295||!Number.isSafeInteger(e)||e<1)throw new Error("Invalid chunk dispatch");let t=Math.min(r,e),o=Math.min(Math.ceil(r/t),e),n=Math.ceil(r/t/o);if(n>e)throw new Error("Chunk operation exceeds the 3D dispatch limit");return{x:t,y:o,z:n}}function cr(r,e){let t=[...Object.entries(e.inputs??{}),...Object.entries(e.outputs)];for(let[,n]of t)if(Pt(n).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let o=e.dispatch.x*e.dispatch.y*e.dispatch.z;return k(M({id:e.id,workload:{commandCount:1,maximumWorkgroupCount:o,maximumInvocationCount:o*(e.workgroupSize??256)},resources:[...Object.values(e.inputs??{}).map(n=>({buffer:n,usage:"storage-read"})),...Object.values(e.outputs).map(n=>({buffer:n,usage:"storage-read-write"}))],compile:({device:n})=>{let i=new A(n,{id:e.id,source:e.source,shaderLayout:{bindings:t.map(([a],s)=>({name:a,group:0,location:s,type:s<Object.keys(e.inputs??{}).length?"read-only-storage":"storage"}))}});return{encode:({computePass:a,getBuffer:s})=>{let u={};for(let[d,c]of t)u[d]=V(c,s);i.dispatch(a,{bindings:u,x:e.dispatch.x,y:e.dispatch.y,z:e.dispatch.z})},destroy:()=>i.destroy()}}}),[e.dispatch.x,e.dispatch.y,e.dispatch.z])}var Oe=256;function ts(r){if(!Number.isSafeInteger(r)||r<1)throw new Error("reduction length must be positive");let e=[];do r=Math.ceil(r/Oe),e.push(r);while(r>1);return e}function mi(r,e){let t=[],o=e.input,n=e.inputB===o?void 0:e.inputB,i=e.inputB===o;for(let[a,s]of ts(o.length).entries()){let u=s>1?Me(r,`${e.id}-partials-${a}`,"float32",s):void 0;t.push(rs(r,{id:`${e.id}-level-${a}`,input:o,inputB:n,square:i,output:u,finalScalar:u?void 0:e.output,accumulate:e.accumulate})),u&&(o=u),n=void 0,i=!1}return t}function rs(r,e){let t=e.output?.length??1,o=Qe(t,r.device.limits.maxComputeWorkgroupsPerDimension),n=e.finalScalar?.arena.buffer,i=e.inputB?2:1,a=dr(r.device,{requiresSubgroupId:!0})==="subgroups",s=os(e,o,a);return k(M({id:e.id,workload:{operation:"GPUDotProductScalar",commandCount:1,maximumWorkgroupCount:o.x*o.y*o.z,maximumInvocationCount:o.x*o.y*o.z*Oe,readByteLength:e.input.length*4*(e.inputB?2:1),writeByteLength:t*4},resources:[{buffer:e.input,usage:"storage-read"},...e.inputB?[{buffer:e.inputB,usage:"storage-read"}]:[],...e.output?[{buffer:e.output,usage:"storage-write"}]:[],...n?[{buffer:n,usage:"storage-read-write"}]:[]],compile:({device:u})=>{let d=new A(u,{id:e.id,source:s,shaderLayout:{bindings:[{name:"inputValues",type:"read-only-storage",group:0,location:0},...e.inputB?[{name:"inputBValues",type:"read-only-storage",group:0,location:1}]:[],{name:e.output?"outputValues":"gpuValues",type:"storage",group:0,location:i}]}});return{encode:({computePass:c,getBuffer:m})=>{let l={inputValues:V(e.input,m)};e.inputB&&(l.inputBValues=V(e.inputB,m)),e.output&&(l.outputValues=V(e.output,m)),n&&(l.gpuValues=m(n)),d.dispatch(c,{bindings:l,...o})},destroy:()=>d.destroy()}}}),[o.x,o.y,o.z])}function os(r,e,t){let o=r.inputB?2:1,n=`inputValues[${E(r.input)}u + index]`,i=r.inputB?`${n} * inputBValues[${E(r.inputB)}u + index]`:r.square?`${n} * ${n}`:n,a=r.output?`outputValues[${E(r.output)}u + groupIndex] = total;`:Se(r.finalScalar,r.accumulate?`${J(r.finalScalar)} + total`:"total");return`${t?`enable subgroups;
50
+ `,f=[k(M({id:this.id,workload:{operation:"GPUVectorScalarMADD",commandCount:1,maximumWorkgroupCount:u.x*u.y*u.z,maximumInvocationCount:u.x*u.y*u.z*ur,readByteLength:t.length*8+4,writeByteLength:i.length*4},resources:[...t===i?[]:[{buffer:t,usage:"storage-read"}],...n===i?[]:[{buffer:n,usage:"storage-read"}],{buffer:i,usage:t===i||n===i?"storage-read-write":"storage-write"},{buffer:s,usage:"storage-read"}],compile:({device:p})=>{let h=new I(p,{id:this.id,source:m,shaderLayout:{bindings:[...t===i?[]:[{name:"inputValues",type:"read-only-storage",group:0,location:0}],...n===i?[]:[{name:"addendValues",type:"read-only-storage",group:0,location:1}],{name:"outputValues",type:"storage",group:0,location:2},{name:"gpuValues",type:"read-only-storage",group:0,location:3}]}});return{encode:({computePass:x,getBuffer:w})=>{let G={...t===i?{}:{inputValues:z(t,w)},...n===i?{}:{addendValues:z(n,w)},outputValues:z(i,w),gpuValues:w(s)};h.dispatch(x,{bindings:G,x:u.x,y:u.y,z:u.z})},destroy:()=>h.destroy()}}}),[u.x,u.y,u.z])];return a?ir(e,f,a.active):f}};fe();function dr(r,e={}){let t=r.features?.has("subgroups"),o=!e.requiresSubgroupId||r.wgslLanguageFeatures?.has("subgroup_id");return t&&o?"subgroups":"portable"}fe();Ie();function Eo(r,e,t,o){if(!Number.isSafeInteger(t)||!Number.isSafeInteger(o)||t<0||o<0||t+o>e.length)throw new Error("Graph range must fit the source");let n=[],i=e instanceof B?e.chunks:[{offset:0,length:e.length,data:e}],a=0,s=i.length;for(;a<s;){let u=Math.floor((a+s)/2);i[u].offset+i[u].length<=t?a=u+1:s=u}for(let u=a;u<i.length&&i[u].offset<t+o;u++){let{data:c,offset:d}=i[u],m=Math.max(t,d),f=Math.min(t+o,d+c.length);m<f&&n.push(m===d&&f===d+c.length?c:r.createDataView(c.buffer,{format:c.format,length:f-m,byteOffset:c.byteOffset+(m-d)*c.byteStride,byteStride:c.byteStride,rowByteLength:c.rowByteLength}))}return new B({id:`graph-range-${t}-${o}`,name:`graph-range-${t}-${o}`,stride:e instanceof B?e.stride:V(e.format).components*(V(e.format).listSize??1),format:e.format,length:o,valueLength:o*(V(e.format).listSize??1),byteStride:e.byteStride,rowByteLength:e.rowByteLength,data:n})}function vi(r,e,t){if([...e,...t].some(s=>s.length>4294967295))throw new Error("Logical lengths must fit uint32 addressing");let o=e.flatMap(A),n=t.flatMap(A);for(let s of[...o,...n])if(s.buffer.graph!==r)throw new Error("Views must belong to the target graph");let i=new Set(o.map(s=>s.buffer)),a=new Map;for(let s of n){if(i.has(s.buffer))throw new Error("Outputs must use separate buffers from inputs");if(!s.length)continue;let u=a.get(s.buffer)??[];u.push(s),a.set(s.buffer,u)}for(let s of a.values()){s.sort((c,d)=>c.byteOffset-d.byteOffset);let u=0;for(let c of s){if(c.byteOffset<u)throw new Error("Writable chunks must not overlap");u=c.byteOffset+(c.length-1)*c.byteStride+c.rowByteLength}}}function Qe(r,e){if(!Number.isSafeInteger(r)||r<1||r>4294967295||!Number.isSafeInteger(e)||e<1)throw new Error("Invalid chunk dispatch");let t=Math.min(r,e),o=Math.min(Math.ceil(r/t),e),n=Math.ceil(r/t/o);if(n>e)throw new Error("Chunk operation exceeds the 3D dispatch limit");return{x:t,y:o,z:n}}function mr(r,e){let t=[...Object.entries(e.inputs??{}),...Object.entries(e.outputs)];for(let[,n]of t)if(Ct(n).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let o=e.dispatch.x*e.dispatch.y*e.dispatch.z;return k(M({id:e.id,workload:{commandCount:1,maximumWorkgroupCount:o,maximumInvocationCount:o*(e.workgroupSize??256)},resources:[...Object.values(e.inputs??{}).map(n=>({buffer:n,usage:"storage-read"})),...Object.values(e.outputs).map(n=>({buffer:n,usage:"storage-read-write"}))],compile:({device:n})=>{let i=new I(n,{id:e.id,source:e.source,shaderLayout:{bindings:t.map(([a],s)=>({name:a,group:0,location:s,type:s<Object.keys(e.inputs??{}).length?"read-only-storage":"storage"}))}});return{encode:({computePass:a,getBuffer:s})=>{let u={};for(let[c,d]of t)u[c]=z(d,s);i.dispatch(a,{bindings:u,x:e.dispatch.x,y:e.dispatch.y,z:e.dispatch.z})},destroy:()=>i.destroy()}}}),[e.dispatch.x,e.dispatch.y,e.dispatch.z])}var Oe=256;function Ts(r){if(!Number.isSafeInteger(r)||r<1)throw new Error("reduction length must be positive");let e=[];do r=Math.ceil(r/Oe),e.push(r);while(r>1);return e}function Si(r,e){let t=[],o=e.input,n=e.inputB===o?void 0:e.inputB,i=e.inputB===o;for(let[a,s]of Ts(o.length).entries()){let u=s>1?Me(r,`${e.id}-partials-${a}`,"float32",s):void 0;t.push(vs(r,{id:`${e.id}-level-${a}`,input:o,inputB:n,square:i,output:u,finalScalar:u?void 0:e.output,accumulate:e.accumulate})),u&&(o=u),n=void 0,i=!1}return t}function vs(r,e){let t=e.output?.length??1,o=Qe(t,r.device.limits.maxComputeWorkgroupsPerDimension),n=e.finalScalar?.arena.buffer,i=e.inputB?2:1,a=dr(r.device,{requiresSubgroupId:!0})==="subgroups",s=Ss(e,o,a);return k(M({id:e.id,workload:{operation:"GPUDotProductScalar",commandCount:1,maximumWorkgroupCount:o.x*o.y*o.z,maximumInvocationCount:o.x*o.y*o.z*Oe,readByteLength:e.input.length*4*(e.inputB?2:1),writeByteLength:t*4},resources:[{buffer:e.input,usage:"storage-read"},...e.inputB?[{buffer:e.inputB,usage:"storage-read"}]:[],...e.output?[{buffer:e.output,usage:"storage-write"}]:[],...n?[{buffer:n,usage:"storage-read-write"}]:[]],compile:({device:u})=>{let c=new I(u,{id:e.id,source:s,shaderLayout:{bindings:[{name:"inputValues",type:"read-only-storage",group:0,location:0},...e.inputB?[{name:"inputBValues",type:"read-only-storage",group:0,location:1}]:[],{name:e.output?"outputValues":"gpuValues",type:"storage",group:0,location:i}]}});return{encode:({computePass:d,getBuffer:m})=>{let f={inputValues:z(e.input,m)};e.inputB&&(f.inputBValues=z(e.inputB,m)),e.output&&(f.outputValues=z(e.output,m)),n&&(f.gpuValues=m(n)),c.dispatch(d,{bindings:f,...o})},destroy:()=>c.destroy()}}}),[o.x,o.y,o.z])}function Ss(r,e,t){let o=r.inputB?2:1,n=`inputValues[${E(r.input)}u + index]`,i=r.inputB?`${n} * inputBValues[${E(r.inputB)}u + index]`:r.square?`${n} * ${n}`:n,a=r.output?`outputValues[${E(r.output)}u + groupIndex] = total;`:Pe(r.finalScalar,r.accumulate?`${J(r.finalScalar)} + total`:"total");return`${t?`enable subgroups;
51
51
  requires subgroup_id;
52
52
  `:""}
53
53
  @group(0) @binding(0) var<storage, read> inputValues: array<f32>;
54
54
  ${r.inputB?"@group(0) @binding(1) var<storage, read> inputBValues: array<f32>;":""}
55
55
  ${r.output?`@group(0) @binding(${o}) var<storage, read_write> outputValues: array<f32>;`:Y(0,o)}
56
- ${t?is:ns}
56
+ ${t?Ps:Cs}
57
57
  @compute @workgroup_size(${Oe})
58
58
  fn main(
59
59
  @builtin(local_invocation_index) lane: u32,
@@ -69,7 +69,7 @@ fn main(
69
69
  if (index < ${r.input.length}u) { value = ${i}; }
70
70
  let total = reduceValue(value, lane${t?", subgroupInvocationId, subgroupSize, subgroupId":""});
71
71
  if (lane == 0u) { ${a} }
72
- }`}var ns=`
72
+ }`}var Cs=`
73
73
  var<workgroup> reductionScratch: array<f32, ${Oe}>;
74
74
  fn reduceValue(value: f32, lane: u32) -> f32 {
75
75
  reductionScratch[lane] = value;
@@ -79,7 +79,7 @@ fn reduceValue(value: f32, lane: u32) -> f32 {
79
79
  workgroupBarrier();
80
80
  }
81
81
  return reductionScratch[0];
82
- }`,is=`
82
+ }`,Ps=`
83
83
  var<workgroup> subgroupTotals: array<f32, 64>;
84
84
  fn reduceValue(value: f32, lane: u32, subgroupInvocationId: u32, subgroupSize: u32, subgroupId: u32) -> f32 {
85
85
  let subtotal = subgroupAdd(value);
@@ -91,7 +91,7 @@ fn reduceValue(value: f32, lane: u32, subgroupInvocationId: u32, subgroupSize: u
91
91
  workgroupBarrier();
92
92
  }
93
93
  return subgroupTotals[0];
94
- }`;var mr=class{props;id;constructor(e){this.props=e,this.id=e.id??"gpu-dot-product-scalar";for(let t of[e.left,e.right])for(let o of D(t))Re(o,["float32"],this.id);if(e.left.length!==e.right.length||e.left.length>4294967295)throw new Error(`${this.id} inputs must have equal uint32-addressable lengths`)}getCommandNodes(e){let{left:t,right:o,output:n,gate:i}=this.props;if(n.arena.graph!==e||i&&i.active.arena.graph!==e||[t,o].flatMap(D).some(u=>u.buffer.graph!==e))throw new Error(`${this.id} resources must belong to target graph`);let a=[],s=0;for(let u of fe(e,[t,o]))for(let d=0;d<u[0].length;){let c=Math.min(u[0].length-d,...u.map(f=>Math.floor((e.device.limits.maxStorageBufferBindingSize-(f.byteOffset+d*4)%256)/4)));if(c<1)throw new Error("Dot product span must fit a storage binding");let m=e.createDataView(u[0].buffer,{format:"float32",byteOffset:u[0].byteOffset+d*4,length:c}),l=u[1]===u[0]?m:e.createDataView(u[1].buffer,{format:"float32",byteOffset:u[1].byteOffset+d*4,length:c});a.push(...mi(e,{id:`${this.id}-chunk-${s}`,input:m,inputB:l,output:n,accumulate:s>0})),s++,d+=c}return s||a.push(...new Ze({id:this.id,output:n,value:0}).getCommandNodes(e)),i?nr(e,a,i.active):a}};Ae();le();Ae();var lr=256,Je=Uint32Array.BYTES_PER_ELEMENT,fr=class{id;source;indices;output;wordsPerRow;constructor(e){this.id=e.id??"gpu-gather",this.source=e.source,this.indices=e.indices,this.output=e.output;for(let o of D(this.indices))ni(o,`${this.id} indices`);for(let o of[this.source,this.output])for(let n of D(o))ss(n,this.id,o===this.output);if(this.source.format!==this.output.format)throw new Error(`${this.id} source and output must use the same format`);if(this.output.length<this.indices.length)throw new Error(`${this.id} output must contain at least indices.length rows`);let t=new Set([...D(this.source).map(o=>o.buffer),...D(this.indices).map(o=>o.buffer)]);if(D(this.output).some(o=>t.has(o.buffer)))throw new Error(`${this.id} output must use a separate buffer`);this.wordsPerRow=N(this.source.format).byteLength/Je}getCommandNodes(e){return as(e,this)}};function as(r,e,t=0,o="GPUGather"){let n=[];for(let d of[e.source,e.indices,e.output])for(let c of D(d))if(c.buffer.graph!==r)throw new Error(`${e.id} views must belong to the target graph`);if(e.indices.length===0)return n;let i=ii(r,e.output,e.indices.length),a=fe(r,[e.indices,i]),s=Ie(D(e.source)).filter(d=>d.length),u=s.length?s:[void 0];for(let[d,[c,m]]of a.entries()){let l=ar(o,c.length,lr,r.device.limits.maxComputeWorkgroupsPerDimension);for(let[f,h]of u.entries()){let y=h?.data;for(let L of[m,...y?[y,c]:[]])if(Pt(L).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let w=a.length===1&&u.length===1?e.id:`${e.id}-span-${d}-source-${f}`,I=us({source:y,sourceOffset:h?.offset??0,indices:c,output:m,wordsPerRow:e.wordsPerRow,initialize:f===0,invalidValue:t,dispatchLayout:l});n.push(k(M({id:w,workload:{operation:o,commandCount:1,maximumWorkgroupCount:l.x*l.y*l.z,maximumInvocationCount:l.x*l.y*l.z*lr,readByteLength:y?c.length*(Je+y.rowByteLength):0,writeByteLength:c.length*m.rowByteLength},resources:[...y?[{buffer:y,usage:"storage-read"},{buffer:c,usage:"storage-read"}]:[],{buffer:m,usage:"storage-write"}],compile:({device:L})=>{let P=new A(L,{id:w,source:I,shaderLayout:{bindings:[{name:"outputWords",type:"storage",group:0,location:0},...y?[{name:"sourceWords",type:"read-only-storage",group:0,location:1},{name:"indices",type:"read-only-storage",group:0,location:2}]:[]]}});return{encode:({computePass:W,getBuffer:g})=>{let p={outputWords:V(m,g)};y&&(p.sourceWords=V(y,g),p.indices=V(c,g)),P.dispatch(W,{bindings:p,x:l.x,y:l.y,z:l.z})},destroy:()=>P.destroy()}}}),[l.x,l.y,l.z]))}}return n}function ss(r,e,t){if(we(r.format)||Te(r.format))throw new Error(`${e} must use a fixed-width GPU data format`);let o=N(r.format);if((t?r.byteStride!==o.byteLength:r.byteStride<o.byteLength||r.byteStride%Je!==0)||r.rowByteLength!==o.byteLength||r.byteOffset%Je!==0||r.rowByteLength%Je!==0)throw new Error(`${e} must be packed, uint32-aligned GPU data with 32-bit-word rows`)}function us(r){let{source:e,indices:t,output:o,wordsPerRow:n,initialize:i,invalidValue:a,dispatchLayout:s}=r;return`const INDEX_COUNT: u32 = ${t.length}u;
94
+ }`;var fr=class{props;id;constructor(e){this.props=e,this.id=e.id??"gpu-dot-product-scalar";for(let t of[e.left,e.right])for(let o of A(t))Re(o,["float32"],this.id);if(e.left.length!==e.right.length||e.left.length>4294967295)throw new Error(`${this.id} inputs must have equal uint32-addressable lengths`)}getCommandNodes(e){let{left:t,right:o,output:n,gate:i}=this.props;if(n.arena.graph!==e||i&&i.active.arena.graph!==e||[t,o].flatMap(A).some(u=>u.buffer.graph!==e))throw new Error(`${this.id} resources must belong to target graph`);let a=[],s=0;for(let u of pe(e,[t,o]))for(let c=0;c<u[0].length;){let d=Math.min(u[0].length-c,...u.map(p=>Math.floor((e.device.limits.maxStorageBufferBindingSize-(p.byteOffset+c*4)%256)/4)));if(d<1)throw new Error("Dot product span must fit a storage binding");let m=e.createDataView(u[0].buffer,{format:"float32",byteOffset:u[0].byteOffset+c*4,length:d}),f=u[1]===u[0]?m:e.createDataView(u[1].buffer,{format:"float32",byteOffset:u[1].byteOffset+c*4,length:d});a.push(...Si(e,{id:`${this.id}-chunk-${s}`,input:m,inputB:f,output:n,accumulate:s>0})),s++,c+=d}return s||a.push(...new Ze({id:this.id,output:n,value:0}).getCommandNodes(e)),i?ir(e,a,i.active):a}};Ie();fe();Ie();var pr=256,Je=Uint32Array.BYTES_PER_ELEMENT,lr=class{id;source;indices;output;wordsPerRow;constructor(e){this.id=e.id??"gpu-gather",this.source=e.source,this.indices=e.indices,this.output=e.output;for(let o of A(this.indices))gi(o,`${this.id} indices`);for(let o of[this.source,this.output])for(let n of A(o))Es(n,this.id,o===this.output);if(this.source.format!==this.output.format)throw new Error(`${this.id} source and output must use the same format`);if(this.output.length<this.indices.length)throw new Error(`${this.id} output must contain at least indices.length rows`);let t=new Set([...A(this.source).map(o=>o.buffer),...A(this.indices).map(o=>o.buffer)]);if(A(this.output).some(o=>t.has(o.buffer)))throw new Error(`${this.id} output must use a separate buffer`);this.wordsPerRow=V(this.source.format).byteLength/Je}getCommandNodes(e){return Bs(e,this)}};function Bs(r,e,t=0,o="GPUGather"){let n=[];for(let c of[e.source,e.indices,e.output])for(let d of A(c))if(d.buffer.graph!==r)throw new Error(`${e.id} views must belong to the target graph`);if(e.indices.length===0)return n;let i=yi(r,e.output,e.indices.length),a=pe(r,[e.indices,i]),s=Ge(A(e.source)).filter(c=>c.length),u=s.length?s:[void 0];for(let[c,[d,m]]of a.entries()){let f=sr(o,d.length,pr,r.device.limits.maxComputeWorkgroupsPerDimension);for(let[p,h]of u.entries()){let x=h?.data;for(let L of[m,...x?[x,d]:[]])if(Ct(L).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let w=a.length===1&&u.length===1?e.id:`${e.id}-span-${c}-source-${p}`,G=Ls({source:x,sourceOffset:h?.offset??0,indices:d,output:m,wordsPerRow:e.wordsPerRow,initialize:p===0,invalidValue:t,dispatchLayout:f});n.push(k(M({id:w,workload:{operation:o,commandCount:1,maximumWorkgroupCount:f.x*f.y*f.z,maximumInvocationCount:f.x*f.y*f.z*pr,readByteLength:x?d.length*(Je+x.rowByteLength):0,writeByteLength:d.length*m.rowByteLength},resources:[...x?[{buffer:x,usage:"storage-read"},{buffer:d,usage:"storage-read"}]:[],{buffer:m,usage:"storage-write"}],compile:({device:L})=>{let C=new I(L,{id:w,source:G,shaderLayout:{bindings:[{name:"outputWords",type:"storage",group:0,location:0},...x?[{name:"sourceWords",type:"read-only-storage",group:0,location:1},{name:"indices",type:"read-only-storage",group:0,location:2}]:[]]}});return{encode:({computePass:W,getBuffer:g})=>{let l={outputWords:z(m,g)};x&&(l.sourceWords=z(x,g),l.indices=z(d,g)),C.dispatch(W,{bindings:l,x:f.x,y:f.y,z:f.z})},destroy:()=>C.destroy()}}}),[f.x,f.y,f.z]))}}return n}function Es(r,e,t){if(we(r.format)||Te(r.format))throw new Error(`${e} must use a fixed-width GPU data format`);let o=V(r.format);if((t?r.byteStride!==o.byteLength:r.byteStride<o.byteLength||r.byteStride%Je!==0)||r.rowByteLength!==o.byteLength||r.byteOffset%Je!==0||r.rowByteLength%Je!==0)throw new Error(`${e} must be packed, uint32-aligned GPU data with 32-bit-word rows`)}function Ls(r){let{source:e,indices:t,output:o,wordsPerRow:n,initialize:i,invalidValue:a,dispatchLayout:s}=r;return`const INDEX_COUNT: u32 = ${t.length}u;
95
95
  const WORDS_PER_ROW: u32 = ${n}u;
96
96
  const OUTPUT_OFFSET: u32 = ${E(o)}u;
97
97
  @group(0) @binding(0) var<storage, read_write> outputWords: array<u32>;
@@ -103,12 +103,12 @@ const INDEX_OFFSET: u32 = ${E(t)}u;
103
103
  @group(0) @binding(1) var<storage, read> sourceWords: array<u32>;
104
104
  @group(0) @binding(2) var<storage, read> indices: array<u32>;
105
105
  `:""}
106
- @compute @workgroup_size(${lr})
106
+ @compute @workgroup_size(${pr})
107
107
  fn main(
108
108
  @builtin(workgroup_id) workgroupId: vec3u,
109
109
  @builtin(local_invocation_index) localInvocationIndex: u32
110
110
  ) {
111
- ${ke(s,lr)}
111
+ ${ke(s,pr)}
112
112
  if (index >= INDEX_COUNT) { return; }
113
113
  let outputBase = OUTPUT_OFFSET + index * WORDS_PER_ROW;
114
114
  ${e?`
@@ -126,27 +126,27 @@ ${i?`
126
126
  outputWords[outputBase + word] = ${a}u;
127
127
  }
128
128
  `:""}
129
- }`}function fi(r){if(r.candidates.length===0)throw new Error("GPU strategy candidate list must not be empty");let e={device:r.device,workload:r.workload},t=r.candidates.filter(i=>i.isSupported?.(e)??!0);if(t.length===0)throw new Error("no supported GPU strategy candidate");if(r.preferredId){let i=t.find(a=>a.id===r.preferredId);if(!i)throw new Error(`preferred GPU strategy "${r.preferredId}" is not supported`);return li(i,e)}let o=t[0],n=o.score(e);for(let i=1;i<t.length;i++){let a=t[i],s=a.score(e);s>n&&(o=a,n=s)}return li(o,e,n)}function li(r,e,t=r.score(e)){return Object.freeze({id:r.id,score:t,reason:r.reason(e),details:Object.freeze(r.createDetails(e))})}function pi(r,e,t){if(!Number.isSafeInteger(e.rows)||e.rows<0)throw new Error("SpMV rows must be non-negative");if(!Number.isSafeInteger(e.nonZeros)||e.nonZeros<0)throw new Error("SpMV nonZeros must be non-negative");let o=e.nonZeros/Math.max(1,e.rows),n=e.statistics?.maxNonZerosPerRow,i=e.statistics?.shortRowFraction,a=dr(r,{requiresSubgroupId:!0})==="subgroups";return fi({device:r,workload:e,preferredId:t,candidates:[{id:"scalar-row",score:()=>o<=8?100:o<=16?60:10,reason:()=>`average row length ${o.toFixed(1)} favors one invocation per row`,createDetails:()=>({rowsPerWorkgroup:64,workgroupSize:64,workgroupsPerLongRow:1})},{id:"subgroup-row",isSupported:()=>a,score:()=>o<=64&&(i===void 0||i<.9)?110:35,reason:()=>"subgroups available; medium CSR rows can reduce within a subgroup",createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:128,workgroupsPerLongRow:1})},{id:"workgroup-row",score:()=>o>32&&(n===void 0||n<=2048)?100:50,reason:()=>`average row length ${o.toFixed(1)} favors cooperative row reduction`,createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:1})},{id:"long-row",score:()=>n!==void 0&&n>2048||o>1024?140:0,reason:()=>"very long rows favor multi-workgroup partial reduction",createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:4})}]})}var pr=class{id;props;constructor(e){this.id=e.id??"gpu-adaptive-spmv",this.props=e;for(let[t,o]of Object.entries({rowOffsets:e.rowOffsets,columnIndices:e.columnIndices,values:e.values,vector:e.vector,output:e.output})){for(let n of D(o))Re(n,[t==="rowOffsets"||t==="columnIndices"?"uint32":"float32"],`${this.id} ${t}`);if(o.length>4294967295)throw new Error("SpMV logical lengths must fit in uint32")}if(e.rowOffsets.length!==e.output.length+1)throw new Error(`${this.id} rowOffsets length must equal output.length + 1`);if(e.columnIndices.length!==e.values.length)throw new Error(`${this.id} columnIndices and values must have equal length`);if(!Number.isSafeInteger(e.columns)||e.columns<0)throw new Error(`${this.id} columns must be a non-negative integer`);if(e.vector.length!==e.columns)throw new Error(`${this.id} vector length must equal columns`)}getStrategy(e){return pi(e.device,{rows:this.props.output.length,nonZeros:this.props.values.length,statistics:this.props.statistics},this.props.strategy)}explain(e){let t=this.getStrategy(e);return Object.freeze({operation:"GPUSpMV",strategy:t.id,score:t.score,reason:t.reason,...t.details})}getCommandNodes(e){let{rowOffsets:t,columnIndices:o,values:n,vector:i,output:a}=this.props;if(ci(e,[t,o,n,i],[a]),!a.length)return[];let s=[],u=this.getStrategy(e),d=u.id,c=u.details.workgroupSize,m=d==="long-row"?u.details.workgroupsPerLongRow:1,l=fe(e,[So(e,t,0,a.length),So(e,t,1,a.length),a]),f=fe(e,[o,n]),h=Ie(D(i)).filter(p=>p.length),y=e.device.limits.maxComputeWorkgroupsPerDimension,w=Math.min(4096,Math.floor(e.device.limits.maxStorageBufferBindingSize/(m*4)));if(w<1)throw new Error("SpMV count scratch must fit a storage binding");let I=[];for(let p of l)for(let T=0;T<p[0].length;T+=w){let C=Math.min(w,p[0].length-T);I.push(p.map(x=>e.createDataView(x.buffer,{format:x.format,length:C,byteOffset:x.byteOffset+T*4})))}let L=I.map(([p],T)=>d==="long-row"?Me(e,`${this.id}-rows-${T}-partials`,"float32",p.length*m):void 0),P=h.length>1&&I.length*h.length>h.length+I.length,W=0,g=[];for(let[p,[T,C]]of f.entries()){let x;if(P){x=Me(e,`${this.id}-gather-${p}`,"float32",T.length);let G=new fr({id:`${this.id}-gather-${p}`,source:i,indices:T,output:x}).getCommandNodes(e);for(let[$,X]of G.entries())s.push($===0?{...X,dependsOn:[...X.dependsOn??[],...g]}:X)}let O=x?[{data:x,offset:0}]:h,S=[];for(let[G,[$,X,ie]]of I.entries()){let pe=$.length,Gt=L[G];for(let[Io,Tr]of O.entries()){let Ao=p===0&&Io===0,Uo=`${this.id}-rows-${G}-nonzeros-${p}-vector-${Io}-${d}`,Ci=d==="scalar-row"?Math.ceil(pe/c):pe*m,$o=Qe(Ci,y),_o=Gt??ie;if(s.push(cr(e,{id:Uo,source:ds({strategy:d,workgroupSize:c,parts:m,length:pe,begins:$,ends:X,indices:T,matrixValues:C,vector:Tr.data,output:_o,nonzeroStart:W,vectorStart:Tr.offset,initialize:Ao,dispatch:$o,gathered:!!x,columns:this.props.columns}),inputs:{rowBegins:$,rowEnds:X,columnIndices:T,matrixValues:C,vectorValues:Tr.data},outputs:{[Gt?"rowPartials":"outputValues"]:_o},dispatch:$o,workgroupSize:c})),Gt){let Ro=Qe(Math.ceil(pe/64),y);s.push(cr(e,{id:`${Uo}-finalize`,inputs:{rowPartials:Gt},outputs:{outputValues:ie},dispatch:Ro,workgroupSize:64,source:`
129
+ }`}function Pi(r){if(r.candidates.length===0)throw new Error("GPU strategy candidate list must not be empty");let e={device:r.device,workload:r.workload},t=r.candidates.filter(i=>i.isSupported?.(e)??!0);if(t.length===0)throw new Error("no supported GPU strategy candidate");if(r.preferredId){let i=t.find(a=>a.id===r.preferredId);if(!i)throw new Error(`preferred GPU strategy "${r.preferredId}" is not supported`);return Ci(i,e)}let o=t[0],n=o.score(e);for(let i=1;i<t.length;i++){let a=t[i],s=a.score(e);s>n&&(o=a,n=s)}return Ci(o,e,n)}function Ci(r,e,t=r.score(e)){return Object.freeze({id:r.id,score:t,reason:r.reason(e),details:Object.freeze(r.createDetails(e))})}function Bi(r,e,t){if(!Number.isSafeInteger(e.rows)||e.rows<0)throw new Error("SpMV rows must be non-negative");if(!Number.isSafeInteger(e.nonZeros)||e.nonZeros<0)throw new Error("SpMV nonZeros must be non-negative");let o=e.nonZeros/Math.max(1,e.rows),n=e.statistics?.maxNonZerosPerRow,i=e.statistics?.shortRowFraction,a=dr(r,{requiresSubgroupId:!0})==="subgroups";return Pi({device:r,workload:e,preferredId:t,candidates:[{id:"scalar-row",score:()=>o<=8?100:o<=16?60:10,reason:()=>`average row length ${o.toFixed(1)} favors one invocation per row`,createDetails:()=>({rowsPerWorkgroup:64,workgroupSize:64,workgroupsPerLongRow:1})},{id:"subgroup-row",isSupported:()=>a,score:()=>o<=64&&(i===void 0||i<.9)?110:35,reason:()=>"subgroups available; medium CSR rows can reduce within a subgroup",createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:128,workgroupsPerLongRow:1})},{id:"workgroup-row",score:()=>o>32&&(n===void 0||n<=2048)?100:50,reason:()=>`average row length ${o.toFixed(1)} favors cooperative row reduction`,createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:1})},{id:"long-row",score:()=>n!==void 0&&n>2048||o>1024?140:0,reason:()=>"very long rows favor multi-workgroup partial reduction",createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:4})}]})}var hr=class{id;props;constructor(e){this.id=e.id??"gpu-adaptive-spmv",this.props=e;for(let[t,o]of Object.entries({rowOffsets:e.rowOffsets,columnIndices:e.columnIndices,values:e.values,vector:e.vector,output:e.output})){for(let n of A(o))Re(n,[t==="rowOffsets"||t==="columnIndices"?"uint32":"float32"],`${this.id} ${t}`);if(o.length>4294967295)throw new Error("SpMV logical lengths must fit in uint32")}if(e.rowOffsets.length!==e.output.length+1)throw new Error(`${this.id} rowOffsets length must equal output.length + 1`);if(e.columnIndices.length!==e.values.length)throw new Error(`${this.id} columnIndices and values must have equal length`);if(!Number.isSafeInteger(e.columns)||e.columns<0)throw new Error(`${this.id} columns must be a non-negative integer`);if(e.vector.length!==e.columns)throw new Error(`${this.id} vector length must equal columns`)}getStrategy(e){return Bi(e.device,{rows:this.props.output.length,nonZeros:this.props.values.length,statistics:this.props.statistics},this.props.strategy)}explain(e){let t=this.getStrategy(e);return Object.freeze({operation:"GPUSpMV",strategy:t.id,score:t.score,reason:t.reason,...t.details})}getCommandNodes(e){let{rowOffsets:t,columnIndices:o,values:n,vector:i,output:a}=this.props;if(vi(e,[t,o,n,i],[a]),!a.length)return[];let s=[],u=this.getStrategy(e),c=u.id,d=u.details.workgroupSize,m=c==="long-row"?u.details.workgroupsPerLongRow:1,f=pe(e,[Eo(e,t,0,a.length),Eo(e,t,1,a.length),a]),p=pe(e,[o,n]),h=Ge(A(i)).filter(l=>l.length),x=e.device.limits.maxComputeWorkgroupsPerDimension,w=Math.min(4096,Math.floor(e.device.limits.maxStorageBufferBindingSize/(m*4)));if(w<1)throw new Error("SpMV count scratch must fit a storage binding");let G=[];for(let l of f)for(let T=0;T<l[0].length;T+=w){let S=Math.min(w,l[0].length-T);G.push(l.map(b=>e.createDataView(b.buffer,{format:b.format,length:S,byteOffset:b.byteOffset+T*4})))}let L=G.map(([l],T)=>c==="long-row"?Me(e,`${this.id}-rows-${T}-partials`,"float32",l.length*m):void 0),C=h.length>1&&G.length*h.length>h.length+G.length,W=0,g=[];for(let[l,[T,S]]of p.entries()){let b;if(C){b=Me(e,`${this.id}-gather-${l}`,"float32",T.length);let D=new lr({id:`${this.id}-gather-${l}`,source:i,indices:T,output:b}).getCommandNodes(e);for(let[U,X]of D.entries())s.push(U===0?{...X,dependsOn:[...X.dependsOn??[],...g]}:X)}let O=b?[{data:b,offset:0}]:h,P=[];for(let[D,[U,X,ie]]of G.entries()){let le=U.length,Dt=L[D];for(let[$o,vr]of O.entries()){let Uo=l===0&&$o===0,_o=`${this.id}-rows-${D}-nonzeros-${l}-vector-${$o}-${c}`,_i=c==="scalar-row"?Math.ceil(le/d):le*m,Ro=Qe(_i,x),Mo=Dt??ie;if(s.push(mr(e,{id:_o,source:Ds({strategy:c,workgroupSize:d,parts:m,length:le,begins:U,ends:X,indices:T,matrixValues:S,vector:vr.data,output:Mo,nonzeroStart:W,vectorStart:vr.offset,initialize:Uo,dispatch:Ro,gathered:!!b,columns:this.props.columns}),inputs:{rowBegins:U,rowEnds:X,columnIndices:T,matrixValues:S,vectorValues:vr.data},outputs:{[Dt?"rowPartials":"outputValues"]:Mo},dispatch:Ro,workgroupSize:d})),Dt){let ko=Qe(Math.ceil(le/64),x);s.push(mr(e,{id:`${_o}-finalize`,inputs:{rowPartials:Dt},outputs:{outputValues:ie},dispatch:ko,workgroupSize:64,source:`
130
130
  @group(0) @binding(0) var<storage, read> rowPartials: array<f32>;
131
131
  @group(0) @binding(1) var<storage, read_write> outputValues: array<f32>;
132
132
  @compute @workgroup_size(64)
133
133
  fn main(@builtin(workgroup_id) workgroupId: vec3u, @builtin(local_invocation_index) localInvocationIndex: u32) {
134
- ${ke(Ro,64)}
135
- if (index >= ${pe}u) { return; }
134
+ ${ke(ko,64)}
135
+ if (index >= ${le}u) { return; }
136
136
  var sum = 0.0;
137
137
  for (var part = 0u; part < ${m}u; part++) {
138
138
  sum += rowPartials[index * ${m}u + part];
139
139
  }
140
- outputValues[${E(ie)}u + index] ${Ao?"=":"+="} sum;
141
- }`}))}}O.length&&S.push(s[s.length-1].id)}g=S,W+=T.length}if(!f.length||!h.length)for(let[p,[T,,C]]of I.entries()){let x=Qe(Math.ceil(T.length/256),y);s.push(cr(e,{id:`${this.id}-rows-${p}-clear`,outputs:{outputValues:C},dispatch:x,source:`
140
+ outputValues[${E(ie)}u + index] ${Uo?"=":"+="} sum;
141
+ }`}))}}O.length&&P.push(s[s.length-1].id)}g=P,W+=T.length}if(!p.length||!h.length)for(let[l,[T,,S]]of G.entries()){let b=Qe(Math.ceil(T.length/256),x);s.push(mr(e,{id:`${this.id}-rows-${l}-clear`,outputs:{outputValues:S},dispatch:b,source:`
142
142
  @group(0) @binding(0) var<storage, read_write> outputValues: array<f32>;
143
143
  @compute @workgroup_size(256)
144
144
  fn main(@builtin(workgroup_id) workgroupId: vec3u, @builtin(local_invocation_index) localInvocationIndex: u32) {
145
- ${ke(x,256)}
145
+ ${ke(b,256)}
146
146
  if (index < ${T.length}u) {
147
- outputValues[${E(C)}u + index] = 0.0;
147
+ outputValues[${E(S)}u + index] = 0.0;
148
148
  }
149
- }`}))}return s}};function ds(r){let{strategy:e,workgroupSize:t,parts:o,length:n,dispatch:i}=r,a=e==="subgroup-row",s=e==="workgroup-row"||e==="long-row",u=e==="long-row",d=u?"rowPartials":"outputValues";return`
149
+ }`}))}return s}};function Ds(r){let{strategy:e,workgroupSize:t,parts:o,length:n,dispatch:i}=r,a=e==="subgroup-row",s=e==="workgroup-row"||e==="long-row",u=e==="long-row",c=u?"rowPartials":"outputValues";return`
150
150
  ${a?`enable subgroups;
151
151
  requires subgroup_id;`:""}
152
152
  @group(0) @binding(0) var<storage, read> rowBegins: array<u32>;
@@ -154,7 +154,7 @@ requires subgroup_id;`:""}
154
154
  @group(0) @binding(2) var<storage, read> columnIndices: array<u32>;
155
155
  @group(0) @binding(3) var<storage, read> matrixValues: array<f32>;
156
156
  @group(0) @binding(4) var<storage, read> vectorValues: array<f32>;
157
- @group(0) @binding(5) var<storage, read_write> ${d}: array<f32>;
157
+ @group(0) @binding(5) var<storage, read_write> ${c}: array<f32>;
158
158
  ${s?`var<workgroup> scratch: array<f32, ${t}>;`:""}
159
159
  @compute @workgroup_size(${t}) fn main(
160
160
  @builtin(workgroup_id) workgroupId: vec3u,
@@ -197,9 +197,9 @@ ${s?`var<workgroup> scratch: array<f32, ${t}>;`:""}
197
197
  }
198
198
  sum = scratch[0];`:""}
199
199
  if (lane == 0u) {
200
- ${d}[${E(r.output)}u + row * ${o}u + ${u?"part":"0u"}] ${u||r.initialize?"=":"+="} sum;
200
+ ${c}[${E(r.output)}u + row * ${o}u + ${u?"part":"0u"}] ${u||r.initialize?"=":"+="} sum;
201
201
  }
202
- }`}le();var hr=class{props;id;constructor(e){if(this.props=e,this.id=e.id??"gpu-predicate-conjunction",e.inputs.length<2)throw new Error(`${this.id} requires at least two predicates`);let t=e.output.arena;if(e.inputs.some(o=>o.arena!==t))throw new Error(`${this.id} predicates must share one GPUValueArena`)}getCommandNodes(e){let{inputs:t,output:o}=this.props;if(o.arena.graph!==e)throw new Error(`${this.id} predicates must belong to target graph`);let n=o.arena.buffer,i=t.map(s=>`(${J(s)} != 0u)`).join(" && "),a=`${Y(0,0)}
203
- @compute @workgroup_size(1)fn main(){${Se(o,`select(0u,1u,${i})`)}}`;return[M({id:this.id,workload:{operation:"GPUPredicateConjunction",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:t.length*4,writeByteLength:4},resources:[{buffer:n,usage:"storage-write"}],compile:({device:s})=>{let u=new A(s,{id:this.id,source:a,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:d,getBuffer:c})=>{let m={gpuValues:c(n)};u.dispatch(d,{bindings:m,x:1,y:1,z:1})},destroy:()=>u.destroy()}}})]}};var et=class extends q{type="conditional";predicate;lowering;constructor(e){let t=Array.isArray(e.body)?e.body:[e.body];super({id:e.id??"gpu-conditional-operation",operations:t,metadata:e.metadata}),this.predicate=Object.freeze({...e.predicate}),this.lowering=e.lowering??"auto"}},tt=class extends q{type="loop";predicate;maximumIterations;minimumIterations;lowering;constructor(e){let t=Array.isArray(e.body)?e.body:[e.body];if(super({id:e.id??"gpu-loop-operation",operations:t,metadata:e.metadata}),!Number.isSafeInteger(e.maximumIterations)||e.maximumIterations<1)throw new Error(`${this.id} maximumIterations must be a positive safe integer`);let o=e.minimumIterations??0;if(!Number.isSafeInteger(o)||o<0||o>e.maximumIterations)throw new Error(`${this.id} minimumIterations must be between zero and maximumIterations`);this.predicate=e.predicate?Object.freeze({...e.predicate}):void 0,this.maximumIterations=e.maximumIterations,this.minimumIterations=o,this.lowering=e.lowering??"auto"}};var rt=class{lowerers=new Map;register(e,t){if(!e)throw new Error("GPU operation lowering type is required");if(this.lowerers.has(e))throw new Error(`GPU operation lowering for "${e}" is already registered`);return this.lowerers.set(e,t),this}get(e){return this.lowerers.get(e)}};function gr(r,e={}){let t=[],o=new Set(r.scalars.map(i=>i.id));for(let i of r.vectors)i.external&&!e.vectors?.[i.id]&&t.push({level:"error",code:"missing-external-vector",valueId:i.id,message:`External vector "${i.id}" has no WebGPU binding`});let n=i=>{let a="id"in i&&typeof i.id=="string"?i.id:void 0;if(i instanceof et||i instanceof tt){let s=i.predicate;s?.source==="gpu"&&(s.value.format!=="uint32"&&t.push({level:"error",code:"invalid-predicate-format",operationId:a,valueId:s.value.id,message:`GPU predicate "${s.id}" must use uint32 state`}),o.has(s.value.id)||t.push({level:"error",code:"missing-predicate-scalar",operationId:a,valueId:s.value.id,message:`GPU predicate "${s.id}" references undeclared scalar "${s.value.id}"`}))}if(i instanceof q)for(let s of i.operations)n(s)};for(let i of r.operations)n(i);return Object.freeze({valid:!t.some(i=>i.level==="error"),issues:Object.freeze(t.map(i=>Object.freeze({...i})))})}var yr=class{device;capabilities;lowerings=new rt;constructor(e){this.device=e,this.capabilities=Object.freeze({backend:"webgpu",gpuConditionals:!0,nativeLoops:!1,childGraphs:!1}),this.registerCoreLowerings()}compile(e,t={}){let o=gr(e,t);if(!o.valid)throw new Error(`GPUGraph "${e.id}" validation failed: ${o.issues.filter(d=>d.level==="error").map(d=>d.message).join("; ")}`);let n=new er(this.device,{id:`${e.id}-commands`}),i=new Map;for(let d of e.scalars)i.set(d.id,Po(n,d.id,d.format));let a=new Map;for(let d of e.vectors){let c;if(d.external){let m=t.vectors[d.id],l="data"in m?m:{format:d.format,length:d.length,data:"buffer"in m?[m]:m};if(c=n.importGPUVector(d.id,l),c.format!==d.format||c.length!==d.length)throw new Error(`${d.id} binding format and length must match its logical vector`);if(d.chunkLengths&&(d.chunkLengths.length!==c.data.length||d.chunkLengths.some((f,h)=>f!==c.data[h].length)))throw new Error(`${d.id} binding must preserve its declared chunk topology`)}else{let m=d.chunkLengths??cs(d.length,this.device),l=m.map((f,h)=>Me(n,m.length===1?d.id:`${d.id}-chunk-${h}`,d.format,f));c=new B({id:d.id,name:d.id,format:d.format,length:d.length,valueLength:d.length,stride:1,byteStride:4,rowByteLength:4,data:l})}a.set(d.id,c)}let s=new Map;for(let d of e.textures){let c=d.external?n.importTexture(d,t.textures?.[d.id]):n.createTransientTexture(d);s.set(d.id,c)}let u={path:[],nodes:[],decisions:[],predicates:[],scalars:i,vectors:a,textures:s,textureValues:e.textures,predicateConjunctions:new Map,commandNodeIds:new Set};for(let d of e.operations)this.lower(n,d,u);return Object.freeze({program:e,graph:n,scalars:i,vectors:a,textures:s,validation:o,lowering:Object.freeze({operations:e.operationTree,nodes:Object.freeze(u.nodes.map(d=>Object.freeze({...d,operationPath:Object.freeze([...d.operationPath])}))),decisions:Object.freeze(u.decisions.map(d=>Object.freeze({...d})))})})}registerCoreLowerings(){this.lowerings.register("scalar-literal",(e,t)=>{let o=new Ze({id:e.id,output:t.resolveScalar(e.props.output),value:e.props.value});this.emitProducer(t.graph,o,[[1,1,1]]),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-scalar-literal",reason:"host-known literal lowers to one compute command node"})}),this.lowerings.register("scalar-operation",(e,t)=>{let o=new ir({id:e.id,operation:e.operation,left:t.resolveScalar(e.left),right:e.right?t.resolveScalar(e.right):void 0,output:t.resolveScalar(e.output)});this.emitProducer(t.graph,o,[[1,1,1]]),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-scalar-kernel",reason:"scalar operation lowers to one compute command node"})}),this.lowerings.register("vector-madd",(e,t)=>{let o=e.props,n=new ur({id:e.id,input:t.resolveVector(o.input),scale:t.resolveScalar(o.scale),addend:t.resolveVector(o.addend),output:t.resolveVector(o.output)});this.emitProducer(t.graph,n),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-vector-madd",reason:"dense float32 MADD lowers through explicit command nodes"})}),this.lowerings.register("dot-product",(e,t)=>{let o=e.props,n=new mr({id:e.id,left:t.resolveVector(o.left),right:t.resolveVector(o.right),output:t.resolveScalar(o.output)});this.emitProducer(t.graph,n),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-hierarchical-dot",reason:"chunk dot products use bounded hierarchical reductions into the scalar arena"})}),this.lowerings.register("spmv",(e,t)=>{let o=e.props,n=o.matrix,i=new pr({id:e.id,rowOffsets:t.resolveVector(n.rowOffsets),columnIndices:t.resolveVector(n.columnIndices),values:t.resolveVector(n.values),vector:t.resolveVector(o.vector),output:t.resolveVector(o.output),columns:n.columns,statistics:n.statistics,strategy:o.strategy}),a=i.getStrategy(t.graph);this.emitProducer(t.graph,i),t.recordDecision({operationId:e.id,operationType:e.type,lowering:`webgpu-spmv:${a.id}`,reason:a.reason})}),this.lowerings.register("conditional",(e,t)=>{t.recordDecision({operationId:e.id,operationType:e.type,lowering:"gpu-indirect-gate",reason:"WebGPU realizes runtime predicates with zero/nonzero indirect dispatch"});for(let o of e.operations)t.lowerConditional(e.predicate,o)}),this.lowerings.register("loop",(e,t)=>{if(!e.predicate||e.lowering==="unroll"){t.recordDecision({operationId:e.id,operationType:e.type,lowering:"bounded-unroll",reason:e.predicate?"explicit unroll preference":"loop has no runtime predicate"});for(let o=0;o<e.maximumIterations;o++)for(let n of e.operations)t.lower(n);return}t.recordDecision({operationId:e.id,operationType:e.type,lowering:"gpu-gated-bounded-sequence",reason:"WebGPU has indirect dispatch but no native graph loop"});for(let o=0;o<e.maximumIterations;o++){let n=o>=e.minimumIterations;for(let i of e.operations)n?t.lowerConditional(e.predicate,i):t.lower(i)}})}lower(e,t,o){let n="id"in t&&typeof t.id=="string"?t.id:t.constructor?.name??"command-node-producer";o.path.push(n);try{if(t instanceof q&&t.type==="composite"){o.decisions.push({operationId:t.id,operationType:t.type,lowering:"flatten",reason:"WebGPU has no executable child-graph primitive"});for(let i of t.operations)this.lower(e,i,o);return}if(yo(t)){let i=this.lowerings.get(t.type);if(i){let a=()=>i(t,{graph:e,capabilities:this.capabilities,lower:s=>this.lower(e,s,o),lowerConditional:(s,u)=>{o.predicates.push(s);try{this.lower(e,u,o)}finally{o.predicates.pop()}},resolveScalar:s=>this.resolveScalar(s,o),resolveVector:s=>this.resolveVector(s,o),resolveTexture:s=>this.resolveTexture(s,o),resolveTextureView:s=>{let u=s instanceof ce?s.texture:s,d=s instanceof ce?s.props:{};return e.createTextureView(this.resolveTexture(u,o),d)},recordDecision:s=>o.decisions.push(s)});t instanceof et||t instanceof tt?a():this.withNodeDecoration(e,o,a);return}}if("getNodes"in t||ri(t)){o.decisions.push({operationId:n,operationType:"command-node-producer",lowering:"explicit-command-nodes",reason:"execution primitive constructs explicit command nodes"}),this.withNodeDecoration(e,o,()=>e.add(t));return}throw new Error(`GPUGraph operation "${n}" has no WebGPU lowering`)}finally{o.path.pop()}}emitProducer(e,t,o){let n=t.getCommandNodes(e);if(!o){_e(e,n);return}if(n.length!==o.length)throw new Error(`lowering produced ${n.length} command nodes but declared ${o.length} dispatches`);let i=n.map((a,s)=>this.attachDispatch(a,o[s]));_e(e,i)}attachDispatch(e,t){if(e.type!=="compute")throw new Error(`dispatch geometry can only be attached to compute command nodes; got ${e.type} node "${e.id}"`);return k(e,t)}withNodeDecoration(e,t,o){return e.withComputeLowering(n=>this.decorateComputeNode(e,n,t),()=>e.withOtherLowering(n=>{if(t.predicates.length)throw new Error(`GPU predicates do not support ${n.type} node "${n.id}"`);let i=this.makeCommandNodeIdUnique(n,t);return t.nodes.push({nodeId:i.id,nodeType:i.type,operationPath:[...t.path]}),i},o))}decorateComputeNode(e,t,o){if(t=this.makeCommandNodeIdUnique(t,o),o.path.length&&o.nodes.push({nodeId:t.id,nodeType:"compute",operationPath:[...o.path]}),!o.predicates.length)return t;if(t.condition)throw new Error(`compute node "${t.id}" already has condition`);let n=tr(t);if(!n)throw new Error(`compute node "${t.id}" under runtime predicate must declare exact dispatch geometry`);let i;if(o.predicates.length===1)i=o.scalars.get(o.predicates[0].value.id);else{let u=o.predicates.map(l=>l.value.id).join("&&"),d=o.predicateConjunctions.get(u);d||(d=Po(e,`predicate-and-${o.predicateConjunctions.size}`,"uint32"),o.predicateConjunctions.set(u,d));let c=o.predicates.map(l=>o.scalars.get(l.value.id)),m=new hr({id:`${t.id}-predicate-and`,inputs:c,output:d}).getCommandNodes(e).map(l=>this.attachDispatch(l,[1,1,1]));e.withoutComputeLowering(()=>_e(e,m)),i=d}if(!i)throw new Error(`runtime predicate for "${t.id}" could not be resolved`);let a=new St(e,{id:`${t.id}-predicate`,active:i,workgroups:n}),s=a.getUpdateCommandNodes(e,`${t.id}-predicate-update`).map(u=>this.attachDispatch(u,[1,1,1]));return e.withoutComputeLowering(()=>_e(e,s)),{...t,condition:a.condition}}makeCommandNodeIdUnique(e,t){if(!t.commandNodeIds.has(e.id))return t.commandNodeIds.add(e.id),e;let o=1,n=`${e.id}-iteration-${o}`;for(;t.commandNodeIds.has(n);)o++,n=`${e.id}-iteration-${o}`;return t.commandNodeIds.add(n),{...e,id:n}}resolveTexture(e,t){if(!t.textureValues.includes(e))throw new Error(`Undeclared program texture "${e.id}"`);return t.textures.get(e.id)}resolveScalar(e,t){let o=t.scalars.get(e.id);if(!o||o.format!==e.format)throw new Error(`GPUGraph scalar "${e.id}" is not part of compilation`);return o}resolveVector(e,t){let o=t.vectors.get(e.id);if(!o||o.format!==e.format||o.length!==e.length)throw new Error(`GPUGraph vector "${e.id}" is not part of compilation`);return o}};function cs(r,e){let t=Math.floor(e.limits.maxStorageBufferBindingSize/4);if(t<1||r<=t)return[r];let o=[];for(let n=0;n<r;n+=t)o.push(Math.min(t,r-n));return o}function hi(r){let e=r.lowering.decisions.map(t=>`${t.operationId}: ${t.lowering} \u2014 ${t.reason}`);return Object.freeze({programId:r.program.id,semanticOperationCount:gi(r.program.operationTree),loweredNodeCount:r.lowering.nodes.length,loweringDecisionCount:r.lowering.decisions.length,scalarCount:r.program.scalars.length,vectorCount:r.program.vectors.length,externalVectorCount:r.program.vectors.filter(t=>t.external).length,cpuReadbackCount:0,backend:"webgpu",decisions:Object.freeze(e)})}function gi(r){return r.reduce((e,t)=>e+1+gi(t.children??[]),0)}var Eo=class{adapter;minimumSampleCount;explorationEnabled;calibrations=new Map;constructor(e){if(!Number.isSafeInteger(e.minimumSampleCount??1)||(e.minimumSampleCount??1)<=0)throw new Error("GPUCommandGraph autotuner minimumSampleCount must be a positive safe integer");if(this.adapter=ls(e.adapter),this.minimumSampleCount=e.minimumSampleCount??1,this.explorationEnabled=e.explorationEnabled??!0,e.profile?.adapter.key===this.adapter.key&&e.profile.version===1)for(let t of e.profile.calibrations)this.importCalibration(t)}selectKernel(e){xr(e.operation,"operation"),bi(e.workloadSize);let t=e.candidates.filter(s=>s.supported!==!1);if(t.length===0)throw new Error(`GPUCommandGraph autotuner operation "${e.operation}" has no supported variants`);for(let s of t)xr(s.id,"variant");let o=xi(e.workloadSize),n=t.map(s=>{let u=this.findNearestCalibration(e.operation,s.id,o);return{candidate:s,calibration:u,sampleCount:u?.workloadBucket===o?u.sampleCount:0,estimatedDurationMilliseconds:u?fs(u,e.workloadSize):void 0}});if(this.explorationEnabled){let s=n.find(u=>u.sampleCount<this.minimumSampleCount);if(s)return Object.freeze({operation:e.operation,variant:s.candidate.id,workloadSize:e.workloadSize,workloadBucket:o,reason:"exploration",sampleCount:s.sampleCount,...s.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:s.estimatedDurationMilliseconds}})}let i=n.filter(s=>s.estimatedDurationMilliseconds!==void 0).sort((s,u)=>(s.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY)-(u.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY))[0],a=i??n[0];return Object.freeze({operation:e.operation,variant:a.candidate.id,workloadSize:e.workloadSize,workloadBucket:o,reason:i?"calibrated":"fallback",sampleCount:a.calibration?.sampleCount??0,...a.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:a.estimatedDurationMilliseconds}})}observeKernel(e){if(xr(e.operation,"operation"),xr(e.variant,"variant"),bi(e.workloadSize),!Number.isFinite(e.durationMilliseconds)||e.durationMilliseconds<0)throw new Error("GPUCommandGraph autotuner durationMilliseconds must be nonnegative");let t=xi(e.workloadSize),o=Bo(e.operation,e.variant,t),n=this.calibrations.get(o)??{operation:e.operation,variant:e.variant,workloadBucket:t,sampleCount:0,meanWorkloadSize:0,meanDurationMilliseconds:0,durationSquaredDifferenceSum:0};n.sampleCount++,n.meanWorkloadSize+=(e.workloadSize-n.meanWorkloadSize)/n.sampleCount;let i=e.durationMilliseconds-n.meanDurationMilliseconds;return n.meanDurationMilliseconds+=i/n.sampleCount,n.durationSquaredDifferenceSum+=i*(e.durationMilliseconds-n.meanDurationMilliseconds),this.calibrations.set(o,n),yi(n)}observeTimingReport(e,t){let o=new Map(t.nodes.map(i=>[i.id,i])),n=0;for(let i of e.nodes){let a=o.get(i.id);i.gpuTimeMilliseconds===void 0||!a?.operation||!a.variant||(this.observeKernel({operation:a.operation,variant:a.variant,workloadSize:Math.max(a.maximumInvocationCount,1),durationMilliseconds:i.gpuTimeMilliseconds}),n++)}return n}exportProfile(){let e=[...this.calibrations.values()].sort((t,o)=>t.operation.localeCompare(o.operation)||t.variant.localeCompare(o.variant)||t.workloadBucket-o.workloadBucket).map(yi);return Object.freeze({version:1,adapter:this.adapter,calibrations:Object.freeze(e)})}reset(){this.calibrations.clear()}importCalibration(e){!e.operation||!e.variant||!Number.isSafeInteger(e.workloadBucket)||!Number.isSafeInteger(e.sampleCount)||e.sampleCount<=0||!Number.isFinite(e.meanWorkloadSize)||e.meanWorkloadSize<=0||!Number.isFinite(e.meanDurationMilliseconds)||e.meanDurationMilliseconds<0||this.calibrations.set(Bo(e.operation,e.variant,e.workloadBucket),{operation:e.operation,variant:e.variant,workloadBucket:e.workloadBucket,sampleCount:e.sampleCount,meanWorkloadSize:e.meanWorkloadSize,meanDurationMilliseconds:e.meanDurationMilliseconds,durationSquaredDifferenceSum:e.sampleCount>1?e.durationStandardDeviationMilliseconds**2*(e.sampleCount-1):0})}findNearestCalibration(e,t,o){let n=this.calibrations.get(Bo(e,t,o));if(n)return n;let i;for(let a of this.calibrations.values())a.operation!==e||a.variant!==t||(!i||Math.abs(a.workloadBucket-o)<Math.abs(i.workloadBucket-o))&&(i=a);return i}};function ms(r){let e=[...r.features].sort(),t={type:r.info.type,vendor:r.info.vendor,renderer:r.info.renderer,version:r.info.version,gpu:r.info.gpu,gpuType:r.info.gpuType,...r.info.gpuArchitecture?{gpuArchitecture:r.info.gpuArchitecture}:{},...r.info.gpuBackend?{gpuBackend:r.info.gpuBackend}:{},...r.info.featureLevel?{featureLevel:r.info.featureLevel}:{},features:Object.freeze(e),...r.info.subgroupMinSize===void 0?{}:{subgroupMinSize:r.info.subgroupMinSize},...r.info.subgroupMaxSize===void 0?{}:{subgroupMaxSize:r.info.subgroupMaxSize},maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension};return Object.freeze({key:JSON.stringify(t),...t})}function ls(r){return Object.freeze({...r,features:Object.freeze([...r.features])})}function yi(r){return Object.freeze({operation:r.operation,variant:r.variant,workloadBucket:r.workloadBucket,sampleCount:r.sampleCount,meanWorkloadSize:r.meanWorkloadSize,meanDurationMilliseconds:r.meanDurationMilliseconds,durationStandardDeviationMilliseconds:r.sampleCount>1?Math.sqrt(r.durationSquaredDifferenceSum/(r.sampleCount-1)):0})}function fs(r,e){return r.meanDurationMilliseconds*(e/Math.max(r.meanWorkloadSize,1))}function xi(r){return Math.floor(Math.log2(Math.max(r,1)))}function Bo(r,e,t){return`${r}\0${e}\0${t}`}function xr(r,e){if(!r)throw new Error(`GPUCommandGraph autotuner ${e} is required`)}function bi(r){if(!Number.isSafeInteger(r)||r<=0)throw new Error("GPUCommandGraph autotuner workloadSize must be a positive safe integer")}var ps={interactive:4,normal:8,background:16},Lo=class{targetStepMilliseconds;latencyPriority;minimumScale;maximumScale;responsiveness;maximumAdjustmentFactor;initialBudget;currentBudget;currentScale=1;currentSampleCount=0;constructor(e){wi(e.initialBudget);let t=e.latencyPriority??"normal",o=e.targetStepMilliseconds??ps[t];Et(o,"targetStepMilliseconds");let n=e.minimumScale??.125,i=e.maximumScale??4,a=e.responsiveness??.25,s=e.maximumAdjustmentFactor??2;if(Et(n,"minimumScale"),Et(i,"maximumScale"),Et(s,"maximumAdjustmentFactor"),n>1||i<1)throw new Error("GPUCommandGraph budget scale range must contain the initial scale 1");if(!Number.isFinite(a)||a<=0||a>1)throw new Error("GPUCommandGraph budget responsiveness must be in the interval (0, 1]");if(s<1)throw new Error("GPUCommandGraph budget maximumAdjustmentFactor must be at least 1");this.initialBudget=vi(e.initialBudget),this.currentBudget=this.initialBudget,this.latencyPriority=t,this.targetStepMilliseconds=o,this.minimumScale=n,this.maximumScale=i,this.responsiveness=a,this.maximumAdjustmentFactor=s}get budget(){return this.currentBudget}get sampleCount(){return this.currentSampleCount}reset(){this.currentBudget=this.initialBudget,this.currentScale=1,this.currentSampleCount=0}observeStep(e,t,o=this.currentBudget){Et(t,"durationMilliseconds"),wi(o);let n=hs(e,o);if(n>0){let i=this.targetStepMilliseconds*Math.min(n,1)/t,s=1+(Ti(i,1/this.maximumAdjustmentFactor,this.maximumAdjustmentFactor)-1)*this.responsiveness;this.currentScale=Ti(this.currentScale*s,this.minimumScale,this.maximumScale),this.currentBudget=gs(this.initialBudget,this.currentScale)}return this.currentSampleCount++,Object.freeze({sampleCount:this.currentSampleCount,durationMilliseconds:t,targetStepMilliseconds:this.targetStepMilliseconds,latencyPriority:this.latencyPriority,saturation:n,scale:this.currentScale,budget:this.currentBudget})}};function hs(r,e){let t=[r.maximumInvocationCount/e.maximumInvocationCount];return e.maximumNodeCount!==void 0&&t.push(r.nodeCount/e.maximumNodeCount),e.maximumCommandCount!==void 0&&t.push(r.commandCount/e.maximumCommandCount),e.maximumReadByteLength!==void 0&&t.push(r.readByteLength/e.maximumReadByteLength),e.maximumWriteByteLength!==void 0&&t.push(r.writeByteLength/e.maximumWriteByteLength),Math.max(...t)}function gs(r,e){return vi({maximumInvocationCount:Bt(r.maximumInvocationCount,e),...r.maximumNodeCount===void 0?{}:{maximumNodeCount:Bt(r.maximumNodeCount,e)},...r.maximumCommandCount===void 0?{}:{maximumCommandCount:Bt(r.maximumCommandCount,e)},...r.maximumReadByteLength===void 0?{}:{maximumReadByteLength:Bt(r.maximumReadByteLength,e)},...r.maximumWriteByteLength===void 0?{}:{maximumWriteByteLength:Bt(r.maximumWriteByteLength,e)}})}function Bt(r,e){return Math.max(1,Math.min(Number.MAX_SAFE_INTEGER,Math.round(r*e)))}function vi(r){return Object.freeze({...r})}function Et(r,e){if(!Number.isFinite(r)||r<=0)throw new Error(`GPUCommandGraph budget ${e} must be positive`)}function wi(r){for(let[e,t]of[["maximumInvocationCount",r.maximumInvocationCount],["maximumNodeCount",r.maximumNodeCount],["maximumCommandCount",r.maximumCommandCount],["maximumReadByteLength",r.maximumReadByteLength],["maximumWriteByteLength",r.maximumWriteByteLength]])if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))throw new Error(`GPUCommandGraph budget ${e} must be a positive safe integer`)}function Ti(r,e,t){return Math.max(e,Math.min(t,r))}var Go=class{maxSamples;getNodeGroup;graphs=new Map;encodingGraphs=new WeakMap;constructor(e={}){let t=e.maxSamples??120;if(!Number.isSafeInteger(t)||t<=0)throw new Error("GPUCommandGraphInspector maxSamples must be a positive safe integer");this.maxSamples=t,this.getNodeGroup=e.getNodeGroup}registerGraph(e){this.graphs.set(e.id,{id:e.id,stats:ys(e.stats),capabilities:Object.freeze({...e.capabilities}),...e.preflight?{preflight:xs(e.preflight)}:{},encodingCount:0,timingReadFailureCount:0,cpuSamples:[],gpuSamples:[],counters:new Map,nodes:new Map});let t=this.getGraph(e.id);for(let o of e.preflight?.nodes??[])this.getNode(t,o)}observeGraph(e){this.registerGraph(e);let t=this.getGraph(e.id),o=new WeakMap,n=!0,i=()=>n&&this.graphs.get(e.id)===t;return Object.freeze({graph:e,encode:(a,s)=>{let u=e.encode(a,s);return i()&&this.recordGraphEncoding(t,u),u},recordGPUTimings:async a=>{let s=o.get(a);if(s)return await s;if(i()&&this.encodingGraphs.get(a)===t){let u=this.recordGraphGPUTimings(e.id,t,a);return o.set(a,u),await u}},recordCounters:a=>{i()&&this.recordGraphCounters(t,a)},detach:()=>{n&&(n=!1,this.graphs.get(e.id)===t&&this.graphs.delete(e.id))}})}clear(){this.graphs.clear()}recordEncoding(e,t){let o=this.getGraph(e);this.recordGraphEncoding(o,t)}async readResource(e,t,o){let n=this.getGraph(e);if(!n.encoding?.readResource)throw new Error("No live resource readback is available.");let i=await n.encoding.readResource(t,o);if(this.graphs.get(e)!==n)throw new Error("Graph registration changed during readback.");return i}recordCounters(e,t){this.recordGraphCounters(this.getGraph(e),t)}recordGraphEncoding(e,t){e.encoding=t,this.encodingGraphs.set(t,e);let{stats:o}=t;e.encodingCount++,this.addSample(e.cpuSamples,o.cpuEncodeTimeMilliseconds);for(let n of o.nodes){let i=this.getNode(e,n);this.addSample(i.cpuSamples,n.cpuEncodeTimeMilliseconds)}}recordGraphCounters(e,t){let o=Object.entries(t);for(let[n,i]of o)if(!n||!Number.isFinite(i)||i<0)throw new Error("GPUCommandGraphInspector counters require an ID and a finite, non-negative value");for(let[n,i]of o){let a=e.counters.get(n);a||(a=[],e.counters.set(n,a)),this.addSample(a,i)}}async recordGPUTimings(e,t){let n=this.encodingGraphs.get(t)??this.getGraph(e);return await this.recordGraphGPUTimings(e,n,t)}async recordGraphGPUTimings(e,t,o){if(this.graphs.get(e)!==t)return;let n;try{n=await o.readTimings()}catch{this.graphs.get(e)===t&&t.timingReadFailureCount++;return}if(this.graphs.get(e)===t){n.gpuTimeMilliseconds!==void 0&&this.addSample(t.gpuSamples,n.gpuTimeMilliseconds);for(let i of n.nodes)if(i.gpuTimeMilliseconds!==void 0){let a=this.getNode(t,i);this.addSample(a.gpuSamples,i.gpuTimeMilliseconds)}return n}}getSnapshot(){let e=Array.from(this.graphs.values(),t=>this.getGraphSnapshot(t));return Object.freeze({graphs:Object.freeze(e)})}getGraph(e){let t=this.graphs.get(e);if(!t)throw new Error(`GPUCommandGraphInspector graph "${e}" is not registered`);return t}getNode(e,t){let o=e.nodes.get(t.id);if(o)return t.description!==void 0&&(o.description=t.description),t.resources!==void 0&&(o.resources=Do(t.resources)),o;let n=Do(t.resources),i=this.getNodeGroup?.({graphId:e.id,id:t.id,type:t.type,description:t.description,resources:n}),a={id:t.id,resources:n,...t.description===void 0?{}:{description:t.description},type:t.type,...i===void 0?{}:{group:i},cpuSamples:[],gpuSamples:[]};return e.nodes.set(a.id,a),a}addSample(e,t){e.push(t),e.length>this.maxSamples&&e.splice(0,e.length-this.maxSamples)}getGraphSnapshot(e){let t=[],o=new Set;for(let a of e.stats.nodeOrder){let s=e.nodes.get(a);s&&(t.push(s),o.add(a))}for(let a of e.nodes.values())o.has(a.id)||t.push(a);let n=t.map(a=>Object.freeze({id:a.id,resources:a.resources,...a.description===void 0?{}:{description:a.description},type:a.type,...a.group===void 0?{}:{group:a.group},cpu:br(a.cpuSamples),gpu:br(a.gpuSamples)})),i=Array.from(e.counters,([a,s])=>bs(a,s));return Object.freeze({id:e.id,stats:e.stats,capabilities:e.capabilities,...e.preflight?{preflight:e.preflight}:{},encodingCount:e.encodingCount,timingReadFailureCount:e.timingReadFailureCount,totals:Object.freeze({cpu:br(e.cpuSamples),gpu:br(e.gpuSamples)}),counters:Object.freeze(i),nodes:Object.freeze(n)})}};function ys(r){return Object.freeze({...r,nodeOrder:Object.freeze([...r.nodeOrder])})}function xs(r){return Object.freeze({...r,nodes:Object.freeze(r.nodes.map(e=>Object.freeze({...e,resources:Do(e.resources)})))})}function br(r){if(r.length===0)return Object.freeze({sampleCount:0});let e=[...r].sort((t,o)=>t-o);return Object.freeze({sampleCount:r.length,latestMilliseconds:r[r.length-1],p50Milliseconds:wr(e,.5),p95Milliseconds:wr(e,.95)})}function bs(r,e){let t=[...e].sort((o,n)=>o-n);return Object.freeze({id:r,sampleCount:e.length,latestValue:e[e.length-1],p50Value:wr(t,.5),p95Value:wr(t,.95)})}function wr(r,e){return r[Math.ceil(e*r.length)-1]}function Do(r){return r&&Object.freeze(r.map(e=>Object.freeze({...e})))}return Ii(Lt);})();
202
+ }`}fe();var gr=class{props;id;constructor(e){if(this.props=e,this.id=e.id??"gpu-predicate-conjunction",e.inputs.length<2)throw new Error(`${this.id} requires at least two predicates`);let t=e.output.arena;if(e.inputs.some(o=>o.arena!==t))throw new Error(`${this.id} predicates must share one GPUValueArena`)}getCommandNodes(e){let{inputs:t,output:o}=this.props;if(o.arena.graph!==e)throw new Error(`${this.id} predicates must belong to target graph`);let n=o.arena.buffer,i=t.map(s=>`(${J(s)} != 0u)`).join(" && "),a=`${Y(0,0)}
203
+ @compute @workgroup_size(1)fn main(){${Pe(o,`select(0u,1u,${i})`)}}`;return[M({id:this.id,workload:{operation:"GPUPredicateConjunction",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:t.length*4,writeByteLength:4},resources:[{buffer:n,usage:"storage-write"}],compile:({device:s})=>{let u=new I(s,{id:this.id,source:a,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:c,getBuffer:d})=>{let m={gpuValues:d(n)};u.dispatch(c,{bindings:m,x:1,y:1,z:1})},destroy:()=>u.destroy()}}})]}};var et=class extends q{type="conditional";predicate;lowering;constructor(e){let t=Array.isArray(e.body)?e.body:[e.body];super({id:e.id??"gpu-conditional-operation",operations:t,metadata:e.metadata}),this.predicate=Object.freeze({...e.predicate}),this.lowering=e.lowering??"auto"}},tt=class extends q{type="loop";predicate;maximumIterations;minimumIterations;lowering;constructor(e){let t=Array.isArray(e.body)?e.body:[e.body];if(super({id:e.id??"gpu-loop-operation",operations:t,metadata:e.metadata}),!Number.isSafeInteger(e.maximumIterations)||e.maximumIterations<1)throw new Error(`${this.id} maximumIterations must be a positive safe integer`);let o=e.minimumIterations??0;if(!Number.isSafeInteger(o)||o<0||o>e.maximumIterations)throw new Error(`${this.id} minimumIterations must be between zero and maximumIterations`);this.predicate=e.predicate?Object.freeze({...e.predicate}):void 0,this.maximumIterations=e.maximumIterations,this.minimumIterations=o,this.lowering=e.lowering??"auto"}};var rt=class{lowerers=new Map;register(e,t){if(!e)throw new Error("GPU operation lowering type is required");if(this.lowerers.has(e))throw new Error(`GPU operation lowering for "${e}" is already registered`);return this.lowerers.set(e,t),this}get(e){return this.lowerers.get(e)}};function yr(r,e={}){let t=[],o=new Set(r.scalars.map(i=>i.id));for(let i of r.vectors)i.external&&!e.vectors?.[i.id]&&t.push({level:"error",code:"missing-external-vector",valueId:i.id,message:`External vector "${i.id}" has no WebGPU binding`});let n=i=>{let a="id"in i&&typeof i.id=="string"?i.id:void 0;if(i instanceof et||i instanceof tt){let s=i.predicate;s?.source==="gpu"&&(s.value.format!=="uint32"&&t.push({level:"error",code:"invalid-predicate-format",operationId:a,valueId:s.value.id,message:`GPU predicate "${s.id}" must use uint32 state`}),o.has(s.value.id)||t.push({level:"error",code:"missing-predicate-scalar",operationId:a,valueId:s.value.id,message:`GPU predicate "${s.id}" references undeclared scalar "${s.value.id}"`}))}if(i instanceof q)for(let s of i.operations)n(s)};for(let i of r.operations)n(i);return Object.freeze({valid:!t.some(i=>i.level==="error"),issues:Object.freeze(t.map(i=>Object.freeze({...i})))})}var xr=class{device;capabilities;lowerings=new rt;constructor(e){this.device=e,this.capabilities=Object.freeze({backend:"webgpu",gpuConditionals:!0,nativeLoops:!1,childGraphs:!1}),this.registerCoreLowerings()}compile(e,t={}){let o=yr(e,t);if(!o.valid)throw new Error(`GPUGraph "${e.id}" validation failed: ${o.issues.filter(c=>c.level==="error").map(c=>c.message).join("; ")}`);let n=new tr(this.device,{id:`${e.id}-commands`}),i=new Map;for(let c of e.scalars)i.set(c.id,Bo(n,c.id,c.format));let a=new Map;for(let c of e.vectors){let d;if(c.external){let m=t.vectors[c.id],f="data"in m?m:{format:c.format,length:c.length,data:"buffer"in m?[m]:m};if(d=n.importGPUVector(c.id,f),d.format!==c.format||d.length!==c.length)throw new Error(`${c.id} binding format and length must match its logical vector`);if(c.chunkLengths&&(c.chunkLengths.length!==d.data.length||c.chunkLengths.some((p,h)=>p!==d.data[h].length)))throw new Error(`${c.id} binding must preserve its declared chunk topology`)}else{let m=c.chunkLengths??As(c.length,this.device),f=m.map((p,h)=>Me(n,m.length===1?c.id:`${c.id}-chunk-${h}`,c.format,p));d=new B({id:c.id,name:c.id,format:c.format,length:c.length,valueLength:c.length,stride:1,byteStride:4,rowByteLength:4,data:f})}a.set(c.id,d)}let s=new Map;for(let c of e.textures){let d=c.external?n.importTexture(c,t.textures?.[c.id]):n.createTransientTexture(c);s.set(c.id,d)}let u={path:[],nodes:[],decisions:[],predicates:[],scalars:i,vectors:a,textures:s,textureValues:e.textures,predicateConjunctions:new Map,commandNodeIds:new Set};for(let c of e.operations)this.lower(n,c,u);return Object.freeze({program:e,graph:n,scalars:i,vectors:a,textures:s,validation:o,lowering:Object.freeze({operations:e.operationTree,nodes:Object.freeze(u.nodes.map(c=>Object.freeze({...c,operationPath:Object.freeze([...c.operationPath])}))),decisions:Object.freeze(u.decisions.map(c=>Object.freeze({...c})))})})}registerCoreLowerings(){this.lowerings.register("scalar-literal",(e,t)=>{let o=new Ze({id:e.id,output:t.resolveScalar(e.props.output),value:e.props.value});this.emitProducer(t.graph,o,[[1,1,1]]),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-scalar-literal",reason:"host-known literal lowers to one compute command node"})}),this.lowerings.register("scalar-operation",(e,t)=>{let o=new ar({id:e.id,operation:e.operation,left:t.resolveScalar(e.left),right:e.right?t.resolveScalar(e.right):void 0,output:t.resolveScalar(e.output)});this.emitProducer(t.graph,o,[[1,1,1]]),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-scalar-kernel",reason:"scalar operation lowers to one compute command node"})}),this.lowerings.register("vector-madd",(e,t)=>{let o=e.props,n=new cr({id:e.id,input:t.resolveVector(o.input),scale:t.resolveScalar(o.scale),addend:t.resolveVector(o.addend),output:t.resolveVector(o.output)});this.emitProducer(t.graph,n),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-vector-madd",reason:"dense float32 MADD lowers through explicit command nodes"})}),this.lowerings.register("dot-product",(e,t)=>{let o=e.props,n=new fr({id:e.id,left:t.resolveVector(o.left),right:t.resolveVector(o.right),output:t.resolveScalar(o.output)});this.emitProducer(t.graph,n),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-hierarchical-dot",reason:"chunk dot products use bounded hierarchical reductions into the scalar arena"})}),this.lowerings.register("spmv",(e,t)=>{let o=e.props,n=o.matrix,i=new hr({id:e.id,rowOffsets:t.resolveVector(n.rowOffsets),columnIndices:t.resolveVector(n.columnIndices),values:t.resolveVector(n.values),vector:t.resolveVector(o.vector),output:t.resolveVector(o.output),columns:n.columns,statistics:n.statistics,strategy:o.strategy}),a=i.getStrategy(t.graph);this.emitProducer(t.graph,i),t.recordDecision({operationId:e.id,operationType:e.type,lowering:`webgpu-spmv:${a.id}`,reason:a.reason})}),this.lowerings.register("conditional",(e,t)=>{t.recordDecision({operationId:e.id,operationType:e.type,lowering:"gpu-indirect-gate",reason:"WebGPU realizes runtime predicates with zero/nonzero indirect dispatch"});for(let o of e.operations)t.lowerConditional(e.predicate,o)}),this.lowerings.register("loop",(e,t)=>{if(!e.predicate||e.lowering==="unroll"){t.recordDecision({operationId:e.id,operationType:e.type,lowering:"bounded-unroll",reason:e.predicate?"explicit unroll preference":"loop has no runtime predicate"});for(let o=0;o<e.maximumIterations;o++)for(let n of e.operations)t.lower(n);return}t.recordDecision({operationId:e.id,operationType:e.type,lowering:"gpu-gated-bounded-sequence",reason:"WebGPU has indirect dispatch but no native graph loop"});for(let o=0;o<e.maximumIterations;o++){let n=o>=e.minimumIterations;for(let i of e.operations)n?t.lowerConditional(e.predicate,i):t.lower(i)}})}lower(e,t,o){let n="id"in t&&typeof t.id=="string"?t.id:t.constructor?.name??"command-node-producer";o.path.push(n);try{if(t instanceof q&&t.type==="composite"){o.decisions.push({operationId:t.id,operationType:t.type,lowering:"flatten",reason:"WebGPU has no executable child-graph primitive"});for(let i of t.operations)this.lower(e,i,o);return}if(bo(t)){let i=this.lowerings.get(t.type);if(i){let a=()=>i(t,{graph:e,capabilities:this.capabilities,lower:s=>this.lower(e,s,o),lowerConditional:(s,u)=>{o.predicates.push(s);try{this.lower(e,u,o)}finally{o.predicates.pop()}},resolveScalar:s=>this.resolveScalar(s,o),resolveVector:s=>this.resolveVector(s,o),resolveTexture:s=>this.resolveTexture(s,o),resolveTextureView:s=>{let u=s instanceof de?s.texture:s,c=s instanceof de?s.props:{};return e.createTextureView(this.resolveTexture(u,o),c)},recordDecision:s=>o.decisions.push(s)});t instanceof et||t instanceof tt?a():this.withNodeDecoration(e,o,a);return}}if("getNodes"in t||li(t)){o.decisions.push({operationId:n,operationType:"command-node-producer",lowering:"explicit-command-nodes",reason:"execution primitive constructs explicit command nodes"}),this.withNodeDecoration(e,o,()=>e.add(t));return}throw new Error(`GPUGraph operation "${n}" has no WebGPU lowering`)}finally{o.path.pop()}}emitProducer(e,t,o){let n=t.getCommandNodes(e);if(!o){_e(e,n);return}if(n.length!==o.length)throw new Error(`lowering produced ${n.length} command nodes but declared ${o.length} dispatches`);let i=n.map((a,s)=>this.attachDispatch(a,o[s]));_e(e,i)}attachDispatch(e,t){if(e.type!=="compute")throw new Error(`dispatch geometry can only be attached to compute command nodes; got ${e.type} node "${e.id}"`);return k(e,t)}withNodeDecoration(e,t,o){return e.withComputeLowering(n=>this.decorateComputeNode(e,n,t),()=>e.withOtherLowering(n=>{if(t.predicates.length)throw new Error(`GPU predicates do not support ${n.type} node "${n.id}"`);let i=this.makeCommandNodeIdUnique(n,t);return t.nodes.push({nodeId:i.id,nodeType:i.type,operationPath:[...t.path]}),i},o))}decorateComputeNode(e,t,o){if(t=this.makeCommandNodeIdUnique(t,o),o.path.length&&o.nodes.push({nodeId:t.id,nodeType:"compute",operationPath:[...o.path]}),!o.predicates.length)return t;if(t.condition)throw new Error(`compute node "${t.id}" already has condition`);let n=rr(t);if(!n)throw new Error(`compute node "${t.id}" under runtime predicate must declare exact dispatch geometry`);let i;if(o.predicates.length===1)i=o.scalars.get(o.predicates[0].value.id);else{let u=o.predicates.map(f=>f.value.id).join("&&"),c=o.predicateConjunctions.get(u);c||(c=Bo(e,`predicate-and-${o.predicateConjunctions.size}`,"uint32"),o.predicateConjunctions.set(u,c));let d=o.predicates.map(f=>o.scalars.get(f.value.id)),m=new gr({id:`${t.id}-predicate-and`,inputs:d,output:c}).getCommandNodes(e).map(f=>this.attachDispatch(f,[1,1,1]));e.withoutComputeLowering(()=>_e(e,m)),i=c}if(!i)throw new Error(`runtime predicate for "${t.id}" could not be resolved`);let a=new Pt(e,{id:`${t.id}-predicate`,active:i,workgroups:n}),s=a.getUpdateCommandNodes(e,`${t.id}-predicate-update`).map(u=>this.attachDispatch(u,[1,1,1]));return e.withoutComputeLowering(()=>_e(e,s)),{...t,condition:a.condition}}makeCommandNodeIdUnique(e,t){if(!t.commandNodeIds.has(e.id))return t.commandNodeIds.add(e.id),e;let o=1,n=`${e.id}-iteration-${o}`;for(;t.commandNodeIds.has(n);)o++,n=`${e.id}-iteration-${o}`;return t.commandNodeIds.add(n),{...e,id:n}}resolveTexture(e,t){if(!t.textureValues.includes(e))throw new Error(`Undeclared program texture "${e.id}"`);return t.textures.get(e.id)}resolveScalar(e,t){let o=t.scalars.get(e.id);if(!o||o.format!==e.format)throw new Error(`GPUGraph scalar "${e.id}" is not part of compilation`);return o}resolveVector(e,t){let o=t.vectors.get(e.id);if(!o||o.format!==e.format||o.length!==e.length)throw new Error(`GPUGraph vector "${e.id}" is not part of compilation`);return o}};function As(r,e){let t=Math.floor(e.limits.maxStorageBufferBindingSize/4);if(t<1||r<=t)return[r];let o=[];for(let n=0;n<r;n+=t)o.push(Math.min(t,r-n));return o}function Ei(r){let e=r.lowering.decisions.map(t=>`${t.operationId}: ${t.lowering} \u2014 ${t.reason}`);return Object.freeze({programId:r.program.id,semanticOperationCount:Li(r.program.operationTree),loweredNodeCount:r.lowering.nodes.length,loweringDecisionCount:r.lowering.decisions.length,scalarCount:r.program.scalars.length,vectorCount:r.program.vectors.length,externalVectorCount:r.program.vectors.filter(t=>t.external).length,cpuReadbackCount:0,backend:"webgpu",decisions:Object.freeze(e)})}function Li(r){return r.reduce((e,t)=>e+1+Li(t.children??[]),0)}var Do=class{adapter;minimumSampleCount;explorationEnabled;calibrations=new Map;constructor(e){if(!Number.isSafeInteger(e.minimumSampleCount??1)||(e.minimumSampleCount??1)<=0)throw new Error("GPUCommandGraph autotuner minimumSampleCount must be a positive safe integer");if(this.adapter=Is(e.adapter),this.minimumSampleCount=e.minimumSampleCount??1,this.explorationEnabled=e.explorationEnabled??!0,e.profile?.adapter.key===this.adapter.key&&e.profile.version===1)for(let t of e.profile.calibrations)this.importCalibration(t)}selectKernel(e){br(e.operation,"operation"),Gi(e.workloadSize);let t=e.candidates.filter(s=>s.supported!==!1);if(t.length===0)throw new Error(`GPUCommandGraph autotuner operation "${e.operation}" has no supported variants`);for(let s of t)br(s.id,"variant");let o=Ai(e.workloadSize),n=t.map(s=>{let u=this.findNearestCalibration(e.operation,s.id,o);return{candidate:s,calibration:u,sampleCount:u?.workloadBucket===o?u.sampleCount:0,estimatedDurationMilliseconds:u?$s(u,e.workloadSize):void 0}});if(this.explorationEnabled){let s=n.find(u=>u.sampleCount<this.minimumSampleCount);if(s)return Object.freeze({operation:e.operation,variant:s.candidate.id,workloadSize:e.workloadSize,workloadBucket:o,reason:"exploration",sampleCount:s.sampleCount,...s.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:s.estimatedDurationMilliseconds}})}let i=n.filter(s=>s.estimatedDurationMilliseconds!==void 0).sort((s,u)=>(s.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY)-(u.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY))[0],a=i??n[0];return Object.freeze({operation:e.operation,variant:a.candidate.id,workloadSize:e.workloadSize,workloadBucket:o,reason:i?"calibrated":"fallback",sampleCount:a.calibration?.sampleCount??0,...a.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:a.estimatedDurationMilliseconds}})}observeKernel(e){if(br(e.operation,"operation"),br(e.variant,"variant"),Gi(e.workloadSize),!Number.isFinite(e.durationMilliseconds)||e.durationMilliseconds<0)throw new Error("GPUCommandGraph autotuner durationMilliseconds must be nonnegative");let t=Ai(e.workloadSize),o=Lo(e.operation,e.variant,t),n=this.calibrations.get(o)??{operation:e.operation,variant:e.variant,workloadBucket:t,sampleCount:0,meanWorkloadSize:0,meanDurationMilliseconds:0,durationSquaredDifferenceSum:0};n.sampleCount++,n.meanWorkloadSize+=(e.workloadSize-n.meanWorkloadSize)/n.sampleCount;let i=e.durationMilliseconds-n.meanDurationMilliseconds;return n.meanDurationMilliseconds+=i/n.sampleCount,n.durationSquaredDifferenceSum+=i*(e.durationMilliseconds-n.meanDurationMilliseconds),this.calibrations.set(o,n),Di(n)}observeTimingReport(e,t){let o=new Map(t.nodes.map(i=>[i.id,i])),n=0;for(let i of e.nodes){let a=o.get(i.id);i.gpuTimeMilliseconds===void 0||!a?.operation||!a.variant||(this.observeKernel({operation:a.operation,variant:a.variant,workloadSize:Math.max(a.maximumInvocationCount,1),durationMilliseconds:i.gpuTimeMilliseconds}),n++)}return n}exportProfile(){let e=[...this.calibrations.values()].sort((t,o)=>t.operation.localeCompare(o.operation)||t.variant.localeCompare(o.variant)||t.workloadBucket-o.workloadBucket).map(Di);return Object.freeze({version:1,adapter:this.adapter,calibrations:Object.freeze(e)})}reset(){this.calibrations.clear()}importCalibration(e){!e.operation||!e.variant||!Number.isSafeInteger(e.workloadBucket)||!Number.isSafeInteger(e.sampleCount)||e.sampleCount<=0||!Number.isFinite(e.meanWorkloadSize)||e.meanWorkloadSize<=0||!Number.isFinite(e.meanDurationMilliseconds)||e.meanDurationMilliseconds<0||this.calibrations.set(Lo(e.operation,e.variant,e.workloadBucket),{operation:e.operation,variant:e.variant,workloadBucket:e.workloadBucket,sampleCount:e.sampleCount,meanWorkloadSize:e.meanWorkloadSize,meanDurationMilliseconds:e.meanDurationMilliseconds,durationSquaredDifferenceSum:e.sampleCount>1?e.durationStandardDeviationMilliseconds**2*(e.sampleCount-1):0})}findNearestCalibration(e,t,o){let n=this.calibrations.get(Lo(e,t,o));if(n)return n;let i;for(let a of this.calibrations.values())a.operation!==e||a.variant!==t||(!i||Math.abs(a.workloadBucket-o)<Math.abs(i.workloadBucket-o))&&(i=a);return i}};function Gs(r){let e=[...r.features].sort(),t={type:r.info.type,vendor:r.info.vendor,renderer:r.info.renderer,version:r.info.version,gpu:r.info.gpu,gpuType:r.info.gpuType,...r.info.gpuArchitecture?{gpuArchitecture:r.info.gpuArchitecture}:{},...r.info.gpuBackend?{gpuBackend:r.info.gpuBackend}:{},...r.info.featureLevel?{featureLevel:r.info.featureLevel}:{},features:Object.freeze(e),...r.info.subgroupMinSize===void 0?{}:{subgroupMinSize:r.info.subgroupMinSize},...r.info.subgroupMaxSize===void 0?{}:{subgroupMaxSize:r.info.subgroupMaxSize},maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension};return Object.freeze({key:JSON.stringify(t),...t})}function Is(r){return Object.freeze({...r,features:Object.freeze([...r.features])})}function Di(r){return Object.freeze({operation:r.operation,variant:r.variant,workloadBucket:r.workloadBucket,sampleCount:r.sampleCount,meanWorkloadSize:r.meanWorkloadSize,meanDurationMilliseconds:r.meanDurationMilliseconds,durationStandardDeviationMilliseconds:r.sampleCount>1?Math.sqrt(r.durationSquaredDifferenceSum/(r.sampleCount-1)):0})}function $s(r,e){return r.meanDurationMilliseconds*(e/Math.max(r.meanWorkloadSize,1))}function Ai(r){return Math.floor(Math.log2(Math.max(r,1)))}function Lo(r,e,t){return`${r}\0${e}\0${t}`}function br(r,e){if(!r)throw new Error(`GPUCommandGraph autotuner ${e} is required`)}function Gi(r){if(!Number.isSafeInteger(r)||r<=0)throw new Error("GPUCommandGraph autotuner workloadSize must be a positive safe integer")}var Us={interactive:4,normal:8,background:16},Ao=class{targetStepMilliseconds;latencyPriority;minimumScale;maximumScale;responsiveness;maximumAdjustmentFactor;initialBudget;currentBudget;currentScale=1;currentSampleCount=0;constructor(e){Ii(e.initialBudget);let t=e.latencyPriority??"normal",o=e.targetStepMilliseconds??Us[t];Et(o,"targetStepMilliseconds");let n=e.minimumScale??.125,i=e.maximumScale??4,a=e.responsiveness??.25,s=e.maximumAdjustmentFactor??2;if(Et(n,"minimumScale"),Et(i,"maximumScale"),Et(s,"maximumAdjustmentFactor"),n>1||i<1)throw new Error("GPUCommandGraph budget scale range must contain the initial scale 1");if(!Number.isFinite(a)||a<=0||a>1)throw new Error("GPUCommandGraph budget responsiveness must be in the interval (0, 1]");if(s<1)throw new Error("GPUCommandGraph budget maximumAdjustmentFactor must be at least 1");this.initialBudget=Ui(e.initialBudget),this.currentBudget=this.initialBudget,this.latencyPriority=t,this.targetStepMilliseconds=o,this.minimumScale=n,this.maximumScale=i,this.responsiveness=a,this.maximumAdjustmentFactor=s}get budget(){return this.currentBudget}get sampleCount(){return this.currentSampleCount}reset(){this.currentBudget=this.initialBudget,this.currentScale=1,this.currentSampleCount=0}observeStep(e,t,o=this.currentBudget){Et(t,"durationMilliseconds"),Ii(o);let n=_s(e,o);if(n>0){let i=this.targetStepMilliseconds*Math.min(n,1)/t,s=1+($i(i,1/this.maximumAdjustmentFactor,this.maximumAdjustmentFactor)-1)*this.responsiveness;this.currentScale=$i(this.currentScale*s,this.minimumScale,this.maximumScale),this.currentBudget=Rs(this.initialBudget,this.currentScale)}return this.currentSampleCount++,Object.freeze({sampleCount:this.currentSampleCount,durationMilliseconds:t,targetStepMilliseconds:this.targetStepMilliseconds,latencyPriority:this.latencyPriority,saturation:n,scale:this.currentScale,budget:this.currentBudget})}};function _s(r,e){let t=[r.maximumInvocationCount/e.maximumInvocationCount];return e.maximumNodeCount!==void 0&&t.push(r.nodeCount/e.maximumNodeCount),e.maximumCommandCount!==void 0&&t.push(r.commandCount/e.maximumCommandCount),e.maximumReadByteLength!==void 0&&t.push(r.readByteLength/e.maximumReadByteLength),e.maximumWriteByteLength!==void 0&&t.push(r.writeByteLength/e.maximumWriteByteLength),Math.max(...t)}function Rs(r,e){return Ui({maximumInvocationCount:Bt(r.maximumInvocationCount,e),...r.maximumNodeCount===void 0?{}:{maximumNodeCount:Bt(r.maximumNodeCount,e)},...r.maximumCommandCount===void 0?{}:{maximumCommandCount:Bt(r.maximumCommandCount,e)},...r.maximumReadByteLength===void 0?{}:{maximumReadByteLength:Bt(r.maximumReadByteLength,e)},...r.maximumWriteByteLength===void 0?{}:{maximumWriteByteLength:Bt(r.maximumWriteByteLength,e)}})}function Bt(r,e){return Math.max(1,Math.min(Number.MAX_SAFE_INTEGER,Math.round(r*e)))}function Ui(r){return Object.freeze({...r})}function Et(r,e){if(!Number.isFinite(r)||r<=0)throw new Error(`GPUCommandGraph budget ${e} must be positive`)}function Ii(r){for(let[e,t]of[["maximumInvocationCount",r.maximumInvocationCount],["maximumNodeCount",r.maximumNodeCount],["maximumCommandCount",r.maximumCommandCount],["maximumReadByteLength",r.maximumReadByteLength],["maximumWriteByteLength",r.maximumWriteByteLength]])if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))throw new Error(`GPUCommandGraph budget ${e} must be a positive safe integer`)}function $i(r,e,t){return Math.max(e,Math.min(t,r))}var Go=class{maxSamples;getNodeGroup;graphs=new Map;encodingGraphs=new WeakMap;constructor(e={}){let t=e.maxSamples??120;if(!Number.isSafeInteger(t)||t<=0)throw new Error("GPUCommandGraphInspector maxSamples must be a positive safe integer");this.maxSamples=t,this.getNodeGroup=e.getNodeGroup}registerGraph(e){this.graphs.set(e.id,{id:e.id,stats:Ms(e.stats),capabilities:Object.freeze({...e.capabilities}),...e.preflight?{preflight:ks(e.preflight)}:{},encodingCount:0,timingReadFailureCount:0,cpuSamples:[],gpuSamples:[],counters:new Map,nodes:new Map});let t=this.getGraph(e.id);for(let o of e.preflight?.nodes??[])this.getNode(t,o)}observeGraph(e){this.registerGraph(e);let t=this.getGraph(e.id),o=new WeakMap,n=!0,i=()=>n&&this.graphs.get(e.id)===t;return Object.freeze({graph:e,encode:(a,s)=>{let u=e.encode(a,s);return i()&&this.recordGraphEncoding(t,u),u},recordGPUTimings:async a=>{let s=o.get(a);if(s)return await s;if(i()&&this.encodingGraphs.get(a)===t){let u=this.recordGraphGPUTimings(e.id,t,a);return o.set(a,u),await u}},recordCounters:a=>{i()&&this.recordGraphCounters(t,a)},detach:()=>{n&&(n=!1,this.graphs.get(e.id)===t&&this.graphs.delete(e.id))}})}clear(){this.graphs.clear()}recordEncoding(e,t){let o=this.getGraph(e);this.recordGraphEncoding(o,t)}async readResource(e,t,o){let n=this.getGraph(e);if(!n.encoding?.readResource)throw new Error("No live resource readback is available.");let i=await n.encoding.readResource(t,o);if(this.graphs.get(e)!==n)throw new Error("Graph registration changed during readback.");return i}recordCounters(e,t){this.recordGraphCounters(this.getGraph(e),t)}recordGraphEncoding(e,t){e.encoding=t,this.encodingGraphs.set(t,e);let{stats:o}=t;e.encodingCount++,this.addSample(e.cpuSamples,o.cpuEncodeTimeMilliseconds);for(let n of o.nodes){let i=this.getNode(e,n);this.addSample(i.cpuSamples,n.cpuEncodeTimeMilliseconds)}}recordGraphCounters(e,t){let o=Object.entries(t);for(let[n,i]of o)if(!n||!Number.isFinite(i)||i<0)throw new Error("GPUCommandGraphInspector counters require an ID and a finite, non-negative value");for(let[n,i]of o){let a=e.counters.get(n);a||(a=[],e.counters.set(n,a)),this.addSample(a,i)}}async recordGPUTimings(e,t){let n=this.encodingGraphs.get(t)??this.getGraph(e);return await this.recordGraphGPUTimings(e,n,t)}async recordGraphGPUTimings(e,t,o){if(this.graphs.get(e)!==t)return;let n;try{n=await o.readTimings()}catch{this.graphs.get(e)===t&&t.timingReadFailureCount++;return}if(this.graphs.get(e)===t){n.gpuTimeMilliseconds!==void 0&&this.addSample(t.gpuSamples,n.gpuTimeMilliseconds);for(let i of n.nodes)if(i.gpuTimeMilliseconds!==void 0){let a=this.getNode(t,i);this.addSample(a.gpuSamples,i.gpuTimeMilliseconds)}return n}}getSnapshot(){let e=Array.from(this.graphs.values(),t=>this.getGraphSnapshot(t));return Object.freeze({graphs:Object.freeze(e)})}getGraph(e){let t=this.graphs.get(e);if(!t)throw new Error(`GPUCommandGraphInspector graph "${e}" is not registered`);return t}getNode(e,t){let o=e.nodes.get(t.id);if(o)return t.description!==void 0&&(o.description=t.description),t.resources!==void 0&&(o.resources=Io(t.resources)),o;let n=Io(t.resources),i=this.getNodeGroup?.({graphId:e.id,id:t.id,type:t.type,description:t.description,resources:n}),a={id:t.id,resources:n,...t.description===void 0?{}:{description:t.description},type:t.type,...i===void 0?{}:{group:i},cpuSamples:[],gpuSamples:[]};return e.nodes.set(a.id,a),a}addSample(e,t){e.push(t),e.length>this.maxSamples&&e.splice(0,e.length-this.maxSamples)}getGraphSnapshot(e){let t=[],o=new Set;for(let a of e.stats.nodeOrder){let s=e.nodes.get(a);s&&(t.push(s),o.add(a))}for(let a of e.nodes.values())o.has(a.id)||t.push(a);let n=t.map(a=>Object.freeze({id:a.id,resources:a.resources,...a.description===void 0?{}:{description:a.description},type:a.type,...a.group===void 0?{}:{group:a.group},cpu:wr(a.cpuSamples),gpu:wr(a.gpuSamples)})),i=Array.from(e.counters,([a,s])=>Os(a,s));return Object.freeze({id:e.id,stats:e.stats,capabilities:e.capabilities,...e.preflight?{preflight:e.preflight}:{},encodingCount:e.encodingCount,timingReadFailureCount:e.timingReadFailureCount,totals:Object.freeze({cpu:wr(e.cpuSamples),gpu:wr(e.gpuSamples)}),counters:Object.freeze(i),nodes:Object.freeze(n)})}};function Ms(r){return Object.freeze({...r,nodeOrder:Object.freeze([...r.nodeOrder])})}function ks(r){return Object.freeze({...r,nodes:Object.freeze(r.nodes.map(e=>Object.freeze({...e,resources:Io(e.resources)})))})}function wr(r){if(r.length===0)return Object.freeze({sampleCount:0});let e=[...r].sort((t,o)=>t-o);return Object.freeze({sampleCount:r.length,latestMilliseconds:r[r.length-1],p50Milliseconds:Tr(e,.5),p95Milliseconds:Tr(e,.95)})}function Os(r,e){let t=[...e].sort((o,n)=>o-n);return Object.freeze({id:r,sampleCount:e.length,latestValue:e[e.length-1],p50Value:Tr(t,.5),p95Value:Tr(t,.95)})}function Tr(r,e){return r[Math.ceil(e*r.length)-1]}function Io(r){return r&&Object.freeze(r.map(e=>Object.freeze({...e})))}return zi(Lt);})();
204
204
  return __exports__;
205
205
  });