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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (575) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +21 -0
  3. package/README.md +101 -2
  4. package/README.zh-CN.md +102 -0
  5. package/dist/Engine.d.ts +77 -0
  6. package/dist/Engine.js +464 -0
  7. package/dist/animation/index.d.ts +6 -0
  8. package/dist/animation/index.js +5 -0
  9. package/dist/animation/sequenceController.d.ts +22 -0
  10. package/dist/animation/sequenceController.js +618 -0
  11. package/dist/animation/sequenceCoordinator.d.ts +26 -0
  12. package/dist/animation/sequenceCoordinator.js +161 -0
  13. package/dist/animation/sequenceInput.d.ts +25 -0
  14. package/dist/animation/sequenceInput.js +108 -0
  15. package/dist/animation/sequenceMath.d.ts +35 -0
  16. package/dist/animation/sequenceMath.js +164 -0
  17. package/dist/animation/sequenceResetSlot.d.ts +7 -0
  18. package/dist/animation/sequenceResetSlot.js +367 -0
  19. package/dist/animation/sequenceResetTypes.d.ts +42 -0
  20. package/dist/animation/sequenceResetTypes.js +2 -0
  21. package/dist/animation/types.d.ts +69 -0
  22. package/dist/animation/types.js +2 -0
  23. package/dist/assetBundle.d.ts +52 -0
  24. package/dist/assetBundle.js +173 -0
  25. package/dist/assetGroup.d.ts +17 -0
  26. package/dist/assetGroup.js +332 -0
  27. package/dist/assetGroupTypes.d.ts +15 -0
  28. package/dist/assetGroupTypes.js +2 -0
  29. package/dist/audio.d.ts +4 -0
  30. package/dist/audio.js +4 -0
  31. package/dist/audioCues.d.ts +43 -0
  32. package/dist/audioCues.js +127 -0
  33. package/dist/audioMixer.d.ts +7 -0
  34. package/dist/audioMixer.js +785 -0
  35. package/dist/audioTypes.d.ts +233 -0
  36. package/dist/audioTypes.js +3 -0
  37. package/dist/bitmapBindingTicket.d.ts +24 -0
  38. package/dist/bitmapBindingTicket.js +215 -0
  39. package/dist/bitmapButton.d.ts +4 -0
  40. package/dist/bitmapButton.js +407 -0
  41. package/dist/bitmapButtonTypes.d.ts +29 -0
  42. package/dist/bitmapButtonTypes.js +2 -0
  43. package/dist/bitmapFontParse.d.ts +10 -0
  44. package/dist/bitmapFontParse.js +246 -0
  45. package/dist/bitmapFontTypes.d.ts +109 -0
  46. package/dist/bitmapFontTypes.js +2 -0
  47. package/dist/bitmapResourceSlot.d.ts +25 -0
  48. package/dist/bitmapResourceSlot.js +340 -0
  49. package/dist/bitmapText.d.ts +6 -0
  50. package/dist/bitmapText.js +320 -0
  51. package/dist/bitmapfont.d.ts +5 -0
  52. package/dist/bitmapfont.js +5 -0
  53. package/dist/camera.d.ts +4 -0
  54. package/dist/camera.js +4 -0
  55. package/dist/camera2d.d.ts +7 -0
  56. package/dist/camera2d.js +411 -0
  57. package/dist/cameraTypes.d.ts +114 -0
  58. package/dist/cameraTypes.js +2 -0
  59. package/dist/closeHost.d.ts +4 -0
  60. package/dist/closeHost.js +66 -0
  61. package/dist/contentArtifacts.d.ts +12 -0
  62. package/dist/contentArtifacts.js +153 -0
  63. package/dist/contentAtlasPages.d.ts +13 -0
  64. package/dist/contentAtlasPages.js +117 -0
  65. package/dist/contentLoader.d.ts +6 -0
  66. package/dist/contentLoader.js +327 -0
  67. package/dist/contentTypes.d.ts +33 -0
  68. package/dist/contentTypes.js +2 -0
  69. package/dist/createEngine.d.ts +7 -0
  70. package/dist/createEngine.js +25 -0
  71. package/dist/createEngineForProfile.d.ts +5 -0
  72. package/dist/createEngineForProfile.js +42 -0
  73. package/dist/displaySubtreeTicket.d.ts +25 -0
  74. package/dist/displaySubtreeTicket.js +76 -0
  75. package/dist/fontContentLoader.d.ts +6 -0
  76. package/dist/fontContentLoader.js +298 -0
  77. package/dist/fontContentTypes.d.ts +34 -0
  78. package/dist/fontContentTypes.js +2 -0
  79. package/dist/gameClock.d.ts +24 -0
  80. package/dist/gameClock.js +246 -0
  81. package/dist/gameClockTypes.d.ts +31 -0
  82. package/dist/gameClockTypes.js +2 -0
  83. package/dist/gameRun.d.ts +50 -0
  84. package/dist/gameRun.js +97 -0
  85. package/dist/gamepad.d.ts +5 -0
  86. package/dist/gamepad.js +5 -0
  87. package/dist/gamepadInput.d.ts +4 -0
  88. package/dist/gamepadInput.js +281 -0
  89. package/dist/gamepadKeys.d.ts +4 -0
  90. package/dist/gamepadKeys.js +205 -0
  91. package/dist/gamepadTypes.d.ts +134 -0
  92. package/dist/gamepadTypes.js +3 -0
  93. package/dist/hover.d.ts +4 -0
  94. package/dist/hover.js +4 -0
  95. package/dist/hoverInput.d.ts +8 -0
  96. package/dist/hoverInput.js +503 -0
  97. package/dist/hoverInputTypes.d.ts +119 -0
  98. package/dist/hoverInputTypes.js +2 -0
  99. package/dist/index.d.ts +49 -0
  100. package/dist/index.js +20 -0
  101. package/dist/input.d.ts +6 -0
  102. package/dist/input.js +5 -0
  103. package/dist/inputActions.d.ts +81 -0
  104. package/dist/inputActions.js +330 -0
  105. package/dist/internal/contentFactoryState.d.ts +19 -0
  106. package/dist/internal/contentFactoryState.js +42 -0
  107. package/dist/internal/mouseInputFactoryState.d.ts +57 -0
  108. package/dist/internal/mouseInputFactoryState.js +125 -0
  109. package/dist/internal/sequenceControllerFactoryState.d.ts +42 -0
  110. package/dist/internal/sequenceControllerFactoryState.js +98 -0
  111. package/dist/internal/textFieldFactoryState.d.ts +11 -0
  112. package/dist/internal/textFieldFactoryState.js +32 -0
  113. package/dist/internal/texturedFrameState.d.ts +4 -0
  114. package/dist/internal/texturedFrameState.js +12 -0
  115. package/dist/internal/uiFactoryState.d.ts +64 -0
  116. package/dist/internal/uiFactoryState.js +157 -0
  117. package/dist/internal/uiRootState.d.ts +67 -0
  118. package/dist/internal/uiRootState.js +103 -0
  119. package/dist/keyboardInput.d.ts +12 -0
  120. package/dist/keyboardInput.js +578 -0
  121. package/dist/keyboardInputTypes.d.ts +81 -0
  122. package/dist/keyboardInputTypes.js +2 -0
  123. package/dist/kit.d.ts +14 -0
  124. package/dist/kit.js +9 -0
  125. package/dist/layout.d.ts +5 -0
  126. package/dist/layout.js +132 -0
  127. package/dist/layoutTypes.d.ts +28 -0
  128. package/dist/layoutTypes.js +2 -0
  129. package/dist/manifestAssetGroup.d.ts +10 -0
  130. package/dist/manifestAssetGroup.js +477 -0
  131. package/dist/manifestResourceState.d.ts +16 -0
  132. package/dist/manifestResourceState.js +57 -0
  133. package/dist/manifestResourceTypes.d.ts +25 -0
  134. package/dist/manifestResourceTypes.js +2 -0
  135. package/dist/motion.d.ts +33 -0
  136. package/dist/motion.js +206 -0
  137. package/dist/mouseInput.d.ts +102 -0
  138. package/dist/mouseInput.js +562 -0
  139. package/dist/mouseInputTypes.d.ts +37 -0
  140. package/dist/mouseInputTypes.js +2 -0
  141. package/dist/paragraph.d.ts +8 -0
  142. package/dist/paragraph.js +7 -0
  143. package/dist/particleEmitter.d.ts +4 -0
  144. package/dist/particleEmitter.js +292 -0
  145. package/dist/particleTypes.d.ts +107 -0
  146. package/dist/particleTypes.js +2 -0
  147. package/dist/particles.d.ts +4 -0
  148. package/dist/particles.js +4 -0
  149. package/dist/physics2d.d.ts +4 -0
  150. package/dist/physics2d.js +4 -0
  151. package/dist/physics2dGeometry.d.ts +39 -0
  152. package/dist/physics2dGeometry.js +230 -0
  153. package/dist/physics2dTypes.d.ts +167 -0
  154. package/dist/physics2dTypes.js +2 -0
  155. package/dist/physics2dWorld.d.ts +4 -0
  156. package/dist/physics2dWorld.js +623 -0
  157. package/dist/pointerInput.d.ts +11 -0
  158. package/dist/pointerInput.js +299 -0
  159. package/dist/pointerInputTypes.d.ts +38 -0
  160. package/dist/pointerInputTypes.js +2 -0
  161. package/dist/random.d.ts +29 -0
  162. package/dist/random.js +131 -0
  163. package/dist/rendering/ownedPreparationFailure2D.d.ts +5 -0
  164. package/dist/rendering/ownedPreparationFailure2D.js +33 -0
  165. package/dist/rendering/packSharedDraws2D.d.ts +50 -0
  166. package/dist/rendering/packSharedDraws2D.js +331 -0
  167. package/dist/rendering/packedOrientation.d.ts +4 -0
  168. package/dist/rendering/packedOrientation.js +7 -0
  169. package/dist/rendering/prepareRectangles2D.d.ts +92 -0
  170. package/dist/rendering/prepareRectangles2D.js +481 -0
  171. package/dist/rendering/prepareSharedDraws2D.d.ts +88 -0
  172. package/dist/rendering/prepareSharedDraws2D.js +652 -0
  173. package/dist/rendering/preparedBatches2D.d.ts +17 -0
  174. package/dist/rendering/preparedBatches2D.js +30 -0
  175. package/dist/rendering/preparedSharedBatches2D.d.ts +44 -0
  176. package/dist/rendering/preparedSharedBatches2D.js +247 -0
  177. package/dist/rendering/sharedColor2D.d.ts +18 -0
  178. package/dist/rendering/sharedColor2D.js +68 -0
  179. package/dist/rendering/sharedEffects2D.d.ts +23 -0
  180. package/dist/rendering/sharedEffects2D.js +118 -0
  181. package/dist/rendering/sharedPreparationRetention2D.d.ts +120 -0
  182. package/dist/rendering/sharedPreparationRetention2D.js +357 -0
  183. package/dist/rendering/srgbBytes.d.ts +3 -0
  184. package/dist/rendering/srgbBytes.js +64 -0
  185. package/dist/rendering/texturedPreparationBudget2D.d.ts +31 -0
  186. package/dist/rendering/texturedPreparationBudget2D.js +81 -0
  187. package/dist/rendering/world3d/Animation3D.d.ts +95 -0
  188. package/dist/rendering/world3d/Animation3D.js +380 -0
  189. package/dist/rendering/world3d/AnimationTexture3D.d.ts +157 -0
  190. package/dist/rendering/world3d/AnimationTexture3D.js +601 -0
  191. package/dist/rendering/world3d/Batch3D.d.ts +71 -0
  192. package/dist/rendering/world3d/Batch3D.js +329 -0
  193. package/dist/rendering/world3d/Camera3D.d.ts +57 -0
  194. package/dist/rendering/world3d/Camera3D.js +129 -0
  195. package/dist/rendering/world3d/Character3D.d.ts +123 -0
  196. package/dist/rendering/world3d/Character3D.js +303 -0
  197. package/dist/rendering/world3d/Cloth3D.d.ts +115 -0
  198. package/dist/rendering/world3d/Cloth3D.js +498 -0
  199. package/dist/rendering/world3d/Compression3D.d.ts +21 -0
  200. package/dist/rendering/world3d/Compression3D.js +702 -0
  201. package/dist/rendering/world3d/Curves3D.d.ts +111 -0
  202. package/dist/rendering/world3d/Curves3D.js +455 -0
  203. package/dist/rendering/world3d/Decal3D.d.ts +41 -0
  204. package/dist/rendering/world3d/Decal3D.js +241 -0
  205. package/dist/rendering/world3d/Geometry3D.d.ts +85 -0
  206. package/dist/rendering/world3d/Geometry3D.js +326 -0
  207. package/dist/rendering/world3d/GeometryBuilder3D.d.ts +51 -0
  208. package/dist/rendering/world3d/GeometryBuilder3D.js +196 -0
  209. package/dist/rendering/world3d/Gizmo3D.d.ts +75 -0
  210. package/dist/rendering/world3d/Gizmo3D.js +512 -0
  211. package/dist/rendering/world3d/Gltf3D.d.ts +67 -0
  212. package/dist/rendering/world3d/Gltf3D.js +976 -0
  213. package/dist/rendering/world3d/GpuParticles3D.d.ts +107 -0
  214. package/dist/rendering/world3d/GpuParticles3D.js +400 -0
  215. package/dist/rendering/world3d/Hdr3D.d.ts +33 -0
  216. package/dist/rendering/world3d/Hdr3D.js +190 -0
  217. package/dist/rendering/world3d/Jelly3D.d.ts +75 -0
  218. package/dist/rendering/world3d/Jelly3D.js +266 -0
  219. package/dist/rendering/world3d/Ktx23D.d.ts +27 -0
  220. package/dist/rendering/world3d/Ktx23D.js +112 -0
  221. package/dist/rendering/world3d/Light3D.d.ts +75 -0
  222. package/dist/rendering/world3d/Light3D.js +93 -0
  223. package/dist/rendering/world3d/Material3D.d.ts +243 -0
  224. package/dist/rendering/world3d/Material3D.js +267 -0
  225. package/dist/rendering/world3d/Mesh3D.d.ts +108 -0
  226. package/dist/rendering/world3d/Mesh3D.js +323 -0
  227. package/dist/rendering/world3d/Meshopt3D.d.ts +12 -0
  228. package/dist/rendering/world3d/Meshopt3D.js +275 -0
  229. package/dist/rendering/world3d/Navigation3D.d.ts +173 -0
  230. package/dist/rendering/world3d/Navigation3D.js +971 -0
  231. package/dist/rendering/world3d/Object3D.d.ts +107 -0
  232. package/dist/rendering/world3d/Object3D.js +305 -0
  233. package/dist/rendering/world3d/Particles3D.d.ts +85 -0
  234. package/dist/rendering/world3d/Particles3D.js +274 -0
  235. package/dist/rendering/world3d/Physics3D.d.ts +416 -0
  236. package/dist/rendering/world3d/Physics3D.js +2835 -0
  237. package/dist/rendering/world3d/PhysicsHull3D.d.ts +35 -0
  238. package/dist/rendering/world3d/PhysicsHull3D.js +227 -0
  239. package/dist/rendering/world3d/PhysicsMesh3D.d.ts +39 -0
  240. package/dist/rendering/world3d/PhysicsMesh3D.js +338 -0
  241. package/dist/rendering/world3d/PhysicsQueries3D.d.ts +24 -0
  242. package/dist/rendering/world3d/PhysicsQueries3D.js +323 -0
  243. package/dist/rendering/world3d/PhysicsRemote3D.d.ts +174 -0
  244. package/dist/rendering/world3d/PhysicsRemote3D.js +534 -0
  245. package/dist/rendering/world3d/Ragdoll3D.d.ts +69 -0
  246. package/dist/rendering/world3d/Ragdoll3D.js +200 -0
  247. package/dist/rendering/world3d/Raycast3D.d.ts +37 -0
  248. package/dist/rendering/world3d/Raycast3D.js +246 -0
  249. package/dist/rendering/world3d/RenderList3D.d.ts +88 -0
  250. package/dist/rendering/world3d/RenderList3D.js +490 -0
  251. package/dist/rendering/world3d/Retarget3D.d.ts +20 -0
  252. package/dist/rendering/world3d/Retarget3D.js +185 -0
  253. package/dist/rendering/world3d/Serialize3D.d.ts +49 -0
  254. package/dist/rendering/world3d/Serialize3D.js +607 -0
  255. package/dist/rendering/world3d/StateMachine3D.d.ts +78 -0
  256. package/dist/rendering/world3d/StateMachine3D.js +277 -0
  257. package/dist/rendering/world3d/Terrain3D.d.ts +227 -0
  258. package/dist/rendering/world3d/Terrain3D.js +803 -0
  259. package/dist/rendering/world3d/Text3D.d.ts +90 -0
  260. package/dist/rendering/world3d/Text3D.js +558 -0
  261. package/dist/rendering/world3d/Texture3D.d.ts +133 -0
  262. package/dist/rendering/world3d/Texture3D.js +252 -0
  263. package/dist/rendering/world3d/Trail3D.d.ts +59 -0
  264. package/dist/rendering/world3d/Trail3D.js +193 -0
  265. package/dist/rendering/world3d/Vehicle3D.d.ts +97 -0
  266. package/dist/rendering/world3d/Vehicle3D.js +226 -0
  267. package/dist/rendering/world3d/VolumetricFog3D.d.ts +55 -0
  268. package/dist/rendering/world3d/VolumetricFog3D.js +229 -0
  269. package/dist/rendering/world3d/Water3D.d.ts +163 -0
  270. package/dist/rendering/world3d/Water3D.js +606 -0
  271. package/dist/rendering/world3d/core3D.d.ts +34 -0
  272. package/dist/rendering/world3d/core3D.js +99 -0
  273. package/dist/rendering/world3d/debug3D.d.ts +64 -0
  274. package/dist/rendering/world3d/debug3D.js +257 -0
  275. package/dist/rendering/world3d/decoders3D.d.ts +42 -0
  276. package/dist/rendering/world3d/decoders3D.js +133 -0
  277. package/dist/rendering/world3d/geometries3D.d.ts +99 -0
  278. package/dist/rendering/world3d/geometries3D.js +605 -0
  279. package/dist/rendering/world3d/helpers3D.d.ts +65 -0
  280. package/dist/rendering/world3d/helpers3D.js +177 -0
  281. package/dist/rendering/world3d/index.d.ts +91 -0
  282. package/dist/rendering/world3d/index.js +56 -0
  283. package/dist/rendering/world3d/math3D.d.ts +78 -0
  284. package/dist/rendering/world3d/math3D.js +640 -0
  285. package/dist/rendering/world3d/primitives3D.d.ts +60 -0
  286. package/dist/rendering/world3d/primitives3D.js +196 -0
  287. package/dist/resources.d.ts +8 -0
  288. package/dist/resources.js +6 -0
  289. package/dist/saveStore.d.ts +56 -0
  290. package/dist/saveStore.js +163 -0
  291. package/dist/semanticList.d.ts +122 -0
  292. package/dist/semanticList.js +174 -0
  293. package/dist/semanticTree.d.ts +10 -0
  294. package/dist/semanticTree.js +532 -0
  295. package/dist/semanticTypes.d.ts +167 -0
  296. package/dist/semanticTypes.js +2 -0
  297. package/dist/semantics.d.ts +6 -0
  298. package/dist/semantics.js +5 -0
  299. package/dist/sequencePlayback.d.ts +19 -0
  300. package/dist/sequencePlayback.js +391 -0
  301. package/dist/sequencePlaybackTypes.d.ts +21 -0
  302. package/dist/sequencePlaybackTypes.js +2 -0
  303. package/dist/sequenceTargetClaims.d.ts +10 -0
  304. package/dist/sequenceTargetClaims.js +31 -0
  305. package/dist/srgbBytes.d.ts +3 -0
  306. package/dist/srgbBytes.js +64 -0
  307. package/dist/startEngine.d.ts +5 -0
  308. package/dist/startEngine.js +31 -0
  309. package/dist/surfaceOwnership.d.ts +3 -0
  310. package/dist/surfaceOwnership.js +15 -0
  311. package/dist/text.d.ts +23 -0
  312. package/dist/text.js +4 -0
  313. package/dist/textField.d.ts +6 -0
  314. package/dist/textField.js +6 -0
  315. package/dist/tileMapDraw.d.ts +7 -0
  316. package/dist/tileMapDraw.js +310 -0
  317. package/dist/tiledImport.d.ts +9 -0
  318. package/dist/tiledImport.js +357 -0
  319. package/dist/tilemap.d.ts +5 -0
  320. package/dist/tilemap.js +5 -0
  321. package/dist/tilemapTypes.d.ts +169 -0
  322. package/dist/tilemapTypes.js +2 -0
  323. package/dist/tween.d.ts +15 -0
  324. package/dist/tween.js +329 -0
  325. package/dist/tweenTypes.d.ts +27 -0
  326. package/dist/tweenTypes.js +2 -0
  327. package/dist/ui/controlKeys.d.ts +109 -0
  328. package/dist/ui/controlKeys.js +249 -0
  329. package/dist/ui/controls.d.ts +52 -0
  330. package/dist/ui/controls.js +288 -0
  331. package/dist/ui/editing.d.ts +3 -0
  332. package/dist/ui/editing.js +3 -0
  333. package/dist/ui/index.d.ts +19 -0
  334. package/dist/ui/index.js +11 -0
  335. package/dist/ui/keyboardFocus.d.ts +32 -0
  336. package/dist/ui/keyboardFocus.js +146 -0
  337. package/dist/ui/layerTypes.d.ts +91 -0
  338. package/dist/ui/layerTypes.js +2 -0
  339. package/dist/ui/layers.d.ts +4 -0
  340. package/dist/ui/layers.js +586 -0
  341. package/dist/ui/leafContent.d.ts +21 -0
  342. package/dist/ui/leafContent.js +136 -0
  343. package/dist/ui/rangeControl.d.ts +50 -0
  344. package/dist/ui/rangeControl.js +167 -0
  345. package/dist/ui/scrollControl.d.ts +72 -0
  346. package/dist/ui/scrollControl.js +218 -0
  347. package/dist/ui/stateControls.d.ts +82 -0
  348. package/dist/ui/stateControls.js +328 -0
  349. package/dist/ui/textEditor.d.ts +53 -0
  350. package/dist/ui/textEditor.js +370 -0
  351. package/dist/ui/textEditorTypes.d.ts +78 -0
  352. package/dist/ui/textEditorTypes.js +2 -0
  353. package/dist/ui/textFieldControl.d.ts +96 -0
  354. package/dist/ui/textFieldControl.js +259 -0
  355. package/dist/ui/theme.d.ts +59 -0
  356. package/dist/ui/theme.js +165 -0
  357. package/dist/ui/types.d.ts +265 -0
  358. package/dist/ui/types.js +2 -0
  359. package/dist/ui/uiRoot.d.ts +4 -0
  360. package/dist/ui/uiRoot.js +1497 -0
  361. package/dist/ui/uiRootDisplay.d.ts +46 -0
  362. package/dist/ui/uiRootDisplay.js +148 -0
  363. package/dist/ui/uiRootModel.d.ts +112 -0
  364. package/dist/ui/uiRootModel.js +60 -0
  365. package/dist/ui/virtualList.d.ts +20 -0
  366. package/dist/ui/virtualList.js +105 -0
  367. package/dist/video.d.ts +4 -0
  368. package/dist/video.js +4 -0
  369. package/dist/videoPlayer.d.ts +4 -0
  370. package/dist/videoPlayer.js +215 -0
  371. package/dist/videoTypes.d.ts +74 -0
  372. package/dist/videoTypes.js +2 -0
  373. package/dist/web/BrowserAssetBundle.d.ts +39 -0
  374. package/dist/web/BrowserAssetBundle.js +136 -0
  375. package/dist/web/BrowserAudio.d.ts +41 -0
  376. package/dist/web/BrowserAudio.js +473 -0
  377. package/dist/web/BrowserFrameLoop.d.ts +65 -0
  378. package/dist/web/BrowserFrameLoop.js +125 -0
  379. package/dist/web/BrowserGame.d.ts +112 -0
  380. package/dist/web/BrowserGame.js +352 -0
  381. package/dist/web/BrowserGamepadInput.d.ts +35 -0
  382. package/dist/web/BrowserGamepadInput.js +134 -0
  383. package/dist/web/BrowserHoverInput.d.ts +24 -0
  384. package/dist/web/BrowserHoverInput.js +266 -0
  385. package/dist/web/BrowserImageTextures.d.ts +66 -0
  386. package/dist/web/BrowserImageTextures.js +169 -0
  387. package/dist/web/BrowserInputActions.d.ts +53 -0
  388. package/dist/web/BrowserInputActions.js +342 -0
  389. package/dist/web/BrowserKeyboardInput.d.ts +4 -0
  390. package/dist/web/BrowserKeyboardInput.js +223 -0
  391. package/dist/web/BrowserPlay.d.ts +289 -0
  392. package/dist/web/BrowserPlay.js +1301 -0
  393. package/dist/web/BrowserPointerInput.d.ts +4 -0
  394. package/dist/web/BrowserPointerInput.js +511 -0
  395. package/dist/web/BrowserSemantics.d.ts +34 -0
  396. package/dist/web/BrowserSemantics.js +418 -0
  397. package/dist/web/BrowserStatsPanel.d.ts +46 -0
  398. package/dist/web/BrowserStatsPanel.js +137 -0
  399. package/dist/web/BrowserStorage.d.ts +33 -0
  400. package/dist/web/BrowserStorage.js +132 -0
  401. package/dist/web/BrowserTextEditor.d.ts +49 -0
  402. package/dist/web/BrowserTextEditor.js +839 -0
  403. package/dist/web/BrowserTextInput.d.ts +83 -0
  404. package/dist/web/BrowserTextInput.js +524 -0
  405. package/dist/web/BrowserTextureProvider.d.ts +52 -0
  406. package/dist/web/BrowserTextureProvider.js +935 -0
  407. package/dist/web/BrowserVideo.d.ts +28 -0
  408. package/dist/web/BrowserVideo.js +211 -0
  409. package/dist/web/CanvasKitFontSetProvider.d.ts +29 -0
  410. package/dist/web/CanvasKitFontSetProvider.js +215 -0
  411. package/dist/web/CanvasKitParagraphProvider.d.ts +169 -0
  412. package/dist/web/CanvasKitParagraphProvider.js +691 -0
  413. package/dist/web/CanvasTextRasterProvider.d.ts +4 -0
  414. package/dist/web/CanvasTextRasterProvider.js +312 -0
  415. package/dist/web/ManifestByteSource.d.ts +147 -0
  416. package/dist/web/ManifestByteSource.js +974 -0
  417. package/dist/web/ManifestFontContentLoader.d.ts +12 -0
  418. package/dist/web/ManifestFontContentLoader.js +30 -0
  419. package/dist/web/MouseInput.d.ts +4 -0
  420. package/dist/web/MouseInput.js +218 -0
  421. package/dist/web/WebGL2Host.d.ts +5 -0
  422. package/dist/web/WebGL2Host.js +2672 -0
  423. package/dist/web/WebGPUHost.d.ts +87 -0
  424. package/dist/web/WebGPUHost.js +3349 -0
  425. package/dist/web/audio.d.ts +3 -0
  426. package/dist/web/audio.js +4 -0
  427. package/dist/web/canvasKitParagraphGeometry.d.ts +27 -0
  428. package/dist/web/canvasKitParagraphGeometry.js +83 -0
  429. package/dist/web/editing.d.ts +5 -0
  430. package/dist/web/editing.js +4 -0
  431. package/dist/web/editorFonts.d.ts +50 -0
  432. package/dist/web/editorFonts.js +297 -0
  433. package/dist/web/game.d.ts +5 -0
  434. package/dist/web/game.js +6 -0
  435. package/dist/web/gamepad.d.ts +3 -0
  436. package/dist/web/gamepad.js +4 -0
  437. package/dist/web/hover.d.ts +3 -0
  438. package/dist/web/hover.js +4 -0
  439. package/dist/web/image.d.ts +4 -0
  440. package/dist/web/image.js +4 -0
  441. package/dist/web/imageProjections2D.d.ts +14 -0
  442. package/dist/web/imageProjections2D.js +2 -0
  443. package/dist/web/input.d.ts +6 -0
  444. package/dist/web/input.js +4 -0
  445. package/dist/web/keyboard.d.ts +3 -0
  446. package/dist/web/keyboard.js +3 -0
  447. package/dist/web/kit.d.ts +10 -0
  448. package/dist/web/kit.js +7 -0
  449. package/dist/web/loop.d.ts +3 -0
  450. package/dist/web/loop.js +4 -0
  451. package/dist/web/paragraph.d.ts +6 -0
  452. package/dist/web/paragraph.js +4 -0
  453. package/dist/web/play.d.ts +5 -0
  454. package/dist/web/play.js +6 -0
  455. package/dist/web/playSfx.d.ts +36 -0
  456. package/dist/web/playSfx.js +112 -0
  457. package/dist/web/pointer.d.ts +3 -0
  458. package/dist/web/pointer.js +3 -0
  459. package/dist/web/prepareSharedSubmission2D.d.ts +27 -0
  460. package/dist/web/prepareSharedSubmission2D.js +57 -0
  461. package/dist/web/resources.d.ts +27 -0
  462. package/dist/web/resources.js +96 -0
  463. package/dist/web/semantics.d.ts +3 -0
  464. package/dist/web/semantics.js +4 -0
  465. package/dist/web/sharedDeviceSession.d.ts +64 -0
  466. package/dist/web/sharedDeviceSession.js +2 -0
  467. package/dist/web/sharedEffectShaders.d.ts +9 -0
  468. package/dist/web/sharedEffectShaders.js +165 -0
  469. package/dist/web/sharedFrameUpload.d.ts +25 -0
  470. package/dist/web/sharedFrameUpload.js +2 -0
  471. package/dist/web/sharedHostDeferred.d.ts +7 -0
  472. package/dist/web/sharedHostDeferred.js +12 -0
  473. package/dist/web/sharedRetentionLedger.d.ts +85 -0
  474. package/dist/web/sharedRetentionLedger.js +391 -0
  475. package/dist/web/sharedSubmissionStorage2D.d.ts +56 -0
  476. package/dist/web/sharedSubmissionStorage2D.js +73 -0
  477. package/dist/web/sharedWebGL2Arena.d.ts +40 -0
  478. package/dist/web/sharedWebGL2Arena.js +77 -0
  479. package/dist/web/sharedWebGL2Options.d.ts +30 -0
  480. package/dist/web/sharedWebGL2Options.js +96 -0
  481. package/dist/web/sharedWebGL2Shaders.d.ts +20 -0
  482. package/dist/web/sharedWebGL2Shaders.js +314 -0
  483. package/dist/web/sharedWebGPUOptions.d.ts +37 -0
  484. package/dist/web/sharedWebGPUOptions.js +126 -0
  485. package/dist/web/text.d.ts +3 -0
  486. package/dist/web/text.js +3 -0
  487. package/dist/web/textInput.d.ts +3 -0
  488. package/dist/web/textInput.js +3 -0
  489. package/dist/web/video.d.ts +3 -0
  490. package/dist/web/video.js +4 -0
  491. package/dist/web/webgl2.d.ts +7 -0
  492. package/dist/web/webgl2.js +4 -0
  493. package/dist/web/webgl2LayerState.d.ts +50 -0
  494. package/dist/web/webgl2LayerState.js +102 -0
  495. package/dist/web/webgl2Native.d.ts +70 -0
  496. package/dist/web/webgl2Native.js +568 -0
  497. package/dist/web/webgl2Types.d.ts +132 -0
  498. package/dist/web/webgl2Types.js +2 -0
  499. package/dist/web/webgpu.d.ts +6 -0
  500. package/dist/web/webgpu.js +2 -0
  501. package/dist/web/webgpuBindingCache.d.ts +26 -0
  502. package/dist/web/webgpuBindingCache.js +223 -0
  503. package/dist/web/webgpuBufferPool.d.ts +51 -0
  504. package/dist/web/webgpuBufferPool.js +58 -0
  505. package/dist/web/webgpuImageResidency.d.ts +53 -0
  506. package/dist/web/webgpuImageResidency.js +61 -0
  507. package/dist/web/webgpuLifetime.d.ts +45 -0
  508. package/dist/web/webgpuLifetime.js +64 -0
  509. package/dist/web/webgpuRetentionPool.d.ts +66 -0
  510. package/dist/web/webgpuRetentionPool.js +84 -0
  511. package/dist/web/webgpuSharedPass.d.ts +7 -0
  512. package/dist/web/webgpuSharedPass.js +211 -0
  513. package/dist/web/webgpuSharedResolvePass.d.ts +3 -0
  514. package/dist/web/webgpuSharedResolvePass.js +29 -0
  515. package/dist/web/world3d/Audio3D.d.ts +68 -0
  516. package/dist/web/world3d/Audio3D.js +212 -0
  517. package/dist/web/world3d/BrowserPlay3D.d.ts +182 -0
  518. package/dist/web/world3d/BrowserPlay3D.js +851 -0
  519. package/dist/web/world3d/FlyControls3D.d.ts +55 -0
  520. package/dist/web/world3d/FlyControls3D.js +160 -0
  521. package/dist/web/world3d/FollowControls3D.d.ts +28 -0
  522. package/dist/web/world3d/FollowControls3D.js +117 -0
  523. package/dist/web/world3d/OrbitControls3D.d.ts +55 -0
  524. package/dist/web/world3d/OrbitControls3D.js +187 -0
  525. package/dist/web/world3d/TransformControls3D.d.ts +34 -0
  526. package/dist/web/world3d/TransformControls3D.js +125 -0
  527. package/dist/web/world3d/WebGL2Renderer3D.d.ts +133 -0
  528. package/dist/web/world3d/WebGL2Renderer3D.js +1173 -0
  529. package/dist/web/world3d/WebGPURenderer3D.d.ts +110 -0
  530. package/dist/web/world3d/WebGPURenderer3D.js +1915 -0
  531. package/dist/web/world3d/World3DView.d.ts +51 -0
  532. package/dist/web/world3d/World3DView.js +77 -0
  533. package/dist/web/world3d/app3D.d.ts +136 -0
  534. package/dist/web/world3d/app3D.js +304 -0
  535. package/dist/web/world3d/assets3D.d.ts +38 -0
  536. package/dist/web/world3d/assets3D.js +112 -0
  537. package/dist/web/world3d/atmosphere3D.d.ts +47 -0
  538. package/dist/web/world3d/atmosphere3D.js +178 -0
  539. package/dist/web/world3d/frame3D.d.ts +142 -0
  540. package/dist/web/world3d/frame3D.js +388 -0
  541. package/dist/web/world3d/gpuResources3D.d.ts +98 -0
  542. package/dist/web/world3d/gpuResources3D.js +901 -0
  543. package/dist/web/world3d/host3D.d.ts +23 -0
  544. package/dist/web/world3d/host3D.js +61 -0
  545. package/dist/web/world3d/index.d.ts +38 -0
  546. package/dist/web/world3d/index.js +23 -0
  547. package/dist/web/world3d/loaders3D.d.ts +26 -0
  548. package/dist/web/world3d/loaders3D.js +138 -0
  549. package/dist/web/world3d/markers3D.d.ts +49 -0
  550. package/dist/web/world3d/markers3D.js +130 -0
  551. package/dist/web/world3d/materialWebGL23D.d.ts +34 -0
  552. package/dist/web/world3d/materialWebGL23D.js +218 -0
  553. package/dist/web/world3d/overlay3D.d.ts +28 -0
  554. package/dist/web/world3d/overlay3D.js +170 -0
  555. package/dist/web/world3d/post3D.d.ts +112 -0
  556. package/dist/web/world3d/post3D.js +459 -0
  557. package/dist/web/world3d/postWebGL23D.d.ts +24 -0
  558. package/dist/web/world3d/postWebGL23D.js +237 -0
  559. package/dist/web/world3d/postWebGPU3D.d.ts +23 -0
  560. package/dist/web/world3d/postWebGPU3D.js +255 -0
  561. package/dist/web/world3d/probe3D.d.ts +14 -0
  562. package/dist/web/world3d/probe3D.js +66 -0
  563. package/dist/web/world3d/shaders3D.d.ts +43 -0
  564. package/dist/web/world3d/shaders3D.js +851 -0
  565. package/dist/web/world3d/stats3D.d.ts +31 -0
  566. package/dist/web/world3d/stats3D.js +80 -0
  567. package/dist/web/world3d/webGL2FrameMetrics3D.d.ts +66 -0
  568. package/dist/web/world3d/webGL2FrameMetrics3D.js +185 -0
  569. package/dist/web/world3d/webgpu.d.ts +35 -0
  570. package/dist/web/world3d/webgpu.js +22 -0
  571. package/dist/web/world3d/webgpuPacking3D.d.ts +13 -0
  572. package/dist/web/world3d/webgpuPacking3D.js +85 -0
  573. package/dist/web/world3d/wgsl3D.d.ts +68 -0
  574. package/dist/web/world3d/wgsl3D.js +781 -0
  575. package/package.json +220 -4
