@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,2672 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { deferred } from './sharedHostDeferred.js';
3
+ import { sharedEffectGLSL, EFFECT_PASSES, EFFECT_UNIFORM_BYTES } from './sharedEffectShaders.js';
4
+ import { SHARED_FRAME_PROFILE_2D } from '@egret/contracts';
5
+ import { readOwnedSharedFrame } from '#egret-textured-frame-state';
6
+ import { admitSharedWebGL2Options } from './sharedWebGL2Options.js';
7
+ import { prepareSharedDraws2D, SharedPreparationError } from '../rendering/prepareSharedDraws2D.js';
8
+ import { SharedPreparationRetention2D } from '../rendering/sharedPreparationRetention2D.js';
9
+ import { GeometryPreparationError } from '../rendering/prepareRectangles2D.js';
10
+ import { packSharedDraws2D, packSharedRegions2D, SHARED_BATCH_PAGES_2D, SHARED_REGION_WINDOW_BYTES_2D } from '../rendering/packSharedDraws2D.js';
11
+ import { PreparedBatchScratch2D } from '../rendering/preparedBatches2D.js';
12
+ import { prepareSharedBatches2D } from '../rendering/preparedSharedBatches2D.js';
13
+ import { decodeSharedSRGBByte } from '../rendering/sharedColor2D.js';
14
+ import { runOwnedPreparationScope } from '../rendering/ownedPreparationFailure2D.js';
15
+ import { planSharedStorageFees2D, withSharedReadbackLayout2D, checkSharedCapacity2D, materializeSharedPages2D, SharedStorageError2D } from './sharedSubmissionStorage2D.js';
16
+ import { planSharedWebGL2Arenas, checkSharedWebGL2ArenaCapacity, qualifySharedWebGL2Alignment } from './sharedWebGL2Arena.js';
17
+ import { createRetentionLedger } from './sharedRetentionLedger.js';
18
+ import { GLNativeSession, glFailure, isGLFailure } from './webgl2Native.js';
19
+ import { sharedWebGL2VertexSource, sharedWebGL2FragmentSource, sharedWebGL2PagedFragmentSource, sharedWebGL2SolidVertexSource, sharedWebGL2SolidFragmentSource, sharedWebGL2ResolveVertexSource, sharedWebGL2ResolveFragmentSource, sharedWebGL2BlendFactors } from './sharedWebGL2Shaders.js';
20
+ import { MAX_LAYER_HANDLES, MAX_LAYER_EXTENT, MAX_LAYER_BYTES, createWebGL2LayerProgram, readWebGL2LayerEffect, readWebGL2LayerPlacement } from './webgl2LayerState.js';
21
+ const schedule = globalThis.setTimeout.bind(globalThis), cancel = globalThis.clearTimeout.bind(globalThis);
22
+ const invoke = Reflect.apply;
23
+ const clock = () => performance.now();
24
+ const TIMING_CAPACITY = 2048;
25
+ const TIMING_PHASES = [
26
+ 'texture-prepare',
27
+ 'texture-upload',
28
+ 'working-framebuffer-validation',
29
+ 'default-framebuffer-validation',
30
+ 'submit',
31
+ 'fence-poll',
32
+ 'completion-error-query',
33
+ 'retire',
34
+ 'sync-delete-error-query'
35
+ ];
36
+ function createFrameTiming() {
37
+ const totals = Object.fromEntries(TIMING_PHASES.map(phase => [phase, { count: 0, totalMs: 0, maxMs: 0 }]));
38
+ return { totals, samples: [], next: 0, dropped: 0 };
39
+ }
40
+ const ATTRIBUTES = Object.freeze({
41
+ alpha: true,
42
+ premultipliedAlpha: true,
43
+ antialias: false,
44
+ depth: false,
45
+ stencil: false,
46
+ preserveDrawingBuffer: false
47
+ });
48
+ const whitePixel = (source, pixels) => source.width === 1 &&
49
+ source.height === 1 &&
50
+ pixels.length === 4 &&
51
+ pixels[0] === 255 &&
52
+ pixels[1] === 255 &&
53
+ pixels[2] === 255 &&
54
+ pixels[3] === 255;
55
+ const DRAW_UNIFORM_MEMBERS = [
56
+ 'viewport',
57
+ 'materialLight',
58
+ 'materialDark',
59
+ 'pageUnits0',
60
+ 'pageUnits1',
61
+ 'domain',
62
+ 'samplerPolicy',
63
+ 'pageExecution'
64
+ ];
65
+ class SharedGLHost {
66
+ surface;
67
+ sharedFrameProfile = SHARED_FRAME_PROFILE_2D;
68
+ options;
69
+ callback;
70
+ state = 'new';
71
+ generation = 0;
72
+ attempt = 0;
73
+ serial = 0;
74
+ firstFailure = null;
75
+ generationFailure = null;
76
+ callbackFailureCount = 0;
77
+ lastCallbackFailure = null;
78
+ cleanupOutcome = 'not-started';
79
+ ready;
80
+ starting;
81
+ closing;
82
+ cpu = deferred();
83
+ busy = false;
84
+ phase;
85
+ uploading;
86
+ token = {};
87
+ lossToken;
88
+ native;
89
+ context;
90
+ lostNative;
91
+ // Fixed-size observations only; original records/native owners still authorize every transition.
92
+ frameTiming;
93
+ resourceCpu = {
94
+ canonicalBytes: 0,
95
+ scratchBytes: 0,
96
+ highCanonicalBytes: 0,
97
+ highScratchBytes: 0,
98
+ highTemporaryBytes: 0,
99
+ saturated: false
100
+ };
101
+ resourceUnknown = {
102
+ knownLogicalBytes: 0,
103
+ objects: 0,
104
+ highKnownLogicalBytes: 0,
105
+ highObjects: 0,
106
+ saturated: false
107
+ };
108
+ resourceReuse = {
109
+ current: {
110
+ idleBytes: 0,
111
+ idleEntries: 0,
112
+ leasedBytes: 0,
113
+ leasedEntries: 0,
114
+ reservedBytes: 0,
115
+ reservedEntries: 0,
116
+ detachedBytes: 0,
117
+ detachedEntries: 0,
118
+ unknownBytes: 0,
119
+ unknownEntries: 0
120
+ },
121
+ highWater: {
122
+ idleBytes: 0,
123
+ idleEntries: 0,
124
+ leasedBytes: 0,
125
+ leasedEntries: 0,
126
+ reservedBytes: 0,
127
+ reservedEntries: 0,
128
+ detachedBytes: 0,
129
+ detachedEntries: 0,
130
+ unknownBytes: 0,
131
+ unknownEntries: 0
132
+ },
133
+ saturated: false,
134
+ unknownNative: this.resourceUnknown
135
+ };
136
+ resourceHighPending = {
137
+ frames: 0,
138
+ uploadCreditBytes: 0,
139
+ pageCreditBytes: 0,
140
+ readbackCreditBytes: 0,
141
+ geometryCreditBytes: 0,
142
+ colorCreditBytes: 0
143
+ };
144
+ resourceHighImages = {
145
+ readyBytes: 0,
146
+ readyEntries: 0,
147
+ pinnedReadyBytes: 0,
148
+ pinnedReadyEntries: 0,
149
+ allocatedLogicalBytes: 0,
150
+ reservedCreditBytes: 0
151
+ };
152
+ resourceTotals = { pageWriteCalls: 0, pageWriteBytes: 0, readyCapacityEvictions: 0 };
153
+ resourceSaturated = false;
154
+ resourceReadyBytes = 0;
155
+ resourcePinnedBytes = 0;
156
+ resourcePinnedEntries = 0;
157
+ resourceNative = {
158
+ pageBytes: 0,
159
+ highPageBytes: 0,
160
+ reservedPageBytes: 0,
161
+ highReservedPageBytes: 0,
162
+ unknown: this.resourceUnknown,
163
+ totals: this.resourceTotals,
164
+ saturated: false
165
+ };
166
+ pool = createRetentionLedger(this.token, this.resourceReuse);
167
+ scratch = new PreparedBatchScratch2D();
168
+ /** The prepared draws of the last ordinary frame. A Host that is not active keeps none. */
169
+ retention = new SharedPreparationRetention2D();
170
+ records = new Set();
171
+ settledHandles = new WeakSet();
172
+ pages = new Map();
173
+ layers = new Map();
174
+ layerGarbage = new Set();
175
+ layerBytes = 0;
176
+ layerProgram;
177
+ layerEffectProgram;
178
+ ticket;
179
+ limits;
180
+ framebuffer;
181
+ program;
182
+ solidProgram;
183
+ pagedProgram;
184
+ effectPrograms = new Map();
185
+ resolveProgram;
186
+ drawVAO;
187
+ resolveVAO;
188
+ pump;
189
+ restoreTimer;
190
+ restoreDeadline = 0;
191
+ restoreAttempt = false;
192
+ removeListeners;
193
+ unsafe = false;
194
+ retiredUnknownBytes = 0;
195
+ retiredUnknownObjects = 0;
196
+ constructor(input) {
197
+ try {
198
+ const admitted = admitSharedWebGL2Options(input);
199
+ this.surface = admitted.surface;
200
+ this.options = admitted.configuration;
201
+ this.callback = admitted.callback;
202
+ this.frameTiming = admitted.measureSharedFrames ? createFrameTiming() : undefined;
203
+ }
204
+ catch (cause) {
205
+ throw glFailure('WEBGL2_OPTIONS_INVALID', cause);
206
+ }
207
+ Object.defineProperty(this, 'surface', { writable: false, configurable: false });
208
+ Object.defineProperty(this, 'sharedFrameProfile', { writable: false, configurable: false });
209
+ this.cpu.resolve();
210
+ }
211
+ recordTiming(phase, startMs, generation, serial) {
212
+ const timing = this.frameTiming, durationMs = clock() - startMs, total = timing.totals[phase];
213
+ if (!Number.isFinite(durationMs) || durationMs < 0)
214
+ return;
215
+ if (total.count < Number.MAX_SAFE_INTEGER) {
216
+ total.count++;
217
+ total.totalMs += durationMs;
218
+ total.maxMs = Math.max(total.maxMs, durationMs);
219
+ }
220
+ if (timing.samples.length === TIMING_CAPACITY)
221
+ timing.dropped = Math.min(timing.dropped + 1, Number.MAX_SAFE_INTEGER);
222
+ timing.samples[timing.next] = { phase, startMs, durationMs, generation, serial };
223
+ timing.next = (timing.next + 1) % TIMING_CAPACITY;
224
+ }
225
+ getSharedFrameTiming() {
226
+ const timing = this.frameTiming;
227
+ if (!timing)
228
+ return null;
229
+ const first = timing.samples.length === TIMING_CAPACITY ? timing.next : 0;
230
+ const recent = Array.from({ length: timing.samples.length }, (_, index) => Object.freeze({ ...timing.samples[(first + index) % TIMING_CAPACITY] }));
231
+ const totals = Object.fromEntries(TIMING_PHASES.map(phase => [phase, Object.freeze({ ...timing.totals[phase] })]));
232
+ return Object.freeze({ totals: Object.freeze(totals), recent: Object.freeze(recent), dropped: timing.dropped });
233
+ }
234
+ reservePageDiagnostics(record) {
235
+ this.resourceNative.reservedPageBytes += record.reservedPageBytes;
236
+ this.resourceNative.highReservedPageBytes = Math.max(this.resourceNative.highReservedPageBytes, this.resourceNative.reservedPageBytes);
237
+ this.sampleResourcePending();
238
+ this.sampleResourceImages();
239
+ }
240
+ pinPageDiagnostics(page) {
241
+ if (page.pins === 0 && this.pages.get(page.source) === page) {
242
+ this.resourcePinnedBytes += page.source.byteLength;
243
+ this.resourcePinnedEntries++;
244
+ this.sampleResourceImages();
245
+ }
246
+ }
247
+ sampleResourcePending() {
248
+ const owner = this.snapshot();
249
+ this.resourceHighPending.frames = Math.max(this.resourceHighPending.frames, owner.pendingFrames);
250
+ this.resourceHighPending.uploadCreditBytes = Math.max(this.resourceHighPending.uploadCreditBytes, owner.pendingUploadBytes);
251
+ this.resourceHighPending.pageCreditBytes = Math.max(this.resourceHighPending.pageCreditBytes, owner.pendingTextureBytes);
252
+ this.resourceHighPending.readbackCreditBytes = Math.max(this.resourceHighPending.readbackCreditBytes, owner.pendingReadbackBytes);
253
+ this.resourceHighPending.geometryCreditBytes = Math.max(this.resourceHighPending.geometryCreditBytes, owner.pendingGeometryBytes);
254
+ this.resourceHighPending.colorCreditBytes = Math.max(this.resourceHighPending.colorCreditBytes, owner.pendingColorBytes);
255
+ }
256
+ sampleResourceImages() {
257
+ this.resourceHighImages.readyBytes = Math.max(this.resourceHighImages.readyBytes, this.resourceReadyBytes);
258
+ this.resourceHighImages.readyEntries = Math.max(this.resourceHighImages.readyEntries, this.pages.size);
259
+ this.resourceHighImages.pinnedReadyBytes = Math.max(this.resourceHighImages.pinnedReadyBytes, this.resourcePinnedBytes);
260
+ this.resourceHighImages.pinnedReadyEntries = Math.max(this.resourceHighImages.pinnedReadyEntries, this.resourcePinnedEntries);
261
+ this.resourceHighImages.allocatedLogicalBytes = Math.max(this.resourceHighImages.allocatedLogicalBytes, this.resourceNative.pageBytes);
262
+ this.resourceHighImages.reservedCreditBytes = Math.max(this.resourceHighImages.reservedCreditBytes, this.resourceNative.reservedPageBytes);
263
+ }
264
+ resourceTotal(key, amount) {
265
+ const old = this.resourceTotals[key];
266
+ if (amount > Number.MAX_SAFE_INTEGER - old) {
267
+ this.resourceTotals[key] = Number.MAX_SAFE_INTEGER;
268
+ this.resourceSaturated = true;
269
+ }
270
+ else
271
+ this.resourceTotals[key] = old + amount;
272
+ }
273
+ /** Read-only logical observations; no native call, callback or state transition. */
274
+ resourceStatus() {
275
+ const owner = this.snapshot();
276
+ return Object.freeze({
277
+ current: Object.freeze({
278
+ pending: Object.freeze({
279
+ frames: owner.pendingFrames,
280
+ uploadCreditBytes: owner.pendingUploadBytes,
281
+ pageCreditBytes: owner.pendingTextureBytes,
282
+ readbackCreditBytes: owner.pendingReadbackBytes,
283
+ geometryCreditBytes: owner.pendingGeometryBytes,
284
+ colorCreditBytes: owner.pendingColorBytes
285
+ }),
286
+ cpu: Object.freeze({
287
+ canonicalBytes: this.resourceCpu.canonicalBytes,
288
+ scratchBytes: this.resourceCpu.scratchBytes,
289
+ temporaryBytes: this.resourceCpu.canonicalBytes + this.resourceCpu.scratchBytes
290
+ }),
291
+ images: Object.freeze({
292
+ readyBytes: this.resourceReadyBytes,
293
+ readyEntries: this.pages.size,
294
+ pinnedReadyBytes: this.resourcePinnedBytes,
295
+ pinnedReadyEntries: this.resourcePinnedEntries,
296
+ allocatedLogicalBytes: this.resourceNative.pageBytes,
297
+ reservedCreditBytes: this.resourceNative.reservedPageBytes
298
+ }),
299
+ reusable: Object.freeze({ ...this.resourceReuse.current }),
300
+ unknownNative: Object.freeze({
301
+ knownLogicalBytes: this.resourceUnknown.knownLogicalBytes,
302
+ objects: this.resourceUnknown.objects
303
+ })
304
+ }),
305
+ highWater: Object.freeze({
306
+ pending: Object.freeze({ ...this.resourceHighPending }),
307
+ cpu: Object.freeze({
308
+ canonicalBytes: this.resourceCpu.highCanonicalBytes,
309
+ scratchBytes: this.resourceCpu.highScratchBytes,
310
+ temporaryBytes: this.resourceCpu.highTemporaryBytes
311
+ }),
312
+ images: Object.freeze({
313
+ ...this.resourceHighImages,
314
+ allocatedLogicalBytes: this.resourceNative.highPageBytes,
315
+ reservedCreditBytes: this.resourceNative.highReservedPageBytes
316
+ }),
317
+ reusable: Object.freeze({ ...this.resourceReuse.highWater }),
318
+ unknownNative: Object.freeze({
319
+ knownLogicalBytes: this.resourceUnknown.highKnownLogicalBytes,
320
+ objects: this.resourceUnknown.highObjects
321
+ })
322
+ }),
323
+ totals: Object.freeze({ ...this.resourceTotals }),
324
+ saturated: this.resourceSaturated ||
325
+ this.resourceCpu.saturated ||
326
+ this.resourceReuse.saturated ||
327
+ this.resourceUnknown.saturated ||
328
+ this.resourceNative.saturated
329
+ });
330
+ }
331
+ stateError() {
332
+ const code = this.state === 'lost'
333
+ ? 'WEBGL2_CONTEXT_LOST'
334
+ : this.state === 'restoring'
335
+ ? 'WEBGL2_CONTEXT_RESTORING'
336
+ : this.state === 'stopped'
337
+ ? 'WEBGL2_STOPPED'
338
+ : this.state === 'closing' || this.state === 'closed'
339
+ ? 'WEBGL2_CLOSED'
340
+ : this.state === 'failed'
341
+ ? 'WEBGL2_FAILED'
342
+ : 'WEBGL2_NOT_STARTED';
343
+ return glFailure(code, this.generationFailure?.cause);
344
+ }
345
+ active() {
346
+ if (this.state !== 'active') {
347
+ this.retention.clear();
348
+ throw this.stateError();
349
+ }
350
+ }
351
+ generationState(token) {
352
+ if (token !== this.token || this.state === 'lost' || this.state === 'closed')
353
+ throw this.stateError();
354
+ if ((this.phase === 'render' || this.phase === 'upload') && this.state !== 'active')
355
+ throw this.stateError();
356
+ if (this.phase === 'upload' && this.uploading?.upload?.control.revoked)
357
+ throw this.uploading.upload.control.failure ?? glFailure('WEBGL2_UPLOAD_ABORTED');
358
+ if (this.phase === 'initialize' && this.state !== 'starting' && this.state !== 'restoring')
359
+ throw this.stateError();
360
+ }
361
+ generationGate(token) {
362
+ this.generationState(token);
363
+ if (this.lostNative?.()) {
364
+ this.onLoss();
365
+ throw glFailure('WEBGL2_CONTEXT_LOST');
366
+ }
367
+ // The captured native loss observation may itself reenter the Host.
368
+ this.generationState(token);
369
+ if (this.state === 'restoring' && clock() >= this.restoreDeadline)
370
+ throw glFailure('WEBGL2_RESTORE_TIMEOUT');
371
+ }
372
+ note(code, cause, phase, serial = null) {
373
+ const failure = Object.freeze({ code, cause, phase, serial, generation: this.generation });
374
+ this.firstFailure ??= failure;
375
+ this.generationFailure ??= failure;
376
+ const callback = this.callback;
377
+ if (callback)
378
+ queueMicrotask(() => {
379
+ if (this.state === 'closed')
380
+ return;
381
+ const failed = (fault) => {
382
+ this.callbackFailureCount = Math.min(Number.MAX_SAFE_INTEGER, this.callbackFailureCount + 1);
383
+ this.lastCallbackFailure = Object.freeze({
384
+ code: 'WEBGL2_DIAGNOSTIC_CALLBACK_FAILED',
385
+ cause: fault,
386
+ phase: 'callback',
387
+ serial,
388
+ generation: failure.generation
389
+ });
390
+ };
391
+ try {
392
+ Promise.resolve(callback.call(undefined, Object.freeze({ ...failure, severity: 'error' }))).catch(failed);
393
+ }
394
+ catch (fault) {
395
+ failed(fault);
396
+ }
397
+ });
398
+ return glFailure(code, cause);
399
+ }
400
+ rejectUnbound(cause) {
401
+ if (this.ticket && !this.ticket.bound) {
402
+ this.ticket.reject(cause);
403
+ this.ticket = undefined;
404
+ }
405
+ }
406
+ start() {
407
+ if (this.state === 'starting' || this.state === 'active')
408
+ return this.starting;
409
+ if (this.state !== 'new') {
410
+ const result = deferred();
411
+ result.reject(this.stateError());
412
+ return result.promise;
413
+ }
414
+ this.state = 'starting';
415
+ this.ready = deferred();
416
+ this.starting = this.ready.promise;
417
+ // Store the public barrier before any externally controlled canvas method.
418
+ queueMicrotask(() => {
419
+ void this.initialize(false);
420
+ });
421
+ return this.starting;
422
+ }
423
+ whenReady() {
424
+ if (this.state === 'starting' || this.state === 'active' || this.state === 'lost' || this.state === 'restoring')
425
+ return this.ready.promise;
426
+ const result = deferred();
427
+ result.reject(this.stateError());
428
+ return result.promise;
429
+ }
430
+ whenIdle() {
431
+ const result = deferred();
432
+ const refused = this.state !== 'active' && this.state !== 'stopped' ? this.stateError() : undefined;
433
+ Promise.allSettled([...this.records].map(record => record.done.promise)).then(outcomes => {
434
+ const first = outcomes.find(row => row.status === 'rejected');
435
+ if (first?.status === 'rejected')
436
+ result.reject(first.reason);
437
+ else if (refused)
438
+ result.reject(refused);
439
+ else
440
+ result.resolve();
441
+ });
442
+ return result.promise;
443
+ }
444
+ requestReadback() {
445
+ const result = deferred();
446
+ if (this.state !== 'active')
447
+ result.reject(this.stateError());
448
+ else if (!this.options.enableReadback)
449
+ result.reject(glFailure('WEBGL2_READBACK_DISABLED'));
450
+ else if (this.ticket)
451
+ result.reject(glFailure('WEBGL2_READBACK_PENDING'));
452
+ else
453
+ this.ticket = { ...result, bound: false };
454
+ return result.promise;
455
+ }
456
+ stop() {
457
+ if (this.state === 'closed' || this.state === 'closing' || this.state === 'failed' || this.state === 'stopped')
458
+ return;
459
+ this.state = 'stopped';
460
+ const failure = glFailure('WEBGL2_STOPPED');
461
+ this.ready?.reject(failure);
462
+ this.cancelRestore();
463
+ this.rejectUnbound(failure);
464
+ this.revokeUploads(failure);
465
+ }
466
+ setTimeout(callback, delayMs) {
467
+ const id = schedule(callback, delayMs);
468
+ return () => cancel(id);
469
+ }
470
+ cancelRestore() {
471
+ if (this.restoreTimer !== undefined) {
472
+ cancel(this.restoreTimer);
473
+ this.restoreTimer = undefined;
474
+ }
475
+ }
476
+ bindListeners() {
477
+ const lost = (event) => {
478
+ if (!this.lostNative?.())
479
+ return;
480
+ event.preventDefault();
481
+ this.onLoss();
482
+ };
483
+ const restored = () => {
484
+ if (this.state !== 'lost' || this.restoreAttempt || this.lostNative?.())
485
+ return;
486
+ this.restoreAttempt = true;
487
+ this.state = 'restoring';
488
+ void this.cpu.promise.then(() => this.initialize(true));
489
+ };
490
+ const add = this.surface.addEventListener.bind(this.surface), remove = this.surface.removeEventListener.bind(this.surface);
491
+ let a = false, b = false;
492
+ this.removeListeners = () => {
493
+ let failure;
494
+ // Listener cleanup is independent: one failing removal cannot skip the other.
495
+ if (a) {
496
+ a = false;
497
+ try {
498
+ remove('webglcontextlost', lost);
499
+ }
500
+ catch (cause) {
501
+ failure = { cause };
502
+ }
503
+ }
504
+ if (b) {
505
+ b = false;
506
+ try {
507
+ remove('webglcontextrestored', restored);
508
+ }
509
+ catch (cause) {
510
+ failure ??= { cause };
511
+ }
512
+ }
513
+ if (failure)
514
+ throw failure.cause;
515
+ };
516
+ a = true;
517
+ add('webglcontextlost', lost);
518
+ b = true;
519
+ add('webglcontextrestored', restored);
520
+ }
521
+ onLoss() {
522
+ if (this.state === 'closed' || this.state === 'lost' || this.lossToken === this.token)
523
+ return;
524
+ const wasClosing = this.state === 'closing', wasStopped = this.state === 'stopped';
525
+ const canRestore = this.state === 'active' || this.state === 'restoring';
526
+ this.lossToken = this.token;
527
+ const cause = this.note('WEBGL2_CONTEXT_LOST', undefined, 'context');
528
+ this.native?.lose();
529
+ for (const slot of this.layers.values())
530
+ this.dropLayer(slot);
531
+ this.pool.invalidate();
532
+ this.pages.clear();
533
+ this.resourceReadyBytes = 0;
534
+ this.resourcePinnedBytes = 0;
535
+ this.resourcePinnedEntries = 0;
536
+ this.sampleResourceImages();
537
+ this.rejectUnbound(cause);
538
+ for (const handle of this.pool.detachIdleForClose())
539
+ if (!this.settledHandles.has(handle)) {
540
+ this.pool.settled(handle, 'context-invalidated');
541
+ this.settledHandles.add(handle);
542
+ }
543
+ for (const record of this.records)
544
+ record.failure ??= cause;
545
+ if (canRestore && !this.unsafe) {
546
+ this.ready?.reject(cause);
547
+ this.cancelRestore();
548
+ this.state = 'lost';
549
+ this.ready = deferred();
550
+ this.restoreAttempt = false;
551
+ this.restoreDeadline = clock() + this.options.restoreTimeoutMs;
552
+ this.restoreTimer = schedule(() => {
553
+ this.restoreTimer = undefined;
554
+ if (this.state !== 'lost' && this.state !== 'restoring')
555
+ return;
556
+ const failure = this.note('WEBGL2_RESTORE_TIMEOUT', undefined, 'restore');
557
+ this.state = 'failed';
558
+ this.ready.reject(failure);
559
+ }, this.options.restoreTimeoutMs);
560
+ }
561
+ else {
562
+ this.state = wasClosing ? 'closing' : wasStopped ? 'stopped' : 'failed';
563
+ this.ready?.reject(cause);
564
+ this.cancelRestore();
565
+ }
566
+ this.revokeUploads(cause);
567
+ if (!this.busy) {
568
+ this.retireLost();
569
+ this.sweepLayers();
570
+ }
571
+ }
572
+ retireLost() {
573
+ for (const record of [...this.records])
574
+ if (record.native.invalidated)
575
+ this.retire(record);
576
+ }
577
+ async initialize(restoring) {
578
+ const barrier = this.ready;
579
+ this.busy = true;
580
+ this.cpu = deferred();
581
+ this.phase = 'initialize';
582
+ try {
583
+ if ((restoring && this.state !== 'restoring') || (!restoring && this.state !== 'starting'))
584
+ throw this.stateError();
585
+ if (restoring && (clock() >= this.restoreDeadline || this.records.size || this.unsafe))
586
+ throw glFailure('WEBGL2_RESTORE_TIMEOUT');
587
+ if (this.generation >= Number.MAX_SAFE_INTEGER || (restoring && this.attempt >= Number.MAX_SAFE_INTEGER))
588
+ throw glFailure('WEBGL2_GENERATION_EXHAUSTED');
589
+ if (restoring)
590
+ this.attempt++;
591
+ // Fixed native handles never cross a context generation, including partial startup.
592
+ this.framebuffer = undefined;
593
+ this.program = undefined;
594
+ this.solidProgram = undefined;
595
+ this.pagedProgram = undefined;
596
+ this.resolveProgram = undefined;
597
+ this.layerProgram = undefined;
598
+ this.layerEffectProgram = undefined;
599
+ this.effectPrograms.clear();
600
+ this.drawVAO = undefined;
601
+ this.resolveVAO = undefined;
602
+ this.limits = undefined;
603
+ this.native = undefined;
604
+ this.generation++;
605
+ this.token = {};
606
+ const token = this.token;
607
+ this.pool = createRetentionLedger(token, this.resourceReuse);
608
+ const context = this.surface.getContext('webgl2', ATTRIBUTES);
609
+ if (!context)
610
+ throw glFailure('WEBGL2_CONTEXT_UNAVAILABLE');
611
+ this.context = context;
612
+ this.lostNative = context.isContextLost.bind(context);
613
+ this.generationGate(token);
614
+ if (!restoring)
615
+ this.bindListeners();
616
+ const generation = this.generation;
617
+ const native = new GLNativeSession(context, () => this.generationGate(token), this.resourceNative, this.frameTiming ? (phase, started, serial) => this.recordTiming(phase, started, generation, serial) : undefined);
618
+ this.native = native;
619
+ const gl = native.gl, attrs = gl.getContextAttributes();
620
+ if (context.canvas !== this.surface ||
621
+ !attrs ||
622
+ Object.entries(ATTRIBUTES).some(([key, value]) => attrs[key] !== value))
623
+ throw glFailure('WEBGL2_CONTEXT_ATTRIBUTES_UNSUPPORTED');
624
+ // Explicitly request the one supported drawing-buffer color space when exposed.
625
+ if ('drawingBufferColorSpace' in context) {
626
+ context.drawingBufferColorSpace = 'srgb';
627
+ this.generationGate(token);
628
+ if (context.drawingBufferColorSpace !== 'srgb')
629
+ throw glFailure('WEBGL2_FORMAT_UNSUPPORTED');
630
+ }
631
+ const integer = (name, min) => {
632
+ const value = gl.getParameter(name);
633
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min)
634
+ throw glFailure('WEBGL2_CONTEXT_LIMIT');
635
+ return value;
636
+ };
637
+ const alignment = integer(gl.UNIFORM_BUFFER_OFFSET_ALIGNMENT, 4);
638
+ try {
639
+ qualifySharedWebGL2Alignment(alignment);
640
+ }
641
+ catch (cause) {
642
+ throw glFailure('WEBGL2_CONTEXT_LIMIT', cause);
643
+ }
644
+ // The vertex stage of a sampled draw reads a second block: one window of the region table.
645
+ integer(gl.MAX_UNIFORM_BLOCK_SIZE, SHARED_REGION_WINDOW_BYTES_2D);
646
+ integer(gl.MAX_UNIFORM_BUFFER_BINDINGS, 2);
647
+ integer(gl.MAX_VERTEX_UNIFORM_BLOCKS, 2);
648
+ integer(gl.MAX_FRAGMENT_UNIFORM_BLOCKS, 1);
649
+ integer(gl.MAX_TEXTURE_IMAGE_UNITS, SHARED_BATCH_PAGES_2D);
650
+ integer(gl.MAX_VERTEX_ATTRIBS, 5);
651
+ const dims = gl.getParameter(gl.MAX_VIEWPORT_DIMS);
652
+ if (!dims ||
653
+ dims.length !== 2 ||
654
+ ![dims[0], dims[1]].every(n => n !== undefined && Number.isSafeInteger(n) && n > 0))
655
+ throw glFailure('WEBGL2_CONTEXT_LIMIT');
656
+ this.limits = {
657
+ alignment,
658
+ texture: integer(gl.MAX_TEXTURE_SIZE, 1),
659
+ renderbuffer: integer(gl.MAX_RENDERBUFFER_SIZE, 1),
660
+ viewportWidth: dims[0],
661
+ viewportHeight: dims[1]
662
+ };
663
+ for (const type of [gl.VERTEX_SHADER, gl.FRAGMENT_SHADER]) {
664
+ const p = gl.getShaderPrecisionFormat(type, gl.HIGH_FLOAT);
665
+ if (!p || p.precision < 23 || p.rangeMin < 126 || p.rangeMax < 127)
666
+ throw glFailure('WEBGL2_CONTEXT_LIMIT');
667
+ }
668
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
669
+ native.attachment(false);
670
+ this.framebuffer = native.create('Framebuffer').value;
671
+ const target = native.create('Texture', 4);
672
+ native.reset(1, 1);
673
+ native.texture(target, 1, 1, true);
674
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
675
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, target.value, 0);
676
+ native.attachment(true);
677
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, null, 0);
678
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
679
+ if (!native.cleanup(target))
680
+ throw glFailure('WEBGL2_CLOSE_UNSAFE', native.cleanupFailure?.cause);
681
+ this.program = native.program(sharedWebGL2VertexSource, sharedWebGL2FragmentSource);
682
+ native.block(this.program, 'DrawUniform', DRAW_UNIFORM_MEMBERS, 128);
683
+ native.block(this.program, 'RegionWindow', ['regions'], SHARED_REGION_WINDOW_BYTES_2D, 1);
684
+ this.solidProgram = native.program(sharedWebGL2SolidVertexSource, sharedWebGL2SolidFragmentSource);
685
+ native.block(this.solidProgram, 'DrawUniform', DRAW_UNIFORM_MEMBERS, 128);
686
+ this.resolveProgram = native.program(sharedWebGL2ResolveVertexSource, sharedWebGL2ResolveFragmentSource);
687
+ if (this.options.enableEffects)
688
+ for (const mode of EFFECT_PASSES) {
689
+ const program = native.program(sharedWebGL2ResolveVertexSource, sharedEffectGLSL(mode));
690
+ const index = gl.getUniformBlockIndex(program, 'Effect');
691
+ if (index === gl.INVALID_INDEX)
692
+ throw glFailure('WEBGL2_CONTEXT_LIMIT');
693
+ gl.uniformBlockBinding(program, index, 0);
694
+ this.effectPrograms.set(mode, program);
695
+ }
696
+ // The program of a batch of several pages. Its eight page samplers name the eight units once, here.
697
+ this.pagedProgram = native.program(sharedWebGL2VertexSource, sharedWebGL2PagedFragmentSource);
698
+ native.block(this.pagedProgram, 'DrawUniform', DRAW_UNIFORM_MEMBERS, 128);
699
+ native.block(this.pagedProgram, 'RegionWindow', ['regions'], SHARED_REGION_WINDOW_BYTES_2D, 1);
700
+ gl.useProgram(this.pagedProgram);
701
+ for (let unit = 0; unit < SHARED_BATCH_PAGES_2D; unit++)
702
+ gl.uniform1i(gl.getUniformLocation(this.pagedProgram, 'page' + unit), unit);
703
+ gl.useProgram(null);
704
+ this.drawVAO = native.create('VertexArray').value;
705
+ this.resolveVAO = native.create('VertexArray').value;
706
+ native.check();
707
+ this.generationGate(token);
708
+ this.state = 'active';
709
+ this.generationFailure = null;
710
+ this.cancelRestore();
711
+ barrier.resolve();
712
+ }
713
+ catch (cause) {
714
+ // A distinct attempted generation may already own a new recovery barrier.
715
+ // This cancelled attempt can settle only the barrier captured on entry.
716
+ if (this.state === 'lost' && this.ready !== barrier) {
717
+ barrier.reject(glFailure('WEBGL2_CONTEXT_LOST', cause));
718
+ return;
719
+ }
720
+ const code = isGLFailure(cause)
721
+ ? cause.code
722
+ : restoring
723
+ ? 'WEBGL2_RESTORE_FAILED'
724
+ : 'WEBGL2_START_FAILED';
725
+ const failure = this.note(code, isGLFailure(cause) ? cause.cause : cause, restoring ? 'restore' : 'startup');
726
+ if (this.state !== 'closing' && this.state !== 'closed' && this.state !== 'stopped')
727
+ this.state = 'failed';
728
+ this.cancelRestore();
729
+ barrier.reject(failure);
730
+ }
731
+ finally {
732
+ this.phase = undefined;
733
+ this.busy = false;
734
+ this.retireLost();
735
+ this.cpu.resolve();
736
+ }
737
+ }
738
+ snapshot() {
739
+ const owner = {
740
+ pendingFrames: this.records.size,
741
+ pendingUploadBytes: 0,
742
+ pendingReadbackBytes: 0,
743
+ pendingTextureBytes: 0,
744
+ pendingGeometryBytes: 0,
745
+ pendingColorBytes: 0,
746
+ pendingCanonicalBytes: 0,
747
+ serial: this.serial
748
+ };
749
+ // At most two accepted records; counters derive from their still-owned immutable fees.
750
+ const mutable = owner;
751
+ for (const r of this.records) {
752
+ mutable.pendingUploadBytes += r.storage.upload;
753
+ mutable.pendingReadbackBytes += r.storage.staging + r.storage.output;
754
+ mutable.pendingTextureBytes += r.storage.prepared.pageBytes;
755
+ mutable.pendingGeometryBytes += r.storage.prepared.geometryBytes;
756
+ mutable.pendingColorBytes += r.storage.colorBytes + r.storage.effectBytes;
757
+ mutable.pendingCanonicalBytes += r.canonicalBytes;
758
+ }
759
+ return owner;
760
+ }
761
+ arenaOwner() {
762
+ let pendingVertexArenaBytes = 0, pendingUniformArenaBytes = 0;
763
+ for (const r of this.records) {
764
+ pendingVertexArenaBytes += r.vertexArenaBytes;
765
+ pendingUniformArenaBytes += r.uniformArenaBytes;
766
+ }
767
+ return { pendingVertexArenaBytes, pendingUniformArenaBytes };
768
+ }
769
+ createSharedLayer2D() {
770
+ this.active();
771
+ if (this.busy)
772
+ throw glFailure('WEBGL2_REENTRANT');
773
+ if (this.layers.size >= MAX_LAYER_HANDLES)
774
+ throw glFailure('WEBGL2_LAYER_BUDGET');
775
+ const slot = { ready: undefined, pending: undefined, wasReady: false, disposed: false };
776
+ const host = this;
777
+ const handle = Object.freeze({
778
+ get state() {
779
+ if (slot.disposed || host.state === 'closing' || host.state === 'closed')
780
+ return 'disposed';
781
+ if (host.state === 'active' && slot.ready?.owner.outcome === 'owned')
782
+ return 'ready';
783
+ return slot.wasReady ? 'stale' : 'empty';
784
+ },
785
+ update: (frame) => this.updateLayer(slot, frame),
786
+ dispose: () => this.disposeLayer(handle, slot)
787
+ });
788
+ this.layers.set(handle, slot);
789
+ return handle;
790
+ }
791
+ getSharedLayerStatus() {
792
+ let readyLayers = 0, pendingLayers = 0;
793
+ for (const slot of this.layers.values()) {
794
+ if (slot.ready?.owner.outcome === 'owned')
795
+ readyLayers++;
796
+ if (slot.pending)
797
+ pendingLayers++;
798
+ }
799
+ return Object.freeze({ readyLayers, pendingLayers, residentBytes: this.layerBytes });
800
+ }
801
+ renderSharedFrameWithLayers(frame, layers) {
802
+ return this.renderOwned(frame, undefined, { placements: layers });
803
+ }
804
+ updateLayer(slot, frame) {
805
+ const done = deferred();
806
+ const write = { slot, done, submitted: false, revision: undefined };
807
+ try {
808
+ if (slot.disposed)
809
+ throw glFailure('WEBGL2_LAYER_DISPOSED');
810
+ this.active();
811
+ if (this.busy)
812
+ throw glFailure('WEBGL2_REENTRANT');
813
+ if (slot.pending)
814
+ throw glFailure('WEBGL2_LAYER_PENDING');
815
+ slot.pending = write;
816
+ this.renderOwned(frame, undefined, { write });
817
+ }
818
+ catch (cause) {
819
+ if (!write.submitted && slot.pending === write)
820
+ slot.pending = undefined;
821
+ done.reject(cause);
822
+ }
823
+ return done.promise;
824
+ }
825
+ disposeLayer(handle, slot) {
826
+ if (slot.disposed)
827
+ return;
828
+ slot.disposed = true;
829
+ this.layers.delete(handle);
830
+ slot.pending?.done.reject(glFailure('WEBGL2_LAYER_DISPOSED'));
831
+ this.dropLayer(slot);
832
+ if (!this.busy) {
833
+ this.busy = true;
834
+ this.cpu = deferred();
835
+ this.phase = 'poll';
836
+ try {
837
+ this.sweepLayers();
838
+ }
839
+ finally {
840
+ this.phase = undefined;
841
+ this.busy = false;
842
+ this.retireLost();
843
+ this.cpu.resolve();
844
+ }
845
+ }
846
+ }
847
+ dropLayer(slot) {
848
+ const revision = slot.ready;
849
+ slot.ready = undefined;
850
+ if (revision) {
851
+ revision.retained = false;
852
+ if (revision.pins === 0)
853
+ this.layerGarbage.add(revision);
854
+ }
855
+ }
856
+ sweepLayers() {
857
+ for (const revision of this.layerGarbage) {
858
+ this.layerGarbage.delete(revision);
859
+ this.layerBytes -= revision.owner.bytes;
860
+ const native = revision.native;
861
+ if (!native.cleanup(revision.owner)) {
862
+ this.unsafe = true;
863
+ const failure = this.note('WEBGL2_CLOSE_UNSAFE', native.cleanupFailure?.cause, 'cleanup');
864
+ if (this.state === 'active') {
865
+ this.state = 'failed';
866
+ this.revokeUploads(failure);
867
+ }
868
+ }
869
+ if (native.invalidated && native === this.native)
870
+ this.onLoss();
871
+ }
872
+ }
873
+ readLayers(input, frameWidth, frameHeight) {
874
+ if (!Array.isArray(input))
875
+ throw glFailure('WEBGL2_LAYER_INVALID');
876
+ const count = input.length;
877
+ if (count > MAX_LAYER_HANDLES)
878
+ throw glFailure('WEBGL2_LAYER_BUDGET');
879
+ if (!Number.isSafeInteger(count) || count < 0)
880
+ throw glFailure('WEBGL2_LAYER_INVALID');
881
+ const reads = [];
882
+ const ratio = this.options.pixelRatio;
883
+ for (let index = 0; index < count; index++) {
884
+ const item = input[index];
885
+ if (!item || typeof item !== 'object')
886
+ throw glFailure('WEBGL2_LAYER_INVALID');
887
+ const { layer, x, y, width, height, effect } = item;
888
+ const light = effect === undefined ? undefined : readWebGL2LayerEffect(this.options, effect, frameWidth, frameHeight);
889
+ this.active();
890
+ const slot = this.layers.get(layer);
891
+ if (!slot)
892
+ throw glFailure('WEBGL2_LAYER_INVALID');
893
+ const revision = slot.ready;
894
+ if (!revision || revision.native !== this.native || revision.owner.outcome !== 'owned')
895
+ throw glFailure('WEBGL2_LAYER_NOT_READY');
896
+ reads.push(readWebGL2LayerPlacement(revision, x, y, width, height, ratio, light));
897
+ }
898
+ // A later placement getter may have disposed an earlier revision.
899
+ if (reads.some(read => !read.revision.retained))
900
+ throw glFailure('WEBGL2_LAYER_NOT_READY');
901
+ return reads;
902
+ }
903
+ finishLayerRecord(record) {
904
+ for (const read of record.layerReads ?? [])
905
+ this.unpinLayer(read.revision);
906
+ const write = record.layerWrite;
907
+ if (!write) {
908
+ this.sweepLayers();
909
+ return;
910
+ }
911
+ const { slot, revision } = write;
912
+ let failure = record.failure;
913
+ if (!failure && slot.disposed)
914
+ failure = glFailure('WEBGL2_LAYER_DISPOSED');
915
+ if (!failure && (this.state !== 'active' || record.native.invalidated))
916
+ failure = this.stateError();
917
+ if (!failure && this.unsafe)
918
+ failure = glFailure('WEBGL2_CLOSE_UNSAFE', record.native.cleanupFailure?.cause);
919
+ if (!failure && revision?.owner.outcome !== 'owned')
920
+ failure = glFailure('WEBGL2_RENDER_FAILED');
921
+ if (!failure && revision) {
922
+ // Publish after the completion proof. Readers of the old revision keep their own pins.
923
+ this.dropLayer(slot);
924
+ revision.retained = true;
925
+ slot.ready = revision;
926
+ slot.wasReady = true;
927
+ }
928
+ if (revision)
929
+ this.unpinLayer(revision);
930
+ this.sweepLayers();
931
+ if (!failure && this.unsafe)
932
+ failure = glFailure('WEBGL2_CLOSE_UNSAFE', record.native.cleanupFailure?.cause);
933
+ if (!failure && (this.state !== 'active' || record.native.invalidated))
934
+ failure = this.stateError();
935
+ slot.pending = undefined;
936
+ if (!failure && slot.disposed)
937
+ failure = glFailure('WEBGL2_LAYER_DISPOSED');
938
+ if (failure)
939
+ write.done.reject(failure);
940
+ else
941
+ write.done.resolve();
942
+ }
943
+ unpinLayer(revision) {
944
+ revision.pins--;
945
+ if (revision.pins === 0 && !revision.retained)
946
+ this.layerGarbage.add(revision);
947
+ }
948
+ renderSharedFrame(input) {
949
+ return this.renderOwned(input);
950
+ }
951
+ stageSharedFrame(input, options) {
952
+ return this.stageOwned(input, options);
953
+ }
954
+ stageOwned(input, options) {
955
+ this.active();
956
+ if (this.busy)
957
+ throw glFailure('WEBGL2_REENTRANT');
958
+ return this.renderOwned(input, { options, token: this.token, end: clock() + 10000, signal: undefined });
959
+ }
960
+ renderOwned(input, staging, layerInput) {
961
+ this.active();
962
+ if (this.busy)
963
+ throw glFailure('WEBGL2_REENTRANT');
964
+ this.busy = true;
965
+ this.cpu = deferred();
966
+ this.phase = 'render';
967
+ let batch;
968
+ let materialized = 0;
969
+ try {
970
+ let owned;
971
+ let admitted;
972
+ try {
973
+ admitted = runOwnedPreparationScope(() => {
974
+ const frame = readOwnedSharedFrame(input);
975
+ if (!frame)
976
+ throw glFailure('WEBGL2_FRAME_PROFILE_UNSUPPORTED');
977
+ if (staging)
978
+ staging.signal = this.captureSignal(staging.options, staging.token);
979
+ const layerWrite = layerInput && 'write' in layerInput ? layerInput.write : undefined;
980
+ const layerReads = layerInput && 'placements' in layerInput
981
+ ? this.readLayers(layerInput.placements, frame.width, frame.height)
982
+ : undefined;
983
+ const options = layerWrite ? { ...this.options, pixelRatio: 1 } : this.options;
984
+ const alpha = layerWrite ? 'premultiplied' : options.outputAlpha;
985
+ if (frame.outputAlpha !== alpha ||
986
+ frame.outputRepresentation !==
987
+ (alpha === 'opaque' ? 'egret.srgb-opaque-unorm8/1' : 'egret.srgb-premultiplied-unorm8/1'))
988
+ throw glFailure('WEBGL2_FRAME_PROFILE_UNSUPPORTED');
989
+ if (alpha === 'opaque' && frame.clearAlpha !== 1)
990
+ throw glFailure('WEBGL2_FRAME_INVALID');
991
+ if (layerWrite) {
992
+ if (frame.clearAlpha !== 0 ||
993
+ !Number.isInteger(frame.width) ||
994
+ !Number.isInteger(frame.height) ||
995
+ frame.commands.some(command => command.kind === 'barrier'
996
+ ? command.effect !== undefined
997
+ : command.kind === 'mesh' || frame.materials[command.materialIndex]?.blend !== 'normal'))
998
+ throw glFailure('WEBGL2_LAYER_INVALID');
999
+ if (frame.width > MAX_LAYER_EXTENT ||
1000
+ frame.height > MAX_LAYER_EXTENT ||
1001
+ this.layerBytes + frame.width * frame.height * 4 > MAX_LAYER_BYTES)
1002
+ throw glFailure('WEBGL2_LAYER_BUDGET');
1003
+ }
1004
+ const width = Math.ceil(frame.width * options.pixelRatio), height = Math.ceil(frame.height * options.pixelRatio);
1005
+ if (!Number.isSafeInteger(width) ||
1006
+ !Number.isSafeInteger(height) ||
1007
+ width <= 0 ||
1008
+ height <= 0 ||
1009
+ width > 4294967295 ||
1010
+ height > 4294967295 ||
1011
+ width > Math.floor(options.maxBackingPixels / height))
1012
+ throw glFailure('WEBGL2_BACKING_LIMIT');
1013
+ // A frame baked into a layer is another sequence of frames; it neither takes nor replaces what the ordinary frames keep.
1014
+ const prepared = prepareSharedDraws2D(frame, width, height, options, layerWrite ? undefined : this.retention);
1015
+ const ticket = !layerWrite && !staging && this.ticket && !this.ticket.bound ? this.ticket : undefined;
1016
+ const reserve = staging ? options.enableReadback : !!ticket;
1017
+ const fees = planSharedStorageFees2D(prepared, options), layout = withSharedReadbackLayout2D(fees, {
1018
+ rowPitch: reserve ? 4 * width : 0,
1019
+ staging: reserve ? fees.colorBytes : 0,
1020
+ output: reserve ? fees.colorBytes : 0
1021
+ });
1022
+ const limits = this.limits;
1023
+ if (width > limits.texture ||
1024
+ height > limits.texture ||
1025
+ width > limits.viewportWidth ||
1026
+ height > limits.viewportHeight)
1027
+ throw glFailure('WEBGL2_CONTEXT_LIMIT');
1028
+ const projectionPlan = {
1029
+ views: frame.pages.map(({ source: image }) => ({
1030
+ image,
1031
+ region: { x: 0, y: 0, width: image.width, height: image.height },
1032
+ byteLength: image.byteLength
1033
+ })),
1034
+ commandViews: [],
1035
+ projectionBytes: prepared.pageBytes,
1036
+ scratchBytes: 0
1037
+ };
1038
+ if (projectionPlan.views.some(({ image }) => image.width > limits.texture || image.height > limits.texture))
1039
+ throw glFailure('WEBGL2_CONTEXT_LIMIT');
1040
+ const storage = { ...layout, projectionPlan };
1041
+ checkSharedCapacity2D(storage, this.snapshot());
1042
+ const packed = packSharedDraws2D(prepared);
1043
+ this.active();
1044
+ const cold = new Set(), hits = new Map();
1045
+ const trackPage = (index) => {
1046
+ const hit = this.pages.get(projectionPlan.views[index].image);
1047
+ if (hit?.ready && hit.generation === this.generation && hit.native.outcome === 'owned')
1048
+ hits.set(index, hit);
1049
+ else
1050
+ cold.add(index);
1051
+ };
1052
+ for (const draw of packed) {
1053
+ if ('barrier' in draw || !draw.vertexCount || draw.prepared.pageIndex === undefined)
1054
+ continue;
1055
+ trackPage(draw.prepared.pageIndex);
1056
+ }
1057
+ for (const group of prepared.effects.groups)
1058
+ if (group.maskPageIndex !== undefined)
1059
+ trackPage(group.maskPageIndex);
1060
+ const timingNative = cold.size ? this.native : undefined, started = timingNative?.startTiming();
1061
+ let pages;
1062
+ try {
1063
+ pages = materializeSharedPages2D(storage, cold, this.snapshot(), this.resourceCpu);
1064
+ }
1065
+ finally {
1066
+ timingNative?.finishTiming('texture-prepare', started);
1067
+ }
1068
+ materialized = pages.canonicalBytes;
1069
+ this.active();
1070
+ checkSharedCapacity2D(storage, this.snapshot(), pages.canonicalBytes);
1071
+ // A staged frame writes its rows after later frames are prepared, so it is given batches of its own.
1072
+ batch = prepareSharedBatches2D(packed, options.maxUploadBytes, this.scratch, staging ? undefined : prepared.retention);
1073
+ this.active();
1074
+ const arena = planSharedWebGL2Arenas(batch.draws, limits.alignment, batch.draws.some(draw => draw.regionWindow >= 0) ? packSharedRegions2D(frame) : undefined);
1075
+ checkSharedWebGL2ArenaCapacity(arena, this.arenaOwner());
1076
+ return { storage, arena, batch, ...pages, ticket, hits, layerWrite, layerReads };
1077
+ }, failure => {
1078
+ owned = failure;
1079
+ });
1080
+ }
1081
+ catch (cause) {
1082
+ if (staging)
1083
+ this.stageLife(staging.token);
1084
+ if (this.state !== 'active')
1085
+ throw this.stateError();
1086
+ if (isGLFailure(cause))
1087
+ throw cause;
1088
+ if (cause === owned) {
1089
+ if (cause instanceof SharedPreparationError)
1090
+ throw glFailure(cause.reason === 'profile'
1091
+ ? 'WEBGL2_FRAME_PROFILE_UNSUPPORTED'
1092
+ : cause.reason === 'budget'
1093
+ ? 'WEBGL2_FRAME_BUDGET'
1094
+ : cause.reason === 'precision'
1095
+ ? 'WEBGL2_PRECISION_UNSUPPORTED'
1096
+ : 'WEBGL2_FRAME_INVALID', cause);
1097
+ if (cause instanceof SharedStorageError2D)
1098
+ throw glFailure(cause.reason === 'device'
1099
+ ? 'WEBGL2_CONTEXT_LIMIT'
1100
+ : cause.reason === 'backpressure'
1101
+ ? 'WEBGL2_BACKPRESSURE'
1102
+ : cause.reason === 'serial'
1103
+ ? 'WEBGL2_SERIAL_EXHAUSTED'
1104
+ : 'WEBGL2_FRAME_BUDGET', cause);
1105
+ if (cause instanceof GeometryPreparationError)
1106
+ throw glFailure('WEBGL2_GEOMETRY_RANGE', cause);
1107
+ }
1108
+ throw glFailure('WEBGL2_FRAME_INVALID', cause);
1109
+ }
1110
+ return staging ? this.admitUpload(admitted, staging) : this.submit(admitted);
1111
+ }
1112
+ finally {
1113
+ if (!batch?.transferred)
1114
+ this.resourceCpu.canonicalBytes -= materialized;
1115
+ if (batch && !batch.transferred)
1116
+ this.scratch.release(batch);
1117
+ this.sweepLayers();
1118
+ this.phase = undefined;
1119
+ this.busy = false;
1120
+ this.retireLost();
1121
+ this.cpu.resolve();
1122
+ }
1123
+ }
1124
+ planRecord(p) {
1125
+ const { width, height } = p.storage.prepared;
1126
+ const requests = [];
1127
+ const add = (role, byteLength) => {
1128
+ const id = requests.length;
1129
+ const target = role === 'color';
1130
+ const request = Object.freeze({ id, role, byteLength, width: target ? width : 0, height: target ? height : 0 });
1131
+ requests.push({ request, key: role + ':' + byteLength + ':' + request.width + ':' + request.height });
1132
+ return id;
1133
+ };
1134
+ const vertex = p.arena.vertexBytes ? add('vertex', p.arena.vertexBytes) : -1, uniform = p.arena.uniformBytes ? add('uniform', p.arena.uniformBytes) : -1, color = p.layerWrite ? -1 : add('color', p.storage.colorBytes);
1135
+ const regions = p.arena.regionTable ? add('uniform', p.arena.regionTable.bytes) : -1;
1136
+ const effectTargets = Array.from({ length: p.storage.prepared.effects.targetCount }, () => add('color', p.storage.colorBytes));
1137
+ const effectUniforms = p.storage.prepared.effects.groups.map(group => add('uniform', group.uniform.byteLength));
1138
+ const plan = this.pool.plan(requests);
1139
+ this.active();
1140
+ checkSharedCapacity2D(p.storage, this.snapshot(), p.canonicalBytes);
1141
+ checkSharedWebGL2ArenaCapacity(p.arena, this.arenaOwner());
1142
+ for (const [index, hit] of p.hits)
1143
+ if (this.pages.get(p.storage.projectionPlan.views[index].image) !== hit || !hit.ready)
1144
+ throw glFailure('WEBGL2_FRAME_INVALID');
1145
+ return {
1146
+ requests,
1147
+ plan,
1148
+ layout: { vertex, uniform, regions, color, effectTargets, effectUniforms, pageTextures: new Map() }
1149
+ };
1150
+ }
1151
+ stageLife(token) {
1152
+ this.active();
1153
+ if (token !== this.token)
1154
+ throw glFailure('WEBGL2_UPLOAD_STALE');
1155
+ }
1156
+ signalRead(token, read) {
1157
+ let value;
1158
+ try {
1159
+ value = read();
1160
+ }
1161
+ catch (cause) {
1162
+ this.stageLife(token);
1163
+ throw glFailure('WEBGL2_UPLOAD_OPTIONS_INVALID', cause);
1164
+ }
1165
+ this.stageLife(token);
1166
+ return value;
1167
+ }
1168
+ captureSignal(options, token) {
1169
+ if (options === undefined)
1170
+ return undefined;
1171
+ if (typeof options !== 'object' || options === null)
1172
+ throw glFailure('WEBGL2_UPLOAD_OPTIONS_INVALID');
1173
+ const source = this.signalRead(token, () => options.signal);
1174
+ if (source === undefined)
1175
+ return undefined;
1176
+ if (typeof source !== 'object' || source === null)
1177
+ throw glFailure('WEBGL2_UPLOAD_OPTIONS_INVALID');
1178
+ const aborted = this.signalRead(token, () => source.aborted);
1179
+ if (typeof aborted !== 'boolean')
1180
+ throw glFailure('WEBGL2_UPLOAD_OPTIONS_INVALID');
1181
+ if (aborted)
1182
+ throw this.abortFailure(source, token);
1183
+ const add = this.signalRead(token, () => source.addEventListener), remove = this.signalRead(token, () => source.removeEventListener);
1184
+ if (typeof add !== 'function' || typeof remove !== 'function')
1185
+ throw glFailure('WEBGL2_UPLOAD_OPTIONS_INVALID');
1186
+ const captured = {
1187
+ source,
1188
+ add,
1189
+ remove,
1190
+ token,
1191
+ listener: () => undefined,
1192
+ subscribed: false,
1193
+ aborted: false,
1194
+ failure: undefined,
1195
+ control: undefined
1196
+ };
1197
+ captured.listener = () => {
1198
+ if (captured.subscribed && captured.control && !captured.control.revoked)
1199
+ this.observeAbort(captured);
1200
+ };
1201
+ return captured;
1202
+ }
1203
+ abortFailure(source, token) {
1204
+ try {
1205
+ const reason = source.reason;
1206
+ this.stageLife(token);
1207
+ return glFailure('WEBGL2_UPLOAD_ABORTED', reason);
1208
+ }
1209
+ catch (cause) {
1210
+ this.stageLife(token);
1211
+ return glFailure('WEBGL2_UPLOAD_OPTIONS_INVALID', cause);
1212
+ }
1213
+ }
1214
+ observeAbort(signal) {
1215
+ const control = signal.control;
1216
+ if (signal.aborted || control?.revoked || control?.transferred || control?.phase === 'retired')
1217
+ return;
1218
+ // Latch before a reason getter can recursively deliver another abort.
1219
+ signal.aborted = true;
1220
+ if (control)
1221
+ control.revoked = true;
1222
+ const ownsSection = !this.busy;
1223
+ if (ownsSection) {
1224
+ this.busy = true;
1225
+ this.cpu = deferred();
1226
+ this.phase = 'poll';
1227
+ }
1228
+ try {
1229
+ let error;
1230
+ try {
1231
+ error = this.abortFailure(signal.source, signal.token);
1232
+ }
1233
+ catch (terminal) {
1234
+ error = terminal;
1235
+ }
1236
+ signal.failure = error;
1237
+ if (control)
1238
+ this.revokeUpload(control, error);
1239
+ }
1240
+ finally {
1241
+ if (ownsSection) {
1242
+ this.phase = undefined;
1243
+ this.busy = false;
1244
+ this.retireLost();
1245
+ this.cpu.resolve();
1246
+ this.schedulePump();
1247
+ }
1248
+ }
1249
+ }
1250
+ removeUploadSignal(control) {
1251
+ const signal = control.signal;
1252
+ if (!signal?.subscribed)
1253
+ return;
1254
+ signal.subscribed = false;
1255
+ try {
1256
+ invoke(signal.remove, signal.source, ['abort', signal.listener]);
1257
+ }
1258
+ catch (cause) {
1259
+ let error;
1260
+ try {
1261
+ this.stageLife(control.token);
1262
+ error = glFailure('WEBGL2_UPLOAD_OPTIONS_INVALID', cause);
1263
+ }
1264
+ catch (terminal) {
1265
+ error = terminal;
1266
+ }
1267
+ control.failure ??= error;
1268
+ if (control.record)
1269
+ control.record.failure ??= error;
1270
+ control.ready.reject(error);
1271
+ }
1272
+ }
1273
+ clearUploadAdmission(control) {
1274
+ if (control.timer !== undefined) {
1275
+ const timer = control.timer;
1276
+ control.timer = undefined;
1277
+ cancel(timer);
1278
+ }
1279
+ this.removeUploadSignal(control);
1280
+ }
1281
+ revokeUpload(control, error) {
1282
+ if (control.transferred || control.phase === 'retired')
1283
+ return;
1284
+ const ownsSection = !this.busy;
1285
+ if (ownsSection) {
1286
+ this.busy = true;
1287
+ this.cpu = deferred();
1288
+ this.phase = 'poll';
1289
+ }
1290
+ try {
1291
+ control.revoked = true;
1292
+ control.failure ??= error;
1293
+ const record = control.record;
1294
+ if (record)
1295
+ record.failure ??= control.failure;
1296
+ control.ready.reject(control.failure);
1297
+ this.clearUploadAdmission(control);
1298
+ // A running native section always installs its original proof in finally.
1299
+ if (record && ownsSection && !record.sync)
1300
+ this.retire(record);
1301
+ else
1302
+ this.schedulePump();
1303
+ }
1304
+ finally {
1305
+ if (ownsSection) {
1306
+ this.phase = undefined;
1307
+ this.busy = false;
1308
+ this.retireLost();
1309
+ this.cpu.resolve();
1310
+ this.schedulePump();
1311
+ }
1312
+ }
1313
+ }
1314
+ revokeUploads(error) {
1315
+ // Revoke every publication before the first external listener removal.
1316
+ const controls = [...this.records].flatMap(record => !record.retired && record.upload && !record.upload.control.transferred ? [record.upload.control] : []);
1317
+ for (const control of controls) {
1318
+ control.revoked = true;
1319
+ control.failure ??= error;
1320
+ control.record.failure ??= control.failure;
1321
+ control.ready.reject(control.failure);
1322
+ }
1323
+ for (const control of controls)
1324
+ this.revokeUpload(control, error);
1325
+ }
1326
+ admitUpload(p, input) {
1327
+ this.stageLife(input.token);
1328
+ const { requests, plan, layout } = this.planRecord(p), native = this.native;
1329
+ const control = {
1330
+ token: input.token,
1331
+ generation: this.generation,
1332
+ frameId: p.storage.prepared.frame.frameId,
1333
+ end: input.end,
1334
+ ready: deferred(),
1335
+ record: undefined,
1336
+ signal: input.signal,
1337
+ timer: undefined,
1338
+ phase: 'admitted',
1339
+ transferred: false,
1340
+ revoked: false,
1341
+ failure: undefined
1342
+ };
1343
+ const record = {
1344
+ serial: 0,
1345
+ generation: this.generation,
1346
+ storage: p.storage,
1347
+ vertexArenaBytes: p.arena.vertexBytes,
1348
+ uniformArenaBytes: p.arena.uniformBytes,
1349
+ canonicalBytes: p.canonicalBytes,
1350
+ reservedPageBytes: p.canonicalBytes,
1351
+ projections: p.projections,
1352
+ done: deferred(),
1353
+ leases: [],
1354
+ pages: [],
1355
+ native,
1356
+ pool: this.pool,
1357
+ rawOwners: [],
1358
+ readback: undefined,
1359
+ ticket: undefined,
1360
+ pbo: undefined,
1361
+ sync: undefined,
1362
+ failure: undefined,
1363
+ retired: false,
1364
+ deadline: 0
1365
+ };
1366
+ record.upload = {
1367
+ control,
1368
+ requests,
1369
+ plan,
1370
+ layout,
1371
+ arena: p.arena,
1372
+ batch: p.batch,
1373
+ writes: [],
1374
+ claimed: false,
1375
+ allocated: false,
1376
+ writeIndex: 0
1377
+ };
1378
+ control.record = record;
1379
+ this.records.add(record);
1380
+ p.batch.transferred = true;
1381
+ this.reservePageDiagnostics(record);
1382
+ try {
1383
+ const signal = input.signal;
1384
+ if (signal) {
1385
+ signal.control = control;
1386
+ signal.subscribed = true;
1387
+ try {
1388
+ invoke(signal.add, signal.source, ['abort', signal.listener, { once: true }]);
1389
+ }
1390
+ catch (cause) {
1391
+ this.stageLife(input.token);
1392
+ throw signal.failure ?? glFailure('WEBGL2_UPLOAD_OPTIONS_INVALID', cause);
1393
+ }
1394
+ this.stageLife(input.token);
1395
+ if (signal.failure)
1396
+ throw signal.failure;
1397
+ const aborted = this.signalRead(input.token, () => signal.source.aborted);
1398
+ if (typeof aborted !== 'boolean')
1399
+ throw glFailure('WEBGL2_UPLOAD_OPTIONS_INVALID');
1400
+ if (aborted)
1401
+ this.observeAbort(signal);
1402
+ this.stageLife(input.token);
1403
+ if (signal.failure)
1404
+ throw signal.failure;
1405
+ }
1406
+ if (clock() >= control.end)
1407
+ throw glFailure('WEBGL2_UPLOAD_EXPIRED');
1408
+ if (control.failure)
1409
+ throw control.failure;
1410
+ record.pool.claim(plan);
1411
+ record.upload.claimed = true;
1412
+ for (const lease of plan.leases)
1413
+ record.leases[lease.requestId] = lease;
1414
+ // All ready page hits are pinned before any victim is cleaned.
1415
+ for (const [index, page] of p.hits) {
1416
+ this.pinPageDiagnostics(page);
1417
+ page.pins++;
1418
+ record.pages.push(page);
1419
+ layout.pageTextures.set(index, page);
1420
+ }
1421
+ const owner = this;
1422
+ const handle = Object.freeze({
1423
+ ready: control.ready.promise,
1424
+ submit() {
1425
+ if (this !== handle)
1426
+ throw glFailure('WEBGL2_UPLOAD_INVALID');
1427
+ return owner.submitUpload(control);
1428
+ },
1429
+ dispose() {
1430
+ if (this !== handle)
1431
+ throw glFailure('WEBGL2_UPLOAD_INVALID');
1432
+ owner.revokeUpload(control, glFailure('WEBGL2_UPLOAD_DISPOSED'));
1433
+ }
1434
+ });
1435
+ control.timer = schedule(() => this.revokeUpload(control, glFailure('WEBGL2_UPLOAD_EXPIRED')), Math.max(0, control.end - clock()));
1436
+ this.schedulePump();
1437
+ return handle;
1438
+ }
1439
+ catch (cause) {
1440
+ let error;
1441
+ try {
1442
+ this.stageLife(input.token);
1443
+ error = control.failure ?? (isGLFailure(cause) ? cause : glFailure('WEBGL2_UPLOAD_OPTIONS_INVALID', cause));
1444
+ }
1445
+ catch (terminal) {
1446
+ error = terminal;
1447
+ }
1448
+ this.revokeUpload(control, error);
1449
+ this.retire(record);
1450
+ throw error;
1451
+ }
1452
+ }
1453
+ allocateUpload(record) {
1454
+ const work = record.upload, native = record.native, gl = native.gl, { width, height } = record.storage.prepared;
1455
+ for (const victim of work.plan.victims)
1456
+ this.disposeHandle(victim, native, record.pool);
1457
+ if (this.unsafe)
1458
+ throw glFailure('WEBGL2_CLOSE_UNSAFE');
1459
+ for (const entry of work.requests) {
1460
+ if (record.leases[entry.request.id])
1461
+ continue;
1462
+ const request = entry.request, owner = native.create(request.role === 'color' ? 'Texture' : 'Buffer', request.byteLength);
1463
+ const lease = record.pool.registerCreated(entry, owner);
1464
+ record.leases[request.id] = lease;
1465
+ owner.accounting = 'retention';
1466
+ if (request.role === 'color')
1467
+ native.texture(owner, width, height, true);
1468
+ else {
1469
+ const target = request.role === 'vertex' ? gl.ARRAY_BUFFER : gl.UNIFORM_BUFFER;
1470
+ gl.bindBuffer(target, owner.value);
1471
+ gl.bufferData(target, request.byteLength, gl.DYNAMIC_DRAW);
1472
+ }
1473
+ }
1474
+ for (let index = 0; index < record.projections.length; index++) {
1475
+ const pixels = record.projections[index];
1476
+ if (!pixels)
1477
+ continue;
1478
+ const source = record.storage.projectionPlan.views[index].image, owner = native.create('Texture', source.byteLength, undefined, record);
1479
+ const page = {
1480
+ source,
1481
+ native: owner,
1482
+ generation: record.generation,
1483
+ white: whitePixel(source, pixels),
1484
+ ready: false,
1485
+ pins: 1
1486
+ };
1487
+ record.pages.push(page);
1488
+ work.layout.pageTextures.set(index, page);
1489
+ native.texture(owner, source.width, source.height, false);
1490
+ work.writes.push({ kind: 'page', page, pixels, row: 0 });
1491
+ }
1492
+ const buffer = (target, lease, offset, data, unit) => {
1493
+ if (data.byteLength)
1494
+ work.writes.push({ kind: 'buffer', target, lease, offset, data, unit, cursor: 0 });
1495
+ };
1496
+ const { vertex, uniform, regions } = work.layout;
1497
+ for (const range of work.arena.sharedRanges) {
1498
+ buffer(gl.ARRAY_BUFFER, vertex, range.vertexOffset, range.draw.data, 52);
1499
+ buffer(gl.UNIFORM_BUFFER, uniform, range.uniformOffset, range.draw.uniform, 128);
1500
+ }
1501
+ for (const part of work.arena.regionTable?.windows ?? [])
1502
+ buffer(gl.UNIFORM_BUFFER, regions, part.offset, part.data, 48);
1503
+ for (let i = 0; i < record.storage.prepared.effects.groups.length; i++)
1504
+ buffer(gl.UNIFORM_BUFFER, work.layout.effectUniforms[i], 0, record.storage.prepared.effects.groups[i].uniform, 16);
1505
+ work.allocated = true;
1506
+ }
1507
+ uploadChunk(record) {
1508
+ const work = record.upload, control = work.control, native = record.native, gl = native.gl;
1509
+ if (control.revoked) {
1510
+ this.retire(record);
1511
+ return;
1512
+ }
1513
+ this.phase = 'upload';
1514
+ this.uploading = record;
1515
+ native.recordOwners = record.rawOwners;
1516
+ control.phase = 'uploading';
1517
+ let issued = false;
1518
+ try {
1519
+ this.stageLife(control.token);
1520
+ if (clock() >= control.end) {
1521
+ this.revokeUpload(control, glFailure('WEBGL2_UPLOAD_EXPIRED'));
1522
+ throw control.failure;
1523
+ }
1524
+ issued = true;
1525
+ native.reset(record.storage.prepared.width, record.storage.prepared.height);
1526
+ if (!work.allocated)
1527
+ this.allocateUpload(record);
1528
+ let remaining = 4194304;
1529
+ while (work.writeIndex < work.writes.length) {
1530
+ const write = work.writes[work.writeIndex];
1531
+ if (write.kind === 'page') {
1532
+ const { source } = write.page, stride = source.width * 4;
1533
+ if (stride > 4194304)
1534
+ throw glFailure('WEBGL2_FRAME_BUDGET');
1535
+ const rows = Math.min(source.height - write.row, Math.floor(remaining / stride));
1536
+ if (rows === 0)
1537
+ break;
1538
+ gl.bindTexture(gl.TEXTURE_2D, write.page.native.value);
1539
+ const bytes = rows * stride, offset = write.row * stride;
1540
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, write.row, source.width, rows, gl.RGBA, gl.UNSIGNED_BYTE, write.pixels.subarray(offset, offset + bytes));
1541
+ write.row += rows;
1542
+ remaining -= bytes;
1543
+ if (write.row === source.height)
1544
+ work.writeIndex++;
1545
+ }
1546
+ else {
1547
+ const bytes = Math.min(write.data.byteLength - write.cursor, Math.floor(remaining / write.unit) * write.unit);
1548
+ if (bytes === 0)
1549
+ break;
1550
+ gl.bindBuffer(write.target, record.leases[write.lease].handle.resource.value);
1551
+ const view = new Uint8Array(write.data.buffer, write.data.byteOffset + write.cursor, bytes);
1552
+ gl.bufferSubData(write.target, write.offset + write.cursor, view);
1553
+ write.cursor += bytes;
1554
+ remaining -= bytes;
1555
+ if (write.cursor === write.data.byteLength)
1556
+ work.writeIndex++;
1557
+ }
1558
+ if (clock() >= control.end) {
1559
+ this.revokeUpload(control, glFailure('WEBGL2_UPLOAD_EXPIRED'));
1560
+ throw control.failure;
1561
+ }
1562
+ }
1563
+ native.check();
1564
+ }
1565
+ catch (cause) {
1566
+ if (!record.failure) {
1567
+ const error = this.note(isGLFailure(cause) ? cause.code : 'WEBGL2_RENDER_FAILED', isGLFailure(cause) ? cause.cause : cause, 'frame');
1568
+ record.failure = error;
1569
+ if (this.state === 'active') {
1570
+ this.state = 'failed';
1571
+ this.revokeUploads(error);
1572
+ }
1573
+ else
1574
+ this.revokeUpload(control, error);
1575
+ }
1576
+ }
1577
+ finally {
1578
+ // Even cancellation after a write needs the real original GL proof.
1579
+ this.uploading = undefined;
1580
+ this.phase = 'poll';
1581
+ try {
1582
+ if (issued)
1583
+ this.issueUploadFence(record);
1584
+ else if (record.failure)
1585
+ this.retire(record);
1586
+ }
1587
+ finally {
1588
+ native.recordOwners = undefined;
1589
+ }
1590
+ }
1591
+ }
1592
+ issueUploadFence(record) {
1593
+ const native = record.native;
1594
+ if (!native.invalidated) {
1595
+ try {
1596
+ this.detachContainers(native);
1597
+ record.sync = native.create('Sync');
1598
+ record.deadline = clock() + 30000;
1599
+ native.gl.flush();
1600
+ native.check();
1601
+ }
1602
+ catch (cause) {
1603
+ record.failure ??= this.note('WEBGL2_SYNC_FAILED', cause, 'frame', record.serial || null);
1604
+ if (!native.invalidated) {
1605
+ this.unsafe = true;
1606
+ this.markUnknown(record);
1607
+ if (this.state === 'active') {
1608
+ this.state = 'failed';
1609
+ this.revokeUploads(record.failure);
1610
+ }
1611
+ }
1612
+ if (record.upload && !record.upload.control.transferred)
1613
+ this.revokeUpload(record.upload.control, record.failure);
1614
+ }
1615
+ }
1616
+ if (native.invalidated || !record.sync)
1617
+ this.retire(record);
1618
+ }
1619
+ submitUpload(control) {
1620
+ this.stageLife(control.token);
1621
+ if (this.busy)
1622
+ throw glFailure('WEBGL2_REENTRANT');
1623
+ if (control.transferred)
1624
+ throw glFailure('WEBGL2_UPLOAD_USED');
1625
+ if (clock() >= control.end)
1626
+ this.revokeUpload(control, glFailure('WEBGL2_UPLOAD_EXPIRED'));
1627
+ if (control.failure)
1628
+ throw control.failure;
1629
+ if (control.phase !== 'ready' || !control.record)
1630
+ throw glFailure('WEBGL2_UPLOAD_NOT_READY');
1631
+ if (this.serial >= Number.MAX_SAFE_INTEGER)
1632
+ throw glFailure('WEBGL2_SERIAL_EXHAUSTED');
1633
+ const record = control.record, work = record.upload, native = record.native;
1634
+ const submitted = native.startTiming();
1635
+ this.busy = true;
1636
+ this.cpu = deferred();
1637
+ this.phase = 'render';
1638
+ try {
1639
+ this.generationGate(control.token);
1640
+ const ticket = this.ticket && !this.ticket.bound ? this.ticket : undefined;
1641
+ record.serial = ++this.serial;
1642
+ if (this.frameTiming)
1643
+ native.timingSerial = record.serial;
1644
+ record.ticket = ticket;
1645
+ if (ticket)
1646
+ ticket.bound = true;
1647
+ record.completion = deferred();
1648
+ control.transferred = true;
1649
+ control.phase = 'submitted';
1650
+ this.clearUploadAdmission(control);
1651
+ native.recordOwners = record.rawOwners;
1652
+ let issued = false;
1653
+ try {
1654
+ // Removal is caller-owned code. Recheck before even reading or
1655
+ // resizing the visible target, and unwind unstarted transfer.
1656
+ this.stageLife(control.token);
1657
+ if (record.failure)
1658
+ throw record.failure;
1659
+ this.generationGate(control.token);
1660
+ issued = true;
1661
+ this.prepareSurface(record);
1662
+ this.drawRecord(record, work.layout, work.arena);
1663
+ }
1664
+ catch (cause) {
1665
+ record.failure ??=
1666
+ !issued && isGLFailure(cause)
1667
+ ? cause
1668
+ : this.note(isGLFailure(cause) ? cause.code : 'WEBGL2_RENDER_FAILED', isGLFailure(cause) ? cause.cause : cause, 'frame', record.serial);
1669
+ if (this.state === 'active' && (issued || !isGLFailure(cause))) {
1670
+ this.state = 'failed';
1671
+ this.revokeUploads(record.failure);
1672
+ }
1673
+ }
1674
+ this.phase = 'poll';
1675
+ if (issued)
1676
+ this.issueUploadFence(record);
1677
+ else
1678
+ this.retire(record);
1679
+ native.recordOwners = undefined;
1680
+ this.schedulePump();
1681
+ if (record.failure) {
1682
+ record.completion.reject(record.failure);
1683
+ throw record.failure;
1684
+ }
1685
+ return Object.freeze({
1686
+ generation: record.generation,
1687
+ frameId: control.frameId,
1688
+ serial: record.serial,
1689
+ completed: record.completion.promise
1690
+ });
1691
+ }
1692
+ finally {
1693
+ if (submitted !== undefined) {
1694
+ native.finishTiming('submit', submitted);
1695
+ native.timingSerial = null;
1696
+ }
1697
+ native.recordOwners = undefined;
1698
+ this.phase = undefined;
1699
+ this.busy = false;
1700
+ this.retireLost();
1701
+ this.cpu.resolve();
1702
+ }
1703
+ }
1704
+ submit(p) {
1705
+ const native = this.native, gl = native.gl, { width, height } = p.storage.prepared;
1706
+ const { requests, plan, layout } = this.planRecord(p), { vertex, uniform, regions } = layout;
1707
+ const record = {
1708
+ serial: this.serial + 1,
1709
+ generation: this.generation,
1710
+ storage: p.storage,
1711
+ vertexArenaBytes: p.arena.vertexBytes,
1712
+ uniformArenaBytes: p.arena.uniformBytes,
1713
+ canonicalBytes: p.canonicalBytes,
1714
+ reservedPageBytes: p.canonicalBytes,
1715
+ projections: p.projections,
1716
+ done: deferred(),
1717
+ leases: [],
1718
+ pages: [],
1719
+ native,
1720
+ pool: this.pool,
1721
+ rawOwners: [],
1722
+ readback: undefined,
1723
+ ticket: p.ticket,
1724
+ pbo: undefined,
1725
+ sync: undefined,
1726
+ failure: undefined,
1727
+ retired: false,
1728
+ deadline: clock() + 30000
1729
+ };
1730
+ for (const lease of plan.leases)
1731
+ record.leases[lease.requestId] = lease;
1732
+ this.records.add(record);
1733
+ this.serial = record.serial;
1734
+ p.batch.transferred = true;
1735
+ this.reservePageDiagnostics(record);
1736
+ if (p.ticket)
1737
+ p.ticket.bound = true;
1738
+ if (p.layerWrite) {
1739
+ record.layerWrite = p.layerWrite;
1740
+ p.layerWrite.submitted = true;
1741
+ }
1742
+ if (p.layerReads) {
1743
+ record.layerReads = p.layerReads;
1744
+ for (const read of p.layerReads)
1745
+ read.revision.pins++;
1746
+ }
1747
+ native.recordOwners = record.rawOwners;
1748
+ const submitted = native.startTiming();
1749
+ if (submitted !== undefined)
1750
+ native.timingSerial = record.serial;
1751
+ try {
1752
+ this.pool.claim(plan);
1753
+ for (const victim of plan.victims)
1754
+ this.disposeHandle(victim, native, this.pool);
1755
+ if (this.unsafe)
1756
+ throw glFailure('WEBGL2_CLOSE_UNSAFE');
1757
+ for (const entry of requests) {
1758
+ if (record.leases[entry.request.id])
1759
+ continue;
1760
+ const owner = native.create(entry.request.role === 'color' ? 'Texture' : 'Buffer', entry.request.byteLength);
1761
+ const lease = this.pool.registerCreated(entry, owner);
1762
+ record.leases[entry.request.id] = lease;
1763
+ owner.accounting = 'retention';
1764
+ if (entry.request.role === 'color')
1765
+ native.texture(owner, width, height, true);
1766
+ else {
1767
+ const target = entry.request.role === 'vertex' ? gl.ARRAY_BUFFER : gl.UNIFORM_BUFFER;
1768
+ gl.bindBuffer(target, owner.value);
1769
+ gl.bufferData(target, entry.request.byteLength, gl.DYNAMIC_DRAW);
1770
+ }
1771
+ }
1772
+ if (record.layerWrite) {
1773
+ const owner = native.create('Texture', p.storage.colorBytes);
1774
+ const revision = { native, owner, pins: 1, retained: false };
1775
+ record.layerWrite.revision = revision;
1776
+ this.layerBytes += owner.bytes;
1777
+ native.reset(width, height);
1778
+ native.texture(owner, width, height, true);
1779
+ }
1780
+ else
1781
+ this.prepareSurface(record);
1782
+ const pageTextures = layout.pageTextures;
1783
+ for (const [index, hit] of p.hits) {
1784
+ this.pinPageDiagnostics(hit);
1785
+ hit.pins++;
1786
+ record.pages.push(hit);
1787
+ pageTextures.set(index, hit);
1788
+ }
1789
+ for (let index = 0; index < p.projections.length; index++) {
1790
+ const pixels = p.projections[index];
1791
+ if (!pixels)
1792
+ continue;
1793
+ const source = p.storage.projectionPlan.views[index].image, owner = native.create('Texture', source.byteLength, undefined, record);
1794
+ const page = {
1795
+ source,
1796
+ native: owner,
1797
+ generation: this.generation,
1798
+ white: whitePixel(source, pixels),
1799
+ ready: false,
1800
+ pins: 1
1801
+ };
1802
+ record.pages.push(page);
1803
+ pageTextures.set(index, page);
1804
+ native.texture(owner, source.width, source.height, false);
1805
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, source.width, source.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
1806
+ }
1807
+ if (vertex >= 0) {
1808
+ gl.bindBuffer(gl.ARRAY_BUFFER, record.leases[vertex].handle.resource.value);
1809
+ for (const range of p.arena.sharedRanges)
1810
+ gl.bufferSubData(gl.ARRAY_BUFFER, range.vertexOffset, range.draw.data);
1811
+ }
1812
+ if (uniform >= 0) {
1813
+ gl.bindBuffer(gl.UNIFORM_BUFFER, record.leases[uniform].handle.resource.value);
1814
+ for (const range of p.arena.sharedRanges)
1815
+ gl.bufferSubData(gl.UNIFORM_BUFFER, range.uniformOffset, range.draw.uniform);
1816
+ }
1817
+ if (regions >= 0) {
1818
+ gl.bindBuffer(gl.UNIFORM_BUFFER, record.leases[regions].handle.resource.value);
1819
+ for (const part of p.arena.regionTable.windows)
1820
+ gl.bufferSubData(gl.UNIFORM_BUFFER, part.offset, part.data);
1821
+ }
1822
+ for (let i = 0; i < record.storage.prepared.effects.groups.length; i++) {
1823
+ gl.bindBuffer(gl.UNIFORM_BUFFER, record.leases[layout.effectUniforms[i]].handle.resource.value);
1824
+ gl.bufferSubData(gl.UNIFORM_BUFFER, 0, record.storage.prepared.effects.groups[i].uniform);
1825
+ }
1826
+ this.drawRecord(record, layout, p.arena);
1827
+ }
1828
+ catch (cause) {
1829
+ record.failure = this.note(isGLFailure(cause) ? cause.code : 'WEBGL2_RENDER_FAILED', isGLFailure(cause) ? cause.cause : cause, 'frame', record.serial);
1830
+ if (this.state === 'active') {
1831
+ this.state = 'failed';
1832
+ this.revokeUploads(record.failure);
1833
+ }
1834
+ }
1835
+ finally {
1836
+ // bufferSubData has copied the CPU rows. Only the native leases and their fence remain pending.
1837
+ this.scratch.release(p.batch);
1838
+ }
1839
+ // Even a partially issued draw owns a completion proof before resources can be reused.
1840
+ if (!native.invalidated) {
1841
+ const old = this.phase;
1842
+ this.phase = 'poll';
1843
+ try {
1844
+ this.detachContainers(native);
1845
+ record.sync = native.create('Sync');
1846
+ record.deadline = clock() + 30000;
1847
+ gl.flush();
1848
+ native.check();
1849
+ }
1850
+ catch (cause) {
1851
+ record.failure ??= this.note('WEBGL2_SYNC_FAILED', cause, 'frame', record.serial);
1852
+ if (!native.invalidated) {
1853
+ this.unsafe = true;
1854
+ this.markUnknown(record);
1855
+ }
1856
+ }
1857
+ finally {
1858
+ this.phase = old;
1859
+ }
1860
+ }
1861
+ if (submitted !== undefined) {
1862
+ native.finishTiming('submit', submitted);
1863
+ native.timingSerial = null;
1864
+ }
1865
+ native.recordOwners = undefined;
1866
+ if (native.invalidated)
1867
+ this.retireLost();
1868
+ else if (!record.sync)
1869
+ this.retire(record);
1870
+ else
1871
+ this.schedulePump();
1872
+ if (record.failure)
1873
+ throw record.failure;
1874
+ return undefined;
1875
+ }
1876
+ prepareSurface(record) {
1877
+ const native = record.native, { width, height } = record.storage.prepared;
1878
+ if (this.surface.width !== width)
1879
+ this.surface.width = width;
1880
+ this.generationGate(this.token);
1881
+ if (this.surface.height !== height)
1882
+ this.surface.height = height;
1883
+ this.generationGate(this.token);
1884
+ if (this.surface.width !== width || this.surface.height !== height)
1885
+ throw new Error('Canvas rejected dimensions');
1886
+ if (this.context.drawingBufferWidth !== width || this.context.drawingBufferHeight !== height)
1887
+ throw glFailure('WEBGL2_BACKING_LIMIT');
1888
+ this.generationGate(this.token);
1889
+ native.reset(width, height);
1890
+ }
1891
+ drawLayers(record, width, height) {
1892
+ const reads = record.layerReads;
1893
+ if (!reads?.length)
1894
+ return;
1895
+ const native = record.native, gl = native.gl;
1896
+ gl.bindVertexArray(this.resolveVAO);
1897
+ gl.activeTexture(gl.TEXTURE0);
1898
+ gl.enable(gl.BLEND);
1899
+ gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
1900
+ let current;
1901
+ for (const read of reads) {
1902
+ const variant = this.getLayerProgram(native, read.effect !== undefined);
1903
+ if (current !== variant) {
1904
+ current = variant;
1905
+ gl.useProgram(variant.program);
1906
+ gl.uniform1i(variant.texture, 0);
1907
+ gl.uniform2f(variant.viewport, width, height);
1908
+ }
1909
+ if (read.effect && variant.effect) {
1910
+ const { left, top, right, bottom, scale, emission } = read.effect, loc = variant.effect;
1911
+ gl.uniform2f(loc.min, left, top);
1912
+ gl.uniform2f(loc.max, right, bottom);
1913
+ gl.uniform2f(loc.scaleRG, scale[0], scale[1]);
1914
+ gl.uniform2f(loc.scaleBAddR, scale[2], emission[0]);
1915
+ gl.uniform2f(loc.addGB, emission[1], emission[2]);
1916
+ }
1917
+ gl.bindTexture(gl.TEXTURE_2D, read.revision.owner.value);
1918
+ gl.uniform2f(variant.origin, read.x, read.y);
1919
+ gl.uniform2f(variant.extent, read.width, read.height);
1920
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
1921
+ }
1922
+ gl.bindTexture(gl.TEXTURE_2D, null);
1923
+ }
1924
+ getLayerProgram(native, effect) {
1925
+ const existing = effect ? this.layerEffectProgram : this.layerProgram;
1926
+ if (existing)
1927
+ return existing;
1928
+ const variant = createWebGL2LayerProgram(native, effect);
1929
+ if (effect)
1930
+ this.layerEffectProgram = variant;
1931
+ else
1932
+ this.layerProgram = variant;
1933
+ return variant;
1934
+ }
1935
+ drawRecord(record, layout, arena) {
1936
+ const native = record.native, gl = native.gl, { width, height, frame } = record.storage.prepared;
1937
+ const { vertex, uniform, regions, color, pageTextures } = layout;
1938
+ const colorTexture = (record.layerWrite?.revision?.owner ?? record.leases[color].handle.resource)
1939
+ .value;
1940
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
1941
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorTexture, 0);
1942
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, null);
1943
+ native.workingAttachment(colorTexture, null);
1944
+ gl.drawBuffers([gl.COLOR_ATTACHMENT0]);
1945
+ const c = frame.clearColor, a = frame.clearAlpha;
1946
+ gl.clearColor(a * decodeSharedSRGBByte(c >>> 16), a * decodeSharedSRGBByte(c >>> 8), a * decodeSharedSRGBByte(c), a);
1947
+ gl.clear(gl.COLOR_BUFFER_BIT);
1948
+ // The program and the window of the region table that are current; both change only between batches.
1949
+ let program, bound = -1;
1950
+ // The page each texture unit after the first holds. A unit keeps its page until a batch needs another there.
1951
+ const units = [];
1952
+ const table = arena.regionTable;
1953
+ const bindDraw = () => {
1954
+ program = this.program;
1955
+ bound = -1;
1956
+ gl.activeTexture(gl.TEXTURE0);
1957
+ gl.useProgram(program);
1958
+ gl.bindVertexArray(this.drawVAO);
1959
+ if (vertex >= 0) {
1960
+ gl.bindBuffer(gl.ARRAY_BUFFER, record.leases[vertex].handle.resource.value);
1961
+ for (const [index, size, offset] of [
1962
+ [0, 2, 0],
1963
+ [1, 2, 8],
1964
+ [2, 4, 16],
1965
+ [3, 3, 32],
1966
+ [4, 2, 44]
1967
+ ]) {
1968
+ gl.enableVertexAttribArray(index);
1969
+ gl.vertexAttribPointer(index, size, gl.FLOAT, false, 52, offset);
1970
+ gl.vertexAttribDivisor(index, 0);
1971
+ }
1972
+ }
1973
+ gl.uniform1i(gl.getUniformLocation(this.program, 'page'), 0);
1974
+ // An effect pass in between has used the units for its own textures.
1975
+ units.length = 0;
1976
+ gl.enable(gl.BLEND);
1977
+ };
1978
+ // A shape is triangles over one white pixel. Every sample of that pixel is 1, whatever the filter and the
1979
+ // address, when every region of the page is the whole pixel: a draw of it then gives what a draw without a page
1980
+ // gives, so it takes that program and samples nothing. Asked once for a page of a record.
1981
+ const plainPages = new Map();
1982
+ const plainPage = (index) => {
1983
+ let plain = plainPages.get(index);
1984
+ if (plain === undefined) {
1985
+ plain =
1986
+ pageTextures.get(index).white &&
1987
+ frame.regions.every(region => region.pageIndex !== index ||
1988
+ (region.logicalWidth === 1 && region.logicalHeight === 1 && region.trimX === 0 && region.trimY === 0));
1989
+ plainPages.set(index, plain);
1990
+ }
1991
+ return plain;
1992
+ };
1993
+ const drawOne = (range) => {
1994
+ const draw = range.draw, page = draw.prepared.pageIndex;
1995
+ const plain = page === undefined || (draw.pages.length === 1 && plainPage(draw.pages[0]));
1996
+ const wanted = plain ? this.solidProgram : draw.pages.length > 1 ? this.pagedProgram : this.program;
1997
+ if (wanted !== program) {
1998
+ gl.useProgram(wanted);
1999
+ program = wanted;
2000
+ }
2001
+ if (draw.regionWindow >= 0 && draw.regionWindow !== bound) {
2002
+ bound = draw.regionWindow;
2003
+ gl.bindBufferRange(gl.UNIFORM_BUFFER, 1, record.leases[regions].handle.resource.value, bound * table.stride, SHARED_REGION_WINDOW_BYTES_2D);
2004
+ }
2005
+ gl.bindTexture(gl.TEXTURE_2D, page === undefined ? null : pageTextures.get(draw.pages[0]).native.value);
2006
+ for (let unit = 1; unit < draw.pages.length; unit++) {
2007
+ const index = draw.pages[unit];
2008
+ if (units[unit] === index)
2009
+ continue;
2010
+ gl.activeTexture(gl.TEXTURE0 + unit);
2011
+ gl.bindTexture(gl.TEXTURE_2D, pageTextures.get(index).native.value);
2012
+ gl.activeTexture(gl.TEXTURE0);
2013
+ units[unit] = index;
2014
+ }
2015
+ gl.bindBufferRange(gl.UNIFORM_BUFFER, 0, record.leases[uniform].handle.resource.value, range.uniformOffset, 128);
2016
+ const blend = sharedWebGL2BlendFactors(draw.prepared.material.blend);
2017
+ gl.blendFuncSeparate(...blend);
2018
+ gl.drawArrays(gl.TRIANGLES, range.firstVertex, draw.vertexCount);
2019
+ };
2020
+ this.drawLayers(record, width, height);
2021
+ bindDraw();
2022
+ if (record.storage.prepared.effects.groups.length === 0) {
2023
+ for (const range of arena.sharedRanges)
2024
+ drawOne(range);
2025
+ }
2026
+ else {
2027
+ const targets = layout.effectTargets.map(id => record.leases[id].handle.resource.value);
2028
+ const setTarget = (target, clear) => {
2029
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
2030
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, target, 0);
2031
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, null);
2032
+ native.workingAttachment(target, null);
2033
+ if (clear) {
2034
+ gl.clearColor(0, 0, 0, 0);
2035
+ gl.clear(gl.COLOR_BUFFER_BIT);
2036
+ }
2037
+ };
2038
+ const groups = record.storage.prepared.effects.groups, enters = new Map(groups.map(g => [g.enter, g])), exits = new Map(groups.map(g => [g.exit, g]));
2039
+ const ranges = new Map(arena.sharedRanges.map(range => [range.draw.prepared.command.ordinal, range]));
2040
+ const effectPass = (group, mode, target, source, glow) => {
2041
+ setTarget(target, mode !== 'composite');
2042
+ const program = this.effectPrograms.get(mode);
2043
+ gl.useProgram(program);
2044
+ gl.bindVertexArray(this.resolveVAO);
2045
+ gl.activeTexture(gl.TEXTURE0);
2046
+ gl.bindTexture(gl.TEXTURE_2D, source);
2047
+ gl.uniform1i(gl.getUniformLocation(program, 'sourceTexture'), 0);
2048
+ if (mode === 'composite') {
2049
+ gl.activeTexture(gl.TEXTURE1);
2050
+ gl.bindSampler(1, null);
2051
+ gl.bindTexture(gl.TEXTURE_2D, group.maskPageIndex === undefined
2052
+ ? source
2053
+ : pageTextures.get(group.maskPageIndex).native.value);
2054
+ gl.uniform1i(gl.getUniformLocation(program, 'maskTexture'), 1);
2055
+ gl.activeTexture(gl.TEXTURE0 + 2);
2056
+ gl.bindSampler(2, null);
2057
+ gl.bindTexture(gl.TEXTURE_2D, glow ?? source);
2058
+ gl.uniform1i(gl.getUniformLocation(program, 'glowTexture'), 2);
2059
+ gl.activeTexture(gl.TEXTURE0);
2060
+ gl.enable(gl.BLEND);
2061
+ gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
2062
+ }
2063
+ else
2064
+ gl.disable(gl.BLEND);
2065
+ gl.bindBufferRange(gl.UNIFORM_BUFFER, 0, record.leases[layout.effectUniforms[groups.indexOf(group)]].handle.resource.value, 0, EFFECT_UNIFORM_BYTES);
2066
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
2067
+ gl.activeTexture(gl.TEXTURE0 + 2);
2068
+ gl.bindTexture(gl.TEXTURE_2D, null);
2069
+ gl.activeTexture(gl.TEXTURE1);
2070
+ gl.bindTexture(gl.TEXTURE_2D, null);
2071
+ gl.activeTexture(gl.TEXTURE0);
2072
+ gl.bindTexture(gl.TEXTURE_2D, null);
2073
+ };
2074
+ for (const command of frame.commands) {
2075
+ const enter = enters.get(command.ordinal), exit = exits.get(command.ordinal);
2076
+ if (enter) {
2077
+ setTarget(targets[(enter.depth - 1) * 2], true);
2078
+ bindDraw();
2079
+ }
2080
+ else if (exit) {
2081
+ const source = targets[(exit.depth - 1) * 2], scratch = targets[(exit.depth - 1) * 2 + 1];
2082
+ if (exit.radius > 0) {
2083
+ effectPass(exit, 'horizontal', scratch, source);
2084
+ effectPass(exit, 'vertical', source, scratch);
2085
+ }
2086
+ // A glow or outline: the group's alpha spread across into the scratch target; the composite spreads it down.
2087
+ if (exit.spread >= 0)
2088
+ effectPass(exit, 'spread', scratch, source);
2089
+ const parent = exit.depth === 1 ? colorTexture : targets[(exit.depth - 2) * 2];
2090
+ effectPass(exit, 'composite', parent, source, scratch);
2091
+ bindDraw();
2092
+ }
2093
+ else {
2094
+ const range = ranges.get(command.ordinal);
2095
+ if (range)
2096
+ drawOne(range);
2097
+ }
2098
+ }
2099
+ }
2100
+ // No page stays bound to a unit only a batch of several pages uses.
2101
+ for (let unit = 1; unit < units.length; unit++)
2102
+ if (units[unit] !== undefined) {
2103
+ gl.activeTexture(gl.TEXTURE0 + unit);
2104
+ gl.bindTexture(gl.TEXTURE_2D, null);
2105
+ gl.activeTexture(gl.TEXTURE0);
2106
+ }
2107
+ if (record.layerWrite) {
2108
+ native.check();
2109
+ return;
2110
+ }
2111
+ gl.disable(gl.BLEND);
2112
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
2113
+ gl.drawBuffers([gl.BACK]);
2114
+ native.attachment(false);
2115
+ gl.useProgram(this.resolveProgram);
2116
+ gl.bindVertexArray(this.resolveVAO);
2117
+ gl.bindTexture(gl.TEXTURE_2D, colorTexture);
2118
+ gl.uniform1i(gl.getUniformLocation(this.resolveProgram, 'workingTexture'), 0);
2119
+ gl.uniform1i(gl.getUniformLocation(this.resolveProgram, 'opaque'), this.options.outputAlpha === 'opaque' ? 1 : 0);
2120
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
2121
+ if (record.ticket) {
2122
+ record.pbo = native.create('Buffer', record.storage.staging);
2123
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, record.pbo.value);
2124
+ gl.bufferData(gl.PIXEL_PACK_BUFFER, record.storage.staging, gl.STREAM_READ);
2125
+ gl.readBuffer(gl.BACK);
2126
+ gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, 0);
2127
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
2128
+ }
2129
+ native.check();
2130
+ }
2131
+ disposeHandle(handle, native, pool) {
2132
+ if (this.settledHandles.has(handle))
2133
+ return;
2134
+ pool.detach(handle);
2135
+ const safe = native.cleanup(handle.resource);
2136
+ if (native.invalidated) {
2137
+ native.lose();
2138
+ pool.invalidate();
2139
+ this.onLoss();
2140
+ }
2141
+ pool.settled(handle, safe ? (handle.resource.outcome === 'context-invalidated' ? 'context-invalidated' : 'destroyed') : 'unknown');
2142
+ this.settledHandles.add(handle);
2143
+ if (!safe)
2144
+ this.unsafe = true;
2145
+ }
2146
+ schedulePump() {
2147
+ if (this.pump !== undefined ||
2148
+ ![...this.records].some(record => !record.retired &&
2149
+ (!record.upload || record.sync || record.failure || record.upload.control.phase !== 'ready')))
2150
+ return;
2151
+ this.pump = schedule(() => {
2152
+ this.pump = undefined;
2153
+ this.poll();
2154
+ }, 0);
2155
+ }
2156
+ detachContainers(native) {
2157
+ const gl = native.gl;
2158
+ // Zero offsets explicitly clear fixed VAO references without a placeholder buffer.
2159
+ for (const [vao, layout] of [
2160
+ [
2161
+ this.drawVAO,
2162
+ [
2163
+ [0, 2],
2164
+ [1, 2],
2165
+ [2, 4],
2166
+ [3, 3],
2167
+ [4, 2]
2168
+ ]
2169
+ ]
2170
+ ]) {
2171
+ if (!vao)
2172
+ continue;
2173
+ gl.bindVertexArray(vao);
2174
+ gl.bindBuffer(gl.ARRAY_BUFFER, null);
2175
+ for (const [index, size] of layout) {
2176
+ gl.disableVertexAttribArray(index);
2177
+ gl.vertexAttribPointer(index, size, gl.FLOAT, false, 0, 0);
2178
+ gl.vertexAttribDivisor(index, 0);
2179
+ }
2180
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
2181
+ }
2182
+ gl.bindVertexArray(null);
2183
+ gl.bindBuffer(gl.ARRAY_BUFFER, null);
2184
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
2185
+ gl.bindBufferRange(gl.UNIFORM_BUFFER, 0, null, 0, 128);
2186
+ gl.bindBufferRange(gl.UNIFORM_BUFFER, 1, null, 0, SHARED_REGION_WINDOW_BYTES_2D);
2187
+ gl.bindBuffer(gl.UNIFORM_BUFFER, null);
2188
+ if (this.options.enableEffects) {
2189
+ gl.activeTexture(gl.TEXTURE1);
2190
+ gl.bindTexture(gl.TEXTURE_2D, null);
2191
+ }
2192
+ gl.activeTexture(gl.TEXTURE0);
2193
+ gl.bindTexture(gl.TEXTURE_2D, null);
2194
+ gl.bindRenderbuffer(gl.RENDERBUFFER, null);
2195
+ if (this.framebuffer) {
2196
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
2197
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, null, 0);
2198
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, null);
2199
+ }
2200
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
2201
+ gl.useProgram(null);
2202
+ }
2203
+ poll() {
2204
+ if (this.busy) {
2205
+ this.schedulePump();
2206
+ return;
2207
+ }
2208
+ this.busy = true;
2209
+ this.cpu = deferred();
2210
+ this.phase = 'poll';
2211
+ let uploaded = false;
2212
+ try {
2213
+ for (const record of [...this.records]) {
2214
+ if (record.retired)
2215
+ continue;
2216
+ if (record.native.invalidated) {
2217
+ this.retire(record);
2218
+ continue;
2219
+ }
2220
+ const work = record.upload;
2221
+ if (work && !work.control.transferred && !record.sync) {
2222
+ if (record.failure) {
2223
+ this.retire(record);
2224
+ continue;
2225
+ }
2226
+ if (work.control.phase !== 'ready' && !uploaded) {
2227
+ uploaded = true;
2228
+ this.uploadChunk(record);
2229
+ }
2230
+ continue;
2231
+ }
2232
+ if (!record.sync)
2233
+ continue;
2234
+ try {
2235
+ if (clock() >= record.deadline)
2236
+ throw glFailure('WEBGL2_SYNC_TIMEOUT');
2237
+ const native = record.native, gl = native.gl, started = native.startTiming();
2238
+ let result;
2239
+ if (started !== undefined)
2240
+ native.timingSerial = record.serial || null;
2241
+ try {
2242
+ result = gl.clientWaitSync(record.sync.value, 0, 0);
2243
+ }
2244
+ finally {
2245
+ native.finishTiming('fence-poll', started);
2246
+ }
2247
+ if (result === gl.TIMEOUT_EXPIRED) {
2248
+ if (clock() < record.deadline)
2249
+ continue;
2250
+ throw glFailure('WEBGL2_SYNC_TIMEOUT');
2251
+ }
2252
+ if (result !== gl.ALREADY_SIGNALED && result !== gl.CONDITION_SATISFIED)
2253
+ throw glFailure('WEBGL2_SYNC_FAILED', result);
2254
+ const checked = native.startTiming();
2255
+ try {
2256
+ native.check();
2257
+ }
2258
+ finally {
2259
+ native.finishTiming('completion-error-query', checked);
2260
+ }
2261
+ if (clock() >= record.deadline)
2262
+ throw glFailure('WEBGL2_SYNC_TIMEOUT');
2263
+ if (work && !work.control.transferred) {
2264
+ const sync = record.sync;
2265
+ record.sync = undefined;
2266
+ if (!record.native.cleanup(sync))
2267
+ throw glFailure('WEBGL2_CLOSE_UNSAFE', record.native.cleanupFailure?.cause);
2268
+ if (record.native.invalidated) {
2269
+ record.native.lose();
2270
+ this.onLoss();
2271
+ this.retire(record);
2272
+ continue;
2273
+ }
2274
+ if (record.failure) {
2275
+ this.retire(record);
2276
+ continue;
2277
+ }
2278
+ this.stageLife(work.control.token);
2279
+ if (clock() >= work.control.end) {
2280
+ this.revokeUpload(work.control, glFailure('WEBGL2_UPLOAD_EXPIRED'));
2281
+ this.retire(record);
2282
+ continue;
2283
+ }
2284
+ if (work.writeIndex === work.writes.length) {
2285
+ work.control.phase = 'ready';
2286
+ work.control.ready.resolve(Object.freeze({ generation: record.generation, frameId: work.control.frameId }));
2287
+ }
2288
+ continue;
2289
+ }
2290
+ if (record.failure)
2291
+ record.completion?.reject(record.failure);
2292
+ else
2293
+ record.completion?.resolve();
2294
+ if (record.ticket && !record.failure) {
2295
+ const { width, height, frame } = record.storage.prepared, bytes = new Uint8Array(record.storage.output);
2296
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, record.pbo.value);
2297
+ gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, bytes);
2298
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
2299
+ record.native.check();
2300
+ // Flip in place with scalar swaps: no additional full-image or row allocation.
2301
+ const pitch = 4 * width;
2302
+ for (let y = 0; y < Math.floor(height / 2); y++)
2303
+ for (let x = 0; x < pitch; x++) {
2304
+ const a = y * pitch + x, b = (height - 1 - y) * pitch + x, temp = bytes[a];
2305
+ bytes[a] = bytes[b];
2306
+ bytes[b] = temp;
2307
+ }
2308
+ if (clock() >= record.deadline)
2309
+ throw glFailure('WEBGL2_SYNC_TIMEOUT');
2310
+ record.readback = Object.freeze({
2311
+ generation: record.generation,
2312
+ serial: record.serial,
2313
+ frameId: frame.frameId,
2314
+ width,
2315
+ height,
2316
+ format: 'rgba8unorm',
2317
+ sourceFormat: 'rgba8unorm',
2318
+ colorSpace: 'srgb',
2319
+ alphaMode: this.options.outputAlpha,
2320
+ bytes
2321
+ });
2322
+ }
2323
+ }
2324
+ catch (cause) {
2325
+ record.failure ??= this.note(isGLFailure(cause) ? cause.code : 'WEBGL2_READBACK_FAILED', cause, 'readback', record.serial || null);
2326
+ if (!record.native.invalidated) {
2327
+ this.unsafe = true;
2328
+ this.markUnknown(record);
2329
+ }
2330
+ if (this.state === 'active') {
2331
+ this.state = 'failed';
2332
+ this.revokeUploads(record.failure);
2333
+ }
2334
+ }
2335
+ finally {
2336
+ if (this.frameTiming)
2337
+ record.native.timingSerial = null;
2338
+ }
2339
+ this.retire(record);
2340
+ }
2341
+ }
2342
+ finally {
2343
+ this.phase = undefined;
2344
+ this.busy = false;
2345
+ this.retireLost();
2346
+ this.cpu.resolve();
2347
+ this.schedulePump();
2348
+ }
2349
+ }
2350
+ markUnknown(record) {
2351
+ // A failed completion proof keeps every possibly in-use allocation charged.
2352
+ record.pool.invalidate();
2353
+ for (const lease of record.leases)
2354
+ if (lease && !this.settledHandles.has(lease.handle)) {
2355
+ lease.handle.resource.outcome = 'unknown';
2356
+ record.native.observeResource(lease.handle.resource);
2357
+ record.pool.settled(lease.handle, 'unknown');
2358
+ this.settledHandles.add(lease.handle);
2359
+ }
2360
+ for (const owner of record.rawOwners)
2361
+ if (owner.outcome === 'owned') {
2362
+ owner.outcome = 'unknown';
2363
+ record.native.observeResource(owner);
2364
+ }
2365
+ for (const page of record.pages) {
2366
+ page.native.outcome = 'unknown';
2367
+ record.native.observeResource(page.native);
2368
+ }
2369
+ for (const read of record.layerReads ?? []) {
2370
+ read.revision.owner.outcome = 'unknown';
2371
+ record.native.observeResource(read.revision.owner);
2372
+ }
2373
+ if (record.pbo) {
2374
+ record.pbo.outcome = 'unknown';
2375
+ record.native.observeResource(record.pbo);
2376
+ }
2377
+ if (record.sync) {
2378
+ record.sync.outcome = 'unknown';
2379
+ record.native.observeResource(record.sync);
2380
+ }
2381
+ }
2382
+ retire(record) {
2383
+ if (record.retired)
2384
+ return;
2385
+ record.retired = true;
2386
+ const native = record.native, work = record.upload;
2387
+ const started = native.startTiming(), previousSerial = native.timingSerial;
2388
+ if (started !== undefined)
2389
+ native.timingSerial = record.serial || null;
2390
+ if (work) {
2391
+ work.control.phase = 'retired';
2392
+ this.clearUploadAdmission(work.control);
2393
+ }
2394
+ try {
2395
+ if (work?.claimed)
2396
+ for (const victim of work.plan.victims)
2397
+ this.disposeHandle(victim, native, record.pool);
2398
+ if (native.invalidated)
2399
+ record.pool.invalidate();
2400
+ if (record.failure || this.state !== 'active' || native.invalidated || this.unsafe) {
2401
+ for (const lease of record.leases)
2402
+ if (lease)
2403
+ this.disposeHandle(lease.handle, native, record.pool);
2404
+ }
2405
+ else {
2406
+ const returns = record.pool.reserveReturns(record.leases);
2407
+ try {
2408
+ record.pool.publishReturns(returns);
2409
+ }
2410
+ catch (cause) {
2411
+ for (const handle of record.pool.cancelReturns(returns))
2412
+ this.disposeHandle(handle, native, record.pool);
2413
+ throw cause;
2414
+ }
2415
+ for (const handle of returns.transient)
2416
+ this.disposeHandle(handle, native, record.pool);
2417
+ }
2418
+ for (const page of record.pages) {
2419
+ if (this.pages.get(page.source) === page && page.pins === 1) {
2420
+ this.resourcePinnedBytes -= page.source.byteLength;
2421
+ this.resourcePinnedEntries--;
2422
+ }
2423
+ page.pins--;
2424
+ this.sampleResourceImages();
2425
+ if (!record.failure && !native.invalidated && this.state === 'active' && !this.unsafe) {
2426
+ const existing = this.pages.get(page.source);
2427
+ if (existing === page)
2428
+ continue; // An existing residence adds no new bytes or entry.
2429
+ if (existing) {
2430
+ if (page.pins === 0 && !native.cleanup(page.native))
2431
+ this.unsafe = true;
2432
+ continue;
2433
+ }
2434
+ let bytes = 0;
2435
+ for (const current of this.pages.values())
2436
+ bytes += current.source.byteLength;
2437
+ for (const [key, victim] of this.pages) {
2438
+ if ((this.pages.size < 256 && bytes + page.source.byteLength <= this.options.maxReadyPageBytes) ||
2439
+ victim.pins > 0)
2440
+ continue;
2441
+ this.pages.delete(key);
2442
+ bytes -= victim.source.byteLength;
2443
+ this.resourceReadyBytes -= victim.source.byteLength;
2444
+ this.resourceTotal('readyCapacityEvictions', 1);
2445
+ this.sampleResourceImages();
2446
+ if (!native.cleanup(victim.native))
2447
+ this.unsafe = true;
2448
+ }
2449
+ if (!this.unsafe &&
2450
+ this.pages.size < 256 &&
2451
+ bytes + page.source.byteLength <= this.options.maxReadyPageBytes) {
2452
+ page.ready = true;
2453
+ this.pages.set(page.source, page);
2454
+ this.resourceReadyBytes += page.source.byteLength;
2455
+ if (page.pins > 0) {
2456
+ this.resourcePinnedBytes += page.source.byteLength;
2457
+ this.resourcePinnedEntries++;
2458
+ }
2459
+ this.sampleResourceImages();
2460
+ }
2461
+ else if (page.pins === 0 && !native.cleanup(page.native))
2462
+ this.unsafe = true;
2463
+ }
2464
+ else if (page.pins === 0) {
2465
+ if (this.pages.get(page.source) === page) {
2466
+ this.pages.delete(page.source);
2467
+ this.resourceReadyBytes -= page.source.byteLength;
2468
+ this.sampleResourceImages();
2469
+ }
2470
+ if (!native.cleanup(page.native))
2471
+ this.unsafe = true;
2472
+ }
2473
+ }
2474
+ if (record.pbo && !native.cleanup(record.pbo))
2475
+ this.unsafe = true;
2476
+ if (record.sync && !native.cleanup(record.sync))
2477
+ this.unsafe = true;
2478
+ if (work || record.layerWrite)
2479
+ for (const owner of record.rawOwners) {
2480
+ // A native create may return an owner and then fail its gate before
2481
+ // registration. This original record still owns that raw result.
2482
+ if (owner === record.layerWrite?.revision?.owner ||
2483
+ owner.accounting === 'retention' ||
2484
+ record.pages.some(page => page.native === owner && (page.pins > 0 || this.pages.get(page.source) === page)))
2485
+ continue;
2486
+ if (!native.cleanup(owner))
2487
+ this.unsafe = true;
2488
+ }
2489
+ }
2490
+ catch (cause) {
2491
+ this.unsafe = true;
2492
+ record.failure ??= this.note('WEBGL2_CLOSE_UNSAFE', cause, 'cleanup', record.serial);
2493
+ }
2494
+ finally {
2495
+ if (native.cleanupFailure)
2496
+ this.unsafe = true;
2497
+ this.finishLayerRecord(record);
2498
+ if (this.unsafe) {
2499
+ record.failure ??= this.note('WEBGL2_CLOSE_UNSAFE', native.cleanupFailure?.cause, 'cleanup', record.serial);
2500
+ if (this.state !== 'closing' && this.state !== 'closed' && this.state !== 'stopped') {
2501
+ this.state = 'failed';
2502
+ this.revokeUploads(record.failure);
2503
+ }
2504
+ }
2505
+ this.resourceCpu.canonicalBytes -= record.canonicalBytes;
2506
+ this.resourceNative.reservedPageBytes -= record.reservedPageBytes;
2507
+ record.reservedPageBytes = 0;
2508
+ record.projections = [];
2509
+ if (work)
2510
+ this.scratch.release(work.batch);
2511
+ this.records.delete(record);
2512
+ if (record.ticket) {
2513
+ if (record.failure)
2514
+ record.ticket.reject(record.failure);
2515
+ else if (record.readback)
2516
+ record.ticket.resolve(record.readback);
2517
+ else
2518
+ record.ticket.reject(glFailure('WEBGL2_READBACK_FAILED'));
2519
+ if (this.ticket === record.ticket)
2520
+ this.ticket = undefined;
2521
+ }
2522
+ if (record.failure)
2523
+ record.done.reject(record.failure);
2524
+ else
2525
+ record.done.resolve();
2526
+ if (record.failure)
2527
+ record.completion?.reject(record.failure);
2528
+ else
2529
+ record.completion?.resolve();
2530
+ if (work) {
2531
+ if (record.failure) {
2532
+ work.control.failure ??= record.failure;
2533
+ work.control.ready.reject(record.failure);
2534
+ }
2535
+ if (work.control.signal)
2536
+ work.control.signal.control = undefined;
2537
+ work.control.signal = undefined;
2538
+ work.control.record = undefined;
2539
+ work.writes.length = 0;
2540
+ work.layout.pageTextures.clear();
2541
+ }
2542
+ if (started !== undefined) {
2543
+ native.finishTiming('retire', started);
2544
+ native.timingSerial = previousSerial;
2545
+ }
2546
+ }
2547
+ }
2548
+ close() {
2549
+ if (this.closing)
2550
+ return this.closing;
2551
+ const barrier = deferred();
2552
+ this.closing = barrier.promise;
2553
+ this.state = 'closing';
2554
+ this.cleanupOutcome = 'pending';
2555
+ this.cancelRestore();
2556
+ this.retention.clear();
2557
+ const failure = glFailure('WEBGL2_CLOSED');
2558
+ this.ready?.reject(failure);
2559
+ this.rejectUnbound(failure);
2560
+ this.revokeUploads(failure);
2561
+ for (const slot of this.layers.values())
2562
+ this.dropLayer(slot);
2563
+ this.layers.clear();
2564
+ const cpu = this.cpu.promise;
2565
+ void cpu.then(async () => {
2566
+ await Promise.allSettled([...this.records].map(record => record.done.promise));
2567
+ let failure = this.native?.cleanupFailure;
2568
+ const attempt = (cleanup) => {
2569
+ try {
2570
+ cleanup();
2571
+ }
2572
+ catch (cause) {
2573
+ this.unsafe = true;
2574
+ failure ??= { cause };
2575
+ }
2576
+ };
2577
+ // Teardown steps are independent; a failed detach must not abandon known owners.
2578
+ attempt(() => {
2579
+ if (this.native && !this.native.invalidated) {
2580
+ try {
2581
+ this.detachContainers(this.native);
2582
+ this.native.check();
2583
+ }
2584
+ catch (cause) {
2585
+ if (!this.native.invalidated)
2586
+ throw cause;
2587
+ }
2588
+ }
2589
+ });
2590
+ attempt(() => {
2591
+ for (const handle of this.pool.detachIdleForClose())
2592
+ attempt(() => this.disposeHandle(handle, this.native, this.pool));
2593
+ });
2594
+ attempt(() => this.pool.invalidate());
2595
+ this.pages.clear();
2596
+ this.resourceReadyBytes = 0;
2597
+ this.resourcePinnedBytes = 0;
2598
+ this.resourcePinnedEntries = 0;
2599
+ this.sampleResourceImages();
2600
+ attempt(() => this.sweepLayers());
2601
+ attempt(() => {
2602
+ if (this.native && !this.native.cleanupAll())
2603
+ this.unsafe = true;
2604
+ });
2605
+ failure ??= this.native?.cleanupFailure;
2606
+ attempt(() => this.removeListeners?.());
2607
+ this.removeListeners = undefined;
2608
+ if (this.pump !== undefined) {
2609
+ const pump = this.pump;
2610
+ this.pump = undefined;
2611
+ attempt(() => cancel(pump));
2612
+ }
2613
+ this.state = 'closed';
2614
+ this.cleanupOutcome = this.unsafe ? 'unsafe' : 'safe';
2615
+ if (this.unsafe)
2616
+ barrier.reject(glFailure('WEBGL2_CLOSE_UNSAFE', failure?.cause));
2617
+ else
2618
+ barrier.resolve();
2619
+ });
2620
+ return this.closing;
2621
+ }
2622
+ getSessionStatus() {
2623
+ return Object.freeze({
2624
+ state: this.state === 'active' ? 'ready' : this.state,
2625
+ generation: this.generation,
2626
+ attempt: this.attempt,
2627
+ firstFailure: this.firstFailure,
2628
+ generationFailure: this.generationFailure
2629
+ });
2630
+ }
2631
+ getStatus() {
2632
+ const owner = this.snapshot();
2633
+ return Object.freeze({
2634
+ state: this.state,
2635
+ generation: this.generation,
2636
+ lastSerial: this.serial,
2637
+ pendingFrames: owner.pendingFrames,
2638
+ pendingUploadBytes: owner.pendingUploadBytes,
2639
+ pendingReadbackBytes: owner.pendingReadbackBytes,
2640
+ firstFailure: this.firstFailure,
2641
+ generationFailure: this.generationFailure,
2642
+ callbackFailureCount: this.callbackFailureCount,
2643
+ lastCallbackFailure: this.lastCallbackFailure,
2644
+ cleanupOutcome: this.cleanupOutcome
2645
+ });
2646
+ }
2647
+ getSharedStatus() {
2648
+ const owner = this.snapshot(), unknown = this.native?.unknown() ?? { bytes: 0, objects: 0 }, retention = this.pool.getStatus();
2649
+ return Object.freeze({
2650
+ host: this.getStatus(),
2651
+ pendingGeometryBytes: owner.pendingGeometryBytes,
2652
+ pendingColorBytes: owner.pendingColorBytes,
2653
+ pendingCanonicalBytes: owner.pendingCanonicalBytes,
2654
+ resources: this.resourceStatus(),
2655
+ retention: Object.freeze({
2656
+ idleBytes: retention.idleBytes,
2657
+ idleEntries: retention.idleEntries,
2658
+ reservedBytes: retention.reservedBytes,
2659
+ reservedEntries: retention.reservedEntries,
2660
+ unknownBytes: retention.unknownBytes,
2661
+ unknownEntries: retention.unknownEntries,
2662
+ unknownNativeBytes: this.retiredUnknownBytes + unknown.bytes,
2663
+ unknownNativeObjects: this.retiredUnknownObjects + unknown.objects
2664
+ })
2665
+ });
2666
+ }
2667
+ }
2668
+ /** Explicit compatibility backend; the Engine retains the original shared-frame contract. */
2669
+ export function createSharedWebGL2Host(options) {
2670
+ return new SharedGLHost(options);
2671
+ }
2672
+ //# sourceMappingURL=WebGL2Host.js.map