@volter/game-editor 0.5.156 → 0.5.157

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 (294) hide show
  1. package/BUNDLED_NOTICES +22 -22
  2. package/catalog/entries/blender.json +2 -2
  3. package/catalog/entries/music.json +2 -2
  4. package/dist/.vite/manifest.json +2163 -2163
  5. package/dist/assets/{AssetBudgetPanel-BQdPOlqp.js → AssetBudgetPanel-X38cPCO3.js} +3 -3
  6. package/dist/assets/{AudioViewer-C5y-GQP-.js → AudioViewer-xMM7RZH9.js} +1 -1
  7. package/dist/assets/{CanvasBoardDocument-DbChIzOl.js → CanvasBoardDocument-DCyh4eaO.js} +1 -1
  8. package/dist/assets/{CanvasSceneViewport-BAUsxjQl.js → CanvasSceneViewport-BA8eRjJY.js} +1 -1
  9. package/dist/assets/{ColorInput-DGN6sIXS.js → ColorInput-y8NzQ5q8.js} +1 -1
  10. package/dist/assets/{ColorPicker-C83d-sVK.js → ColorPicker-C3HI90eU.js} +1 -1
  11. package/dist/assets/{EntityModelDocument-D4IbBjti.js → EntityModelDocument-DrWN0e0N.js} +1 -1
  12. package/dist/assets/{EnvironmentAssetDocument-BqTeI8cz.js → EnvironmentAssetDocument-Bv8M7C1O.js} +1 -1
  13. package/dist/assets/{GameplaySessionTimeline-FqH6Sz1y.js → GameplaySessionTimeline-mMVtRemn.js} +1 -1
  14. package/dist/assets/{ImageViewer-C_4yhkuB.js → ImageViewer-D1mswm2G.js} +1 -1
  15. package/dist/assets/InspectorObjectPreview-DMNRuc0X.js +1 -0
  16. package/dist/assets/{JsonAssetDocument-C-drMm6I.js → JsonAssetDocument-DxLYMceV.js} +1 -1
  17. package/dist/assets/{LiveModuleDocument-C73e8H-p.js → LiveModuleDocument-BOO4_ypf.js} +1 -1
  18. package/dist/assets/{LutAssetDocument-DfBf46zV.js → LutAssetDocument-jf9ogNqN.js} +1 -1
  19. package/dist/assets/{ModelAssetDocument-BgP4YOdh.js → ModelAssetDocument-DbtKJsGQ.js} +1 -1
  20. package/dist/assets/{NonThreeAuthoringBootstrap-qnG1AmuP.js → NonThreeAuthoringBootstrap-ChEoVJQP.js} +1 -1
  21. package/dist/assets/{Object3DDocumentToolbar-34bmavxS.js → Object3DDocumentToolbar-Y-jpI3WD.js} +1 -1
  22. package/dist/assets/Object3DDocumentViewport-BOi94JfA.js +2 -0
  23. package/dist/assets/{Object3DPreview-wWjXCo6v.js → Object3DPreview-7LnLFpmg.js} +1 -1
  24. package/dist/assets/{OnlineAssetDetail-C4iaJDOr.js → OnlineAssetDetail-DVdZv1D1.js} +1 -1
  25. package/dist/assets/{PlayBar-CBvuzv1Q.js → PlayBar-B-GGRbBB.js} +1 -1
  26. package/dist/assets/{QuarksAssetDocument-BlYjfRGp.js → QuarksAssetDocument-2MqOJHlY.js} +1 -1
  27. package/dist/assets/{ReactCanvasControls-C06AmSIB.js → ReactCanvasControls-COp1PvO1.js} +1 -1
  28. package/dist/assets/{RootSelectionOverlay-CPw5aFQf.js → RootSelectionOverlay-6M-HHI3M.js} +1 -1
  29. package/dist/assets/{ShaderAssetDocument-BVeK6Owt.js → ShaderAssetDocument-PrwCSYxk.js} +1 -1
  30. package/dist/assets/{ShadowEditor-BKEyyzOq.js → ShadowEditor-EXaJ1Kud.js} +1 -1
  31. package/dist/assets/{SourceAssetViewer-DB6Fg4Re.js → SourceAssetViewer-Bk_LGk7S.js} +1 -1
  32. package/dist/assets/{StageHost-dHitOcUe.js → StageHost-CK78ezTC.js} +2 -2
  33. package/dist/assets/{StoryPreviewMount-BONsNxze.js → StoryPreviewMount-IbbNNzF4.js} +1 -1
  34. package/dist/assets/{ThreeBoardDocument-D4CSNWux.js → ThreeBoardDocument-DUakOh0j.js} +2 -2
  35. package/dist/assets/{ThreeIsolationSceneContent-DkXfPv14.js → ThreeIsolationSceneContent-BjAyHzL2.js} +1 -1
  36. package/dist/assets/{ToolObject3DPreview-DvGqYC9c.js → ToolObject3DPreview-CRb_pBHc.js} +1 -1
  37. package/dist/assets/{Toolbar-BqUPRrhs.js → Toolbar-Bb7KArdo.js} +1 -1
  38. package/dist/assets/{TransientHint-w6qEumzV.js → TransientHint-BlB2atrU.js} +1 -1
  39. package/dist/assets/{VideoViewer-B99XdTSg.js → VideoViewer-D5fNjrcg.js} +1 -1
  40. package/dist/assets/{ViewportShadingMenu-9AaJLhq_.js → ViewportShadingMenu-D_-wHbzW.js} +1 -1
  41. package/dist/assets/{active-ingest-DwF45MBm.js → active-ingest-DJ8FmH5M.js} +2 -2
  42. package/dist/assets/{animation-clock-DW8tJ4l7.js → animation-clock-CINkiVZd.js} +1 -1
  43. package/dist/assets/{animation-mixers.service-kllpdYjk.js → animation-mixers.service-BST_khGa.js} +1 -1
  44. package/dist/assets/{animation-timeline.utility-C9UVqsSv.js → animation-timeline.utility-X54fMzvE.js} +1 -1
  45. package/dist/assets/{asset-budget-asset.menu-Cl8tmAtz.js → asset-budget-asset.menu-CfJth8-V.js} +1 -1
  46. package/dist/assets/{asset-budget.action-dw6ctYdi.js → asset-budget.action-ByyoIoUI.js} +1 -1
  47. package/dist/assets/{asset-budget.document-BfDL1bS4.js → asset-budget.document-CO1NrMEa.js} +1 -1
  48. package/dist/assets/{asset-budget.menu-DiOMl0Yh.js → asset-budget.menu-Cb99KwLd.js} +1 -1
  49. package/dist/assets/{asset-editor-persistence-D2o6zb5I.js → asset-editor-persistence-BF2Eqt0F.js} +1 -1
  50. package/dist/assets/{asset-loaders-bMb8Nvq8.js → asset-loaders-2LtXp4_y.js} +1 -1
  51. package/dist/assets/{asset-preview-uRqIcg3G.js → asset-preview-t-7PYPjJ.js} +1 -1
  52. package/dist/assets/{audio-unlock.service-CBeaLfYT.js → audio-unlock.service-DwkIGA6J.js} +1 -1
  53. package/dist/assets/{audio.utility-iWLchCUR.js → audio.utility-Mn4GcZIb.js} +1 -1
  54. package/dist/assets/autoplay.service-D7c8d5PV.js +1 -0
  55. package/dist/assets/{babylon-authoring-adapter-Bt8B089v.js → babylon-authoring-adapter-BB5HErRG.js} +1 -1
  56. package/dist/assets/{binding-resolver-qdReeiXP.js → binding-resolver-CXF3o1ZX.js} +2 -2
  57. package/dist/assets/{blender-node-editor.document-DHj3Luuz.js → blender-node-editor.document-djNJTSeo.js} +1 -1
  58. package/dist/assets/{blender-properties-tab-mrwIpZz_.js → blender-properties-tab-06D6TYA0.js} +1 -1
  59. package/dist/assets/{blender-runtime-host-rAbOjzv5.js → blender-runtime-host-Cqitl1ZO.js} +1 -1
  60. package/dist/assets/{blender-runtime-skin-CVACAkwd.js → blender-runtime-skin-RX6nlrgy.js} +72 -58
  61. package/dist/assets/{blender-runtime.document-VP-2qjfk.js → blender-runtime.document-pgD63Zep.js} +1 -1
  62. package/dist/assets/{blender-screenshot.menu-B_zThqdR.js → blender-screenshot.menu-DZ44fIU0.js} +1 -1
  63. package/dist/assets/{blender-timeline.document-BMNJBWXP.js → blender-timeline.document-D53mR9D6.js} +1 -1
  64. package/dist/assets/{blender-uv-editor.document-B2xmye2O.js → blender-uv-editor.document-Dux9ZXaj.js} +1 -1
  65. package/dist/assets/{blender-version.status-BzVGyJhB.js → blender-version.status-hK0_7tRC.js} +1 -1
  66. package/dist/assets/{blender.command-CNlvvxaj.js → blender.command-BF9RHCP_.js} +1 -1
  67. package/dist/assets/{board-guides-BPvQZ1ob.js → board-guides-BYnclES1.js} +1 -1
  68. package/dist/assets/{bridge.command-dqFe1Lyp.js → bridge.command-CS12Cp-B.js} +3 -3
  69. package/dist/assets/{browserAll-DLXEw1rV.js → browserAll-CGQ_uBbB.js} +1 -1
  70. package/dist/assets/{build-player.document-Bra3vDcF.js → build-player.document-RpeG8U_t.js} +1 -1
  71. package/dist/assets/{build-profiles.document-DuSvWEO8.js → build-profiles.document-DydU-eTF.js} +1 -1
  72. package/dist/assets/{build-progress.status-hkKRXBcc.js → build-progress.status-arvTBGok.js} +1 -1
  73. package/dist/assets/{build-session-B5GOV8fm.js → build-session-D8B-93_A.js} +1 -1
  74. package/dist/assets/{build.action-DUrS97Yw.js → build.action-CYKD0CrB.js} +1 -1
  75. package/dist/assets/{build.command-fNnr9pdz.js → build.command-BH-4yWaL.js} +1 -1
  76. package/dist/assets/{build.header-C-WQMQD8.js → build.header-B5-bZp5Z.js} +1 -1
  77. package/dist/assets/{build.menu-CsVJRmY6.js → build.menu-CyOe8xXz.js} +1 -1
  78. package/dist/assets/{build.service-CJfK8K6X.js → build.service-BuhAa1EB.js} +1 -1
  79. package/dist/assets/{camera-CpvCFt-Y.js → camera-KM5i-TaU.js} +1 -1
  80. package/dist/assets/{camera-runtime.inspector-BwSdtfTT.js → camera-runtime.inspector-DA-GqhBI.js} +1 -1
  81. package/dist/assets/{canvas-design-mount-CE-67ZS9.js → canvas-design-mount-PWQPVLiY.js} +3 -3
  82. package/dist/assets/{canvas-entry-runtime-CBpGQGRw.js → canvas-entry-runtime-nWfnVKYb.js} +2 -2
  83. package/dist/assets/{canvas-preview-frames-DoDVjE4O.js → canvas-preview-frames-BwWVTr-u.js} +1 -1
  84. package/dist/assets/{canvas-story-capture.service-hibqSqwB.js → canvas-story-capture.service-B1o-VBky.js} +2 -2
  85. package/dist/assets/{capability-coverage-DWVel6Wq.js → capability-coverage-aT7nf05J.js} +1 -1
  86. package/dist/assets/{collaboration-presence-B9eqNDDB.js → collaboration-presence-h1Fxju0A.js} +1 -1
  87. package/dist/assets/{collider-DD5wreOq.js → collider-BDLEjrr-.js} +1 -1
  88. package/dist/assets/{component-board.service-r8KlRes9.js → component-board.service-CetsHh4L.js} +2 -2
  89. package/dist/assets/{component-board.service-eXvcrWzD.js → component-board.service-DAeFLAlB.js} +2 -2
  90. package/dist/assets/{component-board.service-B1RineLo.js → component-board.service-qH45JxuD.js} +2 -2
  91. package/dist/assets/{component-contracts.service-YWaJqTzM.js → component-contracts.service-nYhZ_ceu.js} +1 -1
  92. package/dist/assets/{component-instance-root-BrRLxTKu.js → component-instance-root-QYCCyhxU.js} +1 -1
  93. package/dist/assets/{component-verbs.command-D5LCfxHY.js → component-verbs.command-y1H2CFq-.js} +1 -1
  94. package/dist/assets/{component-verbs.service-BUTHHNRT.js → component-verbs.service-QvBBdzY3.js} +1 -1
  95. package/dist/assets/{config-DQqPM4dV.js → config-YwJJtCF0.js} +2 -2
  96. package/dist/assets/{configurations-Dn9LLbWO.js → configurations-B52h5RGp.js} +1 -1
  97. package/dist/assets/{connection.status-CMZKs7ch.js → connection.status-DnEU1lk4.js} +1 -1
  98. package/dist/assets/{constraints.inspector-CRay8pK8.js → constraints.inspector-DgbM_8l2.js} +1 -1
  99. package/dist/assets/{content-bounds-UvcUv1DD.js → content-bounds-BRS42hfD.js} +1 -1
  100. package/dist/assets/{contract-system-adapters-Bbw5uUUi.js → contract-system-adapters-DIpeIRm_.js} +1 -1
  101. package/dist/assets/{coverage.service-DeTXoRCC.js → coverage.service-Cjy9MO9F.js} +1 -1
  102. package/dist/assets/{create-runtime-Z7LcpKwn.js → create-runtime-ByZWXstA.js} +1 -1
  103. package/dist/assets/{curve-DGhnvtG4.js → curve-DaFJmPin.js} +1 -1
  104. package/dist/assets/{data-asset-CrnqULWS.js → data-asset-DRCqFyxF.js} +1 -1
  105. package/dist/assets/{data-ref-ym18xkxV.js → data-ref-CkvCIusA.js} +1 -1
  106. package/dist/assets/{debug-bridge-BknWW_8M.js → debug-bridge-C7NLsHKu.js} +1 -1
  107. package/dist/assets/{debug-registry-C7poEnyY.js → debug-registry-BzagDrhV.js} +1 -1
  108. package/dist/assets/{deferred-ingest-play-3qS-wvgF.js → deferred-ingest-play-DMp_yRhc.js} +2 -2
  109. package/dist/assets/{design-time-canvas-mount-JkGmMINz.js → design-time-canvas-mount-kB1ZRIvt.js} +2 -2
  110. package/dist/assets/{design-time-layers-nxUfMfKI.js → design-time-layers-Dzu3jW_N.js} +1 -1
  111. package/dist/assets/{design-time-mount.service-EBZKN6cL.js → design-time-mount.service-CLEJHBLW.js} +2 -2
  112. package/dist/assets/{design-time-mount.service-DQganiM8.js → design-time-mount.service-Dgswmfff.js} +2 -2
  113. package/dist/assets/{design-time-react-mount-COvuTCBY.js → design-time-react-mount-B71UACVS.js} +1 -1
  114. package/dist/assets/{document-preview-three-BaWpv458.js → document-preview-three-DxAxdZRF.js} +1 -1
  115. package/dist/assets/{dom-authoring-adapter-wlPbZwHo.js → dom-authoring-adapter-CQiwffQ4.js} +1 -1
  116. package/dist/assets/{draco3d-DdFfLaRu.js → draco3d-CWfPSgkb.js} +1 -1
  117. package/dist/assets/{edit-mode-audio.service-B74d6zkz.js → edit-mode-audio.service-CikRAHOi.js} +1 -1
  118. package/dist/assets/{edit-mode-authoring-Cf83TffW.js → edit-mode-authoring-DthrLbz-.js} +1 -1
  119. package/dist/assets/{edit-mode-networking.service-C7FSPHzl.js → edit-mode-networking.service-DBmK8YGU.js} +1 -1
  120. package/dist/assets/{editor-api-DLfSJ2g2.js → editor-api-CqqOlRSi.js} +1 -1
  121. package/dist/assets/{editor-layers-BVicagU1.js → editor-layers-k0AjpomL.js} +1 -1
  122. package/dist/assets/{editor-shell-store-CV73gQk5.js → editor-shell-store-B3c29A3l.js} +1 -1
  123. package/dist/assets/{entity-object-DTQ4I2K5.js → entity-object-BOLh6DVA.js} +1 -1
  124. package/dist/assets/{extend-B7YOIXSU.js → extend-CJ7vLkP1.js} +1 -1
  125. package/dist/assets/{fork-menu-BToX8Jv4.js → fork-menu-Bzl-5_GA.js} +1 -1
  126. package/dist/assets/{frame-debugger-store-CuCtiEQ1.js → frame-debugger-store-NGsJt0AK.js} +1 -1
  127. package/dist/assets/{game-contract-seams-DRUf45xM.js → game-contract-seams-CuBiefwV.js} +1 -1
  128. package/dist/assets/{game-css-scope-transform-rbFoxfMV.js → game-css-scope-transform-5yv5zl6t.js} +1 -1
  129. package/dist/assets/{game-document.service-D409VVnQ.js → game-document.service-DtML_s2L.js} +1 -1
  130. package/dist/assets/{game-eval.command-BJ51kPy3.js → game-eval.command-Cghc-6r3.js} +1 -1
  131. package/dist/assets/{game-module-access-ib9tWhJc.js → game-module-access-DPnqfsy_.js} +1 -1
  132. package/dist/assets/{game-network-BZM-o9Ey.js → game-network-TjOj3K-Z.js} +3 -3
  133. package/dist/assets/{gameplay-export-Bsvbs7wO.js → gameplay-export-ebDdiP9T.js} +1 -1
  134. package/dist/assets/{gameplay-replay-k_14DJ5F.js → gameplay-replay-B4BPQnTZ.js} +1 -1
  135. package/dist/assets/{gameplay.command-DGVwoOz_.js → gameplay.command-C__OjBjz.js} +1 -1
  136. package/dist/assets/{generation-jobs-BxpAnwDo.js → generation-jobs-C57_oOgx.js} +1 -1
  137. package/dist/assets/{generation.service-D1win2Pl.js → generation.service-BJel-Oiy.js} +1 -1
  138. package/dist/assets/{generations-Dlu2fhGN.js → generations-DNfmqqzL.js} +1 -1
  139. package/dist/assets/{generations.status-BPYUSGr_.js → generations.status-nXpY7bFU.js} +1 -1
  140. package/dist/assets/{hierarchy-marks-Dn7SO2iG.js → hierarchy-marks-C2temlO0.js} +1 -1
  141. package/dist/assets/{hosted-asset-materialization-DPmn23AM.js → hosted-asset-materialization-BtbO5pyX.js} +1 -1
  142. package/dist/assets/{index-B41IX0yA.js → index-7J5pTwW2.js} +1 -1
  143. package/dist/assets/{index-C_XSSPHO.js → index-B5GZkByz.js} +1 -1
  144. package/dist/assets/{index-_-7lUYI-.js → index-B69_nH5F.js} +1 -1
  145. package/dist/assets/{index-D9shXtZ9.js → index-BfqJPhFO.js} +7 -7
  146. package/dist/assets/{index-BjUxirz3.js → index-BiH6f3Mk.js} +1 -1
  147. package/dist/assets/{index-FWtJb07f.js → index-CFS_B4hc.js} +2 -2
  148. package/dist/assets/{index-B4NI0L5I.js → index-DYoPv2Wb.js} +1 -1
  149. package/dist/assets/{index-Cp9b5Qfa.js → index-my7iu018.js} +1 -1
  150. package/dist/assets/{index-D1nMmQxJ.js → index-zXacXllH.js} +1 -1
  151. package/dist/assets/{inference-diagnostics-V4igFQX2.js → inference-diagnostics-NvA3SRR7.js} +1 -1
  152. package/dist/assets/{ingest-boot-viewport-DBpKatwo.js → ingest-boot-viewport-DHhBi66w.js} +1 -1
  153. package/dist/assets/{ingest-siblings-C8OmNNTc.js → ingest-siblings-CMWO3uRZ.js} +1 -1
  154. package/dist/assets/{ingest-source-persistence-DH7q9G1S.js → ingest-source-persistence-CrXFBT__.js} +1 -1
  155. package/dist/assets/{ingest.service-D3Ru3YUS.js → ingest.service-BYEo4j1s.js} +1 -1
  156. package/dist/assets/{inspect-Bhr2b3pa.js → inspect-UxYR9Ls5.js} +1 -1
  157. package/dist/assets/instances.command-DDOJ3aWq.js +1 -0
  158. package/dist/assets/{json-history-resource-B8_YpeAT.js → json-history-resource-De8KJl61.js} +1 -1
  159. package/dist/assets/{layered-pick-MdBIQeUt.js → layered-pick-Dito5b_J.js} +1 -1
  160. package/dist/assets/{light-BvCKNW4e.js → light-BnSS9Nzc.js} +1 -1
  161. package/dist/assets/{live-project-verbs-DggWGgn-.js → live-project-verbs-CDRzC_D1.js} +1 -1
  162. package/dist/assets/{machine.document-CTyXmK5a.js → machine.document-CVG78EGi.js} +1 -1
  163. package/dist/assets/{machines.finder-C6WR7N-k.js → machines.finder-vrUR_Pb_.js} +1 -1
  164. package/dist/assets/{material-BoHGaIcq.js → material-7mmxSi8g.js} +1 -1
  165. package/dist/assets/{material-factory-D-cyMEti.js → material-factory-CXvJ2goL.js} +1 -1
  166. package/dist/assets/{mesh-B-ksBKUU.js → mesh-DpK09Vho.js} +1 -1
  167. package/dist/assets/{model-asset-sections.service-DHsGD1SZ.js → model-asset-sections.service-ByE7kOXW.js} +1 -1
  168. package/dist/assets/{model-inspection-Bsfj6b48.js → model-inspection-PgxfYOnI.js} +1 -1
  169. package/dist/assets/{model-thumbnail-Bp-1yQ-X.js → model-thumbnail-Dnv7DCt7.js} +1 -1
  170. package/dist/assets/{models.finder-DksRlbR8.js → models.finder-BaD41xeQ.js} +1 -1
  171. package/dist/assets/{module-mode-qROy_5Tk.js → module-mode-Bb9fFtEw.js} +2 -2
  172. package/dist/assets/{mount-canvas-ingest-root-CLbJS_Ob.js → mount-canvas-ingest-root-B0_ckx79.js} +2 -2
  173. package/dist/assets/{mount-dom-ingest-root-CI7VtdaS.js → mount-dom-ingest-root-BnZQSayp.js} +2 -2
  174. package/dist/assets/{mount-ingest-root-BX_usF8y.js → mount-ingest-root-DHVNQKHi.js} +2 -2
  175. package/dist/assets/{mount-manifest-lQBlK2Y1.js → mount-manifest-cYykTsXQ.js} +1 -1
  176. package/dist/assets/{mount-three-ingest-root-g6yhs1S-.js → mount-three-ingest-root-CI-gjlh8.js} +1 -1
  177. package/dist/assets/{mounted-authoring-D5cvzNXX.js → mounted-authoring-B2dc__pv.js} +1 -1
  178. package/dist/assets/{mounted-story-viewport-source-C-RZo_xH.js → mounted-story-viewport-source-Ceh05FK8.js} +1 -1
  179. package/dist/assets/{native-debug-module-Bh_HQdg_.js → native-debug-module-L_Ofssyj.js} +1 -1
  180. package/dist/assets/{navigation-DVO5eQO6.js → navigation-CADCnkrx.js} +1 -1
  181. package/dist/assets/{navmesh.menu-Cu9R-p4V.js → navmesh.menu-3D6ZEGhB.js} +1 -1
  182. package/dist/assets/{navmesh.service-D6EeQxE0.js → navmesh.service-D_TdU1xw.js} +1 -1
  183. package/dist/assets/network-observer.service-D9nUCc15.js +1 -0
  184. package/dist/assets/{network.utility-D4Uo1xUC.js → network.utility-B3riF8KT.js} +1 -1
  185. package/dist/assets/{object3d-document-session-registry-bor-eSgr.js → object3d-document-session-registry-CLizyhis.js} +2 -2
  186. package/dist/assets/{oid-transform-rEmA5PfE.js → oid-transform-CinlfHYa.js} +1 -1
  187. package/dist/assets/{particles-BxlIkQUX.js → particles--V50tPi5.js} +1 -1
  188. package/dist/assets/{pixi-authoring-adapter-CTSRtvNw.js → pixi-authoring-adapter-qbP0YW7g.js} +1 -1
  189. package/dist/assets/{pixi-live-write-target-DaUAvNu7.js → pixi-live-write-target-coTAFFGW.js} +1 -1
  190. package/dist/assets/{play.command-BtV56gUr.js → play.command-kc7rzTlg.js} +2 -2
  191. package/dist/assets/{presentation-DxTT40_3.js → presentation-jBjhcEq1.js} +1 -1
  192. package/dist/assets/{product-BAGhTFHw.js → product-DgYRVeaY.js} +1 -1
  193. package/dist/assets/{profiler.action-DaSS1RoY.js → profiler.action-Dj94ZJLY.js} +1 -1
  194. package/dist/assets/{profiler.menu-5OyI3lyY.js → profiler.menu-BHplCv7a.js} +1 -1
  195. package/dist/assets/{profiler.utility-DLzaMOPh.js → profiler.utility-D32oIOGk.js} +1 -1
  196. package/dist/assets/{project-authoring-session-DZOgiTch.js → project-authoring-session-Cd8SeWEJ.js} +2 -2
  197. package/dist/assets/{properties-bone-constraints.inspector-JMlHKfN2.js → properties-bone-constraints.inspector-VPTHP6BI.js} +1 -1
  198. package/dist/assets/{properties-bone.inspector-C-c7iGEx.js → properties-bone.inspector-4GD1gzCp.js} +1 -1
  199. package/dist/assets/{properties-collection.inspector-PXHDUs1b.js → properties-collection.inspector-CehoAair.js} +1 -1
  200. package/dist/assets/{properties-constraints.inspector-CQnnGi1O.js → properties-constraints.inspector-LgPoqURT.js} +1 -1
  201. package/dist/assets/{properties-data.inspector-DuEPeVBm.js → properties-data.inspector-D3uEJD3t.js} +1 -1
  202. package/dist/assets/{properties-material.inspector-BhKP0Zc_.js → properties-material.inspector-2n9K5IFo.js} +1 -1
  203. package/dist/assets/{properties-modifiers.inspector-lOMb72vk.js → properties-modifiers.inspector-B_RsuDyF.js} +1 -1
  204. package/dist/assets/{properties-object.inspector-BU2hn26Q.js → properties-object.inspector-CBZA72yZ.js} +1 -1
  205. package/dist/assets/{properties-output.inspector-yNaC3IgX.js → properties-output.inspector-DxDAmKI-.js} +1 -1
  206. package/dist/assets/{properties-particles.inspector-CaHfdQZB.js → properties-particles.inspector-pPS920CT.js} +1 -1
  207. package/dist/assets/{properties-physics.inspector-Bt9Xjyu-.js → properties-physics.inspector-XUnPp5Q3.js} +1 -1
  208. package/dist/assets/{properties-render.inspector-Cl8UBLPY.js → properties-render.inspector-DnC4sgP3.js} +1 -1
  209. package/dist/assets/{properties-scene.inspector-D9cgONMx.js → properties-scene.inspector-MZ-gCrYM.js} +1 -1
  210. package/dist/assets/{properties-texture.inspector-804GEF8F.js → properties-texture.inspector-B7QGBzm5.js} +1 -1
  211. package/dist/assets/{properties-view-layer.inspector-CLo0Z-B1.js → properties-view-layer.inspector-rt2qT9SA.js} +1 -1
  212. package/dist/assets/{properties-world.inspector-CjywenDE.js → properties-world.inspector-Vg7GD9HK.js} +1 -1
  213. package/dist/assets/{r3f-design-session-B2k02ypD.js → r3f-design-session-DfRwB6oN.js} +2 -2
  214. package/dist/assets/{r3f-physics-binding-D1rgVgsz.js → r3f-physics-binding-EfYECbQc.js} +1 -1
  215. package/dist/assets/{r3f-source-authoring-adapter-Dj0r13-b.js → r3f-source-authoring-adapter-CVupdJt5.js} +1 -1
  216. package/dist/assets/{react-canvas-navigation-t00NiEKB.js → react-canvas-navigation-DwiPTVdH.js} +1 -1
  217. package/dist/assets/{react-inspector.service-Xp4f-M0O.js → react-inspector.service-DffkStxd.js} +1 -1
  218. package/dist/assets/{react-story-board-DAQaZNga.js → react-story-board-CynnmKqO.js} +1 -1
  219. package/dist/assets/{react-three-rapier.esm-D13B7Exz.js → react-three-rapier.esm-DnUfnQnM.js} +1 -1
  220. package/dist/assets/{react-world-authoring-adapter-zzyaxcpN.js → react-world-authoring-adapter-Cf1jv2dl.js} +1 -1
  221. package/dist/assets/{realm-services-CyeBcuLZ.js → realm-services-CxfLBQQ9.js} +1 -1
  222. package/dist/assets/{reflection-probe-capture.inspector-BpdGQ2gf.js → reflection-probe-capture.inspector-DfzDNtJF.js} +1 -1
  223. package/dist/assets/{registry-DM1tIelZ.js → registry-69pUwZEm.js} +1 -1
  224. package/dist/assets/{relative-import-specifier-txHdCBKR.js → relative-import-specifier-J1WeZQaJ.js} +1 -1
  225. package/dist/assets/{render-env-DiO35wd3.js → render-env-CmR-momj.js} +1 -1
  226. package/dist/assets/{render-features-Bv3_74_x.js → render-features-D7pQr-dE.js} +1 -1
  227. package/dist/assets/{render-settings-8kb_yvkr.js → render-settings-BUT8gPkc.js} +1 -1
  228. package/dist/assets/{resolve-three-D9rgCC5Z.js → resolve-three-Dhw2LtAp.js} +3 -3
  229. package/dist/assets/{root-seam-contract-BgkkJVuJ.js → root-seam-contract-BFs0rvG9.js} +1 -1
  230. package/dist/assets/{run-selection-WrcYgYP3.js → run-selection-CEuu_sxz.js} +1 -1
  231. package/dist/assets/{scene-capture-C08wT5TW.js → scene-capture-DgUSqWTB.js} +1 -1
  232. package/dist/assets/{scene-document.service-D7sb6hvQ.js → scene-document.service-BDDoO22G.js} +2 -2
  233. package/dist/assets/{scene-framing-BSvegpi4.js → scene-framing-Dm-rCn3G.js} +1 -1
  234. package/dist/assets/{seeded-random-Bc5190so.js → seeded-random-C9256-Ag.js} +1 -1
  235. package/dist/assets/{setup-renderer-JwrNwzqH.js → setup-renderer-CWvtkVDR.js} +1 -1
  236. package/dist/assets/{source-object3d-authoring-adapter-BJwLQVsv.js → source-object3d-authoring-adapter-ehtz9UK_.js} +1 -1
  237. package/dist/assets/{source-persistence-backend-DsG30XMj.js → source-persistence-backend-CbCbDOjd.js} +1 -1
  238. package/dist/assets/{stage-keyboard-BnzybgXw.js → stage-keyboard-DiRyZTZd.js} +1 -1
  239. package/dist/assets/{stage-overlay-set-BWxO_Pk6.js → stage-overlay-set-6pmCmKpX.js} +1 -1
  240. package/dist/assets/{stage-presence-markers-BD5JPVX6.js → stage-presence-markers-mZPecAeK.js} +1 -1
  241. package/dist/assets/{stage-transform-tools-CHvXlnKB.js → stage-transform-tools-Qc0QjPrc.js} +1 -1
  242. package/dist/assets/{standard-viewport-dressing-4xAZCGJ3.js → standard-viewport-dressing-BhTPIZTQ.js} +1 -1
  243. package/dist/assets/{state-watch.action-0KAywung.js → state-watch.action-DJfW26od.js} +1 -1
  244. package/dist/assets/{state-watch.menu-4xjTZIEx.js → state-watch.menu-B1GRE_HT.js} +1 -1
  245. package/dist/assets/{state-watch.utility-DZgzPGEZ.js → state-watch.utility-BQaTOFU-.js} +1 -1
  246. package/dist/assets/{story-capture-d695eMLJ.js → story-capture-DZNUtuCH.js} +1 -1
  247. package/dist/assets/{story-documents-C1hZeYU3.js → story-documents-DArOiGNt.js} +1 -1
  248. package/dist/assets/{story-documents.service-CSXB6uqT.js → story-documents.service-Bi89tZQ5.js} +1 -1
  249. package/dist/assets/{story-documents.service-bB0UDbvA.js → story-documents.service-DaPhxnzw.js} +1 -1
  250. package/dist/assets/{story-media-presence-CxD6G_Mu.js → story-media-presence-CMJ7U-7_.js} +1 -1
  251. package/dist/assets/{story-pixi-preview-CJKGDBKs.js → story-pixi-preview-jmF1ab99.js} +1 -1
  252. package/dist/assets/{story-presentation-BBS9x4BP.js → story-presentation-DNXF37vS.js} +1 -1
  253. package/dist/assets/{story-three-preview-v22RRpqB.js → story-three-preview-CH6Kk934.js} +2 -2
  254. package/dist/assets/{studio-environment-CvCEc6PK.js → studio-environment-BNM-AjAn.js} +1 -1
  255. package/dist/assets/{surface-state-EsG-yMSi.js → surface-state-BLuxJ4lb.js} +1 -1
  256. package/dist/assets/{syntactic-prop-specs-DvSr6VoQ.js → syntactic-prop-specs-Coas9J4z.js} +1 -1
  257. package/dist/assets/{team-playtest.service-Bp6j6MAv.js → team-playtest.service-C3cEeDBv.js} +1 -1
  258. package/dist/assets/{three-Do16bEo9.js → three-BvhtsSAr.js} +1 -1
  259. package/dist/assets/{three-authoring-adapter-C2QFVlpK.js → three-authoring-adapter-K8a5THvW.js} +1 -1
  260. package/dist/assets/three-authoring.service-D-uSiCHc.js +2 -0
  261. package/dist/assets/{three-ingest-runtime-DW-lHDmp.js → three-ingest-runtime-QhrURliQ.js} +1 -1
  262. package/dist/assets/{three-integration-C1onOQwq.js → three-integration-CaC8ivB7.js} +2 -2
  263. package/dist/assets/three-integration.service-BvTtbtlD.js +1 -0
  264. package/dist/assets/{three-projection-core-1FETWj5n.js → three-projection-core-C2Zj6hTy.js} +1 -1
  265. package/dist/assets/{three-state-d-szeOea.js → three-state-cYB28OIz.js} +1 -1
  266. package/dist/assets/{three-story-capture.service-gnrRzcjj.js → three-story-capture.service-H2Z2O7Nz.js} +2 -2
  267. package/dist/assets/{three-story-model-CbEMWEte.js → three-story-model-DVfgIOzi.js} +1 -1
  268. package/dist/assets/{three-viewport-presentation-D1ysWIW4.js → three-viewport-presentation-DoViPvQB.js} +1 -1
  269. package/dist/assets/{transform-mode-request-B3AxgwGW.js → transform-mode-request-CflM_ccL.js} +1 -1
  270. package/dist/assets/{transport-strip-D4N14xHx.js → transport-strip-DPoEy7PU.js} +1 -1
  271. package/dist/assets/transport.header-DdI58npA.js +1 -0
  272. package/dist/assets/{tuples-B3URXxaa.js → tuples-CA3u4T9B.js} +1 -1
  273. package/dist/assets/{ui-board-document-BSrfzH8L.js → ui-board-document-CoKY7MDM.js} +2 -2
  274. package/dist/assets/{user-data-DHB4MWum.js → user-data-CTT8ZvVB.js} +1 -1
  275. package/dist/assets/{utility-view-state-CfZ51NRS.js → utility-view-state-BaO3Fx_-.js} +1 -1
  276. package/dist/assets/{viewport-door-DkDcO9tp.js → viewport-door-BBtilr3V.js} +1 -1
  277. package/dist/assets/{viewport-root-presentation-DtuBFJ-J.js → viewport-root-presentation-DmDBAZ8E.js} +1 -1
  278. package/dist/assets/{viewport-surface-status-HKbJtC2G.js → viewport-surface-status-BiDiAZ6z.js} +1 -1
  279. package/dist/assets/{webworkerAll-JD3yAUg1.js → webworkerAll-BCvjBZqG.js} +1 -1
  280. package/dist/assets/{workspace-arrangement-BOk46mGq.js → workspace-arrangement-BXM0R-Uu.js} +1 -1
  281. package/dist/assets/{world-documents-AnhAH_9y.js → world-documents-DGk_J8cp.js} +1 -1
  282. package/dist/assets/{world-root-stage-binding-H0SUNbfK.js → world-root-stage-binding-KaIVpo80.js} +1 -1
  283. package/dist/assets/{xstate-animation-binding-BjWKb5ne.js → xstate-animation-binding-D_kxRsxS.js} +1 -1
  284. package/dist/assets/{xstate-animation-meta-CTBp-Vc5.js → xstate-animation-meta-CX5oWqQv.js} +1 -1
  285. package/dist-node/cli.js +16 -16
  286. package/package.json +16 -16
  287. package/dist/assets/InspectorObjectPreview-DCEUdndv.js +0 -1
  288. package/dist/assets/Object3DDocumentViewport-Blr8aQeS.js +0 -2
  289. package/dist/assets/autoplay.service---Nu6koq.js +0 -1
  290. package/dist/assets/instances.command-CDIwEW8H.js +0 -1
  291. package/dist/assets/network-observer.service-CLE3M7gH.js +0 -1
  292. package/dist/assets/three-authoring.service-DxL4grJx.js +0 -2
  293. package/dist/assets/three-integration.service-26hsEOk3.js +0 -1
  294. package/dist/assets/transport.header-D3j_V-tN.js +0 -1
@@ -1,5 +1,5 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/RectAreaLightUniformsLib-DpPyArRG.js","assets/three.module-BLhyNg0e.js","assets/three.core-3arARmh6.js"])))=>i.map(i=>d[i]);
2
- import{a as To,b as So,L as Po}from"./LineSegments2-DN9pUfWA.js";import{bh as ut,cl as Eo,fo as b,cm as q,N as re,a$ as Rt,em as Pn,b4 as ca,co as kt,ey as ua,cp as je,_ as Mt,ej as Ht,fd as ne,er as da,M as lt,cj as wt,dp as St,aV as ma,cW as Ve,aE as No,c7 as xt,j as _a,f6 as ha,fp as Xe,au as Ye,dw as Ze,bi as En,aT as pa,c1 as oe,dd as _n,eC as hn,e7 as ke,aw as xe,da as Zt,I as me,as as ga,e8 as va,b0 as Ro,K as xa,B as ba,b9 as ya,Y as Io,cw as ae,ed as wa,cA as Oa,ch as Aa,fx as Ma,db as Do,el as Ta,R as Sa,e6 as Pa,c0 as zo,bX as Ea,aI as Be,ao as Na,eG as Ra,d3 as Ia,cs as Da,b5 as Ke,bu as Co,aM as Fo,a_ as za,E as Ae,ex as Nn,cO as Ue,cY as Ca,eU as Fa,cE as pn,c5 as ko,at as ka,ff as $a,eW as La,f7 as ja,F as Va,ev as Ba,et as Ua,dq as Wa,fq as qa,n as Ha,l as Ga,cf as Xa}from"./three.core-3arARmh6.js";import{u as R,v as j,w as z,c5 as et,c4 as Q,c6 as I,e2 as W,_ as Ya,mB as $o,d_ as Gt,x as Z,kE as Ot,e1 as Lo,mC as Y,dZ as Za,mD as Ka}from"./index-D9shXtZ9.js";import{S as Kt}from"./three.module-BLhyNg0e.js";import{t as Qa}from"./blender-runtime-host-rAbOjzv5.js";const gn=new Set;function _t(){for(const n of[...gn])n()}function Ja(n){return gn.add(n),()=>{gn.delete(n)}}function vn(n){const t=atob(n),e=new Uint8Array(t.length);for(let o=0;o<t.length;o++)e[o]=t.charCodeAt(o);return e}const _e=I().finite(),tr=R({name:z(),parent:z().nullable(),connected:et(),hide:et(),length:_e,matrix:j(W([_e,_e,_e,_e])).length(4),select:et(),active:et(),lockedWeight:et()}).strict(),er=R({object:z(),displayType:Q(["OCTAHEDRAL","STICK","BBONE","ENVELOPE","WIRE"]),showInFront:et(),mode:z(),bones:j(tr)}).strict(),Nt={solid:11711154,pose:5294335,poseActive:9240575,poseActiveUnsel:794150,wire:0,vertex:0,lockedWeight:16711680,lockedWeightFactor:128/255};function nr(n){return new Mt(n.r*n.r*.1,n.g*n.g*.1,n.b*n.b*.1)}const Qe=[[0,0,0],[.1,.1,.1],[.1,.1,-.1],[-.1,.1,-.1],[-.1,.1,.1],[0,1,0]],Bn=[[2,1,0],[3,2,0],[4,3,0],[1,4,0],[5,1,2],[5,2,3],[5,3,4],[5,4,1]],Vt=Math.SQRT1_2,or=[[Vt,-Vt,0],[0,-Vt,-Vt],[-Vt,-Vt,0],[0,-Vt,Vt],[.99388373,.11043154,0],[0,.11043154,-.99388373],[-.99388373,.11043154,0],[0,.11043154,.99388373]],ar=[[0,1],[1,5],[5,3],[3,0],[0,4],[4,5],[5,2],[2,0],[1,2],[2,3],[3,4],[4,1]],rr=.05;function Un(n){return n.select||n.active?2:1}const sr=10,ir=4,lr=`
2
+ import{a as Co,b as zo,L as ko}from"./LineSegments2-DN9pUfWA.js";import{bh as dt,cl as Rn,fo as b,cm as G,N as Yt,a$ as It,em as In,b4 as ba,co as Ft,ey as ya,cp as We,_ as bt,ej as Zt,fd as Ht,er as wa,M as ft,cj as Ot,dp as Tt,aV as Oa,cW as qe,aE as Fo,c7 as xt,j as Aa,f6 as Ma,fp as Ee,au as Ke,dw as Qe,bi as Dn,aT as Sa,c1 as re,dd as pn,eC as gn,e7 as Ve,aw as ye,da as Ut,I as _e,as as Ta,e8 as Pa,b0 as $o,K as Ea,B as Na,b9 as Ra,Y as Lo,cw as Gt,ed as Ia,cA as Da,ch as jo,eW as vn,fx as Ca,db as Vo,el as Bo,R as za,e6 as ka,c0 as Uo,bX as Fa,aI as Te,ao as $a,eG as La,d3 as ja,cs as Va,b5 as Je,bu as Wo,aM as qo,a_ as Ba,E as ue,ex as Cn,cO as He,cY as Ua,eU as Wa,cE as xn,c5 as Ho,at as qa,ff as Ha,f7 as Ga,F as Xa,ev as Ya,et as Za,dq as Ka,fq as Qa,n as Ja,l as tr,cf as er}from"./three.core-3arARmh6.js";import{u as I,v as V,w as z,c5 as et,c4 as J,c6 as D,e2 as W,_ as nr,mB as Go,d_ as Kt,x as K,kE as At,e1 as Xo,mC as Z,dZ as or,mD as ar}from"./index-BfqJPhFO.js";import{S as te}from"./three.module-BLhyNg0e.js";import{t as rr}from"./blender-runtime-host-Cqitl1ZO.js";const bn=new Set;function mt(){for(const n of[...bn])n()}function sr(n){return bn.add(n),()=>{bn.delete(n)}}function yn(n){const t=atob(n),e=new Uint8Array(t.length);for(let o=0;o<t.length;o++)e[o]=t.charCodeAt(o);return e}const pe=D().finite(),ir=I({name:z(),parent:z().nullable(),connected:et(),hide:et(),length:pe,matrix:V(W([pe,pe,pe,pe])).length(4),select:et(),active:et(),lockedWeight:et()}).strict(),lr=I({object:z(),displayType:J(["OCTAHEDRAL","STICK","BBONE","ENVELOPE","WIRE"]),showInFront:et(),mode:z(),bones:V(ir)}).strict(),Rt={solid:11711154,pose:5294335,poseActive:9240575,poseActiveUnsel:794150,wire:0,vertex:0,lockedWeight:16711680,lockedWeightFactor:128/255};function fr(n){return new bt(n.r*n.r*.1,n.g*n.g*.1,n.b*n.b*.1)}const tn=[[0,0,0],[.1,.1,.1],[.1,.1,-.1],[-.1,.1,-.1],[-.1,.1,.1],[0,1,0]],Hn=[[2,1,0],[3,2,0],[4,3,0],[1,4,0],[5,1,2],[5,2,3],[5,3,4],[5,4,1]],Vt=Math.SQRT1_2,cr=[[Vt,-Vt,0],[0,-Vt,-Vt],[-Vt,-Vt,0],[0,-Vt,Vt],[.99388373,.11043154,0],[0,.11043154,-.99388373],[-.99388373,.11043154,0],[0,.11043154,.99388373]],ur=[[0,1],[1,5],[5,3],[3,0],[0,4],[4,5],[5,2],[2,0],[1,2],[2,3],[3,4],[4,1]],dr=.05;function Gn(n){return n.select||n.active?2:1}const mr=10,_r=4,hr=`
3
3
  attribute vec3 aSolid;
4
4
  attribute vec3 aHint;
5
5
  varying vec3 vColor;
@@ -10,13 +10,13 @@ import{a as To,b as So,L as Po}from"./LineSegments2-DN9pUfWA.js";import{bh as ut
10
10
  vColor = mix(aHint, aSolid, fac * fac);
11
11
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
12
12
  }
13
- `,fr=`
13
+ `,pr=`
14
14
  varying vec3 vColor;
15
15
  void main() {
16
16
  gl_FragColor = vec4(vColor, 1.0);
17
17
  #include <colorspace_fragment>
18
18
  }
19
- `;function Ut(n){return new Mt().setHex(n,Ht)}function Wn(n,t){const e=n.mode==="POSE";let o;return e?t.active&&t.select?o=Ut(Nt.poseActive):t.active?o=Ut(Nt.poseActiveUnsel):t.select?o=Ut(Nt.pose):o=Ut(Nt.wire):o=Ut(Nt.vertex),e&&t.lockedWeight&&o.lerp(Ut(Nt.lockedWeight),Nt.lockedWeightFactor),o}function qn(n,t){const e=Ut(Nt.solid);return n.mode==="POSE"&&t.lockedWeight&&e.lerp(Ut(Nt.lockedWeight),Nt.lockedWeightFactor),e}const cr=new q,ur=new b,Hn=new Eo;function Gn(n,t){return new q().set(...t.matrix.flat()).premultiply(n).scale(new b().setScalar(t.length))}class dr{constructor(){this.group=new ut,this.disposables=[],this.signature="",this.group.name="BlenderArmatureOverlay"}apply(t,e){const o=[],r=JSON.stringify(t);if(r===this.signature)return o;this.signature=r,this.clear();for(const a of Object.values(t)){const s=e(a.object);if(s===null)continue;a.displayType!=="OCTAHEDRAL"&&a.displayType!=="STICK"&&o.push(`armature ${a.object}: Blender's ${a.displayType} bone display needs data this door does not carry (B-Bone segment matrices, envelope radii), so its bones are drawn octahedral`),a.mode==="EDIT"&&o.push(`armature ${a.object}: in Edit Mode Blender draws the EDIT bones, and this overlay draws the pose — the shapes are the rest pose, not the edited one`);const f=a.bones.filter(d=>!d.hide);if(f.length===0)continue;const c=a.displayType==="STICK"?this.buildStick(a,f,s):this.buildOctahedral(a,f,s);a.showInFront&&c.traverse(d=>{const l=d.material;l&&"depthTest"in l&&(l.depthTest=!1),d.renderOrder=10}),this.group.add(c)}return o}buildOctahedral(t,e,o){const r=new ut;r.name=`${t.object}:bones`;const a=[],s=[],f=[],c=[],d=[],l=[],i=[],u=[],m=[],h=[];for(const _ of e){const p=Gn(o,_),g=qn(t,_),v=nr(g),w=Wn(t,_);Hn.setFromMatrix4(p).invert().transpose();for(let y=0;y<Bn.length;y++){const A=ur.set(...or[y]).applyMatrix3(Hn).normalize().clone();for(const M of Bn[y]){const P=new b(...Qe[M]).applyMatrix4(p);a.push(P.x,P.y,P.z),s.push(A.x,A.y,A.z),f.push(g.r,g.g,g.b),c.push(v.r,v.g,v.b)}}const x=Un(_)===2?i:d,T=Un(_)===2?u:l;for(const[y,A]of ar){const M=new b(...Qe[y]).applyMatrix4(p),P=new b(...Qe[A]).applyMatrix4(p);x.push(M.x,M.y,M.z,P.x,P.y,P.z),T.push(w.r,w.g,w.b,w.r,w.g,w.b)}_.parent!==null&&_.connected||(m.push(p.clone()),h.push(g)),m.push(p.clone().multiply(cr.makeTranslation(0,1,0))),h.push(g)}r.add(this.solidMesh(a,s,f,c)),d.length&&r.add(this.lines(d,l,1)),i.length&&r.add(this.lines(i,u,2));for(let _=0;_<m.length;_++)r.add(this.point(m[_],h[_]));return r}buildStick(t,e,o){const r=new ut;r.name=`${t.object}:bones`;const a=[],s=[],f=[],c=[];for(const d of e){const l=Gn(o,d),i=new b().setFromMatrixPosition(l),u=new b(0,1,0).applyMatrix4(l),m=Wn(t,d),h=qn(t,d);a.push(i.x,i.y,i.z,u.x,u.y,u.z),s.push(m.r,m.g,m.b,m.r,m.g,m.b),f.push(i.x,i.y,i.z,u.x,u.y,u.z),c.push(h.r,h.g,h.b,h.r,h.g,h.b)}return r.add(this.lines(a,s,sr)),r.add(this.lines(f,c,ir)),r}solidMesh(t,e,o,r){const a=new re;a.setAttribute("position",new Rt(t,3)),a.setAttribute("normal",new Rt(e,3)),a.setAttribute("aSolid",new Rt(o,3)),a.setAttribute("aHint",new Rt(r,3));const s=new Pn({vertexShader:lr,fragmentShader:fr,side:ca});this.disposables.push(a,s);const f=new kt(a,s);return f.frustumCulled=!1,f}lines(t,e,o){const r=new To;r.setPositions(t),r.setColors(e);const a=new So({linewidth:o,vertexColors:!0});this.disposables.push(r,a);const s=new Po(r,a);return s.frustumCulled=!1,s}point(t,e){const o=new ua(rr,12,8),r=new je({color:e});this.disposables.push(o,r);const a=new kt(o,r);return a.applyMatrix4(t),a.frustumCulled=!1,a}clear(){for(const t of[...this.group.children])this.group.remove(t);for(const t of this.disposables)t.dispose();this.disposables.length=0}dispose(){this.clear(),this.signature=""}}const Xn="RUNTIME_FRAME_UNKNOWN_GEOMETRY",he="RUNTIME_FRAME_UNKNOWN_IMAGE";function mr(n){const t=Math.fround,e=t(t(t(n[0]*n[0])+t(n[1]*n[1]))+t(n[2]*n[2]));if(e>1e-35){const o=t(Math.sqrt(e)),r=t(1/o);return{unit:[t(n[0]*r),t(n[1]*r),t(n[2]*r)],length:o}}return{unit:[0,0,0],length:0}}const C=Math.fround,We=C(2*Math.PI),Je=C(1-1e-4),Qt=(n,t)=>C(C(C(n[0]*t[0])+C(n[1]*t[1]))+C(n[2]*t[2])),Oe=(n,t,e=1)=>n.map((o,r)=>C(o+C(t[r]*e))),_r=(n,t)=>n.map((e,o)=>C(e-t[o]));function pe(n){const t=C(Math.sqrt(Qt(n,n)));return t>0?n.map(e=>C(e/t)):[0,0,0]}function ge(n){const t=Math.abs(n)<1?C(1-C(1-Math.abs(n))):1;let e=C(C(.077980478)+C(t*C(-.02164095)));e=C(C(-.213300989)+C(t*e)),e=C(C(1.5707963267)+C(t*e));const o=C(C(Math.sqrt(C(1-t)))*e);return n<0?C(C(Math.PI)-o):o}function hr(n){let t=n.at(-1);const e=[0,0,0];for(const o of n){for(let r=0;r<3;r++){const a=(r+1)%3,s=(r+2)%3;e[r]=C(e[r]+C(C(t[a]-o[a])*C(t[s]+o[s])))}t=o}return e}function pr(n){const t=[],e=[],o=(h,_)=>h<_?`${h}:${_}`:`${_}:${h}`,r=new Map((n.edge_order??[]).map(([h,_],p)=>[o(h,_),p])),a=new Set((n.sharp??[]).map(([h,_])=>o(h,_))),s=new Map;for(const[h,_]of n.f.entries()){const p=t.length,g=mr(hr(_.map(v=>n.v[v]))).unit;e.push(g.some(Boolean)?g:[0,0,1]);for(let v=0;v<_.length;v++){const w=o(_[v],_[(v+1)%_.length]);r.has(w)||r.set(w,r.size);const x=n.face_edges?.[h]?.[v]??r.get(w),T=t.length;t.push({vertex:_[v],face:h,edge:x,prev:p+(v+_.length-1)%_.length,next:p+(v+1)%_.length});const y=s.get(x)??[];y.push(T),s.set(x,y)}}const f=new Map,c=new Map;for(const[h,_]of s){if(_.length!==2||n.edge_sharp?.[h])continue;const[p,g]=_,v=t[p],w=t[g];!n.s?.[v.face]||!n.s?.[w.face]||v.vertex!==t[w.next].vertex||w.vertex!==t[v.next].vertex||!n.edge_sharp&&a.has(o(v.vertex,w.vertex))||(c.set(p,w.next),f.set(w.next,p),c.set(g,v.next),f.set(v.next,g))}const d=[],l=[],i=[],u=[],m=(h,_)=>pe(_r(n.v[t[t[h][_]].vertex],n.v[t[h].vertex]));for(let h=0;h<t.length;h++){if(l[h]!==void 0)continue;let _=h;const p=new Set([_]);for(;c.has(_)&&!p.has(c.get(_));)_=c.get(_),p.add(_);c.has(_)&&(_=Math.min(...p));const g=[_];for(;f.has(g.at(-1))&&f.get(g.at(-1))!==_;)g.push(f.get(g.at(-1)));let v=[0,0,0];if(g.length===1)v=e[t[_].face];else{for(const P of g)v=Oe(v,e[t[P].face],ge(Qt(m(P,"prev"),m(P,"next"))));v=pe(v)}const w=m(_,"next"),x=g.at(-1),T=m(x,"prev"),y=Qt(w,v),A=Qt(T,v),M={normal:v,reference:[0,0,0],ortho:[0,0,0],alpha:0,beta:0};if(Math.abs(y)<Je&&Math.abs(A)<Je){const P=g.length>1?g.map(ft=>m(ft,"next")):[];P.length&&t[t[x].prev].edge!==t[_].edge&&P.push(T),M.alpha=P.length?C(P.reduce((ft,O)=>C(ft+ge(Qt(O,v))),0)/P.length):C(C(ge(y)+ge(A))/2),M.reference=pe(Oe(w,v,-y));const F=v,U=M.reference;M.ortho=pe([C(C(F[1]*U[2])-C(F[2]*U[1])),C(C(F[2]*U[0])-C(F[0]*U[2])),C(C(F[0]*U[1])-C(F[1]*U[0]))]);const H=pe(Oe(T,v,-A)),G=Qt(M.reference,H),J=ge(G);M.beta=G<Je?Qt(M.ortho,H)<0?C(We-J):J:We}M.alpha===0&&(M.normal=[0,0,0]);for(const P of g)l[P]=d.length;d.push(g),i.push(M),u.push(v)}return{corners:t,fans:d,fanOf:l,spaces:i,faceNormals:e,fanNormals:u}}function gr(n,t){if(!t[0]||n.alpha===0||n.beta===0)return n.normal;const e=C(t[0]/32767),o=C(t[1]/32767),r=C((e>0?n.alpha:C(We-n.alpha))*e),a=C((o>0?n.beta:C(We-n.beta))*o);let s=n.normal.map(f=>C(f*C(Math.cos(r))));return s=Oe(s,n.reference,C(C(Math.sin(r))*C(Math.cos(a)))),o!==0&&(s=Oe(s,n.ortho,C(C(Math.sin(r))*C(Math.sin(a))))),s}function jo(n,t){if(!t)return null;const{corners:e,fans:o,spaces:r}=pr(n);if(t.type==="INT16_2D"&&t.domain==="CORNER"){const a=new Array(e.length);for(const[s,f]of o.entries()){const c=f.reduce((l,i)=>{const u=t.data[i];return[l[0]+u[0],l[1]+u[1]]},[0,0]),d=gr(r[s],c.map(l=>Math.trunc(l/f.length)));for(const l of f)a[l]=d}return a}if(t.type==="FLOAT_VECTOR")return e.map((a,s)=>{const f=t.domain==="POINT"?a.vertex:t.domain==="FACE"?a.face:s;return t.data[f]});throw new Error(`Unsupported custom_normal attribute: ${t.type}/${t.domain}`)}const tn={FLOAT:{size:1},INT:{size:1},INT8:{size:1},BOOLEAN:{size:1},FLOAT2:{size:2},FLOAT_VECTOR:{size:3},FLOAT_COLOR:{size:4},BYTE_COLOR:{size:4},INT16_2D:{size:2},INT32_2D:{size:2},QUATERNION:{size:4},FLOAT4X4:{size:16},FLOAT4:{size:4},STRING:{size:1}},vr=1e-6;function xr(n){const t=new b;for(let e=0;e<n.length;e++){const o=n[e],r=n[(e+1)%n.length];t.x+=(o.y-r.y)*(o.z+r.z),t.y+=(o.z-r.z)*(o.x+r.x),t.z+=(o.x-r.x)*(o.y+r.y)}return t.multiplyScalar(.5)}const br=(n,t,e)=>(t.x-n.x)*(e.y-n.y)-(t.y-n.y)*(e.x-n.x),Yn=n=>Array.from({length:n-2},(t,e)=>[0,e+1,e+2]);function yr(n){let t=0;for(let e=0;e<n.length;e++){const o=n[e],r=n[(e+1)%n.length];t+=o.x*r.y-r.x*o.y}return t}function Zn(n,t,e){if(n.length!==t.length-2||!(Math.abs(e)>0))return!1;const o=Math.sign(e);let r=0;for(const[a,s,f]of n){const c=br(t[a],t[s],t[f]);if(c*o<0)return!1;r+=Math.abs(c)}return Math.abs(r-Math.abs(e))<=vr*Math.abs(e)}function wr(n){const t=n.length;if(t<3)return{triangles:[],sound:!1,method:"fan"};if(t===3)return{triangles:[[0,1,2]],sound:!0,method:"fan"};const e=xr(n),o=e.length();if(!(o>0)||!Number.isFinite(o))return{triangles:Yn(t),sound:!1,method:"fan"};const r=e.clone().divideScalar(o),a=Math.abs(r.x)<.9?new b(1,0,0):new b(0,1,0),s=new b().crossVectors(a,r).normalize(),f=new b().crossVectors(r,s),c=n[0],d=n.map(m=>{const h=m.clone().sub(c);return new ne(h.dot(s),h.dot(f))}),l=yr(d),i=Yn(t);if(Zn(i,d,l))return{triangles:i,sound:!0,method:"fan"};let u=[];try{u=da.triangulateShape(d,[]).map(m=>[m[0],m[1],m[2]])}catch{return{triangles:i,sound:!1,method:"fan"}}return Zn(u,d,l)?{triangles:u,sound:!0,method:"earcut"}:{triangles:u.length>0?u:i,sound:!1,method:u.length>0?"earcut":"fan"}}const Or=new Set(["FLOAT","FLOAT2","FLOAT_VECTOR","FLOAT_COLOR","BYTE_COLOR"]);function en(n){const t=n/255;return t<.04045?t<0?0:t*(1/12.92):((t+.055)*(1/1.055))**2.4}function nn(n,t,e){switch(n){case"FLOAT":{const o=Number(t[e]);return[o,o,o,1]}case"FLOAT2":return[Number(t[e*2]),Number(t[e*2+1]),0,1];case"FLOAT_VECTOR":return[Number(t[e*3]),Number(t[e*3+1]),Number(t[e*3+2]),1];case"BYTE_COLOR":return[en(Number(t[e*4])),en(Number(t[e*4+1])),en(Number(t[e*4+2])),Number(t[e*4+3])/255];default:return[Number(t[e*4]),Number(t[e*4+1]),Number(t[e*4+2]),Number(t[e*4+3])]}}function Rn(n,t){return n.filter(e=>Or.has(e.type)&&e.domain!=="EDGE"&&!e.name.startsWith(".")&&e.name!=="position"&&e.name!=="custom_normal"&&!(e.type==="FLOAT2"&&e.domain==="CORNER")).map(e=>{const o=t(e.data,e.type),r=[0,0,0,0];return{name:e.name,domain:e.domain,read:(a,s,f)=>e.domain==="POINT"?nn(e.type,o,a):e.domain==="CORNER"?s===void 0?r:nn(e.type,o,s):f===void 0?r:nn(e.type,o,f)}})}function Vo(n){const t=n.vertexCount,e=n.starts.length-1,o=n.starts,r=n.cornerVerts,a=o[e];let s=t;for(let O=0;O<e;O++)s+=(o[O+1]-o[O]-2)*3;const f=new Uint32Array(a),c=new Uint8Array(a),d=new Uint8Array(t),l=new Uint32Array(a);let i=!1;for(let O=0;O<e;O++)if(n.smooth(O)){i=!0;break}const u=(O,B)=>t<94906265?Math.min(O,B)*t+Math.max(O,B):`${Math.min(O,B)}:${Math.max(O,B)}`,m=new Map,h=new Set;for(const[O,B]of n.sharp)h.add(u(O,B));if(n.edges)for(const[O,B]of n.edges){if(O===B)throw new Error("Runtime mesh edge needs distinct vertices");m.set(u(O,B),-1)}const _=O=>{for(;l[O]!==O;)l[O]=l[l[O]],O=l[O];return O},p=(O,B)=>{const L=_(O),N=_(B);l[Math.max(L,N)]=Math.min(L,N)};for(let O=0;O<e;O++){const B=o[O],L=o[O+1]-B,N=n.smooth(O)?1:0;for(let D=0;D<L;D++){const E=B+D;d[r[E]]=1,f[E]=B+(D+1)%L,c[E]=N,l[E]=E}}for(let O=0;O<a;O++){const B=f[O],L=r[O],N=r[B],D=u(L,N),E=m.get(D);if(E!==void 0&&E>=0&&c[O]&&c[E]&&!h.has(D)){const S=f[E];p(O,r[E]===L?E:S),p(B,r[E]===L?S:E)}(E===void 0||E<0||!c[E]&&c[O])&&m.set(D,O)}const g=n.uv,v=new Float32Array(s*3),w=new Float32Array(s*2),x=new Uint32Array(s),T=(n.uvLayers??[]).map(O=>({...O,data:new Float32Array(s*2)})),y=(n.attributeLayers??[]).map(O=>({...O,data:new Float32Array(s*4)})),A=n.orco?new Float32Array(s*3):null,M=new Uint32Array(s),P=new Map,F=[],U=n.normals||n.cornerNormal?new Float32Array(s*3):null;let H=0,G=0;const J=(O,B,L,N,D)=>{const E=H++;for(const S of y)S.data.set(S.read(O,N,D),E*4);if(A)for(let S=0;S<3;S++)A[E*3+S]=n.orco[O*3+S]*.5+.5;if(x[E]=O,n.co(O).toArray(v,E*3),B&&w.set(B,E*2),L&&U.set(L,E*3),N!==void 0)for(const S of T)S.data.set(S.read(N),E*2);return E},ft=(O,B)=>{const L=g?.(O),N=n.cornerNormal?[n.cornerNormal[O*3],n.cornerNormal[O*3+1],n.cornerNormal[O*3+2]]:n.normals?.[O];if(!i)return J(r[O],L,N,O,B);const D=`${c[O]?_(O):O}${L?`:${L[0]}:${L[1]}`:""}${N?`:n${N.join(":")}`:""}${T.map(S=>":"+S.read(O).join(":")).join("")}${y.map(S=>S.domain==="POINT"?"":":"+Array.from(S.read(r[O],O,B)).join(":")).join("")}`;let E=P.get(D);return E===void 0&&(E=J(r[O],L,N,O,B),P.set(D,E)),E};for(let O=0;O<e;O++){const B=G,L=o[O],N=o[O+1]-L,D=[];for(let $=0;$<N;$++)D.push(n.co(r[L+$]));for(const $ of wr(D).triangles)for(const X of $)M[G++]=ft(L+X,O);const E=n.material(O),S=F.at(-1);S?.materialIndex===E?S.count+=G-B:F.push({start:B,count:G-B,materialIndex:E})}for(let O=0;O<t;O++)d[O]||J(O);return{positions:v.slice(0,H*3),normals:U?.slice(0,H*3)??null,uv:g?w.slice(0,H*2):null,uvLayers:T.map(O=>({name:O.name,data:O.data.slice(0,H*2)})),attributeLayers:y.map(O=>({name:O.name,data:O.data.slice(0,H*4)})),orco:A?A.slice(0,H*3):null,indices:M.slice(0,G),sourceVertex:x.slice(0,H),groups:F}}function qt(n){return`blenderA_${Array.from(new TextEncoder().encode(n),t=>t.toString(16).padStart(2,"0")).join("")}`}function $e(n){const t=new re;t.setAttribute("position",new lt(n.positions,3)),t.setAttribute("uv",new lt(n.uv??new Float32Array(n.positions.length/3*2),2)),t.setIndex(new lt(n.indices,1));const e=Object.create(null);for(const[o,r]of(n.uvLayers??[]).entries()){if(o>=8)throw new Error("A Blender mesh supports at most eight UV maps");e[r.name]=o+1,t.setAttribute(`uv${o+1}`,new lt(r.data,2))}t.userData.blenderUvChannels=e;for(const o of n.attributeLayers??[])t.setAttribute(qt(o.name),new lt(o.data,4));t.userData.blenderAttributes=(n.attributeLayers??[]).map(o=>o.name),n.orco&&(t.setAttribute("blenderOrco",new lt(n.orco,3)),t.userData.blenderOrcoFromDoor=!0);for(const o of n.groups)t.addGroup(o.start,o.count,o.materialIndex);return n.normals?t.setAttribute("normal",new lt(n.normals,3)):t.computeVertexNormals(),n.sourceVertex&&t.setAttribute("blenderVertex",new lt(n.sourceVertex,1)),t}function Ar(n,t){const e=n.cornerTri,o=n.cornerNormal,r=n.co.length/3,a=n.corner.length,s=n.faceStart.length-1,f=n.attributes.filter(S=>S.type==="FLOAT2"&&S.domain==="CORNER"),c=n.renderUv??n.activeUv??f[0]?.name,d=f.findIndex(S=>S.name===c);if(c&&d<0)throw new Error(`Runtime UV map ${c} is missing`);const l=Rn(n.attributes,S=>S),i=3+f.length*2+l.length*4,u=new Float32Array(i),m=new Float32Array(i),h=new Uint32Array(u.buffer),_=new Uint32Array(m.buffer),p=new Uint32Array(a),g=new Uint32Array(a),v=new Uint32Array(a),w=new Uint32Array(a),x=new Uint8Array(r);let T=1;for(;T<Math.max(1,a*2);)T*=2;const y=new Uint32Array(T),A=(S,$,X,K)=>{let nt=0;for(let ot=0;ot<3;ot++)K[nt++]=o[S*3+ot];for(const ot of f)for(let at=0;at<2;at++)K[nt++]=Number(ot.data[S*2+at]);for(const ot of l){const at=ot.read(X,S,$);for(let bt=0;bt<4;bt++)K[nt++]=Number(at[bt])}};let M=0;for(let S=0;S<s;S++)for(let $=n.faceStart[S];$<n.faceStart[S+1];$++){const X=n.corner[$];if(X>=r)throw new Error("Native mesh corner references a missing vertex");p[$]=S,x[X]=1,A($,S,X,u);let K=Math.imul(X^2166136261,16777619);for(const at of h)K=Math.imul(K^at,16777619);const nt=K>>>0&T-1;let ot=-1;for(let at=y[nt];at;at=w[at-1]){const bt=at-1,Pt=v[bt];if(n.corner[Pt]!==X)continue;A(Pt,p[Pt],X,m);let $t=!0;for(let rt=0;rt<i;rt++)if(h[rt]!==_[rt]){$t=!1;break}if($t){ot=bt;break}}ot<0&&(ot=M++,v[ot]=$,w[ot]=y[nt],y[nt]=ot+1),g[$]=ot}let P=0;for(const S of x)S||P++;const F=M+P,U=new Float32Array(F*3),H=new Float32Array(F*3),G=new Uint32Array(F),J=f.map(S=>({name:S.name,data:new Float32Array(F*2)})),ft=l.map(S=>({name:S.name,data:new Float32Array(F*4)})),O=n.orco?new Float32Array(F*3):null,B=(S,$)=>{G[S]=$;for(let X=0;X<3;X++)U[S*3+X]=n.co[$*3+X],O&&(O[S*3+X]=n.orco[$*3+X]*.5+.5)};for(let S=0;S<M;S++){const $=v[S],X=n.corner[$];B(S,X),A($,p[$],X,u),H.set(u.subarray(0,3),S*3);let K=3;for(const nt of J)nt.data.set(u.subarray(K,K+2),S*2),K+=2;for(const nt of ft)nt.data.set(u.subarray(K,K+4),S*4),K+=4}let L=M;for(let S=0;S<r;S++)if(!x[S]){B(L,S);for(let $=0;$<l.length;$++)ft[$].data.set(l[$].read(S,void 0,void 0),L*4);L++}const N=new Uint32Array(e.length),D=[];let E=0;for(let S=0;S<s;S++){const $=n.faceStart[S],X=n.faceStart[S+1],K=Math.max(0,X-$-2)*3;if(E+K>e.length)throw new Error("Native mesh triangulation is incomplete");for(let at=0;at<K;at++){const bt=e[E+at];if(bt<$||bt>=X)throw new Error("Native triangle references a different face");N[E+at]=g[bt]}const nt=n.material[S],ot=D.at(-1);ot?.materialIndex===nt?ot.count+=K:D.push({start:E,count:K,materialIndex:nt}),E+=K}if(E!==e.length)throw new Error("Native mesh triangulation has extra triangles");return{positions:U,normals:H,sourceVertex:G,uv:d<0?null:J[d].data,uvLayers:J,attributeLayers:ft,orco:O,indices:N,groups:D,hash:t}}function Kn(n,t){if(n.cornerTri&&n.cornerNormal)return Ar(n,t);const e=n.co.length/3,o=n.attributes.filter(_=>_.type==="FLOAT2"&&_.domain==="CORNER"),r=n.renderUv??n.activeUv??o[0]?.name,a=o.find(_=>_.name===r);if(r&&!a)throw new Error(`Runtime UV map ${r} is missing`);const s=a?a.data:null,f=n.edge.length/2,c=new Array(f);for(let _=0;_<f;_++)c[_]=[n.edge[_*2],n.edge[_*2+1]];const d=[];for(let _=0;_<f;_++)n.edgeSharp[_]===1&&d.push(c[_]);const l=n.cornerNormal?void 0:n.attributes.find(_=>_.name==="custom_normal"),i=l?{v:Array.from({length:e},(_,p)=>[n.co[p*3],n.co[p*3+1],n.co[p*3+2]]),f:Array.from({length:n.faceStart.length-1},(_,p)=>Array.from(n.corner.subarray(n.faceStart[p],n.faceStart[p+1]))),s:Array.from(n.smooth,Boolean),edge_order:c,sharp:d,face_edges:Array.from({length:n.faceStart.length-1},(_,p)=>Array.from(n.cornerEdge.subarray(n.faceStart[p],n.faceStart[p+1]))),edge_sharp:Array.from(n.edgeSharp,Boolean)}:null,u=l?{type:l.type,domain:l.domain,data:Array.from({length:l.data.length/tn[l.type].size},(_,p)=>Array.from({length:tn[l.type].size},(g,v)=>Number(l.data[p*tn[l.type].size+v])))}:void 0,m=new b,h={vertexCount:e,normals:i?jo(i,u):null,cornerNormal:n.cornerNormal,orco:n.orco,co:_=>m.set(n.co[_*3],n.co[_*3+1],n.co[_*3+2]).clone(),starts:n.faceStart,cornerVerts:n.corner,smooth:_=>n.smooth[_]===1,material:_=>n.material[_],edges:c,sharp:d,uv:s?_=>[s[_*2],s[_*2+1]]:null,uvLayers:o.map(_=>({name:_.name,read:p=>[Number(_.data[p*2]),Number(_.data[p*2+1])]})),attributeLayers:Rn(n.attributes,_=>_)};return{...Vo(h),hash:t}}function Mr(n){const t=n.v.map(i=>new b(...i)),e=i=>{const u=t[i];if(!u)throw new Error(`Runtime mesh vertex ${i} is missing`);return u},o=new Uint32Array(n.f.length+1);n.f.forEach((i,u)=>{if(i.length<3||new Set(i).size!==i.length)throw new Error("Runtime mesh face needs at least three distinct vertices");o[u+1]=o[u]+i.length});const r=new Uint32Array(o[n.f.length]);n.f.forEach((i,u)=>i.forEach((m,h)=>{e(m),r[o[u]+h]=m}));for(const[i,u]of n.edge_order??n.e??[])e(i),e(u);const a={POINT:t.length,EDGE:(n.edge_order??n.e??[]).length,FACE:n.f.length,CORNER:r.length};for(const i of n.attributes??[])if(i.domain!=="EDGE"&&i.data.length!==a[i.domain])throw new Error(`Runtime attribute ${i.name} has ${i.data.length} values for ${a[i.domain]} ${i.domain} elements`);const s=(n.attributes??[]).filter(i=>i.type==="FLOAT2"&&i.domain==="CORNER"),f=n.render_uv??n.active_uv??s[0]?.name,c=s.find(i=>i.name===f);if(f&&!c)throw new Error(`Runtime UV map ${f} is missing`);const d=c?.data,l={vertexCount:t.length,normals:jo(n,n.attributes?.find(i=>i.name==="custom_normal")),co:e,starts:o,cornerVerts:r,smooth:i=>!!n.s?.[i],material:i=>n.m?.[i]??0,edges:n.edge_order??n.e??null,sharp:n.sharp??[],uv:d?i=>d[i]:null,uvLayers:s.map(i=>({name:i.name,read:u=>i.data[u]})),attributeLayers:Rn(n.attributes??[],i=>Array.from(i).flat())};return $e(Vo(l))}const Me=1.5707963267948966,Jt=6.283185307179586,Bo=.3183098861837067,Uo=.0795774715459476,Tr=.3,Sr=Uo,Pr=3/16*Bo,xn=.8,Qn=xn*xn,te=6371,Wo=100,bn=te+Wo,Jn=64,to=64,mt=256,Xt=64,Er=[1.679,1.828,1.986,1.307],Nr=[.006605,.01067,.01842,.03156],Rr=[3472e-28,3914e-28,1349e-28,1103e-29],Ir=334.5,Dr=[28722e-28,46168e-28,79706e-28,13578e-27],zr=[15908e-26,17711e-26,20942e-26,24033e-26],eo=13681e16,Cr=2e6,Fr=.73,on=[[53.38691773856467,22.981337506691023,0],[43.90484446636936,71.3477957000534,.10250686796574131],[1.6137278251608962,18.422960591455485,31.742921188390806],[20.762668673810577,2.361421352331437,110.4800964325214]],It=[[3.2409698963165283,-1.5373831987380981,-.49861079454421997],[-.969243586063385,1.8759675025939941,.041555099189281464],[.05563009902834892,-.20397700369358063,1.056971549987793]],qe=n=>n*n,be=n=>n<0?0:n>1?1:n,zt=(n,t,e)=>n+e*(t-n),kr=n=>Math.sqrt(Math.max(n,0)),qo=n=>[-Math.sqrt(1-n*n),0,n];function yn(n,t,e,o,r,a,s){const f=n*o+t*r+e*a,c=n*n+t*t+e*e-s*s;if(c>0&&f>0)return-1;const d=f*f-c;return d<0?-1:d>=f*f?-f+Math.sqrt(d):-f-Math.sqrt(d)}const $r=n=>Pr*(1+qe(n));function Lr(n){const t=1+Qn+2*xn*n;return Uo*(1-Qn)/(t*Math.sqrt(t))}const jr=n=>eo*(Math.exp(-n/Fr)+Cr/eo);function In(n,t){let e=n%Jt;Math.abs(e)>=Math.PI&&(e-=Math.sign(e)*2*Math.PI);let o=t;return(e>=Me||e<=-Me)&&(e=Math.sign(e)*Math.PI-e,o+=Math.PI),o=o%Jt,o<0&&(o+=Jt),o=Jt-o,[e,o]}class Vr{constructor(t,e,o){this.air=t,this.aerosol=e,this.ozone=o,this.lut=new Float32Array(Xt*mt*4)}coefficients(t,e){const o=jr(t)*this.aerosol,r=Math.log(Math.max(t,1e-4)),a=378547397e12*Math.exp(-qe(r-3.22261)*5.55555555-r),s=Math.exp(-.07771971*t**1.16364243);for(let f=0;f<4;f++)e[f]=Dr[f]*o,e[4+f]=zr[f]*o,e[8+f]=Rr[f]*Ir*a*this.ozone,e[12+f]=Nr[f]*s*this.air}transmittance(t,e,o){const[r,a,s]=qo(t),f=zt(te,bn,e),d=yn(0,0,f,r,a,s,bn)/Jn,l=[0,0,0,0],i=new Float64Array(16);for(let u=0;u<Jn;u++){const m=(u+.5)*d,h=r*m,_=a*m,p=f+s*m,g=Math.max(Math.hypot(h,_,p)-te,0);this.coefficients(g,i);for(let v=0;v<4;v++)l[v]+=(i[v]+i[4+v]+i[8+v]+i[12+v])*d}for(let u=0;u<4;u++)o[u]=Math.exp(-l[u])}precompute(){const t=new Float64Array(4);for(let e=0;e<Xt;e++)for(let o=0;o<mt;o++){const r=o/(mt-1),a=e/(Xt-1);this.transmittance(r*2-1,a,t);const s=(e*mt+o)*4;for(let f=0;f<4;f++)this.lut[s+f]=t[f]}}lookup(t,e,o){const r=(mt-1)*be(t*.5+.5),a=(Xt-1)*be(e),s=Math.trunc(r),f=Math.trunc(a),c=Math.min(s+1,mt-1),d=Math.min(f+1,Xt-1),l=r-s,i=a-f,u=(f*mt+s)*4,m=(f*mt+c)*4,h=(d*mt+s)*4,_=(d*mt+c)*4;for(let p=0;p<4;p++)o[p]=zt(zt(this.lut[u+p],this.lut[m+p],l),zt(this.lut[h+p],this.lut[_+p],l),i)}lookupAtGround(t,e){const o=(mt-1)*be(t*.5+.5),r=Math.trunc(o),a=Math.min(r+1,mt-1),s=o-r;for(let f=0;f<4;f++)e[f]=zt(this.lut[r*4+f],this.lut[a*4+f],s)}lookupToSun(t,e){const o=(Xt-1)*be(t),r=Math.trunc(o),a=Math.min(r+1,Xt-1),s=o-r,f=mt-1;for(let c=0;c<4;c++)e[c]=zt(this.lut[(r*mt+f)*4+c],this.lut[(a*mt+f)*4+c],s)}inscattering(t,e,o,r,a,s,f,c,d){const l=-(a*t[0]+s*t[1]+f*t[2]),i=$r(l),u=Lr(l),m=c/to,h=new Float64Array(16),_=new Float64Array(4),p=new Float64Array(4),g=new Float64Array(4),v=new Float64Array(4),w=new Float64Array(4),x=[0,0,0,0],T=[1,1,1,1];for(let y=0;y<to;y++){const A=(y+.5)*m,M=e+a*A,P=o+s*A,F=r+f*A,U=Math.hypot(M,P,F),H=Math.max(U-te,0),G=H/Wo,J=(M*t[0]+P*t[1]+F*t[2])/U;this.coefficients(H,h),this.lookup(J,G,_);const ft=Jt*(1-kr(1-qe(te/U)));this.lookupAtGround(J,g),this.lookupToSun(0,v),this.lookupToSun(G,w);const O=1/(1+5*Math.exp(-17.92*J)),B=[.217,.347,.594,1];for(let L=0;L<4;L++){const N=v[L]/w[L],D=Sr*ft*(Tr*Bo)*g[L]*N*J;p[L]=.02*B[L]*O+D}for(let L=0;L<4;L++){const N=h[L]+h[4+L]+h[8+L]+h[12+L],D=Er[L]*(h[12+L]*(i*_[L]+p[L])+h[4+L]*(u*_[L]+p[L])),E=Math.exp(-m*N),S=Math.max(N,1e-7);x[L]+=T[L]*((D-D*E)/S),T[L]*=E}}for(let y=0;y<4;y++)d[y]=x[y]}}const vt=512,ue=256;function Ho(n,t){const e=new Vr(n.airDensity,n.aerosolDensity,n.ozoneDensity);e.precompute();const o=Math.min(Math.max(n.altitude,1),99999)/1e3,r=qo(Math.cos(Me-t)),a=new Float32Array(vt*ue*3),s=vt/2,f=new Float64Array(4);for(let c=0;c<ue;c++)for(let d=0;d<s;d++){const l=(d+.5)/vt,i=(c+.5)/ue,u=Jt*l,m=i*2-1,h=Math.sign(m)*qe(m)*Me,_=Math.cos(h)*Math.cos(u),p=Math.cos(h)*Math.sin(u),g=Math.sin(h),v=te+o,w=yn(0,0,v,_,p,g,bn),x=yn(0,0,v,_,p,g,te),T=x<0?w:x;e.inscattering(r,0,0,v,_,p,g,T,f);let y=0,A=0,M=0;for(let U=0;U<4;U++)y+=on[U][0]*f[U],A+=on[U][1]*f[U],M+=on[U][2]*f[U];const P=(c*vt+d)*3;a[P]=y,a[P+1]=A,a[P+2]=M;const F=(c*vt+(vt-d-1))*3;a[F]=y,a[F+1]=A,a[F+2]=M}return a}function Br(n){const[t]=In(n.sunElevation,n.sunRotation);return Ho(n,t)}function Dn(n){const[t]=In(n.sunElevation,n.sunRotation);return JSON.stringify([t,n.altitude,n.airDensity,n.aerosolDensity,n.ozoneDensity])}const Ur=6,fe=new Map;function Wr(n){return fe.has(Dn(n))}function Go(n,t){fe.set(Dn(n),t),fe.size>Ur&&fe.delete(fe.keys().next().value)}function qr(n){const[t,e]=In(n.sunElevation,n.sunRotation),o=Dn(n);let r=fe.get(o);r===void 0&&(r=Ho(n,t),Go(n,r));const a=new b;return s=>{const f=Math.hypot(s.x,s.y),c=Math.atan2(s.z,f);let l=(Math.atan2(s.x,s.y)+Math.PI+e)/Jt;l-=Math.floor(l);const i=Math.abs(c),u=be(Math.sqrt(i/Me)*Math.sign(c)*.5+.5),m=l*vt-.5,h=u*ue-.5,_=Math.floor(m),p=Math.floor(h),g=m-_,v=h-p,w=F=>(F%vt+vt)%vt,x=F=>F<0?0:F>ue-1?ue-1:F,T=w(_),y=w(_+1),A=x(p),M=x(p+1),P=[0,0,0];for(let F=0;F<3;F++){const U=zt(r[(A*vt+T)*3+F],r[(A*vt+y)*3+F],g),H=zt(r[(M*vt+T)*3+F],r[(M*vt+y)*3+F],g);P[F]=zt(U,H,v)}return a.set(It[0][0]*P[0]+It[0][1]*P[1]+It[0][2]*P[2],It[1][0]*P[0]+It[1][1]*P[1]+It[1][2]*P[2],It[2][0]*P[0]+It[2][1]*P[1]+It[2][2]*P[2])}}let Bt=null,Pe=!1,Hr=0;const ye=new Map;function Gr(){if(Bt||Pe)return Bt;if(typeof Worker>"u")return Pe=!0,null;try{Bt=new Worker(new URL("/assets/sky-precompute-worker-ChN7J87v.js",import.meta.url),{type:"module"})}catch{return Pe=!0,null}return Bt.onmessage=n=>{const{id:t,pixels:e,error:o}=n.data,r=ye.get(t);r&&(ye.delete(t),e?r.resolve(e):r.reject(new Error(o??"sky worker returned nothing")))},Bt.onerror=n=>{const t=new Error(`sky worker failed: ${n.message||"unknown error"}`);for(const e of ye.values())e.reject(t);ye.clear(),Bt?.terminate(),Bt=null,Pe=!0},Bt}function Xr(n){const t=Gr();if(!t)return Promise.resolve(Br(n));const e=Hr++,o={id:e,parameters:n};return new Promise((r,a)=>{ye.set(e,{resolve:r,reject:a}),t.postMessage(o)})}function Yr(n,t,e,o={}){switch(o.type??"LINEAR"){case"QUADRATIC":{const r=Math.max(n,0);return r*r}case"EASING":{const r=Math.min(1,Math.max(0,n));return r*r*(3-2*r)}case"DIAGONAL":return(n+t)/2;case"SPHERICAL":return Math.max(.999999-Math.hypot(n,t,e),0);case"QUADRATIC_SPHERE":{const r=Math.max(.999999-Math.hypot(n,t,e),0);return r*r}case"RADIAL":return Math.atan2(t,n)/(2*Math.PI)+.5;default:return n}}const an=(n,t)=>t!==0?n/t:0,no=n=>Math.min(1,Math.max(-1,n)),oo=(n,t,e)=>{const o=e!==0?Math.max(e-Math.abs(n-t),0)/e:0;return Math.min(n,t)-o*o*o*e/6},Xo={ADD:(n,t)=>n+t,SUBTRACT:(n,t)=>n-t,MULTIPLY:(n,t)=>n*t,DIVIDE:an,POWER:(n,t)=>t===0?1:n===0||n<0&&!Number.isInteger(t)?0:n**t,LOGARITHM:(n,t)=>n<=0||t<=0?0:an(Math.log(n),Math.log(t)),SQRT:n=>Math.sqrt(Math.max(n,0)),INVERSE_SQRT:n=>n>0?1/Math.sqrt(n):0,ABSOLUTE:Math.abs,RADIANS:n=>n*Math.PI/180,DEGREES:n=>n*180/Math.PI,MINIMUM:(n,t)=>Math.min(n,t),MAXIMUM:(n,t)=>Math.max(n,t),LESS_THAN:(n,t)=>+(n<t),GREATER_THAN:(n,t)=>+(n>t),ROUND:n=>Math.floor(n+.5),FLOOR:Math.floor,CEIL:Math.ceil,FRACT:n=>n-Math.floor(n),MODULO:(n,t)=>t!==0?n%t:0,FLOORED_MODULO:(n,t)=>t!==0?n-Math.floor(n/t)*t:0,TRUNC:Math.trunc,SNAP:(n,t)=>Math.floor(an(n,t))*t,WRAP:(n,t,e)=>t!==e?n-(t-e)*Math.floor((n-e)/(t-e)):e,PINGPONG:(n,t)=>{if(t===0)return 0;const e=(n-t)/(t*2);return Math.abs((e-Math.floor(e))*t*2-t)},SINE:Math.sin,COSINE:Math.cos,TANGENT:Math.tan,SINH:Math.sinh,COSH:Math.cosh,TANH:Math.tanh,ARCSINE:n=>Math.asin(no(n)),ARCCOSINE:n=>Math.acos(no(n)),ARCTANGENT:Math.atan,ARCTAN2:(n,t)=>n===0&&t===0?0:Math.atan2(n,t),SIGN:Math.sign,EXPONENT:Math.exp,COMPARE:(n,t,e)=>+(n===t||Math.abs(n-t)<=Math.max(e,2**-23)),MULTIPLY_ADD:(n,t,e)=>n*t+e,SMOOTH_MIN:oo,SMOOTH_MAX:(n,t,e)=>-oo(-n,-t,e)};function ct(n,t){if(typeof n=="number")return()=>n;if(Array.isArray(n)){const r=new b(...n);return()=>r}if(n.kind==="direction")return r=>r;if(n.kind==="window"){if(!t)throw new Error("World Window coordinates need a render camera");return t}if(n.kind==="gradient"){const r=ct(n.vector,t),a={type:n.gradient_type},s=new b;return f=>{const c=r(f),d=typeof c=="number"?c:c.x,l=typeof c=="number"?c:c.y,i=typeof c=="number"?c:c.z,u=wt.clamp(Yr(d,l,i,a),0,1);return n.output==="Fac"?u:s.setScalar(u)}}if(n.kind==="to_float"){const r=ct(n.value,t);return a=>{const s=r(a);return typeof s=="number"?s:Math.fround(n.source_type==="RGBA"?s.x*.212639+s.y*.7151687+s.z*.0721923:(s.x+s.y+s.z)/3)}}if(n.kind==="math"){const r=n.inputs.map(f=>ct(f,t)),a=Xo[n.operation],s=(f,c)=>{const d=r[f]?.(c)??0;if(typeof d!="number")throw new Error("World Math needs scalar inputs");return Math.fround(d)};return f=>{const c=Math.fround(a(s(0,f),s(1,f),s(2,f)));return n.clamp?wt.clamp(c,0,1):c}}if(n.kind==="mix_color"){const r=ct(n.factor,t),a=ct(n.a,t),s=ct(n.b,t),f=new b,c=new b;return d=>{const l=r(d);if(typeof l!="number")throw new Error("World color Mix needs a scalar factor");const i=a(d);typeof i=="number"?f.setScalar(i):f.copy(i);const u=s(d);return typeof u=="number"?c.setScalar(u):c.copy(u),f.lerp(c,n.clamp_factor?wt.clamp(l,0,1):l),n.clamp_result&&f.clampScalar(0,1),f}}if(n.kind==="sky"){const r=qr({sunElevation:n.sun_elevation,sunRotation:n.sun_rotation,altitude:n.altitude,airDensity:n.air_density,aerosolDensity:n.aerosol_density,ozoneDensity:n.ozone_density});return a=>r(a)}if(n.kind==="mapping"){const r=ct(n.vector,t),a=new b(...n.location),s=new b(...n.scale),f=new St().setFromEuler(new ma(n.rotation[0],n.rotation[1],n.rotation[2],"ZYX")),c=f.clone().invert(),d=new b(...n.scale.map(i=>i===0?0:1/i)),l=new b;return i=>{const u=r(i);switch(typeof u=="number"?l.setScalar(u):l.copy(u),n.vector_type??"POINT"){case"TEXTURE":return l.sub(a).applyQuaternion(c).multiply(d);case"VECTOR":return l.multiply(s).applyQuaternion(f);case"NORMAL":return l.multiply(d).applyQuaternion(f).normalize();case"POINT":return l.multiply(s).applyQuaternion(f).add(a)}}}if(n.kind==="map_range"){const r=ct(n.value,t),a=ct(n.from_min,t),s=ct(n.from_max,t),f=ct(n.to_min,t),c=ct(n.to_max,t),d=ct(n.steps,t),l=(m,h)=>{const _=m(h);if(typeof _!="number")throw new Error("World Map Range needs scalar inputs");return _},i=n.interpolation,u=n.clamp;return m=>{const h=l(r,m),_=l(a,m),p=l(s,m),g=l(f,m),v=l(c,m);if(_===p)return 0;let w;if(i==="STEPPED"){const T=l(d,m),y=(h-_)/(p-_);w=T>0?Math.floor(y*(T+1))/T:0}else if(i==="SMOOTHSTEP"||i==="SMOOTHERSTEP"){const T=wt.clamp((h-Math.min(_,p))/(Math.max(_,p)-Math.min(_,p)),0,1),y=i==="SMOOTHSTEP"?T*T*(3-2*T):T*T*T*(T*(T*6-15)+10);w=_>p?1-y:y}else w=(h-_)/(p-_);const x=g+w*(v-g);return u?g>v?wt.clamp(x,v,g):wt.clamp(x,g,v):x}}if(n.kind==="separate"){const r=ct(n.vector,t);return a=>{const s=r(a);return typeof s=="number"?s:s.getComponent(n.axis)}}const e=ct(n.factor,t),o=new b;return r=>{const a=e(r);if(typeof a!="number")throw new Error("World ColorRamp needs a scalar factor");const s=wt.clamp(a,0,1)*256,f=Math.floor(s),c=n.colors[f],d=n.colors[Math.min(f+1,256)],l=n.interpolate?s-f:0;return o.set(wt.lerp(c[0],d[0],l),wt.lerp(c[1],d[1],l),wt.lerp(c[2],d[2],l))}}function Zr(n,t,e,o){const r=new Float32Array(t*e*3),a=ct(n,o),s=new b;for(let f=0;f<e;f++){const c=((f+.5)/e-.5)*Math.PI;for(let d=0;d<t;d++){const l=((d+.5)/t-.5)*2*Math.PI;s.set(Math.cos(c)*Math.cos(l),-Math.cos(c)*Math.sin(l),Math.sin(c));const i=a(s),u=(f*t+d)*3;r[u]=typeof i=="number"?i:i.x,r[u+1]=typeof i=="number"?i:i.y,r[u+2]=typeof i=="number"?i:i.z}}return r}function ao(n){const t=[],e=o=>{if(!(typeof o=="number"||Array.isArray(o)))switch(o.kind){case"sky":t.push({sunElevation:o.sun_elevation,sunRotation:o.sun_rotation,altitude:o.altitude,airDensity:o.air_density,aerosolDensity:o.aerosol_density,ozoneDensity:o.ozone_density});return;case"mapping":case"gradient":case"separate":e(o.vector);return;case"ramp":e(o.factor);return;case"mix_color":e(o.factor),e(o.a),e(o.b);return;case"math":o.inputs.forEach(e);return;case"to_float":e(o.value);return;case"map_range":e(o.value),e(o.from_min),e(o.from_max),e(o.to_min),e(o.to_max),e(o.steps);return;default:return}};return e(n),t}function Wt(n){if(typeof n=="number"||Array.isArray(n))return!1;switch(n.kind){case"window":return!0;case"mapping":case"gradient":case"separate":return Wt(n.vector);case"ramp":return Wt(n.factor);case"mix_color":return[n.factor,n.a,n.b].some(Wt);case"math":return n.inputs.some(Wt);case"to_float":return Wt(n.value);case"map_range":return[n.value,n.from_min,n.from_max,n.to_min,n.to_max,n.steps].some(Wt);default:return!1}}function Kr(n,t,e,o){o.updateMatrixWorld();const r=new Float32Array(t*e*3),a=new b,s=ct(n,()=>a),f=new b,c=o.getWorldPosition(new b),d=o.getWorldDirection(new b);for(let l=0;l<e;l++)for(let i=0;i<t;i++){const u=(i+.5)/t,m=(l+.5)/e;a.set(u,m,0),o.isOrthographicCamera?f.copy(d):f.set(u*2-1,m*2-1,.5).unproject(o).sub(c).normalize(),f.set(f.x,-f.z,f.y);const h=s(f),_=(l*t+i)*3;r[_]=typeof h=="number"?h:h.x,r[_+1]=typeof h=="number"?h:h.y,r[_+2]=typeof h=="number"?h:h.z}return r}const it=I().finite(),Qr=R({type:Q(["POINT","SUN","SPOT","AREA"]),color:W([it,it,it]),energy:it,use_shadow:et().default(!0),radius:it.optional(),spot_size:it.optional(),spot_blend:it.optional(),shape:Q(["SQUARE","RECTANGLE","DISK","ELLIPSE"]).optional(),size:it.optional(),size_y:it.optional()}).strict();let wn;function Jr(){return wn??=Ya(async()=>{const{RectAreaLightUniformsLib:n}=await import("./RectAreaLightUniformsLib-DpPyArRG.js");return{RectAreaLightUniformsLib:n}},__vite__mapDeps([0,1,2])).then(({RectAreaLightUniformsLib:n})=>{n.init(),_t()}),wn}function ts(){return wn??Promise.resolve()}const es=n=>{const t=n.size??0,e=n.size_y??t;if(n.shape==="RECTANGLE")return[t,e];if(n.shape==="DISK"){const o=Math.sqrt(Math.PI*t*t/4);return[o,o]}if(n.shape==="ELLIPSE"){const o=Math.sqrt(Math.PI/4);return[t*o,e*o]}return[t,t]};function ns(n,t){const e=(s,f)=>t&&f(t)?t:new s;if(n.type==="SUN"){const s=e(No,f=>f.isDirectionalLight);return s.intensity=n.energy,s.color.setRGB(n.color[0],n.color[1],n.color[2],xt),s.castShadow=n.use_shadow,s}if(n.type==="POINT"){const s=e(_n,f=>f.isPointLight);return s.intensity=n.energy/(4*Math.PI),s.distance=0,s.decay=2,s.color.setRGB(n.color[0],n.color[1],n.color[2],xt),s.castShadow=n.use_shadow,s}if(n.type==="SPOT"){const s=e(hn,f=>f.isSpotLight);return s.intensity=n.energy/(4*Math.PI),s.distance=0,s.decay=2,s.angle=(n.spot_size??0)/2,s.penumbra=n.spot_blend??0,s.color.setRGB(n.color[0],n.color[1],n.color[2],xt),s.castShadow=n.use_shadow,s}Jr();const o=e(ke,s=>s.isRectAreaLight),[r,a]=es(n);return o.width=r,o.height=a,o.intensity=n.energy/(Math.max(r*a,Number.MIN_VALUE)*Math.PI),o.color.setRGB(n.color[0],n.color[1],n.color[2],xt),o}function os(n,t,e){if(!n.castShadow||e<=0)return;const r=n.getWorldPosition(new b).distanceTo(t),a=n.shadow;if(!a)return;const s=a.camera;s.near=Math.max(e*.001,r-e),s.far=r+e,n.isDirectionalLight&&(s.left=-e,s.right=e,s.top=e,s.bottom=-e),s.updateProjectionMatrix()}function as(n,t){n.position.set(0,0,0);const e=n;n.isRectAreaLight||e.target&&e.target.parent!==t&&(e.target.position.set(0,0,-1),t.add(e.target))}const zn=[{direction:[-.352546,.170931,-.920051],diffuse:[.033103,.033103,.033103],specular:[.266761,.266761,.266761],smooth:.52662},{direction:[-.408163,.346939,.844415],diffuse:[.521083,.538226,.538226],specular:[.59903,.59903,.59903],smooth:0},{direction:[.521739,.826087,.212999],diffuse:[.038403,.034357,.04953],specular:[.106102,.125981,.158523],smooth:.478261},{direction:[.624519,-.562067,-.542269],diffuse:[.090838,.08208,.072255],specular:[.106535,.084771,.06608],smooth:.2}],ro=.69;class rs{constructor(){this.group=new ut,this.lights=[],this.group.name="BlenderSolidStudio";const t=new Ve;t.name="BlenderSolidStudioTarget",this.group.add(t);const e=new Mt(0,0,0);for(const[r,a]of zn.entries()){const s=(1+a.smooth)**2,f=new No(16777215,Math.PI*ro/s);f.name=`BlenderSolidLight${r}`,f.color.setRGB(a.diffuse[0],a.diffuse[1],a.diffuse[2],xt),f.position.set(a.direction[0],a.direction[1],a.direction[2]),f.target=t,this.group.add(f),this.lights.push(f),e.r+=a.diffuse[0]*a.smooth/s,e.g+=a.diffuse[1]*a.smooth/s,e.b+=a.diffuse[2]*a.smooth/s}const o=new _a(16777215,Math.PI*ro);o.name="BlenderSolidWrapFill",o.color.copy(e),this.group.add(o),this.lights.push(o)}setRendered(t){this.group.visible=!t}dispose(){for(const t of this.lights)t.dispose();this.group.clear()}}const le=W([it,it,it]),tt=$o(()=>Gt([it,le,R({kind:Z("direction")}).strict(),R({kind:Z("window")}).strict(),R({kind:Z("gradient"),gradient_type:Q(["LINEAR","QUADRATIC","EASING","DIAGONAL","SPHERICAL","QUADRATIC_SPHERE","RADIAL"]),output:Q(["Fac","Color"]),vector:tt}).strict(),R({kind:Z("to_float"),source_type:Q(["RGBA","VECTOR"]),value:tt}).strict(),R({kind:Z("math"),operation:Q(Object.keys(Xo)),clamp:et(),inputs:j(tt).min(1).max(3)}).strict(),R({kind:Z("mix_color"),factor:tt,a:tt,b:tt,clamp_factor:et(),clamp_result:et()}).strict(),R({kind:Z("mapping"),vector_type:Q(["POINT","TEXTURE","VECTOR","NORMAL"]).optional(),vector:tt,location:le,rotation:le,scale:le}).strict(),R({kind:Z("separate"),vector:tt,axis:I().int().min(0).max(2)}).strict(),R({kind:Z("ramp"),factor:tt,colors:j(le).length(257),interpolate:et()}).strict(),R({kind:Z("map_range"),interpolation:Q(["LINEAR","STEPPED","SMOOTHSTEP","SMOOTHERSTEP"]),clamp:et(),value:tt,from_min:tt,from_max:tt,to_min:tt,to_max:tt,steps:tt}).strict(),R({kind:Z("sky"),sun_elevation:it,sun_rotation:it,altitude:it,air_density:it,aerosol_density:it,ozone_density:it}).strict()])),so=R({color:le,strength:it,shader:tt.optional()}),ss=so.extend({volume:j(R({kind:Q(["absorption","scatter","principled","emission"]),phase:z(),alpha:tt,weight:tt,color:tt,density:tt,anisotropy:tt,absorption_color:tt,emission_color:tt,emission_strength:tt,blackbody_intensity:tt,temperature:tt,blackbody_tint:tt}).strict()).optional(),lighting:so.strict().optional()}).strict(),is=4,ve=new Map,rn=new Set;function io(n,t,e){const a=Wt(n);if(a&&!e)throw new Error("World Window coordinates need a render camera");e?.updateMatrixWorld();const s=JSON.stringify([n,a?[e.matrixWorld.elements,e.projectionMatrix.elements]:null]),f=ve.get(s);if(f!==void 0)return On(f,t,256,128);const c=new b,d=new Xe,l=e?new q().multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse):null,i=e?.getWorldPosition(new b),m=Zr(n,256,128,a?h=>(c.set(h.x,h.z,-h.y),e.isPerspectiveCamera&&c.add(i),d.set(c.x,c.y,c.z,1).applyMatrix4(l),d.w===0?c.set(0,0,0):c.set(d.x/d.w*.5+.5,d.y/d.w*.5+.5,0)):void 0);return ve.set(s,m),ve.size>is&&ve.delete(ve.keys().next().value),On(m,t,256,128)}function ls(n,t,e,o){const r=xe.toHalfFloat(1);for(let a=0;a<o;a++)n[a*4]=xe.toHalfFloat(t[a*3]*e),n[a*4+1]=xe.toHalfFloat(t[a*3+1]*e),n[a*4+2]=xe.toHalfFloat(t[a*3+2]*e),n[a*4+3]=r}function On(n,t,e,o){const r=new Uint16Array(e*o*4);ls(r,n,t,e*o);const a=new Ye(r,e,o,Ze,En);return a.mapping=pa,a.colorSpace=xt,a.minFilter=oe,a.magFilter=oe,a.needsUpdate=!0,a}class Cn{constructor(){this.pending=null,this.texture=null,this.environmentTexture=null,this.screenTexture=null,this.applied=null,this.generation=0}async ready(){await this.pending}static sceneOf(t){let e=t;for(;e;){if(e.isScene)return e;e=e.parent}return null}apply(t,e,o){if(this.clear(),this.pending=null,!e)return;const r=Cn.sceneOf(t);if(!r)return;this.applied={scene:r,background:r.background,environment:r.environment};const a=e.shader??e.color,s=this.generation,c=[...ao(a),...e.lighting?ao(e.lighting.shader??e.lighting.color):[]].filter(l=>!Wr(l));if(c.length===0){this.compose(r,e,a,o);return}const d=(async()=>{const l=await Promise.all(c.map(Xr));c.forEach((i,u)=>{Go(i,l[u])}),!(this.generation!==s||this.applied?.scene!==r)&&(this.compose(r,e,a,o),_t())})();this.pending=d,rn.add(d),d.then(()=>rn.delete(d),()=>rn.delete(d))}compose(t,e,o,r){if(this.texture=io(o,e.strength,r),Wt(o)){if(!r)throw new Error("World Window coordinates need a render camera");this.screenTexture=On(Kr(o,512,512,r),e.strength,512,512),this.screenTexture.mapping=ha,t.background=this.screenTexture}else if(r&&r.isOrthographicCamera){const s=r.getWorldDirection(new b);s.set(s.x,-s.z,s.y);const f=ct(e.shader??e.color)(s);t.background=typeof f=="number"?new Mt().setRGB(f,f,f).multiplyScalar(e.strength):new Mt().setRGB(f.x,f.y,f.z).multiplyScalar(e.strength)}else t.background=this.texture;const{lighting:a}=e;this.environmentTexture=a?io(a.shader??a.color,a.strength,r):null,t.environment=this.environmentTexture??this.texture}clear(){this.generation++,this.applied&&(this.applied.scene.background=this.applied.background,this.applied.scene.environment=this.applied.environment,this.applied=null,this.texture?.dispose(),this.texture=null,this.environmentTexture?.dispose(),this.environmentTexture=null,this.screenTexture?.dispose(),this.screenTexture=null)}dispose(){this.clear()}}function Yo(n){return[n.min.x,n.max.x].flatMap(t=>[n.min.y,n.max.y].flatMap(e=>[n.min.z,n.max.z].map(o=>new b(t,e,o))))}function fs(n,t){if(n.isEmpty()||!t.intersectsBox(n))return[];const e=Yo(n);if(e.every(l=>t.containsPoint(l)))return e;const o=[...t.planes,new Zt(new b(1,0,0),-n.min.x),new Zt(new b(-1,0,0),n.max.x),new Zt(new b(0,1,0),-n.min.y),new Zt(new b(0,-1,0),n.max.y),new Zt(new b(0,0,1),-n.min.z),new Zt(new b(0,0,-1),n.max.z)],r=[],a=new b,s=new b,f=new b,c=new b,d=Math.max(1,n.min.length(),n.max.length())*1e-8;for(let l=0;l<o.length;l++)for(let i=l+1;i<o.length;i++)for(let u=i+1;u<o.length;u++){const m=o[l],h=o[i],_=o[u];a.crossVectors(h.normal,_.normal);const p=m.normal.dot(a);Math.abs(p)<1e-12||(s.crossVectors(_.normal,m.normal),f.crossVectors(m.normal,h.normal),c.copy(a).multiplyScalar(-m.constant).addScaledVector(s,-h.constant).addScaledVector(f,-_.constant).divideScalar(p),o.every(g=>g.distanceToPoint(c)>=-d)&&r.push(c.clone()))}return r}function cs(n,t,e){if(!n.castShadow||!t.length)return;n.shadow.updateMatrices(n);const o=n.shadow.camera,r=o.matrixWorldInverse,a=new me().setFromPoints(t.map(u=>u.clone().applyMatrix4(r))),s=a.getSize(new b),f=Math.max(s.length()*1e-6,Number.EPSILON),c=2+2*Math.SQRT2,d=Math.max(s.x,s.y,f)/Math.max(1,Math.min(n.shadow.mapSize.x,n.shadow.mapSize.y)-2*c),l=2*Math.SQRT2*d,i=c*d;a.min.x-=i,a.min.y-=i,a.max.x+=i,a.max.y+=i;for(const u of e){if(u.isEmpty())continue;const m=new me().setFromPoints(Yo(u).map(h=>h.applyMatrix4(r)));m.max.x<a.min.x||m.min.x>a.max.x||m.max.y<a.min.y||m.min.y>a.max.y||(a.min.z=Math.min(a.min.z,m.min.z),a.max.z=Math.max(a.max.z,m.max.z))}o.left=a.min.x,o.right=a.max.x,o.bottom=a.min.y,o.top=a.max.y,o.near=-a.max.z-l-f,o.far=-a.min.z+l+f,o.updateProjectionMatrix(),n.shadow.normalBias=l}const de=I().finite(),lo=W([de,de,de]),Zo=R({min:W([I().int(),I().int(),I().int()]),max:W([I().int(),I().int(),I().int()]),density:j(de),voxelSize:de.positive(),color:lo,emission:lo,densityScale:de.nonnegative()}).strict();function us(n){const t=n.max.map((l,i)=>l-n.min[i]+1);if(t.some(l=>l<=0)||t.reduce((l,i)=>l*i,1)!==n.density.length)throw new Error("Volume density dimensions do not match the evaluated grid");const e=new ga(new Float32Array(n.density),t[0],t[1],t[2]);e.format=va,e.type=Ro,e.minFilter=e.magFilter=oe,e.unpackAlignment=1,e.needsUpdate=!0;const o=new b(...n.min).addScalar(-.5).multiplyScalar(n.voxelSize),r=new b(t[0],t[1],t[2]).multiplyScalar(n.voxelSize),a=new xa(r.x,r.y,r.z),s=a.getAttribute("position");for(let l=0;l<s.count;l++)s.setXYZ(l,o.x+(s.getX(l)>0?r.x:0),o.y+(s.getY(l)>0?r.y:0),o.z+(s.getZ(l)>0?r.z:0));s.needsUpdate=!0,a.computeBoundingBox(),a.computeBoundingSphere();const f=new Pn({glslVersion:ya,side:ba,transparent:!0,depthWrite:!1,premultipliedAlpha:!0,uniforms:{densityGrid:{value:e},minimum:{value:o},extent:{value:r},voxelSize:{value:n.voxelSize},densityScale:{value:n.densityScale},volumeColor:{value:new b(...n.color)},emission:{value:new b(...n.emission)},cameraLocal:{value:new b},rayLocal:{value:new b},orthographic:{value:!1},worldScale:{value:new Eo}},vertexShader:`
19
+ `;function Wt(n){return new bt().setHex(n,Zt)}function Xn(n,t){const e=n.mode==="POSE";let o;return e?t.active&&t.select?o=Wt(Rt.poseActive):t.active?o=Wt(Rt.poseActiveUnsel):t.select?o=Wt(Rt.pose):o=Wt(Rt.wire):o=Wt(Rt.vertex),e&&t.lockedWeight&&o.lerp(Wt(Rt.lockedWeight),Rt.lockedWeightFactor),o}function Yn(n,t){const e=Wt(Rt.solid);return n.mode==="POSE"&&t.lockedWeight&&e.lerp(Wt(Rt.lockedWeight),Rt.lockedWeightFactor),e}const gr=new G,vr=new b,Zn=new Rn;function Kn(n,t){return new G().set(...t.matrix.flat()).premultiply(n).scale(new b().setScalar(t.length))}class xr{constructor(){this.group=new dt,this.disposables=[],this.signature="",this.group.name="BlenderArmatureOverlay"}apply(t,e){const o=[],r=JSON.stringify(t);if(r===this.signature)return o;this.signature=r,this.clear();for(const a of Object.values(t)){const s=e(a.object);if(s===null)continue;a.displayType!=="OCTAHEDRAL"&&a.displayType!=="STICK"&&o.push(`armature ${a.object}: Blender's ${a.displayType} bone display needs data this door does not carry (B-Bone segment matrices, envelope radii), so its bones are drawn octahedral`),a.mode==="EDIT"&&o.push(`armature ${a.object}: in Edit Mode Blender draws the EDIT bones, and this overlay draws the pose — the shapes are the rest pose, not the edited one`);const l=a.bones.filter(m=>!m.hide);if(l.length===0)continue;const u=a.displayType==="STICK"?this.buildStick(a,l,s):this.buildOctahedral(a,l,s);a.showInFront&&u.traverse(m=>{const f=m.material;f&&"depthTest"in f&&(f.depthTest=!1),m.renderOrder=10}),this.group.add(u)}return o}buildOctahedral(t,e,o){const r=new dt;r.name=`${t.object}:bones`;const a=[],s=[],l=[],u=[],m=[],f=[],i=[],c=[],d=[],_=[];for(const h of e){const g=Kn(o,h),p=Yn(t,h),v=fr(p),x=Xn(t,h);Zn.setFromMatrix4(g).invert().transpose();for(let M=0;M<Hn.length;M++){const O=vr.set(...cr[M]).applyMatrix3(Zn).normalize().clone();for(const y of Hn[M]){const T=new b(...tn[y]).applyMatrix4(g);a.push(T.x,T.y,T.z),s.push(O.x,O.y,O.z),l.push(p.r,p.g,p.b),u.push(v.r,v.g,v.b)}}const w=Gn(h)===2?i:m,S=Gn(h)===2?c:f;for(const[M,O]of ur){const y=new b(...tn[M]).applyMatrix4(g),T=new b(...tn[O]).applyMatrix4(g);w.push(y.x,y.y,y.z,T.x,T.y,T.z),S.push(x.r,x.g,x.b,x.r,x.g,x.b)}h.parent!==null&&h.connected||(d.push(g.clone()),_.push(p)),d.push(g.clone().multiply(gr.makeTranslation(0,1,0))),_.push(p)}r.add(this.solidMesh(a,s,l,u)),m.length&&r.add(this.lines(m,f,1)),i.length&&r.add(this.lines(i,c,2));for(let h=0;h<d.length;h++)r.add(this.point(d[h],_[h]));return r}buildStick(t,e,o){const r=new dt;r.name=`${t.object}:bones`;const a=[],s=[],l=[],u=[];for(const m of e){const f=Kn(o,m),i=new b().setFromMatrixPosition(f),c=new b(0,1,0).applyMatrix4(f),d=Xn(t,m),_=Yn(t,m);a.push(i.x,i.y,i.z,c.x,c.y,c.z),s.push(d.r,d.g,d.b,d.r,d.g,d.b),l.push(i.x,i.y,i.z,c.x,c.y,c.z),u.push(_.r,_.g,_.b,_.r,_.g,_.b)}return r.add(this.lines(a,s,mr)),r.add(this.lines(l,u,_r)),r}solidMesh(t,e,o,r){const a=new Yt;a.setAttribute("position",new It(t,3)),a.setAttribute("normal",new It(e,3)),a.setAttribute("aSolid",new It(o,3)),a.setAttribute("aHint",new It(r,3));const s=new In({vertexShader:hr,fragmentShader:pr,side:ba});this.disposables.push(a,s);const l=new Ft(a,s);return l.frustumCulled=!1,l}lines(t,e,o){const r=new Co;r.setPositions(t),r.setColors(e);const a=new zo({linewidth:o,vertexColors:!0});this.disposables.push(r,a);const s=new ko(r,a);return s.frustumCulled=!1,s}point(t,e){const o=new ya(dr,12,8),r=new We({color:e});this.disposables.push(o,r);const a=new Ft(o,r);return a.applyMatrix4(t),a.frustumCulled=!1,a}clear(){for(const t of[...this.group.children])this.group.remove(t);for(const t of this.disposables)t.dispose();this.disposables.length=0}dispose(){this.clear(),this.signature=""}}const Qn="RUNTIME_FRAME_UNKNOWN_GEOMETRY",ge="RUNTIME_FRAME_UNKNOWN_IMAGE";function br(n){const t=Math.fround,e=t(t(t(n[0]*n[0])+t(n[1]*n[1]))+t(n[2]*n[2]));if(e>1e-35){const o=t(Math.sqrt(e)),r=t(1/o);return{unit:[t(n[0]*r),t(n[1]*r),t(n[2]*r)],length:o}}return{unit:[0,0,0],length:0}}const k=Math.fround,Ge=k(2*Math.PI),en=k(1-1e-4),ee=(n,t)=>k(k(k(n[0]*t[0])+k(n[1]*t[1]))+k(n[2]*t[2])),Se=(n,t,e=1)=>n.map((o,r)=>k(o+k(t[r]*e))),yr=(n,t)=>n.map((e,o)=>k(e-t[o]));function ve(n){const t=k(Math.sqrt(ee(n,n)));return t>0?n.map(e=>k(e/t)):[0,0,0]}function xe(n){const t=Math.abs(n)<1?k(1-k(1-Math.abs(n))):1;let e=k(k(.077980478)+k(t*k(-.02164095)));e=k(k(-.213300989)+k(t*e)),e=k(k(1.5707963267)+k(t*e));const o=k(k(Math.sqrt(k(1-t)))*e);return n<0?k(k(Math.PI)-o):o}function wr(n){let t=n.at(-1);const e=[0,0,0];for(const o of n){for(let r=0;r<3;r++){const a=(r+1)%3,s=(r+2)%3;e[r]=k(e[r]+k(k(t[a]-o[a])*k(t[s]+o[s])))}t=o}return e}function Or(n){const t=[],e=[],o=(_,h)=>_<h?`${_}:${h}`:`${h}:${_}`,r=new Map((n.edge_order??[]).map(([_,h],g)=>[o(_,h),g])),a=new Set((n.sharp??[]).map(([_,h])=>o(_,h))),s=new Map;for(const[_,h]of n.f.entries()){const g=t.length,p=br(wr(h.map(v=>n.v[v]))).unit;e.push(p.some(Boolean)?p:[0,0,1]);for(let v=0;v<h.length;v++){const x=o(h[v],h[(v+1)%h.length]);r.has(x)||r.set(x,r.size);const w=n.face_edges?.[_]?.[v]??r.get(x),S=t.length;t.push({vertex:h[v],face:_,edge:w,prev:g+(v+h.length-1)%h.length,next:g+(v+1)%h.length});const M=s.get(w)??[];M.push(S),s.set(w,M)}}const l=new Map,u=new Map;for(const[_,h]of s){if(h.length!==2||n.edge_sharp?.[_])continue;const[g,p]=h,v=t[g],x=t[p];!n.s?.[v.face]||!n.s?.[x.face]||v.vertex!==t[x.next].vertex||x.vertex!==t[v.next].vertex||!n.edge_sharp&&a.has(o(v.vertex,x.vertex))||(u.set(g,x.next),l.set(x.next,g),u.set(p,v.next),l.set(v.next,p))}const m=[],f=[],i=[],c=[],d=(_,h)=>ve(yr(n.v[t[t[_][h]].vertex],n.v[t[_].vertex]));for(let _=0;_<t.length;_++){if(f[_]!==void 0)continue;let h=_;const g=new Set([h]);for(;u.has(h)&&!g.has(u.get(h));)h=u.get(h),g.add(h);u.has(h)&&(h=Math.min(...g));const p=[h];for(;l.has(p.at(-1))&&l.get(p.at(-1))!==h;)p.push(l.get(p.at(-1)));let v=[0,0,0];if(p.length===1)v=e[t[h].face];else{for(const T of p)v=Se(v,e[t[T].face],xe(ee(d(T,"prev"),d(T,"next"))));v=ve(v)}const x=d(h,"next"),w=p.at(-1),S=d(w,"prev"),M=ee(x,v),O=ee(S,v),y={normal:v,reference:[0,0,0],ortho:[0,0,0],alpha:0,beta:0};if(Math.abs(M)<en&&Math.abs(O)<en){const T=p.length>1?p.map(ct=>d(ct,"next")):[];T.length&&t[t[w].prev].edge!==t[h].edge&&T.push(S),y.alpha=T.length?k(T.reduce((ct,A)=>k(ct+xe(ee(A,v))),0)/T.length):k(k(xe(M)+xe(O))/2),y.reference=ve(Se(x,v,-M));const P=v,j=y.reference;y.ortho=ve([k(k(P[1]*j[2])-k(P[2]*j[1])),k(k(P[2]*j[0])-k(P[0]*j[2])),k(k(P[0]*j[1])-k(P[1]*j[0]))]);const q=ve(Se(S,v,-O)),H=ee(y.reference,q),X=xe(H);y.beta=H<en?ee(y.ortho,q)<0?k(Ge-X):X:Ge}y.alpha===0&&(y.normal=[0,0,0]);for(const T of p)f[T]=m.length;m.push(p),i.push(y),c.push(v)}return{corners:t,fans:m,fanOf:f,spaces:i,faceNormals:e,fanNormals:c}}function Ar(n,t){if(!t[0]||n.alpha===0||n.beta===0)return n.normal;const e=k(t[0]/32767),o=k(t[1]/32767),r=k((e>0?n.alpha:k(Ge-n.alpha))*e),a=k((o>0?n.beta:k(Ge-n.beta))*o);let s=n.normal.map(l=>k(l*k(Math.cos(r))));return s=Se(s,n.reference,k(k(Math.sin(r))*k(Math.cos(a)))),o!==0&&(s=Se(s,n.ortho,k(k(Math.sin(r))*k(Math.sin(a))))),s}function Yo(n,t){if(!t)return null;const{corners:e,fans:o,spaces:r}=Or(n);if(t.type==="INT16_2D"&&t.domain==="CORNER"){const a=new Array(e.length);for(const[s,l]of o.entries()){const u=l.reduce((f,i)=>{const c=t.data[i];return[f[0]+c[0],f[1]+c[1]]},[0,0]),m=Ar(r[s],u.map(f=>Math.trunc(f/l.length)));for(const f of l)a[f]=m}return a}if(t.type==="FLOAT_VECTOR")return e.map((a,s)=>{const l=t.domain==="POINT"?a.vertex:t.domain==="FACE"?a.face:s;return t.data[l]});throw new Error(`Unsupported custom_normal attribute: ${t.type}/${t.domain}`)}const nn={FLOAT:{size:1},INT:{size:1},INT8:{size:1},BOOLEAN:{size:1},FLOAT2:{size:2},FLOAT_VECTOR:{size:3},FLOAT_COLOR:{size:4},BYTE_COLOR:{size:4},INT16_2D:{size:2},INT32_2D:{size:2},QUATERNION:{size:4},FLOAT4X4:{size:16},FLOAT4:{size:4},STRING:{size:1}},Mr=1e-6;function Sr(n){const t=new b;for(let e=0;e<n.length;e++){const o=n[e],r=n[(e+1)%n.length];t.x+=(o.y-r.y)*(o.z+r.z),t.y+=(o.z-r.z)*(o.x+r.x),t.z+=(o.x-r.x)*(o.y+r.y)}return t.multiplyScalar(.5)}const Tr=(n,t,e)=>(t.x-n.x)*(e.y-n.y)-(t.y-n.y)*(e.x-n.x),Jn=n=>Array.from({length:n-2},(t,e)=>[0,e+1,e+2]);function Pr(n){let t=0;for(let e=0;e<n.length;e++){const o=n[e],r=n[(e+1)%n.length];t+=o.x*r.y-r.x*o.y}return t}function to(n,t,e){if(n.length!==t.length-2||!(Math.abs(e)>0))return!1;const o=Math.sign(e);let r=0;for(const[a,s,l]of n){const u=Tr(t[a],t[s],t[l]);if(u*o<0)return!1;r+=Math.abs(u)}return Math.abs(r-Math.abs(e))<=Mr*Math.abs(e)}function Er(n){const t=n.length;if(t<3)return{triangles:[],sound:!1,method:"fan"};if(t===3)return{triangles:[[0,1,2]],sound:!0,method:"fan"};const e=Sr(n),o=e.length();if(!(o>0)||!Number.isFinite(o))return{triangles:Jn(t),sound:!1,method:"fan"};const r=e.clone().divideScalar(o),a=Math.abs(r.x)<.9?new b(1,0,0):new b(0,1,0),s=new b().crossVectors(a,r).normalize(),l=new b().crossVectors(r,s),u=n[0],m=n.map(d=>{const _=d.clone().sub(u);return new Ht(_.dot(s),_.dot(l))}),f=Pr(m),i=Jn(t);if(to(i,m,f))return{triangles:i,sound:!0,method:"fan"};let c=[];try{c=wa.triangulateShape(m,[]).map(d=>[d[0],d[1],d[2]])}catch{return{triangles:i,sound:!1,method:"fan"}}return to(c,m,f)?{triangles:c,sound:!0,method:"earcut"}:{triangles:c.length>0?c:i,sound:!1,method:c.length>0?"earcut":"fan"}}const Nr=new Set(["FLOAT","FLOAT2","FLOAT_VECTOR","FLOAT_COLOR","BYTE_COLOR"]);function on(n){const t=n/255;return t<.04045?t<0?0:t*(1/12.92):((t+.055)*(1/1.055))**2.4}function an(n,t,e){switch(n){case"FLOAT":{const o=Number(t[e]);return[o,o,o,1]}case"FLOAT2":return[Number(t[e*2]),Number(t[e*2+1]),0,1];case"FLOAT_VECTOR":return[Number(t[e*3]),Number(t[e*3+1]),Number(t[e*3+2]),1];case"BYTE_COLOR":return[on(Number(t[e*4])),on(Number(t[e*4+1])),on(Number(t[e*4+2])),Number(t[e*4+3])/255];default:return[Number(t[e*4]),Number(t[e*4+1]),Number(t[e*4+2]),Number(t[e*4+3])]}}function zn(n,t){return n.filter(e=>Nr.has(e.type)&&e.domain!=="EDGE"&&!e.name.startsWith(".")&&e.name!=="position"&&e.name!=="custom_normal"&&!(e.type==="FLOAT2"&&e.domain==="CORNER")).map(e=>{const o=t(e.data,e.type),r=[0,0,0,0];return{name:e.name,domain:e.domain,read:(a,s,l)=>e.domain==="POINT"?an(e.type,o,a):e.domain==="CORNER"?s===void 0?r:an(e.type,o,s):l===void 0?r:an(e.type,o,l)}})}function Zo(n){const t=n.vertexCount,e=n.starts.length-1,o=n.starts,r=n.cornerVerts,a=o[e];let s=t;for(let A=0;A<e;A++)s+=(o[A+1]-o[A]-2)*3;const l=new Uint32Array(a),u=new Uint8Array(a),m=new Uint8Array(t),f=new Uint32Array(a);let i=!1;for(let A=0;A<e;A++)if(n.smooth(A)){i=!0;break}const c=(A,U)=>t<94906265?Math.min(A,U)*t+Math.max(A,U):`${Math.min(A,U)}:${Math.max(A,U)}`,d=new Map,_=new Set;for(const[A,U]of n.sharp)_.add(c(A,U));if(n.edges)for(const[A,U]of n.edges){if(A===U)throw new Error("Runtime mesh edge needs distinct vertices");d.set(c(A,U),-1)}const h=A=>{for(;f[A]!==A;)f[A]=f[f[A]],A=f[A];return A},g=(A,U)=>{const L=h(A),R=h(U);f[Math.max(L,R)]=Math.min(L,R)};for(let A=0;A<e;A++){const U=o[A],L=o[A+1]-U,R=n.smooth(A)?1:0;for(let C=0;C<L;C++){const N=U+C;m[r[N]]=1,l[N]=U+(C+1)%L,u[N]=R,f[N]=N}}for(let A=0;A<a;A++){const U=l[A],L=r[A],R=r[U],C=c(L,R),N=d.get(C);if(N!==void 0&&N>=0&&u[A]&&u[N]&&!_.has(C)){const E=l[N];g(A,r[N]===L?N:E),g(U,r[N]===L?E:N)}(N===void 0||N<0||!u[N]&&u[A])&&d.set(C,A)}const p=n.uv,v=new Float32Array(s*3),x=new Float32Array(s*2),w=new Uint32Array(s),S=(n.uvLayers??[]).map(A=>({...A,data:new Float32Array(s*2)})),M=(n.attributeLayers??[]).map(A=>({...A,data:new Float32Array(s*4)})),O=n.orco?new Float32Array(s*3):null,y=new Uint32Array(s),T=new Map,P=[],j=n.normals||n.cornerNormal?new Float32Array(s*3):null;let q=0,H=0;const X=(A,U,L,R,C)=>{const N=q++;for(const E of M)E.data.set(E.read(A,R,C),N*4);if(O)for(let E=0;E<3;E++)O[N*3+E]=n.orco[A*3+E]*.5+.5;if(w[N]=A,n.co(A).toArray(v,N*3),U&&x.set(U,N*2),L&&j.set(L,N*3),R!==void 0)for(const E of S)E.data.set(E.read(R),N*2);return N},ct=(A,U)=>{const L=p?.(A),R=n.cornerNormal?[n.cornerNormal[A*3],n.cornerNormal[A*3+1],n.cornerNormal[A*3+2]]:n.normals?.[A];if(!i)return X(r[A],L,R,A,U);const C=`${u[A]?h(A):A}${L?`:${L[0]}:${L[1]}`:""}${R?`:n${R.join(":")}`:""}${S.map(E=>":"+E.read(A).join(":")).join("")}${M.map(E=>E.domain==="POINT"?"":":"+Array.from(E.read(r[A],A,U)).join(":")).join("")}`;let N=T.get(C);return N===void 0&&(N=X(r[A],L,R,A,U),T.set(C,N)),N};for(let A=0;A<e;A++){const U=H,L=o[A],R=o[A+1]-L,C=[];for(let $=0;$<R;$++)C.push(n.co(r[L+$]));for(const $ of Er(C).triangles)for(const Y of $)y[H++]=ct(L+Y,A);const N=n.material(A),E=P.at(-1);E?.materialIndex===N?E.count+=H-U:P.push({start:U,count:H-U,materialIndex:N})}for(let A=0;A<t;A++)m[A]||X(A);return{positions:v.slice(0,q*3),normals:j?.slice(0,q*3)??null,uv:p?x.slice(0,q*2):null,uvLayers:S.map(A=>({name:A.name,data:A.data.slice(0,q*2)})),attributeLayers:M.map(A=>({name:A.name,data:A.data.slice(0,q*4)})),orco:O?O.slice(0,q*3):null,indices:y.slice(0,H),sourceVertex:w.slice(0,q),groups:P}}function Xt(n){return`blenderA_${Array.from(new TextEncoder().encode(n),t=>t.toString(16).padStart(2,"0")).join("")}`}function Be(n){const t=new Yt;t.setAttribute("position",new ft(n.positions,3)),t.setAttribute("uv",new ft(n.uv??new Float32Array(n.positions.length/3*2),2)),t.setIndex(new ft(n.indices,1));const e=Object.create(null);for(const[o,r]of(n.uvLayers??[]).entries()){if(o>=8)throw new Error("A Blender mesh supports at most eight UV maps");e[r.name]=o+1,t.setAttribute(`uv${o+1}`,new ft(r.data,2))}t.userData.blenderUvChannels=e;for(const o of n.attributeLayers??[])t.setAttribute(Xt(o.name),new ft(o.data,4));t.userData.blenderAttributes=(n.attributeLayers??[]).map(o=>o.name),n.orco&&(t.setAttribute("blenderOrco",new ft(n.orco,3)),t.userData.blenderOrcoFromDoor=!0);for(const o of n.groups)t.addGroup(o.start,o.count,o.materialIndex);return n.normals?t.setAttribute("normal",new ft(n.normals,3)):t.computeVertexNormals(),n.sourceVertex&&t.setAttribute("blenderVertex",new ft(n.sourceVertex,1)),t}function Rr(n,t){const e=n.cornerTri,o=n.cornerNormal,r=n.co.length/3,a=n.corner.length,s=n.faceStart.length-1,l=n.attributes.filter(E=>E.type==="FLOAT2"&&E.domain==="CORNER"),u=n.renderUv??n.activeUv??l[0]?.name,m=l.findIndex(E=>E.name===u);if(u&&m<0)throw new Error(`Runtime UV map ${u} is missing`);const f=zn(n.attributes,E=>E),i=3+l.length*2+f.length*4,c=new Float32Array(i),d=new Float32Array(i),_=new Uint32Array(c.buffer),h=new Uint32Array(d.buffer),g=new Uint32Array(a),p=new Uint32Array(a),v=new Uint32Array(a),x=new Uint32Array(a),w=new Uint8Array(r);let S=1;for(;S<Math.max(1,a*2);)S*=2;const M=new Uint32Array(S),O=(E,$,Y,Q)=>{let nt=0;for(let at=0;at<3;at++)Q[nt++]=o[E*3+at];for(const at of l)for(let rt=0;rt<2;rt++)Q[nt++]=Number(at.data[E*2+rt]);for(const at of f){const rt=at.read(Y,E,$);for(let yt=0;yt<4;yt++)Q[nt++]=Number(rt[yt])}};let y=0;for(let E=0;E<s;E++)for(let $=n.faceStart[E];$<n.faceStart[E+1];$++){const Y=n.corner[$];if(Y>=r)throw new Error("Native mesh corner references a missing vertex");g[$]=E,w[Y]=1,O($,E,Y,c);let Q=Math.imul(Y^2166136261,16777619);for(const rt of _)Q=Math.imul(Q^rt,16777619);const nt=Q>>>0&S-1;let at=-1;for(let rt=M[nt];rt;rt=x[rt-1]){const yt=rt-1,Et=v[yt];if(n.corner[Et]!==Y)continue;O(Et,g[Et],Y,d);let $t=!0;for(let st=0;st<i;st++)if(_[st]!==h[st]){$t=!1;break}if($t){at=yt;break}}at<0&&(at=y++,v[at]=$,x[at]=M[nt],M[nt]=at+1),p[$]=at}let T=0;for(const E of w)E||T++;const P=y+T,j=new Float32Array(P*3),q=new Float32Array(P*3),H=new Uint32Array(P),X=l.map(E=>({name:E.name,data:new Float32Array(P*2)})),ct=f.map(E=>({name:E.name,data:new Float32Array(P*4)})),A=n.orco?new Float32Array(P*3):null,U=(E,$)=>{H[E]=$;for(let Y=0;Y<3;Y++)j[E*3+Y]=n.co[$*3+Y],A&&(A[E*3+Y]=n.orco[$*3+Y]*.5+.5)};for(let E=0;E<y;E++){const $=v[E],Y=n.corner[$];U(E,Y),O($,g[$],Y,c),q.set(c.subarray(0,3),E*3);let Q=3;for(const nt of X)nt.data.set(c.subarray(Q,Q+2),E*2),Q+=2;for(const nt of ct)nt.data.set(c.subarray(Q,Q+4),E*4),Q+=4}let L=y;for(let E=0;E<r;E++)if(!w[E]){U(L,E);for(let $=0;$<f.length;$++)ct[$].data.set(f[$].read(E,void 0,void 0),L*4);L++}const R=new Uint32Array(e.length),C=[];let N=0;for(let E=0;E<s;E++){const $=n.faceStart[E],Y=n.faceStart[E+1],Q=Math.max(0,Y-$-2)*3;if(N+Q>e.length)throw new Error("Native mesh triangulation is incomplete");for(let rt=0;rt<Q;rt++){const yt=e[N+rt];if(yt<$||yt>=Y)throw new Error("Native triangle references a different face");R[N+rt]=p[yt]}const nt=n.material[E],at=C.at(-1);at?.materialIndex===nt?at.count+=Q:C.push({start:N,count:Q,materialIndex:nt}),N+=Q}if(N!==e.length)throw new Error("Native mesh triangulation has extra triangles");return{positions:j,normals:q,sourceVertex:H,uv:m<0?null:X[m].data,uvLayers:X,attributeLayers:ct,orco:A,indices:R,groups:C,hash:t}}function eo(n,t){if(n.cornerTri&&n.cornerNormal)return Rr(n,t);const e=n.co.length/3,o=n.attributes.filter(h=>h.type==="FLOAT2"&&h.domain==="CORNER"),r=n.renderUv??n.activeUv??o[0]?.name,a=o.find(h=>h.name===r);if(r&&!a)throw new Error(`Runtime UV map ${r} is missing`);const s=a?a.data:null,l=n.edge.length/2,u=new Array(l);for(let h=0;h<l;h++)u[h]=[n.edge[h*2],n.edge[h*2+1]];const m=[];for(let h=0;h<l;h++)n.edgeSharp[h]===1&&m.push(u[h]);const f=n.cornerNormal?void 0:n.attributes.find(h=>h.name==="custom_normal"),i=f?{v:Array.from({length:e},(h,g)=>[n.co[g*3],n.co[g*3+1],n.co[g*3+2]]),f:Array.from({length:n.faceStart.length-1},(h,g)=>Array.from(n.corner.subarray(n.faceStart[g],n.faceStart[g+1]))),s:Array.from(n.smooth,Boolean),edge_order:u,sharp:m,face_edges:Array.from({length:n.faceStart.length-1},(h,g)=>Array.from(n.cornerEdge.subarray(n.faceStart[g],n.faceStart[g+1]))),edge_sharp:Array.from(n.edgeSharp,Boolean)}:null,c=f?{type:f.type,domain:f.domain,data:Array.from({length:f.data.length/nn[f.type].size},(h,g)=>Array.from({length:nn[f.type].size},(p,v)=>Number(f.data[g*nn[f.type].size+v])))}:void 0,d=new b,_={vertexCount:e,normals:i?Yo(i,c):null,cornerNormal:n.cornerNormal,orco:n.orco,co:h=>d.set(n.co[h*3],n.co[h*3+1],n.co[h*3+2]).clone(),starts:n.faceStart,cornerVerts:n.corner,smooth:h=>n.smooth[h]===1,material:h=>n.material[h],edges:u,sharp:m,uv:s?h=>[s[h*2],s[h*2+1]]:null,uvLayers:o.map(h=>({name:h.name,read:g=>[Number(h.data[g*2]),Number(h.data[g*2+1])]})),attributeLayers:zn(n.attributes,h=>h)};return{...Zo(_),hash:t}}function Ir(n){const t=n.v.map(i=>new b(...i)),e=i=>{const c=t[i];if(!c)throw new Error(`Runtime mesh vertex ${i} is missing`);return c},o=new Uint32Array(n.f.length+1);n.f.forEach((i,c)=>{if(i.length<3||new Set(i).size!==i.length)throw new Error("Runtime mesh face needs at least three distinct vertices");o[c+1]=o[c]+i.length});const r=new Uint32Array(o[n.f.length]);n.f.forEach((i,c)=>i.forEach((d,_)=>{e(d),r[o[c]+_]=d}));for(const[i,c]of n.edge_order??n.e??[])e(i),e(c);const a={POINT:t.length,EDGE:(n.edge_order??n.e??[]).length,FACE:n.f.length,CORNER:r.length};for(const i of n.attributes??[])if(i.domain!=="EDGE"&&i.data.length!==a[i.domain])throw new Error(`Runtime attribute ${i.name} has ${i.data.length} values for ${a[i.domain]} ${i.domain} elements`);const s=(n.attributes??[]).filter(i=>i.type==="FLOAT2"&&i.domain==="CORNER"),l=n.render_uv??n.active_uv??s[0]?.name,u=s.find(i=>i.name===l);if(l&&!u)throw new Error(`Runtime UV map ${l} is missing`);const m=u?.data,f={vertexCount:t.length,normals:Yo(n,n.attributes?.find(i=>i.name==="custom_normal")),co:e,starts:o,cornerVerts:r,smooth:i=>!!n.s?.[i],material:i=>n.m?.[i]??0,edges:n.edge_order??n.e??null,sharp:n.sharp??[],uv:m?i=>m[i]:null,uvLayers:s.map(i=>({name:i.name,read:c=>i.data[c]})),attributeLayers:zn(n.attributes??[],i=>Array.from(i).flat())};return Be(Zo(f))}const Pe=1.5707963267948966,ne=6.283185307179586,Ko=.3183098861837067,Qo=.0795774715459476,Dr=.3,Cr=Qo,zr=3/16*Ko,wn=.8,no=wn*wn,oe=6371,Jo=100,On=oe+Jo,oo=64,ao=64,_t=256,Qt=64,kr=[1.679,1.828,1.986,1.307],Fr=[.006605,.01067,.01842,.03156],$r=[3472e-28,3914e-28,1349e-28,1103e-29],Lr=334.5,jr=[28722e-28,46168e-28,79706e-28,13578e-27],Vr=[15908e-26,17711e-26,20942e-26,24033e-26],ro=13681e16,Br=2e6,Ur=.73,rn=[[53.38691773856467,22.981337506691023,0],[43.90484446636936,71.3477957000534,.10250686796574131],[1.6137278251608962,18.422960591455485,31.742921188390806],[20.762668673810577,2.361421352331437,110.4800964325214]],Ct=[[3.2409698963165283,-1.5373831987380981,-.49861079454421997],[-.969243586063385,1.8759675025939941,.041555099189281464],[.05563009902834892,-.20397700369358063,1.056971549987793]],Xe=n=>n*n,we=n=>n<0?0:n>1?1:n,kt=(n,t,e)=>n+e*(t-n),Wr=n=>Math.sqrt(Math.max(n,0)),ta=n=>[-Math.sqrt(1-n*n),0,n];function An(n,t,e,o,r,a,s){const l=n*o+t*r+e*a,u=n*n+t*t+e*e-s*s;if(u>0&&l>0)return-1;const m=l*l-u;return m<0?-1:m>=l*l?-l+Math.sqrt(m):-l-Math.sqrt(m)}const qr=n=>zr*(1+Xe(n));function Hr(n){const t=1+no+2*wn*n;return Qo*(1-no)/(t*Math.sqrt(t))}const Gr=n=>ro*(Math.exp(-n/Ur)+Br/ro);function kn(n,t){let e=n%ne;Math.abs(e)>=Math.PI&&(e-=Math.sign(e)*2*Math.PI);let o=t;return(e>=Pe||e<=-Pe)&&(e=Math.sign(e)*Math.PI-e,o+=Math.PI),o=o%ne,o<0&&(o+=ne),o=ne-o,[e,o]}class Xr{constructor(t,e,o){this.air=t,this.aerosol=e,this.ozone=o,this.lut=new Float32Array(Qt*_t*4)}coefficients(t,e){const o=Gr(t)*this.aerosol,r=Math.log(Math.max(t,1e-4)),a=378547397e12*Math.exp(-Xe(r-3.22261)*5.55555555-r),s=Math.exp(-.07771971*t**1.16364243);for(let l=0;l<4;l++)e[l]=jr[l]*o,e[4+l]=Vr[l]*o,e[8+l]=$r[l]*Lr*a*this.ozone,e[12+l]=Fr[l]*s*this.air}transmittance(t,e,o){const[r,a,s]=ta(t),l=kt(oe,On,e),m=An(0,0,l,r,a,s,On)/oo,f=[0,0,0,0],i=new Float64Array(16);for(let c=0;c<oo;c++){const d=(c+.5)*m,_=r*d,h=a*d,g=l+s*d,p=Math.max(Math.hypot(_,h,g)-oe,0);this.coefficients(p,i);for(let v=0;v<4;v++)f[v]+=(i[v]+i[4+v]+i[8+v]+i[12+v])*m}for(let c=0;c<4;c++)o[c]=Math.exp(-f[c])}precompute(){const t=new Float64Array(4);for(let e=0;e<Qt;e++)for(let o=0;o<_t;o++){const r=o/(_t-1),a=e/(Qt-1);this.transmittance(r*2-1,a,t);const s=(e*_t+o)*4;for(let l=0;l<4;l++)this.lut[s+l]=t[l]}}lookup(t,e,o){const r=(_t-1)*we(t*.5+.5),a=(Qt-1)*we(e),s=Math.trunc(r),l=Math.trunc(a),u=Math.min(s+1,_t-1),m=Math.min(l+1,Qt-1),f=r-s,i=a-l,c=(l*_t+s)*4,d=(l*_t+u)*4,_=(m*_t+s)*4,h=(m*_t+u)*4;for(let g=0;g<4;g++)o[g]=kt(kt(this.lut[c+g],this.lut[d+g],f),kt(this.lut[_+g],this.lut[h+g],f),i)}lookupAtGround(t,e){const o=(_t-1)*we(t*.5+.5),r=Math.trunc(o),a=Math.min(r+1,_t-1),s=o-r;for(let l=0;l<4;l++)e[l]=kt(this.lut[r*4+l],this.lut[a*4+l],s)}lookupToSun(t,e){const o=(Qt-1)*we(t),r=Math.trunc(o),a=Math.min(r+1,Qt-1),s=o-r,l=_t-1;for(let u=0;u<4;u++)e[u]=kt(this.lut[(r*_t+l)*4+u],this.lut[(a*_t+l)*4+u],s)}inscattering(t,e,o,r,a,s,l,u,m){const f=-(a*t[0]+s*t[1]+l*t[2]),i=qr(f),c=Hr(f),d=u/ao,_=new Float64Array(16),h=new Float64Array(4),g=new Float64Array(4),p=new Float64Array(4),v=new Float64Array(4),x=new Float64Array(4),w=[0,0,0,0],S=[1,1,1,1];for(let M=0;M<ao;M++){const O=(M+.5)*d,y=e+a*O,T=o+s*O,P=r+l*O,j=Math.hypot(y,T,P),q=Math.max(j-oe,0),H=q/Jo,X=(y*t[0]+T*t[1]+P*t[2])/j;this.coefficients(q,_),this.lookup(X,H,h);const ct=ne*(1-Wr(1-Xe(oe/j)));this.lookupAtGround(X,p),this.lookupToSun(0,v),this.lookupToSun(H,x);const A=1/(1+5*Math.exp(-17.92*X)),U=[.217,.347,.594,1];for(let L=0;L<4;L++){const R=v[L]/x[L],C=Cr*ct*(Dr*Ko)*p[L]*R*X;g[L]=.02*U[L]*A+C}for(let L=0;L<4;L++){const R=_[L]+_[4+L]+_[8+L]+_[12+L],C=kr[L]*(_[12+L]*(i*h[L]+g[L])+_[4+L]*(c*h[L]+g[L])),N=Math.exp(-d*R),E=Math.max(R,1e-7);w[L]+=S[L]*((C-C*N)/E),S[L]*=N}}for(let M=0;M<4;M++)m[M]=w[M]}}const vt=512,de=256;function ea(n,t){const e=new Xr(n.airDensity,n.aerosolDensity,n.ozoneDensity);e.precompute();const o=Math.min(Math.max(n.altitude,1),99999)/1e3,r=ta(Math.cos(Pe-t)),a=new Float32Array(vt*de*3),s=vt/2,l=new Float64Array(4);for(let u=0;u<de;u++)for(let m=0;m<s;m++){const f=(m+.5)/vt,i=(u+.5)/de,c=ne*f,d=i*2-1,_=Math.sign(d)*Xe(d)*Pe,h=Math.cos(_)*Math.cos(c),g=Math.cos(_)*Math.sin(c),p=Math.sin(_),v=oe+o,x=An(0,0,v,h,g,p,On),w=An(0,0,v,h,g,p,oe),S=w<0?x:w;e.inscattering(r,0,0,v,h,g,p,S,l);let M=0,O=0,y=0;for(let j=0;j<4;j++)M+=rn[j][0]*l[j],O+=rn[j][1]*l[j],y+=rn[j][2]*l[j];const T=(u*vt+m)*3;a[T]=M,a[T+1]=O,a[T+2]=y;const P=(u*vt+(vt-m-1))*3;a[P]=M,a[P+1]=O,a[P+2]=y}return a}function Yr(n){const[t]=kn(n.sunElevation,n.sunRotation);return ea(n,t)}function Fn(n){const[t]=kn(n.sunElevation,n.sunRotation);return JSON.stringify([t,n.altitude,n.airDensity,n.aerosolDensity,n.ozoneDensity])}const Zr=6,fe=new Map;function Kr(n){return fe.has(Fn(n))}function na(n,t){fe.set(Fn(n),t),fe.size>Zr&&fe.delete(fe.keys().next().value)}function Qr(n){const[t,e]=kn(n.sunElevation,n.sunRotation),o=Fn(n);let r=fe.get(o);r===void 0&&(r=ea(n,t),na(n,r));const a=new b;return s=>{const l=Math.hypot(s.x,s.y),u=Math.atan2(s.z,l);let f=(Math.atan2(s.x,s.y)+Math.PI+e)/ne;f-=Math.floor(f);const i=Math.abs(u),c=we(Math.sqrt(i/Pe)*Math.sign(u)*.5+.5),d=f*vt-.5,_=c*de-.5,h=Math.floor(d),g=Math.floor(_),p=d-h,v=_-g,x=P=>(P%vt+vt)%vt,w=P=>P<0?0:P>de-1?de-1:P,S=x(h),M=x(h+1),O=w(g),y=w(g+1),T=[0,0,0];for(let P=0;P<3;P++){const j=kt(r[(O*vt+S)*3+P],r[(O*vt+M)*3+P],p),q=kt(r[(y*vt+S)*3+P],r[(y*vt+M)*3+P],p);T[P]=kt(j,q,v)}return a.set(Ct[0][0]*T[0]+Ct[0][1]*T[1]+Ct[0][2]*T[2],Ct[1][0]*T[0]+Ct[1][1]*T[1]+Ct[1][2]*T[2],Ct[2][0]*T[0]+Ct[2][1]*T[1]+Ct[2][2]*T[2])}}let Bt=null,Ie=!1,Jr=0;const Oe=new Map;function ts(){if(Bt||Ie)return Bt;if(typeof Worker>"u")return Ie=!0,null;try{Bt=new Worker(new URL("/assets/sky-precompute-worker-ChN7J87v.js",import.meta.url),{type:"module"})}catch{return Ie=!0,null}return Bt.onmessage=n=>{const{id:t,pixels:e,error:o}=n.data,r=Oe.get(t);r&&(Oe.delete(t),e?r.resolve(e):r.reject(new Error(o??"sky worker returned nothing")))},Bt.onerror=n=>{const t=new Error(`sky worker failed: ${n.message||"unknown error"}`);for(const e of Oe.values())e.reject(t);Oe.clear(),Bt?.terminate(),Bt=null,Ie=!0},Bt}function es(n){const t=ts();if(!t)return Promise.resolve(Yr(n));const e=Jr++,o={id:e,parameters:n};return new Promise((r,a)=>{Oe.set(e,{resolve:r,reject:a}),t.postMessage(o)})}function ns(n,t,e,o={}){switch(o.type??"LINEAR"){case"QUADRATIC":{const r=Math.max(n,0);return r*r}case"EASING":{const r=Math.min(1,Math.max(0,n));return r*r*(3-2*r)}case"DIAGONAL":return(n+t)/2;case"SPHERICAL":return Math.max(.999999-Math.hypot(n,t,e),0);case"QUADRATIC_SPHERE":{const r=Math.max(.999999-Math.hypot(n,t,e),0);return r*r}case"RADIAL":return Math.atan2(t,n)/(2*Math.PI)+.5;default:return n}}const sn=(n,t)=>t!==0?n/t:0,so=n=>Math.min(1,Math.max(-1,n)),io=(n,t,e)=>{const o=e!==0?Math.max(e-Math.abs(n-t),0)/e:0;return Math.min(n,t)-o*o*o*e/6},oa={ADD:(n,t)=>n+t,SUBTRACT:(n,t)=>n-t,MULTIPLY:(n,t)=>n*t,DIVIDE:sn,POWER:(n,t)=>t===0?1:n===0||n<0&&!Number.isInteger(t)?0:n**t,LOGARITHM:(n,t)=>n<=0||t<=0?0:sn(Math.log(n),Math.log(t)),SQRT:n=>Math.sqrt(Math.max(n,0)),INVERSE_SQRT:n=>n>0?1/Math.sqrt(n):0,ABSOLUTE:Math.abs,RADIANS:n=>n*Math.PI/180,DEGREES:n=>n*180/Math.PI,MINIMUM:(n,t)=>Math.min(n,t),MAXIMUM:(n,t)=>Math.max(n,t),LESS_THAN:(n,t)=>+(n<t),GREATER_THAN:(n,t)=>+(n>t),ROUND:n=>Math.floor(n+.5),FLOOR:Math.floor,CEIL:Math.ceil,FRACT:n=>n-Math.floor(n),MODULO:(n,t)=>t!==0?n%t:0,FLOORED_MODULO:(n,t)=>t!==0?n-Math.floor(n/t)*t:0,TRUNC:Math.trunc,SNAP:(n,t)=>Math.floor(sn(n,t))*t,WRAP:(n,t,e)=>t!==e?n-(t-e)*Math.floor((n-e)/(t-e)):e,PINGPONG:(n,t)=>{if(t===0)return 0;const e=(n-t)/(t*2);return Math.abs((e-Math.floor(e))*t*2-t)},SINE:Math.sin,COSINE:Math.cos,TANGENT:Math.tan,SINH:Math.sinh,COSH:Math.cosh,TANH:Math.tanh,ARCSINE:n=>Math.asin(so(n)),ARCCOSINE:n=>Math.acos(so(n)),ARCTANGENT:Math.atan,ARCTAN2:(n,t)=>n===0&&t===0?0:Math.atan2(n,t),SIGN:Math.sign,EXPONENT:Math.exp,COMPARE:(n,t,e)=>+(n===t||Math.abs(n-t)<=Math.max(e,2**-23)),MULTIPLY_ADD:(n,t,e)=>n*t+e,SMOOTH_MIN:io,SMOOTH_MAX:(n,t,e)=>-io(-n,-t,e)};function ut(n,t){if(typeof n=="number")return()=>n;if(Array.isArray(n)){const r=new b(...n);return()=>r}if(n.kind==="direction")return r=>r;if(n.kind==="window"){if(!t)throw new Error("World Window coordinates need a render camera");return t}if(n.kind==="gradient"){const r=ut(n.vector,t),a={type:n.gradient_type},s=new b;return l=>{const u=r(l),m=typeof u=="number"?u:u.x,f=typeof u=="number"?u:u.y,i=typeof u=="number"?u:u.z,c=Ot.clamp(ns(m,f,i,a),0,1);return n.output==="Fac"?c:s.setScalar(c)}}if(n.kind==="to_float"){const r=ut(n.value,t);return a=>{const s=r(a);return typeof s=="number"?s:Math.fround(n.source_type==="RGBA"?s.x*.212639+s.y*.7151687+s.z*.0721923:(s.x+s.y+s.z)/3)}}if(n.kind==="math"){const r=n.inputs.map(l=>ut(l,t)),a=oa[n.operation],s=(l,u)=>{const m=r[l]?.(u)??0;if(typeof m!="number")throw new Error("World Math needs scalar inputs");return Math.fround(m)};return l=>{const u=Math.fround(a(s(0,l),s(1,l),s(2,l)));return n.clamp?Ot.clamp(u,0,1):u}}if(n.kind==="mix_color"){const r=ut(n.factor,t),a=ut(n.a,t),s=ut(n.b,t),l=new b,u=new b;return m=>{const f=r(m);if(typeof f!="number")throw new Error("World color Mix needs a scalar factor");const i=a(m);typeof i=="number"?l.setScalar(i):l.copy(i);const c=s(m);return typeof c=="number"?u.setScalar(c):u.copy(c),l.lerp(u,n.clamp_factor?Ot.clamp(f,0,1):f),n.clamp_result&&l.clampScalar(0,1),l}}if(n.kind==="sky"){const r=Qr({sunElevation:n.sun_elevation,sunRotation:n.sun_rotation,altitude:n.altitude,airDensity:n.air_density,aerosolDensity:n.aerosol_density,ozoneDensity:n.ozone_density});return a=>r(a)}if(n.kind==="mapping"){const r=ut(n.vector,t),a=new b(...n.location),s=new b(...n.scale),l=new Tt().setFromEuler(new Oa(n.rotation[0],n.rotation[1],n.rotation[2],"ZYX")),u=l.clone().invert(),m=new b(...n.scale.map(i=>i===0?0:1/i)),f=new b;return i=>{const c=r(i);switch(typeof c=="number"?f.setScalar(c):f.copy(c),n.vector_type??"POINT"){case"TEXTURE":return f.sub(a).applyQuaternion(u).multiply(m);case"VECTOR":return f.multiply(s).applyQuaternion(l);case"NORMAL":return f.multiply(m).applyQuaternion(l).normalize();case"POINT":return f.multiply(s).applyQuaternion(l).add(a)}}}if(n.kind==="map_range"){const r=ut(n.value,t),a=ut(n.from_min,t),s=ut(n.from_max,t),l=ut(n.to_min,t),u=ut(n.to_max,t),m=ut(n.steps,t),f=(d,_)=>{const h=d(_);if(typeof h!="number")throw new Error("World Map Range needs scalar inputs");return h},i=n.interpolation,c=n.clamp;return d=>{const _=f(r,d),h=f(a,d),g=f(s,d),p=f(l,d),v=f(u,d);if(h===g)return 0;let x;if(i==="STEPPED"){const S=f(m,d),M=(_-h)/(g-h);x=S>0?Math.floor(M*(S+1))/S:0}else if(i==="SMOOTHSTEP"||i==="SMOOTHERSTEP"){const S=Ot.clamp((_-Math.min(h,g))/(Math.max(h,g)-Math.min(h,g)),0,1),M=i==="SMOOTHSTEP"?S*S*(3-2*S):S*S*S*(S*(S*6-15)+10);x=h>g?1-M:M}else x=(_-h)/(g-h);const w=p+x*(v-p);return c?p>v?Ot.clamp(w,v,p):Ot.clamp(w,p,v):w}}if(n.kind==="separate"){const r=ut(n.vector,t);return a=>{const s=r(a);return typeof s=="number"?s:s.getComponent(n.axis)}}const e=ut(n.factor,t),o=new b;return r=>{const a=e(r);if(typeof a!="number")throw new Error("World ColorRamp needs a scalar factor");const s=Ot.clamp(a,0,1)*256,l=Math.floor(s),u=n.colors[l],m=n.colors[Math.min(l+1,256)],f=n.interpolate?s-l:0;return o.set(Ot.lerp(u[0],m[0],f),Ot.lerp(u[1],m[1],f),Ot.lerp(u[2],m[2],f))}}function os(n,t,e,o){const r=new Float32Array(t*e*3),a=ut(n,o),s=new b;for(let l=0;l<e;l++){const u=((l+.5)/e-.5)*Math.PI;for(let m=0;m<t;m++){const f=((m+.5)/t-.5)*2*Math.PI;s.set(Math.cos(u)*Math.cos(f),-Math.cos(u)*Math.sin(f),Math.sin(u));const i=a(s),c=(l*t+m)*3;r[c]=typeof i=="number"?i:i.x,r[c+1]=typeof i=="number"?i:i.y,r[c+2]=typeof i=="number"?i:i.z}}return r}function lo(n){const t=[],e=o=>{if(!(typeof o=="number"||Array.isArray(o)))switch(o.kind){case"sky":t.push({sunElevation:o.sun_elevation,sunRotation:o.sun_rotation,altitude:o.altitude,airDensity:o.air_density,aerosolDensity:o.aerosol_density,ozoneDensity:o.ozone_density});return;case"mapping":case"gradient":case"separate":e(o.vector);return;case"ramp":e(o.factor);return;case"mix_color":e(o.factor),e(o.a),e(o.b);return;case"math":o.inputs.forEach(e);return;case"to_float":e(o.value);return;case"map_range":e(o.value),e(o.from_min),e(o.from_max),e(o.to_min),e(o.to_max),e(o.steps);return;default:return}};return e(n),t}function qt(n){if(typeof n=="number"||Array.isArray(n))return!1;switch(n.kind){case"window":return!0;case"mapping":case"gradient":case"separate":return qt(n.vector);case"ramp":return qt(n.factor);case"mix_color":return[n.factor,n.a,n.b].some(qt);case"math":return n.inputs.some(qt);case"to_float":return qt(n.value);case"map_range":return[n.value,n.from_min,n.from_max,n.to_min,n.to_max,n.steps].some(qt);default:return!1}}function as(n,t,e,o){o.updateMatrixWorld();const r=new Float32Array(t*e*3),a=new b,s=ut(n,()=>a),l=new b,u=o.getWorldPosition(new b),m=o.getWorldDirection(new b);for(let f=0;f<e;f++)for(let i=0;i<t;i++){const c=(i+.5)/t,d=(f+.5)/e;a.set(c,d,0),o.isOrthographicCamera?l.copy(m):l.set(c*2-1,d*2-1,.5).unproject(o).sub(u).normalize(),l.set(l.x,-l.z,l.y);const _=s(l),h=(f*t+i)*3;r[h]=typeof _=="number"?_:_.x,r[h+1]=typeof _=="number"?_:_.y,r[h+2]=typeof _=="number"?_:_.z}return r}const lt=D().finite(),rs=I({type:J(["POINT","SUN","SPOT","AREA"]),color:W([lt,lt,lt]),energy:lt,use_shadow:et().default(!0),radius:lt.optional(),spot_size:lt.optional(),spot_blend:lt.optional(),shape:J(["SQUARE","RECTANGLE","DISK","ELLIPSE"]).optional(),size:lt.optional(),size_y:lt.optional()}).strict();let Mn;function ss(){return Mn??=nr(async()=>{const{RectAreaLightUniformsLib:n}=await import("./RectAreaLightUniformsLib-DpPyArRG.js");return{RectAreaLightUniformsLib:n}},__vite__mapDeps([0,1,2])).then(({RectAreaLightUniformsLib:n})=>{n.init(),mt()}),Mn}function is(){return Mn??Promise.resolve()}const ls=n=>{const t=n.size??0,e=n.size_y??t;if(n.shape==="RECTANGLE")return[t,e];if(n.shape==="DISK"){const o=Math.sqrt(Math.PI*t*t/4);return[o,o]}if(n.shape==="ELLIPSE"){const o=Math.sqrt(Math.PI/4);return[t*o,e*o]}return[t,t]};function fs(n,t){const e=(s,l)=>t&&l(t)?t:new s;if(n.type==="SUN"){const s=e(Fo,l=>l.isDirectionalLight);return s.intensity=n.energy,s.color.setRGB(n.color[0],n.color[1],n.color[2],xt),s.castShadow=n.use_shadow,s}if(n.type==="POINT"){const s=e(pn,l=>l.isPointLight);return s.intensity=n.energy/(4*Math.PI),s.distance=0,s.decay=2,s.color.setRGB(n.color[0],n.color[1],n.color[2],xt),s.castShadow=n.use_shadow,s}if(n.type==="SPOT"){const s=e(gn,l=>l.isSpotLight);return s.intensity=n.energy/(4*Math.PI),s.distance=0,s.decay=2,s.angle=(n.spot_size??0)/2,s.penumbra=n.spot_blend??0,s.color.setRGB(n.color[0],n.color[1],n.color[2],xt),s.castShadow=n.use_shadow,s}ss();const o=e(Ve,s=>s.isRectAreaLight),[r,a]=ls(n);return o.width=r,o.height=a,o.intensity=n.energy/(Math.max(r*a,Number.MIN_VALUE)*Math.PI),o.color.setRGB(n.color[0],n.color[1],n.color[2],xt),o}function cs(n,t,e){if(!n.castShadow||e<=0)return;const r=n.getWorldPosition(new b).distanceTo(t),a=n.shadow;if(!a)return;const s=a.camera;s.near=Math.max(e*.001,r-e),s.far=r+e,n.isDirectionalLight&&(s.left=-e,s.right=e,s.top=e,s.bottom=-e),s.updateProjectionMatrix()}function us(n,t){n.position.set(0,0,0);const e=n;n.isRectAreaLight||e.target&&e.target.parent!==t&&(e.target.position.set(0,0,-1),t.add(e.target))}const $n=[{direction:[-.352546,.170931,-.920051],diffuse:[.033103,.033103,.033103],specular:[.266761,.266761,.266761],smooth:.52662},{direction:[-.408163,.346939,.844415],diffuse:[.521083,.538226,.538226],specular:[.59903,.59903,.59903],smooth:0},{direction:[.521739,.826087,.212999],diffuse:[.038403,.034357,.04953],specular:[.106102,.125981,.158523],smooth:.478261},{direction:[.624519,-.562067,-.542269],diffuse:[.090838,.08208,.072255],specular:[.106535,.084771,.06608],smooth:.2}],fo=.69;class ds{constructor(){this.group=new dt,this.lights=[],this.group.name="BlenderSolidStudio";const t=new qe;t.name="BlenderSolidStudioTarget",this.group.add(t);const e=new bt(0,0,0);for(const[r,a]of $n.entries()){const s=(1+a.smooth)**2,l=new Fo(16777215,Math.PI*fo/s);l.name=`BlenderSolidLight${r}`,l.color.setRGB(a.diffuse[0],a.diffuse[1],a.diffuse[2],xt),l.position.set(a.direction[0],a.direction[1],a.direction[2]),l.target=t,this.group.add(l),this.lights.push(l),e.r+=a.diffuse[0]*a.smooth/s,e.g+=a.diffuse[1]*a.smooth/s,e.b+=a.diffuse[2]*a.smooth/s}const o=new Aa(16777215,Math.PI*fo);o.name="BlenderSolidWrapFill",o.color.copy(e),this.group.add(o),this.lights.push(o)}setRendered(t){this.group.visible=!t}dispose(){for(const t of this.lights)t.dispose();this.group.clear()}}const le=W([lt,lt,lt]),tt=Go(()=>Kt([lt,le,I({kind:K("direction")}).strict(),I({kind:K("window")}).strict(),I({kind:K("gradient"),gradient_type:J(["LINEAR","QUADRATIC","EASING","DIAGONAL","SPHERICAL","QUADRATIC_SPHERE","RADIAL"]),output:J(["Fac","Color"]),vector:tt}).strict(),I({kind:K("to_float"),source_type:J(["RGBA","VECTOR"]),value:tt}).strict(),I({kind:K("math"),operation:J(Object.keys(oa)),clamp:et(),inputs:V(tt).min(1).max(3)}).strict(),I({kind:K("mix_color"),factor:tt,a:tt,b:tt,clamp_factor:et(),clamp_result:et()}).strict(),I({kind:K("mapping"),vector_type:J(["POINT","TEXTURE","VECTOR","NORMAL"]).optional(),vector:tt,location:le,rotation:le,scale:le}).strict(),I({kind:K("separate"),vector:tt,axis:D().int().min(0).max(2)}).strict(),I({kind:K("ramp"),factor:tt,colors:V(le).length(257),interpolate:et()}).strict(),I({kind:K("map_range"),interpolation:J(["LINEAR","STEPPED","SMOOTHSTEP","SMOOTHERSTEP"]),clamp:et(),value:tt,from_min:tt,from_max:tt,to_min:tt,to_max:tt,steps:tt}).strict(),I({kind:K("sky"),sun_elevation:lt,sun_rotation:lt,altitude:lt,air_density:lt,aerosol_density:lt,ozone_density:lt}).strict()])),co=I({color:le,strength:lt,shader:tt.optional()}),ms=co.extend({volume:V(I({kind:J(["absorption","scatter","principled","emission"]),phase:z(),alpha:tt,weight:tt,color:tt,density:tt,anisotropy:tt,absorption_color:tt,emission_color:tt,emission_strength:tt,blackbody_intensity:tt,temperature:tt,blackbody_tint:tt}).strict()).optional(),lighting:co.strict().optional()}).strict(),_s=4,be=new Map,ln=new Set;function uo(n,t,e){const a=qt(n);if(a&&!e)throw new Error("World Window coordinates need a render camera");e?.updateMatrixWorld();const s=JSON.stringify([n,a?[e.matrixWorld.elements,e.projectionMatrix.elements]:null]),l=be.get(s);if(l!==void 0)return Sn(l,t,256,128);const u=new b,m=new Ee,f=e?new G().multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse):null,i=e?.getWorldPosition(new b),d=os(n,256,128,a?_=>(u.set(_.x,_.z,-_.y),e.isPerspectiveCamera&&u.add(i),m.set(u.x,u.y,u.z,1).applyMatrix4(f),m.w===0?u.set(0,0,0):u.set(m.x/m.w*.5+.5,m.y/m.w*.5+.5,0)):void 0);return be.set(s,d),be.size>_s&&be.delete(be.keys().next().value),Sn(d,t,256,128)}function hs(n,t,e,o){const r=ye.toHalfFloat(1);for(let a=0;a<o;a++)n[a*4]=ye.toHalfFloat(t[a*3]*e),n[a*4+1]=ye.toHalfFloat(t[a*3+1]*e),n[a*4+2]=ye.toHalfFloat(t[a*3+2]*e),n[a*4+3]=r}function Sn(n,t,e,o){const r=new Uint16Array(e*o*4);hs(r,n,t,e*o);const a=new Ke(r,e,o,Qe,Dn);return a.mapping=Sa,a.colorSpace=xt,a.minFilter=re,a.magFilter=re,a.needsUpdate=!0,a}class Ln{constructor(){this.pending=null,this.texture=null,this.environmentTexture=null,this.screenTexture=null,this.applied=null,this.generation=0}async ready(){await this.pending}static sceneOf(t){let e=t;for(;e;){if(e.isScene)return e;e=e.parent}return null}apply(t,e,o){if(this.clear(),this.pending=null,!e)return;const r=Ln.sceneOf(t);if(!r)return;this.applied={scene:r,background:r.background,environment:r.environment};const a=e.shader??e.color,s=this.generation,u=[...lo(a),...e.lighting?lo(e.lighting.shader??e.lighting.color):[]].filter(f=>!Kr(f));if(u.length===0){this.compose(r,e,a,o);return}const m=(async()=>{const f=await Promise.all(u.map(es));u.forEach((i,c)=>{na(i,f[c])}),!(this.generation!==s||this.applied?.scene!==r)&&(this.compose(r,e,a,o),mt())})();this.pending=m,ln.add(m),m.then(()=>ln.delete(m),()=>ln.delete(m))}compose(t,e,o,r){if(this.texture=uo(o,e.strength,r),qt(o)){if(!r)throw new Error("World Window coordinates need a render camera");this.screenTexture=Sn(as(o,512,512,r),e.strength,512,512),this.screenTexture.mapping=Ma,t.background=this.screenTexture}else if(r&&r.isOrthographicCamera){const s=r.getWorldDirection(new b);s.set(s.x,-s.z,s.y);const l=ut(e.shader??e.color)(s);t.background=typeof l=="number"?new bt().setRGB(l,l,l).multiplyScalar(e.strength):new bt().setRGB(l.x,l.y,l.z).multiplyScalar(e.strength)}else t.background=this.texture;const{lighting:a}=e;this.environmentTexture=a?uo(a.shader??a.color,a.strength,r):null,t.environment=this.environmentTexture??this.texture}clear(){this.generation++,this.applied&&(this.applied.scene.background=this.applied.background,this.applied.scene.environment=this.applied.environment,this.applied=null,this.texture?.dispose(),this.texture=null,this.environmentTexture?.dispose(),this.environmentTexture=null,this.screenTexture?.dispose(),this.screenTexture=null)}dispose(){this.clear()}}function aa(n){return[n.min.x,n.max.x].flatMap(t=>[n.min.y,n.max.y].flatMap(e=>[n.min.z,n.max.z].map(o=>new b(t,e,o))))}function ps(n,t){if(n.isEmpty()||!t.intersectsBox(n))return[];const e=aa(n);if(e.every(f=>t.containsPoint(f)))return e;const o=[...t.planes,new Ut(new b(1,0,0),-n.min.x),new Ut(new b(-1,0,0),n.max.x),new Ut(new b(0,1,0),-n.min.y),new Ut(new b(0,-1,0),n.max.y),new Ut(new b(0,0,1),-n.min.z),new Ut(new b(0,0,-1),n.max.z)],r=[],a=new b,s=new b,l=new b,u=new b,m=Math.max(1,n.min.length(),n.max.length())*1e-8;for(let f=0;f<o.length;f++)for(let i=f+1;i<o.length;i++)for(let c=i+1;c<o.length;c++){const d=o[f],_=o[i],h=o[c];a.crossVectors(_.normal,h.normal);const g=d.normal.dot(a);Math.abs(g)<1e-12||(s.crossVectors(h.normal,d.normal),l.crossVectors(d.normal,_.normal),u.copy(a).multiplyScalar(-d.constant).addScaledVector(s,-_.constant).addScaledVector(l,-h.constant).divideScalar(g),o.every(p=>p.distanceToPoint(u)>=-m)&&r.push(u.clone()))}return r}function gs(n,t,e){if(!n.castShadow||!t.length)return;n.shadow.updateMatrices(n);const o=n.shadow.camera,r=o.matrixWorldInverse,a=new _e().setFromPoints(t.map(c=>c.clone().applyMatrix4(r))),s=a.getSize(new b),l=Math.max(s.length()*1e-6,Number.EPSILON),u=2+2*Math.SQRT2,m=Math.max(s.x,s.y,l)/Math.max(1,Math.min(n.shadow.mapSize.x,n.shadow.mapSize.y)-2*u),f=2*Math.SQRT2*m,i=u*m;a.min.x-=i,a.min.y-=i,a.max.x+=i,a.max.y+=i;for(const c of e){if(c.isEmpty())continue;const d=new _e().setFromPoints(aa(c).map(_=>_.applyMatrix4(r)));d.max.x<a.min.x||d.min.x>a.max.x||d.max.y<a.min.y||d.min.y>a.max.y||(a.min.z=Math.min(a.min.z,d.min.z),a.max.z=Math.max(a.max.z,d.max.z))}o.left=a.min.x,o.right=a.max.x,o.bottom=a.min.y,o.top=a.max.y,o.near=-a.max.z-f-l,o.far=-a.min.z+f+l,o.updateProjectionMatrix(),n.shadow.normalBias=f}const me=D().finite(),mo=W([me,me,me]),ra=I({min:W([D().int(),D().int(),D().int()]),max:W([D().int(),D().int(),D().int()]),density:V(me),voxelSize:me.positive(),color:mo,emission:mo,densityScale:me.nonnegative()}).strict();function vs(n){const t=n.max.map((f,i)=>f-n.min[i]+1);if(t.some(f=>f<=0)||t.reduce((f,i)=>f*i,1)!==n.density.length)throw new Error("Volume density dimensions do not match the evaluated grid");const e=new Ta(new Float32Array(n.density),t[0],t[1],t[2]);e.format=Pa,e.type=$o,e.minFilter=e.magFilter=re,e.unpackAlignment=1,e.needsUpdate=!0;const o=new b(...n.min).addScalar(-.5).multiplyScalar(n.voxelSize),r=new b(t[0],t[1],t[2]).multiplyScalar(n.voxelSize),a=new Ea(r.x,r.y,r.z),s=a.getAttribute("position");for(let f=0;f<s.count;f++)s.setXYZ(f,o.x+(s.getX(f)>0?r.x:0),o.y+(s.getY(f)>0?r.y:0),o.z+(s.getZ(f)>0?r.z:0));s.needsUpdate=!0,a.computeBoundingBox(),a.computeBoundingSphere();const l=new In({glslVersion:Ra,side:Na,transparent:!0,depthWrite:!1,premultipliedAlpha:!0,uniforms:{densityGrid:{value:e},minimum:{value:o},extent:{value:r},voxelSize:{value:n.voxelSize},densityScale:{value:n.densityScale},volumeColor:{value:new b(...n.color)},emission:{value:new b(...n.emission)},cameraLocal:{value:new b},rayLocal:{value:new b},orthographic:{value:!1},worldScale:{value:new Rn}},vertexShader:`
20
20
  out vec3 localPosition;
21
21
  void main() {
22
22
  localPosition = position;
@@ -58,7 +58,7 @@ import{a as To,b as So,L as Po}from"./LineSegments2-DN9pUfWA.js";import{bh as ut
58
58
  outputColor = vec4(radiance, 1.0 - transmission);
59
59
  #include <tonemapping_fragment>
60
60
  #include <colorspace_fragment>
61
- }`}),c=new kt(a,f),d=new q;return c.onBeforeRender=(l,i,u)=>{d.copy(c.matrixWorld).invert(),f.uniforms.cameraLocal.value.setFromMatrixPosition(u.matrixWorld).applyMatrix4(d),u.getWorldDirection(f.uniforms.rayLocal.value).transformDirection(d),f.uniforms.orthographic.value=!!u.isOrthographicCamera,f.uniforms.worldScale.value.setFromMatrix4(c.matrixWorld)},f.addEventListener("dispose",()=>e.dispose()),c}const ds=`#define constexpr const
61
+ }`}),u=new Ft(a,l),m=new G;return u.onBeforeRender=(f,i,c)=>{m.copy(u.matrixWorld).invert(),l.uniforms.cameraLocal.value.setFromMatrixPosition(c.matrixWorld).applyMatrix4(m),c.getWorldDirection(l.uniforms.rayLocal.value).transformDirection(m),l.uniforms.orthographic.value=!!c.isOrthographicCamera,l.uniforms.worldScale.value.setFromMatrix4(u.matrixWorld)},l.addEventListener("dispose",()=>e.dispose()),u}const xs=`#define constexpr const
62
62
  #define bool32_t bool
63
63
  #define bool2 bvec2
64
64
  #define bool3 bvec3
@@ -200,7 +200,7 @@ mat3x3 to_float3x3(mat3x4 m) { return mat3x3(m); }
200
200
  #define float4_from_float(v) float4(float3(v), 1.0f)
201
201
  #define gpu_dfdx(x) dFdx(x)
202
202
  #define gpu_dfdy(x) dFdy(x)
203
- #define gpu_fwidth(x) fwidth(x)`,An={"gpu_shader_common_math.glsl":{deps:["gpu_shader_math_constants_lib.glsl","gpu_shader_math_base_lib.glsl","gpu_shader_math_safe_lib.glsl"],code:`void math_add(float a, float b, float c, _ref(float ,result))
203
+ #define gpu_fwidth(x) fwidth(x)`,Tn={"gpu_shader_common_math.glsl":{deps:["gpu_shader_math_constants_lib.glsl","gpu_shader_math_base_lib.glsl","gpu_shader_math_safe_lib.glsl"],code:`void math_add(float a, float b, float c, _ref(float ,result))
204
204
  {
205
205
  result = a + b;
206
206
  }
@@ -6879,7 +6879,7 @@ void curves_float_mixed(float factor,
6879
6879
  curves_float(
6880
6880
  value, curve_map, layer, range_minimum, range_divider, start_slope, end_slope, result);
6881
6881
  result = mix(value, result, factor);
6882
- }`}},fo=I().finite(),sn=Q(["float","vec2","vec3","vec4"]),Ko=Gt([fo,j(fo)]),Qo=W([z(),I().int().nonnegative()]),Le=Gt([R({value:Ko}).strict(),R({link:Qo}).strict()]),ms=["ShaderNodeTexCoord","ShaderNodeUVMap","ShaderNodeValue","ShaderNodeRGB","ShaderNodeTexImage","ShaderNodeMapping","ShaderNodeMath","ShaderNodeVectorMath","ShaderNodeMix","ShaderNodeMixRGB","ShaderNodeValToRGB","ShaderNodeInvert","ShaderNodeSeparateXYZ","ShaderNodeCombineXYZ","ShaderNodeTexNoise","ShaderNodeTexVoronoi","ShaderNodeTexChecker","ShaderNodeTexWhiteNoise","ShaderNodeTexWave","ShaderNodeTexGradient","ShaderNodeTexMagic","ShaderNodeTexBrick","ShaderNodeMapRange","ShaderNodeClamp","ShaderNodeHueSaturation","ShaderNodeBrightContrast","ShaderNodeGamma","ShaderNodeRGBToBW","ShaderNodeSeparateColor","ShaderNodeCombineColor","ShaderNodeVectorRotate","ShaderNodeFresnel","ShaderNodeLayerWeight","ShaderNodeBump","ShaderNodeNormalMap","ShaderNodeNewGeometry","ShaderNodeVertexColor","ShaderNodeAttribute","ShaderNodeRGBCurve","ShaderNodeVectorCurve","ShaderNodeFloatCurve"],_s=R({type:Q(ms),props:Ot(z(),Lo()),inputs:j(Gt([R({value:Ko,id:z(),gpu:sn,enabled:et()}).strict(),R({link:Qo,id:z(),gpu:sn,enabled:et()}).strict()])),outputs:j(R({id:z(),gpu:sn.or(Z("closure")).nullable()}).strict())}).strict(),we=$o(()=>Gt([R({principled:Z(!0)}).strict(),R({emission:W([Le,Le])}).strict(),R({transparent:I()}).strict(),R({none:Z(!0)}).strict(),R({mix:W([Le,we,we])}).strict(),R({add:W([we,we])}).strict()])),hs=R({surface:Q(["ShaderNodeBsdfPrincipled","ShaderNodeEmission","closure"]),inputs:Ot(z(),Le),closure:we.optional(),nodes:Ot(z(),_s)}).strict();function ps(n){const t=n.inputs.Alpha,e=o=>"transparent"in o||"mix"in o&&(e(o.mix[1])||e(o.mix[2]))||"add"in o&&(e(o.add[0])||e(o.add[1]));return t!==void 0&&"link"in t||n.closure!==void 0&&e(n.closure)}const Jo="vec3(0.2126729, 0.7151522, 0.0721750)",gs=n=>n==="float"?1:Number(n[3]);function vs(n,t){const e=typeof t=="number"?[t]:t,o=gs(n);return Array.from({length:o},(r,a)=>e[a]??(a===3?1:0))}function xs(n,t,e){if(t===e)return n;const o=a=>a==="float"?"float":`float${a[3]}`,r=t==="vec4"&&e==="float"?`, ${Jo}`:"";return`${o(e)}_from_${o(t)}(${n}${r})`}const bs={INVERSE_SQRT:"math_inversesqrt",FRACT:"math_fraction",SMOOTH_MIN:"math_smoothmin",SMOOTH_MAX:"math_smoothmax"},ys={CROSS_PRODUCT:"vector_math_cross",DOT_PRODUCT:"vector_math_dot"},co={MIX:"blend",ADD:"add",MULTIPLY:"mult",SUBTRACT:"sub",SCREEN:"screen",DIVIDE:"div_fallback",DIFFERENCE:"diff",EXCLUSION:"exclusion",DARKEN:"dark",LIGHTEN:"light",OVERLAY:"overlay",DODGE:"dodge",BURN:"burn",HUE:"hue",SATURATION:"sat",VALUE:"val",COLOR:"color",SOFT_LIGHT:"soft",LINEAR_LIGHT:"linear"},ws={MULTIFRACTAL:"multi_fractal",FBM:"fbm",HYBRID_MULTIFRACTAL:"hybrid_multi_fractal",RIDGED_MULTIFRACTAL:"ridged_multi_fractal",HETERO_TERRAIN:"hetero_terrain"},Os={F1:"f1",F2:"f2",SMOOTH_F1:"smooth_f1",DISTANCE_TO_EDGE:"distance_to_edge",N_SPHERE_RADIUS:"n_sphere_radius"},As={EUCLIDEAN:0,MANHATTAN:1,CHEBYCHEV:2,MINKOWSKI:3},Ms=(()=>{const n=new Map;for(const[t,e]of Object.entries(An))for(const o of e.code.matchAll(/^(?:void|float\d?)\s+([A-Za-z_]\w*)\s*\(/gm))n.has(o[1])||n.set(o[1],t);return n})();function V(n,t){if(!(t in n.props))throw new Error(`${n.type} arrived without its '${t}' property`);return n.props[t]}const Ts=`
6882
+ }`}},_o=D().finite(),fn=J(["float","vec2","vec3","vec4"]),sa=Kt([_o,V(_o)]),ia=W([z(),D().int().nonnegative()]),Ue=Kt([I({value:sa}).strict(),I({link:ia}).strict()]),bs=["ShaderNodeTexCoord","ShaderNodeUVMap","ShaderNodeValue","ShaderNodeRGB","ShaderNodeTexImage","ShaderNodeMapping","ShaderNodeMath","ShaderNodeVectorMath","ShaderNodeMix","ShaderNodeMixRGB","ShaderNodeValToRGB","ShaderNodeInvert","ShaderNodeSeparateXYZ","ShaderNodeCombineXYZ","ShaderNodeTexNoise","ShaderNodeTexVoronoi","ShaderNodeTexChecker","ShaderNodeTexWhiteNoise","ShaderNodeTexWave","ShaderNodeTexGradient","ShaderNodeTexMagic","ShaderNodeTexBrick","ShaderNodeMapRange","ShaderNodeClamp","ShaderNodeHueSaturation","ShaderNodeBrightContrast","ShaderNodeGamma","ShaderNodeRGBToBW","ShaderNodeSeparateColor","ShaderNodeCombineColor","ShaderNodeVectorRotate","ShaderNodeFresnel","ShaderNodeLayerWeight","ShaderNodeBump","ShaderNodeNormalMap","ShaderNodeNewGeometry","ShaderNodeVertexColor","ShaderNodeAttribute","ShaderNodeRGBCurve","ShaderNodeVectorCurve","ShaderNodeFloatCurve"],ys=I({type:J(bs),props:At(z(),Xo()),inputs:V(Kt([I({value:sa,id:z(),gpu:fn,enabled:et()}).strict(),I({link:ia,id:z(),gpu:fn,enabled:et()}).strict()])),outputs:V(I({id:z(),gpu:fn.or(K("closure")).nullable()}).strict())}).strict(),Ae=Go(()=>Kt([I({principled:K(!0)}).strict(),I({emission:W([Ue,Ue])}).strict(),I({transparent:D()}).strict(),I({none:K(!0)}).strict(),I({mix:W([Ue,Ae,Ae])}).strict(),I({add:W([Ae,Ae])}).strict()])),ws=I({surface:J(["ShaderNodeBsdfPrincipled","ShaderNodeEmission","closure"]),inputs:At(z(),Ue),closure:Ae.optional(),nodes:At(z(),ys)}).strict();function Os(n){const t=n.inputs.Alpha,e=o=>"transparent"in o||"mix"in o&&(e(o.mix[1])||e(o.mix[2]))||"add"in o&&(e(o.add[0])||e(o.add[1]));return t!==void 0&&"link"in t||n.closure!==void 0&&e(n.closure)}const la="vec3(0.2126729, 0.7151522, 0.0721750)",As=n=>n==="float"?1:Number(n[3]);function Ms(n,t){const e=typeof t=="number"?[t]:t,o=As(n);return Array.from({length:o},(r,a)=>e[a]??(a===3?1:0))}function Ss(n,t,e){if(t===e)return n;const o=a=>a==="float"?"float":`float${a[3]}`,r=t==="vec4"&&e==="float"?`, ${la}`:"";return`${o(e)}_from_${o(t)}(${n}${r})`}const Ts={INVERSE_SQRT:"math_inversesqrt",FRACT:"math_fraction",SMOOTH_MIN:"math_smoothmin",SMOOTH_MAX:"math_smoothmax"},Ps={CROSS_PRODUCT:"vector_math_cross",DOT_PRODUCT:"vector_math_dot"},ho={MIX:"blend",ADD:"add",MULTIPLY:"mult",SUBTRACT:"sub",SCREEN:"screen",DIVIDE:"div_fallback",DIFFERENCE:"diff",EXCLUSION:"exclusion",DARKEN:"dark",LIGHTEN:"light",OVERLAY:"overlay",DODGE:"dodge",BURN:"burn",HUE:"hue",SATURATION:"sat",VALUE:"val",COLOR:"color",SOFT_LIGHT:"soft",LINEAR_LIGHT:"linear"},Es={MULTIFRACTAL:"multi_fractal",FBM:"fbm",HYBRID_MULTIFRACTAL:"hybrid_multi_fractal",RIDGED_MULTIFRACTAL:"ridged_multi_fractal",HETERO_TERRAIN:"hetero_terrain"},Ns={F1:"f1",F2:"f2",SMOOTH_F1:"smooth_f1",DISTANCE_TO_EDGE:"distance_to_edge",N_SPHERE_RADIUS:"n_sphere_radius"},Rs={EUCLIDEAN:0,MANHATTAN:1,CHEBYCHEV:2,MINKOWSKI:3},Is=(()=>{const n=new Map;for(const[t,e]of Object.entries(Tn))for(const o of e.code.matchAll(/^(?:void|float\d?)\s+([A-Za-z_]\w*)\s*\(/gm))n.has(o[1])||n.set(o[1],t);return n})();function B(n,t){if(!(t in n.props))throw new Error(`${n.type} arrived without its '${t}' property`);return n.props[t]}const Ds=`
6883
6883
  #define GPU_FRAGMENT_SHADER
6884
6884
  #define FrontFacing gl_FrontFacing
6885
6885
  #ifndef USE_TRANSMISSION
@@ -6936,7 +6936,7 @@ void blender_init_globals() {
6936
6936
  g_data.curve_T = vec3(0.0);
6937
6937
  g_data.barycentric_coords = vec2(0.0);
6938
6938
  }
6939
- `,Ss=`
6939
+ `,Cs=`
6940
6940
  uniform vec2 blenderViewport;
6941
6941
  vec3 blender_orco() {
6942
6942
  // attr_load_orco: the orco attribute (\`orcoAttribute\`), interpolated.
@@ -7019,33 +7019,37 @@ vec3 blender_reflection() {
7019
7019
  : normalize(cameraPosition - vBlenderWorldPosition);
7020
7020
  return blender_from_three * -reflect(incident, normalize(vBlenderWorldNormal));
7021
7021
  }
7022
- `;class Fn{constructor(t,e,o=!1,r="bgN"){this.graph=t,this.derivative=o,this.prefix=r,this.lines=[],this.emitted=new Map,this.s=e??{files:new Set,uniforms:new Map,uniformTypes:new Map,images:[],ramps:[],uvs:new Set,attributes:new Set,structure:[],functions:[]}}get uniforms(){return this.s.uniforms}get images(){return this.s.images}get ramps(){return this.s.ramps}d(t){return this.derivative?`(${t} + dF_impl(${t}))`:t}uniform(t,e){const o=`bgU${this.s.uniforms.size}`,r=vs(t,e);return this.s.uniforms.set(o,t==="float"?r[0]:r),this.s.uniformTypes.set(o,t),o}use(t){const e=Ms.get(t);if(!e)throw new Error(`Blender's node library has no ${t}`);return this.s.files.add(e),t}source(t,e){if("value"in t)return this.s.structure.push("v"),this.uniform(e,t.value);const[o,r]=t.link,a=this.graph.nodes[o];if(!a)throw new Error(`The graph links to ${o}, which it does not carry`);const f=this.node(o,a)[r];if(!f)throw new Error(`${o} has no output ${r}`);return this.s.structure.push(["l",o,r]),xs(f.name,f.type,e)}input(t,e,o){const r=t.inputs.find(a=>a.id===e)??t.inputs.find(a=>a.id.replace(/_/g," ")===e);if(!r)throw new Error(`${t.type} arrived without its '${e}' input`);return this.source(r,o??r.gpu)}coordinate(t,e){const o=t.inputs[0];return"link"in o?this.source(o,"vec3"):(this.s.structure.push(["default",e]),e==="orco"?this.d("blender_orco()"):(this.s.uvs.add(""),this.d(`vec3(${ce("")}, 0.0)`)))}node(t,e){const o=this.emitted.get(t);if(o)return o;const r=`${this.prefix}${this.emitted.size}`,a=e.outputs.map((i,u)=>({name:`${r}_${u}`,type:i.gpu==="closure"||i.gpu===null?"float":i.gpu}));this.emitted.set(t,a);const s=i=>`${a[i].type} ${a[i].name} = ${a[i].type}(0.0);`,f=a.map((i,u)=>s(u)).join(" "),c=i=>i.map(u=>a[u].name).join(", "),d=(i=[])=>[...e.inputs.map(m=>this.source(m,m.gpu)),...i,...a.map(m=>m.name)].join(", ");this.s.structure.push(["n",e.type,e.props.operation,e.props.blend_type,e.props.data_type,e.props.factor_mode,e.props.clamp_factor,e.props.clamp_result,e.props.use_clamp,e.props.noise_dimensions,e.props.noise_type,e.props.voronoi_dimensions,e.props.feature,e.props.distance,e.props.vector_type,e.props.uv_map,e.props.extension,e.props.interpolation,e.props.image_alpha_mode,e.props.image_is_data,e.props.color_ramp?.elements?.length,e.props.color_ramp?.interpolation]);const l=[f];switch(e.type){case"ShaderNodeValue":case"ShaderNodeRGB":{const i=a[0].type;l.push(`${a[0].name} = ${this.uniform(i,V(e,"value"))};`);break}case"ShaderNodeTexCoord":{this.s.uvs.add(""),["blender_orco()","blender_object_normal()",`vec3(${ce("")}, 0.0)`,"vBlenderObjectPosition","blender_camera()","blender_window()","blender_reflection()"].forEach((u,m)=>{a[m]&&l.push(`${a[m].name} = ${this.d(u)};`)});break}case"ShaderNodeVertexColor":case"ShaderNodeAttribute":{const i=V(e,e.type==="ShaderNodeAttribute"?"attribute_name":"layer_name");this.s.attributes.add(i),this.s.structure.push(["a",i]);const u=e.type==="ShaderNodeAttribute"?"node_attribute":"node_vertex_color";l.push(`${this.use(u)}(${Mn(i)}, ${c(a.map((m,h)=>h))});`);for(const m of a)l.push(`${m.name} = ${this.d(m.name)};`);break}case"ShaderNodeUVMap":{const i=V(e,"uv_map");this.s.uvs.add(i),l.push(`${a[0].name} = ${this.d(`vec3(${ce(i)}, 0.0)`)};`);break}case"ShaderNodeMath":{const i=V(e,"operation"),u=this.use(bs[i]??`math_${i.toLowerCase()}`);l.push(`${u}(${d()});`),V(e,"use_clamp")&&l.push(`${this.use("clamp_value")}(${c([0])}, 0.0, 1.0, ${c([0])});`);break}case"ShaderNodeVectorMath":{const i=V(e,"operation");l.push(`${this.use(ys[i]??`vector_math_${i.toLowerCase()}`)}(${d()});`);break}case"ShaderNodeMapping":l.push(`${this.use(`mapping_${V(e,"vector_type").toLowerCase()}`)}(${d()});`);break;case"ShaderNodeInvert":l.push(`${this.use("invert")}(${d()});`);break;case"ShaderNodeSeparateXYZ":l.push(`${this.use("separate_xyz")}(${d()});`);break;case"ShaderNodeCombineXYZ":l.push(`${this.use("combine_xyz")}(${d()});`);break;case"ShaderNodeMix":{const i=V(e,"data_type"),u=V(e,"factor_mode")==="NON_UNIFORM",m={FLOAT:"Float",VECTOR:"Vector",RGBA:"Color",ROTATION:"Rotation"}[i];if(!m)throw new Error(`Mix has data type ${i}`);const h=i==="VECTOR"&&u;let _=this.input(e,h?"Factor_Vector":"Factor_Float");if(V(e,"clamp_factor")){const v=`${r}_fac`;l.push(h?`vec3 ${v}; ${this.use("node_mix_clamp_vector")}(${_}, vec3(0.0), vec3(1.0), ${v});`:`float ${v}; ${this.use("node_mix_clamp_value")}(${_}, 0.0, 1.0, ${v});`),_=v}const p=i==="FLOAT"?"node_mix_float":i==="VECTOR"?u?"node_mix_vector_non_uniform":"node_mix_vector":i==="RGBA"?`node_mix_${co[V(e,"blend_type")]}`:"node_mix_rotation",g=e.outputs.findIndex(v=>v.id===`Result_${m}`);l.push(`${this.use(p)}(${_}, ${this.input(e,`A_${m}`)}, ${this.input(e,`B_${m}`)}, ${c([g])});`),i==="RGBA"&&V(e,"clamp_result")&&l.push(`${this.use("node_mix_clamp_color")}(${c([g])}, vec4(0.0), vec4(1.0), ${c([g])});`);break}case"ShaderNodeMixRGB":{const i=`${r}_fac`;l.push(`float ${i}; ${this.use("clamp_value")}(${this.input(e,"Fac")}, 0.0, 1.0, ${i});`);const u=e.inputs.slice(1).map(m=>this.source(m,m.gpu));l.push(`${this.use(`mix_${co[V(e,"blend_type")]}`)}(${[i,...u,c([0])].join(", ")});`),V(e,"use_clamp")&&l.push(`${this.use("clamp_color")}(${c([0])}, vec4(0.0), vec4(1.0), ${c([0])});`);break}case"ShaderNodeValToRGB":{const i=V(e,"color_ramp"),u=this.input(e,"Fac"),[m,h]=i.elements,_=p=>this.uniform("vec4",p.slice(1,5));if(i.elements.length===1)l.push(`${c([0])} = ${_(m)}; ${c([1])} = ${c([0])}.a;`);else if(i.elements.length===2&&i.color_mode==="RGB"&&h&&i.interpolation!=="B_SPLINE"&&i.interpolation!=="CARDINAL")if(i.interpolation==="CONSTANT")l.push(`${this.use("valtorgb_opti_constant")}(${u}, ${this.uniform("float",Math.max(m[0],h[0]))}, ${_(m)}, ${_(h)}, ${c([0,1])});`);else{const p=1/(h[0]-m[0]),g=i.interpolation==="EASE"?"valtorgb_opti_ease":"valtorgb_opti_linear";l.push(`${this.use(g)}(${u}, ${this.uniform("vec2",[p,-p*m[0]])}, ${_(m)}, ${_(h)}, ${c([0,1])});`)}else{const p=`bgRamp${this.s.ramps.length}`;this.s.ramps.push({uniform:p,table:i.table}),this.s.structure.push(["ramp",i.interpolation==="CONSTANT"]),l.push(i.interpolation==="CONSTANT"?`${c([0])} = texelFetch(${p}, ivec2(int(clamp(${u}, 0.0, 1.0) * 256.0), 0), 0);`:`${c([0])} = texture(${p}, vec2(clamp(${u}, 0.0, 1.0) * (256.0 / 257.0) + 0.5 / 257.0, 0.5));`),l.push(`${c([1])} = ${c([0])}.a;`)}break}case"ShaderNodeRGBCurve":case"ShaderNodeVectorCurve":case"ShaderNodeFloatCurve":{const i=V(e,"curve_mapping"),u=`bgRamp${this.s.ramps.length}`;this.s.ramps.push({uniform:u,table:i.table}),this.s.structure.push(["curve"]);const m=this.input(e,e.inputs.some(h=>h.id==="Factor")?"Factor":"Fac","float");e.type==="ShaderNodeRGBCurve"?l.push(`${this.use("curves_combined_rgb")}(${m}, ${this.input(e,"Color","vec4")}, vec4(0.0, 0.0, 0.0, 1.0), vec4(1.0), ${u}, 0.5, ${this.uniform("vec4",i.minimums)}, ${this.uniform("vec4",i.dividers)}, ${this.uniform("vec4",i.starts)}, ${this.uniform("vec4",i.ends)}, ${c([0])});`):e.type==="ShaderNodeVectorCurve"?l.push(`${this.use("curves_vector_mixed")}(${m}, ${this.input(e,"Vector","vec3")}, ${u}, 0.5, ${this.uniform("vec3",i.minimums.slice(0,3))}, ${this.uniform("vec3",i.dividers.slice(0,3))}, ${this.uniform("vec3",i.starts.slice(0,3))}, ${this.uniform("vec3",i.ends.slice(0,3))}, ${c([0])});`):l.push(`${this.use("curves_float_mixed")}(${m}, ${this.input(e,"Value","float")}, ${u}, 0.5, ${this.uniform("float",i.minimums[0])}, ${this.uniform("float",i.dividers[0])}, ${this.uniform("float",i.starts[0])}, ${this.uniform("float",i.ends[0])}, ${c([0])});`);break}case"ShaderNodeTexNoise":{const i=Number(V(e,"noise_dimensions")[0]),u=this.use(`node_noise_tex_${ws[V(e,"noise_type")]}_${i}d`),m=this.coordinate(e,"orco"),h=e.inputs.slice(1).map(p=>this.source(p,p.gpu)),_=V(e,"normalize")?"1.0":"0.0";l.push(`${u}(${[m,...h,_,"1.0",c(a.map((p,g)=>g))].join(", ")});`);break}case"ShaderNodeTexVoronoi":{const i=Number(V(e,"voronoi_dimensions")[0]),u=this.use(`node_tex_voronoi_${Os[V(e,"feature")]}_${i}d`),m=this.coordinate(e,"orco"),h=e.inputs.slice(1).map(g=>this.source(g,g.gpu)),_=`${As[V(e,"distance")].toFixed(1)}`,p=V(e,"normalize")?"1.0":"0.0";l.push(`${u}(${[m,...h,_,p,c(a.map((g,v)=>v))].join(", ")});`);break}case"ShaderNodeTexChecker":{const i=this.coordinate(e,"orco"),u=e.inputs.slice(1).map(m=>this.source(m,m.gpu));l.push(`${this.use("node_tex_checker")}(${[i,...u,c(a.map((m,h)=>h))].join(", ")});`);break}case"ShaderNodeTexWhiteNoise":{const i=Number(V(e,"noise_dimensions")[0]);l.push(`${this.use(`node_white_noise_${i}d`)}(${d()});`);break}case"ShaderNodeTexWave":case"ShaderNodeTexGradient":case"ShaderNodeTexMagic":case"ShaderNodeTexBrick":{const i=this.coordinate(e,"orco"),u=e.inputs.slice(1).map(p=>this.source(p,p.gpu)),m=p=>V(e,`${p}#value`).toFixed(1),h=e.type==="ShaderNodeTexWave"?[m("wave_type"),m("bands_direction"),m("rings_direction"),m("wave_profile")]:e.type==="ShaderNodeTexGradient"?[m("gradient_type")]:e.type==="ShaderNodeTexMagic"?[V(e,"turbulence_depth").toFixed(1)]:[this.uniform("float",V(e,"offset")),V(e,"offset_frequency").toFixed(1),this.uniform("float",V(e,"squash")),V(e,"squash_frequency").toFixed(1)],_={ShaderNodeTexWave:"node_tex_wave",ShaderNodeTexGradient:"node_tex_gradient",ShaderNodeTexMagic:"node_tex_magic",ShaderNodeTexBrick:"node_tex_brick"}[e.type];l.push(`${this.use(_)}(${[i,...u,...h,c(a.map((p,g)=>g))].join(", ")});`);break}case"ShaderNodeMapRange":{const i=V(e,"data_type")==="FLOAT_VECTOR",u=V(e,"interpolation_type").toLowerCase(),m=V(e,"clamp");l.push(`${this.use(`${i?"vector_":""}map_range_${u}`)}(${d([m?"1.0":"0.0"])});`),m&&!i&&(u==="linear"||u==="stepped")&&l.push(`${this.use("clamp_range")}(${c([0])}, ${this.input(e,"To Min","float")}, ${this.input(e,"To Max","float")}, ${c([0])});`);break}case"ShaderNodeClamp":l.push(`${this.use(V(e,"clamp_type")==="MINMAX"?"clamp_minmax":"clamp_range")}(${d()});`);break;case"ShaderNodeHueSaturation":l.push(`${this.use("hue_sat")}(${d()});`);break;case"ShaderNodeBrightContrast":l.push(`${this.use("brightness_contrast")}(${d()});`);break;case"ShaderNodeGamma":l.push(`${this.use("node_gamma")}(${d()});`);break;case"ShaderNodeRGBToBW":l.push(`${this.use("rgbtobw")}(${d([Jo])});`);break;case"ShaderNodeSeparateColor":l.push(`${this.use(`separate_color_${V(e,"mode").toLowerCase()}`)}(${d()});`);break;case"ShaderNodeCombineColor":l.push(`${this.use(`combine_color_${V(e,"mode").toLowerCase()}`)}(${d()});`);break;case"ShaderNodeVectorRotate":{const i={AXIS_ANGLE:"axis_angle",X_AXIS:"axis_x",Y_AXIS:"axis_y",Z_AXIS:"axis_z",EULER_XYZ:"euler_xyz"}[V(e,"rotation_type")];l.push(`${this.use(`node_vector_rotate_${i}`)}(${d([V(e,"invert")?"-1.0":"1.0"])});`);break}case"ShaderNodeFresnel":case"ShaderNodeLayerWeight":{const i=e.inputs[1],u="link"in i?this.source(i,"vec3"):"g_data.N";"link"in i||this.s.structure.push("world-normal");const m=this.source(e.inputs[0],"float"),h=e.type==="ShaderNodeFresnel"?"node_fresnel":"node_layer_weight";l.push(`${this.use(h)}(${[m,u,c(a.map((_,p)=>p))].join(", ")});`);break}case"ShaderNodeBump":{const i=e.inputs.find(w=>w.id==="Height"),u=e.inputs.find(w=>w.id==="Normal"),m=u&&"link"in u?this.source(u,"vec3"):"g_data.N";if(!i||!("link"in i)){l.push(`${c([0])} = ${m};`);break}const h=`bgHeight${this.s.functions.length}`;this.s.functions.push("");const _=new Fn(this.graph,this.s,!0,`${h}_`),p=_.source(i,"float");this.s.functions[Number(h.slice(8))]=`float ${h}() {
7023
- ${_.lines.join(`
7022
+ `;class jn{constructor(t,e,o=!1,r="bgN"){this.graph=t,this.derivative=o,this.prefix=r,this.lines=[],this.emitted=new Map,this.s=e??{files:new Set,uniforms:new Map,uniformTypes:new Map,images:[],ramps:[],uvs:new Set,attributes:new Set,structure:[],functions:[]}}get uniforms(){return this.s.uniforms}get images(){return this.s.images}get ramps(){return this.s.ramps}d(t){return this.derivative?`(${t} + dF_impl(${t}))`:t}uniform(t,e){const o=`bgU${this.s.uniforms.size}`,r=Ms(t,e);return this.s.uniforms.set(o,t==="float"?r[0]:r),this.s.uniformTypes.set(o,t),o}use(t){const e=Is.get(t);if(!e)throw new Error(`Blender's node library has no ${t}`);return this.s.files.add(e),t}source(t,e){if("value"in t)return this.s.structure.push("v"),this.uniform(e,t.value);const[o,r]=t.link,a=this.graph.nodes[o];if(!a)throw new Error(`The graph links to ${o}, which it does not carry`);const l=this.node(o,a)[r];if(!l)throw new Error(`${o} has no output ${r}`);return this.s.structure.push(["l",o,r]),Ss(l.name,l.type,e)}input(t,e,o){const r=t.inputs.find(a=>a.id===e)??t.inputs.find(a=>a.id.replace(/_/g," ")===e);if(!r)throw new Error(`${t.type} arrived without its '${e}' input`);return this.source(r,o??r.gpu)}coordinate(t,e){const o=t.inputs[0];return"link"in o?this.source(o,"vec3"):(this.s.structure.push(["default",e]),e==="orco"?this.d("blender_orco()"):(this.s.uvs.add(""),this.d(`vec3(${ce("")}, 0.0)`)))}node(t,e){const o=this.emitted.get(t);if(o)return o;const r=`${this.prefix}${this.emitted.size}`,a=e.outputs.map((i,c)=>({name:`${r}_${c}`,type:i.gpu==="closure"||i.gpu===null?"float":i.gpu}));this.emitted.set(t,a);const s=i=>`${a[i].type} ${a[i].name} = ${a[i].type}(0.0);`,l=a.map((i,c)=>s(c)).join(" "),u=i=>i.map(c=>a[c].name).join(", "),m=(i=[])=>[...e.inputs.map(d=>this.source(d,d.gpu)),...i,...a.map(d=>d.name)].join(", ");this.s.structure.push(["n",e.type,e.props.operation,e.props.blend_type,e.props.data_type,e.props.factor_mode,e.props.clamp_factor,e.props.clamp_result,e.props.use_clamp,e.props.noise_dimensions,e.props.noise_type,e.props.voronoi_dimensions,e.props.feature,e.props.distance,e.props.vector_type,e.props.uv_map,e.props.extension,e.props.interpolation,e.props.image_alpha_mode,e.props.image_is_data,e.props.color_ramp?.elements?.length,e.props.color_ramp?.interpolation]);const f=[l];switch(e.type){case"ShaderNodeValue":case"ShaderNodeRGB":{const i=a[0].type;f.push(`${a[0].name} = ${this.uniform(i,B(e,"value"))};`);break}case"ShaderNodeTexCoord":{this.s.uvs.add(""),["blender_orco()","blender_object_normal()",`vec3(${ce("")}, 0.0)`,"vBlenderObjectPosition","blender_camera()","blender_window()","blender_reflection()"].forEach((c,d)=>{a[d]&&f.push(`${a[d].name} = ${this.d(c)};`)});break}case"ShaderNodeVertexColor":case"ShaderNodeAttribute":{const i=B(e,e.type==="ShaderNodeAttribute"?"attribute_name":"layer_name");this.s.attributes.add(i),this.s.structure.push(["a",i]);const c=e.type==="ShaderNodeAttribute"?"node_attribute":"node_vertex_color";f.push(`${this.use(c)}(${Pn(i)}, ${u(a.map((d,_)=>_))});`);for(const d of a)f.push(`${d.name} = ${this.d(d.name)};`);break}case"ShaderNodeUVMap":{const i=B(e,"uv_map");this.s.uvs.add(i),f.push(`${a[0].name} = ${this.d(`vec3(${ce(i)}, 0.0)`)};`);break}case"ShaderNodeMath":{const i=B(e,"operation"),c=this.use(Ts[i]??`math_${i.toLowerCase()}`);f.push(`${c}(${m()});`),B(e,"use_clamp")&&f.push(`${this.use("clamp_value")}(${u([0])}, 0.0, 1.0, ${u([0])});`);break}case"ShaderNodeVectorMath":{const i=B(e,"operation");f.push(`${this.use(Ps[i]??`vector_math_${i.toLowerCase()}`)}(${m()});`);break}case"ShaderNodeMapping":f.push(`${this.use(`mapping_${B(e,"vector_type").toLowerCase()}`)}(${m()});`);break;case"ShaderNodeInvert":f.push(`${this.use("invert")}(${m()});`);break;case"ShaderNodeSeparateXYZ":f.push(`${this.use("separate_xyz")}(${m()});`);break;case"ShaderNodeCombineXYZ":f.push(`${this.use("combine_xyz")}(${m()});`);break;case"ShaderNodeMix":{const i=B(e,"data_type"),c=B(e,"factor_mode")==="NON_UNIFORM",d={FLOAT:"Float",VECTOR:"Vector",RGBA:"Color",ROTATION:"Rotation"}[i];if(!d)throw new Error(`Mix has data type ${i}`);const _=i==="VECTOR"&&c;let h=this.input(e,_?"Factor_Vector":"Factor_Float");if(B(e,"clamp_factor")){const v=`${r}_fac`;f.push(_?`vec3 ${v}; ${this.use("node_mix_clamp_vector")}(${h}, vec3(0.0), vec3(1.0), ${v});`:`float ${v}; ${this.use("node_mix_clamp_value")}(${h}, 0.0, 1.0, ${v});`),h=v}const g=i==="FLOAT"?"node_mix_float":i==="VECTOR"?c?"node_mix_vector_non_uniform":"node_mix_vector":i==="RGBA"?`node_mix_${ho[B(e,"blend_type")]}`:"node_mix_rotation",p=e.outputs.findIndex(v=>v.id===`Result_${d}`);f.push(`${this.use(g)}(${h}, ${this.input(e,`A_${d}`)}, ${this.input(e,`B_${d}`)}, ${u([p])});`),i==="RGBA"&&B(e,"clamp_result")&&f.push(`${this.use("node_mix_clamp_color")}(${u([p])}, vec4(0.0), vec4(1.0), ${u([p])});`);break}case"ShaderNodeMixRGB":{const i=`${r}_fac`;f.push(`float ${i}; ${this.use("clamp_value")}(${this.input(e,"Fac")}, 0.0, 1.0, ${i});`);const c=e.inputs.slice(1).map(d=>this.source(d,d.gpu));f.push(`${this.use(`mix_${ho[B(e,"blend_type")]}`)}(${[i,...c,u([0])].join(", ")});`),B(e,"use_clamp")&&f.push(`${this.use("clamp_color")}(${u([0])}, vec4(0.0), vec4(1.0), ${u([0])});`);break}case"ShaderNodeValToRGB":{const i=B(e,"color_ramp"),c=this.input(e,"Fac"),[d,_]=i.elements,h=g=>this.uniform("vec4",g.slice(1,5));if(i.elements.length===1)f.push(`${u([0])} = ${h(d)}; ${u([1])} = ${u([0])}.a;`);else if(i.elements.length===2&&i.color_mode==="RGB"&&_&&i.interpolation!=="B_SPLINE"&&i.interpolation!=="CARDINAL")if(i.interpolation==="CONSTANT")f.push(`${this.use("valtorgb_opti_constant")}(${c}, ${this.uniform("float",Math.max(d[0],_[0]))}, ${h(d)}, ${h(_)}, ${u([0,1])});`);else{const g=1/(_[0]-d[0]),p=i.interpolation==="EASE"?"valtorgb_opti_ease":"valtorgb_opti_linear";f.push(`${this.use(p)}(${c}, ${this.uniform("vec2",[g,-g*d[0]])}, ${h(d)}, ${h(_)}, ${u([0,1])});`)}else{const g=`bgRamp${this.s.ramps.length}`;this.s.ramps.push({uniform:g,table:i.table}),this.s.structure.push(["ramp",i.interpolation==="CONSTANT"]),f.push(i.interpolation==="CONSTANT"?`${u([0])} = texelFetch(${g}, ivec2(int(clamp(${c}, 0.0, 1.0) * 256.0), 0), 0);`:`${u([0])} = texture(${g}, vec2(clamp(${c}, 0.0, 1.0) * (256.0 / 257.0) + 0.5 / 257.0, 0.5));`),f.push(`${u([1])} = ${u([0])}.a;`)}break}case"ShaderNodeRGBCurve":case"ShaderNodeVectorCurve":case"ShaderNodeFloatCurve":{const i=B(e,"curve_mapping"),c=`bgRamp${this.s.ramps.length}`;this.s.ramps.push({uniform:c,table:i.table}),this.s.structure.push(["curve"]);const d=this.input(e,e.inputs.some(_=>_.id==="Factor")?"Factor":"Fac","float");e.type==="ShaderNodeRGBCurve"?f.push(`${this.use("curves_combined_rgb")}(${d}, ${this.input(e,"Color","vec4")}, vec4(0.0, 0.0, 0.0, 1.0), vec4(1.0), ${c}, 0.5, ${this.uniform("vec4",i.minimums)}, ${this.uniform("vec4",i.dividers)}, ${this.uniform("vec4",i.starts)}, ${this.uniform("vec4",i.ends)}, ${u([0])});`):e.type==="ShaderNodeVectorCurve"?f.push(`${this.use("curves_vector_mixed")}(${d}, ${this.input(e,"Vector","vec3")}, ${c}, 0.5, ${this.uniform("vec3",i.minimums.slice(0,3))}, ${this.uniform("vec3",i.dividers.slice(0,3))}, ${this.uniform("vec3",i.starts.slice(0,3))}, ${this.uniform("vec3",i.ends.slice(0,3))}, ${u([0])});`):f.push(`${this.use("curves_float_mixed")}(${d}, ${this.input(e,"Value","float")}, ${c}, 0.5, ${this.uniform("float",i.minimums[0])}, ${this.uniform("float",i.dividers[0])}, ${this.uniform("float",i.starts[0])}, ${this.uniform("float",i.ends[0])}, ${u([0])});`);break}case"ShaderNodeTexNoise":{const i=Number(B(e,"noise_dimensions")[0]),c=this.use(`node_noise_tex_${Es[B(e,"noise_type")]}_${i}d`),d=this.coordinate(e,"orco"),_=e.inputs.slice(1).map(g=>this.source(g,g.gpu)),h=B(e,"normalize")?"1.0":"0.0";f.push(`${c}(${[d,..._,h,"1.0",u(a.map((g,p)=>p))].join(", ")});`);break}case"ShaderNodeTexVoronoi":{const i=Number(B(e,"voronoi_dimensions")[0]),c=this.use(`node_tex_voronoi_${Ns[B(e,"feature")]}_${i}d`),d=this.coordinate(e,"orco"),_=e.inputs.slice(1).map(p=>this.source(p,p.gpu)),h=`${Rs[B(e,"distance")].toFixed(1)}`,g=B(e,"normalize")?"1.0":"0.0";f.push(`${c}(${[d,..._,h,g,u(a.map((p,v)=>v))].join(", ")});`);break}case"ShaderNodeTexChecker":{const i=this.coordinate(e,"orco"),c=e.inputs.slice(1).map(d=>this.source(d,d.gpu));f.push(`${this.use("node_tex_checker")}(${[i,...c,u(a.map((d,_)=>_))].join(", ")});`);break}case"ShaderNodeTexWhiteNoise":{const i=Number(B(e,"noise_dimensions")[0]);f.push(`${this.use(`node_white_noise_${i}d`)}(${m()});`);break}case"ShaderNodeTexWave":case"ShaderNodeTexGradient":case"ShaderNodeTexMagic":case"ShaderNodeTexBrick":{const i=this.coordinate(e,"orco"),c=e.inputs.slice(1).map(g=>this.source(g,g.gpu)),d=g=>B(e,`${g}#value`).toFixed(1),_=e.type==="ShaderNodeTexWave"?[d("wave_type"),d("bands_direction"),d("rings_direction"),d("wave_profile")]:e.type==="ShaderNodeTexGradient"?[d("gradient_type")]:e.type==="ShaderNodeTexMagic"?[B(e,"turbulence_depth").toFixed(1)]:[this.uniform("float",B(e,"offset")),B(e,"offset_frequency").toFixed(1),this.uniform("float",B(e,"squash")),B(e,"squash_frequency").toFixed(1)],h={ShaderNodeTexWave:"node_tex_wave",ShaderNodeTexGradient:"node_tex_gradient",ShaderNodeTexMagic:"node_tex_magic",ShaderNodeTexBrick:"node_tex_brick"}[e.type];f.push(`${this.use(h)}(${[i,...c,..._,u(a.map((g,p)=>p))].join(", ")});`);break}case"ShaderNodeMapRange":{const i=B(e,"data_type")==="FLOAT_VECTOR",c=B(e,"interpolation_type").toLowerCase(),d=B(e,"clamp");f.push(`${this.use(`${i?"vector_":""}map_range_${c}`)}(${m([d?"1.0":"0.0"])});`),d&&!i&&(c==="linear"||c==="stepped")&&f.push(`${this.use("clamp_range")}(${u([0])}, ${this.input(e,"To Min","float")}, ${this.input(e,"To Max","float")}, ${u([0])});`);break}case"ShaderNodeClamp":f.push(`${this.use(B(e,"clamp_type")==="MINMAX"?"clamp_minmax":"clamp_range")}(${m()});`);break;case"ShaderNodeHueSaturation":f.push(`${this.use("hue_sat")}(${m()});`);break;case"ShaderNodeBrightContrast":f.push(`${this.use("brightness_contrast")}(${m()});`);break;case"ShaderNodeGamma":f.push(`${this.use("node_gamma")}(${m()});`);break;case"ShaderNodeRGBToBW":f.push(`${this.use("rgbtobw")}(${m([la])});`);break;case"ShaderNodeSeparateColor":f.push(`${this.use(`separate_color_${B(e,"mode").toLowerCase()}`)}(${m()});`);break;case"ShaderNodeCombineColor":f.push(`${this.use(`combine_color_${B(e,"mode").toLowerCase()}`)}(${m()});`);break;case"ShaderNodeVectorRotate":{const i={AXIS_ANGLE:"axis_angle",X_AXIS:"axis_x",Y_AXIS:"axis_y",Z_AXIS:"axis_z",EULER_XYZ:"euler_xyz"}[B(e,"rotation_type")];f.push(`${this.use(`node_vector_rotate_${i}`)}(${m([B(e,"invert")?"-1.0":"1.0"])});`);break}case"ShaderNodeFresnel":case"ShaderNodeLayerWeight":{const i=e.inputs[1],c="link"in i?this.source(i,"vec3"):"g_data.N";"link"in i||this.s.structure.push("world-normal");const d=this.source(e.inputs[0],"float"),_=e.type==="ShaderNodeFresnel"?"node_fresnel":"node_layer_weight";f.push(`${this.use(_)}(${[d,c,u(a.map((h,g)=>g))].join(", ")});`);break}case"ShaderNodeBump":{const i=e.inputs.find(x=>x.id==="Height"),c=e.inputs.find(x=>x.id==="Normal"),d=c&&"link"in c?this.source(c,"vec3"):"g_data.N";if(!i||!("link"in i)){f.push(`${u([0])} = ${d};`);break}const _=`bgHeight${this.s.functions.length}`;this.s.functions.push("");const h=new jn(this.graph,this.s,!0,`${_}_`),g=h.source(i,"float");this.s.functions[Number(_.slice(8))]=`float ${_}() {
7023
+ ${h.lines.join(`
7024
7024
  `)}
7025
- return ${p};
7026
- }`;const g=this.input(e,"Filter Width","float");l.push(`float ${r}_h = ${h}();`,`g_derivative_filter_width = ${g} * derivative_scale_get();`,`g_derivative_flag = 1; float ${r}_hx = ${h}();`,`g_derivative_flag = -1; float ${r}_hy = ${h}();`,"g_derivative_flag = 0;");const v=V(e,"invert")?"-1.0":"1.0";l.push(`${this.use("node_bump")}(${this.input(e,"Strength","float")}, ${this.input(e,"Distance","float")}, ${g}, ${r}_h, ${m}, vec2(${r}_hx, ${r}_hy), ${v}, ${c([0])});`);break}case"ShaderNodeNormalMap":{const i=V(e,"space"),u=this.input(e,"Strength","float"),m=this.input(e,"Color","vec3"),h=`${r}_n`;if(l.push(`vec3 ${h}; ${this.use(i.startsWith("BLENDER_")?"color_to_blender_normal_new_shading":"color_to_normal_new_shading")}(${m}, ${h});`),e.props.convention==="DIRECTX"&&l.push(`${this.use("color_invert_green_channel")}(${h}, ${h});`),i==="TANGENT"){const _=V(e,"uv_map");this.s.uvs.add(_),l.push(`${this.use("node_normal_map")}(blender_uv_tangent(${ce(_)}), ${u}, ${h}, g_data.Ni, ${c([0])});`)}else(i==="OBJECT"||i==="BLENDER_OBJECT")&&l.push(`${this.use("normal_transform_object_to_world")}(${h}, ${h});`),l.push(`${this.use("node_normal_map_mix")}(${u}, ${h}, ${c([0])});`);break}case"ShaderNodeNewGeometry":{l.push(`${this.use("node_geometry")}(${["blender_orco()",c(a.map((i,u)=>u))].join(", ")});`),a[0]&&l.push(`${a[0].name} = ${this.d(a[0].name)};`);for(const i of[1,2,4])a[i]&&l.push(`${a[i].name} = normalize(${a[i].name});`);break}case"ShaderNodeTexImage":{const i=V(e,"image");if(i===null){l.push(e.props.image_missing===!0?`${c([0])} = vec4(1.0, 0.0, 1.0, 1.0); ${c([1])} = 1.0;`:`${c([0])} = vec4(0.0); ${c([1])} = 0.0;`);break}const u=V(e,"projection"),m=V(e,"interpolation"),h=m==="Cubic"||m==="Smart",_=V(e,"extension"),p=`bgImage${this.s.images.length}`;this.s.images.push({uniform:p,node:t,name:i.name,revision:i.revision,extension:_,closest:m==="Closest",mipmap:u!=="SPHERE"&&u!=="TUBE",tiled:u==="FLAT"&&e.props.image_tiled===!0});const g=this.s.images.at(-1).tiled;this.s.structure.push(["img",u,h,g]);let v=this.coordinate(e,"uv");const w=c([0]),x=c([1]);if(u==="BOX"){const M=`${r}_n`;l.push(`vec3 ${M}; ${this.use("world_normals_get")}(${M}); ${this.use("normal_transform_world_to_object")}(${M}, ${M});`,`vec4 ${r}_c1, ${r}_c2, ${r}_c3;`,`${this.use(h?"tex_box_sample_cubic":"tex_box_sample_linear")}(${v}, ${M}, ${p}, ${r}_c1, ${r}_c2, ${r}_c3);`,`${this.use("tex_box_blend")}(${M}, ${r}_c1, ${r}_c2, ${r}_c3, ${this.uniform("float",V(e,"projection_blend"))}, ${w}, ${x});`)}else if(g)h&&this.use("cubic_bspline_coefficients"),l.push(`${h?"blender_tex_tile_cubic":"blender_tex_tile_linear"}(${v}, ${p}, ${p}Map, ${w}, ${x});`);else{if(u==="SPHERE"||u==="TUBE"){const M=`${r}_co`;l.push(`vec3 ${M}; ${this.use("point_texco_remap_square")}(${v}, ${M});`,`${this.use(u==="SPHERE"?"point_map_to_sphere":"point_map_to_tube")}(${M}, ${M});`),v=M}l.push(`${this.use(h?"node_tex_image_cubic":"node_tex_image_linear")}(${v}, ${p}, ${w}, ${x});`),_==="CLIP"&&l.push(`if (any(lessThan(${v}.xy, vec2(0.0))) || any(greaterThan(${v}.xy, vec2(1.0)))) { ${w} = vec4(0.0); ${x} = 0.0; }`)}const T=V(e,"image_alpha_mode"),y=this.uses(t,1),A=c([0]);T==="NONE"||T==="CHANNEL_PACKED"||V(e,"image_is_data")?l.push(`${A}.a = 1.0;`):T==="PREMUL"?l.push(y?`if (${A}.a != 0.0 && ${A}.a != 1.0) ${A}.rgb /= ${A}.a;`:`${A}.a = 1.0;`):l.push(y?`${A}.a = 1.0;`:`${A}.rgb *= ${A}.a;`);break}}return this.lines.push(...l),a}uses(t,e){const o=a=>"link"in a&&a.link[0]===t&&a.link[1]===e,r=a=>a!==void 0&&("emission"in a?a.emission.some(o):"mix"in a?o(a.mix[0])||r(a.mix[1])||r(a.mix[2]):"add"in a?r(a.add[0])||r(a.add[1]):!1);return Object.values(this.graph.inputs).some(o)||Object.values(this.graph.nodes).some(a=>a.inputs.some(o))||r(this.graph.closure)}compile(){const t=this.graph.surface==="ShaderNodeEmission"?{Color:"vec4",Strength:"float"}:{"Base Color":"vec4",Metallic:"float",Roughness:"float",Alpha:"float","Emission Color":"vec4","Emission Strength":"float",Normal:"vec3"},e={},o=[];let r=0;for(const[i,u]of Object.entries(t)){const m=this.graph.inputs[i];if(!m||i==="Normal"&&!("link"in m))continue;const h=`bgOut${r++}`;e[i]={global:h,type:u},this.s.structure.push(["out",i]),o.push(`${h} = ${this.source(m,u)};`)}const a=this.graph.closure;if(a){let i=0;const u=(m,h)=>{if("principled"in m)this.s.structure.push("cP"),o.push(`bgClosureP += ${h};`);else if("emission"in m)this.s.structure.push("cE"),o.push(`bgClosureE += ${h} * ${this.source(m.emission[0],"vec4")}.rgb * ${this.source(m.emission[1],"float")};`);else if("transparent"in m)this.s.structure.push("cT"),o.push(`bgClosureT += ${h} * ${this.source({value:m.transparent},"float")};`);else if("mix"in m){this.s.structure.push("cM");const _=`bgClosureF${i++}`;o.push(`float ${_} = clamp(${this.source(m.mix[0],"float")}, 0.0, 1.0);`),u(m.mix[1],`${h} * (1.0 - ${_})`),u(m.mix[2],`${h} * ${_}`)}else"add"in m?(this.s.structure.push("cA"),u(m.add[0],h),u(m.add[1],h)):this.s.structure.push("c0")};o.push("bgClosureP = 0.0;","bgClosureE = vec3(0.0);","bgClosureT = 0.0;"),u(a,"1.0")}const s=[],f=new Set,c=i=>{if(!f.has(i)){f.add(i);for(const u of An[i].deps)c(u);s.push(i)}};for(const i of this.s.files)c(i);const d=`void blenderGraph() {
7025
+ return ${g};
7026
+ }`;const p=this.input(e,"Filter Width","float");f.push(`float ${r}_h = ${_}();`,`g_derivative_filter_width = ${p} * derivative_scale_get();`,`g_derivative_flag = 1; float ${r}_hx = ${_}();`,`g_derivative_flag = -1; float ${r}_hy = ${_}();`,"g_derivative_flag = 0;");const v=B(e,"invert")?"-1.0":"1.0";f.push(`${this.use("node_bump")}(${this.input(e,"Strength","float")}, ${this.input(e,"Distance","float")}, ${p}, ${r}_h, ${d}, vec2(${r}_hx, ${r}_hy), ${v}, ${u([0])});`);break}case"ShaderNodeNormalMap":{const i=B(e,"space"),c=this.input(e,"Strength","float"),d=this.input(e,"Color","vec3"),_=`${r}_n`;if(f.push(`vec3 ${_}; ${this.use(i.startsWith("BLENDER_")?"color_to_blender_normal_new_shading":"color_to_normal_new_shading")}(${d}, ${_});`),e.props.convention==="DIRECTX"&&f.push(`${this.use("color_invert_green_channel")}(${_}, ${_});`),i==="TANGENT"){const h=B(e,"uv_map");this.s.uvs.add(h),f.push(`${this.use("node_normal_map")}(blender_uv_tangent(${ce(h)}), ${c}, ${_}, g_data.Ni, ${u([0])});`)}else(i==="OBJECT"||i==="BLENDER_OBJECT")&&f.push(`${this.use("normal_transform_object_to_world")}(${_}, ${_});`),f.push(`${this.use("node_normal_map_mix")}(${c}, ${_}, ${u([0])});`);break}case"ShaderNodeNewGeometry":{f.push(`${this.use("node_geometry")}(${["blender_orco()",u(a.map((i,c)=>c))].join(", ")});`),a[0]&&f.push(`${a[0].name} = ${this.d(a[0].name)};`);for(const i of[1,2,4])a[i]&&f.push(`${a[i].name} = normalize(${a[i].name});`);break}case"ShaderNodeTexImage":{const i=B(e,"image");if(i===null){f.push(e.props.image_missing===!0?`${u([0])} = vec4(1.0, 0.0, 1.0, 1.0); ${u([1])} = 1.0;`:`${u([0])} = vec4(0.0); ${u([1])} = 0.0;`);break}const c=B(e,"projection"),d=B(e,"interpolation"),_=d==="Cubic"||d==="Smart",h=B(e,"extension"),g=`bgImage${this.s.images.length}`;this.s.images.push({uniform:g,node:t,name:i.name,revision:i.revision,extension:h,closest:d==="Closest",mipmap:c!=="SPHERE"&&c!=="TUBE",tiled:c==="FLAT"&&e.props.image_tiled===!0});const p=this.s.images.at(-1).tiled;this.s.structure.push(["img",c,_,p]);let v=this.coordinate(e,"uv");const x=u([0]),w=u([1]);if(c==="BOX"){const y=`${r}_n`;f.push(`vec3 ${y}; ${this.use("world_normals_get")}(${y}); ${this.use("normal_transform_world_to_object")}(${y}, ${y});`,`vec4 ${r}_c1, ${r}_c2, ${r}_c3;`,`${this.use(_?"tex_box_sample_cubic":"tex_box_sample_linear")}(${v}, ${y}, ${g}, ${r}_c1, ${r}_c2, ${r}_c3);`,`${this.use("tex_box_blend")}(${y}, ${r}_c1, ${r}_c2, ${r}_c3, ${this.uniform("float",B(e,"projection_blend"))}, ${x}, ${w});`)}else if(p)_&&this.use("cubic_bspline_coefficients"),f.push(`${_?"blender_tex_tile_cubic":"blender_tex_tile_linear"}(${v}, ${g}, ${g}Map, ${x}, ${w});`);else{if(c==="SPHERE"||c==="TUBE"){const y=`${r}_co`;f.push(`vec3 ${y}; ${this.use("point_texco_remap_square")}(${v}, ${y});`,`${this.use(c==="SPHERE"?"point_map_to_sphere":"point_map_to_tube")}(${y}, ${y});`),v=y}f.push(`${this.use(_?"node_tex_image_cubic":"node_tex_image_linear")}(${v}, ${g}, ${x}, ${w});`),h==="CLIP"&&f.push(`if (any(lessThan(${v}.xy, vec2(0.0))) || any(greaterThan(${v}.xy, vec2(1.0)))) { ${x} = vec4(0.0); ${w} = 0.0; }`)}const S=B(e,"image_alpha_mode"),M=this.uses(t,1),O=u([0]);S==="NONE"||S==="CHANNEL_PACKED"||B(e,"image_is_data")?f.push(`${O}.a = 1.0;`):S==="PREMUL"?f.push(M?`if (${O}.a != 0.0 && ${O}.a != 1.0) ${O}.rgb /= ${O}.a;`:`${O}.a = 1.0;`):f.push(M?`${O}.a = 1.0;`:`${O}.rgb *= ${O}.a;`);break}}return this.lines.push(...f),a}uses(t,e){const o=a=>"link"in a&&a.link[0]===t&&a.link[1]===e,r=a=>a!==void 0&&("emission"in a?a.emission.some(o):"mix"in a?o(a.mix[0])||r(a.mix[1])||r(a.mix[2]):"add"in a?r(a.add[0])||r(a.add[1]):!1);return Object.values(this.graph.inputs).some(o)||Object.values(this.graph.nodes).some(a=>a.inputs.some(o))||r(this.graph.closure)}compile(){const t=this.graph.surface==="ShaderNodeEmission"?{Color:"vec4",Strength:"float"}:{"Base Color":"vec4",Metallic:"float",Roughness:"float",Alpha:"float","Emission Color":"vec4","Emission Strength":"float",Normal:"vec3"},e={},o=[];let r=0;for(const[c,d]of Object.entries(t)){const _=this.graph.inputs[c];if(!_||c==="Normal"&&!("link"in _))continue;const h=`bgOut${r++}`;e[c]={global:h,type:d},this.s.structure.push(["out",c]),o.push(`${h} = ${this.source(_,d)};`)}const a=this.graph.closure;if(a){let c=0;const d=(_,h)=>{if("principled"in _)this.s.structure.push("cP"),o.push(`bgClosureP += ${h};`);else if("emission"in _)this.s.structure.push("cE"),o.push(`bgClosureE += ${h} * ${this.source(_.emission[0],"vec4")}.rgb * ${this.source(_.emission[1],"float")};`);else if("transparent"in _)this.s.structure.push("cT"),o.push(`bgClosureT += ${h} * ${this.source({value:_.transparent},"float")};`);else if("mix"in _){this.s.structure.push("cM");const g=`bgClosureF${c++}`;o.push(`float ${g} = clamp(${this.source(_.mix[0],"float")}, 0.0, 1.0);`),d(_.mix[1],`${h} * (1.0 - ${g})`),d(_.mix[2],`${h} * ${g}`)}else"add"in _?(this.s.structure.push("cA"),d(_.add[0],h),d(_.add[1],h)):this.s.structure.push("c0")};o.push("bgClosureP = 0.0;","bgClosureE = vec3(0.0);","bgClosureT = 0.0;"),d(a,"1.0")}const s=[],l=new Set,u=c=>{if(!l.has(c)){l.add(c);for(const d of Tn[c].deps)u(d);s.push(c)}};for(const c of this.s.files)u(c);const m=`void blenderGraph() {
7027
7027
  blender_init_globals();
7028
7028
  ${[...this.lines,...o].join(`
7029
7029
  `)}
7030
- }`,l=[ds,Ps(Ts+s.map(i=>An[i].code).join(`
7030
+ }`,f=[xs,zs(Ds+s.map(c=>Tn[c].code).join(`
7031
7031
  `)+`
7032
- `+Ss,[...this.s.functions,d].join(`
7033
- `)),...[...this.s.uniformTypes].map(([i,u])=>`uniform ${u} ${i};`),...this.images.map(i=>i.tiled?`uniform highp sampler2DArray ${i.uniform};
7034
- uniform highp sampler2D ${i.uniform}Map;`:`uniform sampler2D ${i.uniform};`),...this.ramps.map(i=>`uniform sampler2D ${i.uniform};`),...Object.values(e).map(i=>`${i.type} ${i.global};`),...a?["float bgClosureP;","vec3 bgClosureE;","float bgClosureT;"]:[],...this.s.functions,d].join(`
7035
- `);return{key:JSON.stringify([this.graph.surface,this.s.structure,[...this.s.uvs].sort()]),declarations:l,uniforms:this.uniforms,images:this.images,ramps:this.ramps,uvs:[...this.s.uvs],attributes:[...this.s.attributes],outputs:e,surface:this.graph.surface,closure:a!==void 0}}}function Ps(n,t){const e=[],o=/^[A-Za-z_][\w ]*?\b([A-Za-z_]\w*)\s*\(/gm;let r=0;for(let c;c=o.exec(n);){if(c.index<r)continue;let d=c.index+c[0].length;for(let m=1;d<n.length&&m>0;d++)m+=n[d]==="("?1:n[d]===")"?-1:0;const l=n.slice(d).match(/^\s*(\{|;)/);if(!l||/^\s*#/.test(n.slice(n.lastIndexOf(`
7036
- `,c.index)+1,c.index+1))||n.slice(Math.max(0,c.index-2),c.index).endsWith(`\\
7037
- `))continue;let u=d+l[0].length;if(l[1]==="{")for(let m=1;u<n.length&&m>0;u++)m+=n[u]==="{"?1:n[u]==="}"?-1:0;e.push({text:n.slice(r,c.index),name:null}),e.push({text:n.slice(c.index,u),name:c[1]}),r=u,o.lastIndex=u}e.push({text:n.slice(r),name:null});const a=new Set(e.filter(c=>c.name===null)),s=new Set,f=c=>{for(const d of c.matchAll(/[A-Za-z_]\w*/g))s.add(d[0])};f(t);for(const c of a)f(c.text);for(let c=!0;c;){c=!1;for(const d of e)a.has(d)||d.name===null||!s.has(d.name)||(a.add(d),f(d.text),c=!0)}return e.filter(c=>a.has(c)).map(c=>c.text).join("")}function Mn(n){return`v${qt(n)}`}function ce(n){return n===""?"vBlenderUvRender":`vBlenderUv_${[...n].map(t=>t.charCodeAt(0).toString(16)).join("")}`}function Es(n){return new Fn(n).compile()}function Ns(n){const t=new Uint16Array(n.length*4);n.forEach((o,r)=>t.set([o[0]??0,o[1]??0,o[2]??0,o[3]??1].map(a=>xe.toHalfFloat(a)),r*4));const e=new Ye(t,n.length,1,Ze,En);return e.minFilter=e.magFilter=oe,e.wrapS=e.wrapT=Io,e.needsUpdate=!0,e}const dt=new WeakMap,kn=new Set,Ct=new WeakMap,Ee=new WeakMap;function Ne(n){const t=Ct.get(n);if(t){Ct.delete(n);for(const e of t.binding.ramps)e.dispose()}}function Rs(n,t,e,o=!1){const r=dt.get(n);if(t&&kn.has(t.key)&&(t=null),!t){if(Ne(n),r){for(const f of r.ramps)f.dispose();dt.delete(n),n.needsUpdate=!0}return}if(r&&r.compiled.key===t.key){Ne(n),Re(r,t,e);return}if(o){Ne(n);for(const c of r?.ramps??[])c.dispose();const f={compiled:t,uniforms:{},ramps:[],channels:r?.channels??{}};Re(f,t,e),dt.set(n,f),n.needsUpdate=!0;return}const a=Ct.get(n);if(a&&a.binding.compiled.key===t.key){Re(a.binding,t,e);return}Ne(n);const s={compiled:t,uniforms:{},ramps:[],channels:r?.channels??{}};Re(s,t,e),Ct.set(n,{binding:s,started:!1})}function Is(n,t){if(Ct.has(n))return!1;const e=dt.get(n),o=e&&!kn.has(e.compiled.key)?e:void 0,r=dt.get(t);return o?(!r||r.compiled.key!==o.compiled.key||r.uniforms!==o.uniforms)&&(dt.set(t,{compiled:o.compiled,uniforms:o.uniforms,ramps:[],channels:{}}),t.needsUpdate=!0):r&&(dt.delete(t),t.needsUpdate=!0),!0}function Re(n,t,e){n.compiled=t;for(const[o,r]of t.uniforms){const a=typeof r=="number"?r:r.length===2?new ne(...r):r.length===3?new b(...r):new Xe(...r),s=n.uniforms[o];s?s.value=a:n.uniforms[o]={value:a}}for(const o of n.ramps)o.dispose();n.ramps=t.ramps.map(o=>{const r=Ns(o.table);return(n.uniforms[o.uniform]??={value:null}).value=r,r});for(const o of t.images){const r=e(o);if(o.tiled){const a=r!==null&&"tiles"in r?r:null;(n.uniforms[o.uniform]??={value:null}).value=a?.tiles??null,(n.uniforms[`${o.uniform}Map`]??={value:null}).value=a?.map??null}else(n.uniforms[o.uniform]??={value:null}).value=r!==null&&"tiles"in r?null:r}}function Ds(n){const t=dt.get(n);return t?`${t.compiled.key}|${JSON.stringify(t.channels)}`:""}function zs(n){return Object.values(dt.get(n)?.channels??{})}function ta(n,t){const e=new Set(["position","normal","uv"]);if(t.hasAttribute("tangent")&&e.add("tangent"),n.vertexColors&&e.add("color"),!(n instanceof ae))return e;const o=t.userData.blenderUvChannels,r=a=>{const s=a===""?0:o?.[a]??9;e.add(s===0?"uv":`uv${s}`)};for(const a of[n.map,n.roughnessMap,n.normalMap])a&&r(a.userData.blenderUvName??"");for(const a of[dt.get(n),Ct.get(n)?.binding])if(a){e.add("blenderOrco");for(const s of a.compiled.uvs)r(s);for(const s of a.compiled.attributes)e.add(qt(s))}return e}function uo(n,t){const e=t.userData.blenderUvChannels,o=t.getAttribute("position")?.count??0,r={};for(const a of n.uvs){let s=a===""?0:e?.[a];s===void 0&&(s=9,t.getAttribute("uv9")?.count!==o&&t.setAttribute("uv9",new lt(new Float32Array(o*2),2))),r[a]=s}return r}function Cs(n,t,e){const o=e.userData.blenderUvChannels,r=e.getAttribute("position")?.count??0;let a=Object.keys(t).length===n.uvs.length;for(const s of n.uvs){let f=s===""?0:o?.[s];f===void 0&&(f=9,e.getAttribute("uv9")?.count!==r&&e.setAttribute("uv9",new lt(new Float32Array(r*2),2))),t[s]!==f&&(a=!1)}return a}function Fs(n,t,e,o,r,a,s){const f=Ee.get(n);f&&++f.draws>1&&(f.shadow.dispose(),Ee.delete(n));const c=Ct.get(n);if(c&&!c.started){c.started=!0,c.binding.channels=uo(c.binding.compiled,t);const i=s(n);dt.set(i,c.binding);const u=new kt(t,i);u.castShadow=a.castShadow,u.receiveShadow=a.receiveShadow;const m=()=>{if(Ct.get(n)!==c){i.dispose();return}Ct.delete(n);for(const h of dt.get(n)?.ramps??[])h.dispose();dt.set(n,c.binding),n.needsUpdate=!0,Ee.get(n)?.shadow.dispose(),Ee.set(n,{shadow:i,draws:0}),_t()};e.compileAsync(u,r,o).then(m,m)}const d=dt.get(n);if(!d)return;const l=e.properties.get(n).currentProgram;if(l?.diagnostics?.runnable===!1&&l.cacheKey?.includes(d.compiled.key)){kn.add(d.compiled.key),dt.delete(n),n.needsUpdate=!0;const i=l.diagnostics.fragmentShader.log.split(`
7038
- `).find(u=>u.startsWith("ERROR"))??"";console.warn(`Blender material "${n.name}": its node graph did not compile for WebGL, so it is drawn with its constant values. ${i}`);return}Cs(d.compiled,d.channels,t)||(d.channels=uo(d.compiled,t),n.needsUpdate=!0)}function ks(n){const t=Array.isArray(n.material)?n.material:[n.material];if(!t.some(c=>c instanceof ae&&dt.has(c)))return;const e=n.geometry,o=n.userData.blenderTexspace??null,r=e.getAttribute("position"),a=JSON.stringify([o,r?.version??0,r?.count??0]);!e.userData.blenderOrcoFromDoor&&e.userData.blenderOrcoStamp!==a&&(e.setAttribute("blenderOrco",$s(e,o)),e.userData.blenderOrcoStamp=a);const s=r?.count??0,f=n.userData.blenderDefaultColor;for(const c of t){const d=c instanceof ae?dt.get(c):void 0;for(const l of d?.compiled.attributes??[]){const i=qt(l),u=l===""?f===void 0?void 0:e.getAttribute(qt(f)):e.getAttribute(i);u&&u.count===s?e.getAttribute(i)!==u&&e.setAttribute(i,u):e.getAttribute(i)?.count!==s&&e.setAttribute(i,new lt(new Float32Array(s*4),4))}}}function $s(n,t){const e=n.getAttribute("position");let o,r;if(t)o=[...t[0]],r=[...t[1]];else{n.computeBoundingBox();const s=n.boundingBox;o=[(s.min.x+s.max.x)/2,(s.min.y+s.max.y)/2,(s.min.z+s.max.z)/2],r=[(s.max.x-s.min.x)/2,(s.max.y-s.min.y)/2,(s.max.z-s.min.z)/2]}r=r.map(s=>s===0?1:s);const a=new Float32Array(e.count*3);for(let s=0;s<e.count;s++)a[s*3]=(e.getX(s)-o[0])/r[0]*.5+.5,a[s*3+1]=(e.getY(s)-o[1])/r[1]*.5+.5,a[s*3+2]=(e.getZ(s)-o[2])/r[2]*.5+.5;return new lt(a,3)}function Ls(n,t){const e=dt.get(n);if(!e)return;const{compiled:o,channels:r}=e;Object.assign(t.uniforms,e.uniforms,{blenderViewport:{value:ea}});const a=g=>g===0?"uv":`uv${g}`,s=`varying vec3 vBlenderObjectPosition;
7032
+ `+Cs,[...this.s.functions,m].join(`
7033
+ `))].join(`
7034
+ `),i=[...[...this.s.uniformTypes].map(([c,d])=>`uniform ${d} ${c};`),...this.images.map(c=>c.tiled?`uniform highp sampler2DArray ${c.uniform};
7035
+ uniform highp sampler2D ${c.uniform}Map;`:`uniform sampler2D ${c.uniform};`),...this.ramps.map(c=>`uniform sampler2D ${c.uniform};`),...Object.values(e).map(c=>`${c.type} ${c.global};`),...a?["float bgClosureP;","vec3 bgClosureE;","float bgClosureT;"]:[],...this.s.functions,m].join(`
7036
+ `);return{key:JSON.stringify([this.graph.surface,this.s.structure,[...this.s.uvs].sort()]),declarations:`${f}
7037
+ ${i}`,library:f,program:i,uniforms:this.uniforms,images:this.images,ramps:this.ramps,uvs:[...this.s.uvs],attributes:[...this.s.attributes],outputs:e,surface:this.graph.surface,closure:a!==void 0}}}function zs(n,t){const e=[],o=/^[A-Za-z_][\w ]*?\b([A-Za-z_]\w*)\s*\(/gm;let r=0;for(let u;u=o.exec(n);){if(u.index<r)continue;let m=u.index+u[0].length;for(let d=1;m<n.length&&d>0;m++)d+=n[m]==="("?1:n[m]===")"?-1:0;const f=n.slice(m).match(/^\s*(\{|;)/);if(!f||/^\s*#/.test(n.slice(n.lastIndexOf(`
7038
+ `,u.index)+1,u.index+1))||n.slice(Math.max(0,u.index-2),u.index).endsWith(`\\
7039
+ `))continue;let c=m+f[0].length;if(f[1]==="{")for(let d=1;c<n.length&&d>0;c++)d+=n[c]==="{"?1:n[c]==="}"?-1:0;e.push({text:n.slice(r,u.index),name:null}),e.push({text:n.slice(u.index,c),name:u[1]}),r=c,o.lastIndex=c}e.push({text:n.slice(r),name:null});const a=new Set(e.filter(u=>u.name===null)),s=new Set,l=u=>{for(const m of u.matchAll(/[A-Za-z_]\w*/g))s.add(m[0])};l(t);for(const u of a)l(u.text);for(let u=!0;u;){u=!1;for(const m of e)a.has(m)||m.name===null||!s.has(m.name)||(a.add(m),l(m.text),u=!0)}return e.filter(u=>a.has(u)).map(u=>u.text).join("")}function Pn(n){return`v${Xt(n)}`}function ce(n){return n===""?"vBlenderUvRender":`vBlenderUv_${[...n].map(t=>t.charCodeAt(0).toString(16)).join("")}`}function ks(n){return new jn(n).compile()}function Fs(n){const t=new Uint16Array(n.length*4);n.forEach((o,r)=>t.set([o[0]??0,o[1]??0,o[2]??0,o[3]??1].map(a=>ye.toHalfFloat(a)),r*4));const e=new Ke(t,n.length,1,Qe,Dn);return e.minFilter=e.magFilter=re,e.wrapS=e.wrapT=Lo,e.needsUpdate=!0,e}const ot=new WeakMap,Ne=new Set;function $s(n){return ot.get(n)?.compiled??null}function fa(n){if(n.length!==2||n.some(o=>Pt.has(o)))return null;const t=n.map(o=>ot.get(o)?.compiled),e=t[0];return!e||Ne.has(e.key)||t.some(o=>!o||o.key!==e.key||o.declarations!==e.declarations||o.library!==e.library||JSON.stringify([o.uvs,o.attributes,o.outputs])!==JSON.stringify([e.uvs,e.attributes,e.outputs]))||n.reduce((o,r)=>o+e.images.reduce((a,s)=>a+(s.tiled?2:1),0)+e.ramps.length+[r.map,r.normalMap,r.roughnessMap].filter(Boolean).length,0)>8?null:e}function Ls(n){const t=ot.get(n)?.compiled;return!!t&&!Pt.has(n)&&!Ne.has(t.key)}function js(n){const t=fa(n);if(!t)return null;const e=(s,l)=>s.replace(/\b(bg\w+|blenderGraph)\b/g,u=>`bp${l}_${u}`),o=Object.values(t.outputs).map(s=>`${s.type} ${s.global};`);t.closure&&o.push("float bgClosureP;","vec3 bgClosureE;","float bgClosureT;");const r=[...Object.values(t.outputs).map(s=>s.global),...t.closure?["bgClosureP","bgClosureE","bgClosureT"]:[]],a=[e(t.program,0),e(t.program,1),...o,`void blenderGraph() { bp0_blenderGraph(); bp1_blenderGraph(); ${r.map(s=>`${s} = vBlenderPaletteIndex == 0 ? bp0_${s} : bp1_${s};`).join(" ")} }`].join(`
7040
+ `);return{...t,key:`blender-palette-v1:${t.key}`,program:a,declarations:`${t.library}
7041
+ ${a}`,images:[],ramps:[],uniforms:new Map}}function Vs(n,t,e,o,r){if(!fa(e))return!1;const a={blenderPaletteIndices:{value:o}};for(let s=0;s<e.length;s++){const l=e[s];for(const[u,m]of Object.entries(ot.get(l).uniforms))a[`bp${s}_${u}`]=m;for(const u of["map","normalMap","roughnessMap"])l[u]&&(a[`bp${s}_${u}`]={value:l[u]})}return ot.set(n,{compiled:t,uniforms:a,ramps:[],channels:En(t,r),palette:{indices:o,sources:e}}),n.needsUpdate=!0,!0}const Pt=new WeakMap,De=new WeakMap;function Ce(n){const t=Pt.get(n);if(t){Pt.delete(n);for(const e of t.binding.ramps)e.dispose()}}function Bs(n,t,e,o=!1){const r=ot.get(n);if(t&&Ne.has(t.key)&&(t=null),!t){if(Ce(n),r){for(const l of r.ramps)l.dispose();ot.delete(n),n.needsUpdate=!0}return}if(r&&r.compiled.key===t.key){Ce(n),ze(r,t,e);return}if(o){Ce(n);for(const u of r?.ramps??[])u.dispose();const l={compiled:t,uniforms:{},ramps:[],channels:r?.channels??{}};ze(l,t,e),ot.set(n,l),n.needsUpdate=!0;return}const a=Pt.get(n);if(a&&a.binding.compiled.key===t.key){ze(a.binding,t,e);return}Ce(n);const s={compiled:t,uniforms:{},ramps:[],channels:r?.channels??{}};ze(s,t,e),Pt.set(n,{binding:s,started:!1})}function Us(n,t){if(Pt.has(n))return!1;const e=ot.get(n),o=e&&!Ne.has(e.compiled.key)?e:void 0,r=ot.get(t);return o?(!r||r.compiled.key!==o.compiled.key||r.uniforms!==o.uniforms)&&(ot.set(t,{compiled:o.compiled,uniforms:o.uniforms,ramps:[],channels:{}}),t.needsUpdate=!0):r&&(ot.delete(t),t.needsUpdate=!0),!0}function ze(n,t,e){n.compiled=t;for(const[o,r]of t.uniforms){const a=typeof r=="number"?r:r.length===2?new Ht(...r):r.length===3?new b(...r):new Ee(...r),s=n.uniforms[o];s?s.value=a:n.uniforms[o]={value:a}}for(const o of n.ramps)o.dispose();n.ramps=t.ramps.map(o=>{const r=Fs(o.table);return(n.uniforms[o.uniform]??={value:null}).value=r,r});for(const o of t.images){const r=e(o);if(o.tiled){const a=r!==null&&"tiles"in r?r:null;(n.uniforms[o.uniform]??={value:null}).value=a?.tiles??null,(n.uniforms[`${o.uniform}Map`]??={value:null}).value=a?.map??null}else(n.uniforms[o.uniform]??={value:null}).value=r!==null&&"tiles"in r?null:r}}function Ws(n){const t=ot.get(n);return t?`${t.compiled.key}|${JSON.stringify(t.channels)}`:""}function qs(n){return Object.values(ot.get(n)?.channels??{})}function ca(n,t){const e=new Set(["position","normal","uv"]);if(t.hasAttribute("tangent")&&e.add("tangent"),n.vertexColors&&e.add("color"),!(n instanceof Gt))return e;const o=t.userData.blenderUvChannels,r=a=>{const s=a===""?0:o?.[a]??9;e.add(s===0?"uv":`uv${s}`)};for(const a of[n.map,n.roughnessMap,n.normalMap])a&&r(a.userData.blenderUvName??"");for(const a of[ot.get(n),Pt.get(n)?.binding])if(a){e.add("blenderOrco");for(const s of a.compiled.uvs)r(s);for(const s of a.compiled.attributes)e.add(Xt(s))}return e}function En(n,t){const e=t.userData.blenderUvChannels,o=t.getAttribute("position")?.count??0,r={};for(const a of n.uvs){let s=a===""?0:e?.[a];s===void 0&&(s=9,t.getAttribute("uv9")?.count!==o&&t.setAttribute("uv9",new ft(new Float32Array(o*2),2))),r[a]=s}return r}function Hs(n,t,e){const o=e.userData.blenderUvChannels,r=e.getAttribute("position")?.count??0;let a=Object.keys(t).length===n.uvs.length;for(const s of n.uvs){let l=s===""?0:o?.[s];l===void 0&&(l=9,e.getAttribute("uv9")?.count!==r&&e.setAttribute("uv9",new ft(new Float32Array(r*2),2))),t[s]!==l&&(a=!1)}return a}function Gs(n,t,e,o,r,a,s){const l=De.get(n);l&&++l.draws>1&&(l.shadow.dispose(),De.delete(n));const u=Pt.get(n);if(u&&!u.started){u.started=!0,u.binding.channels=En(u.binding.compiled,t);const i=s(n);ot.set(i,u.binding);const c=new Ft(t,i);c.castShadow=a.castShadow,c.receiveShadow=a.receiveShadow;const d=()=>{if(Pt.get(n)!==u){i.dispose();return}Pt.delete(n);for(const _ of ot.get(n)?.ramps??[])_.dispose();ot.set(n,u.binding),n.needsUpdate=!0,De.get(n)?.shadow.dispose(),De.set(n,{shadow:i,draws:0}),mt()};e.compileAsync(c,r,o).then(d,d)}const m=ot.get(n);if(!m)return;const f=e.properties.get(n).currentProgram;if(f?.diagnostics?.runnable===!1&&f.cacheKey?.includes(m.compiled.key)){Ne.add(m.compiled.key),ot.delete(n),n.needsUpdate=!0;const i=f.diagnostics.fragmentShader.log.split(`
7042
+ `).find(c=>c.startsWith("ERROR"))??"";console.warn(`Blender material "${n.name}": its node graph did not compile for WebGL, so it is drawn with its constant values. ${i}`);return}Hs(m.compiled,m.channels,t)||(m.channels=En(m.compiled,t),n.needsUpdate=!0)}function Xs(n){const t=Array.isArray(n.material)?n.material:[n.material];if(!t.some(u=>u instanceof Gt&&ot.has(u)))return;const e=n.geometry,o=n.userData.blenderTexspace??null,r=e.getAttribute("position"),a=JSON.stringify([o,r?.version??0,r?.count??0]);!e.userData.blenderOrcoFromDoor&&e.userData.blenderOrcoStamp!==a&&(e.setAttribute("blenderOrco",Ys(e,o)),e.userData.blenderOrcoStamp=a);const s=r?.count??0,l=n.userData.blenderDefaultColor;for(const u of t){const m=u instanceof Gt?ot.get(u):void 0;for(const f of m?.compiled.attributes??[]){const i=Xt(f),c=f===""?l===void 0?void 0:e.getAttribute(Xt(l)):e.getAttribute(i);c&&c.count===s?e.getAttribute(i)!==c&&e.setAttribute(i,c):e.getAttribute(i)?.count!==s&&e.setAttribute(i,new ft(new Float32Array(s*4),4))}}}function Ys(n,t){const e=n.getAttribute("position");let o,r;if(t)o=[...t[0]],r=[...t[1]];else{n.computeBoundingBox();const s=n.boundingBox;o=[(s.min.x+s.max.x)/2,(s.min.y+s.max.y)/2,(s.min.z+s.max.z)/2],r=[(s.max.x-s.min.x)/2,(s.max.y-s.min.y)/2,(s.max.z-s.min.z)/2]}r=r.map(s=>s===0?1:s);const a=new Float32Array(e.count*3);for(let s=0;s<e.count;s++)a[s*3]=(e.getX(s)-o[0])/r[0]*.5+.5,a[s*3+1]=(e.getY(s)-o[1])/r[1]*.5+.5,a[s*3+2]=(e.getZ(s)-o[2])/r[2]*.5+.5;return new ft(a,3)}function Zs(n,t){const e=ot.get(n);if(!e)return;const{compiled:o,channels:r}=e;Object.assign(t.uniforms,e.uniforms,{blenderViewport:{value:ua}});const a=p=>p===0?"uv":`uv${p}`,s=`varying vec3 vBlenderObjectPosition;
7039
7043
  varying vec3 vBlenderObjectNormal;
7040
7044
  varying vec3 vBlenderWorldPosition;
7041
7045
  varying vec3 vBlenderWorldNormal;
7042
7046
  varying vec3 vBlenderOrco;
7043
- ${o.attributes.map(g=>`varying vec4 ${Mn(g)};`).join(`
7047
+ ${o.attributes.map(p=>`varying vec4 ${Pn(p)};`).join(`
7044
7048
  `)}
7045
- ${o.uvs.map(g=>`varying vec2 ${ce(g)};`).join(`
7046
- `)}`,f=o.attributes.map(g=>`attribute vec4 ${qt(g)};`).join(`
7047
- `);t.vertexShader=`attribute vec3 blenderOrco;
7048
- ${f}
7049
+ ${o.uvs.map(p=>`varying vec2 ${ce(p)};`).join(`
7050
+ `)}`,l=o.attributes.map(p=>`attribute vec4 ${Xt(p)};`).join(`
7051
+ `);if(t.vertexShader=`attribute vec3 blenderOrco;
7052
+ ${l}
7049
7053
  ${s}
7050
7054
  ${t.vertexShader}`.replace("#include <project_vertex>",`vBlenderObjectPosition = transformed;
7051
7055
  vBlenderObjectNormal = objectNormal;
@@ -7059,11 +7063,21 @@ blenderWorldMatrix = blenderWorldMatrix * instanceMatrix;
7059
7063
  vBlenderWorldPosition = (blenderWorldMatrix * vec4(transformed, 1.0)).xyz;
7060
7064
  vBlenderWorldNormal = normalize(transpose(inverse(mat3(blenderWorldMatrix))) * objectNormal);
7061
7065
  vBlenderOrco = blenderOrco;
7062
- ${o.attributes.map(g=>`${Mn(g)} = ${qt(g)};`).join(`
7066
+ ${o.attributes.map(p=>`${Pn(p)} = ${Xt(p)};`).join(`
7063
7067
  `)}
7064
- ${o.uvs.map(g=>`${ce(g)} = ${a(r[g]??0)};`).join(`
7068
+ ${o.uvs.map(p=>`${ce(p)} = ${a(r[p]??0)};`).join(`
7065
7069
  `)}
7066
- #include <project_vertex>`);const c=g=>o.outputs[g]?.global,d=[];o.surface==="ShaderNodeEmission"?(d.push(["#include <color_fragment>","diffuseColor = vec4(0.0, 0.0, 0.0, 1.0);",!1]),d.push(["#include <emissivemap_fragment>",`totalEmissiveRadiance = ${c("Color")}.rgb * ${c("Strength")};`,!1]),d.push(["#include <opaque_fragment>","outgoingLight = totalEmissiveRadiance;",!0])):o.surface==="closure"?(d.push(["#include <color_fragment>","diffuseColor = vec4(0.0, 0.0, 0.0, 1.0);",!1]),d.push(["#include <emissivemap_fragment>","totalEmissiveRadiance = vec3(0.0);",!1])):(d.push(["#include <color_fragment>",`diffuseColor.rgb = ${c("Base Color")}.rgb;`,!1]),d.push(["#include <alphamap_fragment>",`diffuseColor.a = ${c("Alpha")};`,!1]),d.push(["#include <metalnessmap_fragment>",`roughnessFactor = ${c("Roughness")};`,!0]),d.push(["#include <metalnessmap_fragment>",`metalnessFactor = ${c("Metallic")};`,!1]),d.push(["#include <emissivemap_fragment>",`totalEmissiveRadiance = ${c("Emission Color")}.rgb * ${c("Emission Strength")};`,!1]),c("Normal")&&d.push(["#include <clearcoat_normal_fragment_begin>",`normal = normalize((viewMatrix * vec4(transpose(blender_from_three) * ${c("Normal")}, 0.0)).xyz);`,!0])),o.closure&&d.push(["#include <opaque_fragment>",`{
7070
+ #include <project_vertex>`),e.palette){t.vertexShader=`uniform int blenderPaletteIndices[64];
7071
+ flat varying int vBlenderPaletteIndex;
7072
+ ${t.vertexShader}`.replace("#include <project_vertex>",`vBlenderPaletteIndex = blenderPaletteIndices[int(getIndirectIndex(gl_DrawID))];
7073
+ #include <project_vertex>`),t.fragmentShader=`flat varying int vBlenderPaletteIndex;
7074
+ ${t.fragmentShader}`;for(const[p,v,x]of[["map","vMapUv","blenderMapClip"],["normalMap","vNormalMapUv","blenderNormalClip"],["roughnessMap","vRoughnessMapUv","blenderRoughnessClip"]])n[p]&&(t.fragmentShader=`uniform sampler2D bp0_${p}, bp1_${p};
7075
+ ${t.fragmentShader}`.replaceAll(`blenderImageSample(${p}, ${v}, ${x})`,`blenderPalette_${p}(${v}, ${x})`).replace("void main() {",`vec4 blenderPalette_${p}(vec2 uv, bool clipImage) {
7076
+ vec4 first = blenderImageSample(bp0_${p}, uv, clipImage);
7077
+ vec4 second = blenderImageSample(bp1_${p}, uv, clipImage);
7078
+ return vBlenderPaletteIndex == 0 ? first : second;
7079
+ }
7080
+ void main() {`))}const u=p=>o.outputs[p]?.global,m=[];o.surface==="ShaderNodeEmission"?(m.push(["#include <color_fragment>","diffuseColor = vec4(0.0, 0.0, 0.0, 1.0);",!1]),m.push(["#include <emissivemap_fragment>",`totalEmissiveRadiance = ${u("Color")}.rgb * ${u("Strength")};`,!1]),m.push(["#include <opaque_fragment>","outgoingLight = totalEmissiveRadiance;",!0])):o.surface==="closure"?(m.push(["#include <color_fragment>","diffuseColor = vec4(0.0, 0.0, 0.0, 1.0);",!1]),m.push(["#include <emissivemap_fragment>","totalEmissiveRadiance = vec3(0.0);",!1])):(m.push(["#include <color_fragment>",`diffuseColor.rgb = ${u("Base Color")}.rgb;`,!1]),m.push(["#include <alphamap_fragment>",`diffuseColor.a = ${u("Alpha")};`,!1]),m.push(["#include <metalnessmap_fragment>",`roughnessFactor = ${u("Roughness")};`,!0]),m.push(["#include <metalnessmap_fragment>",`metalnessFactor = ${u("Metallic")};`,!1]),m.push(["#include <emissivemap_fragment>",`totalEmissiveRadiance = ${u("Emission Color")}.rgb * ${u("Emission Strength")};`,!1]),u("Normal")&&m.push(["#include <clearcoat_normal_fragment_begin>",`normal = normalize((viewMatrix * vec4(transpose(blender_from_three) * ${u("Normal")}, 0.0)).xyz);`,!0])),o.closure&&m.push(["#include <opaque_fragment>",`{
7067
7081
  float blenderCoverage = diffuseColor.a;
7068
7082
  vec3 blenderRadiance = bgClosureP * blenderCoverage * outgoingLight + bgClosureE;
7069
7083
  float blenderAlpha = 1.0 - min(bgClosureT + bgClosureP * (1.0 - blenderCoverage), 1.0);
@@ -7073,15 +7087,15 @@ ${o.uvs.map(g=>`${ce(g)} = ${a(r[g]??0)};`).join(`
7073
7087
  outgoingLight = blenderRadiance / max(blenderAlpha, 1e-4);
7074
7088
  #endif
7075
7089
  diffuseColor.a = blenderAlpha;
7076
- }`,!0]);const l=g=>g.replace(/^[ \t]*#include <(\w+)>/gm,(v,w)=>l(Kt[w]??"")),i=l(t.fragmentShader.slice(0,t.fragmentShader.indexOf("void main() {"))),u=new Map([...i.matchAll(/^[ \t]*#define[ \t]+(\w+).*$/gm)].map(g=>[g[1],g[0].trim()])),h=[...new Set([...o.declarations.matchAll(/^[ \t]*#define[ \t]+(\w+)/gm)].map(g=>g[1]))].filter(g=>u.has(g)),_=[...h.map(g=>`#undef ${g}`),o.declarations,...h.flatMap(g=>[`#undef ${g}`,u.get(g)])].join(`
7077
- `);let p=t.fragmentShader.replace("void main() {",`${s}
7078
- ${_}
7090
+ }`,!0]);const f=p=>p.replace(/^[ \t]*#include <(\w+)>/gm,(v,x)=>f(te[x]??"")),i=f(t.fragmentShader.slice(0,t.fragmentShader.indexOf("void main() {"))),c=new Map([...i.matchAll(/^[ \t]*#define[ \t]+(\w+).*$/gm)].map(p=>[p[1],p[0].trim()])),_=[...new Set([...o.declarations.matchAll(/^[ \t]*#define[ \t]+(\w+)/gm)].map(p=>p[1]))].filter(p=>c.has(p)),h=[..._.map(p=>`#undef ${p}`),o.declarations,..._.flatMap(p=>[`#undef ${p}`,c.get(p)])].join(`
7091
+ `);let g=t.fragmentShader.replace("void main() {",`${s}
7092
+ ${h}
7079
7093
  void main() {`).replace("#include <clipping_planes_fragment>",`#include <clipping_planes_fragment>
7080
- blenderGraph();`);for(const[g,v,w]of d){if(!p.includes(g))throw new Error(`three's physical shader has no ${g}`);p=p.replace(g,w?`${v}
7081
- ${g}`:`${g}
7082
- ${v}`)}t.fragmentShader=p}const ea=new ne(1,1);function js(n){n.getDrawingBufferSize(ea)}function Vs(n,t){const e=t.userData.blenderUvChannels;for(const o of[n.map,n.roughnessMap,n.normalMap]){if(!o)continue;const r=o.userData.blenderUvName;let a=r?e?.[r]:0;if(a===void 0){a=9;const s=t.getAttribute("position")?.count;if(s===void 0)throw new Error("A textured Blender draw has no positions");t.getAttribute("uv9")?.count!==s&&t.setAttribute("uv9",new lt(new Float32Array(s*2),2))}o.channel!==a&&(o.channel=a,n.needsUpdate=!0)}}class Bs{constructor(){this.bindings=new Map}get(t,e,o,r,a=""){let s=this.bindings.get(t);if(!s||s.source!==e){this.delete(t),s={source:e,texture:e.clone(),version:-1,disposed:!1},this.bindings.set(t,s);const d=s;r&&r.then(()=>{d.disposed||(d.texture.needsUpdate=!0,d.version=e.version,_t())},()=>{})}const f=o==="REPEAT"?wa:o==="MIRROR"?Oa:Io,c=s.texture.wrapS!==f||s.texture.wrapT!==f;return s.texture.wrapS=s.texture.wrapT=f,s.texture.userData.blenderUvName=a,e.image&&(c||s.version!==e.version)&&(s.texture.needsUpdate=!0,s.version=e.version),s.texture}delete(t){const e=this.bindings.get(t);e&&(e.disposed=!0,e.texture.dispose(),this.bindings.delete(t))}clear(){for(const t of this.bindings.keys())this.delete(t)}}const At=I().finite(),ln=W([At,At,At]),Us=R({coat:At,coat_roughness:At,coat_ior:At,coat_tint:ln,sheen:At,sheen_roughness:At,sheen_tint:ln,anisotropy:At,anisotropy_rotation:At,specular_level:At,specular_tint:ln,film_thickness:At,film_ior:At}).strict(),Ws={coat:0,coat_roughness:.03,coat_ior:1.5,coat_tint:[1,1,1],sheen:0,sheen_roughness:.5,sheen_tint:[1,1,1],anisotropy:0,anisotropy_rotation:0,specular_level:.5,specular_tint:[1,1,1],film_thickness:0,film_ior:1.33},Ft=new WeakMap,na=new WeakMap;function Te(n){const t=na.get(n)??Aa.prototype;return n.onBeforeRender===t.onBeforeRender&&n.onBeforeCompile===t.onBeforeCompile&&n.customProgramCacheKey===t.customProgramCacheKey}function qs(n,t){Ft.has(n)||$n(n),Ft.get(n).blenderWorldExtinction.value.copy(t)}function oa(n){const t=new ae,e=Ft.get(n);$n(t),t.copy(n);const o=Ft.get(t);return e&&(o.blenderCoatIor.value=e.blenderCoatIor.value,o.blenderCoatTint.value.copy(e.blenderCoatTint.value),o.blenderMapClip.value=e.blenderMapClip.value,o.blenderRoughnessClip.value=e.blenderRoughnessClip.value,o.blenderNormalClip.value=e.blenderNormalClip.value,o.blenderWorldExtinction.value.copy(e.blenderWorldExtinction.value)),t}function mo(n,t){if(!(n instanceof ae)||!Ft.has(n)||!Te(n))return null;const e=t??oa(n);if(!Is(n,e))return t||e.dispose(),null;e.copy(n);const o=Ft.get(n),r=Ft.get(e);return r.blenderCoatIor.value=o.blenderCoatIor.value,r.blenderCoatTint.value.copy(o.blenderCoatTint.value),r.blenderMapClip.value=o.blenderMapClip.value,r.blenderRoughnessClip.value=o.blenderRoughnessClip.value,r.blenderNormalClip.value=o.blenderNormalClip.value,r.blenderWorldExtinction.value.copy(o.blenderWorldExtinction.value),e}function $n(n,t,e={}){const o=t??Ws;n.clearcoat=o.coat,n.clearcoatRoughness=o.coat_roughness,n.sheen=o.sheen,n.sheenRoughness=o.sheen_roughness,n.sheenColor.setRGB(...o.sheen_tint,xt),n.anisotropy=o.anisotropy,n.anisotropyRotation=o.anisotropy_rotation*Math.PI*2,n.specularIntensity=o.specular_level*2,n.specularColor.setRGB(...o.specular_tint,xt),n.iridescence=o.film_thickness>0?1:0,n.iridescenceIOR=o.film_ior,n.iridescenceThicknessRange=[o.film_thickness,o.film_thickness];let r=Ft.get(n);if(!r){r={blenderCoatIor:{value:1.5},blenderCoatTint:{value:new Mt(1,1,1)},blenderMapClip:{value:!1},blenderRoughnessClip:{value:!1},blenderNormalClip:{value:!1},blenderWorldExtinction:{value:new b}},Ft.set(n,r);const a=r;n.customProgramCacheKey=()=>`blender-principled-physical-v5${Ds(n)}`,n.onBeforeRender=(s,f,c,d,l)=>{Vs(n,d),Fs(n,d,s,f,c,l,oa),js(s)},n.onBeforeCompile=s=>{const f=new Set([n.map,n.roughnessMap,n.normalMap].flatMap(h=>h?[h.channel]:[]).concat(zs(n)));s.vertexShader=[...f].filter(h=>h>0).sort((h,_)=>h-_).map(h=>h<=3?`#ifndef USE_UV${h}
7083
- attribute vec2 uv${h};
7084
- #endif`:`attribute vec2 uv${h};`).join(`
7094
+ blenderGraph();`);for(const[p,v,x]of m){if(!g.includes(p))throw new Error(`three's physical shader has no ${p}`);g=g.replace(p,x?`${v}
7095
+ ${p}`:`${p}
7096
+ ${v}`)}t.fragmentShader=g}const ua=new Ht(1,1);function Ks(n){n.getDrawingBufferSize(ua)}function da(n,t){const e=t.userData.blenderUvChannels;for(const o of[n.map,n.roughnessMap,n.normalMap]){if(!o)continue;const r=o.userData.blenderUvName;let a=r?e?.[r]:0;if(a===void 0){a=9;const s=t.getAttribute("position")?.count;if(s===void 0)throw new Error("A textured Blender draw has no positions");t.getAttribute("uv9")?.count!==s&&t.setAttribute("uv9",new ft(new Float32Array(s*2),2))}o.channel!==a&&(o.channel=a,n.needsUpdate=!0)}}class Qs{constructor(){this.bindings=new Map}get(t,e,o,r,a=""){let s=this.bindings.get(t);if(!s||s.source!==e){this.delete(t),s={source:e,texture:e.clone(),version:-1,disposed:!1},this.bindings.set(t,s);const m=s;r&&r.then(()=>{m.disposed||(m.texture.needsUpdate=!0,m.version=e.version,mt())},()=>{})}const l=o==="REPEAT"?Ia:o==="MIRROR"?Da:Lo,u=s.texture.wrapS!==l||s.texture.wrapT!==l;return s.texture.wrapS=s.texture.wrapT=l,s.texture.userData.blenderUvName=a,e.image&&(u||s.version!==e.version)&&(s.texture.needsUpdate=!0,s.version=e.version),s.texture}delete(t){const e=this.bindings.get(t);e&&(e.disposed=!0,e.texture.dispose(),this.bindings.delete(t))}clear(){for(const t of this.bindings.keys())this.delete(t)}}const Mt=D().finite(),cn=W([Mt,Mt,Mt]),Js=I({coat:Mt,coat_roughness:Mt,coat_ior:Mt,coat_tint:cn,sheen:Mt,sheen_roughness:Mt,sheen_tint:cn,anisotropy:Mt,anisotropy_rotation:Mt,specular_level:Mt,specular_tint:cn,film_thickness:Mt,film_ior:Mt}).strict(),ti={coat:0,coat_roughness:.03,coat_ior:1.5,coat_tint:[1,1,1],sheen:0,sheen_roughness:.5,sheen_tint:[1,1,1],anisotropy:0,anisotropy_rotation:0,specular_level:.5,specular_tint:[1,1,1],film_thickness:0,film_ior:1.33},Dt=new WeakMap,ma=new WeakMap;function he(n){const t=ma.get(n)??jo.prototype;return n.onBeforeRender===t.onBeforeRender&&n.onBeforeCompile===t.onBeforeCompile&&n.customProgramCacheKey===t.customProgramCacheKey}function ei(n,t){Dt.has(n)||Bn(n),Dt.get(n).blenderWorldExtinction.value.copy(t)}function Vn(n){const t=new Gt,e=Dt.get(n);Bn(t),t.copy(n);const o=Dt.get(t);return e&&(o.blenderCoatIor.value=e.blenderCoatIor.value,o.blenderCoatTint.value.copy(e.blenderCoatTint.value),o.blenderMapClip.value=e.blenderMapClip.value,o.blenderRoughnessClip.value=e.blenderRoughnessClip.value,o.blenderNormalClip.value=e.blenderNormalClip.value,o.blenderWorldExtinction.value.copy(e.blenderWorldExtinction.value)),t}const po=new WeakMap;let ni=0;const oi=new Set(["id","uuid","name","userData","version","_listeners","onBeforeRender","onBeforeCompile","customProgramCacheKey"]),ai=new Set(["id","uuid","name","source","mipmaps","version","_listeners","userData"]),ri=new Set(["map","normalMap","roughnessMap"]),go=n=>{let t=po.get(n);return t===void 0&&(t=++ni,po.set(n,t)),t};function vo(n,t=!1){const e=Dt.get(n);if(!e||!he(n))return null;const o=[],r=(a,s=0)=>{if(a===null||typeof a=="number"||typeof a=="string"||typeof a=="boolean")o.push(a);else if(a===void 0)o.push("undefined");else if(typeof a=="object"||typeof a=="function"){if(s>8){o.push("reference",go(a));return}if(Array.isArray(a)){o.push("array",a.length);for(const l of a)r(l,s+1)}else if(Object.getPrototypeOf(a)===Object.prototype||a instanceof bt||a instanceof Ht||a instanceof b||a instanceof Ee||a instanceof Rn||a instanceof G||a instanceof Ut){o.push("values");for(const l of Object.keys(a).sort())o.push(l),r(a[l],s+1)}else o.push("reference",go(a))}};for(const a of Object.keys(n).sort()){if(oi.has(a))continue;o.push(a);const s=n[a];if(ri.has(a)&&s instanceof vn){if(s.constructor!==vn)return null;s.matrixAutoUpdate&&s.updateMatrix(),o.push("sampled-image"),t&&o.push(s.uuid);for(const l of Object.keys(s).sort())ai.has(l)||(o.push(l),r(s[l]));r(s.userData.blenderUvName??"")}else r(s)}for(const[a,s]of Object.entries(e))o.push(a),r(s.value);return o}function xo(n,t){return n.length===t.length&&n.every((e,o)=>e===t[o])}function bo(n,t,e,o){for(const a of t)da(a,o);const r=Vn(t[0]);return Vs(r,n,t,e,o)?r:(r.dispose(),null)}function yo(n,t){if(!(n instanceof Gt)||!Dt.has(n)||!he(n))return null;const e=t??Vn(n);if(!Us(n,e))return t||e.dispose(),null;e.copy(n);const o=Dt.get(n),r=Dt.get(e);return r.blenderCoatIor.value=o.blenderCoatIor.value,r.blenderCoatTint.value.copy(o.blenderCoatTint.value),r.blenderMapClip.value=o.blenderMapClip.value,r.blenderRoughnessClip.value=o.blenderRoughnessClip.value,r.blenderNormalClip.value=o.blenderNormalClip.value,r.blenderWorldExtinction.value.copy(o.blenderWorldExtinction.value),e}function Bn(n,t,e={}){const o=t??ti;n.clearcoat=o.coat,n.clearcoatRoughness=o.coat_roughness,n.sheen=o.sheen,n.sheenRoughness=o.sheen_roughness,n.sheenColor.setRGB(...o.sheen_tint,xt),n.anisotropy=o.anisotropy,n.anisotropyRotation=o.anisotropy_rotation*Math.PI*2,n.specularIntensity=o.specular_level*2,n.specularColor.setRGB(...o.specular_tint,xt),n.iridescence=o.film_thickness>0?1:0,n.iridescenceIOR=o.film_ior,n.iridescenceThicknessRange=[o.film_thickness,o.film_thickness];let r=Dt.get(n);if(!r){r={blenderCoatIor:{value:1.5},blenderCoatTint:{value:new bt(1,1,1)},blenderMapClip:{value:!1},blenderRoughnessClip:{value:!1},blenderNormalClip:{value:!1},blenderWorldExtinction:{value:new b}},Dt.set(n,r);const a=r;n.customProgramCacheKey=()=>`blender-principled-physical-v5${Ws(n)}`,n.onBeforeRender=(s,l,u,m,f)=>{da(n,m),Gs(n,m,s,l,u,f,Vn),Ks(s)},n.onBeforeCompile=s=>{const l=new Set([n.map,n.roughnessMap,n.normalMap].flatMap(_=>_?[_.channel]:[]).concat(qs(n)));s.vertexShader=[...l].filter(_=>_>0).sort((_,h)=>_-h).map(_=>_<=3?`#ifndef USE_UV${_}
7097
+ attribute vec2 uv${_};
7098
+ #endif`:`attribute vec2 uv${_};`).join(`
7085
7099
  `)+`
7086
7100
  `+s.vertexShader,Object.assign(s.uniforms,a),s.fragmentShader=`uniform float blenderCoatIor;
7087
7101
  uniform vec3 blenderWorldExtinction;
@@ -7094,27 +7108,27 @@ attribute vec2 uv${h};
7094
7108
  if (clipImage && (any(lessThan(uv, vec2(0.0))) || any(greaterThan(uv, vec2(1.0))))) pixel = vec4(0.0);
7095
7109
  return pixel;
7096
7110
  }
7097
- `+s.fragmentShader;const c=Kt.lights_physical_fragment.replace("material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );","material.specularF90 = 1.0;").replace("material.clearcoatF0 = vec3( 0.04 );","material.clearcoatF0 = vec3( pow2( ( blenderCoatIor - 1.0 ) / ( blenderCoatIor + 1.0 ) ) );"),d=Kt.normal_fragment_maps.replace("normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;","vec3 blenderBaseNormal = normal; normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; normal.y *= normalScale.y < 0.0 ? -1.0 : 1.0;").replace("normal = normalize( normalMatrix * normal );","normal = normalize(mix(blenderBaseNormal, normalize(normalMatrix * normal), max(0.0, normalScale.x)));").replace("mapN.xy *= normalScale;","mapN.xy *= normalScale; mapN.z = mix(1.0, mapN.z, clamp(normalScale.x, 0.0, 1.0));").replaceAll("texture2D( normalMap, vNormalMapUv )","blenderImageSample(normalMap, vNormalMapUv, blenderNormalClip)"),l=Kt.map_fragment.replace("texture2D( map, vMapUv )","blenderImageSample(map, vMapUv, blenderMapClip)").replace("diffuseColor *= sampledDiffuseColor;","diffuseColor.rgb *= sampledDiffuseColor.rgb;"),i=Kt.roughnessmap_fragment.replace("texture2D( roughnessMap, vRoughnessMapUv )","blenderImageSample(roughnessMap, vRoughnessMapUv, blenderRoughnessClip)"),u=Kt.lights_fragment_begin.replace("getPointLightInfo( pointLight, geometryPosition, directLight );","getPointLightInfo( pointLight, geometryPosition, directLight ); directLight.color *= exp(-blenderWorldExtinction * length(pointLight.position-geometryPosition));").replace("getSpotLightInfo( spotLight, geometryPosition, directLight );","getSpotLightInfo( spotLight, geometryPosition, directLight ); directLight.color *= exp(-blenderWorldExtinction * length(spotLight.position-geometryPosition));").replace("getDirectionalLightInfo( directionalLight, directLight );","getDirectionalLightInfo( directionalLight, directLight ); directLight.color *= blenderInfiniteTransmission();").replace("rectAreaLight = rectAreaLights[ i ];","rectAreaLight = rectAreaLights[ i ]; rectAreaLight.color *= exp(-blenderWorldExtinction * length(rectAreaLight.position-geometryPosition));").replace("getAmbientLightIrradiance( ambientLightColor )","getAmbientLightIrradiance( ambientLightColor ) * blenderInfiniteTransmission()"),m=Kt.lights_fragment_maps.replaceAll(/(getIBL(?:Irradiance|Radiance|AnisotropyRadiance)\([^;]+\))/g,"$1 * blenderInfiniteTransmission()");s.fragmentShader=s.fragmentShader.replace("#include <lights_physical_fragment>",c).replace("#include <lights_fragment_begin>",u).replace("#include <lights_fragment_maps>",m).replace("#include <normal_fragment_maps>",d).replace("#include <map_fragment>",l).replace("#include <roughnessmap_fragment>",i).replace("vec3 Fcc = F_Schlick",`
7111
+ `+s.fragmentShader;const u=te.lights_physical_fragment.replace("material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );","material.specularF90 = 1.0;").replace("material.clearcoatF0 = vec3( 0.04 );","material.clearcoatF0 = vec3( pow2( ( blenderCoatIor - 1.0 ) / ( blenderCoatIor + 1.0 ) ) );"),m=te.normal_fragment_maps.replace("normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;","vec3 blenderBaseNormal = normal; normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; normal.y *= normalScale.y < 0.0 ? -1.0 : 1.0;").replace("normal = normalize( normalMatrix * normal );","normal = normalize(mix(blenderBaseNormal, normalize(normalMatrix * normal), max(0.0, normalScale.x)));").replace("mapN.xy *= normalScale;","mapN.xy *= normalScale; mapN.z = mix(1.0, mapN.z, clamp(normalScale.x, 0.0, 1.0));").replaceAll("texture2D( normalMap, vNormalMapUv )","blenderImageSample(normalMap, vNormalMapUv, blenderNormalClip)"),f=te.map_fragment.replace("texture2D( map, vMapUv )","blenderImageSample(map, vMapUv, blenderMapClip)").replace("diffuseColor *= sampledDiffuseColor;","diffuseColor.rgb *= sampledDiffuseColor.rgb;"),i=te.roughnessmap_fragment.replace("texture2D( roughnessMap, vRoughnessMapUv )","blenderImageSample(roughnessMap, vRoughnessMapUv, blenderRoughnessClip)"),c=te.lights_fragment_begin.replace("getPointLightInfo( pointLight, geometryPosition, directLight );","getPointLightInfo( pointLight, geometryPosition, directLight ); directLight.color *= exp(-blenderWorldExtinction * length(pointLight.position-geometryPosition));").replace("getSpotLightInfo( spotLight, geometryPosition, directLight );","getSpotLightInfo( spotLight, geometryPosition, directLight ); directLight.color *= exp(-blenderWorldExtinction * length(spotLight.position-geometryPosition));").replace("getDirectionalLightInfo( directionalLight, directLight );","getDirectionalLightInfo( directionalLight, directLight ); directLight.color *= blenderInfiniteTransmission();").replace("rectAreaLight = rectAreaLights[ i ];","rectAreaLight = rectAreaLights[ i ]; rectAreaLight.color *= exp(-blenderWorldExtinction * length(rectAreaLight.position-geometryPosition));").replace("getAmbientLightIrradiance( ambientLightColor )","getAmbientLightIrradiance( ambientLightColor ) * blenderInfiniteTransmission()"),d=te.lights_fragment_maps.replaceAll(/(getIBL(?:Irradiance|Radiance|AnisotropyRadiance)\([^;]+\))/g,"$1 * blenderInfiniteTransmission()");s.fragmentShader=s.fragmentShader.replace("#include <lights_physical_fragment>",u).replace("#include <lights_fragment_begin>",c).replace("#include <lights_fragment_maps>",d).replace("#include <normal_fragment_maps>",m).replace("#include <map_fragment>",f).replace("#include <roughnessmap_fragment>",i).replace("vec3 Fcc = F_Schlick",`
7098
7112
  // Blender's slab_transmittance_at_angle (gpu_shader_material_principled.glsl):
7099
7113
  // Beer-Lambert attenuation through a refracting coat at this view angle.
7100
7114
  float coatPath = blenderCoatIor * inversesqrt(max(1e-8,
7101
7115
  blenderCoatIor * blenderCoatIor - (1.0 - dotNVcc * dotNVcc)));
7102
7116
  outgoingLight *= mix(vec3(1.0), pow(max(blenderCoatTint, vec3(0.0)), vec3(coatPath)), material.clearcoat);
7103
- vec3 Fcc = F_Schlick`),Ls(n,s)},na.set(n,{onBeforeRender:n.onBeforeRender,onBeforeCompile:n.onBeforeCompile,customProgramCacheKey:n.customProgramCacheKey}),n.needsUpdate=!0}r.blenderCoatIor.value=Math.max(1,o.coat_ior),r.blenderCoatTint.value.setRGB(...o.coat_tint,xt),r.blenderMapClip.value=e.map===!0,r.blenderRoughnessClip.value=e.roughness===!0,r.blenderNormalClip.value=e.normal===!0}function Ln(n){const t=r=>{if(!(!r||typeof r!="object")){if("kind"in r&&["direction","window","sky"].includes(String(r.kind)))throw new Error(`World volume spatial input ${r.kind} is not implemented`);for(const a of Object.values(r))t(a)}};t(n);const e=ct(n)(new b);if(!(typeof e=="number"?[e]:e.toArray()).every(Number.isFinite))throw new Error("World volume input is not finite");return e}function se(n){const t=Ln(n);if(typeof t!="number")throw new Error("World volume scalar input resolved to a color");return Math.max(0,t)}function Ie(n){const t=Ln(n);return(typeof t=="number"?new b().setScalar(t):t.clone()).max(new b)}function Hs(n){if(n<800)return new b(5.413294490189271,0,0);if(n>=12e3)return new b(.8262954810464208,.9945080501520986,1.566307710274283);const t=[965,1167,1449,1902,3315,6365].filter(a=>n>=a).length,e=[[1619.19106,-.00205010916,5.02995757],[2488.45471,-.00111330907,3.22621544],[3341.43193,-.000486551192,1.76486769],[4094.61742,-.000127446582,.725731635],[4670.28036,291258199e-13,.126703442],[4595.09185,287495649e-13,.15034502],[3787.1745,935907826e-14,.399075871]][t],o=[[-488.999748,.000604330754,-.0755807526],[-755.994277,.000316730098,.478306139],[-1023.63977,.00012022347,.936662319],[-1265.71316,487340896e-14,1.27054498],[-1425.29332,-401150431e-13,1.43972784],[-1175.54822,-216378048e-13,1.30408023],[-500.799571,-459832026e-14,1.09098763]][t],r=[[596945309e-19,-485742887e-16,-970622247e-13,-.00407936148],[240430366e-19,555021075e-16,-.000198503712,.0289312858],[-140949732e-19,189878968e-15,-.000356632824,.0910767778],[-361460868e-19,284822009e-15,-.000493211319,.15672344],[-197075738e-19,175359352e-15,-.000250542825,-.0222783266],[-161997957e-21,-164216008e-16,.000386216271,-.738077418],[672650283e-21,-273078809e-16,.000424098264,-.752335691]][t];return new b(e[0]/n+e[1]*n+e[2],o[0]/n+o[1]*n+o[2],((r[0]*n+r[1])*n+r[2])*n+r[3]).max(new b)}function _o(n){if(!n?.volume?.length)return null;const t={extinction:new b,emission:new b,lobes:[]};for(const e of n.volume){const o=se(e.weight);if(o===0)continue;const r=Ie(e.color),a=se(e.density),s=new b,f=new b;if(e.kind==="absorption"&&s.set(1-r.x,1-r.y,1-r.z).max(new b).multiplyScalar(a),e.kind==="scatter"||e.kind==="principled"){f.copy(r).multiplyScalar(a);const c=e.kind==="principled"?"HENYEY_GREENSTEIN":e.phase;if(!["HENYEY_GREENSTEIN","DRAINE","RAYLEIGH"].includes(c))throw new Error(`World volume ${c} phase is not implemented`);const d=Ln(e.anisotropy);if(typeof d!="number")throw new Error("World volume anisotropy must be scalar");t.lobes.push({coefficient:f.clone().multiplyScalar(o),g:c==="RAYLEIGH"?0:wt.clamp(d,-.999,.999),alpha:c==="RAYLEIGH"?1:c==="DRAINE"?se(e.alpha):0})}if(e.kind==="principled"){const c=Ie(e.absorption_color);s.set(Math.max(1-r.x,0)*Math.max(1-Math.sqrt(c.x),0),Math.max(1-r.y,0)*Math.max(1-Math.sqrt(c.y),0),Math.max(1-r.z,0)*Math.max(1-Math.sqrt(c.z),0)).multiplyScalar(a);const d=se(e.blackbody_intensity);if(d>.001){const l=se(e.temperature),i=5670373e-20/Math.PI*(1+d*(l**4-1));t.emission.add(Hs(l).multiply(Ie(e.blackbody_tint)).multiplyScalar(i*o))}}(e.kind==="principled"||e.kind==="emission")&&t.emission.add((e.kind==="emission"?r:Ie(e.emission_color)).multiplyScalar(se(e.emission_strength)*o)),t.extinction.add(s.add(f).multiplyScalar(o))}for(const e of["x","y","z"])if(t.extinction[e]===0&&t.emission[e]>0)throw new Error("Unbounded emissive World volume with zero extinction has divergent radiance");return t}class Gs{constructor(t){this.medium=t,this.target=new Ma(1,1,{type:En,depthBuffer:!1}),this.geometry=new Do(2,2),this.scene=new Ta,this.camera=new Sa}render(t,e,o,r){if(!e.depthTexture)throw new Error("World volume render requires surface depth");const a={surface:{value:e.texture},depth:{value:e.depthTexture},inverseProjection:{value:r.projectionMatrixInverse},cameraWorld:{value:r.matrixWorld},orthographic:{value:r.isOrthographicCamera===!0},sigma:{value:this.medium.extinction},emission:{value:this.medium.emission}};let s="",f="",c=0,d=2;o.traverseVisible(m=>{if(!(m instanceof _n||m instanceof hn||m instanceof ke))return;const h=m,_=c++,p=h.getWorldPosition(new b);a[`lp${_}`]={value:p},a[`lc${_}`]={value:h.color.clone().multiplyScalar(h.intensity)},s+=`uniform vec3 lp${_}, lc${_};
7104
- `;let g="1.0",v="1.0";if(h instanceof hn&&(a[`ld${_}`]={value:h.target.getWorldPosition(new b).sub(p).normalize()},a[`cone${_}`]={value:new ne(Math.cos(h.angle),Math.cos(h.angle*(1-h.penumbra)))},s+=`uniform vec3 ld${_}; uniform vec2 cone${_};
7105
- `,v=`smoothstep(cone${_}.x, max(cone${_}.x+1e-6,cone${_}.y),dot(-L,ld${_}))`),!(h instanceof ke)&&h.castShadow&&h.shadow.map){if(++d>t.capabilities.maxTextures)throw new Error("World volume shadow samplers exceed this GPU texture-unit limit");a[`sm${_}`]={value:h.shadow.map.texture},a[`sx${_}`]={value:h.shadow.matrix},a[`ss${_}`]={value:h.shadow.mapSize},a[`sb${_}`]={value:h.shadow.bias},a[`sn${_}`]={value:h.shadow.camera.near},a[`sf${_}`]={value:h.shadow.camera.far},s+=`uniform sampler2D sm${_}; uniform mat4 sx${_}; uniform vec2 ss${_}; uniform float sb${_},sn${_},sf${_};
7106
- `,g=h instanceof _n?`getPointShadow(sm${_},ss${_},1.0,sb${_},1.0,sx${_}*vec4(p,1.0),sn${_},sf${_})`:`getShadow(sm${_},ss${_},1.0,sb${_},1.0,sx${_}*vec4(p,1.0))`}if(h instanceof ke){const w=new q().extractRotation(h.matrixWorld);a[`lx${_}`]={value:new b(h.width,0,0).applyMatrix4(w)},a[`ly${_}`]={value:new b(0,h.height,0).applyMatrix4(w)},a[`ln${_}`]={value:new b(0,0,-1).transformDirection(w)},s+=`uniform vec3 lx${_},ly${_},ln${_};
7107
- `,f+=`for(int ax=0;ax<4;ax++) for(int ay=0;ay<4;ay++) {
7108
- vec3 delta=lp${_}+lx${_}*((float(ax)+.5)/4.-.5)+ly${_}*((float(ay)+.5)/4.-.5)-p;
7117
+ vec3 Fcc = F_Schlick`),Zs(n,s)},ma.set(n,{onBeforeRender:n.onBeforeRender,onBeforeCompile:n.onBeforeCompile,customProgramCacheKey:n.customProgramCacheKey}),n.needsUpdate=!0}r.blenderCoatIor.value=Math.max(1,o.coat_ior),r.blenderCoatTint.value.setRGB(...o.coat_tint,xt),r.blenderMapClip.value=e.map===!0,r.blenderRoughnessClip.value=e.roughness===!0,r.blenderNormalClip.value=e.normal===!0}function Un(n){const t=r=>{if(!(!r||typeof r!="object")){if("kind"in r&&["direction","window","sky"].includes(String(r.kind)))throw new Error(`World volume spatial input ${r.kind} is not implemented`);for(const a of Object.values(r))t(a)}};t(n);const e=ut(n)(new b);if(!(typeof e=="number"?[e]:e.toArray()).every(Number.isFinite))throw new Error("World volume input is not finite");return e}function se(n){const t=Un(n);if(typeof t!="number")throw new Error("World volume scalar input resolved to a color");return Math.max(0,t)}function ke(n){const t=Un(n);return(typeof t=="number"?new b().setScalar(t):t.clone()).max(new b)}function si(n){if(n<800)return new b(5.413294490189271,0,0);if(n>=12e3)return new b(.8262954810464208,.9945080501520986,1.566307710274283);const t=[965,1167,1449,1902,3315,6365].filter(a=>n>=a).length,e=[[1619.19106,-.00205010916,5.02995757],[2488.45471,-.00111330907,3.22621544],[3341.43193,-.000486551192,1.76486769],[4094.61742,-.000127446582,.725731635],[4670.28036,291258199e-13,.126703442],[4595.09185,287495649e-13,.15034502],[3787.1745,935907826e-14,.399075871]][t],o=[[-488.999748,.000604330754,-.0755807526],[-755.994277,.000316730098,.478306139],[-1023.63977,.00012022347,.936662319],[-1265.71316,487340896e-14,1.27054498],[-1425.29332,-401150431e-13,1.43972784],[-1175.54822,-216378048e-13,1.30408023],[-500.799571,-459832026e-14,1.09098763]][t],r=[[596945309e-19,-485742887e-16,-970622247e-13,-.00407936148],[240430366e-19,555021075e-16,-.000198503712,.0289312858],[-140949732e-19,189878968e-15,-.000356632824,.0910767778],[-361460868e-19,284822009e-15,-.000493211319,.15672344],[-197075738e-19,175359352e-15,-.000250542825,-.0222783266],[-161997957e-21,-164216008e-16,.000386216271,-.738077418],[672650283e-21,-273078809e-16,.000424098264,-.752335691]][t];return new b(e[0]/n+e[1]*n+e[2],o[0]/n+o[1]*n+o[2],((r[0]*n+r[1])*n+r[2])*n+r[3]).max(new b)}function wo(n){if(!n?.volume?.length)return null;const t={extinction:new b,emission:new b,lobes:[]};for(const e of n.volume){const o=se(e.weight);if(o===0)continue;const r=ke(e.color),a=se(e.density),s=new b,l=new b;if(e.kind==="absorption"&&s.set(1-r.x,1-r.y,1-r.z).max(new b).multiplyScalar(a),e.kind==="scatter"||e.kind==="principled"){l.copy(r).multiplyScalar(a);const u=e.kind==="principled"?"HENYEY_GREENSTEIN":e.phase;if(!["HENYEY_GREENSTEIN","DRAINE","RAYLEIGH"].includes(u))throw new Error(`World volume ${u} phase is not implemented`);const m=Un(e.anisotropy);if(typeof m!="number")throw new Error("World volume anisotropy must be scalar");t.lobes.push({coefficient:l.clone().multiplyScalar(o),g:u==="RAYLEIGH"?0:Ot.clamp(m,-.999,.999),alpha:u==="RAYLEIGH"?1:u==="DRAINE"?se(e.alpha):0})}if(e.kind==="principled"){const u=ke(e.absorption_color);s.set(Math.max(1-r.x,0)*Math.max(1-Math.sqrt(u.x),0),Math.max(1-r.y,0)*Math.max(1-Math.sqrt(u.y),0),Math.max(1-r.z,0)*Math.max(1-Math.sqrt(u.z),0)).multiplyScalar(a);const m=se(e.blackbody_intensity);if(m>.001){const f=se(e.temperature),i=5670373e-20/Math.PI*(1+m*(f**4-1));t.emission.add(si(f).multiply(ke(e.blackbody_tint)).multiplyScalar(i*o))}}(e.kind==="principled"||e.kind==="emission")&&t.emission.add((e.kind==="emission"?r:ke(e.emission_color)).multiplyScalar(se(e.emission_strength)*o)),t.extinction.add(s.add(l).multiplyScalar(o))}for(const e of["x","y","z"])if(t.extinction[e]===0&&t.emission[e]>0)throw new Error("Unbounded emissive World volume with zero extinction has divergent radiance");return t}class ii{constructor(t){this.medium=t,this.target=new Ca(1,1,{type:Dn,depthBuffer:!1}),this.geometry=new Vo(2,2),this.scene=new Bo,this.camera=new za}render(t,e,o,r){if(!e.depthTexture)throw new Error("World volume render requires surface depth");const a={surface:{value:e.texture},depth:{value:e.depthTexture},inverseProjection:{value:r.projectionMatrixInverse},cameraWorld:{value:r.matrixWorld},orthographic:{value:r.isOrthographicCamera===!0},sigma:{value:this.medium.extinction},emission:{value:this.medium.emission}};let s="",l="",u=0,m=2;o.traverseVisible(d=>{if(!(d instanceof pn||d instanceof gn||d instanceof Ve))return;const _=d,h=u++,g=_.getWorldPosition(new b);a[`lp${h}`]={value:g},a[`lc${h}`]={value:_.color.clone().multiplyScalar(_.intensity)},s+=`uniform vec3 lp${h}, lc${h};
7118
+ `;let p="1.0",v="1.0";if(_ instanceof gn&&(a[`ld${h}`]={value:_.target.getWorldPosition(new b).sub(g).normalize()},a[`cone${h}`]={value:new Ht(Math.cos(_.angle),Math.cos(_.angle*(1-_.penumbra)))},s+=`uniform vec3 ld${h}; uniform vec2 cone${h};
7119
+ `,v=`smoothstep(cone${h}.x, max(cone${h}.x+1e-6,cone${h}.y),dot(-L,ld${h}))`),!(_ instanceof Ve)&&_.castShadow&&_.shadow.map){if(++m>t.capabilities.maxTextures)throw new Error("World volume shadow samplers exceed this GPU texture-unit limit");a[`sm${h}`]={value:_.shadow.map.texture},a[`sx${h}`]={value:_.shadow.matrix},a[`ss${h}`]={value:_.shadow.mapSize},a[`sb${h}`]={value:_.shadow.bias},a[`sn${h}`]={value:_.shadow.camera.near},a[`sf${h}`]={value:_.shadow.camera.far},s+=`uniform sampler2D sm${h}; uniform mat4 sx${h}; uniform vec2 ss${h}; uniform float sb${h},sn${h},sf${h};
7120
+ `,p=_ instanceof pn?`getPointShadow(sm${h},ss${h},1.0,sb${h},1.0,sx${h}*vec4(p,1.0),sn${h},sf${h})`:`getShadow(sm${h},ss${h},1.0,sb${h},1.0,sx${h}*vec4(p,1.0))`}if(_ instanceof Ve){const x=new G().extractRotation(_.matrixWorld);a[`lx${h}`]={value:new b(_.width,0,0).applyMatrix4(x)},a[`ly${h}`]={value:new b(0,_.height,0).applyMatrix4(x)},a[`ln${h}`]={value:new b(0,0,-1).transformDirection(x)},s+=`uniform vec3 lx${h},ly${h},ln${h};
7121
+ `,l+=`for(int ax=0;ax<4;ax++) for(int ay=0;ay<4;ay++) {
7122
+ vec3 delta=lp${h}+lx${h}*((float(ax)+.5)/4.-.5)+ly${h}*((float(ay)+.5)/4.-.5)-p;
7109
7123
  float d=length(delta); vec3 L=delta/max(d,1e-6);
7110
- sum+=lc${_}*exp(-sigma*d)*phase(dot(L,ray))*max(dot(-L,ln${_}),0.)*
7111
- length(lx${_})*length(ly${_})/(16.*max(d*d,1e-4)); }
7112
- `}else a[`cut${_}`]={value:h.distance},a[`decay${_}`]={value:h.decay},s+=`uniform float cut${_},decay${_};
7113
- `,f+=`{ vec3 delta=lp${_}-p; float d=length(delta); vec3 L=delta/max(d,1e-6);
7114
- float cutoff=cut${_}>0.?pow(clamp(1.-pow(d/cut${_},4.),0.,1.),2.):1.;
7115
- sum+=lc${_}*exp(-sigma*d)*phase(dot(L,ray))*${v}*${g}*cutoff/max(pow(d,decay${_}),.01); }
7116
- `});let l="vec3 result=vec3(0.);";this.medium.lobes.forEach((m,h)=>{a[`scatter${h}`]={value:m.coefficient},a[`g${h}`]={value:m.g},a[`a${h}`]={value:m.alpha},s+=`uniform vec3 scatter${h}; uniform float g${h},a${h};
7117
- `,l+=`result+=scatter${h}*(1.-g${h}*g${h})*(1.+a${h}*c*c)/(12.56637061436*(1.+a${h}*(1.+2.*g${h}*g${h})/3.)*pow(1.+g${h}*g${h}-2.*g${h}*c,1.5));`});const i=this.medium.extinction.toArray().filter(m=>m>0);a.range={value:i.length?20/Math.min(...i):1},this.material?.dispose(),this.material=new Pn({uniforms:a,depthTest:!1,depthWrite:!1,toneMapped:!1,defines:{USE_SHADOWMAP:"",NUM_DIR_LIGHT_SHADOWS:0,NUM_SPOT_LIGHT_SHADOWS:0,NUM_POINT_LIGHT_SHADOWS:0,NUM_SPOT_LIGHT_COORDS:0},vertexShader:"varying vec2 vUv; void main(){vUv=uv;gl_Position=vec4(position.xy,0.,1.);}",fragmentShader:`
7124
+ sum+=lc${h}*exp(-sigma*d)*phase(dot(L,ray))*max(dot(-L,ln${h}),0.)*
7125
+ length(lx${h})*length(ly${h})/(16.*max(d*d,1e-4)); }
7126
+ `}else a[`cut${h}`]={value:_.distance},a[`decay${h}`]={value:_.decay},s+=`uniform float cut${h},decay${h};
7127
+ `,l+=`{ vec3 delta=lp${h}-p; float d=length(delta); vec3 L=delta/max(d,1e-6);
7128
+ float cutoff=cut${h}>0.?pow(clamp(1.-pow(d/cut${h},4.),0.,1.),2.):1.;
7129
+ sum+=lc${h}*exp(-sigma*d)*phase(dot(L,ray))*${v}*${p}*cutoff/max(pow(d,decay${h}),.01); }
7130
+ `});let f="vec3 result=vec3(0.);";this.medium.lobes.forEach((d,_)=>{a[`scatter${_}`]={value:d.coefficient},a[`g${_}`]={value:d.g},a[`a${_}`]={value:d.alpha},s+=`uniform vec3 scatter${_}; uniform float g${_},a${_};
7131
+ `,f+=`result+=scatter${_}*(1.-g${_}*g${_})*(1.+a${_}*c*c)/(12.56637061436*(1.+a${_}*(1.+2.*g${_}*g${_})/3.)*pow(1.+g${_}*g${_}-2.*g${_}*c,1.5));`});const i=this.medium.extinction.toArray().filter(d=>d>0);a.range={value:i.length?20/Math.min(...i):1},this.material?.dispose(),this.material=new In({uniforms:a,depthTest:!1,depthWrite:!1,toneMapped:!1,defines:{USE_SHADOWMAP:"",NUM_DIR_LIGHT_SHADOWS:0,NUM_SPOT_LIGHT_SHADOWS:0,NUM_POINT_LIGHT_SHADOWS:0,NUM_SPOT_LIGHT_COORDS:0},vertexShader:"varying vec2 vUv; void main(){vUv=uv;gl_Position=vec4(position.xy,0.,1.);}",fragmentShader:`
7118
7132
  #include <common>
7119
7133
  #include <packing>
7120
7134
  #include <shadowmap_pars_fragment>
@@ -7122,8 +7136,8 @@ attribute vec2 uv${h};
7122
7136
  uniform mat4 inverseProjection,cameraWorld; uniform bool orthographic;
7123
7137
  uniform vec3 sigma,emission; uniform float range;
7124
7138
  ${s}
7125
- vec3 phase(float c){${l} return result;}
7126
- vec3 incident(vec3 p,vec3 ray){vec3 sum=vec3(0.);${f}return sum;}
7139
+ vec3 phase(float c){${f} return result;}
7140
+ vec3 incident(vec3 p,vec3 ray){vec3 sum=vec3(0.);${l}return sum;}
7127
7141
  float integral(float s,float d){float x=s*d;return x<.001 ? d*(1.-x*.5+x*x/6.) : (1.-exp(-x))/s;}
7128
7142
  void main(){
7129
7143
  float z=texture2D(depth,vUv).r; vec4 base=texture2D(surface,vUv);
@@ -7144,10 +7158,10 @@ attribute vec2 uv${h};
7144
7158
  radiance+=incident(origin+ray*t,ray)*exp(-sigma*t)*(hi-lo);
7145
7159
  }
7146
7160
  gl_FragColor=vec4(radiance,base.a+(1.-base.a)*(1.-dot(tr,vec3(1./3.))));
7147
- }`}),this.scene.clear(),this.scene.add(new kt(this.geometry,this.material)),this.target.setSize(e.width,e.height);const u=t.getRenderTarget();try{t.setRenderTarget(this.target),t.render(this.scene,this.camera)}finally{t.setRenderTarget(u)}return this.target}dispose(){this.material?.dispose(),this.geometry.dispose(),this.target.dispose(),this.scene.clear()}}const Xs=R({object:z(),group:z(),groupIndex:I().int().nonnegative(),count:I().int().nonnegative(),digest:z(),alertMode:Q(["NONE","ACTIVE","ALL"]),unchanged:Z(!0).optional(),weightsBase64:z().optional(),alertBase64:z().optional()}).strict();function Ys(n){const e=n<0?0:n>1?1:n,o=(.5+.5*e)**1.5,[r,a,s]=Zs(2/3*(1-e)),f=new Mt;return f.setRGB((r*o)**(1/1.5),(a*o)**(1/1.5),(s*o)**(1/1.5),Ht),f}function Zs(n){const t=(n%1+1)%1,e=Math.floor(t*6),o=t*6-e;switch(e%6){case 0:return[1,o,0];case 1:return[1-o,1,0];case 2:return[0,1,o];case 3:return[0,1-o,1];case 4:return[o,0,1];default:return[1,0,1-o]}}const Ks=0;function ho(n){const t=atob(n),e=new Uint8Array(t.length);for(let o=0;o<t.length;o++)e[o]=t.charCodeAt(o);return e}class Qs{constructor(){this.group=new ut,this.mesh=null,this.material=null,this.geometry=null,this.held=null,this.signature="",this.group.name="BlenderWeightOverlay"}apply(t,e,o){if(t===null||e===null||!e.isMesh||o===null)return this.clear(),this.signature="",null;const r=`${t.object}:${t.group}`;if(t.unchanged===!0){if(this.held?.key!==r)return this.clear(),`weights: the session sent a reference to ${r} that this overlay does not hold; the colours reappear on the next change to the mesh or the group`}else{if(t.weightsBase64===void 0||t.alertBase64===void 0)return this.clear(),`weights: ${r} carried neither an array nor a reference`;const h=ho(t.weightsBase64);this.held={key:r,weights:new Float32Array(h.buffer,h.byteOffset,t.count),alerts:ho(t.alertBase64)}}const a=this.held;if(a===null)return null;const s=`${r}:${t.digest}:${e.geometry.uuid}:${t.alertMode}:${o.elements.join(",")}`;if(s===this.signature&&this.mesh!==null)return null;this.signature=s,this.clear();const f=e.geometry.clone(),c=f.getAttribute("position"),d=f.getAttribute("blenderVertex");if(d===void 0)return f.dispose(),"weights: the presented geometry carries no per-vertex Blender index (`blenderVertex`), so the weights cannot be laid over it";const l=new Float32Array(c.count*3),i=new Mt().setHex(Ks,Ht);for(let h=0;h<c.count;h++){const _=d.getX(h),g=t.alertMode!=="NONE"&&a.alerts[_]===1?i:Ys(a.weights[_]??0);l[h*3]=g.r,l[h*3+1]=g.g,l[h*3+2]=g.b}f.setAttribute("color",new lt(l,3)),f.deleteAttribute("blenderVertex");const u=new je({vertexColors:!0,polygonOffset:!0,polygonOffsetFactor:-1,polygonOffsetUnits:-1}),m=new kt(f,u);return m.name=`${t.object}:weights`,m.frustumCulled=!1,m.matrixAutoUpdate=!1,m.matrix.copy(o),m.matrix.decompose(m.position,m.quaternion,m.scale),this.geometry=f,this.material=u,this.mesh=m,this.group.add(m),null}clear(){this.mesh&&this.group.remove(this.mesh),this.geometry?.dispose(),this.material?.dispose(),this.mesh=null,this.geometry=null,this.material=null}dispose(){this.clear(),this.held=null,this.signature=""}}const De=I().finite(),Js=j(W([De,De,De,De])).length(4),ti=20,po=[16724818,9165824,2658559];function ei(n){const t=e=>Math.min(255,Math.max(0,Math.floor(.75*e+63.75)-60))/255;return new Mt().setRGB(t(n>>16&255),t(n>>8&255),t(n&255),Ht)}function aa(){return new Ea({vertexColors:!0,depthTest:!1,depthWrite:!1,transparent:!0,toneMapped:!1})}function ni(){const n=[],t=[],e=new Mt(0,0,0),o=(a,s,f,c,d)=>{for(const l of[a,s]){const i=[0,0,0];i[f]=l*c,n.push(...i),t.push(d.r,d.g,d.b)}};for(let a=0;a<3;a++){const s=new Mt().setHex(po[a],Ht);o(1,.85,a,1,s),o(.85,.25,a,1,e),o(1,.85,a,-1,ei(po[a])),o(.85,.25,a,-1,e)}const r=new re;return r.setAttribute("position",new Rt(n,3)),r.setAttribute("color",new Rt(t,3)),new zo(r,aa())}function oi(){const t=[],e=[],o=new Mt(1,0,0),r=new Mt(1,1,1);for(let s=0;s<12;s++){const f=(s+1)%2===0?r:o;for(const c of[s,s+1]){const d=2*Math.PI*c/12;t.push(.5*Math.cos(d),.5*Math.sin(d),0),e.push(f.r,f.g,f.b)}}const a=new re;return a.setAttribute("position",new Rt(t,3)),a.setAttribute("color",new Rt(e,3)),new zo(a,aa())}class ai{constructor(){this.group=new ut,this.anchor=new ut,this.lines=ni(),this.circle=oi(),this.seen=null,this.size=new ne,this.scratch=new b,this.parentQuat=new St,this.group.name="BlenderCursor",this.present(!1),this.anchor.matrixAutoUpdate=!1,this.group.add(this.anchor,this.circle),this.anchor.add(this.lines);for(const t of[this.lines,this.circle])t.renderOrder=1001,t.frustumCulled=!1;this.lines.onBeforeRender=(t,e,o)=>this.fit(t,o),this.circle.onBeforeRender=(t,e,o)=>this.fit(t,o)}apply(t){if(t===void 0){this.present(!1);return}this.anchor.matrix.set(...t.flat()),this.anchor.updateMatrixWorld(!0),this.present(!0)}present(t){this.anchor.visible=t,this.circle.visible=t}show(t){const[e,o,r,a]=t.rotation;this.anchor.matrix.compose(new b(...t.location),new St(o,r,a,e),new b(1,1,1)),this.anchor.updateMatrixWorld(!0),this.present(!0)}fit(t,e){this.seen={camera:e,canvas:t.domElement},t.getSize(this.size);const o=Math.max(this.size.y,1),r=this.scratch.setFromMatrixPosition(this.anchor.matrixWorld);let a;if(e.isOrthographicCamera){const f=e;a=(f.top-f.bottom)/f.zoom/o}else{const f=e;a=2*Math.max(-r.applyMatrix4(e.matrixWorldInverse).z,1e-6)*Math.tan(wt.degToRad(f.fov)/2)/f.zoom/o}const s=a*ti;this.lines.scale.setScalar(s),this.lines.updateMatrixWorld(!0),this.circle.position.setFromMatrixPosition(this.anchor.matrix),this.group.getWorldQuaternion(this.parentQuat).invert(),e.getWorldQuaternion(this.circle.quaternion).premultiply(this.parentQuat),this.circle.scale.setScalar(s),this.circle.updateMatrixWorld(!0)}placementAt(t,e,o,r,a){const s=this.seen;if(s===null||o!==s.canvas)return null;const f=s.canvas.getBoundingClientRect(),c=new ne((t-f.left)/Math.max(f.width,1)*2-1,-((e-f.top)/Math.max(f.height,1))*2+1),d=new Pa;d.setFromCamera(c,s.camera);const l=_=>{for(let p=_;p!==null;p=p.parent)if(!p.visible)return!1;return!0},i=d.intersectObject(r,!0).find(_=>_.object.isMesh&&a(_.object)&&l(_.object));let u=i?i.point.clone():null;if(u===null){const _=new b().setFromMatrixPosition(this.anchor.matrixWorld),p=s.camera.getWorldDirection(new b),g=s.camera.getWorldPosition(new b),v=_.clone().sub(g).dot(p);v<=0&&_.addScaledVector(p,-2*v+(v===0?1:0)),u=d.ray.intersectPlane(new Zt().setFromNormalAndCoplanarPoint(p,_),new b)}if(u===null)return null;r.updateWorldMatrix(!0,!1);const m=r.worldToLocal(u),h=r.getWorldQuaternion(new St).invert().multiply(s.camera.getWorldQuaternion(new St));return{location:[m.x,m.y,m.z],rotation:[h.w,h.x,h.y,h.z]}}dispose(){for(const t of[this.lines,this.circle])t.geometry.dispose(),t.material.dispose();this.seen=null}}const Yt=I().finite(),ri=R({display:Q(["PLAIN_AXES","ARROWS","SINGLE_ARROW","CIRCLE","CUBE","SPHERE","CONE","IMAGE"]),size:Yt,image:R({name:z().nullable(),offset:W([Yt,Yt]),depth:Q(["DEFAULT","FRONT","BACK"]),side:Q(["DOUBLE_SIDED","FRONT","BACK"]),perspective:et(),orthographic:et(),axis_aligned:et(),opacity:Yt.nullable(),tint:W([Yt,Yt,Yt]).default([1,1,1]),premultiplied:et().default(!1)}).optional()}),Dt={selected:15554304,active:16752680,camera:0,light:0,lightAlpha:80/255,empty:0},si=1,st=(n,t,e)=>n.push(t[0],t[1],t[2],e[0],e[1],e[2]);function ht(n,t){return Array.from({length:t},(e,o)=>{const r=2*Math.PI*o/t;return[n*Math.cos(r),n*Math.sin(r)]})}function yt(n,t,e=0,o=!1){const r=o?2:1;for(let a=0;a<Math.floor(t.length/r);a++){const s=t[a*r%t.length],f=t[(a*r+1)%t.length];st(n,[s[0],s[1],e],[f[0],f[1],e])}}function ii(n){if(!n.isMesh||n.userData.volterOverrideStandDown)return;n.userData.volterOverrideStandDown=!0;const t=n.onBeforeRender.bind(n),e=n.onAfterRender.bind(n),o=new q;let r=!1;n.onBeforeRender=(a,s,f,c,d,l)=>{t(a,s,f,c,d,l),s.overrideMaterial&&(o.copy(n.matrixWorld),n.matrixWorld.makeScale(0,0,0),r=!0)},n.onAfterRender=(a,s,f,c,d,l)=>{r&&(n.matrixWorld.copy(o),r=!1),e(a,s,f,c,d,l)}}class li{constructor(){this.cameras=new ut,this.lights=new ut,this.empties=new ut,this.lineMaterials=new Map,this.drawn=new Map,this.fillMaterials=new Map,this.scratch=new b,this.size=new ne,this.parentQuat=new St,this.cameras.name="BlenderCameras",this.lights.name="BlenderLights",this.empties.name="BlenderEmpties"}apply(t){const e=new Set;for(const o of t.objects){const r=o.selected?o.name===t.active?Dt.active:Dt.selected:o.type==="CAMERA"?Dt.camera:o.type==="LIGHT"?Dt.light:Dt.empty,a=o.type==="CAMERA"&&o.name!==t.lookingThrough?t.cameras[o.name]:void 0,s=o.type==="LIGHT"&&o.light?t.lights[o.light]:void 0,f=o.type==="EMPTY"?t.empties[o.name]:void 0;if(!a&&!s&&!f)continue;e.add(o.name);const c=s&&o.light?t.lightDistances[o.light]??null:null,d=f?.image?.name?t.image(f.image.name):null,l=JSON.stringify([d?[d.texture.uuid,d.width,d.height]:null,o.matrix,r,a,s,c,f,a?[o.name===t.sceneCamera,t.renderAspect]:null]),i=this.drawn.get(o.name),u=t.presented(o.name);if(i?.key===l){for(const g of i.parts)g.userData.volterPicksAs=u;continue}i&&this.remove(i.parts);const m=new q().set(...o.matrix.flat()),h=a?this.cameras:s?this.lights:this.empties,_=new Set(h.children);a?this.camera(a,m,r,o.name===t.sceneCamera,t.renderAspect):s?this.light(s,m,r,c):f&&this.empty(f,m,r,d);const p=h.children.filter(g=>!_.has(g));for(const g of p)g.userData.volterPicksAs=u,g.traverse(ii);this.drawn.set(o.name,{key:l,parts:p})}for(const[o,r]of this.drawn)e.has(o)||(this.remove(r.parts),this.drawn.delete(o))}remove(t){for(const e of t)e.removeFromParent(),e.geometry?.dispose(),e.userData.volterOwnMaterial&&e.material.dispose()}camera(t,e,o,r,a){const s=t.display_size,c=(t.sensor_fit==="AUTO"?a>=1:t.sensor_fit==="HORIZONTAL")?[1,1/a]:[a,1];let d,l,i,u;if(t.type==="ORTHO")i=[.5*t.ortho_scale*c[0],.5*t.ortho_scale*c[1]],u=[t.shift_x*t.ortho_scale,t.shift_y*t.ortho_scale],l=-s,d=.5*t.ortho_scale;else{const A=.5*(t.sensor_fit==="VERTICAL"?t.sensor_height:t.sensor_width),M=new b().setFromMatrixScale(e);if(M.x===0||M.y===0||M.z===0)return;d=s/2/((1/M.x+1/M.y+1/M.z)/3),l=d*t.lens/-A,i=[d*c[0],d*c[1]],u=[t.shift_x*d*2,t.shift_y*d*2]}const m=[[u[0]+i[0],u[1]+i[1],l],[u[0]+i[0],u[1]-i[1],l],[u[0]-i[0],u[1]-i[1],l],[u[0]-i[0],u[1]+i[1],l]],h=[];for(let A=0;A<4;A++)st(h,m[A],m[(A+1)%4]),st(h,m[A],[0,0,0]);const _=.7*d,p=.1*d,g=u[1]+i[1]+p,v=[[u[0]-_,g,l],[u[0]+_,g,l],[u[0],g+_,l]],w=fn(e);this.cameras.add(this.lines(h,o,1,w));let x;if(r){const A=new re;A.setAttribute("position",new Rt(v.flat(),3)),x=new kt(A,this.fill(o)),x.matrixAutoUpdate=!1,x.matrix.copy(w)}else{const A=[];for(let M=0;M<3;M++)st(A,v[M],v[(M+1)%3]);x=this.lines(A,o,1,w)}const T=new b,y=x.onBeforeRender.bind(x);x.onBeforeRender=(A,M,P,F,U,H)=>{T.setFromMatrixPosition(w).applyMatrix4(this.cameras.matrixWorld);const G=P.getWorldPosition(this.scratch).distanceToSquared(T)>1e-8;x.matrix.copy(w),G||x.matrix.scale(new b(0,0,0)),x.updateMatrixWorld(!0),y(A,M,P,F,U,H)},this.cameras.add(x)}light(t,e,o,r){const a=new b().setFromMatrixPosition(e),s=[];st(s,[a.x,a.y,a.z],[a.x,a.y,0]),this.lights.add(this.lines(s,Dt.light,Dt.lightAlpha,new q));const f=[];yt(f,ht(1.35,4)),this.lights.add(this.screen(f,Dt.light,Dt.lightAlpha,new b(a.x,a.y,0)));const c=[],d=9;if(yt(c,ht(d*.3,4)),yt(c,ht(d,16),0,!0),yt(c,ht(d*1.33,20),0,!0),t.type==="SUN")for(const[u,m]of ht(d,8))st(c,[u*1.6,m*1.6,0],[u*1.9,m*1.9,0]),st(c,[u*2.2,m*2.2,0],[u*2.5,m*2.5,0]);this.lights.add(this.screen(c,o,1,a));const l=fn(e),i=[];if(t.type==="SUN")st(i,[0,0,0],[0,0,-20]);else if(t.type==="AREA"){const u=(t.size??1)/2,m=(t.shape==="RECTANGLE"||t.shape==="ELLIPSE"?t.size_y??t.size??1:t.size??1)/2;t.shape==="DISK"||t.shape==="ELLIPSE"?yt(i,ht(1,32).map(([h,_])=>[h*u,_*m])):yt(i,[[u,m],[-u,m],[-u,-m],[u,-m]])}if(i.length>0&&this.lights.add(this.lines(i,o,1,e.clone())),r&&(t.type==="SPOT"||t.type==="AREA")){const u=new b(0,0,-1).transformDirection(e),m=g=>a.clone().addScaledVector(u,g),[h,_]=r,p=[];st(p,m(h).toArray(),m(_).toArray()),this.lights.add(this.lines(p,o,1,new q));for(const g of[h,_]){const v=[];yt(v,ht(1.2,4)),this.lights.add(this.screen(v,o,1,m(g)))}}if(t.type==="SPOT"){const u=(t.spot_size??Math.PI/4)/2,m=Math.cos(u),h=t.spot_blend??.15,_=m*h-m-h,p=Math.sqrt((m*m-m*m*_*_)/(_*_-m*m*_*_)),g=Math.sqrt(1-m*m),v=fn(e).multiply(new q().makeScale(10,10,10)),w=[];yt(w,ht(g,32),-m),yt(w,ht(g*p,32),-m),this.lights.add(this.lines(w,o,1,v.clone())),this.lights.add(this.silhouette(g,m,o,v))}if((t.type==="POINT"||t.type==="SPOT")&&(t.radius??0)>0){const u=[];yt(u,ht(t.radius,32)),this.lights.add(this.facing(u,o,new b().setFromMatrixPosition(l)))}}empty(t,e,o,r){const a=t.size,s=[],f=(d,l)=>{const i=ht(1,l);for(let u=0;u<l;u++){const[m,h]=i[u],[_,p]=i[(u+1)%l],g=(v,w)=>d==="xy"?[v,w,0]:d==="xz"?[v,0,w]:[0,v,w];st(s,g(m,h),g(_,p))}};switch(t.display){case"PLAIN_AXES":st(s,[0,-1,0],[0,1,0]),st(s,[-1,0,0],[1,0,0]),st(s,[0,0,-1],[0,0,1]);break;case"SINGLE_ARROW":{st(s,[0,0,0],[0,0,.75]);for(const[d,l]of[[.035,.035],[-.035,.035],[-.035,-.035],[.035,-.035]])st(s,[0,0,1],[d,l,.75]);yt(s,[[.035,.035],[-.035,.035],[-.035,-.035],[.035,-.035]],.75);break}case"CUBE":for(const[d,l]of fi)st(s,go[d],go[l]);break;case"CIRCLE":f("xz",64);break;case"SPHERE":f("xy",32),f("xz",32),f("yz",32);break;case"CONE":{const d=ht(1,8);for(let l=0;l<8;l++){const[i,u]=d[l],[m,h]=d[(l+1)%8];st(s,[i,0,u],[0,2,0]),st(s,[i,0,u],[m,0,h])}break}case"ARROWS":for(let d=0;d<3;d++){const l=[0,0,0];l[d]=1,st(s,[0,0,0],l)}break;case"IMAGE":this.imageEmpty(t,e,o,r);return}const c=e.clone().multiply(new q().makeScale(a,a,a));this.empties.add(this.lines(s,o,1,c)),t.display==="ARROWS"&&this.axisNames(e,a,o)}silhouette(t,e,o,r){const a=this.lines(new Array(192).fill(0),o,1,r);a.frustumCulled=!1;const s=a.geometry.getAttribute("instanceStart").data,f=ht(1,32).map(([m,h])=>new b(m*t,h*t,-e)),c=new b,d=new q,l=new b,i=new b,u=new b;return this.onDraw(a,(m,h)=>{d.copy(a.matrixWorld).invert();const _=h.isOrthographicCamera;_?h.getWorldDirection(c).negate().transformDirection(d):c.setFromMatrixPosition(h.matrixWorld).applyMatrix4(d);const p=s.array;let g=!1;for(let v=0;v<32;v++){const w=f[v];l.crossVectors(w,f[(v+31)%32]),i.crossVectors(f[(v+1)%32],w),_?u.copy(c):u.copy(c).sub(w);const x=l.dot(u)>0!=i.dot(u)>0;(p[v*6+3]!==0||p[v*6+5]!==0)!==x&&(g=!0),p.set([0,0,0,x?w.x:0,x?w.y:0,x?w.z:0],v*6)}g&&(s.needsUpdate=!0,_t())}),a}imageEmpty(t,e,o,r){const a=t.image;if(!a)return;const s=r?.width??0,f=r?.height??0,c=s>0&&f>0?s>=f?[1,f/s]:[s/f,1]:[1,1],d=new b,l=new b,i=new b;e.extractBasis(d,l,i),d.multiplyScalar(c[0]*.5*t.size),l.multiplyScalar(c[1]*.5*t.size);const u=new b().setFromMatrixPosition(e).addScaledVector(d,a.offset[0]*2+1).addScaledVector(l,a.offset[1]*2+1),m=new q().makeBasis(d,l,i.clone()).setPosition(u),h=[];yt(h,[[-1,-1],[1,-1],[1,1],[-1,1]]);const _=this.lines(h,o,1,m),p=i.clone().normalize(),g=new b,v=new b,w=(P,F)=>{const U=P.isOrthographicCamera===!0;if(U?!a.orthographic:!a.perspective)return!1;if(!F)return!0;const H=p.clone().transformDirection(this.empties.matrixWorld);P.getWorldDirection(v);let G,J;if(U)G=H.dot(v.clone().negate()),J=1e-5;else{const ft=u.clone().applyMatrix4(this.empties.matrixWorld);G=H.dot(g.setFromMatrixPosition(P.matrixWorld).sub(ft)),J=0}return!(a.side==="FRONT"&&G<J||a.side==="BACK"&&G>-J||a.axis_aligned&&H.clone().projectOnPlane(v).lengthSq()>1e-5)},x=(P,F)=>{const U=P.onBeforeRender.bind(P);P.onBeforeRender=(H,G,J,ft,O,B)=>{P.matrix.copy(m),w(J,F)||P.matrix.scale(new b(0,0,0)),P.updateMatrixWorld(!0),U(H,G,J,ft,O,B)}};if(x(_,!1),this.empties.add(_),!r||a.opacity!==null&&a.opacity<=0)return;const T=a.opacity!==null,y=a.depth==="BACK",A=new je({map:r.texture,side:Be,transparent:T&&!y,opacity:a.opacity??1,alphaTest:T?0:.05,toneMapped:!1,depthTest:a.depth==="DEFAULT",depthWrite:a.depth==="DEFAULT"&&!T});A.color.setRGB(...a.tint,xt),T&&y&&(A.blending=Na,A.blendSrc=Ra,A.blendDst=Ia),A.onBeforeCompile=P=>{const F=a.premultiplied?`if ( sampledDiffuseColor.a > 0.0 && sampledDiffuseColor.a < 1.0 ) sampledDiffuseColor.rgb /= sampledDiffuseColor.a;
7148
- `:"";P.fragmentShader=P.fragmentShader.replace("#include <map_fragment>",`vec4 sampledDiffuseColor = texture2D( map, vMapUv );
7149
- ${F}diffuseColor *= sampledDiffuseColor;`).replace("#include <alphatest_fragment>",T?"#include <alphatest_fragment>":`#include <alphatest_fragment>
7150
- diffuseColor.a = 1.0;`)},A.customProgramCacheKey=()=>`volter-blender-image:${a.premultiplied}:${T}`;const M=new kt(new Do(2,2),A);M.matrixAutoUpdate=!1,M.matrix.copy(m),M.renderOrder=a.depth==="FRONT"?1e3:a.depth==="BACK"?-1e3:0,M.userData.volterOwnMaterial=!0,x(M,!0),this.empties.add(M)}axisNames(t,e,o){const r=[new b,new b,new b];t.extractBasis(r[0],r[1],r[2]);for(let a=0;a<3;a++){const s=r[a].length()*e,f=new b(0,0,0);f.setComponent(a,1.25*e),f.applyMatrix4(t);const c=new b(0,0,0);c.setComponent(a,e),c.applyMatrix4(t);const d=[];for(let u=1;u<=6;u++)yt(d,ht(.007*(4*u/6)*s,4));this.empties.add(this.facing(d,o,c));const l=ci[a],i=[];for(let u=0;u+1<l.length;u+=2){const[m,h]=l[u],[_,p]=l[u+1];st(i,[m*4*s,h*4*s,0],[_*4*s,p*4*s,0])}this.empties.add(this.facing(i,o,f))}}material(t,e){const o=`${t}:${e}`;let r=this.lineMaterials.get(o);return r||(r=new So({color:t,linewidth:si,transparent:e<1,opacity:e,depthTest:!0,depthWrite:e>=1,toneMapped:!1}),this.lineMaterials.set(o,r)),r}fill(t){let e=this.fillMaterials.get(t);return e||(e=new je({color:t,side:Be,toneMapped:!1}),this.fillMaterials.set(t,e)),e}lines(t,e,o,r){const a=new To().setPositions(t),s=new Po(a,this.material(e,o));return s.matrixAutoUpdate=!1,s.matrix.copy(r),s.computeLineDistances(),s}screen(t,e,o,r){const a=this.lines(t,e,o,new q);return a.matrixAutoUpdate=!0,a.position.copy(r),a.scale.setScalar(0),a.frustumCulled=!1,this.onDraw(a,(s,f)=>this.face(a,s,f,!0)),a}facing(t,e,o){const r=this.lines(t,e,1,new q);return r.matrixAutoUpdate=!0,r.position.copy(o),this.onDraw(r,(a,s)=>this.face(r,a,s,!1)),r}onDraw(t,e){const o=t,r=o.onBeforeRender.bind(o);o.onBeforeRender=(a,s,f,c,d,l)=>{e(a,f),r(a,s,f,c,d,l)}}face(t,e,o,r){t.parent?.getWorldQuaternion(this.parentQuat).invert(),o.getWorldQuaternion(t.quaternion).premultiply(this.parentQuat);let a=1;if(r){e.getSize(this.size);const s=Math.max(this.size.y,1),f=this.scratch.setFromMatrixPosition(t.matrixWorld);if(o.isOrthographicCamera){const c=o;a=(c.top-c.bottom)/c.zoom/s}else{const c=o;a=2*Math.max(-f.applyMatrix4(o.matrixWorldInverse).z,1e-6)*Math.tan(wt.degToRad(c.fov)/2)/c.zoom/s}}t.scale.setScalar(a),t.updateMatrixWorld(!0)}dispose(){for(const t of this.drawn.values())this.remove(t.parts);this.drawn.clear();for(const t of this.lineMaterials.values())t.dispose();for(const t of this.fillMaterials.values())t.dispose();this.lineMaterials.clear(),this.fillMaterials.clear()}}function fn(n){const t=new b,e=new St;return n.decompose(t,e,new b),new q().compose(t,e,new b(1,1,1))}const go=[[-1,-1,-1],[1,-1,-1],[1,1,-1],[-1,1,-1],[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],fi=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]],ci=[[[.9,1],[-1,-1],[-.9,1],[1,-1]].map(([n,t])=>[n*.0215,t*.025]),[[-1,1],[0,-.1],[1,1],[0,-.1],[0,-.1],[0,-1]].map(([n,t])=>[n*.0175,t*.025]),[[-.95,1],[.95,1],[.95,1],[.95,.9],[.95,.9],[-1,-.9],[-1,-.9],[-1,-1],[-1,-1],[1,-1]].map(([n,t])=>[n*.02,t*.025])],pt=I().finite(),vo=R({name:z(),type:z(),lens:pt,sensor_width:pt,sensor_height:pt,sensor_fit:Q(["AUTO","HORIZONTAL","VERTICAL"]),ortho_scale:pt,clip_start:pt,clip_end:pt,shift_x:pt,shift_y:pt,matrix:j(W([pt,pt,pt,pt])).length(4),passepartout:pt.default(0),display_size:pt.default(1)}),ui={opening:.5,min:.1657359312880715,max:44.98528137423857},ze={passepartout:"#000000",back:"#3d3d3d",overlay:"#000000",redalert:"#991616"};function di(n,t,e,o){const r=a=>Math.min(1,Math.max(-1,a));return[r(n[0]-e/(2*t)),r(n[1]+o/(2*t))]}function xo(n,t,e,o){const r=n.type==="ORTHO",a=n.sensor_fit==="VERTICAL"?n.sensor_height:n.sensor_width,s=n.sensor_fit==="AUTO"?t>=e:n.sensor_fit==="HORIZONTAL",f=(r?n.ortho_scale:a/n.lens)/2*o;return s?[f,f*e/t]:[f*t/e,f]}function mi(n,t,e,o,r,a){const s=Math.max(e.width,1),f=Math.max(e.height,1),[c,d]=xo(n,s,f,1/o),[l,i]=xo(n,a,1,1),m=2*((n.sensor_fit==="AUTO"?a>=1:n.sensor_fit==="HORIZONTAL")?l:i),h=l/c,_=i/d,p=-2*r[0]*o,g=2*r[1]*o,v=n.shift_x*m-p*2*c,w=n.shift_y*m+g*2*d,x=new q().set(...n.matrix.flat()).premultiply(t),T=new b,y=new St;return x.decompose(T,y,new b),{name:n.name,position:T.toArray(),quaternion:[y.x,y.y,y.z,y.w],projection:n.type==="ORTHO"?"orthographic":"perspective",window:{left:v-c,right:v+c,top:w+d,bottom:w-d},near:n.clip_start,far:n.clip_end,frame:{left:.5-h/2+p,top:.5-_/2+g,width:h,height:_},passepartout:{color:ze.passepartout,opacity:n.passepartout},border:{solid:ze.back,dashed:ze.overlay,locked:ze.redalert}}}const _i={color:[.8,.8,.8,1],roughness:.5,metallic:0},hi=`
7161
+ }`}),this.scene.clear(),this.scene.add(new Ft(this.geometry,this.material)),this.target.setSize(e.width,e.height);const c=t.getRenderTarget();try{t.setRenderTarget(this.target),t.render(this.scene,this.camera)}finally{t.setRenderTarget(c)}return this.target}dispose(){this.material?.dispose(),this.geometry.dispose(),this.target.dispose(),this.scene.clear()}}const li=I({object:z(),group:z(),groupIndex:D().int().nonnegative(),count:D().int().nonnegative(),digest:z(),alertMode:J(["NONE","ACTIVE","ALL"]),unchanged:K(!0).optional(),weightsBase64:z().optional(),alertBase64:z().optional()}).strict();function fi(n){const e=n<0?0:n>1?1:n,o=(.5+.5*e)**1.5,[r,a,s]=ci(2/3*(1-e)),l=new bt;return l.setRGB((r*o)**(1/1.5),(a*o)**(1/1.5),(s*o)**(1/1.5),Zt),l}function ci(n){const t=(n%1+1)%1,e=Math.floor(t*6),o=t*6-e;switch(e%6){case 0:return[1,o,0];case 1:return[1-o,1,0];case 2:return[0,1,o];case 3:return[0,1-o,1];case 4:return[o,0,1];default:return[1,0,1-o]}}const ui=0;function Oo(n){const t=atob(n),e=new Uint8Array(t.length);for(let o=0;o<t.length;o++)e[o]=t.charCodeAt(o);return e}class di{constructor(){this.group=new dt,this.mesh=null,this.material=null,this.geometry=null,this.held=null,this.signature="",this.group.name="BlenderWeightOverlay"}apply(t,e,o){if(t===null||e===null||!e.isMesh||o===null)return this.clear(),this.signature="",null;const r=`${t.object}:${t.group}`;if(t.unchanged===!0){if(this.held?.key!==r)return this.clear(),`weights: the session sent a reference to ${r} that this overlay does not hold; the colours reappear on the next change to the mesh or the group`}else{if(t.weightsBase64===void 0||t.alertBase64===void 0)return this.clear(),`weights: ${r} carried neither an array nor a reference`;const _=Oo(t.weightsBase64);this.held={key:r,weights:new Float32Array(_.buffer,_.byteOffset,t.count),alerts:Oo(t.alertBase64)}}const a=this.held;if(a===null)return null;const s=`${r}:${t.digest}:${e.geometry.uuid}:${t.alertMode}:${o.elements.join(",")}`;if(s===this.signature&&this.mesh!==null)return null;this.signature=s,this.clear();const l=e.geometry.clone(),u=l.getAttribute("position"),m=l.getAttribute("blenderVertex");if(m===void 0)return l.dispose(),"weights: the presented geometry carries no per-vertex Blender index (`blenderVertex`), so the weights cannot be laid over it";const f=new Float32Array(u.count*3),i=new bt().setHex(ui,Zt);for(let _=0;_<u.count;_++){const h=m.getX(_),p=t.alertMode!=="NONE"&&a.alerts[h]===1?i:fi(a.weights[h]??0);f[_*3]=p.r,f[_*3+1]=p.g,f[_*3+2]=p.b}l.setAttribute("color",new ft(f,3)),l.deleteAttribute("blenderVertex");const c=new We({vertexColors:!0,polygonOffset:!0,polygonOffsetFactor:-1,polygonOffsetUnits:-1}),d=new Ft(l,c);return d.name=`${t.object}:weights`,d.frustumCulled=!1,d.matrixAutoUpdate=!1,d.matrix.copy(o),d.matrix.decompose(d.position,d.quaternion,d.scale),this.geometry=l,this.material=c,this.mesh=d,this.group.add(d),null}clear(){this.mesh&&this.group.remove(this.mesh),this.geometry?.dispose(),this.material?.dispose(),this.mesh=null,this.geometry=null,this.material=null}dispose(){this.clear(),this.held=null,this.signature=""}}const Fe=D().finite(),mi=V(W([Fe,Fe,Fe,Fe])).length(4),_i=20,Ao=[16724818,9165824,2658559];function hi(n){const t=e=>Math.min(255,Math.max(0,Math.floor(.75*e+63.75)-60))/255;return new bt().setRGB(t(n>>16&255),t(n>>8&255),t(n&255),Zt)}function _a(){return new Fa({vertexColors:!0,depthTest:!1,depthWrite:!1,transparent:!0,toneMapped:!1})}function pi(){const n=[],t=[],e=new bt(0,0,0),o=(a,s,l,u,m)=>{for(const f of[a,s]){const i=[0,0,0];i[l]=f*u,n.push(...i),t.push(m.r,m.g,m.b)}};for(let a=0;a<3;a++){const s=new bt().setHex(Ao[a],Zt);o(1,.85,a,1,s),o(.85,.25,a,1,e),o(1,.85,a,-1,hi(Ao[a])),o(.85,.25,a,-1,e)}const r=new Yt;return r.setAttribute("position",new It(n,3)),r.setAttribute("color",new It(t,3)),new Uo(r,_a())}function gi(){const t=[],e=[],o=new bt(1,0,0),r=new bt(1,1,1);for(let s=0;s<12;s++){const l=(s+1)%2===0?r:o;for(const u of[s,s+1]){const m=2*Math.PI*u/12;t.push(.5*Math.cos(m),.5*Math.sin(m),0),e.push(l.r,l.g,l.b)}}const a=new Yt;return a.setAttribute("position",new It(t,3)),a.setAttribute("color",new It(e,3)),new Uo(a,_a())}class vi{constructor(){this.group=new dt,this.anchor=new dt,this.lines=pi(),this.circle=gi(),this.seen=null,this.size=new Ht,this.scratch=new b,this.parentQuat=new Tt,this.group.name="BlenderCursor",this.present(!1),this.anchor.matrixAutoUpdate=!1,this.group.add(this.anchor,this.circle),this.anchor.add(this.lines);for(const t of[this.lines,this.circle])t.renderOrder=1001,t.frustumCulled=!1;this.lines.onBeforeRender=(t,e,o)=>this.fit(t,o),this.circle.onBeforeRender=(t,e,o)=>this.fit(t,o)}apply(t){if(t===void 0){this.present(!1);return}this.anchor.matrix.set(...t.flat()),this.anchor.updateMatrixWorld(!0),this.present(!0)}present(t){this.anchor.visible=t,this.circle.visible=t}show(t){const[e,o,r,a]=t.rotation;this.anchor.matrix.compose(new b(...t.location),new Tt(o,r,a,e),new b(1,1,1)),this.anchor.updateMatrixWorld(!0),this.present(!0)}fit(t,e){this.seen={camera:e,canvas:t.domElement},t.getSize(this.size);const o=Math.max(this.size.y,1),r=this.scratch.setFromMatrixPosition(this.anchor.matrixWorld);let a;if(e.isOrthographicCamera){const l=e;a=(l.top-l.bottom)/l.zoom/o}else{const l=e;a=2*Math.max(-r.applyMatrix4(e.matrixWorldInverse).z,1e-6)*Math.tan(Ot.degToRad(l.fov)/2)/l.zoom/o}const s=a*_i;this.lines.scale.setScalar(s),this.lines.updateMatrixWorld(!0),this.circle.position.setFromMatrixPosition(this.anchor.matrix),this.group.getWorldQuaternion(this.parentQuat).invert(),e.getWorldQuaternion(this.circle.quaternion).premultiply(this.parentQuat),this.circle.scale.setScalar(s),this.circle.updateMatrixWorld(!0)}placementAt(t,e,o,r,a){const s=this.seen;if(s===null||o!==s.canvas)return null;const l=s.canvas.getBoundingClientRect(),u=new Ht((t-l.left)/Math.max(l.width,1)*2-1,-((e-l.top)/Math.max(l.height,1))*2+1),m=new ka;m.setFromCamera(u,s.camera);const f=h=>{for(let g=h;g!==null;g=g.parent)if(!g.visible)return!1;return!0},i=m.intersectObject(r,!0).find(h=>h.object.isMesh&&a(h.object)&&f(h.object));let c=i?i.point.clone():null;if(c===null){const h=new b().setFromMatrixPosition(this.anchor.matrixWorld),g=s.camera.getWorldDirection(new b),p=s.camera.getWorldPosition(new b),v=h.clone().sub(p).dot(g);v<=0&&h.addScaledVector(g,-2*v+(v===0?1:0)),c=m.ray.intersectPlane(new Ut().setFromNormalAndCoplanarPoint(g,h),new b)}if(c===null)return null;r.updateWorldMatrix(!0,!1);const d=r.worldToLocal(c),_=r.getWorldQuaternion(new Tt).invert().multiply(s.camera.getWorldQuaternion(new Tt));return{location:[d.x,d.y,d.z],rotation:[_.w,_.x,_.y,_.z]}}dispose(){for(const t of[this.lines,this.circle])t.geometry.dispose(),t.material.dispose();this.seen=null}}const Jt=D().finite(),xi=I({display:J(["PLAIN_AXES","ARROWS","SINGLE_ARROW","CIRCLE","CUBE","SPHERE","CONE","IMAGE"]),size:Jt,image:I({name:z().nullable(),offset:W([Jt,Jt]),depth:J(["DEFAULT","FRONT","BACK"]),side:J(["DOUBLE_SIDED","FRONT","BACK"]),perspective:et(),orthographic:et(),axis_aligned:et(),opacity:Jt.nullable(),tint:W([Jt,Jt,Jt]).default([1,1,1]),premultiplied:et().default(!1)}).optional()}),zt={selected:15554304,active:16752680,camera:0,light:0,lightAlpha:80/255,empty:0},bi=1,it=(n,t,e)=>n.push(t[0],t[1],t[2],e[0],e[1],e[2]);function ht(n,t){return Array.from({length:t},(e,o)=>{const r=2*Math.PI*o/t;return[n*Math.cos(r),n*Math.sin(r)]})}function wt(n,t,e=0,o=!1){const r=o?2:1;for(let a=0;a<Math.floor(t.length/r);a++){const s=t[a*r%t.length],l=t[(a*r+1)%t.length];it(n,[s[0],s[1],e],[l[0],l[1],e])}}function yi(n){if(!n.isMesh||n.userData.volterOverrideStandDown)return;n.userData.volterOverrideStandDown=!0;const t=n.onBeforeRender.bind(n),e=n.onAfterRender.bind(n),o=new G;let r=!1;n.onBeforeRender=(a,s,l,u,m,f)=>{t(a,s,l,u,m,f),s.overrideMaterial&&(o.copy(n.matrixWorld),n.matrixWorld.makeScale(0,0,0),r=!0)},n.onAfterRender=(a,s,l,u,m,f)=>{r&&(n.matrixWorld.copy(o),r=!1),e(a,s,l,u,m,f)}}class wi{constructor(){this.cameras=new dt,this.lights=new dt,this.empties=new dt,this.lineMaterials=new Map,this.drawn=new Map,this.fillMaterials=new Map,this.scratch=new b,this.size=new Ht,this.parentQuat=new Tt,this.cameras.name="BlenderCameras",this.lights.name="BlenderLights",this.empties.name="BlenderEmpties"}apply(t){const e=new Set;for(const o of t.objects){const r=o.selected?o.name===t.active?zt.active:zt.selected:o.type==="CAMERA"?zt.camera:o.type==="LIGHT"?zt.light:zt.empty,a=o.type==="CAMERA"&&o.name!==t.lookingThrough?t.cameras[o.name]:void 0,s=o.type==="LIGHT"&&o.light?t.lights[o.light]:void 0,l=o.type==="EMPTY"?t.empties[o.name]:void 0;if(!a&&!s&&!l)continue;e.add(o.name);const u=s&&o.light?t.lightDistances[o.light]??null:null,m=l?.image?.name?t.image(l.image.name):null,f=JSON.stringify([m?[m.texture.uuid,m.width,m.height]:null,o.matrix,r,a,s,u,l,a?[o.name===t.sceneCamera,t.renderAspect]:null]),i=this.drawn.get(o.name),c=t.presented(o.name);if(i?.key===f){for(const p of i.parts)p.userData.volterPicksAs=c;continue}i&&this.remove(i.parts);const d=new G().set(...o.matrix.flat()),_=a?this.cameras:s?this.lights:this.empties,h=new Set(_.children);a?this.camera(a,d,r,o.name===t.sceneCamera,t.renderAspect):s?this.light(s,d,r,u):l&&this.empty(l,d,r,m);const g=_.children.filter(p=>!h.has(p));for(const p of g)p.userData.volterPicksAs=c,p.traverse(yi);this.drawn.set(o.name,{key:f,parts:g})}for(const[o,r]of this.drawn)e.has(o)||(this.remove(r.parts),this.drawn.delete(o))}remove(t){for(const e of t)e.removeFromParent(),e.geometry?.dispose(),e.userData.volterOwnMaterial&&e.material.dispose()}camera(t,e,o,r,a){const s=t.display_size,u=(t.sensor_fit==="AUTO"?a>=1:t.sensor_fit==="HORIZONTAL")?[1,1/a]:[a,1];let m,f,i,c;if(t.type==="ORTHO")i=[.5*t.ortho_scale*u[0],.5*t.ortho_scale*u[1]],c=[t.shift_x*t.ortho_scale,t.shift_y*t.ortho_scale],f=-s,m=.5*t.ortho_scale;else{const O=.5*(t.sensor_fit==="VERTICAL"?t.sensor_height:t.sensor_width),y=new b().setFromMatrixScale(e);if(y.x===0||y.y===0||y.z===0)return;m=s/2/((1/y.x+1/y.y+1/y.z)/3),f=m*t.lens/-O,i=[m*u[0],m*u[1]],c=[t.shift_x*m*2,t.shift_y*m*2]}const d=[[c[0]+i[0],c[1]+i[1],f],[c[0]+i[0],c[1]-i[1],f],[c[0]-i[0],c[1]-i[1],f],[c[0]-i[0],c[1]+i[1],f]],_=[];for(let O=0;O<4;O++)it(_,d[O],d[(O+1)%4]),it(_,d[O],[0,0,0]);const h=.7*m,g=.1*m,p=c[1]+i[1]+g,v=[[c[0]-h,p,f],[c[0]+h,p,f],[c[0],p+h,f]],x=un(e);this.cameras.add(this.lines(_,o,1,x));let w;if(r){const O=new Yt;O.setAttribute("position",new It(v.flat(),3)),w=new Ft(O,this.fill(o)),w.matrixAutoUpdate=!1,w.matrix.copy(x)}else{const O=[];for(let y=0;y<3;y++)it(O,v[y],v[(y+1)%3]);w=this.lines(O,o,1,x)}const S=new b,M=w.onBeforeRender.bind(w);w.onBeforeRender=(O,y,T,P,j,q)=>{S.setFromMatrixPosition(x).applyMatrix4(this.cameras.matrixWorld);const H=T.getWorldPosition(this.scratch).distanceToSquared(S)>1e-8;w.matrix.copy(x),H||w.matrix.scale(new b(0,0,0)),w.updateMatrixWorld(!0),M(O,y,T,P,j,q)},this.cameras.add(w)}light(t,e,o,r){const a=new b().setFromMatrixPosition(e),s=[];it(s,[a.x,a.y,a.z],[a.x,a.y,0]),this.lights.add(this.lines(s,zt.light,zt.lightAlpha,new G));const l=[];wt(l,ht(1.35,4)),this.lights.add(this.screen(l,zt.light,zt.lightAlpha,new b(a.x,a.y,0)));const u=[],m=9;if(wt(u,ht(m*.3,4)),wt(u,ht(m,16),0,!0),wt(u,ht(m*1.33,20),0,!0),t.type==="SUN")for(const[c,d]of ht(m,8))it(u,[c*1.6,d*1.6,0],[c*1.9,d*1.9,0]),it(u,[c*2.2,d*2.2,0],[c*2.5,d*2.5,0]);this.lights.add(this.screen(u,o,1,a));const f=un(e),i=[];if(t.type==="SUN")it(i,[0,0,0],[0,0,-20]);else if(t.type==="AREA"){const c=(t.size??1)/2,d=(t.shape==="RECTANGLE"||t.shape==="ELLIPSE"?t.size_y??t.size??1:t.size??1)/2;t.shape==="DISK"||t.shape==="ELLIPSE"?wt(i,ht(1,32).map(([_,h])=>[_*c,h*d])):wt(i,[[c,d],[-c,d],[-c,-d],[c,-d]])}if(i.length>0&&this.lights.add(this.lines(i,o,1,e.clone())),r&&(t.type==="SPOT"||t.type==="AREA")){const c=new b(0,0,-1).transformDirection(e),d=p=>a.clone().addScaledVector(c,p),[_,h]=r,g=[];it(g,d(_).toArray(),d(h).toArray()),this.lights.add(this.lines(g,o,1,new G));for(const p of[_,h]){const v=[];wt(v,ht(1.2,4)),this.lights.add(this.screen(v,o,1,d(p)))}}if(t.type==="SPOT"){const c=(t.spot_size??Math.PI/4)/2,d=Math.cos(c),_=t.spot_blend??.15,h=d*_-d-_,g=Math.sqrt((d*d-d*d*h*h)/(h*h-d*d*h*h)),p=Math.sqrt(1-d*d),v=un(e).multiply(new G().makeScale(10,10,10)),x=[];wt(x,ht(p,32),-d),wt(x,ht(p*g,32),-d),this.lights.add(this.lines(x,o,1,v.clone())),this.lights.add(this.silhouette(p,d,o,v))}if((t.type==="POINT"||t.type==="SPOT")&&(t.radius??0)>0){const c=[];wt(c,ht(t.radius,32)),this.lights.add(this.facing(c,o,new b().setFromMatrixPosition(f)))}}empty(t,e,o,r){const a=t.size,s=[],l=(m,f)=>{const i=ht(1,f);for(let c=0;c<f;c++){const[d,_]=i[c],[h,g]=i[(c+1)%f],p=(v,x)=>m==="xy"?[v,x,0]:m==="xz"?[v,0,x]:[0,v,x];it(s,p(d,_),p(h,g))}};switch(t.display){case"PLAIN_AXES":it(s,[0,-1,0],[0,1,0]),it(s,[-1,0,0],[1,0,0]),it(s,[0,0,-1],[0,0,1]);break;case"SINGLE_ARROW":{it(s,[0,0,0],[0,0,.75]);for(const[m,f]of[[.035,.035],[-.035,.035],[-.035,-.035],[.035,-.035]])it(s,[0,0,1],[m,f,.75]);wt(s,[[.035,.035],[-.035,.035],[-.035,-.035],[.035,-.035]],.75);break}case"CUBE":for(const[m,f]of Oi)it(s,Mo[m],Mo[f]);break;case"CIRCLE":l("xz",64);break;case"SPHERE":l("xy",32),l("xz",32),l("yz",32);break;case"CONE":{const m=ht(1,8);for(let f=0;f<8;f++){const[i,c]=m[f],[d,_]=m[(f+1)%8];it(s,[i,0,c],[0,2,0]),it(s,[i,0,c],[d,0,_])}break}case"ARROWS":for(let m=0;m<3;m++){const f=[0,0,0];f[m]=1,it(s,[0,0,0],f)}break;case"IMAGE":this.imageEmpty(t,e,o,r);return}const u=e.clone().multiply(new G().makeScale(a,a,a));this.empties.add(this.lines(s,o,1,u)),t.display==="ARROWS"&&this.axisNames(e,a,o)}silhouette(t,e,o,r){const a=this.lines(new Array(192).fill(0),o,1,r);a.frustumCulled=!1;const s=a.geometry.getAttribute("instanceStart").data,l=ht(1,32).map(([d,_])=>new b(d*t,_*t,-e)),u=new b,m=new G,f=new b,i=new b,c=new b;return this.onDraw(a,(d,_)=>{m.copy(a.matrixWorld).invert();const h=_.isOrthographicCamera;h?_.getWorldDirection(u).negate().transformDirection(m):u.setFromMatrixPosition(_.matrixWorld).applyMatrix4(m);const g=s.array;let p=!1;for(let v=0;v<32;v++){const x=l[v];f.crossVectors(x,l[(v+31)%32]),i.crossVectors(l[(v+1)%32],x),h?c.copy(u):c.copy(u).sub(x);const w=f.dot(c)>0!=i.dot(c)>0;(g[v*6+3]!==0||g[v*6+5]!==0)!==w&&(p=!0),g.set([0,0,0,w?x.x:0,w?x.y:0,w?x.z:0],v*6)}p&&(s.needsUpdate=!0,mt())}),a}imageEmpty(t,e,o,r){const a=t.image;if(!a)return;const s=r?.width??0,l=r?.height??0,u=s>0&&l>0?s>=l?[1,l/s]:[s/l,1]:[1,1],m=new b,f=new b,i=new b;e.extractBasis(m,f,i),m.multiplyScalar(u[0]*.5*t.size),f.multiplyScalar(u[1]*.5*t.size);const c=new b().setFromMatrixPosition(e).addScaledVector(m,a.offset[0]*2+1).addScaledVector(f,a.offset[1]*2+1),d=new G().makeBasis(m,f,i.clone()).setPosition(c),_=[];wt(_,[[-1,-1],[1,-1],[1,1],[-1,1]]);const h=this.lines(_,o,1,d),g=i.clone().normalize(),p=new b,v=new b,x=(T,P)=>{const j=T.isOrthographicCamera===!0;if(j?!a.orthographic:!a.perspective)return!1;if(!P)return!0;const q=g.clone().transformDirection(this.empties.matrixWorld);T.getWorldDirection(v);let H,X;if(j)H=q.dot(v.clone().negate()),X=1e-5;else{const ct=c.clone().applyMatrix4(this.empties.matrixWorld);H=q.dot(p.setFromMatrixPosition(T.matrixWorld).sub(ct)),X=0}return!(a.side==="FRONT"&&H<X||a.side==="BACK"&&H>-X||a.axis_aligned&&q.clone().projectOnPlane(v).lengthSq()>1e-5)},w=(T,P)=>{const j=T.onBeforeRender.bind(T);T.onBeforeRender=(q,H,X,ct,A,U)=>{T.matrix.copy(d),x(X,P)||T.matrix.scale(new b(0,0,0)),T.updateMatrixWorld(!0),j(q,H,X,ct,A,U)}};if(w(h,!1),this.empties.add(h),!r||a.opacity!==null&&a.opacity<=0)return;const S=a.opacity!==null,M=a.depth==="BACK",O=new We({map:r.texture,side:Te,transparent:S&&!M,opacity:a.opacity??1,alphaTest:S?0:.05,toneMapped:!1,depthTest:a.depth==="DEFAULT",depthWrite:a.depth==="DEFAULT"&&!S});O.color.setRGB(...a.tint,xt),S&&M&&(O.blending=$a,O.blendSrc=La,O.blendDst=ja),O.onBeforeCompile=T=>{const P=a.premultiplied?`if ( sampledDiffuseColor.a > 0.0 && sampledDiffuseColor.a < 1.0 ) sampledDiffuseColor.rgb /= sampledDiffuseColor.a;
7162
+ `:"";T.fragmentShader=T.fragmentShader.replace("#include <map_fragment>",`vec4 sampledDiffuseColor = texture2D( map, vMapUv );
7163
+ ${P}diffuseColor *= sampledDiffuseColor;`).replace("#include <alphatest_fragment>",S?"#include <alphatest_fragment>":`#include <alphatest_fragment>
7164
+ diffuseColor.a = 1.0;`)},O.customProgramCacheKey=()=>`volter-blender-image:${a.premultiplied}:${S}`;const y=new Ft(new Vo(2,2),O);y.matrixAutoUpdate=!1,y.matrix.copy(d),y.renderOrder=a.depth==="FRONT"?1e3:a.depth==="BACK"?-1e3:0,y.userData.volterOwnMaterial=!0,w(y,!0),this.empties.add(y)}axisNames(t,e,o){const r=[new b,new b,new b];t.extractBasis(r[0],r[1],r[2]);for(let a=0;a<3;a++){const s=r[a].length()*e,l=new b(0,0,0);l.setComponent(a,1.25*e),l.applyMatrix4(t);const u=new b(0,0,0);u.setComponent(a,e),u.applyMatrix4(t);const m=[];for(let c=1;c<=6;c++)wt(m,ht(.007*(4*c/6)*s,4));this.empties.add(this.facing(m,o,u));const f=Ai[a],i=[];for(let c=0;c+1<f.length;c+=2){const[d,_]=f[c],[h,g]=f[c+1];it(i,[d*4*s,_*4*s,0],[h*4*s,g*4*s,0])}this.empties.add(this.facing(i,o,l))}}material(t,e){const o=`${t}:${e}`;let r=this.lineMaterials.get(o);return r||(r=new zo({color:t,linewidth:bi,transparent:e<1,opacity:e,depthTest:!0,depthWrite:e>=1,toneMapped:!1}),this.lineMaterials.set(o,r)),r}fill(t){let e=this.fillMaterials.get(t);return e||(e=new We({color:t,side:Te,toneMapped:!1}),this.fillMaterials.set(t,e)),e}lines(t,e,o,r){const a=new Co().setPositions(t),s=new ko(a,this.material(e,o));return s.matrixAutoUpdate=!1,s.matrix.copy(r),s.computeLineDistances(),s}screen(t,e,o,r){const a=this.lines(t,e,o,new G);return a.matrixAutoUpdate=!0,a.position.copy(r),a.scale.setScalar(0),a.frustumCulled=!1,this.onDraw(a,(s,l)=>this.face(a,s,l,!0)),a}facing(t,e,o){const r=this.lines(t,e,1,new G);return r.matrixAutoUpdate=!0,r.position.copy(o),this.onDraw(r,(a,s)=>this.face(r,a,s,!1)),r}onDraw(t,e){const o=t,r=o.onBeforeRender.bind(o);o.onBeforeRender=(a,s,l,u,m,f)=>{e(a,l),r(a,s,l,u,m,f)}}face(t,e,o,r){t.parent?.getWorldQuaternion(this.parentQuat).invert(),o.getWorldQuaternion(t.quaternion).premultiply(this.parentQuat);let a=1;if(r){e.getSize(this.size);const s=Math.max(this.size.y,1),l=this.scratch.setFromMatrixPosition(t.matrixWorld);if(o.isOrthographicCamera){const u=o;a=(u.top-u.bottom)/u.zoom/s}else{const u=o;a=2*Math.max(-l.applyMatrix4(o.matrixWorldInverse).z,1e-6)*Math.tan(Ot.degToRad(u.fov)/2)/u.zoom/s}}t.scale.setScalar(a),t.updateMatrixWorld(!0)}dispose(){for(const t of this.drawn.values())this.remove(t.parts);this.drawn.clear();for(const t of this.lineMaterials.values())t.dispose();for(const t of this.fillMaterials.values())t.dispose();this.lineMaterials.clear(),this.fillMaterials.clear()}}function un(n){const t=new b,e=new Tt;return n.decompose(t,e,new b),new G().compose(t,e,new b(1,1,1))}const Mo=[[-1,-1,-1],[1,-1,-1],[1,1,-1],[-1,1,-1],[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],Oi=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]],Ai=[[[.9,1],[-1,-1],[-.9,1],[1,-1]].map(([n,t])=>[n*.0215,t*.025]),[[-1,1],[0,-.1],[1,1],[0,-.1],[0,-.1],[0,-1]].map(([n,t])=>[n*.0175,t*.025]),[[-.95,1],[.95,1],[.95,1],[.95,.9],[.95,.9],[-1,-.9],[-1,-.9],[-1,-1],[-1,-1],[1,-1]].map(([n,t])=>[n*.02,t*.025])],pt=D().finite(),So=I({name:z(),type:z(),lens:pt,sensor_width:pt,sensor_height:pt,sensor_fit:J(["AUTO","HORIZONTAL","VERTICAL"]),ortho_scale:pt,clip_start:pt,clip_end:pt,shift_x:pt,shift_y:pt,matrix:V(W([pt,pt,pt,pt])).length(4),passepartout:pt.default(0),display_size:pt.default(1)}),Mi={opening:.5,min:.1657359312880715,max:44.98528137423857},$e={passepartout:"#000000",back:"#3d3d3d",overlay:"#000000",redalert:"#991616"};function Si(n,t,e,o){const r=a=>Math.min(1,Math.max(-1,a));return[r(n[0]-e/(2*t)),r(n[1]+o/(2*t))]}function To(n,t,e,o){const r=n.type==="ORTHO",a=n.sensor_fit==="VERTICAL"?n.sensor_height:n.sensor_width,s=n.sensor_fit==="AUTO"?t>=e:n.sensor_fit==="HORIZONTAL",l=(r?n.ortho_scale:a/n.lens)/2*o;return s?[l,l*e/t]:[l*t/e,l]}function Ti(n,t,e,o,r,a){const s=Math.max(e.width,1),l=Math.max(e.height,1),[u,m]=To(n,s,l,1/o),[f,i]=To(n,a,1,1),d=2*((n.sensor_fit==="AUTO"?a>=1:n.sensor_fit==="HORIZONTAL")?f:i),_=f/u,h=i/m,g=-2*r[0]*o,p=2*r[1]*o,v=n.shift_x*d-g*2*u,x=n.shift_y*d+p*2*m,w=new G().set(...n.matrix.flat()).premultiply(t),S=new b,M=new Tt;return w.decompose(S,M,new b),{name:n.name,position:S.toArray(),quaternion:[M.x,M.y,M.z,M.w],projection:n.type==="ORTHO"?"orthographic":"perspective",window:{left:v-u,right:v+u,top:x+m,bottom:x-m},near:n.clip_start,far:n.clip_end,frame:{left:.5-_/2+g,top:.5-h/2+p,width:_,height:h},passepartout:{color:$e.passepartout,opacity:n.passepartout},border:{solid:$e.back,dashed:$e.overlay,locked:$e.redalert}}}const Pi={color:[.8,.8,.8,1],roughness:.5,metallic:0},Ei=`
7151
7165
  uniform vec3 wbDir[4];
7152
7166
  uniform vec3 wbDiffuse[4];
7153
7167
  uniform vec3 wbSpecular[4];
@@ -7189,6 +7203,6 @@ vec3 volterWorkbenchLighting(vec3 baseColor, vec3 N, vec3 I) {
7189
7203
  diffuseLight *= diffuseColor * (1.0 - specEnergy);
7190
7204
  return diffuseLight + specularLight;
7191
7205
  }
7192
- `,jn=n=>zn.map(t=>{const[e=0,o=0,r=0]=n(t);return new b(e,o,r)}),pi=jn(n=>n.direction).map(n=>n.normalize()),gi=jn(n=>n.diffuse),vi=jn(n=>n.specular),xi=new Xe(...zn.map(n=>n.smooth));function bi(n,t){const[e,o,r]=n.color,a=new Da({side:t});return a.color.setRGB(e,o,r,xt),a.name="volter:blender-solid",a.onBeforeCompile=s=>{s.uniforms.wbDir={value:pi},s.uniforms.wbDiffuse={value:gi},s.uniforms.wbSpecular={value:vi},s.uniforms.wbWrap={value:xi},s.uniforms.wbRoughness={value:n.roughness},s.uniforms.wbMetallic={value:n.metallic},s.fragmentShader=s.fragmentShader.replace("void main() {",`${hi}
7206
+ `,Wn=n=>$n.map(t=>{const[e=0,o=0,r=0]=n(t);return new b(e,o,r)}),Ni=Wn(n=>n.direction).map(n=>n.normalize()),Ri=Wn(n=>n.diffuse),Ii=Wn(n=>n.specular),Di=new Ee(...$n.map(n=>n.smooth));function Ci(n,t){const[e,o,r]=n.color,a=new Va({side:t});return a.color.setRGB(e,o,r,xt),a.name="volter:blender-solid",a.onBeforeCompile=s=>{s.uniforms.wbDir={value:Ni},s.uniforms.wbDiffuse={value:Ri},s.uniforms.wbSpecular={value:Ii},s.uniforms.wbWrap={value:Di},s.uniforms.wbRoughness={value:n.roughness},s.uniforms.wbMetallic={value:n.metallic},s.fragmentShader=s.fragmentShader.replace("void main() {",`${Ei}
7193
7207
  void main() {`).replace("#include <opaque_fragment>",`outgoingLight = volterWorkbenchLighting(diffuseColor.rgb, normal, isOrthographic ? vec3(0.0, 0.0, 1.0) : normalize(vViewPosition));
7194
- #include <opaque_fragment>`)},a.customProgramCacheKey=()=>"volter-blender-workbench",a}const yi=64;function wi(n,t){return Array.isArray(n)&&Array.isArray(t)?n.length===t.length&&n.every((e,o)=>e===t[o]):n===t}function He(n){return n.onBeforeRender===Ve.prototype.onBeforeRender&&n.onAfterRender===Ve.prototype.onAfterRender}function ee(n){for(let t=n;t;t=t.parent)if(!t.visible)return!1;return!0}function Tn(n){if(n.determinant()<=0)return!1;const t=n.elements,e=Math.hypot(t[0],t[1],t[2]),o=Math.hypot(t[4],t[5],t[6]),r=Math.hypot(t[8],t[9],t[10]),a=(s,f)=>t[s]*t[f]+t[s+1]*t[f+1]+t[s+2]*t[f+2];return Number.isFinite(e+o+r)&&Math.min(e,o,r)>0&&Math.abs(a(0,4))<=1e-7*e*o&&Math.abs(a(0,8))<=1e-7*e*r&&Math.abs(a(4,8))<=1e-7*o*r}class Oi{constructor(t){this.root=t,this.batches=[],this.inverse=new q,this.matrix=new q,this.box=new me,this.projection=new q,this.frustum=new Ke,this.camera=null,this.eligible=0,this.excluded={}}rebuild(t,e){if(this.clear(),!e)return;const o=new Map,r=a=>{this.excluded[a]=(this.excluded[a]??0)+1};this.inverse.copy(this.root.matrixWorld).invert();for(const a of t){const s=a;if(!s.isMesh)continue;if(!He(s)){r("customHooks");continue}if(s.isSkinnedMesh||s.isInstancedMesh||s.morphTargetInfluences||s.layers.mask!==1){r("deformationOrLayers");continue}const f=Array.isArray(s.material)?s.material:[s.material];if(f.some(l=>l.transparent||l.transmission>0||l.isShaderMaterial||!Te(l))){r("material");continue}if(f.some(l=>ta(l,s.geometry).size>12)){r("attributeBudget");continue}if(this.matrix.multiplyMatrices(this.inverse,s.matrixWorld),!Tn(this.matrix)){r("transform");continue}this.eligible++;const c=`${s.geometry.id}:${Array.isArray(s.material)?"slots":"single"}:`+f.map(l=>l.uuid).join(",")+`:${s.renderOrder}`,d=o.get(c);d?d.push(s):o.set(c,[s])}for(const a of o.values()){if(a.length<2)continue;const s=f=>{if(f.length>yi){this.box.makeEmpty();for(const h of f)this.box.expandByPoint(new b().setFromMatrixPosition(h.matrixWorld));const i=this.box.getSize(new b),u=i.x>=i.y&&i.x>=i.z?12:i.y>=i.z?13:14;f.sort((h,_)=>h.matrixWorld.elements[u]-_.matrixWorld.elements[u]);const m=Math.floor(f.length/2);s(f.slice(0,m)),s(f.slice(m));return}if(f.length<2)return;const c=f[0],d=new Co(c.geometry,c.material,f.length);d.name="Blender repeated geometry",d.userData.engineInternal=!0,d.matrixAutoUpdate=!1,d.renderOrder=c.renderOrder,d.instanceMatrix.setUsage(Fo);const l={draw:d,members:f.map(i=>({mesh:i,layers:i.layers.mask}))};d.raycast=(i,u)=>{for(const{mesh:m}of l.members)m.layers.mask===0&&ee(m)&&m.raycast(i,u)},this.root.add(d),d.updateMatrixWorld(!0),this.batches.push(l)};s(a)}this.sync()}sync(){if(this.batches.length){this.inverse.copy(this.root.matrixWorld).invert();for(const{draw:t,members:e}of this.batches){const r=(Array.isArray(t.material)?t.material:[t.material]).every(Te);let a=0,s=!1;for(const f of e){const{mesh:c}=f;if(this.matrix.multiplyMatrices(this.inverse,c.matrixWorld),!(c.parent!==null&&c.geometry===t.geometry&&r&&He(c)&&wi(c.material,t.material)&&Tn(this.matrix))){c.layers.mask|=f.layers;continue}if(c.layers.mask&=~f.layers,!ee(c)||this.camera&&(!this.camera.layers.isEnabled(0)||c.frustumCulled&&!this.frustum.intersectsObject(c)))continue;const l=a*16;this.matrix.elements.some((i,u)=>Math.fround(i)!==t.instanceMatrix.array[l+u])&&(t.setMatrixAt(a,this.matrix),s=!0),a++}s||=t.count!==a||t.boundingSphere===null,t.count=a,s&&(t.instanceMatrix.needsUpdate=!0,t.computeBoundingBox(),t.computeBoundingSphere())}}}prepareDraw(t){t.updateMatrixWorld(),this.camera=t,this.projection.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this.frustum.setFromProjectionMatrix(this.projection)}finishDraw(){this.camera=null}clear(){this.camera=null;for(const{draw:t,members:e}of this.batches){for(const{mesh:o,layers:r}of e)o.layers.mask|=r;t.removeFromParent(),t.dispose()}this.batches.length=0,this.eligible=0,this.excluded={}}inspect(){return{batches:this.batches.length,instances:this.batches.reduce((t,{draw:e})=>t+e.count,0),eligible:this.eligible,excluded:{...this.excluded}}}}const Sn=64,cn=4*1024*1024,Ai=32*1024*1024,Mi=1024;class Ti{constructor(){this.families=new Map,this.partitions=new Map,this.registrations=new Map,this.bytes=0,this.drawCount=0,this.created=0,this.pending=!1}begin(){this.created=0,this.pending=!1,this.registrations.clear()}register(t,e,o){const r=`${t.id}:${e.uuid}:${o}`;if(this.registrations.has(r))return this.registrations.get(r);this.registrations.set(r,null);const a=t.getAttribute("position"),s=t.index?.count??a?.count??0;if(!a||t.drawRange.start!==0||t.drawRange.count<s||Object.keys(t.morphAttributes).length)return null;const f=[!!t.index,t.userData.blenderUvChannels??null],c=[t.index?.id,t.index?.version];let d=(t.index?.count??0)*4;for(const p of Object.keys(t.attributes).sort()){const g=t.getAttribute(p);if(!(g instanceof lt)||g.isInstancedBufferAttribute||g instanceof za||g.count!==a.count)return null;f.push([p,g.array.constructor.name,g.itemSize,g.normalized,g.gpuType]),c.push(p,g.id,g.version),d+=g.array.byteLength}if(d>cn)return null;const l=`multi:${e.uuid}:${o}:${JSON.stringify(f)}`;let i=this.partitions.get(l);i||(i=[],this.partitions.set(l,i));let u=i.find(p=>this.families.get(p).shapes.has(t.id));u??=i.find(p=>this.families.get(p).reservedBytes+d<=cn),u||(u=`${l}:${i.length}`,i.push(u));let m=this.families.get(u);m||(m={material:e,shapes:new Map,template:null,ids:new Map,draws:[],dirty:!0,bytes:0,reservedBytes:0,refused:!1},this.families.set(u,m));const h=JSON.stringify(c),_=m.shapes.get(t.id);return(!_||_.stamp!==h)&&(m.reservedBytes+=d-(_?.bytes??0),m.shapes.set(t.id,{geometry:t,stamp:h,bytes:d}),m.dirty=!0),this.registrations.set(r,u),u}pack(){for(const t of this.families.values()){if(!t.dirty)continue;this.release(t),t.dirty=!1;let e=0,o=0,r=0;for(const{geometry:f}of t.shapes.values()){e+=f.getAttribute("position").count,o+=f.index?.count??0;for(const c of Object.values(f.attributes))r+=c.array.byteLength}if(r+=o*(e>65535?4:2),t.refused=r>cn||this.bytes+r>Ai,t.refused)continue;const a=new Ae(Sn,e,o,t.material);a.sortObjects=!1,a.perObjectFrustumCulled=!1,a.frustumCulled=!1,a.matrixAutoUpdate=!1,a.boundingSphere=new Nn,a.name="Blender ordered multi-draw",a.userData.engineInternal=!0;for(const{geometry:f}of t.shapes.values())t.ids.set(f.id,a.addGeometry(f));const s=t.shapes.values().next().value.geometry;a.geometry.userData.blenderUvChannels=s.userData.blenderUvChannels;for(const f of Object.keys(s.attributes))a.geometry.getAttribute(f).gpuType=s.getAttribute(f).gpuType;t.template=a,t.bytes=r,this.bytes+=r}}available(t){return!!this.families.get(t)?.template}get(t,e){const o=this.families.get(t),r=o.template;if(!r)return null;let a=o.draws[e];if(!a){if(this.drawCount>=Mi)return null;if(this.created>=4)return this.pending=!0,null;a=new Ae(1,0,0,o.material),a.dispose(),a.copy(r),Object.defineProperty(a,"colorTexture",{value:null});for(const f of Object.keys(r.geometry.attributes))a.geometry.setAttribute(f,r.geometry.getAttribute(f));a.geometry.setIndex(r.geometry.index);const s=o.ids.values().next().value;for(let f=0;f<Sn;f++)a.addInstance(s),a.setVisibleAt(f,!1);o.draws.push(a),this.created++,this.drawCount++}return a}geometryId(t,e){return this.families.get(t).ids.get(e.id)}inspect(){return{bytes:this.bytes,draws:this.drawCount,pending:this.pending,refusedFamilies:[...this.families.values()].filter(t=>t.refused).length}}release(t){for(const e of t.draws){e.removeFromParent();for(const o of Object.keys(e.geometry.attributes))e.geometry.deleteAttribute(o);e.geometry.setIndex(null),e.dispose(),this.drawCount--}t.draws.length=0,t.template?.dispose(),t.template=null,t.ids.clear(),this.bytes-=t.bytes,t.bytes=0}clear(){for(const t of this.families.values())this.release(t);this.families.clear(),this.partitions.clear(),this.registrations.clear(),this.pending=!1}}const bo=128;class Si{constructor(){this.sources=new Map,this.geometryKeys=new Map,this.frame=0,this.count=0}begin(){this.frame++,this.geometryKeys.clear()}get(t,e){let o=this.geometryKeys.get(e.geometry);o===void 0&&(o=JSON.stringify([e.geometry.userData.blenderUvChannels??null,Object.keys(e.geometry.attributes).sort().map(f=>[f,e.geometry.getAttribute(f).itemSize])]),this.geometryKeys.set(e.geometry,o));const r=`${e instanceof Ae?"batch":"instance"}:${o}`;let a=this.sources.get(t);a||(a=new Map,this.sources.set(t,a));let s=a.get(r);if(s)s.frame!==this.frame&&(s.ready=mo(t,s.material)!==null,s.sourceVersion!==t.version&&(s.material.needsUpdate=!0),s.sourceVersion=t.version,s.frame=this.frame);else{if(this.count>=bo)return t;const f=mo(t);if(!f)return t;s={material:f,sourceVersion:t.version,frame:this.frame,ready:!0},a.set(r,s),this.count++}return s.ready?s.material:t}clear(){for(const t of this.sources.values())for(const{material:e}of t.values())e.dispose();this.sources.clear(),this.geometryKeys.clear(),this.count=0}inspect(){return{variants:this.count,limit:bo}}}const ie=Sn;function yo(n){for(let t=n.parent;t;t=t.parent)if(t.isGroup)return t.renderOrder;return 0}class Pi{constructor(t){this.root=t,this.objects=[],this.drawMaterials=new Si,this.ordered=new Ti,this.mixedDraws=new Map,this.multiDraw=!1,this.pools=new Map,this.hidden=[],this.inverse=new q,this.matrix=new q,this.projection=new q,this.frustum=new Ke,this.centre=new b,this.depth=new Xe,this.batches=0,this.instances=0,this.excluded={},this.plannedProjection=new q,this.projectionKnown=!1,this.planState=[],this.planned=[],this.stateIndex=0,this.stateChanged=!1}setObjects(t){this.clear(),this.objects=[...t].filter(e=>e.isMesh===!0)}prepare(t,e=!1){if(this.finishDraw(),this.drawMaterials.begin(),!this.objects.length)return;t.updateMatrixWorld(),this.projection.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse);const o=this.multiDraw!==e;if(this.multiDraw=e,!this.planChanged(t)&&!o&&!this.ordered.pending){for(const c of this.planned){c.mesh.visible=!0;const d=c.members[0].material;c.mesh.material=this.drawMaterials.get(Array.isArray(d)?d[0]:d,c.mesh);for(const l of c.members)l.layers.disable(0),this.hidden.push(l)}return}this.planned.length=0;for(const c of this.mixedDraws.values())c.members.length=0;this.ordered.begin();for(const c of this.pools.values())for(const d of c)d.mesh.visible=!1,d.members.length=0;this.batches=this.instances=0,this.excluded={},this.frustum.setFromProjectionMatrix(this.projection),this.inverse.copy(this.root.matrixWorld).invert();const a=[],s=new Map;for(const c of this.objects){const d=Array.isArray(c.material)?c.material:[c.material];if(!d.some(v=>v.visible&&v.transparent)||!ee(c)||!c.layers.test(t.layers)||c.frustumCulled&&!this.frustum.intersectsObject(c))continue;const l=c;l.boundingSphere!==void 0?(l.boundingSphere===null&&l.computeBoundingSphere?.(),this.centre.copy(l.boundingSphere.center)):(c.geometry.boundingSphere||c.geometry.computeBoundingSphere(),this.centre.copy(c.geometry.boundingSphere.center)),this.centre.applyMatrix4(c.matrixWorld);const i=this.centre.clone(),u=this.depth.set(i.x,i.y,i.z,1).applyMatrix4(this.projection).z;let m=null,h=null;const _=d.length===1?d[0]:null,p=yo(c);if(_&&_.visible&&_.transparent&&Te(_)&&He(c)&&!_.isShaderMaterial&&!(_.transmission>0)&&(_.side!==Be||_.forceSinglePass)&&!c.isSkinnedMesh&&!c.morphTargetInfluences&&!c.isInstancedMesh&&c.layers.mask===1&&p===this.root.renderOrder){const v=c.geometry,w=v.index?.count??v.getAttribute("position").count,x=!Array.isArray(c.material)||v.groups.length===1&&v.groups[0].start===0&&v.groups[0].count===w&&v.groups[0].materialIndex===0,T=`${v.id}:${_.uuid}:${c.renderOrder}`;let y=s.get(T);y===void 0&&(y=ta(_,v).size<=12,s.set(T,y)),this.matrix.multiplyMatrices(this.inverse,c.matrixWorld),x&&y&&Tn(this.matrix)&&(m=_,h=T)}if(h===null){const v=_?_.isShaderMaterial?"customShader":_.transmission>0?"transmission":_.side===Be&&!_.forceSinglePass?"twoPass":"geometryLayersOrTransform":"multipleMaterials";this.excluded[v]=(this.excluded[v]??0)+1}const g=e&&h&&m?this.ordered.register(c.geometry,m,c.renderOrder):null;a.push({mesh:c,material:m,key:h,batchKey:g,groupOrder:p,z:u,centre:i})}this.ordered.pack();for(const c of a)c.batchKey&&this.ordered.available(c.batchKey)&&(c.key=c.batchKey);for(const[c]of this.mixedDraws)c.parent||this.mixedDraws.delete(c);a.sort((c,d)=>c.groupOrder-d.groupOrder||c.mesh.renderOrder-d.mesh.renderOrder||d.z-c.z||c.mesh.id-d.mesh.id);const f=new Map;for(let c=0;c<a.length;){const d=a[c];let l=c+1;if(d.key!==null)for(;l<a.length&&a[l].key===d.key;)l++;const i=a[c-1],u=a[l],m=i?.z===d.z&&i.mesh.renderOrder===d.mesh.renderOrder||u?.z===a[l-1].z&&u.mesh.renderOrder===d.mesh.renderOrder;if(d.key!==null&&l-c>=2&&!m){let h=!0;for(let _=c+ie;_<l;_+=ie)a[_-1].z===a[_].z&&(h=!1);if(h)for(let _=c;_<l;_+=ie){const p=Math.min(ie,l-_);if(p<2)continue;const g=a[_],v=f.get(d.key)??0;f.set(d.key,v+1);const w=d.key.startsWith("multi:");let x;if(w){const y=this.ordered.get(d.key,v);if(!y)continue;if(x=this.mixedDraws.get(y),!x){x={mesh:y,members:[]},this.mixedDraws.set(y,x);const A=x;y.raycast=(M,P)=>{if(y.visible)for(const F of A.members)ee(F)&&F.raycast(M,P)},this.root.add(y)}}let T=this.pools.get(d.key);if(T||(T=[],this.pools.set(d.key,T)),w||(x=T[v]),!x){const y=new Co(d.mesh.geometry,d.material,ie);y.name="Blender ordered transparency",y.userData.engineInternal=!0,y.matrixAutoUpdate=!1,y.frustumCulled=!1,y.boundingSphere=new Nn,y.instanceMatrix.setUsage(Fo),x={mesh:y,members:[]};const A=x;y.raycast=(M,P)=>{if(y.visible)for(const F of A.members)ee(F)&&F.raycast(M,P)},T.push(x),this.root.add(y)}x.mesh.material=this.drawMaterials.get(d.material,x.mesh),x.mesh.visible=!0,x.mesh.renderOrder=g.mesh.renderOrder,x.mesh.boundingSphere.center.copy(g.centre).applyMatrix4(this.inverse),x.mesh.updateMatrixWorld(!0);for(let y=0;y<p;y++){const A=a[_+y].mesh;this.matrix.multiplyMatrices(this.inverse,A.matrixWorld),x.mesh.setMatrixAt(y,this.matrix),x.mesh instanceof Ae&&(x.mesh.setGeometryIdAt(y,this.ordered.geometryId(d.key,A.geometry)),x.mesh.setVisibleAt(y,!0)),x.members.push(A),A.layers.disable(0),this.hidden.push(A)}if(x.mesh instanceof Ae)for(let y=p;y<ie;y++)x.mesh.setVisibleAt(y,!1);else x.mesh.count=p,x.mesh.instanceMatrix.needsUpdate=!0;this.planned.push(x),this.batches++,this.instances+=p}}c=l}this.ordered.pending&&queueMicrotask(_t)}inspect(){return{batches:this.batches,instances:this.instances,excluded:{...this.excluded},multiDraw:this.ordered.inspect(),materials:this.drawMaterials.inspect()}}observe(t){this.planState[this.stateIndex]!==t&&(this.planState[this.stateIndex]=t,this.stateChanged=!0),this.stateIndex++}planChanged(t){if(!this.projectionKnown||!this.plannedProjection.equals(this.projection))return this.plannedProjection.copy(this.projection),this.projectionKnown=!0,this.planState.length=0,!0;this.stateIndex=0,this.stateChanged=this.planState.length===0,this.observe(t.layers.mask);for(const r of this.projection.elements)this.observe(r);for(const r of this.root.matrixWorld.elements)this.observe(r);const e=new Set,o=new Set;for(const r of this.objects){if(!(Array.isArray(r.material)?r.material:[r.material]).some(d=>d.visible&&d.transparent))continue;this.observe(r.parent?.id??-1),this.observe(ee(r)?1:0),this.observe(r.layers.mask),this.observe(r.renderOrder),this.observe(yo(r)),this.observe(r.frustumCulled?1:0),this.observe(He(r)?1:0),this.observe(r.morphTargetInfluences?1:0);for(const d of r.matrixWorld.elements)this.observe(d);const s=r.geometry;if(this.observe(s.id),!e.has(s)){e.add(s),this.observe(s.index?.id??-1),this.observe(s.index?.version??-1),this.observe(JSON.stringify(s.userData.blenderUvChannels??null));for(const d of Object.keys(s.attributes).sort()){const l=s.getAttribute(d);this.observe(d),l instanceof lt&&(this.observe(l.id),this.observe(l.version))}}this.observe(s.drawRange.start),this.observe(s.drawRange.count),this.observe(s.index?.count??s.getAttribute("position").count),this.observe(s.groups.length);for(const d of s.groups)this.observe(d.start),this.observe(d.count),this.observe(d.materialIndex??0);const f=r.boundingSphere??s.boundingSphere;this.observe(f?.center.x??0),this.observe(f?.center.y??0),this.observe(f?.center.z??0),this.observe(f?.radius??-1);const c=Array.isArray(r.material)?r.material:null;if(this.observe(c?.length??-1),c)for(const d of c)this.observeMaterial(d,o);else this.observeMaterial(r.material,o)}return this.stateChanged||=this.planState.length!==this.stateIndex,this.planState.length=this.stateIndex,this.stateChanged}observeMaterial(t,e){this.observe(t.uuid),!e.has(t)&&(e.add(t),this.observe(Te(t)?1:0),this.observe(t.version),this.observe(t.visible?1:0),this.observe(t.transparent?1:0),this.observe(t.side),this.observe(t.forceSinglePass?1:0),this.observe(t.transmission??0))}finishDraw(){for(const t of this.hidden)t.layers.enable(0);this.hidden.length=0;for(const t of this.pools.values())for(const{mesh:e}of t)e.visible=!1;for(const{mesh:t}of this.mixedDraws.values())t.visible=!1}clear(){this.finishDraw();for(const t of this.pools.values())for(const{mesh:e}of t)e.removeFromParent(),e.dispose();this.pools.clear(),this.ordered.clear(),this.drawMaterials.clear(),this.mixedDraws.clear(),this.planned.length=0,this.planState.length=0,this.projectionKnown=!1,this.objects=[],this.batches=this.instances=0}}const Ei=8*1024*1024;class Ni{constructor(){this.objects=[],this.copies=new Map,this.swapped=[],this.bytes=0,this.savedDraws=0}setObjects(t){this.clear(),this.objects=[...t].filter(e=>e.isMesh===!0)}prepare(){this.savedDraws=0;for(const t of this.objects){const e=t.geometry,o=t.material;if(t.layers.mask===0||!Array.isArray(o)||e.groups.length<8||!e.index||t.isSkinnedMesh||t.isInstancedMesh||t.morphTargetInfluences||Object.keys(e.morphAttributes).length||e.drawRange.start!==0||e.drawRange.count<e.index.count||o.some(s=>s.transparent||s.transmission>0||s.isShaderMaterial))continue;const r=JSON.stringify([e.id,e.index.id,e.index.version,o.map(s=>s.uuid),e.groups,Object.entries(e.attributes).map(([s,f])=>[s,f.id])]);let a=this.copies.get(r);if(!a){let s=0,f=!0;const c=new Map;for(const m of e.groups){const h=m.materialIndex??0,_=o[h];if(!_||m.start!==s||m.count<=0||m.count%3!==0){f=!1;break}s+=m.count;const p=c.get(_.uuid);p?p.groups.push(m):c.set(_.uuid,{slot:h,groups:[m]})}if(!f||s!==e.index.count||c.size>=e.groups.length)continue;const d=e.index.array.byteLength;if(this.bytes+d>Ei)continue;const l=new re;for(const[m,h]of Object.entries(e.attributes))l.setAttribute(m,h);const i=e.index.clone();let u=0;for(const m of c.values()){const h=u;for(const _ of m.groups)i.array.set(e.index.array.subarray(_.start,_.start+_.count),u),u+=_.count;l.addGroup(h,u-h,m.slot)}l.setIndex(i),l.boundingBox=e.boundingBox?.clone()??null,l.boundingSphere=e.boundingSphere?.clone()??null,l.userData={...e.userData},a={geometry:l,signature:r,bytes:d,before:e.groups.length,after:c.size},this.copies.set(r,a),this.bytes+=d}this.swapped.push({mesh:t,geometry:e}),t.geometry=a.geometry,this.savedDraws+=a.before-a.after}}finish(){for(const{mesh:t,geometry:e}of this.swapped)t.geometry=e;this.swapped.length=0}inspect(){return{copies:this.copies.size,bytes:this.bytes,savedRanges:this.savedDraws}}release(t){for(const e of Object.keys(t.geometry.attributes))t.geometry.deleteAttribute(e);t.geometry.dispose(),this.bytes-=t.bytes}clear(){this.finish();for(const t of this.copies.values())this.release(t);this.copies.clear(),this.objects=[],this.savedDraws=0}}const un=64*1024*1024,wo=150,Ce=49152,Et=8192,Oo=Symbol("navigation geometry replaced");class Ri{constructor(t){this.invalidate=t,this.groups=new Map,this.cache=new Map,this.swapped=[],this.queue=[],this.worker=null,this.pending=null,this.generation=0,this.building=!1,this.nextId=0,this.signature="",this.identities=new WeakMap,this.nextIdentity=0,this.bytes=0,this.unavailable=null,this.reductions=[],this.timer=null,this.cameraWorld=new q,this.cameraProjection=new q,this.cameraKnown=!1,this.movedAt=-1/0,this.projection=new q,this.frustum=new Ke,this.centre=new b,this.boxCentre=new b,this.halfExtent=new b,this.viewWorld=new q,this.drawnMeshes=0,this.fullTriangles=0,this.motionTriangles=0,this.lastNavigation={meshes:0,fullTriangles:0,motionTriangles:0,tooClose:0},this.quietTimer=null}setObjects(t){const e=new Map;for(const s of t){const f=s;if(!f.isMesh||f.isSkinnedMesh||f.isInstancedMesh||f.morphTargetInfluences)continue;const c=f.geometry,d=c.getAttribute("position");if(!c.index||c.index.count<6144||!d||d.count>8e6||Object.values(c.attributes).some(i=>!(i instanceof lt)||i.isFloat16BufferAttribute||i.isInstancedBufferAttribute)||Object.keys(c.morphAttributes).length||c.drawRange.start!==0||c.drawRange.count<c.index.count)continue;if(Array.isArray(f.material)){let i=0;if(!c.groups.length||c.groups.some(u=>{const m=u.start===i&&u.count>0&&u.count%3===0&&Number.isInteger(u.materialIndex)&&u.materialIndex>=0&&u.materialIndex<f.material.length;return i=u.start+u.count,!m})||i!==c.index.count)continue}const l=e.get(c);l?l.push(f):e.set(c,[f])}this.groups=e;const o=s=>{let f=this.identities.get(s);return f===void 0&&(f=++this.nextIdentity,this.identities.set(s,f)),f},r=[...e].map(([s,f])=>`${s.id}:${o(s.index)}:${s.index.version}:${Array.isArray(f[0].material)}:${JSON.stringify(s.groups)}:`+Object.entries(s.attributes).map(([c,d])=>`${c}:${o(d)}:${d.version}`).join(",")).join(";");if(r===this.signature)return;this.releaseCopies(),this.signature=r,this.unavailable=null;const a=[...e].filter(([,s])=>s.length>=3);a.reduce((s,[f,c])=>s+f.index.count*c.length,0)<6e6||(a.sort(([s,f],[c,d])=>c.index.count*d.length-s.index.count*f.length),this.queue=a.map(([s])=>({geometry:s,fine:!1})),this.next())}async next(){if(this.building||this.unavailable||this.bytes>=un)return;const t=this.queue.shift();if(!t){this.worker?.terminate(),this.worker=null;return}const{geometry:e,fine:o}=t;this.building=!0;const r=this.generation,a=()=>{if(r!==this.generation)throw Oo;if(this.unavailable)throw new Error(this.unavailable)},s=async()=>{await new Promise(f=>setTimeout(f,0)),a()};try{this.worker||(this.worker=new Worker(new URL("/assets/blender-motion-worker-CtT2cV3V.js",import.meta.url),{type:"module"}),this.worker.onmessage=N=>{if(this.pending?.id===N.data.id){const D=this.pending;this.pending=null,D.resolve(N.data)}},this.worker.onerror=N=>{this.unavailable=N.message||"Navigation geometry worker unavailable",this.worker?.terminate(),this.worker=null;const D=this.pending;this.pending=null,D?.resolve({id:D.id,refusal:this.unavailable})});const f=e.getAttribute("position"),c=this.groups.get(e),d=Array.isArray(c[0].material);if(c.some(N=>Array.isArray(N.material)!==d))return;const l=d?e.groups:[{start:0,count:e.index.count}],i=l.flatMap(N=>{const D=[];for(let E=N.start;E<N.start+N.count;E+=Ce)D.push({start:E,count:Math.min(Ce,N.start+N.count-E),materialIndex:N.materialIndex});return D}),u=e.getAttribute("blenderVertex"),m=new Uint32Array(f.count),h=new Uint8Array(f.count),_=N=>u?u.getX(N):N;for(let N=0;N<i.length;N++){const D=i[N];for(let E=D.start;E<D.start+D.count;E+=Et){await s();for(let S=E;S<Math.min(E+Et,D.start+D.count);S++){const $=_(e.index.getX(S));if(!Number.isInteger($)||$<0||$>=m.length)return;m[$]?m[$]!==N+1&&(h[$]=1):m[$]=N+1}}}const p=Object.entries(e.attributes).filter(([N])=>N!=="position"&&N!=="blenderVertex"),g=p.reduce((N,[,D])=>N+D.itemSize,0);if(g>32)return;const v=[];let w=0;for(const[N,D]of p)for(let E=0;E<D.itemSize;E++,w++)N!=="normal"&&v.push(w);const x=p.flatMap(([N,D])=>Array(D.itemSize).fill(N==="normal"?.5:1)),T=e.boundingBox?.clone()??new me;if(!e.boundingBox){const N=new b;for(let D=0;D<f.count;D+=Et){await s();for(let E=D;E<Math.min(D+Et,f.count);E++)T.expandByPoint(N.fromBufferAttribute(f,E))}}if(!e.boundingSphere)return;const y=Math.max(T.max.x-T.min.x,T.max.y-T.min.y,T.max.z-T.min.z)*(o?5e-4:.002),A=[],M=[];let P=0,F=0;for(const N of l){const D=P;for(let E=N.start;E<N.start+N.count;E+=Ce){await s();const S=Math.min(E+Ce,N.start+N.count),$=[],X=new Map,K=new Uint32Array(S-E);for(let rt=E;rt<S;rt++){const Tt=e.index.getX(rt);let Lt=X.get(Tt);Lt===void 0&&(Lt=$.length,$.push(Tt),X.set(Tt,Lt)),K[rt-E]=Lt}const nt=new Uint8Array($.length),ot=new Float32Array($.length*3),at=new Float32Array($.length*g);for(let rt=0;rt<$.length;rt+=Et){await s();for(let Tt=rt;Tt<Math.min(rt+Et,$.length);Tt++){const Lt=$[Tt];nt[Tt]=h[_(Lt)];for(let jt=0;jt<3;jt++)ot[Tt*3+jt]=f.getComponent(Lt,jt);let Vn=0;for(const[,jt]of p){for(let Se=0;Se<jt.itemSize;Se++)at[Tt*g+Vn+Se]=jt.getComponent(Lt,Se);Vn+=jt.itemSize}}}const bt=++this.nextId,Pt=await new Promise(rt=>{this.pending={id:bt,resolve:rt};const Tt={id:bt,positions:ot,indices:K,attributes:at,stride:g,weights:x,absoluteError:y,protectedComponents:v,locks:nt};this.worker.postMessage(Tt,[ot.buffer,K.buffer,at.buffer,nt.buffer])});if(a(),Pt.refusal)throw new Error(Pt.refusal);if(!Pt.indices||!Number.isFinite(Pt.error))throw new Error("Invalid navigation geometry response");const $t=Pt.indices;for(let rt=0;rt<$t.length;rt++)$t[rt]=$[$t[rt]];if(P+=$t.length,P*4>un-this.bytes)return;A.push($t),F=Math.max(F,Pt.error)}d&&M.push({start:D,count:P-D,materialIndex:N.materialIndex})}const U={vertices:f.count,fullTriangles:e.index.count/3,reducedTriangles:P/3,error:F,fine:o,accepted:!1};if(this.reductions.length<32&&this.reductions.push(U),!P||P>=e.index.count*.75)return;const H=o?null:new Int32Array(f.count).fill(-1),G=[],J=new Uint32Array(P);let ft=0;for(const N of A){for(let D=0;D<N.length;D+=Et){await s();for(let E=D;E<Math.min(D+Et,N.length);E++){const S=N[E];let $=H?H[S]:S;$<0&&($=G.length,G.push(S),H[S]=$),J[ft+E]=$}}ft+=N.length}const O=J.byteLength+(o?0:Object.values(e.attributes).reduce((N,D)=>N+G.length*D.itemSize*D.array.BYTES_PER_ELEMENT,0));if(U.bytes=O,this.bytes+O>un)return;const B=new re;B.setIndex(new lt(J,1));for(const[N,D]of Object.entries(e.attributes)){if(o){B.setAttribute(N,D);continue}const E=D,S=E.array.constructor,$=new S(G.length*E.itemSize);for(let X=0;X<G.length;X+=Et){await s();for(let K=X;K<Math.min(X+Et,G.length);K++)for(let nt=0;nt<E.itemSize;nt++)$[K*E.itemSize+nt]=E.array[G[K]*E.itemSize+nt]}B.setAttribute(N,new lt($,E.itemSize,E.normalized))}B.boundingSphere=e.boundingSphere.clone(),B.boundingBox=T.clone();for(const N of M)B.addGroup(N.start,N.count,N.materialIndex);B.userData={...e.userData},U.accepted=!0;const L=this.cache.get(e)??[];L.push({geometry:B,error:F,bytes:O,sharedAttributes:o}),this.cache.set(e,L),this.bytes+=O,!o&&e.index.count>=3e5&&P<e.index.count*.25&&this.queue.push({geometry:e,fine:!0})}catch(f){if(f===Oo)return;this.unavailable=String(f),this.worker?.terminate(),this.worker=null,this.pending=null,this.queue.length=0}finally{r===this.generation&&(this.building=!1,this.timer=setTimeout(()=>{this.timer=null,this.next()},0))}}prepare(t,e,o){if(this.finish(),this.drawnMeshes=this.fullTriangles=this.motionTriangles=0,!e||!(o>0))return!1;const r=performance.now(),a=this.cameraKnown&&(!t.matrixWorld.equals(this.cameraWorld)||!t.projectionMatrix.equals(this.cameraProjection));if(this.cameraKnown=!0,this.cameraWorld.copy(t.matrixWorld),this.cameraProjection.copy(t.projectionMatrix),a&&(this.movedAt=r,this.quietTimer&&clearTimeout(this.quietTimer),this.quietTimer=setTimeout(()=>{this.quietTimer=null,this.invalidate()},wo+1)),r-this.movedAt>wo)return!1;this.projection.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this.frustum.setFromProjectionMatrix(this.projection);let s=0;for(const[f,c]of this.cache){const d=c[0].geometry.boundingBox;d.getSize(this.halfExtent).multiplyScalar(.5);for(const l of this.groups.get(f)??[]){if(!ee(l)||l.frustumCulled&&!this.frustum.intersectsObject(l))continue;this.viewWorld.multiplyMatrices(t.matrixWorldInverse,l.matrixWorld);const i=this.viewWorld.elements,u=i[0]**2+i[1]**2+i[2]**2,m=i[4]**2+i[5]**2+i[6]**2,h=i[8]**2+i[9]**2+i[10]**2,_=Math.abs(i[0]*i[4]+i[1]*i[5]+i[2]*i[6]),p=Math.abs(i[0]*i[8]+i[1]*i[9]+i[2]*i[10]),g=Math.abs(i[4]*i[8]+i[5]*i[9]+i[6]*i[10]),v=Math.sqrt(Math.max(u+_+p,m+_+g,h+p+g)),w=f.boundingSphere;this.centre.copy(w.center).applyMatrix4(this.viewWorld);let x=1;if(t.isPerspectiveCamera){const A=-this.centre.z-w.radius*v;d.getCenter(this.boxCentre).applyMatrix4(this.viewWorld);const M=this.viewWorld.elements,P=Math.abs(M[2])*this.halfExtent.x+Math.abs(M[6])*this.halfExtent.y+Math.abs(M[10])*this.halfExtent.z;x=Math.max(A,-this.boxCentre.z-P)}const T=v*Math.abs(t.projectionMatrix.elements[5])*o/(2*x);let y;if(x>0){for(const A of c)if(A.error*T<=1){y=A;break}}if(!y){s++;continue}this.swapped.push({mesh:l,geometry:f}),l.geometry=y.geometry,this.drawnMeshes++,this.fullTriangles+=f.index.count/3,this.motionTriangles+=y.geometry.index.count/3}}return this.lastNavigation={meshes:this.drawnMeshes,fullTriangles:this.fullTriangles,motionTriangles:this.motionTriangles,tooClose:s},this.swapped.length>0}finish(){for(const{mesh:t,geometry:e}of this.swapped)t.geometry=e;this.swapped.length=0}inspect(){return{copies:this.cache.size,levels:[...this.cache.values()].reduce((t,e)=>t+e.length,0),bytes:this.bytes,queued:this.queue.length,pending:this.building,unavailable:this.unavailable,reductions:this.reductions.map(t=>({...t})),lastNavigation:{...this.lastNavigation}}}releaseCopies(){this.finish(),this.timer&&clearTimeout(this.timer),this.timer=null,this.generation++,this.worker?.terminate(),this.worker=null,this.pending?.resolve({id:this.pending.id,refusal:"Navigation geometry replaced"}),this.pending=null,this.building=!1,this.queue=[];for(const t of this.cache.values())for(const e of t){if(e.sharedAttributes)for(const o of Object.keys(e.geometry.attributes))e.geometry.deleteAttribute(o);e.geometry.dispose()}this.cache.clear(),this.bytes=0,this.reductions=[]}clear(){this.releaseCopies(),this.quietTimer&&clearTimeout(this.quietTimer),this.quietTimer=null,this.groups.clear(),this.signature="",this.cameraKnown=!1,this.movedAt=-1/0}}const Ii={WIREFRAME:"wireframe",SOLID:"solid",MATERIAL:"preview",RENDERED:"rendered"},k=I().finite(),ra=W([k,k,k]),Fe=W([I().int().nonnegative(),I().int().nonnegative()]),gt={name:z(),domain:Q(["POINT","EDGE","FACE","CORNER"])},Di=Za("type",[R({...gt,type:Z("FLOAT2"),data:j(W([k,k]))}).strict(),R({...gt,type:Z("FLOAT_VECTOR"),data:j(ra)}).strict(),R({...gt,type:Z("FLOAT_COLOR"),data:j(W([k,k,k,k]))}).strict(),R({...gt,type:Z("BYTE_COLOR"),data:j(W([k,k,k,k]))}).strict(),R({...gt,type:Z("QUATERNION"),data:j(W([k,k,k,k]))}).strict(),R({...gt,type:Z("FLOAT4"),data:j(W([k,k,k,k]))}).strict(),R({...gt,type:Z("FLOAT4X4"),data:j(j(k).length(16))}).strict(),R({...gt,type:Z("INT16_2D"),data:j(W([I().int(),I().int()]))}).strict(),R({...gt,type:Z("INT32_2D"),data:j(W([I().int(),I().int()]))}).strict(),R({...gt,type:Z("FLOAT"),data:j(k)}).strict(),R({...gt,type:Z("INT"),data:j(I().int())}).strict(),R({...gt,type:Z("INT8"),data:j(I().int())}).strict(),R({...gt,type:Z("BOOLEAN"),data:j(et())}).strict(),R({...gt,type:Z("STRING"),data:j(z())}).strict()]),zi=R({positions:Y(Float32Array),normals:Y(Float32Array).nullable(),uv:Y(Float32Array).nullable(),uvLayers:j(R({name:z(),data:Y(Float32Array)}).strict()).optional(),attributeLayers:j(R({name:z(),data:Y(Float32Array)}).strict()).optional(),orco:Y(Float32Array).nullable().optional(),indices:Y(Uint32Array),groups:j(R({start:I().int().nonnegative(),count:I().int().nonnegative(),materialIndex:I().int().nonnegative()}).strict()),hash:z()}).strict(),Ci=R({v:j(ra),f:j(j(I().int().nonnegative())),e:j(Fe).optional(),edge_order:j(Fe).optional(),m:j(I().int().nonnegative()).optional(),s:j(et()).optional(),sharp:j(Fe).optional(),seams:j(Fe).optional(),creases:j(W([k,k,k])).optional(),attributes:j(Di).optional(),active_uv:z().nullable().optional(),render_uv:z().nullable().optional()}).strict(),Fi=R({store:I().int().optional(),revision:I().int(),unchanged:Z(!0)}).strict(),ki=R({co:Gt([Y(Float32Array),Y(Float64Array)]),cornerNormal:Y(Float32Array).optional(),cornerTri:Y(Uint32Array).optional(),orco:Y(Float32Array).optional(),faceStart:Y(Uint32Array),corner:Y(Uint32Array),cornerEdge:Y(Int32Array),edge:Y(Uint32Array),edgeSharp:Y(Uint8Array),edgeSeam:Y(Uint8Array),edgeCrease:Y(Float32Array),material:Y(Uint32Array),smooth:Y(Uint8Array),vertSelect:Y(Uint8Array),vertHide:Y(Uint8Array),edgeSelect:Y(Uint8Array),edgeHide:Y(Uint8Array),faceSelect:Y(Uint8Array),faceHide:Y(Uint8Array)}).strict(),$i=R({name:z(),domain:Q(["POINT","EDGE","FACE","CORNER"]),type:z(),data:Ka(n=>ArrayBuffer.isView(n))}).strict(),sa=R({columns:ki,attributes:j($i),activeUv:z().nullable(),renderUv:z().nullable(),counts:R({verts:I().int().nonnegative(),edges:I().int().nonnegative(),faces:I().int().nonnegative(),corners:I().int().nonnegative()}).strict(),revision:I().int().nonnegative()}).strict(),Li=Gt([zi,sa,Ci,Fi]),Ao=new Set;function ji(n,t){const e=new Blob([n],{type:t}),o=new La;let r=!1;o.addEventListener("dispose",()=>{r=!0,o.image?.close?.()});const a=createImageBitmap(e,{imageOrientation:"flipY",premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(s=>{if(r){s.close();return}o.image=s,o.needsUpdate=!0,_t()}).finally(()=>{Ao.delete(a)});return Ao.add(a),a.catch(()=>{}),{texture:o,ready:a}}function Vi(n,t,e,o){const r=new Ye(n,t,e,Ze,$a);return r.flipY=!1,r.colorSpace=o==="data"?Ue:Ht,r.needsUpdate=!0,r}function Bi(n,t,e){if(t.length===0)throw new Error(`Runtime image ${n} is tiled with no tiles`);const o=Math.max(...t.map(l=>l.width)),r=Math.max(...t.map(l=>l.height)),a=new Uint8Array(o*r*4*t.length),s=Math.max(...t.map(l=>l.number-1001))+1,f=new Float32Array(s*2*4);for(let l=0;l<s;l++)f[l*4]=-1;t.forEach((l,i)=>{const u=l.rgba??(l.rgbaBase64?vn(l.rgbaBase64):void 0);if(!u)throw new Error(`Runtime image ${n} tile ${l.number} carries no raster`);for(let h=0;h<l.height;h++)a.set(u.subarray(h*l.width*4,(h+1)*l.width*4),(i*r+h)*o*4);const m=l.number-1001;f[m*4]=i,f.set([0,0,l.width/o,l.height/r],(s+m)*4)});const c=new ka(a,o,r,t.length);c.colorSpace=e==="data"?Ue:Ht,c.magFilter=oe,c.minFilter=ko,c.generateMipmaps=!0,c.needsUpdate=!0;const d=new Ye(f,s,2,Ze,Ro);return d.magFilter=d.minFilter=pn,d.needsUpdate=!0,{tiles:c,map:d,frame:t}}const Ui=R({width:I().int().positive(),height:I().int().positive(),revision:I().int().nonnegative(),rgba:Y(Uint8Array).optional(),rgbaBase64:z().optional(),colorspace:Q(["sRGB","data"]).optional(),tiles:j(R({number:I().int().min(1001),width:I().int().positive(),height:I().int().positive(),rgba:Y(Uint8Array).optional(),rgbaBase64:z().optional()}).strict()).optional()}).strict(),Wi=R({revision:I().int().nonnegative(),encoded:Y(Uint8Array).optional(),encodedBase64:z().optional(),mime:Q(["image/png","image/jpeg"]),colorspace:Q(["sRGB","data"]).optional()}).strict(),ia=Gt([Ui,Wi]),dn=R({image:R({name:z(),revision:I().int().nonnegative()}).strict(),extension:Q(["REPEAT","EXTEND","MIRROR","CLIP"]).default("REPEAT"),uv:z(),tint:W([k,k,k]).optional()}).strict(),qi=R({name:z(),color:W([k,k,k,k]),roughness:k,metallic:k,transmission:k,ior:k,physical:Us.optional(),normal_texture:dn.optional(),normal_strength:k.default(1),normal_space:Q(["TANGENT","OBJECT"]).default("TANGENT"),normal_directx:et().default(!1),texture:dn.optional(),roughness_texture:dn.optional(),emission:R({color:W([k,k,k]),strength:k}).strict().optional(),graph:hs.optional(),viewport:R({color:W([k,k,k,k]),roughness:k,metallic:k}).strict().optional()}).strict(),Hi=R({session:z(),revision:I().int().nonnegative(),volumes:Ot(z(),Zo).default({}),lights:Ot(z(),Qr).default({}),world:ss.nullable().default(null),meshes:Ot(z(),Li),materials:Ot(z(),qi),images:Ot(z(),ia).default({}),objects:j(R({id:z(),name:z(),type:Q(["MESH","CURVE","SURFACE","FONT","META","ARMATURE","LATTICE","VOLUME","EMPTY","CAMERA","LIGHT","SPEAKER","GREASEPENCIL","POINTCLOUD","LIGHT_PROBE"]),mesh:z().nullable(),volume:z().nullable().optional(),light:z().nullable().optional(),materials:j(z().nullable()),matrix:j(W([k,k,k,k])).length(4),visible:et(),render_visible:et().default(!0),selected:et(),parent:z().nullable(),texspace:W([W([k,k,k]),W([k,k,k])]).optional(),default_color:z().optional()}).strict()),active:z().nullable(),mode:z(),cameras:Ot(z(),Ot(z(),Lo())).default({}),warnings:j(z()).default([]),updated:j(z()).default([]),frame:I().int().default(0),armatures:Ot(z(),er).default({}),weights:Xs.nullable().default(null),cursor:Js.optional(),camera_view:R({scene_camera:z().nullable(),view_layer_cameras:j(z()),aspect:I().finite().positive()}).optional(),light_distances:Ot(z(),W([I().finite(),I().finite()])).default({}),empties:Ot(z(),ri).default({}),view:R({location:W([I(),I(),I()]),rotation:W([I(),I(),I(),I()]),distance:I().finite(),perspective:Q(["PERSP","ORTHO","CAMERA"]),lens:I().finite().positive().default(50),shading:Q(["WIREFRAME","SOLID","MATERIAL","RENDERED"]).optional()}).nullable().optional(),subject:R({frame:I().int(),body:z(),markers:j(W([I().int(),z()]))}).optional(),units:R({system:Q(["NONE","METRIC","IMPERIAL"]),scale_length:I().finite()}).optional()}).strict();function Gi(n,t){for(let e=0,o=n.length-1;e<n.length&&o>=0;e++,o--){if(n[e][0]===t)return n[e][1];if(e===o)break;if(n[o][0]===t)return n[o][1]}return null}const Xi={METRIC:[[1e-6,"Micrometers"],[.001,"Millimeters"],[.01,"Centimeters"],[.1,"10 Centimeters"],[1,"Meters"],[10,"10 Meters"],[100,"100 Meters"],[1e3,"Kilometers"]],IMPERIAL:[[254e-7,"Thou"],[.0254,"Inches"],[.3048,"Feet"],[.9144,"Yards"],[20.1168,"Chains"],[201.168,"Furlongs"],[1609.344,"Miles"]]};class Ge{constructor(){this.root=new ut,this.instances=new Oi(this.root),this.materialRanges=new Ni,this.transparentInstances=new Pi(this.root),this.motionGeometry=new Ri(_t),this.drawBatching=!0,this.objects=new Map,this.meshes=new Map,this.volumes=new Map,this.materials=new Map,this.lights=new Map,this.lighting=new rs,this.world=new Cn,this.armatureOverlay=new dr,this.weightOverlay=new Qs,this.cursorOverlay=new ai,this.extrasOverlay=new li,this.armatureRoot=new ut,this.weightRoot=new ut,this.cursorRoot=new ut,this.cameraExtrasRoot=new ut,this.lightExtrasRoot=new ut,this.emptyExtrasRoot=new ut,this.rendered=!1,this.heldRendered=null,this.worldApplied=null,this.worldKey="null",this.capturing=!1,this.workbench=!1,this.workbenchMaterials=new Map,this.fallback=new ae({color:12172998,roughness:.72}),this.textures=new Map,this.textureNames=new Map,this.roughnessTextureNames=new Map,this.textureSamplers=new Bs,this.graphSamplers=new Map,this.photograph=!1,this.graphs=new Map,this.frame=null,this.retiredSessions=new Set,this.geometryBuilds=0,this.submittedMeshes=new Map,this.submitted=null,this.submittedSession=null,this.photographs=[],this.frameListeners=new Set,this.followers=new Set,this.leader=null,this.cameraViewZoom=ui,this.cameraViewPan=di,this.mode=null,this.drawPreparation={last:null,navigation:null},this.awaitedImages=new Set,this.lookingThrough=null,this.staged=null;const t=this.root.updateMatrixWorld.bind(this.root);this.root.updateMatrixWorld=e=>{t(e),this.instances.sync()},this.root.name="Model",this.root.matrixAutoUpdate=!1,this.root.matrix.set(1,0,0,0,0,0,1,0,0,-1,0,0,0,0,0,1),this.root.updateMatrixWorld(!0);for(const[e,o]of[[this.armatureRoot,this.armatureOverlay.group],[this.weightRoot,this.weightOverlay.group],[this.cursorRoot,this.cursorOverlay.group],[this.cameraExtrasRoot,this.extrasOverlay.cameras],[this.lightExtrasRoot,this.extrasOverlay.lights],[this.emptyExtrasRoot,this.extrasOverlay.empties]])e.matrixAutoUpdate=!1,e.matrix.copy(this.root.matrix),e.add(o),e.updateMatrixWorld(!0);this.armatureRoot.name="BlenderBones",this.weightRoot.name="BlenderWeights",this.cursorRoot.name="Blender3DCursor",this.cameraExtrasRoot.name="BlenderCameraExtras";for(const e of[this.cameraExtrasRoot,this.lightExtrasRoot,this.emptyExtrasRoot])e.userData.volterPickable=!0;this.lightExtrasRoot.name="BlenderLightExtras",this.emptyExtrasRoot.name="BlenderEmptyExtras"}compiledGraph(t){const e=JSON.stringify(t);let o=this.graphs.get(e);return o||(o=Es(t),this.graphs.size>256&&this.graphs.clear(),this.graphs.set(e,o)),o}mirrorPose(t){let e=null;for(const[a,s]of this.objects)if(s===t){e=a;break}if(e===null)return;const o=this.leader?[this.leader,...this.leader.followers]:[...this.followers];let r=!1;for(const a of o){if(a===this)continue;const s=a.objects.get(e);s!==void 0&&(s.matrix.copy(t.matrix),s.matrix.decompose(s.position,s.quaternion,s.scale),s.updateMatrixWorld(!0),r=!0)}r&&_t()}subscribeFrames(t){return this.frameListeners.add(t),()=>{this.frameListeners.delete(t)}}onChange(t){const e=this.subscribeFrames(t),o=Ja(t);return()=>{e(),o()}}blenderObjectName(t){for(const[e,o]of this.objects)if(o===t)return this.frame?.objects.find(r=>r.id===e)?.name??null;return null}noteSavedShading(t){this.frame?.view&&(this.frame.view.shading=t)}savedView(){const t=this.frame?.view;if(!t)return null;const[e,o,r,a]=t.rotation,s=new St(o,r,a,e),f=new b(...t.location).applyMatrix4(this.root.matrix),c=d=>d.applyQuaternion(s).applyMatrix4(this.root.matrix).normalize();return{target:f.toArray(),direction:c(new b(0,0,1)).toArray(),up:c(new b(0,1,0)).toArray(),distance:t.distance,projection:t.perspective==="ORTHO"?"orthographic":"perspective",lens:t.lens,drawMode:t.shading?Ii[t.shading]:null}}cameraViewCamera(){const t=this.frame,e=t?.camera_view;return!t||!e?null:e.scene_camera!==null&&t.cameras[e.scene_camera]?e.scene_camera:t.active!==null&&t.cameras[t.active]?t.active:e.view_layer_cameras.find(o=>t.cameras[o])??null}blenderPose(t,e){const o=new q().copy(this.root.matrix).invert(),r=new q().compose(new b(...t),new St(...e),new b(1,1,1)).premultiply(o),a=new b,s=new St;return r.decompose(a,s,new b),{location:a.toArray(),rotation:[s.w,s.x,s.y,s.z]}}cameraView(t,e,o,r){const a=this.frame,s=vo.safeParse(a?.cameras[t]);return!a?.camera_view||!s.success?null:mi(s.data,this.root.matrix,e,o,r,a.camera_view.aspect)}subjectLine(t){const e=this.frame?.subject;if(e===void 0)return null;const o=t??e.frame,r=Gi(e.markers,o);return`(${o})${e.body}${r===null?"":` <${r}>`}`}gridUnitName(t){const e=this.frame?.units;if(e===void 0||e.system==="NONE")return null;const o=Xi[e.system],r=6*t,a=1/(e.scale_length||1);return(o.find(([f])=>f*a>r)??o[o.length-1])[1]}blenderSelection(){const t=this.frame;return t===null?{selected:[],active:null}:{selected:t.objects.filter(e=>e.selected).map(e=>e.name),active:t.active}}setStageMode(t){this.mode=t}stageMode(){return this.mode}objectForBlenderName(t){const e=this.frame?.objects.find(o=>o.name===t);return e===void 0?null:this.objects.get(e.id)??null}replacePresentedObject(t,e){for(const[o,r]of this.objects)if(r===t){const a=t.parent,s=[...t.children];t.removeFromParent();for(const f of s)e.add(f);a?.add(e),this.objects.set(o,e),this.rebuildInstances();return}}studioLights(){return this.lighting.group}overlayGroups(){return[{kind:"skeletons",object:this.armatureRoot},{kind:"weights",object:this.weightRoot},{kind:"cursor",object:this.cursorRoot},{kind:"cameras",object:this.cameraExtrasRoot},{kind:"lights",object:this.lightExtrasRoot},{kind:"empties",object:this.emptyExtrasRoot}]}placeCursor(t,e,o){const r=new Set(this.objects.values()),a=this.cursorOverlay.placementAt(t,e,o,this.root,s=>r.has(s));return a!==null&&(this.cursorOverlay.show(a),_t()),a}holdRendered(t){t!==this.heldRendered&&(this.heldRendered=t,!this.capturing&&this.report(t===null?this.applyRendered(!1):this.applyRendered(!0,t())))}refreshRendered(){if(this.heldRendered===null||this.capturing)return;const t=this.heldRendered();this.worldKeyFor(t)!==this.worldApplied&&this.report(this.applyRendered(!0,t))}worldKeyFor(t){const o=t.isOrthographicCamera?t.getWorldDirection(new b).toArray().map(r=>r.toFixed(1)).join(","):"";return`${t.uuid}:${o}:${this.worldKey}`}report(t){t.then(_t,e=>console.error(`Rendered shading could not be applied: ${e instanceof Error?e.message:String(e)}`))}setWorkbench(t){t!==this.workbench&&(this.workbench=t,this.applyWorkbench(),_t())}applyWorkbench(){const t=this.workbench&&!this.rendered,e=new Set;for(const o of this.frame?.objects??[]){if(o.mesh===null||o.volume)continue;const r=this.objects.get(o.id);if(!r?.isMesh)continue;const s=(o.materials.length?o.materials:[null]).map(f=>{const c=f===null?this.fallback:this.materials.get(f)??this.fallback;return t?this.workbenchFor(f,c.side,e):c});r.material=o.materials.length?s:s[0]}for(const[o,r]of this.workbenchMaterials)e.has(o)||(r.dispose(),this.workbenchMaterials.delete(o));this.rebuildInstances()}rebuildInstances(){this.transparentInstances.clear(),this.instances.rebuild(this.objects.values(),this.drawBatching&&!this.rendered),this.drawBatching&&!this.rendered&&this.transparentInstances.setObjects(this.objects.values()),this.motionGeometry.setObjects(this.objects.values()),this.materialRanges.setObjects(this.drawBatching&&!this.rendered?this.objects.values():[])}setDrawBatching(t){t!==this.drawBatching&&(this.drawBatching=t,this.rebuildInstances(),_t())}prepareDraw(t,e){try{const o=performance.now();this.instances.prepareDraw(t),this.root.updateMatrixWorld(!0);const r=performance.now(),a=this.motionGeometry.prepare(t,!this.rendered&&(this.mode??this.frame?.mode)==="OBJECT"&&e?.interactive===!0,e?.height??0);a&&this.instances.sync();const s=performance.now();this.materialRanges.prepare();const f=performance.now();this.transparentInstances.prepare(t,e?.multiDraw===!0);const c={opaqueMs:r-o,motionMs:s-r,rangesMs:f-s,transparentMs:performance.now()-f};this.drawPreparation.last=c,a&&(this.drawPreparation.navigation=c)}catch(o){throw this.materialRanges.finish(),this.motionGeometry.finish(),this.instances.finishDraw(),this.transparentInstances.finishDraw(),o}return()=>{this.materialRanges.finish(),this.motionGeometry.finish(),this.instances.finishDraw(),this.transparentInstances.finishDraw()}}workbenchFor(t,e,o){const r=(t!==null?this.frame?.materials[t]?.viewport:void 0)??_i,a=`${r.color.join(",")}|${r.roughness}|${r.metallic}|${e}`;o.add(a);let s=this.workbenchMaterials.get(a);return s||(s=bi(r,e),this.workbenchMaterials.set(a,s)),s}renderedHeld(){return this.heldRendered!==null}async setRendered(t,e){return this.capturing=t,!t&&this.heldRendered!==null?this.applyRendered(!0,this.heldRendered()):this.applyRendered(t,e)}async applyRendered(t,e){const o=(t?_o(this.frame?.world)?.extinction:null)??new b;for(const a of[...this.materials.values(),this.fallback])qs(a,o);this.rendered=t,this.lighting.setRendered(t);const r=t&&e?this.worldKeyFor(e):null;t?(this.capturing||r!==this.worldApplied)&&this.world.apply(this.root,this.frame?.world??null,e):this.world.clear(),this.worldApplied=this.capturing?null:r,this.applyVisibility(),this.applyWorkbench(),this.applyShadows(t,e),t&&(await ts(),await Promise.all([...this.textures.values()].map(a=>a.ready)),await this.world.ready())}applyShadows(t,e){this.root.updateMatrixWorld(!0);const o=[];for(const c of this.objects.values()){const d=c;if(d.isMesh&&(d.castShadow=t,d.receiveShadow=t,t&&d.visible)){const l=new me().setFromObject(d);l.isEmpty()||o.push(l)}}if(!t||!o.length)return;const a=o.reduce((c,d)=>c.union(d),new me).getBoundingSphere(new Nn),s=e?new Ke().setFromProjectionMatrix(new q().multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse)):null,f=s?o.flatMap(c=>fs(c,s)):[];for(const c of this.lights.values())c.isDirectionalLight&&e?cs(c,f,o):os(c,a.center,a.radius)}applyOverlays(t){const e=s=>{const f=t.objects.find(c=>c.name===s);return f===void 0?null:new q().set(...f.matrix.flat())},o=[...this.armatureOverlay.apply(t.armatures,e)],r=t.weights?this.objects.get(t.objects.find(s=>s.name===t.weights?.object)?.id??""):void 0,a=this.weightOverlay.apply(t.weights,r??null,t.weights?e(t.weights.object):null);return a!==null&&o.push(a),this.cursorOverlay.apply(t.cursor),this.applyExtras(t),o}setCameraViewShowing(t){this.lookingThrough!==t&&(this.lookingThrough=t,this.frame&&this.applyExtras(this.frame),_t())}applyExtras(t){const e={};for(const[o,r]of Object.entries(t.cameras)){const a=vo.safeParse(r);a.success&&(e[o]=a.data)}this.extrasOverlay.apply({lookingThrough:this.lookingThrough,lightDistances:t.light_distances,objects:t.objects.filter(o=>o.visible),active:t.active,cameras:e,lights:t.lights,empties:t.empties,sceneCamera:t.camera_view?.scene_camera??null,renderAspect:t.camera_view?.aspect??1,presented:o=>{const r=t.objects.find(a=>a.name===o);return r?this.objects.get(r.id)??null:null},image:o=>{const r=this.textures.get(o);if(!r)return null;const a=r.texture.image,s=r.width||a?.width||0,f=r.height||a?.height||0;return(s===0||f===0)&&r.ready&&!this.awaitedImages.has(o)&&(this.awaitedImages.add(o),r.ready.then(()=>{this.awaitedImages.delete(o),this.frame&&this.applyExtras(this.frame),_t()},()=>this.awaitedImages.delete(o))),{texture:r.texture,width:s,height:f}}})}applyVisibility(){for(const t of this.frame?.objects??[]){const e=this.objects.get(t.id);if(e&&(e.visible=this.rendered?t.render_visible:t.visible),!t.light)continue;const o=this.lights.get(t.light);o&&(o.visible=this.rendered&&t.render_visible)}this.armatureOverlay.group.visible=!this.capturing,this.weightOverlay.group.visible=!this.capturing,this.cursorOverlay.group.visible=!this.capturing;for(const t of[this.extrasOverlay.cameras,this.extrasOverlay.lights,this.extrasOverlay.empties])t.visible=!this.capturing}stageFrame(t){if(t.abort||!t.mesh&&!t.image){for(const o of this.staged?.meshes.values()??[])o.geometry.dispose();this.staged=t.abort?null:{session:t.session,revision:t.revision,meshes:new Map,images:new Map};return}const e=this.staged;if(!e||e.session!==t.session||e.revision!==t.revision)throw new Error("Blender frame piece does not belong to the pending revision");if(t.mesh!==void 0){const o=sa.parse(t.piece);if(e.meshes.has(t.mesh))throw new Error("Duplicate Blender mesh piece");const r=`revision:${o.revision}`;e.meshes.set(t.mesh,{signature:r,geometry:$e(Kn({...o.columns,attributes:o.attributes,activeUv:o.activeUv,renderUv:o.renderUv},r))})}else if(t.image!==void 0){if(e.images.has(t.image))throw new Error("Duplicate Blender image piece");e.images.set(t.image,ia.parse(t.piece))}}applyFrame(t){const e=this.frame===null?null:{session:this.frame.session,revision:this.frame.revision},o=Hi.parse(t),r=this.staged;if(r&&(r.session!==o.session||r.revision!==o.revision))throw new Error("Blender frame manifest does not match its staged revision");if(r)for(const[l,i]of r.images)o.images[l]=i;if(this.retiredSessions.has(o.session))throw new Error("The runtime session was replaced; its delayed frame cannot overwrite the active model");if(this.frame?.session===o.session&&o.revision<this.frame.revision)throw new Error("The runtime frame is older than the displayed model");const a=new Set(o.objects.map(l=>l.id));if(a.size!==o.objects.length)throw new Error("Runtime object IDs must be unique");const s=new Map(o.objects.map(l=>[l.id,l]));for(const l of o.objects){if(l.mesh!==null&&!o.meshes[l.mesh])throw new Error(`Missing runtime mesh ${l.mesh}`);if(l.volume&&(!o.volumes[l.volume]||l.mesh!==null))throw new Error(`Invalid runtime volume ${l.volume}`);if(l.light&&(!o.lights[l.light]||l.mesh!==null))throw new Error(`Invalid runtime light ${l.light}`);for(const m of l.materials)if(m!==null&&!o.materials[m])throw new Error(`Missing runtime material ${m}`);const i=new Set([l.id]);let u=l.parent;for(;u!==null;){if(i.has(u))throw new Error("Runtime parent cycle");i.add(u);const m=s.get(u);if(!m)throw new Error(`Missing runtime parent ${u}`);u=m.parent}}const f=new Map,c=new Map;try{for(const[l,i]of Object.entries(o.volumes)){const u=JSON.stringify(i);this.frame?.session===o.session&&this.volumes.get(l)?.signature===u||c.set(l,{signature:u,mesh:us(i)})}for(const[l,i]of Object.entries(o.meshes)){if("unchanged"in i){const _=r?.meshes.get(l);if(_){if(_.signature!==`revision:${i.revision}`)throw new Error("Staged Blender mesh revision mismatch");f.set(l,_);continue}const p=this.meshes.get(l)?.signature;if(this.frame?.session===o.session&&p!==void 0&&(p===`revision:${i.revision}`||!p.startsWith("revision:")))continue;throw new Error(p===void 0?`${Xn}: the presenter does not hold runtime mesh ${l} (store ${i.store}, revision ${i.revision})`:`${Xn}: the presenter holds runtime mesh ${l} at ${p}, not revision ${i.revision}`)}const u="hash"in i,m="columns"in i,h=m?`revision:${i.revision}`:u?i.hash:JSON.stringify(i);this.frame?.session===o.session&&this.meshes.get(l)?.signature===h||f.set(l,{signature:h,geometry:m?$e(Kn({...i.columns,attributes:i.attributes,activeUv:i.activeUv,renderUv:i.renderUv},h)):u?$e(i):Mr(i)})}}catch(l){for(const i of f.values())i.geometry.dispose();for(const{mesh:i}of c.values())i.geometry.dispose(),i.material.dispose();throw l}if(r){for(const[l,i]of r.meshes)f.has(l)||i.geometry.dispose();this.staged=null}this.frame?.session!==o.session&&(this.frame&&this.retiredSessions.add(this.frame.session),this.clear());for(const[l,i]of c){const u=this.volumes.get(l)?.mesh;u&&(u.removeFromParent(),u.geometry.dispose(),u.material.dispose()),this.volumes.set(l,i)}for(const[l,i]of f)this.meshes.get(l)?.geometry.dispose(),this.meshes.set(l,i),this.geometryBuilds++;for(const[l,i]of Object.entries(o.images)){const u=this.textures.get(l);if("width"in i){const g=i.rgba??(i.rgbaBase64?vn(i.rgbaBase64):void 0);if(!g)throw new Error(`Runtime image ${l} carries no raster`);const v=i.tiles?Bi(l,i.tiles,i.colorspace??"sRGB"):void 0;if(u?.udim&&(u.udim.tiles.dispose(),u.udim.map.dispose(),delete u.udim),u&&u.width===i.width&&u.height===i.height){const w=u.texture.image;if(w.data){w.data.set(g),u.texture.needsUpdate=!0,u.revision=i.revision,v&&(u.udim=v);continue}}u?.texture.dispose(),this.textures.set(l,{texture:Vi(g,i.width,i.height,i.colorspace??"sRGB"),width:i.width,height:i.height,revision:i.revision,...v?{udim:v}:{}});continue}const m=i.encoded??(i.encodedBase64?vn(i.encodedBase64):void 0);if(!m)throw new Error(`Runtime image ${l} carries no bytes`);u?.texture.dispose(),u?.udim?.tiles.dispose(),u?.udim?.map.dispose();const h=i.colorspace??"sRGB",{texture:_,ready:p}=ji(m,i.mime);_.colorSpace=h==="data"?Ue:Ht,this.textures.set(l,{texture:_,ready:p,width:0,height:0,revision:i.revision,encoded:{bytes:m.slice(),mime:i.mime,colorspace:h}})}for(const[l,i]of Object.entries(o.materials)){const u=this.materials.get(l)??new ae;u.name=i.name;const m=i.texture?.tint;i.texture!==void 0?u.color.setRGB(m?.[0]??1,m?.[1]??1,m?.[2]??1,xt):u.color.setRGB(i.color[0],i.color[1],i.color[2],xt),u.opacity=i.color[3];const h=u.opacity<1||i.graph!==void 0&&ps(i.graph);u.transparent!==h&&(u.transparent=h,u.needsUpdate=!0),u.roughness=i.roughness,u.metalness=i.metallic,u.transmission=i.transmission,u.ior=i.ior,$n(u,i.physical,{map:i.texture?.extension==="CLIP",roughness:i.roughness_texture?.extension==="CLIP",normal:i.normal_texture?.extension==="CLIP"});const _=i.normal_texture?.image.name;if(_===void 0)u.normalMap&&(this.textureSamplers.delete(`${l}:normal`),u.normalMap=null,u.needsUpdate=!0);else{const x=this.textures.get(_);if(!x)throw new Error(`${he}: missing normal image ${_}`);const T=this.textureSamplers.get(`${l}:normal`,x.texture,i.normal_texture.extension,x.ready,i.normal_texture.uv);u.normalMap!==T&&(u.normalMap=T,u.needsUpdate=!0);const y=i.normal_space==="OBJECT"?Ca:Fa;u.normalMapType!==y&&(u.normalMapType=y,u.needsUpdate=!0),u.normalScale.set(i.normal_strength,i.normal_strength*(i.normal_directx?-1:1))}i.emission?(u.emissive.setRGB(i.emission.color[0],i.emission.color[1],i.emission.color[2],xt),u.emissiveIntensity=i.emission.strength):(u.emissive.setRGB(0,0,0),u.emissiveIntensity=1);const p=i.roughness_texture?.image.name??null;if(p===null)this.roughnessTextureNames.has(l)&&(this.textureSamplers.delete(`${l}:roughness`),u.roughnessMap=null,this.roughnessTextureNames.delete(l),u.needsUpdate=!0);else{const x=this.textures.get(p);if(!x)throw new Error(`${he}: the presenter does not hold runtime image ${p} (revision ${i.roughness_texture.image.revision})`);const T=this.textureSamplers.get(`${l}:roughness`,x.texture,i.roughness_texture.extension,x.ready,i.roughness_texture.uv);u.roughnessMap!==T&&(u.roughnessMap=T,this.roughnessTextureNames.set(l,p),u.needsUpdate=!0)}const g=i.texture?.image.name??null;if(g===null)this.textureNames.has(l)&&(this.textureSamplers.delete(`${l}:color`),u.map=null,this.textureNames.delete(l),u.needsUpdate=!0);else{const x=this.textures.get(g);if(!x)throw new Error(`${he}: the presenter does not hold runtime image ${g} (revision ${i.texture.image.revision})`);const T=this.textureSamplers.get(`${l}:color`,x.texture,i.texture.extension,x.ready,i.texture.uv);u.map!==T&&(u.map=T,this.textureNames.set(l,g),u.needsUpdate=!0)}const v=i.graph?this.compiledGraph(i.graph):null,w=new Set;Rs(u,v,x=>{const T=this.textures.get(x.name);if(!T)throw new Error(`${he}: the presenter does not hold runtime image ${x.name} (revision ${x.revision})`);if(x.tiled){if(!T.udim)throw new Error(`${he}: runtime image ${x.name} arrived without its UDIM tiles`);return T.udim}const y=`${l}:graph:${x.node}`;w.add(y);const A=this.textureSamplers.get(y,T.texture,x.extension,T.ready),M=x.closest?pn:oe,P=x.closest?pn:x.mipmap?ko:oe;return(A.magFilter!==M||A.minFilter!==P)&&(A.magFilter=M,A.minFilter=P,A.needsUpdate=!0),A},this.photograph);for(const x of this.graphSamplers.get(l)??[])w.has(x)||this.textureSamplers.delete(x);this.graphSamplers.set(l,w),this.materials.set(l,u)}for(const l of o.objects){let i=this.objects.get(l.id);const u=l.volume?this.volumes.get(l.volume).mesh:null;if((!i||(u?i!==u:!!i.isMesh!=(l.mesh!==null)))&&(i?.removeFromParent(),i=u??(l.mesh!==null?new kt(this.meshes.get(l.mesh).geometry,this.fallback):new Ve),this.objects.set(l.id,i)),i.name=l.name,l.type==="CAMERA"||l.type==="LIGHT"||l.type==="EMPTY"?i.userData.volterOwnOverlay=!0:delete i.userData.volterOwnOverlay,i.matrixAutoUpdate=!1,i.matrix.set(...l.matrix.flat()),l.parent){const m=new q().set(...s.get(l.parent).matrix.flat());i.matrix.premultiply(m.invert())}if(i.matrix.decompose(i.position,i.quaternion,i.scale),l.texspace?i.userData.blenderTexspace=l.texspace:delete i.userData.blenderTexspace,l.default_color!==void 0?i.userData.blenderDefaultColor=l.default_color:delete i.userData.blenderDefaultColor,l.mesh!==null){const m=i;m.geometry=this.meshes.get(l.mesh).geometry,m.material=l.materials.length?l.materials.map(h=>h===null?this.fallback:this.materials.get(h)):this.fallback,ks(m)}if(l.light){const m=this.lights.get(l.light)??null,h=ns(o.lights[l.light],m);m&&m!==h&&(m.removeFromParent(),m.dispose()),h.parent!==i&&i.add(h),h.userData.volterOwnOverlay=!0,as(h,i),this.lights.set(l.light,h)}}for(const l of o.objects){const i=this.objects.get(l.id),u=l.parent===null?this.root:this.objects.get(l.parent);i.parent!==u&&u.add(i)}for(const[l,i]of this.objects)a.has(l)||(i.removeFromParent(),this.objects.delete(l));for(const[l,i]of this.volumes)o.volumes[l]||(i.mesh.geometry.dispose(),i.mesh.material.dispose(),this.volumes.delete(l));for(const[l,i]of this.meshes)o.meshes[l]||(i.geometry.dispose(),this.meshes.delete(l));for(const[l,i]of this.materials)if(!o.materials[l]){for(const u of["normal","roughness","color"])this.textureSamplers.delete(`${l}:${u}`);for(const u of this.graphSamplers.get(l)??[])this.textureSamplers.delete(u);this.graphSamplers.delete(l),i.dispose(),this.materials.delete(l)}for(const[l,i]of this.lights)o.lights[l]||(i.removeFromParent(),i.dispose(),this.lights.delete(l));this.root.updateMatrixWorld(!0),this.frame={...o,meshes:{},volumes:{},images:{}},this.worldKey=JSON.stringify(o.world??null);const d=this.applyOverlays(o);d.length&&(this.frame={...this.frame,warnings:[...this.frame.warnings,...d]}),this.applyVisibility(),this.applyWorkbench(),this.heldRendered!==null&&!this.capturing&&this.report(this.applyRendered(!0,this.heldRendered()));for(const l of[...this.frameListeners])l();for(const l of this.followers)try{l.applyFrame(t)}catch{l.applyFrame(this.fullFrame())}return{...this.inspect(),held:e}}inspect(){return{session:this.frame?.session,revision:this.frame?.revision,active:this.frame?.active,mode:this.frame?.mode,geometryBuilds:this.geometryBuilds,instancing:this.drawStatistics(),objects:[...this.objects].map(([t,e])=>({id:t,name:e.name,uuid:e.uuid,geometry:e.geometry?.uuid,visible:e.visible}))}}drawStatistics(){return{enabled:this.drawBatching,preparation:{...this.drawPreparation},materialRanges:this.materialRanges.inspect(),opaque:this.instances.inspect(),transparent:this.transparentInstances.inspect(),motion:this.motionGeometry.inspect()}}snapshot(){return this.frame}fullFrame(){const t=this.frame;if(!t)throw new Error("Blender capture requires a presented frame");const e=structuredClone({...t,images:{},armatures:{},weights:null});for(const[r,{signature:a,geometry:s}]of this.meshes){const f=l=>{const i=s.getAttribute(l);if(!i)return null;if(!(i instanceof lt))throw new Error(`Blender capture cannot copy interleaved ${l}`);return new Float32Array(i.array)},c=f("position");if(!c)throw new Error(`Blender capture mesh ${r} has no positions`);const d=s.getIndex();e.meshes[r]={hash:a,positions:c,normals:f("normal"),uv:f("uv"),uvLayers:Object.entries(s.userData.blenderUvChannels??{}).map(([l,i])=>{const u=f(`uv${i}`);if(!u)throw new Error(`Blender capture mesh ${r} is missing UV layer ${l}`);return{name:l,data:u}}),orco:s.userData.blenderOrcoFromDoor?f("blenderOrco"):null,attributeLayers:(s.userData.blenderAttributes??[]).map(l=>{const i=f(qt(l));if(!i)throw new Error(`Blender capture mesh ${r} is missing attribute ${l}`);return{name:l,data:i}}),indices:d?new Uint32Array(d.array):Uint32Array.from({length:c.length/3},(l,i)=>i),groups:s.groups.map(l=>({start:l.start,count:l.count,materialIndex:l.materialIndex??0}))}}for(const[r,{signature:a}]of this.volumes)e.volumes[r]=Zo.parse(JSON.parse(a));const o=new Set(Object.values(e.materials).flatMap(r=>[r.texture?.image.name,r.roughness_texture?.image.name,r.normal_texture?.image.name,...Object.values(r.graph?.nodes??{}).map(a=>a.props.image?.name)].filter(a=>a!==void 0)));for(const r of o){const a=this.textures.get(r);if(!a)throw new Error(`Blender capture image ${r} is not resident`);if(a.encoded)e.images[r]={revision:a.revision,encoded:a.encoded.bytes.slice(),mime:a.encoded.mime,colorspace:a.encoded.colorspace};else{const s=a.texture.image?.data;if(!(s instanceof Uint8Array))throw new Error(`Blender capture image ${r} has no resident raster`);e.images[r]={revision:a.revision,width:a.width,height:a.height,rgba:s.slice(),colorspace:a.texture.colorSpace===Ue?"data":"sRGB",...a.udim?{tiles:a.udim.frame}:{}}}}return e}follow(){const t=new Ge;this.frame&&t.applyFrame(this.fullFrame()),this.followers.add(t),t.leader=this;let e=!1;return{view:t,dispose:()=>{e||(e=!0,this.followers.delete(t),t.leader=null,t.dispose(),t.root.removeFromParent())}}}captureSnapshot(){const t=this.fullFrame(),e=this.frame,o=this.createWorldVolumePass(),r=new Ge;r.photograph=!0;let a=!1;const s=()=>{a||(a=!0,o?.dispose(),r.dispose(),r.root.removeFromParent())};try{r.applyFrame(t),this.root.updateWorldMatrix(!0,!1),r.root.matrix.copy(this.root.matrixWorld),r.root.updateMatrixWorld(!0)}catch(f){throw s(),f}return{effect:o,root:r.root,session:e.session,revision:e.revision,prepare:f=>{if(a)throw new Error("Blender capture snapshot is disposed");return r.setRendered(!0,f)},dispose:s}}createWorldVolumePass(){const t=_o(this.frame?.world);return t?new Gs(t):void 0}recordPresentation(t){if(typeof t!="object"||t===null)return;const e=t,o=e.meshes;if(typeof o!="object"||o===null)return;const r=typeof e.session=="string"?e.session:null;r!==this.submittedSession&&(this.submittedMeshes.clear(),this.photographs.length=0,this.submittedSession=r);const a=o;for(const[s,f]of Object.entries(a))typeof f=="object"&&f!==null&&!("unchanged"in f)&&this.submittedMeshes.set(s,f);for(const s of[...this.submittedMeshes.keys()])s in a||this.submittedMeshes.delete(s);this.submitted={...e,meshes:Object.fromEntries(this.submittedMeshes)}}recordPhotograph(t){this.photographs.push(t)}observations(){return{presentation:this.submitted,photographs:this.photographs}}clear(){this.materialRanges.clear(),this.motionGeometry.clear(),this.transparentInstances.clear(),this.instances.clear();for(const t of this.staged?.meshes.values()??[])t.geometry.dispose();this.staged=null;for(const t of this.lights.values())t.removeFromParent(),t.dispose();this.lights.clear();for(const t of this.objects.values())t.removeFromParent();for(const t of this.meshes.values())t.geometry.dispose();for(const t of this.materials.values())t.dispose();for(const{mesh:t}of this.volumes.values())t.geometry.dispose(),t.material.dispose();for(const{texture:t,udim:e}of this.textures.values())t.dispose(),e?.tiles.dispose(),e?.map.dispose();this.textures.clear(),this.textureNames.clear(),this.roughnessTextureNames.clear(),this.textureSamplers.clear(),this.volumes.clear(),this.objects.clear(),this.meshes.clear(),this.materials.clear()}dispose(){this.clear(),this.fallback.dispose(),this.lighting.dispose(),this.world.dispose(),this.armatureOverlay.dispose(),this.weightOverlay.dispose(),this.cursorOverlay.dispose(),this.extrasOverlay.dispose();for(const t of this.workbenchMaterials.values())t.dispose();this.workbenchMaterials.clear(),this.frame=null,this.retiredSessions.clear(),this.submittedMeshes.clear(),this.submitted=null,this.submittedSession=null,this.photographs.length=0}}const ol=new Ge;function la(n){const t=atob(n),e=new Uint8Array(t.length);for(let o=0;o<t.length;o++)e[o]=t.charCodeAt(o);return e}function mn(n){const t=la(n);return new Float32Array(t.buffer,t.byteOffset,t.byteLength>>2)}function Yi(n){const t=la(n);return new Uint16Array(t.buffer,t.byteOffset,t.byteLength>>1)}function Zi(n){return new q().set(...n.flat())}function Mo(n,t){return[n.object,n.mesh,n.armature,n.vertexCount,n.bones.length,t].join("|")}class Ki{#e=new Map;#o=null;#a=null;#t=null;#r=null;#n=null;#s=null;#l=new Set;#u=0;#d=[];#i=0;get version(){return this.#u}get engineCalls(){return this.#i}subscribe(t){return this.#l.add(t),()=>this.#l.delete(t)}#f(){this.#u++;for(const t of[...this.#l])t()}state(){const t=this.#t,e=t?.frameStart??1,o=t?.frameEnd??250,r=t?.fps??24;return{frame:this.frame(),start:e,end:o,fps:r,action:t?.action??null,object:t?.object??null,armature:t?.armature??null,bones:[...this.#e.values()].reduce((a,s)=>a+s.bones.length,0),keyframes:t?.keyframes??[],summary:t?.summary??[],clipStart:t?.clipStart??null,clipEnd:t?.clipEnd??null,tracks:t?.tracks.length??0,bound:[...this.#e.keys()],warnings:this.#d,engineCalls:this.#i,blenderFrame:t?.frameCurrent??null}}playhead(){return this.#t?this.frame():null}frame(){const t=this.#t;return this.#r!==null?this.#r:!t||!this.#a||t.clipStart===void 0?t?.frameCurrent??1:t.clipStart+this.#a.time*t.fps}get playable(){return this.#t!==null&&this.#n!==null}async bind(t,e){this.#i++;const o=await e.rig();if(!o)return;const r=[],a=new Set;let s=!1;for(const m of o.rigs){if(!m.object||!m.armature||!m.skinIndexBase64||!m.skinWeightBase64){m.reason&&r.push(m.reason);continue}a.add(m.object);const h=Mo(m,o.frame);if(this.#e.get(m.object)?.signature===h)continue;const _=this.#_(t,m,o.frame,r);_&&(this.#e.get(m.object)?.skeleton.dispose(),this.#e.set(m.object,_),s=!0)}for(const[m,h]of[...this.#e])a.has(m)||(h.skeleton.dispose(),h.boneRoot.removeFromParent(),this.#e.delete(m),s=!0);this.#i++;const f=await e.clip(),c=this.#t,d=f?.frameStart!==c?.frameStart||f?.frameEnd!==c?.frameEnd||f?.fps!==c?.fps,l=f?.action!==c?.action||f?.tracks.length!==c?.tracks.length||f?.clipStart!==c?.clipStart||f?.clipEnd!==c?.clipEnd;this.#t=f??null,(!f||f.scene!==c?.scene)&&(this.#r=null),f?.reason&&r.push(f.reason),f&&(l||s)&&this.#h(t,f,r);const i=this.#n?.snapshot().activeSubject;d&&i&&this.#n?.setActiveSubject(i);const u=this.#n?.snapshot().playbackState==="playing";f&&!u&&(d||c?.frameCurrent!==f.frameCurrent)&&(this.#c(f.frameCurrent),this.#n&&f.fps>0&&this.#n.seek(f.frameCurrent/f.fps)),this.#d=r,this.#f()}#_(t,e,o,r){const a=t.objectForBlenderName(e.object??""),s=t.objectForBlenderName(e.armature??"");if(!a||!s)return null;const f=a,c=f.geometry;if(!c)return null;const d=c.getAttribute("blenderVertex");if(!d)return r.push(`"${e.object}" cannot be skinned: its presented geometry carries no \`blenderVertex\` attribute, so a per-Blender-vertex weight cannot be expanded onto its drawn vertices.`),null;if(e.vertexCount===0)return null;let l=0;for(let y=0;y<d.count;y++)l=Math.max(l,d.getX(y));if(l>=e.vertexCount)return r.push(`"${e.object}" is not skinned here: its presented geometry references Blender vertex ${l} while the mesh declares ${e.vertexCount}, which is a generative modifier (Subdivision, Mirror, Array…) between the two. Blender's own viewport shows the evaluated result; this presenter shows the exported columns unskinned.`),null;const i=Yi(e.skinIndexBase64??""),u=mn(e.skinWeightBase64??""),m=d.count,h=new Uint16Array(m*4),_=new Float32Array(m*4);for(let y=0;y<m;y++){const A=d.getX(y);for(let M=0;M<4;M++)h[y*4+M]=i[A*4+M]??0,_[y*4+M]=u[A*4+M]??0}c.setAttribute("skinIndex",new ja(h,4)),c.setAttribute("skinWeight",new Rt(_,4));const p=new ut;p.name=`${e.armature}:bones`;const g=[],v=e.bones.map(y=>Zi(y.pose)),w=new Map(e.bones.map((y,A)=>[y.name,A]));e.bones.forEach((y,A)=>{const M=new Va;M.name=y.name,g.push(M);const P=y.parent===null?void 0:w.get(y.parent);(P===void 0?v[A].clone():v[P].clone().invert().multiply(v[A])).decompose(M.position,M.quaternion,M.scale),(P===void 0?p:g[P]).add(M)}),s.add(p);const x=new Ba(c,f.material);x.name=f.name,x.matrixAutoUpdate=!1,x.matrix.copy(f.matrix),x.matrix.decompose(x.position,x.quaternion,x.scale),x.userData=f.userData,x.frustumCulled=!1,t.replacePresentedObject(f,x),t.root.updateMatrixWorld(!0);const T=new Ua(g);return x.bind(T,x.matrixWorld.clone()),e.constrainedBones?.length&&r.push(`Bone constraints on ${e.constrainedBones.join(", ")}: the clip is derived from the F-Curves alone, so those bones play their channels rather than Blender's solved pose.`),e.unmappedGroups?.length&&r.push(`${e.object} carries vertex groups no bone is named for (${e.unmappedGroups.join(", ")}); they weight nothing here, exactly as they deform nothing in Blender.`),{object:e.object??"",armature:e.armature??"",mesh:x,boneRoot:p,bones:g,skeleton:T,frame:o,signature:Mo(e,o)}}#h(t,e,o){if(this.#o?.stopAllAction(),this.#o=null,this.#a=null,!e.tracks.length||e.clipStart===void 0||e.clipEnd===void 0)return;const r=e.armature?t.objectForBlenderName(e.armature):null;if(!r)return;const a=new Map;for(const i of this.#e.values())if(i.armature===e.armature)for(const u of i.bones)a.set(u.name,u);const s=[],f=new Set;for(const i of e.tracks){const u=a.get(i.bone);if(!u){f.add(i.bone);continue}const m=mn(i.timeBase64),h=mn(i.valueBase64),_=`${u.uuid}.${i.property}`;s.push(i.property==="quaternion"?new Wa(_,Array.from(m),Array.from(h)):new qa(_,Array.from(m),Array.from(h)))}if(f.size&&o.push(`${e.action} animates ${[...f].join(", ")}, which this binding has no bone for.`),!s.length)return;const c=e.duration??(e.clipEnd-e.clipStart)/e.fps,d=new Ha(r),l=d.clipAction(new Ga(e.action??"action",c,s));l.setLoop(Xa,Number.POSITIVE_INFINITY),l.play(),this.#o=d,this.#a=l,this.#c(e.frameCurrent),this.#m()}#c(t){const e=this.#t;if(!e)return;const o=Math.min(e.frameEnd,Math.max(e.frameStart,t));if(this.#r=o,!this.#o||e.clipStart===void 0||e.clipEnd===void 0)return;const r=(e.clipEnd-e.clipStart)/e.fps;this.#o.setTime(Math.max(0,Math.min(r-1e-4,(o-e.clipStart)/e.fps))),this.#m()}#m(){for(const t of this.#e.values())t.boneRoot.updateMatrixWorld(!0),t.skeleton.update()}get scene(){return this.#t?.scene??null}async writeBookmark(){const t=Math.round(this.frame()),e=this.#t;if(!e)return t;const o=e.scene;return!o||e.frameCurrent===t||(this.#i++,await Qa(`bpy.data.scenes[${JSON.stringify(o)}]`,"frame_current",t,void 0,!1),this.#t={...e,frameCurrent:t},this.#f()),t}get transport(){return this.#n}attachTo(t){this.#s?.(),this.#n=t;const e=t.attach({id:this.#t?.action??"blender-action",label:this.#t?.action??"Action",range:()=>{const f=this.#t,c=f?.fps||24;return{start:(f?.frameStart??1)/c,end:(f?.frameEnd??250)/c,fps:c}},seek:f=>this.seekSeconds(f)}),o=t.onSettled(()=>{this.writeBookmark()});let r=!1;const a=()=>{r||(r=!0,o(),e(),this.#s===a&&(this.#n===t&&(this.#n=null),this.#s=null))};this.#s=a;const s=this.#t;return s&&s.fps>0&&t.seek(s.frameCurrent/s.fps),a}seekSeconds(t){const e=this.#t?.fps||24;this.#c(Math.round(t*e)),this.#f()}keyframes(){return(this.#t?.keyframes??[]).map(t=>t.frame)}dispose(){this.#s?.(),this.#o?.stopAllAction(),this.#o=null,this.#a=null,this.#t=null,this.#r=null;for(const t of this.#e.values())t.skeleton.dispose(),t.boneRoot.removeFromParent();this.#e.clear()}}const fa=new Ki;function al(n){return fa.subscribe(n)}function rl(){return fa.version}export{fa as a,rl as b,ol as c,al as s};
7208
+ #include <opaque_fragment>`)},a.customProgramCacheKey=()=>"volter-blender-workbench",a}const zi=64;function ki(n,t){return Array.isArray(n)&&Array.isArray(t)?n.length===t.length&&n.every((e,o)=>e===t[o]):n===t}function Ye(n){return n.onBeforeRender===qe.prototype.onBeforeRender&&n.onAfterRender===qe.prototype.onAfterRender}function ae(n){for(let t=n;t;t=t.parent)if(!t.visible)return!1;return!0}function Nn(n){if(n.determinant()<=0)return!1;const t=n.elements,e=Math.hypot(t[0],t[1],t[2]),o=Math.hypot(t[4],t[5],t[6]),r=Math.hypot(t[8],t[9],t[10]),a=(s,l)=>t[s]*t[l]+t[s+1]*t[l+1]+t[s+2]*t[l+2];return Number.isFinite(e+o+r)&&Math.min(e,o,r)>0&&Math.abs(a(0,4))<=1e-7*e*o&&Math.abs(a(0,8))<=1e-7*e*r&&Math.abs(a(4,8))<=1e-7*o*r}class Fi{constructor(t){this.root=t,this.batches=[],this.inverse=new G,this.matrix=new G,this.box=new _e,this.projection=new G,this.frustum=new Je,this.camera=null,this.eligible=0,this.excluded={}}rebuild(t,e){if(this.clear(),!e)return;const o=new Map,r=a=>{this.excluded[a]=(this.excluded[a]??0)+1};this.inverse.copy(this.root.matrixWorld).invert();for(const a of t){const s=a;if(!s.isMesh)continue;if(!Ye(s)){r("customHooks");continue}if(s.isSkinnedMesh||s.isInstancedMesh||s.morphTargetInfluences||s.layers.mask!==1){r("deformationOrLayers");continue}const l=Array.isArray(s.material)?s.material:[s.material];if(l.some(f=>f.transparent||f.transmission>0||f.isShaderMaterial||!he(f))){r("material");continue}if(l.some(f=>ca(f,s.geometry).size>12)){r("attributeBudget");continue}if(this.matrix.multiplyMatrices(this.inverse,s.matrixWorld),!Nn(this.matrix)){r("transform");continue}this.eligible++;const u=`${s.geometry.id}:${Array.isArray(s.material)?"slots":"single"}:`+l.map(f=>f.uuid).join(",")+`:${s.renderOrder}`,m=o.get(u);m?m.push(s):o.set(u,[s])}for(const a of o.values()){if(a.length<2)continue;const s=l=>{if(l.length>zi){this.box.makeEmpty();for(const _ of l)this.box.expandByPoint(new b().setFromMatrixPosition(_.matrixWorld));const i=this.box.getSize(new b),c=i.x>=i.y&&i.x>=i.z?12:i.y>=i.z?13:14;l.sort((_,h)=>_.matrixWorld.elements[c]-h.matrixWorld.elements[c]);const d=Math.floor(l.length/2);s(l.slice(0,d)),s(l.slice(d));return}if(l.length<2)return;const u=l[0],m=new Wo(u.geometry,u.material,l.length);m.name="Blender repeated geometry",m.userData.engineInternal=!0,m.matrixAutoUpdate=!1,m.renderOrder=u.renderOrder,m.instanceMatrix.setUsage(qo);const f={draw:m,members:l.map(i=>({mesh:i,layers:i.layers.mask}))};m.raycast=(i,c)=>{for(const{mesh:d}of f.members)d.layers.mask===0&&ae(d)&&d.raycast(i,c)},this.root.add(m),m.updateMatrixWorld(!0),this.batches.push(f)};s(a)}this.sync()}sync(){if(this.batches.length){this.inverse.copy(this.root.matrixWorld).invert();for(const{draw:t,members:e}of this.batches){const r=(Array.isArray(t.material)?t.material:[t.material]).every(he);let a=0,s=!1;for(const l of e){const{mesh:u}=l;if(this.matrix.multiplyMatrices(this.inverse,u.matrixWorld),!(u.parent!==null&&u.geometry===t.geometry&&r&&Ye(u)&&ki(u.material,t.material)&&Nn(this.matrix))){u.layers.mask|=l.layers;continue}if(u.layers.mask&=~l.layers,!ae(u)||this.camera&&(!this.camera.layers.isEnabled(0)||u.frustumCulled&&!this.frustum.intersectsObject(u)))continue;const f=a*16;this.matrix.elements.some((i,c)=>Math.fround(i)!==t.instanceMatrix.array[f+c])&&(t.setMatrixAt(a,this.matrix),s=!0),a++}s||=t.count!==a||t.boundingSphere===null,t.count=a,s&&(t.instanceMatrix.needsUpdate=!0,t.computeBoundingBox(),t.computeBoundingSphere())}}}prepareDraw(t){t.updateMatrixWorld(),this.camera=t,this.projection.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this.frustum.setFromProjectionMatrix(this.projection)}finishDraw(){this.camera=null}clear(){this.camera=null;for(const{draw:t,members:e}of this.batches){for(const{mesh:o,layers:r}of e)o.layers.mask|=r;t.removeFromParent(),t.dispose()}this.batches.length=0,this.eligible=0,this.excluded={}}inspect(){return{batches:this.batches.length,instances:this.batches.reduce((t,{draw:e})=>t+e.count,0),eligible:this.eligible,excluded:{...this.excluded}}}}const Me=64,dn=4*1024*1024,$i=32*1024*1024,Li=1024;class ji{constructor(){this.families=new Map,this.partitions=new Map,this.registrations=new Map,this.bytes=0,this.drawCount=0,this.created=0,this.compiling=0,this.pending=!1,this.generation=0}begin(){this.created=0,this.pending=!1,this.registrations.clear()}beginPaletteFrame(){this.compiling=0}register(t,e,o,r){const a=`${t.id}:${e.uuid}:${o}`;if(this.registrations.has(a))return this.registrations.get(a);this.registrations.set(a,null);const s=t.getAttribute("position"),l=t.index?.count??s?.count??0;if(!s||t.drawRange.start!==0||t.drawRange.count<l||Object.keys(t.morphAttributes).length)return null;const u=[!!t.index,t.userData.blenderUvChannels??null],m=[t.index?.id,t.index?.version];let f=(t.index?.count??0)*4;for(const p of Object.keys(t.attributes).sort()){const v=t.getAttribute(p);if(!(v instanceof ft)||v.isInstancedBufferAttribute||v instanceof Ba||v.count!==s.count)return null;u.push([p,v.array.constructor.name,v.itemSize,v.normalized,v.gpuType]),m.push(p,v.id,v.version),f+=v.array.byteLength}if(f>dn)return null;const i=`multi:${e.uuid}:${o}:${JSON.stringify(u)}`;let c=this.partitions.get(i);c||(c=[],this.partitions.set(i,c));let d=c.find(p=>this.families.get(p).shapes.has(t.id));d??=c.find(p=>this.families.get(p).reservedBytes+f<=dn),d||(d=`${i}:${c.length}`,c.push(d));let _=this.families.get(d);_||(_={material:e,shapes:new Map,template:null,ids:new Map,draws:[],dirty:!0,bytes:0,reservedBytes:0,refused:!1,palette:r,compilations:new Map,drawMaterials:new Map},this.families.set(d,_));const h=JSON.stringify(m),g=_.shapes.get(t.id);return(!g||g.stamp!==h)&&(_.reservedBytes+=f-(g?.bytes??0),_.shapes.set(t.id,{geometry:t,stamp:h,bytes:f}),_.dirty=!0),this.registrations.set(a,d),d}pack(){for(const t of this.families.values()){if(!t.dirty)continue;this.release(t),t.dirty=!1;let e=0,o=0,r=0;for(const{geometry:l}of t.shapes.values()){e+=l.getAttribute("position").count,o+=l.index?.count??0;for(const u of Object.values(l.attributes))r+=u.array.byteLength}if(r+=o*(e>65535?4:2),t.refused=r>dn||this.bytes+r>$i,t.refused)continue;const a=new ue(Me,e,o,t.material);a.sortObjects=!1,a.perObjectFrustumCulled=!1,a.frustumCulled=!1,a.matrixAutoUpdate=!1,a.boundingSphere=new Cn,a.name="Blender ordered multi-draw",a.userData.engineInternal=!0;for(const{geometry:l}of t.shapes.values())t.ids.set(l.id,a.addGeometry(l));const s=t.shapes.values().next().value.geometry;a.geometry.userData.blenderUvChannels=s.userData.blenderUvChannels;for(const l of Object.keys(s.attributes))a.geometry.getAttribute(l).gpuType=s.getAttribute(l).gpuType;t.template=a,t.bytes=r,this.bytes+=r}}compilePalettes(t,e,o){if(!t.getContext().isContextLost())for(const r of this.families.values()){const{template:a,palette:s}=r;if(!a||!s)continue;let l=r.compilations.get(t);if(l?.ready&&t.properties.get(l.material).currentProgram!==l.program&&(l.ready=!1,this.generation++),l?.ready||l?.pending||l?.refused)continue;if(this.compiling>=2){this.pending=!0;continue}if(!l){const i=bo(s.compiled,s.sources,new Int32Array(Me),a.geometry);if(!i)continue;l={material:i,ready:!1,refused:!1,pending:!1,program:null},r.compilations.set(t,l)}const u=l;u.pending=!0,u.material.needsUpdate=!0;const m=new ue(1,0,0,u.material);m.geometry.dispose(),m.geometry=a.geometry,Object.defineProperty(m,"colorTexture",{value:null}),this.compiling++;const f=i=>{if(m.geometry=new Yt,m.dispose(),r.template!==a||r.compilations.get(t)!==u){u.material.dispose();return}u.pending=!1;const c=t.properties.get(u.material).currentProgram,d=t.getContext();u.ready=i&&!d.isContextLost()&&!!c?.program&&d.getProgramParameter(c.program,d.LINK_STATUS)===!0,u.program=c,u.refused=!u.ready&&!d.isContextLost(),this.generation++,u.refused&&console.warn("Blender ordered material palette did not link; canonical draws retained."),mt()};try{t.compileAsync(m,e,o).then(()=>f(!0),()=>f(!1))}catch{f(!1)}}}available(t,e){const o=this.families.get(t);return!!o?.template&&(!o.palette||!!e&&o.compilations.get(e)?.ready===!0)}get(t,e,o){const r=this.families.get(t),a=r.template;if(!a||!this.available(t,o))return null;let s=r.draws[e];if(!s){if(this.drawCount>=Li)return null;if(this.created>=4)return this.pending=!0,null;s=new ue(1,0,0,r.material),s.dispose(),s.copy(a),Object.defineProperty(s,"colorTexture",{value:null});for(const u of Object.keys(a.geometry.attributes))s.geometry.setAttribute(u,a.geometry.getAttribute(u));s.geometry.setIndex(a.geometry.index);const l=r.ids.values().next().value;for(let u=0;u<Me;u++)s.addInstance(l),s.setVisibleAt(u,!1);if(r.palette){const u=new Int32Array(Me),m=bo(r.palette.compiled,r.palette.sources,u,s.geometry);if(!m){for(const f of Object.keys(s.geometry.attributes))s.geometry.deleteAttribute(f);return s.geometry.setIndex(null),s.dispose(),null}s.material=m,r.drawMaterials.set(s,{material:m,indices:u})}r.draws.push(s),this.created++,this.drawCount++}return s}geometryId(t,e){return this.families.get(t).ids.get(e.id)}setMaterialAt(t,e,o,r){const a=this.families.get(t),s=a.drawMaterials.get(e);s&&(s.indices[o]=a.palette.sources.indexOf(r))}isPalette(t){return!!this.families.get(t)?.palette}inspect(){return{bytes:this.bytes,draws:this.drawCount,pending:this.pending,paletteFamilies:[...this.families.values()].filter(t=>!!t.palette).length,paletteReady:[...this.families.values()].filter(t=>[...t.compilations.values()].some(e=>e.ready)).length,paletteRefused:[...this.families.values()].filter(t=>[...t.compilations.values()].some(e=>e.refused)).length,refusedFamilies:[...this.families.values()].filter(t=>t.refused).length}}release(t){this.generation++;for(const e of t.compilations.values())e.pending||e.material.dispose();t.compilations.clear();for(const{material:e}of t.drawMaterials.values())e.dispose();t.drawMaterials.clear();for(const e of t.draws){e.removeFromParent();for(const o of Object.keys(e.geometry.attributes))e.geometry.deleteAttribute(o);e.geometry.setIndex(null),e.dispose(),this.drawCount--}t.draws.length=0,t.template?.dispose(),t.template=null,t.ids.clear(),this.bytes-=t.bytes,t.bytes=0}clear(){for(const t of this.families.values())this.release(t);this.families.clear(),this.partitions.clear(),this.registrations.clear(),this.pending=!1}}const Po=128;class Vi{constructor(){this.sources=new Map,this.geometryKeys=new Map,this.frame=0,this.count=0}begin(){this.frame++,this.geometryKeys.clear()}get(t,e){let o=this.geometryKeys.get(e.geometry);o===void 0&&(o=JSON.stringify([e.geometry.userData.blenderUvChannels??null,Object.keys(e.geometry.attributes).sort().map(l=>[l,e.geometry.getAttribute(l).itemSize])]),this.geometryKeys.set(e.geometry,o));const r=`${e instanceof ue?"batch":"instance"}:${o}`;let a=this.sources.get(t);a||(a=new Map,this.sources.set(t,a));let s=a.get(r);if(s)s.frame!==this.frame&&(s.ready=yo(t,s.material)!==null,s.sourceVersion!==t.version&&(s.material.needsUpdate=!0),s.sourceVersion=t.version,s.frame=this.frame);else{if(this.count>=Po)return t;const l=yo(t);if(!l)return t;s={material:l,sourceVersion:t.version,frame:this.frame,ready:!0},a.set(r,s),this.count++}return s.ready?s.material:t}clear(){for(const t of this.sources.values())for(const{material:e}of t.values())e.dispose();this.sources.clear(),this.geometryKeys.clear(),this.count=0}inspect(){return{variants:this.count,limit:Po}}}class Bi{constructor(){this.snapshots=[],this.palettes=new Map,this.owned=[]}prepare(t,e){const o=[];for(const a of new Set(t)){if(!(a instanceof Gt)||!a.visible||!a.transparent||a.transmission>0||a.side===Te&&!a.forceSinglePass||!Ls(a))continue;const s=vo(a,!0),l=vo(a),u=$s(a);!s||!l||!u||(s.push(u.key,u.declarations),o.push({source:a,state:s,compatible:l}))}if(o.sort((a,s)=>a.source.uuid.localeCompare(s.source.uuid)),o.length===this.snapshots.length&&o.every((a,s)=>a.source===this.snapshots[s].source&&xo(a.state,this.snapshots[s].state)))return!1;e(),this.clear(),this.snapshots=o;const r=new Set;for(let a=0;a<o.length&&this.owned.length<16;a++){const s=o[a];if(!r.has(s.source))for(let l=a+1;l<o.length;l++){const u=o[l];if(r.has(u.source)||!xo(s.compatible,u.compatible))continue;const m=[s.source,u.source],f=js(m);if(!f)continue;const i={identity:new jo,sources:m,compiled:f};this.owned.push(i);for(const c of m)r.add(c),this.palettes.set(c,i);break}}return!0}get(t){return this.palettes.get(t)}clear(){for(const t of this.owned)t.identity.dispose();this.owned.length=0,this.palettes.clear(),this.snapshots=[]}inspect(){return{pairs:this.owned.length,limit:16}}}const ie=Me;function Eo(n){for(let t=n.parent;t;t=t.parent)if(t.isGroup)return t.renderOrder;return 0}class Ui{constructor(t){this.root=t,this.objects=[],this.drawMaterials=new Vi,this.ordered=new ji,this.palettes=new Bi,this.sourceMaterials=new Set,this.plannedGeneration=-1,this.mixedDraws=new Map,this.multiDraw=!1,this.pools=new Map,this.hidden=[],this.inverse=new G,this.matrix=new G,this.projection=new G,this.frustum=new Je,this.centre=new b,this.depth=new Ee,this.batches=0,this.instances=0,this.excluded={},this.plannedProjection=new G,this.projectionKnown=!1,this.planState=[],this.planned=[],this.stateIndex=0,this.stateChanged=!1}setObjects(t){this.clear(),this.objects=[...t].filter(e=>e.isMesh===!0)}prepare(t,e=!1,o){if(this.finishDraw(),this.drawMaterials.begin(),!this.objects.length)return;t.updateMatrixWorld(),this.projection.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse);let r=this.root;for(;r.parent;)r=r.parent;const a=r instanceof Bo?r:null,s=this.multiDraw!==e||this.renderer!==o;this.renderer=o,this.multiDraw=e;const l=this.planChanged(t);if(l){this.sourceMaterials.clear();for(const c of this.objects)for(const d of Array.isArray(c.material)?c.material:[c.material])this.sourceMaterials.add(d)}const u=this.palettes.prepare(this.sourceMaterials,()=>{this.ordered.clear(),this.mixedDraws.clear(),this.planned.length=0});if(this.ordered.beginPaletteFrame(),o&&a&&this.ordered.compilePalettes(o,t,a),!l&&!s&&!u&&this.plannedGeneration===this.ordered.generation&&!this.ordered.pending){for(const c of this.planned){c.mesh.visible=!0;const d=c.members[0].material;c.palette||(c.mesh.material=this.drawMaterials.get(Array.isArray(d)?d[0]:d,c.mesh));for(const _ of c.members)_.layers.disable(0),this.hidden.push(_)}return}this.planned.length=0;for(const c of this.mixedDraws.values())c.members.length=0;this.ordered.begin();for(const c of this.pools.values())for(const d of c)d.mesh.visible=!1,d.members.length=0;this.batches=this.instances=0,this.excluded={},this.frustum.setFromProjectionMatrix(this.projection),this.inverse.copy(this.root.matrixWorld).invert();const m=[],f=new Map;for(const c of this.objects){const d=Array.isArray(c.material)?c.material:[c.material];if(!d.some(O=>O.visible&&O.transparent)||!ae(c)||!c.layers.test(t.layers)||c.frustumCulled&&!this.frustum.intersectsObject(c))continue;const _=c;_.boundingSphere!==void 0?(_.boundingSphere===null&&_.computeBoundingSphere?.(),this.centre.copy(_.boundingSphere.center)):(c.geometry.boundingSphere||c.geometry.computeBoundingSphere(),this.centre.copy(c.geometry.boundingSphere.center)),this.centre.applyMatrix4(c.matrixWorld);const h=this.centre.clone(),g=this.depth.set(h.x,h.y,h.z,1).applyMatrix4(this.projection).z;let p=null,v=null;const x=d.length===1?d[0]:null,w=Eo(c);if(x&&x.visible&&x.transparent&&he(x)&&Ye(c)&&!x.isShaderMaterial&&!(x.transmission>0)&&(x.side!==Te||x.forceSinglePass)&&!c.isSkinnedMesh&&!c.morphTargetInfluences&&!c.isInstancedMesh&&c.layers.mask===1&&w===this.root.renderOrder){const O=c.geometry,y=O.index?.count??O.getAttribute("position").count,T=!Array.isArray(c.material)||O.groups.length===1&&O.groups[0].start===0&&O.groups[0].count===y&&O.groups[0].materialIndex===0,P=`${O.id}:${x.uuid}:${c.renderOrder}`;let j=f.get(P);j===void 0&&(j=ca(x,O).size<=12,f.set(P,j)),this.matrix.multiplyMatrices(this.inverse,c.matrixWorld),T&&j&&Nn(this.matrix)&&(p=x,v=P)}if(v===null){const O=x?x.isShaderMaterial?"customShader":x.transmission>0?"transmission":x.side===Te&&!x.forceSinglePass?"twoPass":"geometryLayersOrTransform":"multipleMaterials";this.excluded[O]=(this.excluded[O]??0)+1}const S=o&&a&&p?this.palettes.get(p):void 0,M=e&&v&&p?this.ordered.register(c.geometry,S?.identity??p,c.renderOrder,S):null;m.push({mesh:c,material:p,key:v,batchKey:M,groupOrder:w,z:g,centre:h})}this.ordered.pack(),o&&a&&this.ordered.compilePalettes(o,t,a);for(const c of m)c.batchKey&&this.ordered.available(c.batchKey,o)&&(c.key=c.batchKey);for(const[c]of this.mixedDraws)c.parent||this.mixedDraws.delete(c);m.sort((c,d)=>c.groupOrder-d.groupOrder||c.mesh.renderOrder-d.mesh.renderOrder||d.z-c.z||c.mesh.id-d.mesh.id);const i=new Map;for(let c=0;c<m.length;){const d=m[c];let _=c+1;if(d.key!==null)for(;_<m.length&&m[_].key===d.key;)_++;const h=m[c-1],g=m[_],p=h?.z===d.z&&h.mesh.renderOrder===d.mesh.renderOrder||g?.z===m[_-1].z&&g.mesh.renderOrder===d.mesh.renderOrder;if(d.key!==null&&_-c>=2&&!p){let v=!0;for(let x=c+ie;x<_;x+=ie)m[x-1].z===m[x].z&&(v=!1);if(v)for(let x=c;x<_;x+=ie){const w=Math.min(ie,_-x);if(w<2)continue;const S=m[x],M=i.get(d.key)??0;i.set(d.key,M+1);const O=d.key.startsWith("multi:");let y;if(O){const P=this.ordered.get(d.key,M,o);if(!P)continue;if(y=this.mixedDraws.get(P),!y){y={mesh:P,members:[],palette:this.ordered.isPalette(d.key)},this.mixedDraws.set(P,y);const j=y;P.raycast=(q,H)=>{if(P.visible)for(const X of j.members)ae(X)&&X.raycast(q,H)},this.root.add(P)}}let T=this.pools.get(d.key);if(T||(T=[],this.pools.set(d.key,T)),O||(y=T[M]),!y){const P=new Wo(d.mesh.geometry,d.material,ie);P.name="Blender ordered transparency",P.userData.engineInternal=!0,P.matrixAutoUpdate=!1,P.frustumCulled=!1,P.boundingSphere=new Cn,P.instanceMatrix.setUsage(qo),y={mesh:P,members:[],palette:!1};const j=y;P.raycast=(q,H)=>{if(P.visible)for(const X of j.members)ae(X)&&X.raycast(q,H)},T.push(y),this.root.add(P)}y.palette||(y.mesh.material=this.drawMaterials.get(d.material,y.mesh)),y.mesh.visible=!0,y.mesh.renderOrder=S.mesh.renderOrder,y.mesh.boundingSphere.center.copy(S.centre).applyMatrix4(this.inverse),y.mesh.updateMatrixWorld(!0);for(let P=0;P<w;P++){const j=m[x+P].mesh;this.matrix.multiplyMatrices(this.inverse,j.matrixWorld),y.mesh.setMatrixAt(P,this.matrix),y.mesh instanceof ue&&(y.mesh.setGeometryIdAt(P,this.ordered.geometryId(d.key,j.geometry)),this.ordered.setMaterialAt(d.key,y.mesh,P,m[x+P].material),y.mesh.setVisibleAt(P,!0)),y.members.push(j),j.layers.disable(0),this.hidden.push(j)}if(y.mesh instanceof ue)for(let P=w;P<ie;P++)y.mesh.setVisibleAt(P,!1);else y.mesh.count=w,y.mesh.instanceMatrix.needsUpdate=!0;this.planned.push(y),this.batches++,this.instances+=w}}c=_}this.ordered.pending&&queueMicrotask(mt),this.plannedGeneration=this.ordered.generation}inspect(){return{batches:this.batches,instances:this.instances,excluded:{...this.excluded},multiDraw:this.ordered.inspect(),materials:this.drawMaterials.inspect(),palettes:this.palettes.inspect()}}observe(t){this.planState[this.stateIndex]!==t&&(this.planState[this.stateIndex]=t,this.stateChanged=!0),this.stateIndex++}planChanged(t){if(!this.projectionKnown||!this.plannedProjection.equals(this.projection))return this.plannedProjection.copy(this.projection),this.projectionKnown=!0,this.planState.length=0,!0;this.stateIndex=0,this.stateChanged=this.planState.length===0,this.observe(t.layers.mask);for(const r of this.projection.elements)this.observe(r);for(const r of this.root.matrixWorld.elements)this.observe(r);const e=new Set,o=new Set;for(const r of this.objects){if(!(Array.isArray(r.material)?r.material:[r.material]).some(m=>m.visible&&m.transparent))continue;this.observe(r.parent?.id??-1),this.observe(ae(r)?1:0),this.observe(r.layers.mask),this.observe(r.renderOrder),this.observe(Eo(r)),this.observe(r.frustumCulled?1:0),this.observe(Ye(r)?1:0),this.observe(r.morphTargetInfluences?1:0);for(const m of r.matrixWorld.elements)this.observe(m);const s=r.geometry;if(this.observe(s.id),!e.has(s)){e.add(s),this.observe(s.index?.id??-1),this.observe(s.index?.version??-1),this.observe(JSON.stringify(s.userData.blenderUvChannels??null));for(const m of Object.keys(s.attributes).sort()){const f=s.getAttribute(m);this.observe(m),f instanceof ft&&(this.observe(f.id),this.observe(f.version))}}this.observe(s.drawRange.start),this.observe(s.drawRange.count),this.observe(s.index?.count??s.getAttribute("position").count),this.observe(s.groups.length);for(const m of s.groups)this.observe(m.start),this.observe(m.count),this.observe(m.materialIndex??0);const l=r.boundingSphere??s.boundingSphere;this.observe(l?.center.x??0),this.observe(l?.center.y??0),this.observe(l?.center.z??0),this.observe(l?.radius??-1);const u=Array.isArray(r.material)?r.material:null;if(this.observe(u?.length??-1),u)for(const m of u)this.observeMaterial(m,o);else this.observeMaterial(r.material,o)}return this.stateChanged||=this.planState.length!==this.stateIndex,this.planState.length=this.stateIndex,this.stateChanged}observeMaterial(t,e){this.observe(t.uuid),!e.has(t)&&(e.add(t),this.observe(he(t)?1:0),this.observe(t.version),this.observe(t.visible?1:0),this.observe(t.transparent?1:0),this.observe(t.side),this.observe(t.forceSinglePass?1:0),this.observe(t.transmission??0))}finishDraw(){for(const t of this.hidden)t.layers.enable(0);this.hidden.length=0;for(const t of this.pools.values())for(const{mesh:e}of t)e.visible=!1;for(const{mesh:t}of this.mixedDraws.values())t.visible=!1}clear(){this.finishDraw();for(const t of this.pools.values())for(const{mesh:e}of t)e.removeFromParent(),e.dispose();this.pools.clear(),this.ordered.clear(),this.palettes.clear(),this.sourceMaterials.clear(),this.plannedGeneration=-1,this.renderer=void 0,this.drawMaterials.clear(),this.mixedDraws.clear(),this.planned.length=0,this.planState.length=0,this.projectionKnown=!1,this.objects=[],this.batches=this.instances=0}}const Wi=8*1024*1024;class qi{constructor(){this.objects=[],this.copies=new Map,this.swapped=[],this.bytes=0,this.savedDraws=0}setObjects(t){this.clear(),this.objects=[...t].filter(e=>e.isMesh===!0)}prepare(){this.savedDraws=0;for(const t of this.objects){const e=t.geometry,o=t.material;if(t.layers.mask===0||!Array.isArray(o)||e.groups.length<8||!e.index||t.isSkinnedMesh||t.isInstancedMesh||t.morphTargetInfluences||Object.keys(e.morphAttributes).length||e.drawRange.start!==0||e.drawRange.count<e.index.count||o.some(s=>s.transparent||s.transmission>0||s.isShaderMaterial))continue;const r=JSON.stringify([e.id,e.index.id,e.index.version,o.map(s=>s.uuid),e.groups,Object.entries(e.attributes).map(([s,l])=>[s,l.id])]);let a=this.copies.get(r);if(!a){let s=0,l=!0;const u=new Map;for(const d of e.groups){const _=d.materialIndex??0,h=o[_];if(!h||d.start!==s||d.count<=0||d.count%3!==0){l=!1;break}s+=d.count;const g=u.get(h.uuid);g?g.groups.push(d):u.set(h.uuid,{slot:_,groups:[d]})}if(!l||s!==e.index.count||u.size>=e.groups.length)continue;const m=e.index.array.byteLength;if(this.bytes+m>Wi)continue;const f=new Yt;for(const[d,_]of Object.entries(e.attributes))f.setAttribute(d,_);const i=e.index.clone();let c=0;for(const d of u.values()){const _=c;for(const h of d.groups)i.array.set(e.index.array.subarray(h.start,h.start+h.count),c),c+=h.count;f.addGroup(_,c-_,d.slot)}f.setIndex(i),f.boundingBox=e.boundingBox?.clone()??null,f.boundingSphere=e.boundingSphere?.clone()??null,f.userData={...e.userData},a={geometry:f,signature:r,bytes:m,before:e.groups.length,after:u.size},this.copies.set(r,a),this.bytes+=m}this.swapped.push({mesh:t,geometry:e}),t.geometry=a.geometry,this.savedDraws+=a.before-a.after}}finish(){for(const{mesh:t,geometry:e}of this.swapped)t.geometry=e;this.swapped.length=0}inspect(){return{copies:this.copies.size,bytes:this.bytes,savedRanges:this.savedDraws}}release(t){for(const e of Object.keys(t.geometry.attributes))t.geometry.deleteAttribute(e);t.geometry.dispose(),this.bytes-=t.bytes}clear(){this.finish();for(const t of this.copies.values())this.release(t);this.copies.clear(),this.objects=[],this.savedDraws=0}}const mn=64*1024*1024,No=150,Le=49152,Nt=8192,Ro=Symbol("navigation geometry replaced");class Hi{constructor(t){this.invalidate=t,this.groups=new Map,this.cache=new Map,this.swapped=[],this.queue=[],this.worker=null,this.pending=null,this.generation=0,this.building=!1,this.nextId=0,this.signature="",this.identities=new WeakMap,this.nextIdentity=0,this.bytes=0,this.unavailable=null,this.reductions=[],this.timer=null,this.cameraWorld=new G,this.cameraProjection=new G,this.cameraKnown=!1,this.movedAt=-1/0,this.projection=new G,this.frustum=new Je,this.centre=new b,this.boxCentre=new b,this.halfExtent=new b,this.viewWorld=new G,this.drawnMeshes=0,this.fullTriangles=0,this.motionTriangles=0,this.lastNavigation={meshes:0,fullTriangles:0,motionTriangles:0,tooClose:0},this.quietTimer=null}setObjects(t){const e=new Map;for(const s of t){const l=s;if(!l.isMesh||l.isSkinnedMesh||l.isInstancedMesh||l.morphTargetInfluences)continue;const u=l.geometry,m=u.getAttribute("position");if(!u.index||u.index.count<6144||!m||m.count>8e6||Object.values(u.attributes).some(i=>!(i instanceof ft)||i.isFloat16BufferAttribute||i.isInstancedBufferAttribute)||Object.keys(u.morphAttributes).length||u.drawRange.start!==0||u.drawRange.count<u.index.count)continue;if(Array.isArray(l.material)){let i=0;if(!u.groups.length||u.groups.some(c=>{const d=c.start===i&&c.count>0&&c.count%3===0&&Number.isInteger(c.materialIndex)&&c.materialIndex>=0&&c.materialIndex<l.material.length;return i=c.start+c.count,!d})||i!==u.index.count)continue}const f=e.get(u);f?f.push(l):e.set(u,[l])}this.groups=e;const o=s=>{let l=this.identities.get(s);return l===void 0&&(l=++this.nextIdentity,this.identities.set(s,l)),l},r=[...e].map(([s,l])=>`${s.id}:${o(s.index)}:${s.index.version}:${Array.isArray(l[0].material)}:${JSON.stringify(s.groups)}:`+Object.entries(s.attributes).map(([u,m])=>`${u}:${o(m)}:${m.version}`).join(",")).join(";");if(r===this.signature)return;this.releaseCopies(),this.signature=r,this.unavailable=null;const a=[...e].filter(([,s])=>s.length>=3);a.reduce((s,[l,u])=>s+l.index.count*u.length,0)<6e6||(a.sort(([s,l],[u,m])=>u.index.count*m.length-s.index.count*l.length),this.queue=a.map(([s])=>({geometry:s,fine:!1})),this.next())}async next(){if(this.building||this.unavailable||this.bytes>=mn)return;const t=this.queue.shift();if(!t){this.worker?.terminate(),this.worker=null;return}const{geometry:e,fine:o}=t;this.building=!0;const r=this.generation,a=()=>{if(r!==this.generation)throw Ro;if(this.unavailable)throw new Error(this.unavailable)},s=async()=>{await new Promise(l=>setTimeout(l,0)),a()};try{this.worker||(this.worker=new Worker(new URL("/assets/blender-motion-worker-CtT2cV3V.js",import.meta.url),{type:"module"}),this.worker.onmessage=R=>{if(this.pending?.id===R.data.id){const C=this.pending;this.pending=null,C.resolve(R.data)}},this.worker.onerror=R=>{this.unavailable=R.message||"Navigation geometry worker unavailable",this.worker?.terminate(),this.worker=null;const C=this.pending;this.pending=null,C?.resolve({id:C.id,refusal:this.unavailable})});const l=e.getAttribute("position"),u=this.groups.get(e),m=Array.isArray(u[0].material);if(u.some(R=>Array.isArray(R.material)!==m))return;const f=m?e.groups:[{start:0,count:e.index.count}],i=f.flatMap(R=>{const C=[];for(let N=R.start;N<R.start+R.count;N+=Le)C.push({start:N,count:Math.min(Le,R.start+R.count-N),materialIndex:R.materialIndex});return C}),c=e.getAttribute("blenderVertex"),d=new Uint32Array(l.count),_=new Uint8Array(l.count),h=R=>c?c.getX(R):R;for(let R=0;R<i.length;R++){const C=i[R];for(let N=C.start;N<C.start+C.count;N+=Nt){await s();for(let E=N;E<Math.min(N+Nt,C.start+C.count);E++){const $=h(e.index.getX(E));if(!Number.isInteger($)||$<0||$>=d.length)return;d[$]?d[$]!==R+1&&(_[$]=1):d[$]=R+1}}}const g=Object.entries(e.attributes).filter(([R])=>R!=="position"&&R!=="blenderVertex"),p=g.reduce((R,[,C])=>R+C.itemSize,0);if(p>32)return;const v=[];let x=0;for(const[R,C]of g)for(let N=0;N<C.itemSize;N++,x++)R!=="normal"&&v.push(x);const w=g.flatMap(([R,C])=>Array(C.itemSize).fill(R==="normal"?.5:1)),S=e.boundingBox?.clone()??new _e;if(!e.boundingBox){const R=new b;for(let C=0;C<l.count;C+=Nt){await s();for(let N=C;N<Math.min(C+Nt,l.count);N++)S.expandByPoint(R.fromBufferAttribute(l,N))}}if(!e.boundingSphere)return;const M=Math.max(S.max.x-S.min.x,S.max.y-S.min.y,S.max.z-S.min.z)*(o?5e-4:.002),O=[],y=[];let T=0,P=0;for(const R of f){const C=T;for(let N=R.start;N<R.start+R.count;N+=Le){await s();const E=Math.min(N+Le,R.start+R.count),$=[],Y=new Map,Q=new Uint32Array(E-N);for(let st=N;st<E;st++){const St=e.index.getX(st);let Lt=Y.get(St);Lt===void 0&&(Lt=$.length,$.push(St),Y.set(St,Lt)),Q[st-N]=Lt}const nt=new Uint8Array($.length),at=new Float32Array($.length*3),rt=new Float32Array($.length*p);for(let st=0;st<$.length;st+=Nt){await s();for(let St=st;St<Math.min(st+Nt,$.length);St++){const Lt=$[St];nt[St]=_[h(Lt)];for(let jt=0;jt<3;jt++)at[St*3+jt]=l.getComponent(Lt,jt);let qn=0;for(const[,jt]of g){for(let Re=0;Re<jt.itemSize;Re++)rt[St*p+qn+Re]=jt.getComponent(Lt,Re);qn+=jt.itemSize}}}const yt=++this.nextId,Et=await new Promise(st=>{this.pending={id:yt,resolve:st};const St={id:yt,positions:at,indices:Q,attributes:rt,stride:p,weights:w,absoluteError:M,protectedComponents:v,locks:nt};this.worker.postMessage(St,[at.buffer,Q.buffer,rt.buffer,nt.buffer])});if(a(),Et.refusal)throw new Error(Et.refusal);if(!Et.indices||!Number.isFinite(Et.error))throw new Error("Invalid navigation geometry response");const $t=Et.indices;for(let st=0;st<$t.length;st++)$t[st]=$[$t[st]];if(T+=$t.length,T*4>mn-this.bytes)return;O.push($t),P=Math.max(P,Et.error)}m&&y.push({start:C,count:T-C,materialIndex:R.materialIndex})}const j={vertices:l.count,fullTriangles:e.index.count/3,reducedTriangles:T/3,error:P,fine:o,accepted:!1};if(this.reductions.length<32&&this.reductions.push(j),!T||T>=e.index.count*.75)return;const q=o?null:new Int32Array(l.count).fill(-1),H=[],X=new Uint32Array(T);let ct=0;for(const R of O){for(let C=0;C<R.length;C+=Nt){await s();for(let N=C;N<Math.min(C+Nt,R.length);N++){const E=R[N];let $=q?q[E]:E;$<0&&($=H.length,H.push(E),q[E]=$),X[ct+N]=$}}ct+=R.length}const A=X.byteLength+(o?0:Object.values(e.attributes).reduce((R,C)=>R+H.length*C.itemSize*C.array.BYTES_PER_ELEMENT,0));if(j.bytes=A,this.bytes+A>mn)return;const U=new Yt;U.setIndex(new ft(X,1));for(const[R,C]of Object.entries(e.attributes)){if(o){U.setAttribute(R,C);continue}const N=C,E=N.array.constructor,$=new E(H.length*N.itemSize);for(let Y=0;Y<H.length;Y+=Nt){await s();for(let Q=Y;Q<Math.min(Y+Nt,H.length);Q++)for(let nt=0;nt<N.itemSize;nt++)$[Q*N.itemSize+nt]=N.array[H[Q]*N.itemSize+nt]}U.setAttribute(R,new ft($,N.itemSize,N.normalized))}U.boundingSphere=e.boundingSphere.clone(),U.boundingBox=S.clone();for(const R of y)U.addGroup(R.start,R.count,R.materialIndex);U.userData={...e.userData},j.accepted=!0;const L=this.cache.get(e)??[];L.push({geometry:U,error:P,bytes:A,sharedAttributes:o}),this.cache.set(e,L),this.bytes+=A,!o&&e.index.count>=3e5&&T<e.index.count*.25&&this.queue.push({geometry:e,fine:!0})}catch(l){if(l===Ro)return;this.unavailable=String(l),this.worker?.terminate(),this.worker=null,this.pending=null,this.queue.length=0}finally{r===this.generation&&(this.building=!1,this.timer=setTimeout(()=>{this.timer=null,this.next()},0))}}prepare(t,e,o){if(this.finish(),this.drawnMeshes=this.fullTriangles=this.motionTriangles=0,!e||!(o>0))return!1;const r=performance.now(),a=this.cameraKnown&&(!t.matrixWorld.equals(this.cameraWorld)||!t.projectionMatrix.equals(this.cameraProjection));if(this.cameraKnown=!0,this.cameraWorld.copy(t.matrixWorld),this.cameraProjection.copy(t.projectionMatrix),a&&(this.movedAt=r,this.quietTimer&&clearTimeout(this.quietTimer),this.quietTimer=setTimeout(()=>{this.quietTimer=null,this.invalidate()},No+1)),r-this.movedAt>No)return!1;this.projection.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this.frustum.setFromProjectionMatrix(this.projection);let s=0;for(const[l,u]of this.cache){const m=u[0].geometry.boundingBox;m.getSize(this.halfExtent).multiplyScalar(.5);for(const f of this.groups.get(l)??[]){if(!ae(f)||f.frustumCulled&&!this.frustum.intersectsObject(f))continue;this.viewWorld.multiplyMatrices(t.matrixWorldInverse,f.matrixWorld);const i=this.viewWorld.elements,c=i[0]**2+i[1]**2+i[2]**2,d=i[4]**2+i[5]**2+i[6]**2,_=i[8]**2+i[9]**2+i[10]**2,h=Math.abs(i[0]*i[4]+i[1]*i[5]+i[2]*i[6]),g=Math.abs(i[0]*i[8]+i[1]*i[9]+i[2]*i[10]),p=Math.abs(i[4]*i[8]+i[5]*i[9]+i[6]*i[10]),v=Math.sqrt(Math.max(c+h+g,d+h+p,_+g+p)),x=l.boundingSphere;this.centre.copy(x.center).applyMatrix4(this.viewWorld);let w=1;if(t.isPerspectiveCamera){const O=-this.centre.z-x.radius*v;m.getCenter(this.boxCentre).applyMatrix4(this.viewWorld);const y=this.viewWorld.elements,T=Math.abs(y[2])*this.halfExtent.x+Math.abs(y[6])*this.halfExtent.y+Math.abs(y[10])*this.halfExtent.z;w=Math.max(O,-this.boxCentre.z-T)}const S=v*Math.abs(t.projectionMatrix.elements[5])*o/(2*w);let M;if(w>0){for(const O of u)if(O.error*S<=1){M=O;break}}if(!M){s++;continue}this.swapped.push({mesh:f,geometry:l}),f.geometry=M.geometry,this.drawnMeshes++,this.fullTriangles+=l.index.count/3,this.motionTriangles+=M.geometry.index.count/3}}return this.lastNavigation={meshes:this.drawnMeshes,fullTriangles:this.fullTriangles,motionTriangles:this.motionTriangles,tooClose:s},this.swapped.length>0}finish(){for(const{mesh:t,geometry:e}of this.swapped)t.geometry=e;this.swapped.length=0}inspect(){return{copies:this.cache.size,levels:[...this.cache.values()].reduce((t,e)=>t+e.length,0),bytes:this.bytes,queued:this.queue.length,pending:this.building,unavailable:this.unavailable,reductions:this.reductions.map(t=>({...t})),lastNavigation:{...this.lastNavigation}}}releaseCopies(){this.finish(),this.timer&&clearTimeout(this.timer),this.timer=null,this.generation++,this.worker?.terminate(),this.worker=null,this.pending?.resolve({id:this.pending.id,refusal:"Navigation geometry replaced"}),this.pending=null,this.building=!1,this.queue=[];for(const t of this.cache.values())for(const e of t){if(e.sharedAttributes)for(const o of Object.keys(e.geometry.attributes))e.geometry.deleteAttribute(o);e.geometry.dispose()}this.cache.clear(),this.bytes=0,this.reductions=[]}clear(){this.releaseCopies(),this.quietTimer&&clearTimeout(this.quietTimer),this.quietTimer=null,this.groups.clear(),this.signature="",this.cameraKnown=!1,this.movedAt=-1/0}}const Gi={WIREFRAME:"wireframe",SOLID:"solid",MATERIAL:"preview",RENDERED:"rendered"},F=D().finite(),ha=W([F,F,F]),je=W([D().int().nonnegative(),D().int().nonnegative()]),gt={name:z(),domain:J(["POINT","EDGE","FACE","CORNER"])},Xi=or("type",[I({...gt,type:K("FLOAT2"),data:V(W([F,F]))}).strict(),I({...gt,type:K("FLOAT_VECTOR"),data:V(ha)}).strict(),I({...gt,type:K("FLOAT_COLOR"),data:V(W([F,F,F,F]))}).strict(),I({...gt,type:K("BYTE_COLOR"),data:V(W([F,F,F,F]))}).strict(),I({...gt,type:K("QUATERNION"),data:V(W([F,F,F,F]))}).strict(),I({...gt,type:K("FLOAT4"),data:V(W([F,F,F,F]))}).strict(),I({...gt,type:K("FLOAT4X4"),data:V(V(F).length(16))}).strict(),I({...gt,type:K("INT16_2D"),data:V(W([D().int(),D().int()]))}).strict(),I({...gt,type:K("INT32_2D"),data:V(W([D().int(),D().int()]))}).strict(),I({...gt,type:K("FLOAT"),data:V(F)}).strict(),I({...gt,type:K("INT"),data:V(D().int())}).strict(),I({...gt,type:K("INT8"),data:V(D().int())}).strict(),I({...gt,type:K("BOOLEAN"),data:V(et())}).strict(),I({...gt,type:K("STRING"),data:V(z())}).strict()]),Yi=I({positions:Z(Float32Array),normals:Z(Float32Array).nullable(),uv:Z(Float32Array).nullable(),uvLayers:V(I({name:z(),data:Z(Float32Array)}).strict()).optional(),attributeLayers:V(I({name:z(),data:Z(Float32Array)}).strict()).optional(),orco:Z(Float32Array).nullable().optional(),indices:Z(Uint32Array),groups:V(I({start:D().int().nonnegative(),count:D().int().nonnegative(),materialIndex:D().int().nonnegative()}).strict()),hash:z()}).strict(),Zi=I({v:V(ha),f:V(V(D().int().nonnegative())),e:V(je).optional(),edge_order:V(je).optional(),m:V(D().int().nonnegative()).optional(),s:V(et()).optional(),sharp:V(je).optional(),seams:V(je).optional(),creases:V(W([F,F,F])).optional(),attributes:V(Xi).optional(),active_uv:z().nullable().optional(),render_uv:z().nullable().optional()}).strict(),Ki=I({store:D().int().optional(),revision:D().int(),unchanged:K(!0)}).strict(),Qi=I({co:Kt([Z(Float32Array),Z(Float64Array)]),cornerNormal:Z(Float32Array).optional(),cornerTri:Z(Uint32Array).optional(),orco:Z(Float32Array).optional(),faceStart:Z(Uint32Array),corner:Z(Uint32Array),cornerEdge:Z(Int32Array),edge:Z(Uint32Array),edgeSharp:Z(Uint8Array),edgeSeam:Z(Uint8Array),edgeCrease:Z(Float32Array),material:Z(Uint32Array),smooth:Z(Uint8Array),vertSelect:Z(Uint8Array),vertHide:Z(Uint8Array),edgeSelect:Z(Uint8Array),edgeHide:Z(Uint8Array),faceSelect:Z(Uint8Array),faceHide:Z(Uint8Array)}).strict(),Ji=I({name:z(),domain:J(["POINT","EDGE","FACE","CORNER"]),type:z(),data:ar(n=>ArrayBuffer.isView(n))}).strict(),pa=I({columns:Qi,attributes:V(Ji),activeUv:z().nullable(),renderUv:z().nullable(),counts:I({verts:D().int().nonnegative(),edges:D().int().nonnegative(),faces:D().int().nonnegative(),corners:D().int().nonnegative()}).strict(),revision:D().int().nonnegative()}).strict(),tl=Kt([Yi,pa,Zi,Ki]),Io=new Set;function el(n,t){const e=new Blob([n],{type:t}),o=new vn;let r=!1;o.addEventListener("dispose",()=>{r=!0,o.image?.close?.()});const a=createImageBitmap(e,{imageOrientation:"flipY",premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(s=>{if(r){s.close();return}o.image=s,o.needsUpdate=!0,mt()}).finally(()=>{Io.delete(a)});return Io.add(a),a.catch(()=>{}),{texture:o,ready:a}}function nl(n,t,e,o){const r=new Ke(n,t,e,Qe,Ha);return r.flipY=!1,r.colorSpace=o==="data"?He:Zt,r.needsUpdate=!0,r}function ol(n,t,e){if(t.length===0)throw new Error(`Runtime image ${n} is tiled with no tiles`);const o=Math.max(...t.map(f=>f.width)),r=Math.max(...t.map(f=>f.height)),a=new Uint8Array(o*r*4*t.length),s=Math.max(...t.map(f=>f.number-1001))+1,l=new Float32Array(s*2*4);for(let f=0;f<s;f++)l[f*4]=-1;t.forEach((f,i)=>{const c=f.rgba??(f.rgbaBase64?yn(f.rgbaBase64):void 0);if(!c)throw new Error(`Runtime image ${n} tile ${f.number} carries no raster`);for(let _=0;_<f.height;_++)a.set(c.subarray(_*f.width*4,(_+1)*f.width*4),(i*r+_)*o*4);const d=f.number-1001;l[d*4]=i,l.set([0,0,f.width/o,f.height/r],(s+d)*4)});const u=new qa(a,o,r,t.length);u.colorSpace=e==="data"?He:Zt,u.magFilter=re,u.minFilter=Ho,u.generateMipmaps=!0,u.needsUpdate=!0;const m=new Ke(l,s,2,Qe,$o);return m.magFilter=m.minFilter=xn,m.needsUpdate=!0,{tiles:u,map:m,frame:t}}const al=I({width:D().int().positive(),height:D().int().positive(),revision:D().int().nonnegative(),rgba:Z(Uint8Array).optional(),rgbaBase64:z().optional(),colorspace:J(["sRGB","data"]).optional(),tiles:V(I({number:D().int().min(1001),width:D().int().positive(),height:D().int().positive(),rgba:Z(Uint8Array).optional(),rgbaBase64:z().optional()}).strict()).optional()}).strict(),rl=I({revision:D().int().nonnegative(),encoded:Z(Uint8Array).optional(),encodedBase64:z().optional(),mime:J(["image/png","image/jpeg"]),colorspace:J(["sRGB","data"]).optional()}).strict(),ga=Kt([al,rl]),_n=I({image:I({name:z(),revision:D().int().nonnegative()}).strict(),extension:J(["REPEAT","EXTEND","MIRROR","CLIP"]).default("REPEAT"),uv:z(),tint:W([F,F,F]).optional()}).strict(),sl=I({name:z(),color:W([F,F,F,F]),roughness:F,metallic:F,transmission:F,ior:F,physical:Js.optional(),normal_texture:_n.optional(),normal_strength:F.default(1),normal_space:J(["TANGENT","OBJECT"]).default("TANGENT"),normal_directx:et().default(!1),texture:_n.optional(),roughness_texture:_n.optional(),emission:I({color:W([F,F,F]),strength:F}).strict().optional(),graph:ws.optional(),viewport:I({color:W([F,F,F,F]),roughness:F,metallic:F}).strict().optional()}).strict(),il=I({session:z(),revision:D().int().nonnegative(),volumes:At(z(),ra).default({}),lights:At(z(),rs).default({}),world:ms.nullable().default(null),meshes:At(z(),tl),materials:At(z(),sl),images:At(z(),ga).default({}),objects:V(I({id:z(),name:z(),type:J(["MESH","CURVE","SURFACE","FONT","META","ARMATURE","LATTICE","VOLUME","EMPTY","CAMERA","LIGHT","SPEAKER","GREASEPENCIL","POINTCLOUD","LIGHT_PROBE"]),mesh:z().nullable(),volume:z().nullable().optional(),light:z().nullable().optional(),materials:V(z().nullable()),matrix:V(W([F,F,F,F])).length(4),visible:et(),render_visible:et().default(!0),selected:et(),parent:z().nullable(),texspace:W([W([F,F,F]),W([F,F,F])]).optional(),default_color:z().optional()}).strict()),active:z().nullable(),mode:z(),cameras:At(z(),At(z(),Xo())).default({}),warnings:V(z()).default([]),updated:V(z()).default([]),frame:D().int().default(0),armatures:At(z(),lr).default({}),weights:li.nullable().default(null),cursor:mi.optional(),camera_view:I({scene_camera:z().nullable(),view_layer_cameras:V(z()),aspect:D().finite().positive()}).optional(),light_distances:At(z(),W([D().finite(),D().finite()])).default({}),empties:At(z(),xi).default({}),view:I({location:W([D(),D(),D()]),rotation:W([D(),D(),D(),D()]),distance:D().finite(),perspective:J(["PERSP","ORTHO","CAMERA"]),lens:D().finite().positive().default(50),shading:J(["WIREFRAME","SOLID","MATERIAL","RENDERED"]).optional()}).nullable().optional(),subject:I({frame:D().int(),body:z(),markers:V(W([D().int(),z()]))}).optional(),units:I({system:J(["NONE","METRIC","IMPERIAL"]),scale_length:D().finite()}).optional()}).strict();function ll(n,t){for(let e=0,o=n.length-1;e<n.length&&o>=0;e++,o--){if(n[e][0]===t)return n[e][1];if(e===o)break;if(n[o][0]===t)return n[o][1]}return null}const fl={METRIC:[[1e-6,"Micrometers"],[.001,"Millimeters"],[.01,"Centimeters"],[.1,"10 Centimeters"],[1,"Meters"],[10,"10 Meters"],[100,"100 Meters"],[1e3,"Kilometers"]],IMPERIAL:[[254e-7,"Thou"],[.0254,"Inches"],[.3048,"Feet"],[.9144,"Yards"],[20.1168,"Chains"],[201.168,"Furlongs"],[1609.344,"Miles"]]};class Ze{constructor(){this.root=new dt,this.instances=new Fi(this.root),this.materialRanges=new qi,this.transparentInstances=new Ui(this.root),this.motionGeometry=new Hi(mt),this.drawBatching=!0,this.objects=new Map,this.meshes=new Map,this.volumes=new Map,this.materials=new Map,this.lights=new Map,this.lighting=new ds,this.world=new Ln,this.armatureOverlay=new xr,this.weightOverlay=new di,this.cursorOverlay=new vi,this.extrasOverlay=new wi,this.armatureRoot=new dt,this.weightRoot=new dt,this.cursorRoot=new dt,this.cameraExtrasRoot=new dt,this.lightExtrasRoot=new dt,this.emptyExtrasRoot=new dt,this.rendered=!1,this.heldRendered=null,this.worldApplied=null,this.worldKey="null",this.capturing=!1,this.workbench=!1,this.workbenchMaterials=new Map,this.fallback=new Gt({color:12172998,roughness:.72}),this.textures=new Map,this.textureNames=new Map,this.roughnessTextureNames=new Map,this.textureSamplers=new Qs,this.graphSamplers=new Map,this.photograph=!1,this.graphs=new Map,this.frame=null,this.retiredSessions=new Set,this.geometryBuilds=0,this.submittedMeshes=new Map,this.submitted=null,this.submittedSession=null,this.photographs=[],this.frameListeners=new Set,this.followers=new Set,this.leader=null,this.cameraViewZoom=Mi,this.cameraViewPan=Si,this.mode=null,this.drawPreparation={last:null,navigation:null},this.awaitedImages=new Set,this.lookingThrough=null,this.staged=null;const t=this.root.updateMatrixWorld.bind(this.root);this.root.updateMatrixWorld=e=>{t(e),this.instances.sync()},this.root.name="Model",this.root.matrixAutoUpdate=!1,this.root.matrix.set(1,0,0,0,0,0,1,0,0,-1,0,0,0,0,0,1),this.root.updateMatrixWorld(!0);for(const[e,o]of[[this.armatureRoot,this.armatureOverlay.group],[this.weightRoot,this.weightOverlay.group],[this.cursorRoot,this.cursorOverlay.group],[this.cameraExtrasRoot,this.extrasOverlay.cameras],[this.lightExtrasRoot,this.extrasOverlay.lights],[this.emptyExtrasRoot,this.extrasOverlay.empties]])e.matrixAutoUpdate=!1,e.matrix.copy(this.root.matrix),e.add(o),e.updateMatrixWorld(!0);this.armatureRoot.name="BlenderBones",this.weightRoot.name="BlenderWeights",this.cursorRoot.name="Blender3DCursor",this.cameraExtrasRoot.name="BlenderCameraExtras";for(const e of[this.cameraExtrasRoot,this.lightExtrasRoot,this.emptyExtrasRoot])e.userData.volterPickable=!0;this.lightExtrasRoot.name="BlenderLightExtras",this.emptyExtrasRoot.name="BlenderEmptyExtras"}compiledGraph(t){const e=JSON.stringify(t);let o=this.graphs.get(e);return o||(o=ks(t),this.graphs.size>256&&this.graphs.clear(),this.graphs.set(e,o)),o}mirrorPose(t){let e=null;for(const[a,s]of this.objects)if(s===t){e=a;break}if(e===null)return;const o=this.leader?[this.leader,...this.leader.followers]:[...this.followers];let r=!1;for(const a of o){if(a===this)continue;const s=a.objects.get(e);s!==void 0&&(s.matrix.copy(t.matrix),s.matrix.decompose(s.position,s.quaternion,s.scale),s.updateMatrixWorld(!0),r=!0)}r&&mt()}subscribeFrames(t){return this.frameListeners.add(t),()=>{this.frameListeners.delete(t)}}onChange(t){const e=this.subscribeFrames(t),o=sr(t);return()=>{e(),o()}}blenderObjectName(t){for(const[e,o]of this.objects)if(o===t)return this.frame?.objects.find(r=>r.id===e)?.name??null;return null}noteSavedShading(t){this.frame?.view&&(this.frame.view.shading=t)}savedView(){const t=this.frame?.view;if(!t)return null;const[e,o,r,a]=t.rotation,s=new Tt(o,r,a,e),l=new b(...t.location).applyMatrix4(this.root.matrix),u=m=>m.applyQuaternion(s).applyMatrix4(this.root.matrix).normalize();return{target:l.toArray(),direction:u(new b(0,0,1)).toArray(),up:u(new b(0,1,0)).toArray(),distance:t.distance,projection:t.perspective==="ORTHO"?"orthographic":"perspective",lens:t.lens,drawMode:t.shading?Gi[t.shading]:null}}cameraViewCamera(){const t=this.frame,e=t?.camera_view;return!t||!e?null:e.scene_camera!==null&&t.cameras[e.scene_camera]?e.scene_camera:t.active!==null&&t.cameras[t.active]?t.active:e.view_layer_cameras.find(o=>t.cameras[o])??null}blenderPose(t,e){const o=new G().copy(this.root.matrix).invert(),r=new G().compose(new b(...t),new Tt(...e),new b(1,1,1)).premultiply(o),a=new b,s=new Tt;return r.decompose(a,s,new b),{location:a.toArray(),rotation:[s.w,s.x,s.y,s.z]}}cameraView(t,e,o,r){const a=this.frame,s=So.safeParse(a?.cameras[t]);return!a?.camera_view||!s.success?null:Ti(s.data,this.root.matrix,e,o,r,a.camera_view.aspect)}subjectLine(t){const e=this.frame?.subject;if(e===void 0)return null;const o=t??e.frame,r=ll(e.markers,o);return`(${o})${e.body}${r===null?"":` <${r}>`}`}gridUnitName(t){const e=this.frame?.units;if(e===void 0||e.system==="NONE")return null;const o=fl[e.system],r=6*t,a=1/(e.scale_length||1);return(o.find(([l])=>l*a>r)??o[o.length-1])[1]}blenderSelection(){const t=this.frame;return t===null?{selected:[],active:null}:{selected:t.objects.filter(e=>e.selected).map(e=>e.name),active:t.active}}setStageMode(t){this.mode=t}stageMode(){return this.mode}objectForBlenderName(t){const e=this.frame?.objects.find(o=>o.name===t);return e===void 0?null:this.objects.get(e.id)??null}replacePresentedObject(t,e){for(const[o,r]of this.objects)if(r===t){const a=t.parent,s=[...t.children];t.removeFromParent();for(const l of s)e.add(l);a?.add(e),this.objects.set(o,e),this.rebuildInstances();return}}studioLights(){return this.lighting.group}overlayGroups(){return[{kind:"skeletons",object:this.armatureRoot},{kind:"weights",object:this.weightRoot},{kind:"cursor",object:this.cursorRoot},{kind:"cameras",object:this.cameraExtrasRoot},{kind:"lights",object:this.lightExtrasRoot},{kind:"empties",object:this.emptyExtrasRoot}]}placeCursor(t,e,o){const r=new Set(this.objects.values()),a=this.cursorOverlay.placementAt(t,e,o,this.root,s=>r.has(s));return a!==null&&(this.cursorOverlay.show(a),mt()),a}holdRendered(t){t!==this.heldRendered&&(this.heldRendered=t,!this.capturing&&this.report(t===null?this.applyRendered(!1):this.applyRendered(!0,t())))}refreshRendered(){if(this.heldRendered===null||this.capturing)return;const t=this.heldRendered();this.worldKeyFor(t)!==this.worldApplied&&this.report(this.applyRendered(!0,t))}worldKeyFor(t){const o=t.isOrthographicCamera?t.getWorldDirection(new b).toArray().map(r=>r.toFixed(1)).join(","):"";return`${t.uuid}:${o}:${this.worldKey}`}report(t){t.then(mt,e=>console.error(`Rendered shading could not be applied: ${e instanceof Error?e.message:String(e)}`))}setWorkbench(t){t!==this.workbench&&(this.workbench=t,this.applyWorkbench(),mt())}applyWorkbench(){const t=this.workbench&&!this.rendered,e=new Set;for(const o of this.frame?.objects??[]){if(o.mesh===null||o.volume)continue;const r=this.objects.get(o.id);if(!r?.isMesh)continue;const s=(o.materials.length?o.materials:[null]).map(l=>{const u=l===null?this.fallback:this.materials.get(l)??this.fallback;return t?this.workbenchFor(l,u.side,e):u});r.material=o.materials.length?s:s[0]}for(const[o,r]of this.workbenchMaterials)e.has(o)||(r.dispose(),this.workbenchMaterials.delete(o));this.rebuildInstances()}rebuildInstances(){this.transparentInstances.clear(),this.instances.rebuild(this.objects.values(),this.drawBatching&&!this.rendered),this.drawBatching&&!this.rendered&&this.transparentInstances.setObjects(this.objects.values()),this.motionGeometry.setObjects(this.objects.values()),this.materialRanges.setObjects(this.drawBatching&&!this.rendered?this.objects.values():[])}setDrawBatching(t){t!==this.drawBatching&&(this.drawBatching=t,this.rebuildInstances(),mt())}prepareDraw(t,e){try{const o=performance.now();this.instances.prepareDraw(t),this.root.updateMatrixWorld(!0);const r=performance.now(),a=this.motionGeometry.prepare(t,!this.rendered&&(this.mode??this.frame?.mode)==="OBJECT"&&e?.interactive===!0,e?.height??0);a&&this.instances.sync();const s=performance.now();this.materialRanges.prepare();const l=performance.now();this.transparentInstances.prepare(t,e?.multiDraw===!0,e?.renderer);const u={opaqueMs:r-o,motionMs:s-r,rangesMs:l-s,transparentMs:performance.now()-l};this.drawPreparation.last=u,a&&(this.drawPreparation.navigation=u)}catch(o){throw this.materialRanges.finish(),this.motionGeometry.finish(),this.instances.finishDraw(),this.transparentInstances.finishDraw(),o}return()=>{this.materialRanges.finish(),this.motionGeometry.finish(),this.instances.finishDraw(),this.transparentInstances.finishDraw()}}workbenchFor(t,e,o){const r=(t!==null?this.frame?.materials[t]?.viewport:void 0)??Pi,a=`${r.color.join(",")}|${r.roughness}|${r.metallic}|${e}`;o.add(a);let s=this.workbenchMaterials.get(a);return s||(s=Ci(r,e),this.workbenchMaterials.set(a,s)),s}renderedHeld(){return this.heldRendered!==null}async setRendered(t,e){return this.capturing=t,!t&&this.heldRendered!==null?this.applyRendered(!0,this.heldRendered()):this.applyRendered(t,e)}async applyRendered(t,e){const o=(t?wo(this.frame?.world)?.extinction:null)??new b;for(const a of[...this.materials.values(),this.fallback])ei(a,o);this.rendered=t,this.lighting.setRendered(t);const r=t&&e?this.worldKeyFor(e):null;t?(this.capturing||r!==this.worldApplied)&&this.world.apply(this.root,this.frame?.world??null,e):this.world.clear(),this.worldApplied=this.capturing?null:r,this.applyVisibility(),this.applyWorkbench(),this.applyShadows(t,e),t&&(await is(),await Promise.all([...this.textures.values()].map(a=>a.ready)),await this.world.ready())}applyShadows(t,e){this.root.updateMatrixWorld(!0);const o=[];for(const u of this.objects.values()){const m=u;if(m.isMesh&&(m.castShadow=t,m.receiveShadow=t,t&&m.visible)){const f=new _e().setFromObject(m);f.isEmpty()||o.push(f)}}if(!t||!o.length)return;const a=o.reduce((u,m)=>u.union(m),new _e).getBoundingSphere(new Cn),s=e?new Je().setFromProjectionMatrix(new G().multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse)):null,l=s?o.flatMap(u=>ps(u,s)):[];for(const u of this.lights.values())u.isDirectionalLight&&e?gs(u,l,o):cs(u,a.center,a.radius)}applyOverlays(t){const e=s=>{const l=t.objects.find(u=>u.name===s);return l===void 0?null:new G().set(...l.matrix.flat())},o=[...this.armatureOverlay.apply(t.armatures,e)],r=t.weights?this.objects.get(t.objects.find(s=>s.name===t.weights?.object)?.id??""):void 0,a=this.weightOverlay.apply(t.weights,r??null,t.weights?e(t.weights.object):null);return a!==null&&o.push(a),this.cursorOverlay.apply(t.cursor),this.applyExtras(t),o}setCameraViewShowing(t){this.lookingThrough!==t&&(this.lookingThrough=t,this.frame&&this.applyExtras(this.frame),mt())}applyExtras(t){const e={};for(const[o,r]of Object.entries(t.cameras)){const a=So.safeParse(r);a.success&&(e[o]=a.data)}this.extrasOverlay.apply({lookingThrough:this.lookingThrough,lightDistances:t.light_distances,objects:t.objects.filter(o=>o.visible),active:t.active,cameras:e,lights:t.lights,empties:t.empties,sceneCamera:t.camera_view?.scene_camera??null,renderAspect:t.camera_view?.aspect??1,presented:o=>{const r=t.objects.find(a=>a.name===o);return r?this.objects.get(r.id)??null:null},image:o=>{const r=this.textures.get(o);if(!r)return null;const a=r.texture.image,s=r.width||a?.width||0,l=r.height||a?.height||0;return(s===0||l===0)&&r.ready&&!this.awaitedImages.has(o)&&(this.awaitedImages.add(o),r.ready.then(()=>{this.awaitedImages.delete(o),this.frame&&this.applyExtras(this.frame),mt()},()=>this.awaitedImages.delete(o))),{texture:r.texture,width:s,height:l}}})}applyVisibility(){for(const t of this.frame?.objects??[]){const e=this.objects.get(t.id);if(e&&(e.visible=this.rendered?t.render_visible:t.visible),!t.light)continue;const o=this.lights.get(t.light);o&&(o.visible=this.rendered&&t.render_visible)}this.armatureOverlay.group.visible=!this.capturing,this.weightOverlay.group.visible=!this.capturing,this.cursorOverlay.group.visible=!this.capturing;for(const t of[this.extrasOverlay.cameras,this.extrasOverlay.lights,this.extrasOverlay.empties])t.visible=!this.capturing}stageFrame(t){if(t.abort||!t.mesh&&!t.image){for(const o of this.staged?.meshes.values()??[])o.geometry.dispose();this.staged=t.abort?null:{session:t.session,revision:t.revision,meshes:new Map,images:new Map};return}const e=this.staged;if(!e||e.session!==t.session||e.revision!==t.revision)throw new Error("Blender frame piece does not belong to the pending revision");if(t.mesh!==void 0){const o=pa.parse(t.piece);if(e.meshes.has(t.mesh))throw new Error("Duplicate Blender mesh piece");const r=`revision:${o.revision}`;e.meshes.set(t.mesh,{signature:r,geometry:Be(eo({...o.columns,attributes:o.attributes,activeUv:o.activeUv,renderUv:o.renderUv},r))})}else if(t.image!==void 0){if(e.images.has(t.image))throw new Error("Duplicate Blender image piece");e.images.set(t.image,ga.parse(t.piece))}}applyFrame(t){const e=this.frame===null?null:{session:this.frame.session,revision:this.frame.revision},o=il.parse(t),r=this.staged;if(r&&(r.session!==o.session||r.revision!==o.revision))throw new Error("Blender frame manifest does not match its staged revision");if(r)for(const[f,i]of r.images)o.images[f]=i;if(this.retiredSessions.has(o.session))throw new Error("The runtime session was replaced; its delayed frame cannot overwrite the active model");if(this.frame?.session===o.session&&o.revision<this.frame.revision)throw new Error("The runtime frame is older than the displayed model");const a=new Set(o.objects.map(f=>f.id));if(a.size!==o.objects.length)throw new Error("Runtime object IDs must be unique");const s=new Map(o.objects.map(f=>[f.id,f]));for(const f of o.objects){if(f.mesh!==null&&!o.meshes[f.mesh])throw new Error(`Missing runtime mesh ${f.mesh}`);if(f.volume&&(!o.volumes[f.volume]||f.mesh!==null))throw new Error(`Invalid runtime volume ${f.volume}`);if(f.light&&(!o.lights[f.light]||f.mesh!==null))throw new Error(`Invalid runtime light ${f.light}`);for(const d of f.materials)if(d!==null&&!o.materials[d])throw new Error(`Missing runtime material ${d}`);const i=new Set([f.id]);let c=f.parent;for(;c!==null;){if(i.has(c))throw new Error("Runtime parent cycle");i.add(c);const d=s.get(c);if(!d)throw new Error(`Missing runtime parent ${c}`);c=d.parent}}const l=new Map,u=new Map;try{for(const[f,i]of Object.entries(o.volumes)){const c=JSON.stringify(i);this.frame?.session===o.session&&this.volumes.get(f)?.signature===c||u.set(f,{signature:c,mesh:vs(i)})}for(const[f,i]of Object.entries(o.meshes)){if("unchanged"in i){const h=r?.meshes.get(f);if(h){if(h.signature!==`revision:${i.revision}`)throw new Error("Staged Blender mesh revision mismatch");l.set(f,h);continue}const g=this.meshes.get(f)?.signature;if(this.frame?.session===o.session&&g!==void 0&&(g===`revision:${i.revision}`||!g.startsWith("revision:")))continue;throw new Error(g===void 0?`${Qn}: the presenter does not hold runtime mesh ${f} (store ${i.store}, revision ${i.revision})`:`${Qn}: the presenter holds runtime mesh ${f} at ${g}, not revision ${i.revision}`)}const c="hash"in i,d="columns"in i,_=d?`revision:${i.revision}`:c?i.hash:JSON.stringify(i);this.frame?.session===o.session&&this.meshes.get(f)?.signature===_||l.set(f,{signature:_,geometry:d?Be(eo({...i.columns,attributes:i.attributes,activeUv:i.activeUv,renderUv:i.renderUv},_)):c?Be(i):Ir(i)})}}catch(f){for(const i of l.values())i.geometry.dispose();for(const{mesh:i}of u.values())i.geometry.dispose(),i.material.dispose();throw f}if(r){for(const[f,i]of r.meshes)l.has(f)||i.geometry.dispose();this.staged=null}this.frame?.session!==o.session&&(this.frame&&this.retiredSessions.add(this.frame.session),this.clear());for(const[f,i]of u){const c=this.volumes.get(f)?.mesh;c&&(c.removeFromParent(),c.geometry.dispose(),c.material.dispose()),this.volumes.set(f,i)}for(const[f,i]of l)this.meshes.get(f)?.geometry.dispose(),this.meshes.set(f,i),this.geometryBuilds++;for(const[f,i]of Object.entries(o.images)){const c=this.textures.get(f);if("width"in i){const p=i.rgba??(i.rgbaBase64?yn(i.rgbaBase64):void 0);if(!p)throw new Error(`Runtime image ${f} carries no raster`);const v=i.tiles?ol(f,i.tiles,i.colorspace??"sRGB"):void 0;if(c?.udim&&(c.udim.tiles.dispose(),c.udim.map.dispose(),delete c.udim),c&&c.width===i.width&&c.height===i.height){const x=c.texture.image;if(x.data){x.data.set(p),c.texture.needsUpdate=!0,c.revision=i.revision,v&&(c.udim=v);continue}}c?.texture.dispose(),this.textures.set(f,{texture:nl(p,i.width,i.height,i.colorspace??"sRGB"),width:i.width,height:i.height,revision:i.revision,...v?{udim:v}:{}});continue}const d=i.encoded??(i.encodedBase64?yn(i.encodedBase64):void 0);if(!d)throw new Error(`Runtime image ${f} carries no bytes`);c?.texture.dispose(),c?.udim?.tiles.dispose(),c?.udim?.map.dispose();const _=i.colorspace??"sRGB",{texture:h,ready:g}=el(d,i.mime);h.colorSpace=_==="data"?He:Zt,this.textures.set(f,{texture:h,ready:g,width:0,height:0,revision:i.revision,encoded:{bytes:d.slice(),mime:i.mime,colorspace:_}})}for(const[f,i]of Object.entries(o.materials)){const c=this.materials.get(f)??new Gt;c.name=i.name;const d=i.texture?.tint;i.texture!==void 0?c.color.setRGB(d?.[0]??1,d?.[1]??1,d?.[2]??1,xt):c.color.setRGB(i.color[0],i.color[1],i.color[2],xt),c.opacity=i.color[3];const _=c.opacity<1||i.graph!==void 0&&Os(i.graph);c.transparent!==_&&(c.transparent=_,c.needsUpdate=!0),c.roughness=i.roughness,c.metalness=i.metallic,c.transmission=i.transmission,c.ior=i.ior,Bn(c,i.physical,{map:i.texture?.extension==="CLIP",roughness:i.roughness_texture?.extension==="CLIP",normal:i.normal_texture?.extension==="CLIP"});const h=i.normal_texture?.image.name;if(h===void 0)c.normalMap&&(this.textureSamplers.delete(`${f}:normal`),c.normalMap=null,c.needsUpdate=!0);else{const w=this.textures.get(h);if(!w)throw new Error(`${ge}: missing normal image ${h}`);const S=this.textureSamplers.get(`${f}:normal`,w.texture,i.normal_texture.extension,w.ready,i.normal_texture.uv);c.normalMap!==S&&(c.normalMap=S,c.needsUpdate=!0);const M=i.normal_space==="OBJECT"?Ua:Wa;c.normalMapType!==M&&(c.normalMapType=M,c.needsUpdate=!0),c.normalScale.set(i.normal_strength,i.normal_strength*(i.normal_directx?-1:1))}i.emission?(c.emissive.setRGB(i.emission.color[0],i.emission.color[1],i.emission.color[2],xt),c.emissiveIntensity=i.emission.strength):(c.emissive.setRGB(0,0,0),c.emissiveIntensity=1);const g=i.roughness_texture?.image.name??null;if(g===null)this.roughnessTextureNames.has(f)&&(this.textureSamplers.delete(`${f}:roughness`),c.roughnessMap=null,this.roughnessTextureNames.delete(f),c.needsUpdate=!0);else{const w=this.textures.get(g);if(!w)throw new Error(`${ge}: the presenter does not hold runtime image ${g} (revision ${i.roughness_texture.image.revision})`);const S=this.textureSamplers.get(`${f}:roughness`,w.texture,i.roughness_texture.extension,w.ready,i.roughness_texture.uv);c.roughnessMap!==S&&(c.roughnessMap=S,this.roughnessTextureNames.set(f,g),c.needsUpdate=!0)}const p=i.texture?.image.name??null;if(p===null)this.textureNames.has(f)&&(this.textureSamplers.delete(`${f}:color`),c.map=null,this.textureNames.delete(f),c.needsUpdate=!0);else{const w=this.textures.get(p);if(!w)throw new Error(`${ge}: the presenter does not hold runtime image ${p} (revision ${i.texture.image.revision})`);const S=this.textureSamplers.get(`${f}:color`,w.texture,i.texture.extension,w.ready,i.texture.uv);c.map!==S&&(c.map=S,this.textureNames.set(f,p),c.needsUpdate=!0)}const v=i.graph?this.compiledGraph(i.graph):null,x=new Set;Bs(c,v,w=>{const S=this.textures.get(w.name);if(!S)throw new Error(`${ge}: the presenter does not hold runtime image ${w.name} (revision ${w.revision})`);if(w.tiled){if(!S.udim)throw new Error(`${ge}: runtime image ${w.name} arrived without its UDIM tiles`);return S.udim}const M=`${f}:graph:${w.node}`;x.add(M);const O=this.textureSamplers.get(M,S.texture,w.extension,S.ready),y=w.closest?xn:re,T=w.closest?xn:w.mipmap?Ho:re;return(O.magFilter!==y||O.minFilter!==T)&&(O.magFilter=y,O.minFilter=T,O.needsUpdate=!0),O},this.photograph);for(const w of this.graphSamplers.get(f)??[])x.has(w)||this.textureSamplers.delete(w);this.graphSamplers.set(f,x),this.materials.set(f,c)}for(const f of o.objects){let i=this.objects.get(f.id);const c=f.volume?this.volumes.get(f.volume).mesh:null;if((!i||(c?i!==c:!!i.isMesh!=(f.mesh!==null)))&&(i?.removeFromParent(),i=c??(f.mesh!==null?new Ft(this.meshes.get(f.mesh).geometry,this.fallback):new qe),this.objects.set(f.id,i)),i.name=f.name,f.type==="CAMERA"||f.type==="LIGHT"||f.type==="EMPTY"?i.userData.volterOwnOverlay=!0:delete i.userData.volterOwnOverlay,i.matrixAutoUpdate=!1,i.matrix.set(...f.matrix.flat()),f.parent){const d=new G().set(...s.get(f.parent).matrix.flat());i.matrix.premultiply(d.invert())}if(i.matrix.decompose(i.position,i.quaternion,i.scale),f.texspace?i.userData.blenderTexspace=f.texspace:delete i.userData.blenderTexspace,f.default_color!==void 0?i.userData.blenderDefaultColor=f.default_color:delete i.userData.blenderDefaultColor,f.mesh!==null){const d=i;d.geometry=this.meshes.get(f.mesh).geometry,d.material=f.materials.length?f.materials.map(_=>_===null?this.fallback:this.materials.get(_)):this.fallback,Xs(d)}if(f.light){const d=this.lights.get(f.light)??null,_=fs(o.lights[f.light],d);d&&d!==_&&(d.removeFromParent(),d.dispose()),_.parent!==i&&i.add(_),_.userData.volterOwnOverlay=!0,us(_,i),this.lights.set(f.light,_)}}for(const f of o.objects){const i=this.objects.get(f.id),c=f.parent===null?this.root:this.objects.get(f.parent);i.parent!==c&&c.add(i)}for(const[f,i]of this.objects)a.has(f)||(i.removeFromParent(),this.objects.delete(f));for(const[f,i]of this.volumes)o.volumes[f]||(i.mesh.geometry.dispose(),i.mesh.material.dispose(),this.volumes.delete(f));for(const[f,i]of this.meshes)o.meshes[f]||(i.geometry.dispose(),this.meshes.delete(f));for(const[f,i]of this.materials)if(!o.materials[f]){for(const c of["normal","roughness","color"])this.textureSamplers.delete(`${f}:${c}`);for(const c of this.graphSamplers.get(f)??[])this.textureSamplers.delete(c);this.graphSamplers.delete(f),i.dispose(),this.materials.delete(f)}for(const[f,i]of this.lights)o.lights[f]||(i.removeFromParent(),i.dispose(),this.lights.delete(f));this.root.updateMatrixWorld(!0),this.frame={...o,meshes:{},volumes:{},images:{}},this.worldKey=JSON.stringify(o.world??null);const m=this.applyOverlays(o);m.length&&(this.frame={...this.frame,warnings:[...this.frame.warnings,...m]}),this.applyVisibility(),this.applyWorkbench(),this.heldRendered!==null&&!this.capturing&&this.report(this.applyRendered(!0,this.heldRendered()));for(const f of[...this.frameListeners])f();for(const f of this.followers)try{f.applyFrame(t)}catch{f.applyFrame(this.fullFrame())}return{...this.inspect(),held:e}}inspect(){return{session:this.frame?.session,revision:this.frame?.revision,active:this.frame?.active,mode:this.frame?.mode,geometryBuilds:this.geometryBuilds,instancing:this.drawStatistics(),objects:[...this.objects].map(([t,e])=>({id:t,name:e.name,uuid:e.uuid,geometry:e.geometry?.uuid,visible:e.visible}))}}drawStatistics(){return{enabled:this.drawBatching,preparation:{...this.drawPreparation},materialRanges:this.materialRanges.inspect(),opaque:this.instances.inspect(),transparent:this.transparentInstances.inspect(),motion:this.motionGeometry.inspect()}}snapshot(){return this.frame}fullFrame(){const t=this.frame;if(!t)throw new Error("Blender capture requires a presented frame");const e=structuredClone({...t,images:{},armatures:{},weights:null});for(const[r,{signature:a,geometry:s}]of this.meshes){const l=f=>{const i=s.getAttribute(f);if(!i)return null;if(!(i instanceof ft))throw new Error(`Blender capture cannot copy interleaved ${f}`);return new Float32Array(i.array)},u=l("position");if(!u)throw new Error(`Blender capture mesh ${r} has no positions`);const m=s.getIndex();e.meshes[r]={hash:a,positions:u,normals:l("normal"),uv:l("uv"),uvLayers:Object.entries(s.userData.blenderUvChannels??{}).map(([f,i])=>{const c=l(`uv${i}`);if(!c)throw new Error(`Blender capture mesh ${r} is missing UV layer ${f}`);return{name:f,data:c}}),orco:s.userData.blenderOrcoFromDoor?l("blenderOrco"):null,attributeLayers:(s.userData.blenderAttributes??[]).map(f=>{const i=l(Xt(f));if(!i)throw new Error(`Blender capture mesh ${r} is missing attribute ${f}`);return{name:f,data:i}}),indices:m?new Uint32Array(m.array):Uint32Array.from({length:u.length/3},(f,i)=>i),groups:s.groups.map(f=>({start:f.start,count:f.count,materialIndex:f.materialIndex??0}))}}for(const[r,{signature:a}]of this.volumes)e.volumes[r]=ra.parse(JSON.parse(a));const o=new Set(Object.values(e.materials).flatMap(r=>[r.texture?.image.name,r.roughness_texture?.image.name,r.normal_texture?.image.name,...Object.values(r.graph?.nodes??{}).map(a=>a.props.image?.name)].filter(a=>a!==void 0)));for(const r of o){const a=this.textures.get(r);if(!a)throw new Error(`Blender capture image ${r} is not resident`);if(a.encoded)e.images[r]={revision:a.revision,encoded:a.encoded.bytes.slice(),mime:a.encoded.mime,colorspace:a.encoded.colorspace};else{const s=a.texture.image?.data;if(!(s instanceof Uint8Array))throw new Error(`Blender capture image ${r} has no resident raster`);e.images[r]={revision:a.revision,width:a.width,height:a.height,rgba:s.slice(),colorspace:a.texture.colorSpace===He?"data":"sRGB",...a.udim?{tiles:a.udim.frame}:{}}}}return e}follow(){const t=new Ze;this.frame&&t.applyFrame(this.fullFrame()),this.followers.add(t),t.leader=this;let e=!1;return{view:t,dispose:()=>{e||(e=!0,this.followers.delete(t),t.leader=null,t.dispose(),t.root.removeFromParent())}}}captureSnapshot(){const t=this.fullFrame(),e=this.frame,o=this.createWorldVolumePass(),r=new Ze;r.photograph=!0;let a=!1;const s=()=>{a||(a=!0,o?.dispose(),r.dispose(),r.root.removeFromParent())};try{r.applyFrame(t),this.root.updateWorldMatrix(!0,!1),r.root.matrix.copy(this.root.matrixWorld),r.root.updateMatrixWorld(!0)}catch(l){throw s(),l}return{effect:o,root:r.root,session:e.session,revision:e.revision,prepare:l=>{if(a)throw new Error("Blender capture snapshot is disposed");return r.setRendered(!0,l)},dispose:s}}createWorldVolumePass(){const t=wo(this.frame?.world);return t?new ii(t):void 0}recordPresentation(t){if(typeof t!="object"||t===null)return;const e=t,o=e.meshes;if(typeof o!="object"||o===null)return;const r=typeof e.session=="string"?e.session:null;r!==this.submittedSession&&(this.submittedMeshes.clear(),this.photographs.length=0,this.submittedSession=r);const a=o;for(const[s,l]of Object.entries(a))typeof l=="object"&&l!==null&&!("unchanged"in l)&&this.submittedMeshes.set(s,l);for(const s of[...this.submittedMeshes.keys()])s in a||this.submittedMeshes.delete(s);this.submitted={...e,meshes:Object.fromEntries(this.submittedMeshes)}}recordPhotograph(t){this.photographs.push(t)}observations(){return{presentation:this.submitted,photographs:this.photographs}}clear(){this.materialRanges.clear(),this.motionGeometry.clear(),this.transparentInstances.clear(),this.instances.clear();for(const t of this.staged?.meshes.values()??[])t.geometry.dispose();this.staged=null;for(const t of this.lights.values())t.removeFromParent(),t.dispose();this.lights.clear();for(const t of this.objects.values())t.removeFromParent();for(const t of this.meshes.values())t.geometry.dispose();for(const t of this.materials.values())t.dispose();for(const{mesh:t}of this.volumes.values())t.geometry.dispose(),t.material.dispose();for(const{texture:t,udim:e}of this.textures.values())t.dispose(),e?.tiles.dispose(),e?.map.dispose();this.textures.clear(),this.textureNames.clear(),this.roughnessTextureNames.clear(),this.textureSamplers.clear(),this.volumes.clear(),this.objects.clear(),this.meshes.clear(),this.materials.clear()}dispose(){this.clear(),this.fallback.dispose(),this.lighting.dispose(),this.world.dispose(),this.armatureOverlay.dispose(),this.weightOverlay.dispose(),this.cursorOverlay.dispose(),this.extrasOverlay.dispose();for(const t of this.workbenchMaterials.values())t.dispose();this.workbenchMaterials.clear(),this.frame=null,this.retiredSessions.clear(),this.submittedMeshes.clear(),this.submitted=null,this.submittedSession=null,this.photographs.length=0}}const vl=new Ze;function va(n){const t=atob(n),e=new Uint8Array(t.length);for(let o=0;o<t.length;o++)e[o]=t.charCodeAt(o);return e}function hn(n){const t=va(n);return new Float32Array(t.buffer,t.byteOffset,t.byteLength>>2)}function cl(n){const t=va(n);return new Uint16Array(t.buffer,t.byteOffset,t.byteLength>>1)}function ul(n){return new G().set(...n.flat())}function Do(n,t){return[n.object,n.mesh,n.armature,n.vertexCount,n.bones.length,t].join("|")}class dl{#e=new Map;#o=null;#a=null;#t=null;#r=null;#n=null;#s=null;#l=new Set;#u=0;#d=[];#i=0;get version(){return this.#u}get engineCalls(){return this.#i}subscribe(t){return this.#l.add(t),()=>this.#l.delete(t)}#f(){this.#u++;for(const t of[...this.#l])t()}state(){const t=this.#t,e=t?.frameStart??1,o=t?.frameEnd??250,r=t?.fps??24;return{frame:this.frame(),start:e,end:o,fps:r,action:t?.action??null,object:t?.object??null,armature:t?.armature??null,bones:[...this.#e.values()].reduce((a,s)=>a+s.bones.length,0),keyframes:t?.keyframes??[],summary:t?.summary??[],clipStart:t?.clipStart??null,clipEnd:t?.clipEnd??null,tracks:t?.tracks.length??0,bound:[...this.#e.keys()],warnings:this.#d,engineCalls:this.#i,blenderFrame:t?.frameCurrent??null}}playhead(){return this.#t?this.frame():null}frame(){const t=this.#t;return this.#r!==null?this.#r:!t||!this.#a||t.clipStart===void 0?t?.frameCurrent??1:t.clipStart+this.#a.time*t.fps}get playable(){return this.#t!==null&&this.#n!==null}async bind(t,e){this.#i++;const o=await e.rig();if(!o)return;const r=[],a=new Set;let s=!1;for(const d of o.rigs){if(!d.object||!d.armature||!d.skinIndexBase64||!d.skinWeightBase64){d.reason&&r.push(d.reason);continue}a.add(d.object);const _=Do(d,o.frame);if(this.#e.get(d.object)?.signature===_)continue;const h=this.#_(t,d,o.frame,r);h&&(this.#e.get(d.object)?.skeleton.dispose(),this.#e.set(d.object,h),s=!0)}for(const[d,_]of[...this.#e])a.has(d)||(_.skeleton.dispose(),_.boneRoot.removeFromParent(),this.#e.delete(d),s=!0);this.#i++;const l=await e.clip(),u=this.#t,m=l?.frameStart!==u?.frameStart||l?.frameEnd!==u?.frameEnd||l?.fps!==u?.fps,f=l?.action!==u?.action||l?.tracks.length!==u?.tracks.length||l?.clipStart!==u?.clipStart||l?.clipEnd!==u?.clipEnd;this.#t=l??null,(!l||l.scene!==u?.scene)&&(this.#r=null),l?.reason&&r.push(l.reason),l&&(f||s)&&this.#h(t,l,r);const i=this.#n?.snapshot().activeSubject;m&&i&&this.#n?.setActiveSubject(i);const c=this.#n?.snapshot().playbackState==="playing";l&&!c&&(m||u?.frameCurrent!==l.frameCurrent)&&(this.#c(l.frameCurrent),this.#n&&l.fps>0&&this.#n.seek(l.frameCurrent/l.fps)),this.#d=r,this.#f()}#_(t,e,o,r){const a=t.objectForBlenderName(e.object??""),s=t.objectForBlenderName(e.armature??"");if(!a||!s)return null;const l=a,u=l.geometry;if(!u)return null;const m=u.getAttribute("blenderVertex");if(!m)return r.push(`"${e.object}" cannot be skinned: its presented geometry carries no \`blenderVertex\` attribute, so a per-Blender-vertex weight cannot be expanded onto its drawn vertices.`),null;if(e.vertexCount===0)return null;let f=0;for(let M=0;M<m.count;M++)f=Math.max(f,m.getX(M));if(f>=e.vertexCount)return r.push(`"${e.object}" is not skinned here: its presented geometry references Blender vertex ${f} while the mesh declares ${e.vertexCount}, which is a generative modifier (Subdivision, Mirror, Array…) between the two. Blender's own viewport shows the evaluated result; this presenter shows the exported columns unskinned.`),null;const i=cl(e.skinIndexBase64??""),c=hn(e.skinWeightBase64??""),d=m.count,_=new Uint16Array(d*4),h=new Float32Array(d*4);for(let M=0;M<d;M++){const O=m.getX(M);for(let y=0;y<4;y++)_[M*4+y]=i[O*4+y]??0,h[M*4+y]=c[O*4+y]??0}u.setAttribute("skinIndex",new Ga(_,4)),u.setAttribute("skinWeight",new It(h,4));const g=new dt;g.name=`${e.armature}:bones`;const p=[],v=e.bones.map(M=>ul(M.pose)),x=new Map(e.bones.map((M,O)=>[M.name,O]));e.bones.forEach((M,O)=>{const y=new Xa;y.name=M.name,p.push(y);const T=M.parent===null?void 0:x.get(M.parent);(T===void 0?v[O].clone():v[T].clone().invert().multiply(v[O])).decompose(y.position,y.quaternion,y.scale),(T===void 0?g:p[T]).add(y)}),s.add(g);const w=new Ya(u,l.material);w.name=l.name,w.matrixAutoUpdate=!1,w.matrix.copy(l.matrix),w.matrix.decompose(w.position,w.quaternion,w.scale),w.userData=l.userData,w.frustumCulled=!1,t.replacePresentedObject(l,w),t.root.updateMatrixWorld(!0);const S=new Za(p);return w.bind(S,w.matrixWorld.clone()),e.constrainedBones?.length&&r.push(`Bone constraints on ${e.constrainedBones.join(", ")}: the clip is derived from the F-Curves alone, so those bones play their channels rather than Blender's solved pose.`),e.unmappedGroups?.length&&r.push(`${e.object} carries vertex groups no bone is named for (${e.unmappedGroups.join(", ")}); they weight nothing here, exactly as they deform nothing in Blender.`),{object:e.object??"",armature:e.armature??"",mesh:w,boneRoot:g,bones:p,skeleton:S,frame:o,signature:Do(e,o)}}#h(t,e,o){if(this.#o?.stopAllAction(),this.#o=null,this.#a=null,!e.tracks.length||e.clipStart===void 0||e.clipEnd===void 0)return;const r=e.armature?t.objectForBlenderName(e.armature):null;if(!r)return;const a=new Map;for(const i of this.#e.values())if(i.armature===e.armature)for(const c of i.bones)a.set(c.name,c);const s=[],l=new Set;for(const i of e.tracks){const c=a.get(i.bone);if(!c){l.add(i.bone);continue}const d=hn(i.timeBase64),_=hn(i.valueBase64),h=`${c.uuid}.${i.property}`;s.push(i.property==="quaternion"?new Ka(h,Array.from(d),Array.from(_)):new Qa(h,Array.from(d),Array.from(_)))}if(l.size&&o.push(`${e.action} animates ${[...l].join(", ")}, which this binding has no bone for.`),!s.length)return;const u=e.duration??(e.clipEnd-e.clipStart)/e.fps,m=new Ja(r),f=m.clipAction(new tr(e.action??"action",u,s));f.setLoop(er,Number.POSITIVE_INFINITY),f.play(),this.#o=m,this.#a=f,this.#c(e.frameCurrent),this.#m()}#c(t){const e=this.#t;if(!e)return;const o=Math.min(e.frameEnd,Math.max(e.frameStart,t));if(this.#r=o,!this.#o||e.clipStart===void 0||e.clipEnd===void 0)return;const r=(e.clipEnd-e.clipStart)/e.fps;this.#o.setTime(Math.max(0,Math.min(r-1e-4,(o-e.clipStart)/e.fps))),this.#m()}#m(){for(const t of this.#e.values())t.boneRoot.updateMatrixWorld(!0),t.skeleton.update()}get scene(){return this.#t?.scene??null}async writeBookmark(){const t=Math.round(this.frame()),e=this.#t;if(!e)return t;const o=e.scene;return!o||e.frameCurrent===t||(this.#i++,await rr(`bpy.data.scenes[${JSON.stringify(o)}]`,"frame_current",t,void 0,!1),this.#t={...e,frameCurrent:t},this.#f()),t}get transport(){return this.#n}attachTo(t){this.#s?.(),this.#n=t;const e=t.attach({id:this.#t?.action??"blender-action",label:this.#t?.action??"Action",range:()=>{const l=this.#t,u=l?.fps||24;return{start:(l?.frameStart??1)/u,end:(l?.frameEnd??250)/u,fps:u}},seek:l=>this.seekSeconds(l)}),o=t.onSettled(()=>{this.writeBookmark()});let r=!1;const a=()=>{r||(r=!0,o(),e(),this.#s===a&&(this.#n===t&&(this.#n=null),this.#s=null))};this.#s=a;const s=this.#t;return s&&s.fps>0&&t.seek(s.frameCurrent/s.fps),a}seekSeconds(t){const e=this.#t?.fps||24;this.#c(Math.round(t*e)),this.#f()}keyframes(){return(this.#t?.keyframes??[]).map(t=>t.frame)}dispose(){this.#s?.(),this.#o?.stopAllAction(),this.#o=null,this.#a=null,this.#t=null,this.#r=null;for(const t of this.#e.values())t.skeleton.dispose(),t.boneRoot.removeFromParent();this.#e.clear()}}const xa=new dl;function xl(n){return xa.subscribe(n)}function bl(){return xa.version}export{xa as a,bl as b,vl as c,xl as s};