@@ -0,0 +1,1915 @@
1
+ import { World3DError } from '../../rendering/world3d/core3D.js';
2
+ import { linearToSrgb, mat3NormalFromMat4, mat4Invert } from '../../rendering/world3d/math3D.js';
3
+ import { instanceStreamRevisions3D } from '../../rendering/world3d/Mesh3D.js';
4
+ import { SkinnedInstancedMesh3D } from '../../rendering/world3d/AnimationTexture3D.js';
5
+ import { GpuParticles3D } from '../../rendering/world3d/GpuParticles3D.js';
6
+ import { RenderList3D } from '../../rendering/world3d/RenderList3D.js';
7
+ import { COMPRESSED_BLOCK_BYTES_3D, CubeTexture3D, RenderTarget3D, isCompressedPixels3D, isTexturePixels3D } from '../../rendering/world3d/Texture3D.js';
8
+ import { FRAME_BLOCK_FLOATS_3D, FRAME_OFFSETS_3D, TILED_LIGHTS_3D, writeTiledLights3D, outputToneMapping3D, planShadows3D, writeFrameBlock3D } from './frame3D.js';
9
+ import { createPostProcessSettings3D, outlineActive3D, postViewFromCamera3D } from './post3D.js';
10
+ import { PostChainWebGPU3D } from './postWebGPU3D.js';
11
+ import { MATERIAL_BLOCK_BYTES_3D, MIPMAP_WGSL_3D, OBJECT_BLOCK_BYTES_3D, SKYBOX_WGSL_3D, buildMaterialWgsl3D, shaderFeatureKey3D } from './wgsl3D.js';
12
+ import { convertVertexAttribute3D, packMorphStorage3D, packWireIndices3D, writeObjectMorph3D } from './webgpuPacking3D.js';
13
+ // WebGPU flag values, spelled out so this module needs no global constant namespaces.
14
+ const SHADER_STAGE = Object.freeze({ VERTEX: 1, FRAGMENT: 2 });
15
+ const BUFFER_USAGE = Object.freeze({
16
+ MAP_READ: 1,
17
+ COPY_DST: 8,
18
+ INDEX: 16,
19
+ VERTEX: 32,
20
+ UNIFORM: 64,
21
+ STORAGE: 128
22
+ });
23
+ const TEXTURE_USAGE = Object.freeze({ COPY_SRC: 1, COPY_DST: 2, TEXTURE_BINDING: 4, RENDER_ATTACHMENT: 16 });
24
+ const MAP_MODE_READ = 1;
25
+ const ATTRIBUTE_SLOTS = ['position', 'normal', 'uv', 'tangent', 'color', 'joints', 'weights', 'uv1'];
26
+ const TARGET_FORMAT = 'rgba8unorm-srgb', HDR_FORMAT = 'rgba16float';
27
+ const SHADOW_FORMAT = 'depth32float';
28
+ const DEPTH_FORMAT = 'depth24plus';
29
+ const IDENTITY4 = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
30
+ const PRUNE_INTERVAL = 600;
31
+ function hostSize(source) {
32
+ const size = source;
33
+ return [Math.max(1, size.videoWidth ?? size.width ?? 1), Math.max(1, size.videoHeight ?? size.height ?? 1)];
34
+ }
35
+ // The device loss promise can outlive a renderer that borrows the device.
36
+ function observeDeviceLoss(device, listener) {
37
+ void device.lost.then(info => {
38
+ const callback = listener;
39
+ listener = undefined;
40
+ callback?.(info);
41
+ });
42
+ return () => {
43
+ listener = undefined;
44
+ };
45
+ }
46
+ export class WebGPURenderer3D {
47
+ canvas;
48
+ device;
49
+ toneMapping;
50
+ exposure;
51
+ shadowsEnabled;
52
+ /** Bloom, color grading and FXAA; set `enabled` to turn the chain on. */
53
+ postProcess = createPostProcessSettings3D();
54
+ viewport;
55
+ autoClear = true;
56
+ #post;
57
+ #inPost = false;
58
+ #frameToneMapping = 'none';
59
+ info = {
60
+ frame: 0,
61
+ drawCalls: 0,
62
+ triangles: 0,
63
+ visited: 0,
64
+ culled: 0,
65
+ lightsDropped: 0,
66
+ lightsTiled: 0,
67
+ shadowMaps: 0,
68
+ programs: 0,
69
+ geometries: 0,
70
+ textures: 0
71
+ };
72
+ #context;
73
+ #format;
74
+ #sampleCount;
75
+ #alpha;
76
+ #ownsDevice;
77
+ #list = new RenderList3D();
78
+ #frameData = new Float32Array(FRAME_BLOCK_FLOATS_3D);
79
+ #frameBuffer;
80
+ #tiledTable = new Float32Array(TILED_LIGHTS_3D.width * TILED_LIGHTS_3D.rows * 4);
81
+ #tiledBuffer;
82
+ #frameLayout;
83
+ #depthFrameLayout;
84
+ #materialLayout;
85
+ #objectLayout;
86
+ #skinLayout;
87
+ #pipelineLayout;
88
+ #depthPipelineLayout;
89
+ #modules = new Map();
90
+ #pipelines = new Map();
91
+ #geometries = new Map();
92
+ #instances = new Map();
93
+ #textures = new Map();
94
+ #targets = new Map();
95
+ #materials = new Map();
96
+ #bones = new Map();
97
+ #animations = new Map();
98
+ #sceneDepth;
99
+ /** True while the frame being drawn has a depth image of its solid geometry. */
100
+ #softDepth = false;
101
+ #sceneDepthSerial = 0;
102
+ #skins = new WeakMap();
103
+ #samplers = new Map();
104
+ #mipPipelines = new Map();
105
+ #shadowSlots = new Map();
106
+ #depthFrames = [];
107
+ #whiteTexture;
108
+ #whiteCubeTexture;
109
+ #white;
110
+ #whiteCube;
111
+ #unsubscribeDeviceLoss;
112
+ #defaultSampler;
113
+ #shadowSampler;
114
+ #dummyBones;
115
+ #dummyMorph;
116
+ #dummySkin;
117
+ #shadowAtlasSize;
118
+ #shadowTexture;
119
+ #shadowView;
120
+ #frameGroup;
121
+ #grabSampler;
122
+ /** Copies of the output for see-through surfaces, one per kind of output. */
123
+ #grabs = new Map();
124
+ #frameGroupKey = '';
125
+ #objectBuffer;
126
+ #objectGroup;
127
+ #objectCapacity = 256;
128
+ #objectStaging = new ArrayBuffer(256 * OBJECT_BLOCK_BYTES_3D);
129
+ #objectFloats = new Float32Array(this.#objectStaging);
130
+ #objectInts = new Int32Array(this.#objectStaging);
131
+ #objectCount = 0;
132
+ #canvasDepth;
133
+ #canvasColor;
134
+ #canvasKey = '';
135
+ #skyBuffer;
136
+ #skyGroup;
137
+ #skyLayout;
138
+ #serial = 0;
139
+ #shadowCount = 0;
140
+ #lost = false;
141
+ #disposed = false;
142
+ #scratch16 = new Float32Array(16);
143
+ #scratch9 = new Float32Array(9);
144
+ #materialData = new Float32Array(MATERIAL_BLOCK_BYTES_3D / 4);
145
+ /** Use createWebGPURenderer3D(); the constructor needs an acquired device. */
146
+ constructor(options, device, ownsDevice) {
147
+ const canvas = options.canvas;
148
+ const context = canvas.getContext('webgpu');
149
+ if (!context)
150
+ throw new World3DError('WORLD3D_CONTEXT_UNAVAILABLE', 'webgpu canvas context');
151
+ this.canvas = canvas;
152
+ this.device = device;
153
+ this.#ownsDevice = ownsDevice;
154
+ this.#context = context;
155
+ this.#format = navigator.gpu.getPreferredCanvasFormat();
156
+ this.#alpha = options.alpha ?? false;
157
+ this.#sampleCount = (options.antialias ?? true) ? 4 : 1;
158
+ this.toneMapping = options.toneMapping ?? 'aces';
159
+ this.exposure = options.exposure ?? 1;
160
+ this.shadowsEnabled = options.shadows ?? true;
161
+ this.#shadowAtlasSize = Math.min(options.shadowAtlasSize ?? 2048, device.limits.maxTextureDimension2D);
162
+ // The canvas image is copied when see-through surfaces need what lies behind them.
163
+ context.configure({
164
+ device,
165
+ format: this.#format,
166
+ alphaMode: this.#alpha ? 'premultiplied' : 'opaque',
167
+ usage: TEXTURE_USAGE.RENDER_ATTACHMENT | TEXTURE_USAGE.COPY_SRC
168
+ });
169
+ const filtering = [];
170
+ for (let i = 0; i < 7; i++) {
171
+ filtering.push({ binding: 1 + i * 2, visibility: SHADER_STAGE.FRAGMENT, texture: {} });
172
+ filtering.push({ binding: 2 + i * 2, visibility: SHADER_STAGE.FRAGMENT, sampler: {} });
173
+ }
174
+ const both = SHADER_STAGE.VERTEX | SHADER_STAGE.FRAGMENT;
175
+ this.#frameLayout = device.createBindGroupLayout({
176
+ entries: [
177
+ { binding: 0, visibility: both, buffer: {} },
178
+ { binding: 1, visibility: SHADER_STAGE.FRAGMENT, texture: { sampleType: 'depth' } },
179
+ { binding: 2, visibility: SHADER_STAGE.FRAGMENT, sampler: { type: 'comparison' } },
180
+ { binding: 3, visibility: SHADER_STAGE.FRAGMENT, texture: { viewDimension: 'cube' } },
181
+ { binding: 4, visibility: SHADER_STAGE.FRAGMENT, sampler: {} },
182
+ { binding: 5, visibility: SHADER_STAGE.FRAGMENT, texture: {} },
183
+ { binding: 6, visibility: SHADER_STAGE.FRAGMENT, sampler: {} },
184
+ { binding: 7, visibility: SHADER_STAGE.FRAGMENT, texture: { sampleType: 'depth' } },
185
+ { binding: 8, visibility: SHADER_STAGE.FRAGMENT, buffer: { type: 'read-only-storage' } }
186
+ ]
187
+ });
188
+ this.#depthFrameLayout = device.createBindGroupLayout({ entries: [{ binding: 0, visibility: both, buffer: {} }] });
189
+ this.#materialLayout = device.createBindGroupLayout({
190
+ entries: [{ binding: 0, visibility: both, buffer: {} }, ...filtering]
191
+ });
192
+ this.#objectLayout = device.createBindGroupLayout({
193
+ entries: [
194
+ { binding: 0, visibility: both, buffer: { hasDynamicOffset: true, minBindingSize: OBJECT_BLOCK_BYTES_3D } }
195
+ ]
196
+ });
197
+ this.#skinLayout = device.createBindGroupLayout({
198
+ entries: [
199
+ { binding: 0, visibility: SHADER_STAGE.VERTEX, buffer: { type: 'read-only-storage' } },
200
+ { binding: 1, visibility: SHADER_STAGE.VERTEX, buffer: { type: 'read-only-storage' } }
201
+ ]
202
+ });
203
+ this.#pipelineLayout = device.createPipelineLayout({
204
+ bindGroupLayouts: [this.#frameLayout, this.#materialLayout, this.#objectLayout, this.#skinLayout]
205
+ });
206
+ this.#depthPipelineLayout = device.createPipelineLayout({
207
+ bindGroupLayouts: [this.#depthFrameLayout, this.#materialLayout, this.#objectLayout, this.#skinLayout]
208
+ });
209
+ this.#frameBuffer = device.createBuffer({
210
+ size: FRAME_BLOCK_FLOATS_3D * 4,
211
+ usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST
212
+ });
213
+ this.#tiledBuffer = device.createBuffer({
214
+ size: this.#tiledTable.byteLength,
215
+ usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.COPY_DST
216
+ });
217
+ this.#objectBuffer = this.createObjectBuffer();
218
+ this.#objectGroup = this.createObjectGroup();
219
+ const white = (this.#whiteTexture = device.createTexture({
220
+ size: [1, 1],
221
+ format: 'rgba8unorm',
222
+ usage: TEXTURE_USAGE.TEXTURE_BINDING | TEXTURE_USAGE.COPY_DST
223
+ }));
224
+ device.queue.writeTexture({ texture: white }, new Uint8Array([255, 255, 255, 255]), {}, [1, 1]);
225
+ this.#white = white.createView();
226
+ const whiteCube = (this.#whiteCubeTexture = device.createTexture({
227
+ size: [1, 1, 6],
228
+ format: 'rgba8unorm',
229
+ usage: TEXTURE_USAGE.TEXTURE_BINDING | TEXTURE_USAGE.COPY_DST
230
+ }));
231
+ for (let face = 0; face < 6; face++)
232
+ device.queue.writeTexture({ texture: whiteCube, origin: [0, 0, face] }, new Uint8Array([255, 255, 255, 255]), {}, [1, 1]);
233
+ this.#whiteCube = whiteCube.createView({ dimension: 'cube' });
234
+ this.#defaultSampler = device.createSampler({ magFilter: 'linear', minFilter: 'linear', mipmapFilter: 'linear' });
235
+ this.#shadowSampler = device.createSampler({ compare: 'less-equal', magFilter: 'linear', minFilter: 'linear' });
236
+ this.#grabSampler = device.createSampler({
237
+ magFilter: 'linear',
238
+ minFilter: 'linear',
239
+ addressModeU: 'clamp-to-edge',
240
+ addressModeV: 'clamp-to-edge'
241
+ });
242
+ this.#dummyBones = device.createBuffer({ size: 64, usage: BUFFER_USAGE.STORAGE });
243
+ this.#dummyMorph = device.createBuffer({ size: 16, usage: BUFFER_USAGE.STORAGE });
244
+ this.#dummySkin = this.createSkinGroup(this.#dummyBones, this.#dummyMorph);
245
+ this.#unsubscribeDeviceLoss = observeDeviceLoss(device, info => {
246
+ this.#lost = true;
247
+ options.onDeviceLost?.(info.message);
248
+ });
249
+ }
250
+ get isDeviceLost() {
251
+ return this.#lost;
252
+ }
253
+ setSize(width, height, pixelRatio = 1) {
254
+ const w = Math.max(1, Math.floor(width * pixelRatio)), h = Math.max(1, Math.floor(height * pixelRatio));
255
+ if (!Number.isFinite(w) || !Number.isFinite(h))
256
+ throw new World3DError('WORLD3D_INPUT_INVALID', 'size');
257
+ if (this.canvas.width !== w)
258
+ this.canvas.width = w;
259
+ if (this.canvas.height !== h)
260
+ this.canvas.height = h;
261
+ }
262
+ resizeToDisplaySize(pixelRatio = 1) {
263
+ const element = this.canvas;
264
+ if (typeof element.clientWidth !== 'number')
265
+ return false;
266
+ const w = Math.max(1, Math.floor(element.clientWidth * pixelRatio)), h = Math.max(1, Math.floor(element.clientHeight * pixelRatio));
267
+ if (element.width === w && element.height === h)
268
+ return false;
269
+ element.width = w;
270
+ element.height = h;
271
+ return true;
272
+ }
273
+ // ---- small GPU helpers -----------------------------------------------------
274
+ createObjectBuffer() {
275
+ return this.device.createBuffer({
276
+ size: this.#objectCapacity * OBJECT_BLOCK_BYTES_3D,
277
+ usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST
278
+ });
279
+ }
280
+ createObjectGroup() {
281
+ return this.device.createBindGroup({
282
+ layout: this.#objectLayout,
283
+ entries: [{ binding: 0, resource: { buffer: this.#objectBuffer, size: OBJECT_BLOCK_BYTES_3D } }]
284
+ });
285
+ }
286
+ createSkinGroup(bones, morph) {
287
+ return this.device.createBindGroup({
288
+ layout: this.#skinLayout,
289
+ entries: [
290
+ { binding: 0, resource: { buffer: bones } },
291
+ { binding: 1, resource: { buffer: morph } }
292
+ ]
293
+ });
294
+ }
295
+ /** Write `data` into a buffer of at least its size, recreating the buffer when it must grow. */
296
+ writeBuffer(entry, data, usage, length = data.length) {
297
+ const bytes = Math.max(4, Math.ceil((length * data.BYTES_PER_ELEMENT) / 4) * 4);
298
+ let target = entry;
299
+ if (!target || target.bytes < bytes) {
300
+ target?.buffer.destroy();
301
+ target = {
302
+ buffer: this.device.createBuffer({ size: bytes, usage: usage | BUFFER_USAGE.COPY_DST }),
303
+ version: -1,
304
+ bytes
305
+ };
306
+ }
307
+ // Uint16 index data may end on a 2-byte boundary; pad the final write to 4 bytes.
308
+ if ((length * data.BYTES_PER_ELEMENT) % 4 === 0)
309
+ this.device.queue.writeBuffer(target.buffer, 0, data.buffer, data.byteOffset, length * data.BYTES_PER_ELEMENT);
310
+ else {
311
+ const padded = new Uint16Array(length + 1);
312
+ padded.set(data.subarray(0, length));
313
+ this.device.queue.writeBuffer(target.buffer, 0, padded);
314
+ }
315
+ return target;
316
+ }
317
+ sampler(texture) {
318
+ const anisotropy = texture.magFilter === 'linear' && texture.minFilter === 'linear' && texture.mipmaps
319
+ ? Math.min(Math.max(Math.floor(texture.anisotropy), 1), 16)
320
+ : 1;
321
+ const key = texture.wrapS + texture.wrapT + texture.magFilter + texture.minFilter + texture.mipmaps + anisotropy;
322
+ let sampler = this.#samplers.get(key);
323
+ if (!sampler) {
324
+ const wrap = (mode) => mode === 'clamp' ? 'clamp-to-edge' : mode === 'mirror' ? 'mirror-repeat' : 'repeat';
325
+ sampler = this.device.createSampler({
326
+ addressModeU: wrap(texture.wrapS),
327
+ addressModeV: wrap(texture.wrapT),
328
+ addressModeW: 'clamp-to-edge',
329
+ magFilter: texture.magFilter,
330
+ minFilter: texture.minFilter,
331
+ mipmapFilter: texture.mipmaps ? 'linear' : 'nearest',
332
+ maxAnisotropy: anisotropy
333
+ });
334
+ this.#samplers.set(key, sampler);
335
+ }
336
+ return sampler;
337
+ }
338
+ // ---- textures ---------------------------------------------------------------
339
+ uploadSource(texture, source, layer, flipY) {
340
+ const queue = this.device.queue;
341
+ if (isTexturePixels3D(source)) {
342
+ let data = source.data;
343
+ if (flipY) {
344
+ const row = source.width * 4, flipped = new Uint8Array(data.length);
345
+ for (let y = 0; y < source.height; y++)
346
+ flipped.set(data.subarray(y * row, y * row + row), (source.height - 1 - y) * row);
347
+ data = flipped;
348
+ }
349
+ queue.writeTexture({ texture, origin: [0, 0, layer] }, data.buffer, { offset: data.byteOffset, bytesPerRow: source.width * 4, rowsPerImage: source.height }, [source.width, source.height]);
350
+ return;
351
+ }
352
+ const [width, height] = hostSize(source);
353
+ queue.copyExternalImageToTexture({ source: source, flipY }, { texture, origin: [0, 0, layer] }, [width, height]);
354
+ }
355
+ generateMipmaps(texture, layers) {
356
+ const device = this.device, format = texture.format;
357
+ let pipeline = this.#mipPipelines.get(format);
358
+ if (!pipeline) {
359
+ const module = device.createShaderModule({ code: MIPMAP_WGSL_3D });
360
+ pipeline = device.createRenderPipeline({
361
+ layout: 'auto',
362
+ vertex: { module, entryPoint: 'vertexMain' },
363
+ fragment: { module, entryPoint: 'fragmentMain', targets: [{ format }] },
364
+ primitive: { topology: 'triangle-list' }
365
+ });
366
+ this.#mipPipelines.set(format, pipeline);
367
+ }
368
+ const encoder = device.createCommandEncoder();
369
+ for (let layer = 0; layer < layers; layer++) {
370
+ for (let level = 1; level < texture.mipLevelCount; level++) {
371
+ const source = texture.createView({
372
+ dimension: '2d',
373
+ baseMipLevel: level - 1,
374
+ mipLevelCount: 1,
375
+ baseArrayLayer: layer,
376
+ arrayLayerCount: 1
377
+ });
378
+ const pass = encoder.beginRenderPass({
379
+ colorAttachments: [
380
+ {
381
+ view: texture.createView({
382
+ dimension: '2d',
383
+ baseMipLevel: level,
384
+ mipLevelCount: 1,
385
+ baseArrayLayer: layer,
386
+ arrayLayerCount: 1
387
+ }),
388
+ loadOp: 'clear',
389
+ storeOp: 'store'
390
+ }
391
+ ]
392
+ });
393
+ pass.setPipeline(pipeline);
394
+ pass.setBindGroup(0, device.createBindGroup({
395
+ layout: pipeline.getBindGroupLayout(0),
396
+ entries: [
397
+ { binding: 0, resource: source },
398
+ { binding: 1, resource: this.#defaultSampler }
399
+ ]
400
+ }));
401
+ pass.draw(3);
402
+ pass.end();
403
+ }
404
+ }
405
+ device.queue.submit([encoder.finish()]);
406
+ }
407
+ createColorTexture(width, height, layers, texture) {
408
+ const limit = this.device.limits.maxTextureDimension2D;
409
+ if (width > limit || height > limit)
410
+ throw new World3DError('WORLD3D_BUDGET', 'texture size');
411
+ return this.device.createTexture({
412
+ size: [width, height, layers],
413
+ format: texture.colorSpace === 'srgb' ? 'rgba8unorm-srgb' : 'rgba8unorm',
414
+ mipLevelCount: texture.mipmaps ? Math.floor(Math.log2(Math.max(width, height))) + 1 : 1,
415
+ usage: TEXTURE_USAGE.TEXTURE_BINDING | TEXTURE_USAGE.COPY_DST | TEXTURE_USAGE.RENDER_ATTACHMENT
416
+ });
417
+ }
418
+ textureEntry(texture, create) {
419
+ let entry = this.#textures.get(texture);
420
+ if (entry && entry.version === texture.version)
421
+ return entry;
422
+ const { texture: gpu, view } = create();
423
+ const previous = entry?.texture;
424
+ if (entry) {
425
+ entry.texture = gpu;
426
+ entry.view = view;
427
+ }
428
+ else {
429
+ const created = {
430
+ texture: gpu,
431
+ view,
432
+ sampler: this.#defaultSampler,
433
+ version: -1,
434
+ maxMip: 0,
435
+ unsubscribe: texture.onDispose(() => {
436
+ const current = this.#textures.get(texture);
437
+ if (current && this.#textures.delete(texture))
438
+ current.texture.destroy();
439
+ })
440
+ };
441
+ this.#textures.set(texture, (entry = created));
442
+ }
443
+ previous?.destroy();
444
+ entry.sampler = this.sampler(texture);
445
+ entry.maxMip = gpu.mipLevelCount - 1;
446
+ entry.version = texture.version;
447
+ return entry;
448
+ }
449
+ /** GPU view and sampler for a 2D texture, uploading when its version changed. */
450
+ texture2d(texture) {
451
+ const source = texture.source;
452
+ if (source instanceof RenderTarget3D) {
453
+ // A target's texture samples the color attachment directly.
454
+ const target = this.target(source);
455
+ return { view: target.colorView, sampler: this.sampler(texture), key: 't' + source.id + ':' + source.version };
456
+ }
457
+ const entry = this.textureEntry(texture, () => {
458
+ if (isCompressedPixels3D(source)) {
459
+ const format = this.compressedFormat(source.format, texture.colorSpace === 'srgb');
460
+ if (!format)
461
+ throw new World3DError('WORLD3D_RESOURCE_FAILED', 'compressed format ' + source.format + ' is not supported by this device');
462
+ const block = COMPRESSED_BLOCK_BYTES_3D[source.format];
463
+ // The base size must be block-aligned; smaller mips are padded to whole blocks on upload.
464
+ const gpu = this.device.createTexture({
465
+ size: [Math.ceil(source.width / 4) * 4, Math.ceil(source.height / 4) * 4],
466
+ format,
467
+ mipLevelCount: source.levels.length,
468
+ usage: TEXTURE_USAGE.TEXTURE_BINDING | TEXTURE_USAGE.COPY_DST
469
+ });
470
+ let width = gpu.width, height = gpu.height;
471
+ source.levels.forEach((level, mipLevel) => {
472
+ const columns = Math.ceil(width / 4), rows = Math.ceil(height / 4);
473
+ this.device.queue.writeTexture({ texture: gpu, mipLevel }, level.buffer, { offset: level.byteOffset, bytesPerRow: columns * block, rowsPerImage: rows }, [columns * 4, rows * 4]);
474
+ width = Math.max(1, width >> 1);
475
+ height = Math.max(1, height >> 1);
476
+ });
477
+ return { texture: gpu, view: gpu.createView() };
478
+ }
479
+ const [width, height] = isTexturePixels3D(source) ? [source.width, source.height] : hostSize(source);
480
+ const gpu = this.createColorTexture(width, height, 1, texture);
481
+ this.uploadSource(gpu, source, 0, texture.flipY);
482
+ if (gpu.mipLevelCount > 1)
483
+ this.generateMipmaps(gpu, 1);
484
+ return { texture: gpu, view: gpu.createView() };
485
+ });
486
+ return { view: entry.view, sampler: entry.sampler, key: texture.id + ':' + texture.version };
487
+ }
488
+ compressedFormat(format, srgb) {
489
+ const table = {
490
+ 'bc1': ['texture-compression-bc', 'bc1-rgba-unorm'],
491
+ 'bc3': ['texture-compression-bc', 'bc3-rgba-unorm'],
492
+ 'bc7': ['texture-compression-bc', 'bc7-rgba-unorm'],
493
+ 'etc2-rgb8': ['texture-compression-etc2', 'etc2-rgb8unorm'],
494
+ 'etc2-rgba8': ['texture-compression-etc2', 'etc2-rgba8unorm'],
495
+ 'astc-4x4': ['texture-compression-astc', 'astc-4x4-unorm']
496
+ };
497
+ const entry = table[format];
498
+ if (!entry || !this.device.features.has(entry[0]))
499
+ return undefined;
500
+ return (entry[1] + (srgb ? '-srgb' : ''));
501
+ }
502
+ /** True when textures in this compressed format can be used on this device. */
503
+ supportsCompressedFormat(format) {
504
+ return this.compressedFormat(format, false) !== undefined;
505
+ }
506
+ textureCube(texture) {
507
+ return this.textureEntry(texture, () => {
508
+ const first = texture.faces[0], size = isTexturePixels3D(first) ? first.width : hostSize(first)[0];
509
+ const gpu = this.createColorTexture(size, size, 6, texture);
510
+ texture.faces.forEach((face, layer) => this.uploadSource(gpu, face, layer, false));
511
+ if (gpu.mipLevelCount > 1)
512
+ this.generateMipmaps(gpu, 6);
513
+ return { texture: gpu, view: gpu.createView({ dimension: 'cube' }) };
514
+ });
515
+ }
516
+ target(target) {
517
+ if (target.isDisposed)
518
+ throw new World3DError('WORLD3D_DISPOSED', 'render target');
519
+ let entry = this.#targets.get(target);
520
+ if (entry && entry.version === target.version)
521
+ return entry;
522
+ const limit = this.device.limits.maxTextureDimension2D;
523
+ if (target.width > limit || target.height > limit)
524
+ throw new World3DError('WORLD3D_BUDGET', 'render target size');
525
+ const color = this.device.createTexture({
526
+ size: [target.width, target.height],
527
+ format: target.format === 'rgba16f' ? HDR_FORMAT : TARGET_FORMAT,
528
+ usage: TEXTURE_USAGE.RENDER_ATTACHMENT | TEXTURE_USAGE.TEXTURE_BINDING | TEXTURE_USAGE.COPY_SRC
529
+ });
530
+ const depth = target.depth
531
+ ? this.device.createTexture({
532
+ size: [target.width, target.height],
533
+ format: DEPTH_FORMAT,
534
+ usage: target.depthTexture
535
+ ? TEXTURE_USAGE.RENDER_ATTACHMENT | TEXTURE_USAGE.TEXTURE_BINDING
536
+ : TEXTURE_USAGE.RENDER_ATTACHMENT
537
+ })
538
+ : undefined;
539
+ if (entry) {
540
+ entry.color.destroy();
541
+ entry.depth?.destroy();
542
+ entry.color = color;
543
+ entry.colorView = color.createView();
544
+ entry.depth = depth;
545
+ entry.depthView = depth?.createView();
546
+ }
547
+ else {
548
+ const created = {
549
+ color,
550
+ colorView: color.createView(),
551
+ depth,
552
+ depthView: depth?.createView(),
553
+ version: -1,
554
+ unsubscribe: target.onDispose(() => {
555
+ const current = this.#targets.get(target);
556
+ if (current && this.#targets.delete(target)) {
557
+ current.color.destroy();
558
+ current.depth?.destroy();
559
+ }
560
+ })
561
+ };
562
+ this.#targets.set(target, (entry = created));
563
+ }
564
+ entry.version = target.version;
565
+ return entry;
566
+ }
567
+ // ---- geometry ---------------------------------------------------------------
568
+ convert(name, attribute) {
569
+ return convertVertexAttribute3D(name, attribute);
570
+ }
571
+ geometry(geometry) {
572
+ let entry = this.#geometries.get(geometry);
573
+ // Buffers are checked against the CPU versions once per render call.
574
+ if (entry && entry.serial === this.#serial)
575
+ return entry;
576
+ if (!entry) {
577
+ const created = {
578
+ buffers: new Map(),
579
+ index: undefined,
580
+ wire: undefined,
581
+ morph: undefined,
582
+ layoutVersion: -1,
583
+ serial: -1,
584
+ unsubscribe: geometry.onDispose(() => this.releaseGeometry(geometry))
585
+ };
586
+ this.#geometries.set(geometry, (entry = created));
587
+ }
588
+ for (const name of ATTRIBUTE_SLOTS) {
589
+ const attribute = geometry.getAttribute(name), current = entry.buffers.get(name);
590
+ if (!attribute) {
591
+ if (current) {
592
+ current.buffer.destroy();
593
+ entry.buffers.delete(name);
594
+ }
595
+ continue;
596
+ }
597
+ if (current && current.version === attribute.version)
598
+ continue;
599
+ const next = this.writeBuffer(current, this.convert(name, attribute), BUFFER_USAGE.VERTEX);
600
+ next.version = attribute.version;
601
+ entry.buffers.set(name, next);
602
+ }
603
+ const index = geometry.index;
604
+ if (index) {
605
+ if (!entry.index || entry.index.version !== index.version) {
606
+ const data = index.data instanceof Uint32Array || index.data instanceof Uint16Array
607
+ ? index.data
608
+ : Uint16Array.from(index.data);
609
+ const next = this.writeBuffer(entry.index, data, BUFFER_USAGE.INDEX);
610
+ entry.index = {
611
+ buffer: next.buffer,
612
+ bytes: next.bytes,
613
+ version: index.version,
614
+ format: data instanceof Uint32Array ? 'uint32' : 'uint16'
615
+ };
616
+ }
617
+ }
618
+ else if (entry.index) {
619
+ entry.index.buffer.destroy();
620
+ entry.index = undefined;
621
+ }
622
+ if (entry.layoutVersion !== geometry.layoutVersion) {
623
+ entry.morph?.buffer.destroy();
624
+ entry.morph = undefined;
625
+ const targets = geometry.morphTargets;
626
+ if (targets.length > 0) {
627
+ const vertexCount = geometry.vertexCount, channels = targets.some(target => target.normal) ? 2 : 1;
628
+ const data = packMorphStorage3D(targets, channels, vertexCount);
629
+ if (data.byteLength > this.device.limits.maxStorageBufferBindingSize)
630
+ throw new World3DError('WORLD3D_BUDGET', 'morph target data');
631
+ entry.morph = { buffer: this.writeBuffer(undefined, data, BUFFER_USAGE.STORAGE).buffer, channels, vertexCount };
632
+ }
633
+ entry.wire?.buffer.destroy();
634
+ entry.wire = undefined;
635
+ entry.layoutVersion = geometry.layoutVersion;
636
+ }
637
+ entry.serial = this.#serial;
638
+ return entry;
639
+ }
640
+ wireframe(geometry, entry) {
641
+ if (entry.wire && entry.wire.version === geometry.version)
642
+ return entry.wire;
643
+ const lines = packWireIndices3D(geometry);
644
+ entry.wire?.buffer.destroy();
645
+ const wire = {
646
+ buffer: this.writeBuffer(undefined, lines, BUFFER_USAGE.INDEX).buffer,
647
+ count: lines.length,
648
+ version: geometry.version
649
+ };
650
+ entry.wire = wire;
651
+ return wire;
652
+ }
653
+ releaseGeometry(geometry) {
654
+ const entry = this.#geometries.get(geometry);
655
+ if (!entry)
656
+ return;
657
+ this.#geometries.delete(geometry);
658
+ for (const buffer of entry.buffers.values())
659
+ buffer.buffer.destroy();
660
+ entry.index?.buffer.destroy();
661
+ entry.wire?.buffer.destroy();
662
+ entry.morph?.buffer.destroy();
663
+ }
664
+ uploadInstances(entry, source, version) {
665
+ if (entry?.source === source && entry.version === version)
666
+ return entry;
667
+ const buffer = this.writeBuffer(entry, source, BUFFER_USAGE.VERTEX);
668
+ buffer.source = source;
669
+ buffer.version = version;
670
+ return buffer;
671
+ }
672
+ instances(mesh, frame) {
673
+ const crowd = mesh instanceof SkinnedInstancedMesh3D ? mesh : undefined;
674
+ const revisions = crowd ? undefined : instanceStreamRevisions3D(mesh);
675
+ const matrices = crowd?.drawMatrices ?? mesh.instanceMatrices;
676
+ const matrixVersion = revisions?.matrices ?? mesh.instanceVersion;
677
+ let entry = this.#instances.get(mesh);
678
+ const resident = this.uploadInstances(entry?.matrices, matrices, matrixVersion);
679
+ if (!entry) {
680
+ entry = { matrices: resident, colors: undefined, lastFrame: frame };
681
+ this.#instances.set(mesh, entry);
682
+ }
683
+ else
684
+ entry.matrices = resident;
685
+ entry.lastFrame = frame;
686
+ const colors = crowd ? crowd.drawColors : mesh.instanceColors;
687
+ if (colors)
688
+ entry.colors = this.uploadInstances(entry.colors, colors, revisions?.colors ?? mesh.instanceVersion);
689
+ else if (entry.colors)
690
+ entry.colors.source = undefined;
691
+ if (crowd)
692
+ entry.animation = this.uploadInstances(entry.animation, crowd.drawAnimation, mesh.instanceVersion);
693
+ return entry;
694
+ }
695
+ /** Bind group holding the bone matrices and morph deltas for a mesh. */
696
+ skin(mesh, gpu, skinned, frame) {
697
+ const crowd = !skinned && mesh instanceof SkinnedInstancedMesh3D ? mesh.animations : undefined;
698
+ if (!skinned && !gpu.morph && !crowd)
699
+ return this.#dummySkin;
700
+ let bonesBuffer = this.#dummyBones;
701
+ if (crowd) {
702
+ // Baked poses are uploaded once and stay until the table is disposed.
703
+ let table = this.#animations.get(crowd);
704
+ if (!table) {
705
+ table = this.device.createBuffer({
706
+ size: crowd.data.byteLength,
707
+ usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.COPY_DST
708
+ });
709
+ this.device.queue.writeBuffer(table, 0, crowd.data.buffer, crowd.data.byteOffset, crowd.data.byteLength);
710
+ this.#animations.set(crowd, table);
711
+ const created = table;
712
+ crowd.onDispose(() => {
713
+ if (this.#animations.get(crowd) === created) {
714
+ created.destroy();
715
+ this.#animations.delete(crowd);
716
+ }
717
+ });
718
+ }
719
+ bonesBuffer = table;
720
+ }
721
+ if (skinned) {
722
+ const skeleton = mesh.skeleton, count = skeleton.bones.length;
723
+ let bones = this.#bones.get(skeleton);
724
+ if (!bones || bones.count !== count) {
725
+ bones?.buffer.destroy();
726
+ bones = {
727
+ buffer: this.device.createBuffer({
728
+ size: Math.max(count, 1) * 64,
729
+ usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.COPY_DST
730
+ }),
731
+ version: -1,
732
+ count,
733
+ lastFrame: frame
734
+ };
735
+ this.#bones.set(skeleton, bones);
736
+ }
737
+ bones.lastFrame = frame;
738
+ if (bones.version !== skeleton.version && count > 0) {
739
+ this.device.queue.writeBuffer(bones.buffer, 0, skeleton.boneMatrices.buffer, skeleton.boneMatrices.byteOffset, skeleton.boneMatrices.byteLength);
740
+ bones.version = skeleton.version;
741
+ }
742
+ bonesBuffer = bones.buffer;
743
+ }
744
+ const morphBuffer = gpu.morph?.buffer ?? this.#dummyMorph;
745
+ let entry = this.#skins.get(mesh);
746
+ if (!entry || entry.bones !== bonesBuffer || entry.morph !== morphBuffer) {
747
+ entry = { group: this.createSkinGroup(bonesBuffer, morphBuffer), bones: bonesBuffer, morph: morphBuffer };
748
+ this.#skins.set(mesh, entry);
749
+ }
750
+ return entry.group;
751
+ }
752
+ // ---- materials and pipelines ---------------------------------------------------
753
+ material(material) {
754
+ let entry = this.#materials.get(material);
755
+ if (!entry) {
756
+ const buffer = this.device.createBuffer({
757
+ size: MATERIAL_BLOCK_BYTES_3D,
758
+ usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST
759
+ });
760
+ const created = {
761
+ buffer,
762
+ group: undefined,
763
+ key: '',
764
+ serial: -1,
765
+ unsubscribe: material.onDispose(() => {
766
+ if (this.#materials.delete(material))
767
+ buffer.destroy();
768
+ })
769
+ };
770
+ this.#materials.set(material, (entry = created));
771
+ }
772
+ if (entry.serial === this.#serial && entry.group)
773
+ return entry.group;
774
+ entry.serial = this.#serial;
775
+ // Scalars are rewritten once per frame so plain field edits need no touch().
776
+ const data = this.#materialData, e = material.emissiveIntensity, map = material.map;
777
+ data[0] = material.color[0];
778
+ data[1] = material.color[1];
779
+ data[2] = material.color[2];
780
+ data[3] = material.opacity;
781
+ data[4] = material.emissive[0] * e;
782
+ data[5] = material.emissive[1] * e;
783
+ data[6] = material.emissive[2] * e;
784
+ data[7] = material.softness;
785
+ data[8] = material.metallic;
786
+ data[9] = material.roughness;
787
+ data[10] = material.normalScale;
788
+ data[11] = material.occlusionStrength;
789
+ data[12] = material.specular[0];
790
+ data[13] = material.specular[1];
791
+ data[14] = material.specular[2];
792
+ data[15] = material.shading === 'toon' ? material.toonSteps : material.shininess;
793
+ data[16] = material.alphaCutoff;
794
+ data[17] = material.environmentIntensity;
795
+ data[18] = material.clearcoat;
796
+ data[19] = material.clearcoatRoughness;
797
+ let ax = 1, bx = 0, tx = 0, ay = 0, by = 1, ty = 0;
798
+ if (map?.hasTransform) {
799
+ const c = Math.cos(map.rotation), s = Math.sin(map.rotation);
800
+ ax = c * map.repeat[0];
801
+ bx = -s * map.repeat[1];
802
+ tx = map.offset[0];
803
+ ay = s * map.repeat[0];
804
+ by = c * map.repeat[1];
805
+ ty = map.offset[1];
806
+ }
807
+ // WebGPU stores rendered images top row first, so target textures are read with V flipped.
808
+ if (map?.source instanceof RenderTarget3D) {
809
+ ay = -ay;
810
+ by = -by;
811
+ ty = 1 - ty;
812
+ }
813
+ data[20] = ax;
814
+ data[21] = bx;
815
+ data[22] = tx;
816
+ data[23] = 0;
817
+ data[24] = ay;
818
+ data[25] = by;
819
+ data[26] = ty;
820
+ data[27] = 0;
821
+ data[28] = material.rotation;
822
+ data[29] = material.sizeAttenuation ? 1 : 0;
823
+ data[30] = material.reflectionDistortion;
824
+ data[31] = material.reflectionStrength;
825
+ if (material.shader)
826
+ data.set(material.shader.uniforms, 32);
827
+ else
828
+ data.fill(0, 32, 48);
829
+ data[48] = material.sheenColor[0] * material.sheen;
830
+ data[49] = material.sheenColor[1] * material.sheen;
831
+ data[50] = material.sheenColor[2] * material.sheen;
832
+ data[51] = material.sheenRoughness;
833
+ data[52] = material.lightMapIntensity;
834
+ data[53] = material.transmission;
835
+ data[54] = material.ior;
836
+ data[55] = material.thickness;
837
+ data[56] = material.attenuationColor[0];
838
+ data[57] = material.attenuationColor[1];
839
+ data[58] = material.attenuationColor[2];
840
+ data[59] = Number.isFinite(material.attenuationDistance) ? material.attenuationDistance : 0;
841
+ const splat = material.splat;
842
+ data[60] = splat?.repeat[0] ?? 1;
843
+ data[61] = splat?.repeat[1] ?? 1;
844
+ data[62] = splat?.repeat[2] ?? 1;
845
+ data[63] = splat?.repeat[3] ?? 1;
846
+ this.device.queue.writeBuffer(entry.buffer, 0, data);
847
+ const entries = [{ binding: 0, resource: { buffer: entry.buffer } }];
848
+ let key = '';
849
+ // Ground layers borrow the slots of the maps they stand in for; a missing layer reads the first.
850
+ (splat
851
+ ? [
852
+ splat.layers[0],
853
+ material.normalMap,
854
+ splat.layers[3] ?? splat.layers[0],
855
+ splat.layers[2] ?? splat.layers[0],
856
+ splat.layers[1] ?? splat.layers[0],
857
+ splat.weights,
858
+ material.reflectionMap
859
+ ]
860
+ : [
861
+ material.map,
862
+ material.normalMap,
863
+ material.metallicRoughnessMap,
864
+ material.occlusionMap,
865
+ material.emissiveMap,
866
+ material.lightMap,
867
+ material.reflectionMap
868
+ ]).forEach((texture, i) => {
869
+ const gpu = texture && !texture.isDisposed ? this.texture2d(texture) : undefined;
870
+ entries.push({ binding: 1 + i * 2, resource: gpu?.view ?? this.#white }, { binding: 2 + i * 2, resource: gpu?.sampler ?? this.#defaultSampler });
871
+ key += (gpu?.key ?? '-') + '|';
872
+ });
873
+ if (!entry.group || entry.key !== key) {
874
+ entry.group = this.device.createBindGroup({ layout: this.#materialLayout, entries });
875
+ entry.key = key;
876
+ }
877
+ return entry.group;
878
+ }
879
+ features(item, gpu, kind, frameFlags) {
880
+ const { mesh, material } = item, depthOnly = kind === 'depth' || kind === 'scene-depth';
881
+ const lit = material.shading !== 'unlit' && material.shading !== 'matcap' && !depthOnly;
882
+ const uv = gpu.buffers.has('uv'), instanced = mesh.isInstanced;
883
+ // A map on the second coordinate set needs only that set; it falls back to the first when the geometry lacks it.
884
+ const second = gpu.buffers.has('uv1') && !depthOnly, occlusionUv1 = second && lit && material.occlusionMap?.channel === 1;
885
+ const emissiveUv1 = second && material.shading !== 'matcap' && material.emissiveMap?.channel === 1;
886
+ const lightUv1 = second && lit && material.lightMap?.channel === 1, lightMap = lit && material.lightMap !== undefined && (uv || lightUv1);
887
+ const skinning = mesh.skeleton !== undefined && gpu.buffers.has('joints') && gpu.buffers.has('weights');
888
+ // A draw may bind eight vertex buffers. Baked instances use them up, so they do without tangents, vertex colors and second coordinates.
889
+ const baked = instanced && !skinning && mesh instanceof SkinnedInstancedMesh3D;
890
+ return {
891
+ shading: material.shading,
892
+ depthOnly,
893
+ normal: gpu.buffers.has('normal') && (!depthOnly || material.shader?.wgslVertex !== undefined),
894
+ uv: uv &&
895
+ (!depthOnly ||
896
+ (material.map !== undefined && material.alphaMode !== 'opaque') ||
897
+ material.shader?.wgslVertex !== undefined),
898
+ tangent: lit && uv && material.normalMap !== undefined && gpu.buffers.has('tangent') && !baked,
899
+ vertexColor: material.vertexColors && gpu.buffers.has('color') && !baked,
900
+ skinning,
901
+ morph: gpu.morph !== undefined,
902
+ morphNormals: gpu.morph?.channels === 2,
903
+ skinInstancing: instanced &&
904
+ !skinning &&
905
+ mesh instanceof SkinnedInstancedMesh3D &&
906
+ gpu.buffers.has('joints') &&
907
+ gpu.buffers.has('weights'),
908
+ splat: !depthOnly && uv && material.splat !== undefined,
909
+ gpuParticles: instanced && !depthOnly && mesh instanceof GpuParticles3D,
910
+ softDepth: !depthOnly && material.softness > 0 && this.#softDepth,
911
+ instancing: instanced,
912
+ instanceColor: instanced && !depthOnly && mesh.instanceColors !== undefined,
913
+ billboard: material.billboard && !material.screenSpace,
914
+ screenSpace: material.screenSpace,
915
+ map: uv && material.map !== undefined && (!depthOnly || material.alphaMode !== 'opaque'),
916
+ mapFromTarget: !depthOnly && uv && material.map?.source instanceof RenderTarget3D,
917
+ normalMap: lit && uv && material.normalMap !== undefined,
918
+ metallicRoughnessMap: lit && uv && material.metallicRoughnessMap !== undefined && material.shading === 'standard',
919
+ occlusionMap: lit && (uv || occlusionUv1) && material.occlusionMap !== undefined,
920
+ uv1: (occlusionUv1 || emissiveUv1 || lightUv1) && !baked,
921
+ occlusionUv1: occlusionUv1 && !baked,
922
+ emissiveUv1: emissiveUv1 && !baked,
923
+ lightMap,
924
+ lightUv1: lightUv1 && !baked,
925
+ transmission: !depthOnly && this.#grabbed && material.shading === 'standard' && material.transmission > 0,
926
+ emissiveMap: !depthOnly && (uv || emissiveUv1) && material.emissiveMap !== undefined && material.shading !== 'matcap',
927
+ alphaMask: material.alphaMode === 'mask',
928
+ alphaBlend: material.alphaMode === 'blend',
929
+ premultipliedAlpha: !depthOnly && material.alphaMode === 'blend' && material.blending === 'premultiplied',
930
+ flatShading: material.flatShading,
931
+ doubleSided: material.side === 'double',
932
+ receiveShadow: lit && mesh.receiveShadow && this.#shadowCount > 0,
933
+ environment: lit && frameFlags.environment,
934
+ fog: !depthOnly && frameFlags.fog && material.fog,
935
+ ...(!depthOnly && material.shader?.wgsl !== undefined
936
+ ? { customKey: material.shader.key, customWgsl: material.shader.wgsl }
937
+ : {}),
938
+ ...(material.shader?.wgslVertex !== undefined
939
+ ? { customKey: material.shader.key, customVertexWgsl: material.shader.wgslVertex }
940
+ : {}),
941
+ ...(lit && material.shader?.wgslNormal !== undefined
942
+ ? { customKey: material.shader.key, customNormalWgsl: material.shader.wgslNormal }
943
+ : {}),
944
+ reflectionMap: lit && material.shading === 'standard' && material.reflectionMap !== undefined,
945
+ toneMapped: !depthOnly && this.#frameToneMapping !== 'none' && material.toneMapped,
946
+ linearOutput: kind === 'target' || kind === 'hdr'
947
+ };
948
+ }
949
+ pipeline(features, item, gpu, kind, mirrored, wire) {
950
+ const { geometry, material, mesh } = item, shadow = kind === 'depth', depthOnly = shadow || kind === 'scene-depth';
951
+ const featureKey = shaderFeatureKey3D(features);
952
+ const topology = wire
953
+ ? 'line-list'
954
+ : geometry.topology === 'triangles'
955
+ ? 'triangle-list'
956
+ : geometry.topology === 'lines'
957
+ ? 'line-list'
958
+ : geometry.topology === 'line-strip'
959
+ ? 'line-strip'
960
+ : 'point-list';
961
+ // Shadow maps draw both faces: closed and open meshes then cast alike.
962
+ const cull = shadow || material.side === 'double' || material.billboard ? 'none' : material.side === 'back' ? 'front' : 'back';
963
+ const blend = !depthOnly && material.alphaMode === 'blend' ? material.blending : 'off';
964
+ const depthWrite = shadow || material.depthWrite, offset = shadow ? '1.5,2' : material.polygonOffset ? material.polygonOffset.join(',') : '';
965
+ const colorSize = geometry.getAttribute('color')?.itemSize ?? 4, instanceColorSize = mesh.isInstanced ? mesh.instanceColorSize : 4;
966
+ const strip = topology === 'line-strip' && gpu.index ? gpu.index.format : '';
967
+ const key = [
968
+ featureKey,
969
+ kind,
970
+ topology,
971
+ cull,
972
+ mirrored ? 'cw' : 'ccw',
973
+ blend,
974
+ depthWrite,
975
+ material.depthTest,
976
+ offset,
977
+ colorSize,
978
+ instanceColorSize,
979
+ strip
980
+ ].join('/');
981
+ let pipeline = this.#pipelines.get(key);
982
+ if (pipeline)
983
+ return pipeline;
984
+ let module = this.#modules.get(featureKey);
985
+ if (!module) {
986
+ module = this.device.createShaderModule({ code: buildMaterialWgsl3D(features), label: featureKey });
987
+ this.#modules.set(featureKey, module);
988
+ }
989
+ const buffers = [];
990
+ const add = (enabled, location, format, stride) => {
991
+ if (enabled)
992
+ buffers.push({ arrayStride: stride, attributes: [{ shaderLocation: location, offset: 0, format }] });
993
+ };
994
+ add(true, 0, 'float32x3', 12);
995
+ add(features.normal, 1, 'float32x3', 12);
996
+ add(features.uv, 2, 'float32x2', 8);
997
+ add(features.tangent, 3, 'float32x4', 16);
998
+ add(features.vertexColor, 4, colorSize === 3 ? 'float32x3' : 'float32x4', colorSize * 4);
999
+ add(features.skinning || features.skinInstancing === true, 5, 'uint32x4', 16);
1000
+ add(features.skinning || features.skinInstancing === true, 6, 'float32x4', 16);
1001
+ add(features.uv1, 7, 'float32x2', 8);
1002
+ if (features.instancing) {
1003
+ buffers.push({
1004
+ arrayStride: 64,
1005
+ stepMode: 'instance',
1006
+ attributes: [0, 1, 2, 3].map(column => ({
1007
+ shaderLocation: 8 + column,
1008
+ offset: column * 16,
1009
+ format: 'float32x4'
1010
+ }))
1011
+ });
1012
+ }
1013
+ if (features.instanceColor) {
1014
+ buffers.push({
1015
+ arrayStride: instanceColorSize * 4,
1016
+ stepMode: 'instance',
1017
+ attributes: [{ shaderLocation: 12, offset: 0, format: instanceColorSize === 3 ? 'float32x3' : 'float32x4' }]
1018
+ });
1019
+ }
1020
+ if (features.skinInstancing)
1021
+ buffers.push({
1022
+ arrayStride: 48,
1023
+ stepMode: 'instance',
1024
+ attributes: [0, 1, 2].map(part => ({
1025
+ shaderLocation: 13 + part,
1026
+ offset: part * 16,
1027
+ format: 'float32x4'
1028
+ }))
1029
+ });
1030
+ const blendState = blend === 'off'
1031
+ ? undefined
1032
+ : blend === 'additive'
1033
+ ? { color: { srcFactor: 'src-alpha', dstFactor: 'one' }, alpha: { srcFactor: 'zero', dstFactor: 'one' } }
1034
+ : blend === 'multiply'
1035
+ ? { color: { srcFactor: 'dst', dstFactor: 'zero' }, alpha: { srcFactor: 'zero', dstFactor: 'one' } }
1036
+ : blend === 'premultiplied'
1037
+ ? {
1038
+ color: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha' },
1039
+ alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha' }
1040
+ }
1041
+ : {
1042
+ color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha' },
1043
+ alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha' }
1044
+ };
1045
+ const needsFragment = !depthOnly || features.alphaMask || features.alphaBlend;
1046
+ const filled = topology === 'triangle-list';
1047
+ const descriptor = {
1048
+ label: key,
1049
+ layout: depthOnly ? this.#depthPipelineLayout : this.#pipelineLayout,
1050
+ vertex: { module, entryPoint: 'vertexMain', buffers },
1051
+ primitive: {
1052
+ topology,
1053
+ cullMode: cull,
1054
+ frontFace: mirrored ? 'cw' : 'ccw',
1055
+ ...(strip ? { stripIndexFormat: strip } : {})
1056
+ },
1057
+ depthStencil: {
1058
+ format: depthOnly ? SHADOW_FORMAT : DEPTH_FORMAT,
1059
+ depthWriteEnabled: depthWrite,
1060
+ depthCompare: material.depthTest || shadow ? 'less-equal' : 'always',
1061
+ // Depth bias applies to filled triangles only.
1062
+ ...(filled && shadow ? { depthBias: 2, depthBiasSlopeScale: 1.5 } : {}),
1063
+ ...(filled && !shadow && material.polygonOffset
1064
+ ? { depthBias: Math.round(material.polygonOffset[1]), depthBiasSlopeScale: material.polygonOffset[0] }
1065
+ : {})
1066
+ },
1067
+ multisample: { count: kind === 'canvas' ? this.#sampleCount : 1 },
1068
+ ...(needsFragment
1069
+ ? {
1070
+ fragment: {
1071
+ module,
1072
+ entryPoint: 'fragmentMain',
1073
+ targets: depthOnly
1074
+ ? []
1075
+ : [{ format: this.colorFormat(kind), ...(blendState ? { blend: blendState } : {}) }]
1076
+ }
1077
+ }
1078
+ : {})
1079
+ };
1080
+ pipeline = this.device.createRenderPipeline(descriptor);
1081
+ this.#pipelines.set(key, pipeline);
1082
+ return pipeline;
1083
+ }
1084
+ // ---- drawing -----------------------------------------------------------------
1085
+ writeObject(mesh, gpu, skinned) {
1086
+ const index = this.#objectCount++, o = index * (OBJECT_BLOCK_BYTES_3D / 4), floats = this.#objectFloats, ints = this.#objectInts;
1087
+ if (skinned) {
1088
+ floats.set(IDENTITY4, o);
1089
+ floats.set(mesh.bindMatrix, o + 28);
1090
+ }
1091
+ else {
1092
+ floats.set(mesh.matrixWorld, o);
1093
+ const normal = mat3NormalFromMat4(this.#scratch9, mesh.matrixWorld);
1094
+ for (let column = 0; column < 3; column++) {
1095
+ floats[o + 16 + column * 4] = normal[column * 3];
1096
+ floats[o + 17 + column * 4] = normal[column * 3 + 1];
1097
+ floats[o + 18 + column * 4] = normal[column * 3 + 2];
1098
+ }
1099
+ }
1100
+ if (gpu.morph) {
1101
+ writeObjectMorph3D(mesh, gpu, floats, ints, o);
1102
+ }
1103
+ else
1104
+ ints[o + 46] = 0;
1105
+ return index * OBJECT_BLOCK_BYTES_3D;
1106
+ }
1107
+ // Pass-local memo of the last bound state; consecutive draws that share it skip the redundant calls.
1108
+ #boundPipeline;
1109
+ #boundMaterial;
1110
+ #boundSkin;
1111
+ #boundVertices;
1112
+ #boundIndex;
1113
+ #drawVariants = new WeakMap();
1114
+ #grabbed = false;
1115
+ resetPassState() {
1116
+ this.#boundPipeline = undefined;
1117
+ this.#boundMaterial = undefined;
1118
+ this.#boundSkin = undefined;
1119
+ this.#boundVertices = undefined;
1120
+ this.#boundIndex = undefined;
1121
+ }
1122
+ draw(pass, item, kind, frameFlags) {
1123
+ const { mesh, geometry, material } = item, frame = this.#list.frame;
1124
+ const gpu = this.geometry(geometry);
1125
+ if (!gpu.buffers.has('position'))
1126
+ return;
1127
+ const instanced = mesh.isInstanced;
1128
+ const instances = mesh instanceof SkinnedInstancedMesh3D ? mesh.drawCount : instanced ? mesh.count : 1;
1129
+ if (instances <= 0 || this.#objectCount >= this.#objectCapacity)
1130
+ return;
1131
+ const world = mesh.matrixWorld;
1132
+ const determinant = world[0] * (world[5] * world[10] - world[6] * world[9]) -
1133
+ world[4] * (world[1] * world[10] - world[2] * world[9]) +
1134
+ world[8] * (world[1] * world[6] - world[2] * world[5]);
1135
+ const wire = material.wireframe && kind !== 'depth' && geometry.topology === 'triangles';
1136
+ // Everything that selects a pipeline besides the material and geometry themselves,
1137
+ // packed into one number so the common case is a single map lookup.
1138
+ const bits = (kind === 'canvas' ? 0 : kind === 'target' ? 1 : kind === 'depth' ? 2 : kind === 'hdr' ? 3 : 65536) |
1139
+ (wire ? 4 : 0) |
1140
+ (determinant < 0 ? 8 : 0) |
1141
+ (instanced ? 16 : 0) |
1142
+ (instanced && mesh.instanceColors ? 32 : 0) |
1143
+ (mesh.skeleton ? 64 : 0) |
1144
+ (mesh.receiveShadow && this.#shadowCount > 0 ? 128 : 0) |
1145
+ (frameFlags.fog ? 256 : 0) |
1146
+ (frameFlags.environment ? 512 : 0) |
1147
+ (this.#frameToneMapping !== 'none' ? 1024 : 0) |
1148
+ (instanced && mesh.instanceColorSize === 4 ? 2048 : 0) |
1149
+ (material.side === 'double' ? 4096 : material.side === 'back' ? 8192 : 0) |
1150
+ (mesh instanceof SkinnedInstancedMesh3D ? 16384 : 0) |
1151
+ (mesh instanceof GpuParticles3D ? 32768 : 0);
1152
+ let cache = this.#drawVariants.get(material);
1153
+ if (!cache || cache.version !== material.version)
1154
+ this.#drawVariants.set(material, (cache = { version: material.version, variants: new Map() }));
1155
+ // Material fields that select shader features or pipeline state. They are read every
1156
+ // draw so plain assignments (a new map, another blend mode) need no touch().
1157
+ const map = material.map;
1158
+ const surface = (map ? 1 : 0) |
1159
+ (map?.source instanceof RenderTarget3D ? 2 : 0) |
1160
+ (material.normalMap ? 4 : 0) |
1161
+ (material.metallicRoughnessMap ? 8 : 0) |
1162
+ (material.occlusionMap ? 16 : 0) |
1163
+ (material.emissiveMap ? 32 : 0) |
1164
+ (material.alphaMode === 'mask' ? 64 : material.alphaMode === 'blend' ? 128 : 0) |
1165
+ (material.blending === 'premultiplied'
1166
+ ? 256
1167
+ : material.blending === 'additive'
1168
+ ? 32768
1169
+ : material.blending === 'multiply'
1170
+ ? 65536
1171
+ : 0) |
1172
+ (material.flatShading ? 512 : 0) |
1173
+ (material.vertexColors ? 1024 : 0) |
1174
+ (material.billboard ? 2048 : 0) |
1175
+ (material.screenSpace ? 4096 : 0) |
1176
+ (material.depthTest ? 8192 : 0) |
1177
+ (material.depthWrite ? 16384 : 0) |
1178
+ (material.fog ? 131072 : 0) |
1179
+ (material.toneMapped ? 262144 : 0) |
1180
+ (material.polygonOffset ? 524288 : 0) |
1181
+ (material.occlusionMap?.channel === 1 ? 1048576 : 0) |
1182
+ (material.emissiveMap?.channel === 1 ? 2097152 : 0) |
1183
+ (material.lightMap ? 4194304 : 0) |
1184
+ (material.lightMap?.channel === 1 ? 8388608 : 0) |
1185
+ (material.reflectionMap ? 16777216 : 0) |
1186
+ (material.softness > 0 && this.#softDepth ? 33554432 : 0) |
1187
+ (material.splat ? 67108864 : 0);
1188
+ const variantKey = surface * 131072 + bits;
1189
+ let byGeometry = cache.variants.get(geometry.id);
1190
+ if (!byGeometry)
1191
+ cache.variants.set(geometry.id, (byGeometry = new Map()));
1192
+ let variant = byGeometry.get(variantKey);
1193
+ if (!variant || variant.layoutVersion !== gpu.layoutVersion) {
1194
+ const built = this.features(item, gpu, kind, frameFlags);
1195
+ variant = {
1196
+ features: built,
1197
+ pipeline: this.pipeline(built, item, gpu, kind, determinant < 0 && !built.skinning, wire),
1198
+ layoutVersion: gpu.layoutVersion
1199
+ };
1200
+ byGeometry.set(variantKey, variant);
1201
+ }
1202
+ const features = variant.features;
1203
+ if (variant.pipeline !== this.#boundPipeline) {
1204
+ pass.setPipeline(variant.pipeline);
1205
+ this.#boundPipeline = variant.pipeline;
1206
+ }
1207
+ const materialGroup = this.material(material);
1208
+ if (materialGroup !== this.#boundMaterial) {
1209
+ pass.setBindGroup(1, materialGroup);
1210
+ this.#boundMaterial = materialGroup;
1211
+ }
1212
+ pass.setBindGroup(2, this.#objectGroup, [this.writeObject(mesh, gpu, features.skinning)]);
1213
+ const skinGroup = this.skin(mesh, gpu, features.skinning, frame);
1214
+ if (skinGroup !== this.#boundSkin) {
1215
+ pass.setBindGroup(3, skinGroup);
1216
+ this.#boundSkin = skinGroup;
1217
+ }
1218
+ // Vertex bindings depend on the geometry and on which attributes this variant reads.
1219
+ if (instanced || this.#boundVertices !== variant || this.#boundPipeline !== variant.pipeline) {
1220
+ let slot = 0;
1221
+ const bind = (enabled, name) => {
1222
+ if (enabled)
1223
+ pass.setVertexBuffer(slot++, gpu.buffers.get(name).buffer);
1224
+ };
1225
+ bind(true, 'position');
1226
+ bind(features.normal, 'normal');
1227
+ bind(features.uv, 'uv');
1228
+ bind(features.tangent, 'tangent');
1229
+ bind(features.vertexColor, 'color');
1230
+ bind(features.skinning || features.skinInstancing === true, 'joints');
1231
+ bind(features.skinning || features.skinInstancing === true, 'weights');
1232
+ bind(features.uv1, 'uv1');
1233
+ if (instanced) {
1234
+ const instance = this.instances(mesh, frame);
1235
+ pass.setVertexBuffer(slot++, instance.matrices.buffer);
1236
+ if (features.instanceColor)
1237
+ pass.setVertexBuffer(slot++, instance.colors.buffer);
1238
+ if (features.skinInstancing)
1239
+ pass.setVertexBuffer(slot++, instance.animation.buffer);
1240
+ }
1241
+ this.#boundVertices = instanced ? undefined : variant;
1242
+ this.#boundIndex = undefined;
1243
+ }
1244
+ if (wire) {
1245
+ // Wireframe draws the whole geometry: its edge list is not split by groups.
1246
+ const lines = this.wireframe(geometry, gpu);
1247
+ pass.setIndexBuffer(lines.buffer, 'uint32');
1248
+ pass.drawIndexed(lines.count, instances);
1249
+ this.#boundIndex = undefined;
1250
+ }
1251
+ else if (gpu.index) {
1252
+ if (gpu.index.buffer !== this.#boundIndex) {
1253
+ pass.setIndexBuffer(gpu.index.buffer, gpu.index.format);
1254
+ this.#boundIndex = gpu.index.buffer;
1255
+ }
1256
+ pass.drawIndexed(item.count, instances, item.start);
1257
+ }
1258
+ else
1259
+ pass.draw(item.count, instances, item.start);
1260
+ if (kind !== 'depth' && kind !== 'scene-depth') {
1261
+ this.info.drawCalls++;
1262
+ if (!wire && geometry.topology === 'triangles')
1263
+ this.info.triangles += (item.count / 3) * instances;
1264
+ }
1265
+ }
1266
+ depthItem = {
1267
+ mesh: undefined,
1268
+ geometry: undefined,
1269
+ material: undefined,
1270
+ start: 0,
1271
+ count: 0,
1272
+ depth: 0
1273
+ };
1274
+ drawDepth(pass, mesh) {
1275
+ const geometry = mesh.geometry, item = this.depthItem, groups = geometry.groups, flags = { fog: false, environment: false };
1276
+ if (geometry.topology !== 'triangles')
1277
+ return;
1278
+ item.mesh = mesh;
1279
+ item.geometry = geometry;
1280
+ if (Array.isArray(mesh.material) && groups.length > 0) {
1281
+ for (const group of groups) {
1282
+ item.material = mesh.materialAt(group.materialIndex);
1283
+ item.start = group.start;
1284
+ item.count = group.count;
1285
+ if (item.material.visible && !item.material.isDisposed && !item.material.billboard)
1286
+ this.draw(pass, item, 'depth', flags);
1287
+ }
1288
+ }
1289
+ else {
1290
+ item.material = mesh.materialAt(0);
1291
+ item.start = 0;
1292
+ item.count = geometry.drawCount;
1293
+ if (item.material.visible && !item.material.isDisposed && !item.material.billboard)
1294
+ this.draw(pass, item, 'depth', flags);
1295
+ }
1296
+ }
1297
+ ensureShadowAtlas() {
1298
+ if (!this.#shadowTexture) {
1299
+ const size = this.#shadowAtlasSize;
1300
+ this.#shadowTexture = this.device.createTexture({
1301
+ size: [size, size],
1302
+ format: SHADOW_FORMAT,
1303
+ usage: TEXTURE_USAGE.RENDER_ATTACHMENT | TEXTURE_USAGE.TEXTURE_BINDING
1304
+ });
1305
+ this.#shadowView = this.#shadowTexture.createView();
1306
+ }
1307
+ return this.#shadowView;
1308
+ }
1309
+ canvasAttachments(texture) {
1310
+ const key = texture.width + 'x' + texture.height;
1311
+ if (key !== this.#canvasKey || !this.#canvasDepth) {
1312
+ this.#canvasDepth?.destroy();
1313
+ this.#canvasColor?.destroy();
1314
+ const size = [texture.width, texture.height];
1315
+ this.#canvasDepth = this.device.createTexture({
1316
+ size,
1317
+ format: DEPTH_FORMAT,
1318
+ sampleCount: this.#sampleCount,
1319
+ usage: TEXTURE_USAGE.RENDER_ATTACHMENT
1320
+ });
1321
+ this.#canvasColor =
1322
+ this.#sampleCount > 1
1323
+ ? this.device.createTexture({
1324
+ size,
1325
+ format: this.#format,
1326
+ sampleCount: this.#sampleCount,
1327
+ usage: TEXTURE_USAGE.RENDER_ATTACHMENT
1328
+ })
1329
+ : undefined;
1330
+ this.#canvasKey = key;
1331
+ }
1332
+ return { color: this.#canvasColor?.createView(), depth: this.#canvasDepth.createView() };
1333
+ }
1334
+ colorFormat(kind) {
1335
+ return kind === 'target' ? TARGET_FORMAT : kind === 'hdr' ? HDR_FORMAT : this.#format;
1336
+ }
1337
+ drawSkybox(pass, texture, intensity, camera, kind) {
1338
+ const device = this.device, key = 'skybox/' + kind;
1339
+ if (!mat4Invert(this.#scratch16, camera.viewProjectionMatrix))
1340
+ return;
1341
+ let pipeline = this.#pipelines.get(key);
1342
+ if (!pipeline) {
1343
+ this.#skyLayout ??= device.createBindGroupLayout({
1344
+ entries: [
1345
+ { binding: 0, visibility: SHADER_STAGE.VERTEX | SHADER_STAGE.FRAGMENT, buffer: {} },
1346
+ { binding: 1, visibility: SHADER_STAGE.FRAGMENT, texture: { viewDimension: 'cube' } },
1347
+ { binding: 2, visibility: SHADER_STAGE.FRAGMENT, sampler: {} }
1348
+ ]
1349
+ });
1350
+ const module = device.createShaderModule({ code: SKYBOX_WGSL_3D, label: 'skybox' });
1351
+ pipeline = device.createRenderPipeline({
1352
+ label: key,
1353
+ layout: device.createPipelineLayout({ bindGroupLayouts: [this.#skyLayout] }),
1354
+ vertex: { module, entryPoint: 'vertexMain' },
1355
+ fragment: { module, entryPoint: 'fragmentMain', targets: [{ format: this.colorFormat(kind) }] },
1356
+ primitive: { topology: 'triangle-list' },
1357
+ depthStencil: { format: DEPTH_FORMAT, depthWriteEnabled: false, depthCompare: 'less-equal' },
1358
+ multisample: { count: kind === 'canvas' ? this.#sampleCount : 1 }
1359
+ });
1360
+ this.#pipelines.set(key, pipeline);
1361
+ }
1362
+ this.#skyBuffer ??= device.createBuffer({ size: 80, usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST });
1363
+ const data = new Float32Array(20);
1364
+ data.set(this.#scratch16);
1365
+ data[16] = intensity;
1366
+ data[17] = kind === 'canvas' ? 0 : 1;
1367
+ data[18] = this.exposure;
1368
+ data[19] = this.#frameToneMapping === 'aces' ? 2 : this.#frameToneMapping === 'reinhard' ? 1 : 0;
1369
+ device.queue.writeBuffer(this.#skyBuffer, 0, data);
1370
+ const cube = this.textureCube(texture), groupKey = texture.id + ':' + texture.version;
1371
+ if (!this.#skyGroup || this.#skyGroup.key !== groupKey) {
1372
+ this.#skyGroup = {
1373
+ key: groupKey,
1374
+ group: device.createBindGroup({
1375
+ layout: this.#skyLayout,
1376
+ entries: [
1377
+ { binding: 0, resource: { buffer: this.#skyBuffer } },
1378
+ { binding: 1, resource: cube.view },
1379
+ { binding: 2, resource: cube.sampler }
1380
+ ]
1381
+ })
1382
+ };
1383
+ }
1384
+ pass.setPipeline(pipeline);
1385
+ pass.setBindGroup(0, this.#skyGroup.group);
1386
+ pass.draw(3);
1387
+ this.info.drawCalls++;
1388
+ }
1389
+ /**
1390
+ * Draw one frame to the canvas, or into `target` when given. Returns false
1391
+ * when the device is lost and nothing was drawn.
1392
+ */
1393
+ /**
1394
+ * Draw runs of plain meshes that share a geometry and a material as one
1395
+ * instanced draw each, in the main view and in shadow maps. On by default;
1396
+ * the meshes themselves are untouched.
1397
+ */
1398
+ /** Point lights past the eight nearest are lit by screen tile, up to 256; false drops them instead. */
1399
+ get tiledLights() {
1400
+ return this.#list.tiledLights;
1401
+ }
1402
+ set tiledLights(value) {
1403
+ this.#list.tiledLights = Boolean(value);
1404
+ }
1405
+ get autoInstancing() {
1406
+ return this.#list.autoInstanceThreshold > 1;
1407
+ }
1408
+ set autoInstancing(value) {
1409
+ this.#list.autoInstanceThreshold = value ? 8 : 0;
1410
+ }
1411
+ render(scene, camera, target) {
1412
+ return this.renderView(scene, camera, target);
1413
+ }
1414
+ /** Draw the mirror directly with its own output, shadows and object selection. */
1415
+ renderReflectionPass(scene, camera, pass) {
1416
+ return this.renderView(scene, camera, pass.target, pass);
1417
+ }
1418
+ /** The retained mirror image must still belong to the live WebGPU device. */
1419
+ reuseReflection(target) {
1420
+ return !this.#disposed && !this.#lost && this.#targets.get(target)?.version === target.version;
1421
+ }
1422
+ renderView(scene, camera, target, reflection) {
1423
+ if (this.#disposed)
1424
+ throw new World3DError('WORLD3D_DISPOSED', 'renderer');
1425
+ if (this.#lost)
1426
+ return false;
1427
+ if (!reflection && this.postProcess.enabled && !this.#inPost)
1428
+ return this.renderPost(scene, camera, target);
1429
+ const device = this.device, list = this.#list, info = this.info, kind = target ? (target.format === 'rgba16f' ? 'hdr' : 'target') : 'canvas';
1430
+ if (target?.isDisposed)
1431
+ throw new World3DError('WORLD3D_DISPOSED', 'render target');
1432
+ this.#frameToneMapping = outputToneMapping3D(reflection?.toneMapping ?? this.toneMapping, target);
1433
+ list.build(scene, camera, reflection);
1434
+ this.#serial++;
1435
+ this.#objectCount = 0;
1436
+ info.frame = list.frame;
1437
+ info.drawCalls = info.triangles = 0;
1438
+ info.visited = list.stats.visited;
1439
+ info.culled = list.stats.culled;
1440
+ info.lightsDropped = list.stats.lightsDropped;
1441
+ const atlas = this.ensureShadowAtlas();
1442
+ const plans = planShadows3D(this.#frameData, list, this.#shadowAtlasSize, this.shadowsEnabled && (reflection?.shadows ?? true), true, this.#shadowSlots, camera);
1443
+ this.#shadowCount = plans.length;
1444
+ const environment = scene.environment && !scene.environment.isDisposed ? this.textureCube(scene.environment) : undefined;
1445
+ writeFrameBlock3D(this.#frameData, scene, camera, list, this.#shadowSlots, {
1446
+ exposure: this.exposure,
1447
+ toneMapping: this.#frameToneMapping,
1448
+ environmentMaxMip: environment?.maxMip ?? 0
1449
+ });
1450
+ this.#frameData[FRAME_OFFSETS_3D.clipInfo + 2] = this.viewport ? this.viewport[2] : 1;
1451
+ this.#frameData[FRAME_OFFSETS_3D.clipInfo + 3] = this.viewport ? this.viewport[3] : 1;
1452
+ {
1453
+ // Lights past the eight in the frame block go to the tiled list, read by screen tile.
1454
+ const fullWidth = target ? target.width : this.#context.getCurrentTexture().width, fullHeight = target ? target.height : this.#context.getCurrentTexture().height;
1455
+ const rect = this.viewport;
1456
+ const tileWidth = rect ? Math.max(Math.round(rect[2] * fullWidth), 1) : fullWidth, tileHeight = rect ? Math.max(Math.round(rect[3] * fullHeight), 1) : fullHeight;
1457
+ const originX = rect ? Math.round(rect[0] * fullWidth) : 0, originY = rect ? Math.max(fullHeight - Math.round(rect[1] * fullHeight) - tileHeight, 0) : 0;
1458
+ const tiled = writeTiledLights3D(this.#frameData, this.#tiledTable, list.tiledPointLights, camera.viewProjectionMatrix, tileWidth, tileHeight, true, originX, originY);
1459
+ if (tiled > 0)
1460
+ device.queue.writeBuffer(this.#tiledBuffer, 0, this.#tiledTable);
1461
+ this.info.lightsTiled = tiled;
1462
+ }
1463
+ device.queue.writeBuffer(this.#frameBuffer, 0, this.#frameData);
1464
+ // Surfaces that fade near solid geometry read its depth, drawn once before the frame.
1465
+ const soft = list.transparent.some(item => item.material.softness > 0);
1466
+ const softWidth = target ? target.width : this.#context.getCurrentTexture().width, softHeight = target ? target.height : this.#context.getCurrentTexture().height;
1467
+ if (soft &&
1468
+ (!this.#sceneDepth ||
1469
+ this.#sceneDepth.texture.width !== softWidth ||
1470
+ this.#sceneDepth.texture.height !== softHeight)) {
1471
+ this.#sceneDepth?.texture.destroy();
1472
+ this.#sceneDepth?.buffer.destroy();
1473
+ const texture = device.createTexture({
1474
+ size: [softWidth, softHeight],
1475
+ format: SHADOW_FORMAT,
1476
+ usage: TEXTURE_USAGE.RENDER_ATTACHMENT | TEXTURE_USAGE.TEXTURE_BINDING
1477
+ });
1478
+ const buffer = device.createBuffer({ size: 128, usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST });
1479
+ this.#sceneDepth = {
1480
+ texture,
1481
+ view: texture.createView(),
1482
+ buffer,
1483
+ group: device.createBindGroup({
1484
+ layout: this.#depthFrameLayout,
1485
+ entries: [{ binding: 0, resource: { buffer } }]
1486
+ })
1487
+ };
1488
+ this.#sceneDepthSerial++;
1489
+ }
1490
+ this.#softDepth = soft;
1491
+ const sceneDepthView = soft ? this.#sceneDepth.view : atlas;
1492
+ const frameKey = (environment ? scene.environment.id + ':' + scene.environment.version : '-') +
1493
+ (soft ? '|d' + this.#sceneDepthSerial : '');
1494
+ if (!this.#frameGroup || this.#frameGroupKey !== frameKey) {
1495
+ this.#frameGroup = device.createBindGroup({
1496
+ layout: this.#frameLayout,
1497
+ entries: [
1498
+ { binding: 0, resource: { buffer: this.#frameBuffer } },
1499
+ { binding: 1, resource: atlas },
1500
+ { binding: 2, resource: this.#shadowSampler },
1501
+ { binding: 3, resource: environment?.view ?? this.#whiteCube },
1502
+ { binding: 4, resource: environment?.sampler ?? this.#defaultSampler },
1503
+ { binding: 5, resource: this.#white },
1504
+ { binding: 6, resource: this.#grabSampler },
1505
+ { binding: 7, resource: sceneDepthView },
1506
+ { binding: 8, resource: { buffer: this.#tiledBuffer } }
1507
+ ]
1508
+ });
1509
+ this.#frameGroupKey = frameKey;
1510
+ }
1511
+ // Size the per-draw uniform buffer before any pass references its bind group.
1512
+ let needed = list.opaque.length * (soft ? 2 : 1) + list.transparent.length;
1513
+ for (const plan of plans)
1514
+ for (const mesh of plan.casters)
1515
+ needed += Array.isArray(mesh.material) ? Math.max(mesh.geometry.groups.length, 1) : 1;
1516
+ if (needed > this.#objectCapacity) {
1517
+ while (this.#objectCapacity < needed)
1518
+ this.#objectCapacity *= 2;
1519
+ this.#objectBuffer.destroy();
1520
+ this.#objectBuffer = this.createObjectBuffer();
1521
+ this.#objectGroup = this.createObjectGroup();
1522
+ this.#objectStaging = new ArrayBuffer(this.#objectCapacity * OBJECT_BLOCK_BYTES_3D);
1523
+ this.#objectFloats = new Float32Array(this.#objectStaging);
1524
+ this.#objectInts = new Int32Array(this.#objectStaging);
1525
+ }
1526
+ const encoder = device.createCommandEncoder();
1527
+ if (plans.length > 0) {
1528
+ this.resetPassState();
1529
+ const pass = encoder.beginRenderPass({
1530
+ colorAttachments: [],
1531
+ depthStencilAttachment: { view: atlas, depthClearValue: 1, depthLoadOp: 'clear', depthStoreOp: 'store' }
1532
+ });
1533
+ for (const plan of plans) {
1534
+ let slot = this.#depthFrames[plan.slot];
1535
+ if (!slot) {
1536
+ const buffer = device.createBuffer({ size: 128, usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST });
1537
+ slot = this.#depthFrames[plan.slot] = {
1538
+ buffer,
1539
+ group: device.createBindGroup({
1540
+ layout: this.#depthFrameLayout,
1541
+ entries: [{ binding: 0, resource: { buffer } }]
1542
+ })
1543
+ };
1544
+ }
1545
+ device.queue.writeBuffer(slot.buffer, 0, plan.matrix);
1546
+ pass.setViewport(plan.x, plan.y, plan.tile, plan.tile, 0, 1);
1547
+ pass.setScissorRect(plan.x, plan.y, plan.tile, plan.tile);
1548
+ pass.setBindGroup(0, slot.group);
1549
+ for (const mesh of plan.casters)
1550
+ this.drawDepth(pass, mesh);
1551
+ }
1552
+ pass.end();
1553
+ }
1554
+ if (soft) {
1555
+ const depth = this.#sceneDepth;
1556
+ // The depth-only frame block holds a view-projection matrix followed by the view matrix.
1557
+ device.queue.writeBuffer(depth.buffer, 0, camera.viewProjectionMatrix);
1558
+ device.queue.writeBuffer(depth.buffer, 64, camera.viewMatrix);
1559
+ this.resetPassState();
1560
+ const pass = encoder.beginRenderPass({
1561
+ colorAttachments: [],
1562
+ depthStencilAttachment: { view: depth.view, depthClearValue: 1, depthLoadOp: 'clear', depthStoreOp: 'store' }
1563
+ });
1564
+ const rect = this.viewport;
1565
+ if (rect) {
1566
+ const w = Math.max(Math.round(rect[2] * softWidth), 1), h = Math.max(Math.round(rect[3] * softHeight), 1);
1567
+ const x = Math.min(Math.max(Math.round(rect[0] * softWidth), 0), softWidth - 1), y = Math.min(Math.max(softHeight - Math.round(rect[1] * softHeight) - h, 0), softHeight - 1);
1568
+ pass.setViewport(x, y, Math.min(w, softWidth - x), Math.min(h, softHeight - y), 0, 1);
1569
+ }
1570
+ pass.setBindGroup(0, depth.group);
1571
+ const none = { fog: false, environment: false };
1572
+ // Scene depth follows the main view's culling and material offset.
1573
+ for (const item of list.opaque) {
1574
+ if (item.geometry.topology === 'triangles' &&
1575
+ item.material.depthWrite &&
1576
+ !item.material.billboard &&
1577
+ !item.material.screenSpace)
1578
+ this.draw(pass, item, 'scene-depth', none);
1579
+ }
1580
+ pass.end();
1581
+ }
1582
+ const background = scene.background;
1583
+ // sRGB targets encode on write, so they are cleared with linear values.
1584
+ const encode = target ? (value) => value : linearToSrgb;
1585
+ const clearValue = Array.isArray(background)
1586
+ ? [encode(background[0]), encode(background[1]), encode(background[2]), 1]
1587
+ : [0, 0, 0, (target || this.#alpha) && !background ? 0 : 1];
1588
+ let colorAttachment, depthView, outputWidth, outputHeight, outputTexture;
1589
+ // See-through surfaces read a copy of everything drawn before them, which splits the pass in two.
1590
+ const grab = list.transparent.some(item => item.material.transmission > 0 && item.material.shading === 'standard');
1591
+ const loadOp = this.autoClear ? 'clear' : 'load';
1592
+ if (target) {
1593
+ const entry = this.target(target);
1594
+ colorAttachment = { view: entry.colorView, clearValue, loadOp, storeOp: 'store' };
1595
+ depthView = entry.depthView;
1596
+ outputTexture = entry.color;
1597
+ outputWidth = target.width;
1598
+ outputHeight = target.height;
1599
+ if (!depthView)
1600
+ throw new World3DError('WORLD3D_INPUT_INVALID', 'the WebGPU backend requires render targets with depth');
1601
+ }
1602
+ else {
1603
+ const current = this.#context.getCurrentTexture(), attachments = this.canvasAttachments(current), view = current.createView();
1604
+ // The multisampled color is kept so a later view of the same frame can load it.
1605
+ colorAttachment = attachments.color
1606
+ ? { view: attachments.color, resolveTarget: view, clearValue, loadOp, storeOp: 'store' }
1607
+ : { view, clearValue, loadOp, storeOp: 'store' };
1608
+ depthView = attachments.depth;
1609
+ outputTexture = current;
1610
+ outputWidth = current.width;
1611
+ outputHeight = current.height;
1612
+ }
1613
+ this.resetPassState();
1614
+ const depthStoreOp = target?.depthTexture || grab ? 'store' : 'discard';
1615
+ let pass = encoder.beginRenderPass({
1616
+ colorAttachments: [colorAttachment],
1617
+ depthStencilAttachment: { view: depthView, depthClearValue: 1, depthLoadOp: 'clear', depthStoreOp }
1618
+ });
1619
+ const view = this.viewport;
1620
+ const frame = () => {
1621
+ if (!view)
1622
+ return;
1623
+ // The public rectangle has its origin at the bottom left; WebGPU's is at the top left.
1624
+ const w = Math.max(Math.round(view[2] * outputWidth), 1), h = Math.max(Math.round(view[3] * outputHeight), 1);
1625
+ const x = Math.min(Math.max(Math.round(view[0] * outputWidth), 0), outputWidth - 1), y = Math.min(Math.max(outputHeight - Math.round(view[1] * outputHeight) - h, 0), outputHeight - 1);
1626
+ const cw = Math.min(w, outputWidth - x), ch = Math.min(h, outputHeight - y);
1627
+ pass.setViewport(x, y, cw, ch, 0, 1);
1628
+ pass.setScissorRect(x, y, cw, ch);
1629
+ };
1630
+ frame();
1631
+ const flags = { fog: scene.fog !== undefined, environment: environment !== undefined };
1632
+ pass.setBindGroup(0, this.#frameGroup);
1633
+ for (const item of list.opaque)
1634
+ this.draw(pass, item, kind, flags);
1635
+ if (background instanceof CubeTexture3D && !background.isDisposed) {
1636
+ this.drawSkybox(pass, background, scene.backgroundIntensity, camera, kind);
1637
+ this.resetPassState();
1638
+ pass.setBindGroup(0, this.#frameGroup);
1639
+ }
1640
+ if (grab) {
1641
+ pass.end();
1642
+ const format = this.colorFormat(kind);
1643
+ let entry = this.#grabs.get(kind);
1644
+ if (!entry ||
1645
+ entry.texture.width !== outputWidth ||
1646
+ entry.texture.height !== outputHeight ||
1647
+ entry.texture.format !== format) {
1648
+ entry?.texture.destroy();
1649
+ const texture = device.createTexture({
1650
+ size: [outputWidth, outputHeight],
1651
+ format,
1652
+ usage: TEXTURE_USAGE.TEXTURE_BINDING | TEXTURE_USAGE.COPY_DST
1653
+ });
1654
+ this.#grabs.set(kind, (entry = { texture, view: texture.createView(), group: undefined, key: '' }));
1655
+ }
1656
+ if (!entry.group || entry.key !== frameKey) {
1657
+ entry.group = device.createBindGroup({
1658
+ layout: this.#frameLayout,
1659
+ entries: [
1660
+ { binding: 0, resource: { buffer: this.#frameBuffer } },
1661
+ { binding: 1, resource: atlas },
1662
+ { binding: 2, resource: this.#shadowSampler },
1663
+ { binding: 3, resource: environment?.view ?? this.#whiteCube },
1664
+ { binding: 4, resource: environment?.sampler ?? this.#defaultSampler },
1665
+ { binding: 5, resource: entry.view },
1666
+ { binding: 6, resource: this.#grabSampler },
1667
+ { binding: 7, resource: sceneDepthView },
1668
+ { binding: 8, resource: { buffer: this.#tiledBuffer } }
1669
+ ]
1670
+ });
1671
+ entry.key = frameKey;
1672
+ }
1673
+ encoder.copyTextureToTexture({ texture: outputTexture }, { texture: entry.texture }, [outputWidth, outputHeight]);
1674
+ pass = encoder.beginRenderPass({
1675
+ colorAttachments: [{ ...colorAttachment, loadOp: 'load' }],
1676
+ depthStencilAttachment: {
1677
+ view: depthView,
1678
+ depthLoadOp: 'load',
1679
+ depthStoreOp: target?.depthTexture ? 'store' : 'discard'
1680
+ }
1681
+ });
1682
+ frame();
1683
+ this.resetPassState();
1684
+ pass.setBindGroup(0, entry.group);
1685
+ this.#grabbed = true;
1686
+ }
1687
+ for (const item of list.transparent)
1688
+ this.draw(pass, item, kind, flags);
1689
+ this.#grabbed = false;
1690
+ pass.end();
1691
+ if (this.#objectCount > 0)
1692
+ device.queue.writeBuffer(this.#objectBuffer, 0, this.#objectStaging, 0, this.#objectCount * OBJECT_BLOCK_BYTES_3D);
1693
+ device.queue.submit([encoder.finish()]);
1694
+ this.prune(list.frame);
1695
+ info.programs = this.#pipelines.size;
1696
+ info.geometries = this.#geometries.size;
1697
+ info.textures = this.#textures.size;
1698
+ info.shadowMaps = plans.length;
1699
+ return true;
1700
+ }
1701
+ /** Draw the scene into the half-float chain target, then post-process into the output. */
1702
+ renderPost(scene, camera, target) {
1703
+ if (target?.isDisposed)
1704
+ throw new World3DError('WORLD3D_DISPOSED', 'render target');
1705
+ const current = target ? undefined : this.#context.getCurrentTexture();
1706
+ const width = target ? target.width : current.width, height = target ? target.height : current.height;
1707
+ const post = (this.#post ??= new PostChainWebGPU3D(this.device));
1708
+ post.scene.setSize(Math.max(width, 1), Math.max(height, 1));
1709
+ this.#inPost = true;
1710
+ try {
1711
+ if (!this.render(scene, camera, post.scene))
1712
+ return false;
1713
+ }
1714
+ finally {
1715
+ this.#inPost = false;
1716
+ }
1717
+ const encoder = this.device.createCommandEncoder();
1718
+ const output = target ? this.target(target).colorView : current.createView();
1719
+ const format = target ? (target.format === 'rgba16f' ? HDR_FORMAT : TARGET_FORMAT) : this.#format;
1720
+ // 8-bit targets encode sRGB on write and half-float targets store linear light; only the canvas needs encoded values.
1721
+ // Outlined objects are drawn once more, flat white, into a mask the composite traces.
1722
+ let maskView;
1723
+ if (outlineActive3D(this.postProcess)) {
1724
+ post.mask.setSize(Math.max(width, 1), Math.max(height, 1));
1725
+ const saved = {
1726
+ layerMask: camera.layerMask,
1727
+ override: scene.overrideMaterial,
1728
+ background: scene.background,
1729
+ shadows: this.shadowsEnabled,
1730
+ planes: scene.clippingPlanes
1731
+ };
1732
+ camera.layerMask = this.postProcess.outlineLayers;
1733
+ scene.overrideMaterial = post.maskMaterial;
1734
+ scene.background = [0, 0, 0];
1735
+ this.shadowsEnabled = false;
1736
+ this.#inPost = true;
1737
+ // The counters describe the scene, not this helper pass.
1738
+ const counted = { ...this.info };
1739
+ try {
1740
+ if (this.render(scene, camera, post.mask))
1741
+ maskView = this.target(post.mask).colorView;
1742
+ }
1743
+ finally {
1744
+ this.#inPost = false;
1745
+ camera.layerMask = saved.layerMask;
1746
+ scene.overrideMaterial = saved.override;
1747
+ scene.background = saved.background;
1748
+ this.shadowsEnabled = saved.shadows;
1749
+ Object.assign(this.info, counted);
1750
+ }
1751
+ }
1752
+ const sceneEntry = this.target(post.scene);
1753
+ this.info.drawCalls += post.run(encoder, sceneEntry.colorView, sceneEntry.depthView, maskView, postViewFromCamera3D(camera), width, height, output, format, target !== undefined, this.postProcess, target?.format === 'rgba16f' ? 'none' : this.toneMapping);
1754
+ this.device.queue.submit([encoder.finish()]);
1755
+ return true;
1756
+ }
1757
+ /** Retire per-mesh and per-skeleton buffers that have not been drawn recently. */
1758
+ prune(frame) {
1759
+ if (frame % PRUNE_INTERVAL !== 0)
1760
+ return;
1761
+ for (const [mesh, entry] of this.#instances) {
1762
+ if (frame - entry.lastFrame < PRUNE_INTERVAL)
1763
+ continue;
1764
+ entry.matrices.buffer.destroy();
1765
+ entry.colors?.buffer.destroy();
1766
+ entry.animation?.buffer.destroy();
1767
+ this.#instances.delete(mesh);
1768
+ }
1769
+ for (const [skeleton, entry] of this.#bones) {
1770
+ if (frame - entry.lastFrame < PRUNE_INTERVAL)
1771
+ continue;
1772
+ entry.buffer.destroy();
1773
+ this.#bones.delete(skeleton);
1774
+ }
1775
+ }
1776
+ /** RGBA8 pixels of a render target, top row first. */
1777
+ async readRenderTargetPixels(target) {
1778
+ if (target.format === 'rgba16f')
1779
+ throw new World3DError('WORLD3D_INPUT_INVALID', 'half-float targets cannot be read back as bytes');
1780
+ if (this.#disposed)
1781
+ throw new World3DError('WORLD3D_DISPOSED', 'renderer');
1782
+ if (this.#lost)
1783
+ throw new World3DError('WORLD3D_CONTEXT_LOST', 'readback');
1784
+ const device = this.device, entry = this.target(target), width = target.width, height = target.height;
1785
+ // Buffer rows must be padded to a multiple of 256 bytes.
1786
+ const bytesPerRow = Math.ceil((width * 4) / 256) * 256;
1787
+ const buffer = device.createBuffer({
1788
+ size: bytesPerRow * height,
1789
+ usage: BUFFER_USAGE.COPY_DST | BUFFER_USAGE.MAP_READ
1790
+ });
1791
+ try {
1792
+ const encoder = device.createCommandEncoder();
1793
+ encoder.copyTextureToBuffer({ texture: entry.color }, { buffer, bytesPerRow, rowsPerImage: height }, [
1794
+ width,
1795
+ height
1796
+ ]);
1797
+ device.queue.submit([encoder.finish()]);
1798
+ await buffer.mapAsync(MAP_MODE_READ);
1799
+ const mapped = new Uint8Array(buffer.getMappedRange()), out = new Uint8Array(width * height * 4);
1800
+ for (let y = 0; y < height; y++)
1801
+ out.set(mapped.subarray(y * bytesPerRow, y * bytesPerRow + width * 4), y * width * 4);
1802
+ buffer.unmap();
1803
+ return out;
1804
+ }
1805
+ catch (cause) {
1806
+ throw new World3DError('WORLD3D_RESOURCE_FAILED', 'render target readback', cause);
1807
+ }
1808
+ finally {
1809
+ buffer.destroy();
1810
+ }
1811
+ }
1812
+ /** Release every GPU object and unconfigure the canvas. Idempotent. */
1813
+ dispose() {
1814
+ if (this.#disposed)
1815
+ return;
1816
+ this.#disposed = true;
1817
+ this.#unsubscribeDeviceLoss();
1818
+ this.#list.clear();
1819
+ this.#post?.dispose();
1820
+ this.#post = undefined;
1821
+ for (const geometry of [...this.#geometries.keys()]) {
1822
+ this.#geometries.get(geometry).unsubscribe();
1823
+ this.releaseGeometry(geometry);
1824
+ }
1825
+ for (const entry of this.#textures.values()) {
1826
+ entry.unsubscribe();
1827
+ entry.texture.destroy();
1828
+ }
1829
+ for (const entry of this.#targets.values()) {
1830
+ entry.unsubscribe();
1831
+ entry.color.destroy();
1832
+ entry.depth?.destroy();
1833
+ }
1834
+ for (const entry of this.#materials.values()) {
1835
+ entry.unsubscribe();
1836
+ entry.buffer.destroy();
1837
+ }
1838
+ for (const entry of this.#instances.values()) {
1839
+ entry.matrices.buffer.destroy();
1840
+ entry.colors?.buffer.destroy();
1841
+ entry.animation?.buffer.destroy();
1842
+ }
1843
+ for (const entry of this.#bones.values())
1844
+ entry.buffer.destroy();
1845
+ for (const table of this.#animations.values())
1846
+ table.destroy();
1847
+ this.#animations.clear();
1848
+ for (const slot of this.#depthFrames)
1849
+ slot?.buffer.destroy();
1850
+ this.#textures.clear();
1851
+ this.#targets.clear();
1852
+ this.#materials.clear();
1853
+ this.#instances.clear();
1854
+ this.#bones.clear();
1855
+ this.#pipelines.clear();
1856
+ this.#modules.clear();
1857
+ this.#frameBuffer.destroy();
1858
+ this.#tiledBuffer.destroy();
1859
+ this.#objectBuffer.destroy();
1860
+ this.#skyBuffer?.destroy();
1861
+ this.#dummyBones.destroy();
1862
+ this.#dummyMorph.destroy();
1863
+ this.#whiteTexture.destroy();
1864
+ this.#whiteCubeTexture.destroy();
1865
+ for (const entry of this.#grabs.values())
1866
+ entry.texture.destroy();
1867
+ this.#grabs.clear();
1868
+ this.#shadowTexture?.destroy();
1869
+ this.#canvasDepth?.destroy();
1870
+ this.#canvasColor?.destroy();
1871
+ this.#sceneDepth?.texture.destroy();
1872
+ this.#sceneDepth?.buffer.destroy();
1873
+ this.#sceneDepth = undefined;
1874
+ try {
1875
+ this.#context.unconfigure();
1876
+ }
1877
+ catch {
1878
+ /* The canvas may already be detached. */
1879
+ }
1880
+ if (this.#ownsDevice)
1881
+ this.device.destroy();
1882
+ }
1883
+ }
1884
+ /** Acquire a device (unless one is borrowed) and create the WebGPU renderer. */
1885
+ export async function createWebGPURenderer3D(options) {
1886
+ const canvas = options?.canvas;
1887
+ if (!canvas || typeof canvas.getContext !== 'function')
1888
+ throw new World3DError('WORLD3D_INPUT_INVALID', 'canvas');
1889
+ if (options.device)
1890
+ return new WebGPURenderer3D(options, options.device, false);
1891
+ if (typeof navigator === 'undefined' || !navigator.gpu)
1892
+ throw new World3DError('WORLD3D_CONTEXT_UNAVAILABLE', 'webgpu');
1893
+ const adapter = await navigator.gpu.requestAdapter({
1894
+ powerPreference: options.powerPreference ?? 'high-performance'
1895
+ });
1896
+ if (!adapter)
1897
+ throw new World3DError('WORLD3D_CONTEXT_UNAVAILABLE', 'webgpu adapter');
1898
+ let device;
1899
+ // Enable every block-compression family the adapter offers so compressed textures can be uploaded.
1900
+ const requiredFeatures = ['texture-compression-bc', 'texture-compression-etc2', 'texture-compression-astc'].filter(feature => adapter.features.has(feature));
1901
+ try {
1902
+ device = await adapter.requestDevice({ requiredFeatures });
1903
+ }
1904
+ catch (cause) {
1905
+ throw new World3DError('WORLD3D_CONTEXT_UNAVAILABLE', 'webgpu device', cause);
1906
+ }
1907
+ try {
1908
+ return new WebGPURenderer3D(options, device, true);
1909
+ }
1910
+ catch (cause) {
1911
+ device.destroy();
1912
+ throw cause;
1913
+ }
1914
+ }
1915
+ //# sourceMappingURL=WebGPURenderer3D.js.map