@egret/engine 0.0.0-stage → 7.0.1-rc.3

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 (575) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +21 -0
  3. package/README.md +101 -2
  4. package/README.zh-CN.md +102 -0
  5. package/dist/Engine.d.ts +77 -0
  6. package/dist/Engine.js +464 -0
  7. package/dist/animation/index.d.ts +6 -0
  8. package/dist/animation/index.js +5 -0
  9. package/dist/animation/sequenceController.d.ts +22 -0
  10. package/dist/animation/sequenceController.js +618 -0
  11. package/dist/animation/sequenceCoordinator.d.ts +26 -0
  12. package/dist/animation/sequenceCoordinator.js +161 -0
  13. package/dist/animation/sequenceInput.d.ts +25 -0
  14. package/dist/animation/sequenceInput.js +108 -0
  15. package/dist/animation/sequenceMath.d.ts +35 -0
  16. package/dist/animation/sequenceMath.js +164 -0
  17. package/dist/animation/sequenceResetSlot.d.ts +7 -0
  18. package/dist/animation/sequenceResetSlot.js +367 -0
  19. package/dist/animation/sequenceResetTypes.d.ts +42 -0
  20. package/dist/animation/sequenceResetTypes.js +2 -0
  21. package/dist/animation/types.d.ts +69 -0
  22. package/dist/animation/types.js +2 -0
  23. package/dist/assetBundle.d.ts +52 -0
  24. package/dist/assetBundle.js +173 -0
  25. package/dist/assetGroup.d.ts +17 -0
  26. package/dist/assetGroup.js +332 -0
  27. package/dist/assetGroupTypes.d.ts +15 -0
  28. package/dist/assetGroupTypes.js +2 -0
  29. package/dist/audio.d.ts +4 -0
  30. package/dist/audio.js +4 -0
  31. package/dist/audioCues.d.ts +43 -0
  32. package/dist/audioCues.js +127 -0
  33. package/dist/audioMixer.d.ts +7 -0
  34. package/dist/audioMixer.js +785 -0
  35. package/dist/audioTypes.d.ts +233 -0
  36. package/dist/audioTypes.js +3 -0
  37. package/dist/bitmapBindingTicket.d.ts +24 -0
  38. package/dist/bitmapBindingTicket.js +215 -0
  39. package/dist/bitmapButton.d.ts +4 -0
  40. package/dist/bitmapButton.js +407 -0
  41. package/dist/bitmapButtonTypes.d.ts +29 -0
  42. package/dist/bitmapButtonTypes.js +2 -0
  43. package/dist/bitmapFontParse.d.ts +10 -0
  44. package/dist/bitmapFontParse.js +246 -0
  45. package/dist/bitmapFontTypes.d.ts +109 -0
  46. package/dist/bitmapFontTypes.js +2 -0
  47. package/dist/bitmapResourceSlot.d.ts +25 -0
  48. package/dist/bitmapResourceSlot.js +340 -0
  49. package/dist/bitmapText.d.ts +6 -0
  50. package/dist/bitmapText.js +320 -0
  51. package/dist/bitmapfont.d.ts +5 -0
  52. package/dist/bitmapfont.js +5 -0
  53. package/dist/camera.d.ts +4 -0
  54. package/dist/camera.js +4 -0
  55. package/dist/camera2d.d.ts +7 -0
  56. package/dist/camera2d.js +411 -0
  57. package/dist/cameraTypes.d.ts +114 -0
  58. package/dist/cameraTypes.js +2 -0
  59. package/dist/closeHost.d.ts +4 -0
  60. package/dist/closeHost.js +66 -0
  61. package/dist/contentArtifacts.d.ts +12 -0
  62. package/dist/contentArtifacts.js +153 -0
  63. package/dist/contentAtlasPages.d.ts +13 -0
  64. package/dist/contentAtlasPages.js +117 -0
  65. package/dist/contentLoader.d.ts +6 -0
  66. package/dist/contentLoader.js +327 -0
  67. package/dist/contentTypes.d.ts +33 -0
  68. package/dist/contentTypes.js +2 -0
  69. package/dist/createEngine.d.ts +7 -0
  70. package/dist/createEngine.js +25 -0
  71. package/dist/createEngineForProfile.d.ts +5 -0
  72. package/dist/createEngineForProfile.js +42 -0
  73. package/dist/displaySubtreeTicket.d.ts +25 -0
  74. package/dist/displaySubtreeTicket.js +76 -0
  75. package/dist/fontContentLoader.d.ts +6 -0
  76. package/dist/fontContentLoader.js +298 -0
  77. package/dist/fontContentTypes.d.ts +34 -0
  78. package/dist/fontContentTypes.js +2 -0
  79. package/dist/gameClock.d.ts +24 -0
  80. package/dist/gameClock.js +246 -0
  81. package/dist/gameClockTypes.d.ts +31 -0
  82. package/dist/gameClockTypes.js +2 -0
  83. package/dist/gameRun.d.ts +50 -0
  84. package/dist/gameRun.js +97 -0
  85. package/dist/gamepad.d.ts +5 -0
  86. package/dist/gamepad.js +5 -0
  87. package/dist/gamepadInput.d.ts +4 -0
  88. package/dist/gamepadInput.js +281 -0
  89. package/dist/gamepadKeys.d.ts +4 -0
  90. package/dist/gamepadKeys.js +205 -0
  91. package/dist/gamepadTypes.d.ts +134 -0
  92. package/dist/gamepadTypes.js +3 -0
  93. package/dist/hover.d.ts +4 -0
  94. package/dist/hover.js +4 -0
  95. package/dist/hoverInput.d.ts +8 -0
  96. package/dist/hoverInput.js +503 -0
  97. package/dist/hoverInputTypes.d.ts +119 -0
  98. package/dist/hoverInputTypes.js +2 -0
  99. package/dist/index.d.ts +49 -0
  100. package/dist/index.js +20 -0
  101. package/dist/input.d.ts +6 -0
  102. package/dist/input.js +5 -0
  103. package/dist/inputActions.d.ts +81 -0
  104. package/dist/inputActions.js +330 -0
  105. package/dist/internal/contentFactoryState.d.ts +19 -0
  106. package/dist/internal/contentFactoryState.js +42 -0
  107. package/dist/internal/mouseInputFactoryState.d.ts +57 -0
  108. package/dist/internal/mouseInputFactoryState.js +125 -0
  109. package/dist/internal/sequenceControllerFactoryState.d.ts +42 -0
  110. package/dist/internal/sequenceControllerFactoryState.js +98 -0
  111. package/dist/internal/textFieldFactoryState.d.ts +11 -0
  112. package/dist/internal/textFieldFactoryState.js +32 -0
  113. package/dist/internal/texturedFrameState.d.ts +4 -0
  114. package/dist/internal/texturedFrameState.js +12 -0
  115. package/dist/internal/uiFactoryState.d.ts +64 -0
  116. package/dist/internal/uiFactoryState.js +157 -0
  117. package/dist/internal/uiRootState.d.ts +67 -0
  118. package/dist/internal/uiRootState.js +103 -0
  119. package/dist/keyboardInput.d.ts +12 -0
  120. package/dist/keyboardInput.js +578 -0
  121. package/dist/keyboardInputTypes.d.ts +81 -0
  122. package/dist/keyboardInputTypes.js +2 -0
  123. package/dist/kit.d.ts +14 -0
  124. package/dist/kit.js +9 -0
  125. package/dist/layout.d.ts +5 -0
  126. package/dist/layout.js +132 -0
  127. package/dist/layoutTypes.d.ts +28 -0
  128. package/dist/layoutTypes.js +2 -0
  129. package/dist/manifestAssetGroup.d.ts +10 -0
  130. package/dist/manifestAssetGroup.js +477 -0
  131. package/dist/manifestResourceState.d.ts +16 -0
  132. package/dist/manifestResourceState.js +57 -0
  133. package/dist/manifestResourceTypes.d.ts +25 -0
  134. package/dist/manifestResourceTypes.js +2 -0
  135. package/dist/motion.d.ts +33 -0
  136. package/dist/motion.js +206 -0
  137. package/dist/mouseInput.d.ts +102 -0
  138. package/dist/mouseInput.js +562 -0
  139. package/dist/mouseInputTypes.d.ts +37 -0
  140. package/dist/mouseInputTypes.js +2 -0
  141. package/dist/paragraph.d.ts +8 -0
  142. package/dist/paragraph.js +7 -0
  143. package/dist/particleEmitter.d.ts +4 -0
  144. package/dist/particleEmitter.js +292 -0
  145. package/dist/particleTypes.d.ts +107 -0
  146. package/dist/particleTypes.js +2 -0
  147. package/dist/particles.d.ts +4 -0
  148. package/dist/particles.js +4 -0
  149. package/dist/physics2d.d.ts +4 -0
  150. package/dist/physics2d.js +4 -0
  151. package/dist/physics2dGeometry.d.ts +39 -0
  152. package/dist/physics2dGeometry.js +230 -0
  153. package/dist/physics2dTypes.d.ts +167 -0
  154. package/dist/physics2dTypes.js +2 -0
  155. package/dist/physics2dWorld.d.ts +4 -0
  156. package/dist/physics2dWorld.js +623 -0
  157. package/dist/pointerInput.d.ts +11 -0
  158. package/dist/pointerInput.js +299 -0
  159. package/dist/pointerInputTypes.d.ts +38 -0
  160. package/dist/pointerInputTypes.js +2 -0
  161. package/dist/random.d.ts +29 -0
  162. package/dist/random.js +131 -0
  163. package/dist/rendering/ownedPreparationFailure2D.d.ts +5 -0
  164. package/dist/rendering/ownedPreparationFailure2D.js +33 -0
  165. package/dist/rendering/packSharedDraws2D.d.ts +50 -0
  166. package/dist/rendering/packSharedDraws2D.js +331 -0
  167. package/dist/rendering/packedOrientation.d.ts +4 -0
  168. package/dist/rendering/packedOrientation.js +7 -0
  169. package/dist/rendering/prepareRectangles2D.d.ts +92 -0
  170. package/dist/rendering/prepareRectangles2D.js +481 -0
  171. package/dist/rendering/prepareSharedDraws2D.d.ts +88 -0
  172. package/dist/rendering/prepareSharedDraws2D.js +652 -0
  173. package/dist/rendering/preparedBatches2D.d.ts +17 -0
  174. package/dist/rendering/preparedBatches2D.js +30 -0
  175. package/dist/rendering/preparedSharedBatches2D.d.ts +44 -0
  176. package/dist/rendering/preparedSharedBatches2D.js +247 -0
  177. package/dist/rendering/sharedColor2D.d.ts +18 -0
  178. package/dist/rendering/sharedColor2D.js +68 -0
  179. package/dist/rendering/sharedEffects2D.d.ts +23 -0
  180. package/dist/rendering/sharedEffects2D.js +118 -0
  181. package/dist/rendering/sharedPreparationRetention2D.d.ts +120 -0
  182. package/dist/rendering/sharedPreparationRetention2D.js +357 -0
  183. package/dist/rendering/srgbBytes.d.ts +3 -0
  184. package/dist/rendering/srgbBytes.js +64 -0
  185. package/dist/rendering/texturedPreparationBudget2D.d.ts +31 -0
  186. package/dist/rendering/texturedPreparationBudget2D.js +81 -0
  187. package/dist/rendering/world3d/Animation3D.d.ts +95 -0
  188. package/dist/rendering/world3d/Animation3D.js +380 -0
  189. package/dist/rendering/world3d/AnimationTexture3D.d.ts +157 -0
  190. package/dist/rendering/world3d/AnimationTexture3D.js +601 -0
  191. package/dist/rendering/world3d/Batch3D.d.ts +71 -0
  192. package/dist/rendering/world3d/Batch3D.js +329 -0
  193. package/dist/rendering/world3d/Camera3D.d.ts +57 -0
  194. package/dist/rendering/world3d/Camera3D.js +129 -0
  195. package/dist/rendering/world3d/Character3D.d.ts +123 -0
  196. package/dist/rendering/world3d/Character3D.js +303 -0
  197. package/dist/rendering/world3d/Cloth3D.d.ts +115 -0
  198. package/dist/rendering/world3d/Cloth3D.js +498 -0
  199. package/dist/rendering/world3d/Compression3D.d.ts +21 -0
  200. package/dist/rendering/world3d/Compression3D.js +702 -0
  201. package/dist/rendering/world3d/Curves3D.d.ts +111 -0
  202. package/dist/rendering/world3d/Curves3D.js +455 -0
  203. package/dist/rendering/world3d/Decal3D.d.ts +41 -0
  204. package/dist/rendering/world3d/Decal3D.js +241 -0
  205. package/dist/rendering/world3d/Geometry3D.d.ts +85 -0
  206. package/dist/rendering/world3d/Geometry3D.js +326 -0
  207. package/dist/rendering/world3d/GeometryBuilder3D.d.ts +51 -0
  208. package/dist/rendering/world3d/GeometryBuilder3D.js +196 -0
  209. package/dist/rendering/world3d/Gizmo3D.d.ts +75 -0
  210. package/dist/rendering/world3d/Gizmo3D.js +512 -0
  211. package/dist/rendering/world3d/Gltf3D.d.ts +67 -0
  212. package/dist/rendering/world3d/Gltf3D.js +976 -0
  213. package/dist/rendering/world3d/GpuParticles3D.d.ts +107 -0
  214. package/dist/rendering/world3d/GpuParticles3D.js +400 -0
  215. package/dist/rendering/world3d/Hdr3D.d.ts +33 -0
  216. package/dist/rendering/world3d/Hdr3D.js +190 -0
  217. package/dist/rendering/world3d/Jelly3D.d.ts +75 -0
  218. package/dist/rendering/world3d/Jelly3D.js +266 -0
  219. package/dist/rendering/world3d/Ktx23D.d.ts +27 -0
  220. package/dist/rendering/world3d/Ktx23D.js +112 -0
  221. package/dist/rendering/world3d/Light3D.d.ts +75 -0
  222. package/dist/rendering/world3d/Light3D.js +93 -0
  223. package/dist/rendering/world3d/Material3D.d.ts +243 -0
  224. package/dist/rendering/world3d/Material3D.js +267 -0
  225. package/dist/rendering/world3d/Mesh3D.d.ts +108 -0
  226. package/dist/rendering/world3d/Mesh3D.js +323 -0
  227. package/dist/rendering/world3d/Meshopt3D.d.ts +12 -0
  228. package/dist/rendering/world3d/Meshopt3D.js +275 -0
  229. package/dist/rendering/world3d/Navigation3D.d.ts +173 -0
  230. package/dist/rendering/world3d/Navigation3D.js +971 -0
  231. package/dist/rendering/world3d/Object3D.d.ts +107 -0
  232. package/dist/rendering/world3d/Object3D.js +305 -0
  233. package/dist/rendering/world3d/Particles3D.d.ts +85 -0
  234. package/dist/rendering/world3d/Particles3D.js +274 -0
  235. package/dist/rendering/world3d/Physics3D.d.ts +416 -0
  236. package/dist/rendering/world3d/Physics3D.js +2835 -0
  237. package/dist/rendering/world3d/PhysicsHull3D.d.ts +35 -0
  238. package/dist/rendering/world3d/PhysicsHull3D.js +227 -0
  239. package/dist/rendering/world3d/PhysicsMesh3D.d.ts +39 -0
  240. package/dist/rendering/world3d/PhysicsMesh3D.js +338 -0
  241. package/dist/rendering/world3d/PhysicsQueries3D.d.ts +24 -0
  242. package/dist/rendering/world3d/PhysicsQueries3D.js +323 -0
  243. package/dist/rendering/world3d/PhysicsRemote3D.d.ts +174 -0
  244. package/dist/rendering/world3d/PhysicsRemote3D.js +534 -0
  245. package/dist/rendering/world3d/Ragdoll3D.d.ts +69 -0
  246. package/dist/rendering/world3d/Ragdoll3D.js +200 -0
  247. package/dist/rendering/world3d/Raycast3D.d.ts +37 -0
  248. package/dist/rendering/world3d/Raycast3D.js +246 -0
  249. package/dist/rendering/world3d/RenderList3D.d.ts +88 -0
  250. package/dist/rendering/world3d/RenderList3D.js +490 -0
  251. package/dist/rendering/world3d/Retarget3D.d.ts +20 -0
  252. package/dist/rendering/world3d/Retarget3D.js +185 -0
  253. package/dist/rendering/world3d/Serialize3D.d.ts +49 -0
  254. package/dist/rendering/world3d/Serialize3D.js +607 -0
  255. package/dist/rendering/world3d/StateMachine3D.d.ts +78 -0
  256. package/dist/rendering/world3d/StateMachine3D.js +277 -0
  257. package/dist/rendering/world3d/Terrain3D.d.ts +227 -0
  258. package/dist/rendering/world3d/Terrain3D.js +803 -0
  259. package/dist/rendering/world3d/Text3D.d.ts +90 -0
  260. package/dist/rendering/world3d/Text3D.js +558 -0
  261. package/dist/rendering/world3d/Texture3D.d.ts +133 -0
  262. package/dist/rendering/world3d/Texture3D.js +252 -0
  263. package/dist/rendering/world3d/Trail3D.d.ts +59 -0
  264. package/dist/rendering/world3d/Trail3D.js +193 -0
  265. package/dist/rendering/world3d/Vehicle3D.d.ts +97 -0
  266. package/dist/rendering/world3d/Vehicle3D.js +226 -0
  267. package/dist/rendering/world3d/VolumetricFog3D.d.ts +55 -0
  268. package/dist/rendering/world3d/VolumetricFog3D.js +229 -0
  269. package/dist/rendering/world3d/Water3D.d.ts +163 -0
  270. package/dist/rendering/world3d/Water3D.js +606 -0
  271. package/dist/rendering/world3d/core3D.d.ts +34 -0
  272. package/dist/rendering/world3d/core3D.js +99 -0
  273. package/dist/rendering/world3d/debug3D.d.ts +64 -0
  274. package/dist/rendering/world3d/debug3D.js +257 -0
  275. package/dist/rendering/world3d/decoders3D.d.ts +42 -0
  276. package/dist/rendering/world3d/decoders3D.js +133 -0
  277. package/dist/rendering/world3d/geometries3D.d.ts +99 -0
  278. package/dist/rendering/world3d/geometries3D.js +605 -0
  279. package/dist/rendering/world3d/helpers3D.d.ts +65 -0
  280. package/dist/rendering/world3d/helpers3D.js +177 -0
  281. package/dist/rendering/world3d/index.d.ts +91 -0
  282. package/dist/rendering/world3d/index.js +56 -0
  283. package/dist/rendering/world3d/math3D.d.ts +78 -0
  284. package/dist/rendering/world3d/math3D.js +640 -0
  285. package/dist/rendering/world3d/primitives3D.d.ts +60 -0
  286. package/dist/rendering/world3d/primitives3D.js +196 -0
  287. package/dist/resources.d.ts +8 -0
  288. package/dist/resources.js +6 -0
  289. package/dist/saveStore.d.ts +56 -0
  290. package/dist/saveStore.js +163 -0
  291. package/dist/semanticList.d.ts +122 -0
  292. package/dist/semanticList.js +174 -0
  293. package/dist/semanticTree.d.ts +10 -0
  294. package/dist/semanticTree.js +532 -0
  295. package/dist/semanticTypes.d.ts +167 -0
  296. package/dist/semanticTypes.js +2 -0
  297. package/dist/semantics.d.ts +6 -0
  298. package/dist/semantics.js +5 -0
  299. package/dist/sequencePlayback.d.ts +19 -0
  300. package/dist/sequencePlayback.js +391 -0
  301. package/dist/sequencePlaybackTypes.d.ts +21 -0
  302. package/dist/sequencePlaybackTypes.js +2 -0
  303. package/dist/sequenceTargetClaims.d.ts +10 -0
  304. package/dist/sequenceTargetClaims.js +31 -0
  305. package/dist/srgbBytes.d.ts +3 -0
  306. package/dist/srgbBytes.js +64 -0
  307. package/dist/startEngine.d.ts +5 -0
  308. package/dist/startEngine.js +31 -0
  309. package/dist/surfaceOwnership.d.ts +3 -0
  310. package/dist/surfaceOwnership.js +15 -0
  311. package/dist/text.d.ts +23 -0
  312. package/dist/text.js +4 -0
  313. package/dist/textField.d.ts +6 -0
  314. package/dist/textField.js +6 -0
  315. package/dist/tileMapDraw.d.ts +7 -0
  316. package/dist/tileMapDraw.js +310 -0
  317. package/dist/tiledImport.d.ts +9 -0
  318. package/dist/tiledImport.js +357 -0
  319. package/dist/tilemap.d.ts +5 -0
  320. package/dist/tilemap.js +5 -0
  321. package/dist/tilemapTypes.d.ts +169 -0
  322. package/dist/tilemapTypes.js +2 -0
  323. package/dist/tween.d.ts +15 -0
  324. package/dist/tween.js +329 -0
  325. package/dist/tweenTypes.d.ts +27 -0
  326. package/dist/tweenTypes.js +2 -0
  327. package/dist/ui/controlKeys.d.ts +109 -0
  328. package/dist/ui/controlKeys.js +249 -0
  329. package/dist/ui/controls.d.ts +52 -0
  330. package/dist/ui/controls.js +288 -0
  331. package/dist/ui/editing.d.ts +3 -0
  332. package/dist/ui/editing.js +3 -0
  333. package/dist/ui/index.d.ts +19 -0
  334. package/dist/ui/index.js +11 -0
  335. package/dist/ui/keyboardFocus.d.ts +32 -0
  336. package/dist/ui/keyboardFocus.js +146 -0
  337. package/dist/ui/layerTypes.d.ts +91 -0
  338. package/dist/ui/layerTypes.js +2 -0
  339. package/dist/ui/layers.d.ts +4 -0
  340. package/dist/ui/layers.js +586 -0
  341. package/dist/ui/leafContent.d.ts +21 -0
  342. package/dist/ui/leafContent.js +136 -0
  343. package/dist/ui/rangeControl.d.ts +50 -0
  344. package/dist/ui/rangeControl.js +167 -0
  345. package/dist/ui/scrollControl.d.ts +72 -0
  346. package/dist/ui/scrollControl.js +218 -0
  347. package/dist/ui/stateControls.d.ts +82 -0
  348. package/dist/ui/stateControls.js +328 -0
  349. package/dist/ui/textEditor.d.ts +53 -0
  350. package/dist/ui/textEditor.js +370 -0
  351. package/dist/ui/textEditorTypes.d.ts +78 -0
  352. package/dist/ui/textEditorTypes.js +2 -0
  353. package/dist/ui/textFieldControl.d.ts +96 -0
  354. package/dist/ui/textFieldControl.js +259 -0
  355. package/dist/ui/theme.d.ts +59 -0
  356. package/dist/ui/theme.js +165 -0
  357. package/dist/ui/types.d.ts +265 -0
  358. package/dist/ui/types.js +2 -0
  359. package/dist/ui/uiRoot.d.ts +4 -0
  360. package/dist/ui/uiRoot.js +1497 -0
  361. package/dist/ui/uiRootDisplay.d.ts +46 -0
  362. package/dist/ui/uiRootDisplay.js +148 -0
  363. package/dist/ui/uiRootModel.d.ts +112 -0
  364. package/dist/ui/uiRootModel.js +60 -0
  365. package/dist/ui/virtualList.d.ts +20 -0
  366. package/dist/ui/virtualList.js +105 -0
  367. package/dist/video.d.ts +4 -0
  368. package/dist/video.js +4 -0
  369. package/dist/videoPlayer.d.ts +4 -0
  370. package/dist/videoPlayer.js +215 -0
  371. package/dist/videoTypes.d.ts +74 -0
  372. package/dist/videoTypes.js +2 -0
  373. package/dist/web/BrowserAssetBundle.d.ts +39 -0
  374. package/dist/web/BrowserAssetBundle.js +136 -0
  375. package/dist/web/BrowserAudio.d.ts +41 -0
  376. package/dist/web/BrowserAudio.js +473 -0
  377. package/dist/web/BrowserFrameLoop.d.ts +65 -0
  378. package/dist/web/BrowserFrameLoop.js +125 -0
  379. package/dist/web/BrowserGame.d.ts +112 -0
  380. package/dist/web/BrowserGame.js +352 -0
  381. package/dist/web/BrowserGamepadInput.d.ts +35 -0
  382. package/dist/web/BrowserGamepadInput.js +134 -0
  383. package/dist/web/BrowserHoverInput.d.ts +24 -0
  384. package/dist/web/BrowserHoverInput.js +266 -0
  385. package/dist/web/BrowserImageTextures.d.ts +66 -0
  386. package/dist/web/BrowserImageTextures.js +169 -0
  387. package/dist/web/BrowserInputActions.d.ts +53 -0
  388. package/dist/web/BrowserInputActions.js +342 -0
  389. package/dist/web/BrowserKeyboardInput.d.ts +4 -0
  390. package/dist/web/BrowserKeyboardInput.js +223 -0
  391. package/dist/web/BrowserPlay.d.ts +289 -0
  392. package/dist/web/BrowserPlay.js +1301 -0
  393. package/dist/web/BrowserPointerInput.d.ts +4 -0
  394. package/dist/web/BrowserPointerInput.js +511 -0
  395. package/dist/web/BrowserSemantics.d.ts +34 -0
  396. package/dist/web/BrowserSemantics.js +418 -0
  397. package/dist/web/BrowserStatsPanel.d.ts +46 -0
  398. package/dist/web/BrowserStatsPanel.js +137 -0
  399. package/dist/web/BrowserStorage.d.ts +33 -0
  400. package/dist/web/BrowserStorage.js +132 -0
  401. package/dist/web/BrowserTextEditor.d.ts +49 -0
  402. package/dist/web/BrowserTextEditor.js +839 -0
  403. package/dist/web/BrowserTextInput.d.ts +83 -0
  404. package/dist/web/BrowserTextInput.js +524 -0
  405. package/dist/web/BrowserTextureProvider.d.ts +52 -0
  406. package/dist/web/BrowserTextureProvider.js +935 -0
  407. package/dist/web/BrowserVideo.d.ts +28 -0
  408. package/dist/web/BrowserVideo.js +211 -0
  409. package/dist/web/CanvasKitFontSetProvider.d.ts +29 -0
  410. package/dist/web/CanvasKitFontSetProvider.js +215 -0
  411. package/dist/web/CanvasKitParagraphProvider.d.ts +169 -0
  412. package/dist/web/CanvasKitParagraphProvider.js +691 -0
  413. package/dist/web/CanvasTextRasterProvider.d.ts +4 -0
  414. package/dist/web/CanvasTextRasterProvider.js +312 -0
  415. package/dist/web/ManifestByteSource.d.ts +147 -0
  416. package/dist/web/ManifestByteSource.js +974 -0
  417. package/dist/web/ManifestFontContentLoader.d.ts +12 -0
  418. package/dist/web/ManifestFontContentLoader.js +30 -0
  419. package/dist/web/MouseInput.d.ts +4 -0
  420. package/dist/web/MouseInput.js +218 -0
  421. package/dist/web/WebGL2Host.d.ts +5 -0
  422. package/dist/web/WebGL2Host.js +2672 -0
  423. package/dist/web/WebGPUHost.d.ts +87 -0
  424. package/dist/web/WebGPUHost.js +3349 -0
  425. package/dist/web/audio.d.ts +3 -0
  426. package/dist/web/audio.js +4 -0
  427. package/dist/web/canvasKitParagraphGeometry.d.ts +27 -0
  428. package/dist/web/canvasKitParagraphGeometry.js +83 -0
  429. package/dist/web/editing.d.ts +5 -0
  430. package/dist/web/editing.js +4 -0
  431. package/dist/web/editorFonts.d.ts +50 -0
  432. package/dist/web/editorFonts.js +297 -0
  433. package/dist/web/game.d.ts +5 -0
  434. package/dist/web/game.js +6 -0
  435. package/dist/web/gamepad.d.ts +3 -0
  436. package/dist/web/gamepad.js +4 -0
  437. package/dist/web/hover.d.ts +3 -0
  438. package/dist/web/hover.js +4 -0
  439. package/dist/web/image.d.ts +4 -0
  440. package/dist/web/image.js +4 -0
  441. package/dist/web/imageProjections2D.d.ts +14 -0
  442. package/dist/web/imageProjections2D.js +2 -0
  443. package/dist/web/input.d.ts +6 -0
  444. package/dist/web/input.js +4 -0
  445. package/dist/web/keyboard.d.ts +3 -0
  446. package/dist/web/keyboard.js +3 -0
  447. package/dist/web/kit.d.ts +10 -0
  448. package/dist/web/kit.js +7 -0
  449. package/dist/web/loop.d.ts +3 -0
  450. package/dist/web/loop.js +4 -0
  451. package/dist/web/paragraph.d.ts +6 -0
  452. package/dist/web/paragraph.js +4 -0
  453. package/dist/web/play.d.ts +5 -0
  454. package/dist/web/play.js +6 -0
  455. package/dist/web/playSfx.d.ts +36 -0
  456. package/dist/web/playSfx.js +112 -0
  457. package/dist/web/pointer.d.ts +3 -0
  458. package/dist/web/pointer.js +3 -0
  459. package/dist/web/prepareSharedSubmission2D.d.ts +27 -0
  460. package/dist/web/prepareSharedSubmission2D.js +57 -0
  461. package/dist/web/resources.d.ts +27 -0
  462. package/dist/web/resources.js +96 -0
  463. package/dist/web/semantics.d.ts +3 -0
  464. package/dist/web/semantics.js +4 -0
  465. package/dist/web/sharedDeviceSession.d.ts +64 -0
  466. package/dist/web/sharedDeviceSession.js +2 -0
  467. package/dist/web/sharedEffectShaders.d.ts +9 -0
  468. package/dist/web/sharedEffectShaders.js +165 -0
  469. package/dist/web/sharedFrameUpload.d.ts +25 -0
  470. package/dist/web/sharedFrameUpload.js +2 -0
  471. package/dist/web/sharedHostDeferred.d.ts +7 -0
  472. package/dist/web/sharedHostDeferred.js +12 -0
  473. package/dist/web/sharedRetentionLedger.d.ts +85 -0
  474. package/dist/web/sharedRetentionLedger.js +391 -0
  475. package/dist/web/sharedSubmissionStorage2D.d.ts +56 -0
  476. package/dist/web/sharedSubmissionStorage2D.js +73 -0
  477. package/dist/web/sharedWebGL2Arena.d.ts +40 -0
  478. package/dist/web/sharedWebGL2Arena.js +77 -0
  479. package/dist/web/sharedWebGL2Options.d.ts +30 -0
  480. package/dist/web/sharedWebGL2Options.js +96 -0
  481. package/dist/web/sharedWebGL2Shaders.d.ts +20 -0
  482. package/dist/web/sharedWebGL2Shaders.js +314 -0
  483. package/dist/web/sharedWebGPUOptions.d.ts +37 -0
  484. package/dist/web/sharedWebGPUOptions.js +126 -0
  485. package/dist/web/text.d.ts +3 -0
  486. package/dist/web/text.js +3 -0
  487. package/dist/web/textInput.d.ts +3 -0
  488. package/dist/web/textInput.js +3 -0
  489. package/dist/web/video.d.ts +3 -0
  490. package/dist/web/video.js +4 -0
  491. package/dist/web/webgl2.d.ts +7 -0
  492. package/dist/web/webgl2.js +4 -0
  493. package/dist/web/webgl2LayerState.d.ts +50 -0
  494. package/dist/web/webgl2LayerState.js +102 -0
  495. package/dist/web/webgl2Native.d.ts +70 -0
  496. package/dist/web/webgl2Native.js +568 -0
  497. package/dist/web/webgl2Types.d.ts +132 -0
  498. package/dist/web/webgl2Types.js +2 -0
  499. package/dist/web/webgpu.d.ts +6 -0
  500. package/dist/web/webgpu.js +2 -0
  501. package/dist/web/webgpuBindingCache.d.ts +26 -0
  502. package/dist/web/webgpuBindingCache.js +223 -0
  503. package/dist/web/webgpuBufferPool.d.ts +51 -0
  504. package/dist/web/webgpuBufferPool.js +58 -0
  505. package/dist/web/webgpuImageResidency.d.ts +53 -0
  506. package/dist/web/webgpuImageResidency.js +61 -0
  507. package/dist/web/webgpuLifetime.d.ts +45 -0
  508. package/dist/web/webgpuLifetime.js +64 -0
  509. package/dist/web/webgpuRetentionPool.d.ts +66 -0
  510. package/dist/web/webgpuRetentionPool.js +84 -0
  511. package/dist/web/webgpuSharedPass.d.ts +7 -0
  512. package/dist/web/webgpuSharedPass.js +211 -0
  513. package/dist/web/webgpuSharedResolvePass.d.ts +3 -0
  514. package/dist/web/webgpuSharedResolvePass.js +29 -0
  515. package/dist/web/world3d/Audio3D.d.ts +68 -0
  516. package/dist/web/world3d/Audio3D.js +212 -0
  517. package/dist/web/world3d/BrowserPlay3D.d.ts +182 -0
  518. package/dist/web/world3d/BrowserPlay3D.js +851 -0
  519. package/dist/web/world3d/FlyControls3D.d.ts +55 -0
  520. package/dist/web/world3d/FlyControls3D.js +160 -0
  521. package/dist/web/world3d/FollowControls3D.d.ts +28 -0
  522. package/dist/web/world3d/FollowControls3D.js +117 -0
  523. package/dist/web/world3d/OrbitControls3D.d.ts +55 -0
  524. package/dist/web/world3d/OrbitControls3D.js +187 -0
  525. package/dist/web/world3d/TransformControls3D.d.ts +34 -0
  526. package/dist/web/world3d/TransformControls3D.js +125 -0
  527. package/dist/web/world3d/WebGL2Renderer3D.d.ts +133 -0
  528. package/dist/web/world3d/WebGL2Renderer3D.js +1173 -0
  529. package/dist/web/world3d/WebGPURenderer3D.d.ts +110 -0
  530. package/dist/web/world3d/WebGPURenderer3D.js +1915 -0
  531. package/dist/web/world3d/World3DView.d.ts +51 -0
  532. package/dist/web/world3d/World3DView.js +77 -0
  533. package/dist/web/world3d/app3D.d.ts +136 -0
  534. package/dist/web/world3d/app3D.js +304 -0
  535. package/dist/web/world3d/assets3D.d.ts +38 -0
  536. package/dist/web/world3d/assets3D.js +112 -0
  537. package/dist/web/world3d/atmosphere3D.d.ts +47 -0
  538. package/dist/web/world3d/atmosphere3D.js +178 -0
  539. package/dist/web/world3d/frame3D.d.ts +142 -0
  540. package/dist/web/world3d/frame3D.js +388 -0
  541. package/dist/web/world3d/gpuResources3D.d.ts +98 -0
  542. package/dist/web/world3d/gpuResources3D.js +901 -0
  543. package/dist/web/world3d/host3D.d.ts +23 -0
  544. package/dist/web/world3d/host3D.js +61 -0
  545. package/dist/web/world3d/index.d.ts +38 -0
  546. package/dist/web/world3d/index.js +23 -0
  547. package/dist/web/world3d/loaders3D.d.ts +26 -0
  548. package/dist/web/world3d/loaders3D.js +138 -0
  549. package/dist/web/world3d/markers3D.d.ts +49 -0
  550. package/dist/web/world3d/markers3D.js +130 -0
  551. package/dist/web/world3d/materialWebGL23D.d.ts +34 -0
  552. package/dist/web/world3d/materialWebGL23D.js +218 -0
  553. package/dist/web/world3d/overlay3D.d.ts +28 -0
  554. package/dist/web/world3d/overlay3D.js +170 -0
  555. package/dist/web/world3d/post3D.d.ts +112 -0
  556. package/dist/web/world3d/post3D.js +459 -0
  557. package/dist/web/world3d/postWebGL23D.d.ts +24 -0
  558. package/dist/web/world3d/postWebGL23D.js +237 -0
  559. package/dist/web/world3d/postWebGPU3D.d.ts +23 -0
  560. package/dist/web/world3d/postWebGPU3D.js +255 -0
  561. package/dist/web/world3d/probe3D.d.ts +14 -0
  562. package/dist/web/world3d/probe3D.js +66 -0
  563. package/dist/web/world3d/shaders3D.d.ts +43 -0
  564. package/dist/web/world3d/shaders3D.js +851 -0
  565. package/dist/web/world3d/stats3D.d.ts +31 -0
  566. package/dist/web/world3d/stats3D.js +80 -0
  567. package/dist/web/world3d/webGL2FrameMetrics3D.d.ts +66 -0
  568. package/dist/web/world3d/webGL2FrameMetrics3D.js +185 -0
  569. package/dist/web/world3d/webgpu.d.ts +35 -0
  570. package/dist/web/world3d/webgpu.js +22 -0
  571. package/dist/web/world3d/webgpuPacking3D.d.ts +13 -0
  572. package/dist/web/world3d/webgpuPacking3D.js +85 -0
  573. package/dist/web/world3d/wgsl3D.d.ts +68 -0
  574. package/dist/web/world3d/wgsl3D.js +781 -0
  575. package/package.json +220 -4
