@luma.gl/graph 10.0.0-beta.2 → 10.0.0-beta.4

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 (317) hide show
  1. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.cjs +22 -9
  2. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.d.ts +11 -2
  3. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.d.ts.map +1 -1
  4. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.js +27 -10
  5. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.js.map +1 -1
  6. package/dist/arrow/gpu/arrow-gpu-analytics-readback.cjs +24 -13
  7. package/dist/arrow/gpu/arrow-gpu-analytics-readback.d.ts +9 -1
  8. package/dist/arrow/gpu/arrow-gpu-analytics-readback.d.ts.map +1 -1
  9. package/dist/arrow/gpu/arrow-gpu-analytics-readback.js +41 -14
  10. package/dist/arrow/gpu/arrow-gpu-analytics-readback.js.map +1 -1
  11. package/dist/arrow/gpu/arrow-gpu-table-conversion.cjs +82 -23
  12. package/dist/arrow/gpu/arrow-gpu-table-conversion.d.ts +16 -1
  13. package/dist/arrow/gpu/arrow-gpu-table-conversion.d.ts.map +1 -1
  14. package/dist/arrow/gpu/arrow-gpu-table-conversion.js +98 -24
  15. package/dist/arrow/gpu/arrow-gpu-table-conversion.js.map +1 -1
  16. package/dist/arrow/gpu/arrow-gpu-vector-conversion.cjs +7 -0
  17. package/dist/arrow/gpu/arrow-gpu-vector-conversion.d.ts +2 -0
  18. package/dist/arrow/gpu/arrow-gpu-vector-conversion.d.ts.map +1 -1
  19. package/dist/arrow/gpu/arrow-gpu-vector-conversion.js +14 -0
  20. package/dist/arrow/gpu/arrow-gpu-vector-conversion.js.map +1 -1
  21. package/dist/arrow/index.cjs +2 -0
  22. package/dist/arrow/index.cjs.map +3 -3
  23. package/dist/arrow/index.d.ts +1 -1
  24. package/dist/arrow/index.d.ts.map +1 -1
  25. package/dist/arrow/index.js +1 -1
  26. package/dist/arrow/index.js.map +1 -1
  27. package/dist/arrow/vectors/arrow-temporal-gpu-vector.cjs +1 -2
  28. package/dist/arrow/vectors/arrow-temporal-gpu-vector.js +2 -2
  29. package/dist/arrow/vectors/arrow-temporal-gpu-vector.js.map +1 -1
  30. package/dist/dist.dev.js +62 -27
  31. package/dist/dist.min.js +48 -47
  32. package/dist/gpu-core/gpu-bvh-bounds.cjs +63 -0
  33. package/dist/gpu-core/gpu-bvh-bounds.d.ts +32 -0
  34. package/dist/gpu-core/gpu-bvh-bounds.d.ts.map +1 -0
  35. package/dist/gpu-core/gpu-bvh-bounds.js +56 -0
  36. package/dist/gpu-core/gpu-bvh-bounds.js.map +1 -0
  37. package/dist/gpu-core/gpu-command-graph-budget-controller.cjs +10 -2
  38. package/dist/gpu-core/gpu-command-graph-budget-controller.d.ts +4 -0
  39. package/dist/gpu-core/gpu-command-graph-budget-controller.d.ts.map +1 -1
  40. package/dist/gpu-core/gpu-command-graph-budget-controller.js +10 -2
  41. package/dist/gpu-core/gpu-command-graph-budget-controller.js.map +1 -1
  42. package/dist/gpu-core/gpu-command-graph-submission-pacer.cjs +92 -0
  43. package/dist/gpu-core/gpu-command-graph-submission-pacer.d.ts +41 -0
  44. package/dist/gpu-core/gpu-command-graph-submission-pacer.d.ts.map +1 -0
  45. package/dist/gpu-core/gpu-command-graph-submission-pacer.js +85 -0
  46. package/dist/gpu-core/gpu-command-graph-submission-pacer.js.map +1 -0
  47. package/dist/gpu-core/gpu-group-aggregation.cjs +45 -21
  48. package/dist/gpu-core/gpu-group-aggregation.d.ts +4 -0
  49. package/dist/gpu-core/gpu-group-aggregation.d.ts.map +1 -1
  50. package/dist/gpu-core/gpu-group-aggregation.js +58 -24
  51. package/dist/gpu-core/gpu-group-aggregation.js.map +1 -1
  52. package/dist/gpu-core/index.cjs +6 -0
  53. package/dist/gpu-core/index.cjs.map +3 -3
  54. package/dist/gpu-core/index.d.ts +4 -0
  55. package/dist/gpu-core/index.d.ts.map +1 -1
  56. package/dist/gpu-core/index.js +2 -0
  57. package/dist/gpu-core/index.js.map +1 -1
  58. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.cjs +6 -6
  59. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.d.ts +1 -1
  60. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.d.ts.map +1 -1
  61. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.js +6 -6
  62. package/dist/gpu-dataframe/gpu-analytics-compiler-utils.js.map +1 -1
  63. package/dist/gpu-dataframe/gpu-data-frame-query.cjs +55 -14
  64. package/dist/gpu-dataframe/gpu-data-frame-query.d.ts +13 -2
  65. package/dist/gpu-dataframe/gpu-data-frame-query.d.ts.map +1 -1
  66. package/dist/gpu-dataframe/gpu-data-frame-query.js +58 -17
  67. package/dist/gpu-dataframe/gpu-data-frame-query.js.map +1 -1
  68. package/dist/gpu-dataframe/gpu-data-frame.cjs +1 -3
  69. package/dist/gpu-dataframe/gpu-data-frame.d.ts +10 -0
  70. package/dist/gpu-dataframe/gpu-data-frame.d.ts.map +1 -1
  71. package/dist/gpu-dataframe/gpu-data-frame.js +1 -3
  72. package/dist/gpu-dataframe/gpu-data-frame.js.map +1 -1
  73. package/dist/gpu-dataframe/gpu-expression-shader.cjs +94 -44
  74. package/dist/gpu-dataframe/gpu-expression-shader.d.ts +8 -5
  75. package/dist/gpu-dataframe/gpu-expression-shader.d.ts.map +1 -1
  76. package/dist/gpu-dataframe/gpu-expression-shader.js +110 -47
  77. package/dist/gpu-dataframe/gpu-expression-shader.js.map +1 -1
  78. package/dist/gpu-dataframe/gpu-expression.cjs +14 -8
  79. package/dist/gpu-dataframe/gpu-expression.d.ts +12 -1
  80. package/dist/gpu-dataframe/gpu-expression.d.ts.map +1 -1
  81. package/dist/gpu-dataframe/gpu-expression.js +11 -6
  82. package/dist/gpu-dataframe/gpu-expression.js.map +1 -1
  83. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.cjs +8 -4
  84. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.d.ts +2 -1
  85. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.d.ts.map +1 -1
  86. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.js +10 -4
  87. package/dist/gpu-dataframe/gpu-global-aggregation-compiler.js.map +1 -1
  88. package/dist/gpu-dataframe/gpu-global-aggregation-query.cjs +2 -2
  89. package/dist/gpu-dataframe/gpu-global-aggregation-query.d.ts +5 -1
  90. package/dist/gpu-dataframe/gpu-global-aggregation-query.d.ts.map +1 -1
  91. package/dist/gpu-dataframe/gpu-global-aggregation-query.js +6 -2
  92. package/dist/gpu-dataframe/gpu-global-aggregation-query.js.map +1 -1
  93. package/dist/gpu-dataframe/gpu-global-sort-compiler.cjs +156 -124
  94. package/dist/gpu-dataframe/gpu-global-sort-compiler.d.ts +12 -2
  95. package/dist/gpu-dataframe/gpu-global-sort-compiler.d.ts.map +1 -1
  96. package/dist/gpu-dataframe/gpu-global-sort-compiler.js +160 -128
  97. package/dist/gpu-dataframe/gpu-global-sort-compiler.js.map +1 -1
  98. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.cjs +366 -53
  99. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.d.ts +26 -4
  100. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.d.ts.map +1 -1
  101. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.js +378 -47
  102. package/dist/gpu-dataframe/gpu-group-aggregation-compiler.js.map +1 -1
  103. package/dist/gpu-dataframe/gpu-group-by-query.cjs +20 -9
  104. package/dist/gpu-dataframe/gpu-group-by-query.d.ts +15 -2
  105. package/dist/gpu-dataframe/gpu-group-by-query.d.ts.map +1 -1
  106. package/dist/gpu-dataframe/gpu-group-by-query.js +22 -8
  107. package/dist/gpu-dataframe/gpu-group-by-query.js.map +1 -1
  108. package/dist/gpu-dataframe/gpu-join-compiler.cjs +61 -8
  109. package/dist/gpu-dataframe/gpu-join-compiler.d.ts +10 -2
  110. package/dist/gpu-dataframe/gpu-join-compiler.d.ts.map +1 -1
  111. package/dist/gpu-dataframe/gpu-join-compiler.js +60 -7
  112. package/dist/gpu-dataframe/gpu-join-compiler.js.map +1 -1
  113. package/dist/gpu-dataframe/gpu-query-compiler.cjs +61 -11
  114. package/dist/gpu-dataframe/gpu-query-compiler.d.ts +5 -1
  115. package/dist/gpu-dataframe/gpu-query-compiler.d.ts.map +1 -1
  116. package/dist/gpu-dataframe/gpu-query-compiler.js +61 -10
  117. package/dist/gpu-dataframe/gpu-query-compiler.js.map +1 -1
  118. package/dist/gpu-dataframe/index.cjs +4 -2
  119. package/dist/gpu-dataframe/index.cjs.map +3 -3
  120. package/dist/gpu-dataframe/index.d.ts +1 -1
  121. package/dist/gpu-dataframe/index.d.ts.map +1 -1
  122. package/dist/gpu-dataframe/index.js +1 -1
  123. package/dist/gpu-dataframe/index.js.map +1 -1
  124. package/dist/gpu-graph/index.cjs.map +1 -1
  125. package/dist/gpu-graph-algorithms/benchmarks.cjs.map +2 -2
  126. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.cjs +182 -62
  127. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.d.ts +29 -2
  128. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.d.ts.map +1 -1
  129. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.js +200 -64
  130. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.js.map +1 -1
  131. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path.cjs +135 -9
  132. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path.d.ts +55 -8
  133. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path.d.ts.map +1 -1
  134. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path.js +145 -14
  135. package/dist/gpu-graph-algorithms/gpu-graph-single-source-shortest-path.js.map +1 -1
  136. package/dist/gpu-graph-algorithms/index.cjs.map +3 -3
  137. package/dist/gpu-physics/articulation-tree-shader.cjs +177 -0
  138. package/dist/gpu-physics/articulation-tree-shader.d.ts +3 -0
  139. package/dist/gpu-physics/articulation-tree-shader.d.ts.map +1 -0
  140. package/dist/gpu-physics/articulation-tree-shader.js +159 -0
  141. package/dist/gpu-physics/articulation-tree-shader.js.map +1 -0
  142. package/dist/gpu-physics/gpu-articulation-tree.cjs +203 -0
  143. package/dist/gpu-physics/gpu-articulation-tree.d.ts +81 -0
  144. package/dist/gpu-physics/gpu-articulation-tree.d.ts.map +1 -0
  145. package/dist/gpu-physics/gpu-articulation-tree.js +205 -0
  146. package/dist/gpu-physics/gpu-articulation-tree.js.map +1 -0
  147. package/dist/gpu-physics/gpu-physics-batch.cjs +11 -10
  148. package/dist/gpu-physics/gpu-physics-batch.d.ts +1 -0
  149. package/dist/gpu-physics/gpu-physics-batch.d.ts.map +1 -1
  150. package/dist/gpu-physics/gpu-physics-batch.js +14 -10
  151. package/dist/gpu-physics/gpu-physics-batch.js.map +1 -1
  152. package/dist/gpu-physics/gpu-physics-ensemble.cjs +9 -4
  153. package/dist/gpu-physics/gpu-physics-ensemble.d.ts +10 -1
  154. package/dist/gpu-physics/gpu-physics-ensemble.d.ts.map +1 -1
  155. package/dist/gpu-physics/gpu-physics-ensemble.js +11 -4
  156. package/dist/gpu-physics/gpu-physics-ensemble.js.map +1 -1
  157. package/dist/gpu-physics/gpu-rigid-body-world.cjs +323 -68
  158. package/dist/gpu-physics/gpu-rigid-body-world.d.ts +59 -2
  159. package/dist/gpu-physics/gpu-rigid-body-world.d.ts.map +1 -1
  160. package/dist/gpu-physics/gpu-rigid-body-world.js +400 -75
  161. package/dist/gpu-physics/gpu-rigid-body-world.js.map +1 -1
  162. package/dist/gpu-physics/index.cjs +3 -0
  163. package/dist/gpu-physics/index.cjs.map +3 -3
  164. package/dist/gpu-physics/index.d.ts +3 -1
  165. package/dist/gpu-physics/index.d.ts.map +1 -1
  166. package/dist/gpu-physics/index.js +1 -0
  167. package/dist/gpu-physics/index.js.map +1 -1
  168. package/dist/gpu-physics/rigid-body-cache-shaders.cjs +10 -6
  169. package/dist/gpu-physics/rigid-body-cache-shaders.d.ts +2 -1
  170. package/dist/gpu-physics/rigid-body-cache-shaders.d.ts.map +1 -1
  171. package/dist/gpu-physics/rigid-body-cache-shaders.js +15 -6
  172. package/dist/gpu-physics/rigid-body-cache-shaders.js.map +1 -1
  173. package/dist/gpu-physics/rigid-body-capacity.cjs +15 -2
  174. package/dist/gpu-physics/rigid-body-capacity.d.ts +3 -1
  175. package/dist/gpu-physics/rigid-body-capacity.d.ts.map +1 -1
  176. package/dist/gpu-physics/rigid-body-capacity.js +21 -2
  177. package/dist/gpu-physics/rigid-body-capacity.js.map +1 -1
  178. package/dist/gpu-physics/rigid-body-cast-index.cjs +192 -0
  179. package/dist/gpu-physics/rigid-body-cast-index.d.ts +44 -0
  180. package/dist/gpu-physics/rigid-body-cast-index.d.ts.map +1 -0
  181. package/dist/gpu-physics/rigid-body-cast-index.js +194 -0
  182. package/dist/gpu-physics/rigid-body-cast-index.js.map +1 -0
  183. package/dist/gpu-physics/rigid-body-ensemble-layout.cjs +4 -2
  184. package/dist/gpu-physics/rigid-body-ensemble-layout.d.ts +2 -1
  185. package/dist/gpu-physics/rigid-body-ensemble-layout.d.ts.map +1 -1
  186. package/dist/gpu-physics/rigid-body-ensemble-layout.js +5 -2
  187. package/dist/gpu-physics/rigid-body-ensemble-layout.js.map +1 -1
  188. package/dist/gpu-physics/rigid-body-ensemble-reset.cjs +11 -9
  189. package/dist/gpu-physics/rigid-body-ensemble-reset.d.ts +1 -1
  190. package/dist/gpu-physics/rigid-body-ensemble-reset.d.ts.map +1 -1
  191. package/dist/gpu-physics/rigid-body-ensemble-reset.js +13 -9
  192. package/dist/gpu-physics/rigid-body-ensemble-reset.js.map +1 -1
  193. package/dist/gpu-physics/rigid-body-ensemble-shaders.cjs +14 -7
  194. package/dist/gpu-physics/rigid-body-ensemble-shaders.d.ts +5 -0
  195. package/dist/gpu-physics/rigid-body-ensemble-shaders.d.ts.map +1 -1
  196. package/dist/gpu-physics/rigid-body-ensemble-shaders.js +17 -7
  197. package/dist/gpu-physics/rigid-body-ensemble-shaders.js.map +1 -1
  198. package/dist/gpu-physics/rigid-body-ensemble-transaction.cjs +21 -11
  199. package/dist/gpu-physics/rigid-body-ensemble-transaction.d.ts +2 -2
  200. package/dist/gpu-physics/rigid-body-ensemble-transaction.d.ts.map +1 -1
  201. package/dist/gpu-physics/rigid-body-ensemble-transaction.js +28 -12
  202. package/dist/gpu-physics/rigid-body-ensemble-transaction.js.map +1 -1
  203. package/dist/gpu-physics/rigid-body-event-compaction.cjs +184 -0
  204. package/dist/gpu-physics/rigid-body-event-compaction.d.ts +35 -0
  205. package/dist/gpu-physics/rigid-body-event-compaction.d.ts.map +1 -0
  206. package/dist/gpu-physics/rigid-body-event-compaction.js +168 -0
  207. package/dist/gpu-physics/rigid-body-event-compaction.js.map +1 -0
  208. package/dist/gpu-physics/rigid-body-event-snapshot.cjs +51 -0
  209. package/dist/gpu-physics/rigid-body-event-snapshot.d.ts +33 -0
  210. package/dist/gpu-physics/rigid-body-event-snapshot.d.ts.map +1 -0
  211. package/dist/gpu-physics/rigid-body-event-snapshot.js +34 -0
  212. package/dist/gpu-physics/rigid-body-event-snapshot.js.map +1 -0
  213. package/dist/gpu-physics/rigid-body-events.cjs +57 -25
  214. package/dist/gpu-physics/rigid-body-events.d.ts +2 -1
  215. package/dist/gpu-physics/rigid-body-events.d.ts.map +1 -1
  216. package/dist/gpu-physics/rigid-body-events.js +60 -25
  217. package/dist/gpu-physics/rigid-body-events.js.map +1 -1
  218. package/dist/gpu-physics/rigid-body-joints.cjs +8 -3
  219. package/dist/gpu-physics/rigid-body-joints.d.ts +2 -0
  220. package/dist/gpu-physics/rigid-body-joints.d.ts.map +1 -1
  221. package/dist/gpu-physics/rigid-body-joints.js +10 -6
  222. package/dist/gpu-physics/rigid-body-joints.js.map +1 -1
  223. package/dist/gpu-physics/rigid-body-queries.cjs +159 -16
  224. package/dist/gpu-physics/rigid-body-queries.d.ts +24 -1
  225. package/dist/gpu-physics/rigid-body-queries.d.ts.map +1 -1
  226. package/dist/gpu-physics/rigid-body-queries.js +166 -14
  227. package/dist/gpu-physics/rigid-body-queries.js.map +1 -1
  228. package/dist/gpu-physics/rigid-body-shaders.cjs +3 -3
  229. package/dist/gpu-physics/rigid-body-shaders.d.ts +1 -1
  230. package/dist/gpu-physics/rigid-body-shaders.d.ts.map +1 -1
  231. package/dist/gpu-physics/rigid-body-shaders.js +3 -3
  232. package/dist/gpu-physics/rigid-body-shaders.js.map +1 -1
  233. package/dist/gpu-physics/rigid-body-triggers.cjs +53 -15
  234. package/dist/gpu-physics/rigid-body-triggers.d.ts +1 -0
  235. package/dist/gpu-physics/rigid-body-triggers.d.ts.map +1 -1
  236. package/dist/gpu-physics/rigid-body-triggers.js +55 -15
  237. package/dist/gpu-physics/rigid-body-triggers.js.map +1 -1
  238. package/dist/gpu-physics/sphere-world-shaders.cjs +48 -20
  239. package/dist/gpu-physics/sphere-world-shaders.d.ts.map +1 -1
  240. package/dist/gpu-physics/sphere-world-shaders.js +51 -21
  241. package/dist/gpu-physics/sphere-world-shaders.js.map +1 -1
  242. package/dist/gpu-project/benchmarks.cjs.map +2 -2
  243. package/dist/gpu-project/crs.cjs.map +2 -2
  244. package/dist/gpu-project/graph.cjs.map +2 -2
  245. package/dist/gpu-project/index.cjs.map +2 -2
  246. package/dist/gpu-project/projection-program.cjs +2 -9
  247. package/dist/gpu-project/projection-program.d.ts.map +1 -1
  248. package/dist/gpu-project/projection-program.js +1 -8
  249. package/dist/gpu-project/projection-program.js.map +1 -1
  250. package/dist/gpu-simple-graph/index.cjs.map +2 -2
  251. package/dist/gpu-sql/gpu-sql.cjs +345 -81
  252. package/dist/gpu-sql/gpu-sql.d.ts +42 -2
  253. package/dist/gpu-sql/gpu-sql.d.ts.map +1 -1
  254. package/dist/gpu-sql/gpu-sql.js +393 -90
  255. package/dist/gpu-sql/gpu-sql.js.map +1 -1
  256. package/dist/gpu-sql/index.cjs.map +3 -3
  257. package/dist/gpu-sql/index.d.ts +1 -1
  258. package/dist/gpu-sql/index.d.ts.map +1 -1
  259. package/dist/index.cjs.map +1 -1
  260. package/dist/utils/float32.cjs +35 -0
  261. package/dist/utils/float32.d.ts +3 -0
  262. package/dist/utils/float32.d.ts.map +1 -0
  263. package/dist/utils/float32.js +16 -0
  264. package/dist/utils/float32.js.map +1 -0
  265. package/package.json +8 -8
  266. package/src/arrow/gpu/arrow-gpu-analytics-adapters.ts +77 -25
  267. package/src/arrow/gpu/arrow-gpu-analytics-readback.ts +52 -16
  268. package/src/arrow/gpu/arrow-gpu-table-conversion.ts +130 -31
  269. package/src/arrow/gpu/arrow-gpu-vector-conversion.ts +19 -0
  270. package/src/arrow/index.ts +1 -0
  271. package/src/arrow/vectors/arrow-temporal-gpu-vector.ts +2 -2
  272. package/src/gpu-core/gpu-bvh-bounds.ts +84 -0
  273. package/src/gpu-core/gpu-command-graph-budget-controller.ts +22 -2
  274. package/src/gpu-core/gpu-command-graph-submission-pacer.ts +102 -0
  275. package/src/gpu-core/gpu-group-aggregation.ts +68 -30
  276. package/src/gpu-core/index.ts +5 -0
  277. package/src/gpu-dataframe/gpu-analytics-compiler-utils.ts +7 -10
  278. package/src/gpu-dataframe/gpu-data-frame-query.ts +106 -25
  279. package/src/gpu-dataframe/gpu-data-frame.ts +35 -2
  280. package/src/gpu-dataframe/gpu-expression-shader.ts +172 -58
  281. package/src/gpu-dataframe/gpu-expression.ts +62 -9
  282. package/src/gpu-dataframe/gpu-global-aggregation-compiler.ts +15 -4
  283. package/src/gpu-dataframe/gpu-global-aggregation-query.ts +12 -3
  284. package/src/gpu-dataframe/gpu-global-sort-compiler.ts +231 -156
  285. package/src/gpu-dataframe/gpu-group-aggregation-compiler.ts +645 -61
  286. package/src/gpu-dataframe/gpu-group-by-query.ts +51 -14
  287. package/src/gpu-dataframe/gpu-join-compiler.ts +87 -6
  288. package/src/gpu-dataframe/gpu-query-compiler.ts +100 -18
  289. package/src/gpu-dataframe/index.ts +1 -1
  290. package/src/gpu-graph-algorithms/README.md +4 -2
  291. package/src/gpu-graph-algorithms/gpu-graph-single-source-shortest-path-internals.ts +248 -66
  292. package/src/gpu-graph-algorithms/gpu-graph-single-source-shortest-path.ts +218 -20
  293. package/src/gpu-physics/articulation-tree-shader.ts +169 -0
  294. package/src/gpu-physics/gpu-articulation-tree.ts +279 -0
  295. package/src/gpu-physics/gpu-physics-batch.ts +19 -13
  296. package/src/gpu-physics/gpu-physics-ensemble.ts +20 -4
  297. package/src/gpu-physics/gpu-rigid-body-world.ts +510 -93
  298. package/src/gpu-physics/index.ts +16 -0
  299. package/src/gpu-physics/rigid-body-cache-shaders.ts +18 -6
  300. package/src/gpu-physics/rigid-body-capacity.ts +25 -4
  301. package/src/gpu-physics/rigid-body-cast-index.ts +277 -0
  302. package/src/gpu-physics/rigid-body-ensemble-layout.ts +6 -2
  303. package/src/gpu-physics/rigid-body-ensemble-reset.ts +21 -9
  304. package/src/gpu-physics/rigid-body-ensemble-shaders.ts +18 -7
  305. package/src/gpu-physics/rigid-body-ensemble-transaction.ts +31 -13
  306. package/src/gpu-physics/rigid-body-event-compaction.ts +252 -0
  307. package/src/gpu-physics/rigid-body-event-snapshot.ts +76 -0
  308. package/src/gpu-physics/rigid-body-events.ts +63 -25
  309. package/src/gpu-physics/rigid-body-joints.ts +11 -11
  310. package/src/gpu-physics/rigid-body-queries.ts +202 -14
  311. package/src/gpu-physics/rigid-body-shaders.ts +4 -3
  312. package/src/gpu-physics/rigid-body-triggers.ts +64 -20
  313. package/src/gpu-physics/sphere-world-shaders.ts +53 -21
  314. package/src/gpu-project/projection-program.ts +1 -9
  315. package/src/gpu-sql/gpu-sql.ts +629 -124
  316. package/src/gpu-sql/index.ts +1 -1
  317. package/src/utils/float32.ts +16 -0
package/dist/dist.min.js CHANGED
@@ -4,9 +4,9 @@
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 da=Object.create;var kr=Object.defineProperty;var la=Object.getOwnPropertyDescriptor;var fa=Object.getOwnPropertyNames;var ha=Object.getPrototypeOf,ma=Object.prototype.hasOwnProperty;var pa=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ga=(r,e)=>{for(var t in e)kr(r,t,{get:e[t],enumerable:!0})},$r=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of fa(e))!ma.call(r,o)&&o!==t&&kr(r,o,{get:()=>e[o],enumerable:!(n=la(e,o))||n.enumerable});return r},Ir=(r,e,t)=>($r(r,e,"default"),t&&$r(t,e,"default")),F=(r,e,t)=>(t=r!=null?da(ha(r)):{},$r(e||!r||!r.__esModule?kr(t,"default",{value:r,enumerable:!0}):t,r)),ya=r=>$r(kr({},"__esModule",{value:!0}),r);var A=pa((Jc,ai)=>{ai.exports=globalThis.luma});var Or={};ga(Or,{CompiledGPUCommandGraph:()=>bt,CompiledGPUGraph:()=>Yt,DynamicBuffer:()=>Se,DynamicTexture:()=>ot,GPUCPUOperation:()=>Te,GPUCommandGraph:()=>xt,GPUCommandGraphAutotuner:()=>En,GPUCommandGraphEncoding:()=>Ft,GPUCommandGraphExecution:()=>At,GPUCommandGraphExecutionBudgetController:()=>Pn,GPUCommandGraphInspector:()=>Ln,GPUCompactionOperation:()=>On,GPUCopyOperation:()=>Ye,GPUExpressionOperation:()=>Ve,GPUGraph:()=>ke,GPUGraphCompiler:()=>St,GPUGraphGroupAggregation:()=>Tn,GPUGraphReduction:()=>vn,GPUGraphScalar:()=>Ae,GPUGraphTexture:()=>de,GPUGraphTextureView:()=>Fe,GPUGraphVector:()=>Q,GPUShaderPassOperation:()=>ft,GPUUploadOperation:()=>qe,GraphBufferHandle:()=>je,GraphDataView:()=>De,GraphExternalTextureHandle:()=>ct,GraphTextureHandle:()=>Ce,GraphTextureView:()=>_e,GraphVectorView:()=>O,Kernel:()=>D,PreparedGPUGraphExecution:()=>Cr,RenderKernel:()=>qt,composite:()=>Zo,getGPUCommandGraphAdapterIdentity:()=>oa,getGPUCommandGraphExecutionPlan:()=>Kr,getPlatformInfo:()=>ua,gpuGraph:()=>M,inspectGPUGraphCompilation:()=>Qo,validateGPUGraph:()=>vr});Ir(Or,F(A(),1));var mt=F(A(),1);async function ui(r,e){if(r.destroyed)throw new Error("Resource has been destroyed.");if(r instanceof mt.Buffer){if(!(r.usage&mt.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)&mt.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 n=e.baseMipLevel??0,o=Math.min(32,e.width??Math.max(1,r.width>>n)),i=Math.min(32,e.height??Math.max(1,r.height>>n)),s=r.computeMemoryLayout({width:o,height:i,depthOrArrayLayers:1}),a=r.device.createBuffer({byteLength:s.byteLength,usage:mt.Buffer.MAP_READ|mt.Buffer.COPY_DST}),u=r.device.createCommandEncoder();try{u.copyTextureToBuffer({sourceTexture:r,destinationBuffer:a,mipLevel:n,origin:[0,0,e.baseArrayLayer??0],width:o,height:i,depthOrArrayLayers:1,bytesPerRow:s.bytesPerRow}),r.device.submit(u.finish());let c=await a.readAsync(),d=o*t.bytesPerPixel,l=new Uint8Array(d*i);for(let f=0;f<i;f++)l.set(c.subarray(f*s.bytesPerRow,f*s.bytesPerRow+d),f*d);return{data:l,width:o,height:i,format:r.format}}finally{a.destroy(),u.destroy()}}var ce=F(A(),1);var Xt=globalThis,ba=globalThis.document||{},Ur=globalThis.process||{},xa=globalThis.console,wa=globalThis.navigator||{};function Gr(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)}function Je(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||Gr()}var $n="5.0.0";function Lt(r,e){if(!r)throw new Error(e||"Assertion failed")}function Dr(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 Lt(Number.isFinite(e)&&e>=0),e}function kn(r){let{logLevel:e,message:t}=r;r.logLevel=Dr(e);let n=r.args?Array.from(r.args):[];for(;n.length&&n.shift()!==t;);switch(typeof e){case"string":case"function":t!==void 0&&n.unshift(t),r.message=e;break;case"object":Object.assign(r,e);break;default:}typeof r.message=="function"&&(r.message=r.message());let o=typeof r.message;return Lt(o==="string"||o==="object"),Object.assign(r,{args:n},r.opts)}var et=()=>{},pt=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,...n){return this._log("log",e,t,n)}info(e,t,...n){return this._log("info",e,t,n)}once(e,t,...n){return this._log("once",e,t,n,{once:!0})}_log(e,t,n,o,i={}){let s=kn({logLevel:t,message:n,args:this._buildArgs(t,n,o),opts:i});return this._createLogFunction(e,s,i)}_buildArgs(e,t,n){return[e,t,...n]}_createLogFunction(e,t,n){if(!this._shouldLog(t.logLevel))return et;let o=this._getOnceTag(n.tag??t.tag??t.message);if((n.once||t.once)&&o!==void 0){if(this._onceCache.has(o))return et;this._onceCache.add(o)}return this._emit(e,t)}_shouldLog(e){return this.getLevel()>=Dr(e)}_getOnceTag(e){if(e!==void 0)try{return typeof e=="string"?e:String(e)}catch{return}}};function va(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,t),e.removeItem(t),e}catch{return null}}var Kt=class{constructor(e,t,n="sessionStorage"){this.storage=va(n),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 ci(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 In(r,e=8){let t=Math.max(e-r.length,0);return`${" ".repeat(t)}${r}`}var Zt;(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"})(Zt||(Zt={}));var Sa=10;function di(r){return typeof r!="string"?r:(r=r.toUpperCase(),Zt[r]||Zt.WHITE)}function Un(r,e,t){return!Je&&typeof r=="string"&&(e&&(r=`\x1B[${di(e)}m${r}\x1B[39m`),t&&(r=`\x1B[${di(t)+Sa}m${r}\x1B[49m`)),r}function Gn(r,e=["constructor"]){let t=Object.getPrototypeOf(r),n=Object.getOwnPropertyNames(t),o=r;for(let i of n){let s=o[i];typeof s=="function"&&(e.find(a=>i===a)||(o[i]=s.bind(r)))}}var _r=class{getHighResolutionTimer(){let e;if(Je()&&Xt.performance)e=Xt?.performance?.now?.();else if("hrtime"in Ur){let t=Ur?.hrtime?.();e=t[0]*1e3+t[1]/1e6}else e=Date.now();return e}getMemoryUsageMB(){let t=Xt?.performance?.memory?.usedJSHeapSize;return t==null?null:Math.trunc(t/1024/1024)}},me=new _r;globalThis.Probe=_r;globalThis.probe=me;var Bt={debug:Je()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},Dn={enabled:!0,level:0},Me=class extends pt{constructor({id:e}={id:""}){super({level:0}),this.VERSION=$n,this._startTs=me.getHighResolutionTimer(),this._deltaTs=me.getHighResolutionTimer(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new Kt(`__probe-${this.id}__`,{[this.id]:Dn}),this.timeStamp(`${this.id} started`),Gn(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((me.getHighResolutionTimer()-this._startTs).toPrecision(10))}getDelta(){return Number((me.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:Bt.warn,once:!0})}error(e,...t){return this._log("error",0,e,t,{method:Bt.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,...n){let o=me.getMemoryUsageMB();if(o!==null){let i=`${o}MB `;typeof t=="function"?t=()=>`${i}${t()}`:typeof t=="string"&&(t=`${i}${t}`)}return this._log("log",e,t,n,{method:Bt.log,time:!0,once:!0})}log(e,t,...n){return this._log("log",e,t,n,{method:Bt.debug})}info(e,t,...n){return this._log("info",e,t,n,{method:console.info})}once(e,t,...n){return this._log("once",e,t,n,{method:Bt.debug||Bt.info,once:!0})}table(e,t,n){return t?this._log("table",e,t,n&&[n]||[],{method:console.table||et,tag:Pa(t)}):et}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||et})}group(e,t,n={collapsed:!1}){let o=(n.collapsed?console.groupCollapsed:console.group)||console.info;return this._log("group",e,t,[],{method:o})}groupCollapsed(e,t,n={}){return this.group(e,t,Object.assign({},n,{collapsed:!0}))}groupEnd(e){return this._log("groupEnd",e,"",[],{method:console.groupEnd||et})}withGroup(e,t,n){this.group(e,t)();try{n()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&super._shouldLog(e)}_emit(e,t){let n=t.method;Lt(n),t.total=this.getTotal(),t.delta=this.getDelta(),this._deltaTs=me.getHighResolutionTimer();let o=Ea(this.id,t.message,t);return n.bind(console,o,...t.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(Dn),this._storage.config[this.id]}_updateConfiguration(e){let t=this._storage.config[this.id]||{...Dn};this._storage.setConfiguration({[this.id]:{...t,...e}})}};Me.VERSION=$n;function Ea(r,e,t){if(typeof e=="string"){let n=t.time?In(ci(t.total)):"";e=t.time?`${r}: ${n} ${e}`:`${r}: ${e}`,e=Un(e,t.color,t.background)}return e}function Pa(r){for(let e in r)for(let t in r[e])return t||"untitled";return"empty"}globalThis.probe||(globalThis.probe=me);var el=new Me({id:"@probe.gl/log"});var ve=new Me({id:"luma.gl"});var _n={};function Ot(r="id"){_n[r]=_n[r]||1;let e=_n[r]++;return`${r}-${e}`}function $t(r,e){if(!r){let t=new Error(e??"luma.gl assertion failed.");throw Error.captureStackTrace?.(t,$t),t}}var Ar=class{_owner=null;_ownedResources=new Set;_state="live";_destroyingOwnedResources=!1;_destroyRequested=!1;get owner(){return this._owner}get ownedResources(){return Array.from(this._ownedResources)}get destroyed(){return this._state==="destroyed"}transferOwnershipTo(e){$t(this._state==="live"&&!this._destroyingOwnedResources),$t(!this._owner||this._owner.canChangeOwnership()),$t(!e||e.canChangeOwnership());for(let t=e;t;t=t._owner)$t(t!==this);return e!==this._owner&&(this._owner?._ownedResources.delete(this),this._owner=e,e?._ownedResources.add(this)),this}destroy(){if(this._state!=="live")return;if(this._destroyingOwnedResources){this._destroyRequested=!0;return}this._destroyRequested=!1,this._state="destroying",this._owner?._ownedResources.delete(this),this._owner=null;let e=[];try{try{this.onBeforeDestroy()}catch(t){e.push(t)}this.destroyChildren(e);try{this.onDestroy()}catch(t){e.push(t)}}finally{this._state="destroyed"}if(e.length)throw new AggregateError(e,"Resource cleanup failed")}delete(){return this.destroy(),this}attachResource(e){e.transferOwnershipTo(this)}detachResource(e){e._owner===this&&e.transferOwnershipTo(null)}destroyAttachedResource(e){e._owner===this&&e.destroy()}destroyAttachedResources(){if(this._state!=="live"||this._destroyingOwnedResources)return;let e=[];if(this.destroyChildren(e),this._destroyRequested)try{this.destroy()}catch(t){e.push(t)}if(e.length)throw new AggregateError(e,"Resource cleanup failed")}onBeforeDestroy(){}onDestroy(){}canChangeOwnership(){return this._state==="live"&&!this._destroyingOwnedResources}destroyChildren(e){this._destroyingOwnedResources=!0;try{for(let t of this._ownedResources)try{t.destroy()}catch(n){e.push(n)}}finally{this._ownedResources.clear(),this._destroyingOwnedResources=!1}}};var Ca="cpu-hotspot-profiler",li="GPU Resource Counts",fi="Resource Counts",hi="GPU Time and Memory",La=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],Ba=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","SharedRenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],Oa=La.flatMap(r=>[`${r} Created`,`${r} Active`]),$a=Ba.flatMap(r=>[`${r} Created`,`${r} Active`]),mi=new WeakMap,pi=new WeakMap,pe=class extends Ar{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;allocatedBytes=0;allocatedBytesName=null;get ownsHandle(){return(this.props.handle===void 0||this.props.handle===null)&&!this.isHandleBorrowed}get isHandleBorrowed(){return!!this.props._isHandleBorrowed}constructor(e,t,n){if(super(),!e)throw new Error("no device");this._device=e,this.props=ka(t,n);let o=this.props.id!=="undefined"?this.props.id:Ot(this[Symbol.toStringTag]);this.props.id=o,this.id=o,this.userData=this.props.userData||{},this.addStats()}getProps(){return this.props}destroyHandle(){}onDestroy(){try{this.destroyHandle()}finally{this.trackDeallocatedMemory(),this.removeStats()}}removeStats(){let e=Qt(this._device),t=e?tt():0,n=[this._device.statsManager.getStats(li),this._device.statsManager.getStats(fi)],o=yi(this._device);for(let s of n)gi(s,o);let i=this.getStatsName();for(let s of n)s.get("Resources Active").decrementCount(),s.get(`${i}s Active`).decrementCount();e&&(e.statsBookkeepingCalls=(e.statsBookkeepingCalls||0)+1,e.statsBookkeepingTimeMs=(e.statsBookkeepingTimeMs||0)+(tt()-t))}trackAllocatedMemory(e,t=this.getStatsName()){let n=Qt(this._device),o=n?tt():0,i=this._device.statsManager.getStats(hi);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),n&&(n.statsBookkeepingCalls=(n.statsBookkeepingCalls||0)+1,n.statsBookkeepingTimeMs=(n.statsBookkeepingTimeMs||0)+(tt()-o)),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=Qt(this._device),n=t?tt():0,o=this._device.statsManager.getStats(hi);o.get("GPU Memory").subtractCount(this.allocatedBytes),o.get(`${this.allocatedBytesName||e} Memory`).subtractCount(this.allocatedBytes),t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(tt()-n)),this.allocatedBytes=0,this.allocatedBytesName=null}trackDeallocatedReferencedMemory(e=this.getStatsName()){this.trackDeallocatedMemory(`Referenced ${e}`)}addStats(){let e=this.getStatsName(),t=Qt(this._device),n=t?tt():0,o=[this._device.statsManager.getStats(li),this._device.statsManager.getStats(fi)],i=yi(this._device);for(let s of o)gi(s,i);for(let s of o)s.get("Resources Created").incrementCount(),s.get("Resources Active").incrementCount(),s.get(`${e}s Created`).incrementCount(),s.get(`${e}s Active`).incrementCount();t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(tt()-n)),Ia(this._device,e)}getStatsName(){return Ua(this)}};function ka(r,e){let t={...e};for(let n in r)r[n]!==void 0&&(t[n]=r[n]);return t}function gi(r,e){let t=r.stats,n=!1;for(let u of e)t[u]||(r.get(u),n=!0);let o=Object.keys(t).length,i=mi.get(r);if(!n&&i?.orderedStatNames===e&&i.statCount===o)return;let s={},a=pi.get(e);a||(a=new Set(e),pi.set(e,a));for(let u of e)t[u]&&(s[u]=t[u]);for(let[u,c]of Object.entries(t))a.has(u)||(s[u]=c);for(let u of Object.keys(t))delete t[u];Object.assign(t,s),mi.set(r,{orderedStatNames:e,statCount:o})}function yi(r){return r.type==="webgl"?$a:Oa}function Qt(r){let e=r.userData[Ca];return e?.enabled?e:null}function tt(){return globalThis.performance?.now?.()??Date.now()}function Ia(r,e){let t=Qt(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 Ua(r){let e=Object.getPrototypeOf(r);for(;e;){let t=Object.getPrototypeOf(e);if(!t||t===pe.prototype)return Ga(e)||r[Symbol.toStringTag]||r.constructor.name;e=t}return r[Symbol.toStringTag]||r.constructor.name}function Ga(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 Ie=class r extends pe{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 n={...t};(t.usage||0)&r.INDEX&&!t.indexType&&(t.data instanceof Uint32Array?n.indexType="uint32":t.data instanceof Uint16Array?n.indexType="uint16":t.data instanceof Uint8Array&&(n.indexType="uint8")),delete n.data,super(e,n,r.defaultProps),this.usage=n.usage||0,this.indexType=n.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,n){if(!this.device.props.debug)return;let o=null,i;ArrayBuffer.isView(e)?(o=e,i=e.buffer):i=e;let s=Math.min(e?e.byteLength:n,r.DEBUG_DATA_MAX_LENGTH);if(i===null)this.debugData=new ArrayBuffer(s);else{let a=Math.min(o?.byteOffset||0,i.byteLength),u=Math.max(0,i.byteLength-a),c=Math.min(s,u);this.debugData=new Uint8Array(i,a,c).slice().buffer}}static defaultProps={...pe.defaultProps,handle:void 0,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}};var An=globalThis.Float16Array;function bi(){return An??Uint16Array}function xi(r){return!!(An&&r===An)}function Fr(r,e){switch(e){case 1:return r;case 2:return r+r%2;default:return r+(4-r%4)%4}}var wi=new Map;function Ti(r){let e=wi.get(r);if(e)return e;let t=Object.freeze(Da(r));return Object.hasOwn(Rr,r)&&wi.set(r,t),t}function Da(r){let e=r.includes("norm"),t=!e&&!r.startsWith("float"),n=r.startsWith("s"),o=Rr[r],[i,s,a]=o||["uint8 ","i32",1];return{signedType:i,primitiveType:s,byteLength:a,normalized:e,integer:t,signed:n}}function vi(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 _a(r){let e=ArrayBuffer.isView(r)?r.constructor:r;if(xi(e))return"float16";if(e===Uint8ClampedArray)return"uint8";let t=Object.values(Rr).find(n=>e===n[4]);if(!t)throw new Error(e.name);return t[0]}function Si(r){return _a(r)}function Aa(r){if(r==="float16")return bi();let e=Rr[r];if(!e)throw new Error(r);let[,,,,t]=e;return t}function Ei(r){return Aa(r)}var Rr={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 Fn=class{getDataTypeInfo(e){return Ti(e)}getNormalizedDataType(e){return vi(e)}alignTo(e,t){return Fr(e,t)}getDataType(e){return Si(e)}getTypedArrayConstructor(e){return Ei(e)}},Pi=new Fn;var oe="texture-compression-bc",R="texture-compression-astc",Ue="texture-compression-etc2",Ci="texture-compression-etc1-webgl",Vr="texture-compression-pvrtc-webgl",Rn="texture-compression-atc-webgl",Mr="float32-renderable-webgl",Vn="float16-renderable-webgl",Fa="rgb9e5ufloat-renderable-webgl",Mn="snorm8-renderable-webgl",rt="norm16-webgl",Nn="norm16-renderable-webgl",zn="snorm16-renderable-webgl",Nr="float32-filterable",Li="float16-filterable-webgl",Jt=1,er=2,Hn=4,qn=8,It=16,Wr=5,Oi=10,Z=Jt|er,zr=Jt|Hn,Ne=Jt|er|Hn|qn,Ge=Jt|er|It,Ra=Jt|Hn|It,jn=Ne|It,Bi=(er|qn|It)<<Wr,Va=(er|qn)<<Wr,ue=It<<Wr,kt=jn<<Wr,Ma=Ne<<Oi,Wn=It<<Oi;function jr(r){let e=Wa[r];if(!e)throw new Error(`Unsupported texture format ${r}`);return e}var Na={r8unorm:{webgpu:Ne|ue},rg8unorm:{webgpu:Ne|ue},"rgb8unorm-webgl":{},rgba8unorm:{webgpu:jn},"rgba8unorm-srgb":{webgpu:Ne},r8snorm:{render:Mn,webgpu:zr|Bi},rg8snorm:{render:Mn,webgpu:zr|Bi},"rgb8snorm-webgl":{},rgba8snorm:{render:Mn,webgpu:Ra|Va},r8uint:{webgpu:Z|ue},rg8uint:{webgpu:Z|ue},rgba8uint:{webgpu:Ge},r8sint:{webgpu:Z|ue},rg8sint:{webgpu:Z|ue},rgba8sint:{webgpu:Ge},bgra8unorm:{webgpu:Ne},"bgra8unorm-srgb":{webgpu:Ma},r16unorm:{f:rt,render:Nn,webgpu:kt},rg16unorm:{f:rt,render:Nn,webgpu:kt},"rgb16unorm-webgl":{f:rt,render:!1},rgba16unorm:{f:rt,render:Nn,webgpu:kt},r16snorm:{f:rt,render:zn,webgpu:kt},rg16snorm:{f:rt,render:zn,webgpu:kt},"rgb16snorm-webgl":{f:rt,render:!1},rgba16snorm:{f:rt,render:zn,webgpu:kt},r16uint:{webgpu:Z|ue},rg16uint:{webgpu:Z|ue},rgba16uint:{webgpu:Ge},r16sint:{webgpu:Z|ue},rg16sint:{webgpu:Z|ue},rgba16sint:{webgpu:Ge},r16float:{render:Vn,filter:"float16-filterable-webgl",webgpu:Ne|ue},rg16float:{render:Vn,filter:Li,webgpu:Ne|ue},rgba16float:{render:Vn,filter:Li,webgpu:jn},r32uint:{webgpu:Ge},rg32uint:{webgpu:Z|Wn},rgba32uint:{webgpu:Ge},r32sint:{webgpu:Ge},rg32sint:{webgpu:Z|Wn},rgba32sint:{webgpu:Ge},r32float:{render:Mr,filter:Nr,webgpu:Ge},rg32float:{render:!1,filter:Nr,webgpu:Z|Wn},"rgb32float-webgl":{render:Mr,filter:Nr},rgba32float:{render:Mr,filter:Nr,webgpu:Ge},"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:Fa,webgpu:zr},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:Mr,webgpu:zr|ue},rgb10a2unorm:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:Ne|ue},rgb10a2uint:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:Z|ue},stencil8:{attachment:"stencil",bitsPerChannel:[8,0,0,0],dataType:"uint8",webgpu:Z},depth16unorm:{attachment:"depth",bitsPerChannel:[16,0,0,0],dataType:"uint16",webgpu:Z},depth24plus:{attachment:"depth",bitsPerChannel:[24,0,0,0],dataType:"uint32",webgpu:Z},depth32float:{attachment:"depth",bitsPerChannel:[32,0,0,0],dataType:"float32",webgpu:Z},"depth24plus-stencil8":{attachment:"depth-stencil",bitsPerChannel:[24,8,0,0],packed:!0,webgpu:Z},"depth32float-stencil8":{attachment:"depth-stencil",bitsPerChannel:[32,8,0,0],packed:!0,f:"depth32float-stencil8",webgpu:Z}},za={"bc1-rgb-unorm-webgl":{f:oe},"bc1-rgb-unorm-srgb-webgl":{f:oe},"bc1-rgba-unorm":{f:oe},"bc1-rgba-unorm-srgb":{f:oe},"bc2-rgba-unorm":{f:oe},"bc2-rgba-unorm-srgb":{f:oe},"bc3-rgba-unorm":{f:oe},"bc3-rgba-unorm-srgb":{f:oe},"bc4-r-unorm":{f:oe},"bc4-r-snorm":{f:oe},"bc5-rg-unorm":{f:oe},"bc5-rg-snorm":{f:oe},"bc6h-rgb-ufloat":{f:oe},"bc6h-rgb-float":{f:oe},"bc7-rgba-unorm":{f:oe},"bc7-rgba-unorm-srgb":{f:oe},"etc2-rgb8unorm":{f:Ue},"etc2-rgb8unorm-srgb":{f:Ue},"etc2-rgb8a1unorm":{f:Ue},"etc2-rgb8a1unorm-srgb":{f:Ue},"etc2-rgba8unorm":{f:Ue},"etc2-rgba8unorm-srgb":{f:Ue},"eac-r11unorm":{f:Ue},"eac-r11snorm":{f:Ue},"eac-rg11unorm":{f:Ue},"eac-rg11snorm":{f:Ue},"astc-4x4-unorm":{f:R},"astc-4x4-unorm-srgb":{f:R},"astc-5x4-unorm":{f:R},"astc-5x4-unorm-srgb":{f:R},"astc-5x5-unorm":{f:R},"astc-5x5-unorm-srgb":{f:R},"astc-6x5-unorm":{f:R},"astc-6x5-unorm-srgb":{f:R},"astc-6x6-unorm":{f:R},"astc-6x6-unorm-srgb":{f:R},"astc-8x5-unorm":{f:R},"astc-8x5-unorm-srgb":{f:R},"astc-8x6-unorm":{f:R},"astc-8x6-unorm-srgb":{f:R},"astc-8x8-unorm":{f:R},"astc-8x8-unorm-srgb":{f:R},"astc-10x5-unorm":{f:R},"astc-10x5-unorm-srgb":{f:R},"astc-10x6-unorm":{f:R},"astc-10x6-unorm-srgb":{f:R},"astc-10x8-unorm":{f:R},"astc-10x8-unorm-srgb":{f:R},"astc-10x10-unorm":{f:R},"astc-10x10-unorm-srgb":{f:R},"astc-12x10-unorm":{f:R},"astc-12x10-unorm-srgb":{f:R},"astc-12x12-unorm":{f:R},"astc-12x12-unorm-srgb":{f:R},"pvrtc-rgb4unorm-webgl":{f:Vr},"pvrtc-rgba4unorm-webgl":{f:Vr},"pvrtc-rgb2unorm-webgl":{f:Vr},"pvrtc-rgba2unorm-webgl":{f:Vr},"etc1-rgb-unorm-webgl":{f:Ci},"etc1-rbg-unorm-webgl":{f:Ci},"atc-rgb-unorm-webgl":{f:Rn},"atc-rgba-unorm-webgl":{f:Rn},"atc-rgbai-unorm-webgl":{f:Rn}},Wa={...Na,...za};var ja=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,Ha=["rgb","rgba","bgra"],qa=["depth","stencil"],Ya=5,Xa=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"],Yn=class{isColor(e){return Ha.some(t=>e.startsWith(t))}isDepthStencil(e){return qa.some(t=>e.startsWith(t))}isCompressed(e){return Xa.some(t=>e.startsWith(t))}getInfo(e){return ki(e)}getCapabilities(e){return Za(e)}getWebGPUCapabilities(e){let t=jr(e);return t.webgpu!==void 0?t.webgpu:this.isCompressed(e)&&!e.endsWith("-webgl")?Ya:0}computeMemoryLayout(e,t){return Ka(e,t)}},Ut=new Yn;function Ka({format:r,width:e,height:t,depth:n,byteAlignment:o},i={}){let s=Ut.getInfo(r),{bytesPerPixel:a,blockHeight:u=1,compressed:c=!1}=s,d=Xn(s,e,o),l=c?Math.ceil(t/u):t;return i.bytesPerPixel=a,i.bytesPerRow=d,i.rowsPerImage=l,i.depthOrArrayLayers=n,i.bytesPerImage=d*l,i.byteLength=i.bytesPerImage*n,i}function Xn(r,e,t){let{bytesPerPixel:n,bytesPerBlock:o=n,blockWidth:i=1,compressed:s=!1}=r,a=s?Math.ceil(e/i):e;return Math.ceil(a*o/t)*t}function Za(r){let e=jr(r),t={format:r,create:e.f??!0,render:e.render??!0,filter:e.filter??!0,blend:e.blend??!0,store:e.store??!0},n=ki(r),o=r.startsWith("depth")||r.startsWith("stencil"),i=n?.signed,s=n?.integer,a=n?.webgl,u=!!n?.compressed;return t.render&&=!o&&!u,t.filter&&=!o&&!i&&!s&&!a,t}var $i=new Map;function ki(r){let e=$i.get(r);if(!e){let t=Qa(r);t.bitsPerChannel=Object.freeze([...t.bitsPerChannel]),e=Object.freeze(t),$i.set(r,e)}return e}function Qa(r){let e=Ja(r);if(Ut.isCompressed(r)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0,e.bytesPerBlock=tu(r);let n=eu(r);n&&(e.blockWidth=n.blockWidth,e.blockHeight=n.blockHeight)}let t=e.packed?null:ja.exec(r);if(t){let[,n,o,i,s,a]=t,u=`${i}${o}`,c=Pi.getDataTypeInfo(u),d=c.byteLength*8,l=n?.length??1,f=[d,l>=2?d:0,l>=3?d:0,l>=4?d:0];e={format:r,attachment:e.attachment,dataType:c.signedType,components:l,channels:n,integer:c.integer,signed:c.signed,normalized:c.normalized,bitsPerChannel:f,bytesPerPixel:c.byteLength*l,packed:e.packed,srgb:e.srgb},a==="-webgl"&&(e.webgl=!0),s==="-srgb"&&(e.srgb=!0)}return r.endsWith("-webgl")&&(e.webgl=!0),r.endsWith("-srgb")&&(e.srgb=!0),e}function Ja(r){let e={...jr(r)},t=e.bytesPerPixel||1,n=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:n,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 eu(r){let t=/.*-(\d+)x(\d+)-.*/.exec(r);if(t){let[,n,o]=t;return{blockWidth:Number(n),blockHeight:Number(o)}}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 tu(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}function tr(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 Hr(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 nt=class r extends pe{static defaultProps={...pe.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}};function Ii(r,e){let t=e instanceof nt?e:r.device.createSampler(e);if(t===r.sampler)return;e instanceof nt||t.transferOwnershipTo(r);let n=r.sampler;r.sampler=t,n?.owner===r&&n.destroy()}var Ui=[],ru=Object.freeze({}),nu={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"},ie=class r extends pe{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,n){if(t=r.normalizeProps(e,t),super(e,t,r.defaultProps),this.dimension=this.props.dimension,this.baseDimension=nu[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 o=e.getExternalImageSize(t.data);this.width=o?.width||1,this.height=o?.height||1}else this.width=1,this.height=1,(this.props.width===void 0||this.props.height===void 0)&&ve.warn(`${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`)();this.byteAlignment=n?.byteAlignment||1,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createTexture({...this.props,...e})}setSampler(e){Ii(this,e)}copyImageData(e){let{data:t,depth:n,...o}=e;this.writeData(t,{...o,depthOrArrayLayers:o.depthOrArrayLayers??n})}computeMemoryLayout(e=ru,t){let n=Ui.pop()||{readOptions:{},layoutOptions:{}};try{let o=this._normalizeTextureReadOptions(e,n.readOptions),i=n.layoutOptions;return i.format=this.format,i.width=o.width,i.height=o.height,i.depth=o.depthOrArrayLayers,i.byteAlignment=this.byteAlignment,Ut.computeMemoryLayout(i,t)}finally{Ui.push(n)}}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 n={...t},{width:o,height:i}=n;return typeof o=="number"&&(n.width=Math.max(1,Math.ceil(o))),typeof i=="number"&&(n.height=Math.max(1,Math.ceil(i))),n}_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,t={}){let{data:n,depth:o,depthOrArrayLayers:i}=e;if(this._normalizeTextureWriteOptions(e,t),i===void 0&&o!==void 0){let s=this.dimension==="3d"?Math.max(1,this.depth>>t.mipLevel):this.depth;t.depthOrArrayLayers=Math.min(o,s-t.z)}return t.data=n,t.depth=t.depthOrArrayLayers,t}_normalizeCopyExternalImageOptions(e,t={}){let{width:n,height:o}=e,i=this.device.getExternalImageSize(e.image),s=r._normalizeOptions(e,r.defaultCopyExternalImageOptions,t),a=Math.max(1,this.width>>s.mipLevel),u=this.baseDimension==="1d"?1:Math.max(1,this.height>>s.mipLevel),c=this.dimension==="3d"?Math.max(1,this.depth>>s.mipLevel):this.depth;return s.width=Math.min(n??i.width,a-s.x),s.height=Math.min(o??i.height,u-s.y),s.depth=Math.min(s.depth,c-s.z),s}_normalizeCopyElementImageOptions(e,t={}){let n=r._normalizeOptions(e,r.defaultCopyElementImageOptions,t),o=Math.max(1,this.width>>n.mipLevel),i=this.baseDimension==="1d"?1:Math.max(1,this.height>>n.mipLevel),s=this.dimension==="3d"?Math.max(1,this.depth>>n.mipLevel):this.depth;return n.width=Math.min(n.width??o,o-n.x),n.height=Math.min(n.height??i,i-n.y),n.depth=Math.min(n.depth,s-n.z),n}_normalizeTextureReadOptions(e,t={}){let{depthOrArrayLayers:n}=e,o=r._normalizeOptions(e,r.defaultTextureReadOptions,t),i=Math.max(1,this.width>>o.mipLevel),s=this.baseDimension==="1d"?1:Math.max(1,this.height>>o.mipLevel),a=this.dimension==="3d"?Math.max(1,this.depth>>o.mipLevel):this.depth;return o.width=Math.min(o.width??i,i-o.x),o.height=Math.min(o.height??s,s-o.y),o.depthOrArrayLayers=Math.min(n??a,a-o.z),o}_getSupportedColorReadOptions(e){let t=this._normalizeTextureReadOptions(e),n=Ut.getInfo(this.format);switch(this._validateColorReadAspect(t),this._validateColorReadFormat(n),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,t={}){let{byteOffset:n=0,bytesPerRow:o,rowsPerImage:i}=e;this._normalizeTextureReadOptions(e,t);let s=t;s.byteOffset=n;let a=this.device.getTextureFormatInfo(this.format),u=a.bytesPerPixel*s.width;if(s.bytesPerRow=o??Xn(a,s.width,this.byteAlignment),s.rowsPerImage=i??s.height,s.bytesPerRow<u)throw new Error(`bytesPerRow (${s.bytesPerRow}) must be at least ${u} for ${this.format}`);if(s.rowsPerImage<s.height)throw new Error(`rowsPerImage (${s.rowsPerImage}) must be at least ${s.height} for ${this.format}`);let{bytesPerPixel:c}=a;if(c&&s.bytesPerRow%c!==0)throw new Error(`bytesPerRow (${s.bytesPerRow}) must be a multiple of bytesPerPixel (${c}) for ${this.format}`);return s}_getMipLevelSize(e){let t=Math.max(1,this.width>>e),n=this.baseDimension==="1d"?1:Math.max(1,this.height>>e),o=this.dimension==="3d"?Math.max(1,this.depth>>e):this.depth;return{width:t,height:n,depthOrArrayLayers:o}}getAllocatedByteLength(){let e=0;for(let t=0;t<this.mipLevels;t++){let{width:n,height:o,depthOrArrayLayers:i}=this._getMipLevelSize(t);e+=Ut.computeMemoryLayout({format:this.format,width:n,height:o,depth:i,byteAlignment:1}).byteLength}return e*this.samples}static _normalizeOptions(e,t,n){for(let o in t)n[o]=e[o]===void 0?t[o]:e[o];return n}static defaultProps={...pe.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"}};var ou=Ie.DEBUG_DATA_MAX_LENGTH,Se=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:n=!1,buffer:o,ownsBuffer:i=!0,...s}=t;if(o&&o.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(o&&(s.byteLength!==void 0||s.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let a=t.id||o?.id||Ot("dynamic-buffer"),u={...s,id:a,usage:s.usage??o?.usage,indexType:s.indexType??o?.indexType};(u.usage||0)&Ie.INDEX&&!u.indexType&&(s.data instanceof Uint32Array?u.indexType="uint32":s.data instanceof Uint16Array?u.indexType="uint16":s.data instanceof Uint8Array&&(u.indexType="uint8")),delete u.data,delete u.byteOffset,this.device=e,this.id=a,this.props=u,this.usage=u.usage||0,this._debugDataEnabled=!!n,this._maxDebugDataByteLength=typeof n=="object"&&n.maxByteLength!==void 0?n.maxByteLength:ou,this._ownsBuffer=i,this._buffer=o??this.device.createBuffer({...s,id:a}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),s.data&&this._writeDebugData(s.data,s.byteOffset||0)}write(e,t=0){this._buffer.write(e,t),this._touch(),this._writeDebugData(e,t)}async mapAndWriteAsync(e,t=0,n=this.byteLength-t){let o=null;await this._buffer.mapAndWriteAsync(async(i,s)=>{await e(i,s),o=new Uint8Array(i.slice(0,n))},t,n),this._touch(),o&&this._writeDebugData(o,t)}async readAsync(e=0,t=this.byteLength-e){let n=await this._buffer.readAsync(e,t);return this._writeDebugData(n,e)&&this._touch(),n}async mapAndReadAsync(e,t=0,n=this.byteLength-t){let o=null,i=await this._buffer.mapAndReadAsync(async(s,a)=>(o=new Uint8Array(s.slice(0)),await e(s,a)),t,n);return o&&this._writeDebugData(o,t)&&this._touch(),i}resize(e){let{byteLength:t,preserveData:n=!1}=e;if(t===this.byteLength)return!1;let o=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),i=this._buffer,s=this.debugData.slice(0),{data:a,byteOffset:u,...c}=this.props,d=this.device.createBuffer({...c,byteLength:t});return n&&o>0&&this._copyBufferContents(i,d,o),this._buffer=d,this._resetDebugData(t),n&&s.byteLength>0&&this._writeDebugData(s,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,n){let o=this.device.type==="webgpu"?Math.ceil(n/4)*4:n,i=this.device.createCommandEncoder();i.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:o}),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 n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),o=new Uint8Array(this.debugData),i=Math.min(n.byteLength,o.byteLength-t);return o.set(n.subarray(0,i),t),i>0}};var Kn={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function rr(r){return r?Array.isArray(r)?r[0]??null:r:null}function Gi(r){let{dimension:e,data:t}=r;if(!t)return null;switch(e){case"1d":{let n=rr(t);if(!n)return null;let{width:o}=nr(n);return{width:o,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let n=rr(t);return n?nr(n):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let n=rr(t[0]);return n?nr(n):null}case"cube":{let n=Object.keys(t)[0]??null;if(!n)return null;let o=t[n],i=rr(o);return i?nr(i):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let n=t[0],o=Object.keys(n)[0]??null;if(!o)return null;let i=rr(n[o]);return i?nr(i):null}default:return null}}function nr(r){if(tr(r))return Hr(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 iu(r){return typeof r=="object"&&r!==null&&"data"in r&&"width"in r&&"height"in r}function su(r){return ArrayBuffer.isView(r)}function Zn(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 Di(r){let e=Kn[r];if(e===void 0)throw new Error(`Invalid cube face: ${r}`);return e}function au(r,e){return 6*r+Di(e)}function Qn(r){throw new Error("setTexture1DData not supported in WebGL.")}function uu(r){return Array.isArray(r)?r:[r]}function gt(r,e,t,n){let o=uu(e),i=r,s=[];for(let a=0;a<o.length;a++){let u=o[a];if(tr(u))s.push({type:"external-image",image:u,z:i,mipLevel:a});else if(iu(u))s.push({type:"texture-data",data:u,textureFormat:Zn(u),z:i,mipLevel:a});else if(su(u)&&t)s.push({type:"texture-data",data:{data:u,width:Math.max(1,t.width>>a),height:Math.max(1,t.height>>a),...n?{format:n}:{}},textureFormat:n,z:i,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return s}function Jn(r){let e=[];for(let t=0;t<r.length;t++)e.push(...gt(t,r[t]));return e}function eo(r){let e=[];for(let t=0;t<r.length;t++)e.push(...gt(t,r[t]));return e}function to(r){let e=[];for(let[t,n]of Object.entries(r)){let o=Di(t);e.push(...gt(o,n))}return e}function ro(r){let e=[];return r.forEach((t,n)=>{for(let[o,i]of Object.entries(t)){let s=au(n,o);e.push(...gt(s,i))}}),e}var ot=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 n=Ot("dynamic-texture"),o=t;this.props={...r.defaultProps,id:n,...t,data:null},this.id=this.props.id,this.ready=new Promise((i,s)=>{this.resolveReady=i,this.rejectReady=s}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(o)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let n=t.data?cu({...t,width:e.width,height:e.height,format:e.format}):[],o="format"in e&&e.format!==void 0,i="usage"in e&&e.usage!==void 0,a=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let g=Gi(t);return g||{width:this.props.width||1,height:this.props.height||1}})();if(!a||a.width<=0||a.height<=0)throw new Error(`${this} size could not be determined or was zero`);let u=du(this.device,n,a,{format:o?e.format:void 0}),c=u.format??this.props.format,d={...this.props,...a,format:c,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(c)&&!i&&(d.usage=ie.SAMPLE|ie.COPY_DST);let l=this.props.mipmaps&&!u.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(c);if(this.device.type==="webgpu"&&l){let g=this.props.dimension==="3d"?ie.SAMPLE|ie.STORAGE|ie.COPY_DST|ie.COPY_SRC:ie.SAMPLE|ie.RENDER|ie.COPY_DST|ie.COPY_SRC;d.usage|=g}let f=this.device.getMipLevelCount(d.width,d.height),h=u.hasExplicitMipChain?u.mipLevels:this.props.mipLevels==="auto"?f:Math.max(1,Math.min(f,this.props.mipLevels??1)),m={...d,mipLevels:h};this._texture=this.device.createTexture(m),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),u.subresources.length&&this._setTextureSubresources(u.subresources),this.props.mipmaps&&!u.hasExplicitMipChain&&!l&&ve.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),l&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),ve.info(1,`${this} created`)()}catch(t){let n=t instanceof Error?t:new Error(String(t));this.rejectReady(n)}}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()):ve.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof nt?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,n=e.height??this.texture.height,o=e.depthOrArrayLayers??this.texture.depth,i=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:o}),s=this.device.createBuffer({byteLength:i.byteLength,usage:Ie.COPY_DST|Ie.MAP_READ});this.texture.readBuffer({...e,width:t,height:n,depthOrArrayLayers:o},s);let a=this.device.createFence();return await a.signaled,a.destroy(),s}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,o=e.depthOrArrayLayers??this.texture.depth,i=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:o}),s=await this.readBuffer(e),a=await s.readAsync(0,i.byteLength);return s.destroy(),a.buffer instanceof ArrayBuffer?a.buffer:a.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(),ve.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=Kn[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=Qn(e);this._setTextureSubresources(t)}setTexture2DData(e,t=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let n=gt(t,e);this._setTextureSubresources(n)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=Jn(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=eo(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=to(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=ro(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:n,mipLevel:o}=t;switch(t.type){case"external-image":let{image:i,flipY:s}=t;this.texture.copyExternalImage({image:i,z:n,mipLevel:o,flipY:s});break;case"texture-data":let{data:a,textureFormat:u}=t;if(u&&u!==this.texture.format)throw new Error(`${this} mip level ${o} uses format "${u}" but texture format is "${this.texture.format}"`);this.texture.writeData(a.data,{x:0,y:0,z:n,width:a.width,height:a.height,depthOrArrayLayers:1,mipLevel:o});break;default:throw new Error("Unsupported 2D mip-level payload")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await no(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&ve.warn(`${this} already destroyed`)}_checkReady(){this.isReady||ve.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...ie.defaultProps,dimension:"2d",data:null,mipmaps:!1}};function cu(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 Qn(r.data);case"2d":return gt(0,r.data,e,t);case"3d":return Jn(r.data);case"2d-array":return eo(r.data);case"cube":return to(r.data);case"cube-array":return ro(r.data);default:throw new Error(`Unhandled dimension ${r.dimension}`)}}function du(r,e,t,n){if(e.length===0)return{subresources:e,mipLevels:1,format:n.format,hasExplicitMipChain:!1};let o=new Map;for(let d of e){let l=o.get(d.z)??[];l.push(d),o.set(d.z,l)}let i=e.some(d=>d.mipLevel>0),s=n.format,a=Number.POSITIVE_INFINITY,u=[];for(let[d,l]of o){let f=[...l].sort((w,S)=>w.mipLevel-S.mipLevel),h=f[0];if(!h||h.mipLevel!==0)throw new Error(`DynamicTexture: slice ${d} is missing mip level 0`);let m=Ai(r,h);if(m.width!==t.width||m.height!==t.height)throw new Error(`DynamicTexture: slice ${d} base level dimensions ${m.width}x${m.height} do not match expected ${t.width}x${t.height}`);let g=_i(h);if(g){if(s&&s!==g)throw new Error(`DynamicTexture: slice ${d} base level format "${g}" does not match texture format "${s}"`);s=g}let y=s&&r.isTextureFormatCompressed(s)?lu(r,m.width,m.height,s):r.getMipLevelCount(m.width,m.height),p=0;for(let w=0;w<f.length;w++){let S=f[w];if(!S||S.mipLevel!==w||w>=y)break;let T=Ai(r,S),v=Math.max(1,m.width>>w),b=Math.max(1,m.height>>w);if(T.width!==v||T.height!==b)break;let C=_i(S);if(C&&(s||(s=C),C!==s))break;p++,u.push(S)}a=Math.min(a,p)}let c=Number.isFinite(a)?Math.max(1,a):1;return{subresources:u.filter(d=>d.mipLevel<c),mipLevels:c,format:s,hasExplicitMipChain:i}}function _i(r){if(r.type==="texture-data")return r.textureFormat??Zn(r.data)}function Ai(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 lu(r,e,t,n){let{blockWidth:o=1,blockHeight:i=1}=r.getTextureFormatInfo(n),s=1;for(let a=1;;a++){let u=Math.max(1,e>>a),c=Math.max(1,t>>a);if(u<o||c<i)break;s++}return s}async function no(r){if(r=await r,Array.isArray(r))return await Promise.all(r.map(no));if(r&&typeof r=="object"&&r.constructor===Object){let e=r,t=await Promise.all(Object.values(e).map(no)),n=Object.keys(e),o={};for(let i=0;i<n.length;i++)o[n[i]]=t[i];return o}return r}var or=F(A(),1),Fi=/^vertex-list<([^<>]+)>$/,Ri=/^value-list<([^<>]+)>$/,bu=/^fixed-size-list<([^<>,]+),([1-9][0-9]*)>$/;function it(r){return Fi.test(r)}function st(r){return Ri.test(r)}function Vi(r){let e=Fi.exec(r),t=Ri.exec(r),o=Mi(r)?.elementFormat??e?.[1]??t?.[1]??r;try{or.vertexFormatDecoder.getVertexFormatInfo(o)}catch{throw new Error(`Unsupported GPUVector format ${r}`)}return o}function U(r){let e=Vi(r),t=it(r),n=st(r),o=Mi(r),i=or.vertexFormatDecoder.getVertexFormatInfo(e),s=i.byteLength*(o?.listSize??1);if(!Number.isSafeInteger(s))throw new Error(`Unsupported GPUVector format ${r}`);let a=i.type,u=i.normalized,c=xu(a,u);return{format:r,elementFormat:e,vertexList:t,valueList:n,fixedSizeList:!!o,...o?{listSize:o.listSize}:{},type:a,signedDataType:wu(e,a),primitiveType:c,components:i.components,elementByteLength:i.byteLength,byteLength:s,integer:i.integer,signed:i.signed,normalized:u,...i.webglOnly?{webglOnly:!0}:{}}}function Mi(r){let e=bu.exec(r);if(!e)return;let t=Number(e[2]);if(!Number.isSafeInteger(t))return;let n=e[1];try{let o=or.vertexFormatDecoder.getVertexFormatInfo(n);if(!Number.isSafeInteger(t*o.components)||!Number.isSafeInteger(t*o.byteLength))return}catch{return}return{elementFormat:n,listSize:t}}function xu(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 wu(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 io=F(A(),1),ir=class{buffer;format;length;byteOffset;byteStride;constructor(e){let t=io.vertexFormatDecoder.getVertexFormatInfo(e.format).byteLength,n=e.byteOffset??0,o=e.byteStride??t;if(oo(e.length,"GPUDataView length"),oo(n,"GPUDataView byteOffset"),oo(o,"GPUDataView byteStride"),o<t)throw new Error(`GPUDataView byteStride ${o} is smaller than ${e.format} byte length ${t}`);let i=e.length===0?0:(e.length-1)*o+t,s=n+i;if(!Number.isSafeInteger(i)||!Number.isSafeInteger(s))throw new Error("GPUDataView byte range must use safe integers");if(s>e.buffer.byteLength)throw new Error("GPUDataView exceeds its backing buffer byte length");this.buffer=e.buffer,this.format=e.format,this.length=e.length,this.byteOffset=n,this.byteStride=o}get elementByteLength(){return io.vertexFormatDecoder.getVertexFormatInfo(this.format).byteLength}get byteLength(){return this.length===0?0:(this.length-1)*this.byteStride+this.elementByteLength}};function oo(r,e){if(!Number.isSafeInteger(r)||r<0)throw new Error(`${e} must be a non-negative safe integer`)}var Gt=F(A(),1);function Yr(r){return!!(r&&typeof r=="object"&&r.type==="struct")}function zi(r,e){let t=Object.entries(r);if(t.length===0)throw new Error("GPUData struct format must declare at least one field");return e==="packed"?Tu(t):vu(t)}function Tu(r){let e=[],t=0,n=0;for(let[o,i]of r){let s=Gt.vertexFormatDecoder.getVertexFormatInfo(i);if(s.webglOnly)throw new Error(`Packed GPUData struct field "${o}" uses WebGL-only format ${i}`);t=Ni(t,Math.min(4,s.byteLength)),e.push([o,Object.freeze({format:i,byteOffset:t,byteLength:s.byteLength})]),t+=s.byteLength,n+=s.components}return Object.freeze({type:"struct",layout:"packed",fields:Object.freeze(Object.fromEntries(e)),components:n,byteStride:Ni(t,4),rowByteLength:t})}function vu(r){let e=Object.fromEntries(r.map(([s,a])=>[s,Su(a)])),t=(0,Gt.makeShaderBlockLayout)(e,{layout:"wgsl-storage"}),n=[],o=0,i=0;for(let[s,a]of r){let u=Gt.vertexFormatDecoder.getVertexFormatInfo(a),c=t.fields[s].offset*4;n.push([s,Object.freeze({format:a,byteOffset:c,byteLength:u.byteLength})]),o=Math.max(o,c+u.byteLength),i+=u.components}return Object.freeze({type:"struct",layout:"wgsl-storage",fields:Object.freeze(Object.fromEntries(n)),components:i,byteStride:t.byteLength,rowByteLength:o})}function Su(r){let e=Gt.vertexFormatDecoder.getVertexFormatInfo(r);switch(e.type){case"float32":return qr("f32",e.components);case"sint32":return qr("i32",e.components);case"uint32":return qr("u32",e.components);default:{let t=Math.ceil(e.byteLength/4);return qr("u32",t)}}}function qr(r,e){return e===1?r:`vec${e}<${r}>`}function Ni(r,e){return Math.ceil(r/e)*e}var so=class{buffer;ownsDataBuffer;constructor(e,t){this.buffer=e,this.ownsDataBuffer=t}get ownsBuffer(){return this.ownsDataBuffer}transferBufferOwnership(e){if(e.buffer!==this.buffer)throw new Error("GPUData ownership can only be transferred to the same buffer");e.ownsDataBuffer=this.ownsDataBuffer,this.ownsDataBuffer=!1}destroy(){this.ownsDataBuffer&&(this.buffer.destroy(),this.ownsDataBuffer=!1)}},ao=class extends so{dataType;format;length;valueLength;stride;byteOffset;byteStride;rowByteLength;readbackMetadata;valueOffsets;nullBitmap;valueByteLength;constructor(e){let{buffer:t,format:n,length:o,valueLength:i,stride:s,byteOffset:a=0,byteStride:u,rowByteLength:c,ownsBuffer:d=!1,readbackMetadata:l,valueOffsets:f,nullBitmap:h,valueByteLength:m,dataType:g}=e;super(t,d);let y;n?typeof n=="string"?y=n:y=zi(n,e.layout??"wgsl-storage"):y=void 0;let p=Yr(y)?y:void 0,w=typeof y=="string"?U(y):void 0;if(this.dataType=g,this.format=y,this.length=o,this.valueLength=i??o*(w?.listSize??1),this.stride=s??(w?w.components*(w.listSize??1):void 0)??p?.components??u??c??1,this.byteOffset=a,this.rowByteLength=c??p?.rowByteLength??w?.byteLength??u??this.stride,this.byteStride=u??p?.byteStride??this.rowByteLength,w?.fixedSizeList){let S=o*w.listSize;if(!Number.isSafeInteger(o)||o<0||!Number.isSafeInteger(S)||!Number.isSafeInteger(this.byteOffset)||this.byteOffset<0||!Number.isSafeInteger(this.byteStride)||!Number.isSafeInteger(this.rowByteLength)||!Number.isSafeInteger(this.stride))throw new Error("GPUData fixed-size-list row layout must use safe non-negative integers");if(this.valueLength!==S)throw new Error("GPUData fixed-size-list valueLength must equal its flattened row elements");if(this.stride<w.components*w.listSize)throw new Error("GPUData fixed-size-list stride cannot truncate its row components");if(this.rowByteLength<w.byteLength)throw new Error("GPUData fixed-size-list rowByteLength cannot truncate its row payload");if(this.byteStride<this.rowByteLength)throw new Error("GPUData fixed-size-list byteStride cannot overlap its row payload");let T=o===0?0:(o-1)*this.byteStride+this.rowByteLength,v=this.byteOffset+T;if(!Number.isSafeInteger(T)||!Number.isSafeInteger(v))throw new Error("GPUData fixed-size-list byte range must use safe integers");if(v>t.byteLength)throw new Error("GPUData fixed-size-list exceeds its backing buffer byte length")}if(p){if(this.rowByteLength<p.rowByteLength)throw new Error(`GPUData rowByteLength ${this.rowByteLength} is smaller than struct format row byte length ${p.rowByteLength}`);if(this.byteStride<Math.max(p.byteStride,this.rowByteLength))throw new Error(`GPUData byteStride ${this.byteStride} is smaller than its struct row layout`)}this.readbackMetadata=l,this.valueOffsets=f,this.nullBitmap=h,this.valueByteLength=m}getChild(e){if(!Yr(this.format))return null;let t=this.format.fields[e];return t?new ir({buffer:this.buffer,format:t.format,length:this.length,byteOffset:this.byteOffset+t.byteOffset,byteStride:this.byteStride}):null}getChildAt(e){if(!Yr(this.format))return null;let t=Object.values(this.format.fields)[e];return t?new ir({buffer:this.buffer,format:t.format,length:this.length,byteOffset:this.byteOffset+t.byteOffset,byteStride:this.byteStride}):null}},Dt=ao;function ze(r){let e=0;return Object.freeze(r.map(t=>{let n=Object.freeze({offset:e,length:t.length,data:t});return e+=t.length,n}))}var H=class{name;dataType;format;length;valueLength;stride;byteOffset;byteStride;rowByteLength;bufferLayout;data=[];device;bufferProps;isAppendable=!1;ownsDataChunks=!0;ownedVectors=[];appendableByteLength=0;get chunks(){return ze(this.data)}constructor(e){switch(e.type){case"buffer":{let{name:t,buffer:n,format:o,length:i,valueLength:s,byteOffset:a=0,ownsBuffer:u=!1}=e,{stride:c,byteStride:d,rowByteLength:l,listSize:f}=Wi(e),h=s??i*(f??1);this.name=t,this.dataType=e.dataType,this.format=o,this.length=i,this.valueLength=h,this.stride=c,this.byteOffset=a,this.byteStride=d,this.rowByteLength=l,this.data.push(new Dt({buffer:n,format:o,length:i,valueLength:h,stride:c,byteOffset:a,byteStride:d,rowByteLength:l,ownsBuffer:u,dataType:e.dataType}));return}case"interleaved":{let{name:t,buffer:n,format:o,length:i,valueLength:s,byteOffset:a=0,byteStride:u,attributes:c,ownsBuffer:d=!1}=e,l=o?U(o):void 0,f=s??i*(l?.listSize??1),h=l?.fixedSizeList?l.components*l.listSize:u,m=l?.fixedSizeList?l.byteLength:u;this.name=t,this.dataType=e.dataType,this.format=o,this.length=i,this.valueLength=f,this.stride=h,this.byteOffset=a,this.byteStride=u,this.rowByteLength=m,this.bufferLayout={name:t,byteStride:u,attributes:c},this.data.push(new Dt({buffer:n,format:o,length:i,valueLength:f,stride:h,byteOffset:a,byteStride:u,rowByteLength:m,ownsBuffer:d,dataType:e.dataType}));return}case"data":{let t=e.format??Eu(e.data),n=t?U(t):void 0,{name:o,data:i,stride:s=i[0]?.stride??(n?n.components*(n.listSize??1):1),valueLength:a=i.reduce((f,h)=>f+h.valueLength,0),byteStride:u=i[0]?.byteStride??n?.byteLength,rowByteLength:c=i[0]?.rowByteLength??n?.byteLength,bufferLayout:d,ownsData:l=!1}=e;if(u===void 0||c===void 0)throw new Error("GPUVector requires format or explicit byte layout metadata");t&&Pu(i,t),this.name=o,this.dataType=e.dataType,this.format=t,this.length=i.reduce((f,h)=>f+h.length,0),this.valueLength=a,this.stride=s,this.byteOffset=i.length===1?i[0].byteOffset:0,this.byteStride=u,this.rowByteLength=c,this.bufferLayout=d,this.ownsDataChunks=l,this.data.push(...i);return}case"appendable":{let{name:t,device:n,format:o,valueLength:i=0,bufferProps:s}=e,{stride:a,byteStride:u,rowByteLength:c}=Wi(e);this.name=t,this.dataType=e.dataType,this.format=o,this.length=0,this.valueLength=i,this.stride=a,this.byteOffset=0,this.byteStride=u,this.rowByteLength=c,this.device=n,this.bufferProps=s,this.isAppendable=!0;return}}}get ownsBuffer(){return this.ownsDataChunks&&this.data.some(e=>e.ownsBuffer)||this.ownedVectors.some(e=>e.ownsBuffer)}get capacityRows(){return this.isAppendable?this.length:void 0}get appendedByteLength(){return this.appendableByteLength}addData(e){if(this.format&&e.format!==this.format)throw new Error("GPUVector.addData() requires matching formats");if(e.byteStride!==this.byteStride)throw new Error("GPUVector.addData() requires matching byteStride");if(e.rowByteLength!==this.rowByteLength)throw new Error("GPUVector.addData() requires matching rowByteLength");return this.data.push(e),this.length+=e.length,this.valueLength+=e.valueLength,this}appendDataChunk(e,t=this.appendableByteLength+e.buffer.byteLength){if(!this.isAppendable)throw new Error("GPUVector.appendDataChunk() requires appendable vector storage");if(this.format&&e.format!==this.format)throw new Error("GPUVector.appendDataChunk() requires matching formats");if(e.byteStride!==this.byteStride||e.rowByteLength!==this.rowByteLength)throw new Error("GPUVector.appendDataChunk() requires matching byte layout metadata");return this.data.push(e),this.length+=e.length,this.valueLength+=e.valueLength,this.appendableByteLength=t,this}resetLastBatch(){if(!this.isAppendable)throw new Error("GPUVector.resetLastBatch() requires appendable vector storage");for(let e of this.data.splice(0))e.destroy();return this.length=0,this.valueLength=0,this.appendableByteLength=0,this}retainOwnedVectors(e){return this.ownedVectors.push(...e),this}transferBufferOwnership(e){let t=this.data[0],n=e.data[0];if(!t||!n||t.buffer!==n.buffer)throw new Error("GPUVector ownership can only be transferred to the same buffer");t.transferBufferOwnership(n)}destroy(){if(this.ownsDataChunks)for(let e of this.data)e.destroy();for(let e of this.ownedVectors.splice(0))e.destroy()}};function Wi(r){let e=r.format?U(r.format):void 0,t=r.rowByteLength??(e?.fixedSizeList?e.byteLength:r.byteStride)??e?.byteLength;if(t===void 0)throw new Error("GPUVector requires format or explicit rowByteLength");return{stride:r.stride??(e?e.components*(e.listSize??1):1),byteStride:r.byteStride??t,rowByteLength:t,...e?.listSize?{listSize:e.listSize}:{}}}function Eu(r){return r[0]?.format}function Pu(r,e){if(r.find(n=>n.format!==e))throw new Error("GPUVector data chunks must share the declared format")}var uo=F(A(),1);var sr=F(A(),1);var ar=class{buffer;format;length;valueLength;byteOffset;byteStride;rowByteLength;valueOffsets;nullBitmap;constructor(e){let t=U(e.format),n=ArrayBuffer.isView(e.buffer)?e.buffer:void 0;this.buffer=n?n.buffer:e.buffer,this.format=e.format,this.length=e.length,this.valueLength=e.valueLength??e.length*(t.listSize??1);let o=e.byteOffset??0;this.byteOffset=(n?.byteOffset??0)+o,this.rowByteLength=e.rowByteLength??t.byteLength,this.byteStride=e.byteStride??this.rowByteLength,this.valueOffsets=e.valueOffsets,this.nullBitmap=e.nullBitmap;let i=t.vertexList||t.valueList,s=i?this.valueLength:this.length;(0,sr.assert)([this.length,this.valueLength,o,this.rowByteLength,this.byteStride].every(a=>Number.isSafeInteger(a)&&a>=0)),(0,sr.assert)(this.rowByteLength>=t.byteLength&&this.byteStride>=this.rowByteLength),(0,sr.assert)(i||this.valueLength===this.length*(t.listSize??1)),(0,sr.assert)(o+(s?(s-1)*this.byteStride+this.rowByteLength:0)<=e.buffer.byteLength)}};var ji=F(A(),1),Ee=class{name;format;data;length;valueLength;constructor(e){(0,ji.assert)(e.data.every(t=>t.format===e.format)),this.name=e.name??"",this.format=e.format,this.data=Object.freeze([...e.data]),this.length=this.data.reduce((t,n)=>t+n.length,0),this.valueLength=this.data.reduce((t,n)=>t+n.valueLength,0)}};var ur=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 n=Math.floor((t-1)/2);if(this.compare(this.values[n],e)<=0)break;this.values[t]=this.values[n],t=n}this.values[t]=e}pop(){let e=this.values[0],t=this.values.pop();if(this.values.length&&t!==void 0){let n=0;for(;n*2+1<this.values.length;){let o=n*2+1;if(o+1<this.values.length&&this.compare(this.values[o+1],this.values[o])<0&&o++,this.compare(t,this.values[o])<=0)break;this.values[n]=this.values[o],n=o}this.values[n]=t}return e}};var at=F(A(),1);function Ki(r){let e=es(r.nodes),t=ts(e,r.buffers.values()),n=rs(e,r.textures.values()),o=new Map,i=new Map,s=[];try{for(let a of t){a.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(a)}`,byteLength:a.byteLength,usage:a.usage});for(let u of a.handles)o.set(u,a.buffer)}for(let a of n){a.texture=r.device.createTexture({...a.descriptor,id:`${r.id}-transient-texture-${n.indexOf(a)}`});for(let u of a.handles)i.set(u,a.texture)}for(let a of e)s.push({node:a,executable:a.compile({device:r.device})})}catch(a){for(let u of s)u.executable.destroy?.();for(let u of t)u.buffer?.destroy();for(let u of n)u.texture?.destroy();throw a}return Qi(r,e,s,o,i,t,n)}async function Zi(r){let e=es(r.nodes),t=ts(e,r.buffers.values()),n=rs(e,r.textures.values()),o=new Map,i=new Map;try{for(let h of t){h.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(h)}`,byteLength:h.byteLength,usage:h.usage});for(let m of h.handles)o.set(m,h.buffer)}for(let h of n){h.texture=r.device.createTexture({...h.descriptor,id:`${r.id}-transient-texture-${n.indexOf(h)}`});for(let m of h.handles)i.set(m,h.texture)}let s=at.PipelineFactory.beginAsyncCompilation(r.device),a=e.map(async h=>({node:h,executable:h.compileAsync?await h.compileAsync({device:r.device}):h.compile({device:r.device})}));at.PipelineFactory.endAsyncCompilation(r.device,s);let[u,c]=await Promise.all([Promise.allSettled(a),Promise.allSettled(s)]),d=[],l=c.find(h=>h.status==="rejected"),f=l?.status==="rejected"?l.reason:void 0;for(let h of u)h.status==="fulfilled"?d.push(h.value):f??=h.reason;if(f){for(let h of d)h.executable.destroy?.();throw f}return Qi(r,e,d,o,i,t,n)}catch(s){for(let a of t)a.buffer?.destroy();for(let a of n)a.texture?.destroy();throw s}}function Qi(r,e,t,n,o,i,s){let a=Array.from(r.buffers.values()),u=a.filter(E=>!E.transient),c=a.filter(E=>E.transient),d=_t(u.map(E=>E.byteLength),"imported buffer capacities"),l=_t(c.map(E=>E.byteLength),"logical transient buffer capacities"),f=yt(d,l,"logical buffer capacities"),h=_t(i.map(E=>E.byteLength),"physical transient buffer capacities"),m=Math.max(0,l-h),g=Array.from(r.textures.values()),y=g.filter(E=>!E.transient),p=g.filter(E=>E.transient),w=_t(y.map(ho),"imported texture estimates"),S=_t(p.map(ho),"logical transient texture estimates"),T=yt(w,S,"logical texture estimates"),v=_t(s.map(E=>E.byteLength),"physical transient texture estimates"),b=Math.max(0,S-v),C={nodeOrder:e.map(E=>E.id),importedBufferCount:u.length,importedBufferBytes:d,logicalBufferCount:a.length,logicalBufferBytes:f,logicalTransientBufferCount:c.length,physicalTransientBufferCount:i.length,logicalTransientBytes:l,physicalTransientBytes:h,reusedTransientBytes:m,reusePercentage:l>0?m/l*100:0,importedTextureCount:y.length,importedTextureBytes:w,logicalTextureCount:g.length,logicalTextureBytes:T,logicalTransientTextureCount:p.length,physicalTransientTextureCount:s.length,logicalTransientTextureBytes:S,physicalTransientTextureBytes:v,reusedTransientTextureBytes:b,textureReusePercentage:S>0?b/S*100:0,logicalResourceBytes:yt(f,T,"logical resource estimates"),physicalTransientResourceBytes:yt(h,v,"physical transient resource estimates")},B=Lu(r.device,a,e,r.kernelMetadata);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:n,transientTextures:o,bufferTransientAllocations:i,textureTransientAllocations:s,stats:C,preflight:B}}function Cu(r){if("buffer"in r){let t=r.buffer,n="buffer"in t?t:void 0;return Object.freeze({id:n?n.buffer.id:t.id,kind:"buffer",usage:r.usage,byteOffset:n?.byteOffset??0,byteLength:n?n.length===0?0:(n.length-1)*n.byteStride+n.rowByteLength:t.byteLength,...n?{format:n.format,length:n.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 Lu(r,e,t,n){let o=t.map(u=>{let c=u.workload??{},d=n&&u.type==="compute"?u.kernel:void 0;return Object.freeze({id:u.id,...u.description===void 0?{}:{description:u.description},type:u.type,...d&&{kernel:Object.freeze({entryPoint:d.entryPoint,workgroupSize:Object.freeze([...d.workgroupSize]),bindings:Object.freeze(d.bindings.map(({name:l,type:f,group:h,location:m})=>Object.freeze({name:l,type:f,group:h,location:m}))),...n==="source"&&d.source!==void 0?{source:d.source}:{}})},resources:Object.freeze((u.resources??[]).map(Cu)),...c.operation?{operation:c.operation}:{},...c.variant?{variant:c.variant}:{},...u.publication?{publication:Object.freeze({...u.publication})}:{},...u.condition?{condition:Object.freeze(u.condition.source==="cpu"?{id:u.condition.id,source:"cpu",mode:"skip"}:{id:u.condition.id,source:"gpu",mode:"indirect",bufferId:u.condition.buffer.id,byteOffset:u.condition.byteOffset??0})}:{},commandCount:c.commandCount??0,maximumWorkgroupCount:c.maximumWorkgroupCount??0,maximumInvocationCount:c.maximumInvocationCount??0,readByteLength:c.readByteLength??0,writeByteLength:c.writeByteLength??0})}),i=e.reduce((u,c)=>Math.max(u,c.byteLength),0),s=t.reduce((u,c)=>{for(let d of c.resources??[])ut(d)&&(d.usage==="storage-read"||d.usage==="storage-write"||d.usage==="storage-read-write")&&(u=Math.max(u,lo(d.buffer).size));return u},0),a=u=>o.reduce((c,d)=>{let l=d[u];return typeof l=="number"?yt(c,l,"workload estimates"):c},0);return Object.freeze({nodes:Object.freeze(o),annotatedNodeCount:t.filter(u=>u.workload!==void 0).length,conditionalNodeCount:t.filter(u=>u.condition!==void 0).length,commandCount:a("commandCount"),maximumWorkgroupCount:a("maximumWorkgroupCount"),maximumInvocationCount:a("maximumInvocationCount"),readByteLength:a("readByteLength"),writeByteLength:a("writeByteLength"),largestBufferByteLength:i,largestStorageBufferBindingByteLength:s,maxBufferByteLength:r.limits.maxBufferSize,maxStorageBufferBindingByteLength:r.limits.maxStorageBufferBindingSize,fitsDeviceLimits:i<=r.limits.maxBufferSize&&s<=r.limits.maxStorageBufferBindingSize})}function Pe(r){return"buffer"in r?r.buffer:r}function We(r){return"texture"in r?r.texture:r}function ut(r){return"buffer"in r}function cr(r){return"texture"in r}function Ji(r){if(r.type==="copy")return;let e=(r.resources??[]).filter(t=>ut(t)&&(t.usage==="storage-read"||t.usage==="storage-write"||t.usage==="storage-read-write"));for(let t=0;t<e.length;t++){let n=e[t];for(let o=t+1;o<e.length;o++){let i=e[o];if(n.buffer===i.buffer||Pe(n.buffer)!==Pe(i.buffer)||!fo(n.usage)&&!fo(i.usage))continue;let s=lo(n.buffer),a=lo(i.buffer);if(s.offset<a.offset+a.size&&a.offset<s.offset+s.size){let u=Pe(n.buffer);throw new Error(`GPUCommandGraph node "${r.id}" has overlapping writable storage bindings for buffer "${u.id}" (${Hi(s)} and ${Hi(a)}). Bind the shared range once or align the views to non-overlapping storage binding ranges.`)}}}}function lo(r){if(!("buffer"in r))return{offset:0,size:r.byteLength};let e=256,t=Math.floor(r.byteOffset/e)*e,n=r.byteOffset-t,o=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:t,size:n+Math.max(o,r.rowByteLength)}}function Hi(r){return`${r.offset}\u2013${r.offset+r.size} bytes`}function Bu(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 qi(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 es(r){let e=new Map(r.map(l=>[l.id,l])),t=new Map,n=new Map,o=new Map,i=new Map;for(let l of r){let f=new Set(l.dependsOn??[]);for(let h of f)if(!e.has(h))throw new Error(`GPUCommandGraph node "${l.id}" depends on missing node "${h}"`);for(let h of l.resources??[])if(ut(h)){let m=Pe(h.buffer);if(Bu(h.usage)){let g=n.get(m);g&&f.add(g);let y=o.get(m)??new Set;y.add(l.id),o.set(m,y)}if(fo(h.usage)){let g=n.get(m);g&&f.add(g);for(let y of o.get(m)??[])y!==l.id&&f.add(y);o.set(m,new Set),n.set(m,l.id)}}else if(cr(h)){let m=We(h.texture),g=i.get(m)??[];for(let y of g)y.nodeId!==l.id&&Ou(y.resource,h)&&(qi(h.usage)&&co(y.resource.usage)||co(h.usage)&&(qi(y.resource.usage)||co(y.resource.usage)))&&f.add(y.nodeId);g.push({nodeId:l.id,resource:h}),i.set(m,g)}f.delete(l.id),t.set(l.id,f)}let s=r.map(()=>[]),a=new Map(r.map((l,f)=>[l.id,f])),u=r.map(l=>t.get(l.id).size);for(let[l,f]of r.entries())for(let h of t.get(f.id))s[a.get(h)].push(l);let c=u.flatMap((l,f)=>l===0?[f]:[]),d=[];for(;c.length;){let l=[];for(let f of c){d.push(r[f]);for(let h of s[f])--u[h]===0&&l.push(h)}c=l.sort((f,h)=>f-h)}if(d.length!==r.length)throw new Error("GPUCommandGraph contains a dependency cycle");return d}function Ou(r,e){let t=We(r.texture),n=We(e.texture);if(t!==n)return!1;let o=Yi(r.texture),i=Yi(e.texture);return $u(o.aspect,i.aspect)&&Xi(o.baseMipLevel,o.mipLevelCount,i.baseMipLevel,i.mipLevelCount)&&Xi(o.baseArrayLayer,o.arrayLayerCount,i.baseArrayLayer,i.arrayLayerCount)}function Yi(r){return"texture"in r?r:{aspect:"all",baseMipLevel:0,mipLevelCount:r.mipLevels,baseArrayLayer:0,arrayLayerCount:r.dimension==="3d"?1:r.depth}}function $u(r,e){return r==="all"||e==="all"||r===e}function Xi(r,e,t,n){return r<t+n&&t<r+e}function ts(r,e){let t=ns(r,c=>ut(c)?Pe(c.buffer):null),n=new Map;r.forEach((c,d)=>{if(!c.retainedBuffers?.length)return;let l=n.get(c.retainedBuffers);l?l.lastUse=d:n.set(c.retainedBuffers,{firstUse:d,lastUse:d})});for(let[c,d]of n)for(let l of c){if(!l.transient)continue;let f=t.get(l);t.set(l,{firstUse:Math.min(f?.firstUse??d.firstUse,d.firstUse),lastUse:Math.max(f?.lastUse??d.lastUse,d.lastUse)})}let o=[],i=Array.from(e).filter(c=>c.transient).map(c=>({buffer:c,lifetime:t.get(c)})).sort((c,d)=>(c.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(d.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)),s=new ur((c,d)=>c.allocation.lastUse-d.allocation.lastUse||c.index-d.index),a=new Map,u=c=>{let d=c&(at.Buffer.MAP_READ|at.Buffer.MAP_WRITE),l=a.get(d);return l||(l=new ur((f,h)=>f.allocation.byteLength-h.allocation.byteLength||f.index-h.index),a.set(d,l)),l};for(let{buffer:c,lifetime:d}of i){if(!d)continue;for(;s.peek()&&s.peek().allocation.lastUse<d.firstUse;){let h=s.pop();u(h.allocation.usage).push(h)}let l=u(c.usage).pop();l||(l={allocation:{byteLength:0,usage:0,lastUse:-1,handles:[]},index:o.length},o.push(l.allocation));let{allocation:f}=l;f.byteLength=Math.max(f.byteLength,c.byteLength),f.usage|=c.usage,f.lastUse=d.lastUse,f.handles.push(c),s.push(l)}return o}function rs(r,e){let t=ns(r,i=>cr(i)?We(i.texture):null),n=[],o=Array.from(e).filter(i=>i.transient).map(i=>({texture:i,lifetime:t.get(i)})).sort((i,s)=>(i.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(s.lifetime?.firstUse??Number.MAX_SAFE_INTEGER));for(let{texture:i,lifetime:s}of o){if(!s)continue;let a=n.find(u=>u.lastUse<s.firstUse&&Iu(u.descriptor,i));a||(a={descriptor:ku(i),byteLength:ho(i),lastUse:-1,handles:[]},n.push(a)),a.descriptor.usage|=i.usage,a.lastUse=s.lastUse,a.handles.push(i)}return n}function ns(r,e){let t=new Map;return r.forEach((n,o)=>{for(let i of n.resources??[]){let s=e(i);if(!s||!("transient"in s)||!s.transient)continue;let a=t.get(s);a?a.lastUse=o:t.set(s,{firstUse:o,lastUse:o})}}),t}function ku(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 Iu(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 ho(r){let e=0;for(let n=0;n<r.mipLevels;n++)e=yt(e,at.textureFormatDecoder.computeMemoryLayout({format:r.format,width:Math.max(1,r.width>>n),height:r.dimension==="1d"?1:Math.max(1,r.height>>n),depth:r.dimension==="3d"?Math.max(1,r.depth>>n):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 yt(r,e,t){let n=r+e;if(!Number.isSafeInteger(n))throw new Error(`GPUCommandGraph ${t} exceed safe integer range`);return n}function _t(r,e){return r.reduce((t,n)=>yt(t,n,e),0)}var je=class{id;byteLength;usage;transient;graph;defaultBuffer;constructor(e,t,n,o){this.graph=e,this.id=t.id,this.byteLength=t.byteLength,this.usage=t.usage,this.transient=n,this.defaultBuffer=o}},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}},O=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,n)=>t+n.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=ze(this.data)}},Ce=class{id;format;width;height;usage;dimension;depth;mipLevels;samples;transient;frameScoped;graph;defaultTexture;constructor(e,t,n,o,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=n,this.frameScoped=i,this.defaultTexture=o}},ct=class{id;width;height;graph;constructor(e,t){this.graph=e,this.id=t.id,this.width=t.width,this.height=t.height}},_e=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 mo(r,e){switch(e.type){case"compute":{let{type:t,...n}=e;r.addComputePass(n);return}case"render":{let{type:t,...n}=e;r.addRenderPass(n);return}case"copy":{let{type:t,...n}=e;r.addCopyPass(n);return}}}function He(r,e){for(let t of e)mo(r,t)}function V(r){return{...r,type:"compute"}}var Uu=4,At=class{nodeCount;budget;plan;encodeNodeRange;nextStepIndex=0;currentPublishedProgress=0;constructor(e){cs(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 n=this.plan.steps[this.nextStepIndex],o=this.encodeNodeRange(e,t,n.firstNodeIndex,n.nextNodeIndex);return this.nextStepIndex++,n.publishable&&(this.currentPublishedProgress=this.progress),{...n,encoding:o,progress:this.progress,completed:this.completed,publishedProgress:this.publishedProgress}}};function Kr(r,e,t={}){cs(e);let n=t.latencyPriority??"normal",o=t.publicationPolicy??"final";if(!["interactive","normal","background"].includes(n))throw new Error(`GPUCommandGraph execution latency priority "${n}" is invalid`);if(!["final","progressive"].includes(o))throw new Error(`GPUCommandGraph execution publication policy "${o}" is invalid`);let i=r.nodes,s=[],a=0;for(;a<i.length;){let c=a,d=os();for(;a<i.length;){let h=is(d,i[a]);if(a>c&&ss(h,e)||(d=h,a++,o==="progressive"&&i[a-1].publication)||Gu(d,e))break}let l=Object.freeze(o==="progressive"?i.slice(c,a).flatMap(h=>h.publication?[h.publication]:[]):[]),f=a===i.length;s.push(Object.freeze({stepIndex:s.length,firstNodeIndex:c,nextNodeIndex:a,...d,exceedsBudget:ss(d,e),latencyPriority:n,publications:l,publishable:f||l.length>0}))}let u=i.reduce((c,d)=>is(c,d),os());return Object.freeze({...u,annotatedNodeCount:r.annotatedNodeCount,stepCount:s.length,oversizedStepCount:s.filter(c=>c.exceedsBudget).length,latencyPriority:n,publicationPolicy:o,publicationCount:s.reduce((c,d)=>c+d.publications.length,0),steps:Object.freeze(s)})}function os(){return{nodeCount:0,commandCount:0,maximumInvocationCount:0,readByteLength:0,writeByteLength:0,conditionalNodeCount:0}}function is(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 ss(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 Gu(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 cs(r){let e=[["maximumInvocationCount",r.maximumInvocationCount],["maximumNodeCount",r.maximumNodeCount],["maximumCommandCount",r.maximumCommandCount],["maximumReadByteLength",r.maximumReadByteLength],["maximumWriteByteLength",r.maximumWriteByteLength]];for(let[t,n]of e)if(n!==void 0&&(!Number.isSafeInteger(n)||n<=0))throw new Error(`GPUCommandGraph execution ${t} must be a positive safe integer`)}function Du(r,e,t,n){let o=0;return{computePass:new Proxy(r,{get(s,a){if(a==="dispatch")return()=>{if(o>0)throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must encode exactly one dispatch`);o++,s.dispatchIndirect(e,t)};if(a==="dispatchIndirect")return()=>{throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must use dispatch(); the graph supplies its indirect command`)};let u=Reflect.get(s,a,s);return typeof u=="function"?u.bind(s):u}}),assertDispatched:()=>{if(o!==1)throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must encode exactly one dispatch`)}}}var Ft=class{readResource;stats;canReadGPUTimings;nodes;constructor(e,t,n=e.filter(a=>a.stats.type==="compute"&&a.stats.condition?.outcome!=="skipped").length,o,i,s){this.readResource=s,this.nodes=e,this.canReadGPUTimings=e.some(c=>c.timestamp!==void 0);let a=e.filter(c=>c.stats.condition?.outcome!=="skipped"),u=a.filter(c=>c.stats.type==="compute").length;this.stats={cpuEncodeTimeMilliseconds:t,cpuEncodeStartTimeMilliseconds:o,cpuEncodeEndTimeMilliseconds:i,nodeCount:a.length,skippedNodeCount:e.length-a.length,computePassCount:n,coalescedComputeNodeCount:u-n,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:s,timestamp:a})=>{if(!a)return{...s};let{querySet:u,snapshot:c,beginIndex:d,endIndex:l}=a;if(u.device.type!=="webgpu")return{...s,gpuTimeMilliseconds:await u.readTimestampDuration(d,l)};let f=await(c??u).readResults({firstQuery:d,queryCount:l-d+1}),h=f[0],m=f[f.length-1];return{...s,gpuStartTimeMilliseconds:Number(h)/1e6,gpuEndTimeMilliseconds:Number(m)/1e6,gpuTimeMilliseconds:Number(m-h)/1e6}})),t=e.filter(s=>s.gpuTimeMilliseconds!==void 0),n=e.filter(s=>s.gpuStartTimeMilliseconds!==void 0),i=this.nodes.flatMap(s=>s.timestamp?.snapshot?.clockCorrelation?[s.timestamp.snapshot.clockCorrelation]:[]).sort((s,a)=>s.uncertaintyMilliseconds-a.uncertaintyMilliseconds)[0];return{...i?{clockCorrelation:i}:{},cpuEncodeStartTimeMilliseconds:this.stats.cpuEncodeStartTimeMilliseconds,cpuEncodeEndTimeMilliseconds:this.stats.cpuEncodeEndTimeMilliseconds,...n.length>0?{gpuStartTimeMilliseconds:Math.min(...n.map(s=>s.gpuStartTimeMilliseconds)),gpuEndTimeMilliseconds:Math.max(...n.map(s=>s.gpuEndTimeMilliseconds))}:{},cpuEncodeTimeMilliseconds:this.stats.cpuEncodeTimeMilliseconds,...t.length>0?{gpuTimeMilliseconds:t.reduce((s,a)=>s+(a.gpuTimeMilliseconds??0),0)}:{},nodes:e}}},go=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={}){Xr(e,"construction"),this.device=e,this.id=t.id??"gpu-command-graph",this.autotuner=t.autotuner}importBuffer(e,t){this.assertMutable(),us(e,this.device),t&&ds(t,e,this.device);let n=this.addBuffer(new je(this,e,!1,t));if(t){let o=fr(t);this.importedBufferHandles.has(o)||this.importedBufferHandles.set(o,n),t instanceof Se&&!this.dynamicBufferHandles.has(t)&&this.dynamicBufferHandles.set(t,n)}return n}createTransientBuffer(e){return this.assertMutable(),us(e,this.device),this.addBuffer(new je(this,e,!0))}getUniqueResourceId(e){let t=e,n=1;for(;this.buffers.has(t)||this.textures.has(t)||this.externalTextures.has(t);)t=`${e}-${n++}`;return t}createDataView(e,t){this.assertBuffer(e);let n=U(t.format),o=t.byteOffset??0,i=t.rowByteLength??n.byteLength,s=t.byteStride??i;return Mu(e,{length:t.length,byteOffset:o,byteStride:s,rowByteLength:i}),new De(e,{format:t.format,length:t.length,byteOffset:o,byteStride:s,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 n=t.format??t.data[0]?.format;if(!n)throw new Error(`GPUCommandGraph import "${e}" requires GPUVector.format`);if(it(n)||st(n))throw new Error(`GPUCommandGraph import "${e}" requires a fixed-width GPUVector format`);let o=U(n),i=t.data.map((s,a)=>{if(s.format!==n)throw new Error(`GPUCommandGraph import "${e}" requires matching GPUVector chunk formats`);let u=t.data.length===1?e:`${e}-chunk-${a}`;return this.importGPUDataView(u,s)});return new O({id:e,name:t.name??e,format:n,length:t.length,valueLength:t.valueLength??t.data.reduce((s,a)=>s+a.valueLength,0),stride:t.stride??t.data[0]?.stride??o.components*(o.listSize??1),byteStride:t.byteStride??i[0]?.byteStride??o.byteLength,rowByteLength:t.rowByteLength??i[0]?.rowByteLength??o.byteLength,data:i})}importTexture(e,t){this.assertMutable();let n=po(e,this.device);return t&&bo(t,n,this.device),this.addTexture(new Ce(this,n,!1,t))}importFrameTexture(e){this.assertMutable();let t=po(e,this.device);return this.addTexture(new Ce(this,t,!1,void 0,!0))}importExternalTexture(e){return this.assertMutable(),Ru(e,this.device),this.addExternalTexture(new ct(this,e))}createTransientTexture(e){this.assertMutable();let t=po(e,this.device);return this.addTexture(new Ce(this,t,!0))}createTextureView(e,t={}){this.assertTexture(e);let n=Vu(e,t);return new _e(e,n)}add(e){if(this.assertMutable(),"getNodes"in e)for(let t of e.getNodes())this.add(t);else if("getCommandNodes"in e)He(this,e.getCommandNodes(this));else if("type"in e)mo(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(n=>({texture:n,usage:"render-attachment"})),...(e.attachments.resolveTargets??[]).filter(n=>n!==null).map(n=>({texture:n,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(e={}){return this.assertMutable(),Xr(this.device,"compilation"),this.compiled=!0,new bt(Ki({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes,kernelMetadata:e.kernelMetadata}))}async compileAsync(e={}){return this.assertMutable(),Xr(this.device,"compilation"),this.compiled=!0,new bt(await Zi({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes,kernelMetadata:e.kernelMetadata}))}addNode(e){if(this.device.type!=="webgpu"&&e.type!=="render")throw new Error("WebGL graphs support render passes only");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,n]of Object.entries(e.workload??{}))if(t==="operation"||t==="variant"){if(typeof n!="string"||!n)throw new Error(`GPUCommandGraph node "${e.id}" workload ${t} must be nonempty`)}else if(typeof n!="number"||!Number.isSafeInteger(n)||n<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 n=t.byteOffset??0;if(!Number.isSafeInteger(n)||n<0||n%4!==0)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition byteOffset must be a nonnegative multiple of 4`);if(n+3*Uu>t.buffer.byteLength)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition indirect command exceeds buffer "${t.buffer.id}"`);(e.resources??[]).some(o=>ut(o)&&Pe(o.buffer)===t.buffer&&o.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(ut(t)){let n=Pe(t.buffer);this.assertBuffer(n),zu(n,t.usage)}else if(cr(t)){let n=We(t.texture);if(this.assertTexture(n),Wu(n,t.usage),ju(t.texture,t.usage),this.device.type==="webgl"&&t.usage==="sampled"&&t.texture instanceof _e&&!ls(t.texture))throw new Error("WebGL sampled textures require a full-resource view")}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")}Ji(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 n=fr(t.buffer),o={byteLength:_u(t),usage:n.usage},i=t.buffer instanceof Se?this.getDynamicBufferHandle(t.buffer,o):this.getImportedBufferHandle(n,o);return i||(i=this.importBuffer({id:e,byteLength:n.byteLength,usage:n.usage},t.buffer),t.buffer instanceof Se?this.dynamicBufferHandles.set(t.buffer,i):this.importedBufferHandles.set(n,i)),this.createDataView(i,{format:t.format,length:t.length,byteOffset:t.byteOffset,byteStride:t.byteStride,rowByteLength:t.rowByteLength})}getDynamicBufferHandle(e,t){let n=this.dynamicBufferHandles.get(e);if(n?.defaultBuffer===e&&dr(n,t))return n;this.dynamicBufferHandles.delete(e);for(let o of this.buffers.values())if(o.defaultBuffer===e&&dr(o,t))return this.dynamicBufferHandles.set(e,o),o}getImportedBufferHandle(e,t){let n=this.importedBufferHandles.get(e);if(n?.defaultBuffer&&fr(n.defaultBuffer)===e&&dr(n,t))return n;this.importedBufferHandles.delete(e);for(let[o,i]of this.dynamicBufferHandles)if(o.buffer===e&&dr(i,t))return this.importedBufferHandles.set(e,i),i;for(let o of this.buffers.values())if(o.defaultBuffer===e&&dr(o,t))return this.importedBufferHandles.set(e,o),o}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 n=[...t.colorAttachments,...t.depthStencilAttachment?[t.depthStencilAttachment]:[]];for(let s of n)if(this.assertTexture(s.texture),s.dimension!=="2d"||s.mipLevelCount!==1||s.arrayLayerCount!==1)throw new Error(`GPUCommandGraph render node "${e}" attachments must be single-mip, single-layer 2d views`);let[o,...i]=n;for(let s of i)if(s.width!==o.width||s.height!==o.height||s.texture.samples!==o.texture.samples)throw new Error(`GPUCommandGraph render node "${e}" attachments must have matching extent and samples`);this.validateResolveTargets(e,t)}validateResolveTargets(e,t){let n=t.resolveTargets;if(n){if(this.device.type!=="webgpu")throw new Error(`GPUCommandGraph render node "${e}" resolve targets require WebGPU`);if(n.length!==t.colorAttachments.length)throw new Error(`GPUCommandGraph render node "${e}" requires one resolve entry per color attachment`);for(let o=0;o<n.length;o++){let i=n[o];if(!i)continue;let s=t.colorAttachments[o];if(this.assertTexture(i.texture),s.texture.samples<=1||i.texture.samples!==1||s.format!==i.format||s.width!==i.width||s.height!==i.height)throw new Error(`GPUCommandGraph render node "${e}" resolve target ${o} 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`)}}}},bt=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 n of t.resources??[])if(ut(n)){let o=Pe(n.buffer);o.transient||(this.activeImportedBufferHandles.add(o),(n.usage==="storage-write"||n.usage==="storage-read-write"||n.usage==="copy-destination")&&this.writableImportedBufferHandles.add(o))}else if(cr(n)){let o=We(n.texture);o.transient||(this.activeImportedTextureHandles.add(o),(n.usage==="storage-write"||n.usage==="storage-read-write"||n.usage==="render-attachment"||n.usage==="copy-destination")&&this.writableImportedTextureHandles.add(o))}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=Fu(this.device)}encode(e,t){return this.encodeNodeRange(e,t,0,this.compiledNodes.length)}getExecutionPlan(e,t={}){return Kr(this.preflight,e,t)}createExecution(e,t={}){return new At({plan:this.getExecutionPlan(e,t),budget:e,encodeNodeRange:(n,o,i,s)=>this.encodeNodeRange(n,o,i,s)})}encodeNodeRange(e,t,n,o){if(this.destroyed)throw new Error(`CompiledGPUCommandGraph "${this.id}" has been destroyed`);if(Xr(this.device,"encoding"),e.device!==this.device)throw new Error("GPUCommandGraph command encoder must belong to the graph device");let i=lr(),s=this.resolveImportedBuffers(t.buffers??{});Au(t.frameTextures??{},t.externalTextures??{});let a=this.resolveImportedTextures(t.textures??{},t.frameTextures??{}),u=this.resolveExternalTextures(t.externalTextures??{});for(let[v,b]of a.frameIds)this.lastFrameIds.set(v,b);for(let[v,b]of u.frameIds)this.lastExternalTextureFrameIds.set(v,b);for(let v of u.textures.values())this.consumedExternalTextures.add(v);let c=a.textures,d=v=>{let b=Pe(v),C=b.transient?this.transientBuffers.get(b):s.get(b);if(!C)throw new Error(`GPUCommandGraph buffer "${b.id}" is not bound`);return C},l=v=>{let b=We(v),C=b.transient?this.transientTextures.get(b):c.get(b);if(!C)throw new Error(`GPUCommandGraph texture "${b.id}" is not bound`);return C},f=v=>{let b=l(v);if(v instanceof Ce||ls(v))return b.view;if(v.texture.frameScoped){let E=this.lastFrameIds.get(v.texture);for(let $=this.cachedTextureViews.length-1;$>=0;$--){let L=this.cachedTextureViews[$];L.logicalView===v&&L.frameId!==E&&(this.destroyFramebuffersUsingView(L.view),L.view.destroy(),this.cachedTextureViews.splice($,1))}}let C=this.cachedTextureViews.find(E=>E.logicalView===v&&E.texture===b&&(!v.texture.frameScoped||E.frameId===this.lastFrameIds.get(v.texture)));if(C)return C.view;let B=b.createView({format:v.format,dimension:v.dimension,aspect:v.aspect,baseMipLevel:v.baseMipLevel,mipLevelCount:v.mipLevelCount,baseArrayLayer:v.baseArrayLayer,arrayLayerCount:v.arrayLayerCount});return this.cachedTextureViews.push({logicalView:v,texture:b,view:B,...v.texture.frameScoped?{frameId:this.lastFrameIds.get(v.texture)}:{}}),B},h=v=>{let b=u.textures.get(v);if(!b)throw new Error(`GPUCommandGraph external texture "${v.id}" is not bound`);return b},m={commandEncoder:e,parameters:t.parameters,getBuffer:d,getTexture:l,getTextureView:f,getExternalTexture:h},g=[],y,p=0,w=t.coalesceComputePasses!==!1&&e.getTimeProfilingQuerySet()===null,S=()=>{let v=y;y=void 0,v?.end()};try{for(let v=n;v<o;v++){let{node:b,executable:C}=this.compiledNodes[v],B=lr();if(b.condition?.source==="cpu"){let L=!1;try{L=b.condition.evaluate(t.parameters)}catch(_){let W=_ instanceof Error?_.message:String(_);throw new Error(`GPUCommandGraph CPU condition "${b.condition.id}" failed for node "${b.id}": ${W}`)}if(!L){let _=lr();g.push({stats:{id:b.id,description:b.description,resources:this.preflight.nodes[v].resources,operation:b.workload?.operation,type:b.type,cpuEncodeStartTimeMilliseconds:B,cpuEncodeEndTimeMilliseconds:_,cpuEncodeTimeMilliseconds:_-B,hasGPUTimestamps:!1,condition:{id:b.condition.id,source:"cpu",outcome:"skipped"}}});continue}}let E;switch(b.type){case"compute":{y||(y=e.beginComputePass({id:b.id}),p++);let L=y;E=as(L,e),E&&(w=!1),L.pushDebugGroup(b.id);try{let _=b.condition?.source==="gpu"?b.condition:void 0,W=_?Du(L,d(_.buffer),_.byteOffset??0,b.id):void 0;C.encode({...m,computePass:W?.computePass??L}),W?.assertDispatched()}finally{L.popDebugGroup()}w||S();break}case"render":{S();let L=C,_=L.getRenderPassProps?.(m)??{id:b.id};if(b.attachments&&_.framebuffer!==void 0)throw new Error(`GPUCommandGraph render node "${b.id}" cannot supply framebuffer with graph attachments`);if(b.attachments?.resolveTargets&&_.resolveTargets!==void 0)throw new Error(`GPUCommandGraph render node "${b.id}" cannot supply resolveTargets with graph attachments`);let W=b.attachments?this.getFramebuffer(b.id,b.attachments,f):void 0,j=b.attachments?.resolveTargets?.map(ne=>ne?f(ne):null),le=e.beginRenderPass({..._,...W?{framebuffer:W}:{},...j?{resolveTargets:j}:{}});E=as(le,e),le.pushDebugGroup(b.id);try{L.encode({...m,renderPass:le})}finally{le.popDebugGroup(),le.end()}break}case"copy":S(),C.encode(m);break}let $=lr();g.push({stats:{id:b.id,description:b.description,resources:this.preflight.nodes[v].resources,operation:b.workload?.operation,type:b.type,cpuEncodeStartTimeMilliseconds:B,cpuEncodeEndTimeMilliseconds:$,cpuEncodeTimeMilliseconds:$-B,hasGPUTimestamps:E!==void 0,...b.condition?{condition:{id:b.condition.id,source:b.condition.source,outcome:b.condition.source==="gpu"?"gpu-resolved":"executed"}}:{}},timestamp:E})}}finally{S()}let T=lr();return new Ft(g,T-i,p,i,T,async(v,b)=>{if(this.destroyed)throw new Error("Graph has been destroyed.");let C=this.compiledNodes.findIndex(({node:W})=>W.id===v),B=this.compiledNodes[C]?.node.resources?.[b],E=this.preflight.nodes[C]?.resources?.[b];if(!B||!E)throw new Error("Resource is unavailable.");if("externalTexture"in B)throw new Error("External images cannot be read back.");let $="buffer"in B?Pe(B.buffer):We(B.texture);if("frameScoped"in $&&$.frameScoped)throw new Error("Frame textures expire after presentation.");let L="buffer"in B?d(B.buffer):l(B.texture),_=L instanceof ce.Buffer?this.transientBuffers:this.transientTextures;if($.transient&&[..._].some(([W,j])=>W!==$&&j===L))throw new Error("Transient allocation is reused; logical contents are no longer available.");return ui(L,E)})}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,n=new Map;for(let[o,i]of this.buffers){if(i.transient)continue;let s=e[o]??i.defaultBuffer;if(!s)throw new Error(`GPUCommandGraph imported buffer "${o}" is required`);ds(s,i,this.device);let a=fr(s);if(this.activeImportedBufferHandles.has(i)){let u=a.handle,c=typeof u=="object"&&u!==null||typeof u=="function"?u:a,d=n.get(c);if(d&&(this.writableImportedBufferHandles.has(d)||this.writableImportedBufferHandles.has(i)))throw new Error(`GPUCommandGraph imported buffers "${d.id}" and "${o}" resolve to the same physical buffer`);d||n.set(c,i)}t.set(i,a)}for(let o of Object.keys(e)){let i=this.buffers.get(o);if(!i||i.transient)throw new Error(`GPUCommandGraph has no imported buffer named "${o}"`)}return t}resolveImportedTextures(e,t){let n=new Map,o=new Map;for(let[s,a]of this.textures){if(a.transient)continue;if(a.frameScoped){let c=t[s];if(!c)throw new Error(`GPUCommandGraph frame texture "${s}" is required`);let d=this.lastFrameIds.get(a);if(d!==void 0&&c.frameId<=d)throw new Error(`GPUCommandGraph frame texture "${s}" frameId ${c.frameId} is stale; expected greater than ${d}`);bo(c.texture,a,this.device),n.set(a,yo(c.texture)),o.set(a,c.frameId);continue}let u=e[s]??a.defaultTexture;if(!u)throw new Error(`GPUCommandGraph imported texture "${s}" is required`);bo(u,a,this.device),n.set(a,yo(u))}for(let s of Object.keys(e)){let a=this.textures.get(s);if(!a||a.transient||a.frameScoped)throw new Error(`GPUCommandGraph has no imported texture named "${s}"`)}for(let s of Object.keys(t))if(!this.textures.get(s)?.frameScoped)throw new Error(`GPUCommandGraph has no frame texture named "${s}"`);let i=new Map;for(let[s,a]of n){if(!this.activeImportedTextureHandles.has(s))continue;let u=a.handle,c=typeof u=="object"&&u!==null||typeof u=="function"?u:a,d=i.get(c);if(d&&(this.writableImportedTextureHandles.has(d)||this.writableImportedTextureHandles.has(s)))throw new Error(`GPUCommandGraph imported textures "${d.id}" and "${s.id}" resolve to the same physical texture`);d||i.set(c,s)}return{textures:n,frameIds:o}}resolveExternalTextures(e){let t=new Map,n=new Map;for(let[o,i]of this.externalTextures){let s=e[o];if(!s)throw new Error(`GPUCommandGraph external texture "${o}" is required`);let a=this.lastExternalTextureFrameIds.get(i);if(a!==void 0&&s.frameId<=a)throw new Error(`GPUCommandGraph external texture "${o}" frameId ${s.frameId} is stale; expected greater than ${a}`);if(this.consumedExternalTextures.has(s.texture))throw new Error(`GPUCommandGraph external texture "${o}" requires a fresh binding for each frame`);Nu(s.texture,i,this.device),t.set(i,s.texture),n.set(i,s.frameId)}for(let o of Object.keys(e))if(!this.externalTextures.has(o))throw new Error(`GPUCommandGraph has no external texture named "${o}"`);return{textures:t,frameIds:n}}getFramebuffer(e,t,n){let o=t.colorAttachments.map(n),i=t.depthStencilAttachment?n(t.depthStencilAttachment):void 0,s=this.cachedFramebuffers.find(c=>c.nodeId===e&&c.depthStencilAttachment===i&&c.colorAttachments.length===o.length&&c.colorAttachments.every((d,l)=>d===o[l]));if(s)return s.framebuffer;let a=t.colorAttachments[0]??t.depthStencilAttachment,u=this.device.createFramebuffer({id:`${this.id}-${e}-framebuffer-${this.cachedFramebuffers.length}`,width:a.width,height:a.height,colorAttachments:o,depthStencilAttachment:i??null});return this.cachedFramebuffers.push({nodeId:e,colorAttachments:o,depthStencilAttachment:i,framebuffer:u}),u}destroyFramebuffersUsingView(e){for(let t=this.cachedFramebuffers.length-1;t>=0;t--){let n=this.cachedFramebuffers[t];(n.depthStencilAttachment===e||n.colorAttachments.some(o=>o===e))&&(n.framebuffer.destroy(),this.cachedFramebuffers.splice(t,1))}}};function fr(r){return r instanceof Se?r.buffer:r}function _u(r){let e=r.length===0?0:(r.length-1)*r.byteStride+r.rowByteLength;return r.byteOffset+e}function dr(r,e){return r.byteLength>=e.byteLength&&(r.usage&e.usage)===e.usage}function yo(r){if(r instanceof ot){if(!r.isReady)throw new Error(`GPUCommandGraph dynamic texture "${r.id}" is not ready`);return r.texture}return r}function Au(r,e){let t;for(let[n,o]of[...Object.entries(r),...Object.entries(e)]){if(!Number.isSafeInteger(o.frameId)||o.frameId<0)throw new Error(`GPUCommandGraph frame resource "${n}" requires a valid frameId`);if(t!==void 0&&o.frameId!==t)throw new Error("GPUCommandGraph frame resources must share one frameId per encoding");t=o.frameId}}function as(r,e){let{timestampQuerySet:t,beginTimestampIndex:n,endTimestampIndex:o}=r.props;return t&&Number.isSafeInteger(n)&&Number.isSafeInteger(o)&&n>=0&&o>n?{querySet:t,snapshot:t.device.type==="webgpu"?e.captureTimestampQuerySet?.(t):void 0,beginIndex:n,endIndex:o}:void 0}function Fu(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 Xr(r,e){if(r.isLost)throw new Error(`GPUCommandGraph cannot perform ${e} after device loss`)}function lr(){return globalThis.performance?.now()??Date.now()}function us(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 Ru(r,e){if(!r.id)throw new Error("GPUCommandGraph external texture id is required");for(let[t,n]of Object.entries({width:r.width,height:r.height}))if(!Number.isSafeInteger(n)||n<=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 po(r,e){if(!r.id)throw new Error("GPUCommandGraph texture id is required");let t=r.dimension??"2d",n=t==="cube"?6:r.depth??1,o=r.mipLevels??1,i=r.samples??1;for(let[c,d]of Object.entries({width:r.width,height:r.height,depth:n,mipLevels:o,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||n!==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||n%6!==0))throw new Error(`GPUCommandGraph cube-array texture "${r.id}" must be square with depth divisible by 6`);if(o>e.getMipLevelCount(r.width,r.height,t==="3d"?n:1))throw new Error(`GPUCommandGraph texture "${r.id}" declares too many mip levels`);let s=t==="1d"?e.limits.maxTextureDimension1D:t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,a=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,u=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureArrayLayers;if(r.width>s||r.height>a||n>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:n,mipLevels:o,samples:i}}function Vu(r,e){let t=e.dimension??r.dimension,n=e.aspect??"all",o=e.baseMipLevel??0,i=e.mipLevelCount??r.mipLevels-o,s=e.baseArrayLayer??0,a=r.dimension==="3d"?1:r.depth,u=e.arrayLayerCount??a-s;for(let[f,h]of Object.entries({baseMipLevel:o,mipLevelCount:i,baseArrayLayer:s,arrayLayerCount:u}))if(!Number.isSafeInteger(h)||h<0)throw new Error(`Graph texture view ${f} must be a non-negative safe integer`);if(i===0||o+i>r.mipLevels)throw new Error(`Graph texture view exceeds texture "${r.id}" mip levels`);if(u===0||s+u>a||r.dimension==="3d"&&(s!==0||u!==1))throw new Error(`Graph texture view exceeds texture "${r.id}" array layers`);let c=Math.max(1,r.width>>o),d=r.dimension==="1d"?1:Math.max(1,r.height>>o),l=r.dimension==="3d"?Math.max(1,r.depth>>o):u;return{dimension:t,aspect:n,baseMipLevel:o,mipLevelCount:i,baseArrayLayer:s,arrayLayerCount:u,width:c,height:d,depth:l}}function Mu(r,e){for(let[o,i]of Object.entries(e))if(!Number.isSafeInteger(i)||i<0)throw new Error(`Graph data view ${o} 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,n=e.byteOffset+t;if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n))throw new Error("Graph data view byte range exceeds safe integer precision");if(n>r.byteLength)throw new Error(`Graph data view exceeds buffer "${r.id}" byte length`)}function ds(r,e,t){let n=fr(r);if(n.device!==t)throw new Error(`GPUCommandGraph buffer "${e.id}" belongs to another device`);if(n.byteLength<e.byteLength)throw new Error(`GPUCommandGraph buffer "${e.id}" is smaller than compiled capacity`);if((n.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph buffer "${e.id}" has incompatible usage flags`)}function bo(r,e,t){let n=yo(r);if(n.device!==t)throw new Error(`GPUCommandGraph texture "${e.id}" belongs to another device`);for(let[o,i,s]of[["format",e.format,n.format],["dimension",e.dimension,n.dimension],["width",e.width,n.width],["height",e.height,n.height],["depth",e.depth,n.depth],["mipLevels",e.mipLevels,n.mipLevels],["samples",e.samples,n.samples]])if(s!==i)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible ${o} (${s} !== ${i})`);if((n.props.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible usage flags`)}function Nu(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 zu(r,e){let t=Hu(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph buffer "${r.id}" does not declare usage required by ${e}`)}function Wu(r,e){let t=qu(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph texture "${r.id}" does not declare usage required by ${e}`)}function ju(r,e){if(r instanceof _e&&e.startsWith("storage-")&&r.mipLevelCount!==1)throw new Error("GPUCommandGraph storage texture views must contain exactly one mip level")}function Hu(r){switch(r){case"storage-read":case"storage-write":case"storage-read-write":return ce.Buffer.STORAGE;case"uniform":return ce.Buffer.UNIFORM;case"copy-source":return ce.Buffer.COPY_SRC;case"copy-destination":return ce.Buffer.COPY_DST;case"indirect":return ce.Buffer.INDIRECT;case"vertex":return ce.Buffer.VERTEX;case"index":return ce.Buffer.INDEX}}function qu(r){switch(r){case"sampled":return ce.Texture.SAMPLE;case"storage-read":case"storage-write":case"storage-read-write":return ce.Texture.STORAGE;case"render-attachment":return ce.Texture.RENDER;case"copy-source":return ce.Texture.COPY_SRC;case"copy-destination":return ce.Texture.COPY_DST}}function ls(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 xt=class extends go{constructor(e,t={}){if(e.type!=="webgpu")throw new Error("GPUCommandGraph requires a WebGPU device");super(e,t)}};var Pt=F(A(),1);var I=F(A(),1);var M={texture(r){return Object.freeze({...r,type:"texture",...r.extent?{extent:Object.freeze({...r.extent,..."scale"in r.extent&&r.extent.scale?{scale:Object.freeze([...r.extent.scale])}:{}})}:{}})},scalar(r){return Object.freeze({type:"scalar",format:r})},vector(r,e={}){return Object.freeze({type:"vector",format:r,...e,...e.chunkLengths?{chunkLengths:Object.freeze([...e.chunkLengths])}:{}})}},Ae=class{role;id;format;constructor(e,t,n){if(this.role=n,!e)throw new Error("GPUGraphScalar id is required");this.id=e,this.format=t}},Q=class{id;format;length;external;role;chunkLengths;constructor(e){if(!e.id)throw new Error("GPUGraphVector id is required");if(e.length!==void 0&&(!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,this.role=e.role,e.chunkLengths){if(e.chunkLengths.some(t=>!Number.isSafeInteger(t)||t<0)||e.length!==void 0&&e.chunkLengths.reduce((t,n)=>t+n,0)!==e.length)throw new Error(`${e.id} chunk lengths must partition its logical length`);this.chunkLengths=Object.freeze([...e.chunkLengths])}}},de=class{id;format;width;height;role;descriptor;usage;dimension;depth;mipLevels;samples;external;constructor(e){this.role=e.role,this.descriptor=e.descriptor?M.texture(e.descriptor):void 0,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}},Fe=class{texture;props;constructor(e,t={}){this.texture=e,this.props=Object.freeze({...t})}};function k(r){return typeof r=="string"?r:r.id}function xo(r,e){let t=k(e),n=[...r.scalars,...r.vectors,...r.textures].find(o=>o.id===t);if(!n)throw new Error(`Undeclared operation value ${t}`);if(typeof e!="string"&&(e.constructor!==n.constructor||e.format!==n.format))throw new Error(`Incompatible operation reference ${t}`);return n}function Rt(r,e){for(let t of e.values){let n=xo(r,t.value);if(n instanceof de&&t.shape&&"like"in t.shape){if(!(xo(r,t.shape.like)instanceof de))throw new Error("Texture shape requires a texture source");continue}if(t.shape){if(!(n instanceof Q)||t.access==="read")throw new Error("Operation shapes require writable vectors");if("like"in t.shape){if(!(xo(r,t.shape.like)instanceof Q))throw new Error("Operation shape source must be a vector");let o=k(t.shape.like);if(!e.values.some(i=>i.access!=="write"&&k(i.value)===o))throw new Error("Operation shape source must be a declared read")}else{let{length:o,chunkLengths:i}=t.shape;if(!Number.isSafeInteger(o)||o<0||i&&(i.some(s=>!Number.isSafeInteger(s)||s<0)||i.reduce((s,a)=>s+a,0)!==o))throw new Error("Invalid operation output shape")}}}}function ee(r){let e=r instanceof I.TextureView?r.texture:r,t=r instanceof I.TextureView?r.props:{},n=t.baseMipLevel??0,o=t.baseArrayLayer??0,i=t.dimension??e.dimension,s=t.mipLevelCount??e.mipLevels-n,a=i==="3d"?Math.max(1,e.depth>>n):t.arrayLayerCount??(i==="cube"?6:i==="2d"?1:e.depth-o);return(0,I.assert)((t.format??e.format)===e.format&&(t.aspect??"all")==="all"),(0,I.assert)(!r.destroyed&&!e.destroyed),(0,I.assert)(Number.isInteger(n)&&n>=0&&Number.isInteger(s)&&s>0&&n+s<=e.mipLevels),(0,I.assert)(Number.isInteger(o)&&o>=0&&Number.isInteger(a)&&a>0&&(i==="3d"?o===0:o+a<=e.depth)),{texture:e,format:e.format,dimension:i,width:Math.max(1,e.width>>n),height:Math.max(1,e.height>>n),depth:a,mipLevels:s,samples:e.samples,baseMipLevel:n,baseArrayLayer:o}}function fs(r,e={}){let t=ee(r),n=e.baseMipLevel??0,o=e.baseArrayLayer??0,i=e.dimension??t.dimension,s=e.mipLevelCount??t.mipLevels-n,a=e.arrayLayerCount??(i==="cube"?6:i==="2d"||i==="3d"?1:t.depth-o);return(0,I.assert)(n>=0&&n+s<=t.mipLevels&&o>=0&&o+a<=t.depth),{...e,dimension:i,baseMipLevel:t.baseMipLevel+n,mipLevelCount:s,baseArrayLayer:t.baseArrayLayer+o,arrayLayerCount:a}}var Yu={sampled:I.Texture.SAMPLE,"storage-read":I.Texture.STORAGE,"storage-write":I.Texture.STORAGE,"storage-read-write":I.Texture.STORAGE,"render-attachment":I.Texture.RENDER,"copy-source":I.Texture.COPY_SRC,"copy-destination":I.Texture.COPY_DST},Zr=class{values=new Map;owned=new Set;constructor(e,t,n,o,i){let s=new Map,a=new Set;for(let u of n)for(let c of u.values){let d=k(c.value);if(!t.some(f=>f.id===d))continue;(0,I.assert)(c.textureUsage);let l=c.textureUsage;(0,I.assert)(c.access==="read"&&["sampled","storage-read","copy-source"].includes(l)||c.access==="write"&&["storage-write","render-attachment","copy-destination"].includes(l)||c.access==="read-write"&&["storage-read-write","render-attachment"].includes(l)),s.set(d,(s.get(d)??0)|Yu[l]),c.access!=="read"&&a.add(d)}try{let u=new Set(t);for(;u.size;){let c=!1;for(let d of u){let l=d.descriptor??{type:"texture",format:d.format,dimension:d.dimension,extent:d.width===void 0?void 0:{width:d.width,height:d.height,depth:d.depth},mipLevels:d.mipLevels,samples:d.samples},f=l.extent,h=f&&"like"in f?this.values.get(f.like):void 0;if(f&&"like"in f&&!h)continue;let m=h?ee(h):void 0,g=f&&"like"in f?f.scale??[1,1]:[1,1];(0,I.assert)(g.every(E=>Number.isFinite(E)&&E>0));let y=m?Math.max(1,Math.round(m.width*g[0])):f&&"width"in f?f.width:void 0,p=m?Math.max(1,Math.round(m.height*g[1])):f&&"height"in f?f.height:void 0,w=l.dimension??m?.dimension??"2d",S=w==="cube"?6:m?.depth??(f&&"depth"in f?f.depth:void 0),T=l.mipLevels??m?.mipLevels??1,v=l.samples??m?.samples??1,b=(s.get(d.id)??0)|d.usage;(0,I.assert)(v===1||!(b&(I.Texture.COPY_SRC|I.Texture.COPY_DST)));let C=i[d.id]??o[d.id];if(C===void 0){(0,I.assert)(d.role!=="input"&&!d.external&&y!==void 0&&p!==void 0&&b!==0),(0,I.assert)(Number.isSafeInteger(y)&&y>0&&Number.isSafeInteger(p)&&p>0);let E=e.createTexture({id:d.id,format:l.format,dimension:w,width:y,height:p,depth:S??1,mipLevels:T,samples:v,usage:b|(v===1?I.Texture.COPY_SRC:0)|I.Texture.SAMPLE});this.owned.add(E),C=E}(0,I.assert)(C instanceof I.Texture||C instanceof I.TextureView);let B=ee(C);(0,I.assert)(B.samples===1||!(b&(I.Texture.COPY_SRC|I.Texture.COPY_DST))),(0,I.assert)(B.texture.device===e&&B.format===l.format&&B.dimension===w&&(y===void 0||B.width===y)&&(p===void 0||B.height===p)&&(S===void 0||B.depth===S)&&(l.mipLevels===void 0&&d.role==="input"||B.mipLevels===T)&&(l.samples===void 0&&d.role==="input"||B.samples===v)&&(B.texture.props.usage&b)===b),this.values.set(d.id,C),u.delete(d),c=!0}(0,I.assert)(c)}for(let c of a){let d=ee(this.values.get(c)).texture;for(let[l,f]of this.values)(0,I.assert)(c===l||ee(f).texture!==d)}}catch(u){throw this.destroy(),u}}finish(e){for(let t of e){let n=this.values.get(t);n instanceof I.Texture&&this.owned.delete(n)}this.destroy()}destroy(){for(let e of this.owned)e.destroy();this.owned.clear()}};var hs=F(A(),1);function ms(r,e,t){let n=ee(e),o=ee(t);wo(e,t);for(let i=0;i<n.mipLevels;i++)r.copyTextureToTexture({sourceTexture:n.texture,destinationTexture:o.texture,mipLevel:n.baseMipLevel+i,destinationMipLevel:o.baseMipLevel+i,origin:[0,0,n.baseArrayLayer],destinationOrigin:[0,0,o.baseArrayLayer],width:Math.max(1,n.width>>i),height:Math.max(1,n.height>>i),depthOrArrayLayers:n.dimension==="3d"?Math.max(1,n.depth>>i):n.depth})}function wo(r,e){let t=ee(r),n=ee(e);(0,hs.assert)(t.texture!==n.texture&&t.samples===1&&n.samples===1&&t.format===n.format&&t.width===n.width&&t.height===n.height&&t.depth===n.depth&&t.mipLevels===n.mipLevels&&t.dimension===n.dimension)}var hr=F(A(),1);function ps(r,e){let t=e.resolveVector(r.output),n=r.getData();for(let[o,i]of t.data.entries()){if(!i.length)continue;let s=n[o];e.graph.addCopyPass({id:`${r.id}-${o}`,resources:[{buffer:i,usage:"copy-destination"}],compile:({device:a})=>{let u=a.createBuffer({data:s,usage:hr.Buffer.COPY_SRC});return{encode:({commandEncoder:c,getBuffer:d})=>{let l=i.byteStride===i.rowByteLength;for(let f=0;f<i.length;f+=l?i.length:1)c.copyBufferToBuffer({sourceBuffer:u,sourceOffset:f*i.rowByteLength,destinationBuffer:d(i),destinationOffset:i.byteOffset+f*i.byteStride,size:l?s.byteLength:i.rowByteLength})},destroy:()=>u.destroy()}}})}}function gs(r,e){let t=e.resolveVector(r.input),n=e.resolveVector(r.output);(0,hr.assert)(t.format===n.format&&t.data.length===n.data.length);for(let[o,i]of t.data.entries()){let s=n.data[o];(0,hr.assert)(i.length===s.length),i.length&&e.graph.addCopyPass({id:`${r.id}-${o}`,resources:[{buffer:i,usage:"copy-source"},{buffer:s,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:a,getBuffer:u})=>{let c=i.byteStride===i.rowByteLength&&s.byteStride===s.rowByteLength;for(let d=0;d<i.length;d+=c?i.length:1)a.copyBufferToBuffer({sourceBuffer:u(i),sourceOffset:i.byteOffset+d*i.byteStride,destinationBuffer:u(s),destinationOffset:s.byteOffset+d*s.byteStride,size:i.rowByteLength*(c?i.length:1)})}})})}}function ys(r,e){let t=e.resolveTextureView(r.input),n=e.resolveTextureView(r.output);e.graph.addCopyPass({id:r.id,resources:[{texture:t,usage:"copy-source"},{texture:n,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:o,getTextureView:i})=>ms(o,i(t),i(n))})})}var To=F(A(),1);var qe=class{type="vector-upload";id;output;format;chunks;chunkLengths;constructor(e){this.id=e.id??`${e.output}-upload`,this.output=e.output,this.format=e.format;let t=U(e.format),n=Array.isArray(e.data)?e.data:[e.data],o=t.signedDataType==="float32"?Float32Array:t.signedDataType==="uint32"?Uint32Array:Int32Array;(0,To.assert)(n.every(i=>i instanceof o&&i.byteLength%t.byteLength===0)),this.chunks=n.map(i=>new Uint8Array(i.buffer,i.byteOffset,i.byteLength).slice()),this.chunkLengths=Object.freeze(this.chunks.map(i=>i.byteLength/t.byteLength))}getData(){return this.chunks.map(e=>e.slice())}get contract(){let e={length:this.chunkLengths.reduce((t,n)=>t+n,0),chunkLengths:this.chunkLengths};return{outputs:{[this.output]:M.vector(this.format,e)},values:[{value:this.output,access:"write",shape:e}]}}},Ye=class{type="vector-copy";id;input;output;constructor(e){this.id=e.id??`${e.output}-copy`,this.input=e.input,this.output=e.output}get contract(){return{outputs:({getValue:e})=>{let t=e(this.input);return t.type==="texture"?{[this.output]:M.texture({...t,extent:{like:this.input}})}:((0,To.assert)(t.type==="vector"),{[this.output]:M.vector(t.format,{length:t.length,chunkLengths:t.chunkLengths})})},values:[{value:this.input,access:"read",textureUsage:"copy-source"},{value:this.output,access:"write",shape:{like:this.input},textureUsage:"copy-destination"}]}}};function Y(r){return r instanceof O?r.data:[r]}function X(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 n=e.map(Y),o=e.map(()=>0),i=e.map(()=>0),s=[],a=0;for(;a<t;){for(let l=0;l<n.length;l++)for(;n[l][o[l]]?.length===i[l];)o[l]++,i[l]=0;let u=n.map((l,f)=>l[o[f]]),c=Math.min(...u.map((l,f)=>l.length-i[f])),d=[];for(let l=0;l<u.length;l++){let f=u[l],h=u.findIndex((m,g)=>g<l&&m===f&&i[g]===i[l]);d.push(h>=0?d[h]:i[l]===0&&c===f.length?f:r.createDataView(f.buffer,{format:f.format,length:c,byteOffset:f.byteOffset+i[l]*f.byteStride,byteStride:f.byteStride,rowByteLength:f.rowByteLength}))}s.push(d);for(let l=0;l<i.length;l++)i[l]+=c;a+=c}return s}function N(r,e){let[t,n,o]=e;for(let[i,s]of[["x",t],["y",n],["z",o]])if(!Number.isSafeInteger(s)||s<0)throw new Error(`compute dispatch ${i} workgroup count must be a non-negative safe integer`);return{...r,dispatchWorkgroups:Object.freeze([t,n,o])}}function Qr(r){return r.dispatchWorkgroups}var Xe=F(A(),1),D=class r{static async createAsync(e,t){let n=!Xe.PipelineFactory.getAsyncCompilation(e),o=n?Xe.PipelineFactory.beginAsyncCompilation(e):Xe.PipelineFactory.getAsyncCompilation(e),i;try{i=new r(e,t)}finally{n&&Xe.PipelineFactory.endAsyncCompilation(e,o)}try{return n?await Promise.all(o):await i._pipelineInitialization,i}catch(s){throw i.destroy(),s}}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:n,pipelineFactory:o,shaderFactory:i,debugShaders:s,...a}=t;this.device=e,this.id=t.id??"kernel",this.source=n,this.pipelineFactory=o??Xe.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=i??Xe.ShaderFactory.getDefaultShaderFactory(e),this.shader=this.shaderFactory.createShader({id:`${this.id}-compute`,stage:"compute",source:this.source,debugShaders:s});let u={...a,shader:this.shader},c=Xe.PipelineFactory.getAsyncCompilation(e);if(c){let d=this.pipelineFactory.createComputePipelineAsync(u);this._pipelineInitialization=d,c.push(d.then(l=>(this.pipeline=l,l)))}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)}};function fe(r,e,t,n){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new Error(`${r} element count must be a non-negative uint32`);return bs(r,t),Xu(r,Math.max(1,Math.ceil(e/t)),n)}function Xu(r,e,t){let n=Math.floor(t);if(!Number.isSafeInteger(n)||n<1)throw new Error("maxComputeWorkgroupsPerDimension must be a positive integer");let o=Math.min(e,n),i=Math.min(Math.ceil(e/o),n),s=Math.ceil(e/o/i);if(s>n)throw new Error(`${r} requires ${e} workgroups, exceeding the 3D dispatch limit of ${n} per dimension`);return{x:o,y:i,z:s}}function J(r,e){bs("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;
7
+ "use strict";var __exports__=(()=>{var da=Object.create;var kr=Object.defineProperty;var la=Object.getOwnPropertyDescriptor;var fa=Object.getOwnPropertyNames;var ha=Object.getPrototypeOf,ma=Object.prototype.hasOwnProperty;var pa=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ga=(r,e)=>{for(var t in e)kr(r,t,{get:e[t],enumerable:!0})},$r=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of fa(e))!ma.call(r,o)&&o!==t&&kr(r,o,{get:()=>e[o],enumerable:!(n=la(e,o))||n.enumerable});return r},Ir=(r,e,t)=>($r(r,e,"default"),t&&$r(t,e,"default")),F=(r,e,t)=>(t=r!=null?da(ha(r)):{},$r(e||!r||!r.__esModule?kr(t,"default",{value:r,enumerable:!0}):t,r)),ya=r=>$r(kr({},"__esModule",{value:!0}),r);var A=pa((Jc,ui)=>{ui.exports=globalThis.luma});var Or={};ga(Or,{CompiledGPUCommandGraph:()=>bt,CompiledGPUGraph:()=>Yt,DynamicBuffer:()=>Se,DynamicTexture:()=>ot,GPUCPUOperation:()=>Te,GPUCommandGraph:()=>xt,GPUCommandGraphAutotuner:()=>En,GPUCommandGraphEncoding:()=>Ft,GPUCommandGraphExecution:()=>At,GPUCommandGraphExecutionBudgetController:()=>Pn,GPUCommandGraphInspector:()=>Ln,GPUCompactionOperation:()=>On,GPUCopyOperation:()=>Ye,GPUExpressionOperation:()=>Ve,GPUGraph:()=>ke,GPUGraphCompiler:()=>St,GPUGraphGroupAggregation:()=>Tn,GPUGraphReduction:()=>vn,GPUGraphScalar:()=>Ae,GPUGraphTexture:()=>de,GPUGraphTextureView:()=>Fe,GPUGraphVector:()=>Q,GPUShaderPassOperation:()=>ft,GPUUploadOperation:()=>qe,GraphBufferHandle:()=>We,GraphDataView:()=>De,GraphExternalTextureHandle:()=>ct,GraphTextureHandle:()=>Ce,GraphTextureView:()=>_e,GraphVectorView:()=>O,Kernel:()=>D,PreparedGPUGraphExecution:()=>Cr,RenderKernel:()=>qt,composite:()=>Zo,getGPUCommandGraphAdapterIdentity:()=>ia,getGPUCommandGraphExecutionPlan:()=>Kr,getPlatformInfo:()=>ua,gpuGraph:()=>M,inspectGPUGraphCompilation:()=>Qo,validateGPUGraph:()=>vr});Ir(Or,F(A(),1));var mt=F(A(),1);async function ci(r,e){if(r.destroyed)throw new Error("Resource has been destroyed.");if(r instanceof mt.Buffer){if(!(r.usage&mt.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)&mt.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 n=e.baseMipLevel??0,o=Math.min(32,e.width??Math.max(1,r.width>>n)),i=Math.min(32,e.height??Math.max(1,r.height>>n)),s=r.computeMemoryLayout({width:o,height:i,depthOrArrayLayers:1}),a=r.device.createBuffer({byteLength:s.byteLength,usage:mt.Buffer.MAP_READ|mt.Buffer.COPY_DST}),u=r.device.createCommandEncoder();try{u.copyTextureToBuffer({sourceTexture:r,destinationBuffer:a,mipLevel:n,origin:[0,0,e.baseArrayLayer??0],width:o,height:i,depthOrArrayLayers:1,bytesPerRow:s.bytesPerRow}),r.device.submit(u.finish());let c=await a.readAsync(),d=o*t.bytesPerPixel,l=new Uint8Array(d*i);for(let h=0;h<i;h++)l.set(c.subarray(h*s.bytesPerRow,h*s.bytesPerRow+d),h*d);return{data:l,width:o,height:i,format:r.format}}finally{a.destroy(),u.destroy()}}var ce=F(A(),1);var Xt=globalThis,ba=globalThis.document||{},Ur=globalThis.process||{},xa=globalThis.console,wa=globalThis.navigator||{};function Gr(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)}function Je(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||Gr()}var $n="5.0.0";function Lt(r,e){if(!r)throw new Error(e||"Assertion failed")}function Dr(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 Lt(Number.isFinite(e)&&e>=0),e}function kn(r){let{logLevel:e,message:t}=r;r.logLevel=Dr(e);let n=r.args?Array.from(r.args):[];for(;n.length&&n.shift()!==t;);switch(typeof e){case"string":case"function":t!==void 0&&n.unshift(t),r.message=e;break;case"object":Object.assign(r,e);break;default:}typeof r.message=="function"&&(r.message=r.message());let o=typeof r.message;return Lt(o==="string"||o==="object"),Object.assign(r,{args:n},r.opts)}var et=()=>{},pt=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,...n){return this._log("log",e,t,n)}info(e,t,...n){return this._log("info",e,t,n)}once(e,t,...n){return this._log("once",e,t,n,{once:!0})}_log(e,t,n,o,i={}){let s=kn({logLevel:t,message:n,args:this._buildArgs(t,n,o),opts:i});return this._createLogFunction(e,s,i)}_buildArgs(e,t,n){return[e,t,...n]}_createLogFunction(e,t,n){if(!this._shouldLog(t.logLevel))return et;let o=this._getOnceTag(n.tag??t.tag??t.message);if((n.once||t.once)&&o!==void 0){if(this._onceCache.has(o))return et;this._onceCache.add(o)}return this._emit(e,t)}_shouldLog(e){return this.getLevel()>=Dr(e)}_getOnceTag(e){if(e!==void 0)try{return typeof e=="string"?e:String(e)}catch{return}}};function va(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,t),e.removeItem(t),e}catch{return null}}var Kt=class{constructor(e,t,n="sessionStorage"){this.storage=va(n),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 di(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 In(r,e=8){let t=Math.max(e-r.length,0);return`${" ".repeat(t)}${r}`}var Zt;(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"})(Zt||(Zt={}));var Sa=10;function li(r){return typeof r!="string"?r:(r=r.toUpperCase(),Zt[r]||Zt.WHITE)}function Un(r,e,t){return!Je&&typeof r=="string"&&(e&&(r=`\x1B[${li(e)}m${r}\x1B[39m`),t&&(r=`\x1B[${li(t)+Sa}m${r}\x1B[49m`)),r}function Gn(r,e=["constructor"]){let t=Object.getPrototypeOf(r),n=Object.getOwnPropertyNames(t),o=r;for(let i of n){let s=o[i];typeof s=="function"&&(e.find(a=>i===a)||(o[i]=s.bind(r)))}}var _r=class{getHighResolutionTimer(){let e;if(Je()&&Xt.performance)e=Xt?.performance?.now?.();else if("hrtime"in Ur){let t=Ur?.hrtime?.();e=t[0]*1e3+t[1]/1e6}else e=Date.now();return e}getMemoryUsageMB(){let t=Xt?.performance?.memory?.usedJSHeapSize;return t==null?null:Math.trunc(t/1024/1024)}},me=new _r;globalThis.Probe=_r;globalThis.probe=me;var Bt={debug:Je()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},Dn={enabled:!0,level:0},Me=class extends pt{constructor({id:e}={id:""}){super({level:0}),this.VERSION=$n,this._startTs=me.getHighResolutionTimer(),this._deltaTs=me.getHighResolutionTimer(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new Kt(`__probe-${this.id}__`,{[this.id]:Dn}),this.timeStamp(`${this.id} started`),Gn(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((me.getHighResolutionTimer()-this._startTs).toPrecision(10))}getDelta(){return Number((me.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:Bt.warn,once:!0})}error(e,...t){return this._log("error",0,e,t,{method:Bt.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,...n){let o=me.getMemoryUsageMB();if(o!==null){let i=`${o}MB `;typeof t=="function"?t=()=>`${i}${t()}`:typeof t=="string"&&(t=`${i}${t}`)}return this._log("log",e,t,n,{method:Bt.log,time:!0,once:!0})}log(e,t,...n){return this._log("log",e,t,n,{method:Bt.debug})}info(e,t,...n){return this._log("info",e,t,n,{method:console.info})}once(e,t,...n){return this._log("once",e,t,n,{method:Bt.debug||Bt.info,once:!0})}table(e,t,n){return t?this._log("table",e,t,n&&[n]||[],{method:console.table||et,tag:Pa(t)}):et}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||et})}group(e,t,n={collapsed:!1}){let o=(n.collapsed?console.groupCollapsed:console.group)||console.info;return this._log("group",e,t,[],{method:o})}groupCollapsed(e,t,n={}){return this.group(e,t,Object.assign({},n,{collapsed:!0}))}groupEnd(e){return this._log("groupEnd",e,"",[],{method:console.groupEnd||et})}withGroup(e,t,n){this.group(e,t)();try{n()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&super._shouldLog(e)}_emit(e,t){let n=t.method;Lt(n),t.total=this.getTotal(),t.delta=this.getDelta(),this._deltaTs=me.getHighResolutionTimer();let o=Ea(this.id,t.message,t);return n.bind(console,o,...t.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(Dn),this._storage.config[this.id]}_updateConfiguration(e){let t=this._storage.config[this.id]||{...Dn};this._storage.setConfiguration({[this.id]:{...t,...e}})}};Me.VERSION=$n;function Ea(r,e,t){if(typeof e=="string"){let n=t.time?In(di(t.total)):"";e=t.time?`${r}: ${n} ${e}`:`${r}: ${e}`,e=Un(e,t.color,t.background)}return e}function Pa(r){for(let e in r)for(let t in r[e])return t||"untitled";return"empty"}globalThis.probe||(globalThis.probe=me);var el=new Me({id:"@probe.gl/log"});var ve=new Me({id:"luma.gl"});var _n={};function Ot(r="id"){_n[r]=_n[r]||1;let e=_n[r]++;return`${r}-${e}`}function $t(r,e){if(!r){let t=new Error(e??"luma.gl assertion failed.");throw Error.captureStackTrace?.(t,$t),t}}var Ar=class{_owner=null;_ownedResources=new Set;_state="live";_destroyingOwnedResources=!1;_destroyRequested=!1;get owner(){return this._owner}get ownedResources(){return Array.from(this._ownedResources)}get destroyed(){return this._state==="destroyed"}transferOwnershipTo(e){$t(this._state==="live"&&!this._destroyingOwnedResources),$t(!this._owner||this._owner.canChangeOwnership()),$t(!e||e.canChangeOwnership());for(let t=e;t;t=t._owner)$t(t!==this);return e!==this._owner&&(this._owner?._ownedResources.delete(this),this._owner=e,e?._ownedResources.add(this)),this}destroy(){if(this._state!=="live")return;if(this._destroyingOwnedResources){this._destroyRequested=!0;return}this._destroyRequested=!1,this._state="destroying",this._owner?._ownedResources.delete(this),this._owner=null;let e=[];try{try{this.onBeforeDestroy()}catch(t){e.push(t)}this.destroyChildren(e);try{this.onDestroy()}catch(t){e.push(t)}}finally{this._state="destroyed"}if(e.length)throw new AggregateError(e,"Resource cleanup failed")}delete(){return this.destroy(),this}attachResource(e){e.transferOwnershipTo(this)}detachResource(e){e._owner===this&&e.transferOwnershipTo(null)}destroyAttachedResource(e){e._owner===this&&e.destroy()}destroyAttachedResources(){if(this._state!=="live"||this._destroyingOwnedResources)return;let e=[];if(this.destroyChildren(e),this._destroyRequested)try{this.destroy()}catch(t){e.push(t)}if(e.length)throw new AggregateError(e,"Resource cleanup failed")}onBeforeDestroy(){}onDestroy(){}canChangeOwnership(){return this._state==="live"&&!this._destroyingOwnedResources}destroyChildren(e){this._destroyingOwnedResources=!0;try{for(let t of this._ownedResources)try{t.destroy()}catch(n){e.push(n)}}finally{this._ownedResources.clear(),this._destroyingOwnedResources=!1}}};var Ca="cpu-hotspot-profiler",fi="GPU Resource Counts",hi="Resource Counts",mi="GPU Time and Memory",La=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],Ba=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","SharedRenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],Oa=La.flatMap(r=>[`${r} Created`,`${r} Active`]),$a=Ba.flatMap(r=>[`${r} Created`,`${r} Active`]),pi=new WeakMap,gi=new WeakMap,pe=class extends Ar{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;allocatedBytes=0;allocatedBytesName=null;get ownsHandle(){return(this.props.handle===void 0||this.props.handle===null)&&!this.isHandleBorrowed}get isHandleBorrowed(){return!!this.props._isHandleBorrowed}constructor(e,t,n){if(super(),!e)throw new Error("no device");this._device=e,this.props=ka(t,n);let o=this.props.id!=="undefined"?this.props.id:Ot(this[Symbol.toStringTag]);this.props.id=o,this.id=o,this.userData=this.props.userData||{},this.addStats()}getProps(){return this.props}destroyHandle(){}onDestroy(){try{this.destroyHandle()}finally{this.trackDeallocatedMemory(),this.removeStats()}}removeStats(){let e=Qt(this._device),t=e?tt():0,n=[this._device.statsManager.getStats(fi),this._device.statsManager.getStats(hi)],o=bi(this._device);for(let s of n)yi(s,o);let i=this.getStatsName();for(let s of n)s.get("Resources Active").decrementCount(),s.get(`${i}s Active`).decrementCount();e&&(e.statsBookkeepingCalls=(e.statsBookkeepingCalls||0)+1,e.statsBookkeepingTimeMs=(e.statsBookkeepingTimeMs||0)+(tt()-t))}trackAllocatedMemory(e,t=this.getStatsName()){let n=Qt(this._device),o=n?tt():0,i=this._device.statsManager.getStats(mi);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),n&&(n.statsBookkeepingCalls=(n.statsBookkeepingCalls||0)+1,n.statsBookkeepingTimeMs=(n.statsBookkeepingTimeMs||0)+(tt()-o)),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=Qt(this._device),n=t?tt():0,o=this._device.statsManager.getStats(mi);o.get("GPU Memory").subtractCount(this.allocatedBytes),o.get(`${this.allocatedBytesName||e} Memory`).subtractCount(this.allocatedBytes),t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(tt()-n)),this.allocatedBytes=0,this.allocatedBytesName=null}trackDeallocatedReferencedMemory(e=this.getStatsName()){this.trackDeallocatedMemory(`Referenced ${e}`)}addStats(){let e=this.getStatsName(),t=Qt(this._device),n=t?tt():0,o=[this._device.statsManager.getStats(fi),this._device.statsManager.getStats(hi)],i=bi(this._device);for(let s of o)yi(s,i);for(let s of o)s.get("Resources Created").incrementCount(),s.get("Resources Active").incrementCount(),s.get(`${e}s Created`).incrementCount(),s.get(`${e}s Active`).incrementCount();t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(tt()-n)),Ia(this._device,e)}getStatsName(){return Ua(this)}};function ka(r,e){let t={...e};for(let n in r)r[n]!==void 0&&(t[n]=r[n]);return t}function yi(r,e){let t=r.stats,n=!1;for(let u of e)t[u]||(r.get(u),n=!0);let o=Object.keys(t).length,i=pi.get(r);if(!n&&i?.orderedStatNames===e&&i.statCount===o)return;let s={},a=gi.get(e);a||(a=new Set(e),gi.set(e,a));for(let u of e)t[u]&&(s[u]=t[u]);for(let[u,c]of Object.entries(t))a.has(u)||(s[u]=c);for(let u of Object.keys(t))delete t[u];Object.assign(t,s),pi.set(r,{orderedStatNames:e,statCount:o})}function bi(r){return r.type==="webgl"?$a:Oa}function Qt(r){let e=r.userData[Ca];return e?.enabled?e:null}function tt(){return globalThis.performance?.now?.()??Date.now()}function Ia(r,e){let t=Qt(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 Ua(r){let e=Object.getPrototypeOf(r);for(;e;){let t=Object.getPrototypeOf(e);if(!t||t===pe.prototype)return Ga(e)||r[Symbol.toStringTag]||r.constructor.name;e=t}return r[Symbol.toStringTag]||r.constructor.name}function Ga(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 Ie=class r extends pe{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 n={...t};(t.usage||0)&r.INDEX&&!t.indexType&&(t.data instanceof Uint32Array?n.indexType="uint32":t.data instanceof Uint16Array?n.indexType="uint16":t.data instanceof Uint8Array&&(n.indexType="uint8")),delete n.data,super(e,n,r.defaultProps),this.usage=n.usage||0,this.indexType=n.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,n){if(!this.device.props.debug)return;let o=null,i;ArrayBuffer.isView(e)?(o=e,i=e.buffer):i=e;let s=Math.min(e?e.byteLength:n,r.DEBUG_DATA_MAX_LENGTH);if(i===null)this.debugData=new ArrayBuffer(s);else{let a=Math.min(o?.byteOffset||0,i.byteLength),u=Math.max(0,i.byteLength-a),c=Math.min(s,u);this.debugData=new Uint8Array(i,a,c).slice().buffer}}static defaultProps={...pe.defaultProps,handle:void 0,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}};var An=globalThis.Float16Array;function xi(){return An??Uint16Array}function wi(r){return!!(An&&r===An)}function Fr(r,e){switch(e){case 1:return r;case 2:return r+r%2;default:return r+(4-r%4)%4}}var Ti=new Map;function vi(r){let e=Ti.get(r);if(e)return e;let t=Object.freeze(Da(r));return Object.hasOwn(Rr,r)&&Ti.set(r,t),t}function Da(r){let e=r.includes("norm"),t=!e&&!r.startsWith("float"),n=r.startsWith("s"),o=Rr[r],[i,s,a]=o||["uint8 ","i32",1];return{signedType:i,primitiveType:s,byteLength:a,normalized:e,integer:t,signed:n}}function Si(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 _a(r){let e=ArrayBuffer.isView(r)?r.constructor:r;if(wi(e))return"float16";if(e===Uint8ClampedArray)return"uint8";let t=Object.values(Rr).find(n=>e===n[4]);if(!t)throw new Error(e.name);return t[0]}function Ei(r){return _a(r)}function Aa(r){if(r==="float16")return xi();let e=Rr[r];if(!e)throw new Error(r);let[,,,,t]=e;return t}function Pi(r){return Aa(r)}var Rr={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 Fn=class{getDataTypeInfo(e){return vi(e)}getNormalizedDataType(e){return Si(e)}alignTo(e,t){return Fr(e,t)}getDataType(e){return Ei(e)}getTypedArrayConstructor(e){return Pi(e)}},Ci=new Fn;var oe="texture-compression-bc",R="texture-compression-astc",Ue="texture-compression-etc2",Li="texture-compression-etc1-webgl",Vr="texture-compression-pvrtc-webgl",Rn="texture-compression-atc-webgl",Mr="float32-renderable-webgl",Vn="float16-renderable-webgl",Fa="rgb9e5ufloat-renderable-webgl",Mn="snorm8-renderable-webgl",rt="norm16-webgl",Nn="norm16-renderable-webgl",zn="snorm16-renderable-webgl",Nr="float32-filterable",Bi="float16-filterable-webgl",Jt=1,er=2,Hn=4,qn=8,It=16,jr=5,$i=10,Z=Jt|er,zr=Jt|Hn,Ne=Jt|er|Hn|qn,Ge=Jt|er|It,Ra=Jt|Hn|It,Wn=Ne|It,Oi=(er|qn|It)<<jr,Va=(er|qn)<<jr,ue=It<<jr,kt=Wn<<jr,Ma=Ne<<$i,jn=It<<$i;function Wr(r){let e=ja[r];if(!e)throw new Error(`Unsupported texture format ${r}`);return e}var Na={r8unorm:{webgpu:Ne|ue},rg8unorm:{webgpu:Ne|ue},"rgb8unorm-webgl":{},rgba8unorm:{webgpu:Wn},"rgba8unorm-srgb":{webgpu:Ne},r8snorm:{render:Mn,webgpu:zr|Oi},rg8snorm:{render:Mn,webgpu:zr|Oi},"rgb8snorm-webgl":{},rgba8snorm:{render:Mn,webgpu:Ra|Va},r8uint:{webgpu:Z|ue},rg8uint:{webgpu:Z|ue},rgba8uint:{webgpu:Ge},r8sint:{webgpu:Z|ue},rg8sint:{webgpu:Z|ue},rgba8sint:{webgpu:Ge},bgra8unorm:{webgpu:Ne},"bgra8unorm-srgb":{webgpu:Ma},r16unorm:{f:rt,render:Nn,webgpu:kt},rg16unorm:{f:rt,render:Nn,webgpu:kt},"rgb16unorm-webgl":{f:rt,render:!1},rgba16unorm:{f:rt,render:Nn,webgpu:kt},r16snorm:{f:rt,render:zn,webgpu:kt},rg16snorm:{f:rt,render:zn,webgpu:kt},"rgb16snorm-webgl":{f:rt,render:!1},rgba16snorm:{f:rt,render:zn,webgpu:kt},r16uint:{webgpu:Z|ue},rg16uint:{webgpu:Z|ue},rgba16uint:{webgpu:Ge},r16sint:{webgpu:Z|ue},rg16sint:{webgpu:Z|ue},rgba16sint:{webgpu:Ge},r16float:{render:Vn,filter:"float16-filterable-webgl",webgpu:Ne|ue},rg16float:{render:Vn,filter:Bi,webgpu:Ne|ue},rgba16float:{render:Vn,filter:Bi,webgpu:Wn},r32uint:{webgpu:Ge},rg32uint:{webgpu:Z|jn},rgba32uint:{webgpu:Ge},r32sint:{webgpu:Ge},rg32sint:{webgpu:Z|jn},rgba32sint:{webgpu:Ge},r32float:{render:Mr,filter:Nr,webgpu:Ge},rg32float:{render:!1,filter:Nr,webgpu:Z|jn},"rgb32float-webgl":{render:Mr,filter:Nr},rgba32float:{render:Mr,filter:Nr,webgpu:Ge},"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:Fa,webgpu:zr},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:Mr,webgpu:zr|ue},rgb10a2unorm:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:Ne|ue},rgb10a2uint:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:Z|ue},stencil8:{attachment:"stencil",bitsPerChannel:[8,0,0,0],dataType:"uint8",webgpu:Z},depth16unorm:{attachment:"depth",bitsPerChannel:[16,0,0,0],dataType:"uint16",webgpu:Z},depth24plus:{attachment:"depth",bitsPerChannel:[24,0,0,0],dataType:"uint32",webgpu:Z},depth32float:{attachment:"depth",bitsPerChannel:[32,0,0,0],dataType:"float32",webgpu:Z},"depth24plus-stencil8":{attachment:"depth-stencil",bitsPerChannel:[24,8,0,0],packed:!0,webgpu:Z},"depth32float-stencil8":{attachment:"depth-stencil",bitsPerChannel:[32,8,0,0],packed:!0,f:"depth32float-stencil8",webgpu:Z}},za={"bc1-rgb-unorm-webgl":{f:oe},"bc1-rgb-unorm-srgb-webgl":{f:oe},"bc1-rgba-unorm":{f:oe},"bc1-rgba-unorm-srgb":{f:oe},"bc2-rgba-unorm":{f:oe},"bc2-rgba-unorm-srgb":{f:oe},"bc3-rgba-unorm":{f:oe},"bc3-rgba-unorm-srgb":{f:oe},"bc4-r-unorm":{f:oe},"bc4-r-snorm":{f:oe},"bc5-rg-unorm":{f:oe},"bc5-rg-snorm":{f:oe},"bc6h-rgb-ufloat":{f:oe},"bc6h-rgb-float":{f:oe},"bc7-rgba-unorm":{f:oe},"bc7-rgba-unorm-srgb":{f:oe},"etc2-rgb8unorm":{f:Ue},"etc2-rgb8unorm-srgb":{f:Ue},"etc2-rgb8a1unorm":{f:Ue},"etc2-rgb8a1unorm-srgb":{f:Ue},"etc2-rgba8unorm":{f:Ue},"etc2-rgba8unorm-srgb":{f:Ue},"eac-r11unorm":{f:Ue},"eac-r11snorm":{f:Ue},"eac-rg11unorm":{f:Ue},"eac-rg11snorm":{f:Ue},"astc-4x4-unorm":{f:R},"astc-4x4-unorm-srgb":{f:R},"astc-5x4-unorm":{f:R},"astc-5x4-unorm-srgb":{f:R},"astc-5x5-unorm":{f:R},"astc-5x5-unorm-srgb":{f:R},"astc-6x5-unorm":{f:R},"astc-6x5-unorm-srgb":{f:R},"astc-6x6-unorm":{f:R},"astc-6x6-unorm-srgb":{f:R},"astc-8x5-unorm":{f:R},"astc-8x5-unorm-srgb":{f:R},"astc-8x6-unorm":{f:R},"astc-8x6-unorm-srgb":{f:R},"astc-8x8-unorm":{f:R},"astc-8x8-unorm-srgb":{f:R},"astc-10x5-unorm":{f:R},"astc-10x5-unorm-srgb":{f:R},"astc-10x6-unorm":{f:R},"astc-10x6-unorm-srgb":{f:R},"astc-10x8-unorm":{f:R},"astc-10x8-unorm-srgb":{f:R},"astc-10x10-unorm":{f:R},"astc-10x10-unorm-srgb":{f:R},"astc-12x10-unorm":{f:R},"astc-12x10-unorm-srgb":{f:R},"astc-12x12-unorm":{f:R},"astc-12x12-unorm-srgb":{f:R},"pvrtc-rgb4unorm-webgl":{f:Vr},"pvrtc-rgba4unorm-webgl":{f:Vr},"pvrtc-rgb2unorm-webgl":{f:Vr},"pvrtc-rgba2unorm-webgl":{f:Vr},"etc1-rgb-unorm-webgl":{f:Li},"etc1-rbg-unorm-webgl":{f:Li},"atc-rgb-unorm-webgl":{f:Rn},"atc-rgba-unorm-webgl":{f:Rn},"atc-rgbai-unorm-webgl":{f:Rn}},ja={...Na,...za};var Wa=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,Ha=["rgb","rgba","bgra"],qa=["depth","stencil"],Ya=5,Xa=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"],Yn=class{isColor(e){return Ha.some(t=>e.startsWith(t))}isDepthStencil(e){return qa.some(t=>e.startsWith(t))}isCompressed(e){return Xa.some(t=>e.startsWith(t))}getInfo(e){return Ii(e)}getCapabilities(e){return Za(e)}getWebGPUCapabilities(e){let t=Wr(e);return t.webgpu!==void 0?t.webgpu:this.isCompressed(e)&&!e.endsWith("-webgl")?Ya:0}computeMemoryLayout(e,t){return Ka(e,t)}},Ut=new Yn;function Ka({format:r,width:e,height:t,depth:n,byteAlignment:o},i={}){let s=Ut.getInfo(r),{bytesPerPixel:a,blockHeight:u=1,compressed:c=!1}=s,d=Xn(s,e,o),l=c?Math.ceil(t/u):t;return i.bytesPerPixel=a,i.bytesPerRow=d,i.rowsPerImage=l,i.depthOrArrayLayers=n,i.bytesPerImage=d*l,i.byteLength=i.bytesPerImage*n,i}function Xn(r,e,t){let{bytesPerPixel:n,bytesPerBlock:o=n,blockWidth:i=1,compressed:s=!1}=r,a=s?Math.ceil(e/i):e;return Math.ceil(a*o/t)*t}function Za(r){let e=Wr(r),t={format:r,create:e.f??!0,render:e.render??!0,filter:e.filter??!0,blend:e.blend??!0,store:e.store??!0},n=Ii(r),o=r.startsWith("depth")||r.startsWith("stencil"),i=n?.signed,s=n?.integer,a=n?.webgl,u=!!n?.compressed;return t.render&&=!o&&!u,t.filter&&=!o&&!i&&!s&&!a,t}var ki=new Map;function Ii(r){let e=ki.get(r);if(!e){let t=Qa(r);t.bitsPerChannel=Object.freeze([...t.bitsPerChannel]),e=Object.freeze(t),ki.set(r,e)}return e}function Qa(r){let e=Ja(r);if(Ut.isCompressed(r)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0,e.bytesPerBlock=tu(r);let n=eu(r);n&&(e.blockWidth=n.blockWidth,e.blockHeight=n.blockHeight)}let t=e.packed?null:Wa.exec(r);if(t){let[,n,o,i,s,a]=t,u=`${i}${o}`,c=Ci.getDataTypeInfo(u),d=c.byteLength*8,l=n?.length??1,h=[d,l>=2?d:0,l>=3?d:0,l>=4?d:0];e={format:r,attachment:e.attachment,dataType:c.signedType,components:l,channels:n,integer:c.integer,signed:c.signed,normalized:c.normalized,bitsPerChannel:h,bytesPerPixel:c.byteLength*l,packed:e.packed,srgb:e.srgb},a==="-webgl"&&(e.webgl=!0),s==="-srgb"&&(e.srgb=!0)}return r.endsWith("-webgl")&&(e.webgl=!0),r.endsWith("-srgb")&&(e.srgb=!0),e}function Ja(r){let e={...Wr(r)},t=e.bytesPerPixel||1,n=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:n,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 eu(r){let t=/.*-(\d+)x(\d+)-.*/.exec(r);if(t){let[,n,o]=t;return{blockWidth:Number(n),blockHeight:Number(o)}}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 tu(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}function tr(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 Hr(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 nt=class r extends pe{static defaultProps={...pe.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}};function Ui(r,e){let t=e instanceof nt?e:r.device.createSampler(e);if(t===r.sampler)return;e instanceof nt||t.transferOwnershipTo(r);let n=r.sampler;r.sampler=t,n?.owner===r&&n.destroy()}var Gi=[],ru=Object.freeze({}),nu={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"},ie=class r extends pe{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,n){if(t=r.normalizeProps(e,t),super(e,t,r.defaultProps),this.dimension=this.props.dimension,this.baseDimension=nu[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 o=e.getExternalImageSize(t.data);this.width=o?.width||1,this.height=o?.height||1}else this.width=1,this.height=1,(this.props.width===void 0||this.props.height===void 0)&&ve.warn(`${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`)();this.byteAlignment=n?.byteAlignment||1,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createTexture({...this.props,...e})}setSampler(e){Ui(this,e)}copyImageData(e){let{data:t,depth:n,...o}=e;this.writeData(t,{...o,depthOrArrayLayers:o.depthOrArrayLayers??n})}computeMemoryLayout(e=ru,t){let n=Gi.pop()||{readOptions:{},layoutOptions:{}};try{let o=this._normalizeTextureReadOptions(e,n.readOptions),i=n.layoutOptions;return i.format=this.format,i.width=o.width,i.height=o.height,i.depth=o.depthOrArrayLayers,i.byteAlignment=this.byteAlignment,Ut.computeMemoryLayout(i,t)}finally{Gi.push(n)}}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 n={...t},{width:o,height:i}=n;return typeof o=="number"&&(n.width=Math.max(1,Math.ceil(o))),typeof i=="number"&&(n.height=Math.max(1,Math.ceil(i))),n}_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,t={}){let{data:n,depth:o,depthOrArrayLayers:i}=e;if(this._normalizeTextureWriteOptions(e,t),i===void 0&&o!==void 0){let s=this.dimension==="3d"?Math.max(1,this.depth>>t.mipLevel):this.depth;t.depthOrArrayLayers=Math.min(o,s-t.z)}return t.data=n,t.depth=t.depthOrArrayLayers,t}_normalizeCopyExternalImageOptions(e,t={}){let{width:n,height:o}=e,i=this.device.getExternalImageSize(e.image),s=r._normalizeOptions(e,r.defaultCopyExternalImageOptions,t),a=Math.max(1,this.width>>s.mipLevel),u=this.baseDimension==="1d"?1:Math.max(1,this.height>>s.mipLevel),c=this.dimension==="3d"?Math.max(1,this.depth>>s.mipLevel):this.depth;return s.width=Math.min(n??i.width,a-s.x),s.height=Math.min(o??i.height,u-s.y),s.depth=Math.min(s.depth,c-s.z),s}_normalizeCopyElementImageOptions(e,t={}){let n=r._normalizeOptions(e,r.defaultCopyElementImageOptions,t),o=Math.max(1,this.width>>n.mipLevel),i=this.baseDimension==="1d"?1:Math.max(1,this.height>>n.mipLevel),s=this.dimension==="3d"?Math.max(1,this.depth>>n.mipLevel):this.depth;return n.width=Math.min(n.width??o,o-n.x),n.height=Math.min(n.height??i,i-n.y),n.depth=Math.min(n.depth,s-n.z),n}_normalizeTextureReadOptions(e,t={}){let{depthOrArrayLayers:n}=e,o=r._normalizeOptions(e,r.defaultTextureReadOptions,t),i=Math.max(1,this.width>>o.mipLevel),s=this.baseDimension==="1d"?1:Math.max(1,this.height>>o.mipLevel),a=this.dimension==="3d"?Math.max(1,this.depth>>o.mipLevel):this.depth;return o.width=Math.min(o.width??i,i-o.x),o.height=Math.min(o.height??s,s-o.y),o.depthOrArrayLayers=Math.min(n??a,a-o.z),o}_getSupportedColorReadOptions(e){let t=this._normalizeTextureReadOptions(e),n=Ut.getInfo(this.format);switch(this._validateColorReadAspect(t),this._validateColorReadFormat(n),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,t={}){let{byteOffset:n=0,bytesPerRow:o,rowsPerImage:i}=e;this._normalizeTextureReadOptions(e,t);let s=t;s.byteOffset=n;let a=this.device.getTextureFormatInfo(this.format),u=a.bytesPerPixel*s.width;if(s.bytesPerRow=o??Xn(a,s.width,this.byteAlignment),s.rowsPerImage=i??s.height,s.bytesPerRow<u)throw new Error(`bytesPerRow (${s.bytesPerRow}) must be at least ${u} for ${this.format}`);if(s.rowsPerImage<s.height)throw new Error(`rowsPerImage (${s.rowsPerImage}) must be at least ${s.height} for ${this.format}`);let{bytesPerPixel:c}=a;if(c&&s.bytesPerRow%c!==0)throw new Error(`bytesPerRow (${s.bytesPerRow}) must be a multiple of bytesPerPixel (${c}) for ${this.format}`);return s}_getMipLevelSize(e){let t=Math.max(1,this.width>>e),n=this.baseDimension==="1d"?1:Math.max(1,this.height>>e),o=this.dimension==="3d"?Math.max(1,this.depth>>e):this.depth;return{width:t,height:n,depthOrArrayLayers:o}}getAllocatedByteLength(){let e=0;for(let t=0;t<this.mipLevels;t++){let{width:n,height:o,depthOrArrayLayers:i}=this._getMipLevelSize(t);e+=Ut.computeMemoryLayout({format:this.format,width:n,height:o,depth:i,byteAlignment:1}).byteLength}return e*this.samples}static _normalizeOptions(e,t,n){for(let o in t)n[o]=e[o]===void 0?t[o]:e[o];return n}static defaultProps={...pe.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"}};var ou=Ie.DEBUG_DATA_MAX_LENGTH,Se=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:n=!1,buffer:o,ownsBuffer:i=!0,...s}=t;if(o&&o.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(o&&(s.byteLength!==void 0||s.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let a=t.id||o?.id||Ot("dynamic-buffer"),u={...s,id:a,usage:s.usage??o?.usage,indexType:s.indexType??o?.indexType};(u.usage||0)&Ie.INDEX&&!u.indexType&&(s.data instanceof Uint32Array?u.indexType="uint32":s.data instanceof Uint16Array?u.indexType="uint16":s.data instanceof Uint8Array&&(u.indexType="uint8")),delete u.data,delete u.byteOffset,this.device=e,this.id=a,this.props=u,this.usage=u.usage||0,this._debugDataEnabled=!!n,this._maxDebugDataByteLength=typeof n=="object"&&n.maxByteLength!==void 0?n.maxByteLength:ou,this._ownsBuffer=i,this._buffer=o??this.device.createBuffer({...s,id:a}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),s.data&&this._writeDebugData(s.data,s.byteOffset||0)}write(e,t=0){this._buffer.write(e,t),this._touch(),this._writeDebugData(e,t)}async mapAndWriteAsync(e,t=0,n=this.byteLength-t){let o=null;await this._buffer.mapAndWriteAsync(async(i,s)=>{await e(i,s),o=new Uint8Array(i.slice(0,n))},t,n),this._touch(),o&&this._writeDebugData(o,t)}async readAsync(e=0,t=this.byteLength-e){let n=await this._buffer.readAsync(e,t);return this._writeDebugData(n,e)&&this._touch(),n}async mapAndReadAsync(e,t=0,n=this.byteLength-t){let o=null,i=await this._buffer.mapAndReadAsync(async(s,a)=>(o=new Uint8Array(s.slice(0)),await e(s,a)),t,n);return o&&this._writeDebugData(o,t)&&this._touch(),i}resize(e){let{byteLength:t,preserveData:n=!1}=e;if(t===this.byteLength)return!1;let o=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),i=this._buffer,s=this.debugData.slice(0),{data:a,byteOffset:u,...c}=this.props,d=this.device.createBuffer({...c,byteLength:t});return n&&o>0&&this._copyBufferContents(i,d,o),this._buffer=d,this._resetDebugData(t),n&&s.byteLength>0&&this._writeDebugData(s,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,n){let o=this.device.type==="webgpu"?Math.ceil(n/4)*4:n,i=this.device.createCommandEncoder();i.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:o}),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 n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),o=new Uint8Array(this.debugData),i=Math.min(n.byteLength,o.byteLength-t);return o.set(n.subarray(0,i),t),i>0}};var Kn={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function rr(r){return r?Array.isArray(r)?r[0]??null:r:null}function Di(r){let{dimension:e,data:t}=r;if(!t)return null;switch(e){case"1d":{let n=rr(t);if(!n)return null;let{width:o}=nr(n);return{width:o,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let n=rr(t);return n?nr(n):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let n=rr(t[0]);return n?nr(n):null}case"cube":{let n=Object.keys(t)[0]??null;if(!n)return null;let o=t[n],i=rr(o);return i?nr(i):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let n=t[0],o=Object.keys(n)[0]??null;if(!o)return null;let i=rr(n[o]);return i?nr(i):null}default:return null}}function nr(r){if(tr(r))return Hr(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 iu(r){return typeof r=="object"&&r!==null&&"data"in r&&"width"in r&&"height"in r}function su(r){return ArrayBuffer.isView(r)}function Zn(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 _i(r){let e=Kn[r];if(e===void 0)throw new Error(`Invalid cube face: ${r}`);return e}function au(r,e){return 6*r+_i(e)}function Qn(r){throw new Error("setTexture1DData not supported in WebGL.")}function uu(r){return Array.isArray(r)?r:[r]}function gt(r,e,t,n){let o=uu(e),i=r,s=[];for(let a=0;a<o.length;a++){let u=o[a];if(tr(u))s.push({type:"external-image",image:u,z:i,mipLevel:a});else if(iu(u))s.push({type:"texture-data",data:u,textureFormat:Zn(u),z:i,mipLevel:a});else if(su(u)&&t)s.push({type:"texture-data",data:{data:u,width:Math.max(1,t.width>>a),height:Math.max(1,t.height>>a),...n?{format:n}:{}},textureFormat:n,z:i,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return s}function Jn(r){let e=[];for(let t=0;t<r.length;t++)e.push(...gt(t,r[t]));return e}function eo(r){let e=[];for(let t=0;t<r.length;t++)e.push(...gt(t,r[t]));return e}function to(r){let e=[];for(let[t,n]of Object.entries(r)){let o=_i(t);e.push(...gt(o,n))}return e}function ro(r){let e=[];return r.forEach((t,n)=>{for(let[o,i]of Object.entries(t)){let s=au(n,o);e.push(...gt(s,i))}}),e}var ot=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 n=Ot("dynamic-texture"),o=t;this.props={...r.defaultProps,id:n,...t,data:null},this.id=this.props.id,this.ready=new Promise((i,s)=>{this.resolveReady=i,this.rejectReady=s}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(o)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let n=t.data?cu({...t,width:e.width,height:e.height,format:e.format}):[],o="format"in e&&e.format!==void 0,i="usage"in e&&e.usage!==void 0,a=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let p=Di(t);return p||{width:this.props.width||1,height:this.props.height||1}})();if(!a||a.width<=0||a.height<=0)throw new Error(`${this} size could not be determined or was zero`);let u=du(this.device,n,a,{format:o?e.format:void 0}),c=u.format??this.props.format,d={...this.props,...a,format:c,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(c)&&!i&&(d.usage=ie.SAMPLE|ie.COPY_DST);let l=this.props.mipmaps&&!u.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(c);if(this.device.type==="webgpu"&&l){let p=this.props.dimension==="3d"?ie.SAMPLE|ie.STORAGE|ie.COPY_DST|ie.COPY_SRC:ie.SAMPLE|ie.RENDER|ie.COPY_DST|ie.COPY_SRC;d.usage|=p}let h=this.device.getMipLevelCount(d.width,d.height),f=u.hasExplicitMipChain?u.mipLevels:this.props.mipLevels==="auto"?h:Math.max(1,Math.min(h,this.props.mipLevels??1)),m={...d,mipLevels:f};this._texture=this.device.createTexture(m),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),u.subresources.length&&this._setTextureSubresources(u.subresources),this.props.mipmaps&&!u.hasExplicitMipChain&&!l&&ve.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),l&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),ve.info(1,`${this} created`)()}catch(t){let n=t instanceof Error?t:new Error(String(t));this.rejectReady(n)}}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()):ve.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof nt?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,n=e.height??this.texture.height,o=e.depthOrArrayLayers??this.texture.depth,i=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:o}),s=this.device.createBuffer({byteLength:i.byteLength,usage:Ie.COPY_DST|Ie.MAP_READ});this.texture.readBuffer({...e,width:t,height:n,depthOrArrayLayers:o},s);let a=this.device.createFence();return await a.signaled,a.destroy(),s}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,o=e.depthOrArrayLayers??this.texture.depth,i=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:o}),s=await this.readBuffer(e),a=await s.readAsync(0,i.byteLength);return s.destroy(),a.buffer instanceof ArrayBuffer?a.buffer:a.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(),ve.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=Kn[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=Qn(e);this._setTextureSubresources(t)}setTexture2DData(e,t=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let n=gt(t,e);this._setTextureSubresources(n)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=Jn(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=eo(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=to(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=ro(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:n,mipLevel:o}=t;switch(t.type){case"external-image":let{image:i,flipY:s}=t;this.texture.copyExternalImage({image:i,z:n,mipLevel:o,flipY:s});break;case"texture-data":let{data:a,textureFormat:u}=t;if(u&&u!==this.texture.format)throw new Error(`${this} mip level ${o} uses format "${u}" but texture format is "${this.texture.format}"`);this.texture.writeData(a.data,{x:0,y:0,z:n,width:a.width,height:a.height,depthOrArrayLayers:1,mipLevel:o});break;default:throw new Error("Unsupported 2D mip-level payload")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await no(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&ve.warn(`${this} already destroyed`)}_checkReady(){this.isReady||ve.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...ie.defaultProps,dimension:"2d",data:null,mipmaps:!1}};function cu(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 Qn(r.data);case"2d":return gt(0,r.data,e,t);case"3d":return Jn(r.data);case"2d-array":return eo(r.data);case"cube":return to(r.data);case"cube-array":return ro(r.data);default:throw new Error(`Unhandled dimension ${r.dimension}`)}}function du(r,e,t,n){if(e.length===0)return{subresources:e,mipLevels:1,format:n.format,hasExplicitMipChain:!1};let o=new Map;for(let d of e){let l=o.get(d.z)??[];l.push(d),o.set(d.z,l)}let i=e.some(d=>d.mipLevel>0),s=n.format,a=Number.POSITIVE_INFINITY,u=[];for(let[d,l]of o){let h=[...l].sort((w,S)=>w.mipLevel-S.mipLevel),f=h[0];if(!f||f.mipLevel!==0)throw new Error(`DynamicTexture: slice ${d} is missing mip level 0`);let m=Fi(r,f);if(m.width!==t.width||m.height!==t.height)throw new Error(`DynamicTexture: slice ${d} base level dimensions ${m.width}x${m.height} do not match expected ${t.width}x${t.height}`);let p=Ai(f);if(p){if(s&&s!==p)throw new Error(`DynamicTexture: slice ${d} base level format "${p}" does not match texture format "${s}"`);s=p}let y=s&&r.isTextureFormatCompressed(s)?lu(r,m.width,m.height,s):r.getMipLevelCount(m.width,m.height),g=0;for(let w=0;w<h.length;w++){let S=h[w];if(!S||S.mipLevel!==w||w>=y)break;let T=Fi(r,S),v=Math.max(1,m.width>>w),b=Math.max(1,m.height>>w);if(T.width!==v||T.height!==b)break;let C=Ai(S);if(C&&(s||(s=C),C!==s))break;g++,u.push(S)}a=Math.min(a,g)}let c=Number.isFinite(a)?Math.max(1,a):1;return{subresources:u.filter(d=>d.mipLevel<c),mipLevels:c,format:s,hasExplicitMipChain:i}}function Ai(r){if(r.type==="texture-data")return r.textureFormat??Zn(r.data)}function Fi(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 lu(r,e,t,n){let{blockWidth:o=1,blockHeight:i=1}=r.getTextureFormatInfo(n),s=1;for(let a=1;;a++){let u=Math.max(1,e>>a),c=Math.max(1,t>>a);if(u<o||c<i)break;s++}return s}async function no(r){if(r=await r,Array.isArray(r))return await Promise.all(r.map(no));if(r&&typeof r=="object"&&r.constructor===Object){let e=r,t=await Promise.all(Object.values(e).map(no)),n=Object.keys(e),o={};for(let i=0;i<n.length;i++)o[n[i]]=t[i];return o}return r}var or=F(A(),1),Ri=/^vertex-list<([^<>]+)>$/,Vi=/^value-list<([^<>]+)>$/,bu=/^fixed-size-list<([^<>,]+),([1-9][0-9]*)>$/;function it(r){return Ri.test(r)}function st(r){return Vi.test(r)}function Mi(r){let e=Ri.exec(r),t=Vi.exec(r),o=Ni(r)?.elementFormat??e?.[1]??t?.[1]??r;try{or.vertexFormatDecoder.getVertexFormatInfo(o)}catch{throw new Error(`Unsupported GPUVector format ${r}`)}return o}function U(r){let e=Mi(r),t=it(r),n=st(r),o=Ni(r),i=or.vertexFormatDecoder.getVertexFormatInfo(e),s=i.byteLength*(o?.listSize??1);if(!Number.isSafeInteger(s))throw new Error(`Unsupported GPUVector format ${r}`);let a=i.type,u=i.normalized,c=xu(a,u);return{format:r,elementFormat:e,vertexList:t,valueList:n,fixedSizeList:!!o,...o?{listSize:o.listSize}:{},type:a,signedDataType:wu(e,a),primitiveType:c,components:i.components,elementByteLength:i.byteLength,byteLength:s,integer:i.integer,signed:i.signed,normalized:u,...i.webglOnly?{webglOnly:!0}:{}}}function Ni(r){let e=bu.exec(r);if(!e)return;let t=Number(e[2]);if(!Number.isSafeInteger(t))return;let n=e[1];try{let o=or.vertexFormatDecoder.getVertexFormatInfo(n);if(!Number.isSafeInteger(t*o.components)||!Number.isSafeInteger(t*o.byteLength))return}catch{return}return{elementFormat:n,listSize:t}}function xu(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 wu(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 io=F(A(),1),ir=class{buffer;format;length;byteOffset;byteStride;constructor(e){let t=io.vertexFormatDecoder.getVertexFormatInfo(e.format).byteLength,n=e.byteOffset??0,o=e.byteStride??t;if(oo(e.length,"GPUDataView length"),oo(n,"GPUDataView byteOffset"),oo(o,"GPUDataView byteStride"),o<t)throw new Error(`GPUDataView byteStride ${o} is smaller than ${e.format} byte length ${t}`);let i=e.length===0?0:(e.length-1)*o+t,s=n+i;if(!Number.isSafeInteger(i)||!Number.isSafeInteger(s))throw new Error("GPUDataView byte range must use safe integers");if(s>e.buffer.byteLength)throw new Error("GPUDataView exceeds its backing buffer byte length");this.buffer=e.buffer,this.format=e.format,this.length=e.length,this.byteOffset=n,this.byteStride=o}get elementByteLength(){return io.vertexFormatDecoder.getVertexFormatInfo(this.format).byteLength}get byteLength(){return this.length===0?0:(this.length-1)*this.byteStride+this.elementByteLength}};function oo(r,e){if(!Number.isSafeInteger(r)||r<0)throw new Error(`${e} must be a non-negative safe integer`)}var Gt=F(A(),1);function Yr(r){return!!(r&&typeof r=="object"&&r.type==="struct")}function ji(r,e){let t=Object.entries(r);if(t.length===0)throw new Error("GPUData struct format must declare at least one field");return e==="packed"?Tu(t):vu(t)}function Tu(r){let e=[],t=0,n=0;for(let[o,i]of r){let s=Gt.vertexFormatDecoder.getVertexFormatInfo(i);if(s.webglOnly)throw new Error(`Packed GPUData struct field "${o}" uses WebGL-only format ${i}`);t=zi(t,Math.min(4,s.byteLength)),e.push([o,Object.freeze({format:i,byteOffset:t,byteLength:s.byteLength})]),t+=s.byteLength,n+=s.components}return Object.freeze({type:"struct",layout:"packed",fields:Object.freeze(Object.fromEntries(e)),components:n,byteStride:zi(t,4),rowByteLength:t})}function vu(r){let e=Object.fromEntries(r.map(([s,a])=>[s,Su(a)])),t=(0,Gt.makeShaderBlockLayout)(e,{layout:"wgsl-storage"}),n=[],o=0,i=0;for(let[s,a]of r){let u=Gt.vertexFormatDecoder.getVertexFormatInfo(a),c=t.fields[s].offset*4;n.push([s,Object.freeze({format:a,byteOffset:c,byteLength:u.byteLength})]),o=Math.max(o,c+u.byteLength),i+=u.components}return Object.freeze({type:"struct",layout:"wgsl-storage",fields:Object.freeze(Object.fromEntries(n)),components:i,byteStride:t.byteLength,rowByteLength:o})}function Su(r){let e=Gt.vertexFormatDecoder.getVertexFormatInfo(r);switch(e.type){case"float32":return qr("f32",e.components);case"sint32":return qr("i32",e.components);case"uint32":return qr("u32",e.components);default:{let t=Math.ceil(e.byteLength/4);return qr("u32",t)}}}function qr(r,e){return e===1?r:`vec${e}<${r}>`}function zi(r,e){return Math.ceil(r/e)*e}var so=class{buffer;ownsDataBuffer;constructor(e,t){this.buffer=e,this.ownsDataBuffer=t}get ownsBuffer(){return this.ownsDataBuffer}transferBufferOwnership(e){if(e.buffer!==this.buffer)throw new Error("GPUData ownership can only be transferred to the same buffer");e.ownsDataBuffer=this.ownsDataBuffer,this.ownsDataBuffer=!1}destroy(){this.ownsDataBuffer&&(this.buffer.destroy(),this.ownsDataBuffer=!1)}},ao=class extends so{dataType;format;length;valueLength;stride;byteOffset;byteStride;rowByteLength;readbackMetadata;valueOffsets;nullBitmap;valueByteLength;constructor(e){let{buffer:t,format:n,length:o,valueLength:i,stride:s,byteOffset:a=0,byteStride:u,rowByteLength:c,ownsBuffer:d=!1,readbackMetadata:l,valueOffsets:h,nullBitmap:f,valueByteLength:m,dataType:p}=e;super(t,d);let y;n?typeof n=="string"?y=n:y=ji(n,e.layout??"wgsl-storage"):y=void 0;let g=Yr(y)?y:void 0,w=typeof y=="string"?U(y):void 0;if(this.dataType=p,this.format=y,this.length=o,this.valueLength=i??o*(w?.listSize??1),this.stride=s??(w?w.components*(w.listSize??1):void 0)??g?.components??u??c??1,this.byteOffset=a,this.rowByteLength=c??g?.rowByteLength??w?.byteLength??u??this.stride,this.byteStride=u??g?.byteStride??this.rowByteLength,w?.fixedSizeList){let S=o*w.listSize;if(!Number.isSafeInteger(o)||o<0||!Number.isSafeInteger(S)||!Number.isSafeInteger(this.byteOffset)||this.byteOffset<0||!Number.isSafeInteger(this.byteStride)||!Number.isSafeInteger(this.rowByteLength)||!Number.isSafeInteger(this.stride))throw new Error("GPUData fixed-size-list row layout must use safe non-negative integers");if(this.valueLength!==S)throw new Error("GPUData fixed-size-list valueLength must equal its flattened row elements");if(this.stride<w.components*w.listSize)throw new Error("GPUData fixed-size-list stride cannot truncate its row components");if(this.rowByteLength<w.byteLength)throw new Error("GPUData fixed-size-list rowByteLength cannot truncate its row payload");if(this.byteStride<this.rowByteLength)throw new Error("GPUData fixed-size-list byteStride cannot overlap its row payload");let T=o===0?0:(o-1)*this.byteStride+this.rowByteLength,v=this.byteOffset+T;if(!Number.isSafeInteger(T)||!Number.isSafeInteger(v))throw new Error("GPUData fixed-size-list byte range must use safe integers");if(v>t.byteLength)throw new Error("GPUData fixed-size-list exceeds its backing buffer byte length")}if(g){if(this.rowByteLength<g.rowByteLength)throw new Error(`GPUData rowByteLength ${this.rowByteLength} is smaller than struct format row byte length ${g.rowByteLength}`);if(this.byteStride<Math.max(g.byteStride,this.rowByteLength))throw new Error(`GPUData byteStride ${this.byteStride} is smaller than its struct row layout`)}this.readbackMetadata=l,this.valueOffsets=h,this.nullBitmap=f,this.valueByteLength=m}getChild(e){if(!Yr(this.format))return null;let t=this.format.fields[e];return t?new ir({buffer:this.buffer,format:t.format,length:this.length,byteOffset:this.byteOffset+t.byteOffset,byteStride:this.byteStride}):null}getChildAt(e){if(!Yr(this.format))return null;let t=Object.values(this.format.fields)[e];return t?new ir({buffer:this.buffer,format:t.format,length:this.length,byteOffset:this.byteOffset+t.byteOffset,byteStride:this.byteStride}):null}},Dt=ao;function ze(r){let e=0;return Object.freeze(r.map(t=>{let n=Object.freeze({offset:e,length:t.length,data:t});return e+=t.length,n}))}var H=class{name;dataType;format;length;valueLength;stride;byteOffset;byteStride;rowByteLength;bufferLayout;data=[];device;bufferProps;isAppendable=!1;ownsDataChunks=!0;ownedVectors=[];appendableByteLength=0;get chunks(){return ze(this.data)}constructor(e){switch(e.type){case"buffer":{let{name:t,buffer:n,format:o,length:i,valueLength:s,byteOffset:a=0,ownsBuffer:u=!1}=e,{stride:c,byteStride:d,rowByteLength:l,listSize:h}=Wi(e),f=s??i*(h??1);this.name=t,this.dataType=e.dataType,this.format=o,this.length=i,this.valueLength=f,this.stride=c,this.byteOffset=a,this.byteStride=d,this.rowByteLength=l,this.data.push(new Dt({buffer:n,format:o,length:i,valueLength:f,stride:c,byteOffset:a,byteStride:d,rowByteLength:l,ownsBuffer:u,dataType:e.dataType}));return}case"interleaved":{let{name:t,buffer:n,format:o,length:i,valueLength:s,byteOffset:a=0,byteStride:u,attributes:c,ownsBuffer:d=!1}=e,l=o?U(o):void 0,h=s??i*(l?.listSize??1),f=l?.fixedSizeList?l.components*l.listSize:u,m=l?.fixedSizeList?l.byteLength:u;this.name=t,this.dataType=e.dataType,this.format=o,this.length=i,this.valueLength=h,this.stride=f,this.byteOffset=a,this.byteStride=u,this.rowByteLength=m,this.bufferLayout={name:t,byteStride:u,attributes:c},this.data.push(new Dt({buffer:n,format:o,length:i,valueLength:h,stride:f,byteOffset:a,byteStride:u,rowByteLength:m,ownsBuffer:d,dataType:e.dataType}));return}case"data":{let t=e.format??Eu(e.data),n=t?U(t):void 0,{name:o,data:i,stride:s=i[0]?.stride??(n?n.components*(n.listSize??1):1),valueLength:a=i.reduce((h,f)=>h+f.valueLength,0),byteStride:u=i[0]?.byteStride??n?.byteLength,rowByteLength:c=i[0]?.rowByteLength??n?.byteLength,bufferLayout:d,ownsData:l=!1}=e;if(u===void 0||c===void 0)throw new Error("GPUVector requires format or explicit byte layout metadata");t&&Pu(i,t),this.name=o,this.dataType=e.dataType,this.format=t,this.length=i.reduce((h,f)=>h+f.length,0),this.valueLength=a,this.stride=s,this.byteOffset=i.length===1?i[0].byteOffset:0,this.byteStride=u,this.rowByteLength=c,this.bufferLayout=d,this.ownsDataChunks=l,this.data.push(...i);return}case"appendable":{let{name:t,device:n,format:o,valueLength:i=0,bufferProps:s}=e,{stride:a,byteStride:u,rowByteLength:c}=Wi(e);this.name=t,this.dataType=e.dataType,this.format=o,this.length=0,this.valueLength=i,this.stride=a,this.byteOffset=0,this.byteStride=u,this.rowByteLength=c,this.device=n,this.bufferProps=s,this.isAppendable=!0;return}}}get ownsBuffer(){return this.ownsDataChunks&&this.data.some(e=>e.ownsBuffer)||this.ownedVectors.some(e=>e.ownsBuffer)}get capacityRows(){return this.isAppendable?this.length:void 0}get appendedByteLength(){return this.appendableByteLength}addData(e){if(this.format&&e.format!==this.format)throw new Error("GPUVector.addData() requires matching formats");if(e.byteStride!==this.byteStride)throw new Error("GPUVector.addData() requires matching byteStride");if(e.rowByteLength!==this.rowByteLength)throw new Error("GPUVector.addData() requires matching rowByteLength");return this.data.push(e),this.length+=e.length,this.valueLength+=e.valueLength,this}appendDataChunk(e,t=this.appendableByteLength+e.buffer.byteLength){if(!this.isAppendable)throw new Error("GPUVector.appendDataChunk() requires appendable vector storage");if(this.format&&e.format!==this.format)throw new Error("GPUVector.appendDataChunk() requires matching formats");if(e.byteStride!==this.byteStride||e.rowByteLength!==this.rowByteLength)throw new Error("GPUVector.appendDataChunk() requires matching byte layout metadata");return this.data.push(e),this.length+=e.length,this.valueLength+=e.valueLength,this.appendableByteLength=t,this}resetLastBatch(){if(!this.isAppendable)throw new Error("GPUVector.resetLastBatch() requires appendable vector storage");for(let e of this.data.splice(0))e.destroy();return this.length=0,this.valueLength=0,this.appendableByteLength=0,this}retainOwnedVectors(e){return this.ownedVectors.push(...e),this}transferBufferOwnership(e){let t=this.data[0],n=e.data[0];if(!t||!n||t.buffer!==n.buffer)throw new Error("GPUVector ownership can only be transferred to the same buffer");t.transferBufferOwnership(n)}destroy(){if(this.ownsDataChunks)for(let e of this.data)e.destroy();for(let e of this.ownedVectors.splice(0))e.destroy()}};function Wi(r){let e=r.format?U(r.format):void 0,t=r.rowByteLength??(e?.fixedSizeList?e.byteLength:r.byteStride)??e?.byteLength;if(t===void 0)throw new Error("GPUVector requires format or explicit rowByteLength");return{stride:r.stride??(e?e.components*(e.listSize??1):1),byteStride:r.byteStride??t,rowByteLength:t,...e?.listSize?{listSize:e.listSize}:{}}}function Eu(r){return r[0]?.format}function Pu(r,e){if(r.find(n=>n.format!==e))throw new Error("GPUVector data chunks must share the declared format")}var uo=F(A(),1);var sr=F(A(),1);var ar=class{buffer;format;length;valueLength;byteOffset;byteStride;rowByteLength;valueOffsets;nullBitmap;constructor(e){let t=U(e.format),n=ArrayBuffer.isView(e.buffer)?e.buffer:void 0;this.buffer=n?n.buffer:e.buffer,this.format=e.format,this.length=e.length,this.valueLength=e.valueLength??e.length*(t.listSize??1);let o=e.byteOffset??0;this.byteOffset=(n?.byteOffset??0)+o,this.rowByteLength=e.rowByteLength??t.byteLength,this.byteStride=e.byteStride??this.rowByteLength,this.valueOffsets=e.valueOffsets,this.nullBitmap=e.nullBitmap;let i=t.vertexList||t.valueList,s=i?this.valueLength:this.length;(0,sr.assert)([this.length,this.valueLength,o,this.rowByteLength,this.byteStride].every(a=>Number.isSafeInteger(a)&&a>=0)),(0,sr.assert)(this.rowByteLength>=t.byteLength&&this.byteStride>=this.rowByteLength),(0,sr.assert)(i||this.valueLength===this.length*(t.listSize??1)),(0,sr.assert)(o+(s?(s-1)*this.byteStride+this.rowByteLength:0)<=e.buffer.byteLength)}};var Hi=F(A(),1),Ee=class{name;format;data;length;valueLength;constructor(e){(0,Hi.assert)(e.data.every(t=>t.format===e.format)),this.name=e.name??"",this.format=e.format,this.data=Object.freeze([...e.data]),this.length=this.data.reduce((t,n)=>t+n.length,0),this.valueLength=this.data.reduce((t,n)=>t+n.valueLength,0)}};var ur=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 n=Math.floor((t-1)/2);if(this.compare(this.values[n],e)<=0)break;this.values[t]=this.values[n],t=n}this.values[t]=e}pop(){let e=this.values[0],t=this.values.pop();if(this.values.length&&t!==void 0){let n=0;for(;n*2+1<this.values.length;){let o=n*2+1;if(o+1<this.values.length&&this.compare(this.values[o+1],this.values[o])<0&&o++,this.compare(t,this.values[o])<=0)break;this.values[n]=this.values[o],n=o}this.values[n]=t}return e}};var at=F(A(),1);function Zi(r){let e=ts(r.nodes),t=rs(e,r.buffers.values()),n=ns(e,r.textures.values()),o=new Map,i=new Map,s=[];try{for(let a of t){a.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(a)}`,byteLength:a.byteLength,usage:a.usage});for(let u of a.handles)o.set(u,a.buffer)}for(let a of n){a.texture=r.device.createTexture({...a.descriptor,id:`${r.id}-transient-texture-${n.indexOf(a)}`});for(let u of a.handles)i.set(u,a.texture)}for(let a of e)s.push({node:a,executable:a.compile({device:r.device})})}catch(a){for(let u of s)u.executable.destroy?.();for(let u of t)u.buffer?.destroy();for(let u of n)u.texture?.destroy();throw a}return Ji(r,e,s,o,i,t,n)}async function Qi(r){let e=ts(r.nodes),t=rs(e,r.buffers.values()),n=ns(e,r.textures.values()),o=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 m of f.handles)o.set(m,f.buffer)}for(let f of n){f.texture=r.device.createTexture({...f.descriptor,id:`${r.id}-transient-texture-${n.indexOf(f)}`});for(let m of f.handles)i.set(m,f.texture)}let s=at.PipelineFactory.beginAsyncCompilation(r.device),a=e.map(async f=>({node:f,executable:f.compileAsync?await f.compileAsync({device:r.device}):f.compile({device:r.device})}));at.PipelineFactory.endAsyncCompilation(r.device,s);let[u,c]=await Promise.all([Promise.allSettled(a),Promise.allSettled(s)]),d=[],l=c.find(f=>f.status==="rejected"),h=l?.status==="rejected"?l.reason:void 0;for(let f of u)f.status==="fulfilled"?d.push(f.value):h??=f.reason;if(h){for(let f of d)f.executable.destroy?.();throw h}return Ji(r,e,d,o,i,t,n)}catch(s){for(let a of t)a.buffer?.destroy();for(let a of n)a.texture?.destroy();throw s}}function Ji(r,e,t,n,o,i,s){let a=Array.from(r.buffers.values()),u=a.filter(E=>!E.transient),c=a.filter(E=>E.transient),d=_t(u.map(E=>E.byteLength),"imported buffer capacities"),l=_t(c.map(E=>E.byteLength),"logical transient buffer capacities"),h=yt(d,l,"logical buffer capacities"),f=_t(i.map(E=>E.byteLength),"physical transient buffer capacities"),m=Math.max(0,l-f),p=Array.from(r.textures.values()),y=p.filter(E=>!E.transient),g=p.filter(E=>E.transient),w=_t(y.map(ho),"imported texture estimates"),S=_t(g.map(ho),"logical transient texture estimates"),T=yt(w,S,"logical texture estimates"),v=_t(s.map(E=>E.byteLength),"physical transient texture estimates"),b=Math.max(0,S-v),C={nodeOrder:e.map(E=>E.id),importedBufferCount:u.length,importedBufferBytes:d,logicalBufferCount:a.length,logicalBufferBytes:h,logicalTransientBufferCount:c.length,physicalTransientBufferCount:i.length,logicalTransientBytes:l,physicalTransientBytes:f,reusedTransientBytes:m,reusePercentage:l>0?m/l*100:0,importedTextureCount:y.length,importedTextureBytes:w,logicalTextureCount:p.length,logicalTextureBytes:T,logicalTransientTextureCount:g.length,physicalTransientTextureCount:s.length,logicalTransientTextureBytes:S,physicalTransientTextureBytes:v,reusedTransientTextureBytes:b,textureReusePercentage:S>0?b/S*100:0,logicalResourceBytes:yt(h,T,"logical resource estimates"),physicalTransientResourceBytes:yt(f,v,"physical transient resource estimates")},B=Lu(r.device,a,e,r.kernelMetadata);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:n,transientTextures:o,bufferTransientAllocations:i,textureTransientAllocations:s,stats:C,preflight:B}}function Cu(r){if("buffer"in r){let t=r.buffer,n="buffer"in t?t:void 0;return Object.freeze({id:n?n.buffer.id:t.id,kind:"buffer",usage:r.usage,byteOffset:n?.byteOffset??0,byteLength:n?n.length===0?0:(n.length-1)*n.byteStride+n.rowByteLength:t.byteLength,...n?{format:n.format,length:n.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 Lu(r,e,t,n){let o=t.map(u=>{let c=u.workload??{},d=n&&u.type==="compute"?u.kernel:void 0;return Object.freeze({id:u.id,...u.description===void 0?{}:{description:u.description},type:u.type,...d&&{kernel:Object.freeze({entryPoint:d.entryPoint,workgroupSize:Object.freeze([...d.workgroupSize]),bindings:Object.freeze(d.bindings.map(({name:l,type:h,group:f,location:m})=>Object.freeze({name:l,type:h,group:f,location:m}))),...n==="source"&&d.source!==void 0?{source:d.source}:{}})},resources:Object.freeze((u.resources??[]).map(Cu)),...c.operation?{operation:c.operation}:{},...c.variant?{variant:c.variant}:{},...u.publication?{publication:Object.freeze({...u.publication})}:{},...u.condition?{condition:Object.freeze(u.condition.source==="cpu"?{id:u.condition.id,source:"cpu",mode:"skip"}:{id:u.condition.id,source:"gpu",mode:"indirect",bufferId:u.condition.buffer.id,byteOffset:u.condition.byteOffset??0})}:{},commandCount:c.commandCount??0,maximumWorkgroupCount:c.maximumWorkgroupCount??0,maximumInvocationCount:c.maximumInvocationCount??0,readByteLength:c.readByteLength??0,writeByteLength:c.writeByteLength??0})}),i=e.reduce((u,c)=>Math.max(u,c.byteLength),0),s=t.reduce((u,c)=>{for(let d of c.resources??[])ut(d)&&(d.usage==="storage-read"||d.usage==="storage-write"||d.usage==="storage-read-write")&&(u=Math.max(u,lo(d.buffer).size));return u},0),a=u=>o.reduce((c,d)=>{let l=d[u];return typeof l=="number"?yt(c,l,"workload estimates"):c},0);return Object.freeze({nodes:Object.freeze(o),annotatedNodeCount:t.filter(u=>u.workload!==void 0).length,conditionalNodeCount:t.filter(u=>u.condition!==void 0).length,commandCount:a("commandCount"),maximumWorkgroupCount:a("maximumWorkgroupCount"),maximumInvocationCount:a("maximumInvocationCount"),readByteLength:a("readByteLength"),writeByteLength:a("writeByteLength"),largestBufferByteLength:i,largestStorageBufferBindingByteLength:s,maxBufferByteLength:r.limits.maxBufferSize,maxStorageBufferBindingByteLength:r.limits.maxStorageBufferBindingSize,fitsDeviceLimits:i<=r.limits.maxBufferSize&&s<=r.limits.maxStorageBufferBindingSize})}function Pe(r){return"buffer"in r?r.buffer:r}function je(r){return"texture"in r?r.texture:r}function ut(r){return"buffer"in r}function cr(r){return"texture"in r}function es(r){if(r.type==="copy")return;let e=(r.resources??[]).filter(t=>ut(t)&&(t.usage==="storage-read"||t.usage==="storage-write"||t.usage==="storage-read-write"));for(let t=0;t<e.length;t++){let n=e[t];for(let o=t+1;o<e.length;o++){let i=e[o];if(n.buffer===i.buffer||Pe(n.buffer)!==Pe(i.buffer)||!fo(n.usage)&&!fo(i.usage))continue;let s=lo(n.buffer),a=lo(i.buffer);if(s.offset<a.offset+a.size&&a.offset<s.offset+s.size){let u=Pe(n.buffer);throw new Error(`GPUCommandGraph node "${r.id}" has overlapping writable storage bindings for buffer "${u.id}" (${qi(s)} and ${qi(a)}). Bind the shared range once or align the views to non-overlapping storage binding ranges.`)}}}}function lo(r){if(!("buffer"in r))return{offset:0,size:r.byteLength};let e=256,t=Math.floor(r.byteOffset/e)*e,n=r.byteOffset-t,o=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:t,size:n+Math.max(o,r.rowByteLength)}}function qi(r){return`${r.offset}\u2013${r.offset+r.size} bytes`}function Bu(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 Yi(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 ts(r){let e=new Map(r.map(l=>[l.id,l])),t=new Map,n=new Map,o=new Map,i=new Map;for(let l of r){let h=new Set(l.dependsOn??[]);for(let f of h)if(!e.has(f))throw new Error(`GPUCommandGraph node "${l.id}" depends on missing node "${f}"`);for(let f of l.resources??[])if(ut(f)){let m=Pe(f.buffer);if(Bu(f.usage)){let p=n.get(m);p&&h.add(p);let y=o.get(m)??new Set;y.add(l.id),o.set(m,y)}if(fo(f.usage)){let p=n.get(m);p&&h.add(p);for(let y of o.get(m)??[])y!==l.id&&h.add(y);o.set(m,new Set),n.set(m,l.id)}}else if(cr(f)){let m=je(f.texture),p=i.get(m)??[];for(let y of p)y.nodeId!==l.id&&Ou(y.resource,f)&&(Yi(f.usage)&&co(y.resource.usage)||co(f.usage)&&(Yi(y.resource.usage)||co(y.resource.usage)))&&h.add(y.nodeId);p.push({nodeId:l.id,resource:f}),i.set(m,p)}h.delete(l.id),t.set(l.id,h)}let s=r.map(()=>[]),a=new Map(r.map((l,h)=>[l.id,h])),u=r.map(l=>t.get(l.id).size);for(let[l,h]of r.entries())for(let f of t.get(h.id))s[a.get(f)].push(l);let c=u.flatMap((l,h)=>l===0?[h]:[]),d=[];for(;c.length;){let l=[];for(let h of c){d.push(r[h]);for(let f of s[h])--u[f]===0&&l.push(f)}c=l.sort((h,f)=>h-f)}if(d.length!==r.length)throw new Error("GPUCommandGraph contains a dependency cycle");return d}function Ou(r,e){let t=je(r.texture),n=je(e.texture);if(t!==n)return!1;let o=Xi(r.texture),i=Xi(e.texture);return $u(o.aspect,i.aspect)&&Ki(o.baseMipLevel,o.mipLevelCount,i.baseMipLevel,i.mipLevelCount)&&Ki(o.baseArrayLayer,o.arrayLayerCount,i.baseArrayLayer,i.arrayLayerCount)}function Xi(r){return"texture"in r?r:{aspect:"all",baseMipLevel:0,mipLevelCount:r.mipLevels,baseArrayLayer:0,arrayLayerCount:r.dimension==="3d"?1:r.depth}}function $u(r,e){return r==="all"||e==="all"||r===e}function Ki(r,e,t,n){return r<t+n&&t<r+e}function rs(r,e){let t=os(r,c=>ut(c)?Pe(c.buffer):null),n=new Map;r.forEach((c,d)=>{if(!c.retainedBuffers?.length)return;let l=n.get(c.retainedBuffers);l?l.lastUse=d:n.set(c.retainedBuffers,{firstUse:d,lastUse:d})});for(let[c,d]of n)for(let l of c){if(!l.transient)continue;let h=t.get(l);t.set(l,{firstUse:Math.min(h?.firstUse??d.firstUse,d.firstUse),lastUse:Math.max(h?.lastUse??d.lastUse,d.lastUse)})}let o=[],i=Array.from(e).filter(c=>c.transient).map(c=>({buffer:c,lifetime:t.get(c)})).sort((c,d)=>(c.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(d.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)),s=new ur((c,d)=>c.allocation.lastUse-d.allocation.lastUse||c.index-d.index),a=new Map,u=c=>{let d=c&(at.Buffer.MAP_READ|at.Buffer.MAP_WRITE),l=a.get(d);return l||(l=new ur((h,f)=>h.allocation.byteLength-f.allocation.byteLength||h.index-f.index),a.set(d,l)),l};for(let{buffer:c,lifetime:d}of i){if(!d)continue;for(;s.peek()&&s.peek().allocation.lastUse<d.firstUse;){let f=s.pop();u(f.allocation.usage).push(f)}let l=u(c.usage).pop();l||(l={allocation:{byteLength:0,usage:0,lastUse:-1,handles:[]},index:o.length},o.push(l.allocation));let{allocation:h}=l;h.byteLength=Math.max(h.byteLength,c.byteLength),h.usage|=c.usage,h.lastUse=d.lastUse,h.handles.push(c),s.push(l)}return o}function ns(r,e){let t=os(r,i=>cr(i)?je(i.texture):null),n=[],o=Array.from(e).filter(i=>i.transient).map(i=>({texture:i,lifetime:t.get(i)})).sort((i,s)=>(i.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(s.lifetime?.firstUse??Number.MAX_SAFE_INTEGER));for(let{texture:i,lifetime:s}of o){if(!s)continue;let a=n.find(u=>u.lastUse<s.firstUse&&Iu(u.descriptor,i));a||(a={descriptor:ku(i),byteLength:ho(i),lastUse:-1,handles:[]},n.push(a)),a.descriptor.usage|=i.usage,a.lastUse=s.lastUse,a.handles.push(i)}return n}function os(r,e){let t=new Map;return r.forEach((n,o)=>{for(let i of n.resources??[]){let s=e(i);if(!s||!("transient"in s)||!s.transient)continue;let a=t.get(s);a?a.lastUse=o:t.set(s,{firstUse:o,lastUse:o})}}),t}function ku(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 Iu(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 ho(r){let e=0;for(let n=0;n<r.mipLevels;n++)e=yt(e,at.textureFormatDecoder.computeMemoryLayout({format:r.format,width:Math.max(1,r.width>>n),height:r.dimension==="1d"?1:Math.max(1,r.height>>n),depth:r.dimension==="3d"?Math.max(1,r.depth>>n):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 yt(r,e,t){let n=r+e;if(!Number.isSafeInteger(n))throw new Error(`GPUCommandGraph ${t} exceed safe integer range`);return n}function _t(r,e){return r.reduce((t,n)=>yt(t,n,e),0)}var We=class{id;byteLength;usage;transient;graph;defaultBuffer;constructor(e,t,n,o){this.graph=e,this.id=t.id,this.byteLength=t.byteLength,this.usage=t.usage,this.transient=n,this.defaultBuffer=o}},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}},O=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,n)=>t+n.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=ze(this.data)}},Ce=class{id;format;width;height;usage;dimension;depth;mipLevels;samples;transient;frameScoped;graph;defaultTexture;constructor(e,t,n,o,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=n,this.frameScoped=i,this.defaultTexture=o}},ct=class{id;width;height;graph;constructor(e,t){this.graph=e,this.id=t.id,this.width=t.width,this.height=t.height}},_e=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 mo(r,e){switch(e.type){case"compute":{let{type:t,...n}=e;r.addComputePass(n);return}case"render":{let{type:t,...n}=e;r.addRenderPass(n);return}case"copy":{let{type:t,...n}=e;r.addCopyPass(n);return}}}function He(r,e){for(let t of e)mo(r,t)}function V(r){return{...r,type:"compute"}}var Uu=4,At=class{nodeCount;budget;plan;encodeNodeRange;nextStepIndex=0;currentPublishedProgress=0;constructor(e){ds(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 n=this.plan.steps[this.nextStepIndex],o=this.encodeNodeRange(e,t,n.firstNodeIndex,n.nextNodeIndex);return this.nextStepIndex++,n.publishable&&(this.currentPublishedProgress=this.progress),{...n,encoding:o,progress:this.progress,completed:this.completed,publishedProgress:this.publishedProgress}}};function Kr(r,e,t={}){ds(e);let n=t.latencyPriority??"normal",o=t.publicationPolicy??"final";if(!["interactive","normal","background"].includes(n))throw new Error(`GPUCommandGraph execution latency priority "${n}" is invalid`);if(!["final","progressive"].includes(o))throw new Error(`GPUCommandGraph execution publication policy "${o}" is invalid`);let i=r.nodes,s=[],a=0;for(;a<i.length;){let c=a,d=is();for(;a<i.length;){let f=ss(d,i[a]);if(a>c&&as(f,e)||(d=f,a++,o==="progressive"&&i[a-1].publication)||Gu(d,e))break}let l=Object.freeze(o==="progressive"?i.slice(c,a).flatMap(f=>f.publication?[f.publication]:[]):[]),h=a===i.length;s.push(Object.freeze({stepIndex:s.length,firstNodeIndex:c,nextNodeIndex:a,...d,exceedsBudget:as(d,e),latencyPriority:n,publications:l,publishable:h||l.length>0}))}let u=i.reduce((c,d)=>ss(c,d),is());return Object.freeze({...u,annotatedNodeCount:r.annotatedNodeCount,stepCount:s.length,oversizedStepCount:s.filter(c=>c.exceedsBudget).length,latencyPriority:n,publicationPolicy:o,publicationCount:s.reduce((c,d)=>c+d.publications.length,0),steps:Object.freeze(s)})}function is(){return{nodeCount:0,commandCount:0,maximumInvocationCount:0,readByteLength:0,writeByteLength:0,conditionalNodeCount:0}}function ss(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 as(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 Gu(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 ds(r){let e=[["maximumInvocationCount",r.maximumInvocationCount],["maximumNodeCount",r.maximumNodeCount],["maximumCommandCount",r.maximumCommandCount],["maximumReadByteLength",r.maximumReadByteLength],["maximumWriteByteLength",r.maximumWriteByteLength]];for(let[t,n]of e)if(n!==void 0&&(!Number.isSafeInteger(n)||n<=0))throw new Error(`GPUCommandGraph execution ${t} must be a positive safe integer`)}function Du(r,e,t,n){let o=0;return{computePass:new Proxy(r,{get(s,a){if(a==="dispatch")return()=>{if(o>0)throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must encode exactly one dispatch`);o++,s.dispatchIndirect(e,t)};if(a==="dispatchIndirect")return()=>{throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must use dispatch(); the graph supplies its indirect command`)};let u=Reflect.get(s,a,s);return typeof u=="function"?u.bind(s):u}}),assertDispatched:()=>{if(o!==1)throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must encode exactly one dispatch`)}}}var Ft=class{readResource;stats;canReadGPUTimings;nodes;constructor(e,t,n=e.filter(a=>a.stats.type==="compute"&&a.stats.condition?.outcome!=="skipped").length,o,i,s){this.readResource=s,this.nodes=e,this.canReadGPUTimings=e.some(c=>c.timestamp!==void 0);let a=e.filter(c=>c.stats.condition?.outcome!=="skipped"),u=a.filter(c=>c.stats.type==="compute").length;this.stats={cpuEncodeTimeMilliseconds:t,cpuEncodeStartTimeMilliseconds:o,cpuEncodeEndTimeMilliseconds:i,nodeCount:a.length,skippedNodeCount:e.length-a.length,computePassCount:n,coalescedComputeNodeCount:u-n,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:s,timestamp:a})=>{if(!a)return{...s};let{querySet:u,snapshot:c,beginIndex:d,endIndex:l}=a;if(u.device.type!=="webgpu")return{...s,gpuTimeMilliseconds:await u.readTimestampDuration(d,l)};let h=await(c??u).readResults({firstQuery:d,queryCount:l-d+1}),f=h[0],m=h[h.length-1];return{...s,gpuStartTimeMilliseconds:Number(f)/1e6,gpuEndTimeMilliseconds:Number(m)/1e6,gpuTimeMilliseconds:Number(m-f)/1e6}})),t=e.filter(s=>s.gpuTimeMilliseconds!==void 0),n=e.filter(s=>s.gpuStartTimeMilliseconds!==void 0),i=this.nodes.flatMap(s=>s.timestamp?.snapshot?.clockCorrelation?[s.timestamp.snapshot.clockCorrelation]:[]).sort((s,a)=>s.uncertaintyMilliseconds-a.uncertaintyMilliseconds)[0];return{...i?{clockCorrelation:i}:{},cpuEncodeStartTimeMilliseconds:this.stats.cpuEncodeStartTimeMilliseconds,cpuEncodeEndTimeMilliseconds:this.stats.cpuEncodeEndTimeMilliseconds,...n.length>0?{gpuStartTimeMilliseconds:Math.min(...n.map(s=>s.gpuStartTimeMilliseconds)),gpuEndTimeMilliseconds:Math.max(...n.map(s=>s.gpuEndTimeMilliseconds))}:{},cpuEncodeTimeMilliseconds:this.stats.cpuEncodeTimeMilliseconds,...t.length>0?{gpuTimeMilliseconds:t.reduce((s,a)=>s+(a.gpuTimeMilliseconds??0),0)}:{},nodes:e}}},go=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={}){Xr(e,"construction"),this.device=e,this.id=t.id??"gpu-command-graph",this.autotuner=t.autotuner}importBuffer(e,t){this.assertMutable(),cs(e,this.device),t&&ls(t,e,this.device);let n=this.addBuffer(new We(this,e,!1,t));if(t){let o=fr(t);this.importedBufferHandles.has(o)||this.importedBufferHandles.set(o,n),t instanceof Se&&!this.dynamicBufferHandles.has(t)&&this.dynamicBufferHandles.set(t,n)}return n}createTransientBuffer(e){return this.assertMutable(),cs(e,this.device),this.addBuffer(new We(this,e,!0))}getUniqueResourceId(e){let t=e,n=1;for(;this.buffers.has(t)||this.textures.has(t)||this.externalTextures.has(t);)t=`${e}-${n++}`;return t}createDataView(e,t){this.assertBuffer(e);let n=U(t.format),o=t.byteOffset??0,i=t.rowByteLength??n.byteLength,s=t.byteStride??i;return Mu(e,{length:t.length,byteOffset:o,byteStride:s,rowByteLength:i}),new De(e,{format:t.format,length:t.length,byteOffset:o,byteStride:s,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 n=t.format??t.data[0]?.format;if(!n)throw new Error(`GPUCommandGraph import "${e}" requires GPUVector.format`);if(it(n)||st(n))throw new Error(`GPUCommandGraph import "${e}" requires a fixed-width GPUVector format`);let o=U(n),i=t.data.map((s,a)=>{if(s.format!==n)throw new Error(`GPUCommandGraph import "${e}" requires matching GPUVector chunk formats`);let u=t.data.length===1?e:`${e}-chunk-${a}`;return this.importGPUDataView(u,s)});return new O({id:e,name:t.name??e,format:n,length:t.length,valueLength:t.valueLength??t.data.reduce((s,a)=>s+a.valueLength,0),stride:t.stride??t.data[0]?.stride??o.components*(o.listSize??1),byteStride:t.byteStride??i[0]?.byteStride??o.byteLength,rowByteLength:t.rowByteLength??i[0]?.rowByteLength??o.byteLength,data:i})}importTexture(e,t){this.assertMutable();let n=po(e,this.device);return t&&bo(t,n,this.device),this.addTexture(new Ce(this,n,!1,t))}importFrameTexture(e){this.assertMutable();let t=po(e,this.device);return this.addTexture(new Ce(this,t,!1,void 0,!0))}importExternalTexture(e){return this.assertMutable(),Ru(e,this.device),this.addExternalTexture(new ct(this,e))}createTransientTexture(e){this.assertMutable();let t=po(e,this.device);return this.addTexture(new Ce(this,t,!0))}createTextureView(e,t={}){this.assertTexture(e);let n=Vu(e,t);return new _e(e,n)}add(e){if(this.assertMutable(),"getNodes"in e)for(let t of e.getNodes())this.add(t);else if("getCommandNodes"in e)He(this,e.getCommandNodes(this));else if("type"in e)mo(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(n=>({texture:n,usage:"render-attachment"})),...(e.attachments.resolveTargets??[]).filter(n=>n!==null).map(n=>({texture:n,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(e={}){return this.assertMutable(),Xr(this.device,"compilation"),this.compiled=!0,new bt(Zi({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes,kernelMetadata:e.kernelMetadata}))}async compileAsync(e={}){return this.assertMutable(),Xr(this.device,"compilation"),this.compiled=!0,new bt(await Qi({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes,kernelMetadata:e.kernelMetadata}))}addNode(e){if(this.device.type!=="webgpu"&&e.type!=="render")throw new Error("WebGL graphs support render passes only");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,n]of Object.entries(e.workload??{}))if(t==="operation"||t==="variant"){if(typeof n!="string"||!n)throw new Error(`GPUCommandGraph node "${e.id}" workload ${t} must be nonempty`)}else if(typeof n!="number"||!Number.isSafeInteger(n)||n<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 n=t.byteOffset??0;if(!Number.isSafeInteger(n)||n<0||n%4!==0)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition byteOffset must be a nonnegative multiple of 4`);if(n+3*Uu>t.buffer.byteLength)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition indirect command exceeds buffer "${t.buffer.id}"`);(e.resources??[]).some(o=>ut(o)&&Pe(o.buffer)===t.buffer&&o.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(ut(t)){let n=Pe(t.buffer);this.assertBuffer(n),zu(n,t.usage)}else if(cr(t)){let n=je(t.texture);if(this.assertTexture(n),ju(n,t.usage),Wu(t.texture,t.usage),this.device.type==="webgl"&&t.usage==="sampled"&&t.texture instanceof _e&&!fs(t.texture))throw new Error("WebGL sampled textures require a full-resource view")}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")}es(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 n=fr(t.buffer),o={byteLength:_u(t),usage:n.usage},i=t.buffer instanceof Se?this.getDynamicBufferHandle(t.buffer,o):this.getImportedBufferHandle(n,o);return i||(i=this.importBuffer({id:e,byteLength:n.byteLength,usage:n.usage},t.buffer),t.buffer instanceof Se?this.dynamicBufferHandles.set(t.buffer,i):this.importedBufferHandles.set(n,i)),this.createDataView(i,{format:t.format,length:t.length,byteOffset:t.byteOffset,byteStride:t.byteStride,rowByteLength:t.rowByteLength})}getDynamicBufferHandle(e,t){let n=this.dynamicBufferHandles.get(e);if(n?.defaultBuffer===e&&dr(n,t))return n;this.dynamicBufferHandles.delete(e);for(let o of this.buffers.values())if(o.defaultBuffer===e&&dr(o,t))return this.dynamicBufferHandles.set(e,o),o}getImportedBufferHandle(e,t){let n=this.importedBufferHandles.get(e);if(n?.defaultBuffer&&fr(n.defaultBuffer)===e&&dr(n,t))return n;this.importedBufferHandles.delete(e);for(let[o,i]of this.dynamicBufferHandles)if(o.buffer===e&&dr(i,t))return this.importedBufferHandles.set(e,i),i;for(let o of this.buffers.values())if(o.defaultBuffer===e&&dr(o,t))return this.importedBufferHandles.set(e,o),o}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 n=[...t.colorAttachments,...t.depthStencilAttachment?[t.depthStencilAttachment]:[]];for(let s of n)if(this.assertTexture(s.texture),s.dimension!=="2d"||s.mipLevelCount!==1||s.arrayLayerCount!==1)throw new Error(`GPUCommandGraph render node "${e}" attachments must be single-mip, single-layer 2d views`);let[o,...i]=n;for(let s of i)if(s.width!==o.width||s.height!==o.height||s.texture.samples!==o.texture.samples)throw new Error(`GPUCommandGraph render node "${e}" attachments must have matching extent and samples`);this.validateResolveTargets(e,t)}validateResolveTargets(e,t){let n=t.resolveTargets;if(n){if(this.device.type!=="webgpu")throw new Error(`GPUCommandGraph render node "${e}" resolve targets require WebGPU`);if(n.length!==t.colorAttachments.length)throw new Error(`GPUCommandGraph render node "${e}" requires one resolve entry per color attachment`);for(let o=0;o<n.length;o++){let i=n[o];if(!i)continue;let s=t.colorAttachments[o];if(this.assertTexture(i.texture),s.texture.samples<=1||i.texture.samples!==1||s.format!==i.format||s.width!==i.width||s.height!==i.height)throw new Error(`GPUCommandGraph render node "${e}" resolve target ${o} 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`)}}}},bt=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 n of t.resources??[])if(ut(n)){let o=Pe(n.buffer);o.transient||(this.activeImportedBufferHandles.add(o),(n.usage==="storage-write"||n.usage==="storage-read-write"||n.usage==="copy-destination")&&this.writableImportedBufferHandles.add(o))}else if(cr(n)){let o=je(n.texture);o.transient||(this.activeImportedTextureHandles.add(o),(n.usage==="storage-write"||n.usage==="storage-read-write"||n.usage==="render-attachment"||n.usage==="copy-destination")&&this.writableImportedTextureHandles.add(o))}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=Fu(this.device)}encode(e,t){return this.encodeNodeRange(e,t,0,this.compiledNodes.length)}getExecutionPlan(e,t={}){return Kr(this.preflight,e,t)}createExecution(e,t={}){return new At({plan:this.getExecutionPlan(e,t),budget:e,encodeNodeRange:(n,o,i,s)=>this.encodeNodeRange(n,o,i,s)})}encodeNodeRange(e,t,n,o){if(this.destroyed)throw new Error(`CompiledGPUCommandGraph "${this.id}" has been destroyed`);if(Xr(this.device,"encoding"),e.device!==this.device)throw new Error("GPUCommandGraph command encoder must belong to the graph device");let i=lr(),s=this.resolveImportedBuffers(t.buffers??{});Au(t.frameTextures??{},t.externalTextures??{});let a=this.resolveImportedTextures(t.textures??{},t.frameTextures??{}),u=this.resolveExternalTextures(t.externalTextures??{});for(let[v,b]of a.frameIds)this.lastFrameIds.set(v,b);for(let[v,b]of u.frameIds)this.lastExternalTextureFrameIds.set(v,b);for(let v of u.textures.values())this.consumedExternalTextures.add(v);let c=a.textures,d=v=>{let b=Pe(v),C=b.transient?this.transientBuffers.get(b):s.get(b);if(!C)throw new Error(`GPUCommandGraph buffer "${b.id}" is not bound`);return C},l=v=>{let b=je(v),C=b.transient?this.transientTextures.get(b):c.get(b);if(!C)throw new Error(`GPUCommandGraph texture "${b.id}" is not bound`);return C},h=v=>{let b=l(v);if(v instanceof Ce||fs(v))return b.view;if(v.texture.frameScoped){let E=this.lastFrameIds.get(v.texture);for(let $=this.cachedTextureViews.length-1;$>=0;$--){let L=this.cachedTextureViews[$];L.logicalView===v&&L.frameId!==E&&(this.destroyFramebuffersUsingView(L.view),L.view.destroy(),this.cachedTextureViews.splice($,1))}}let C=this.cachedTextureViews.find(E=>E.logicalView===v&&E.texture===b&&(!v.texture.frameScoped||E.frameId===this.lastFrameIds.get(v.texture)));if(C)return C.view;let B=b.createView({format:v.format,dimension:v.dimension,aspect:v.aspect,baseMipLevel:v.baseMipLevel,mipLevelCount:v.mipLevelCount,baseArrayLayer:v.baseArrayLayer,arrayLayerCount:v.arrayLayerCount});return this.cachedTextureViews.push({logicalView:v,texture:b,view:B,...v.texture.frameScoped?{frameId:this.lastFrameIds.get(v.texture)}:{}}),B},f=v=>{let b=u.textures.get(v);if(!b)throw new Error(`GPUCommandGraph external texture "${v.id}" is not bound`);return b},m={commandEncoder:e,parameters:t.parameters,getBuffer:d,getTexture:l,getTextureView:h,getExternalTexture:f},p=[],y,g=0,w=t.coalesceComputePasses!==!1&&e.getTimeProfilingQuerySet()===null,S=()=>{let v=y;y=void 0,v?.end()};try{for(let v=n;v<o;v++){let{node:b,executable:C}=this.compiledNodes[v],B=lr();if(b.condition?.source==="cpu"){let L=!1;try{L=b.condition.evaluate(t.parameters)}catch(_){let j=_ instanceof Error?_.message:String(_);throw new Error(`GPUCommandGraph CPU condition "${b.condition.id}" failed for node "${b.id}": ${j}`)}if(!L){let _=lr();p.push({stats:{id:b.id,description:b.description,resources:this.preflight.nodes[v].resources,operation:b.workload?.operation,type:b.type,cpuEncodeStartTimeMilliseconds:B,cpuEncodeEndTimeMilliseconds:_,cpuEncodeTimeMilliseconds:_-B,hasGPUTimestamps:!1,condition:{id:b.condition.id,source:"cpu",outcome:"skipped"}}});continue}}let E;switch(b.type){case"compute":{y||(y=e.beginComputePass({id:b.id}),g++);let L=y;E=us(L,e),E&&(w=!1),L.pushDebugGroup(b.id);try{let _=b.condition?.source==="gpu"?b.condition:void 0,j=_?Du(L,d(_.buffer),_.byteOffset??0,b.id):void 0;C.encode({...m,computePass:j?.computePass??L}),j?.assertDispatched()}finally{L.popDebugGroup()}w||S();break}case"render":{S();let L=C,_=L.getRenderPassProps?.(m)??{id:b.id};if(b.attachments&&_.framebuffer!==void 0)throw new Error(`GPUCommandGraph render node "${b.id}" cannot supply framebuffer with graph attachments`);if(b.attachments?.resolveTargets&&_.resolveTargets!==void 0)throw new Error(`GPUCommandGraph render node "${b.id}" cannot supply resolveTargets with graph attachments`);let j=b.attachments?this.getFramebuffer(b.id,b.attachments,h):void 0,W=b.attachments?.resolveTargets?.map(ne=>ne?h(ne):null),le=e.beginRenderPass({..._,...j?{framebuffer:j}:{},...W?{resolveTargets:W}:{}});E=us(le,e),le.pushDebugGroup(b.id);try{L.encode({...m,renderPass:le})}finally{le.popDebugGroup(),le.end()}break}case"copy":S(),C.encode(m);break}let $=lr();p.push({stats:{id:b.id,description:b.description,resources:this.preflight.nodes[v].resources,operation:b.workload?.operation,type:b.type,cpuEncodeStartTimeMilliseconds:B,cpuEncodeEndTimeMilliseconds:$,cpuEncodeTimeMilliseconds:$-B,hasGPUTimestamps:E!==void 0,...b.condition?{condition:{id:b.condition.id,source:b.condition.source,outcome:b.condition.source==="gpu"?"gpu-resolved":"executed"}}:{}},timestamp:E})}}finally{S()}let T=lr();return new Ft(p,T-i,g,i,T,async(v,b)=>{if(this.destroyed)throw new Error("Graph has been destroyed.");let C=this.compiledNodes.findIndex(({node:j})=>j.id===v),B=this.compiledNodes[C]?.node.resources?.[b],E=this.preflight.nodes[C]?.resources?.[b];if(!B||!E)throw new Error("Resource is unavailable.");if("externalTexture"in B)throw new Error("External images cannot be read back.");let $="buffer"in B?Pe(B.buffer):je(B.texture);if("frameScoped"in $&&$.frameScoped)throw new Error("Frame textures expire after presentation.");let L="buffer"in B?d(B.buffer):l(B.texture),_=L instanceof ce.Buffer?this.transientBuffers:this.transientTextures;if($.transient&&[..._].some(([j,W])=>j!==$&&W===L))throw new Error("Transient allocation is reused; logical contents are no longer available.");return ci(L,E)})}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,n=new Map;for(let[o,i]of this.buffers){if(i.transient)continue;let s=e[o]??i.defaultBuffer;if(!s)throw new Error(`GPUCommandGraph imported buffer "${o}" is required`);ls(s,i,this.device);let a=fr(s);if(this.activeImportedBufferHandles.has(i)){let u=a.handle,c=typeof u=="object"&&u!==null||typeof u=="function"?u:a,d=n.get(c);if(d&&(this.writableImportedBufferHandles.has(d)||this.writableImportedBufferHandles.has(i)))throw new Error(`GPUCommandGraph imported buffers "${d.id}" and "${o}" resolve to the same physical buffer`);d||n.set(c,i)}t.set(i,a)}for(let o of Object.keys(e)){let i=this.buffers.get(o);if(!i||i.transient)throw new Error(`GPUCommandGraph has no imported buffer named "${o}"`)}return t}resolveImportedTextures(e,t){let n=new Map,o=new Map;for(let[s,a]of this.textures){if(a.transient)continue;if(a.frameScoped){let c=t[s];if(!c)throw new Error(`GPUCommandGraph frame texture "${s}" is required`);let d=this.lastFrameIds.get(a);if(d!==void 0&&c.frameId<=d)throw new Error(`GPUCommandGraph frame texture "${s}" frameId ${c.frameId} is stale; expected greater than ${d}`);bo(c.texture,a,this.device),n.set(a,yo(c.texture)),o.set(a,c.frameId);continue}let u=e[s]??a.defaultTexture;if(!u)throw new Error(`GPUCommandGraph imported texture "${s}" is required`);bo(u,a,this.device),n.set(a,yo(u))}for(let s of Object.keys(e)){let a=this.textures.get(s);if(!a||a.transient||a.frameScoped)throw new Error(`GPUCommandGraph has no imported texture named "${s}"`)}for(let s of Object.keys(t))if(!this.textures.get(s)?.frameScoped)throw new Error(`GPUCommandGraph has no frame texture named "${s}"`);let i=new Map;for(let[s,a]of n){if(!this.activeImportedTextureHandles.has(s))continue;let u=a.handle,c=typeof u=="object"&&u!==null||typeof u=="function"?u:a,d=i.get(c);if(d&&(this.writableImportedTextureHandles.has(d)||this.writableImportedTextureHandles.has(s)))throw new Error(`GPUCommandGraph imported textures "${d.id}" and "${s.id}" resolve to the same physical texture`);d||i.set(c,s)}return{textures:n,frameIds:o}}resolveExternalTextures(e){let t=new Map,n=new Map;for(let[o,i]of this.externalTextures){let s=e[o];if(!s)throw new Error(`GPUCommandGraph external texture "${o}" is required`);let a=this.lastExternalTextureFrameIds.get(i);if(a!==void 0&&s.frameId<=a)throw new Error(`GPUCommandGraph external texture "${o}" frameId ${s.frameId} is stale; expected greater than ${a}`);if(this.consumedExternalTextures.has(s.texture))throw new Error(`GPUCommandGraph external texture "${o}" requires a fresh binding for each frame`);Nu(s.texture,i,this.device),t.set(i,s.texture),n.set(i,s.frameId)}for(let o of Object.keys(e))if(!this.externalTextures.has(o))throw new Error(`GPUCommandGraph has no external texture named "${o}"`);return{textures:t,frameIds:n}}getFramebuffer(e,t,n){let o=t.colorAttachments.map(n),i=t.depthStencilAttachment?n(t.depthStencilAttachment):void 0,s=this.cachedFramebuffers.find(c=>c.nodeId===e&&c.depthStencilAttachment===i&&c.colorAttachments.length===o.length&&c.colorAttachments.every((d,l)=>d===o[l]));if(s)return s.framebuffer;let a=t.colorAttachments[0]??t.depthStencilAttachment,u=this.device.createFramebuffer({id:`${this.id}-${e}-framebuffer-${this.cachedFramebuffers.length}`,width:a.width,height:a.height,colorAttachments:o,depthStencilAttachment:i??null});return this.cachedFramebuffers.push({nodeId:e,colorAttachments:o,depthStencilAttachment:i,framebuffer:u}),u}destroyFramebuffersUsingView(e){for(let t=this.cachedFramebuffers.length-1;t>=0;t--){let n=this.cachedFramebuffers[t];(n.depthStencilAttachment===e||n.colorAttachments.some(o=>o===e))&&(n.framebuffer.destroy(),this.cachedFramebuffers.splice(t,1))}}};function fr(r){return r instanceof Se?r.buffer:r}function _u(r){let e=r.length===0?0:(r.length-1)*r.byteStride+r.rowByteLength;return r.byteOffset+e}function dr(r,e){return r.byteLength>=e.byteLength&&(r.usage&e.usage)===e.usage}function yo(r){if(r instanceof ot){if(!r.isReady)throw new Error(`GPUCommandGraph dynamic texture "${r.id}" is not ready`);return r.texture}return r}function Au(r,e){let t;for(let[n,o]of[...Object.entries(r),...Object.entries(e)]){if(!Number.isSafeInteger(o.frameId)||o.frameId<0)throw new Error(`GPUCommandGraph frame resource "${n}" requires a valid frameId`);if(t!==void 0&&o.frameId!==t)throw new Error("GPUCommandGraph frame resources must share one frameId per encoding");t=o.frameId}}function us(r,e){let{timestampQuerySet:t,beginTimestampIndex:n,endTimestampIndex:o}=r.props;return t&&Number.isSafeInteger(n)&&Number.isSafeInteger(o)&&n>=0&&o>n?{querySet:t,snapshot:t.device.type==="webgpu"?e.captureTimestampQuerySet?.(t):void 0,beginIndex:n,endIndex:o}:void 0}function Fu(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 Xr(r,e){if(r.isLost)throw new Error(`GPUCommandGraph cannot perform ${e} after device loss`)}function lr(){return globalThis.performance?.now()??Date.now()}function cs(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 Ru(r,e){if(!r.id)throw new Error("GPUCommandGraph external texture id is required");for(let[t,n]of Object.entries({width:r.width,height:r.height}))if(!Number.isSafeInteger(n)||n<=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 po(r,e){if(!r.id)throw new Error("GPUCommandGraph texture id is required");let t=r.dimension??"2d",n=t==="cube"?6:r.depth??1,o=r.mipLevels??1,i=r.samples??1;for(let[c,d]of Object.entries({width:r.width,height:r.height,depth:n,mipLevels:o,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||n!==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||n%6!==0))throw new Error(`GPUCommandGraph cube-array texture "${r.id}" must be square with depth divisible by 6`);if(o>e.getMipLevelCount(r.width,r.height,t==="3d"?n:1))throw new Error(`GPUCommandGraph texture "${r.id}" declares too many mip levels`);let s=t==="1d"?e.limits.maxTextureDimension1D:t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,a=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,u=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureArrayLayers;if(r.width>s||r.height>a||n>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:n,mipLevels:o,samples:i}}function Vu(r,e){let t=e.dimension??r.dimension,n=e.aspect??"all",o=e.baseMipLevel??0,i=e.mipLevelCount??r.mipLevels-o,s=e.baseArrayLayer??0,a=r.dimension==="3d"?1:r.depth,u=e.arrayLayerCount??a-s;for(let[h,f]of Object.entries({baseMipLevel:o,mipLevelCount:i,baseArrayLayer:s,arrayLayerCount:u}))if(!Number.isSafeInteger(f)||f<0)throw new Error(`Graph texture view ${h} must be a non-negative safe integer`);if(i===0||o+i>r.mipLevels)throw new Error(`Graph texture view exceeds texture "${r.id}" mip levels`);if(u===0||s+u>a||r.dimension==="3d"&&(s!==0||u!==1))throw new Error(`Graph texture view exceeds texture "${r.id}" array layers`);let c=Math.max(1,r.width>>o),d=r.dimension==="1d"?1:Math.max(1,r.height>>o),l=r.dimension==="3d"?Math.max(1,r.depth>>o):u;return{dimension:t,aspect:n,baseMipLevel:o,mipLevelCount:i,baseArrayLayer:s,arrayLayerCount:u,width:c,height:d,depth:l}}function Mu(r,e){for(let[o,i]of Object.entries(e))if(!Number.isSafeInteger(i)||i<0)throw new Error(`Graph data view ${o} 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,n=e.byteOffset+t;if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n))throw new Error("Graph data view byte range exceeds safe integer precision");if(n>r.byteLength)throw new Error(`Graph data view exceeds buffer "${r.id}" byte length`)}function ls(r,e,t){let n=fr(r);if(n.device!==t)throw new Error(`GPUCommandGraph buffer "${e.id}" belongs to another device`);if(n.byteLength<e.byteLength)throw new Error(`GPUCommandGraph buffer "${e.id}" is smaller than compiled capacity`);if((n.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph buffer "${e.id}" has incompatible usage flags`)}function bo(r,e,t){let n=yo(r);if(n.device!==t)throw new Error(`GPUCommandGraph texture "${e.id}" belongs to another device`);for(let[o,i,s]of[["format",e.format,n.format],["dimension",e.dimension,n.dimension],["width",e.width,n.width],["height",e.height,n.height],["depth",e.depth,n.depth],["mipLevels",e.mipLevels,n.mipLevels],["samples",e.samples,n.samples]])if(s!==i)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible ${o} (${s} !== ${i})`);if((n.props.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible usage flags`)}function Nu(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 zu(r,e){let t=Hu(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph buffer "${r.id}" does not declare usage required by ${e}`)}function ju(r,e){let t=qu(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph texture "${r.id}" does not declare usage required by ${e}`)}function Wu(r,e){if(r instanceof _e&&e.startsWith("storage-")&&r.mipLevelCount!==1)throw new Error("GPUCommandGraph storage texture views must contain exactly one mip level")}function Hu(r){switch(r){case"storage-read":case"storage-write":case"storage-read-write":return ce.Buffer.STORAGE;case"uniform":return ce.Buffer.UNIFORM;case"copy-source":return ce.Buffer.COPY_SRC;case"copy-destination":return ce.Buffer.COPY_DST;case"indirect":return ce.Buffer.INDIRECT;case"vertex":return ce.Buffer.VERTEX;case"index":return ce.Buffer.INDEX}}function qu(r){switch(r){case"sampled":return ce.Texture.SAMPLE;case"storage-read":case"storage-write":case"storage-read-write":return ce.Texture.STORAGE;case"render-attachment":return ce.Texture.RENDER;case"copy-source":return ce.Texture.COPY_SRC;case"copy-destination":return ce.Texture.COPY_DST}}function fs(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 xt=class extends go{constructor(e,t={}){if(e.type!=="webgpu")throw new Error("GPUCommandGraph requires a WebGPU device");super(e,t)}};var Pt=F(A(),1);var I=F(A(),1);var M={texture(r){return Object.freeze({...r,type:"texture",...r.extent?{extent:Object.freeze({...r.extent,..."scale"in r.extent&&r.extent.scale?{scale:Object.freeze([...r.extent.scale])}:{}})}:{}})},scalar(r){return Object.freeze({type:"scalar",format:r})},vector(r,e={}){return Object.freeze({type:"vector",format:r,...e,...e.chunkLengths?{chunkLengths:Object.freeze([...e.chunkLengths])}:{}})}},Ae=class{role;id;format;constructor(e,t,n){if(this.role=n,!e)throw new Error("GPUGraphScalar id is required");this.id=e,this.format=t}},Q=class{id;format;length;external;role;chunkLengths;constructor(e){if(!e.id)throw new Error("GPUGraphVector id is required");if(e.length!==void 0&&(!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,this.role=e.role,e.chunkLengths){if(e.chunkLengths.some(t=>!Number.isSafeInteger(t)||t<0)||e.length!==void 0&&e.chunkLengths.reduce((t,n)=>t+n,0)!==e.length)throw new Error(`${e.id} chunk lengths must partition its logical length`);this.chunkLengths=Object.freeze([...e.chunkLengths])}}},de=class{id;format;width;height;role;descriptor;usage;dimension;depth;mipLevels;samples;external;constructor(e){this.role=e.role,this.descriptor=e.descriptor?M.texture(e.descriptor):void 0,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}},Fe=class{texture;props;constructor(e,t={}){this.texture=e,this.props=Object.freeze({...t})}};function k(r){return typeof r=="string"?r:r.id}function xo(r,e){let t=k(e),n=[...r.scalars,...r.vectors,...r.textures].find(o=>o.id===t);if(!n)throw new Error(`Undeclared operation value ${t}`);if(typeof e!="string"&&(e.constructor!==n.constructor||e.format!==n.format))throw new Error(`Incompatible operation reference ${t}`);return n}function Rt(r,e){for(let t of e.values){let n=xo(r,t.value);if(n instanceof de&&t.shape&&"like"in t.shape){if(!(xo(r,t.shape.like)instanceof de))throw new Error("Texture shape requires a texture source");continue}if(t.shape){if(!(n instanceof Q)||t.access==="read")throw new Error("Operation shapes require writable vectors");if("like"in t.shape){if(!(xo(r,t.shape.like)instanceof Q))throw new Error("Operation shape source must be a vector");let o=k(t.shape.like);if(!e.values.some(i=>i.access!=="write"&&k(i.value)===o))throw new Error("Operation shape source must be a declared read")}else{let{length:o,chunkLengths:i}=t.shape;if(!Number.isSafeInteger(o)||o<0||i&&(i.some(s=>!Number.isSafeInteger(s)||s<0)||i.reduce((s,a)=>s+a,0)!==o))throw new Error("Invalid operation output shape")}}}}function ee(r){let e=r instanceof I.TextureView?r.texture:r,t=r instanceof I.TextureView?r.props:{},n=t.baseMipLevel??0,o=t.baseArrayLayer??0,i=t.dimension??e.dimension,s=t.mipLevelCount??e.mipLevels-n,a=i==="3d"?Math.max(1,e.depth>>n):t.arrayLayerCount??(i==="cube"?6:i==="2d"?1:e.depth-o);return(0,I.assert)((t.format??e.format)===e.format&&(t.aspect??"all")==="all"),(0,I.assert)(!r.destroyed&&!e.destroyed),(0,I.assert)(Number.isInteger(n)&&n>=0&&Number.isInteger(s)&&s>0&&n+s<=e.mipLevels),(0,I.assert)(Number.isInteger(o)&&o>=0&&Number.isInteger(a)&&a>0&&(i==="3d"?o===0:o+a<=e.depth)),{texture:e,format:e.format,dimension:i,width:Math.max(1,e.width>>n),height:Math.max(1,e.height>>n),depth:a,mipLevels:s,samples:e.samples,baseMipLevel:n,baseArrayLayer:o}}function hs(r,e={}){let t=ee(r),n=e.baseMipLevel??0,o=e.baseArrayLayer??0,i=e.dimension??t.dimension,s=e.mipLevelCount??t.mipLevels-n,a=e.arrayLayerCount??(i==="cube"?6:i==="2d"||i==="3d"?1:t.depth-o);return(0,I.assert)(n>=0&&n+s<=t.mipLevels&&o>=0&&o+a<=t.depth),{...e,dimension:i,baseMipLevel:t.baseMipLevel+n,mipLevelCount:s,baseArrayLayer:t.baseArrayLayer+o,arrayLayerCount:a}}var Yu={sampled:I.Texture.SAMPLE,"storage-read":I.Texture.STORAGE,"storage-write":I.Texture.STORAGE,"storage-read-write":I.Texture.STORAGE,"render-attachment":I.Texture.RENDER,"copy-source":I.Texture.COPY_SRC,"copy-destination":I.Texture.COPY_DST},Zr=class{values=new Map;owned=new Set;constructor(e,t,n,o,i){let s=new Map,a=new Set;for(let u of n)for(let c of u.values){let d=k(c.value);if(!t.some(h=>h.id===d))continue;(0,I.assert)(c.textureUsage);let l=c.textureUsage;(0,I.assert)(c.access==="read"&&["sampled","storage-read","copy-source"].includes(l)||c.access==="write"&&["storage-write","render-attachment","copy-destination"].includes(l)||c.access==="read-write"&&["storage-read-write","render-attachment"].includes(l)),s.set(d,(s.get(d)??0)|Yu[l]),c.access!=="read"&&a.add(d)}try{let u=new Set(t);for(;u.size;){let c=!1;for(let d of u){let l=d.descriptor??{type:"texture",format:d.format,dimension:d.dimension,extent:d.width===void 0?void 0:{width:d.width,height:d.height,depth:d.depth},mipLevels:d.mipLevels,samples:d.samples},h=l.extent,f=h&&"like"in h?this.values.get(h.like):void 0;if(h&&"like"in h&&!f)continue;let m=f?ee(f):void 0,p=h&&"like"in h?h.scale??[1,1]:[1,1];(0,I.assert)(p.every(E=>Number.isFinite(E)&&E>0));let y=m?Math.max(1,Math.round(m.width*p[0])):h&&"width"in h?h.width:void 0,g=m?Math.max(1,Math.round(m.height*p[1])):h&&"height"in h?h.height:void 0,w=l.dimension??m?.dimension??"2d",S=w==="cube"?6:m?.depth??(h&&"depth"in h?h.depth:void 0),T=l.mipLevels??m?.mipLevels??1,v=l.samples??m?.samples??1,b=(s.get(d.id)??0)|d.usage;(0,I.assert)(v===1||!(b&(I.Texture.COPY_SRC|I.Texture.COPY_DST)));let C=i[d.id]??o[d.id];if(C===void 0){(0,I.assert)(d.role!=="input"&&!d.external&&y!==void 0&&g!==void 0&&b!==0),(0,I.assert)(Number.isSafeInteger(y)&&y>0&&Number.isSafeInteger(g)&&g>0);let E=e.createTexture({id:d.id,format:l.format,dimension:w,width:y,height:g,depth:S??1,mipLevels:T,samples:v,usage:b|(v===1?I.Texture.COPY_SRC:0)|I.Texture.SAMPLE});this.owned.add(E),C=E}(0,I.assert)(C instanceof I.Texture||C instanceof I.TextureView);let B=ee(C);(0,I.assert)(B.samples===1||!(b&(I.Texture.COPY_SRC|I.Texture.COPY_DST))),(0,I.assert)(B.texture.device===e&&B.format===l.format&&B.dimension===w&&(y===void 0||B.width===y)&&(g===void 0||B.height===g)&&(S===void 0||B.depth===S)&&(l.mipLevels===void 0&&d.role==="input"||B.mipLevels===T)&&(l.samples===void 0&&d.role==="input"||B.samples===v)&&(B.texture.props.usage&b)===b),this.values.set(d.id,C),u.delete(d),c=!0}(0,I.assert)(c)}for(let c of a){let d=ee(this.values.get(c)).texture;for(let[l,h]of this.values)(0,I.assert)(c===l||ee(h).texture!==d)}}catch(u){throw this.destroy(),u}}finish(e){for(let t of e){let n=this.values.get(t);n instanceof I.Texture&&this.owned.delete(n)}this.destroy()}destroy(){for(let e of this.owned)e.destroy();this.owned.clear()}};var ms=F(A(),1);function ps(r,e,t){let n=ee(e),o=ee(t);wo(e,t);for(let i=0;i<n.mipLevels;i++)r.copyTextureToTexture({sourceTexture:n.texture,destinationTexture:o.texture,mipLevel:n.baseMipLevel+i,destinationMipLevel:o.baseMipLevel+i,origin:[0,0,n.baseArrayLayer],destinationOrigin:[0,0,o.baseArrayLayer],width:Math.max(1,n.width>>i),height:Math.max(1,n.height>>i),depthOrArrayLayers:n.dimension==="3d"?Math.max(1,n.depth>>i):n.depth})}function wo(r,e){let t=ee(r),n=ee(e);(0,ms.assert)(t.texture!==n.texture&&t.samples===1&&n.samples===1&&t.format===n.format&&t.width===n.width&&t.height===n.height&&t.depth===n.depth&&t.mipLevels===n.mipLevels&&t.dimension===n.dimension)}var hr=F(A(),1);function gs(r,e){let t=e.resolveVector(r.output),n=r.getData();for(let[o,i]of t.data.entries()){if(!i.length)continue;let s=n[o];e.graph.addCopyPass({id:`${r.id}-${o}`,resources:[{buffer:i,usage:"copy-destination"}],compile:({device:a})=>{let u=a.createBuffer({data:s,usage:hr.Buffer.COPY_SRC});return{encode:({commandEncoder:c,getBuffer:d})=>{let l=i.byteStride===i.rowByteLength;for(let h=0;h<i.length;h+=l?i.length:1)c.copyBufferToBuffer({sourceBuffer:u,sourceOffset:h*i.rowByteLength,destinationBuffer:d(i),destinationOffset:i.byteOffset+h*i.byteStride,size:l?s.byteLength:i.rowByteLength})},destroy:()=>u.destroy()}}})}}function ys(r,e){let t=e.resolveVector(r.input),n=e.resolveVector(r.output);(0,hr.assert)(t.format===n.format&&t.data.length===n.data.length);for(let[o,i]of t.data.entries()){let s=n.data[o];(0,hr.assert)(i.length===s.length),i.length&&e.graph.addCopyPass({id:`${r.id}-${o}`,resources:[{buffer:i,usage:"copy-source"},{buffer:s,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:a,getBuffer:u})=>{let c=i.byteStride===i.rowByteLength&&s.byteStride===s.rowByteLength;for(let d=0;d<i.length;d+=c?i.length:1)a.copyBufferToBuffer({sourceBuffer:u(i),sourceOffset:i.byteOffset+d*i.byteStride,destinationBuffer:u(s),destinationOffset:s.byteOffset+d*s.byteStride,size:i.rowByteLength*(c?i.length:1)})}})})}}function bs(r,e){let t=e.resolveTextureView(r.input),n=e.resolveTextureView(r.output);e.graph.addCopyPass({id:r.id,resources:[{texture:t,usage:"copy-source"},{texture:n,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:o,getTextureView:i})=>ps(o,i(t),i(n))})})}var To=F(A(),1);var qe=class{type="vector-upload";id;output;format;chunks;chunkLengths;constructor(e){this.id=e.id??`${e.output}-upload`,this.output=e.output,this.format=e.format;let t=U(e.format),n=Array.isArray(e.data)?e.data:[e.data],o=t.signedDataType==="float32"?Float32Array:t.signedDataType==="uint32"?Uint32Array:Int32Array;(0,To.assert)(n.every(i=>i instanceof o&&i.byteLength%t.byteLength===0)),this.chunks=n.map(i=>new Uint8Array(i.buffer,i.byteOffset,i.byteLength).slice()),this.chunkLengths=Object.freeze(this.chunks.map(i=>i.byteLength/t.byteLength))}getData(){return this.chunks.map(e=>e.slice())}get contract(){let e={length:this.chunkLengths.reduce((t,n)=>t+n,0),chunkLengths:this.chunkLengths};return{outputs:{[this.output]:M.vector(this.format,e)},values:[{value:this.output,access:"write",shape:e}]}}},Ye=class{type="vector-copy";id;input;output;constructor(e){this.id=e.id??`${e.output}-copy`,this.input=e.input,this.output=e.output}get contract(){return{outputs:({getValue:e})=>{let t=e(this.input);return t.type==="texture"?{[this.output]:M.texture({...t,extent:{like:this.input}})}:((0,To.assert)(t.type==="vector"),{[this.output]:M.vector(t.format,{length:t.length,chunkLengths:t.chunkLengths})})},values:[{value:this.input,access:"read",textureUsage:"copy-source"},{value:this.output,access:"write",shape:{like:this.input},textureUsage:"copy-destination"}]}}};function Y(r){return r instanceof O?r.data:[r]}function X(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 n=e.map(Y),o=e.map(()=>0),i=e.map(()=>0),s=[],a=0;for(;a<t;){for(let l=0;l<n.length;l++)for(;n[l][o[l]]?.length===i[l];)o[l]++,i[l]=0;let u=n.map((l,h)=>l[o[h]]),c=Math.min(...u.map((l,h)=>l.length-i[h])),d=[];for(let l=0;l<u.length;l++){let h=u[l],f=u.findIndex((m,p)=>p<l&&m===h&&i[p]===i[l]);d.push(f>=0?d[f]:i[l]===0&&c===h.length?h:r.createDataView(h.buffer,{format:h.format,length:c,byteOffset:h.byteOffset+i[l]*h.byteStride,byteStride:h.byteStride,rowByteLength:h.rowByteLength}))}s.push(d);for(let l=0;l<i.length;l++)i[l]+=c;a+=c}return s}function N(r,e){let[t,n,o]=e;for(let[i,s]of[["x",t],["y",n],["z",o]])if(!Number.isSafeInteger(s)||s<0)throw new Error(`compute dispatch ${i} workgroup count must be a non-negative safe integer`);return{...r,dispatchWorkgroups:Object.freeze([t,n,o])}}function Qr(r){return r.dispatchWorkgroups}var Xe=F(A(),1),D=class r{static async createAsync(e,t){let n=!Xe.PipelineFactory.getAsyncCompilation(e),o=n?Xe.PipelineFactory.beginAsyncCompilation(e):Xe.PipelineFactory.getAsyncCompilation(e),i;try{i=new r(e,t)}finally{n&&Xe.PipelineFactory.endAsyncCompilation(e,o)}try{return n?await Promise.all(o):await i._pipelineInitialization,i}catch(s){throw i.destroy(),s}}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:n,pipelineFactory:o,shaderFactory:i,debugShaders:s,...a}=t;this.device=e,this.id=t.id??"kernel",this.source=n,this.pipelineFactory=o??Xe.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=i??Xe.ShaderFactory.getDefaultShaderFactory(e),this.shader=this.shaderFactory.createShader({id:`${this.id}-compute`,stage:"compute",source:this.source,debugShaders:s});let u={...a,shader:this.shader},c=Xe.PipelineFactory.getAsyncCompilation(e);if(c){let d=this.pipelineFactory.createComputePipelineAsync(u);this._pipelineInitialization=d,c.push(d.then(l=>(this.pipeline=l,l)))}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)}};function fe(r,e,t,n){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new Error(`${r} element count must be a non-negative uint32`);return xs(r,t),Xu(r,Math.max(1,Math.ceil(e/t)),n)}function Xu(r,e,t){let n=Math.floor(t);if(!Number.isSafeInteger(n)||n<1)throw new Error("maxComputeWorkgroupsPerDimension must be a positive integer");let o=Math.min(e,n),i=Math.min(Math.ceil(e/o),n),s=Math.ceil(e/o/i);if(s>n)throw new Error(`${r} requires ${e} workgroups, exceeding the 3D dispatch limit of ${n} per dimension`);return{x:o,y:i,z:s}}function J(r,e){xs("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;
8
8
  if (workgroupIndex >= ${t}u) { return; }
9
- let index = workgroupIndex * ${e}u + localInvocationIndex;`}function bs(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`)}var vo=F(A(),1);var So=Uint32Array.BYTES_PER_ELEMENT,Eo=256;function ge(r,e,t){let n=U(r.format);if(!e.includes(r.format)||r.byteStride!==n.byteLength||r.rowByteLength!==n.byteLength||r.byteOffset%So!==0)throw new Error(`${t} must be packed, uint32-aligned ${e.join(" or ")} GPU data`)}function Le(r,e){ge(r,["uint32"],e)}function G(r,e){let t=mr(r),n={buffer:e(r),...t};if(n.offset+n.size>r.buffer.byteLength)throw new Error("GraphDataView storage binding exceeds its logical buffer");return n}function mr(r){let e=Math.floor(r.byteOffset/Eo)*Eo,t=r.byteOffset-e,n=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:e,size:t+Math.max(n,r.rowByteLength)}}function P(r){if(r.byteOffset%So!==0)throw new Error("GraphDataView storage binding must be uint32-aligned");return r.byteOffset%Eo/So}function z(r,e,t,n,o=vo.Buffer.STORAGE){if(!Number.isSafeInteger(n)||n<0)throw new Error("Transient GraphDataView length must be a non-negative safe integer");if((o&vo.Buffer.STORAGE)===0)throw new Error("Transient GraphDataView usage must include Buffer.STORAGE");if(it(t)||st(t))throw new Error("Transient GraphDataView requires a fixed-width GPUVector format");let i=U(t),s=r.createTransientBuffer({id:e,byteLength:Math.max(n,1)*i.byteLength,usage:o});return r.createDataView(s,{format:t,length:n})}function Po(r,e,t){let n,o=t.data.map((i,s)=>i.length===0?(n??=z(r,`${e}-empty`,t.format,0),n):z(r,`${e}-chunk-${s}`,t.format,i.length));return new O({id:e,name:e,format:t.format,length:t.length,valueLength:t.valueLength,stride:t.stride,byteStride:t.byteStride,rowByteLength:t.rowByteLength,data:o})}function xs(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 n=e instanceof O?e.data:[e],o=t,i=[];for(let s of n){let a=Math.min(o,s.length);if(i.push(a===s.length?s:r.createDataView(s.buffer,{format:s.format,length:a,byteOffset:s.byteOffset,byteStride:s.byteStride,rowByteLength:s.rowByteLength})),o-=a,o===0)break}return e instanceof O?new O({...e,length:t,valueLength:t*(U(e.format).listSize??1),data:i}):i[0]}function Be(r,e={}){let t=r.features?.has("subgroups"),n=!e.requiresSubgroupId||r.wgslLanguageFeatures?.has("subgroup_id");return t&&n?"subgroups":"portable"}function Co(){return`
9
+ let index = workgroupIndex * ${e}u + localInvocationIndex;`}function xs(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`)}var vo=F(A(),1);var So=Uint32Array.BYTES_PER_ELEMENT,Eo=256;function ge(r,e,t){let n=U(r.format);if(!e.includes(r.format)||r.byteStride!==n.byteLength||r.rowByteLength!==n.byteLength||r.byteOffset%So!==0)throw new Error(`${t} must be packed, uint32-aligned ${e.join(" or ")} GPU data`)}function Le(r,e){ge(r,["uint32"],e)}function G(r,e){let t=mr(r),n={buffer:e(r),...t};if(n.offset+n.size>r.buffer.byteLength)throw new Error("GraphDataView storage binding exceeds its logical buffer");return n}function mr(r){let e=Math.floor(r.byteOffset/Eo)*Eo,t=r.byteOffset-e,n=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:e,size:t+Math.max(n,r.rowByteLength)}}function P(r){if(r.byteOffset%So!==0)throw new Error("GraphDataView storage binding must be uint32-aligned");return r.byteOffset%Eo/So}function z(r,e,t,n,o=vo.Buffer.STORAGE){if(!Number.isSafeInteger(n)||n<0)throw new Error("Transient GraphDataView length must be a non-negative safe integer");if((o&vo.Buffer.STORAGE)===0)throw new Error("Transient GraphDataView usage must include Buffer.STORAGE");if(it(t)||st(t))throw new Error("Transient GraphDataView requires a fixed-width GPUVector format");let i=U(t),s=r.createTransientBuffer({id:e,byteLength:Math.max(n,1)*i.byteLength,usage:o});return r.createDataView(s,{format:t,length:n})}function Po(r,e,t){let n,o=t.data.map((i,s)=>i.length===0?(n??=z(r,`${e}-empty`,t.format,0),n):z(r,`${e}-chunk-${s}`,t.format,i.length));return new O({id:e,name:e,format:t.format,length:t.length,valueLength:t.valueLength,stride:t.stride,byteStride:t.byteStride,rowByteLength:t.rowByteLength,data:o})}function ws(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 n=e instanceof O?e.data:[e],o=t,i=[];for(let s of n){let a=Math.min(o,s.length);if(i.push(a===s.length?s:r.createDataView(s.buffer,{format:s.format,length:a,byteOffset:s.byteOffset,byteStride:s.byteStride,rowByteLength:s.rowByteLength})),o-=a,o===0)break}return e instanceof O?new O({...e,length:t,valueLength:t*(U(e.format).listSize??1),data:i}):i[0]}function Be(r,e={}){let t=r.features?.has("subgroups"),n=!e.requiresSubgroupId||r.wgslLanguageFeatures?.has("subgroup_id");return t&&n?"subgroups":"portable"}function Co(){return`
10
10
  fn getFirstBallotLane(mask: vec4<u32>) -> u32 {
11
11
  if (mask.x != 0u) { return firstTrailingBit(mask.x); }
12
12
  if (mask.y != 0u) { return 32u + firstTrailingBit(mask.y); }
@@ -29,7 +29,7 @@ fn getBallotPrefixLaneCount(mask: vec4<u32>, invocation: u32) -> u32 {
29
29
  if (word > 2u) { count += countOneBits(mask.z); }
30
30
  let lowerBits = (1u << bit) - 1u;
31
31
  return count + countOneBits(mask[word] & lowerBits);
32
- }`}function ws(r,e,t,n){return`
32
+ }`}function Ts(r,e,t,n){return`
33
33
  var subgroupPending = ${r};
34
34
  for (var subgroupGroup = 0u; subgroupGroup < ${n}u; subgroupGroup++) {
35
35
  let pendingBallot = subgroupBallot(subgroupPending);
@@ -42,7 +42,7 @@ fn getBallotPrefixLaneCount(mask: vec4<u32>, invocation: u32) -> u32 {
42
42
  atomicAdd(&${t}[leaderKey], getBallotLaneCount(matchingBallot));
43
43
  }
44
44
  subgroupPending = subgroupPending && !matchingKey;
45
- }`}var ye=256,vs=256,Ss=16,gr=Uint32Array.BYTES_PER_ELEMENT,br=class{id;keys;values;output;mask;operation;constructor(e){this.id=e.id??"gpu-group-aggregation",this.keys=e.keys,this.values=e.values,this.output=e.output,this.mask=e.mask,this.operation=e.operation??"count";for(let[t,n]of pr(this.keys).entries())Lo(n,"uint32",`${this.id} keys chunk ${t}`);if(this.output.length===0)throw new Error(`${this.id} output must contain at least one group`);if(!["count","sum","min","max","mean"].includes(this.operation))throw new Error(`${this.id} operation must be count, sum, min, max, or mean`);if(this.operation==="count"){if(Le(this.output,`${this.id} count output`),this.values)throw new Error(`${this.id} count operation must not provide values`)}else{if(ge(this.output,["float32"],`${this.id} statistic output`),!this.values)throw new Error(`${this.id} ${this.operation} operation requires values`);for(let[t,n]of Bo(this.values).entries())Lo(n,"float32",`${this.id} values chunk ${t}`);if(Ts(this.keys,this.values,`${this.id} keys and values`),this.operation==="mean"&&this.keys.length>4294967295)throw new Error(`${this.id} mean input length must fit in uint32 group counts`)}if(pr(this.keys).some(t=>t.buffer===this.output.buffer))throw new Error(`${this.id} keys and output must use separate buffers`);if(this.values&&Bo(this.values).some(t=>t.buffer===this.output.buffer))throw new Error(`${this.id} values and output must use separate buffers`);if(this.mask){for(let[t,n]of pr(this.mask).entries())if(Lo(n,"uint32",`${this.id} mask chunk ${t}`),n.buffer===this.output.buffer)throw new Error(`${this.id} mask and output must use separate buffers`);Ts(this.keys,this.mask,`${this.id} keys and mask`)}}getCommandNodes(e){let t=[],n=pr(this.keys),o=this.mask?pr(this.mask):void 0,i=this.values?Bo(this.values):void 0;if(n.some(c=>c.buffer.graph!==e)||o?.some(c=>c.buffer.graph!==e)||i?.some(c=>c.buffer.graph!==e)||this.output.buffer.graph!==e)throw new Error(`${this.id} views must belong to the target graph`);if(this.values){let c=X(e,[this.keys,this.values,this.mask??this.keys]);n=c.map(([d])=>d),i=c.map(([,d])=>d),o=this.mask?c.map(([,,d])=>d):void 0}else if(this.mask){let c=X(e,[this.keys,this.mask]);n=c.map(([d])=>d),o=c.map(([,d])=>d)}if(this.operation==="count"){let c=this.output;t.push(...Ku(e,this.id,c));let d=c.length<=vs?"local":"global";for(let l=0;l<n.length;l++){let f=n[l];f.length!==0&&t.push(...Zu(e,{id:this.keys instanceof O||n.length>1?`${this.id}-chunk-${l}-${d}`:`${this.id}-${d}`,keys:f,output:c,mask:o?.[l],dispatchLayout:xr(f.length,e.device.limits.maxComputeWorkgroupsPerDimension)}))}return t}let s=this.output,a=this.operation,u=a==="mean"?z(e,`${this.id}-counts`,"uint32",s.length):void 0;t.push(...Qu(e,this.id,s,a,u));for(let c=0;c<n.length;c++){let d=n[c];d.length!==0&&t.push(...Ju(e,{id:this.keys instanceof O||n.length>1?`${this.id}-chunk-${c}`:this.id,keys:d,values:i[c],mask:o?.[c],output:s,operation:a,counts:u,dispatchLayout:xr(d.length,e.device.limits.maxComputeWorkgroupsPerDimension)}))}return a!=="sum"&&t.push(...ec(e,this.id,s,a,u)),t}};function Lo(r,e,t){if(r.format!==e||r.rowByteLength!==gr||r.byteStride<gr||r.byteStride%gr!==0||r.byteOffset%gr!==0)throw new Error(`${t} must be a uint32-aligned scalar ${e} GPU data view`)}function yr(r){return r.byteStride/gr}function pr(r){return r instanceof O?r.data:[r]}function Bo(r){return r instanceof O?r.data:[r]}function Ts(r,e,t){if(r.length!==e.length)throw new Error(`${t} lengths must match`)}function Ku(r,e,t){let n=[],o=xr(t.length,r.device.limits.maxComputeWorkgroupsPerDimension),i=`
45
+ }`}var ye=256,Ss=256,Es=16,gr=Uint32Array.BYTES_PER_ELEMENT,br=class{id;keys;values;output;mask;operation;meanPartitionSize;constructor(e){this.id=e.id??"gpu-group-aggregation",this.keys=e.keys,this.values=e.values,this.output=e.output,this.mask=e.mask,this.operation=e.operation??"count";let t=e.maxMeanScratchBytes;if(t!==void 0&&(!Number.isSafeInteger(t)||t<4))throw new Error(`${this.id} mean scratch budget requires at least four bytes`);this.meanPartitionSize=Math.min(this.output.length,Math.floor((t??1/0)/4));for(let[n,o]of pr(this.keys).entries())Lo(o,"uint32",`${this.id} keys chunk ${n}`);if(this.output.length===0)throw new Error(`${this.id} output must contain at least one group`);if(!["count","sum","min","max","mean"].includes(this.operation))throw new Error(`${this.id} operation must be count, sum, min, max, or mean`);if(this.operation==="count"){if(Le(this.output,`${this.id} count output`),this.values)throw new Error(`${this.id} count operation must not provide values`)}else{if(ge(this.output,["float32"],`${this.id} statistic output`),!this.values)throw new Error(`${this.id} ${this.operation} operation requires values`);for(let[n,o]of Bo(this.values).entries())Lo(o,"float32",`${this.id} values chunk ${n}`);if(vs(this.keys,this.values,`${this.id} keys and values`),this.operation==="mean"&&this.keys.length>4294967295)throw new Error(`${this.id} mean input length must fit in uint32 group counts`)}if(pr(this.keys).some(n=>n.buffer===this.output.buffer))throw new Error(`${this.id} keys and output must use separate buffers`);if(this.values&&Bo(this.values).some(n=>n.buffer===this.output.buffer))throw new Error(`${this.id} values and output must use separate buffers`);if(this.mask){for(let[n,o]of pr(this.mask).entries())if(Lo(o,"uint32",`${this.id} mask chunk ${n}`),o.buffer===this.output.buffer)throw new Error(`${this.id} mask and output must use separate buffers`);vs(this.keys,this.mask,`${this.id} keys and mask`)}}getCommandNodes(e){let t=[],n=pr(this.keys),o=this.mask?pr(this.mask):void 0,i=this.values?Bo(this.values):void 0;if(n.some(d=>d.buffer.graph!==e)||o?.some(d=>d.buffer.graph!==e)||i?.some(d=>d.buffer.graph!==e)||this.output.buffer.graph!==e)throw new Error(`${this.id} views must belong to the target graph`);if(this.values){let d=X(e,[this.keys,this.values,this.mask??this.keys]);n=d.map(([l])=>l),i=d.map(([,l])=>l),o=this.mask?d.map(([,,l])=>l):void 0}else if(this.mask){let d=X(e,[this.keys,this.mask]);n=d.map(([l])=>l),o=d.map(([,l])=>l)}if(this.operation==="count"){let d=this.output;t.push(...Ku(e,this.id,d));let l=d.length<=Ss?"local":"global";for(let h=0;h<n.length;h++){let f=n[h];f.length!==0&&t.push(...Zu(e,{id:this.keys instanceof O||n.length>1?`${this.id}-chunk-${h}-${l}`:`${this.id}-${l}`,keys:f,output:d,mask:o?.[h],dispatchLayout:xr(f.length,e.device.limits.maxComputeWorkgroupsPerDimension)}))}return t}let s=this.output,a=this.operation,u=a==="mean"?this.meanPartitionSize:s.length,c=a==="mean"?z(e,this.id+"-counts","uint32",u):void 0;for(let d=0;d<s.length;d+=u){let l=Math.min(u,s.length-d),h=d===0&&l===s.length?s:e.createDataView(s.buffer,{format:"float32",length:l,byteOffset:s.byteOffset+d*4}),f=c&&l!==c.length?e.createDataView(c.buffer,{format:"uint32",length:l,byteOffset:c.byteOffset}):c,m=u===s.length?this.id:this.id+"-partition-"+d;t.push(...Qu(e,m,h,a,f));for(let p=0;p<n.length;p++){let y=n[p];y.length!==0&&t.push(...Ju(e,{id:this.keys instanceof O||n.length>1?m+"-chunk-"+p:m,keys:y,values:i[p],mask:o?.[p],output:h,operation:a,counts:f,firstGroup:d,dispatchLayout:xr(y.length,e.device.limits.maxComputeWorkgroupsPerDimension)}))}a!=="sum"&&t.push(...ec(e,m,h,a,f))}return t}};function Lo(r,e,t){if(r.format!==e||r.rowByteLength!==gr||r.byteStride<gr||r.byteStride%gr!==0||r.byteOffset%gr!==0)throw new Error(`${t} must be a uint32-aligned scalar ${e} GPU data view`)}function yr(r){return r.byteStride/gr}function pr(r){return r instanceof O?r.data:[r]}function Bo(r){return r instanceof O?r.data:[r]}function vs(r,e,t){if(r.length!==e.length)throw new Error(`${t} lengths must match`)}function Ku(r,e,t){let n=[],o=xr(t.length,r.device.limits.maxComputeWorkgroupsPerDimension),i=`
46
46
  const GROUP_COUNT: u32 = ${t.length}u;
47
47
  const OUTPUT_OFFSET: u32 = ${P(t)}u;
48
48
  @group(0) @binding(0) var<storage, read_write> outputCounts: array<atomic<u32>>;
@@ -56,7 +56,7 @@ fn main(
56
56
  if (index < GROUP_COUNT) {
57
57
  atomicStore(&outputCounts[OUTPUT_OFFSET + index], 0u);
58
58
  }
59
- }`;return n.push(...wr(r,{id:`${e}-clear`,source:i,resources:[{buffer:t,usage:"storage-write"}],bindings:{outputCounts:t},dispatchSize:o})),n}function Zu(r,e){let t=[],n=e.output.length<=vs,o=n&&e.output.length<=Ss&&Be(r.device)==="subgroups",i=e.mask?"@group(0) @binding(1) var<storage, read> selectionMask: array<u32>;":"",s=e.mask?2:1,a=e.mask?`selectionMask[${P(e.mask)}u + index * ${yr(e.mask)}u] != 0u`:"true",u=o?ws("accepted","groupIndex","localCounts",e.output.length):" if (accepted) { atomicAdd(&localCounts[groupIndex], 1u); }",c=n?`${u}
59
+ }`;return n.push(...wr(r,{id:`${e}-clear`,source:i,resources:[{buffer:t,usage:"storage-write"}],bindings:{outputCounts:t},dispatchSize:o})),n}function Zu(r,e){let t=[],n=e.output.length<=Ss,o=n&&e.output.length<=Es&&Be(r.device)==="subgroups",i=e.mask?"@group(0) @binding(1) var<storage, read> selectionMask: array<u32>;":"",s=e.mask?2:1,a=e.mask?`selectionMask[${P(e.mask)}u + index * ${yr(e.mask)}u] != 0u`:"true",u=o?Ts("accepted","groupIndex","localCounts",e.output.length):" if (accepted) { atomicAdd(&localCounts[groupIndex], 1u); }",c=n?`${u}
60
60
  workgroupBarrier();
61
61
  if (lane < GROUP_COUNT) {
62
62
  atomicAdd(&outputCounts[OUTPUT_OFFSET + lane], atomicLoad(&localCounts[lane]));
@@ -104,8 +104,8 @@ ${u}
104
104
  atomicStore(&outputValues[OUTPUT_OFFSET + index], ${a});
105
105
  ${c}
106
106
  }
107
- }`;return i.push(...wr(r,{id:n==="sum"?`${e}-clear`:`${e}-initialize`,source:d,resources:[{buffer:t,usage:"storage-write"},...o?[{buffer:o,usage:"storage-write"}]:[]],bindings:{outputValues:t,...o?{outputCounts:o}:{}},dispatchSize:s})),i}function Ju(r,e){let t=[],n=e.output.length<=Ss&&Be(r.device)==="subgroups",o=e.mask?"@group(0) @binding(2) var<storage, read> selectionMask: array<u32>;":"",i=e.mask?3:2,s=e.counts?`@group(0) @binding(${i+1}) var<storage, read_write> outputCounts: array<atomic<u32>>;`:"",a=e.mask?`selectionMask[${P(e.mask)}u + index * ${yr(e.mask)}u] != 0u`:"true",u=n?rc(e.operation,e.output.length,e.counts):` if (accepted) {
108
- ${Es(e.operation,"groupIndex")}
107
+ }`;return i.push(...wr(r,{id:n==="sum"?`${e}-clear`:`${e}-initialize`,source:d,resources:[{buffer:t,usage:"storage-write"},...o?[{buffer:o,usage:"storage-write"}]:[]],bindings:{outputValues:t,...o?{outputCounts:o}:{}},dispatchSize:s})),i}function Ju(r,e){let t=[],n=e.output.length<=Es&&Be(r.device)==="subgroups",o=e.mask?"@group(0) @binding(2) var<storage, read> selectionMask: array<u32>;":"",i=e.mask?3:2,s=e.counts?`@group(0) @binding(${i+1}) var<storage, read_write> outputCounts: array<atomic<u32>>;`:"",a=e.mask?`selectionMask[${P(e.mask)}u + index * ${yr(e.mask)}u] != 0u`:"true",u=n?rc(e.operation,e.output.length,e.counts):` if (accepted) {
108
+ ${Ps(e.operation,"groupIndex")}
109
109
  ${e.counts?`atomicAdd(&outputCounts[${P(e.counts)}u + groupIndex], 1u);`:""}
110
110
  }`,c=`
111
111
  ${n?"enable subgroups;":""}
@@ -136,10 +136,11 @@ ${n?Co():""}
136
136
  var groupIndex = 0u;
137
137
  var value = 0.0;
138
138
  if (index < ELEMENT_COUNT && ${a}) {
139
- groupIndex = groupKeys[KEYS_OFFSET + index * KEYS_STRIDE];
139
+ let key = groupKeys[KEYS_OFFSET + index * KEYS_STRIDE];
140
+ groupIndex = key - ${e.firstGroup}u;
140
141
  value = inputValues[VALUES_OFFSET + index * VALUES_STRIDE];
141
142
  let finiteValue = value == value && abs(value) <= 3.402823466e+38;
142
- accepted = groupIndex < GROUP_COUNT && finiteValue;
143
+ accepted = key >= ${e.firstGroup}u && groupIndex < GROUP_COUNT && finiteValue;
143
144
  }
144
145
  ${u}
145
146
  }`,d=[{buffer:e.keys,usage:"storage-read"},{buffer:e.values,usage:"storage-read"},...e.mask?[{buffer:e.mask,usage:"storage-read"}]:[],{buffer:e.output,usage:"storage-read-write"},...e.counts?[{buffer:e.counts,usage:"storage-read-write"}]:[]];return t.push(...wr(r,{id:`${e.id}-${e.operation}`,source:c,resources:d,bindings:{groupKeys:e.keys,inputValues:e.values,...e.mask?{selectionMask:e.mask}:{},outputValues:e.output,...e.counts?{outputCounts:e.counts}:{}},dispatchSize:e.dispatchLayout})),t}function ec(r,e,t,n,o){let i=[],s=xr(t.length,r.device.limits.maxComputeWorkgroupsPerDimension),a=o?"@group(0) @binding(1) var<storage, read> outputCounts: array<u32>;":"",u=n==="mean"?`let count = outputCounts[${P(o)}u + index];
@@ -181,7 +182,7 @@ ${c}
181
182
  if (result.exchanged) { break; }
182
183
  oldBits = result.old_value;
183
184
  }
184
- }`}function Es(r,e,t="value"){return r==="min"||r==="max"?`${r==="min"?"atomicMin":"atomicMax"}(&outputValues[OUTPUT_OFFSET + ${e}], encodeOrderedFloat(${t}));`:`atomicAddFloat(&outputValues[OUTPUT_OFFSET + ${e}], ${t});`}function rc(r,e,t){let n=r==="min"||r==="max",o=n?`select(${r==="min"?"0xffffffffu":"0u"}, encodeOrderedFloat(value), matchingKey)`:"select(0.0, value, matchingKey)",i=r==="min"?"subgroupMin(selectedValue)":r==="max"?"subgroupMax(selectedValue)":"subgroupAdd(selectedValue)",s=n?`${r==="min"?"atomicMin":"atomicMax"}(&outputValues[OUTPUT_OFFSET + leaderKey], aggregatedValue);`:Es(r,"leaderKey","aggregatedValue");return`
185
+ }`}function Ps(r,e,t="value"){return r==="min"||r==="max"?`${r==="min"?"atomicMin":"atomicMax"}(&outputValues[OUTPUT_OFFSET + ${e}], encodeOrderedFloat(${t}));`:`atomicAddFloat(&outputValues[OUTPUT_OFFSET + ${e}], ${t});`}function rc(r,e,t){let n=r==="min"||r==="max",o=n?`select(${r==="min"?"0xffffffffu":"0u"}, encodeOrderedFloat(value), matchingKey)`:"select(0.0, value, matchingKey)",i=r==="min"?"subgroupMin(selectedValue)":r==="max"?"subgroupMax(selectedValue)":"subgroupAdd(selectedValue)",s=n?`${r==="min"?"atomicMin":"atomicMax"}(&outputValues[OUTPUT_OFFSET + leaderKey], aggregatedValue);`:Ps(r,"leaderKey","aggregatedValue");return`
185
186
  var subgroupPending = accepted;
186
187
  for (var subgroupGroup = 0u; subgroupGroup < ${e}u; subgroupGroup++) {
187
188
  let pendingBallot = subgroupBallot(subgroupPending);
@@ -197,14 +198,14 @@ ${c}
197
198
  ${t?`atomicAdd(&outputCounts[${P(t)}u + leaderKey], getBallotLaneCount(matchingBallot));`:""}
198
199
  }
199
200
  subgroupPending = subgroupPending && !matchingKey;
200
- }`}function xr(r,e){return fe("GPUGroupAggregation",r,ye,e)}function wr(r,e){let{x:t,y:n,z:o}=e.dispatchSize??{x:e.dispatchCount??1,y:1,z:1},i=t*n*o,s=V({id:e.id,resources:e.resources,workload:{operation:"GPUGroupAggregation",commandCount:1,maximumWorkgroupCount:i,maximumInvocationCount:i*ye},compile:({device:a})=>{let u=new D(a,{id:e.id,source:e.source,shaderLayout:{bindings:Object.keys(e.bindings).map((c,d)=>({name:c,type:"storage",group:0,location:d}))}});return{encode:({computePass:c,getBuffer:d})=>{let l={};for(let[f,h]of Object.entries(e.bindings))l[f]=G(h,d);u.dispatch(c,{bindings:l,x:t,y:n,z:o})},destroy:()=>u.destroy()}}});return[N(s,[t,n,o])]}var Re=256,Ps=["uint32","sint32","float32"];function nc(r){return Be(r,{requiresSubgroupId:!0})}var Jr=class{id;input;mask;output;operation;constructor(e){this.id=e.id??"gpu-reduction",this.input=e.input,this.mask=e.mask,this.output=e.output,this.operation=e.operation;for(let[n,o]of $o(this.input).entries()){let i=this.input instanceof O?` input chunk ${n}`:" input";if(ge(o,Ps,`${this.id}${i}`),o.format!==this.input.format)throw new Error(`${this.id}${i} format must match the input format`)}if(ge(this.output,Ps,`${this.id} output`),this.input.format!==this.output.format)throw new Error(`${this.id} input and output formats must match`);if(!["sum","min","max","extent"].includes(this.operation))throw new Error(`${this.id} operation must be sum, min, max, or extent`);let t=this.operation==="extent"?2:1;if(this.output.length!==t)throw new Error(`${this.id} ${this.operation} output must contain ${t} row(s)`);if($o(this.input).some(n=>n.buffer===this.output.buffer))throw new Error(`${this.id} inputs and output must use separate buffers`);if(this.mask){for(let[n,o]of Ls(this.mask).entries())if(Le(o,`${this.id} mask chunk ${n}`),o.buffer===this.output.buffer)throw new Error(`${this.id} mask and output must use separate buffers`);if(this.input.length!==this.mask.length)throw new Error(`${this.id} input and mask lengths must match`)}}getCommandNodes(e){let t=[],n=$o(this.input),o=this.mask?Ls(this.mask):void 0;if(n.some(c=>c.buffer.graph!==e)||o?.some(c=>c.buffer.graph!==e)||this.output.buffer.graph!==e)throw new Error(`${this.id} views must belong to the target graph`);if(this.mask){let c=X(e,[this.input,this.mask]);n=c.map(([d])=>d),o=c.map(([,d])=>d)}let i=n.map((c,d)=>({input:c,mask:o?.[d]})).filter(({input:c})=>c.length>0);if(i.length===0)return t.push(...cc(e,this.id,this.output)),t;let s=this.operation==="extent"?2:1,a=this.operation!=="sum"&&(this.input.format==="float32"||!!this.mask),u;if(i.length===1)u=Oo(e,{id:this.id,format:this.input.format,operation:this.operation,inputValues:i[0].input,inputValidity:i[0].mask,inputLength:i[0].input.length,valuesPerRow:s,firstLevel:!0,needsValidity:a}),t.push(...u.nodes);else{let c=z(e,`${this.id}-chunk-values`,this.input.format,i.length*s),d=a?z(e,`${this.id}-chunk-validity`,"uint32",i.length):void 0;i.forEach(({input:l,mask:f},h)=>{t.push(...Oo(e,{id:`${this.id}-chunk-${h}`,format:this.input.format,operation:this.operation,inputValues:l,inputValidity:f,inputLength:l.length,valuesPerRow:s,firstLevel:!0,needsValidity:a,finalValues:Cs(e,c,h*s,s),finalValidity:d?Cs(e,d,h,1):void 0}).nodes)}),u=Oo(e,{id:`${this.id}-merge`,format:this.input.format,operation:this.operation,inputValues:c,inputValidity:d,inputLength:i.length,valuesPerRow:s,firstLevel:!1,needsValidity:a}),t.push(...u.nodes)}return t.push(...uc(e,{id:`${this.id}-finalize`,format:this.input.format,inputValues:u.values,inputValidity:u.validity,output:this.output,valuesPerRow:s})),t}};function Oo(r,e){let t=[],n=e.inputValues,o=e.inputValidity,i=e.inputLength,s=0;for(;i>1||s===0;){let a=Math.ceil(i/Re),u=a===1,c=u&&e.finalValues?e.finalValues:z(r,`${e.id}-level-${s}-values`,e.format,a*e.valuesPerRow),d=e.needsValidity?u&&e.finalValidity?e.finalValidity:z(r,`${e.id}-level-${s}-validity`,"uint32",a):void 0;t.push(...oc(r,{id:`${e.id}-level-${s}`,format:e.format,operation:e.operation,inputValues:n,inputValidity:o,outputValues:c,outputValidity:d,inputLength:i,valuesPerRow:e.valuesPerRow,firstLevel:e.firstLevel&&s===0})),n=c,o=d,i=a,s++}return{values:n,validity:o,nodes:t}}function Cs(r,e,t,n){return r.createDataView(e.buffer,{format:e.format,length:n,byteOffset:e.byteOffset+t*e.rowByteLength})}function $o(r){return r instanceof O?r.data:[r]}function Ls(r){return r instanceof O?r.data:[r]}function oc(r,e){let t=[],n=fe("GPUReduction",e.inputLength,Re,r.device.limits.maxComputeWorkgroupsPerDimension),o=Io(e.format),i=Uo(e.format),s=e.operation==="sum",a=e.operation==="extent",u=e.inputValidity?"@group(0) @binding(1) var<storage, read> inputValidity: array<u32>;":"",c=e.inputValidity?2:1,d=c+1,l=e.format==="float32"?"value == value && abs(value) <= 3.402823466e+38":"true",f=e.firstLevel&&e.inputValidity&&e.format==="float32"&&s?`
201
- if (valid == 0u) { value = 0.0; secondValue = 0.0; }`:"",h=`value = inputValues[INPUT_OFFSET + index];
201
+ }`}function xr(r,e){return fe("GPUGroupAggregation",r,ye,e)}function wr(r,e){let{x:t,y:n,z:o}=e.dispatchSize??{x:e.dispatchCount??1,y:1,z:1},i=t*n*o,s=V({id:e.id,resources:e.resources,workload:{operation:"GPUGroupAggregation",commandCount:1,maximumWorkgroupCount:i,maximumInvocationCount:i*ye},compile:({device:a})=>{let u=new D(a,{id:e.id,source:e.source,shaderLayout:{bindings:Object.keys(e.bindings).map((c,d)=>({name:c,type:"storage",group:0,location:d}))}});return{encode:({computePass:c,getBuffer:d})=>{let l={};for(let[h,f]of Object.entries(e.bindings))l[h]=G(f,d);u.dispatch(c,{bindings:l,x:t,y:n,z:o})},destroy:()=>u.destroy()}}});return[N(s,[t,n,o])]}var Re=256,Cs=["uint32","sint32","float32"];function nc(r){return Be(r,{requiresSubgroupId:!0})}var Jr=class{id;input;mask;output;operation;constructor(e){this.id=e.id??"gpu-reduction",this.input=e.input,this.mask=e.mask,this.output=e.output,this.operation=e.operation;for(let[n,o]of $o(this.input).entries()){let i=this.input instanceof O?` input chunk ${n}`:" input";if(ge(o,Cs,`${this.id}${i}`),o.format!==this.input.format)throw new Error(`${this.id}${i} format must match the input format`)}if(ge(this.output,Cs,`${this.id} output`),this.input.format!==this.output.format)throw new Error(`${this.id} input and output formats must match`);if(!["sum","min","max","extent"].includes(this.operation))throw new Error(`${this.id} operation must be sum, min, max, or extent`);let t=this.operation==="extent"?2:1;if(this.output.length!==t)throw new Error(`${this.id} ${this.operation} output must contain ${t} row(s)`);if($o(this.input).some(n=>n.buffer===this.output.buffer))throw new Error(`${this.id} inputs and output must use separate buffers`);if(this.mask){for(let[n,o]of Bs(this.mask).entries())if(Le(o,`${this.id} mask chunk ${n}`),o.buffer===this.output.buffer)throw new Error(`${this.id} mask and output must use separate buffers`);if(this.input.length!==this.mask.length)throw new Error(`${this.id} input and mask lengths must match`)}}getCommandNodes(e){let t=[],n=$o(this.input),o=this.mask?Bs(this.mask):void 0;if(n.some(c=>c.buffer.graph!==e)||o?.some(c=>c.buffer.graph!==e)||this.output.buffer.graph!==e)throw new Error(`${this.id} views must belong to the target graph`);if(this.mask){let c=X(e,[this.input,this.mask]);n=c.map(([d])=>d),o=c.map(([,d])=>d)}let i=n.map((c,d)=>({input:c,mask:o?.[d]})).filter(({input:c})=>c.length>0);if(i.length===0)return t.push(...cc(e,this.id,this.output)),t;let s=this.operation==="extent"?2:1,a=this.operation!=="sum"&&(this.input.format==="float32"||!!this.mask),u;if(i.length===1)u=Oo(e,{id:this.id,format:this.input.format,operation:this.operation,inputValues:i[0].input,inputValidity:i[0].mask,inputLength:i[0].input.length,valuesPerRow:s,firstLevel:!0,needsValidity:a}),t.push(...u.nodes);else{let c=z(e,`${this.id}-chunk-values`,this.input.format,i.length*s),d=a?z(e,`${this.id}-chunk-validity`,"uint32",i.length):void 0;i.forEach(({input:l,mask:h},f)=>{t.push(...Oo(e,{id:`${this.id}-chunk-${f}`,format:this.input.format,operation:this.operation,inputValues:l,inputValidity:h,inputLength:l.length,valuesPerRow:s,firstLevel:!0,needsValidity:a,finalValues:Ls(e,c,f*s,s),finalValidity:d?Ls(e,d,f,1):void 0}).nodes)}),u=Oo(e,{id:`${this.id}-merge`,format:this.input.format,operation:this.operation,inputValues:c,inputValidity:d,inputLength:i.length,valuesPerRow:s,firstLevel:!1,needsValidity:a}),t.push(...u.nodes)}return t.push(...uc(e,{id:`${this.id}-finalize`,format:this.input.format,inputValues:u.values,inputValidity:u.validity,output:this.output,valuesPerRow:s})),t}};function Oo(r,e){let t=[],n=e.inputValues,o=e.inputValidity,i=e.inputLength,s=0;for(;i>1||s===0;){let a=Math.ceil(i/Re),u=a===1,c=u&&e.finalValues?e.finalValues:z(r,`${e.id}-level-${s}-values`,e.format,a*e.valuesPerRow),d=e.needsValidity?u&&e.finalValidity?e.finalValidity:z(r,`${e.id}-level-${s}-validity`,"uint32",a):void 0;t.push(...oc(r,{id:`${e.id}-level-${s}`,format:e.format,operation:e.operation,inputValues:n,inputValidity:o,outputValues:c,outputValidity:d,inputLength:i,valuesPerRow:e.valuesPerRow,firstLevel:e.firstLevel&&s===0})),n=c,o=d,i=a,s++}return{values:n,validity:o,nodes:t}}function Ls(r,e,t,n){return r.createDataView(e.buffer,{format:e.format,length:n,byteOffset:e.byteOffset+t*e.rowByteLength})}function $o(r){return r instanceof O?r.data:[r]}function Bs(r){return r instanceof O?r.data:[r]}function oc(r,e){let t=[],n=fe("GPUReduction",e.inputLength,Re,r.device.limits.maxComputeWorkgroupsPerDimension),o=Io(e.format),i=Uo(e.format),s=e.operation==="sum",a=e.operation==="extent",u=e.inputValidity?"@group(0) @binding(1) var<storage, read> inputValidity: array<u32>;":"",c=e.inputValidity?2:1,d=c+1,l=e.format==="float32"?"value == value && abs(value) <= 3.402823466e+38":"true",h=e.firstLevel&&e.inputValidity&&e.format==="float32"&&s?`
202
+ if (valid == 0u) { value = 0.0; secondValue = 0.0; }`:"",f=`value = inputValues[INPUT_OFFSET + index];
202
203
  secondValue = value;
203
- valid = select(0u, 1u, ${l});${f}`,m=e.firstLevel?e.inputValidity?`if (inputValidity[VALIDITY_OFFSET + index] != 0u) {
204
- ${h}
205
- }`:h:`value = inputValues[INPUT_OFFSET + index * VALUES_PER_ROW];
204
+ valid = select(0u, 1u, ${l});${h}`,m=e.firstLevel?e.inputValidity?`if (inputValidity[VALIDITY_OFFSET + index] != 0u) {
205
+ ${f}
206
+ }`:f:`value = inputValues[INPUT_OFFSET + index * VALUES_PER_ROW];
206
207
  secondValue = inputValues[INPUT_OFFSET + index * VALUES_PER_ROW + ${a?"1u":"0u"}];
207
- ${e.inputValidity?"valid = inputValidity[VALIDITY_OFFSET + index];":"valid = 1u;"}`,g=s?"firstScratch[lane] = firstScratch[lane] + firstScratch[lane + stride];":`let rightValid = validityScratch[lane + stride];
208
+ ${e.inputValidity?"valid = inputValidity[VALIDITY_OFFSET + index];":"valid = 1u;"}`,p=s?"firstScratch[lane] = firstScratch[lane] + firstScratch[lane + stride];":`let rightValid = validityScratch[lane + stride];
208
209
  if (rightValid != 0u) {
209
210
  if (validityScratch[lane] == 0u) {
210
211
  firstScratch[lane] = firstScratch[lane + stride];
@@ -214,7 +215,7 @@ ${c}
214
215
  secondScratch[lane] = ${a||e.operation==="max"?"max":"min"}(secondScratch[lane], secondScratch[lane + stride]);
215
216
  }
216
217
  validityScratch[lane] = 1u;
217
- }`,y=nc(r.device),p=y==="subgroups"?sc({format:e.format,operation:e.operation,combine:g}):ic(g),w=`
218
+ }`,y=nc(r.device),g=y==="subgroups"?sc({format:e.format,operation:e.operation,combine:p}):ic(p),w=`
218
219
  ${y==="subgroups"?`enable subgroups;
219
220
  requires subgroup_id;`:""}
220
221
  const ELEMENT_COUNT: u32 = ${e.inputLength}u;
@@ -249,7 +250,7 @@ var<workgroup> validityScratch: array<u32, ${Re}>;
249
250
  if (index < ELEMENT_COUNT) {
250
251
  ${m}
251
252
  }
252
- ${p}
253
+ ${g}
253
254
  if (lane == 0u) {
254
255
  outputValues[OUTPUT_OFFSET + workgroupIndex * VALUES_PER_ROW] = firstScratch[0];
255
256
  ${a?"outputValues[OUTPUT_OFFSET + workgroupIndex * VALUES_PER_ROW + 1u] = secondScratch[0];":""}
@@ -267,7 +268,7 @@ var<workgroup> validityScratch: array<u32, ${Re}>;
267
268
  workgroupBarrier();
268
269
  if (stride == 1u) { break; }
269
270
  stride = stride / 2u;
270
- }`}function sc(r){let e=Bs(r.format,r.operation==="extent"?"min":r.operation,"value","valid"),t=Bs(r.format,r.operation==="extent"?"max":r.operation,"secondValue","valid");return`let subgroupValid = subgroupMax(valid);
271
+ }`}function sc(r){let e=Os(r.format,r.operation==="extent"?"min":r.operation,"value","valid"),t=Os(r.format,r.operation==="extent"?"max":r.operation,"secondValue","valid");return`let subgroupValid = subgroupMax(valid);
271
272
  let subgroupFirst = ${e};
272
273
  let subgroupSecond = ${t};
273
274
  if (subgroupInvocationId == 0u) {
@@ -287,7 +288,7 @@ var<workgroup> validityScratch: array<u32, ${Re}>;
287
288
  if (stride == 1u) { break; }
288
289
  stride = stride / 2u;
289
290
  }
290
- }`}function Bs(r,e,t,n){if(e==="sum")return`subgroupAdd(${t})`;let o=ac(r,e);return`${e==="min"?"subgroupMin":"subgroupMax"}(select(${o}, ${t}, ${n} != 0u))`}function ac(r,e){return r==="uint32"?e==="min"?"4294967295u":"0u":r==="sint32"?e==="min"?"2147483647":"(-2147483647 - 1)":e==="min"?"3.402823466e+38":"-3.402823466e+38"}function uc(r,e){let t=[],n=Io(e.format),o=Uo(e.format),i=Array.from({length:e.valuesPerRow},(a,u)=>{let c=`inputValues[INPUT_OFFSET + ${u}u]`;return`outputValues[OUTPUT_OFFSET + ${u}u] = ${e.inputValidity?`select(${o}, ${c}, valid)`:c};`}).join(`
291
+ }`}function Os(r,e,t,n){if(e==="sum")return`subgroupAdd(${t})`;let o=ac(r,e);return`${e==="min"?"subgroupMin":"subgroupMax"}(select(${o}, ${t}, ${n} != 0u))`}function ac(r,e){return r==="uint32"?e==="min"?"4294967295u":"0u":r==="sint32"?e==="min"?"2147483647":"(-2147483647 - 1)":e==="min"?"3.402823466e+38":"-3.402823466e+38"}function uc(r,e){let t=[],n=Io(e.format),o=Uo(e.format),i=Array.from({length:e.valuesPerRow},(a,u)=>{let c=`inputValues[INPUT_OFFSET + ${u}u]`;return`outputValues[OUTPUT_OFFSET + ${u}u] = ${e.inputValidity?`select(${o}, ${c}, valid)`:c};`}).join(`
291
292
  `),s=`
292
293
  const INPUT_OFFSET: u32 = ${P(e.inputValues)}u;
293
294
  const OUTPUT_OFFSET: u32 = ${P(e.output)}u;
@@ -302,17 +303,17 @@ ${e.inputValidity?"@group(0) @binding(1) var<storage, read> inputValidity: array
302
303
  @group(0) @binding(0) var<storage, read_write> outputValues: array<${i}>;
303
304
  @compute @workgroup_size(1) fn main() {
304
305
  for (var index = 0u; index < ${t.length}u; index++) { outputValues[OUTPUT_OFFSET + index] = ${s}; }
305
- }`,resources:[{buffer:t,usage:"storage-write"}],bindings:{outputValues:t},dispatchCount:1})),n}function ko(r,e){let{x:t,y:n,z:o}=e.dispatchLayout??{x:e.dispatchCount??1,y:1,z:1},i=V({id:e.id,resources:e.resources,compile:({device:s})=>{let a=Object.keys(e.bindings),u=new D(s,{id:e.id,source:e.source,shaderLayout:{bindings:a.map((c,d)=>({name:c,type:"storage",group:0,location:d}))}});return{encode:({computePass:c,getBuffer:d})=>{let l={};for(let[f,h]of Object.entries(e.bindings))l[f]=G(h,d);u.dispatch(c,{bindings:l,x:t,y:n,z:o})},destroy:()=>u.destroy()}}});return[N(i,[t,n,o])]}function Io(r){return r==="uint32"?"u32":r==="sint32"?"i32":"f32"}function Uo(r){return r==="uint32"?"0u":r==="sint32"?"0":"0.0"}var K=256,dc=64;function Os(r,e=!1){return e?"portable":Be(r,{requiresSubgroupId:!0})}var en=class{id;input;output;mode;segmentFlags;constructor(e){if(this.id=e.id??"gpu-scan",this.input=e.input,this.output=e.output,this.mode=e.mode??"exclusive",this.segmentFlags=e.segmentFlags,Do(this.input,`${this.id} input`),Do(this.output,`${this.id} output`),this.output.length<this.input.length)throw new Error(`${this.id} output must contain at least input.length rows`);if(this.output instanceof O&&this.output.length!==this.input.length)throw new Error(`${this.id} vector output length must equal input length`);if(this.segmentFlags){if(Do(this.segmentFlags,`${this.id} segmentFlags`),this.segmentFlags.length<this.input.length)throw new Error(`${this.id} segmentFlags must contain at least input.length rows`);if(this.segmentFlags instanceof O&&this.segmentFlags.length!==this.input.length)throw new Error(`${this.id} vector segmentFlags length must equal input length`);let t=new Set(Is(this.output).map(n=>n.buffer));if(Is(this.segmentFlags).some(n=>t.has(n.buffer)))throw new Error(`${this.id} segmentFlags and output must use separate buffers`)}}getCommandNodes(e){let t=[];return t.push(...Fo(this,e,e.device.limits.maxComputeWorkgroupsPerDimension)),t}};function Fo(r,e,t){let n=[];_o(e,r.input,r.id),_o(e,r.output,r.id),r.segmentFlags&&_o(e,r.segmentFlags,r.id);let o=$s(e,r.output,r.input.length),i=r.segmentFlags?$s(e,r.segmentFlags,r.input.length):void 0,s=i?X(e,[r.input,o,i]):X(e,[r.input,o]);return n.push(...lc(e,{id:r.id,inputChunks:s.map(a=>a[0]),outputChunks:s.map(a=>a[1]),segmentFlagChunks:i?s.map(a=>a[2]):void 0,isVector:s.length>1,mode:r.mode},t)),n}function $s(r,e,t){return e.length===t||e instanceof O?e:r.createDataView(e.buffer,{format:e.format,length:t,byteOffset:e.byteOffset,byteStride:e.byteStride,rowByteLength:e.rowByteLength})}function lc(r,e,t){let n=[],o=e.inputChunks,i=e.outputChunks,s=e.segmentFlagChunks,a=o.map((f,h)=>({chunkIndex:h,input:f,output:i[h],segmentFlags:s?.[h]})).filter(f=>f.input.length>0);if(a.length===0)return n;if(a.length===1){let f=a[0];return n.push(...Go(r,{id:e.isVector?`${e.id}-chunk-${f.chunkIndex}`:e.id,input:f.input,output:f.output,mode:e.mode,segmentFlags:f.segmentFlags,maxComputeWorkgroupsPerDimension:t})),n}let u=z(r,`${e.id}-chunk-totals`,"uint32",a.length),c=z(r,`${e.id}-chunk-offsets`,"uint32",a.length),d=s?z(r,`${e.id}-chunk-segment-flags`,"uint32",a.length):void 0,l=s?a.map(f=>z(r,`${e.id}-chunk-${f.chunkIndex}-segment-prefixes`,"uint32",f.input.length)):void 0;for(let[f,h]of a.entries())n.push(...Go(r,{id:`${e.id}-chunk-${h.chunkIndex}`,input:h.input,output:h.output,mode:e.mode,segmentFlags:h.segmentFlags,outputSegmentPrefixes:l?.[f],finalSum:ks(r,u,f),finalSegmentFlag:d?ks(r,d,f):void 0,maxComputeWorkgroupsPerDimension:t}));n.push(...Go(r,{id:`${e.id}-chunk-carries`,input:u,output:c,mode:"exclusive",segmentFlags:d,segmentSummaryInput:!!d,maxComputeWorkgroupsPerDimension:t}));for(let[f,h]of a.entries())n.push(...Us(r,{id:`${e.id}-chunk-${h.chunkIndex}-add-carry`,output:h.output,offsets:c,length:h.output.length,offsetIndex:f,segmentPrefixes:l?.[f],dispatchLayout:Ao(h.output.length,t)}));return n}function Go(r,e){let t=[];if(e.input.length===0)return t;let n=[],o=e.input,i=e.output,s=e.segmentFlags,a=e.input.length,u=0;for(;;){let c=Math.ceil(a/K),d,l;c>1&&(d=z(r,`${e.id}-level-${u}-block-sums`,"uint32",c),s&&(l=z(r,`${e.id}-level-${u}-block-segment-flags`,"uint32",c)));let f=s?u===0&&e.outputSegmentPrefixes?e.outputSegmentPrefixes:c>1||u>0?z(r,`${e.id}-level-${u}-segment-prefixes`,"uint32",a):void 0:void 0;if(t.push(...fc(r,{id:`${e.id}-level-${u}-scan`,input:o,output:i,mode:u===0?e.mode:"exclusive",segmentFlags:s,segmentSummaryInput:!!s&&(u>0||e.segmentSummaryInput),segmentPrefixes:f,blockSums:d,blockSegmentFlags:l,finalSum:d?void 0:e.finalSum,finalSegmentFlag:d?void 0:e.finalSegmentFlag,length:a,blockCount:c,dispatchLayout:Ao(a,e.maxComputeWorkgroupsPerDimension)})),n.push({output:i,length:a,segmentPrefixes:f}),!d)break;let h=z(r,`${e.id}-level-${u}-block-offsets`,"uint32",c);n[n.length-1].blockOffsets=h,o=d,i=h,s=l,a=c,u++}for(let c=n.length-2;c>=0;c--){let d=n[c],l=n[c+1];t.push(...Us(r,{id:`${e.id}-level-${c}-add-offsets`,output:d.output,offsets:d.blockOffsets,length:d.length,segmentPrefixes:d.segmentPrefixes,offsetSegmentPrefixes:l.segmentPrefixes,dispatchLayout:Ao(d.length,e.maxComputeWorkgroupsPerDimension)}))}return t}function ks(r,e,t){return r.createDataView(e.buffer,{format:"uint32",length:1,byteOffset:e.byteOffset+t*e.rowByteLength})}function Do(r,e){let t=r instanceof O?r.data:[r];for(let n of t)Le(n,e)}function Is(r){return r instanceof O?r.data:[r]}function _o(r,e,t){if((e instanceof O?e.data:[e]).some(o=>o.buffer.graph!==r))throw new Error(`${t} views must belong to the target graph`)}function fc(r,e){let t=[],n=e.blockSums??e.finalSum,o=e.blockSegmentFlags??e.finalSegmentFlag,i=n?"@group(0) @binding(2) var<storage, read_write> sumValues: array<u32>;":"",s=e.segmentFlags?"@group(0) @binding(3) var<storage, read> segmentFlags: array<u32>;":"",a=e.segmentPrefixes?"@group(0) @binding(4) var<storage, read_write> segmentPrefixes: array<u32>;":"",u=o?"@group(0) @binding(5) var<storage, read_write> summarySegmentFlags: array<u32>;":"",c=e.blockSums?"sumValues[SUM_OFFSET + workgroupIndex] = scratch[255u];":e.finalSum?"sumValues[SUM_OFFSET] = scratch[255u];":"",d=e.blockSegmentFlags?"summarySegmentFlags[SUMMARY_SEGMENT_FLAGS_OFFSET + workgroupIndex] = segmentScratch[255u];":e.finalSegmentFlag?"summarySegmentFlags[SUMMARY_SEGMENT_FLAGS_OFFSET] = segmentScratch[255u];":"",l=e.segmentFlags?"segmentFlags[SEGMENT_FLAGS_OFFSET + index]":"0u",f=e.segmentFlags?`if (lane >= stride) {
306
+ }`,resources:[{buffer:t,usage:"storage-write"}],bindings:{outputValues:t},dispatchCount:1})),n}function ko(r,e){let{x:t,y:n,z:o}=e.dispatchLayout??{x:e.dispatchCount??1,y:1,z:1},i=V({id:e.id,resources:e.resources,compile:({device:s})=>{let a=Object.keys(e.bindings),u=new D(s,{id:e.id,source:e.source,shaderLayout:{bindings:a.map((c,d)=>({name:c,type:"storage",group:0,location:d}))}});return{encode:({computePass:c,getBuffer:d})=>{let l={};for(let[h,f]of Object.entries(e.bindings))l[h]=G(f,d);u.dispatch(c,{bindings:l,x:t,y:n,z:o})},destroy:()=>u.destroy()}}});return[N(i,[t,n,o])]}function Io(r){return r==="uint32"?"u32":r==="sint32"?"i32":"f32"}function Uo(r){return r==="uint32"?"0u":r==="sint32"?"0":"0.0"}var K=256,dc=64;function $s(r,e=!1){return e?"portable":Be(r,{requiresSubgroupId:!0})}var en=class{id;input;output;mode;segmentFlags;constructor(e){if(this.id=e.id??"gpu-scan",this.input=e.input,this.output=e.output,this.mode=e.mode??"exclusive",this.segmentFlags=e.segmentFlags,Do(this.input,`${this.id} input`),Do(this.output,`${this.id} output`),this.output.length<this.input.length)throw new Error(`${this.id} output must contain at least input.length rows`);if(this.output instanceof O&&this.output.length!==this.input.length)throw new Error(`${this.id} vector output length must equal input length`);if(this.segmentFlags){if(Do(this.segmentFlags,`${this.id} segmentFlags`),this.segmentFlags.length<this.input.length)throw new Error(`${this.id} segmentFlags must contain at least input.length rows`);if(this.segmentFlags instanceof O&&this.segmentFlags.length!==this.input.length)throw new Error(`${this.id} vector segmentFlags length must equal input length`);let t=new Set(Us(this.output).map(n=>n.buffer));if(Us(this.segmentFlags).some(n=>t.has(n.buffer)))throw new Error(`${this.id} segmentFlags and output must use separate buffers`)}}getCommandNodes(e){let t=[];return t.push(...Fo(this,e,e.device.limits.maxComputeWorkgroupsPerDimension)),t}};function Fo(r,e,t){let n=[];_o(e,r.input,r.id),_o(e,r.output,r.id),r.segmentFlags&&_o(e,r.segmentFlags,r.id);let o=ks(e,r.output,r.input.length),i=r.segmentFlags?ks(e,r.segmentFlags,r.input.length):void 0,s=i?X(e,[r.input,o,i]):X(e,[r.input,o]);return n.push(...lc(e,{id:r.id,inputChunks:s.map(a=>a[0]),outputChunks:s.map(a=>a[1]),segmentFlagChunks:i?s.map(a=>a[2]):void 0,isVector:s.length>1,mode:r.mode},t)),n}function ks(r,e,t){return e.length===t||e instanceof O?e:r.createDataView(e.buffer,{format:e.format,length:t,byteOffset:e.byteOffset,byteStride:e.byteStride,rowByteLength:e.rowByteLength})}function lc(r,e,t){let n=[],o=e.inputChunks,i=e.outputChunks,s=e.segmentFlagChunks,a=o.map((h,f)=>({chunkIndex:f,input:h,output:i[f],segmentFlags:s?.[f]})).filter(h=>h.input.length>0);if(a.length===0)return n;if(a.length===1){let h=a[0];return n.push(...Go(r,{id:e.isVector?`${e.id}-chunk-${h.chunkIndex}`:e.id,input:h.input,output:h.output,mode:e.mode,segmentFlags:h.segmentFlags,maxComputeWorkgroupsPerDimension:t})),n}let u=z(r,`${e.id}-chunk-totals`,"uint32",a.length),c=z(r,`${e.id}-chunk-offsets`,"uint32",a.length),d=s?z(r,`${e.id}-chunk-segment-flags`,"uint32",a.length):void 0,l=s?a.map(h=>z(r,`${e.id}-chunk-${h.chunkIndex}-segment-prefixes`,"uint32",h.input.length)):void 0;for(let[h,f]of a.entries())n.push(...Go(r,{id:`${e.id}-chunk-${f.chunkIndex}`,input:f.input,output:f.output,mode:e.mode,segmentFlags:f.segmentFlags,outputSegmentPrefixes:l?.[h],finalSum:Is(r,u,h),finalSegmentFlag:d?Is(r,d,h):void 0,maxComputeWorkgroupsPerDimension:t}));n.push(...Go(r,{id:`${e.id}-chunk-carries`,input:u,output:c,mode:"exclusive",segmentFlags:d,segmentSummaryInput:!!d,maxComputeWorkgroupsPerDimension:t}));for(let[h,f]of a.entries())n.push(...Gs(r,{id:`${e.id}-chunk-${f.chunkIndex}-add-carry`,output:f.output,offsets:c,length:f.output.length,offsetIndex:h,segmentPrefixes:l?.[h],dispatchLayout:Ao(f.output.length,t)}));return n}function Go(r,e){let t=[];if(e.input.length===0)return t;let n=[],o=e.input,i=e.output,s=e.segmentFlags,a=e.input.length,u=0;for(;;){let c=Math.ceil(a/K),d,l;c>1&&(d=z(r,`${e.id}-level-${u}-block-sums`,"uint32",c),s&&(l=z(r,`${e.id}-level-${u}-block-segment-flags`,"uint32",c)));let h=s?u===0&&e.outputSegmentPrefixes?e.outputSegmentPrefixes:c>1||u>0?z(r,`${e.id}-level-${u}-segment-prefixes`,"uint32",a):void 0:void 0;if(t.push(...fc(r,{id:`${e.id}-level-${u}-scan`,input:o,output:i,mode:u===0?e.mode:"exclusive",segmentFlags:s,segmentSummaryInput:!!s&&(u>0||e.segmentSummaryInput),segmentPrefixes:h,blockSums:d,blockSegmentFlags:l,finalSum:d?void 0:e.finalSum,finalSegmentFlag:d?void 0:e.finalSegmentFlag,length:a,blockCount:c,dispatchLayout:Ao(a,e.maxComputeWorkgroupsPerDimension)})),n.push({output:i,length:a,segmentPrefixes:h}),!d)break;let f=z(r,`${e.id}-level-${u}-block-offsets`,"uint32",c);n[n.length-1].blockOffsets=f,o=d,i=f,s=l,a=c,u++}for(let c=n.length-2;c>=0;c--){let d=n[c],l=n[c+1];t.push(...Gs(r,{id:`${e.id}-level-${c}-add-offsets`,output:d.output,offsets:d.blockOffsets,length:d.length,segmentPrefixes:d.segmentPrefixes,offsetSegmentPrefixes:l.segmentPrefixes,dispatchLayout:Ao(d.length,e.maxComputeWorkgroupsPerDimension)}))}return t}function Is(r,e,t){return r.createDataView(e.buffer,{format:"uint32",length:1,byteOffset:e.byteOffset+t*e.rowByteLength})}function Do(r,e){let t=r instanceof O?r.data:[r];for(let n of t)Le(n,e)}function Us(r){return r instanceof O?r.data:[r]}function _o(r,e,t){if((e instanceof O?e.data:[e]).some(o=>o.buffer.graph!==r))throw new Error(`${t} views must belong to the target graph`)}function fc(r,e){let t=[],n=e.blockSums??e.finalSum,o=e.blockSegmentFlags??e.finalSegmentFlag,i=n?"@group(0) @binding(2) var<storage, read_write> sumValues: array<u32>;":"",s=e.segmentFlags?"@group(0) @binding(3) var<storage, read> segmentFlags: array<u32>;":"",a=e.segmentPrefixes?"@group(0) @binding(4) var<storage, read_write> segmentPrefixes: array<u32>;":"",u=o?"@group(0) @binding(5) var<storage, read_write> summarySegmentFlags: array<u32>;":"",c=e.blockSums?"sumValues[SUM_OFFSET + workgroupIndex] = scratch[255u];":e.finalSum?"sumValues[SUM_OFFSET] = scratch[255u];":"",d=e.blockSegmentFlags?"summarySegmentFlags[SUMMARY_SEGMENT_FLAGS_OFFSET + workgroupIndex] = segmentScratch[255u];":e.finalSegmentFlag?"summarySegmentFlags[SUMMARY_SEGMENT_FLAGS_OFFSET] = segmentScratch[255u];":"",l=e.segmentFlags?"segmentFlags[SEGMENT_FLAGS_OFFSET + index]":"0u",h=e.segmentFlags?`if (lane >= stride) {
306
307
  scratch[lane] = select(addend + scratch[lane], scratch[lane], segmentScratch[lane] != 0u);
307
308
  segmentScratch[lane] = addendSegment | segmentScratch[lane];
308
309
  }`:`if (lane >= stride) {
309
310
  scratch[lane] = scratch[lane] + addend;
310
- }`,h=e.mode==="inclusive"?"scratch[lane]":"scratch[lane] - inputValue",m=e.segmentFlags&&e.mode==="exclusive"?`var scannedOutput = 0u;
311
+ }`,f=e.mode==="inclusive"?"scratch[lane]":"scratch[lane] - inputValue",m=e.segmentFlags&&e.mode==="exclusive"?`var scannedOutput = 0u;
311
312
  if (lane > 0u) {
312
313
  scannedOutput = scratch[lane - 1u];
313
314
  }
314
315
  ${e.segmentSummaryInput?"":"if (inputSegmentFlag != 0u) { scannedOutput = 0u; }"}
315
- outputValues[OUTPUT_OFFSET + index] = scannedOutput;`:`outputValues[OUTPUT_OFFSET + index] = ${h};`,g=e.segmentPrefixes?e.segmentSummaryInput?`var segmentPrefix = 0u;
316
+ outputValues[OUTPUT_OFFSET + index] = scannedOutput;`:`outputValues[OUTPUT_OFFSET + index] = ${f};`,p=e.segmentPrefixes?e.segmentSummaryInput?`var segmentPrefix = 0u;
316
317
  if (lane > 0u) {
317
318
  segmentPrefix = segmentScratch[lane - 1u];
318
319
  }
@@ -338,7 +339,7 @@ ${e.segmentFlags?`var<workgroup> segmentScratch: array<u32, ${K}>;`:""}
338
339
  @builtin(local_invocation_index) localInvocationIndex: u32,
339
340
  @builtin(workgroup_id) workgroupId: vec3<u32>
340
341
  ) {
341
- ${Gs(e.dispatchLayout)}
342
+ ${Ds(e.dispatchLayout)}
342
343
  if (workgroupIndex >= BLOCK_COUNT) { return; }
343
344
  let lane = localInvocationIndex;
344
345
  var inputValue = 0u;
@@ -359,7 +360,7 @@ ${e.segmentFlags?`var<workgroup> segmentScratch: array<u32, ${K}>;`:""}
359
360
  ${e.segmentFlags?"addendSegment = segmentScratch[lane - stride];":""}
360
361
  }
361
362
  workgroupBarrier();
362
- ${f}
363
+ ${h}
363
364
  workgroupBarrier();
364
365
  }
365
366
 
@@ -369,9 +370,9 @@ ${e.segmentFlags?`var<workgroup> segmentScratch: array<u32, ${K}>;`:""}
369
370
  }
370
371
  if (index < ELEMENT_COUNT) {
371
372
  ${m}
372
- ${g}
373
+ ${p}
373
374
  }
374
- }`,p=hc(r,!!e.segmentFlags,e.length),w=p==="subgroups"?mc(e,n,i):y,S={bindings:[{name:"inputValues",type:"storage",group:0,location:0},{name:"outputValues",type:"storage",group:0,location:1},...n?[{name:"sumValues",type:"storage",group:0,location:2}]:[],...e.segmentFlags?[{name:"segmentFlags",type:"storage",group:0,location:3}]:[],...e.segmentPrefixes?[{name:"segmentPrefixes",type:"storage",group:0,location:4}]:[],...o?[{name:"summarySegmentFlags",type:"storage",group:0,location:5}]:[]]};return t.push(V({id:e.id,kernel:{entryPoint:"main",workgroupSize:[K,1,1],bindings:S.bindings,source:w},workload:{operation:"GPUScan",variant:p,commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*K,readByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT,writeByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT+e.blockCount*Uint32Array.BYTES_PER_ELEMENT},resources:[{buffer:e.input,usage:"storage-read"},{buffer:e.output,usage:"storage-write"},...n?[{buffer:n,usage:"storage-write"}]:[],...e.segmentFlags?[{buffer:e.segmentFlags,usage:"storage-read"}]:[],...e.segmentPrefixes?[{buffer:e.segmentPrefixes,usage:"storage-write"}]:[],...o?[{buffer:o,usage:"storage-write"}]:[]],compile:({device:T})=>{let v=new D(T,{id:e.id,source:w,shaderLayout:S});return{encode:({computePass:b,getBuffer:C})=>{let B={inputValues:G(e.input,C),outputValues:G(e.output,C)};n&&(B.sumValues=G(n,C)),e.segmentFlags&&(B.segmentFlags=G(e.segmentFlags,C)),e.segmentPrefixes&&(B.segmentPrefixes=G(e.segmentPrefixes,C)),o&&(B.summarySegmentFlags=G(o,C)),v.dispatch(b,{bindings:B,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>v.destroy()}}})),t.map(T=>N(T,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function hc(r,e,t){let n=Os(r.device,e);if(!r.autotuner||e)return n;let o=n==="subgroups"?"portable":"subgroups";return r.autotuner.selectKernel({operation:"GPUScan",workloadSize:t,candidates:[{id:n},{id:o,supported:o==="portable"||Os(r.device,!1)==="subgroups"}]}).variant}function mc(r,e,t){let n=r.mode==="inclusive"?"blockPrefix":"blockPrefix - inputValue",o=r.blockSums?"sumValues[SUM_OFFSET + workgroupIndex] = blockPrefix;":r.finalSum?"sumValues[SUM_OFFSET] = blockPrefix;":"",i=Math.floor(4294967295/K)+1;return`
375
+ }`,g=hc(r,!!e.segmentFlags,e.length),w=g==="subgroups"?mc(e,n,i):y,S={bindings:[{name:"inputValues",type:"storage",group:0,location:0},{name:"outputValues",type:"storage",group:0,location:1},...n?[{name:"sumValues",type:"storage",group:0,location:2}]:[],...e.segmentFlags?[{name:"segmentFlags",type:"storage",group:0,location:3}]:[],...e.segmentPrefixes?[{name:"segmentPrefixes",type:"storage",group:0,location:4}]:[],...o?[{name:"summarySegmentFlags",type:"storage",group:0,location:5}]:[]]};return t.push(V({id:e.id,kernel:{entryPoint:"main",workgroupSize:[K,1,1],bindings:S.bindings,source:w},workload:{operation:"GPUScan",variant:g,commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*K,readByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT,writeByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT+e.blockCount*Uint32Array.BYTES_PER_ELEMENT},resources:[{buffer:e.input,usage:"storage-read"},{buffer:e.output,usage:"storage-write"},...n?[{buffer:n,usage:"storage-write"}]:[],...e.segmentFlags?[{buffer:e.segmentFlags,usage:"storage-read"}]:[],...e.segmentPrefixes?[{buffer:e.segmentPrefixes,usage:"storage-write"}]:[],...o?[{buffer:o,usage:"storage-write"}]:[]],compile:({device:T})=>{let v=new D(T,{id:e.id,source:w,shaderLayout:S});return{encode:({computePass:b,getBuffer:C})=>{let B={inputValues:G(e.input,C),outputValues:G(e.output,C)};n&&(B.sumValues=G(n,C)),e.segmentFlags&&(B.segmentFlags=G(e.segmentFlags,C)),e.segmentPrefixes&&(B.segmentPrefixes=G(e.segmentPrefixes,C)),o&&(B.summarySegmentFlags=G(o,C)),v.dispatch(b,{bindings:B,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>v.destroy()}}})),t.map(T=>N(T,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function hc(r,e,t){let n=$s(r.device,e);if(!r.autotuner||e)return n;let o=n==="subgroups"?"portable":"subgroups";return r.autotuner.selectKernel({operation:"GPUScan",workloadSize:t,candidates:[{id:n},{id:o,supported:o==="portable"||$s(r.device,!1)==="subgroups"}]}).variant}function mc(r,e,t){let n=r.mode==="inclusive"?"blockPrefix":"blockPrefix - inputValue",o=r.blockSums?"sumValues[SUM_OFFSET + workgroupIndex] = blockPrefix;":r.finalSum?"sumValues[SUM_OFFSET] = blockPrefix;":"",i=Math.floor(4294967295/K)+1;return`
375
376
  enable subgroups;
376
377
  requires subgroup_id;
377
378
 
@@ -424,7 +425,7 @@ var<workgroup> subgroupOffsets: array<u32, ${dc}>;
424
425
  if (index < ELEMENT_COUNT) {
425
426
  outputValues[OUTPUT_OFFSET + index] = ${n};
426
427
  }
427
- }`}function Us(r,e){let t=[],n=e.offsetIndex===void 0?`index / ${K}u`:`${e.offsetIndex}u`,o=`
428
+ }`}function Gs(r,e){let t=[],n=e.offsetIndex===void 0?`index / ${K}u`:`${e.offsetIndex}u`,o=`
428
429
  const ELEMENT_COUNT: u32 = ${e.length}u;
429
430
  const OUTPUT_OFFSET: u32 = ${P(e.output)}u;
430
431
  const OFFSETS_OFFSET: u32 = ${P(e.offsets)}u;
@@ -439,7 +440,7 @@ ${e.offsetSegmentPrefixes?"@group(0) @binding(3) var<storage, read> offsetSegmen
439
440
  @builtin(local_invocation_index) localInvocationIndex: u32,
440
441
  @builtin(workgroup_id) workgroupId: vec3<u32>
441
442
  ) {
442
- ${Gs(e.dispatchLayout)}
443
+ ${Ds(e.dispatchLayout)}
443
444
  if (index < ELEMENT_COUNT) {
444
445
  ${e.offsetSegmentPrefixes?`let offsetSegmentPrefix = offsetSegmentPrefixes[OFFSET_SEGMENT_PREFIXES_OFFSET + ${n}];`:""}
445
446
  ${e.segmentPrefixes?`let segmentPrefix = segmentPrefixes[SEGMENT_PREFIXES_OFFSET + index];
@@ -448,7 +449,7 @@ ${e.offsetSegmentPrefixes?"@group(0) @binding(3) var<storage, read> offsetSegmen
448
449
  ${e.segmentPrefixes?"}":""}
449
450
  ${e.segmentPrefixes&&e.offsetSegmentPrefixes?"segmentPrefixes[SEGMENT_PREFIXES_OFFSET + index] = segmentPrefix | offsetSegmentPrefix;":""}
450
451
  }
451
- }`,i={bindings:[{name:"outputValues",type:"storage",group:0,location:0},{name:"offsets",type:"storage",group:0,location:1},...e.segmentPrefixes?[{name:"segmentPrefixes",type:"storage",group:0,location:2}]:[],...e.offsetSegmentPrefixes?[{name:"offsetSegmentPrefixes",type:"storage",group:0,location:3}]:[]]};return t.push(V({id:e.id,kernel:{entryPoint:"main",workgroupSize:[K,1,1],bindings:i.bindings,source:o},workload:{operation:"GPUScan",commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*K,readByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT*2,writeByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT},resources:[{buffer:e.output,usage:"storage-read-write"},{buffer:e.offsets,usage:"storage-read"},...e.segmentPrefixes?[{buffer:e.segmentPrefixes,usage:e.offsetSegmentPrefixes?"storage-read-write":"storage-read"}]:[],...e.offsetSegmentPrefixes?[{buffer:e.offsetSegmentPrefixes,usage:"storage-read"}]:[]],compile:({device:s})=>{let a=new D(s,{id:e.id,source:o,shaderLayout:i});return{encode:({computePass:u,getBuffer:c})=>{let d={outputValues:G(e.output,c),offsets:G(e.offsets,c)};e.segmentPrefixes&&(d.segmentPrefixes=G(e.segmentPrefixes,c)),e.offsetSegmentPrefixes&&(d.offsetSegmentPrefixes=G(e.offsetSegmentPrefixes,c)),a.dispatch(u,{bindings:d,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>a.destroy()}}})),t.map(s=>N(s,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function Ao(r,e){return fe("GPUScan",r,K,e)}function Gs(r){return J(r,K)}var Tt=256,tn=class{id;input;flags;output;count;constructor(e){if(this.id=e.id??"gpu-compaction",this.input=e.input,this.flags=e.flags,this.output=e.output,this.count=e.count,Ro(this.input,`${this.id} input`),Ro(this.flags,`${this.id} flags`),Ro(this.output,`${this.id} output`),Le(this.count,`${this.id} count`),this.flags.length!==this.input.length)throw new Error(`${this.id} flags.length must equal input.length`);if(this.output.length<this.input.length)throw new Error(`${this.id} output must contain at least input.length rows`);if(this.count.length<1)throw new Error(`${this.id} count must contain one uint32 row`)}getCommandNodes(e){let t=[];return t.push(...pc(this,e,e.device.limits.maxComputeWorkgroupsPerDimension)),t}};function pc(r,e,t){let n=[];for(let a of[...wt(r.input),...wt(r.flags),...wt(r.output),r.count])if(a.buffer.graph!==e)throw new Error(`${r.id} views must belong to the target graph`);if(r.input.length===0)return n.push(...gc(e,r.id,r.count)),n;let o=r.flags instanceof O?Po(e,`${r.id}-offsets`,r.flags):z(e,`${r.id}-offsets`,"uint32",r.flags.length),i=r.flags instanceof O?Po(e,`${r.id}-flags`,r.flags):z(e,`${r.id}-flags`,"uint32",r.flags.length);for(let[a,u]of wt(r.flags).entries()){if(!u.length)continue;let c=wt(i)[a],d=fe(r.id,u.length,Tt,t);n.push(...Ds(e,{id:`${r.id}-normalize-${a}`,source:`
452
+ }`,i={bindings:[{name:"outputValues",type:"storage",group:0,location:0},{name:"offsets",type:"storage",group:0,location:1},...e.segmentPrefixes?[{name:"segmentPrefixes",type:"storage",group:0,location:2}]:[],...e.offsetSegmentPrefixes?[{name:"offsetSegmentPrefixes",type:"storage",group:0,location:3}]:[]]};return t.push(V({id:e.id,kernel:{entryPoint:"main",workgroupSize:[K,1,1],bindings:i.bindings,source:o},workload:{operation:"GPUScan",commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*K,readByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT*2,writeByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT},resources:[{buffer:e.output,usage:"storage-read-write"},{buffer:e.offsets,usage:"storage-read"},...e.segmentPrefixes?[{buffer:e.segmentPrefixes,usage:e.offsetSegmentPrefixes?"storage-read-write":"storage-read"}]:[],...e.offsetSegmentPrefixes?[{buffer:e.offsetSegmentPrefixes,usage:"storage-read"}]:[]],compile:({device:s})=>{let a=new D(s,{id:e.id,source:o,shaderLayout:i});return{encode:({computePass:u,getBuffer:c})=>{let d={outputValues:G(e.output,c),offsets:G(e.offsets,c)};e.segmentPrefixes&&(d.segmentPrefixes=G(e.segmentPrefixes,c)),e.offsetSegmentPrefixes&&(d.offsetSegmentPrefixes=G(e.offsetSegmentPrefixes,c)),a.dispatch(u,{bindings:d,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>a.destroy()}}})),t.map(s=>N(s,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function Ao(r,e){return fe("GPUScan",r,K,e)}function Ds(r){return J(r,K)}var Tt=256,tn=class{id;input;flags;output;count;constructor(e){if(this.id=e.id??"gpu-compaction",this.input=e.input,this.flags=e.flags,this.output=e.output,this.count=e.count,Ro(this.input,`${this.id} input`),Ro(this.flags,`${this.id} flags`),Ro(this.output,`${this.id} output`),Le(this.count,`${this.id} count`),this.flags.length!==this.input.length)throw new Error(`${this.id} flags.length must equal input.length`);if(this.output.length<this.input.length)throw new Error(`${this.id} output must contain at least input.length rows`);if(this.count.length<1)throw new Error(`${this.id} count must contain one uint32 row`)}getCommandNodes(e){let t=[];return t.push(...pc(this,e,e.device.limits.maxComputeWorkgroupsPerDimension)),t}};function pc(r,e,t){let n=[];for(let a of[...wt(r.input),...wt(r.flags),...wt(r.output),r.count])if(a.buffer.graph!==e)throw new Error(`${r.id} views must belong to the target graph`);if(r.input.length===0)return n.push(...gc(e,r.id,r.count)),n;let o=r.flags instanceof O?Po(e,`${r.id}-offsets`,r.flags):z(e,`${r.id}-offsets`,"uint32",r.flags.length),i=r.flags instanceof O?Po(e,`${r.id}-flags`,r.flags):z(e,`${r.id}-flags`,"uint32",r.flags.length);for(let[a,u]of wt(r.flags).entries()){if(!u.length)continue;let c=wt(i)[a],d=fe(r.id,u.length,Tt,t);n.push(..._s(e,{id:`${r.id}-normalize-${a}`,source:`
452
453
  @group(0) @binding(0) var<storage, read> inputValues: array<u32>;
453
454
  @group(0) @binding(1) var<storage, read_write> outputValues: array<u32>;
454
455
  @compute @workgroup_size(${Tt}) fn main(
@@ -460,7 +461,7 @@ ${e.offsetSegmentPrefixes?"@group(0) @binding(3) var<storage, read> offsetSegmen
460
461
  outputValues[${P(c)}u + index] = min(inputValues[${P(u)}u + index], 1u);
461
462
  }`,resources:[{buffer:u,usage:"storage-read"},{buffer:c,usage:"storage-write"}],bindings:{inputValues:u,outputValues:c},dispatchLayout:d}))}let s=new en({id:`${r.id}-scan`,input:i,output:o});return n.push(...Fo(s,e,t)),n.push(...yc(e,r.id,r.input,r.flags,o,r.output,r.count,t)),n}function gc(r,e,t){let n=[],o=`${e}-clear-count`;return n.push(V({id:o,resources:[{buffer:t,usage:"storage-write"}],compile:({device:i})=>{let s=new D(i,{id:o,source:`const COUNT_OFFSET: u32 = ${P(t)}u;
462
463
  @group(0) @binding(0) var<storage, read_write> outputCount: array<u32>;
463
- @compute @workgroup_size(1) fn main() { outputCount[COUNT_OFFSET] = 0u; }`,shaderLayout:{bindings:[{name:"outputCount",type:"storage",group:0,location:0}]}});return{encode:({computePass:a,getBuffer:u})=>{s.dispatch(a,{bindings:{outputCount:G(t,u)},x:1})},destroy:()=>s.destroy()}}})),n.map(i=>N(i,[1,1,1]))}function yc(r,e,t,n,o,i,s,a){let u=[],c=X(r,[t,n,o]),d=c.map(T=>T[0]),l=c.map(T=>T[1]),f=c.map(T=>T[2]),h=wt(i),m=d.map((T,v)=>T.length>0?v:-1).filter(T=>T>=0),g=h.map((T,v)=>T.length>0?v:-1).filter(T=>T>=0),y=m[m.length-1],p=g[g.length-1],w=c.length>1||i instanceof O,S=0;for(let T=0;T<h.length;T++){let v=h[T],b=S+v.length;if(v.length>0)for(let C of m){let B=C===y&&T===p;u.push(...bc(r,{id:w?`${e}-scatter-input-${C}-output-${T}`:`${e}-scatter`,input:d[C],flags:l[C],offsets:f[C],output:v,outputStart:S,outputEnd:b,count:B?s:void 0,dispatchLayout:fe("GPUCompaction",d[C].length,Tt,a)}))}S=b}return u}function bc(r,e){let t=[],n=e.count?"@group(0) @binding(4) var<storage, read_write> outputCount: array<u32>;":"",o=e.count?`if (index == ELEMENT_COUNT - 1u) {
464
+ @compute @workgroup_size(1) fn main() { outputCount[COUNT_OFFSET] = 0u; }`,shaderLayout:{bindings:[{name:"outputCount",type:"storage",group:0,location:0}]}});return{encode:({computePass:a,getBuffer:u})=>{s.dispatch(a,{bindings:{outputCount:G(t,u)},x:1})},destroy:()=>s.destroy()}}})),n.map(i=>N(i,[1,1,1]))}function yc(r,e,t,n,o,i,s,a){let u=[],c=X(r,[t,n,o]),d=c.map(T=>T[0]),l=c.map(T=>T[1]),h=c.map(T=>T[2]),f=wt(i),m=d.map((T,v)=>T.length>0?v:-1).filter(T=>T>=0),p=f.map((T,v)=>T.length>0?v:-1).filter(T=>T>=0),y=m[m.length-1],g=p[p.length-1],w=c.length>1||i instanceof O,S=0;for(let T=0;T<f.length;T++){let v=f[T],b=S+v.length;if(v.length>0)for(let C of m){let B=C===y&&T===g;u.push(...bc(r,{id:w?`${e}-scatter-input-${C}-output-${T}`:`${e}-scatter`,input:d[C],flags:l[C],offsets:h[C],output:v,outputStart:S,outputEnd:b,count:B?s:void 0,dispatchLayout:fe("GPUCompaction",d[C].length,Tt,a)}))}S=b}return u}function bc(r,e){let t=[],n=e.count?"@group(0) @binding(4) var<storage, read_write> outputCount: array<u32>;":"",o=e.count?`if (index == ELEMENT_COUNT - 1u) {
464
465
  outputCount[COUNT_OFFSET] = outputIndex + flag;
465
466
  }`:"",i=`
466
467
  const ELEMENT_COUNT: u32 = ${e.input.length}u;
@@ -489,7 +490,7 @@ ${n}
489
490
  outputValues[OUTPUT_OFFSET + outputIndex - OUTPUT_START] = inputValues[INPUT_OFFSET + index];
490
491
  }
491
492
  ${o}
492
- }`;return t.push(...Ds(r,{id:e.id,source:i,resources:[{buffer:e.input,usage:"storage-read"},{buffer:e.flags,usage:"storage-read"},{buffer:e.offsets,usage:"storage-read"},{buffer:e.output,usage:"storage-write"},...e.count?[{buffer:e.count,usage:"storage-write"}]:[]],bindings:{inputValues:e.input,flags:e.flags,offsets:e.offsets,outputValues:e.output,...e.count?{outputCount:e.count}:{}},dispatchLayout:e.dispatchLayout})),t}function Ds(r,e){let t=[];return t.push(V({id:e.id,workload:{operation:"GPUCompaction",commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*Tt,readByteLength:e.resources.reduce((n,o)=>n+(o.usage==="storage-read"||o.usage==="storage-read-write"?o.buffer.length*o.buffer.rowByteLength:0),0),writeByteLength:e.resources.reduce((n,o)=>n+(o.usage==="storage-write"||o.usage==="storage-read-write"?o.buffer.length*o.buffer.rowByteLength:0),0)},resources:e.resources,compile:({device:n})=>{let o=new D(n,{id:e.id,source:e.source,shaderLayout:{bindings:Object.keys(e.bindings).map((i,s)=>({name:i,type:"storage",group:0,location:s}))}});return{encode:({computePass:i,getBuffer:s})=>{let a={};for(let[u,c]of Object.entries(e.bindings))a[u]=G(c,s);o.dispatch(i,{bindings:a,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>o.destroy()}}})),t.map(n=>N(n,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function wt(r){return r instanceof O?r.data:[r]}function Ro(r,e){for(let t of wt(r))Le(t,e)}var se=F(A(),1);var rn=class extends xt{computeLowerings=[];loweringsSuspended=0;otherLowerings=[];addRenderPass(e){let t={...e,type:"render"},n=this.otherLowerings.at(-1);n&&(t=n(t)),super.addRenderPass(t)}addCopyPass(e){let t={...e,type:"copy"},n=this.otherLowerings.at(-1);n&&(t=n(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 n=this.computeLowerings.length-1;n>=0;n--)t=this.computeLowerings[n](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 on=F(A(),1);var nn=F(A(),1);var xc=16*1024,_s=new WeakMap;function As(r){let e=r,t=_s.get(e);return t||(t=new Vo(r),_s.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",n=xc){if(this.id=t,this.graph=e,!Number.isSafeInteger(n)||n<=0||n%4!==0)throw new Error(`${this.id} capacityByteLength must be a positive multiple of 4`);this.capacityByteLength=n,this.buffer=e.createTransientBuffer({id:`${this.id}-buffer`,byteLength:n,usage:nn.Buffer.STORAGE|nn.Buffer.COPY_SRC|nn.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 n=Object.freeze({id:e,format:t,byteOffset:this.nextByteOffset});return this.nextByteOffset+=4,this.slots.set(e,n),this.views.set(e,new De(this.buffer,{format:t,length:1,byteOffset:n.byteOffset,byteStride:4,rowByteLength:4})),n}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 Mo=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 No(r,e,t){let n=As(r);return new Mo(n,n.allocate(e,t))}function Fs(r){switch(r){case"float32":return"f32";case"uint32":return"u32";case"sint32":return"i32"}}function Oe(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 dt(r,e,t="gpuValues"){let n=`${t}[${r.wordOffset}u]`;switch(r.format){case"float32":return`${n} = bitcast<u32>(${e});`;case"uint32":return`${n} = ${e};`;case"sint32":return`${n} = bitcast<u32>(${e});`}}function be(r,e,t="gpuValues"){return`@group(${r}) @binding(${e}) var<storage, read_write> ${t}: array<u32>;`}var Tr=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:on.Buffer.STORAGE|on.Buffer.INDIRECT|on.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 n=this.active.arena.buffer,[o,i,s]=this.workgroups,a=`${be(0,0)}
493
+ }`;return t.push(..._s(r,{id:e.id,source:i,resources:[{buffer:e.input,usage:"storage-read"},{buffer:e.flags,usage:"storage-read"},{buffer:e.offsets,usage:"storage-read"},{buffer:e.output,usage:"storage-write"},...e.count?[{buffer:e.count,usage:"storage-write"}]:[]],bindings:{inputValues:e.input,flags:e.flags,offsets:e.offsets,outputValues:e.output,...e.count?{outputCount:e.count}:{}},dispatchLayout:e.dispatchLayout})),t}function _s(r,e){let t=[];return t.push(V({id:e.id,workload:{operation:"GPUCompaction",commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*Tt,readByteLength:e.resources.reduce((n,o)=>n+(o.usage==="storage-read"||o.usage==="storage-read-write"?o.buffer.length*o.buffer.rowByteLength:0),0),writeByteLength:e.resources.reduce((n,o)=>n+(o.usage==="storage-write"||o.usage==="storage-read-write"?o.buffer.length*o.buffer.rowByteLength:0),0)},resources:e.resources,compile:({device:n})=>{let o=new D(n,{id:e.id,source:e.source,shaderLayout:{bindings:Object.keys(e.bindings).map((i,s)=>({name:i,type:"storage",group:0,location:s}))}});return{encode:({computePass:i,getBuffer:s})=>{let a={};for(let[u,c]of Object.entries(e.bindings))a[u]=G(c,s);o.dispatch(i,{bindings:a,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>o.destroy()}}})),t.map(n=>N(n,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function wt(r){return r instanceof O?r.data:[r]}function Ro(r,e){for(let t of wt(r))Le(t,e)}var se=F(A(),1);var rn=class extends xt{computeLowerings=[];loweringsSuspended=0;otherLowerings=[];addRenderPass(e){let t={...e,type:"render"},n=this.otherLowerings.at(-1);n&&(t=n(t)),super.addRenderPass(t)}addCopyPass(e){let t={...e,type:"copy"},n=this.otherLowerings.at(-1);n&&(t=n(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 n=this.computeLowerings.length-1;n>=0;n--)t=this.computeLowerings[n](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 on=F(A(),1);var nn=F(A(),1);var xc=16*1024,As=new WeakMap;function Fs(r){let e=r,t=As.get(e);return t||(t=new Vo(r),As.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",n=xc){if(this.id=t,this.graph=e,!Number.isSafeInteger(n)||n<=0||n%4!==0)throw new Error(`${this.id} capacityByteLength must be a positive multiple of 4`);this.capacityByteLength=n,this.buffer=e.createTransientBuffer({id:`${this.id}-buffer`,byteLength:n,usage:nn.Buffer.STORAGE|nn.Buffer.COPY_SRC|nn.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 n=Object.freeze({id:e,format:t,byteOffset:this.nextByteOffset});return this.nextByteOffset+=4,this.slots.set(e,n),this.views.set(e,new De(this.buffer,{format:t,length:1,byteOffset:n.byteOffset,byteStride:4,rowByteLength:4})),n}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 Mo=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 No(r,e,t){let n=Fs(r);return new Mo(n,n.allocate(e,t))}function Rs(r){switch(r){case"float32":return"f32";case"uint32":return"u32";case"sint32":return"i32"}}function Oe(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 dt(r,e,t="gpuValues"){let n=`${t}[${r.wordOffset}u]`;switch(r.format){case"float32":return`${n} = bitcast<u32>(${e});`;case"uint32":return`${n} = ${e};`;case"sint32":return`${n} = bitcast<u32>(${e});`}}function be(r,e,t="gpuValues"){return`@group(${r}) @binding(${e}) var<storage, read_write> ${t}: array<u32>;`}var Tr=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:on.Buffer.STORAGE|on.Buffer.INDIRECT|on.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 n=this.active.arena.buffer,[o,i,s]=this.workgroups,a=`${be(0,0)}
493
494
  @group(0) @binding(1) var<storage, read_write> dispatch: array<u32>;
494
495
  @compute @workgroup_size(1)
495
496
  fn main() {
@@ -497,7 +498,7 @@ fn main() {
497
498
  dispatch[0] = select(0u, ${o}u, enabled);
498
499
  dispatch[1] = ${i}u;
499
500
  dispatch[2] = ${s}u;
500
- }`;return[V({id:t,workload:{operation:"GPUScalarDispatchGate",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:4,writeByteLength:12},resources:[{buffer:n,usage:"storage-read"},{buffer:this.dispatchBuffer,usage:"storage-write"}],compile:({device:u})=>{let c=new D(u,{id:t,source:a,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:l})=>{let f={gpuValues:l(n),dispatch:l(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 sn(r,e,t){return e.flatMap(n=>{let o=Qr(n);if(n.type!=="compute"||n.condition||!o)throw new Error("Gated primitives must expose unconditional compute nodes with exact dispatch geometry");let i=new Tr(r,{id:`${n.id}-gate`,active:t,workgroups:o});return[...i.getUpdateCommandNodes(r).map(s=>N(s,[1,1,1])),{...n,condition:i.condition}]})}var an=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,wc(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 n=t.buffer,o=Tc(this);return[N(V({id:this.id,workload:{operation:"GPUScalarCompute",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:this.right?8:4,writeByteLength:4},resources:[{buffer:n,usage:"storage-write"}],compile:({device:i})=>{let s=new D(i,{id:this.id,source:o,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:a,getBuffer:u})=>{let c={gpuValues:u(n)};s.dispatch(a,{bindings:c,x:1,y:1,z:1})},destroy:()=>s.destroy()}}}),[1,1,1])]}};function wc(r){let e=r.operation==="copy"||r.operation==="sqrt",t=Sc(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 Tc(r){let e=Oe(r.left),t=r.right?Oe(r.right):void 0,n=vc(r.operation,e,t);return`${be(0,0)}
501
+ }`;return[V({id:t,workload:{operation:"GPUScalarDispatchGate",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:4,writeByteLength:12},resources:[{buffer:n,usage:"storage-read"},{buffer:this.dispatchBuffer,usage:"storage-write"}],compile:({device:u})=>{let c=new D(u,{id:t,source:a,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:l})=>{let h={gpuValues:l(n),dispatch:l(this.dispatchBuffer)};c.dispatch(d,{bindings:h,x:1,y:1,z:1})},destroy:()=>c.destroy()}}})]}get condition(){return{id:`${this.id}-active`,source:"gpu",mode:"indirect",buffer:this.dispatchBuffer}}};function sn(r,e,t){return e.flatMap(n=>{let o=Qr(n);if(n.type!=="compute"||n.condition||!o)throw new Error("Gated primitives must expose unconditional compute nodes with exact dispatch geometry");let i=new Tr(r,{id:`${n.id}-gate`,active:t,workgroups:o});return[...i.getUpdateCommandNodes(r).map(s=>N(s,[1,1,1])),{...n,condition:i.condition}]})}var an=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,wc(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 n=t.buffer,o=Tc(this);return[N(V({id:this.id,workload:{operation:"GPUScalarCompute",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:this.right?8:4,writeByteLength:4},resources:[{buffer:n,usage:"storage-write"}],compile:({device:i})=>{let s=new D(i,{id:this.id,source:o,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:a,getBuffer:u})=>{let c={gpuValues:u(n)};s.dispatch(a,{bindings:c,x:1,y:1,z:1})},destroy:()=>s.destroy()}}}),[1,1,1])]}};function wc(r){let e=r.operation==="copy"||r.operation==="sqrt",t=Sc(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 Tc(r){let e=Oe(r.left),t=r.right?Oe(r.right):void 0,n=vc(r.operation,e,t);return`${be(0,0)}
501
502
  @compute @workgroup_size(1) fn main(){${dt(r.output,n)}}`}function vc(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 Sc(r){return["equal","not-equal","less-than","less-than-or-equal","greater-than","greater-than-or-equal"].includes(r)}var Vt=class{props;id;constructor(e){this.props=e,this.id=e.id??`${e.output.id}-literal`}getCommandNodes(e){let{output:t,value:n}=this.props;if(t.arena.graph!==e)throw new Error(`${this.id} output must belong to target graph`);let o=t.format==="float32"?`f32(${n})`:t.format==="uint32"?`${n}u`:`${n}i`,i=`
502
503
  ${be(0,0)}
503
504
 
@@ -505,7 +506,7 @@ ${be(0,0)}
505
506
  fn main() {
506
507
  ${dt(t,o)}
507
508
  }
508
- `,s=t.arena.buffer;return[N(V({id:this.id,workload:{operation:"GPUScalarLiteral",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:0,writeByteLength:4},resources:[{buffer:s,usage:"storage-write"}],compile:({device:a})=>{let u=new D(a,{id:this.id,source:i,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:c,getBuffer:d})=>{let l={gpuValues:d(s)};u.dispatch(c,{bindings:l,x:1,y:1,z:1})},destroy:()=>u.destroy()}}}),[1,1,1])]}};var un=256,cn=class r{props;id;constructor(e){this.props=e,this.id=e.id??"gpu-vector-scalar-madd";for(let[t,n]of Object.entries({input:e.input,addend:e.addend,output:e.output}))for(let o of Y(n))ge(o,["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:n,addend:o,output:i,gate:s}=this.props;if(t instanceof O||o instanceof O||i instanceof O)return X(e,[t,o,i]).flatMap(([h,m,g],y)=>new r({id:`${this.id}-chunk-${y}`,input:h,addend:m,output:g,scale:n,gate:s}).getCommandNodes(e));if([t,o,i].some(h=>h.buffer.graph!==e)||n.arena.graph!==e)throw new Error(`${this.id} resources must belong to target graph`);if(i.length===0)return[];let a=n.arena.buffer,u=fe("GPUVectorScalarMADD",i.length,un,e.device.limits.maxComputeWorkgroupsPerDimension),c=t===i?"outputValues":"inputValues",d=o===i?"outputValues":"addendValues",l=`
509
+ `,s=t.arena.buffer;return[N(V({id:this.id,workload:{operation:"GPUScalarLiteral",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:0,writeByteLength:4},resources:[{buffer:s,usage:"storage-write"}],compile:({device:a})=>{let u=new D(a,{id:this.id,source:i,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:c,getBuffer:d})=>{let l={gpuValues:d(s)};u.dispatch(c,{bindings:l,x:1,y:1,z:1})},destroy:()=>u.destroy()}}}),[1,1,1])]}};var un=256,cn=class r{props;id;constructor(e){this.props=e,this.id=e.id??"gpu-vector-scalar-madd";for(let[t,n]of Object.entries({input:e.input,addend:e.addend,output:e.output}))for(let o of Y(n))ge(o,["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:n,addend:o,output:i,gate:s}=this.props;if(t instanceof O||o instanceof O||i instanceof O)return X(e,[t,o,i]).flatMap(([f,m,p],y)=>new r({id:`${this.id}-chunk-${y}`,input:f,addend:m,output:p,scale:n,gate:s}).getCommandNodes(e));if([t,o,i].some(f=>f.buffer.graph!==e)||n.arena.graph!==e)throw new Error(`${this.id} resources must belong to target graph`);if(i.length===0)return[];let a=n.arena.buffer,u=fe("GPUVectorScalarMADD",i.length,un,e.device.limits.maxComputeWorkgroupsPerDimension),c=t===i?"outputValues":"inputValues",d=o===i?"outputValues":"addendValues",l=`
509
510
  const LENGTH: u32 = ${i.length}u;
510
511
  const I: u32 = ${P(t)}u;
511
512
  const A: u32 = ${P(o)}u;
@@ -530,7 +531,7 @@ fn main(
530
531
  let y = ${d}[A + index];
531
532
  outputValues[O + index] = ${Oe(n)} * x + y;
532
533
  }
533
- `,f=[N(V({id:this.id,workload:{operation:"GPUVectorScalarMADD",commandCount:1,maximumWorkgroupCount:u.x*u.y*u.z,maximumInvocationCount:u.x*u.y*u.z*un,readByteLength:t.length*8+4,writeByteLength:i.length*4},resources:[...t===i?[]:[{buffer:t,usage:"storage-read"}],...o===i?[]:[{buffer:o,usage:"storage-read"}],{buffer:i,usage:t===i||o===i?"storage-read-write":"storage-write"},{buffer:a,usage:"storage-read"}],compile:({device:h})=>{let m=new D(h,{id:this.id,source:l,shaderLayout:{bindings:[...t===i?[]:[{name:"inputValues",type:"read-only-storage",group:0,location:0}],...o===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:g,getBuffer:y})=>{let p={...t===i?{}:{inputValues:G(t,y)},...o===i?{}:{addendValues:G(o,y)},outputValues:G(i,y),gpuValues:y(a)};m.dispatch(g,{bindings:p,x:u.x,y:u.y,z:u.z})},destroy:()=>m.destroy()}}}),[u.x,u.y,u.z])];return s?sn(e,f,s.active):f}};function zo(r,e,t,n){if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n)||t<0||n<0||t+n>e.length)throw new Error("Graph range must fit the source");let o=[],i=e instanceof O?e.chunks:[{offset:0,length:e.length,data:e}],s=0,a=i.length;for(;s<a;){let u=Math.floor((s+a)/2);i[u].offset+i[u].length<=t?s=u+1:a=u}for(let u=s;u<i.length&&i[u].offset<t+n;u++){let{data:c,offset:d}=i[u],l=Math.max(t,d),f=Math.min(t+n,d+c.length);l<f&&o.push(l===d&&f===d+c.length?c:r.createDataView(c.buffer,{format:c.format,length:f-l,byteOffset:c.byteOffset+(l-d)*c.byteStride,byteStride:c.byteStride,rowByteLength:c.rowByteLength}))}return new O({id:`graph-range-${t}-${n}`,name:`graph-range-${t}-${n}`,stride:e instanceof O?e.stride:U(e.format).components*(U(e.format).listSize??1),format:e.format,length:n,valueLength:n*(U(e.format).listSize??1),byteStride:e.byteStride,rowByteLength:e.rowByteLength,data:o})}function Rs(r,e,t){if([...e,...t].some(a=>a.length>4294967295))throw new Error("Logical lengths must fit uint32 addressing");let n=e.flatMap(Y),o=t.flatMap(Y);for(let a of[...n,...o])if(a.buffer.graph!==r)throw new Error("Views must belong to the target graph");let i=new Set(n.map(a=>a.buffer)),s=new Map;for(let a of o){if(i.has(a.buffer))throw new Error("Outputs must use separate buffers from inputs");if(!a.length)continue;let u=s.get(a.buffer)??[];u.push(a),s.set(a.buffer,u)}for(let a of s.values()){a.sort((c,d)=>c.byteOffset-d.byteOffset);let u=0;for(let c of a){if(c.byteOffset<u)throw new Error("Writable chunks must not overlap");u=c.byteOffset+(c.length-1)*c.byteStride+c.rowByteLength}}}function Mt(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),n=Math.min(Math.ceil(r/t),e),o=Math.ceil(r/t/n);if(o>e)throw new Error("Chunk operation exceeds the 3D dispatch limit");return{x:t,y:n,z:o}}function dn(r,e){let t=[...Object.entries(e.inputs??{}),...Object.entries(e.outputs)];for(let[,o]of t)if(mr(o).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let n=e.dispatch.x*e.dispatch.y*e.dispatch.z;return N(V({id:e.id,workload:{commandCount:1,maximumWorkgroupCount:n,maximumInvocationCount:n*(e.workgroupSize??256)},resources:[...Object.values(e.inputs??{}).map(o=>({buffer:o,usage:"storage-read"})),...Object.values(e.outputs).map(o=>({buffer:o,usage:"storage-read-write"}))],compile:({device:o})=>{let i=new D(o,{id:e.id,source:e.source,shaderLayout:{bindings:t.map(([s],a)=>({name:s,group:0,location:a,type:a<Object.keys(e.inputs??{}).length?"read-only-storage":"storage"}))}});return{encode:({computePass:s,getBuffer:a})=>{let u={};for(let[c,d]of t)u[c]=G(d,a);i.dispatch(s,{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 vt=256;function Ec(r){if(!Number.isSafeInteger(r)||r<1)throw new Error("reduction length must be positive");let e=[];do r=Math.ceil(r/vt),e.push(r);while(r>1);return e}function Vs(r,e){let t=[],n=e.input,o=e.inputB===n?void 0:e.inputB,i=e.inputB===n;for(let[s,a]of Ec(n.length).entries()){let u=a>1?z(r,`${e.id}-partials-${s}`,"float32",a):void 0;t.push(Pc(r,{id:`${e.id}-level-${s}`,input:n,inputB:o,square:i,output:u,finalScalar:u?void 0:e.output,accumulate:e.accumulate})),u&&(n=u),o=void 0,i=!1}return t}function Pc(r,e){let t=e.output?.length??1,n=Mt(t,r.device.limits.maxComputeWorkgroupsPerDimension),o=e.finalScalar?.arena.buffer,i=e.inputB?2:1,s=Be(r.device,{requiresSubgroupId:!0})==="subgroups",a=Cc(e,n,s);return N(V({id:e.id,workload:{operation:"GPUDotProductScalar",commandCount:1,maximumWorkgroupCount:n.x*n.y*n.z,maximumInvocationCount:n.x*n.y*n.z*vt,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"}]:[],...o?[{buffer:o,usage:"storage-read-write"}]:[]],compile:({device:u})=>{let c=new D(u,{id:e.id,source:a,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:l})=>{let f={inputValues:G(e.input,l)};e.inputB&&(f.inputBValues=G(e.inputB,l)),e.output&&(f.outputValues=G(e.output,l)),o&&(f.gpuValues=l(o)),c.dispatch(d,{bindings:f,...n})},destroy:()=>c.destroy()}}}),[n.x,n.y,n.z])}function Cc(r,e,t){let n=r.inputB?2:1,o=`inputValues[${P(r.input)}u + index]`,i=r.inputB?`${o} * inputBValues[${P(r.inputB)}u + index]`:r.square?`${o} * ${o}`:o,s=r.output?`outputValues[${P(r.output)}u + groupIndex] = total;`:dt(r.finalScalar,r.accumulate?`${Oe(r.finalScalar)} + total`:"total");return`${t?`enable subgroups;
534
+ `,h=[N(V({id:this.id,workload:{operation:"GPUVectorScalarMADD",commandCount:1,maximumWorkgroupCount:u.x*u.y*u.z,maximumInvocationCount:u.x*u.y*u.z*un,readByteLength:t.length*8+4,writeByteLength:i.length*4},resources:[...t===i?[]:[{buffer:t,usage:"storage-read"}],...o===i?[]:[{buffer:o,usage:"storage-read"}],{buffer:i,usage:t===i||o===i?"storage-read-write":"storage-write"},{buffer:a,usage:"storage-read"}],compile:({device:f})=>{let m=new D(f,{id:this.id,source:l,shaderLayout:{bindings:[...t===i?[]:[{name:"inputValues",type:"read-only-storage",group:0,location:0}],...o===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:p,getBuffer:y})=>{let g={...t===i?{}:{inputValues:G(t,y)},...o===i?{}:{addendValues:G(o,y)},outputValues:G(i,y),gpuValues:y(a)};m.dispatch(p,{bindings:g,x:u.x,y:u.y,z:u.z})},destroy:()=>m.destroy()}}}),[u.x,u.y,u.z])];return s?sn(e,h,s.active):h}};function zo(r,e,t,n){if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n)||t<0||n<0||t+n>e.length)throw new Error("Graph range must fit the source");let o=[],i=e instanceof O?e.chunks:[{offset:0,length:e.length,data:e}],s=0,a=i.length;for(;s<a;){let u=Math.floor((s+a)/2);i[u].offset+i[u].length<=t?s=u+1:a=u}for(let u=s;u<i.length&&i[u].offset<t+n;u++){let{data:c,offset:d}=i[u],l=Math.max(t,d),h=Math.min(t+n,d+c.length);l<h&&o.push(l===d&&h===d+c.length?c:r.createDataView(c.buffer,{format:c.format,length:h-l,byteOffset:c.byteOffset+(l-d)*c.byteStride,byteStride:c.byteStride,rowByteLength:c.rowByteLength}))}return new O({id:`graph-range-${t}-${n}`,name:`graph-range-${t}-${n}`,stride:e instanceof O?e.stride:U(e.format).components*(U(e.format).listSize??1),format:e.format,length:n,valueLength:n*(U(e.format).listSize??1),byteStride:e.byteStride,rowByteLength:e.rowByteLength,data:o})}function Vs(r,e,t){if([...e,...t].some(a=>a.length>4294967295))throw new Error("Logical lengths must fit uint32 addressing");let n=e.flatMap(Y),o=t.flatMap(Y);for(let a of[...n,...o])if(a.buffer.graph!==r)throw new Error("Views must belong to the target graph");let i=new Set(n.map(a=>a.buffer)),s=new Map;for(let a of o){if(i.has(a.buffer))throw new Error("Outputs must use separate buffers from inputs");if(!a.length)continue;let u=s.get(a.buffer)??[];u.push(a),s.set(a.buffer,u)}for(let a of s.values()){a.sort((c,d)=>c.byteOffset-d.byteOffset);let u=0;for(let c of a){if(c.byteOffset<u)throw new Error("Writable chunks must not overlap");u=c.byteOffset+(c.length-1)*c.byteStride+c.rowByteLength}}}function Mt(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),n=Math.min(Math.ceil(r/t),e),o=Math.ceil(r/t/n);if(o>e)throw new Error("Chunk operation exceeds the 3D dispatch limit");return{x:t,y:n,z:o}}function dn(r,e){let t=[...Object.entries(e.inputs??{}),...Object.entries(e.outputs)];for(let[,o]of t)if(mr(o).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let n=e.dispatch.x*e.dispatch.y*e.dispatch.z;return N(V({id:e.id,workload:{commandCount:1,maximumWorkgroupCount:n,maximumInvocationCount:n*(e.workgroupSize??256)},resources:[...Object.values(e.inputs??{}).map(o=>({buffer:o,usage:"storage-read"})),...Object.values(e.outputs).map(o=>({buffer:o,usage:"storage-read-write"}))],compile:({device:o})=>{let i=new D(o,{id:e.id,source:e.source,shaderLayout:{bindings:t.map(([s],a)=>({name:s,group:0,location:a,type:a<Object.keys(e.inputs??{}).length?"read-only-storage":"storage"}))}});return{encode:({computePass:s,getBuffer:a})=>{let u={};for(let[c,d]of t)u[c]=G(d,a);i.dispatch(s,{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 vt=256;function Ec(r){if(!Number.isSafeInteger(r)||r<1)throw new Error("reduction length must be positive");let e=[];do r=Math.ceil(r/vt),e.push(r);while(r>1);return e}function Ms(r,e){let t=[],n=e.input,o=e.inputB===n?void 0:e.inputB,i=e.inputB===n;for(let[s,a]of Ec(n.length).entries()){let u=a>1?z(r,`${e.id}-partials-${s}`,"float32",a):void 0;t.push(Pc(r,{id:`${e.id}-level-${s}`,input:n,inputB:o,square:i,output:u,finalScalar:u?void 0:e.output,accumulate:e.accumulate})),u&&(n=u),o=void 0,i=!1}return t}function Pc(r,e){let t=e.output?.length??1,n=Mt(t,r.device.limits.maxComputeWorkgroupsPerDimension),o=e.finalScalar?.arena.buffer,i=e.inputB?2:1,s=Be(r.device,{requiresSubgroupId:!0})==="subgroups",a=Cc(e,n,s);return N(V({id:e.id,workload:{operation:"GPUDotProductScalar",commandCount:1,maximumWorkgroupCount:n.x*n.y*n.z,maximumInvocationCount:n.x*n.y*n.z*vt,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"}]:[],...o?[{buffer:o,usage:"storage-read-write"}]:[]],compile:({device:u})=>{let c=new D(u,{id:e.id,source:a,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:l})=>{let h={inputValues:G(e.input,l)};e.inputB&&(h.inputBValues=G(e.inputB,l)),e.output&&(h.outputValues=G(e.output,l)),o&&(h.gpuValues=l(o)),c.dispatch(d,{bindings:h,...n})},destroy:()=>c.destroy()}}}),[n.x,n.y,n.z])}function Cc(r,e,t){let n=r.inputB?2:1,o=`inputValues[${P(r.input)}u + index]`,i=r.inputB?`${o} * inputBValues[${P(r.inputB)}u + index]`:r.square?`${o} * ${o}`:o,s=r.output?`outputValues[${P(r.output)}u + groupIndex] = total;`:dt(r.finalScalar,r.accumulate?`${Oe(r.finalScalar)} + total`:"total");return`${t?`enable subgroups;
534
535
  requires subgroup_id;
535
536
  `:""}
536
537
  @group(0) @binding(0) var<storage, read> inputValues: array<f32>;
@@ -574,7 +575,7 @@ fn reduceValue(value: f32, lane: u32, subgroupInvocationId: u32, subgroupSize: u
574
575
  workgroupBarrier();
575
576
  }
576
577
  return subgroupTotals[0];
577
- }`;var ln=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 n of Y(t))ge(n,["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:n,output:o,gate:i}=this.props;if(o.arena.graph!==e||i&&i.active.arena.graph!==e||[t,n].flatMap(Y).some(u=>u.buffer.graph!==e))throw new Error(`${this.id} resources must belong to target graph`);let s=[],a=0;for(let u of X(e,[t,n]))for(let c=0;c<u[0].length;){let d=Math.min(u[0].length-c,...u.map(h=>Math.floor((e.device.limits.maxStorageBufferBindingSize-(h.byteOffset+c*4)%256)/4)));if(d<1)throw new Error("Dot product span must fit a storage binding");let l=e.createDataView(u[0].buffer,{format:"float32",byteOffset:u[0].byteOffset+c*4,length:d}),f=u[1]===u[0]?l:e.createDataView(u[1].buffer,{format:"float32",byteOffset:u[1].byteOffset+c*4,length:d});s.push(...Vs(e,{id:`${this.id}-chunk-${a}`,input:l,inputB:f,output:o,accumulate:a>0})),a++,c+=d}return a||s.push(...new Vt({id:this.id,output:o,value:0}).getCommandNodes(e)),i?sn(e,s,i.active):s}};var fn=256,Nt=Uint32Array.BYTES_PER_ELEMENT,hn=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 n of Y(this.indices))Le(n,`${this.id} indices`);for(let n of[this.source,this.output])for(let o of Y(n))$c(o,this.id,n===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([...Y(this.source).map(n=>n.buffer),...Y(this.indices).map(n=>n.buffer)]);if(Y(this.output).some(n=>t.has(n.buffer)))throw new Error(`${this.id} output must use a separate buffer`);this.wordsPerRow=U(this.source.format).byteLength/Nt}getCommandNodes(e){return Oc(e,this)}};function Oc(r,e,t=0,n="GPUGather"){let o=[];for(let c of[e.source,e.indices,e.output])for(let d of Y(c))if(d.buffer.graph!==r)throw new Error(`${e.id} views must belong to the target graph`);if(e.indices.length===0)return o;let i=xs(r,e.output,e.indices.length),s=X(r,[e.indices,i]),a=ze(Y(e.source)).filter(c=>c.length),u=a.length?a:[void 0];for(let[c,[d,l]]of s.entries()){let f=fe(n,d.length,fn,r.device.limits.maxComputeWorkgroupsPerDimension);for(let[h,m]of u.entries()){let g=m?.data;for(let w of[l,...g?[g,d]:[]])if(mr(w).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let y=s.length===1&&u.length===1?e.id:`${e.id}-span-${c}-source-${h}`,p=kc({source:g,sourceOffset:m?.offset??0,indices:d,output:l,wordsPerRow:e.wordsPerRow,initialize:h===0,invalidValue:t,dispatchLayout:f});o.push(N(V({id:y,workload:{operation:n,commandCount:1,maximumWorkgroupCount:f.x*f.y*f.z,maximumInvocationCount:f.x*f.y*f.z*fn,readByteLength:g?d.length*(Nt+g.rowByteLength):0,writeByteLength:d.length*l.rowByteLength},resources:[...g?[{buffer:g,usage:"storage-read"},{buffer:d,usage:"storage-read"}]:[],{buffer:l,usage:"storage-write"}],compile:({device:w})=>{let S=new D(w,{id:y,source:p,shaderLayout:{bindings:[{name:"outputWords",type:"storage",group:0,location:0},...g?[{name:"sourceWords",type:"read-only-storage",group:0,location:1},{name:"indices",type:"read-only-storage",group:0,location:2}]:[]]}});return{encode:({computePass:T,getBuffer:v})=>{let b={outputWords:G(l,v)};g&&(b.sourceWords=G(g,v),b.indices=G(d,v)),S.dispatch(T,{bindings:b,x:f.x,y:f.y,z:f.z})},destroy:()=>S.destroy()}}}),[f.x,f.y,f.z]))}}return o}function $c(r,e,t){if(it(r.format)||st(r.format))throw new Error(`${e} must use a fixed-width GPU data format`);let n=U(r.format);if((t?r.byteStride!==n.byteLength:r.byteStride<n.byteLength||r.byteStride%Nt!==0)||r.rowByteLength!==n.byteLength||r.byteOffset%Nt!==0||r.rowByteLength%Nt!==0)throw new Error(`${e} must be packed, uint32-aligned GPU data with 32-bit-word rows`)}function kc(r){let{source:e,indices:t,output:n,wordsPerRow:o,initialize:i,invalidValue:s,dispatchLayout:a}=r;return`const INDEX_COUNT: u32 = ${t.length}u;
578
+ }`;var ln=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 n of Y(t))ge(n,["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:n,output:o,gate:i}=this.props;if(o.arena.graph!==e||i&&i.active.arena.graph!==e||[t,n].flatMap(Y).some(u=>u.buffer.graph!==e))throw new Error(`${this.id} resources must belong to target graph`);let s=[],a=0;for(let u of X(e,[t,n]))for(let c=0;c<u[0].length;){let d=Math.min(u[0].length-c,...u.map(f=>Math.floor((e.device.limits.maxStorageBufferBindingSize-(f.byteOffset+c*4)%256)/4)));if(d<1)throw new Error("Dot product span must fit a storage binding");let l=e.createDataView(u[0].buffer,{format:"float32",byteOffset:u[0].byteOffset+c*4,length:d}),h=u[1]===u[0]?l:e.createDataView(u[1].buffer,{format:"float32",byteOffset:u[1].byteOffset+c*4,length:d});s.push(...Ms(e,{id:`${this.id}-chunk-${a}`,input:l,inputB:h,output:o,accumulate:a>0})),a++,c+=d}return a||s.push(...new Vt({id:this.id,output:o,value:0}).getCommandNodes(e)),i?sn(e,s,i.active):s}};var fn=256,Nt=Uint32Array.BYTES_PER_ELEMENT,hn=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 n of Y(this.indices))Le(n,`${this.id} indices`);for(let n of[this.source,this.output])for(let o of Y(n))$c(o,this.id,n===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([...Y(this.source).map(n=>n.buffer),...Y(this.indices).map(n=>n.buffer)]);if(Y(this.output).some(n=>t.has(n.buffer)))throw new Error(`${this.id} output must use a separate buffer`);this.wordsPerRow=U(this.source.format).byteLength/Nt}getCommandNodes(e){return Oc(e,this)}};function Oc(r,e,t=0,n="GPUGather"){let o=[];for(let c of[e.source,e.indices,e.output])for(let d of Y(c))if(d.buffer.graph!==r)throw new Error(`${e.id} views must belong to the target graph`);if(e.indices.length===0)return o;let i=ws(r,e.output,e.indices.length),s=X(r,[e.indices,i]),a=ze(Y(e.source)).filter(c=>c.length),u=a.length?a:[void 0];for(let[c,[d,l]]of s.entries()){let h=fe(n,d.length,fn,r.device.limits.maxComputeWorkgroupsPerDimension);for(let[f,m]of u.entries()){let p=m?.data;for(let w of[l,...p?[p,d]:[]])if(mr(w).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let y=s.length===1&&u.length===1?e.id:`${e.id}-span-${c}-source-${f}`,g=kc({source:p,sourceOffset:m?.offset??0,indices:d,output:l,wordsPerRow:e.wordsPerRow,initialize:f===0,invalidValue:t,dispatchLayout:h});o.push(N(V({id:y,workload:{operation:n,commandCount:1,maximumWorkgroupCount:h.x*h.y*h.z,maximumInvocationCount:h.x*h.y*h.z*fn,readByteLength:p?d.length*(Nt+p.rowByteLength):0,writeByteLength:d.length*l.rowByteLength},resources:[...p?[{buffer:p,usage:"storage-read"},{buffer:d,usage:"storage-read"}]:[],{buffer:l,usage:"storage-write"}],compile:({device:w})=>{let S=new D(w,{id:y,source:g,shaderLayout:{bindings:[{name:"outputWords",type:"storage",group:0,location:0},...p?[{name:"sourceWords",type:"read-only-storage",group:0,location:1},{name:"indices",type:"read-only-storage",group:0,location:2}]:[]]}});return{encode:({computePass:T,getBuffer:v})=>{let b={outputWords:G(l,v)};p&&(b.sourceWords=G(p,v),b.indices=G(d,v)),S.dispatch(T,{bindings:b,x:h.x,y:h.y,z:h.z})},destroy:()=>S.destroy()}}}),[h.x,h.y,h.z]))}}return o}function $c(r,e,t){if(it(r.format)||st(r.format))throw new Error(`${e} must use a fixed-width GPU data format`);let n=U(r.format);if((t?r.byteStride!==n.byteLength:r.byteStride<n.byteLength||r.byteStride%Nt!==0)||r.rowByteLength!==n.byteLength||r.byteOffset%Nt!==0||r.rowByteLength%Nt!==0)throw new Error(`${e} must be packed, uint32-aligned GPU data with 32-bit-word rows`)}function kc(r){let{source:e,indices:t,output:n,wordsPerRow:o,initialize:i,invalidValue:s,dispatchLayout:a}=r;return`const INDEX_COUNT: u32 = ${t.length}u;
578
579
  const WORDS_PER_ROW: u32 = ${o}u;
579
580
  const OUTPUT_OFFSET: u32 = ${P(n)}u;
580
581
  @group(0) @binding(0) var<storage, read_write> outputWords: array<u32>;
@@ -609,19 +610,19 @@ ${i?`
609
610
  outputWords[outputBase + word] = ${s}u;
610
611
  }
611
612
  `:""}
612
- }`}function Ns(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(s=>s.id===r.preferredId);if(!i)throw new Error(`preferred GPU strategy "${r.preferredId}" is not supported`);return Ms(i,e)}let n=t[0],o=n.score(e);for(let i=1;i<t.length;i++){let s=t[i],a=s.score(e);a>o&&(n=s,o=a)}return Ms(n,e,o)}function Ms(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 zs(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 n=e.nonZeros/Math.max(1,e.rows),o=e.statistics?.maxNonZerosPerRow,i=e.statistics?.shortRowFraction,s=Be(r,{requiresSubgroupId:!0})==="subgroups";return Ns({device:r,workload:e,preferredId:t,candidates:[{id:"scalar-row",score:()=>n<=8?100:n<=16?60:10,reason:()=>`average row length ${n.toFixed(1)} favors one invocation per row`,createDetails:()=>({rowsPerWorkgroup:64,workgroupSize:64,workgroupsPerLongRow:1})},{id:"subgroup-row",isSupported:()=>s,score:()=>n<=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:()=>n>32&&(o===void 0||o<=2048)?100:50,reason:()=>`average row length ${n.toFixed(1)} favors cooperative row reduction`,createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:1})},{id:"long-row",score:()=>o!==void 0&&o>2048||n>1024?140:0,reason:()=>"very long rows favor multi-workgroup partial reduction",createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:4})}]})}var mn=class{id;props;constructor(e){this.id=e.id??"gpu-adaptive-spmv",this.props=e;for(let[t,n]of Object.entries({rowOffsets:e.rowOffsets,columnIndices:e.columnIndices,values:e.values,vector:e.vector,output:e.output})){for(let o of Y(n))ge(o,[t==="rowOffsets"||t==="columnIndices"?"uint32":"float32"],`${this.id} ${t}`);if(n.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 zs(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:n,values:o,vector:i,output:s}=this.props;if(Rs(e,[t,n,o,i],[s]),!s.length)return[];let a=[],u=this.getStrategy(e),c=u.id,d=u.details.workgroupSize,l=c==="long-row"?u.details.workgroupsPerLongRow:1,f=X(e,[zo(e,t,0,s.length),zo(e,t,1,s.length),s]),h=X(e,[n,o]),m=ze(Y(i)).filter(b=>b.length),g=e.device.limits.maxComputeWorkgroupsPerDimension,y=Math.min(4096,Math.floor(e.device.limits.maxStorageBufferBindingSize/(l*4)));if(y<1)throw new Error("SpMV count scratch must fit a storage binding");let p=[];for(let b of f)for(let C=0;C<b[0].length;C+=y){let B=Math.min(y,b[0].length-C);p.push(b.map(E=>e.createDataView(E.buffer,{format:E.format,length:B,byteOffset:E.byteOffset+C*4})))}let w=p.map(([b],C)=>c==="long-row"?z(e,`${this.id}-rows-${C}-partials`,"float32",b.length*l):void 0),S=m.length>1&&p.length*m.length>m.length+p.length,T=0,v=[];for(let[b,[C,B]]of h.entries()){let E;if(S){E=z(e,`${this.id}-gather-${b}`,"float32",C.length);let _=new hn({id:`${this.id}-gather-${b}`,source:i,indices:C,output:E}).getCommandNodes(e);for(let[W,j]of _.entries())a.push(W===0?{...j,dependsOn:[...j.dependsOn??[],...v]}:j)}let $=E?[{data:E,offset:0}]:m,L=[];for(let[_,[W,j,le]]of p.entries()){let ne=W.length,Ze=w[_];for(let[Qe,ht]of $.entries()){let ri=b===0&&Qe===0,ni=`${this.id}-rows-${_}-nonzeros-${b}-vector-${Qe}-${c}`,ca=c==="scalar-row"?Math.ceil(ne/d):ne*l,oi=Mt(ca,g),ii=Ze??le;if(a.push(dn(e,{id:ni,source:Ic({strategy:c,workgroupSize:d,parts:l,length:ne,begins:W,ends:j,indices:C,matrixValues:B,vector:ht.data,output:ii,nonzeroStart:T,vectorStart:ht.offset,initialize:ri,dispatch:oi,gathered:!!E,columns:this.props.columns}),inputs:{rowBegins:W,rowEnds:j,columnIndices:C,matrixValues:B,vectorValues:ht.data},outputs:{[Ze?"rowPartials":"outputValues"]:ii},dispatch:oi,workgroupSize:d})),Ze){let si=Mt(Math.ceil(ne/64),g);a.push(dn(e,{id:`${ni}-finalize`,inputs:{rowPartials:Ze},outputs:{outputValues:le},dispatch:si,workgroupSize:64,source:`
613
+ }`}function zs(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(s=>s.id===r.preferredId);if(!i)throw new Error(`preferred GPU strategy "${r.preferredId}" is not supported`);return Ns(i,e)}let n=t[0],o=n.score(e);for(let i=1;i<t.length;i++){let s=t[i],a=s.score(e);a>o&&(n=s,o=a)}return Ns(n,e,o)}function Ns(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 js(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 n=e.nonZeros/Math.max(1,e.rows),o=e.statistics?.maxNonZerosPerRow,i=e.statistics?.shortRowFraction,s=Be(r,{requiresSubgroupId:!0})==="subgroups";return zs({device:r,workload:e,preferredId:t,candidates:[{id:"scalar-row",score:()=>n<=8?100:n<=16?60:10,reason:()=>`average row length ${n.toFixed(1)} favors one invocation per row`,createDetails:()=>({rowsPerWorkgroup:64,workgroupSize:64,workgroupsPerLongRow:1})},{id:"subgroup-row",isSupported:()=>s,score:()=>n<=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:()=>n>32&&(o===void 0||o<=2048)?100:50,reason:()=>`average row length ${n.toFixed(1)} favors cooperative row reduction`,createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:1})},{id:"long-row",score:()=>o!==void 0&&o>2048||n>1024?140:0,reason:()=>"very long rows favor multi-workgroup partial reduction",createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:4})}]})}var mn=class{id;props;constructor(e){this.id=e.id??"gpu-adaptive-spmv",this.props=e;for(let[t,n]of Object.entries({rowOffsets:e.rowOffsets,columnIndices:e.columnIndices,values:e.values,vector:e.vector,output:e.output})){for(let o of Y(n))ge(o,[t==="rowOffsets"||t==="columnIndices"?"uint32":"float32"],`${this.id} ${t}`);if(n.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 js(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:n,values:o,vector:i,output:s}=this.props;if(Vs(e,[t,n,o,i],[s]),!s.length)return[];let a=[],u=this.getStrategy(e),c=u.id,d=u.details.workgroupSize,l=c==="long-row"?u.details.workgroupsPerLongRow:1,h=X(e,[zo(e,t,0,s.length),zo(e,t,1,s.length),s]),f=X(e,[n,o]),m=ze(Y(i)).filter(b=>b.length),p=e.device.limits.maxComputeWorkgroupsPerDimension,y=Math.min(4096,Math.floor(e.device.limits.maxStorageBufferBindingSize/(l*4)));if(y<1)throw new Error("SpMV count scratch must fit a storage binding");let g=[];for(let b of h)for(let C=0;C<b[0].length;C+=y){let B=Math.min(y,b[0].length-C);g.push(b.map(E=>e.createDataView(E.buffer,{format:E.format,length:B,byteOffset:E.byteOffset+C*4})))}let w=g.map(([b],C)=>c==="long-row"?z(e,`${this.id}-rows-${C}-partials`,"float32",b.length*l):void 0),S=m.length>1&&g.length*m.length>m.length+g.length,T=0,v=[];for(let[b,[C,B]]of f.entries()){let E;if(S){E=z(e,`${this.id}-gather-${b}`,"float32",C.length);let _=new hn({id:`${this.id}-gather-${b}`,source:i,indices:C,output:E}).getCommandNodes(e);for(let[j,W]of _.entries())a.push(j===0?{...W,dependsOn:[...W.dependsOn??[],...v]}:W)}let $=E?[{data:E,offset:0}]:m,L=[];for(let[_,[j,W,le]]of g.entries()){let ne=j.length,Ze=w[_];for(let[Qe,ht]of $.entries()){let ni=b===0&&Qe===0,oi=`${this.id}-rows-${_}-nonzeros-${b}-vector-${Qe}-${c}`,ca=c==="scalar-row"?Math.ceil(ne/d):ne*l,ii=Mt(ca,p),si=Ze??le;if(a.push(dn(e,{id:oi,source:Ic({strategy:c,workgroupSize:d,parts:l,length:ne,begins:j,ends:W,indices:C,matrixValues:B,vector:ht.data,output:si,nonzeroStart:T,vectorStart:ht.offset,initialize:ni,dispatch:ii,gathered:!!E,columns:this.props.columns}),inputs:{rowBegins:j,rowEnds:W,columnIndices:C,matrixValues:B,vectorValues:ht.data},outputs:{[Ze?"rowPartials":"outputValues"]:si},dispatch:ii,workgroupSize:d})),Ze){let ai=Mt(Math.ceil(ne/64),p);a.push(dn(e,{id:`${oi}-finalize`,inputs:{rowPartials:Ze},outputs:{outputValues:le},dispatch:ai,workgroupSize:64,source:`
613
614
  @group(0) @binding(0) var<storage, read> rowPartials: array<f32>;
614
615
  @group(0) @binding(1) var<storage, read_write> outputValues: array<f32>;
615
616
  @compute @workgroup_size(64)
616
617
  fn main(@builtin(workgroup_id) workgroupId: vec3u, @builtin(local_invocation_index) localInvocationIndex: u32) {
617
- ${J(si,64)}
618
+ ${J(ai,64)}
618
619
  if (index >= ${ne}u) { return; }
619
620
  var sum = 0.0;
620
621
  for (var part = 0u; part < ${l}u; part++) {
621
622
  sum += rowPartials[index * ${l}u + part];
622
623
  }
623
- outputValues[${P(le)}u + index] ${ri?"=":"+="} sum;
624
- }`}))}}$.length&&L.push(a[a.length-1].id)}v=L,T+=C.length}if(!h.length||!m.length)for(let[b,[C,,B]]of p.entries()){let E=Mt(Math.ceil(C.length/256),g);a.push(dn(e,{id:`${this.id}-rows-${b}-clear`,outputs:{outputValues:B},dispatch:E,source:`
624
+ outputValues[${P(le)}u + index] ${ni?"=":"+="} sum;
625
+ }`}))}}$.length&&L.push(a[a.length-1].id)}v=L,T+=C.length}if(!f.length||!m.length)for(let[b,[C,,B]]of g.entries()){let E=Mt(Math.ceil(C.length/256),p);a.push(dn(e,{id:`${this.id}-rows-${b}-clear`,outputs:{outputValues:B},dispatch:E,source:`
625
626
  @group(0) @binding(0) var<storage, read_write> outputValues: array<f32>;
626
627
  @compute @workgroup_size(256)
627
628
  fn main(@builtin(workgroup_id) workgroupId: vec3u, @builtin(local_invocation_index) localInvocationIndex: u32) {
@@ -683,8 +684,8 @@ ${a?`var<workgroup> scratch: array<f32, ${t}>;`:""}
683
684
  ${c}[${P(r.output)}u + row * ${n}u + ${u?"part":"0u"}] ${u||r.initialize?"=":"+="} sum;
684
685
  }
685
686
  }`}var pn=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(n=>n.arena!==t))throw new Error(`${this.id} predicates must share one GPUValueArena`)}getCommandNodes(e){let{inputs:t,output:n}=this.props;if(n.arena.graph!==e)throw new Error(`${this.id} predicates must belong to target graph`);let o=n.arena.buffer,i=t.map(a=>`(${Oe(a)} != 0u)`).join(" && "),s=`${be(0,0)}
686
- @compute @workgroup_size(1)fn main(){${dt(n,`select(0u,1u,${i})`)}}`;return[V({id:this.id,workload:{operation:"GPUPredicateConjunction",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:t.length*4,writeByteLength:4},resources:[{buffer:o,usage:"storage-write"}],compile:({device:a})=>{let u=new D(a,{id:this.id,source:s,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:c,getBuffer:d})=>{let l={gpuValues:d(o)};u.dispatch(c,{bindings:l,x:1,y:1,z:1})},destroy:()=>u.destroy()}}})]}};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 $e(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))}):$e(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 Ws(r){return typeof r.getCommandNodes=="function"}var zt=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"}},lt=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 n=e.minimumIterations??0;if(!Number.isSafeInteger(n)||n<0||n>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=n,this.lowering=e.lowering??"auto"}};function Wt(r){let e=r.clone(),t=new Map([...e.scalars,...e.vectors,...e.textures].map(i=>[i.id,i])),n=new Set,o=(i,s=!1)=>{if(i instanceof q){for(let a of i.operations)o(a,s||i.type!=="composite");return}if($e(i))try{let a=i.contract;if(!a)return;let u=typeof a.outputs=="function"?a.outputs({getValue(d){let l=t.get(d);if(!l)throw new Error(`Undeclared operation value ${d}`);return l instanceof de?l.descriptor??M.texture({format:l.format,dimension:l.dimension,extent:{width:l.width,height:l.height,depth:l.depth},mipLevels:l.mipLevels,samples:l.samples}):l instanceof Ae?M.scalar(l.format):M.vector(l.format,{length:l.length,chunkLengths:l.chunkLengths})}}):a.outputs;for(let[d,l]of Object.entries(u??{})){if(!a.values.some(h=>h.access==="write"&&k(h.value)===d))throw new Error(`Operation result ${d} requires a write`);if(l.type==="texture"&&l.extent&&"like"in l.extent){let h=l.extent.like;if(!(t.get(h)instanceof de)||!a.values.some(m=>m.access!=="write"&&k(m.value)===h))throw new Error(`Texture extent source ${h} must be a declared texture read`)}let f=t.get(d);if(f?.role==="input"||f?.role==="state")throw new Error(`Operation result conflicts with ${f.role} ${d}`);if(f){if(f.format!==l.format||f instanceof Q!=(l.type==="vector")||f instanceof de!=(l.type==="texture"))throw new Error(`Incompatible operation result ${d}`);f instanceof Q&&l.type==="vector"&&t.set(d,e.constrainResult(f,l))}else{if(s)throw new Error("Operation results inside control flow require explicit declarations");let h=a.values.find(y=>k(y.value)===d&&y.access==="write")?.shape,m=l;if(l.type==="vector"&&l.length===void 0&&h){let y="like"in h?t.get(k(h.like)):void 0,p="length"in h?h:y instanceof Q?y:void 0;p?.length!==void 0&&(m={...l,length:p.length,chunkLengths:l.chunkLengths??p.chunkLengths})}let g=e.addDeclaration(d,m,"value");t.set(d,g)}}Rt(e,a);for(let d of a.values){let l=k(d.value),f=t.get(l);if(d.access!=="read"&&f?.role==="input")throw new Error(`Cannot write graph input ${l}`);if(d.access!=="write"&&f?.role==="value"&&!n.has(l))throw new Error(`Reads ${l} before it is produced`)}let c=new Set(a.values.filter(d=>d.access!=="read").map(d=>k(d.value)));for(let d of c){if(t.get(d)?.role==="value"&&n.has(d))throw new Error(`Multiple writers for graph result ${d}`);n.add(d)}}catch(a){throw new Error(`${i.id}: ${a instanceof Error?a.message:String(a)}`,{cause:a})}};return e.operations.forEach(i=>o(i)),e}function vr(r,e={}){let t=[];try{r=Wt(r)}catch(i){return{valid:!1,issues:[{level:"error",code:"invalid-operation-contract",message:i instanceof Error?i.message:String(i)}]}}for(let i of r.scalars)i.role==="input"&&e.scalars?.[i.id]===void 0&&t.push({level:"error",code:"missing-input",valueId:i.id,message:`Missing input binding ${i.id}`}),i.role==="value"&&e.scalars?.[i.id]!==void 0&&t.push({level:"error",code:"result-binding",valueId:i.id,message:`Cannot initialize graph result ${i.id}`});let n=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 o=i=>{let s="id"in i&&typeof i.id=="string"?i.id:void 0;if($e(i))try{let a=i.contract;a&&Rt(r,a)}catch(a){t.push({level:"error",code:"invalid-operation-contract",operationId:s,message:`${s}: ${a instanceof Error?a.message:String(a)}`})}if(i instanceof zt||i instanceof lt){let a=i.predicate;a?.source==="gpu"&&(a.value.format!=="uint32"&&t.push({level:"error",code:"invalid-predicate-format",operationId:s,valueId:a.value.id,message:`GPU predicate "${a.id}" must use uint32 state`}),n.has(a.value.id)||t.push({level:"error",code:"missing-predicate-scalar",operationId:s,valueId:a.value.id,message:`GPU predicate "${a.id}" references undeclared scalar "${a.value.id}"`}))}if(i instanceof q)for(let a of i.operations)o(a)};for(let i of r.operations)o(i);return Object.freeze({valid:!t.some(i=>i.level==="error"),issues:Object.freeze(t.map(i=>Object.freeze({...i})))})}var St=class{device;capabilities;lowerings;compactionIndex=0;aggregationIndex=0;constructor(e,t=[]){this.device=e,this.capabilities=Object.freeze({backend:"webgpu",gpuConditionals:!0,nativeLoops:!1,childGraphs:!1});let n=[...this.createCoreLowerings(),...t],o=new Set;for(let i of n){if(!i.type||o.has(i.type))throw new Error(`Duplicate or empty lowering type: ${i.type}`);o.add(i.type)}this.lowerings=Object.freeze(n.map(i=>Object.freeze({type:i.type,lower:i.lower.bind(i)})))}compile(e,t={}){this.compactionIndex=0,this.aggregationIndex=0,e=e.clone();for(let h of e.vectors){let m=t.vectors?.[h.id];if(!h.external||!m||h.chunkLengths)continue;let g="data"in m?m.data:"buffer"in m?[m]:m;e.constrainResult(h,{type:"vector",format:h.format,chunkLengths:g.map(y=>y.length)})}e=Wt(e);let n=new Map,o=(h,m)=>{n.set(h,(n.get(h)??0)|m)},i=h=>{h instanceof q?h.operations.forEach(i):h instanceof qe?o(h.output,se.Buffer.COPY_DST):h instanceof Ye&&(o(h.input,se.Buffer.COPY_SRC),o(h.output,se.Buffer.COPY_DST))};e.operations.forEach(i);let s=vr(e,t);if(!s.valid)throw new Error(`GPUGraph "${e.id}" validation failed: ${s.issues.filter(h=>h.level==="error").map(h=>h.message).join("; ")}`);let a=new rn(this.device,{id:`${e.id}-commands`}),u=new Map;for(let h of e.scalars)u.set(h.id,No(a,h.id,h.format));for(let[h,m]of Object.entries(t.scalars??{})){let g=u.get(h);if(!g)throw new Error(`Undeclared scalar binding ${h}`);let y=g.view;a.addCopyPass({id:`${h}-binding`,resources:[{buffer:y,usage:"copy-destination"}],compile:({device:p})=>{let w=g.format==="float32"?new Float32Array([m]):g.format==="uint32"?new Uint32Array([m]):new Int32Array([m]),S=p.createBuffer({data:w,usage:se.Buffer.COPY_SRC});return{encode:({commandEncoder:T,getBuffer:v})=>T.copyBufferToBuffer({sourceBuffer:S,destinationBuffer:v(y),destinationOffset:y.byteOffset,size:4}),destroy:()=>S.destroy()}}})}let c=new Map;for(let h of e.vectors){if(h.length===void 0)throw new Error(`${h.id}: bind dynamic dimensions through program.compile(device).run(bindings)`);let m;if(h.external){let g=t.vectors[h.id],y="data"in g?g:{format:h.format,length:h.length,data:"buffer"in g?[g]:g};if(m=a.importGPUVector(h.id,y),m.format!==h.format||m.length!==h.length)throw new Error(`${h.id} binding format and length must match its logical vector`);if(h.chunkLengths&&(h.chunkLengths.length!==m.data.length||h.chunkLengths.some((p,w)=>p!==m.data[w].length)))throw new Error(`${h.id} binding must preserve its declared chunk topology`)}else{let g=h.chunkLengths??Uc(h.length,this.device,U(h.format).byteLength),y=g.map((w,S)=>z(a,g.length===1?h.id:`${h.id}-chunk-${S}`,h.format,w,h.role==="value"?se.Buffer.STORAGE|se.Buffer.VERTEX|se.Buffer.COPY_SRC|se.Buffer.COPY_DST:se.Buffer.STORAGE|(n.get(h.id)??0))),p=U(h.format);m=new O({id:h.id,name:h.id,format:h.format,length:h.length,valueLength:h.length,stride:p.components,byteStride:p.byteLength,rowByteLength:p.byteLength,data:y})}c.set(h.id,m)}let d=new Map,l=new Map;for(let h of e.textures){(0,se.assert)(h.width!==void 0&&h.height!==void 0);let m=t.textures?.[h.id],g={...h,width:h.width,height:h.height};if(m instanceof se.TextureView){let p=ee(m);(0,se.assert)(p.format===h.format&&p.width===h.width&&p.height===h.height),l.set(h.id,m),m=p.texture,g={...g,dimension:m.dimension,width:m.width,height:m.height,depth:m.depth,mipLevels:m.mipLevels,samples:m.samples}}let y=h.external?a.importTexture(g,m):a.createTransientTexture(g);d.set(h.id,y)}let f={path:[],nodes:[],decisions:[],predicates:[],scalars:u,vectors:c,textures:d,textureValues:e.textures,textureViews:l,predicateConjunctions:new Map,commandNodeIds:new Set,transientResultNames:new Set(e.vectors.filter(h=>h.role==="value"&&!h.external).map(h=>h.id)),retainedBuffers:[]};for(let h of e.operations)this.lower(a,h,f);return Object.freeze({program:e,graph:a,scalars:u,vectors:c,textures:d,validation:s,lowering:Object.freeze({operations:e.operationTree,nodes:Object.freeze(f.nodes.map(h=>Object.freeze({...h,operationPath:Object.freeze([...h.operationPath])}))),decisions:Object.freeze(f.decisions.map(h=>Object.freeze({...h})))})})}createCoreLowerings(){return[{type:"vector-upload",lower:ps},{type:"vector-copy",lower:gs},{type:"group-aggregation",lower:(e,t)=>{let{props:n}=e,o=`${e.id}-${this.aggregationIndex++}`,i=t.resolveVector(n.keys),s=n.mask?t.resolveVector(n.mask):void 0;n.operation==="count"?t.graph.add(new br({id:o,keys:i,mask:s,operation:"count",output:jo(t.resolveVector(n.output))})):t.graph.add(new br({id:o,keys:i,mask:s,operation:n.operation,values:t.resolveVector(n.values),output:jo(t.resolveVector(n.output))}))}},{type:"reduction",lower:(e,t)=>{let{props:n}=e;t.graph.add(new Jr({id:`${e.id}-${this.aggregationIndex++}`,input:t.resolveVector(n.input),mask:n.mask?t.resolveVector(n.mask):void 0,operation:n.operation,output:jo(t.resolveVector(n.output))}))}},{type:"compaction",lower:(e,t)=>{let{input:n,flags:o,output:i,count:s}=e.props;t.graph.add(new tn({id:`${e.id}-${this.compactionIndex++}`,input:t.resolveVector(n),flags:t.resolveVector(o),output:t.resolveVector(i),count:t.resolveScalar(s).view}))}},{type:"scalar-literal",lower:(e,t)=>{let n=new Vt({id:e.id,output:t.resolveScalar(e.props.output),value:e.props.value});this.emitProducer(t.graph,n,[[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"})}},{type:"scalar-operation",lower:(e,t)=>{let n=new an({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,n,[[1,1,1]]),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-scalar-kernel",reason:"scalar operation lowers to one compute command node"})}},{type:"vector-madd",lower:(e,t)=>{let n=e.props,o=new cn({id:e.id,input:t.resolveVector(n.input),scale:t.resolveScalar(n.scale),addend:t.resolveVector(n.addend),output:t.resolveVector(n.output)});this.emitProducer(t.graph,o),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-vector-madd",reason:"dense float32 MADD lowers through explicit command nodes"})}},{type:"dot-product",lower:(e,t)=>{let n=e.props,o=new ln({id:e.id,left:t.resolveVector(n.left),right:t.resolveVector(n.right),output:t.resolveScalar(n.output)});this.emitProducer(t.graph,o),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-hierarchical-dot",reason:"chunk dot products use bounded hierarchical reductions into the scalar arena"})}},{type:"spmv",lower:(e,t)=>{let n=e.props,o=n.matrix,i=new mn({id:e.id,rowOffsets:t.resolveVector(o.rowOffsets),columnIndices:t.resolveVector(o.columnIndices),values:t.resolveVector(o.values),vector:t.resolveVector(n.vector),output:t.resolveVector(n.output),columns:o.columns,statistics:o.statistics,strategy:n.strategy}),s=i.getStrategy(t.graph);this.emitProducer(t.graph,i),t.recordDecision({operationId:e.id,operationType:e.type,lowering:`webgpu-spmv:${s.id}`,reason:s.reason})}},{type:"conditional",lower:(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 n of e.operations)t.lowerConditional(e.predicate,n)}},{type:"loop",lower:(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 n=0;n<e.maximumIterations;n++)for(let o of e.operations)t.lower(o);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 n=0;n<e.maximumIterations;n++){let o=n>=e.minimumIterations;for(let i of e.operations)o?t.lowerConditional(e.predicate,i):t.lower(i)}}}]}lower(e,t,n){let o="id"in t&&typeof t.id=="string"?t.id:t.constructor?.name??"command-node-producer";n.path.push(o);let i=n.retainedBuffers,s=[...i];if($e(t))for(let a of t.contract?.values??[]){let u=typeof a.value=="string"?a.value:a.value.id;if(n.transientResultNames.has(u))for(let c of n.vectors.get(u).data)s.push(c.buffer)}n.retainedBuffers=s;try{if(t instanceof q&&t.type==="composite"){n.decisions.push({operationId:t.id,operationType:t.type,lowering:"flatten",reason:"WebGPU has no executable child-graph primitive"});for(let a of t.operations)this.lower(e,a,n);return}if($e(t)){for(let u of t.contract?.requiredFeatures??[])if(!this.device.features.has(u))throw new Error(`${o} requires ${u}`);let a=this.lowerings.find(u=>u.type===t.type)?.lower;if(a){let u=()=>(t instanceof Ye&&n.textureValues.some(c=>c.id===t.input)?ys:a)(t,{graph:e,capabilities:this.capabilities,lower:c=>this.lower(e,c,n),lowerConditional:(c,d)=>{n.predicates.push(c);try{this.lower(e,d,n)}finally{n.predicates.pop()}},resolveScalar:c=>this.resolveScalar(c,n),resolveVector:c=>this.resolveVector(c,n),resolveTexture:c=>this.resolveTexture(c,n),resolveTextureView:c=>{let d=c instanceof Fe?c.texture:c,l=c instanceof Fe?c.props:{},f=n.textureViews.get(typeof d=="string"?d:d.id);return e.createTextureView(this.resolveTexture(d,n),f?fs(f,l):l)},recordDecision:c=>n.decisions.push(c)});t instanceof zt||t instanceof lt?u():this.withNodeDecoration(e,n,u);return}}if("getNodes"in t||Ws(t)){n.decisions.push({operationId:o,operationType:"command-node-producer",lowering:"explicit-command-nodes",reason:"execution primitive constructs explicit command nodes"}),this.withNodeDecoration(e,n,()=>e.add(t));return}throw new Error(`GPUGraph operation "${o}" has no WebGPU lowering`)}finally{n.retainedBuffers=i,n.path.pop()}}emitProducer(e,t,n){let o=t.getCommandNodes(e);if(!n){He(e,o);return}if(o.length!==n.length)throw new Error(`lowering produced ${o.length} command nodes but declared ${n.length} dispatches`);let i=o.map((s,a)=>this.attachDispatch(s,n[a]));He(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 N(e,t)}withNodeDecoration(e,t,n){return e.withComputeLowering(o=>this.decorateComputeNode(e,o,t),()=>e.withOtherLowering(o=>{if(t.predicates.length)throw new Error(`GPU predicates do not support ${o.type} node "${o.id}"`);let i=this.makeCommandNodeIdUnique(o,t);return t.nodes.push({nodeId:i.id,nodeType:i.type,operationPath:[...t.path]}),{...i,retainedBuffers:t.retainedBuffers}},n))}decorateComputeNode(e,t,n){if(t={...this.makeCommandNodeIdUnique(t,n),retainedBuffers:n.retainedBuffers},n.path.length&&n.nodes.push({nodeId:t.id,nodeType:"compute",operationPath:[...n.path]}),!n.predicates.length)return t;if(t.condition)throw new Error(`compute node "${t.id}" already has condition`);let o=Qr(t);if(!o)throw new Error(`compute node "${t.id}" under runtime predicate must declare exact dispatch geometry`);let i;if(n.predicates.length===1)i=n.scalars.get(n.predicates[0].value.id);else{let u=n.predicates.map(f=>f.value.id).join("&&"),c=n.predicateConjunctions.get(u);c||(c=No(e,`predicate-and-${n.predicateConjunctions.size}`,"uint32"),n.predicateConjunctions.set(u,c));let d=n.predicates.map(f=>n.scalars.get(f.value.id)),l=new pn({id:`${t.id}-predicate-and`,inputs:d,output:c}).getCommandNodes(e).map(f=>this.attachDispatch(f,[1,1,1]));e.withoutComputeLowering(()=>He(e,l)),i=c}if(!i)throw new Error(`runtime predicate for "${t.id}" could not be resolved`);let s=new Tr(e,{id:`${t.id}-predicate`,active:i,workgroups:o}),a=s.getUpdateCommandNodes(e,`${t.id}-predicate-update`).map(u=>this.attachDispatch(u,[1,1,1]));return e.withoutComputeLowering(()=>He(e,a)),{...t,condition:s.condition}}makeCommandNodeIdUnique(e,t){if(!t.commandNodeIds.has(e.id))return t.commandNodeIds.add(e.id),e;let n=1,o=`${e.id}-iteration-${n}`;for(;t.commandNodeIds.has(o);)n++,o=`${e.id}-iteration-${n}`;return t.commandNodeIds.add(o),{...e,id:o}}resolveTexture(e,t){let n=typeof e=="string"?e:e.id;if(typeof e=="string"?!t.textures.has(n):!t.textureValues.includes(e))throw new Error(`Undeclared program texture "${n}"`);return t.textures.get(n)}resolveScalar(e,t){let n=typeof e=="string"?e:e.id,o=t.scalars.get(n);if(!o||typeof e!="string"&&o.format!==e.format)throw new Error(`GPUGraph scalar "${n}" is not part of compilation`);return o}resolveVector(e,t){let n=typeof e=="string"?e:e.id,o=t.vectors.get(n);if(!o||typeof e!="string"&&(o.format!==e.format||e.length!==void 0&&o.length!==e.length))throw new Error(`GPUGraph vector "${n}" is not part of compilation`);return o}};function Uc(r,e,t){let n=Math.floor(e.limits.maxStorageBufferBindingSize/t);if(n<1||r<=n)return[r];let o=[];for(let i=0;i<r;i+=n)o.push(Math.min(n,r-i));return o}function jo(r){return(0,se.assert)(r.data.length===1),r.data[0]}var we=F(A(),1);var Et=F(A(),1);var ft=class{type="shader-pass";id;fragmentSource;inputs;samplers;parameters;output;outputDescriptor;constructor(e){this.id=e.id??`${e.output}-shader-pass`,this.fragmentSource=e.fragmentSource,this.inputs=Object.freeze({...e.inputs}),this.parameters=Object.freeze({...e.parameters}),this.samplers=Object.freeze(Object.fromEntries(Object.entries(e.samplers??{}).map(([o,i])=>[o,Object.freeze({...i})]))),this.output=e.output;let t=e.outputDescriptor;(0,Et.assert)(t.extent&&(t.dimension??"2d")==="2d"&&(t.mipLevels??1)===1&&(t.samples??1)===1),this.outputDescriptor=M.texture({...t,dimension:"2d",mipLevels:1,samples:1});let n=[...Object.keys(this.inputs),...Object.keys(this.samplers)];(0,Et.assert)(new Set(n).size===n.length);for(let o of[...n,...Object.keys(this.parameters)])(0,Et.assert)(/^[A-Za-z][A-Za-z0-9_]*$/.test(o)&&!["parameters","shade","vertexMain","fragmentMain"].includes(o)&&!o.startsWith("GraphShaderPass"));for(let o of Object.values(this.samplers))(0,Et.assert)((o.type??"color-sampler")==="color-sampler")}get contract(){return{values:[...Object.values(this.inputs).map(e=>({value:e,access:"read",textureUsage:"sampled"})),...Object.values(this.parameters).map(e=>({value:e,access:"read"})),{value:this.output,access:"write",textureUsage:"render-attachment"}],outputs:({getValue:e})=>{for(let t of Object.values(this.inputs)){let n=e(t);(0,Et.assert)(n.type==="texture"&&(n.dimension??"2d")==="2d"&&(n.samples??1)===1)}for(let t of Object.values(this.parameters))(0,Et.assert)(e(t).type==="scalar");return{[this.output]:this.outputDescriptor}}}}};function js(r,e){if(r)try{r.error(e instanceof Error?e.message:String(e),e)()}catch{}}var Gc=class{add(r,e,t){if(typeof arguments[0]!="string")for(let n in arguments[0])this.add(n,arguments[0][n],arguments[1]);else(Array.isArray(r)?r:[r]).forEach(function(n){this[n]=this[n]||[],e&&this[n][t?"unshift":"push"](e)},this)}run(r,e){this[r]=this[r]||[],this[r].forEach(function(t){t.call(e&&e.context?e.context:e,e)})}},Dc=class{constructor(r){this.jsep=r,this.registered={}}register(...r){r.forEach(e=>{if(typeof e!="object"||!e.name||!e.init)throw new Error("Invalid JSEP plugin format");this.registered[e.name]||(e.init(this.jsep),this.registered[e.name]=e)})}},xe=class x{static get version(){return"1.4.0"}static toString(){return"JavaScript Expression Parser (JSEP) v"+x.version}static addUnaryOp(e){return x.max_unop_len=Math.max(e.length,x.max_unop_len),x.unary_ops[e]=1,x}static addBinaryOp(e,t,n){return x.max_binop_len=Math.max(e.length,x.max_binop_len),x.binary_ops[e]=t,n?x.right_associative.add(e):x.right_associative.delete(e),x}static addIdentifierChar(e){return x.additional_identifier_chars.add(e),x}static addLiteral(e,t){return x.literals[e]=t,x}static removeUnaryOp(e){return delete x.unary_ops[e],e.length===x.max_unop_len&&(x.max_unop_len=x.getMaxKeyLen(x.unary_ops)),x}static removeAllUnaryOps(){return x.unary_ops={},x.max_unop_len=0,x}static removeIdentifierChar(e){return x.additional_identifier_chars.delete(e),x}static removeBinaryOp(e){return delete x.binary_ops[e],e.length===x.max_binop_len&&(x.max_binop_len=x.getMaxKeyLen(x.binary_ops)),x.right_associative.delete(e),x}static removeAllBinaryOps(){return x.binary_ops={},x.max_binop_len=0,x}static removeLiteral(e){return delete x.literals[e],x}static removeAllLiterals(){return x.literals={},x}get char(){return this.expr.charAt(this.index)}get code(){return this.expr.charCodeAt(this.index)}constructor(e){this.expr=e,this.index=0}static parse(e){return new x(e).parse()}static getMaxKeyLen(e){return Math.max(0,...Object.keys(e).map(t=>t.length))}static isDecimalDigit(e){return e>=48&&e<=57}static binaryPrecedence(e){return x.binary_ops[e]||0}static isIdentifierStart(e){return e>=65&&e<=90||e>=97&&e<=122||e>=128&&!x.binary_ops[String.fromCharCode(e)]||x.additional_identifier_chars.has(String.fromCharCode(e))}static isIdentifierPart(e){return x.isIdentifierStart(e)||x.isDecimalDigit(e)}throwError(e){let t=new Error(e+" at character "+this.index);throw t.index=this.index,t.description=e,t}runHook(e,t){if(x.hooks[e]){let n={context:this,node:t};return x.hooks.run(e,n),n.node}return t}searchHook(e){if(x.hooks[e]){let t={context:this};return x.hooks[e].find(function(n){return n.call(t.context,t),t.node}),t.node}}gobbleSpaces(){let e=this.code;for(;e===x.SPACE_CODE||e===x.TAB_CODE||e===x.LF_CODE||e===x.CR_CODE;)e=this.expr.charCodeAt(++this.index);this.runHook("gobble-spaces")}parse(){this.runHook("before-all");let e=this.gobbleExpressions(),t=e.length===1?e[0]:{type:x.COMPOUND,body:e};return this.runHook("after-all",t)}gobbleExpressions(e){let t=[],n,o;for(;this.index<this.expr.length;)if(n=this.code,n===x.SEMCOL_CODE||n===x.COMMA_CODE)this.index++;else if(o=this.gobbleExpression())t.push(o);else if(this.index<this.expr.length){if(n===e)break;this.throwError('Unexpected "'+this.char+'"')}return t}gobbleExpression(){let e=this.searchHook("gobble-expression")||this.gobbleBinaryExpression();return this.gobbleSpaces(),this.runHook("after-expression",e)}gobbleBinaryOp(){this.gobbleSpaces();let e=this.expr.substr(this.index,x.max_binop_len),t=e.length;for(;t>0;){if(x.binary_ops.hasOwnProperty(e)&&(!x.isIdentifierStart(this.code)||this.index+e.length<this.expr.length&&!x.isIdentifierPart(this.expr.charCodeAt(this.index+e.length))))return this.index+=t,e;e=e.substr(0,--t)}return!1}gobbleBinaryExpression(){let e,t,n,o,i,s,a,u,c;if(s=this.gobbleToken(),!s||(t=this.gobbleBinaryOp(),!t))return s;for(i={value:t,prec:x.binaryPrecedence(t),right_a:x.right_associative.has(t)},a=this.gobbleToken(),a||this.throwError("Expected expression after "+t),o=[s,i,a];t=this.gobbleBinaryOp();){if(n=x.binaryPrecedence(t),n===0){this.index-=t.length;break}i={value:t,prec:n,right_a:x.right_associative.has(t)},c=t;let d=l=>i.right_a&&l.right_a?n>l.prec:n<=l.prec;for(;o.length>2&&d(o[o.length-2]);)a=o.pop(),t=o.pop().value,s=o.pop(),e={type:x.BINARY_EXP,operator:t,left:s,right:a},o.push(e);e=this.gobbleToken(),e||this.throwError("Expected expression after "+c),o.push(i,e)}for(u=o.length-1,e=o[u];u>1;)e={type:x.BINARY_EXP,operator:o[u-1].value,left:o[u-2],right:e},u-=2;return e}gobbleToken(){let e,t,n,o;if(this.gobbleSpaces(),o=this.searchHook("gobble-token"),o)return this.runHook("after-token",o);if(e=this.code,x.isDecimalDigit(e)||e===x.PERIOD_CODE)return this.gobbleNumericLiteral();if(e===x.SQUOTE_CODE||e===x.DQUOTE_CODE)o=this.gobbleStringLiteral();else if(e===x.OBRACK_CODE)o=this.gobbleArray();else{for(t=this.expr.substr(this.index,x.max_unop_len),n=t.length;n>0;){if(x.unary_ops.hasOwnProperty(t)&&(!x.isIdentifierStart(this.code)||this.index+t.length<this.expr.length&&!x.isIdentifierPart(this.expr.charCodeAt(this.index+t.length)))){this.index+=n;let i=this.gobbleToken();return i||this.throwError("missing unaryOp argument"),this.runHook("after-token",{type:x.UNARY_EXP,operator:t,argument:i,prefix:!0})}t=t.substr(0,--n)}x.isIdentifierStart(e)?(o=this.gobbleIdentifier(),x.literals.hasOwnProperty(o.name)?o={type:x.LITERAL,value:x.literals[o.name],raw:o.name}:o.name===x.this_str&&(o={type:x.THIS_EXP})):e===x.OPAREN_CODE&&(o=this.gobbleGroup())}return o?(o=this.gobbleTokenProperty(o),this.runHook("after-token",o)):this.runHook("after-token",!1)}gobbleTokenProperty(e){this.gobbleSpaces();let t=this.code;for(;t===x.PERIOD_CODE||t===x.OBRACK_CODE||t===x.OPAREN_CODE||t===x.QUMARK_CODE;){let n;if(t===x.QUMARK_CODE){if(this.expr.charCodeAt(this.index+1)!==x.PERIOD_CODE)break;n=!0,this.index+=2,this.gobbleSpaces(),t=this.code}this.index++,t===x.OBRACK_CODE?(e={type:x.MEMBER_EXP,computed:!0,object:e,property:this.gobbleExpression()},e.property||this.throwError('Unexpected "'+this.char+'"'),this.gobbleSpaces(),t=this.code,t!==x.CBRACK_CODE&&this.throwError("Unclosed ["),this.index++):t===x.OPAREN_CODE?e={type:x.CALL_EXP,arguments:this.gobbleArguments(x.CPAREN_CODE),callee:e}:(t===x.PERIOD_CODE||n)&&(n&&this.index--,this.gobbleSpaces(),e={type:x.MEMBER_EXP,computed:!1,object:e,property:this.gobbleIdentifier()}),n&&(e.optional=!0),this.gobbleSpaces(),t=this.code}return e}gobbleNumericLiteral(){let e="",t,n;for(;x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);if(this.code===x.PERIOD_CODE)for(e+=this.expr.charAt(this.index++);x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);if(t=this.char,t==="e"||t==="E"){for(e+=this.expr.charAt(this.index++),t=this.char,(t==="+"||t==="-")&&(e+=this.expr.charAt(this.index++));x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);x.isDecimalDigit(this.expr.charCodeAt(this.index-1))||this.throwError("Expected exponent ("+e+this.char+")")}return n=this.code,x.isIdentifierStart(n)?this.throwError("Variable names cannot start with a number ("+e+this.char+")"):(n===x.PERIOD_CODE||e.length===1&&e.charCodeAt(0)===x.PERIOD_CODE)&&this.throwError("Unexpected period"),{type:x.LITERAL,value:parseFloat(e),raw:e}}gobbleStringLiteral(){let e="",t=this.index,n=this.expr.charAt(this.index++),o=!1;for(;this.index<this.expr.length;){let i=this.expr.charAt(this.index++);if(i===n){o=!0;break}else if(i==="\\")switch(i=this.expr.charAt(this.index++),i){case"n":e+=`
687
- `;break;case"r":e+="\r";break;case"t":e+=" ";break;case"b":e+="\b";break;case"f":e+="\f";break;case"v":e+="\v";break;default:e+=i}else e+=i}return o||this.throwError('Unclosed quote after "'+e+'"'),{type:x.LITERAL,value:e,raw:this.expr.substring(t,this.index)}}gobbleIdentifier(){let e=this.code,t=this.index;for(x.isIdentifierStart(e)?this.index++:this.throwError("Unexpected "+this.char);this.index<this.expr.length&&(e=this.code,x.isIdentifierPart(e));)this.index++;return{type:x.IDENTIFIER,name:this.expr.slice(t,this.index)}}gobbleArguments(e){let t=[],n=!1,o=0;for(;this.index<this.expr.length;){this.gobbleSpaces();let i=this.code;if(i===e){n=!0,this.index++,e===x.CPAREN_CODE&&o&&o>=t.length&&this.throwError("Unexpected token "+String.fromCharCode(e));break}else if(i===x.COMMA_CODE){if(this.index++,o++,o!==t.length){if(e===x.CPAREN_CODE)this.throwError("Unexpected token ,");else if(e===x.CBRACK_CODE)for(let s=t.length;s<o;s++)t.push(null)}}else if(t.length!==o&&o!==0)this.throwError("Expected comma");else{let s=this.gobbleExpression();(!s||s.type===x.COMPOUND)&&this.throwError("Expected comma"),t.push(s)}}return n||this.throwError("Expected "+String.fromCharCode(e)),t}gobbleGroup(){this.index++;let e=this.gobbleExpressions(x.CPAREN_CODE);if(this.code===x.CPAREN_CODE)return this.index++,e.length===1?e[0]:e.length?{type:x.SEQUENCE_EXP,expressions:e}:!1;this.throwError("Unclosed (")}gobbleArray(){return this.index++,{type:x.ARRAY_EXP,elements:this.gobbleArguments(x.CBRACK_CODE)}}},_c=new Gc;Object.assign(xe,{hooks:_c,plugins:new Dc(xe),COMPOUND:"Compound",SEQUENCE_EXP:"SequenceExpression",IDENTIFIER:"Identifier",MEMBER_EXP:"MemberExpression",LITERAL:"Literal",THIS_EXP:"ThisExpression",CALL_EXP:"CallExpression",UNARY_EXP:"UnaryExpression",BINARY_EXP:"BinaryExpression",ARRAY_EXP:"ArrayExpression",TAB_CODE:9,LF_CODE:10,CR_CODE:13,SPACE_CODE:32,PERIOD_CODE:46,COMMA_CODE:44,SQUOTE_CODE:39,DQUOTE_CODE:34,OPAREN_CODE:40,CPAREN_CODE:41,OBRACK_CODE:91,CBRACK_CODE:93,QUMARK_CODE:63,SEMCOL_CODE:59,COLON_CODE:58,unary_ops:{"-":1,"!":1,"~":1,"+":1},binary_ops:{"||":1,"??":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":10,"/":10,"%":10,"**":11},right_associative:new Set(["**"]),additional_identifier_chars:new Set(["$","_"]),literals:{true:!0,false:!1,null:null},this_str:"this"});xe.max_unop_len=xe.getMaxKeyLen(xe.unary_ops);xe.max_binop_len=xe.getMaxKeyLen(xe.binary_ops);var Sr=r=>new xe(r).parse(),Ac=Object.getOwnPropertyNames(class{});Object.getOwnPropertyNames(xe).filter(r=>!Ac.includes(r)&&Sr[r]===void 0).forEach(r=>{Sr[r]=xe[r]});Sr.Jsep=xe;var Fc="ConditionalExpression",Rc={name:"ternary",init(r){r.hooks.add("after-expression",function(t){if(t.node&&this.code===r.QUMARK_CODE){this.index++;let n=t.node,o=this.gobbleExpression();if(o||this.throwError("Expected expression"),this.gobbleSpaces(),this.code===r.COLON_CODE){this.index++;let i=this.gobbleExpression();if(i||this.throwError("Expected expression"),t.node={type:Fc,test:n,consequent:o,alternate:i},n.operator&&r.binary_ops[n.operator]<=.9){let s=n;for(;s.right.operator&&r.binary_ops[s.right.operator]<=.9;)s=s.right;t.node.test=s.right,s.right=t.node,t.node=n}}else this.throwError("Expected :")}})}};Sr.plugins.register(Rc);var Hs=Sr;var Vc=Hs;function Ho(r,e){try{return typeof r=="string"?Vc(r):r}catch(t){throw js(e?.log,t),t}}var Ve=class{get contract(){let e=gn(this.expression),t=yn(e);return{outputs:({getValue:n})=>{let o=t.map(a=>{let u=n(a);if(u.type==="texture")throw new Error("Numeric expressions cannot read textures");return[a,u]}),i=he(e,new Map(o.map(([a,u])=>[a,u.format]))),s=o.some(([,a])=>a.type==="vector");return{[this.output]:s||!qs(i)?M.vector(i,s?{}:{length:1}):M.scalar(i)}},values:[...yn(gn(this.expression)).map(n=>({value:n,access:"read"})),{value:this.output,access:"write"}]}}type="expression";id;output;expression;integerRounding;constructor(e){this.id=e.id??`${e.output}-expression`,this.output=e.output,this.expression=e.expression,this.integerRounding=e.integerRounding??"truncate"}};function qo(r){return/^(float32|sint32|uint32)(x[234])?$/.test(r)}function te(r){let e=U(r);return{components:e.components,componentType:e.signedDataType}}function Er(r,e){return e===1?r:`${r}x${e}`}function gn(r){let e=t=>{let n=t;switch(n.type){case"Identifier":return{kind:"reference",name:n.name};case"Literal":if(typeof n.value=="number"&&Number.isFinite(Math.fround(n.value)))return{kind:"literal",value:n.value};break;case"UnaryExpression":if(n.operator==="-")return{kind:"negate",argument:e(n.argument)};break;case"MemberExpression":{let o=n.property;if(n.computed||o.type!=="Identifier")throw new Error("Computed component access is unsupported");if(!/^[xyzw]{1,4}$/.test(o.name))throw new Error(`Invalid swizzle .${o.name}: expected 1\u20134 xyzw components`);return{kind:"swizzle",argument:e(n.object),components:[...o.name].map(i=>"xyzw".indexOf(i))}}case"CallExpression":{let o=n.callee;if(o.type!=="Identifier")break;let i=o.name;if(/^vec[234]$/.test(i)){if(n.arguments.length<1||n.arguments.length>4)throw new Error(`${i}: expected 1\u20134 arguments, received ${n.arguments.length}`);return{kind:"construct",width:Number(i[3]),arguments:n.arguments.map(e)}}if(qs(i)){if(n.arguments.length!==1)throw new Error(`Invalid argument count for ${i}`);return{kind:"cast",format:i,argument:e(n.arguments[0])}}if(!["abs","sqrt","pow","sin","cos","tan","exp","log","dot","length","equalAll","select"].includes(i))break;let s=i==="select"?3:["pow","dot","equalAll"].includes(i)?2:1;if(n.arguments.length!==s)throw new Error(`Invalid argument count for GPU expression function ${i}`);return{kind:"call",name:i,arguments:n.arguments.map(e)}}case"BinaryExpression":if(["+","-","*","/"].includes(n.operator))return{kind:"binary",operator:n.operator,left:e(n.left),right:e(n.right)};break}throw new Error(`Unsupported GPU expression syntax: ${n.type}`)};return e(typeof r=="string"?Ho(r):r)}function yn(r){let e=new Set,t=n=>{switch(n.kind){case"reference":e.add(n.name);break;case"swizzle":case"cast":case"negate":t(n.argument);break;case"construct":case"call":n.arguments.forEach(t);break;case"binary":t(n.left),t(n.right);break}};return t(r),[...e]}function qs(r){return r==="float32"||r==="sint32"||r==="uint32"}function he(r,e){switch(r.kind){case"literal":return"float32";case"reference":{let t=e.get(r.name);if(!t)throw new Error(`Undeclared numeric input ${r.name}`);return t}case"swizzle":{let t=te(he(r.argument,e)),n=Math.max(...r.components)+1;if(n>t.components){let o=r.components.map(s=>"xyzw"[s]).join(""),i=r.argument.kind==="reference"?r.argument.name:"input";throw new Error(`.${o} needs ${n} components; ${i} has ${t.components}`)}return Er(t.componentType,r.components.length)}case"construct":{let t=r.arguments.map(i=>te(he(i,e))),n=t[0].componentType;if(t.some(i=>i.componentType!==n))throw new Error(`vec${r.width}: mixed component types (${t.map(i=>i.componentType).join(", ")})`);let o=t.reduce((i,s)=>i+s.components,0);if(!(t.length===1&&o===1)&&o!==r.width)throw new Error(`vec${r.width}(...) needs ${r.width} components; received ${o}`);return Er(n,r.width)}case"cast":return Er(r.format,te(he(r.argument,e)).components);default:{let n=(r.kind==="call"?r.arguments:r.kind==="negate"?[r.argument]:[r.left,r.right]).map(i=>te(he(i,e)));if(r.kind==="call"){let[i,s,a]=n;if(r.name==="equalAll"){if(i.componentType!==s.componentType||i.components!==s.components)throw new Error("equalAll requires matching types and row widths");return"uint32"}if(r.name==="select"){if(s.componentType!==a.componentType)throw new Error("select branches require matching component types");let u=Math.max(s.components,a.components);if(n.some(c=>c.components!==1&&c.components!==u))throw new Error("select widths must match its branches or be one component");return Er(s.componentType,u)}if(r.name==="dot"&&i.components!==s.components)throw new Error("dot requires matching row widths")}if(n.some(i=>i.componentType!=="float32"))throw new Error("Arithmetic requires float32 operands; use an explicit float32 cast");if(r.kind==="call"&&(r.name==="dot"||r.name==="length"))return"float32";let o=Math.max(...n.map(i=>i.components));if(n.some(i=>i.components!==1&&i.components!==o))throw new Error("Expression row widths must match or broadcast from one component");return Er("float32",o)}}}var jt=class{contracts=new Map;resultNames;expressions;operations;outputs;scalars;vectors;textures;constructor(e,t={}){e=Wt(e),this.scalars=e.scalars,this.vectors=e.vectors,this.textures=e.textures;let n=[],o=m=>{if(m instanceof q&&m.type==="composite")m.operations.forEach(o);else{if(m instanceof q){let g=p=>p instanceof ft||p instanceof q&&p.operations.some(g);if(m.operations.some(g))throw new Error("Shader-pass operations inside control flow are not supported");let y=p=>p instanceof Ve||p instanceof q&&p.operations.some(y);if(m.operations.some(y))throw new Error("Expression operations inside control flow are not supported")}n.push(m)}};e.operations.forEach(o),this.operations=n;let i=new Map([...this.scalars,...this.vectors,...this.textures].map(m=>[m.id,m])),s=n.filter(m=>m instanceof Ve),a=new Set,u=new Map;for(let m of n)if(m instanceof Ve&&u.set(m,new Set(a)),!!$e(m))try{let g=Xs(m,this.scalars);if(!g)continue;Rt(e,g),this.contracts.set(m,g);for(let y of g.values){let p=k(y.value);y.access!=="read"&&this.scalars.some(w=>w.id===p)&&a.add(p)}}catch(g){throw new Error(`${m.id}: ${g instanceof Error?g.message:String(g)}`,{cause:g})}let c=new Set;for(let m of s){if(c.has(m.output))throw new Error(`Multiple expression writers for ${m.output}`);c.add(m.output)}let d=new Set([...i.keys()].filter(m=>!c.has(m)&&i.get(m)?.role!=="value")),l=[];for(let m of n){let g=this.contracts.get(m);if(!(m instanceof Ve)){for(let y of g?.values??[]){let p=k(y.value);if(y.access!=="write"&&!d.has(p))throw new Error(`${"id"in m?m.id:"Operation"}: Reads ${p} before it is produced`)}for(let y of g?.values??[])y.access!=="read"&&d.add(k(y.value));continue}try{let y=i.get(m.output);if(!y||!qo(y.format))throw new Error(`Expression output ${m.output} must declare a 32-bit numeric row of width 1\u20134`);let p=gn(m.expression),w=yn(p);if(w.includes(m.output))throw new Error(`Reads ${m.output} before it is produced`);let S=new Map;for(let b of w){let C=i.get(b);if(!C||!qo(C.format))throw new Error(`Expression input ${b} must declare a 32-bit numeric row of width 1\u20134`);if(S.set(b,C.format),!d.has(b))throw new Error(`Reads ${b} before it is produced`)}if(this.scalars.some(b=>b.id===y.id)&&w.some(b=>this.vectors.some(C=>C.id===b)))throw new Error(`Vector expression cannot write scalar ${m.output}`);if(this.vectors.some(b=>b.id===m.output)&&!w.some(b=>this.vectors.some(C=>C.id===b))&&!(y instanceof Q&&y.role==="value"&&y.length!==void 0))throw new Error(`Vector expression ${m.output} requires a vector input to determine its shape`);let T=he(p,S);if(y.format!==T)throw new Error("Expression result type must match its output declaration");d.add(m.output);let v=w.filter(b=>u.get(m).has(b));l.push({operation:m,expression:p,format:T,formats:S,references:w,gpuScalarInputs:v})}catch(y){throw y instanceof Error?new Error(`${m.id}: ${y.message}`,{cause:y}):y}}this.expressions=l;let f=[...i.values()].filter(m=>m.role==="value");this.resultNames=new Set([...this.contracts.values()].flatMap(m=>m.values.filter(g=>g.access!=="read").map(g=>k(g.value))).filter(m=>i.get(m)?.role!=="input"&&i.get(m)?.role!=="state"));let h=new Set([...this.contracts.values()].flatMap(m=>m.values.filter(g=>g.access!=="write").map(g=>k(g.value))));this.outputs=[...t.outputs??(f.length?[...this.resultNames].filter(m=>!h.has(m)):s.map(m=>m.output))];for(let m of this.outputs){if(!i.has(m))throw new Error(`Undeclared output ${m}`);if(this.scalars.some(g=>g.id===m)&&!c.has(m)&&!a.has(m))throw new Error(`Selected scalar ${m} must be produced by a graph operation`)}}resolveBindings(e,t={}){let n=[...this.scalars,...this.vectors,...this.textures];if(!(n.some(c=>c.role==="input"||c.role==="state")||Object.values(e).some(c=>c!==void 0&&typeof c=="object"&&!(c instanceof H)&&!(c instanceof Ee)&&!(c instanceof we.Texture)&&!(c instanceof we.TextureView)))){for(let c of Object.keys(e))if(n.find(d=>d.id===c)?.role==="value")throw new Error(`Use outputTargets for graph result ${c}`);return{bindings:e,options:t}}for(let c of Object.keys(e))if(!["inputs","state","outputTargets"].includes(c))throw new Error(`Unknown execution option ${c}`);let s=e,a=Object.create(null);for(let[c,d]of[["input",s.inputs],["state",s.state]])for(let[l,f]of Object.entries(d??{})){let h=n.find(g=>g.id===l),m=h?.role??(this.resultNames.has(l)?"value":"input");if(!h||m!==c)throw new Error(`Invalid ${c} binding ${l}`);a[l]=f}for(let c of n)if((c.role==="input"||c.role==="state")&&a[c.id]===void 0)throw new Error(`Missing ${c.role} binding ${c.id}`);if(t.outputTargets&&s.outputTargets)throw new Error("Duplicate output targets");let u=s.outputTargets??t.outputTargets;for(let c of Object.keys(u??{}))if(!this.resultNames.has(c)||!this.outputs.includes(c))throw new Error(`Invalid graph output target ${c}`);return{bindings:a,options:{outputTargets:u}}}prepare(e,t,n={},o=!1){let i=new Zr(e,this.textures,[...this.contracts.values()],t,n.outputTargets??{}),s=new Map,a=new Set,u=new Map,c=o&&!this.operations.some(p=>p instanceof q),d=p=>{let w=s.get(p);return w instanceof H?{length:w.length,chunkLengths:w.data.map(S=>S.length)}:u.get(p)},l=(p,w,S)=>{if(c&&!this.outputs.includes(p)&&this.vectors.some(T=>T.id===p&&T.role==="value"))u.set(p,{length:w.reduce((T,v)=>T+v,0),chunkLengths:w});else{let T=Ys(e,p,w,S);a.add(T),s.set(p,T)}},f=new Set(this.expressions.map(p=>p.operation.output)),h=new Map;for(let[p,w]of Object.entries(n.outputTargets??{}))if(!this.textures.some(S=>S.id===p)){if(!(w instanceof H))throw i.destroy(),new Error(`Expected GPUVector ${p}`);h.set(p,w)}let m=new Set([...this.contracts.values()].flatMap(p=>p.values.filter(w=>w.access!=="read"&&this.vectors.some(S=>S.id===k(w.value))).map(w=>k(w.value)))),g=new Set,y=new Set;try{for(let[p,w]of Object.entries(t)){if(this.textures.some(v=>v.id===p))continue;if(f.has(p))throw new Error(`Use outputTargets for expression output ${p}`);let S=this.scalars.find(v=>v.id===p),T=this.vectors.find(v=>v.id===p);if(S){if(typeof w!="number"||!Number.isFinite(w))throw new Error(`Expected numeric scalar ${p}`);if(S.format!=="float32"&&(!Number.isInteger(w)||w<(S.format==="uint32"?0:-2147483648)||w>(S.format==="uint32"?4294967295:2147483647)))throw new Error(`Scalar ${p} is outside its declared integer format`)}else if(T){if(!(w instanceof H))throw new Error(`Expected GPUVector ${p}`);bn(e,w,T.format,T.length,T.chunkLengths)}else throw new Error(`Undeclared binding ${p}`);s.set(p,w)}for(let p of this.operations){p instanceof Ye&&i.values.has(p.input)&&wo(i.values.get(p.input),i.values.get(p.output));for(let E of this.contracts.get(p)?.values??[]){let $=k(E.value);E.access!=="write"&&s.get($)instanceof H&&y.add($)}if(!(p instanceof Ve)){let E=this.contracts.get(p);for(let $ of E?.values??[]){let L=k($.value);if($.access!=="write"&&!s.has(L)&&!i.values.has(L)&&!u.has(L)&&!g.has(L))throw new Error(`Missing ${$.access==="read-write"?"read-write":"execution"} binding ${L}`)}for(let $ of E?.values??[]){let L=k($.value);$.access!=="read"&&this.scalars.some(_=>_.id===L)&&g.add(L)}for(let $ of E?.requiredFeatures??[])if(!e.features.has($))throw new Error(`Operation requires ${$}`);for(let $ of E?.values??[]){if($.access==="read")continue;let L=this.vectors.find(Qe=>Qe.id===k($.value));if(!L)continue;let _=s.get(L.id),W=h.get(L.id)??(_ instanceof H?_:void 0),j=$.shape,le=j&&"like"in j?d(k(j.like)):void 0;if(j&&"like"in j&&!le)throw new Error(`Missing shape input ${k(j.like)}`);let ne=le?le.chunkLengths:j&&"length"in j?j.chunkLengths??L.chunkLengths??[j.length]:L.chunkLengths??(L.length===void 0?void 0:[L.length]);if($.access==="read-write"&&!(_ instanceof H))throw new Error(`Missing read-write binding ${L.id}`);if($.access==="read-write"&&W!==_)throw new Error(`Read-write target must use its bound storage: ${L.id}`);if(y.has(L.id)&&W!==_)throw new Error(`Output target replaces an earlier read: ${L.id}`);if(!W&&!ne)throw new Error(`Cannot infer length of produced vector ${L.id}`);let Ze=ne?.reduce((Qe,ht)=>Qe+ht,0)??W.length;if(L.length!==void 0&&L.length!==Ze||j&&"length"in j&&j.length!==Ze)throw new Error(`Length constraint failed for ${L.id}`);if(L.chunkLengths&&ne&&(L.chunkLengths.length!==ne.length||L.chunkLengths.some((Qe,ht)=>Qe!==ne[ht])))throw new Error(`Chunk constraint failed for ${L.id}`);W?(bn(e,W,L.format,Ze,ne),Yo(L.id,W,s),s.set(L.id,W)):l(L.id,ne,L.format)}continue}let w=this.expressions.find(E=>E.operation===p),S=[];for(let E of w.references){if(s.get(E)===void 0&&!u.has(E)&&!w.gpuScalarInputs.includes(E))throw new Error(`Missing execution binding ${E}`);let L=d(E);L&&this.vectors.some(_=>_.id===E)&&S.push(L)}let T=this.vectors.find(E=>E.id===w.operation.output),v=S[0],b=T?v?.chunkLengths??T.chunkLengths??(T.length===void 0?void 0:[T.length]):[1];if(!b)throw new Error(`Cannot infer length of ${w.operation.output}`);for(let E of S)if(E.chunkLengths.length!==b.length||E.chunkLengths.some(($,L)=>$!==b[L]))throw new Error(`Expression ${w.operation.id} requires matching vector chunk boundaries`);let C=b.reduce((E,$)=>E+$,0);if(T?.length!==void 0&&T.length!==C)throw new Error(`Length constraint failed for ${T.id}`);if(T?.chunkLengths&&(T.chunkLengths.length!==b.length||T.chunkLengths.some((E,$)=>E!==b[$])))throw new Error(`Chunk constraint failed for ${T.id}`);let B=h.get(w.operation.output);B?(bn(e,B,w.format,C,b),Yo(w.operation.output,B,s),s.set(w.operation.output,B)):l(w.operation.output,b,w.format)}for(let p of Object.keys(n.outputTargets??{})){let w=this.outputs.includes(p)&&this.scalars.some(S=>S.id===p);if(!f.has(p)&&!m.has(p)&&!w&&!this.textures.some(S=>S.id===p&&S.role==="value"))throw new Error(`Unknown graph output target ${p}`)}for(let p of this.outputs)if(!(s.get(p)instanceof H)&&this.scalars.some(w=>w.id===p)){let w=h.get(p);if(w){bn(e,w,this.scalars.find(T=>T.id===p).format,1,[1]),Yo(p,w,s),s.set(p,w);continue}let S=Ys(e,p,[1],this.scalars.find(T=>T.id===p).format);a.add(S),s.set(p,S)}return new Xo(this,s,a,u,i)}catch(p){i.destroy();for(let w of a)w.destroy();throw p}}};function Xs(r,e){if(r instanceof q&&(r.type==="composite"||r instanceof lt&&!r.predicate)){let t=new Set,n=new Set;for(let o of r.operations){let i=(Xs(o,e)?.values??[]).filter(s=>e.some(a=>a.id===k(s.value)));for(let s of i){let a=k(s.value);s.access!=="write"&&!n.has(a)&&t.add(a)}for(let s of i)s.access!=="read"&&n.add(k(s.value))}return{values:[...new Set([...t,...n])].map(o=>({value:o,access:t.has(o)?n.has(o)?"read-write":"read":"write"}))}}return $e(r)?r.contract:void 0}var Xo=class{program;values;owned;transientVectors;textures;constructor(e,t,n,o=new Map,i){this.program=e,this.values=t,this.owned=n,this.transientVectors=o,this.textures=i}getOutputs(){let e=Object.create(null);for(let t of this.program.outputs){let n=this.textures?.values.get(t)??this.values.get(t);if(!(n instanceof H||n instanceof we.Texture||n instanceof we.TextureView))throw new Error(`Output ${t} has no materialized resource`);e[t]=n}return e}finish(){let e=this.getOutputs();for(let t of Object.values(e))t instanceof H&&this.owned.delete(t);return this.textures?.finish(this.program.outputs),this.destroy(),e}destroy(){this.textures?.destroy();for(let e of this.owned)e.destroy();this.owned.clear()}};function Ys(r,e,t,n="float32"){let o=[];try{for(let i of t)o.push(new Dt({buffer:r.createBuffer({byteLength:Math.max(1,i)*te(n).components*4,usage:we.Buffer.STORAGE|we.Buffer.VERTEX|we.Buffer.COPY_SRC|we.Buffer.COPY_DST}),format:n,length:i,ownsBuffer:!0}));return new H({type:"data",name:e,format:n,data:o,ownsData:!0})}catch(i){for(let s of o)s.destroy();throw i}}function bn(r,e,t,n,o){if(e.format!==t||n!==void 0&&e.length!==n)throw new Error(`Incompatible vector ${e.name}`);if(o&&(o.length!==e.data.length||o.some((s,a)=>s!==e.data[a].length)))throw new Error(`Incompatible chunks for ${e.name}`);let i=U(e.format).byteLength;for(let s of e.data)if(s.buffer.device!==r||s.byteStride!==i||s.byteOffset%4!==0||s.rowByteLength!==i)throw new Error(`Expression vector ${e.name} must contain packed 32-bit numeric chunks on the execution device`)}function Yo(r,e,t){let n=i=>i.buffer instanceof we.Buffer?i.buffer:i.buffer.buffer,o=new Map;for(let i of e.data){if(i.length===0)continue;let s=n(i),a=o.get(s)??[];a.push({start:i.byteOffset,end:i.byteOffset+i.length*i.byteStride}),o.set(s,a)}for(let i of o.values())if(i.sort((s,a)=>s.start-a.start),i.some((s,a)=>a>0&&s.start<i[a-1].end))throw new Error(`Output ${r} has overlapping writable chunks`);for(let[i,s]of t)if(i!==r&&s instanceof H&&s.data.some(a=>o.has(n(a))))throw new Error("Expression output targets must not alias inputs or earlier outputs")}var Qs=F(A(),1);var Ht={float32:"f32",sint32:"i32",uint32:"u32"};function Ks(r,e,t,n){if(e===t)return r;let o=Ht;if(t==="float32")return`${o.float32}(${r})`;if(e==="float32"){let s=n==="nearest"?`expression_round_nearest(${r})`:r;return`expression_to_${t}(${s})`}let i=t==="uint32"?`max(${r}, 0)`:`min(${r}, 2147483647u)`;return`${o[t]}(${i})`}var Zs=`
687
+ @compute @workgroup_size(1)fn main(){${dt(n,`select(0u,1u,${i})`)}}`;return[V({id:this.id,workload:{operation:"GPUPredicateConjunction",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:t.length*4,writeByteLength:4},resources:[{buffer:o,usage:"storage-write"}],compile:({device:a})=>{let u=new D(a,{id:this.id,source:s,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:c,getBuffer:d})=>{let l={gpuValues:d(o)};u.dispatch(c,{bindings:l,x:1,y:1,z:1})},destroy:()=>u.destroy()}}})]}};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 $e(r){let e=r;return typeof e.id=="string"&&typeof e.type=="string"}function jo(r){return r instanceof q?Object.freeze({id:r.id,type:r.type,...r.metadata?{metadata:r.metadata}:{},children:Object.freeze(r.operations.map(jo))}):$e(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 Ws(r){return typeof r.getCommandNodes=="function"}var zt=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"}},lt=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 n=e.minimumIterations??0;if(!Number.isSafeInteger(n)||n<0||n>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=n,this.lowering=e.lowering??"auto"}};function jt(r){let e=r.clone(),t=new Map([...e.scalars,...e.vectors,...e.textures].map(i=>[i.id,i])),n=new Set,o=(i,s=!1)=>{if(i instanceof q){for(let a of i.operations)o(a,s||i.type!=="composite");return}if($e(i))try{let a=i.contract;if(!a)return;let u=typeof a.outputs=="function"?a.outputs({getValue(d){let l=t.get(d);if(!l)throw new Error(`Undeclared operation value ${d}`);return l instanceof de?l.descriptor??M.texture({format:l.format,dimension:l.dimension,extent:{width:l.width,height:l.height,depth:l.depth},mipLevels:l.mipLevels,samples:l.samples}):l instanceof Ae?M.scalar(l.format):M.vector(l.format,{length:l.length,chunkLengths:l.chunkLengths})}}):a.outputs;for(let[d,l]of Object.entries(u??{})){if(!a.values.some(f=>f.access==="write"&&k(f.value)===d))throw new Error(`Operation result ${d} requires a write`);if(l.type==="texture"&&l.extent&&"like"in l.extent){let f=l.extent.like;if(!(t.get(f)instanceof de)||!a.values.some(m=>m.access!=="write"&&k(m.value)===f))throw new Error(`Texture extent source ${f} must be a declared texture read`)}let h=t.get(d);if(h?.role==="input"||h?.role==="state")throw new Error(`Operation result conflicts with ${h.role} ${d}`);if(h){if(h.format!==l.format||h instanceof Q!=(l.type==="vector")||h instanceof de!=(l.type==="texture"))throw new Error(`Incompatible operation result ${d}`);h instanceof Q&&l.type==="vector"&&t.set(d,e.constrainResult(h,l))}else{if(s)throw new Error("Operation results inside control flow require explicit declarations");let f=a.values.find(y=>k(y.value)===d&&y.access==="write")?.shape,m=l;if(l.type==="vector"&&l.length===void 0&&f){let y="like"in f?t.get(k(f.like)):void 0,g="length"in f?f:y instanceof Q?y:void 0;g?.length!==void 0&&(m={...l,length:g.length,chunkLengths:l.chunkLengths??g.chunkLengths})}let p=e.addDeclaration(d,m,"value");t.set(d,p)}}Rt(e,a);for(let d of a.values){let l=k(d.value),h=t.get(l);if(d.access!=="read"&&h?.role==="input")throw new Error(`Cannot write graph input ${l}`);if(d.access!=="write"&&h?.role==="value"&&!n.has(l))throw new Error(`Reads ${l} before it is produced`)}let c=new Set(a.values.filter(d=>d.access!=="read").map(d=>k(d.value)));for(let d of c){if(t.get(d)?.role==="value"&&n.has(d))throw new Error(`Multiple writers for graph result ${d}`);n.add(d)}}catch(a){throw new Error(`${i.id}: ${a instanceof Error?a.message:String(a)}`,{cause:a})}};return e.operations.forEach(i=>o(i)),e}function vr(r,e={}){let t=[];try{r=jt(r)}catch(i){return{valid:!1,issues:[{level:"error",code:"invalid-operation-contract",message:i instanceof Error?i.message:String(i)}]}}for(let i of r.scalars)i.role==="input"&&e.scalars?.[i.id]===void 0&&t.push({level:"error",code:"missing-input",valueId:i.id,message:`Missing input binding ${i.id}`}),i.role==="value"&&e.scalars?.[i.id]!==void 0&&t.push({level:"error",code:"result-binding",valueId:i.id,message:`Cannot initialize graph result ${i.id}`});let n=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 o=i=>{let s="id"in i&&typeof i.id=="string"?i.id:void 0;if($e(i))try{let a=i.contract;a&&Rt(r,a)}catch(a){t.push({level:"error",code:"invalid-operation-contract",operationId:s,message:`${s}: ${a instanceof Error?a.message:String(a)}`})}if(i instanceof zt||i instanceof lt){let a=i.predicate;a?.source==="gpu"&&(a.value.format!=="uint32"&&t.push({level:"error",code:"invalid-predicate-format",operationId:s,valueId:a.value.id,message:`GPU predicate "${a.id}" must use uint32 state`}),n.has(a.value.id)||t.push({level:"error",code:"missing-predicate-scalar",operationId:s,valueId:a.value.id,message:`GPU predicate "${a.id}" references undeclared scalar "${a.value.id}"`}))}if(i instanceof q)for(let a of i.operations)o(a)};for(let i of r.operations)o(i);return Object.freeze({valid:!t.some(i=>i.level==="error"),issues:Object.freeze(t.map(i=>Object.freeze({...i})))})}var St=class{device;capabilities;lowerings;compactionIndex=0;aggregationIndex=0;constructor(e,t=[]){this.device=e,this.capabilities=Object.freeze({backend:"webgpu",gpuConditionals:!0,nativeLoops:!1,childGraphs:!1});let n=[...this.createCoreLowerings(),...t],o=new Set;for(let i of n){if(!i.type||o.has(i.type))throw new Error(`Duplicate or empty lowering type: ${i.type}`);o.add(i.type)}this.lowerings=Object.freeze(n.map(i=>Object.freeze({type:i.type,lower:i.lower.bind(i)})))}compile(e,t={}){this.compactionIndex=0,this.aggregationIndex=0,e=e.clone();for(let f of e.vectors){let m=t.vectors?.[f.id];if(!f.external||!m||f.chunkLengths)continue;let p="data"in m?m.data:"buffer"in m?[m]:m;e.constrainResult(f,{type:"vector",format:f.format,chunkLengths:p.map(y=>y.length)})}e=jt(e);let n=new Map,o=(f,m)=>{n.set(f,(n.get(f)??0)|m)},i=f=>{f instanceof q?f.operations.forEach(i):f instanceof qe?o(f.output,se.Buffer.COPY_DST):f instanceof Ye&&(o(f.input,se.Buffer.COPY_SRC),o(f.output,se.Buffer.COPY_DST))};e.operations.forEach(i);let s=vr(e,t);if(!s.valid)throw new Error(`GPUGraph "${e.id}" validation failed: ${s.issues.filter(f=>f.level==="error").map(f=>f.message).join("; ")}`);let a=new rn(this.device,{id:`${e.id}-commands`}),u=new Map;for(let f of e.scalars)u.set(f.id,No(a,f.id,f.format));for(let[f,m]of Object.entries(t.scalars??{})){let p=u.get(f);if(!p)throw new Error(`Undeclared scalar binding ${f}`);let y=p.view;a.addCopyPass({id:`${f}-binding`,resources:[{buffer:y,usage:"copy-destination"}],compile:({device:g})=>{let w=p.format==="float32"?new Float32Array([m]):p.format==="uint32"?new Uint32Array([m]):new Int32Array([m]),S=g.createBuffer({data:w,usage:se.Buffer.COPY_SRC});return{encode:({commandEncoder:T,getBuffer:v})=>T.copyBufferToBuffer({sourceBuffer:S,destinationBuffer:v(y),destinationOffset:y.byteOffset,size:4}),destroy:()=>S.destroy()}}})}let c=new Map;for(let f of e.vectors){if(f.length===void 0)throw new Error(`${f.id}: bind dynamic dimensions through program.compile(device).run(bindings)`);let m;if(f.external){let p=t.vectors[f.id],y="data"in p?p:{format:f.format,length:f.length,data:"buffer"in p?[p]:p};if(m=a.importGPUVector(f.id,y),m.format!==f.format||m.length!==f.length)throw new Error(`${f.id} binding format and length must match its logical vector`);if(f.chunkLengths&&(f.chunkLengths.length!==m.data.length||f.chunkLengths.some((g,w)=>g!==m.data[w].length)))throw new Error(`${f.id} binding must preserve its declared chunk topology`)}else{let p=f.chunkLengths??Uc(f.length,this.device,U(f.format).byteLength),y=p.map((w,S)=>z(a,p.length===1?f.id:`${f.id}-chunk-${S}`,f.format,w,f.role==="value"?se.Buffer.STORAGE|se.Buffer.VERTEX|se.Buffer.COPY_SRC|se.Buffer.COPY_DST:se.Buffer.STORAGE|(n.get(f.id)??0))),g=U(f.format);m=new O({id:f.id,name:f.id,format:f.format,length:f.length,valueLength:f.length,stride:g.components,byteStride:g.byteLength,rowByteLength:g.byteLength,data:y})}c.set(f.id,m)}let d=new Map,l=new Map;for(let f of e.textures){(0,se.assert)(f.width!==void 0&&f.height!==void 0);let m=t.textures?.[f.id],p={...f,width:f.width,height:f.height};if(m instanceof se.TextureView){let g=ee(m);(0,se.assert)(g.format===f.format&&g.width===f.width&&g.height===f.height),l.set(f.id,m),m=g.texture,p={...p,dimension:m.dimension,width:m.width,height:m.height,depth:m.depth,mipLevels:m.mipLevels,samples:m.samples}}let y=f.external?a.importTexture(p,m):a.createTransientTexture(p);d.set(f.id,y)}let h={path:[],nodes:[],decisions:[],predicates:[],scalars:u,vectors:c,textures:d,textureValues:e.textures,textureViews:l,predicateConjunctions:new Map,commandNodeIds:new Set,transientResultNames:new Set(e.vectors.filter(f=>f.role==="value"&&!f.external).map(f=>f.id)),retainedBuffers:[]};for(let f of e.operations)this.lower(a,f,h);return Object.freeze({program:e,graph:a,scalars:u,vectors:c,textures:d,validation:s,lowering:Object.freeze({operations:e.operationTree,nodes:Object.freeze(h.nodes.map(f=>Object.freeze({...f,operationPath:Object.freeze([...f.operationPath])}))),decisions:Object.freeze(h.decisions.map(f=>Object.freeze({...f})))})})}createCoreLowerings(){return[{type:"vector-upload",lower:gs},{type:"vector-copy",lower:ys},{type:"group-aggregation",lower:(e,t)=>{let{props:n}=e,o=`${e.id}-${this.aggregationIndex++}`,i=t.resolveVector(n.keys),s=n.mask?t.resolveVector(n.mask):void 0;n.operation==="count"?t.graph.add(new br({id:o,keys:i,mask:s,operation:"count",output:Wo(t.resolveVector(n.output))})):t.graph.add(new br({id:o,keys:i,mask:s,operation:n.operation,values:t.resolveVector(n.values),output:Wo(t.resolveVector(n.output))}))}},{type:"reduction",lower:(e,t)=>{let{props:n}=e;t.graph.add(new Jr({id:`${e.id}-${this.aggregationIndex++}`,input:t.resolveVector(n.input),mask:n.mask?t.resolveVector(n.mask):void 0,operation:n.operation,output:Wo(t.resolveVector(n.output))}))}},{type:"compaction",lower:(e,t)=>{let{input:n,flags:o,output:i,count:s}=e.props;t.graph.add(new tn({id:`${e.id}-${this.compactionIndex++}`,input:t.resolveVector(n),flags:t.resolveVector(o),output:t.resolveVector(i),count:t.resolveScalar(s).view}))}},{type:"scalar-literal",lower:(e,t)=>{let n=new Vt({id:e.id,output:t.resolveScalar(e.props.output),value:e.props.value});this.emitProducer(t.graph,n,[[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"})}},{type:"scalar-operation",lower:(e,t)=>{let n=new an({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,n,[[1,1,1]]),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-scalar-kernel",reason:"scalar operation lowers to one compute command node"})}},{type:"vector-madd",lower:(e,t)=>{let n=e.props,o=new cn({id:e.id,input:t.resolveVector(n.input),scale:t.resolveScalar(n.scale),addend:t.resolveVector(n.addend),output:t.resolveVector(n.output)});this.emitProducer(t.graph,o),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-vector-madd",reason:"dense float32 MADD lowers through explicit command nodes"})}},{type:"dot-product",lower:(e,t)=>{let n=e.props,o=new ln({id:e.id,left:t.resolveVector(n.left),right:t.resolveVector(n.right),output:t.resolveScalar(n.output)});this.emitProducer(t.graph,o),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-hierarchical-dot",reason:"chunk dot products use bounded hierarchical reductions into the scalar arena"})}},{type:"spmv",lower:(e,t)=>{let n=e.props,o=n.matrix,i=new mn({id:e.id,rowOffsets:t.resolveVector(o.rowOffsets),columnIndices:t.resolveVector(o.columnIndices),values:t.resolveVector(o.values),vector:t.resolveVector(n.vector),output:t.resolveVector(n.output),columns:o.columns,statistics:o.statistics,strategy:n.strategy}),s=i.getStrategy(t.graph);this.emitProducer(t.graph,i),t.recordDecision({operationId:e.id,operationType:e.type,lowering:`webgpu-spmv:${s.id}`,reason:s.reason})}},{type:"conditional",lower:(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 n of e.operations)t.lowerConditional(e.predicate,n)}},{type:"loop",lower:(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 n=0;n<e.maximumIterations;n++)for(let o of e.operations)t.lower(o);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 n=0;n<e.maximumIterations;n++){let o=n>=e.minimumIterations;for(let i of e.operations)o?t.lowerConditional(e.predicate,i):t.lower(i)}}}]}lower(e,t,n){let o="id"in t&&typeof t.id=="string"?t.id:t.constructor?.name??"command-node-producer";n.path.push(o);let i=n.retainedBuffers,s=[...i];if($e(t))for(let a of t.contract?.values??[]){let u=typeof a.value=="string"?a.value:a.value.id;if(n.transientResultNames.has(u))for(let c of n.vectors.get(u).data)s.push(c.buffer)}n.retainedBuffers=s;try{if(t instanceof q&&t.type==="composite"){n.decisions.push({operationId:t.id,operationType:t.type,lowering:"flatten",reason:"WebGPU has no executable child-graph primitive"});for(let a of t.operations)this.lower(e,a,n);return}if($e(t)){for(let u of t.contract?.requiredFeatures??[])if(!this.device.features.has(u))throw new Error(`${o} requires ${u}`);let a=this.lowerings.find(u=>u.type===t.type)?.lower;if(a){let u=()=>(t instanceof Ye&&n.textureValues.some(c=>c.id===t.input)?bs:a)(t,{graph:e,capabilities:this.capabilities,lower:c=>this.lower(e,c,n),lowerConditional:(c,d)=>{n.predicates.push(c);try{this.lower(e,d,n)}finally{n.predicates.pop()}},resolveScalar:c=>this.resolveScalar(c,n),resolveVector:c=>this.resolveVector(c,n),resolveTexture:c=>this.resolveTexture(c,n),resolveTextureView:c=>{let d=c instanceof Fe?c.texture:c,l=c instanceof Fe?c.props:{},h=n.textureViews.get(typeof d=="string"?d:d.id);return e.createTextureView(this.resolveTexture(d,n),h?hs(h,l):l)},recordDecision:c=>n.decisions.push(c)});t instanceof zt||t instanceof lt?u():this.withNodeDecoration(e,n,u);return}}if("getNodes"in t||Ws(t)){n.decisions.push({operationId:o,operationType:"command-node-producer",lowering:"explicit-command-nodes",reason:"execution primitive constructs explicit command nodes"}),this.withNodeDecoration(e,n,()=>e.add(t));return}throw new Error(`GPUGraph operation "${o}" has no WebGPU lowering`)}finally{n.retainedBuffers=i,n.path.pop()}}emitProducer(e,t,n){let o=t.getCommandNodes(e);if(!n){He(e,o);return}if(o.length!==n.length)throw new Error(`lowering produced ${o.length} command nodes but declared ${n.length} dispatches`);let i=o.map((s,a)=>this.attachDispatch(s,n[a]));He(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 N(e,t)}withNodeDecoration(e,t,n){return e.withComputeLowering(o=>this.decorateComputeNode(e,o,t),()=>e.withOtherLowering(o=>{if(t.predicates.length)throw new Error(`GPU predicates do not support ${o.type} node "${o.id}"`);let i=this.makeCommandNodeIdUnique(o,t);return t.nodes.push({nodeId:i.id,nodeType:i.type,operationPath:[...t.path]}),{...i,retainedBuffers:t.retainedBuffers}},n))}decorateComputeNode(e,t,n){if(t={...this.makeCommandNodeIdUnique(t,n),retainedBuffers:n.retainedBuffers},n.path.length&&n.nodes.push({nodeId:t.id,nodeType:"compute",operationPath:[...n.path]}),!n.predicates.length)return t;if(t.condition)throw new Error(`compute node "${t.id}" already has condition`);let o=Qr(t);if(!o)throw new Error(`compute node "${t.id}" under runtime predicate must declare exact dispatch geometry`);let i;if(n.predicates.length===1)i=n.scalars.get(n.predicates[0].value.id);else{let u=n.predicates.map(h=>h.value.id).join("&&"),c=n.predicateConjunctions.get(u);c||(c=No(e,`predicate-and-${n.predicateConjunctions.size}`,"uint32"),n.predicateConjunctions.set(u,c));let d=n.predicates.map(h=>n.scalars.get(h.value.id)),l=new pn({id:`${t.id}-predicate-and`,inputs:d,output:c}).getCommandNodes(e).map(h=>this.attachDispatch(h,[1,1,1]));e.withoutComputeLowering(()=>He(e,l)),i=c}if(!i)throw new Error(`runtime predicate for "${t.id}" could not be resolved`);let s=new Tr(e,{id:`${t.id}-predicate`,active:i,workgroups:o}),a=s.getUpdateCommandNodes(e,`${t.id}-predicate-update`).map(u=>this.attachDispatch(u,[1,1,1]));return e.withoutComputeLowering(()=>He(e,a)),{...t,condition:s.condition}}makeCommandNodeIdUnique(e,t){if(!t.commandNodeIds.has(e.id))return t.commandNodeIds.add(e.id),e;let n=1,o=`${e.id}-iteration-${n}`;for(;t.commandNodeIds.has(o);)n++,o=`${e.id}-iteration-${n}`;return t.commandNodeIds.add(o),{...e,id:o}}resolveTexture(e,t){let n=typeof e=="string"?e:e.id;if(typeof e=="string"?!t.textures.has(n):!t.textureValues.includes(e))throw new Error(`Undeclared program texture "${n}"`);return t.textures.get(n)}resolveScalar(e,t){let n=typeof e=="string"?e:e.id,o=t.scalars.get(n);if(!o||typeof e!="string"&&o.format!==e.format)throw new Error(`GPUGraph scalar "${n}" is not part of compilation`);return o}resolveVector(e,t){let n=typeof e=="string"?e:e.id,o=t.vectors.get(n);if(!o||typeof e!="string"&&(o.format!==e.format||e.length!==void 0&&o.length!==e.length))throw new Error(`GPUGraph vector "${n}" is not part of compilation`);return o}};function Uc(r,e,t){let n=Math.floor(e.limits.maxStorageBufferBindingSize/t);if(n<1||r<=n)return[r];let o=[];for(let i=0;i<r;i+=n)o.push(Math.min(n,r-i));return o}function Wo(r){return(0,se.assert)(r.data.length===1),r.data[0]}var we=F(A(),1);var Et=F(A(),1);var ft=class{type="shader-pass";id;fragmentSource;inputs;samplers;parameters;output;outputDescriptor;constructor(e){this.id=e.id??`${e.output}-shader-pass`,this.fragmentSource=e.fragmentSource,this.inputs=Object.freeze({...e.inputs}),this.parameters=Object.freeze({...e.parameters}),this.samplers=Object.freeze(Object.fromEntries(Object.entries(e.samplers??{}).map(([o,i])=>[o,Object.freeze({...i})]))),this.output=e.output;let t=e.outputDescriptor;(0,Et.assert)(t.extent&&(t.dimension??"2d")==="2d"&&(t.mipLevels??1)===1&&(t.samples??1)===1),this.outputDescriptor=M.texture({...t,dimension:"2d",mipLevels:1,samples:1});let n=[...Object.keys(this.inputs),...Object.keys(this.samplers)];(0,Et.assert)(new Set(n).size===n.length);for(let o of[...n,...Object.keys(this.parameters)])(0,Et.assert)(/^[A-Za-z][A-Za-z0-9_]*$/.test(o)&&!["parameters","shade","vertexMain","fragmentMain"].includes(o)&&!o.startsWith("GraphShaderPass"));for(let o of Object.values(this.samplers))(0,Et.assert)((o.type??"color-sampler")==="color-sampler")}get contract(){return{values:[...Object.values(this.inputs).map(e=>({value:e,access:"read",textureUsage:"sampled"})),...Object.values(this.parameters).map(e=>({value:e,access:"read"})),{value:this.output,access:"write",textureUsage:"render-attachment"}],outputs:({getValue:e})=>{for(let t of Object.values(this.inputs)){let n=e(t);(0,Et.assert)(n.type==="texture"&&(n.dimension??"2d")==="2d"&&(n.samples??1)===1)}for(let t of Object.values(this.parameters))(0,Et.assert)(e(t).type==="scalar");return{[this.output]:this.outputDescriptor}}}}};function Hs(r,e){if(r)try{r.error(e instanceof Error?e.message:String(e),e)()}catch{}}var Gc=class{add(r,e,t){if(typeof arguments[0]!="string")for(let n in arguments[0])this.add(n,arguments[0][n],arguments[1]);else(Array.isArray(r)?r:[r]).forEach(function(n){this[n]=this[n]||[],e&&this[n][t?"unshift":"push"](e)},this)}run(r,e){this[r]=this[r]||[],this[r].forEach(function(t){t.call(e&&e.context?e.context:e,e)})}},Dc=class{constructor(r){this.jsep=r,this.registered={}}register(...r){r.forEach(e=>{if(typeof e!="object"||!e.name||!e.init)throw new Error("Invalid JSEP plugin format");this.registered[e.name]||(e.init(this.jsep),this.registered[e.name]=e)})}},xe=class x{static get version(){return"1.4.0"}static toString(){return"JavaScript Expression Parser (JSEP) v"+x.version}static addUnaryOp(e){return x.max_unop_len=Math.max(e.length,x.max_unop_len),x.unary_ops[e]=1,x}static addBinaryOp(e,t,n){return x.max_binop_len=Math.max(e.length,x.max_binop_len),x.binary_ops[e]=t,n?x.right_associative.add(e):x.right_associative.delete(e),x}static addIdentifierChar(e){return x.additional_identifier_chars.add(e),x}static addLiteral(e,t){return x.literals[e]=t,x}static removeUnaryOp(e){return delete x.unary_ops[e],e.length===x.max_unop_len&&(x.max_unop_len=x.getMaxKeyLen(x.unary_ops)),x}static removeAllUnaryOps(){return x.unary_ops={},x.max_unop_len=0,x}static removeIdentifierChar(e){return x.additional_identifier_chars.delete(e),x}static removeBinaryOp(e){return delete x.binary_ops[e],e.length===x.max_binop_len&&(x.max_binop_len=x.getMaxKeyLen(x.binary_ops)),x.right_associative.delete(e),x}static removeAllBinaryOps(){return x.binary_ops={},x.max_binop_len=0,x}static removeLiteral(e){return delete x.literals[e],x}static removeAllLiterals(){return x.literals={},x}get char(){return this.expr.charAt(this.index)}get code(){return this.expr.charCodeAt(this.index)}constructor(e){this.expr=e,this.index=0}static parse(e){return new x(e).parse()}static getMaxKeyLen(e){return Math.max(0,...Object.keys(e).map(t=>t.length))}static isDecimalDigit(e){return e>=48&&e<=57}static binaryPrecedence(e){return x.binary_ops[e]||0}static isIdentifierStart(e){return e>=65&&e<=90||e>=97&&e<=122||e>=128&&!x.binary_ops[String.fromCharCode(e)]||x.additional_identifier_chars.has(String.fromCharCode(e))}static isIdentifierPart(e){return x.isIdentifierStart(e)||x.isDecimalDigit(e)}throwError(e){let t=new Error(e+" at character "+this.index);throw t.index=this.index,t.description=e,t}runHook(e,t){if(x.hooks[e]){let n={context:this,node:t};return x.hooks.run(e,n),n.node}return t}searchHook(e){if(x.hooks[e]){let t={context:this};return x.hooks[e].find(function(n){return n.call(t.context,t),t.node}),t.node}}gobbleSpaces(){let e=this.code;for(;e===x.SPACE_CODE||e===x.TAB_CODE||e===x.LF_CODE||e===x.CR_CODE;)e=this.expr.charCodeAt(++this.index);this.runHook("gobble-spaces")}parse(){this.runHook("before-all");let e=this.gobbleExpressions(),t=e.length===1?e[0]:{type:x.COMPOUND,body:e};return this.runHook("after-all",t)}gobbleExpressions(e){let t=[],n,o;for(;this.index<this.expr.length;)if(n=this.code,n===x.SEMCOL_CODE||n===x.COMMA_CODE)this.index++;else if(o=this.gobbleExpression())t.push(o);else if(this.index<this.expr.length){if(n===e)break;this.throwError('Unexpected "'+this.char+'"')}return t}gobbleExpression(){let e=this.searchHook("gobble-expression")||this.gobbleBinaryExpression();return this.gobbleSpaces(),this.runHook("after-expression",e)}gobbleBinaryOp(){this.gobbleSpaces();let e=this.expr.substr(this.index,x.max_binop_len),t=e.length;for(;t>0;){if(x.binary_ops.hasOwnProperty(e)&&(!x.isIdentifierStart(this.code)||this.index+e.length<this.expr.length&&!x.isIdentifierPart(this.expr.charCodeAt(this.index+e.length))))return this.index+=t,e;e=e.substr(0,--t)}return!1}gobbleBinaryExpression(){let e,t,n,o,i,s,a,u,c;if(s=this.gobbleToken(),!s||(t=this.gobbleBinaryOp(),!t))return s;for(i={value:t,prec:x.binaryPrecedence(t),right_a:x.right_associative.has(t)},a=this.gobbleToken(),a||this.throwError("Expected expression after "+t),o=[s,i,a];t=this.gobbleBinaryOp();){if(n=x.binaryPrecedence(t),n===0){this.index-=t.length;break}i={value:t,prec:n,right_a:x.right_associative.has(t)},c=t;let d=l=>i.right_a&&l.right_a?n>l.prec:n<=l.prec;for(;o.length>2&&d(o[o.length-2]);)a=o.pop(),t=o.pop().value,s=o.pop(),e={type:x.BINARY_EXP,operator:t,left:s,right:a},o.push(e);e=this.gobbleToken(),e||this.throwError("Expected expression after "+c),o.push(i,e)}for(u=o.length-1,e=o[u];u>1;)e={type:x.BINARY_EXP,operator:o[u-1].value,left:o[u-2],right:e},u-=2;return e}gobbleToken(){let e,t,n,o;if(this.gobbleSpaces(),o=this.searchHook("gobble-token"),o)return this.runHook("after-token",o);if(e=this.code,x.isDecimalDigit(e)||e===x.PERIOD_CODE)return this.gobbleNumericLiteral();if(e===x.SQUOTE_CODE||e===x.DQUOTE_CODE)o=this.gobbleStringLiteral();else if(e===x.OBRACK_CODE)o=this.gobbleArray();else{for(t=this.expr.substr(this.index,x.max_unop_len),n=t.length;n>0;){if(x.unary_ops.hasOwnProperty(t)&&(!x.isIdentifierStart(this.code)||this.index+t.length<this.expr.length&&!x.isIdentifierPart(this.expr.charCodeAt(this.index+t.length)))){this.index+=n;let i=this.gobbleToken();return i||this.throwError("missing unaryOp argument"),this.runHook("after-token",{type:x.UNARY_EXP,operator:t,argument:i,prefix:!0})}t=t.substr(0,--n)}x.isIdentifierStart(e)?(o=this.gobbleIdentifier(),x.literals.hasOwnProperty(o.name)?o={type:x.LITERAL,value:x.literals[o.name],raw:o.name}:o.name===x.this_str&&(o={type:x.THIS_EXP})):e===x.OPAREN_CODE&&(o=this.gobbleGroup())}return o?(o=this.gobbleTokenProperty(o),this.runHook("after-token",o)):this.runHook("after-token",!1)}gobbleTokenProperty(e){this.gobbleSpaces();let t=this.code;for(;t===x.PERIOD_CODE||t===x.OBRACK_CODE||t===x.OPAREN_CODE||t===x.QUMARK_CODE;){let n;if(t===x.QUMARK_CODE){if(this.expr.charCodeAt(this.index+1)!==x.PERIOD_CODE)break;n=!0,this.index+=2,this.gobbleSpaces(),t=this.code}this.index++,t===x.OBRACK_CODE?(e={type:x.MEMBER_EXP,computed:!0,object:e,property:this.gobbleExpression()},e.property||this.throwError('Unexpected "'+this.char+'"'),this.gobbleSpaces(),t=this.code,t!==x.CBRACK_CODE&&this.throwError("Unclosed ["),this.index++):t===x.OPAREN_CODE?e={type:x.CALL_EXP,arguments:this.gobbleArguments(x.CPAREN_CODE),callee:e}:(t===x.PERIOD_CODE||n)&&(n&&this.index--,this.gobbleSpaces(),e={type:x.MEMBER_EXP,computed:!1,object:e,property:this.gobbleIdentifier()}),n&&(e.optional=!0),this.gobbleSpaces(),t=this.code}return e}gobbleNumericLiteral(){let e="",t,n;for(;x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);if(this.code===x.PERIOD_CODE)for(e+=this.expr.charAt(this.index++);x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);if(t=this.char,t==="e"||t==="E"){for(e+=this.expr.charAt(this.index++),t=this.char,(t==="+"||t==="-")&&(e+=this.expr.charAt(this.index++));x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);x.isDecimalDigit(this.expr.charCodeAt(this.index-1))||this.throwError("Expected exponent ("+e+this.char+")")}return n=this.code,x.isIdentifierStart(n)?this.throwError("Variable names cannot start with a number ("+e+this.char+")"):(n===x.PERIOD_CODE||e.length===1&&e.charCodeAt(0)===x.PERIOD_CODE)&&this.throwError("Unexpected period"),{type:x.LITERAL,value:parseFloat(e),raw:e}}gobbleStringLiteral(){let e="",t=this.index,n=this.expr.charAt(this.index++),o=!1;for(;this.index<this.expr.length;){let i=this.expr.charAt(this.index++);if(i===n){o=!0;break}else if(i==="\\")switch(i=this.expr.charAt(this.index++),i){case"n":e+=`
688
+ `;break;case"r":e+="\r";break;case"t":e+=" ";break;case"b":e+="\b";break;case"f":e+="\f";break;case"v":e+="\v";break;default:e+=i}else e+=i}return o||this.throwError('Unclosed quote after "'+e+'"'),{type:x.LITERAL,value:e,raw:this.expr.substring(t,this.index)}}gobbleIdentifier(){let e=this.code,t=this.index;for(x.isIdentifierStart(e)?this.index++:this.throwError("Unexpected "+this.char);this.index<this.expr.length&&(e=this.code,x.isIdentifierPart(e));)this.index++;return{type:x.IDENTIFIER,name:this.expr.slice(t,this.index)}}gobbleArguments(e){let t=[],n=!1,o=0;for(;this.index<this.expr.length;){this.gobbleSpaces();let i=this.code;if(i===e){n=!0,this.index++,e===x.CPAREN_CODE&&o&&o>=t.length&&this.throwError("Unexpected token "+String.fromCharCode(e));break}else if(i===x.COMMA_CODE){if(this.index++,o++,o!==t.length){if(e===x.CPAREN_CODE)this.throwError("Unexpected token ,");else if(e===x.CBRACK_CODE)for(let s=t.length;s<o;s++)t.push(null)}}else if(t.length!==o&&o!==0)this.throwError("Expected comma");else{let s=this.gobbleExpression();(!s||s.type===x.COMPOUND)&&this.throwError("Expected comma"),t.push(s)}}return n||this.throwError("Expected "+String.fromCharCode(e)),t}gobbleGroup(){this.index++;let e=this.gobbleExpressions(x.CPAREN_CODE);if(this.code===x.CPAREN_CODE)return this.index++,e.length===1?e[0]:e.length?{type:x.SEQUENCE_EXP,expressions:e}:!1;this.throwError("Unclosed (")}gobbleArray(){return this.index++,{type:x.ARRAY_EXP,elements:this.gobbleArguments(x.CBRACK_CODE)}}},_c=new Gc;Object.assign(xe,{hooks:_c,plugins:new Dc(xe),COMPOUND:"Compound",SEQUENCE_EXP:"SequenceExpression",IDENTIFIER:"Identifier",MEMBER_EXP:"MemberExpression",LITERAL:"Literal",THIS_EXP:"ThisExpression",CALL_EXP:"CallExpression",UNARY_EXP:"UnaryExpression",BINARY_EXP:"BinaryExpression",ARRAY_EXP:"ArrayExpression",TAB_CODE:9,LF_CODE:10,CR_CODE:13,SPACE_CODE:32,PERIOD_CODE:46,COMMA_CODE:44,SQUOTE_CODE:39,DQUOTE_CODE:34,OPAREN_CODE:40,CPAREN_CODE:41,OBRACK_CODE:91,CBRACK_CODE:93,QUMARK_CODE:63,SEMCOL_CODE:59,COLON_CODE:58,unary_ops:{"-":1,"!":1,"~":1,"+":1},binary_ops:{"||":1,"??":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":10,"/":10,"%":10,"**":11},right_associative:new Set(["**"]),additional_identifier_chars:new Set(["$","_"]),literals:{true:!0,false:!1,null:null},this_str:"this"});xe.max_unop_len=xe.getMaxKeyLen(xe.unary_ops);xe.max_binop_len=xe.getMaxKeyLen(xe.binary_ops);var Sr=r=>new xe(r).parse(),Ac=Object.getOwnPropertyNames(class{});Object.getOwnPropertyNames(xe).filter(r=>!Ac.includes(r)&&Sr[r]===void 0).forEach(r=>{Sr[r]=xe[r]});Sr.Jsep=xe;var Fc="ConditionalExpression",Rc={name:"ternary",init(r){r.hooks.add("after-expression",function(t){if(t.node&&this.code===r.QUMARK_CODE){this.index++;let n=t.node,o=this.gobbleExpression();if(o||this.throwError("Expected expression"),this.gobbleSpaces(),this.code===r.COLON_CODE){this.index++;let i=this.gobbleExpression();if(i||this.throwError("Expected expression"),t.node={type:Fc,test:n,consequent:o,alternate:i},n.operator&&r.binary_ops[n.operator]<=.9){let s=n;for(;s.right.operator&&r.binary_ops[s.right.operator]<=.9;)s=s.right;t.node.test=s.right,s.right=t.node,t.node=n}}else this.throwError("Expected :")}})}};Sr.plugins.register(Rc);var qs=Sr;var Vc=qs;function Ho(r,e){try{return typeof r=="string"?Vc(r):r}catch(t){throw Hs(e?.log,t),t}}var Ve=class{get contract(){let e=gn(this.expression),t=yn(e);return{outputs:({getValue:n})=>{let o=t.map(a=>{let u=n(a);if(u.type==="texture")throw new Error("Numeric expressions cannot read textures");return[a,u]}),i=he(e,new Map(o.map(([a,u])=>[a,u.format]))),s=o.some(([,a])=>a.type==="vector");return{[this.output]:s||!Ys(i)?M.vector(i,s?{}:{length:1}):M.scalar(i)}},values:[...yn(gn(this.expression)).map(n=>({value:n,access:"read"})),{value:this.output,access:"write"}]}}type="expression";id;output;expression;integerRounding;constructor(e){this.id=e.id??`${e.output}-expression`,this.output=e.output,this.expression=e.expression,this.integerRounding=e.integerRounding??"truncate"}};function qo(r){return/^(float32|sint32|uint32)(x[234])?$/.test(r)}function te(r){let e=U(r);return{components:e.components,componentType:e.signedDataType}}function Er(r,e){return e===1?r:`${r}x${e}`}function gn(r){let e=t=>{let n=t;switch(n.type){case"Identifier":return{kind:"reference",name:n.name};case"Literal":if(typeof n.value=="number"&&Number.isFinite(Math.fround(n.value)))return{kind:"literal",value:n.value};break;case"UnaryExpression":if(n.operator==="-")return{kind:"negate",argument:e(n.argument)};break;case"MemberExpression":{let o=n.property;if(n.computed||o.type!=="Identifier")throw new Error("Computed component access is unsupported");if(!/^[xyzw]{1,4}$/.test(o.name))throw new Error(`Invalid swizzle .${o.name}: expected 1\u20134 xyzw components`);return{kind:"swizzle",argument:e(n.object),components:[...o.name].map(i=>"xyzw".indexOf(i))}}case"CallExpression":{let o=n.callee;if(o.type!=="Identifier")break;let i=o.name;if(/^vec[234]$/.test(i)){if(n.arguments.length<1||n.arguments.length>4)throw new Error(`${i}: expected 1\u20134 arguments, received ${n.arguments.length}`);return{kind:"construct",width:Number(i[3]),arguments:n.arguments.map(e)}}if(Ys(i)){if(n.arguments.length!==1)throw new Error(`Invalid argument count for ${i}`);return{kind:"cast",format:i,argument:e(n.arguments[0])}}if(!["abs","sqrt","pow","sin","cos","tan","exp","log","dot","length","equalAll","select"].includes(i))break;let s=i==="select"?3:["pow","dot","equalAll"].includes(i)?2:1;if(n.arguments.length!==s)throw new Error(`Invalid argument count for GPU expression function ${i}`);return{kind:"call",name:i,arguments:n.arguments.map(e)}}case"BinaryExpression":if(["+","-","*","/"].includes(n.operator))return{kind:"binary",operator:n.operator,left:e(n.left),right:e(n.right)};break}throw new Error(`Unsupported GPU expression syntax: ${n.type}`)};return e(typeof r=="string"?Ho(r):r)}function yn(r){let e=new Set,t=n=>{switch(n.kind){case"reference":e.add(n.name);break;case"swizzle":case"cast":case"negate":t(n.argument);break;case"construct":case"call":n.arguments.forEach(t);break;case"binary":t(n.left),t(n.right);break}};return t(r),[...e]}function Ys(r){return r==="float32"||r==="sint32"||r==="uint32"}function he(r,e){switch(r.kind){case"literal":return"float32";case"reference":{let t=e.get(r.name);if(!t)throw new Error(`Undeclared numeric input ${r.name}`);return t}case"swizzle":{let t=te(he(r.argument,e)),n=Math.max(...r.components)+1;if(n>t.components){let o=r.components.map(s=>"xyzw"[s]).join(""),i=r.argument.kind==="reference"?r.argument.name:"input";throw new Error(`.${o} needs ${n} components; ${i} has ${t.components}`)}return Er(t.componentType,r.components.length)}case"construct":{let t=r.arguments.map(i=>te(he(i,e))),n=t[0].componentType;if(t.some(i=>i.componentType!==n))throw new Error(`vec${r.width}: mixed component types (${t.map(i=>i.componentType).join(", ")})`);let o=t.reduce((i,s)=>i+s.components,0);if(!(t.length===1&&o===1)&&o!==r.width)throw new Error(`vec${r.width}(...) needs ${r.width} components; received ${o}`);return Er(n,r.width)}case"cast":return Er(r.format,te(he(r.argument,e)).components);default:{let n=(r.kind==="call"?r.arguments:r.kind==="negate"?[r.argument]:[r.left,r.right]).map(i=>te(he(i,e)));if(r.kind==="call"){let[i,s,a]=n;if(r.name==="equalAll"){if(i.componentType!==s.componentType||i.components!==s.components)throw new Error("equalAll requires matching types and row widths");return"uint32"}if(r.name==="select"){if(s.componentType!==a.componentType)throw new Error("select branches require matching component types");let u=Math.max(s.components,a.components);if(n.some(c=>c.components!==1&&c.components!==u))throw new Error("select widths must match its branches or be one component");return Er(s.componentType,u)}if(r.name==="dot"&&i.components!==s.components)throw new Error("dot requires matching row widths")}if(n.some(i=>i.componentType!=="float32"))throw new Error("Arithmetic requires float32 operands; use an explicit float32 cast");if(r.kind==="call"&&(r.name==="dot"||r.name==="length"))return"float32";let o=Math.max(...n.map(i=>i.components));if(n.some(i=>i.components!==1&&i.components!==o))throw new Error("Expression row widths must match or broadcast from one component");return Er("float32",o)}}}var Wt=class{contracts=new Map;resultNames;expressions;operations;outputs;scalars;vectors;textures;constructor(e,t={}){e=jt(e),this.scalars=e.scalars,this.vectors=e.vectors,this.textures=e.textures;let n=[],o=m=>{if(m instanceof q&&m.type==="composite")m.operations.forEach(o);else{if(m instanceof q){let p=g=>g instanceof ft||g instanceof q&&g.operations.some(p);if(m.operations.some(p))throw new Error("Shader-pass operations inside control flow are not supported");let y=g=>g instanceof Ve||g instanceof q&&g.operations.some(y);if(m.operations.some(y))throw new Error("Expression operations inside control flow are not supported")}n.push(m)}};e.operations.forEach(o),this.operations=n;let i=new Map([...this.scalars,...this.vectors,...this.textures].map(m=>[m.id,m])),s=n.filter(m=>m instanceof Ve),a=new Set,u=new Map;for(let m of n)if(m instanceof Ve&&u.set(m,new Set(a)),!!$e(m))try{let p=Ks(m,this.scalars);if(!p)continue;Rt(e,p),this.contracts.set(m,p);for(let y of p.values){let g=k(y.value);y.access!=="read"&&this.scalars.some(w=>w.id===g)&&a.add(g)}}catch(p){throw new Error(`${m.id}: ${p instanceof Error?p.message:String(p)}`,{cause:p})}let c=new Set;for(let m of s){if(c.has(m.output))throw new Error(`Multiple expression writers for ${m.output}`);c.add(m.output)}let d=new Set([...i.keys()].filter(m=>!c.has(m)&&i.get(m)?.role!=="value")),l=[];for(let m of n){let p=this.contracts.get(m);if(!(m instanceof Ve)){for(let y of p?.values??[]){let g=k(y.value);if(y.access!=="write"&&!d.has(g))throw new Error(`${"id"in m?m.id:"Operation"}: Reads ${g} before it is produced`)}for(let y of p?.values??[])y.access!=="read"&&d.add(k(y.value));continue}try{let y=i.get(m.output);if(!y||!qo(y.format))throw new Error(`Expression output ${m.output} must declare a 32-bit numeric row of width 1\u20134`);let g=gn(m.expression),w=yn(g);if(w.includes(m.output))throw new Error(`Reads ${m.output} before it is produced`);let S=new Map;for(let b of w){let C=i.get(b);if(!C||!qo(C.format))throw new Error(`Expression input ${b} must declare a 32-bit numeric row of width 1\u20134`);if(S.set(b,C.format),!d.has(b))throw new Error(`Reads ${b} before it is produced`)}if(this.scalars.some(b=>b.id===y.id)&&w.some(b=>this.vectors.some(C=>C.id===b)))throw new Error(`Vector expression cannot write scalar ${m.output}`);if(this.vectors.some(b=>b.id===m.output)&&!w.some(b=>this.vectors.some(C=>C.id===b))&&!(y instanceof Q&&y.role==="value"&&y.length!==void 0))throw new Error(`Vector expression ${m.output} requires a vector input to determine its shape`);let T=he(g,S);if(y.format!==T)throw new Error("Expression result type must match its output declaration");d.add(m.output);let v=w.filter(b=>u.get(m).has(b));l.push({operation:m,expression:g,format:T,formats:S,references:w,gpuScalarInputs:v})}catch(y){throw y instanceof Error?new Error(`${m.id}: ${y.message}`,{cause:y}):y}}this.expressions=l;let h=[...i.values()].filter(m=>m.role==="value");this.resultNames=new Set([...this.contracts.values()].flatMap(m=>m.values.filter(p=>p.access!=="read").map(p=>k(p.value))).filter(m=>i.get(m)?.role!=="input"&&i.get(m)?.role!=="state"));let f=new Set([...this.contracts.values()].flatMap(m=>m.values.filter(p=>p.access!=="write").map(p=>k(p.value))));this.outputs=[...t.outputs??(h.length?[...this.resultNames].filter(m=>!f.has(m)):s.map(m=>m.output))];for(let m of this.outputs){if(!i.has(m))throw new Error(`Undeclared output ${m}`);if(this.scalars.some(p=>p.id===m)&&!c.has(m)&&!a.has(m))throw new Error(`Selected scalar ${m} must be produced by a graph operation`)}}resolveBindings(e,t={}){let n=[...this.scalars,...this.vectors,...this.textures];if(!(n.some(c=>c.role==="input"||c.role==="state")||Object.values(e).some(c=>c!==void 0&&typeof c=="object"&&!(c instanceof H)&&!(c instanceof Ee)&&!(c instanceof we.Texture)&&!(c instanceof we.TextureView)))){for(let c of Object.keys(e))if(n.find(d=>d.id===c)?.role==="value")throw new Error(`Use outputTargets for graph result ${c}`);return{bindings:e,options:t}}for(let c of Object.keys(e))if(!["inputs","state","outputTargets"].includes(c))throw new Error(`Unknown execution option ${c}`);let s=e,a=Object.create(null);for(let[c,d]of[["input",s.inputs],["state",s.state]])for(let[l,h]of Object.entries(d??{})){let f=n.find(p=>p.id===l),m=f?.role??(this.resultNames.has(l)?"value":"input");if(!f||m!==c)throw new Error(`Invalid ${c} binding ${l}`);a[l]=h}for(let c of n)if((c.role==="input"||c.role==="state")&&a[c.id]===void 0)throw new Error(`Missing ${c.role} binding ${c.id}`);if(t.outputTargets&&s.outputTargets)throw new Error("Duplicate output targets");let u=s.outputTargets??t.outputTargets;for(let c of Object.keys(u??{}))if(!this.resultNames.has(c)||!this.outputs.includes(c))throw new Error(`Invalid graph output target ${c}`);return{bindings:a,options:{outputTargets:u}}}prepare(e,t,n={},o=!1){let i=new Zr(e,this.textures,[...this.contracts.values()],t,n.outputTargets??{}),s=new Map,a=new Set,u=new Map,c=o&&!this.operations.some(g=>g instanceof q),d=g=>{let w=s.get(g);return w instanceof H?{length:w.length,chunkLengths:w.data.map(S=>S.length)}:u.get(g)},l=(g,w,S)=>{if(c&&!this.outputs.includes(g)&&this.vectors.some(T=>T.id===g&&T.role==="value"))u.set(g,{length:w.reduce((T,v)=>T+v,0),chunkLengths:w});else{let T=Xs(e,g,w,S);a.add(T),s.set(g,T)}},h=new Set(this.expressions.map(g=>g.operation.output)),f=new Map;for(let[g,w]of Object.entries(n.outputTargets??{}))if(!this.textures.some(S=>S.id===g)){if(!(w instanceof H))throw i.destroy(),new Error(`Expected GPUVector ${g}`);f.set(g,w)}let m=new Set([...this.contracts.values()].flatMap(g=>g.values.filter(w=>w.access!=="read"&&this.vectors.some(S=>S.id===k(w.value))).map(w=>k(w.value)))),p=new Set,y=new Set;try{for(let[g,w]of Object.entries(t)){if(this.textures.some(v=>v.id===g))continue;if(h.has(g))throw new Error(`Use outputTargets for expression output ${g}`);let S=this.scalars.find(v=>v.id===g),T=this.vectors.find(v=>v.id===g);if(S){if(typeof w!="number"||!Number.isFinite(w))throw new Error(`Expected numeric scalar ${g}`);if(S.format!=="float32"&&(!Number.isInteger(w)||w<(S.format==="uint32"?0:-2147483648)||w>(S.format==="uint32"?4294967295:2147483647)))throw new Error(`Scalar ${g} is outside its declared integer format`)}else if(T){if(!(w instanceof H))throw new Error(`Expected GPUVector ${g}`);bn(e,w,T.format,T.length,T.chunkLengths)}else throw new Error(`Undeclared binding ${g}`);s.set(g,w)}for(let g of this.operations){g instanceof Ye&&i.values.has(g.input)&&wo(i.values.get(g.input),i.values.get(g.output));for(let E of this.contracts.get(g)?.values??[]){let $=k(E.value);E.access!=="write"&&s.get($)instanceof H&&y.add($)}if(!(g instanceof Ve)){let E=this.contracts.get(g);for(let $ of E?.values??[]){let L=k($.value);if($.access!=="write"&&!s.has(L)&&!i.values.has(L)&&!u.has(L)&&!p.has(L))throw new Error(`Missing ${$.access==="read-write"?"read-write":"execution"} binding ${L}`)}for(let $ of E?.values??[]){let L=k($.value);$.access!=="read"&&this.scalars.some(_=>_.id===L)&&p.add(L)}for(let $ of E?.requiredFeatures??[])if(!e.features.has($))throw new Error(`Operation requires ${$}`);for(let $ of E?.values??[]){if($.access==="read")continue;let L=this.vectors.find(Qe=>Qe.id===k($.value));if(!L)continue;let _=s.get(L.id),j=f.get(L.id)??(_ instanceof H?_:void 0),W=$.shape,le=W&&"like"in W?d(k(W.like)):void 0;if(W&&"like"in W&&!le)throw new Error(`Missing shape input ${k(W.like)}`);let ne=le?le.chunkLengths:W&&"length"in W?W.chunkLengths??L.chunkLengths??[W.length]:L.chunkLengths??(L.length===void 0?void 0:[L.length]);if($.access==="read-write"&&!(_ instanceof H))throw new Error(`Missing read-write binding ${L.id}`);if($.access==="read-write"&&j!==_)throw new Error(`Read-write target must use its bound storage: ${L.id}`);if(y.has(L.id)&&j!==_)throw new Error(`Output target replaces an earlier read: ${L.id}`);if(!j&&!ne)throw new Error(`Cannot infer length of produced vector ${L.id}`);let Ze=ne?.reduce((Qe,ht)=>Qe+ht,0)??j.length;if(L.length!==void 0&&L.length!==Ze||W&&"length"in W&&W.length!==Ze)throw new Error(`Length constraint failed for ${L.id}`);if(L.chunkLengths&&ne&&(L.chunkLengths.length!==ne.length||L.chunkLengths.some((Qe,ht)=>Qe!==ne[ht])))throw new Error(`Chunk constraint failed for ${L.id}`);j?(bn(e,j,L.format,Ze,ne),Yo(L.id,j,s),s.set(L.id,j)):l(L.id,ne,L.format)}continue}let w=this.expressions.find(E=>E.operation===g),S=[];for(let E of w.references){if(s.get(E)===void 0&&!u.has(E)&&!w.gpuScalarInputs.includes(E))throw new Error(`Missing execution binding ${E}`);let L=d(E);L&&this.vectors.some(_=>_.id===E)&&S.push(L)}let T=this.vectors.find(E=>E.id===w.operation.output),v=S[0],b=T?v?.chunkLengths??T.chunkLengths??(T.length===void 0?void 0:[T.length]):[1];if(!b)throw new Error(`Cannot infer length of ${w.operation.output}`);for(let E of S)if(E.chunkLengths.length!==b.length||E.chunkLengths.some(($,L)=>$!==b[L]))throw new Error(`Expression ${w.operation.id} requires matching vector chunk boundaries`);let C=b.reduce((E,$)=>E+$,0);if(T?.length!==void 0&&T.length!==C)throw new Error(`Length constraint failed for ${T.id}`);if(T?.chunkLengths&&(T.chunkLengths.length!==b.length||T.chunkLengths.some((E,$)=>E!==b[$])))throw new Error(`Chunk constraint failed for ${T.id}`);let B=f.get(w.operation.output);B?(bn(e,B,w.format,C,b),Yo(w.operation.output,B,s),s.set(w.operation.output,B)):l(w.operation.output,b,w.format)}for(let g of Object.keys(n.outputTargets??{})){let w=this.outputs.includes(g)&&this.scalars.some(S=>S.id===g);if(!h.has(g)&&!m.has(g)&&!w&&!this.textures.some(S=>S.id===g&&S.role==="value"))throw new Error(`Unknown graph output target ${g}`)}for(let g of this.outputs)if(!(s.get(g)instanceof H)&&this.scalars.some(w=>w.id===g)){let w=f.get(g);if(w){bn(e,w,this.scalars.find(T=>T.id===g).format,1,[1]),Yo(g,w,s),s.set(g,w);continue}let S=Xs(e,g,[1],this.scalars.find(T=>T.id===g).format);a.add(S),s.set(g,S)}return new Xo(this,s,a,u,i)}catch(g){i.destroy();for(let w of a)w.destroy();throw g}}};function Ks(r,e){if(r instanceof q&&(r.type==="composite"||r instanceof lt&&!r.predicate)){let t=new Set,n=new Set;for(let o of r.operations){let i=(Ks(o,e)?.values??[]).filter(s=>e.some(a=>a.id===k(s.value)));for(let s of i){let a=k(s.value);s.access!=="write"&&!n.has(a)&&t.add(a)}for(let s of i)s.access!=="read"&&n.add(k(s.value))}return{values:[...new Set([...t,...n])].map(o=>({value:o,access:t.has(o)?n.has(o)?"read-write":"read":"write"}))}}return $e(r)?r.contract:void 0}var Xo=class{program;values;owned;transientVectors;textures;constructor(e,t,n,o=new Map,i){this.program=e,this.values=t,this.owned=n,this.transientVectors=o,this.textures=i}getOutputs(){let e=Object.create(null);for(let t of this.program.outputs){let n=this.textures?.values.get(t)??this.values.get(t);if(!(n instanceof H||n instanceof we.Texture||n instanceof we.TextureView))throw new Error(`Output ${t} has no materialized resource`);e[t]=n}return e}finish(){let e=this.getOutputs();for(let t of Object.values(e))t instanceof H&&this.owned.delete(t);return this.textures?.finish(this.program.outputs),this.destroy(),e}destroy(){this.textures?.destroy();for(let e of this.owned)e.destroy();this.owned.clear()}};function Xs(r,e,t,n="float32"){let o=[];try{for(let i of t)o.push(new Dt({buffer:r.createBuffer({byteLength:Math.max(1,i)*te(n).components*4,usage:we.Buffer.STORAGE|we.Buffer.VERTEX|we.Buffer.COPY_SRC|we.Buffer.COPY_DST}),format:n,length:i,ownsBuffer:!0}));return new H({type:"data",name:e,format:n,data:o,ownsData:!0})}catch(i){for(let s of o)s.destroy();throw i}}function bn(r,e,t,n,o){if(e.format!==t||n!==void 0&&e.length!==n)throw new Error(`Incompatible vector ${e.name}`);if(o&&(o.length!==e.data.length||o.some((s,a)=>s!==e.data[a].length)))throw new Error(`Incompatible chunks for ${e.name}`);let i=U(e.format).byteLength;for(let s of e.data)if(s.buffer.device!==r||s.byteStride!==i||s.byteOffset%4!==0||s.rowByteLength!==i)throw new Error(`Expression vector ${e.name} must contain packed 32-bit numeric chunks on the execution device`)}function Yo(r,e,t){let n=i=>i.buffer instanceof we.Buffer?i.buffer:i.buffer.buffer,o=new Map;for(let i of e.data){if(i.length===0)continue;let s=n(i),a=o.get(s)??[];a.push({start:i.byteOffset,end:i.byteOffset+i.length*i.byteStride}),o.set(s,a)}for(let i of o.values())if(i.sort((s,a)=>s.start-a.start),i.some((s,a)=>a>0&&s.start<i[a-1].end))throw new Error(`Output ${r} has overlapping writable chunks`);for(let[i,s]of t)if(i!==r&&s instanceof H&&s.data.some(a=>o.has(n(a))))throw new Error("Expression output targets must not alias inputs or earlier outputs")}var Js=F(A(),1);var Ht={float32:"f32",sint32:"i32",uint32:"u32"};function Zs(r,e,t,n){if(e===t)return r;let o=Ht;if(t==="float32")return`${o.float32}(${r})`;if(e==="float32"){let s=n==="nearest"?`expression_round_nearest(${r})`:r;return`expression_to_${t}(${s})`}let i=t==="uint32"?`max(${r}, 0)`:`min(${r}, 2147483647u)`;return`${o[t]}(${i})`}var Qs=`
688
689
  fn expression_round_nearest(value: f32) -> f32 {
689
690
  let magnitude = abs(value);
690
691
  let integral = floor(magnitude);
@@ -700,16 +701,16 @@ fn expression_to_uint32(value: f32) -> u32 {
700
701
  if (value >= 4294967296.0) { return 4294967295u; }
701
702
  if (value <= 0.0) { return 0u; }
702
703
  return u32(value);
703
- }`;var Ko=64,xn=class{program;plan;kernel;vectorNames;scalarNames;outputIsScalar;constructor(e,t,n){this.program=t,this.plan=n,this.vectorNames=n.references.filter(l=>t.vectors.some(f=>f.id===l)),this.scalarNames=n.references.filter(l=>t.scalars.some(f=>f.id===l)),this.outputIsScalar=t.scalars.some(l=>l.id===n.operation.output);let o=this.scalarNames.length>0||this.outputIsScalar,i=l=>`metadata[${Math.floor(l/4)}][${l%4}]`,s=(l,f)=>{switch(te(he(l,n.formats)).components===1&&(f=0),l.kind){case"literal":return`f32(${Object.is(l.value,-0)?"-0.0":l.value.toExponential()})`;case"swizzle":return s(l.argument,l.components[f]);case"construct":{let h=l.arguments.flatMap(g=>Array.from({length:te(he(g,n.formats)).components},(y,p)=>({argument:g,component:p}))),m=h[h.length===1?0:f];return s(m.argument,m.component)}case"negate":return`(-${s(l.argument,f)})`;case"cast":return Ks(s(l.argument,f),te(he(l.argument,n.formats)).componentType,l.format,n.operation.integerRounding);case"call":{let[h,m,g]=l.arguments;if(l.name==="select"){let y=te(he(h,n.formats)).componentType;return`select(${s(g,f)}, ${s(m,f)}, ${s(h,f)} != ${Ht[y]}(0))`}if(["dot","length","equalAll"].includes(l.name)){let y=te(he(h,n.formats)).components,p=Array.from({length:y},(S,T)=>{let v=s(h,T),b=s(l.name==="length"?h:m,T);return`(${v} ${l.name==="equalAll"?"==":"*"} ${b})`});if(l.name==="equalAll")return`select(0u, 1u, ${p.join(" && ")})`;let w=p.reduce((S,T)=>`(${S} + ${T})`,"0.0");return l.name==="length"?`sqrt(${w})`:w}return`${l.name}(${l.arguments.map(y=>s(y,f)).join(", ")})`}case"binary":return`(${s(l.left,f)} ${l.operator} ${s(l.right,f)})`;case"reference":{let h=this.vectorNames.indexOf(l.name),{components:m,componentType:g}=te(n.formats.get(l.name));return h>=0?`input${h}[${i(h+2)} + index * ${m}u + ${m===1?0:f}u]`:`bitcast<${Ht[g]}>(gpuValues[${t.scalars.findIndex(y=>y.id===l.name)}])`}}},a=this.vectorNames.map((l,f)=>({name:`input${f}`,type:"read-only-storage",group:0,location:f})),u=[...a],c=a.map((l,f)=>`@group(0) @binding(${l.location}) var<storage, read> ${l.name}: array<${Ht[te(n.formats.get(this.vectorNames[f])).componentType]}>;`);this.outputIsScalar||(c.push(`@group(0) @binding(${u.length}) var<storage, read_write> outputValues: array<${Ht[te(n.format).componentType]}>;`),u.push({name:"outputValues",type:"storage",group:0,location:u.length})),o&&(c.push(`@group(0) @binding(${u.length}) var<storage, ${this.outputIsScalar?"read_write":"read"}> gpuValues: array<u32>;`),u.push({name:"gpuValues",type:this.outputIsScalar?"storage":"read-only-storage",group:0,location:u.length})),c.push(`@group(0) @binding(${u.length}) var<uniform> metadata: array<vec4u, ${Math.ceil((this.vectorNames.length+2)/4)}>;`),u.push({name:"metadata",type:"uniform",group:0,location:u.length});let d=this.outputIsScalar?`gpuValues[${t.scalars.findIndex(l=>l.id===n.operation.output)}] = bitcast<u32>(${s(n.expression,0)});`:Array.from({length:te(n.format).components},(l,f)=>`outputValues[${i(1)} + index * ${te(n.format).components}u + ${f}u] = ${s(n.expression,f)};`).join(`
704
+ }`;var Ko=64,xn=class{program;plan;kernel;vectorNames;scalarNames;outputIsScalar;constructor(e,t,n){this.program=t,this.plan=n,this.vectorNames=n.references.filter(l=>t.vectors.some(h=>h.id===l)),this.scalarNames=n.references.filter(l=>t.scalars.some(h=>h.id===l)),this.outputIsScalar=t.scalars.some(l=>l.id===n.operation.output);let o=this.scalarNames.length>0||this.outputIsScalar,i=l=>`metadata[${Math.floor(l/4)}][${l%4}]`,s=(l,h)=>{switch(te(he(l,n.formats)).components===1&&(h=0),l.kind){case"literal":return`f32(${Object.is(l.value,-0)?"-0.0":l.value.toExponential()})`;case"swizzle":return s(l.argument,l.components[h]);case"construct":{let f=l.arguments.flatMap(p=>Array.from({length:te(he(p,n.formats)).components},(y,g)=>({argument:p,component:g}))),m=f[f.length===1?0:h];return s(m.argument,m.component)}case"negate":return`(-${s(l.argument,h)})`;case"cast":return Zs(s(l.argument,h),te(he(l.argument,n.formats)).componentType,l.format,n.operation.integerRounding);case"call":{let[f,m,p]=l.arguments;if(l.name==="select"){let y=te(he(f,n.formats)).componentType;return`select(${s(p,h)}, ${s(m,h)}, ${s(f,h)} != ${Ht[y]}(0))`}if(["dot","length","equalAll"].includes(l.name)){let y=te(he(f,n.formats)).components,g=Array.from({length:y},(S,T)=>{let v=s(f,T),b=s(l.name==="length"?f:m,T);return`(${v} ${l.name==="equalAll"?"==":"*"} ${b})`});if(l.name==="equalAll")return`select(0u, 1u, ${g.join(" && ")})`;let w=g.reduce((S,T)=>`(${S} + ${T})`,"0.0");return l.name==="length"?`sqrt(${w})`:w}return`${l.name}(${l.arguments.map(y=>s(y,h)).join(", ")})`}case"binary":return`(${s(l.left,h)} ${l.operator} ${s(l.right,h)})`;case"reference":{let f=this.vectorNames.indexOf(l.name),{components:m,componentType:p}=te(n.formats.get(l.name));return f>=0?`input${f}[${i(f+2)} + index * ${m}u + ${m===1?0:h}u]`:`bitcast<${Ht[p]}>(gpuValues[${t.scalars.findIndex(y=>y.id===l.name)}])`}}},a=this.vectorNames.map((l,h)=>({name:`input${h}`,type:"read-only-storage",group:0,location:h})),u=[...a],c=a.map((l,h)=>`@group(0) @binding(${l.location}) var<storage, read> ${l.name}: array<${Ht[te(n.formats.get(this.vectorNames[h])).componentType]}>;`);this.outputIsScalar||(c.push(`@group(0) @binding(${u.length}) var<storage, read_write> outputValues: array<${Ht[te(n.format).componentType]}>;`),u.push({name:"outputValues",type:"storage",group:0,location:u.length})),o&&(c.push(`@group(0) @binding(${u.length}) var<storage, ${this.outputIsScalar?"read_write":"read"}> gpuValues: array<u32>;`),u.push({name:"gpuValues",type:this.outputIsScalar?"storage":"read-only-storage",group:0,location:u.length})),c.push(`@group(0) @binding(${u.length}) var<uniform> metadata: array<vec4u, ${Math.ceil((this.vectorNames.length+2)/4)}>;`),u.push({name:"metadata",type:"uniform",group:0,location:u.length});let d=this.outputIsScalar?`gpuValues[${t.scalars.findIndex(l=>l.id===n.operation.output)}] = bitcast<u32>(${s(n.expression,0)});`:Array.from({length:te(n.format).components},(l,h)=>`outputValues[${i(1)} + index * ${te(n.format).components}u + ${h}u] = ${s(n.expression,h)};`).join(`
704
705
  `);this.kernel=new D(e,{id:n.operation.id,source:`${c.join(`
705
706
  `)}
706
- ${Zs}
707
+ ${Qs}
707
708
  @compute @workgroup_size(${Ko})
708
709
  fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimensions: vec3u, @builtin(local_invocation_index) localIndex: u32) {
709
710
  let index = (workgroup.y * dimensions.x + workgroup.x) * ${Ko}u + localIndex;
710
711
  if (index >= ${i(0)}) { return; }
711
712
  ${d}
712
- }`,shaderLayout:{bindings:u}})}lower(e){let t=this.vectorNames.map(u=>e.resolveVector(this.program.vectors.find(c=>c.id===u))),n=this.outputIsScalar?e.resolveScalar(this.program.scalars.find(u=>u.id===this.plan.operation.output)):void 0,o=this.outputIsScalar?void 0:e.resolveVector(this.program.vectors.find(u=>u.id===this.plan.operation.output)),i=n?.arena??(this.scalarNames.length?e.resolveScalar(this.program.scalars.find(u=>u.id===this.scalarNames[0])).arena:void 0),a=(o?.data??[n.view]).flatMap((u,c)=>{if(u.length===0)return[];let d=t.map(y=>y.data[c]);if(d.some(y=>!y||y.length!==u.length))throw new Error("Expression chunk mismatch");let l=Math.ceil(u.length/Ko),f=e.graph.device.limits.maxComputeWorkgroupsPerDimension,h=Math.min(l,f),m=Math.ceil(l/h);if(m>f)throw new Error("Expression chunk exceeds dispatch limits");let g=[...d.map(y=>({buffer:y,usage:"storage-read"})),...o?[{buffer:u,usage:"storage-write"}]:[],...i?[{buffer:i.buffer,usage:this.outputIsScalar?"storage-read-write":"storage-read"}]:[]];return[N(V({id:`${this.plan.operation.id}-chunk-${c}`,resources:g,compile:({device:y})=>{let p=new Uint32Array(Math.ceil((this.vectorNames.length+2)/4)*4);p.set([u.length,P(u),...d.map(P)]);let w=y.createBuffer({data:p,usage:Qs.Buffer.UNIFORM});return{encode:({computePass:S,getBuffer:T})=>{let v={metadata:w};d.forEach((b,C)=>{v[`input${C}`]=G(b,T)}),o&&(v.outputValues=G(u,T)),i&&(v.gpuValues=T(i.buffer)),this.kernel.dispatch(S,{bindings:v,x:h,y:m,z:1})},destroy:()=>w.destroy()}}}),[h,m,1])]});He(e.graph,a),e.recordDecision({operationId:this.plan.operation.id,operationType:"expression",lowering:"webgpu-expression",reason:"shape-independent expression shader with execution-time chunk dimensions"})}destroy(){this.kernel.destroy()}};var ae=F(A(),1);var Ke=F(A(),1),qt=class r{static async createAsync(e,t){let n=!Ke.PipelineFactory.getAsyncCompilation(e),o=n?Ke.PipelineFactory.beginAsyncCompilation(e):Ke.PipelineFactory.getAsyncCompilation(e),i;try{i=new r(e,t)}finally{n&&Ke.PipelineFactory.endAsyncCompilation(e,o)}try{return n?await Promise.all(o):await i._pipelineInitialization,i}catch(s){throw i.destroy(),s}}device;id;vertexSource;fragmentSource;pipelineFactory;shaderFactory;vertexShader;fragmentShader;pipeline;_pipelineInitialization;_destroyed=!1;drawDefaults;constructor(e,t){if(e.type!=="webgpu"&&e.type!=="webgl")throw new Error("RenderKernel requires WebGL or WebGPU");if(e.type==="webgl"&&!t.fragmentSource)throw new Error("WebGL RenderKernel requires a fragment shader");let{vertexSource:n,fragmentSource:o,pipelineFactory:i,shaderFactory:s,debugShaders:a,...u}=t;this.device=e,this.drawDefaults={parameters:t.parameters??{},topology:t.topology??"triangle-list"},this.id=t.id??"render-kernel",this.vertexSource=n,this.fragmentSource=o,this.pipelineFactory=i??Ke.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=s??Ke.ShaderFactory.getDefaultShaderFactory(e),this.vertexShader=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.vertexSource,debugShaders:a}),this.fragmentShader=this.fragmentSource?this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.fragmentSource,debugShaders:a}):null;let c={...u,vs:this.vertexShader,fs:this.fragmentShader},d=Ke.PipelineFactory.getAsyncCompilation(e);if(d){let l=this.pipelineFactory.createRenderPipelineAsync(c);this._pipelineInitialization=l,d.push(l.then(f=>(this.pipeline=f,f)))}else this.pipeline=this.pipelineFactory.createRenderPipeline(c)}draw(e,t){let{bindings:n={},vertexArray:o,...i}=t;return this._setPipeline(e,n,o),e.draw(this.device.type==="webgl"?{...this.drawDefaults,...i,isInstanced:i.isInstanced??i.instanceCount!==void 0}:i)}drawIndirect(e,t){if(this.device.type!=="webgpu")throw new Error("Indirect drawing is only supported in WebGPU");let{bindings:n={},vertexArray:o,indirectBuffer:i,indirectOffset:s=0}=t;this._setPipeline(e,n,o),e.drawIndirect(i,s)}drawIndexedIndirect(e,t){if(this.device.type!=="webgpu")throw new Error("Indirect drawing is only supported in WebGPU");let{bindings:n={},vertexArray:o,indirectBuffer:i,indirectOffset:s=0}=t;this._setPipeline(e,n,o),e.drawIndexedIndirect(i,s)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.vertexShader),this.fragmentShader&&this.shaderFactory.release(this.fragmentShader),this._destroyed=!0)}_setPipeline(e,t,n){e.setPipeline(this.pipeline),e.setBindings(t),e.setVertexArray(n)}};var Mc=`
713
+ }`,shaderLayout:{bindings:u}})}lower(e){let t=this.vectorNames.map(u=>e.resolveVector(this.program.vectors.find(c=>c.id===u))),n=this.outputIsScalar?e.resolveScalar(this.program.scalars.find(u=>u.id===this.plan.operation.output)):void 0,o=this.outputIsScalar?void 0:e.resolveVector(this.program.vectors.find(u=>u.id===this.plan.operation.output)),i=n?.arena??(this.scalarNames.length?e.resolveScalar(this.program.scalars.find(u=>u.id===this.scalarNames[0])).arena:void 0),a=(o?.data??[n.view]).flatMap((u,c)=>{if(u.length===0)return[];let d=t.map(y=>y.data[c]);if(d.some(y=>!y||y.length!==u.length))throw new Error("Expression chunk mismatch");let l=Math.ceil(u.length/Ko),h=e.graph.device.limits.maxComputeWorkgroupsPerDimension,f=Math.min(l,h),m=Math.ceil(l/f);if(m>h)throw new Error("Expression chunk exceeds dispatch limits");let p=[...d.map(y=>({buffer:y,usage:"storage-read"})),...o?[{buffer:u,usage:"storage-write"}]:[],...i?[{buffer:i.buffer,usage:this.outputIsScalar?"storage-read-write":"storage-read"}]:[]];return[N(V({id:`${this.plan.operation.id}-chunk-${c}`,resources:p,compile:({device:y})=>{let g=new Uint32Array(Math.ceil((this.vectorNames.length+2)/4)*4);g.set([u.length,P(u),...d.map(P)]);let w=y.createBuffer({data:g,usage:Js.Buffer.UNIFORM});return{encode:({computePass:S,getBuffer:T})=>{let v={metadata:w};d.forEach((b,C)=>{v[`input${C}`]=G(b,T)}),o&&(v.outputValues=G(u,T)),i&&(v.gpuValues=T(i.buffer)),this.kernel.dispatch(S,{bindings:v,x:f,y:m,z:1})},destroy:()=>w.destroy()}}}),[f,m,1])]});He(e.graph,a),e.recordDecision({operationId:this.plan.operation.id,operationType:"expression",lowering:"webgpu-expression",reason:"shape-independent expression shader with execution-time chunk dimensions"})}destroy(){this.kernel.destroy()}};var ae=F(A(),1);var Ke=F(A(),1),qt=class r{static async createAsync(e,t){let n=!Ke.PipelineFactory.getAsyncCompilation(e),o=n?Ke.PipelineFactory.beginAsyncCompilation(e):Ke.PipelineFactory.getAsyncCompilation(e),i;try{i=new r(e,t)}finally{n&&Ke.PipelineFactory.endAsyncCompilation(e,o)}try{return n?await Promise.all(o):await i._pipelineInitialization,i}catch(s){throw i.destroy(),s}}device;id;vertexSource;fragmentSource;pipelineFactory;shaderFactory;vertexShader;fragmentShader;pipeline;_pipelineInitialization;_destroyed=!1;drawDefaults;constructor(e,t){if(e.type!=="webgpu"&&e.type!=="webgl")throw new Error("RenderKernel requires WebGL or WebGPU");if(e.type==="webgl"&&!t.fragmentSource)throw new Error("WebGL RenderKernel requires a fragment shader");let{vertexSource:n,fragmentSource:o,pipelineFactory:i,shaderFactory:s,debugShaders:a,...u}=t;this.device=e,this.drawDefaults={parameters:t.parameters??{},topology:t.topology??"triangle-list"},this.id=t.id??"render-kernel",this.vertexSource=n,this.fragmentSource=o,this.pipelineFactory=i??Ke.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=s??Ke.ShaderFactory.getDefaultShaderFactory(e),this.vertexShader=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.vertexSource,debugShaders:a}),this.fragmentShader=this.fragmentSource?this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.fragmentSource,debugShaders:a}):null;let c={...u,vs:this.vertexShader,fs:this.fragmentShader},d=Ke.PipelineFactory.getAsyncCompilation(e);if(d){let l=this.pipelineFactory.createRenderPipelineAsync(c);this._pipelineInitialization=l,d.push(l.then(h=>(this.pipeline=h,h)))}else this.pipeline=this.pipelineFactory.createRenderPipeline(c)}draw(e,t){let{bindings:n={},vertexArray:o,...i}=t;return this._setPipeline(e,n,o),e.draw(this.device.type==="webgl"?{...this.drawDefaults,...i,isInstanced:i.isInstanced??i.instanceCount!==void 0}:i)}drawIndirect(e,t){if(this.device.type!=="webgpu")throw new Error("Indirect drawing is only supported in WebGPU");let{bindings:n={},vertexArray:o,indirectBuffer:i,indirectOffset:s=0}=t;this._setPipeline(e,n,o),e.drawIndirect(i,s)}drawIndexedIndirect(e,t){if(this.device.type!=="webgpu")throw new Error("Indirect drawing is only supported in WebGPU");let{bindings:n={},vertexArray:o,indirectBuffer:i,indirectOffset:s=0}=t;this._setPipeline(e,n,o),e.drawIndexedIndirect(i,s)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.vertexShader),this.fragmentShader&&this.shaderFactory.release(this.fragmentShader),this._destroyed=!0)}_setPipeline(e,t,n){e.setPipeline(this.pipeline),e.setBindings(t),e.setVertexArray(n)}};var Mc=`
713
714
  struct GraphShaderPassVertex {
714
715
  @builtin(position) position: vec4<f32>,
715
716
  @location(0) textureCoordinates: vec2<f32>
@@ -720,13 +721,13 @@ struct GraphShaderPassVertex {
720
721
  result.position = vec4<f32>(position * 2.0 - 1.0, 0.0, 1.0);
721
722
  result.textureCoordinates = vec2<f32>(position.x, 1.0 - position.y);
722
723
  return result;
723
- }`,wn=class{device;operation;kernel;vertexArray;samplers=Object.create(null);parameterFormats;parameterByteLength;constructor(e,t,n){this.device=e,this.operation=t,(0,ae.assert)(e.type==="webgpu"),this.parameterFormats=Object.values(t.parameters).map(u=>{let c=n.scalars.find(d=>d.id===u);return(0,ae.assert)(c),c.format}),this.parameterByteLength=Math.ceil(this.parameterFormats.length/4)*16;for(let u of Object.values(t.inputs)){let c=n.textures.find(l=>l.id===u),d=e.getTextureFormatInfo(c.format);(0,ae.assert)(!d.integer&&d.attachment!=="depth"&&d.attachment!=="depth-stencil"&&e.getTextureFormatCapabilities(c.format).filter)}let o=e.getTextureFormatInfo(t.outputDescriptor.format);(0,ae.assert)(!o.integer&&e.getTextureFormatCapabilities(t.outputDescriptor.format).render);let i=[...Object.keys(t.inputs).map((u,c)=>({name:u,location:c,group:0,type:"texture",viewDimension:"2d",sampleType:"float"})),...Object.keys(t.samplers).map((u,c)=>({name:u,location:Object.keys(t.inputs).length+c,group:0,type:"sampler"}))],s=0,a=[...Object.keys(t.inputs).map(u=>`@group(0) @binding(${s++}) var ${u}: texture_2d<f32>;`),...Object.keys(t.samplers).map(u=>`@group(0) @binding(${s++}) var ${u}: sampler;`)];this.parameterFormats.length&&(i.push({name:"parameters",location:s,group:0,type:"uniform"}),a.push(`struct GraphShaderPassParameters {${Object.keys(t.parameters).map((u,c)=>`${u}: ${Fs(this.parameterFormats[c])}`).join(",")}};
724
+ }`,wn=class{device;operation;kernel;vertexArray;samplers=Object.create(null);parameterFormats;parameterByteLength;constructor(e,t,n){this.device=e,this.operation=t,(0,ae.assert)(e.type==="webgpu"),this.parameterFormats=Object.values(t.parameters).map(u=>{let c=n.scalars.find(d=>d.id===u);return(0,ae.assert)(c),c.format}),this.parameterByteLength=Math.ceil(this.parameterFormats.length/4)*16;for(let u of Object.values(t.inputs)){let c=n.textures.find(l=>l.id===u),d=e.getTextureFormatInfo(c.format);(0,ae.assert)(!d.integer&&d.attachment!=="depth"&&d.attachment!=="depth-stencil"&&e.getTextureFormatCapabilities(c.format).filter)}let o=e.getTextureFormatInfo(t.outputDescriptor.format);(0,ae.assert)(!o.integer&&e.getTextureFormatCapabilities(t.outputDescriptor.format).render);let i=[...Object.keys(t.inputs).map((u,c)=>({name:u,location:c,group:0,type:"texture",viewDimension:"2d",sampleType:"float"})),...Object.keys(t.samplers).map((u,c)=>({name:u,location:Object.keys(t.inputs).length+c,group:0,type:"sampler"}))],s=0,a=[...Object.keys(t.inputs).map(u=>`@group(0) @binding(${s++}) var ${u}: texture_2d<f32>;`),...Object.keys(t.samplers).map(u=>`@group(0) @binding(${s++}) var ${u}: sampler;`)];this.parameterFormats.length&&(i.push({name:"parameters",location:s,group:0,type:"uniform"}),a.push(`struct GraphShaderPassParameters {${Object.keys(t.parameters).map((u,c)=>`${u}: ${Rs(this.parameterFormats[c])}`).join(",")}};
724
725
  @group(0) @binding(${s}) var<uniform> parameters: GraphShaderPassParameters;`));try{this.kernel=new qt(e,{id:t.id,vertexSource:Mc,fragmentSource:`${a.join(`
725
726
  `)}
726
727
  ${t.fragmentSource}
727
728
 
728
729
  @fragment fn fragmentMain(@location(0) textureCoordinates: vec2<f32>) -> @location(0) vec4<f32> {
729
730
  return shade(textureCoordinates);
730
- }`,vertexEntryPoint:"vertexMain",fragmentEntryPoint:"fragmentMain",topology:"triangle-list",shaderLayout:{attributes:[],bindings:i},colorAttachmentFormats:[t.outputDescriptor.format],parameters:{depthWriteEnabled:!1}}),this.vertexArray=e.createVertexArray({shaderLayout:this.kernel.pipeline.shaderLayout,bufferLayout:[]});for(let[u,c]of Object.entries(t.samplers))this.samplers[u]=e.createSampler(c)}catch(u){throw this.destroy(),u}}validateTextures(e){for(let t of[...Object.values(this.operation.inputs),this.operation.output]){let n=e.get(t);(0,ae.assert)(n);let o=ee(n);(0,ae.assert)(o.texture.device===this.device&&o.dimension==="2d"&&o.depth===1&&o.samples===1),t===this.operation.output&&(0,ae.assert)(o.mipLevels===1)}}lower(e){let t=this.operation,n=Object.fromEntries(Object.entries(t.inputs).map(([s,a])=>[s,e.resolveTextureView(a)])),o=e.resolveTextureView(t.output),i=this.parameterFormats.length?e.graph.createTransientBuffer({id:e.graph.getUniqueResourceId(`${t.id}-parameters`),byteLength:this.parameterByteLength,usage:ae.Buffer.UNIFORM|ae.Buffer.COPY_DST}):void 0;if(i){let s=Object.values(t.parameters).map(a=>e.resolveScalar(a).view);e.graph.addCopyPass({id:`${t.id}-parameters`,resources:[...s.map(a=>({buffer:a,usage:"copy-source"})),{buffer:i,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:a,getBuffer:u})=>{s.forEach((c,d)=>a.copyBufferToBuffer({sourceBuffer:u(c),sourceOffset:c.byteOffset,destinationBuffer:u(i),destinationOffset:d*4,size:4}))}})})}e.graph.addRenderPass({id:t.id,resources:[...Object.values(n).map(s=>({texture:s,usage:"sampled"})),...i?[{buffer:i,usage:"uniform"}]:[]],attachments:{colorAttachments:[o]},compile:()=>({getRenderPassProps:()=>({clearColor:[0,0,0,0],clearDepth:!1}),encode:({renderPass:s,getTextureView:a,getBuffer:u})=>this.draw(s,Object.fromEntries(Object.entries(n).map(([c,d])=>[c,a(d)])),i?u(i):void 0)})})}prepare(e,t){this.validateTextures(e);let n=Object.fromEntries(Object.entries(this.operation.inputs).map(([l,f])=>[l,e.get(f)])),o=e.get(this.operation.output),i=ee(o),s=new Uint8Array(this.parameterByteLength),a=new DataView(s.buffer),u=Object.values(this.operation.parameters).map((l,f)=>{let h=t.get(l);if((0,ae.assert)(h!==void 0),typeof h=="number")switch(this.parameterFormats[f]){case"float32":a.setFloat32(f*4,h,!0);break;case"sint32":a.setInt32(f*4,h,!0);break;case"uint32":a.setUint32(f*4,h,!0);break}else(0,ae.assert)(h.length===1&&h.data.length===1);return h}),c=s.byteLength?this.device.createBuffer({data:s,usage:ae.Buffer.UNIFORM|ae.Buffer.COPY_DST}):void 0,d;try{d=this.device.createFramebuffer({width:i.width,height:i.height,colorAttachments:[o]})}catch(l){throw c?.destroy(),l}return{encode:l=>{this.validateTextures(e),c&&u.forEach((h,m)=>{if(!(h instanceof H))return;let g=h.data[0],y=g.buffer instanceof ae.Buffer?g.buffer:g.buffer.buffer;l.copyBufferToBuffer({sourceBuffer:y,sourceOffset:g.byteOffset,destinationBuffer:c,destinationOffset:m*4,size:4})});let f=l.beginRenderPass({framebuffer:d,clearColor:[0,0,0,0],clearDepth:!1});try{this.draw(f,n,c)}finally{f.end()}},destroy:()=>{d.destroy(),c?.destroy()}}}destroy(){for(let e of Object.values(this.samplers))e.destroy();this.vertexArray?.destroy(),this.kernel?.destroy()}draw(e,t,n){let o={...t,...this.samplers};n&&(o.parameters=n),this.kernel.draw(e,{vertexArray:this.vertexArray,vertexCount:3,bindings:o})}};var Te=class{type="cpu";id;inputs;outputs;execute;constructor(e){this.id=e.id,this.inputs=Object.freeze({...e.inputs}),this.outputs=Object.freeze(Object.fromEntries(Object.entries(e.outputs).map(([t,n])=>[t,Object.freeze({...n,...n.chunkLengths?{chunkLengths:Object.freeze([...n.chunkLengths])}:{}})]))),this.execute=e.execute}get contract(){return{outputs:this.outputs,values:[...Object.values(this.inputs).map(e=>({value:e,access:"read"})),...Object.keys(this.outputs).map(e=>({value:e,access:"write"}))]}}};var re=F(A(),1);var Pr=class{device;program;compileStage;stages=[];constructor(e,t,n){this.device=e,this.program=t,this.compileStage=n,(0,re.assert)(!t.textures.length&&!t.vectors.some(s=>s.role==="state"));let o=[...t.scalars,...t.vectors],i=(s,a)=>{let u=o.find(d=>d.id===a);(0,re.assert)(u);let c=t.vectors.find(d=>d.id===a);c?s.addInput(a,M.vector(c.format,{length:c.length,chunkLengths:c.chunkLengths})):s.addInput(a,M.scalar(t.scalars.find(d=>d.id===a).format))};try{for(let s of t.operations){if(s instanceof Te){this.stages.push(s);continue}(0,re.assert)("contract"in s&&s.contract);let a=s.contract.values.filter(d=>d.access!=="write").map(d=>typeof d.value=="string"?d.value:d.value.id),u=s.contract.values.filter(d=>d.access!=="read").map(d=>typeof d.value=="string"?d.value:d.value.id),c=new ke;for(let d of new Set(a))i(c,d);for(let d of new Set(u)){let l=t.vectors.find(f=>f.id===d);l&&c.addDeclaration(d,M.vector(l.format,{length:l.length,chunkLengths:l.chunkLengths}),"value")}c.add(s),this.stages.push({graph:n(c,u),inputs:a})}}catch(s){throw this.destroy(),s}}async run(e,t={}){for(let[u,c]of Object.entries(t))(0,re.assert)(this.program.outputs.includes(u)&&(c==="cpu"||c==="gpu"));let n=new Map;for(let u of[...this.program.vectors,...this.program.scalars].filter(c=>c.role==="input")){let c=e[u.id];if((0,re.assert)(c!==void 0),!(c instanceof Ee)){let d=new ke,l=this.program.vectors.find(f=>f.id===u.id);l?d.addInput(u.id,M.vector(l.format,{length:l.length,chunkLengths:l.chunkLengths})):d.addInput(u.id,M.scalar(this.program.scalars.find(f=>f.id===u.id).format)),new jt(d,{outputs:[]}).prepare(this.device,{[u.id]:c}).finish()}if(c instanceof Ee){(0,re.assert)(c.data.every(l=>!l.nullBitmap&&!l.valueOffsets)),(0,re.assert)(c.format===u.format);let d=this.program.vectors.find(l=>l.id===u.id);(0,re.assert)(d&&(d.length===void 0||d.length===c.length)),(0,re.assert)(!d.chunkLengths||d.chunkLengths.length===c.data.length&&d.chunkLengths.every((l,f)=>l===c.data[f].length)),n.set(u.id,c)}}let o={...e},i=new Set,s=async u=>{let c=n.get(u);if(!c){let d=o[u];(0,re.assert)(d instanceof H);let l=await Nc(d);c=Js(l.format,l.chunks.map(f=>f.values)),n.set(u,c)}return zc(c)},a=async u=>{let c=o[u];if(c instanceof H)return c;let d=await s(u),l=new ke;l.add(new qe({output:u,format:d.format,data:d.chunks.map(h=>h.values)}));let f=this.compileStage(l);try{let h=(await f.run({}))[u];return i.add(h),o[u]=h,h}finally{f.destroy()}};try{for(let c of this.stages){let d;if(c instanceof Te){let l=Object.create(null);for(let[h,m]of Object.entries(c.inputs)){let g=o[m],y=typeof g=="number"?g:await s(m);l[h]=typeof y!="number"&&this.program.scalars.some(p=>p.id===m)?y.pack()[0]:y}let f=await c.execute({inputs:l});(0,re.assert)(Object.keys(f).length===Object.keys(c.outputs).length);for(let h of Object.keys(c.outputs)){let m=this.program.vectors.find(S=>S.id===h),g=f[h];(0,re.assert)(g);let y="chunks"in g?g.chunks.map(S=>S.values):[g],p=new qe({output:h,format:m.format,data:y}),w=p.chunkLengths.reduce((S,T)=>S+T,0);(0,re.assert)(m.length===void 0||m.length===w),(0,re.assert)(!m.chunkLengths||m.chunkLengths.length===y.length&&m.chunkLengths.every((S,T)=>S===p.chunkLengths[T])),n.set(h,Js(m.format,y)),delete o[h]}continue}else{let l=Object.create(null);for(let f of c.inputs){let h=o[f];l[f]=this.program.scalars.some(m=>m.id===f)?typeof h=="number"?h:(await s(f)).pack()[0]:await a(f)}d=await c.graph.run({inputs:l})}for(let[l,f]of Object.entries(d))n.delete(l),o[l]=f,i.add(f)}let u=Object.create(null);for(let c of this.program.outputs)t[c]==="cpu"?(await s(c),u[c]=n.get(c)):u[c]=await a(c);for(let c of Object.values(u))c instanceof H&&i.delete(c);return u}finally{for(let u of i)u.destroy()}}destroy(){for(let e of this.stages)e instanceof Te||e.graph.destroy()}};async function Nc(r){(0,re.assert)(r.format);let e=U(r.format),t=e.signedDataType==="float32"?Float32Array:e.signedDataType==="uint32"?Uint32Array:Int32Array,n=[];for(let o of r.data){let i=new t(o.length*e.byteLength/4);if(o.length){let s=await o.buffer.readAsync(o.byteOffset,(o.length-1)*o.byteStride+e.byteLength),a=new Uint8Array(i.buffer);for(let u=0;u<o.length;u++)a.set(s.subarray(u*o.byteStride,u*o.byteStride+e.byteLength),u*e.byteLength)}n.push({values:i,length:o.length})}return{format:r.format,length:r.length,chunks:n,pack(){let o=new t(n.reduce((s,a)=>s+a.values.length,0)),i=0;for(let s of n)o.set(s.values,i),i+=s.values.length;return o}}}function Js(r,e){let t=U(r).byteLength;return new Ee({format:r,data:e.map(n=>new ar({buffer:n,format:r,length:n.byteLength/t}))})}function zc(r){let e=r.format;(0,re.assert)(/^(float32|sint32|uint32)(x[234])?$/.test(e));let t=U(e),n=t.signedDataType==="float32"?Float32Array:t.signedDataType==="uint32"?Uint32Array:Int32Array,o=r.data.map(i=>{let s=new n(i.length*t.components),a=new Uint8Array(s.buffer);for(let u=0;u<i.length;u++)a.set(new Uint8Array(i.buffer,i.byteOffset+u*i.byteStride,t.byteLength),u*t.byteLength);return{values:s,length:i.length}});return{format:e,length:r.length,chunks:o,pack(){let i=new n(r.length*t.components),s=0;for(let a of o)i.set(a.values,s),s+=a.values.length;return i}}}var Yt=class r{device;program;stageLowerings;compiler;kernels=new Map;shaderPasses=new Map;destroyed=!1;runningCPU=!1;cpuExecution;outputLocations;constructor(e,t,n={},o){if(this.device=e,e.type!=="webgpu")throw new Error("GPUGraph execution requires WebGPU");if(this.program=new jt(t,n),this.outputLocations=n.outputLocations??{},this.stageLowerings=o??n.lowerings??[],this.compiler=new St(e,[...o??n.lowerings??[],{type:"shader-pass",lower:(i,s)=>this.shaderPasses.get(i).lower(s)},{type:"expression",lower:(i,s)=>this.kernels.get(i).lower(s)}]),this.program.operations.some(i=>i instanceof Te)||Object.values(this.outputLocations).includes("cpu")){this.cpuExecution=new Pr(e,this.program,(i,s)=>new r(e,i,{outputs:s},o??n.lowerings));return}try{for(let i of this.program.expressions)this.kernels.set(i.operation,new xn(e,this.program,i));for(let i of this.program.operations)i instanceof ft&&this.shaderPasses.set(i,new wn(e,i,this.program))}catch(i){throw this.destroy(),i}}async run(e,t={}){(0,Pt.assert)(!this.destroyed&&!this.runningCPU);let n="inputs"in e?e.inputs:e,o=this.program.operations.some(a=>a instanceof Te)||Object.values(this.outputLocations).includes("cpu")||Object.values(n??{}).some(a=>a instanceof Ee);if(!this.cpuExecution&&o&&(this.cpuExecution=new Pr(this.device,this.program,(a,u)=>new r(this.device,a,{outputs:u},this.stageLowerings))),o&&this.cpuExecution){let a=this.program.resolveBindings(e,t);(0,Pt.assert)(!a.options.outputTargets||Object.keys(a.options.outputTargets).length===0),this.runningCPU=!0;try{return await this.cpuExecution.run(a.bindings,this.outputLocations)}finally{this.runningCPU=!1}}let i=this.prepare(e,t),s;try{return s=this.device.createCommandEncoder(),i.encode(s),this.device.submit(s.finish()),i.outputs}catch(a){throw i.discard(),a}finally{i.destroy(),s?.destroy()}}prepare(e,t={}){if((0,Pt.assert)(!this.destroyed),this.program.operations.some(a=>a instanceof Te)||Object.values(this.outputLocations).includes("cpu"))throw new Error("CPU operations require asynchronous run(), not prepare()");let n=this.program.resolveBindings(e,t),o=n.bindings;t=n.options;let i=this.program.prepare(this.device,o,t,!0),s;try{for(let f of this.shaderPasses.values())f.validateTextures(i.textures.values);let a=new ke;for(let f of this.program.scalars)a.scalar(f.id,f.format);let u=Object.create(null),c=Object.create(null);for(let[f,h]of i.values)typeof h=="number"?c[f]=h:this.program.vectors.some(m=>m.id===f)&&(u[f]=h);for(let[f,h]of Object.entries(o))typeof h=="number"&&(c[f]=h);for(let f of this.program.vectors){let h=u[f.id],m=i.transientVectors.get(f.id);if(m){a.addDeclaration(f.id,{type:"vector",format:f.format,length:m.length,chunkLengths:m.chunkLengths},"value");continue}if(!h&&f.length===void 0)throw new Error(`Missing length or execution binding for ${f.id}`);a.vector(f.id,f.format,h?.length??f.length,{external:!!h,chunkLengths:h?.data.map(g=>g.length)??f.chunkLengths})}let d=Object.create(null);for(let f of this.program.textures){let h=i.textures.values.get(f.id),m=ee(h);a.texture(f.id,{format:m.format,dimension:m.dimension,width:m.width,height:m.height,depth:m.depth,mipLevels:m.mipLevels,samples:m.samples,usage:m.texture.props.usage,external:!0}),d[f.id]=h}a.add(this.program.operations);let l=this.compiler.compile(a,{vectors:u,scalars:c,textures:d});for(let f of this.program.scalars){let h=i.values.get(f.id);if(!(h instanceof H))continue;let m=l.scalars.get(f.id).view,g=l.graph.importGPUVector(`${f.id}-result`,h).data[0];l.graph.addCopyPass({id:`${f.id}-result-copy`,resources:[{buffer:m,usage:"copy-source"},{buffer:g,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:y,getBuffer:p})=>y.copyBufferToBuffer({sourceBuffer:p(m),sourceOffset:m.byteOffset,destinationBuffer:p(g),destinationOffset:g.byteOffset,size:4})})})}return s=l.graph.compile(),new Cr(this.device,i,s,()=>{(0,Pt.assert)(!this.destroyed)})}catch(a){throw s?.destroy(),i.destroy(),a}}destroy(){(0,Pt.assert)(!this.runningCPU),this.cpuExecution?.destroy();for(let e of this.shaderPasses.values())e.destroy();this.shaderPasses.clear();for(let e of this.kernels.values())e.destroy();this.kernels.clear(),this.destroyed=!0}},Cr=class{device;invocation;executable;checkProgram;outputs;encoded=!1;destroyed=!1;constructor(e,t,n,o){this.device=e,this.invocation=t,this.executable=n,this.checkProgram=o,this.outputs=t.getOutputs()}encode(e){(0,Pt.assert)(!this.destroyed&&!this.encoded&&e.device===this.device),this.checkProgram(),this.encoded=!0,this.executable.encode(e,{parameters:void 0})}destroy(){this.destroyed||(this.destroyed=!0,this.executable.destroy(),this.invocation.finish())}discard(){this.destroyed||(this.destroyed=!0,this.executable.destroy(),this.invocation.destroy())}};var ke=class r{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}addInput(e,t){return this.addDeclaration(e,t,"input")}addState(e,t){if(t.type!=="vector")throw new Error("Graph state requires vector storage");return this.addDeclaration(e,t,"state")}addDeclaration(e,t,n){if(this.assertValueId(e),t.type==="texture"){let i=new de({id:e,...t,usage:0,role:n,descriptor:t,external:n==="input",..."width"in(t.extent??{})?t.extent:{}});return this.programTextures.set(e,i),i}if(t.type==="scalar"){let i=new Ae(e,t.format,n);return this.programScalars.set(e,i),i}let o=new Q({id:e,...t,role:n,external:n==="input"||n==="state"});return this.programVectors.set(e,o),o}scalar(e,t){this.assertValueId(e);let n=new Ae(e,t);return this.programScalars.set(e,n),n}vector(e,t,n,o={}){this.assertValueId(e);let i=typeof n=="number"?{length:n,...o}:n??o,s=new Q({id:e,format:t,...i});return this.programVectors.set(e,s),s}texture(e,t){this.assertValueId(e);let n=new de({...t,id:e});return this.programTextures.set(e,n),n}textureView(e,t={}){if(this.programTextures.get(e.id)!==e)throw new Error(`Undeclared program texture "${e.id}"`);return new Fe(e,t)}compile(e,t={}){return new Yt(e,this,t)}constrainResult(e,t){if(e.length!==void 0&&t.length!==void 0&&e.length!==t.length)throw new Error(`Incompatible result length ${e.id}`);if(e.chunkLengths&&t.chunkLengths&&(e.chunkLengths.length!==t.chunkLengths.length||e.chunkLengths.some((o,i)=>o!==t.chunkLengths[i])))throw new Error(`Incompatible result chunks ${e.id}`);let n=new Q({...e,length:e.length??t.length,chunkLengths:e.chunkLengths??t.chunkLengths});return this.programVectors.set(e.id,n),n}clone(){let e=new r({id:this.id});for(let[t,n]of this.programScalars)e.programScalars.set(t,n);for(let[t,n]of this.programVectors)e.programVectors.set(t,n);for(let[t,n]of this.programTextures)e.programTextures.set(t,n);return e.programOperations.push(...this.programOperations),e}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 Zo(r,e={}){return new q({id:e.id,operations:r})}function Qo(r){let e=r.lowering.decisions.map(t=>`${t.operationId}: ${t.lowering} \u2014 ${t.reason}`);return Object.freeze({programId:r.program.id,semanticOperationCount:ea(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 ea(r){return r.reduce((e,t)=>e+1+ea(t.children??[]),0)}var Ct=F(A(),1);var Tn=class{type="group-aggregation";id;props;constructor(e){(0,Ct.assert)(e.groupCount===void 0||Number.isSafeInteger(e.groupCount)&&e.groupCount>0),this.id=e.id??`${k(e.output)}-group-aggregation`,this.props=Object.freeze({...e})}get contract(){let{keys:e,mask:t,output:n,groupCount:o}=this.props,i=this.props.operation==="count"?void 0:this.props.values;return{outputs:({getValue:s})=>{for(let a of[e,t])if(a){let u=s(k(a));(0,Ct.assert)(u.type==="vector"&&u.format==="uint32")}if(i){let a=s(k(i));(0,Ct.assert)(a.type==="vector"&&a.format==="float32")}return{[k(n)]:M.vector(this.props.operation==="count"?"uint32":"float32",{length:o})}},values:[{value:e,access:"read"},...i?[{value:i,access:"read"}]:[],...t?[{value:t,access:"read"}]:[],{value:n,access:"write"}]}}},vn=class{type="reduction";id;props;constructor(e){this.id=e.id??`${k(e.output)}-reduction`,this.props=Object.freeze({...e})}get contract(){let{input:e,mask:t,output:n,operation:o}=this.props;return{outputs:({getValue:i})=>{let s=i(k(e));(0,Ct.assert)(s.type==="vector");let{format:a}=s;if((0,Ct.assert)(a==="uint32"||a==="sint32"||a==="float32"),t){let u=i(k(t));(0,Ct.assert)(u.type==="vector"&&u.format==="uint32")}return{[k(n)]:M.vector(a,{length:o==="extent"?2:1})}},values:[{value:e,access:"read"},...t?[{value:t,access:"read"}]:[],{value:n,access:"write"}]}}};var En=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=Wc(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){Sn(e.operation,"operation"),na(e.workloadSize);let t=e.candidates.filter(a=>a.supported!==!1);if(t.length===0)throw new Error(`GPUCommandGraph autotuner operation "${e.operation}" has no supported variants`);for(let a of t)Sn(a.id,"variant");let n=ra(e.workloadSize),o=t.map(a=>{let u=this.findNearestCalibration(e.operation,a.id,n);return{candidate:a,calibration:u,sampleCount:u?.workloadBucket===n?u.sampleCount:0,estimatedDurationMilliseconds:u?jc(u,e.workloadSize):void 0}});if(this.explorationEnabled){let a=o.find(u=>u.sampleCount<this.minimumSampleCount);if(a)return Object.freeze({operation:e.operation,variant:a.candidate.id,workloadSize:e.workloadSize,workloadBucket:n,reason:"exploration",sampleCount:a.sampleCount,...a.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:a.estimatedDurationMilliseconds}})}let i=o.filter(a=>a.estimatedDurationMilliseconds!==void 0).sort((a,u)=>(a.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY)-(u.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY))[0],s=i??o[0];return Object.freeze({operation:e.operation,variant:s.candidate.id,workloadSize:e.workloadSize,workloadBucket:n,reason:i?"calibrated":"fallback",sampleCount:s.calibration?.sampleCount??0,...s.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:s.estimatedDurationMilliseconds}})}observeKernel(e){if(Sn(e.operation,"operation"),Sn(e.variant,"variant"),na(e.workloadSize),!Number.isFinite(e.durationMilliseconds)||e.durationMilliseconds<0)throw new Error("GPUCommandGraph autotuner durationMilliseconds must be nonnegative");let t=ra(e.workloadSize),n=Jo(e.operation,e.variant,t),o=this.calibrations.get(n)??{operation:e.operation,variant:e.variant,workloadBucket:t,sampleCount:0,meanWorkloadSize:0,meanDurationMilliseconds:0,durationSquaredDifferenceSum:0};o.sampleCount++,o.meanWorkloadSize+=(e.workloadSize-o.meanWorkloadSize)/o.sampleCount;let i=e.durationMilliseconds-o.meanDurationMilliseconds;return o.meanDurationMilliseconds+=i/o.sampleCount,o.durationSquaredDifferenceSum+=i*(e.durationMilliseconds-o.meanDurationMilliseconds),this.calibrations.set(n,o),ta(o)}observeTimingReport(e,t){let n=new Map(t.nodes.map(i=>[i.id,i])),o=0;for(let i of e.nodes){let s=n.get(i.id);i.gpuTimeMilliseconds===void 0||!s?.operation||!s.variant||(this.observeKernel({operation:s.operation,variant:s.variant,workloadSize:Math.max(s.maximumInvocationCount,1),durationMilliseconds:i.gpuTimeMilliseconds}),o++)}return o}exportProfile(){let e=[...this.calibrations.values()].sort((t,n)=>t.operation.localeCompare(n.operation)||t.variant.localeCompare(n.variant)||t.workloadBucket-n.workloadBucket).map(ta);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(Jo(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,n){let o=this.calibrations.get(Jo(e,t,n));if(o)return o;let i;for(let s of this.calibrations.values())s.operation!==e||s.variant!==t||(!i||Math.abs(s.workloadBucket-n)<Math.abs(i.workloadBucket-n))&&(i=s);return i}};function oa(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 Wc(r){return Object.freeze({...r,features:Object.freeze([...r.features])})}function ta(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 jc(r,e){return r.meanDurationMilliseconds*(e/Math.max(r.meanWorkloadSize,1))}function ra(r){return Math.floor(Math.log2(Math.max(r,1)))}function Jo(r,e,t){return`${r}\0${e}\0${t}`}function Sn(r,e){if(!r)throw new Error(`GPUCommandGraph autotuner ${e} is required`)}function na(r){if(!Number.isSafeInteger(r)||r<=0)throw new Error("GPUCommandGraph autotuner workloadSize must be a positive safe integer")}var Hc={interactive:4,normal:8,background:16},Pn=class{targetStepMilliseconds;latencyPriority;minimumScale;maximumScale;responsiveness;maximumAdjustmentFactor;initialBudget;currentBudget;currentScale=1;currentSampleCount=0;constructor(e){ia(e.initialBudget);let t=e.latencyPriority??"normal",n=e.targetStepMilliseconds??Hc[t];Br(n,"targetStepMilliseconds");let o=e.minimumScale??.125,i=e.maximumScale??4,s=e.responsiveness??.25,a=e.maximumAdjustmentFactor??2;if(Br(o,"minimumScale"),Br(i,"maximumScale"),Br(a,"maximumAdjustmentFactor"),o>1||i<1)throw new Error("GPUCommandGraph budget scale range must contain the initial scale 1");if(!Number.isFinite(s)||s<=0||s>1)throw new Error("GPUCommandGraph budget responsiveness must be in the interval (0, 1]");if(a<1)throw new Error("GPUCommandGraph budget maximumAdjustmentFactor must be at least 1");this.initialBudget=aa(e.initialBudget),this.currentBudget=this.initialBudget,this.latencyPriority=t,this.targetStepMilliseconds=n,this.minimumScale=o,this.maximumScale=i,this.responsiveness=s,this.maximumAdjustmentFactor=a}get budget(){return this.currentBudget}get sampleCount(){return this.currentSampleCount}reset(){this.currentBudget=this.initialBudget,this.currentScale=1,this.currentSampleCount=0}observeStep(e,t,n=this.currentBudget){Br(t,"durationMilliseconds"),ia(n);let o=qc(e,n);if(o>0){let i=this.targetStepMilliseconds*Math.min(o,1)/t,a=1+(sa(i,1/this.maximumAdjustmentFactor,this.maximumAdjustmentFactor)-1)*this.responsiveness;this.currentScale=sa(this.currentScale*a,this.minimumScale,this.maximumScale),this.currentBudget=Yc(this.initialBudget,this.currentScale)}return this.currentSampleCount++,Object.freeze({sampleCount:this.currentSampleCount,durationMilliseconds:t,targetStepMilliseconds:this.targetStepMilliseconds,latencyPriority:this.latencyPriority,saturation:o,scale:this.currentScale,budget:this.currentBudget})}};function qc(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 Yc(r,e){return aa({maximumInvocationCount:Lr(r.maximumInvocationCount,e),...r.maximumNodeCount===void 0?{}:{maximumNodeCount:Lr(r.maximumNodeCount,e)},...r.maximumCommandCount===void 0?{}:{maximumCommandCount:Lr(r.maximumCommandCount,e)},...r.maximumReadByteLength===void 0?{}:{maximumReadByteLength:Lr(r.maximumReadByteLength,e)},...r.maximumWriteByteLength===void 0?{}:{maximumWriteByteLength:Lr(r.maximumWriteByteLength,e)}})}function Lr(r,e){return Math.max(1,Math.min(Number.MAX_SAFE_INTEGER,Math.round(r*e)))}function aa(r){return Object.freeze({...r})}function Br(r,e){if(!Number.isFinite(r)||r<=0)throw new Error(`GPUCommandGraph budget ${e} must be positive`)}function ia(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 sa(r,e,t){return Math.max(e,Math.min(t,r))}var Ln=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:Xc(e.stats),capabilities:Object.freeze({...e.capabilities}),...e.preflight?{preflight:Kc(e.preflight)}:{},encodingCount:0,timingReadFailureCount:0,cpuSamples:[],gpuSamples:[],counters:new Map,nodes:new Map});let t=this.getGraph(e.id);for(let n of e.preflight?.nodes??[])this.getNode(t,n)}observeGraph(e){this.registerGraph(e);let t=this.getGraph(e.id),n=new WeakMap,o=!0,i=()=>o&&this.graphs.get(e.id)===t;return Object.freeze({graph:e,encode:(s,a)=>{let u=e.encode(s,a);return i()&&this.recordGraphEncoding(t,u),u},recordGPUTimings:async s=>{let a=n.get(s);if(a)return await a;if(i()&&this.encodingGraphs.get(s)===t){let u=this.recordGraphGPUTimings(e.id,t,s);return n.set(s,u),await u}},recordCounters:s=>{i()&&this.recordGraphCounters(t,s)},detach:()=>{o&&(o=!1,this.graphs.get(e.id)===t&&this.graphs.delete(e.id))}})}clear(){this.graphs.clear()}recordEncoding(e,t){let n=this.getGraph(e);this.recordGraphEncoding(n,t)}async readResource(e,t,n){let o=this.getGraph(e);if(!o.encoding?.readResource)throw new Error("No live resource readback is available.");let i=await o.encoding.readResource(t,n);if(this.graphs.get(e)!==o)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:n}=t;e.encodingCount++,this.addSample(e.cpuSamples,n.cpuEncodeTimeMilliseconds);for(let o of n.nodes){let i=this.getNode(e,o);this.addSample(i.cpuSamples,o.cpuEncodeTimeMilliseconds)}}recordGraphCounters(e,t){let n=Object.entries(t);for(let[o,i]of n)if(!o||!Number.isFinite(i)||i<0)throw new Error("GPUCommandGraphInspector counters require an ID and a finite, non-negative value");for(let[o,i]of n){let s=e.counters.get(o);s||(s=[],e.counters.set(o,s)),this.addSample(s,i)}}async recordGPUTimings(e,t){let o=this.encodingGraphs.get(t)??this.getGraph(e);return await this.recordGraphGPUTimings(e,o,t)}async recordGraphGPUTimings(e,t,n){if(this.graphs.get(e)!==t)return;let o;try{o=await n.readTimings()}catch{this.graphs.get(e)===t&&t.timingReadFailureCount++;return}if(this.graphs.get(e)===t){o.gpuTimeMilliseconds!==void 0&&this.addSample(t.gpuSamples,o.gpuTimeMilliseconds);for(let i of o.nodes)if(i.gpuTimeMilliseconds!==void 0){let s=this.getNode(t,i);this.addSample(s.gpuSamples,i.gpuTimeMilliseconds)}return o}}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 n=e.nodes.get(t.id);if(n)return t.description!==void 0&&(n.description=t.description),t.resources!==void 0&&(n.resources=ei(t.resources)),n;let o=ei(t.resources),i=this.getNodeGroup?.({graphId:e.id,id:t.id,type:t.type,description:t.description,resources:o}),s={id:t.id,resources:o,...t.description===void 0?{}:{description:t.description},type:t.type,...i===void 0?{}:{group:i},cpuSamples:[],gpuSamples:[]};return e.nodes.set(s.id,s),s}addSample(e,t){e.push(t),e.length>this.maxSamples&&e.splice(0,e.length-this.maxSamples)}getGraphSnapshot(e){let t=[],n=new Set;for(let s of e.stats.nodeOrder){let a=e.nodes.get(s);a&&(t.push(a),n.add(s))}for(let s of e.nodes.values())n.has(s.id)||t.push(s);let o=t.map(s=>Object.freeze({id:s.id,resources:s.resources,...s.description===void 0?{}:{description:s.description},type:s.type,...s.group===void 0?{}:{group:s.group},cpu:Cn(s.cpuSamples),gpu:Cn(s.gpuSamples)})),i=Array.from(e.counters,([s,a])=>Zc(s,a));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:Cn(e.cpuSamples),gpu:Cn(e.gpuSamples)}),counters:Object.freeze(i),nodes:Object.freeze(o)})}};function Xc(r){return Object.freeze({...r,nodeOrder:Object.freeze([...r.nodeOrder])})}function Kc(r){return Object.freeze({...r,nodes:Object.freeze(r.nodes.map(e=>Object.freeze({...e,resources:ei(e.resources)})))})}function Cn(r){if(r.length===0)return Object.freeze({sampleCount:0});let e=[...r].sort((t,n)=>t-n);return Object.freeze({sampleCount:r.length,latestMilliseconds:r[r.length-1],p50Milliseconds:Bn(e,.5),p95Milliseconds:Bn(e,.95)})}function Zc(r,e){let t=[...e].sort((n,o)=>n-o);return Object.freeze({id:r,sampleCount:e.length,latestValue:e[e.length-1],p50Value:Bn(t,.5),p95Value:Bn(t,.95)})}function Bn(r,e){return r[Math.ceil(e*r.length)-1]}function ei(r){return r&&Object.freeze(r.map(e=>Object.freeze({...e})))}function ua(r){return{type:r.type,shaderLanguage:r.info.shadingLanguage,shaderLanguageVersion:r.info.shadingLanguageVersion,gpu:r.info.gpu,limits:r.limits,features:r.features}}var ti=F(A(),1);var On=class{type="compaction";id;props;constructor(e){this.id=e.id??`${e.output}-compaction`,this.props=Object.freeze({...e})}get contract(){let{input:e,flags:t,output:n,count:o}=this.props;return{outputs:({getValue:i})=>{for(let s of[e,t]){let a=i(s);(0,ti.assert)(a.type==="vector"&&a.format==="uint32")}return(0,ti.assert)(n!==o),{[n]:M.vector("uint32"),[o]:M.scalar("uint32")}},values:[{value:e,access:"read"},{value:t,access:"read"},{value:n,access:"write",shape:{like:e}},{value:o,access:"write"}]}}};return ya(Or);})();
731
+ }`,vertexEntryPoint:"vertexMain",fragmentEntryPoint:"fragmentMain",topology:"triangle-list",shaderLayout:{attributes:[],bindings:i},colorAttachmentFormats:[t.outputDescriptor.format],parameters:{depthWriteEnabled:!1}}),this.vertexArray=e.createVertexArray({shaderLayout:this.kernel.pipeline.shaderLayout,bufferLayout:[]});for(let[u,c]of Object.entries(t.samplers))this.samplers[u]=e.createSampler(c)}catch(u){throw this.destroy(),u}}validateTextures(e){for(let t of[...Object.values(this.operation.inputs),this.operation.output]){let n=e.get(t);(0,ae.assert)(n);let o=ee(n);(0,ae.assert)(o.texture.device===this.device&&o.dimension==="2d"&&o.depth===1&&o.samples===1),t===this.operation.output&&(0,ae.assert)(o.mipLevels===1)}}lower(e){let t=this.operation,n=Object.fromEntries(Object.entries(t.inputs).map(([s,a])=>[s,e.resolveTextureView(a)])),o=e.resolveTextureView(t.output),i=this.parameterFormats.length?e.graph.createTransientBuffer({id:e.graph.getUniqueResourceId(`${t.id}-parameters`),byteLength:this.parameterByteLength,usage:ae.Buffer.UNIFORM|ae.Buffer.COPY_DST}):void 0;if(i){let s=Object.values(t.parameters).map(a=>e.resolveScalar(a).view);e.graph.addCopyPass({id:`${t.id}-parameters`,resources:[...s.map(a=>({buffer:a,usage:"copy-source"})),{buffer:i,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:a,getBuffer:u})=>{s.forEach((c,d)=>a.copyBufferToBuffer({sourceBuffer:u(c),sourceOffset:c.byteOffset,destinationBuffer:u(i),destinationOffset:d*4,size:4}))}})})}e.graph.addRenderPass({id:t.id,resources:[...Object.values(n).map(s=>({texture:s,usage:"sampled"})),...i?[{buffer:i,usage:"uniform"}]:[]],attachments:{colorAttachments:[o]},compile:()=>({getRenderPassProps:()=>({clearColor:[0,0,0,0],clearDepth:!1}),encode:({renderPass:s,getTextureView:a,getBuffer:u})=>this.draw(s,Object.fromEntries(Object.entries(n).map(([c,d])=>[c,a(d)])),i?u(i):void 0)})})}prepare(e,t){this.validateTextures(e);let n=Object.fromEntries(Object.entries(this.operation.inputs).map(([l,h])=>[l,e.get(h)])),o=e.get(this.operation.output),i=ee(o),s=new Uint8Array(this.parameterByteLength),a=new DataView(s.buffer),u=Object.values(this.operation.parameters).map((l,h)=>{let f=t.get(l);if((0,ae.assert)(f!==void 0),typeof f=="number")switch(this.parameterFormats[h]){case"float32":a.setFloat32(h*4,f,!0);break;case"sint32":a.setInt32(h*4,f,!0);break;case"uint32":a.setUint32(h*4,f,!0);break}else(0,ae.assert)(f.length===1&&f.data.length===1);return f}),c=s.byteLength?this.device.createBuffer({data:s,usage:ae.Buffer.UNIFORM|ae.Buffer.COPY_DST}):void 0,d;try{d=this.device.createFramebuffer({width:i.width,height:i.height,colorAttachments:[o]})}catch(l){throw c?.destroy(),l}return{encode:l=>{this.validateTextures(e),c&&u.forEach((f,m)=>{if(!(f instanceof H))return;let p=f.data[0],y=p.buffer instanceof ae.Buffer?p.buffer:p.buffer.buffer;l.copyBufferToBuffer({sourceBuffer:y,sourceOffset:p.byteOffset,destinationBuffer:c,destinationOffset:m*4,size:4})});let h=l.beginRenderPass({framebuffer:d,clearColor:[0,0,0,0],clearDepth:!1});try{this.draw(h,n,c)}finally{h.end()}},destroy:()=>{d.destroy(),c?.destroy()}}}destroy(){for(let e of Object.values(this.samplers))e.destroy();this.vertexArray?.destroy(),this.kernel?.destroy()}draw(e,t,n){let o={...t,...this.samplers};n&&(o.parameters=n),this.kernel.draw(e,{vertexArray:this.vertexArray,vertexCount:3,bindings:o})}};var Te=class{type="cpu";id;inputs;outputs;execute;constructor(e){this.id=e.id,this.inputs=Object.freeze({...e.inputs}),this.outputs=Object.freeze(Object.fromEntries(Object.entries(e.outputs).map(([t,n])=>[t,Object.freeze({...n,...n.chunkLengths?{chunkLengths:Object.freeze([...n.chunkLengths])}:{}})]))),this.execute=e.execute}get contract(){return{outputs:this.outputs,values:[...Object.values(this.inputs).map(e=>({value:e,access:"read"})),...Object.keys(this.outputs).map(e=>({value:e,access:"write"}))]}}};var re=F(A(),1);var Pr=class{device;program;compileStage;stages=[];constructor(e,t,n){this.device=e,this.program=t,this.compileStage=n,(0,re.assert)(!t.textures.length&&!t.vectors.some(s=>s.role==="state"));let o=[...t.scalars,...t.vectors],i=(s,a)=>{let u=o.find(d=>d.id===a);(0,re.assert)(u);let c=t.vectors.find(d=>d.id===a);c?s.addInput(a,M.vector(c.format,{length:c.length,chunkLengths:c.chunkLengths})):s.addInput(a,M.scalar(t.scalars.find(d=>d.id===a).format))};try{for(let s of t.operations){if(s instanceof Te){this.stages.push(s);continue}(0,re.assert)("contract"in s&&s.contract);let a=s.contract.values.filter(d=>d.access!=="write").map(d=>typeof d.value=="string"?d.value:d.value.id),u=s.contract.values.filter(d=>d.access!=="read").map(d=>typeof d.value=="string"?d.value:d.value.id),c=new ke;for(let d of new Set(a))i(c,d);for(let d of new Set(u)){let l=t.vectors.find(h=>h.id===d);l&&c.addDeclaration(d,M.vector(l.format,{length:l.length,chunkLengths:l.chunkLengths}),"value")}c.add(s),this.stages.push({graph:n(c,u),inputs:a})}}catch(s){throw this.destroy(),s}}async run(e,t={}){for(let[u,c]of Object.entries(t))(0,re.assert)(this.program.outputs.includes(u)&&(c==="cpu"||c==="gpu"));let n=new Map;for(let u of[...this.program.vectors,...this.program.scalars].filter(c=>c.role==="input")){let c=e[u.id];if((0,re.assert)(c!==void 0),!(c instanceof Ee)){let d=new ke,l=this.program.vectors.find(h=>h.id===u.id);l?d.addInput(u.id,M.vector(l.format,{length:l.length,chunkLengths:l.chunkLengths})):d.addInput(u.id,M.scalar(this.program.scalars.find(h=>h.id===u.id).format)),new Wt(d,{outputs:[]}).prepare(this.device,{[u.id]:c}).finish()}if(c instanceof Ee){(0,re.assert)(c.data.every(l=>!l.nullBitmap&&!l.valueOffsets)),(0,re.assert)(c.format===u.format);let d=this.program.vectors.find(l=>l.id===u.id);(0,re.assert)(d&&(d.length===void 0||d.length===c.length)),(0,re.assert)(!d.chunkLengths||d.chunkLengths.length===c.data.length&&d.chunkLengths.every((l,h)=>l===c.data[h].length)),n.set(u.id,c)}}let o={...e},i=new Set,s=async u=>{let c=n.get(u);if(!c){let d=o[u];(0,re.assert)(d instanceof H);let l=await Nc(d);c=ea(l.format,l.chunks.map(h=>h.values)),n.set(u,c)}return zc(c)},a=async u=>{let c=o[u];if(c instanceof H)return c;let d=await s(u),l=new ke;l.add(new qe({output:u,format:d.format,data:d.chunks.map(f=>f.values)}));let h=this.compileStage(l);try{let f=(await h.run({}))[u];return i.add(f),o[u]=f,f}finally{h.destroy()}};try{for(let c of this.stages){let d;if(c instanceof Te){let l=Object.create(null);for(let[f,m]of Object.entries(c.inputs)){let p=o[m],y=typeof p=="number"?p:await s(m);l[f]=typeof y!="number"&&this.program.scalars.some(g=>g.id===m)?y.pack()[0]:y}let h=await c.execute({inputs:l});(0,re.assert)(Object.keys(h).length===Object.keys(c.outputs).length);for(let f of Object.keys(c.outputs)){let m=this.program.vectors.find(S=>S.id===f),p=h[f];(0,re.assert)(p);let y="chunks"in p?p.chunks.map(S=>S.values):[p],g=new qe({output:f,format:m.format,data:y}),w=g.chunkLengths.reduce((S,T)=>S+T,0);(0,re.assert)(m.length===void 0||m.length===w),(0,re.assert)(!m.chunkLengths||m.chunkLengths.length===y.length&&m.chunkLengths.every((S,T)=>S===g.chunkLengths[T])),n.set(f,ea(m.format,y)),delete o[f]}continue}else{let l=Object.create(null);for(let h of c.inputs){let f=o[h];l[h]=this.program.scalars.some(m=>m.id===h)?typeof f=="number"?f:(await s(h)).pack()[0]:await a(h)}d=await c.graph.run({inputs:l})}for(let[l,h]of Object.entries(d))n.delete(l),o[l]=h,i.add(h)}let u=Object.create(null);for(let c of this.program.outputs)t[c]==="cpu"?(await s(c),u[c]=n.get(c)):u[c]=await a(c);for(let c of Object.values(u))c instanceof H&&i.delete(c);return u}finally{for(let u of i)u.destroy()}}destroy(){for(let e of this.stages)e instanceof Te||e.graph.destroy()}};async function Nc(r){(0,re.assert)(r.format);let e=U(r.format),t=e.signedDataType==="float32"?Float32Array:e.signedDataType==="uint32"?Uint32Array:Int32Array,n=[];for(let o of r.data){let i=new t(o.length*e.byteLength/4);if(o.length){let s=await o.buffer.readAsync(o.byteOffset,(o.length-1)*o.byteStride+e.byteLength),a=new Uint8Array(i.buffer);for(let u=0;u<o.length;u++)a.set(s.subarray(u*o.byteStride,u*o.byteStride+e.byteLength),u*e.byteLength)}n.push({values:i,length:o.length})}return{format:r.format,length:r.length,chunks:n,pack(){let o=new t(n.reduce((s,a)=>s+a.values.length,0)),i=0;for(let s of n)o.set(s.values,i),i+=s.values.length;return o}}}function ea(r,e){let t=U(r).byteLength;return new Ee({format:r,data:e.map(n=>new ar({buffer:n,format:r,length:n.byteLength/t}))})}function zc(r){let e=r.format;(0,re.assert)(/^(float32|sint32|uint32)(x[234])?$/.test(e));let t=U(e),n=t.signedDataType==="float32"?Float32Array:t.signedDataType==="uint32"?Uint32Array:Int32Array,o=r.data.map(i=>{let s=new n(i.length*t.components),a=new Uint8Array(s.buffer);for(let u=0;u<i.length;u++)a.set(new Uint8Array(i.buffer,i.byteOffset+u*i.byteStride,t.byteLength),u*t.byteLength);return{values:s,length:i.length}});return{format:e,length:r.length,chunks:o,pack(){let i=new n(r.length*t.components),s=0;for(let a of o)i.set(a.values,s),s+=a.values.length;return i}}}var Yt=class r{device;program;stageLowerings;compiler;kernels=new Map;shaderPasses=new Map;destroyed=!1;runningCPU=!1;cpuExecution;outputLocations;constructor(e,t,n={},o){if(this.device=e,e.type!=="webgpu")throw new Error("GPUGraph execution requires WebGPU");if(this.program=new Wt(t,n),this.outputLocations=n.outputLocations??{},this.stageLowerings=o??n.lowerings??[],this.compiler=new St(e,[...o??n.lowerings??[],{type:"shader-pass",lower:(i,s)=>this.shaderPasses.get(i).lower(s)},{type:"expression",lower:(i,s)=>this.kernels.get(i).lower(s)}]),this.program.operations.some(i=>i instanceof Te)||Object.values(this.outputLocations).includes("cpu")){this.cpuExecution=new Pr(e,this.program,(i,s)=>new r(e,i,{outputs:s},o??n.lowerings));return}try{for(let i of this.program.expressions)this.kernels.set(i.operation,new xn(e,this.program,i));for(let i of this.program.operations)i instanceof ft&&this.shaderPasses.set(i,new wn(e,i,this.program))}catch(i){throw this.destroy(),i}}async run(e,t={}){(0,Pt.assert)(!this.destroyed&&!this.runningCPU);let n="inputs"in e?e.inputs:e,o=this.program.operations.some(a=>a instanceof Te)||Object.values(this.outputLocations).includes("cpu")||Object.values(n??{}).some(a=>a instanceof Ee);if(!this.cpuExecution&&o&&(this.cpuExecution=new Pr(this.device,this.program,(a,u)=>new r(this.device,a,{outputs:u},this.stageLowerings))),o&&this.cpuExecution){let a=this.program.resolveBindings(e,t);(0,Pt.assert)(!a.options.outputTargets||Object.keys(a.options.outputTargets).length===0),this.runningCPU=!0;try{return await this.cpuExecution.run(a.bindings,this.outputLocations)}finally{this.runningCPU=!1}}let i=this.prepare(e,t),s;try{return s=this.device.createCommandEncoder(),i.encode(s),this.device.submit(s.finish()),i.outputs}catch(a){throw i.discard(),a}finally{i.destroy(),s?.destroy()}}prepare(e,t={}){if((0,Pt.assert)(!this.destroyed),this.program.operations.some(a=>a instanceof Te)||Object.values(this.outputLocations).includes("cpu"))throw new Error("CPU operations require asynchronous run(), not prepare()");let n=this.program.resolveBindings(e,t),o=n.bindings;t=n.options;let i=this.program.prepare(this.device,o,t,!0),s;try{for(let h of this.shaderPasses.values())h.validateTextures(i.textures.values);let a=new ke;for(let h of this.program.scalars)a.scalar(h.id,h.format);let u=Object.create(null),c=Object.create(null);for(let[h,f]of i.values)typeof f=="number"?c[h]=f:this.program.vectors.some(m=>m.id===h)&&(u[h]=f);for(let[h,f]of Object.entries(o))typeof f=="number"&&(c[h]=f);for(let h of this.program.vectors){let f=u[h.id],m=i.transientVectors.get(h.id);if(m){a.addDeclaration(h.id,{type:"vector",format:h.format,length:m.length,chunkLengths:m.chunkLengths},"value");continue}if(!f&&h.length===void 0)throw new Error(`Missing length or execution binding for ${h.id}`);a.vector(h.id,h.format,f?.length??h.length,{external:!!f,chunkLengths:f?.data.map(p=>p.length)??h.chunkLengths})}let d=Object.create(null);for(let h of this.program.textures){let f=i.textures.values.get(h.id),m=ee(f);a.texture(h.id,{format:m.format,dimension:m.dimension,width:m.width,height:m.height,depth:m.depth,mipLevels:m.mipLevels,samples:m.samples,usage:m.texture.props.usage,external:!0}),d[h.id]=f}a.add(this.program.operations);let l=this.compiler.compile(a,{vectors:u,scalars:c,textures:d});for(let h of this.program.scalars){let f=i.values.get(h.id);if(!(f instanceof H))continue;let m=l.scalars.get(h.id).view,p=l.graph.importGPUVector(`${h.id}-result`,f).data[0];l.graph.addCopyPass({id:`${h.id}-result-copy`,resources:[{buffer:m,usage:"copy-source"},{buffer:p,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:y,getBuffer:g})=>y.copyBufferToBuffer({sourceBuffer:g(m),sourceOffset:m.byteOffset,destinationBuffer:g(p),destinationOffset:p.byteOffset,size:4})})})}return s=l.graph.compile(),new Cr(this.device,i,s,()=>{(0,Pt.assert)(!this.destroyed)})}catch(a){throw s?.destroy(),i.destroy(),a}}destroy(){(0,Pt.assert)(!this.runningCPU),this.cpuExecution?.destroy();for(let e of this.shaderPasses.values())e.destroy();this.shaderPasses.clear();for(let e of this.kernels.values())e.destroy();this.kernels.clear(),this.destroyed=!0}},Cr=class{device;invocation;executable;checkProgram;outputs;encoded=!1;destroyed=!1;constructor(e,t,n,o){this.device=e,this.invocation=t,this.executable=n,this.checkProgram=o,this.outputs=t.getOutputs()}encode(e){(0,Pt.assert)(!this.destroyed&&!this.encoded&&e.device===this.device),this.checkProgram(),this.encoded=!0,this.executable.encode(e,{parameters:void 0})}destroy(){this.destroyed||(this.destroyed=!0,this.executable.destroy(),this.invocation.finish())}discard(){this.destroyed||(this.destroyed=!0,this.executable.destroy(),this.invocation.destroy())}};var ke=class r{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}addInput(e,t){return this.addDeclaration(e,t,"input")}addState(e,t){if(t.type!=="vector")throw new Error("Graph state requires vector storage");return this.addDeclaration(e,t,"state")}addDeclaration(e,t,n){if(this.assertValueId(e),t.type==="texture"){let i=new de({id:e,...t,usage:0,role:n,descriptor:t,external:n==="input",..."width"in(t.extent??{})?t.extent:{}});return this.programTextures.set(e,i),i}if(t.type==="scalar"){let i=new Ae(e,t.format,n);return this.programScalars.set(e,i),i}let o=new Q({id:e,...t,role:n,external:n==="input"||n==="state"});return this.programVectors.set(e,o),o}scalar(e,t){this.assertValueId(e);let n=new Ae(e,t);return this.programScalars.set(e,n),n}vector(e,t,n,o={}){this.assertValueId(e);let i=typeof n=="number"?{length:n,...o}:n??o,s=new Q({id:e,format:t,...i});return this.programVectors.set(e,s),s}texture(e,t){this.assertValueId(e);let n=new de({...t,id:e});return this.programTextures.set(e,n),n}textureView(e,t={}){if(this.programTextures.get(e.id)!==e)throw new Error(`Undeclared program texture "${e.id}"`);return new Fe(e,t)}compile(e,t={}){return new Yt(e,this,t)}constrainResult(e,t){if(e.length!==void 0&&t.length!==void 0&&e.length!==t.length)throw new Error(`Incompatible result length ${e.id}`);if(e.chunkLengths&&t.chunkLengths&&(e.chunkLengths.length!==t.chunkLengths.length||e.chunkLengths.some((o,i)=>o!==t.chunkLengths[i])))throw new Error(`Incompatible result chunks ${e.id}`);let n=new Q({...e,length:e.length??t.length,chunkLengths:e.chunkLengths??t.chunkLengths});return this.programVectors.set(e.id,n),n}clone(){let e=new r({id:this.id});for(let[t,n]of this.programScalars)e.programScalars.set(t,n);for(let[t,n]of this.programVectors)e.programVectors.set(t,n);for(let[t,n]of this.programTextures)e.programTextures.set(t,n);return e.programOperations.push(...this.programOperations),e}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(jo))}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 Zo(r,e={}){return new q({id:e.id,operations:r})}function Qo(r){let e=r.lowering.decisions.map(t=>`${t.operationId}: ${t.lowering} \u2014 ${t.reason}`);return Object.freeze({programId:r.program.id,semanticOperationCount:ta(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 ta(r){return r.reduce((e,t)=>e+1+ta(t.children??[]),0)}var Ct=F(A(),1);var Tn=class{type="group-aggregation";id;props;constructor(e){(0,Ct.assert)(e.groupCount===void 0||Number.isSafeInteger(e.groupCount)&&e.groupCount>0),this.id=e.id??`${k(e.output)}-group-aggregation`,this.props=Object.freeze({...e})}get contract(){let{keys:e,mask:t,output:n,groupCount:o}=this.props,i=this.props.operation==="count"?void 0:this.props.values;return{outputs:({getValue:s})=>{for(let a of[e,t])if(a){let u=s(k(a));(0,Ct.assert)(u.type==="vector"&&u.format==="uint32")}if(i){let a=s(k(i));(0,Ct.assert)(a.type==="vector"&&a.format==="float32")}return{[k(n)]:M.vector(this.props.operation==="count"?"uint32":"float32",{length:o})}},values:[{value:e,access:"read"},...i?[{value:i,access:"read"}]:[],...t?[{value:t,access:"read"}]:[],{value:n,access:"write"}]}}},vn=class{type="reduction";id;props;constructor(e){this.id=e.id??`${k(e.output)}-reduction`,this.props=Object.freeze({...e})}get contract(){let{input:e,mask:t,output:n,operation:o}=this.props;return{outputs:({getValue:i})=>{let s=i(k(e));(0,Ct.assert)(s.type==="vector");let{format:a}=s;if((0,Ct.assert)(a==="uint32"||a==="sint32"||a==="float32"),t){let u=i(k(t));(0,Ct.assert)(u.type==="vector"&&u.format==="uint32")}return{[k(n)]:M.vector(a,{length:o==="extent"?2:1})}},values:[{value:e,access:"read"},...t?[{value:t,access:"read"}]:[],{value:n,access:"write"}]}}};var En=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=jc(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){Sn(e.operation,"operation"),oa(e.workloadSize);let t=e.candidates.filter(a=>a.supported!==!1);if(t.length===0)throw new Error(`GPUCommandGraph autotuner operation "${e.operation}" has no supported variants`);for(let a of t)Sn(a.id,"variant");let n=na(e.workloadSize),o=t.map(a=>{let u=this.findNearestCalibration(e.operation,a.id,n);return{candidate:a,calibration:u,sampleCount:u?.workloadBucket===n?u.sampleCount:0,estimatedDurationMilliseconds:u?Wc(u,e.workloadSize):void 0}});if(this.explorationEnabled){let a=o.find(u=>u.sampleCount<this.minimumSampleCount);if(a)return Object.freeze({operation:e.operation,variant:a.candidate.id,workloadSize:e.workloadSize,workloadBucket:n,reason:"exploration",sampleCount:a.sampleCount,...a.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:a.estimatedDurationMilliseconds}})}let i=o.filter(a=>a.estimatedDurationMilliseconds!==void 0).sort((a,u)=>(a.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY)-(u.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY))[0],s=i??o[0];return Object.freeze({operation:e.operation,variant:s.candidate.id,workloadSize:e.workloadSize,workloadBucket:n,reason:i?"calibrated":"fallback",sampleCount:s.calibration?.sampleCount??0,...s.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:s.estimatedDurationMilliseconds}})}observeKernel(e){if(Sn(e.operation,"operation"),Sn(e.variant,"variant"),oa(e.workloadSize),!Number.isFinite(e.durationMilliseconds)||e.durationMilliseconds<0)throw new Error("GPUCommandGraph autotuner durationMilliseconds must be nonnegative");let t=na(e.workloadSize),n=Jo(e.operation,e.variant,t),o=this.calibrations.get(n)??{operation:e.operation,variant:e.variant,workloadBucket:t,sampleCount:0,meanWorkloadSize:0,meanDurationMilliseconds:0,durationSquaredDifferenceSum:0};o.sampleCount++,o.meanWorkloadSize+=(e.workloadSize-o.meanWorkloadSize)/o.sampleCount;let i=e.durationMilliseconds-o.meanDurationMilliseconds;return o.meanDurationMilliseconds+=i/o.sampleCount,o.durationSquaredDifferenceSum+=i*(e.durationMilliseconds-o.meanDurationMilliseconds),this.calibrations.set(n,o),ra(o)}observeTimingReport(e,t){let n=new Map(t.nodes.map(i=>[i.id,i])),o=0;for(let i of e.nodes){let s=n.get(i.id);i.gpuTimeMilliseconds===void 0||!s?.operation||!s.variant||(this.observeKernel({operation:s.operation,variant:s.variant,workloadSize:Math.max(s.maximumInvocationCount,1),durationMilliseconds:i.gpuTimeMilliseconds}),o++)}return o}exportProfile(){let e=[...this.calibrations.values()].sort((t,n)=>t.operation.localeCompare(n.operation)||t.variant.localeCompare(n.variant)||t.workloadBucket-n.workloadBucket).map(ra);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(Jo(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,n){let o=this.calibrations.get(Jo(e,t,n));if(o)return o;let i;for(let s of this.calibrations.values())s.operation!==e||s.variant!==t||(!i||Math.abs(s.workloadBucket-n)<Math.abs(i.workloadBucket-n))&&(i=s);return i}};function ia(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 jc(r){return Object.freeze({...r,features:Object.freeze([...r.features])})}function ra(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 Wc(r,e){return r.meanDurationMilliseconds*(e/Math.max(r.meanWorkloadSize,1))}function na(r){return Math.floor(Math.log2(Math.max(r,1)))}function Jo(r,e,t){return`${r}\0${e}\0${t}`}function Sn(r,e){if(!r)throw new Error(`GPUCommandGraph autotuner ${e} is required`)}function oa(r){if(!Number.isSafeInteger(r)||r<=0)throw new Error("GPUCommandGraph autotuner workloadSize must be a positive safe integer")}var Hc={interactive:4,normal:8,background:16},Pn=class{targetStepMilliseconds;latencyPriority;minimumScale;maximumScale;responsiveness;maximumAdjustmentFactor;initialBudget;currentBudget;currentScale=1;currentSampleCount=0;constructor(e){ei(e.initialBudget);let t=e.latencyPriority??"normal",n=e.targetStepMilliseconds??Hc[t];Br(n,"targetStepMilliseconds");let o=e.minimumScale??.125,i=e.maximumScale??4,s=e.responsiveness??.25,a=e.maximumAdjustmentFactor??2;if(Br(o,"minimumScale"),Br(i,"maximumScale"),Br(a,"maximumAdjustmentFactor"),o>1||i<1)throw new Error("GPUCommandGraph budget scale range must contain the initial scale 1");if(!Number.isFinite(s)||s<=0||s>1)throw new Error("GPUCommandGraph budget responsiveness must be in the interval (0, 1]");if(a<1)throw new Error("GPUCommandGraph budget maximumAdjustmentFactor must be at least 1");this.initialBudget=aa(e.initialBudget),this.currentBudget=this.initialBudget,this.latencyPriority=t,this.targetStepMilliseconds=n,this.minimumScale=o,this.maximumScale=i,this.responsiveness=s,this.maximumAdjustmentFactor=a}get budget(){return this.currentBudget}get sampleCount(){return this.currentSampleCount}reset(){this.currentBudget=this.initialBudget,this.currentScale=1,this.currentSampleCount=0}observeStep(e,t,n=this.currentBudget){return ei(n),this.observeSaturation(qc(e,n),t)}observeInvocations(e,t,n=this.currentBudget){return ei(n),this.observeSaturation(e/n.maximumInvocationCount,t)}observeSaturation(e,t){if(Br(t,"durationMilliseconds"),e>0){let n=this.targetStepMilliseconds*Math.min(e,1)/t,i=1+(sa(n,1/this.maximumAdjustmentFactor,this.maximumAdjustmentFactor)-1)*this.responsiveness;this.currentScale=sa(this.currentScale*i,this.minimumScale,this.maximumScale),this.currentBudget=Yc(this.initialBudget,this.currentScale)}return this.currentSampleCount++,Object.freeze({sampleCount:this.currentSampleCount,durationMilliseconds:t,targetStepMilliseconds:this.targetStepMilliseconds,latencyPriority:this.latencyPriority,saturation:e,scale:this.currentScale,budget:this.currentBudget})}};function qc(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 Yc(r,e){return aa({maximumInvocationCount:Lr(r.maximumInvocationCount,e),...r.maximumNodeCount===void 0?{}:{maximumNodeCount:Lr(r.maximumNodeCount,e)},...r.maximumCommandCount===void 0?{}:{maximumCommandCount:Lr(r.maximumCommandCount,e)},...r.maximumReadByteLength===void 0?{}:{maximumReadByteLength:Lr(r.maximumReadByteLength,e)},...r.maximumWriteByteLength===void 0?{}:{maximumWriteByteLength:Lr(r.maximumWriteByteLength,e)}})}function Lr(r,e){return Math.max(1,Math.min(Number.MAX_SAFE_INTEGER,Math.round(r*e)))}function aa(r){return Object.freeze({...r})}function Br(r,e){if(!Number.isFinite(r)||r<=0)throw new Error(`GPUCommandGraph budget ${e} must be positive`)}function ei(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 sa(r,e,t){return Math.max(e,Math.min(t,r))}var Ln=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:Xc(e.stats),capabilities:Object.freeze({...e.capabilities}),...e.preflight?{preflight:Kc(e.preflight)}:{},encodingCount:0,timingReadFailureCount:0,cpuSamples:[],gpuSamples:[],counters:new Map,nodes:new Map});let t=this.getGraph(e.id);for(let n of e.preflight?.nodes??[])this.getNode(t,n)}observeGraph(e){this.registerGraph(e);let t=this.getGraph(e.id),n=new WeakMap,o=!0,i=()=>o&&this.graphs.get(e.id)===t;return Object.freeze({graph:e,encode:(s,a)=>{let u=e.encode(s,a);return i()&&this.recordGraphEncoding(t,u),u},recordGPUTimings:async s=>{let a=n.get(s);if(a)return await a;if(i()&&this.encodingGraphs.get(s)===t){let u=this.recordGraphGPUTimings(e.id,t,s);return n.set(s,u),await u}},recordCounters:s=>{i()&&this.recordGraphCounters(t,s)},detach:()=>{o&&(o=!1,this.graphs.get(e.id)===t&&this.graphs.delete(e.id))}})}clear(){this.graphs.clear()}recordEncoding(e,t){let n=this.getGraph(e);this.recordGraphEncoding(n,t)}async readResource(e,t,n){let o=this.getGraph(e);if(!o.encoding?.readResource)throw new Error("No live resource readback is available.");let i=await o.encoding.readResource(t,n);if(this.graphs.get(e)!==o)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:n}=t;e.encodingCount++,this.addSample(e.cpuSamples,n.cpuEncodeTimeMilliseconds);for(let o of n.nodes){let i=this.getNode(e,o);this.addSample(i.cpuSamples,o.cpuEncodeTimeMilliseconds)}}recordGraphCounters(e,t){let n=Object.entries(t);for(let[o,i]of n)if(!o||!Number.isFinite(i)||i<0)throw new Error("GPUCommandGraphInspector counters require an ID and a finite, non-negative value");for(let[o,i]of n){let s=e.counters.get(o);s||(s=[],e.counters.set(o,s)),this.addSample(s,i)}}async recordGPUTimings(e,t){let o=this.encodingGraphs.get(t)??this.getGraph(e);return await this.recordGraphGPUTimings(e,o,t)}async recordGraphGPUTimings(e,t,n){if(this.graphs.get(e)!==t)return;let o;try{o=await n.readTimings()}catch{this.graphs.get(e)===t&&t.timingReadFailureCount++;return}if(this.graphs.get(e)===t){o.gpuTimeMilliseconds!==void 0&&this.addSample(t.gpuSamples,o.gpuTimeMilliseconds);for(let i of o.nodes)if(i.gpuTimeMilliseconds!==void 0){let s=this.getNode(t,i);this.addSample(s.gpuSamples,i.gpuTimeMilliseconds)}return o}}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 n=e.nodes.get(t.id);if(n)return t.description!==void 0&&(n.description=t.description),t.resources!==void 0&&(n.resources=ti(t.resources)),n;let o=ti(t.resources),i=this.getNodeGroup?.({graphId:e.id,id:t.id,type:t.type,description:t.description,resources:o}),s={id:t.id,resources:o,...t.description===void 0?{}:{description:t.description},type:t.type,...i===void 0?{}:{group:i},cpuSamples:[],gpuSamples:[]};return e.nodes.set(s.id,s),s}addSample(e,t){e.push(t),e.length>this.maxSamples&&e.splice(0,e.length-this.maxSamples)}getGraphSnapshot(e){let t=[],n=new Set;for(let s of e.stats.nodeOrder){let a=e.nodes.get(s);a&&(t.push(a),n.add(s))}for(let s of e.nodes.values())n.has(s.id)||t.push(s);let o=t.map(s=>Object.freeze({id:s.id,resources:s.resources,...s.description===void 0?{}:{description:s.description},type:s.type,...s.group===void 0?{}:{group:s.group},cpu:Cn(s.cpuSamples),gpu:Cn(s.gpuSamples)})),i=Array.from(e.counters,([s,a])=>Zc(s,a));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:Cn(e.cpuSamples),gpu:Cn(e.gpuSamples)}),counters:Object.freeze(i),nodes:Object.freeze(o)})}};function Xc(r){return Object.freeze({...r,nodeOrder:Object.freeze([...r.nodeOrder])})}function Kc(r){return Object.freeze({...r,nodes:Object.freeze(r.nodes.map(e=>Object.freeze({...e,resources:ti(e.resources)})))})}function Cn(r){if(r.length===0)return Object.freeze({sampleCount:0});let e=[...r].sort((t,n)=>t-n);return Object.freeze({sampleCount:r.length,latestMilliseconds:r[r.length-1],p50Milliseconds:Bn(e,.5),p95Milliseconds:Bn(e,.95)})}function Zc(r,e){let t=[...e].sort((n,o)=>n-o);return Object.freeze({id:r,sampleCount:e.length,latestValue:e[e.length-1],p50Value:Bn(t,.5),p95Value:Bn(t,.95)})}function Bn(r,e){return r[Math.ceil(e*r.length)-1]}function ti(r){return r&&Object.freeze(r.map(e=>Object.freeze({...e})))}function ua(r){return{type:r.type,shaderLanguage:r.info.shadingLanguage,shaderLanguageVersion:r.info.shadingLanguageVersion,gpu:r.info.gpu,limits:r.limits,features:r.features}}var ri=F(A(),1);var On=class{type="compaction";id;props;constructor(e){this.id=e.id??`${e.output}-compaction`,this.props=Object.freeze({...e})}get contract(){let{input:e,flags:t,output:n,count:o}=this.props;return{outputs:({getValue:i})=>{for(let s of[e,t]){let a=i(s);(0,ri.assert)(a.type==="vector"&&a.format==="uint32")}return(0,ri.assert)(n!==o),{[n]:M.vector("uint32"),[o]:M.scalar("uint32")}},values:[{value:e,access:"read"},{value:t,access:"read"},{value:n,access:"write",shape:{like:e}},{value:o,access:"write"}]}}};return ya(Or);})();
731
732
  return __exports__;
732
733
  });