@egret/engine 0.0.0-stage → 7.0.2

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