@@ -0,0 +1,3349 @@
1
+ import { SHARED_FRAME_PROFILE_2D } from '@egret/contracts';
2
+ import { admitSharedWebGPUOptions } from './sharedWebGPUOptions.js';
3
+ import { prepareSharedDraws2D, SharedPreparationError } from '../rendering/prepareSharedDraws2D.js';
4
+ import { SharedPreparationRetention2D } from '../rendering/sharedPreparationRetention2D.js';
5
+ import { planSharedSubmission2D, packSharedSubmission2D, packSharedRegionWindows2D, SHARED_REGION_WINDOW_STRIDE_2D, SHARED_REGION_WINDOW_BYTES_2D, materializeSharedPages2D, checkSharedCapacity2D, SharedStorageError2D } from './prepareSharedSubmission2D.js';
6
+ import { SHARED_BATCH_PAGES_2D } from '../rendering/packSharedDraws2D.js';
7
+ import { prepareSharedBatches2D } from '../rendering/preparedSharedBatches2D.js';
8
+ import { decodeSharedSRGBByte } from '../rendering/sharedColor2D.js';
9
+ import { createSharedWebGPUPipeline, SHARED_BLENDS, SHARED_PIPELINE_KINDS } from './webgpuSharedPass.js';
10
+ import { createSharedEffectPipeline, EFFECT_PASSES, EFFECT_UNIFORM_BYTES } from './sharedEffectShaders.js';
11
+ import { createSharedResolvePipeline } from './webgpuSharedResolvePass.js';
12
+ import { createWebGPURetentionPool } from './webgpuRetentionPool.js';
13
+ import { readOwnedSharedFrame } from '#egret-textured-frame-state';
14
+ import { EgretError } from '@egret/runtime';
15
+ import { GeometryPreparationError } from '../rendering/prepareRectangles2D.js';
16
+ import { PreparedBatchScratch2D } from '../rendering/preparedBatches2D.js';
17
+ import { collectWebGPUImageDemand, selectWebGPUImageVictims } from './webgpuImageResidency.js';
18
+ import { observed, deferred, cleanupWebGPUBuffer, cleanupWebGPUTexture, observeWebGPUDeviceLoss, observeAuthenticatedWebGPUDeviceLoss } from './webgpuLifetime.js';
19
+ import { runOwnedPreparationScope } from '../rendering/ownedPreparationFailure2D.js';
20
+ import { createWebGPUBindingCache } from './webgpuBindingCache.js';
21
+ const DEVICE_LIMIT_KEYS = [
22
+ 'maxTextureDimension2D',
23
+ 'maxBufferSize',
24
+ 'maxVertexBuffers',
25
+ 'maxVertexAttributes',
26
+ 'maxVertexBufferArrayStride',
27
+ 'maxColorAttachments',
28
+ 'maxColorAttachmentBytesPerSample',
29
+ 'maxBindGroups',
30
+ 'maxBindingsPerBindGroup',
31
+ 'maxSampledTexturesPerShaderStage',
32
+ 'maxSamplersPerShaderStage',
33
+ 'maxUniformBuffersPerShaderStage',
34
+ 'maxUniformBufferBindingSize',
35
+ 'maxBindGroupsPlusVertexBuffers',
36
+ 'maxInterStageShaderVariables'
37
+ ];
38
+ function error(code, cause) {
39
+ return new EgretError(code, { cause });
40
+ }
41
+ /** Private control-flow origin; callers receive only publicError, never this signal. */
42
+ class ClassifiedWebGPUFailure {
43
+ code;
44
+ original;
45
+ publicError;
46
+ constructor(code, original = undefined, publicError = error(code, original)) {
47
+ this.code = code;
48
+ this.original = original;
49
+ this.publicError = publicError;
50
+ }
51
+ }
52
+ function isObject(value) {
53
+ return typeof value === 'object' && value !== null;
54
+ }
55
+ const SHARED_OPTIONS = new WeakMap();
56
+ /** The sole lifecycle/submission authority; resource helpers only record settled ownership. */
57
+ class WebGPUHostImplementation {
58
+ surface;
59
+ options;
60
+ borrowed;
61
+ borrowedPolicy = false;
62
+ callback;
63
+ state = 'new';
64
+ starting;
65
+ startingPending = false;
66
+ closing;
67
+ busy = false;
68
+ cpu = deferred();
69
+ firstFailure = null;
70
+ callbackFailureCount = 0;
71
+ lastCallbackFailure = null;
72
+ cleanupOutcome = 'not-started';
73
+ unsafeCause;
74
+ unsafe = false;
75
+ finalizing = false;
76
+ lastSerial = 0;
77
+ pendingUploadBytes = 0;
78
+ pendingReadbackBytes = 0;
79
+ pendingTextureBytes = 0;
80
+ pendingGeometryBytes = 0;
81
+ pendingColorBytes = 0;
82
+ pendingCanonicalBytes = 0;
83
+ ledger = new Set();
84
+ batchScratch = new PreparedBatchScratch2D();
85
+ /** The prepared draws of the last frame. A Host that is not active keeps none. */
86
+ retention = new SharedPreparationRetention2D();
87
+ // Fixed-size observations only; original records/native owners still authorize every transition.
88
+ resourceCpu = {
89
+ canonicalBytes: 0,
90
+ scratchBytes: 0,
91
+ highCanonicalBytes: 0,
92
+ highScratchBytes: 0,
93
+ highTemporaryBytes: 0,
94
+ saturated: false
95
+ };
96
+ resourceUnknown = {
97
+ knownLogicalBytes: 0,
98
+ objects: 0,
99
+ highKnownLogicalBytes: 0,
100
+ highObjects: 0,
101
+ saturated: false
102
+ };
103
+ resourceReuse = {
104
+ current: {
105
+ idleBytes: 0,
106
+ idleEntries: 0,
107
+ leasedBytes: 0,
108
+ leasedEntries: 0,
109
+ reservedBytes: 0,
110
+ reservedEntries: 0,
111
+ detachedBytes: 0,
112
+ detachedEntries: 0,
113
+ unknownBytes: 0,
114
+ unknownEntries: 0
115
+ },
116
+ highWater: {
117
+ idleBytes: 0,
118
+ idleEntries: 0,
119
+ leasedBytes: 0,
120
+ leasedEntries: 0,
121
+ reservedBytes: 0,
122
+ reservedEntries: 0,
123
+ detachedBytes: 0,
124
+ detachedEntries: 0,
125
+ unknownBytes: 0,
126
+ unknownEntries: 0
127
+ },
128
+ saturated: false
129
+ };
130
+ resourceHighPending = {
131
+ frames: 0,
132
+ uploadCreditBytes: 0,
133
+ pageCreditBytes: 0,
134
+ readbackCreditBytes: 0,
135
+ geometryCreditBytes: 0,
136
+ colorCreditBytes: 0
137
+ };
138
+ resourceHighImages = {
139
+ readyBytes: 0,
140
+ readyEntries: 0,
141
+ pinnedReadyBytes: 0,
142
+ pinnedReadyEntries: 0,
143
+ allocatedLogicalBytes: 0,
144
+ reservedCreditBytes: 0
145
+ };
146
+ resourceTotals = { pageWriteCalls: 0, pageWriteBytes: 0, readyCapacityEvictions: 0 };
147
+ resourceSaturated = false;
148
+ resourceReadyBytes = 0;
149
+ resourcePinnedBytes = 0;
150
+ resourcePinnedEntries = 0;
151
+ imageEpoch = {};
152
+ bufferPool = createWebGPURetentionPool(this.imageEpoch, this.resourceReuse);
153
+ bindingCache = createWebGPUBindingCache(this.imageEpoch);
154
+ // Detached allocations retain an explicit owner even when an earlier native
155
+ // destroy throws. Unknown destruction is charged permanently and never retried.
156
+ bufferCleanup = new Set();
157
+ closingBuffers = [];
158
+ imageEnabled = false;
159
+ imageRevision = {};
160
+ imageDirectory = new WeakMap();
161
+ imageOldest;
162
+ imageNewest;
163
+ readyCount = 0;
164
+ allocatedImageBytes = 0;
165
+ reservedImageBytes = 0;
166
+ imageCleanup = new Set();
167
+ ticket;
168
+ device;
169
+ destroyDevice;
170
+ context;
171
+ configure;
172
+ unconfigure;
173
+ currentTexture;
174
+ configured = false;
175
+ format = 'rgba8unorm';
176
+ limits = { maxTextureDimension2D: 0, maxBufferSize: 0 };
177
+ sharedPipelines = new Map();
178
+ sharedSamplers = new Map();
179
+ effectPipelines = new Map();
180
+ resolvePipeline;
181
+ resolveLayout;
182
+ push;
183
+ pop;
184
+ write;
185
+ writeTexture;
186
+ submit;
187
+ fence;
188
+ buffer;
189
+ texture;
190
+ bindGroup;
191
+ encoder;
192
+ removeListener;
193
+ // Pending borrowed device.lost retains only this detachable cell after lease return.
194
+ lossCell = {};
195
+ generation = 0;
196
+ attempt = 0;
197
+ episodeAttempts = 0;
198
+ generationFailure = null;
199
+ owner;
200
+ usedDevices = new WeakSet();
201
+ readiness;
202
+ readinessPending = false;
203
+ recoveryAttempt;
204
+ stagePumpScheduled = false;
205
+ cancelStagePump;
206
+ monotonicNow;
207
+ now() {
208
+ this.monotonicNow ??= globalThis.performance.now.bind(globalThis.performance);
209
+ return this.monotonicNow();
210
+ }
211
+ timers;
212
+ constructor(input) {
213
+ try {
214
+ const admitted = admitSharedWebGPUOptions(input);
215
+ this.surface = admitted.surface;
216
+ Object.defineProperty(this, 'surface', { writable: false, configurable: false });
217
+ this.options = admitted.configuration;
218
+ this.borrowed = admitted.borrowed;
219
+ this.callback = admitted.callback;
220
+ SHARED_OPTIONS.set(this, admitted.configuration);
221
+ }
222
+ catch (cause) {
223
+ throw error('WEBGPU_OPTIONS_INVALID', cause);
224
+ }
225
+ this.borrowedPolicy = this.borrowed !== undefined;
226
+ Object.defineProperties(this, {
227
+ sharedFrameProfile: { value: SHARED_FRAME_PROFILE_2D, enumerable: true },
228
+ renderSharedFrame: {
229
+ value: (frame) => this.renderSharedOwnedFrame(frame),
230
+ enumerable: true
231
+ },
232
+ getSessionStatus: {
233
+ value: () => Object.freeze({
234
+ state: this.state === 'active' ? 'ready' : this.state,
235
+ generation: this.generation,
236
+ attempt: this.attempt,
237
+ firstFailure: this.firstFailure,
238
+ generationFailure: this.generationFailure
239
+ }),
240
+ enumerable: true
241
+ },
242
+ whenReady: { value: () => this.sharedWhenReady(), enumerable: true },
243
+ recover: { value: (device) => this.recoverShared(device), enumerable: true },
244
+ stageSharedFrame: {
245
+ value: (frame, options) => this.renderSharedOwnedFrame(frame, { options }),
246
+ enumerable: true
247
+ },
248
+ getSharedStatus: {
249
+ value: () => Object.freeze({
250
+ host: this.getStatus(),
251
+ pendingGeometryBytes: this.pendingGeometryBytes,
252
+ pendingColorBytes: this.pendingColorBytes,
253
+ pendingCanonicalBytes: this.pendingCanonicalBytes,
254
+ resources: this.resourceStatus()
255
+ }),
256
+ enumerable: true
257
+ }
258
+ });
259
+ }
260
+ getStatus() {
261
+ return Object.freeze({
262
+ state: this.state === 'lost' ? 'failed' : this.state === 'restoring' ? 'starting' : this.state,
263
+ lastSerial: this.lastSerial,
264
+ pendingFrames: this.ledger.size,
265
+ pendingUploadBytes: this.pendingUploadBytes,
266
+ pendingReadbackBytes: this.pendingReadbackBytes,
267
+ firstFailure: this.firstFailure,
268
+ callbackFailureCount: this.callbackFailureCount,
269
+ lastCallbackFailure: this.lastCallbackFailure,
270
+ cleanupOutcome: this.cleanupOutcome
271
+ });
272
+ }
273
+ sampleResourcePending() {
274
+ this.resourceHighPending.frames = Math.max(this.resourceHighPending.frames, this.ledger.size);
275
+ this.resourceHighPending.uploadCreditBytes = Math.max(this.resourceHighPending.uploadCreditBytes, this.pendingUploadBytes);
276
+ this.resourceHighPending.pageCreditBytes = Math.max(this.resourceHighPending.pageCreditBytes, this.pendingTextureBytes);
277
+ this.resourceHighPending.readbackCreditBytes = Math.max(this.resourceHighPending.readbackCreditBytes, this.pendingReadbackBytes);
278
+ this.resourceHighPending.geometryCreditBytes = Math.max(this.resourceHighPending.geometryCreditBytes, this.pendingGeometryBytes);
279
+ this.resourceHighPending.colorCreditBytes = Math.max(this.resourceHighPending.colorCreditBytes, this.pendingColorBytes);
280
+ }
281
+ sampleResourceImages() {
282
+ this.resourceHighImages.readyBytes = Math.max(this.resourceHighImages.readyBytes, this.resourceReadyBytes);
283
+ this.resourceHighImages.readyEntries = Math.max(this.resourceHighImages.readyEntries, this.readyCount);
284
+ this.resourceHighImages.pinnedReadyBytes = Math.max(this.resourceHighImages.pinnedReadyBytes, this.resourcePinnedBytes);
285
+ this.resourceHighImages.pinnedReadyEntries = Math.max(this.resourceHighImages.pinnedReadyEntries, this.resourcePinnedEntries);
286
+ this.resourceHighImages.allocatedLogicalBytes = Math.max(this.resourceHighImages.allocatedLogicalBytes, this.allocatedImageBytes);
287
+ this.resourceHighImages.reservedCreditBytes = Math.max(this.resourceHighImages.reservedCreditBytes, this.reservedImageBytes);
288
+ }
289
+ resourceTotal(key, amount) {
290
+ const old = this.resourceTotals[key];
291
+ if (amount > Number.MAX_SAFE_INTEGER - old) {
292
+ this.resourceTotals[key] = Number.MAX_SAFE_INTEGER;
293
+ this.resourceSaturated = true;
294
+ }
295
+ else
296
+ this.resourceTotals[key] = old + amount;
297
+ }
298
+ resourcePageWrite(bytes) {
299
+ this.resourceTotal('pageWriteCalls', 1);
300
+ this.resourceTotal('pageWriteBytes', bytes);
301
+ }
302
+ /** Read-only logical observations; no native call, callback or state transition. */
303
+ resourceStatus() {
304
+ return Object.freeze({
305
+ current: Object.freeze({
306
+ pending: Object.freeze({
307
+ frames: this.ledger.size,
308
+ uploadCreditBytes: this.pendingUploadBytes,
309
+ pageCreditBytes: this.pendingTextureBytes,
310
+ readbackCreditBytes: this.pendingReadbackBytes,
311
+ geometryCreditBytes: this.pendingGeometryBytes,
312
+ colorCreditBytes: this.pendingColorBytes
313
+ }),
314
+ cpu: Object.freeze({
315
+ canonicalBytes: this.resourceCpu.canonicalBytes,
316
+ scratchBytes: this.resourceCpu.scratchBytes,
317
+ temporaryBytes: this.resourceCpu.canonicalBytes + this.resourceCpu.scratchBytes
318
+ }),
319
+ images: Object.freeze({
320
+ readyBytes: this.resourceReadyBytes,
321
+ readyEntries: this.readyCount,
322
+ pinnedReadyBytes: this.resourcePinnedBytes,
323
+ pinnedReadyEntries: this.resourcePinnedEntries,
324
+ allocatedLogicalBytes: this.allocatedImageBytes,
325
+ reservedCreditBytes: this.reservedImageBytes
326
+ }),
327
+ reusable: Object.freeze({ ...this.resourceReuse.current }),
328
+ unknownNative: Object.freeze({
329
+ knownLogicalBytes: this.resourceUnknown.knownLogicalBytes,
330
+ objects: this.resourceUnknown.objects
331
+ })
332
+ }),
333
+ highWater: Object.freeze({
334
+ pending: Object.freeze({ ...this.resourceHighPending }),
335
+ cpu: Object.freeze({
336
+ canonicalBytes: this.resourceCpu.highCanonicalBytes,
337
+ scratchBytes: this.resourceCpu.highScratchBytes,
338
+ temporaryBytes: this.resourceCpu.highTemporaryBytes
339
+ }),
340
+ images: Object.freeze({ ...this.resourceHighImages }),
341
+ reusable: Object.freeze({ ...this.resourceReuse.highWater }),
342
+ unknownNative: Object.freeze({
343
+ knownLogicalBytes: this.resourceUnknown.highKnownLogicalBytes,
344
+ objects: this.resourceUnknown.highObjects
345
+ })
346
+ }),
347
+ totals: Object.freeze({ ...this.resourceTotals }),
348
+ saturated: this.resourceSaturated ||
349
+ this.resourceCpu.saturated ||
350
+ this.resourceReuse.saturated ||
351
+ this.resourceUnknown.saturated
352
+ });
353
+ }
354
+ noteUnknownResource(resource) {
355
+ if (resource.diagnosticUnknown ||
356
+ resource.settlement === 'destroyed' ||
357
+ resource.settlement === 'context-invalidated')
358
+ return;
359
+ resource.diagnosticUnknown = true;
360
+ const bytes = resource.logicalByteLength ?? 0, state = this.resourceUnknown;
361
+ if (bytes > Number.MAX_SAFE_INTEGER - state.knownLogicalBytes || state.objects === Number.MAX_SAFE_INTEGER)
362
+ state.saturated = true;
363
+ state.knownLogicalBytes = Math.min(Number.MAX_SAFE_INTEGER, state.knownLogicalBytes + bytes);
364
+ state.objects = Math.min(Number.MAX_SAFE_INTEGER, state.objects + 1);
365
+ state.highKnownLogicalBytes = Math.max(state.highKnownLogicalBytes, state.knownLogicalBytes);
366
+ state.highObjects = Math.max(state.highObjects, state.objects);
367
+ }
368
+ noteUnknownRecord(record) {
369
+ for (const resource of record.resources)
370
+ this.noteUnknownResource(resource);
371
+ for (const resource of record.textures)
372
+ this.noteUnknownResource(resource);
373
+ for (const lease of record.bufferLeases)
374
+ if (lease)
375
+ this.noteUnknownResource(lease.handle.resource);
376
+ if (record.imageUse)
377
+ for (const entry of record.imageUse.hits.values())
378
+ if (entry.resource)
379
+ this.noteUnknownResource(entry.resource);
380
+ if (record.shared)
381
+ for (const raw of record.shared.rawTargets)
382
+ if (raw.texture !== undefined)
383
+ this.noteUnknownResource(raw);
384
+ }
385
+ active() {
386
+ if (this.state !== 'active') {
387
+ this.retention.clear();
388
+ throw this.stateError();
389
+ }
390
+ }
391
+ stateError() {
392
+ return error(this.state === 'stopped'
393
+ ? 'WEBGPU_STOPPED'
394
+ : this.state === 'closing' || this.state === 'closed'
395
+ ? 'WEBGPU_CLOSED'
396
+ : this.state === 'failed'
397
+ ? 'WEBGPU_FAILED'
398
+ : this.state === 'lost' || this.state === 'restoring'
399
+ ? 'WEBGPU_DEVICE_LOST'
400
+ : 'WEBGPU_NOT_STARTED', (SHARED_OPTIONS.get(this)?.recovery ? this.generationFailure : this.firstFailure)?.cause);
401
+ }
402
+ startupCancelled() {
403
+ return this.state === 'stopped' || this.state === 'closing' || this.state === 'closed';
404
+ }
405
+ startupGate() {
406
+ if (this.state === 'failed' && this.firstFailure) {
407
+ throw new ClassifiedWebGPUFailure(this.firstFailure.code, this.firstFailure.cause);
408
+ }
409
+ if (this.state !== 'starting') {
410
+ throw new ClassifiedWebGPUFailure('WEBGPU_START_CANCELLED', this.firstFailure?.cause);
411
+ }
412
+ }
413
+ proofFailed(cause) {
414
+ if (this.owner) {
415
+ this.owner.unknown = true;
416
+ this.noteUnknownResource(this.owner);
417
+ }
418
+ for (const record of this.ledger)
419
+ this.noteUnknownRecord(record);
420
+ this.invalidateImageResidency();
421
+ if (!this.unsafe) {
422
+ this.unsafe = true;
423
+ this.unsafeCause = cause;
424
+ }
425
+ }
426
+ fail(code, cause, phase, serial, unsafe = false) {
427
+ this.invalidateImageResidency();
428
+ const attempt = this.recoveryAttempt;
429
+ const safeRecovery = attempt && !attempt.cancelled && this.state === 'restoring' && !unsafe && !this.unsafe;
430
+ const failure = Object.freeze({ code, cause, phase: attempt ? 'device' : phase, serial });
431
+ if (safeRecovery)
432
+ attempt.failure ??= error(code, cause);
433
+ if (unsafe) {
434
+ if (this.owner)
435
+ this.owner.unknown = true;
436
+ this.proofFailed(cause);
437
+ }
438
+ if (this.firstFailure === null)
439
+ this.firstFailure = failure;
440
+ this.generationFailure = failure;
441
+ if (this.state !== 'closing' && this.state !== 'closed' && this.state !== 'stopped' && !safeRecovery)
442
+ this.state = 'failed';
443
+ this.cancelTicket(error(code, cause));
444
+ this.diagnose(failure);
445
+ this.revokeStages(error(code, cause));
446
+ return error(code, cause);
447
+ }
448
+ diagnose(failure) {
449
+ const serial = failure.serial;
450
+ const callback = this.callback;
451
+ if (callback && this.state !== 'closed' && !this.finalizing) {
452
+ queueMicrotask(() => {
453
+ if (this.state === 'closed')
454
+ return;
455
+ const callbackFailure = (fault) => {
456
+ this.callbackFailureCount = Math.min(Number.MAX_SAFE_INTEGER, this.callbackFailureCount + 1);
457
+ this.lastCallbackFailure = Object.freeze({
458
+ code: 'WEBGPU_DIAGNOSTIC_CALLBACK_FAILED',
459
+ cause: fault,
460
+ phase: 'callback',
461
+ serial
462
+ });
463
+ };
464
+ try {
465
+ observed(callback.call(undefined, Object.freeze({ ...failure, severity: 'error' }))).catch(callbackFailure);
466
+ }
467
+ catch (fault) {
468
+ callbackFailure(fault);
469
+ }
470
+ });
471
+ }
472
+ }
473
+ cancelTicket(cause) {
474
+ if (this.ticket && !this.ticket.bound) {
475
+ this.ticket.reject(cause);
476
+ this.ticket = undefined;
477
+ }
478
+ }
479
+ stop() {
480
+ if (this.state === 'new' ||
481
+ this.state === 'starting' ||
482
+ this.state === 'active' ||
483
+ this.state === 'lost' ||
484
+ this.state === 'restoring')
485
+ this.state = 'stopped';
486
+ const failure = error('WEBGPU_STOPPED');
487
+ this.revokeRecovery(failure);
488
+ this.revokeStages(failure);
489
+ this.invalidateImageResidency();
490
+ this.cancelTicket(failure);
491
+ }
492
+ start() {
493
+ if (this.state === 'lost' || this.state === 'restoring')
494
+ return observed(Promise.reject(error('WEBGPU_DEVICE_LOST', this.generationFailure?.cause)));
495
+ if (this.state === 'starting' || this.state === 'active')
496
+ return this.starting;
497
+ if (this.state !== 'new')
498
+ return observed(Promise.reject(this.stateError()));
499
+ const barrier = deferred();
500
+ this.starting = barrier.promise;
501
+ this.startingPending = true;
502
+ this.state = 'starting';
503
+ if (SHARED_OPTIONS.has(this)) {
504
+ this.readiness = barrier;
505
+ this.readinessPending = true;
506
+ }
507
+ // Cache before any getter/call can reenter start or close.
508
+ this.initialize().then(() => {
509
+ this.startingPending = false;
510
+ if (this.readiness === barrier)
511
+ this.readinessPending = false;
512
+ barrier.resolve();
513
+ }, cause => {
514
+ this.startingPending = false;
515
+ if (this.readiness === barrier)
516
+ this.readinessPending = false;
517
+ barrier.reject(cause);
518
+ });
519
+ return barrier.promise;
520
+ }
521
+ method(object, key, gate) {
522
+ const value = object[key];
523
+ gate();
524
+ if (typeof value !== 'function')
525
+ throw new TypeError(String(key));
526
+ return value.bind(object);
527
+ }
528
+ sharedWhenReady() {
529
+ if (this.recoveryAttempt)
530
+ this.checkRecoveryDeadline(this.recoveryAttempt);
531
+ if (this.state === 'starting' || this.state === 'active' || this.state === 'lost' || this.state === 'restoring')
532
+ return this.readiness?.promise ?? observed(Promise.reject(this.stateError()));
533
+ return observed(Promise.reject(this.stateError()));
534
+ }
535
+ /** Fixed WebIDL getters authenticate the native receiver; method capture never adopts it. */
536
+ captureNativeDevice(device, gate) {
537
+ if (!isObject(device) || this.usedDevices.has(device))
538
+ throw new TypeError('Fresh native GPUDevice required');
539
+ const constructor = globalThis.GPUDevice;
540
+ gate();
541
+ if (typeof constructor !== 'function')
542
+ throw new TypeError('Native GPUDevice unavailable');
543
+ const prototype = constructor.prototype;
544
+ gate();
545
+ const lostGetter = Object.getOwnPropertyDescriptor(prototype, 'lost')?.get;
546
+ const limitsGetter = Object.getOwnPropertyDescriptor(prototype, 'limits')?.get;
547
+ if (typeof lostGetter !== 'function' || typeof limitsGetter !== 'function')
548
+ throw new TypeError('Native GPUDevice accessors unavailable');
549
+ const lost = observed(lostGetter.call(device));
550
+ gate();
551
+ const limitsObject = limitsGetter.call(device);
552
+ gate();
553
+ const limits = {};
554
+ for (const key of DEVICE_LIMIT_KEYS) {
555
+ limits[key] = limitsObject[key];
556
+ gate();
557
+ if (!Number.isSafeInteger(limits[key]) || limits[key] <= 0)
558
+ throw new TypeError('Device limit');
559
+ }
560
+ if (limits['maxVertexBuffers'] < 1 ||
561
+ limits['maxVertexAttributes'] < 5 ||
562
+ limits['maxVertexBufferArrayStride'] < 52 ||
563
+ limits['maxColorAttachments'] < 1 ||
564
+ limits['maxColorAttachmentBytesPerSample'] < 4 ||
565
+ limits['maxBindGroups'] < 2 ||
566
+ limits['maxBindingsPerBindGroup'] < 2 + SHARED_BATCH_PAGES_2D ||
567
+ limits['maxSampledTexturesPerShaderStage'] < SHARED_BATCH_PAGES_2D ||
568
+ limits['maxSamplersPerShaderStage'] < 1 ||
569
+ limits['maxUniformBuffersPerShaderStage'] < 2 ||
570
+ limits['maxUniformBufferBindingSize'] < SHARED_REGION_WINDOW_BYTES_2D ||
571
+ limits['maxBindGroupsPlusVertexBuffers'] < 3 ||
572
+ limits['maxInterStageShaderVariables'] < 8)
573
+ throw new TypeError('Device capabilities');
574
+ const queue = device.queue;
575
+ gate();
576
+ const capture = (key) => this.method(device, key, gate);
577
+ return {
578
+ device,
579
+ lost,
580
+ limits,
581
+ add: capture('addEventListener'),
582
+ remove: capture('removeEventListener'),
583
+ write: this.method(queue, 'writeBuffer', gate),
584
+ writeTexture: this.method(queue, 'writeTexture', gate),
585
+ submit: this.method(queue, 'submit', gate),
586
+ fence: this.method(queue, 'onSubmittedWorkDone', gate),
587
+ push: capture('pushErrorScope'),
588
+ pop: capture('popErrorScope'),
589
+ buffer: capture('createBuffer'),
590
+ texture: capture('createTexture'),
591
+ encoder: capture('createCommandEncoder'),
592
+ bindGroup: capture('createBindGroup'),
593
+ sampler: capture('createSampler'),
594
+ shader: capture('createShaderModule'),
595
+ pipeline: capture('createRenderPipelineAsync')
596
+ };
597
+ }
598
+ nativeLoss(owner, cause) {
599
+ if (this.owner !== owner || owner.invalidated || this.state === 'closed')
600
+ return;
601
+ owner.invalidated = true;
602
+ owner.finishReadbackLossWait?.();
603
+ if (owner.unknown || this.unsafe) {
604
+ this.revokeStages(error('WEBGPU_DEVICE_LOST', cause));
605
+ return;
606
+ }
607
+ const wasReady = this.state === 'active' && !this.readinessPending;
608
+ if (wasReady)
609
+ this.episodeAttempts = 0;
610
+ const terminal = this.state === 'stopped' || this.state === 'closing';
611
+ if (!terminal)
612
+ this.state = 'lost';
613
+ const failure = Object.freeze({
614
+ code: 'WEBGPU_DEVICE_LOST',
615
+ cause,
616
+ phase: 'device',
617
+ serial: null
618
+ });
619
+ this.firstFailure ??= failure;
620
+ this.generationFailure = failure;
621
+ const refused = error('WEBGPU_DEVICE_LOST', cause);
622
+ for (const record of this.ledger)
623
+ if (record.owner === owner) {
624
+ record.failure ??= refused;
625
+ record.stage?.native.reject(refused);
626
+ }
627
+ if (!terminal && !this.recoveryAttempt) {
628
+ this.readiness = deferred();
629
+ this.readinessPending = true;
630
+ }
631
+ // Confirmed generation loss invalidates CPU retention before ready stages retire.
632
+ // Otherwise context-invalidated settlement reaches a still-active ledger.
633
+ this.invalidateImageResidency();
634
+ this.revokeStages(refused);
635
+ this.cancelTicket(refused);
636
+ this.diagnose(failure);
637
+ if (!terminal && !this.recoveryAttempt && SHARED_OPTIONS.get(this)?.recovery?.mode === 'automatic') {
638
+ // Publication was revoked synchronously; the one automatic attempt begins in a later microtask.
639
+ queueMicrotask(() => {
640
+ if (this.state === 'lost' && !this.recoveryAttempt && this.episodeAttempts === 0)
641
+ observed(this.recoverShared());
642
+ });
643
+ }
644
+ }
645
+ checkRecoveryDeadline(attempt) {
646
+ if (this.recoveryAttempt !== attempt || attempt.cancelled || this.now() < attempt.deadline)
647
+ return;
648
+ attempt.cancelled = true;
649
+ this.state = 'failed';
650
+ const failure = error('WEBGPU_RECOVERY_TIMEOUT');
651
+ this.generationFailure = Object.freeze({
652
+ code: 'WEBGPU_RECOVERY_TIMEOUT',
653
+ cause: failure,
654
+ phase: 'device',
655
+ serial: null
656
+ });
657
+ this.firstFailure ??= this.generationFailure;
658
+ attempt.barrier.reject(failure);
659
+ this.readinessPending = false;
660
+ this.revokeStages(failure);
661
+ this.diagnose(this.generationFailure);
662
+ }
663
+ revokeRecovery(cause) {
664
+ const attempt = this.recoveryAttempt;
665
+ if (attempt) {
666
+ attempt.cancelled = true;
667
+ attempt.cancelTimer?.();
668
+ attempt.cancelTimer = undefined;
669
+ attempt.barrier.reject(cause);
670
+ this.readinessPending = false;
671
+ }
672
+ else if (this.readinessPending && this.readiness?.promise !== this.starting) {
673
+ this.readiness?.reject(cause);
674
+ this.readinessPending = false;
675
+ }
676
+ }
677
+ recoverShared(device) {
678
+ const recovery = SHARED_OPTIONS.get(this)?.recovery;
679
+ try {
680
+ if (!recovery)
681
+ throw error('WEBGPU_RECOVERY_DISABLED');
682
+ if (this.busy)
683
+ throw error('WEBGPU_REENTRANT');
684
+ if (this.state === 'stopped' || this.state === 'closing' || this.state === 'closed' || this.state === 'failed')
685
+ throw this.stateError();
686
+ if (this.recoveryAttempt) {
687
+ this.checkRecoveryDeadline(this.recoveryAttempt);
688
+ return this.recoveryAttempt.barrier.promise;
689
+ }
690
+ if (this.state !== 'lost')
691
+ throw error('WEBGPU_RECOVERY_STATE_INVALID');
692
+ if (this.episodeAttempts >= 3)
693
+ throw error('WEBGPU_RECOVERY_LIMIT');
694
+ if (this.attempt === Number.MAX_SAFE_INTEGER || this.generation === Number.MAX_SAFE_INTEGER)
695
+ throw error('WEBGPU_GENERATION_EXHAUSTED');
696
+ let captured;
697
+ this.busy = true;
698
+ this.cpu = deferred();
699
+ try {
700
+ if (this.borrowedPolicy) {
701
+ if (device === undefined)
702
+ throw new TypeError('Replacement borrowed device required');
703
+ captured = this.captureNativeDevice(device, () => {
704
+ if (this.state !== 'lost')
705
+ throw this.stateError();
706
+ });
707
+ }
708
+ else if (device !== undefined)
709
+ throw new TypeError('Acquire policy does not accept a device');
710
+ }
711
+ catch (cause) {
712
+ if (this.state !== 'lost')
713
+ throw this.stateError();
714
+ throw error('WEBGPU_RECOVERY_DEVICE_INVALID', cause);
715
+ }
716
+ finally {
717
+ this.busy = false;
718
+ this.cpu.resolve();
719
+ }
720
+ const barrier = this.readinessPending && this.readiness ? this.readiness : deferred();
721
+ this.readiness = barrier;
722
+ this.readinessPending = true;
723
+ this.attempt++;
724
+ this.episodeAttempts++;
725
+ this.state = 'restoring';
726
+ const attempt = {
727
+ barrier,
728
+ actual: Promise.resolve(),
729
+ deadline: this.now() + recovery.timeoutMs,
730
+ failure: undefined,
731
+ cancelled: false,
732
+ cancelTimer: undefined
733
+ };
734
+ this.recoveryAttempt = attempt;
735
+ attempt.cancelTimer = this.ownedTimeout(() => this.checkRecoveryDeadline(attempt), recovery.timeoutMs);
736
+ const gate = () => {
737
+ this.checkRecoveryDeadline(attempt);
738
+ if (attempt.cancelled || this.state !== 'restoring')
739
+ throw this.stateError();
740
+ };
741
+ attempt.actual = observed((async () => {
742
+ try {
743
+ if (this.startingPending && this.starting)
744
+ await Promise.allSettled([this.starting]);
745
+ await Promise.allSettled([...this.ledger].map(record => record.outcome));
746
+ gate();
747
+ await this.releaseGeneration();
748
+ gate();
749
+ if (this.unsafe)
750
+ throw error('WEBGPU_CLOSE_UNSAFE', this.unsafeCause);
751
+ this.imageEpoch = {};
752
+ this.bufferPool = createWebGPURetentionPool(this.imageEpoch, this.resourceReuse);
753
+ this.bindingCache = createWebGPUBindingCache(this.imageEpoch);
754
+ this.imageDirectory = new WeakMap();
755
+ this.lossCell = {};
756
+ this.owner = undefined;
757
+ this.sharedPipelines.clear();
758
+ this.sharedSamplers.clear();
759
+ await this.initialize(captured);
760
+ this.checkRecoveryDeadline(attempt);
761
+ if (attempt.cancelled || this.state !== 'active')
762
+ throw this.stateError();
763
+ this.generationFailure = null;
764
+ this.readinessPending = false;
765
+ barrier.resolve();
766
+ }
767
+ catch (cause) {
768
+ if (!this.startupCancelled() && !attempt.cancelled) {
769
+ await this.releaseGeneration();
770
+ this.checkRecoveryDeadline(attempt);
771
+ if (!this.startupCancelled() && !attempt.cancelled) {
772
+ this.state = this.unsafe || this.episodeAttempts >= 3 ? 'failed' : 'lost';
773
+ const code = this.unsafe
774
+ ? 'WEBGPU_CLOSE_UNSAFE'
775
+ : this.episodeAttempts >= 3
776
+ ? 'WEBGPU_RECOVERY_LIMIT'
777
+ : 'WEBGPU_RECOVERY_FAILED';
778
+ const failure = error(code, cause);
779
+ this.generationFailure = Object.freeze({ code, cause, phase: 'device', serial: null });
780
+ this.firstFailure ??= this.generationFailure;
781
+ barrier.reject(failure);
782
+ this.readinessPending = false;
783
+ }
784
+ }
785
+ if (this.startupCancelled()) {
786
+ barrier.reject(this.stateError());
787
+ this.readinessPending = false;
788
+ }
789
+ }
790
+ finally {
791
+ attempt.cancelTimer?.();
792
+ attempt.cancelTimer = undefined;
793
+ if (this.recoveryAttempt === attempt)
794
+ this.recoveryAttempt = undefined;
795
+ }
796
+ })());
797
+ return barrier.promise;
798
+ }
799
+ catch (cause) {
800
+ return observed(Promise.reject(cause));
801
+ }
802
+ }
803
+ async releaseGeneration() {
804
+ for (const record of [...this.ledger])
805
+ if (!record.unsafe) {
806
+ try {
807
+ this.retire(record);
808
+ }
809
+ catch (cause) {
810
+ this.proofFailed(cause);
811
+ }
812
+ }
813
+ this.closeBuffers();
814
+ this.closeImageResidency();
815
+ if (this.configured) {
816
+ this.configured = false;
817
+ try {
818
+ this.unconfigure();
819
+ }
820
+ catch (cause) {
821
+ this.proofFailed(cause);
822
+ }
823
+ }
824
+ if (this.removeListener) {
825
+ const remove = this.removeListener;
826
+ this.removeListener = undefined;
827
+ try {
828
+ remove();
829
+ }
830
+ catch (cause) {
831
+ this.proofFailed(cause);
832
+ }
833
+ }
834
+ await Promise.resolve();
835
+ delete this.lossCell.notify;
836
+ delete this.lossCell.unknown;
837
+ if (this.destroyDevice) {
838
+ const destroy = this.destroyDevice;
839
+ this.destroyDevice = undefined;
840
+ try {
841
+ destroy();
842
+ }
843
+ catch (cause) {
844
+ this.proofFailed(cause);
845
+ }
846
+ }
847
+ this.clearNativeReferences();
848
+ }
849
+ clearNativeReferences() {
850
+ this.device = undefined;
851
+ this.owner = undefined;
852
+ this.context = undefined;
853
+ this.configure = undefined;
854
+ this.unconfigure = undefined;
855
+ this.currentTexture = undefined;
856
+ this.push = undefined;
857
+ this.pop = undefined;
858
+ this.write = undefined;
859
+ this.writeTexture = undefined;
860
+ this.submit = undefined;
861
+ this.fence = undefined;
862
+ this.buffer = undefined;
863
+ this.texture = undefined;
864
+ this.bindGroup = undefined;
865
+ this.encoder = undefined;
866
+ this.resolvePipeline = undefined;
867
+ this.resolveLayout = undefined;
868
+ this.effectPipelines.clear();
869
+ this.sharedPipelines.clear();
870
+ this.sharedSamplers.clear();
871
+ }
872
+ async initialize(supplied) {
873
+ let stage = 'WEBGPU_UNAVAILABLE';
874
+ const operation = this.recoveryAttempt;
875
+ const gate = () => {
876
+ if (operation) {
877
+ this.checkRecoveryDeadline(operation);
878
+ if (operation.failure)
879
+ throw new ClassifiedWebGPUFailure(operation.failure.code, operation.failure.cause, operation.failure);
880
+ if (this.recoveryAttempt !== operation || operation.cancelled || this.state !== 'restoring')
881
+ throw new ClassifiedWebGPUFailure('WEBGPU_START_CANCELLED', this.generationFailure?.cause);
882
+ }
883
+ else
884
+ this.startupGate();
885
+ };
886
+ try {
887
+ const navigatorValue = globalThis.navigator;
888
+ gate();
889
+ const gpu = navigatorValue?.gpu;
890
+ gate();
891
+ if (!gpu)
892
+ throw new ClassifiedWebGPUFailure('WEBGPU_UNAVAILABLE');
893
+ const preferred = this.method(gpu, 'getPreferredCanvasFormat', gate);
894
+ const format = preferred();
895
+ gate();
896
+ if (format !== 'rgba8unorm' && format !== 'bgra8unorm')
897
+ throw new ClassifiedWebGPUFailure('WEBGPU_FORMAT_UNSUPPORTED');
898
+ this.format = format;
899
+ stage = 'WEBGPU_CONTEXT_UNAVAILABLE';
900
+ const getContext = this.method(this.surface, 'getContext', gate);
901
+ const context = getContext('webgpu');
902
+ gate();
903
+ if (!context)
904
+ throw new ClassifiedWebGPUFailure('WEBGPU_CONTEXT_UNAVAILABLE');
905
+ this.context = context;
906
+ this.configure = this.method(context, 'configure', gate);
907
+ this.unconfigure = this.method(context, 'unconfigure', gate);
908
+ this.currentTexture = this.method(context, 'getCurrentTexture', gate);
909
+ let device;
910
+ if (supplied)
911
+ device = supplied.device;
912
+ else if (this.borrowed)
913
+ device = this.borrowed;
914
+ else {
915
+ stage = 'WEBGPU_ADAPTER_UNAVAILABLE';
916
+ const request = this.method(gpu, 'requestAdapter', gate);
917
+ const adapter = await observed(request());
918
+ gate();
919
+ if (!adapter)
920
+ throw new ClassifiedWebGPUFailure('WEBGPU_ADAPTER_UNAVAILABLE');
921
+ stage = 'WEBGPU_DEVICE_FAILED';
922
+ const acquire = this.method(adapter, 'requestDevice', gate);
923
+ device = await observed(acquire());
924
+ }
925
+ // Acquire ownership before checking cancellation so close can clean a late device.
926
+ this.device = device;
927
+ stage = 'WEBGPU_START_FAILED';
928
+ const cleanupGate = () => undefined;
929
+ if (!this.borrowedPolicy) {
930
+ try {
931
+ this.destroyDevice = this.method(device, 'destroy', cleanupGate);
932
+ }
933
+ catch (cause) {
934
+ this.proofFailed(cause);
935
+ throw cause;
936
+ }
937
+ }
938
+ const recovery = SHARED_OPTIONS.get(this)?.recovery;
939
+ const native = recovery ? (supplied ?? this.captureNativeDevice(device, gate)) : undefined;
940
+ gate();
941
+ const lost = native?.lost ?? device.lost;
942
+ const add = native?.add ?? this.method(device, 'addEventListener', gate), remove = native?.remove ?? this.method(device, 'removeEventListener', gate);
943
+ const queue = native ? undefined : device.queue;
944
+ gate();
945
+ this.write = native?.write ?? this.method(queue, 'writeBuffer', gate);
946
+ this.writeTexture = native?.writeTexture ?? this.method(queue, 'writeTexture', gate);
947
+ this.submit = native?.submit ?? this.method(queue, 'submit', gate);
948
+ this.fence = native?.fence ?? this.method(queue, 'onSubmittedWorkDone', gate);
949
+ this.push = native?.push ?? this.method(device, 'pushErrorScope', gate);
950
+ this.pop = native?.pop ?? this.method(device, 'popErrorScope', gate);
951
+ this.buffer = native?.buffer ?? this.method(device, 'createBuffer', gate);
952
+ this.encoder = native?.encoder ?? this.method(device, 'createCommandEncoder', gate);
953
+ this.texture = native?.texture ?? this.method(device, 'createTexture', gate);
954
+ this.bindGroup = native?.bindGroup ?? this.method(device, 'createBindGroup', gate);
955
+ const sampler = native?.sampler ?? this.method(device, 'createSampler', gate), shader = native?.shader ?? this.method(device, 'createShaderModule', gate), pipeline = native?.pipeline ?? this.method(device, 'createRenderPipelineAsync', gate);
956
+ const captured = native?.limits ?? {};
957
+ if (!native) {
958
+ const limits = device.limits;
959
+ gate();
960
+ for (const key of DEVICE_LIMIT_KEYS) {
961
+ captured[key] = limits[key];
962
+ gate();
963
+ if (!Number.isSafeInteger(captured[key]) || captured[key] <= 0)
964
+ throw new ClassifiedWebGPUFailure('WEBGPU_DEVICE_LIMIT');
965
+ }
966
+ }
967
+ {
968
+ if (this.generation === Number.MAX_SAFE_INTEGER)
969
+ throw new ClassifiedWebGPUFailure('WEBGPU_GENERATION_EXHAUSTED');
970
+ const owner = {
971
+ number: ++this.generation,
972
+ device,
973
+ pool: this.bufferPool,
974
+ cache: this.bindingCache,
975
+ epoch: this.imageEpoch,
976
+ format: this.format,
977
+ alpha: SHARED_OPTIONS.get(this).outputAlpha,
978
+ fence: this.fence,
979
+ pop: this.pop,
980
+ native: {
981
+ write: this.write,
982
+ writeTexture: this.writeTexture,
983
+ submit: this.submit,
984
+ push: this.push,
985
+ buffer: this.buffer,
986
+ texture: this.texture,
987
+ bindGroup: this.bindGroup,
988
+ encoder: this.encoder,
989
+ configure: this.configure,
990
+ unconfigure: this.unconfigure,
991
+ currentTexture: this.currentTexture
992
+ },
993
+ invalidated: false,
994
+ unknown: false
995
+ };
996
+ this.owner = owner;
997
+ this.usedDevices.add(device);
998
+ if (recovery)
999
+ this.borrowed = undefined;
1000
+ const cell = this.lossCell;
1001
+ if (recovery) {
1002
+ cell.notify = cause => this.nativeLoss(owner, cause);
1003
+ cell.unknown = cause => {
1004
+ if (this.owner === owner) {
1005
+ owner.unknown = true;
1006
+ owner.finishReadbackLossWait?.();
1007
+ const failure = this.fail('WEBGPU_DEVICE_LOST', cause, 'device', null, true);
1008
+ this.revokeRecovery(failure);
1009
+ this.revokeStages(failure);
1010
+ }
1011
+ };
1012
+ observeAuthenticatedWebGPUDeviceLoss(lost, cell);
1013
+ }
1014
+ else {
1015
+ cell.notify = cause => {
1016
+ this.fail('WEBGPU_DEVICE_LOST', cause, 'device', null, true);
1017
+ this.revokeStages(error('WEBGPU_DEVICE_LOST', cause));
1018
+ };
1019
+ observeWebGPUDeviceLoss(lost, cell);
1020
+ }
1021
+ }
1022
+ gate();
1023
+ stage = 'WEBGPU_START_FAILED';
1024
+ const observedOwner = this.owner;
1025
+ const listener = (event) => {
1026
+ if (observedOwner && this.owner !== observedOwner)
1027
+ return;
1028
+ this.fail('WEBGPU_UNCAPTURED_ERROR', event.error, 'device', null);
1029
+ };
1030
+ this.removeListener = () => remove('uncapturederror', listener);
1031
+ add('uncapturederror', listener);
1032
+ gate();
1033
+ if (captured['maxVertexBuffers'] < 1 ||
1034
+ captured['maxVertexAttributes'] < 5 ||
1035
+ captured['maxVertexBufferArrayStride'] < 52 ||
1036
+ captured['maxColorAttachments'] < 1 ||
1037
+ captured['maxColorAttachmentBytesPerSample'] < 4 ||
1038
+ captured['maxBindGroups'] < 2 ||
1039
+ captured['maxBindingsPerBindGroup'] < 2 + SHARED_BATCH_PAGES_2D ||
1040
+ captured['maxSampledTexturesPerShaderStage'] < SHARED_BATCH_PAGES_2D ||
1041
+ captured['maxSamplersPerShaderStage'] < 1 ||
1042
+ captured['maxUniformBuffersPerShaderStage'] < 2 ||
1043
+ captured['maxUniformBufferBindingSize'] < SHARED_REGION_WINDOW_BYTES_2D ||
1044
+ captured['maxBindGroupsPlusVertexBuffers'] < 3 ||
1045
+ captured['maxInterStageShaderVariables'] < 8)
1046
+ throw new ClassifiedWebGPUFailure('WEBGPU_DEVICE_LIMIT');
1047
+ if (SHARED_OPTIONS.get(this)?.enableEffects &&
1048
+ (captured['maxUniformBufferBindingSize'] < EFFECT_UNIFORM_BYTES ||
1049
+ captured['maxSampledTexturesPerShaderStage'] < 3))
1050
+ throw new ClassifiedWebGPUFailure('WEBGPU_DEVICE_LIMIT');
1051
+ this.limits = {
1052
+ maxTextureDimension2D: captured['maxTextureDimension2D'],
1053
+ maxBufferSize: captured['maxBufferSize']
1054
+ };
1055
+ const scopes = [];
1056
+ const pipelines = [];
1057
+ const capturedShader = (descriptor) => {
1058
+ gate();
1059
+ const module = shader(descriptor);
1060
+ gate();
1061
+ return module;
1062
+ };
1063
+ const capturedPipeline = (descriptor) => {
1064
+ gate();
1065
+ const result = observed(pipeline(descriptor));
1066
+ // A later call/gate can throw; close must still drain every already started peer.
1067
+ pipelines.push(result);
1068
+ gate();
1069
+ return result;
1070
+ };
1071
+ let synchronous;
1072
+ try {
1073
+ this.scoped(null, 'startup', scopes, gate, () => {
1074
+ for (const kind of SHARED_PIPELINE_KINDS)
1075
+ for (const blend of SHARED_BLENDS)
1076
+ createSharedWebGPUPipeline(capturedShader, capturedPipeline, kind, blend);
1077
+ createSharedResolvePipeline(capturedShader, capturedPipeline, this.format, SHARED_OPTIONS.get(this).outputAlpha === 'opaque');
1078
+ if (SHARED_OPTIONS.get(this).enableEffects)
1079
+ for (const mode of EFFECT_PASSES)
1080
+ createSharedEffectPipeline(capturedShader, capturedPipeline, mode);
1081
+ for (const filter of ['nearest', 'linear'])
1082
+ for (const u of ['clamp-to-edge', 'repeat', 'mirror-repeat'])
1083
+ for (const v of ['clamp-to-edge', 'repeat', 'mirror-repeat']) {
1084
+ const value = sampler({
1085
+ addressModeU: u,
1086
+ addressModeV: v,
1087
+ addressModeW: 'clamp-to-edge',
1088
+ minFilter: filter,
1089
+ magFilter: filter,
1090
+ mipmapFilter: 'nearest',
1091
+ lodMinClamp: 0,
1092
+ lodMaxClamp: 0,
1093
+ maxAnisotropy: 1
1094
+ });
1095
+ this.sharedSamplers.set(filter + ':' + u + ':' + v, value);
1096
+ gate();
1097
+ }
1098
+ });
1099
+ }
1100
+ catch (cause) {
1101
+ // Occurrence is independent of the arbitrary thrown value, including undefined.
1102
+ synchronous = { cause };
1103
+ }
1104
+ // Pop all scopes before awaiting independently observed async pipeline work.
1105
+ const outcomes = await Promise.allSettled([...scopes, ...pipelines]);
1106
+ if (synchronous && this.startupCancelled())
1107
+ throw synchronous.cause;
1108
+ gate();
1109
+ if (synchronous)
1110
+ throw synchronous.cause;
1111
+ const rejected = outcomes.find(outcome => outcome.status === 'rejected');
1112
+ if (rejected?.status === 'rejected')
1113
+ throw rejected.reason;
1114
+ // Scope outcomes do not select pipeline roles; the pipelines' own ordered results do.
1115
+ const roles = outcomes.slice(scopes.length);
1116
+ {
1117
+ let index = 0;
1118
+ for (const kind of SHARED_PIPELINE_KINDS)
1119
+ for (const blend of SHARED_BLENDS) {
1120
+ const value = roles[index++].value;
1121
+ const layout = this.method(value, 'getBindGroupLayout', gate)(0);
1122
+ gate();
1123
+ const regions = kind !== 'solid' ? this.method(value, 'getBindGroupLayout', gate)(1) : undefined;
1124
+ gate();
1125
+ this.sharedPipelines.set(kind + ':' + blend, { pipeline: value, layout, regions });
1126
+ }
1127
+ this.resolvePipeline = roles[index++].value;
1128
+ this.resolveLayout = this.method(this.resolvePipeline, 'getBindGroupLayout', gate)(0);
1129
+ gate();
1130
+ if (SHARED_OPTIONS.get(this).enableEffects)
1131
+ for (const mode of EFFECT_PASSES) {
1132
+ const pipeline = roles[index++].value, layout = this.method(pipeline, 'getBindGroupLayout', gate)(0);
1133
+ gate();
1134
+ this.effectPipelines.set(mode, { pipeline, layout });
1135
+ }
1136
+ }
1137
+ const configureScopes = [];
1138
+ let configureFailure;
1139
+ try {
1140
+ this.scoped(null, 'startup', configureScopes, gate, () => this.configureSurface(gate));
1141
+ }
1142
+ catch (cause) {
1143
+ configureFailure = { cause };
1144
+ }
1145
+ const configured = await Promise.allSettled(configureScopes);
1146
+ if (configureFailure && this.startupCancelled())
1147
+ throw configureFailure.cause;
1148
+ gate();
1149
+ if (configureFailure)
1150
+ throw configureFailure.cause;
1151
+ const failed = configured.find(outcome => outcome.status === 'rejected');
1152
+ if (failed?.status === 'rejected')
1153
+ throw failed.reason;
1154
+ this.state = 'active';
1155
+ this.imageEnabled = true;
1156
+ this.generationFailure = null;
1157
+ }
1158
+ catch (cause) {
1159
+ const classified = cause instanceof ClassifiedWebGPUFailure ? cause : undefined;
1160
+ const original = classified ? classified.original : cause;
1161
+ if (this.startupCancelled()) {
1162
+ throw error('WEBGPU_START_CANCELLED', original);
1163
+ }
1164
+ if (operation?.cancelled)
1165
+ throw this.stateError();
1166
+ if (this.state === 'lost' ||
1167
+ (!operation && SHARED_OPTIONS.get(this)?.recovery && this.readiness?.promise !== this.starting))
1168
+ throw error('WEBGPU_DEVICE_LOST', this.generationFailure?.cause);
1169
+ if (classified && this.firstFailure?.code === classified.code) {
1170
+ throw classified.publicError;
1171
+ }
1172
+ // Public EgretError instances are ordinary external causes, regardless of their code.
1173
+ throw this.fail(classified ? classified.code : stage, original, 'startup', null);
1174
+ }
1175
+ }
1176
+ scoped(serial, phase, outcomes, gate, work) {
1177
+ const owner = this.owner, push = this.push, pop = this.pop;
1178
+ const scopeFailure = (code, cause, unsafe = false) => {
1179
+ if (owner?.invalidated && !owner.unknown)
1180
+ return error('WEBGPU_DEVICE_LOST', cause);
1181
+ if (owner && this.owner !== owner) {
1182
+ if (unsafe)
1183
+ this.proofFailed(cause);
1184
+ return error(code, cause);
1185
+ }
1186
+ return this.fail(code, cause, phase, serial, unsafe);
1187
+ };
1188
+ const filters = ['out-of-memory', 'internal', 'validation'];
1189
+ let pushed = 0;
1190
+ try {
1191
+ for (const filter of filters) {
1192
+ gate();
1193
+ push(filter);
1194
+ pushed++;
1195
+ gate();
1196
+ }
1197
+ work();
1198
+ }
1199
+ finally {
1200
+ while (pushed > 0) {
1201
+ const filter = filters[--pushed];
1202
+ try {
1203
+ const result = observed(pop()).then(fault => {
1204
+ if (fault) {
1205
+ const code = filter === 'validation'
1206
+ ? 'WEBGPU_VALIDATION'
1207
+ : filter === 'internal'
1208
+ ? 'WEBGPU_INTERNAL'
1209
+ : 'WEBGPU_OUT_OF_MEMORY';
1210
+ throw new ClassifiedWebGPUFailure(code, fault, scopeFailure(code, fault));
1211
+ }
1212
+ }, cause => {
1213
+ throw new ClassifiedWebGPUFailure('WEBGPU_SCOPE_FAILED', cause, scopeFailure('WEBGPU_SCOPE_FAILED', cause, true));
1214
+ });
1215
+ outcomes.push(observed(result));
1216
+ }
1217
+ catch (cause) {
1218
+ const failure = new ClassifiedWebGPUFailure('WEBGPU_SCOPE_FAILED', cause, scopeFailure('WEBGPU_SCOPE_FAILED', cause, true));
1219
+ outcomes.push(observed(Promise.reject(failure)));
1220
+ }
1221
+ }
1222
+ }
1223
+ }
1224
+ configureSurface(gate) {
1225
+ gate();
1226
+ // A throwing external configure may already have changed the leased context.
1227
+ this.configured = true;
1228
+ this.configure({
1229
+ device: this.device,
1230
+ format: this.format,
1231
+ colorSpace: 'srgb',
1232
+ alphaMode: SHARED_OPTIONS.get(this)?.outputAlpha ?? 'premultiplied',
1233
+ usage: 16 | (this.options.enableReadback ? 1 : 0)
1234
+ });
1235
+ gate();
1236
+ }
1237
+ ownedBuffer(size, usage, record, gate) {
1238
+ gate();
1239
+ const buffer = (record.owner?.native.buffer ?? this.buffer)({ size, usage });
1240
+ // Record ownership immediately, even if capture getters throw or close reentrantly.
1241
+ const resource = {
1242
+ buffer,
1243
+ destroy: () => {
1244
+ throw new TypeError('uncaptured destroy');
1245
+ },
1246
+ unmap: () => {
1247
+ throw new TypeError('uncaptured unmap');
1248
+ },
1249
+ map: () => Promise.reject(new TypeError('uncaptured map')),
1250
+ mappedRange: () => {
1251
+ throw new TypeError('uncaptured range');
1252
+ },
1253
+ mapped: false,
1254
+ cleaned: false,
1255
+ logicalByteLength: size
1256
+ };
1257
+ if (record.owner)
1258
+ resource.generation = record.owner;
1259
+ record.resources.push(resource);
1260
+ let destroy;
1261
+ try {
1262
+ destroy = this.method(buffer, 'destroy', () => undefined);
1263
+ }
1264
+ catch (cause) {
1265
+ record.unsafe = true;
1266
+ this.proofFailed(cause);
1267
+ throw cause;
1268
+ }
1269
+ Object.assign(resource, { destroy });
1270
+ gate();
1271
+ const unmap = this.method(buffer, 'unmap', gate), map = this.method(buffer, 'mapAsync', gate), mappedRange = this.method(buffer, 'getMappedRange', gate);
1272
+ Object.assign(resource, { unmap, map, mappedRange });
1273
+ gate();
1274
+ return resource;
1275
+ }
1276
+ ownedTexture(view, record, gate, candidate) {
1277
+ gate();
1278
+ const texture = (record.owner?.native.texture ?? this.texture)({
1279
+ size: { width: view.region.width, height: view.region.height, depthOrArrayLayers: 1 },
1280
+ dimension: '2d',
1281
+ format: candidate.entry.format,
1282
+ mipLevelCount: 1,
1283
+ sampleCount: 1,
1284
+ usage: 2 | 4
1285
+ });
1286
+ // Register the returned object before any gate or cleanup/view getter can reenter close.
1287
+ const resource = {
1288
+ texture,
1289
+ destroy: () => {
1290
+ throw new TypeError('uncaptured texture destroy');
1291
+ },
1292
+ cleaned: false,
1293
+ logicalByteLength: candidate.entry.bytes
1294
+ };
1295
+ if (record.owner)
1296
+ resource.generation = record.owner;
1297
+ record.textures.push(resource);
1298
+ candidate.entry.resource = resource;
1299
+ record.imageUse.reserved -= candidate.entry.bytes;
1300
+ this.reservedImageBytes -= candidate.entry.bytes;
1301
+ this.allocatedImageBytes += candidate.entry.bytes;
1302
+ this.sampleResourceImages();
1303
+ let destroy;
1304
+ try {
1305
+ destroy = this.method(texture, 'destroy', () => undefined);
1306
+ }
1307
+ catch (cause) {
1308
+ record.unsafe = true;
1309
+ this.proofFailed(cause);
1310
+ throw cause;
1311
+ }
1312
+ Object.assign(resource, { destroy });
1313
+ gate();
1314
+ const createView = this.method(texture, 'createView', gate);
1315
+ gate();
1316
+ const result = createView();
1317
+ candidate.entry.view = result;
1318
+ record.views.push(result);
1319
+ gate();
1320
+ return { texture, view: result };
1321
+ }
1322
+ planImageResidency(projectionPlan, draws, shared = false) {
1323
+ this.active();
1324
+ const hits = new Map(), candidates = new Map();
1325
+ const bytes = collectWebGPUImageDemand(projectionPlan, draws, shared, this.imageDirectory, this.imageEnabled, this.imageEpoch, hits, candidates);
1326
+ // Every profile of this Host shares one ready residence; a shared Host may lower its bytes.
1327
+ const victims = selectWebGPUImageVictims(this.imageOldest, this.imageEpoch, this.allocatedImageBytes + this.reservedImageBytes, this.readyCount, SHARED_OPTIONS.get(this)?.maxReadyPageBytes ?? 33554432, bytes, candidates.size, hits);
1328
+ return {
1329
+ epoch: this.imageEpoch,
1330
+ revision: this.imageRevision,
1331
+ victims,
1332
+ bytes,
1333
+ use: {
1334
+ epoch: this.imageEpoch,
1335
+ hits,
1336
+ candidates,
1337
+ reserved: 0,
1338
+ pinned: false,
1339
+ finished: false,
1340
+ touchedQueue: false
1341
+ }
1342
+ };
1343
+ }
1344
+ assertImagePlanCurrent(plan) {
1345
+ this.active();
1346
+ if (!this.imageEnabled || plan.epoch !== this.imageEpoch || plan.revision !== this.imageRevision)
1347
+ throw new TypeError('stale image plan');
1348
+ }
1349
+ unlinkImageResidency(entry) {
1350
+ if (entry.previous)
1351
+ entry.previous.next = entry.next;
1352
+ else
1353
+ this.imageOldest = entry.next;
1354
+ if (entry.next)
1355
+ entry.next.previous = entry.previous;
1356
+ else
1357
+ this.imageNewest = entry.previous;
1358
+ entry.previous = undefined;
1359
+ entry.next = undefined;
1360
+ }
1361
+ appendImageResidency(entry) {
1362
+ entry.previous = this.imageNewest;
1363
+ entry.next = undefined;
1364
+ if (this.imageNewest)
1365
+ this.imageNewest.next = entry;
1366
+ else
1367
+ this.imageOldest = entry;
1368
+ this.imageNewest = entry;
1369
+ }
1370
+ detachReadyImage(entry) {
1371
+ this.imageCleanup.add(entry);
1372
+ this.bindingCache.invalidateTexture(entry.identity);
1373
+ if (entry.state === 'ready') {
1374
+ entry.bucket.delete(entry.cropKey);
1375
+ this.unlinkImageResidency(entry);
1376
+ entry.state = 'detached';
1377
+ this.readyCount--;
1378
+ this.resourceReadyBytes -= entry.bytes;
1379
+ if (entry.pinCount > 0) {
1380
+ this.resourcePinnedBytes -= entry.bytes;
1381
+ this.resourcePinnedEntries--;
1382
+ }
1383
+ this.sampleResourceImages();
1384
+ this.imageRevision = {};
1385
+ }
1386
+ }
1387
+ destroyReadyImage(entry) {
1388
+ // Registration and dependent-binding invalidation precede native cleanup.
1389
+ this.detachReadyImage(entry);
1390
+ const resource = entry.resource;
1391
+ if (resource.cleaned)
1392
+ return;
1393
+ const failures = cleanupWebGPUTexture(resource);
1394
+ if (failures.length) {
1395
+ this.noteUnknownResource(resource);
1396
+ this.proofFailed(failures[0]);
1397
+ throw failures[0];
1398
+ }
1399
+ // The native callback ran with the entire detached allocation charged.
1400
+ this.allocatedImageBytes -= entry.bytes;
1401
+ this.imageCleanup.delete(entry);
1402
+ }
1403
+ beginImageResidency(record, plan) {
1404
+ this.active();
1405
+ if (!this.busy || !this.imageEnabled || plan.epoch !== this.imageEpoch || plan.revision !== this.imageRevision)
1406
+ throw new TypeError('stale image plan');
1407
+ const use = plan.use;
1408
+ record.imageUse = use;
1409
+ for (const candidate of use.candidates.values())
1410
+ this.imageDirectory.set(candidate.image, candidate.entry.bucket);
1411
+ // Pin the complete hit set before touching order or entering any native call.
1412
+ for (const entry of use.hits.values()) {
1413
+ if (entry.pinCount === 0) {
1414
+ this.resourcePinnedBytes += entry.bytes;
1415
+ this.resourcePinnedEntries++;
1416
+ }
1417
+ entry.pinCount++;
1418
+ }
1419
+ this.sampleResourceImages();
1420
+ use.pinned = true;
1421
+ for (const entry of use.hits.values()) {
1422
+ this.unlinkImageResidency(entry);
1423
+ this.appendImageResidency(entry);
1424
+ }
1425
+ this.imageRevision = {};
1426
+ // This phase only transfers metadata. Buffer leases must be attached and
1427
+ // claimed before any victim's captured native destroy can reenter.
1428
+ for (const entry of plan.victims) {
1429
+ const capacityVictim = entry.state === 'ready';
1430
+ this.detachReadyImage(entry);
1431
+ if (capacityVictim && entry.state === 'detached')
1432
+ this.resourceTotal('readyCapacityEvictions', 1);
1433
+ }
1434
+ use.reserved = plan.bytes;
1435
+ this.reservedImageBytes += plan.bytes;
1436
+ this.sampleResourceImages();
1437
+ return use;
1438
+ }
1439
+ realizeImageResidency(record, use, viewIndex, gate) {
1440
+ gate();
1441
+ const hit = use.hits.get(viewIndex);
1442
+ if (hit) {
1443
+ record.views.push(hit.view);
1444
+ return { texture: hit.resource.texture, view: hit.view };
1445
+ }
1446
+ const candidate = use.candidates.get(viewIndex), projection = record.projectionPlan.views[viewIndex];
1447
+ const owned = this.ownedTexture(projection, record, gate, candidate);
1448
+ if (record.stage) {
1449
+ record.stage.writes.push({
1450
+ kind: 'texture',
1451
+ texture: owned.texture,
1452
+ data: record.projections[viewIndex],
1453
+ width: projection.region.width,
1454
+ height: projection.region.height,
1455
+ offset: 0
1456
+ });
1457
+ return owned;
1458
+ }
1459
+ // Attempted queue writes retain the original fence obligation, including throws.
1460
+ use.touchedQueue = true;
1461
+ (record.owner?.native.writeTexture ?? this.writeTexture)({ texture: owned.texture, mipLevel: 0, origin: { x: 0, y: 0, z: 0 }, aspect: 'all' }, record.projections[viewIndex], { offset: 0, bytesPerRow: 4 * projection.region.width, rowsPerImage: projection.region.height }, { width: projection.region.width, height: projection.region.height, depthOrArrayLayers: 1 });
1462
+ if (record.shared)
1463
+ this.resourcePageWrite(record.projections[viewIndex].byteLength);
1464
+ gate();
1465
+ return owned;
1466
+ }
1467
+ sharedWrite(record, buffer, data, unit) {
1468
+ if (record.stage) {
1469
+ record.stage.writes.push({ kind: 'buffer', buffer, data, unit, offset: 0 });
1470
+ return;
1471
+ }
1472
+ if (record.imageUse)
1473
+ record.imageUse.touchedQueue = true;
1474
+ (record.owner?.native.write ?? this.write)(buffer, 0, data);
1475
+ }
1476
+ isReuseEligible(record) {
1477
+ return (this.state === 'active' &&
1478
+ this.imageEnabled &&
1479
+ (SHARED_OPTIONS.get(this)?.recovery ? !this.generationFailure : !this.firstFailure) &&
1480
+ (!record.owner || (record.owner === this.owner && !record.owner.invalidated)) &&
1481
+ !this.unsafe &&
1482
+ !this.finalizing &&
1483
+ !record.failure &&
1484
+ !record.unsafe);
1485
+ }
1486
+ isImagePromotionEligible(record) {
1487
+ return this.isReuseEligible(record) && record.imageUse?.epoch === this.imageEpoch;
1488
+ }
1489
+ finishImageResidency(record, allowPromotion) {
1490
+ const use = record.imageUse;
1491
+ if (!use || use.finished)
1492
+ return;
1493
+ use.finished = true;
1494
+ if (use.pinned) {
1495
+ use.pinned = false;
1496
+ for (const entry of use.hits.values()) {
1497
+ if (entry.state === 'ready' && entry.pinCount === 1) {
1498
+ this.resourcePinnedBytes -= entry.bytes;
1499
+ this.resourcePinnedEntries--;
1500
+ }
1501
+ entry.pinCount--;
1502
+ }
1503
+ this.sampleResourceImages();
1504
+ }
1505
+ const failed = (cause) => {
1506
+ const failure = this.fail('WEBGPU_RENDER_FAILED', cause, 'cleanup', record.serial, true);
1507
+ record.unsafe = true;
1508
+ record.failure ??= failure;
1509
+ };
1510
+ for (const candidate of use.candidates.values()) {
1511
+ const entry = candidate.entry, resource = entry.resource;
1512
+ if (!resource || candidate.transferred)
1513
+ continue;
1514
+ // Re-read qualification, winner and slot after every earlier cleanup callback.
1515
+ if (allowPromotion &&
1516
+ this.isImagePromotionEligible(record) &&
1517
+ entry.epoch === this.imageEpoch &&
1518
+ !entry.bucket.has(entry.cropKey) &&
1519
+ this.readyCount < 256) {
1520
+ try {
1521
+ const revision = {};
1522
+ entry.bucket.set(entry.cropKey, entry);
1523
+ this.appendImageResidency(entry);
1524
+ entry.state = 'ready';
1525
+ this.readyCount++;
1526
+ this.resourceReadyBytes += entry.bytes;
1527
+ this.sampleResourceImages();
1528
+ candidate.transferred = true;
1529
+ record.textures.splice(record.textures.indexOf(resource), 1);
1530
+ this.imageRevision = revision;
1531
+ }
1532
+ catch (cause) {
1533
+ // No native call occurs during publication; restore the original owner.
1534
+ if (entry.bucket.get(entry.cropKey) === entry)
1535
+ entry.bucket.delete(entry.cropKey);
1536
+ if (entry.state === 'ready') {
1537
+ this.unlinkImageResidency(entry);
1538
+ this.readyCount--;
1539
+ this.resourceReadyBytes -= entry.bytes;
1540
+ entry.state = 'cold';
1541
+ this.sampleResourceImages();
1542
+ }
1543
+ candidate.transferred = false;
1544
+ failed(cause);
1545
+ }
1546
+ }
1547
+ if (!candidate.transferred && !resource.cleaned) {
1548
+ const failures = cleanupWebGPUTexture(resource);
1549
+ if (failures.length) {
1550
+ this.noteUnknownResource(resource);
1551
+ for (const cause of failures)
1552
+ failed(cause);
1553
+ }
1554
+ else
1555
+ this.allocatedImageBytes -= entry.bytes;
1556
+ }
1557
+ }
1558
+ this.reservedImageBytes -= use.reserved;
1559
+ use.reserved = 0;
1560
+ use.hits.clear();
1561
+ use.candidates.clear();
1562
+ record.imageUse = undefined;
1563
+ this.imageRevision = {};
1564
+ }
1565
+ invalidateImageResidency() {
1566
+ this.imageEnabled = false;
1567
+ this.imageRevision = {};
1568
+ this.bufferPool.invalidate();
1569
+ this.bindingCache.invalidate();
1570
+ }
1571
+ closeImageResidency() {
1572
+ this.invalidateImageResidency();
1573
+ while (this.imageOldest) {
1574
+ const entry = this.imageOldest;
1575
+ try {
1576
+ this.destroyReadyImage(entry);
1577
+ }
1578
+ catch (cause) {
1579
+ this.fail('WEBGPU_RENDER_FAILED', cause, 'cleanup', null, true);
1580
+ }
1581
+ // Registration failure leaves the directory owner intact, never lost.
1582
+ if (entry === this.imageOldest)
1583
+ break;
1584
+ }
1585
+ for (const entry of this.imageCleanup) {
1586
+ if (entry.resource.cleaned)
1587
+ continue;
1588
+ try {
1589
+ this.destroyReadyImage(entry);
1590
+ }
1591
+ catch (cause) {
1592
+ this.fail('WEBGPU_RENDER_FAILED', cause, 'cleanup', null, true);
1593
+ }
1594
+ }
1595
+ }
1596
+ submissionBuffer(record, requestId, gate) {
1597
+ gate();
1598
+ const existing = record.bufferLeases[requestId];
1599
+ if (existing)
1600
+ return existing;
1601
+ const request = record.bufferPlan.requests[requestId];
1602
+ if (request.kind !== 'buffer')
1603
+ throw new TypeError('Expected buffer lease');
1604
+ const resource = this.ownedBuffer(request.byteLength, request.usage, record, gate);
1605
+ const lease = (record.owner?.pool ?? this.bufferPool).registerCreated(request, resource);
1606
+ // Slots are preallocated before admission commits, in request order.
1607
+ // Transfer from the raw owner without a post-registration allocation.
1608
+ record.bufferLeases[requestId] = lease;
1609
+ record.resources.length--;
1610
+ return lease;
1611
+ }
1612
+ submissionBinding(record, key, entries, image, gate) {
1613
+ gate();
1614
+ const binding = (record.owner?.cache ?? this.bindingCache).lookup(key) ??
1615
+ (record.owner?.native.bindGroup ?? this.bindGroup)({ layout: key.layout, entries });
1616
+ // The record owns the returned binding before checking a native callback's state.
1617
+ record.bindings.push(binding);
1618
+ record.bindingCandidates.push({ key, binding, image });
1619
+ gate();
1620
+ return binding;
1621
+ }
1622
+ // The historical method name is retained, but the single cleanup path is
1623
+ // kind-aware for mixed target/buffer victims, returns and terminal close.
1624
+ destroyPooledBuffer(handle, pool = this.bufferPool, cache = this.bindingCache) {
1625
+ this.bufferCleanup.add(handle);
1626
+ if (handle.kind === 'buffer')
1627
+ cache.invalidateBuffer(handle.identity);
1628
+ pool.detach(handle);
1629
+ if (handle.resource.cleaned)
1630
+ return;
1631
+ const failures = handle.kind === 'buffer' ? cleanupWebGPUBuffer(handle.resource) : cleanupWebGPUTexture(handle.resource);
1632
+ if (handle.resource.settlement === 'context-invalidated')
1633
+ pool.contextInvalidated(handle);
1634
+ else
1635
+ pool.destroyed(handle, failures.length === 0);
1636
+ if (failures.length) {
1637
+ this.noteUnknownResource(handle.resource);
1638
+ this.proofFailed(failures[0]);
1639
+ throw failures[0];
1640
+ }
1641
+ this.bufferCleanup.delete(handle);
1642
+ }
1643
+ closeBuffers() {
1644
+ this.bufferPool.invalidate();
1645
+ this.bindingCache.clear();
1646
+ this.closingBuffers = this.bufferPool.detachIdleForClose();
1647
+ for (const handle of this.closingBuffers) {
1648
+ try {
1649
+ this.destroyPooledBuffer(handle);
1650
+ }
1651
+ catch (cause) {
1652
+ this.fail('WEBGPU_RENDER_FAILED', cause, 'cleanup', null, true);
1653
+ }
1654
+ }
1655
+ for (const handle of this.bufferCleanup) {
1656
+ if (handle.resource.cleaned)
1657
+ continue;
1658
+ try {
1659
+ this.destroyPooledBuffer(handle);
1660
+ }
1661
+ catch (cause) {
1662
+ this.fail('WEBGPU_RENDER_FAILED', cause, 'cleanup', null, true);
1663
+ }
1664
+ }
1665
+ this.closingBuffers = [];
1666
+ }
1667
+ sharedOwnerSnapshot() {
1668
+ this.active();
1669
+ return {
1670
+ pendingFrames: this.ledger.size,
1671
+ pendingUploadBytes: this.pendingUploadBytes,
1672
+ pendingReadbackBytes: this.pendingReadbackBytes,
1673
+ pendingTextureBytes: this.pendingTextureBytes,
1674
+ pendingGeometryBytes: this.pendingGeometryBytes,
1675
+ serial: this.lastSerial,
1676
+ pendingColorBytes: this.pendingColorBytes,
1677
+ pendingCanonicalBytes: this.pendingCanonicalBytes
1678
+ };
1679
+ }
1680
+ renderSharedOwnedFrame(input, staging) {
1681
+ this.active();
1682
+ if (this.busy)
1683
+ throw error('WEBGPU_REENTRANT');
1684
+ this.busy = true;
1685
+ this.cpu = deferred();
1686
+ let batch, signal, materialized = 0;
1687
+ try {
1688
+ let ownedFailure;
1689
+ const trusted = new WeakSet();
1690
+ const refuse = code => {
1691
+ const failure = new ClassifiedWebGPUFailure(code);
1692
+ trusted.add(failure);
1693
+ throw failure;
1694
+ };
1695
+ let admitted;
1696
+ try {
1697
+ admitted = runOwnedPreparationScope(() => {
1698
+ const options = SHARED_OPTIONS.get(this);
1699
+ if (!options)
1700
+ refuse('WEBGPU_FRAME_PROFILE_UNSUPPORTED');
1701
+ const frame = readOwnedSharedFrame(input);
1702
+ if (!frame)
1703
+ refuse('WEBGPU_FRAME_PROFILE_UNSUPPORTED');
1704
+ if (staging) {
1705
+ try {
1706
+ signal = this.captureStageSignal(staging.options);
1707
+ }
1708
+ catch (cause) {
1709
+ if (cause instanceof ClassifiedWebGPUFailure)
1710
+ trusted.add(cause);
1711
+ throw cause;
1712
+ }
1713
+ }
1714
+ if (frame.outputAlpha !== options.outputAlpha ||
1715
+ frame.outputRepresentation !==
1716
+ (options.outputAlpha === 'opaque' ? 'egret.srgb-opaque-unorm8/1' : 'egret.srgb-premultiplied-unorm8/1'))
1717
+ refuse('WEBGPU_FRAME_PROFILE_UNSUPPORTED');
1718
+ if (options.outputAlpha === 'opaque' && frame.clearAlpha !== 1)
1719
+ refuse('WEBGPU_FRAME_INVALID');
1720
+ const width = Math.ceil(frame.width * options.pixelRatio), height = Math.ceil(frame.height * options.pixelRatio);
1721
+ if (!Number.isSafeInteger(width) ||
1722
+ !Number.isSafeInteger(height) ||
1723
+ width <= 0 ||
1724
+ height <= 0 ||
1725
+ width > 4294967295 ||
1726
+ height > 4294967295 ||
1727
+ width > Math.floor(options.maxBackingPixels / height))
1728
+ refuse('WEBGPU_BACKING_LIMIT');
1729
+ const prepared = prepareSharedDraws2D(frame, width, height, options, this.retention), ticket = this.ticket && !this.ticket.bound ? this.ticket : undefined;
1730
+ const storage = planSharedSubmission2D(prepared, options, this.limits, this.sharedOwnerSnapshot(), staging ? options.enableReadback : ticket !== undefined);
1731
+ this.active();
1732
+ const packed = packSharedSubmission2D(prepared);
1733
+ this.active();
1734
+ const demands = [];
1735
+ for (const entry of packed) {
1736
+ if ('barrier' in entry)
1737
+ continue;
1738
+ const viewIndex = entry.prepared.pageIndex;
1739
+ if (viewIndex === undefined)
1740
+ demands.push({ kind: 'rect' });
1741
+ else
1742
+ demands.push({
1743
+ kind: entry.prepared.command.kind === 'mesh' ? 'mesh' : 'image',
1744
+ packed: { vertexCount: entry.vertexCount },
1745
+ viewIndex
1746
+ });
1747
+ }
1748
+ for (const group of prepared.effects.groups)
1749
+ if (group.maskPageIndex !== undefined)
1750
+ demands.push({ kind: 'image', packed: { vertexCount: 3 }, viewIndex: group.maskPageIndex });
1751
+ const imagePlan = this.planImageResidency(storage.projectionPlan, demands, true);
1752
+ const pages = materializeSharedPages2D(storage, new Set(imagePlan.use.candidates.keys()), this.sharedOwnerSnapshot(), this.resourceCpu);
1753
+ materialized = pages.canonicalBytes;
1754
+ this.active();
1755
+ checkSharedCapacity2D(storage, this.sharedOwnerSnapshot(), pages.canonicalBytes);
1756
+ // A staged frame writes its rows after later frames are prepared, so it is given batches of its own.
1757
+ batch = prepareSharedBatches2D(packed, this.limits.maxBufferSize, this.batchScratch, staging ? undefined : prepared.retention);
1758
+ this.active();
1759
+ const regions = batch.draws.some(draw => draw.regionWindow >= 0)
1760
+ ? packSharedRegionWindows2D(prepared.frame)
1761
+ : undefined;
1762
+ return { storage, imagePlan, ...pages, ticket, batch, regions };
1763
+ }, failure => {
1764
+ ownedFailure = failure;
1765
+ });
1766
+ }
1767
+ catch (cause) {
1768
+ if (this.state !== 'active')
1769
+ throw this.stateError();
1770
+ if (cause instanceof ClassifiedWebGPUFailure && trusted.has(cause))
1771
+ throw cause.publicError;
1772
+ if (cause === ownedFailure) {
1773
+ if (cause instanceof SharedPreparationError)
1774
+ throw error(cause.reason === 'profile'
1775
+ ? 'WEBGPU_FRAME_PROFILE_UNSUPPORTED'
1776
+ : cause.reason === 'budget'
1777
+ ? 'WEBGPU_FRAME_BUDGET'
1778
+ : cause.reason === 'precision'
1779
+ ? 'WEBGPU_PRECISION_UNSUPPORTED'
1780
+ : 'WEBGPU_FRAME_INVALID', cause);
1781
+ if (cause instanceof SharedStorageError2D)
1782
+ throw error(cause.reason === 'device'
1783
+ ? 'WEBGPU_DEVICE_LIMIT'
1784
+ : cause.reason === 'backpressure'
1785
+ ? 'WEBGPU_BACKPRESSURE'
1786
+ : cause.reason === 'serial'
1787
+ ? 'WEBGPU_SERIAL_EXHAUSTED'
1788
+ : 'WEBGPU_FRAME_BUDGET', cause);
1789
+ if (cause instanceof GeometryPreparationError)
1790
+ throw error(cause.reason === 'range'
1791
+ ? 'WEBGPU_GEOMETRY_RANGE'
1792
+ : cause.reason === 'budget'
1793
+ ? 'WEBGPU_FRAME_BUDGET'
1794
+ : 'WEBGPU_PRECISION_UNSUPPORTED', cause.cause);
1795
+ }
1796
+ throw error('WEBGPU_FRAME_INVALID', cause);
1797
+ }
1798
+ return this.submitShared(admitted, staging ? { signal } : undefined);
1799
+ }
1800
+ finally {
1801
+ if (!batch?.transferred)
1802
+ this.resourceCpu.canonicalBytes -= materialized;
1803
+ if (batch && !batch.transferred)
1804
+ this.batchScratch.release(batch);
1805
+ this.busy = false;
1806
+ this.cpu.resolve();
1807
+ }
1808
+ }
1809
+ captureStageSignal(options) {
1810
+ const gate = () => this.active();
1811
+ try {
1812
+ if (options !== undefined && !isObject(options))
1813
+ throw new TypeError('Upload options');
1814
+ const signal = options?.signal;
1815
+ gate();
1816
+ if (signal === undefined)
1817
+ return undefined;
1818
+ if (!isObject(signal))
1819
+ throw new TypeError('Upload signal');
1820
+ const add = this.method(signal, 'addEventListener', gate), remove = this.method(signal, 'removeEventListener', gate);
1821
+ const aborted = signal.aborted;
1822
+ gate();
1823
+ if (typeof aborted !== 'boolean')
1824
+ throw new TypeError('Signal aborted');
1825
+ const captured = {
1826
+ signal,
1827
+ add,
1828
+ remove,
1829
+ aborted: false,
1830
+ abortFailure: undefined,
1831
+ readingReason: false
1832
+ };
1833
+ if (aborted) {
1834
+ const failure = this.stageAbortReason(captured);
1835
+ throw new ClassifiedWebGPUFailure(failure.code, failure.cause, failure);
1836
+ }
1837
+ return captured;
1838
+ }
1839
+ catch (cause) {
1840
+ if (this.state !== 'active')
1841
+ throw this.stateError();
1842
+ if (cause instanceof ClassifiedWebGPUFailure)
1843
+ throw cause;
1844
+ throw new ClassifiedWebGPUFailure('WEBGPU_UPLOAD_OPTIONS_INVALID', cause);
1845
+ }
1846
+ }
1847
+ stageAbortReason(signal) {
1848
+ if (signal.abortFailure)
1849
+ return signal.abortFailure;
1850
+ signal.aborted = true;
1851
+ signal.readingReason = true;
1852
+ let failure;
1853
+ try {
1854
+ const reason = signal.signal.reason;
1855
+ failure = error('WEBGPU_UPLOAD_ABORTED', reason);
1856
+ }
1857
+ catch (cause) {
1858
+ failure = error('WEBGPU_UPLOAD_OPTIONS_INVALID', cause);
1859
+ }
1860
+ signal.readingReason = false;
1861
+ if (this.state !== 'active')
1862
+ failure = this.stateError();
1863
+ signal.abortFailure = failure;
1864
+ return failure;
1865
+ }
1866
+ stageGate(record) {
1867
+ this.active();
1868
+ if (record.owner !== this.owner || record.owner?.invalidated)
1869
+ throw error('WEBGPU_UPLOAD_STALE');
1870
+ if (record.stage &&
1871
+ !record.stage.failure &&
1872
+ record.stage.phase !== 'submitted' &&
1873
+ this.now() >= record.stage.deadline)
1874
+ this.revokeStage(record, error('WEBGPU_UPLOAD_EXPIRED'));
1875
+ this.active();
1876
+ if (record.stage?.failure)
1877
+ throw record.stage.failure;
1878
+ if (record.stage?.phase === 'revoked')
1879
+ throw error('WEBGPU_UPLOAD_ABORTED');
1880
+ }
1881
+ removeStageListener(stage) {
1882
+ if (stage.removeOnce)
1883
+ return;
1884
+ stage.removeOnce = true;
1885
+ stage.cancelDeadline?.();
1886
+ stage.cancelDeadline = undefined;
1887
+ const listener = stage.listener, signal = stage.signal;
1888
+ stage.listener = undefined;
1889
+ stage.signal = undefined;
1890
+ if (listener && signal)
1891
+ signal.remove('abort', listener);
1892
+ }
1893
+ /** A retained public ticket closes over only its cleared record, never admission arguments. */
1894
+ createStageHandle(record) {
1895
+ const stage = record.stage;
1896
+ const host = this;
1897
+ const handle = Object.freeze({
1898
+ ready: stage.ready.promise,
1899
+ submit() {
1900
+ if (this !== handle)
1901
+ throw error('WEBGPU_UPLOAD_INVALID');
1902
+ return host.submitStage(record);
1903
+ },
1904
+ dispose() {
1905
+ if (this !== handle)
1906
+ throw error('WEBGPU_UPLOAD_INVALID');
1907
+ if (stage.phase === 'submitted' || stage.phase === 'revoked')
1908
+ return;
1909
+ host.revokeStage(record, error('WEBGPU_UPLOAD_DISPOSED'));
1910
+ }
1911
+ });
1912
+ return handle;
1913
+ }
1914
+ admitStageRecord(record, p, done, signal, deadline) {
1915
+ const stage = {
1916
+ deadline,
1917
+ plan: p,
1918
+ frameId: p.storage.prepared.frame.frameId,
1919
+ generation: record.owner.number,
1920
+ done,
1921
+ ready: deferred(),
1922
+ native: deferred(),
1923
+ signal,
1924
+ phase: 'admitted',
1925
+ failure: undefined,
1926
+ returned: false,
1927
+ listener: undefined,
1928
+ removeOnce: false,
1929
+ cancelDeadline: undefined,
1930
+ recipe: undefined,
1931
+ writes: [],
1932
+ cursor: 0,
1933
+ outcomes: [],
1934
+ touched: false,
1935
+ proofStarted: false,
1936
+ proofSettled: false,
1937
+ inside: false
1938
+ };
1939
+ record.stage = stage;
1940
+ record.completion = observed(done.promise.then(() => {
1941
+ if (record.failure)
1942
+ throw record.failure;
1943
+ }));
1944
+ const handle = this.createStageHandle(record);
1945
+ try {
1946
+ stage.cancelDeadline = this.ownedTimeout(() => this.revokeStage(record, error('WEBGPU_UPLOAD_EXPIRED')), 10000);
1947
+ if (signal) {
1948
+ stage.listener = () => {
1949
+ if (signal.aborted || stage.phase === 'submitted' || stage.phase === 'revoked')
1950
+ return;
1951
+ // Revoke authority before the controlled reason getter, but publish its tagged result afterwards.
1952
+ stage.phase = 'revoked';
1953
+ signal.aborted = true;
1954
+ const failure = this.stageAbortReason(signal);
1955
+ this.revokeStage(record, failure);
1956
+ };
1957
+ signal.add('abort', stage.listener, { once: true });
1958
+ this.active();
1959
+ const aborted = signal.signal.aborted;
1960
+ this.active();
1961
+ if (typeof aborted !== 'boolean')
1962
+ throw new TypeError('Signal aborted');
1963
+ if (aborted && !signal.aborted)
1964
+ stage.listener();
1965
+ if (stage.failure)
1966
+ throw stage.failure;
1967
+ }
1968
+ this.stageGate(record);
1969
+ for (const handle of record.bufferPlan.victims)
1970
+ this.bufferCleanup.add(handle);
1971
+ this.beginImageResidency(record, p.imagePlan);
1972
+ this.bufferPool.claim(record.bufferPlan);
1973
+ record.bufferClaimed = true;
1974
+ this.stageGate(record);
1975
+ stage.returned = true;
1976
+ this.scheduleStagePump();
1977
+ return handle;
1978
+ }
1979
+ catch (cause) {
1980
+ const failure = this.state !== 'active' ? this.stateError() : (stage.failure ?? error('WEBGPU_UPLOAD_OPTIONS_INVALID', cause));
1981
+ // No native operation has begun. Subscription failures unwind this exact charged record synchronously.
1982
+ stage.phase = 'revoked';
1983
+ stage.failure = failure;
1984
+ record.failure = failure;
1985
+ stage.ready.reject(failure);
1986
+ stage.native.reject(failure);
1987
+ try {
1988
+ this.removeStageListener(stage);
1989
+ }
1990
+ catch { }
1991
+ try {
1992
+ this.retire(record);
1993
+ }
1994
+ finally {
1995
+ done.resolve();
1996
+ }
1997
+ throw failure;
1998
+ }
1999
+ }
2000
+ revokeStages(cause) {
2001
+ // Latch every authority before the first captured signal-removal callback can reenter.
2002
+ const affected = [];
2003
+ for (const record of this.ledger) {
2004
+ const stage = record.stage;
2005
+ if (stage && stage.phase !== 'submitted' && !stage.failure) {
2006
+ stage.phase = 'revoked';
2007
+ stage.failure = cause;
2008
+ record.failure ??= cause;
2009
+ stage.ready.reject(cause);
2010
+ stage.native.reject(cause);
2011
+ affected.push(record);
2012
+ }
2013
+ }
2014
+ for (const record of affected)
2015
+ this.finishStageRevocation(record);
2016
+ }
2017
+ revokeStage(record, cause) {
2018
+ const stage = record.stage;
2019
+ if (stage.phase === 'submitted' || stage.failure)
2020
+ return;
2021
+ stage.phase = 'revoked';
2022
+ stage.failure = this.state === 'active' ? cause : this.stateError();
2023
+ record.failure ??= stage.failure;
2024
+ stage.ready.reject(stage.failure);
2025
+ stage.native.reject(stage.failure);
2026
+ this.finishStageRevocation(record);
2027
+ }
2028
+ finishStageRevocation(record) {
2029
+ const stage = record.stage;
2030
+ try {
2031
+ this.removeStageListener(stage);
2032
+ }
2033
+ catch (cause) {
2034
+ stage.failure ??= error('WEBGPU_UPLOAD_OPTIONS_INVALID', cause);
2035
+ record.failure ??= stage.failure;
2036
+ }
2037
+ if (![...this.ledger].some(item => item.stage?.phase === 'admitted' || item.stage?.phase === 'uploading')) {
2038
+ this.cancelStagePump?.();
2039
+ this.cancelStagePump = undefined;
2040
+ this.stagePumpScheduled = false;
2041
+ }
2042
+ if (!stage.returned || stage.inside)
2043
+ return;
2044
+ if (stage.proofSettled)
2045
+ this.retireStage(record);
2046
+ else if (!stage.proofStarted)
2047
+ this.proveStage(record);
2048
+ }
2049
+ retireStage(record) {
2050
+ const stage = record.stage;
2051
+ // Scope rejection and observer failure are Host/owner classifications.
2052
+ // Latch them before the shared retirement sink can release this record.
2053
+ if (this.unsafe || record.owner?.unknown)
2054
+ record.unsafe = true;
2055
+ try {
2056
+ if (!record.unsafe)
2057
+ this.retire(record);
2058
+ }
2059
+ catch (cause) {
2060
+ record.unsafe = true;
2061
+ record.failure ??= this.fail('WEBGPU_RENDER_FAILED', cause, 'cleanup', record.serial, true);
2062
+ }
2063
+ finally {
2064
+ stage.writes.length = 0;
2065
+ stage.recipe = undefined;
2066
+ stage.done.resolve();
2067
+ }
2068
+ }
2069
+ scheduleStagePump() {
2070
+ if (this.stagePumpScheduled)
2071
+ return;
2072
+ this.stagePumpScheduled = true;
2073
+ this.cancelStagePump = this.ownedTimeout(() => {
2074
+ this.cancelStagePump = undefined;
2075
+ this.stagePumpScheduled = false;
2076
+ this.pumpStages();
2077
+ }, 0);
2078
+ }
2079
+ pumpStages() {
2080
+ if (this.busy) {
2081
+ this.scheduleStagePump();
2082
+ return;
2083
+ }
2084
+ let remaining = 4194304, more = false;
2085
+ this.busy = true;
2086
+ this.cpu = deferred();
2087
+ try {
2088
+ for (const record of this.ledger) {
2089
+ const stage = record.stage;
2090
+ if (!stage || (stage.phase !== 'admitted' && stage.phase !== 'uploading'))
2091
+ continue;
2092
+ if (remaining === 0) {
2093
+ more = true;
2094
+ continue;
2095
+ }
2096
+ stage.inside = true;
2097
+ const gate = () => this.stageGate(record);
2098
+ try {
2099
+ gate();
2100
+ stage.phase = 'uploading';
2101
+ this.scoped(null, 'frame', stage.outcomes, gate, () => {
2102
+ if (!stage.recipe) {
2103
+ for (const entry of stage.plan.imagePlan.victims) {
2104
+ gate();
2105
+ this.destroyReadyImage(entry);
2106
+ gate();
2107
+ }
2108
+ for (const handle of record.bufferPlan.victims) {
2109
+ gate();
2110
+ this.destroyPooledBuffer(handle);
2111
+ gate();
2112
+ }
2113
+ const color = record.bufferPlan.requests.find(request => request.kind === 'color').id;
2114
+ stage.recipe = this.prepareSharedGPU(record, stage.plan, color, gate);
2115
+ }
2116
+ while (stage.cursor < stage.writes.length) {
2117
+ const write = stage.writes[stage.cursor];
2118
+ const unit = write.kind === 'buffer' ? write.unit : 4 * write.width;
2119
+ const available = write.kind === 'buffer'
2120
+ ? write.data.byteLength - write.offset
2121
+ : 4 * write.width * write.height - write.offset;
2122
+ const count = Math.min(available, Math.floor(remaining / unit) * unit);
2123
+ if (count === 0) {
2124
+ more = true;
2125
+ break;
2126
+ }
2127
+ gate();
2128
+ stage.touched = true;
2129
+ if (record.imageUse)
2130
+ record.imageUse.touchedQueue = true;
2131
+ if (write.kind === 'buffer') {
2132
+ const view = new Uint8Array(write.data.buffer, write.data.byteOffset + write.offset, count);
2133
+ record.owner.native.write(write.buffer, write.offset, view);
2134
+ }
2135
+ else {
2136
+ const row = write.width * 4, rows = count / row;
2137
+ record.owner.native.writeTexture({ texture: write.texture, mipLevel: 0, origin: { x: 0, y: write.offset / row, z: 0 }, aspect: 'all' }, write.data, { offset: write.offset, bytesPerRow: row, rowsPerImage: rows }, { width: write.width, height: rows, depthOrArrayLayers: 1 });
2138
+ this.resourcePageWrite(count);
2139
+ }
2140
+ write.offset += count;
2141
+ remaining -= count;
2142
+ gate();
2143
+ if (count === available)
2144
+ stage.cursor++;
2145
+ }
2146
+ });
2147
+ }
2148
+ catch (cause) {
2149
+ const failure = stage.failure ??
2150
+ (this.state !== 'active'
2151
+ ? this.stateError()
2152
+ : cause instanceof ClassifiedWebGPUFailure
2153
+ ? cause.publicError
2154
+ : this.fail('WEBGPU_RENDER_FAILED', cause, 'frame', null));
2155
+ this.revokeStage(record, failure);
2156
+ }
2157
+ finally {
2158
+ stage.inside = false;
2159
+ }
2160
+ if (stage.failure || stage.cursor === stage.writes.length)
2161
+ this.proveStage(record);
2162
+ else
2163
+ more = true;
2164
+ }
2165
+ }
2166
+ finally {
2167
+ this.busy = false;
2168
+ this.cpu.resolve();
2169
+ }
2170
+ if (more && this.state === 'active')
2171
+ this.scheduleStagePump();
2172
+ }
2173
+ proveStage(record) {
2174
+ const stage = record.stage;
2175
+ if (stage.proofStarted)
2176
+ return;
2177
+ stage.proofStarted = true;
2178
+ if (!stage.failure)
2179
+ stage.phase = 'proof';
2180
+ const outcomes = [...stage.outcomes];
2181
+ if (stage.touched) {
2182
+ try {
2183
+ outcomes.push(observed(record.owner.fence()).catch(cause => {
2184
+ throw this.recordAsyncFailure(record, 'WEBGPU_QUEUE_FAILED', cause, 'frame');
2185
+ }));
2186
+ }
2187
+ catch (cause) {
2188
+ outcomes.push(observed(Promise.reject(this.recordAsyncFailure(record, 'WEBGPU_QUEUE_FAILED', cause, 'frame'))));
2189
+ }
2190
+ }
2191
+ observed(Promise.allSettled(outcomes).then(results => {
2192
+ stage.proofSettled = true;
2193
+ const rejected = results.find(result => result.status === 'rejected');
2194
+ if (rejected?.status === 'rejected' && !stage.failure) {
2195
+ const cause = rejected.reason;
2196
+ this.revokeStage(record, cause instanceof ClassifiedWebGPUFailure ? cause.publicError : cause);
2197
+ }
2198
+ if (!stage.failure) {
2199
+ try {
2200
+ this.stageGate(record);
2201
+ stage.phase = 'ready';
2202
+ stage.ready.resolve(Object.freeze({ generation: stage.generation, frameId: stage.frameId }));
2203
+ }
2204
+ catch (cause) {
2205
+ this.revokeStage(record, cause);
2206
+ }
2207
+ }
2208
+ if (stage.failure)
2209
+ this.retireStage(record);
2210
+ })).catch(cause => {
2211
+ record.unsafe = true;
2212
+ record.failure = this.fail('WEBGPU_RENDER_FAILED', cause, 'cleanup', null, true);
2213
+ stage.ready.reject(record.failure);
2214
+ stage.done.resolve();
2215
+ });
2216
+ }
2217
+ submitStage(record) {
2218
+ const stage = record.stage;
2219
+ this.active();
2220
+ if (this.busy)
2221
+ throw error('WEBGPU_REENTRANT');
2222
+ if (stage.generation !== this.generation || this.owner?.invalidated)
2223
+ throw error('WEBGPU_UPLOAD_STALE');
2224
+ if (stage.phase === 'submitted')
2225
+ throw error('WEBGPU_UPLOAD_USED');
2226
+ if (!stage.failure && this.now() >= stage.deadline)
2227
+ this.revokeStage(record, error('WEBGPU_UPLOAD_EXPIRED'));
2228
+ this.active();
2229
+ if (stage.failure)
2230
+ throw stage.failure;
2231
+ if (stage.phase !== 'ready')
2232
+ throw error('WEBGPU_UPLOAD_NOT_READY');
2233
+ if (this.lastSerial === Number.MAX_SAFE_INTEGER)
2234
+ throw error('WEBGPU_SERIAL_EXHAUSTED');
2235
+ this.busy = true;
2236
+ this.cpu = deferred();
2237
+ const plan = stage.plan, { storage } = plan, { frame, width, height } = storage.prepared;
2238
+ let ticket, staging, synchronous, submitted = false, touched = false;
2239
+ const outcomes = [];
2240
+ try {
2241
+ record.serial = ++this.lastSerial;
2242
+ stage.phase = 'submitted';
2243
+ if (record.imageUse)
2244
+ record.imageUse.touchedQueue = false;
2245
+ ticket = this.ticket && !this.ticket.bound ? this.ticket : undefined;
2246
+ if (ticket)
2247
+ ticket.bound = true;
2248
+ this.removeStageListener(stage);
2249
+ const gate = () => {
2250
+ this.active();
2251
+ if (record.owner !== this.owner || record.owner?.invalidated)
2252
+ throw error('WEBGPU_UPLOAD_STALE');
2253
+ };
2254
+ this.scoped(record.serial, 'frame', outcomes, gate, () => {
2255
+ const oldWidth = this.surface.width;
2256
+ gate();
2257
+ const oldHeight = this.surface.height;
2258
+ gate();
2259
+ if (oldWidth !== width) {
2260
+ this.surface.width = width;
2261
+ gate();
2262
+ }
2263
+ if (oldHeight !== height) {
2264
+ this.surface.height = height;
2265
+ gate();
2266
+ }
2267
+ const actualWidth = this.surface.width;
2268
+ gate();
2269
+ const actualHeight = this.surface.height;
2270
+ gate();
2271
+ if (actualWidth !== width || actualHeight !== height)
2272
+ throw new Error('Canvas rejected dimensions');
2273
+ if (oldWidth !== width || oldHeight !== height)
2274
+ this.configureSurface(gate);
2275
+ staging = ticket ? this.ownedBuffer(storage.staging, 9, record, gate) : undefined;
2276
+ touched = true;
2277
+ submitted = this.drawSharedGPU(record, plan, stage.recipe, staging, ticket, gate);
2278
+ });
2279
+ }
2280
+ catch (cause) {
2281
+ synchronous =
2282
+ this.state !== 'active'
2283
+ ? this.stateError()
2284
+ : cause instanceof ClassifiedWebGPUFailure
2285
+ ? cause.publicError
2286
+ : this.fail('WEBGPU_RENDER_FAILED', cause, 'frame', record.serial);
2287
+ record.failure = synchronous;
2288
+ }
2289
+ try {
2290
+ this.finishSubmission(record, ticket, stage.done, outcomes, touched, synchronous, submitted, staging, frame.frameId, width, height, storage.rowPitch, storage.output);
2291
+ return Object.freeze({
2292
+ generation: stage.generation,
2293
+ frameId: frame.frameId,
2294
+ serial: record.serial,
2295
+ completed: stage.native.promise
2296
+ });
2297
+ }
2298
+ finally {
2299
+ this.busy = false;
2300
+ this.cpu.resolve();
2301
+ }
2302
+ }
2303
+ recordAsyncFailure(record, code, cause, phase) {
2304
+ const owner = record.owner;
2305
+ if (owner?.invalidated && !owner.unknown && !record.unsafe)
2306
+ return record.failure ?? error('WEBGPU_DEVICE_LOST', cause);
2307
+ record.unsafe = true;
2308
+ if (owner)
2309
+ owner.unknown = true;
2310
+ if (owner && this.owner !== owner) {
2311
+ this.proofFailed(cause);
2312
+ return error(code, cause);
2313
+ }
2314
+ return this.fail(code, cause, phase, record.serial, true);
2315
+ }
2316
+ submissionTarget(record, requestId, gate) {
2317
+ gate();
2318
+ const request = record.bufferPlan.requests[requestId];
2319
+ if (request.kind === 'buffer')
2320
+ throw new TypeError('Expected target lease');
2321
+ let lease = record.bufferLeases[requestId];
2322
+ if (!lease) {
2323
+ const raw = record.shared?.rawTargets.find(slot => slot.requestId === requestId);
2324
+ if (!raw)
2325
+ throw new TypeError('Missing raw target owner');
2326
+ // The slot already exists: retain the returned native object before
2327
+ // allocating its registered wrapper or reading any external method.
2328
+ raw.logicalByteLength = request.byteLength;
2329
+ raw.texture = (record.owner?.native.texture ?? this.texture)({
2330
+ size: { width: request.width, height: request.height, depthOrArrayLayers: 1 },
2331
+ dimension: '2d',
2332
+ format: request.format,
2333
+ mipLevelCount: 1,
2334
+ sampleCount: 1,
2335
+ usage: request.usage
2336
+ });
2337
+ const texture = raw.texture;
2338
+ try {
2339
+ raw.destroy = this.method(texture, 'destroy', () => undefined);
2340
+ }
2341
+ catch (cause) {
2342
+ record.unsafe = true;
2343
+ this.proofFailed(cause);
2344
+ throw cause;
2345
+ }
2346
+ gate();
2347
+ const resource = {
2348
+ texture,
2349
+ destroy: raw.destroy,
2350
+ cleaned: false,
2351
+ logicalByteLength: request.byteLength,
2352
+ ...(raw.diagnosticUnknown ? { diagnosticUnknown: true } : {})
2353
+ };
2354
+ if (record.owner)
2355
+ resource.generation = record.owner;
2356
+ lease = (record.owner?.pool ?? this.bufferPool).registerCreated(request, resource);
2357
+ record.bufferLeases[requestId] = lease;
2358
+ // Only the completed, recorded registration transfers ownership.
2359
+ raw.texture = undefined;
2360
+ raw.destroy = undefined;
2361
+ }
2362
+ if (lease.handle.kind === 'buffer')
2363
+ throw new TypeError('Target lease kind');
2364
+ const resource = lease.handle.resource, view = this.method(resource.texture, 'createView', gate)();
2365
+ record.views.push(view);
2366
+ gate();
2367
+ return { resource, view };
2368
+ }
2369
+ submitShared(p, stageInput) {
2370
+ const { storage, imagePlan, batch } = p, { prepared } = storage, { frame, width, height } = prepared;
2371
+ this.assertImagePlanCurrent(imagePlan);
2372
+ const requests = [];
2373
+ const buffer = (role, usage, byteLength) => {
2374
+ if (byteLength > 0)
2375
+ requests.push({ kind: 'buffer', id: requests.length, role, usage, byteLength });
2376
+ };
2377
+ for (const draw of batch.draws) {
2378
+ buffer('vertex', 40, draw.data.byteLength);
2379
+ buffer('uniform', 72, 128);
2380
+ }
2381
+ if (p.regions)
2382
+ buffer('uniform', 72, p.regions.byteLength);
2383
+ for (const group of prepared.effects.groups)
2384
+ buffer('uniform', 72, group.uniform.byteLength);
2385
+ const colorId = requests.length;
2386
+ requests.push({
2387
+ kind: 'color',
2388
+ id: colorId,
2389
+ width,
2390
+ height,
2391
+ format: 'rgba8unorm-srgb',
2392
+ usage: 20,
2393
+ byteLength: storage.colorBytes,
2394
+ sampleCount: 1,
2395
+ mipLevelCount: 1,
2396
+ depthOrArrayLayers: 1,
2397
+ recipe: 'egret.srgb-pma8-target/1'
2398
+ });
2399
+ for (let i = 0; i < prepared.effects.targetCount; i++)
2400
+ requests.push({
2401
+ kind: 'color',
2402
+ id: requests.length,
2403
+ width,
2404
+ height,
2405
+ format: 'rgba8unorm-srgb',
2406
+ usage: 20,
2407
+ byteLength: storage.colorBytes,
2408
+ sampleCount: 1,
2409
+ mipLevelCount: 1,
2410
+ depthOrArrayLayers: 1,
2411
+ recipe: 'egret.srgb-pma8-target/1'
2412
+ });
2413
+ const bufferPlan = this.bufferPool.plan(requests), bufferLeases = new Array(requests.length).fill(undefined);
2414
+ for (const lease of bufferPlan.leases)
2415
+ bufferLeases[lease.requestId] = lease;
2416
+ const rawTargets = [
2417
+ { requestId: colorId, texture: undefined, destroy: undefined, cleanupAttempted: false }
2418
+ ];
2419
+ for (let i = 0; i < prepared.effects.targetCount; i++)
2420
+ rawTargets.push({ requestId: colorId + 1 + i, texture: undefined, destroy: undefined, cleanupAttempted: false });
2421
+ this.assertImagePlanCurrent(imagePlan);
2422
+ checkSharedCapacity2D(storage, this.sharedOwnerSnapshot(), p.canonicalBytes);
2423
+ const stageDeadline = stageInput ? this.now() + 10000 : 0;
2424
+ this.active();
2425
+ const owner = this.owner;
2426
+ // This shared-only path requires the exact prepared generation before charging a record.
2427
+ if (!owner ||
2428
+ owner.invalidated ||
2429
+ owner.number !== this.generation ||
2430
+ owner.device !== this.device ||
2431
+ owner.epoch !== imagePlan.epoch ||
2432
+ owner.pool !== this.bufferPool)
2433
+ throw error('WEBGPU_DEVICE_LOST', this.generationFailure?.cause);
2434
+ const serial = stageInput ? 0 : ++this.lastSerial, done = deferred();
2435
+ const record = {
2436
+ owner,
2437
+ batchPlan: batch,
2438
+ shared: {
2439
+ frame,
2440
+ draws: batch.draws,
2441
+ colorBytes: storage.colorBytes + storage.effectBytes,
2442
+ canonicalBytes: p.canonicalBytes,
2443
+ rawTargets
2444
+ },
2445
+ serial,
2446
+ upload: storage.upload,
2447
+ readback: storage.staging + storage.output,
2448
+ textureBytes: prepared.pageBytes,
2449
+ geometryBytes: prepared.geometryBytes,
2450
+ resources: [],
2451
+ textures: [],
2452
+ views: [],
2453
+ bindings: [],
2454
+ projectionPlan: storage.projectionPlan,
2455
+ projections: p.projections,
2456
+ imageUse: undefined,
2457
+ bufferPlan,
2458
+ bufferClaimed: false,
2459
+ bufferLeases,
2460
+ bufferReturns: undefined,
2461
+ retiring: false,
2462
+ bindingCandidates: [],
2463
+ outcome: done.promise,
2464
+ completion: done.promise,
2465
+ failure: undefined,
2466
+ unsafe: false,
2467
+ retired: false
2468
+ };
2469
+ this.ledger.add(record);
2470
+ batch.transferred = true;
2471
+ this.pendingUploadBytes += record.upload;
2472
+ this.pendingReadbackBytes += record.readback;
2473
+ this.pendingTextureBytes += record.textureBytes;
2474
+ this.pendingGeometryBytes += record.geometryBytes;
2475
+ // Active targets and retained canonical CPU arrays have separate ledgers.
2476
+ // Neither is an upload byte or a second idle retention allowance.
2477
+ this.pendingColorBytes += storage.colorBytes + storage.effectBytes;
2478
+ this.pendingCanonicalBytes += p.canonicalBytes;
2479
+ this.sampleResourcePending();
2480
+ if (stageInput)
2481
+ return this.admitStageRecord(record, p, done, stageInput.signal, stageDeadline);
2482
+ const ticket = p.ticket;
2483
+ if (ticket)
2484
+ ticket.bound = true;
2485
+ const outcomes = [];
2486
+ let touchedQueue = false, synchronous, staging, submitted = false;
2487
+ const gate = () => this.active();
2488
+ try {
2489
+ for (const handle of bufferPlan.victims)
2490
+ this.bufferCleanup.add(handle);
2491
+ this.beginImageResidency(record, imagePlan);
2492
+ this.bufferPool.claim(bufferPlan);
2493
+ record.bufferClaimed = true;
2494
+ for (const entry of imagePlan.victims) {
2495
+ gate();
2496
+ this.destroyReadyImage(entry);
2497
+ gate();
2498
+ }
2499
+ for (const handle of bufferPlan.victims) {
2500
+ gate();
2501
+ this.destroyPooledBuffer(handle);
2502
+ gate();
2503
+ }
2504
+ this.scoped(serial, 'frame', outcomes, gate, () => {
2505
+ const oldWidth = this.surface.width;
2506
+ gate();
2507
+ const oldHeight = this.surface.height;
2508
+ gate();
2509
+ if (oldWidth !== width) {
2510
+ this.surface.width = width;
2511
+ gate();
2512
+ }
2513
+ if (oldHeight !== height) {
2514
+ this.surface.height = height;
2515
+ gate();
2516
+ }
2517
+ const actualWidth = this.surface.width;
2518
+ gate();
2519
+ const actualHeight = this.surface.height;
2520
+ gate();
2521
+ if (actualWidth !== width || actualHeight !== height)
2522
+ throw new Error('Canvas rejected dimensions');
2523
+ if (oldWidth !== width || oldHeight !== height)
2524
+ this.configureSurface(gate);
2525
+ const recipe = this.prepareSharedGPU(record, p, colorId, gate);
2526
+ staging = ticket ? this.ownedBuffer(storage.staging, 9, record, gate) : undefined;
2527
+ touchedQueue = true;
2528
+ submitted = this.drawSharedGPU(record, p, recipe, staging, ticket, gate);
2529
+ });
2530
+ }
2531
+ catch (cause) {
2532
+ synchronous =
2533
+ cause instanceof ClassifiedWebGPUFailure
2534
+ ? cause.publicError
2535
+ : this.fail('WEBGPU_RENDER_FAILED', cause, 'frame', serial);
2536
+ record.failure = synchronous;
2537
+ }
2538
+ finally {
2539
+ // Direct uploads have copied the rows and draw encoding is synchronous.
2540
+ // The submission still owns its native resources until completion.
2541
+ this.batchScratch.release(batch);
2542
+ }
2543
+ return this.finishSubmission(record, ticket, done, outcomes, touchedQueue, synchronous, submitted, staging, frame.frameId, width, height, storage.rowPitch, storage.output);
2544
+ }
2545
+ /** The pipeline of a draw: without a region, of one page, or of several pages. */
2546
+ sharedRole(draw) {
2547
+ return this.sharedPipelines.get((draw.pages.length === 0 ? 'solid:' : draw.pages.length > 1 ? 'paged:' : 'sampled:') +
2548
+ draw.prepared.material.blend);
2549
+ }
2550
+ prepareSharedGPU(record, p, colorId, gate) {
2551
+ const { batch } = p, imageUse = record.imageUse;
2552
+ const realized = new Map();
2553
+ for (const draw of batch.draws)
2554
+ for (const index of draw.pages)
2555
+ if (!realized.has(index))
2556
+ realized.set(index, this.realizeImageResidency(record, imageUse, index, gate));
2557
+ for (const group of p.storage.prepared.effects.groups) {
2558
+ const index = group.maskPageIndex;
2559
+ if (index !== undefined && !realized.has(index))
2560
+ realized.set(index, this.realizeImageResidency(record, imageUse, index, gate));
2561
+ }
2562
+ let requestId = 0;
2563
+ const vertices = new Map(), bindings = new Map();
2564
+ for (const draw of batch.draws) {
2565
+ const vertex = this.submissionBuffer(record, requestId++, gate).handle.resource, lease = this.submissionBuffer(record, requestId++, gate), uniform = lease.handle.resource;
2566
+ vertices.set(draw, vertex);
2567
+ this.sharedWrite(record, vertex.buffer, draw.data, 52);
2568
+ gate();
2569
+ this.sharedWrite(record, uniform.buffer, draw.uniform, 128);
2570
+ gate();
2571
+ const source = draw.prepared, index = source.pageIndex, sampled = index !== undefined, role = this.sharedRole(draw);
2572
+ const image = sampled ? (imageUse.hits.get(index) ?? imageUse.candidates.get(index).entry) : undefined;
2573
+ const view = sampled ? realized.get(index).view : undefined, sampler = sampled
2574
+ ? this.sharedSamplers.get(source.material.filter + ':' + source.material.addressU + ':' + source.material.addressV)
2575
+ : undefined;
2576
+ const key = {
2577
+ session: this.imageEpoch,
2578
+ layout: role.layout,
2579
+ texture: image?.identity,
2580
+ view,
2581
+ sampler,
2582
+ uniform: lease.handle,
2583
+ offset: 0,
2584
+ size: 128
2585
+ };
2586
+ const entries = [{ binding: 0, resource: { buffer: uniform.buffer, offset: 0, size: 128 } }];
2587
+ if (sampled)
2588
+ entries.push({ binding: 1, resource: view }, { binding: 2, resource: sampler });
2589
+ // A batch of several pages has a view for each of the eight units of its pipeline. A unit the batch does not name
2590
+ // holds the first page again; no vertex selects it. The cache knows a group by one page, so this group is made
2591
+ // for the record and kept by it alone.
2592
+ if (draw.pages.length > 1) {
2593
+ for (let unit = 1; unit < SHARED_BATCH_PAGES_2D; unit++)
2594
+ entries.push({
2595
+ binding: 2 + unit,
2596
+ resource: unit < draw.pages.length ? realized.get(draw.pages[unit]).view : view
2597
+ });
2598
+ const binding = (record.owner?.native.bindGroup ?? this.bindGroup)({ layout: role.layout, entries });
2599
+ record.bindings.push(binding);
2600
+ gate();
2601
+ bindings.set(draw, binding);
2602
+ }
2603
+ else
2604
+ bindings.set(draw, this.submissionBinding(record, key, entries, image, gate));
2605
+ }
2606
+ // One buffer holds the region table of the record. A sampled draw binds its window of it as a second
2607
+ // group, made once for each pipeline and window the record uses and kept by the record alone.
2608
+ const regionBindings = new Map();
2609
+ if (p.regions) {
2610
+ const table = this.submissionBuffer(record, requestId++, gate).handle.resource;
2611
+ this.sharedWrite(record, table.buffer, p.regions, 16);
2612
+ gate();
2613
+ const made = new Map();
2614
+ for (const draw of batch.draws) {
2615
+ if (draw.regionWindow < 0)
2616
+ continue;
2617
+ const layout = this.sharedRole(draw).regions;
2618
+ let byWindow = made.get(layout);
2619
+ if (!byWindow) {
2620
+ byWindow = new Map();
2621
+ made.set(layout, byWindow);
2622
+ }
2623
+ let binding = byWindow.get(draw.regionWindow);
2624
+ if (!binding) {
2625
+ binding = (record.owner?.native.bindGroup ?? this.bindGroup)({
2626
+ layout,
2627
+ entries: [
2628
+ {
2629
+ binding: 0,
2630
+ resource: {
2631
+ buffer: table.buffer,
2632
+ offset: draw.regionWindow * SHARED_REGION_WINDOW_STRIDE_2D,
2633
+ size: SHARED_REGION_WINDOW_BYTES_2D
2634
+ }
2635
+ }
2636
+ ]
2637
+ });
2638
+ record.bindings.push(binding);
2639
+ gate();
2640
+ byWindow.set(draw.regionWindow, binding);
2641
+ }
2642
+ regionBindings.set(draw, binding);
2643
+ }
2644
+ }
2645
+ const effectUniforms = new Map();
2646
+ for (const group of p.storage.prepared.effects.groups) {
2647
+ const uniform = this.submissionBuffer(record, requestId++, gate).handle.resource;
2648
+ this.sharedWrite(record, uniform.buffer, group.uniform, 16);
2649
+ gate();
2650
+ effectUniforms.set(group, uniform);
2651
+ }
2652
+ const effectTargets = [];
2653
+ for (let i = 0; i < p.storage.prepared.effects.targetCount; i++)
2654
+ effectTargets.push(this.submissionTarget(record, colorId + 1 + i, gate));
2655
+ const effects = new Map();
2656
+ for (const group of p.storage.prepared.effects.groups) {
2657
+ const bindings = new Map(), source = effectTargets[(group.depth - 1) * 2], scratch = effectTargets[(group.depth - 1) * 2 + 1];
2658
+ for (const mode of EFFECT_PASSES) {
2659
+ const role = this.effectPipelines.get(mode);
2660
+ const entries = [
2661
+ {
2662
+ binding: 0,
2663
+ resource: { buffer: effectUniforms.get(group).buffer, offset: 0, size: EFFECT_UNIFORM_BYTES }
2664
+ },
2665
+ { binding: 1, resource: (mode === 'vertical' ? scratch : source).view }
2666
+ ];
2667
+ if (mode === 'composite')
2668
+ entries.push({
2669
+ binding: 2,
2670
+ resource: group.maskPageIndex === undefined ? source.view : realized.get(group.maskPageIndex).view
2671
+ }, { binding: 3, resource: scratch.view });
2672
+ const binding = record.owner.native.bindGroup({ layout: role.layout, entries });
2673
+ record.bindings.push(binding);
2674
+ gate();
2675
+ bindings.set(mode, binding);
2676
+ }
2677
+ effects.set(group, bindings);
2678
+ }
2679
+ const color = this.submissionTarget(record, colorId, gate);
2680
+ const resolveBinding = record.owner.native.bindGroup({
2681
+ layout: this.resolveLayout,
2682
+ entries: [{ binding: 0, resource: color.view }]
2683
+ });
2684
+ record.bindings.push(resolveBinding);
2685
+ gate();
2686
+ return { vertices, bindings, regionBindings, color, resolveBinding, effectTargets, effects };
2687
+ }
2688
+ drawSharedGPU(record, p, recipe, staging, ticket, gate) {
2689
+ const { storage, batch } = p, { frame, width, height } = storage.prepared, serial = record.serial;
2690
+ const { vertices, bindings, color, resolveBinding } = recipe;
2691
+ const texture = record.owner.native.currentTexture();
2692
+ gate();
2693
+ const canvasView = this.method(texture, 'createView', gate)();
2694
+ gate();
2695
+ const encoder = record.owner.native.encoder();
2696
+ gate();
2697
+ const begin = this.method(encoder, 'beginRenderPass', gate), finish = this.method(encoder, 'finish', gate), copy = ticket ? this.method(encoder, 'copyTextureToBuffer', gate) : undefined;
2698
+ const c = frame.clearColor, a = frame.clearAlpha;
2699
+ const attachment = {
2700
+ view: color.view,
2701
+ loadOp: 'clear',
2702
+ storeOp: 'store',
2703
+ clearValue: {
2704
+ r: a * decodeSharedSRGBByte(c >>> 16),
2705
+ g: a * decodeSharedSRGBByte(c >>> 8),
2706
+ b: a * decodeSharedSRGBByte(c),
2707
+ a
2708
+ }
2709
+ };
2710
+ const capture = (pass, keys) => {
2711
+ const captured = {};
2712
+ for (const key of keys) {
2713
+ const method = this.method(pass, key, gate);
2714
+ Object.defineProperty(captured, key, {
2715
+ value: (...args) => {
2716
+ gate();
2717
+ const result = method(...args);
2718
+ gate();
2719
+ return result;
2720
+ }
2721
+ });
2722
+ }
2723
+ return captured;
2724
+ };
2725
+ const openPass = (view, clear, initial = false) => {
2726
+ const colors = initial
2727
+ ? attachment
2728
+ : {
2729
+ view,
2730
+ loadOp: clear ? 'clear' : 'load',
2731
+ storeOp: 'store',
2732
+ ...(clear ? { clearValue: { r: 0, g: 0, b: 0, a: 0 } } : {})
2733
+ };
2734
+ const raw = begin({ colorAttachments: [colors] });
2735
+ gate();
2736
+ return {
2737
+ pass: capture(raw, ['setPipeline', 'setViewport', 'setScissorRect', 'setVertexBuffer', 'setBindGroup', 'draw']),
2738
+ end: this.method(raw, 'end', gate)
2739
+ };
2740
+ };
2741
+ let active = openPass(color.view, false, true);
2742
+ const drawOne = (draw) => {
2743
+ const role = this.sharedRole(draw);
2744
+ active.pass.setPipeline(role.pipeline);
2745
+ active.pass.setViewport(0, 0, width, height, 0, 1);
2746
+ active.pass.setScissorRect(0, 0, width, height);
2747
+ active.pass.setVertexBuffer(0, vertices.get(draw).buffer);
2748
+ active.pass.setBindGroup(0, bindings.get(draw));
2749
+ if (draw.regionWindow >= 0)
2750
+ active.pass.setBindGroup(1, recipe.regionBindings.get(draw));
2751
+ active.pass.draw(draw.vertexCount);
2752
+ };
2753
+ if (storage.prepared.effects.groups.length === 0) {
2754
+ for (const draw of batch.draws)
2755
+ drawOne(draw);
2756
+ }
2757
+ else {
2758
+ const byOrdinal = new Map(batch.draws.map(draw => [draw.prepared.command.ordinal, draw]));
2759
+ const enters = new Map(storage.prepared.effects.groups.map(group => [group.enter, group])), exits = new Map(storage.prepared.effects.groups.map(group => [group.exit, group]));
2760
+ const effectPass = (group, mode, view, clear) => {
2761
+ const run = openPass(view, clear);
2762
+ run.pass.setPipeline(this.effectPipelines.get(mode).pipeline);
2763
+ run.pass.setViewport(0, 0, width, height, 0, 1);
2764
+ run.pass.setScissorRect(0, 0, width, height);
2765
+ run.pass.setBindGroup(0, recipe.effects.get(group).get(mode));
2766
+ run.pass.draw(3);
2767
+ run.end();
2768
+ gate();
2769
+ };
2770
+ for (const command of frame.commands) {
2771
+ const enter = enters.get(command.ordinal), exit = exits.get(command.ordinal);
2772
+ if (enter) {
2773
+ active.end();
2774
+ gate();
2775
+ active = openPass(recipe.effectTargets[(enter.depth - 1) * 2].view, true);
2776
+ }
2777
+ else if (exit) {
2778
+ active.end();
2779
+ gate();
2780
+ const source = recipe.effectTargets[(exit.depth - 1) * 2], scratch = recipe.effectTargets[(exit.depth - 1) * 2 + 1];
2781
+ if (exit.radius > 0) {
2782
+ effectPass(exit, 'horizontal', scratch.view, true);
2783
+ effectPass(exit, 'vertical', source.view, true);
2784
+ }
2785
+ if (exit.spread >= 0)
2786
+ effectPass(exit, 'spread', scratch.view, true);
2787
+ const parent = exit.depth === 1 ? color : recipe.effectTargets[(exit.depth - 2) * 2];
2788
+ effectPass(exit, 'composite', parent.view, false);
2789
+ active = openPass(parent.view, false);
2790
+ }
2791
+ else {
2792
+ const draw = byOrdinal.get(command.ordinal);
2793
+ if (draw)
2794
+ drawOne(draw);
2795
+ }
2796
+ }
2797
+ }
2798
+ active.end();
2799
+ gate();
2800
+ const resolveRaw = begin({
2801
+ colorAttachments: [
2802
+ { view: canvasView, loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 0 } }
2803
+ ]
2804
+ });
2805
+ gate();
2806
+ const resolve = capture(resolveRaw, ['setPipeline', 'setViewport', 'setScissorRect', 'setBindGroup', 'draw']), endResolve = this.method(resolveRaw, 'end', gate);
2807
+ resolve.setPipeline(this.resolvePipeline);
2808
+ resolve.setViewport(0, 0, width, height, 0, 1);
2809
+ resolve.setScissorRect(0, 0, width, height);
2810
+ resolve.setBindGroup(0, resolveBinding);
2811
+ resolve.draw(3);
2812
+ endResolve();
2813
+ gate();
2814
+ if (staging) {
2815
+ try {
2816
+ copy({ texture }, { buffer: staging.buffer, bytesPerRow: storage.rowPitch, rowsPerImage: height }, { width, height, depthOrArrayLayers: 1 });
2817
+ }
2818
+ catch (cause) {
2819
+ throw new ClassifiedWebGPUFailure('WEBGPU_READBACK_FAILED', cause, this.fail('WEBGPU_READBACK_FAILED', cause, 'readback', serial));
2820
+ }
2821
+ gate();
2822
+ }
2823
+ const commands = finish();
2824
+ gate();
2825
+ record.owner.native.submit([commands]);
2826
+ gate();
2827
+ return true;
2828
+ }
2829
+ finishSubmission(record, ticket, done, outcomes, touchedQueue, synchronous, submitted, staging, frameId, width, height, rowPitch, output) {
2830
+ const serial = record.serial;
2831
+ let result;
2832
+ const nativeOutcomes = [...outcomes], nativeFailure = synchronous;
2833
+ if (submitted && staging && !synchronous) {
2834
+ try {
2835
+ outcomes.push(this.readPixels(staging, record, frameId, width, height, rowPitch, output).then(value => {
2836
+ result = value;
2837
+ }));
2838
+ }
2839
+ catch (cause) {
2840
+ synchronous = this.recordAsyncFailure(record, 'WEBGPU_READBACK_FAILED', cause, 'readback');
2841
+ record.failure = synchronous;
2842
+ }
2843
+ }
2844
+ if (touchedQueue || record.imageUse?.touchedQueue) {
2845
+ let proof;
2846
+ try {
2847
+ proof = observed((record.owner?.fence ?? this.fence)()).catch(cause => {
2848
+ throw this.recordAsyncFailure(record, 'WEBGPU_QUEUE_FAILED', cause, 'frame');
2849
+ });
2850
+ }
2851
+ catch (cause) {
2852
+ proof = observed(Promise.reject(this.recordAsyncFailure(record, 'WEBGPU_QUEUE_FAILED', cause, 'frame')));
2853
+ }
2854
+ outcomes.push(proof);
2855
+ nativeOutcomes.push(proof);
2856
+ }
2857
+ if (record.stage) {
2858
+ const stage = record.stage;
2859
+ observed(Promise.allSettled(nativeOutcomes).then(results => {
2860
+ const rejected = results.find(value => value.status === 'rejected');
2861
+ if (nativeFailure)
2862
+ stage.native.reject(nativeFailure);
2863
+ else if (record.owner?.invalidated)
2864
+ stage.native.reject(record.failure ?? error('WEBGPU_DEVICE_LOST'));
2865
+ else if (rejected?.status === 'rejected')
2866
+ stage.native.reject(rejected.reason instanceof ClassifiedWebGPUFailure ? rejected.reason.publicError : rejected.reason);
2867
+ else
2868
+ stage.native.resolve();
2869
+ }));
2870
+ }
2871
+ const settled = Promise.allSettled(outcomes).then(results => {
2872
+ const rejected = results.find(value => value.status === 'rejected');
2873
+ if (rejected?.status === 'rejected')
2874
+ record.failure ??=
2875
+ rejected.reason instanceof ClassifiedWebGPUFailure
2876
+ ? rejected.reason.publicError
2877
+ : rejected.reason;
2878
+ if (this.unsafe)
2879
+ record.unsafe = true;
2880
+ if (!record.unsafe)
2881
+ this.retire(record);
2882
+ if (ticket) {
2883
+ if (record.failure)
2884
+ ticket.reject(record.failure);
2885
+ else if (!SHARED_OPTIONS.get(this)?.recovery && this.firstFailure)
2886
+ ticket.reject(error(this.firstFailure.code, this.firstFailure.cause));
2887
+ else if (result)
2888
+ ticket.resolve(result);
2889
+ else
2890
+ ticket.reject(error('WEBGPU_READBACK_FAILED'));
2891
+ if (this.ticket === ticket)
2892
+ this.ticket = undefined;
2893
+ }
2894
+ done.resolve();
2895
+ });
2896
+ observed(settled).catch(cause => {
2897
+ record.unsafe = true;
2898
+ record.failure = this.fail('WEBGPU_RENDER_FAILED', cause, 'cleanup', serial, true);
2899
+ ticket?.reject(record.failure);
2900
+ done.resolve();
2901
+ });
2902
+ record.completion = observed(done.promise.then(() => {
2903
+ if (record.failure)
2904
+ throw record.failure;
2905
+ if (!SHARED_OPTIONS.get(this)?.recovery &&
2906
+ this.firstFailure &&
2907
+ (this.firstFailure.serial === null || this.firstFailure.serial <= serial))
2908
+ throw error(this.firstFailure.code, this.firstFailure.cause);
2909
+ }));
2910
+ if (synchronous)
2911
+ throw synchronous;
2912
+ return undefined;
2913
+ }
2914
+ async rejectReadbackMapping(record, cause) {
2915
+ const owner = record.owner, recovery = SHARED_OPTIONS.get(this)?.recovery;
2916
+ if (recovery &&
2917
+ owner &&
2918
+ owner === this.owner &&
2919
+ !record.stage &&
2920
+ !owner.invalidated &&
2921
+ !owner.unknown &&
2922
+ !record.unsafe &&
2923
+ !this.unsafe) {
2924
+ let abort = false;
2925
+ try {
2926
+ const name = Object.getOwnPropertyDescriptor(DOMException.prototype, 'name')?.get;
2927
+ abort = name !== undefined && Reflect.apply(name, cause, []) === 'AbortError';
2928
+ }
2929
+ catch {
2930
+ // Missing platform support or a non-DOMException must take the original failure path.
2931
+ }
2932
+ if (abort) {
2933
+ // A native map abort can arrive before the authenticated loss notification.
2934
+ // It is never loss proof on its own. Do not subscribe again to device.lost.
2935
+ await new Promise(resolve => {
2936
+ let cancel, settled = false;
2937
+ const finish = () => {
2938
+ if (settled)
2939
+ return;
2940
+ settled = true;
2941
+ delete owner.finishReadbackLossWait;
2942
+ try {
2943
+ cancel?.();
2944
+ }
2945
+ catch {
2946
+ // A failed cancellation cannot keep this waiter or obstruct genuine loss.
2947
+ }
2948
+ resolve();
2949
+ };
2950
+ owner.finishReadbackLossWait = finish;
2951
+ try {
2952
+ cancel = this.ownedTimeout(finish, Math.min(recovery.timeoutMs, 1000));
2953
+ }
2954
+ catch {
2955
+ finish();
2956
+ }
2957
+ });
2958
+ }
2959
+ }
2960
+ throw this.recordAsyncFailure(record, 'WEBGPU_READBACK_FAILED', cause, 'readback');
2961
+ }
2962
+ readPixels(staging, record, frameId, width, height, rowPitch, output) {
2963
+ const owner = record.owner, format = owner?.format ?? this.format, alpha = owner?.alpha ?? 'premultiplied';
2964
+ const mapping = observed(staging.map(1));
2965
+ return observed(mapping.then(() => {
2966
+ try {
2967
+ if (owner?.invalidated)
2968
+ throw record.failure ?? error('WEBGPU_DEVICE_LOST');
2969
+ staging.mapped = true;
2970
+ const mapped = new Uint8Array(staging.mappedRange()), bytes = new Uint8Array(output);
2971
+ if (owner?.invalidated)
2972
+ throw record.failure ?? error('WEBGPU_DEVICE_LOST');
2973
+ for (let y = 0; y < height; y++)
2974
+ bytes.set(mapped.subarray(y * rowPitch, y * rowPitch + width * 4), y * width * 4);
2975
+ if (format === 'bgra8unorm')
2976
+ for (let i = 0; i < bytes.length; i += 4) {
2977
+ const blue = bytes[i];
2978
+ bytes[i] = bytes[i + 2];
2979
+ bytes[i + 2] = blue;
2980
+ }
2981
+ const value = {
2982
+ serial: record.serial,
2983
+ frameId,
2984
+ width,
2985
+ height,
2986
+ format: 'rgba8unorm',
2987
+ sourceFormat: format,
2988
+ colorSpace: 'srgb',
2989
+ alphaMode: alpha,
2990
+ bytes
2991
+ };
2992
+ return owner
2993
+ ? Object.freeze({ ...value, generation: owner.number })
2994
+ : Object.freeze({ ...value, alphaMode: 'premultiplied' });
2995
+ }
2996
+ catch (cause) {
2997
+ throw this.recordAsyncFailure(record, 'WEBGPU_READBACK_FAILED', cause, 'readback');
2998
+ }
2999
+ }, cause => this.rejectReadbackMapping(record, cause)));
3000
+ }
3001
+ retire(record) {
3002
+ if (record.retired || record.retiring)
3003
+ return;
3004
+ record.retiring = true;
3005
+ const pool = record.owner?.pool ?? this.bufferPool, cache = record.owner?.cache ?? this.bindingCache;
3006
+ if (record.unsafe || record.owner?.unknown)
3007
+ this.noteUnknownRecord(record);
3008
+ const failed = (cause) => {
3009
+ const failure = this.fail('WEBGPU_RENDER_FAILED', cause, 'cleanup', record.serial, true);
3010
+ record.failure ??= failure;
3011
+ record.unsafe = true;
3012
+ };
3013
+ const cleanLease = (index) => {
3014
+ const lease = record.bufferLeases[index];
3015
+ if (!lease)
3016
+ return;
3017
+ try {
3018
+ this.destroyPooledBuffer(lease.handle, pool, cache);
3019
+ }
3020
+ catch (cause) {
3021
+ failed(cause);
3022
+ }
3023
+ // The persistent detached owner retains unknown destruction. If its
3024
+ // registration failed before cleanup, keep this record's exact slot.
3025
+ if (lease.handle.resource.cleaned)
3026
+ record.bufferLeases[index] = undefined;
3027
+ };
3028
+ try {
3029
+ // Admission can detach victims before the first scheduled task. Their existing
3030
+ // cleanup ownership must settle even when the stage is revoked before that task.
3031
+ if (record.stage?.plan && record.imageUse) {
3032
+ for (const entry of record.stage.plan.imagePlan.victims) {
3033
+ if (entry.state === 'detached' && this.imageCleanup.has(entry) && !entry.resource.cleaned) {
3034
+ try {
3035
+ this.destroyReadyImage(entry);
3036
+ }
3037
+ catch (cause) {
3038
+ failed(cause);
3039
+ }
3040
+ }
3041
+ }
3042
+ }
3043
+ if (record.stage && record.bufferClaimed) {
3044
+ for (const handle of record.bufferPlan.victims) {
3045
+ if (this.bufferCleanup.has(handle) && !handle.resource.cleaned) {
3046
+ try {
3047
+ this.destroyPooledBuffer(handle, pool, cache);
3048
+ }
3049
+ catch (cause) {
3050
+ failed(cause);
3051
+ }
3052
+ }
3053
+ }
3054
+ }
3055
+ if (!record.bufferClaimed)
3056
+ record.bufferLeases.fill(undefined);
3057
+ if (!record.bufferReturns && this.isReuseEligible(record)) {
3058
+ const leases = record.bufferLeases.filter((lease) => lease !== undefined);
3059
+ // Any later metadata failure leaves this exact reservation and
3060
+ // every lease reachable from the unretired ledger record.
3061
+ record.bufferReturns = pool.reserveReturns(leases);
3062
+ }
3063
+ const retained = new Set(record.bufferReturns?.retained);
3064
+ for (const resource of record.resources)
3065
+ for (const cause of cleanupWebGPUBuffer(resource))
3066
+ failed(cause);
3067
+ for (let index = 0; index < record.bufferLeases.length; index++) {
3068
+ const lease = record.bufferLeases[index];
3069
+ if (lease && !retained.has(lease.handle))
3070
+ cleanLease(index);
3071
+ }
3072
+ for (const resource of record.textures) {
3073
+ let candidateOwned = false;
3074
+ if (record.imageUse)
3075
+ for (const candidate of record.imageUse.candidates.values()) {
3076
+ if (candidate.entry.resource === resource) {
3077
+ candidateOwned = true;
3078
+ break;
3079
+ }
3080
+ }
3081
+ if (candidateOwned)
3082
+ continue;
3083
+ for (const cause of cleanupWebGPUTexture(resource))
3084
+ failed(cause);
3085
+ }
3086
+ if (record.shared)
3087
+ for (const raw of record.shared.rawTargets) {
3088
+ if (raw.texture === undefined || raw.cleanupAttempted)
3089
+ continue;
3090
+ // Unknown cleanup is terminal. Keep the exact native owner and
3091
+ // the submission charge; neither close nor a later retire retries.
3092
+ raw.cleanupAttempted = true;
3093
+ try {
3094
+ if (!raw.destroy)
3095
+ throw new TypeError('Target destruction method was not captured');
3096
+ if (!record.owner?.invalidated)
3097
+ raw.destroy();
3098
+ raw.texture = undefined;
3099
+ raw.destroy = undefined;
3100
+ }
3101
+ catch (cause) {
3102
+ failed(cause);
3103
+ }
3104
+ }
3105
+ this.finishImageResidency(record, !this.finalizing);
3106
+ if (record.bufferReturns) {
3107
+ let published = false;
3108
+ if (this.isReuseEligible(record)) {
3109
+ try {
3110
+ pool.publishReturns(record.bufferReturns);
3111
+ published = true;
3112
+ }
3113
+ catch (cause) {
3114
+ failed(cause);
3115
+ }
3116
+ }
3117
+ if (published) {
3118
+ // The pool is now the sole native owner. Clear only the
3119
+ // transferred slots before any subsequent metadata work.
3120
+ for (let index = 0; index < record.bufferLeases.length; index++) {
3121
+ const lease = record.bufferLeases[index];
3122
+ if (lease && retained.has(lease.handle))
3123
+ record.bufferLeases[index] = undefined;
3124
+ }
3125
+ record.bufferReturns = undefined;
3126
+ }
3127
+ else {
3128
+ pool.cancelReturns(record.bufferReturns);
3129
+ record.bufferReturns = undefined;
3130
+ for (let index = 0; index < record.bufferLeases.length; index++)
3131
+ cleanLease(index);
3132
+ retained.clear();
3133
+ }
3134
+ }
3135
+ if (this.isReuseEligible(record)) {
3136
+ try {
3137
+ cache.publish(record.bindingCandidates.filter(candidate => retained.has(candidate.key.uniform) &&
3138
+ (!candidate.image || (candidate.image.state === 'ready' && !candidate.image.resource.cleaned))));
3139
+ }
3140
+ catch (cause) {
3141
+ failed(cause);
3142
+ }
3143
+ }
3144
+ // An uncompleted ownership transfer must retain both its ledger
3145
+ // charge and record for explicit close; never silently drop it.
3146
+ if (record.bufferLeases.some(lease => lease !== undefined))
3147
+ throw new TypeError('Unfinished buffer cleanup');
3148
+ if (record.shared?.rawTargets.some(raw => raw.texture !== undefined))
3149
+ throw new TypeError('Unfinished target cleanup');
3150
+ // New staged/recovery authority retains unknown charges. Legacy immediate
3151
+ // retirement releases logical accounting only after its once cleanup;
3152
+ // unsafe outcome and persistent detached owners remain quarantined.
3153
+ if ((record.stage || SHARED_OPTIONS.get(this)?.recovery) &&
3154
+ (record.unsafe ||
3155
+ record.resources.some(resource => resource.settlement === 'unknown') ||
3156
+ record.textures.some(resource => resource.settlement === 'unknown')))
3157
+ throw new TypeError('Unknown native ownership remains charged');
3158
+ this.ledger.delete(record);
3159
+ this.pendingUploadBytes -= record.upload;
3160
+ this.pendingReadbackBytes -= record.readback;
3161
+ this.pendingTextureBytes -= record.textureBytes;
3162
+ this.pendingGeometryBytes -= record.geometryBytes;
3163
+ if (record.shared) {
3164
+ this.pendingColorBytes -= record.shared.colorBytes;
3165
+ this.pendingCanonicalBytes -= record.shared.canonicalBytes;
3166
+ this.resourceCpu.canonicalBytes -= record.shared.canonicalBytes;
3167
+ record.shared.draws.length = 0;
3168
+ delete record.shared;
3169
+ }
3170
+ record.resources.length = 0;
3171
+ record.textures.length = 0;
3172
+ record.views.length = 0;
3173
+ record.bindings.length = 0;
3174
+ record.projections.length = 0;
3175
+ record.projectionPlan = undefined;
3176
+ record.bufferLeases.length = 0;
3177
+ record.bindingCandidates.length = 0;
3178
+ this.batchScratch.release(record.batchPlan);
3179
+ record.retired = true;
3180
+ if (record.stage) {
3181
+ record.stage.writes.length = 0;
3182
+ record.stage.recipe = undefined;
3183
+ record.stage.outcomes.length = 0;
3184
+ record.stage.plan = undefined;
3185
+ }
3186
+ delete record.owner;
3187
+ }
3188
+ catch (cause) {
3189
+ failed(cause);
3190
+ throw cause;
3191
+ }
3192
+ finally {
3193
+ record.retiring = false;
3194
+ }
3195
+ }
3196
+ requestReadback() {
3197
+ try {
3198
+ this.active();
3199
+ if (!this.options.enableReadback)
3200
+ throw error('WEBGPU_READBACK_DISABLED');
3201
+ if (this.ticket)
3202
+ throw error('WEBGPU_READBACK_PENDING');
3203
+ this.ticket = { ...deferred(), bound: false };
3204
+ return this.ticket.promise;
3205
+ }
3206
+ catch (cause) {
3207
+ return observed(Promise.reject(cause));
3208
+ }
3209
+ }
3210
+ whenIdle() {
3211
+ if (this.cleanupOutcome === 'unsafe')
3212
+ return observed(Promise.reject(error('WEBGPU_CLOSE_UNSAFE', this.unsafeCause)));
3213
+ const shared = SHARED_OPTIONS.has(this), recovery = SHARED_OPTIONS.get(this)?.recovery;
3214
+ if (shared && (recovery || [...this.ledger].some(record => record.stage))) {
3215
+ const pending = [...this.ledger].map(record => record.completion);
3216
+ const capturedFailure = this.state === 'lost' || this.state === 'failed' ? this.generationFailure : null;
3217
+ if (this.startingPending && this.starting)
3218
+ pending.push(this.starting);
3219
+ const attempt = this.recoveryAttempt;
3220
+ if (attempt)
3221
+ pending.push(attempt.barrier.promise, attempt.actual);
3222
+ return observed(Promise.allSettled(pending).then(results => {
3223
+ const rejected = results.find(result => result.status === 'rejected');
3224
+ if (rejected?.status === 'rejected')
3225
+ throw rejected.reason;
3226
+ if (capturedFailure)
3227
+ throw error(capturedFailure.code, capturedFailure.cause);
3228
+ }));
3229
+ }
3230
+ if (this.firstFailure)
3231
+ return observed(Promise.reject(error(this.firstFailure.code, this.firstFailure.cause)));
3232
+ if (this.state === 'closed')
3233
+ return Promise.resolve();
3234
+ const serial = this.lastSerial, pending = [...this.ledger].map(record => record.completion);
3235
+ if (this.starting)
3236
+ pending.push(this.starting);
3237
+ return observed(Promise.allSettled(pending).then(results => {
3238
+ const failed = results.find(result => result.status === 'rejected');
3239
+ if (failed?.status === 'rejected')
3240
+ throw failed.reason;
3241
+ if (this.firstFailure && (this.firstFailure.serial === null || this.firstFailure.serial <= serial))
3242
+ throw error(this.firstFailure.code, this.firstFailure.cause);
3243
+ }));
3244
+ }
3245
+ close() {
3246
+ if (this.closing)
3247
+ return this.closing;
3248
+ this.invalidateImageResidency();
3249
+ const barrier = deferred();
3250
+ this.closing = barrier.promise;
3251
+ this.state = 'closing';
3252
+ this.cleanupOutcome = 'pending';
3253
+ this.retention.clear();
3254
+ this.revokeRecovery(error('WEBGPU_CLOSED'));
3255
+ this.revokeStages(error('WEBGPU_CLOSED'));
3256
+ this.cancelTicket(error('WEBGPU_CLOSED'));
3257
+ this.cleanup().then(barrier.resolve, barrier.reject);
3258
+ return barrier.promise;
3259
+ }
3260
+ async cleanup() {
3261
+ if (this.starting)
3262
+ await Promise.allSettled([this.starting]);
3263
+ if (this.recoveryAttempt)
3264
+ await Promise.allSettled([this.recoveryAttempt.actual]);
3265
+ if (this.busy)
3266
+ await this.cpu.promise;
3267
+ await Promise.allSettled([...this.ledger].map(record => record.outcome));
3268
+ if (this.fence && !this.unsafe && !this.owner?.invalidated) {
3269
+ try {
3270
+ await observed(this.fence());
3271
+ }
3272
+ catch (cause) {
3273
+ this.proofFailed(cause);
3274
+ }
3275
+ }
3276
+ this.finalizing = true;
3277
+ for (const record of [...this.ledger]) {
3278
+ try {
3279
+ this.retire(record);
3280
+ }
3281
+ catch (cause) {
3282
+ this.fail('WEBGPU_RENDER_FAILED', cause, 'cleanup', record.serial, true);
3283
+ }
3284
+ }
3285
+ this.closeBuffers();
3286
+ this.closeImageResidency();
3287
+ if (this.configured) {
3288
+ this.configured = false;
3289
+ try {
3290
+ this.unconfigure();
3291
+ }
3292
+ catch (cause) {
3293
+ this.proofFailed(cause);
3294
+ }
3295
+ }
3296
+ if (this.removeListener) {
3297
+ const remove = this.removeListener;
3298
+ this.removeListener = undefined;
3299
+ try {
3300
+ remove();
3301
+ }
3302
+ catch (cause) {
3303
+ this.proofFailed(cause);
3304
+ }
3305
+ }
3306
+ // Deliver a loss queued by a cleanup boundary before detaching the leased observer.
3307
+ await Promise.resolve();
3308
+ // The safe return boundary ends the borrowed lease; deliberate owned destruction is ignored.
3309
+ delete this.lossCell.notify;
3310
+ delete this.lossCell.unknown;
3311
+ if (this.destroyDevice) {
3312
+ const destroy = this.destroyDevice;
3313
+ this.destroyDevice = undefined;
3314
+ try {
3315
+ destroy();
3316
+ }
3317
+ catch (cause) {
3318
+ this.proofFailed(cause);
3319
+ }
3320
+ }
3321
+ if (SHARED_OPTIONS.get(this)?.recovery && !this.unsafe) {
3322
+ this.borrowed = undefined;
3323
+ this.clearNativeReferences();
3324
+ }
3325
+ this.cleanupOutcome = this.unsafe ? 'unsafe' : 'safe';
3326
+ this.state = 'closed';
3327
+ if (this.unsafe)
3328
+ throw error('WEBGPU_CLOSE_UNSAFE', this.unsafeCause);
3329
+ }
3330
+ setTimeout(callback, delayMs) {
3331
+ return this.ownedTimeout(callback, delayMs);
3332
+ }
3333
+ ownedTimeout(callback, delayMs) {
3334
+ this.timers ??= { set: globalThis.setTimeout.bind(globalThis), clear: globalThis.clearTimeout.bind(globalThis) };
3335
+ const timer = this.timers.set(callback, delayMs);
3336
+ let cancelled = false;
3337
+ const clear = this.timers.clear;
3338
+ return () => {
3339
+ if (!cancelled) {
3340
+ cancelled = true;
3341
+ clear(timer);
3342
+ }
3343
+ };
3344
+ }
3345
+ }
3346
+ export function createSharedWebGPUHost(options) {
3347
+ return new WebGPUHostImplementation(options);
3348
+ }
3349
+ //# sourceMappingURL=WebGPUHost.js.map