@volter/model-editor 0.5.66 → 0.5.67

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 (200) hide show
  1. package/dist/.vite/manifest.json +1022 -1006
  2. package/dist/assets/AudioViewer-DVXaSSYC.js +1 -0
  3. package/dist/assets/{BVHLoader-xUHWsz84.js → BVHLoader-msuIvJVn.js} +1 -1
  4. package/dist/assets/ColladaLoader-BpvxwqkB.js +3 -0
  5. package/dist/assets/EntityModelDocument-BtlQZcoU.js +1 -0
  6. package/dist/assets/EnvironmentAssetDocument-BH3zT9rt.js +1 -0
  7. package/dist/assets/FBXLoader-CsdO937F.js +1 -0
  8. package/dist/assets/{GameplaySessionTimeline-HJLZUV4Q.js → GameplaySessionTimeline-Dko95kB7.js} +10 -10
  9. package/dist/assets/ImageViewer-CZ_RMER2.js +1 -0
  10. package/dist/assets/{InspectorCanvasPreview-CLDhscy0.js → InspectorCanvasPreview-BLecDHpc.js} +1 -1
  11. package/dist/assets/InspectorObjectPreview-CSIWwJQE.js +1 -0
  12. package/dist/assets/JsonAssetDocument-CGYSeJyl.js +2 -0
  13. package/dist/assets/{LineSegments2-C8H20K8w.js → LineSegments2-BKEsgiC8.js} +2 -2
  14. package/dist/assets/LiveModuleDocument-CIvS-SUT.js +2 -0
  15. package/dist/assets/LutAssetDocument-BA70uU3w.js +1 -0
  16. package/dist/assets/{MTLLoader-C-rA0fNF.js → MTLLoader-DNh2pFDc.js} +2 -2
  17. package/dist/assets/ModelAssetDocument-D0lNEhOg.js +1 -0
  18. package/dist/assets/NonThreeAuthoringBootstrap-C0pCfkJ4.js +2 -0
  19. package/dist/assets/OBJLoader-DPi99VIm.js +5 -0
  20. package/dist/assets/Object3DDocumentToolbar-PGYkZEwr.js +1 -0
  21. package/dist/assets/Object3DPreview-BROKXSTC.js +2 -0
  22. package/dist/assets/OnlineAssetDetail-lEHnhdUS.js +1 -0
  23. package/dist/assets/OrbitControls-smIenN60.js +1 -0
  24. package/dist/assets/PLYLoader-Cx9Yc9xe.js +2 -0
  25. package/dist/assets/QuarksAssetDocument-C_8eG4KG.js +2 -0
  26. package/dist/assets/RectAreaLightUniformsLib-Iam8rS8R.js +1 -0
  27. package/dist/assets/STLLoader-BaJkM-k1.js +1 -0
  28. package/dist/assets/{ShaderAssetDocument-qlLeb2S3.js → ShaderAssetDocument-Gdp7OCfv.js} +5 -5
  29. package/dist/assets/SourceAssetViewer-l72u0hOa.js +1 -0
  30. package/dist/assets/StageHost-CdzuP0NS.js +1179 -0
  31. package/dist/assets/TDSLoader-BskhMiUy.js +1 -0
  32. package/dist/assets/ToolObject3DPreview-CU5klD6l.js +1 -0
  33. package/dist/assets/Toolbar-DI0LGx25.js +1 -0
  34. package/dist/assets/TransientHint-myZtSdd6.js +1 -0
  35. package/dist/assets/VideoViewer-z0JPXPKa.js +1 -0
  36. package/dist/assets/ViewportShadingMenu-CVU2bU_3.js +1 -0
  37. package/dist/assets/animation-mixers.service-DSIsxWG5.js +1 -0
  38. package/dist/assets/animation-timeline.utility-BEgDQC04.js +1 -0
  39. package/dist/assets/asset-editor-persistence-BtRQI8t6.js +1 -0
  40. package/dist/assets/bitmap-label-Ct4k6ehY.js +1 -0
  41. package/dist/assets/{blender-emscripten-engine-CEsWgnR7.js → blender-emscripten-engine-BeWFjMn-.js} +1 -1
  42. package/dist/assets/blender-node-editor.document-C_kpsARB.js +1 -0
  43. package/dist/assets/{blender-properties-tab-C5tUuCSv.js → blender-properties-tab-B_XBg6S8.js} +3 -3
  44. package/dist/assets/blender-runtime-host-CYhl4T9S.js +4 -0
  45. package/dist/assets/{blender-runtime-skin-DMq0XAvO.js → blender-runtime-skin-Bk6uXECD.js} +98 -51
  46. package/dist/assets/blender-runtime.document-CAPDRCvN.js +12 -0
  47. package/dist/assets/blender-timeline.document-CcEymQyL.js +1 -0
  48. package/dist/assets/blender-uv-editor.document-DSPvSEuE.js +1 -0
  49. package/dist/assets/blender-version.status-CEu7vCi3.js +1 -0
  50. package/dist/assets/{blender-wali-engine-D3iKpzn9.js → blender-wali-engine-da698rDf.js} +1 -1
  51. package/dist/assets/blender.command-BCb_c9lw.js +1 -0
  52. package/dist/assets/blender.keymap-_rF_vRX8.js +1 -0
  53. package/dist/assets/{blender.status-ujwGU6dU.js → blender.status-DrasQhJV.js} +1 -1
  54. package/dist/assets/{blender.style-CxfbTFcE.js → blender.style-DaIh9SiA.js} +1 -1
  55. package/dist/assets/{client-DNXj_opT.js → client-mkWk8S65.js} +1 -1
  56. package/dist/assets/content-bounds-_QWiKD5_.js +85 -0
  57. package/dist/assets/{hosted-asset-materialization-BXM49Qkc.js → hosted-asset-materialization-hUS3IhTD.js} +2 -2
  58. package/dist/assets/index-0Lm0Nf1M.css +1 -0
  59. package/dist/assets/{index-CJbYy-CF.js → index-7vd2obXq.js} +2 -2
  60. package/dist/assets/{index-DgapqSPi.js → index-BRLA7zdc.js} +1 -1
  61. package/dist/assets/{index-BtfYaG4D.js → index-CQG6JOSy.js} +18 -18
  62. package/dist/assets/{index-CanA16PU.js → index-CnvSS9lU.js} +1 -1
  63. package/dist/assets/{index-Bge9JUr6.js → index-DYNMP0kE.js} +1 -1
  64. package/dist/assets/index-Dm_h-T4x.js +1406 -0
  65. package/dist/assets/{index-gHZae-lw.js → index-Dz8qGBZc.js} +1 -1
  66. package/dist/assets/{index-BncK9THk.js → index-Fv4R0cYr.js} +1 -1
  67. package/dist/assets/{index-IEjydI9d.js → index-f-MQ14bP.js} +1 -1
  68. package/dist/assets/{index-D2LwEE0L.js → index-jib6KJY8.js} +6 -6
  69. package/dist/assets/{index-DUqP1RMl.js → index-ux8XhRyW.js} +1 -1
  70. package/dist/assets/{jsx-runtime-DPjLkJKQ.js → jsx-runtime-CAUTK36e.js} +1 -1
  71. package/dist/assets/layered-pick-CT4HlEpW.js +1 -0
  72. package/dist/assets/live-mixers-B-bwLZ7c.js +1 -0
  73. package/dist/assets/model-inspection-DDZE59vp.js +1 -0
  74. package/dist/assets/models.finder-Caf-3Yix.js +1 -0
  75. package/dist/assets/product-DbFrUS6F.js +1 -0
  76. package/dist/assets/properties-bone-constraints.inspector-DB3Rc_Hf.js +1 -0
  77. package/dist/assets/properties-bone.inspector-B7f7H_Co.js +1 -0
  78. package/dist/assets/properties-collection.inspector-JCtV3h3Y.js +1 -0
  79. package/dist/assets/properties-constraints.inspector-Cs8MwS-1.js +1 -0
  80. package/dist/assets/properties-data.inspector-DKGiHu8O.js +1 -0
  81. package/dist/assets/properties-material.inspector-Dc18RI13.js +1 -0
  82. package/dist/assets/properties-modifiers.inspector-DvGvXq2v.js +1 -0
  83. package/dist/assets/properties-object.inspector-Bl9nrytP.js +1 -0
  84. package/dist/assets/properties-output.inspector-B6QsU94n.js +1 -0
  85. package/dist/assets/properties-particles.inspector-B1dMnZSA.js +1 -0
  86. package/dist/assets/properties-physics.inspector-BwfNykfW.js +1 -0
  87. package/dist/assets/properties-render.inspector-KrL2EiTH.js +1 -0
  88. package/dist/assets/properties-scene.inspector-CewQnyRt.js +1 -0
  89. package/dist/assets/properties-texture.inspector-BITMzY-f.js +1 -0
  90. package/dist/assets/properties-view-layer.inspector-BpkDbmcb.js +1 -0
  91. package/dist/assets/properties-world.inspector-DLRH45Oj.js +1 -0
  92. package/dist/assets/{react-18-DyywM-Z2.js → react-18-D335xReo.js} +1 -1
  93. package/dist/assets/{react-story-board-B9V-j_Y5.js → react-story-board-CkaP4mEG.js} +1 -1
  94. package/dist/assets/{session-CsR0lApe.js → session-CTXsU1lK.js} +176 -1
  95. package/dist/assets/{spark.module-gG1EsWx8.js → spark.module-DMQ9J7rT.js} +11 -11
  96. package/dist/assets/stage-keyboard-BY7u9_MB.js +1 -0
  97. package/dist/assets/stage-overlay-set-DRFcVd27.js +1 -0
  98. package/dist/assets/stage-presence-markers-D2IpuOAY.js +1 -0
  99. package/dist/assets/stage-transform-tools-BGcIULoe.js +1 -0
  100. package/dist/assets/story-capture-RSWY8I8h.js +1 -0
  101. package/dist/assets/three-integration.service-0EyPpd5f.js +4 -0
  102. package/dist/assets/{three.module-ZILb6uB7.js → three.module-CrYDk-Xr.js} +1 -1
  103. package/dist/assets/transform-mode-request-Cz6fzydi.js +1 -0
  104. package/dist/assets/transport-strip-Co-ZDkf-.js +1 -0
  105. package/dist/assets/{vgai-shared-fontawesome-CFSkqz69.js → vgai-shared-fontawesome-2ZSGa7vM.js} +1 -1
  106. package/dist/assets/vgai-shared-jsx-dev-runtime-hkPLeIJV.js +1 -0
  107. package/dist/assets/vgai-shared-jsx-runtime-CUvvjEqj.js +1 -0
  108. package/dist/assets/{vgai-shared-react-dom-client-S0ozfl6_.js → vgai-shared-react-dom-client-CS681GK2.js} +1 -1
  109. package/dist/assets/{vgai-shared-three-DzfWDqlp.js → vgai-shared-three-CLJ0K3jQ.js} +1 -1
  110. package/dist/assets/viewport-door-BdL0u5rd.js +1 -0
  111. package/dist/assets/viewport-editor-controls-BYaAZ_Ku.js +1 -0
  112. package/dist/assets/viewport-surface-status-yS6CrXH7.js +24 -0
  113. package/dist/assets/{worker-B7zhIsFh.js → worker-CC9Ug5Ei.js} +1 -1
  114. package/dist/assets/world-documents-B5IWN-ng.js +3 -0
  115. package/dist/vgai-shared-react.json +4 -4
  116. package/dist/vgai-shared-three.json +1 -1
  117. package/dist-node/cli.js +248 -209
  118. package/dist-node/create.js +77 -77
  119. package/package.json +10 -10
  120. package/src/index.ts +1 -0
  121. package/dist/assets/AudioViewer-CRWsJVYN.js +0 -1
  122. package/dist/assets/ColladaLoader-Ccy_gHsu.js +0 -3
  123. package/dist/assets/EntityModelDocument-Dal8YnLK.js +0 -1
  124. package/dist/assets/EnvironmentAssetDocument-DFOFYX5v.js +0 -1
  125. package/dist/assets/FBXLoader-Dh0pOBW2.js +0 -1
  126. package/dist/assets/ImageViewer-BzqBpqL-.js +0 -1
  127. package/dist/assets/InspectorObjectPreview-BUZEp4xS.js +0 -1
  128. package/dist/assets/JsonAssetDocument-DCkqRS0N.js +0 -2
  129. package/dist/assets/LiveModuleDocument-CuOBVz3A.js +0 -2
  130. package/dist/assets/LutAssetDocument-IyEir1rq.js +0 -1
  131. package/dist/assets/ModelAssetDocument-DNStNyCc.js +0 -1
  132. package/dist/assets/NonThreeAuthoringBootstrap-BE15Wpmw.js +0 -2
  133. package/dist/assets/OBJLoader-CopWRneC.js +0 -5
  134. package/dist/assets/Object3DDocumentToolbar-5Dv_8caG.js +0 -1
  135. package/dist/assets/Object3DPreview-C09u9uQZ.js +0 -2
  136. package/dist/assets/OnlineAssetDetail-DOPUI1iu.js +0 -1
  137. package/dist/assets/OrbitControls-DrFzvAAB.js +0 -1
  138. package/dist/assets/PLYLoader-D_esTZ2f.js +0 -2
  139. package/dist/assets/QuarksAssetDocument-BbSJ970L.js +0 -2
  140. package/dist/assets/RectAreaLightUniformsLib-u1ciScuw.js +0 -1
  141. package/dist/assets/STLLoader-Cl5I0sAi.js +0 -1
  142. package/dist/assets/SourceAssetViewer-DwhuqbA4.js +0 -1
  143. package/dist/assets/StageHost-D-o8MsFS.js +0 -1122
  144. package/dist/assets/TDSLoader-KKBg8ef1.js +0 -1
  145. package/dist/assets/ToolObject3DPreview-ILbch3kN.js +0 -1
  146. package/dist/assets/Toolbar-DYJjJKTt.js +0 -1
  147. package/dist/assets/TransientHint-D94hsJSR.js +0 -1
  148. package/dist/assets/VideoViewer-Bx3FPbgE.js +0 -1
  149. package/dist/assets/ViewportShadingMenu-B3N6hSdN.js +0 -1
  150. package/dist/assets/animation-mixers.service-N9HxGOMf.js +0 -1
  151. package/dist/assets/asset-editor-persistence-DGD05u26.js +0 -1
  152. package/dist/assets/blender-node-editor.document-BT2M622g.js +0 -1
  153. package/dist/assets/blender-runtime-host-4ufXy47O.js +0 -4
  154. package/dist/assets/blender-runtime.document-DeFQQsF6.js +0 -8
  155. package/dist/assets/blender-timeline.document-BnlSdxy0.js +0 -1
  156. package/dist/assets/blender-uv-editor.document-UC-XeNn0.js +0 -1
  157. package/dist/assets/blender-version.status-BZP39oH7.js +0 -1
  158. package/dist/assets/blender.command-IGP5wuda.js +0 -1
  159. package/dist/assets/blender.keymap-GAQgeklK.js +0 -1
  160. package/dist/assets/browserAll-2r3AVaAO.js +0 -14
  161. package/dist/assets/canvas-preview-frames-CO60PDM7.js +0 -5
  162. package/dist/assets/index-B4bmKkgY.css +0 -1
  163. package/dist/assets/index-cpXNKgvz.js +0 -1498
  164. package/dist/assets/live-mixers-BRkRHd6g.js +0 -1
  165. package/dist/assets/material-preview.view-DqNcpd_b.js +0 -1
  166. package/dist/assets/model-inspection-JC6gbV8Q.js +0 -1
  167. package/dist/assets/models.finder-BplPGS4I.js +0 -1
  168. package/dist/assets/product-CfZaqLpw.js +0 -1
  169. package/dist/assets/properties-bone-constraints.inspector-Di8kNtAi.js +0 -1
  170. package/dist/assets/properties-bone.inspector-CqAIKNsE.js +0 -1
  171. package/dist/assets/properties-collection.inspector-DpHC_fXW.js +0 -1
  172. package/dist/assets/properties-constraints.inspector-C7G7NOZU.js +0 -1
  173. package/dist/assets/properties-data.inspector-D1sUUst6.js +0 -1
  174. package/dist/assets/properties-material.inspector-BUSjc8tl.js +0 -1
  175. package/dist/assets/properties-modifiers.inspector-Sq9bcfFz.js +0 -1
  176. package/dist/assets/properties-object.inspector-BzqiU_29.js +0 -1
  177. package/dist/assets/properties-output.inspector-BWpFqvfT.js +0 -1
  178. package/dist/assets/properties-particles.inspector-DO1KoaTz.js +0 -1
  179. package/dist/assets/properties-physics.inspector-BgkrTNSA.js +0 -1
  180. package/dist/assets/properties-render.inspector-BU5NOVoQ.js +0 -1
  181. package/dist/assets/properties-scene.inspector-DbMErJ48.js +0 -1
  182. package/dist/assets/properties-texture.inspector-toPpEwqp.js +0 -1
  183. package/dist/assets/properties-view-layer.inspector-COpx9iEK.js +0 -1
  184. package/dist/assets/properties-world.inspector-CxU0DrYX.js +0 -1
  185. package/dist/assets/react-three-rapier.esm-CN6t4A7c.js +0 -1
  186. package/dist/assets/stage-keyboard-CzlqI0nh.js +0 -1
  187. package/dist/assets/stage-overlay-set-DQeskS16.js +0 -1
  188. package/dist/assets/stage-presence-markers-S1lMOwIa.js +0 -1
  189. package/dist/assets/stage-transform-tools-Cqtv-ZQ1.js +0 -1
  190. package/dist/assets/story-capture-DmIUyEQn.js +0 -1
  191. package/dist/assets/story-mount-turn-2IYGgHob.js +0 -1
  192. package/dist/assets/story-pixi-preview-aw8xQhvF.js +0 -1
  193. package/dist/assets/story-three-preview-DDmMjlI8.js +0 -37
  194. package/dist/assets/transform-mode-request-DSPwviXs.js +0 -1
  195. package/dist/assets/vgai-shared-jsx-dev-runtime-DFDKL7fx.js +0 -1
  196. package/dist/assets/vgai-shared-jsx-runtime-DIqBpTut.js +0 -1
  197. package/dist/assets/viewport-pick-context-DkawXbEi.js +0 -1
  198. package/dist/assets/viewport-surface-status-DuININWe.js +0 -20
  199. package/dist/assets/webworkerAll-CqQUotBj.js +0 -101
  200. package/dist/assets/world-documents-DkBqH8VU.js +0 -3
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/RectAreaLightUniformsLib-u1ciScuw.js","assets/three.module-ZILb6uB7.js"])))=>i.map(i=>d[i]);
2
- import{L as ne,a as oe,b as ee}from"./LineSegments2-C8H20K8w.js";import{aJ as _t,ap as Oo,V as y,d as mt,ak as To,aK as Ht,r as Vn,a9 as ae,k as At,m as le,j as Po,h as gt,e as $t,a as _n,bu as re,al as tt,b as it,Q as ie,aA as se,aD as Ao,a$ as So,I as at,b6 as fe,bb as ce,o as Eo,a4 as mn,Z as dn,_ as jn,E as ue,L as St,b8 as Sn,b7 as En,bC as rn,bc as Wt,P as Mt,B as fn,$ as _e,a5 as me,F as No,b3 as de,a7 as he,an as pe,a3 as Mo,bD as Qt,aF as yt,q as ve,bE as ge,t as xe,i as be,f as ye,au as we,bn as Oe,bF as Te,bG as Pe,bH as Ae,u as Nn,ae as Ro,J as Bn,az as Se,w as Ee,ab as Ne,bt as Me,aV as Re,b9 as Ie,aU as Fe,aX as ze,aW as De,b2 as Ce,aY as ke,bI as $e}from"./three.module-ZILb6uB7.js";import{o as O,a as z,s as A,e7 as Y,e8 as X,e9 as R,ea as j,a$ as Le,eb as Io,ec as Nt,l as L,cH as st,ed as Fo,ee as V,ef as Ve,eg as je}from"./index-cpXNKgvz.js";import{t as Be}from"./blender-runtime-host-4ufXy47O.js";const Mn=new Set;function Jt(){for(const n of[...Mn])n()}function Ue(n){return Mn.add(n),()=>{Mn.delete(n)}}function Rn(n){const t=atob(n),o=new Uint8Array(t.length);for(let e=0;e<t.length;e++)o[e]=t.charCodeAt(e);return o}const Vt=R().finite(),qe=O({name:A(),parent:A().nullable(),connected:Y(),hide:Y(),length:Vt,matrix:z(j([Vt,Vt,Vt,Vt])).length(4),select:Y(),active:Y(),lockedWeight:Y()}).strict(),He=O({object:A(),displayType:X(["OCTAHEDRAL","STICK","BBONE","ENVELOPE","WIRE"]),showInFront:Y(),mode:A(),bones:z(qe)}).strict(),ft={solid:11711154,pose:5294335,poseActive:9240575,poseActiveUnsel:794150,wire:0,vertex:0,lockedWeight:16711680,lockedWeightFactor:128/255};function We(n){return new gt(n.r*n.r*.1,n.g*n.g*.1,n.b*n.b*.1)}const hn=[[0,0,0],[.1,.1,.1],[.1,.1,-.1],[-.1,.1,-.1],[-.1,.1,.1],[0,1,0]],Zn=[[2,1,0],[3,2,0],[4,3,0],[1,4,0],[5,1,2],[5,2,3],[5,3,4],[5,4,1]],dt=Math.SQRT1_2,Ge=[[dt,-dt,0],[0,-dt,-dt],[-dt,-dt,0],[0,-dt,dt],[.99388373,.11043154,0],[0,.11043154,-.99388373],[-.99388373,.11043154,0],[0,.11043154,.99388373]],Xe=[[0,1],[1,5],[5,3],[3,0],[0,4],[4,5],[5,2],[2,0],[1,2],[2,3],[3,4],[4,1]],Ye=.05;function Qn(n){return n.select||n.active?2:1}const Ze=10,Qe=4,Ke=`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/RectAreaLightUniformsLib-Iam8rS8R.js","assets/three.module-CrYDk-Xr.js"])))=>i.map(i=>d[i]);
2
+ import{L as Uo,a as Wo,b as Ho}from"./LineSegments2-BKEsgiC8.js";import{G as ot,M as qo,V as x,a as X,B as fn,F as bt,S as Kn,b as Te,c as Tt,d as Pe,e as bn,C as ht,f as Mt,g as $t,h as Ae,i as it,j as ut,Q as gt,E as Se,O as Go,D as Xo,L as ft,A as Ee,U as Me,k as Jn,l as Tn,R as Pn,H as to,m as Ne,n as Lt,o as Ln,p as Vn,q as gn,r as nn,s as It,t as yn,u as Re,v as Ie,w as Yo,x as ze,y as Fe,z as De,I as Zo,J as ln,K as zt,N as Ce,T as ke,W as $e,X as Qo,Y as Le,Z as Ve,$ as je,a0 as Ko,a1 as Be,a2 as uo,a3 as Ue,a4 as We,a5 as He,a6 as qe,a7 as Ge,a8 as Xe,a9 as Ye,aa as Ze,ab as jn,ac as Jo,ad as no,ae as Qe,af as Ke,ag as Je,ah as ta,ai as na,aj as oa,ak as ea,al as aa,am as ra,an as la,ao as ia,ap as sa}from"./three.module-CrYDk-Xr.js";import{o as P,f as z,g as E,h as q,_ as W,n as S,t as $,i as fa,l as te,u as jt,j,k as _t,m as ne,p as B,q as ca,w as ua}from"./index-Dm_h-T4x.js";import{q as _a}from"./blender-runtime-host-CYhl4T9S.js";const Bn=new Set;function vt(){for(const o of[...Bn])o()}function ma(o){return Bn.add(o),()=>{Bn.delete(o)}}function Un(o){const t=atob(o),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}const Zt=S().finite(),da=P({name:E(),parent:E().nullable(),connected:q(),hide:q(),length:Zt,matrix:z($([Zt,Zt,Zt,Zt])).length(4),select:q(),active:q(),lockedWeight:q()}).strict(),ha=P({object:E(),displayType:W(["OCTAHEDRAL","STICK","BBONE","ENVELOPE","WIRE"]),showInFront:q(),mode:E(),bones:z(da)}).strict(),xt={solid:11711154,pose:5294335,poseActive:9240575,poseActiveUnsel:794150,wire:0,vertex:0,lockedWeight:16711680,lockedWeightFactor:128/255};function pa(o){return new ht(o.r*o.r*.1,o.g*o.g*.1,o.b*o.b*.1)}const An=[[0,0,0],[.1,.1,.1],[.1,.1,-.1],[-.1,.1,-.1],[-.1,.1,.1],[0,1,0]],_o=[[2,1,0],[3,2,0],[4,3,0],[1,4,0],[5,1,2],[5,2,3],[5,3,4],[5,4,1]],Pt=Math.SQRT1_2,va=[[Pt,-Pt,0],[0,-Pt,-Pt],[-Pt,-Pt,0],[0,-Pt,Pt],[.99388373,.11043154,0],[0,.11043154,-.99388373],[-.99388373,.11043154,0],[0,.11043154,.99388373]],ga=[[0,1],[1,5],[5,3],[3,0],[0,4],[4,5],[5,2],[2,0],[1,2],[2,3],[3,4],[4,1]],xa=.05;function mo(o){return o.select||o.active?2:1}const ba=10,ya=4,wa=`
3
3
  attribute vec3 aSolid;
4
4
  attribute vec3 aHint;
5
5
  varying vec3 vColor;
@@ -10,13 +10,13 @@ import{L as ne,a as oe,b as ee}from"./LineSegments2-C8H20K8w.js";import{aJ as _t
10
10
  vColor = mix(aHint, aSolid, fac * fac);
11
11
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
12
12
  }
13
- `,Je=`
13
+ `,Oa=`
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 pt(n){return new gt().setHex(n,$t)}function Kn(n,t){const o=n.mode==="POSE";let e;return o?t.active&&t.select?e=pt(ft.poseActive):t.active?e=pt(ft.poseActiveUnsel):t.select?e=pt(ft.pose):e=pt(ft.wire):e=pt(ft.vertex),o&&t.lockedWeight&&e.lerp(pt(ft.lockedWeight),ft.lockedWeightFactor),e}function Jn(n,t){const o=pt(ft.solid);return n.mode==="POSE"&&t.lockedWeight&&o.lerp(pt(ft.lockedWeight),ft.lockedWeightFactor),o}const ta=new mt,na=new y,to=new Oo;function no(n,t){return new mt().set(...t.matrix.flat()).premultiply(n).scale(new y().setScalar(t.length))}class oa{constructor(){this.group=new _t,this.disposables=[],this.signature="",this.group.name="BlenderArmatureOverlay"}apply(t,o){const e=[],a=JSON.stringify(t);if(a===this.signature)return e;this.signature=a,this.clear();for(const i of Object.values(t)){const s=o(i.object);if(s===null)continue;i.displayType!=="OCTAHEDRAL"&&i.displayType!=="STICK"&&e.push(`armature ${i.object}: Blender's ${i.displayType} bone display needs data this door does not carry (B-Bone segment matrices, envelope radii), so its bones are drawn octahedral`),i.mode==="EDIT"&&e.push(`armature ${i.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 u=i.bones.filter(f=>!f.hide);if(u.length===0)continue;const c=i.displayType==="STICK"?this.buildStick(i,u,s):this.buildOctahedral(i,u,s);i.showInFront&&c.traverse(f=>{const r=f.material;r&&"depthTest"in r&&(r.depthTest=!1),f.renderOrder=10}),this.group.add(c)}return e}buildOctahedral(t,o,e){const a=new _t;a.name=`${t.object}:bones`;const i=[],s=[],u=[],c=[],f=[],r=[],l=[],m=[],h=[],d=[];for(const _ of o){const p=no(e,_),v=Jn(t,_),g=We(v),b=Kn(t,_);to.setFromMatrix4(p).invert().transpose();for(let w=0;w<Zn.length;w++){const E=na.set(...Ge[w]).applyMatrix3(to).normalize().clone();for(const I of Zn[w]){const F=new y(...hn[I]).applyMatrix4(p);i.push(F.x,F.y,F.z),s.push(E.x,E.y,E.z),u.push(v.r,v.g,v.b),c.push(g.r,g.g,g.b)}}const P=Qn(_)===2?l:f,D=Qn(_)===2?m:r;for(const[w,E]of Xe){const I=new y(...hn[w]).applyMatrix4(p),F=new y(...hn[E]).applyMatrix4(p);P.push(I.x,I.y,I.z,F.x,F.y,F.z),D.push(b.r,b.g,b.b,b.r,b.g,b.b)}_.parent!==null&&_.connected||(h.push(p.clone()),d.push(v)),h.push(p.clone().multiply(ta.makeTranslation(0,1,0))),d.push(v)}a.add(this.solidMesh(i,s,u,c)),f.length&&a.add(this.lines(f,r,1)),l.length&&a.add(this.lines(l,m,2));for(let _=0;_<h.length;_++)a.add(this.point(h[_],d[_]));return a}buildStick(t,o,e){const a=new _t;a.name=`${t.object}:bones`;const i=[],s=[],u=[],c=[];for(const f of o){const r=no(e,f),l=new y().setFromMatrixPosition(r),m=new y(0,1,0).applyMatrix4(r),h=Kn(t,f),d=Jn(t,f);i.push(l.x,l.y,l.z,m.x,m.y,m.z),s.push(h.r,h.g,h.b,h.r,h.g,h.b),u.push(l.x,l.y,l.z,m.x,m.y,m.z),c.push(d.r,d.g,d.b,d.r,d.g,d.b)}return a.add(this.lines(i,s,Ze)),a.add(this.lines(u,c,Qe)),a}solidMesh(t,o,e,a){const i=new To;i.setAttribute("position",new Ht(t,3)),i.setAttribute("normal",new Ht(o,3)),i.setAttribute("aSolid",new Ht(e,3)),i.setAttribute("aHint",new Ht(a,3));const s=new Vn({vertexShader:Ke,fragmentShader:Je,side:ae});this.disposables.push(i,s);const u=new At(i,s);return u.frustumCulled=!1,u}lines(t,o,e){const a=new ne;a.setPositions(t),a.setColors(o);const i=new oe({linewidth:e,vertexColors:!0});this.disposables.push(a,i);const s=new ee(a,i);return s.frustumCulled=!1,s}point(t,o){const e=new le(Ye,12,8),a=new Po({color:o});this.disposables.push(e,a);const i=new At(e,a);return i.applyMatrix4(t),i.frustumCulled=!1,i}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 ea="RUNTIME_FRAME_UNKNOWN_GEOMETRY",jt="RUNTIME_FRAME_UNKNOWN_IMAGE";function aa(n){const t=Math.fround,o=t(t(t(n[0]*n[0])+t(n[1]*n[1]))+t(n[2]*n[2]));if(o>1e-35){const e=t(Math.sqrt(o)),a=t(1/e);return{unit:[t(n[0]*a),t(n[1]*a),t(n[2]*a)],length:e}}return{unit:[0,0,0],length:0}}const T=Math.fround,cn=T(2*Math.PI),pn=T(1-1e-4),wt=(n,t)=>T(T(T(n[0]*t[0])+T(n[1]*t[1]))+T(n[2]*t[2])),Zt=(n,t,o=1)=>n.map((e,a)=>T(e+T(t[a]*o))),la=(n,t)=>n.map((o,e)=>T(o-t[e]));function Bt(n){const t=T(Math.sqrt(wt(n,n)));return t>0?n.map(o=>T(o/t)):[0,0,0]}function Ut(n){const t=Math.abs(n)<1?T(1-T(1-Math.abs(n))):1;let o=T(T(.077980478)+T(t*T(-.02164095)));o=T(T(-.213300989)+T(t*o)),o=T(T(1.5707963267)+T(t*o));const e=T(T(Math.sqrt(T(1-t)))*o);return n<0?T(T(Math.PI)-e):e}function ra(n){let t=n.at(-1);const o=[0,0,0];for(const e of n){for(let a=0;a<3;a++){const i=(a+1)%3,s=(a+2)%3;o[a]=T(o[a]+T(T(t[i]-e[i])*T(t[s]+e[s])))}t=e}return o}function ia(n){const t=[],o=[],e=(d,_)=>d<_?`${d}:${_}`:`${_}:${d}`,a=new Map((n.edge_order??[]).map(([d,_],p)=>[e(d,_),p])),i=new Set((n.sharp??[]).map(([d,_])=>e(d,_))),s=new Map;for(const[d,_]of n.f.entries()){const p=t.length,v=aa(ra(_.map(g=>n.v[g]))).unit;o.push(v.some(Boolean)?v:[0,0,1]);for(let g=0;g<_.length;g++){const b=e(_[g],_[(g+1)%_.length]);a.has(b)||a.set(b,a.size);const P=n.face_edges?.[d]?.[g]??a.get(b),D=t.length;t.push({vertex:_[g],face:d,edge:P,prev:p+(g+_.length-1)%_.length,next:p+(g+1)%_.length});const w=s.get(P)??[];w.push(D),s.set(P,w)}}const u=new Map,c=new Map;for(const[d,_]of s){if(_.length!==2||n.edge_sharp?.[d])continue;const[p,v]=_,g=t[p],b=t[v];!n.s?.[g.face]||!n.s?.[b.face]||g.vertex!==t[b.next].vertex||b.vertex!==t[g.next].vertex||!n.edge_sharp&&i.has(e(g.vertex,b.vertex))||(c.set(p,b.next),u.set(b.next,p),c.set(v,g.next),u.set(g.next,v))}const f=[],r=[],l=[],m=[],h=(d,_)=>Bt(la(n.v[t[t[d][_]].vertex],n.v[t[d].vertex]));for(let d=0;d<t.length;d++){if(r[d]!==void 0)continue;let _=d;const p=new Set([_]);for(;c.has(_)&&!p.has(c.get(_));)_=c.get(_),p.add(_);c.has(_)&&(_=Math.min(...p));const v=[_];for(;u.has(v.at(-1))&&u.get(v.at(-1))!==_;)v.push(u.get(v.at(-1)));let g=[0,0,0];if(v.length===1)g=o[t[_].face];else{for(const F of v)g=Zt(g,o[t[F].face],Ut(wt(h(F,"prev"),h(F,"next"))));g=Bt(g)}const b=h(_,"next"),P=v.at(-1),D=h(P,"prev"),w=wt(b,g),E=wt(D,g),I={normal:g,reference:[0,0,0],ortho:[0,0,0],alpha:0,beta:0};if(Math.abs(w)<pn&&Math.abs(E)<pn){const F=v.length>1?v.map(xt=>h(xt,"next")):[];F.length&&t[t[P].prev].edge!==t[_].edge&&F.push(D),I.alpha=F.length?T(F.reduce((xt,x)=>T(xt+Ut(wt(x,g))),0)/F.length):T(T(Ut(w)+Ut(E))/2),I.reference=Bt(Zt(b,g,-w));const k=g,U=I.reference;I.ortho=Bt([T(T(k[1]*U[2])-T(k[2]*U[1])),T(T(k[2]*U[0])-T(k[0]*U[2])),T(T(k[0]*U[1])-T(k[1]*U[0]))]);const Q=Bt(Zt(D,g,-E)),lt=wt(I.reference,Q),rt=Ut(lt);I.beta=lt<pn?wt(I.ortho,Q)<0?T(cn-rt):rt:cn}I.alpha===0&&(I.normal=[0,0,0]);for(const F of v)r[F]=f.length;f.push(v),l.push(I),m.push(g)}return{corners:t,fans:f,fanOf:r,spaces:l,faceNormals:o,fanNormals:m}}function sa(n,t){if(!t[0]||n.alpha===0||n.beta===0)return n.normal;const o=T(t[0]/32767),e=T(t[1]/32767),a=T((o>0?n.alpha:T(cn-n.alpha))*o),i=T((e>0?n.beta:T(cn-n.beta))*e);let s=n.normal.map(u=>T(u*T(Math.cos(a))));return s=Zt(s,n.reference,T(T(Math.sin(a))*T(Math.cos(i)))),e!==0&&(s=Zt(s,n.ortho,T(T(Math.sin(a))*T(Math.sin(i))))),s}function zo(n,t){if(!t)return null;const{corners:o,fans:e,spaces:a}=ia(n);if(t.type==="INT16_2D"&&t.domain==="CORNER"){const i=new Array(o.length);for(const[s,u]of e.entries()){const c=u.reduce((r,l)=>{const m=t.data[l];return[r[0]+m[0],r[1]+m[1]]},[0,0]),f=sa(a[s],c.map(r=>Math.trunc(r/u.length)));for(const r of u)i[r]=f}return i}if(t.type==="FLOAT_VECTOR")return o.map((i,s)=>{const u=t.domain==="POINT"?i.vertex:t.domain==="FACE"?i.face:s;return t.data[u]});throw new Error(`Unsupported custom_normal attribute: ${t.type}/${t.domain}`)}const vn={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}},fa=1e-6;function ca(n){const t=new y;for(let o=0;o<n.length;o++){const e=n[o],a=n[(o+1)%n.length];t.x+=(e.y-a.y)*(e.z+a.z),t.y+=(e.z-a.z)*(e.x+a.x),t.z+=(e.x-a.x)*(e.y+a.y)}return t.multiplyScalar(.5)}const ua=(n,t,o)=>(t.x-n.x)*(o.y-n.y)-(t.y-n.y)*(o.x-n.x),oo=n=>Array.from({length:n-2},(t,o)=>[0,o+1,o+2]);function _a(n){let t=0;for(let o=0;o<n.length;o++){const e=n[o],a=n[(o+1)%n.length];t+=e.x*a.y-a.x*e.y}return t}function eo(n,t,o){if(n.length!==t.length-2||!(Math.abs(o)>0))return!1;const e=Math.sign(o);let a=0;for(const[i,s,u]of n){const c=ua(t[i],t[s],t[u]);if(c*e<0)return!1;a+=Math.abs(c)}return Math.abs(a-Math.abs(o))<=fa*Math.abs(o)}function ma(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 o=ca(n),e=o.length();if(!(e>0)||!Number.isFinite(e))return{triangles:oo(t),sound:!1,method:"fan"};const a=o.clone().divideScalar(e),i=Math.abs(a.x)<.9?new y(1,0,0):new y(0,1,0),s=new y().crossVectors(i,a).normalize(),u=new y().crossVectors(a,s),c=n[0],f=n.map(h=>{const d=h.clone().sub(c);return new _n(d.dot(s),d.dot(u))}),r=_a(f),l=oo(t);if(eo(l,f,r))return{triangles:l,sound:!0,method:"fan"};let m=[];try{m=re.triangulateShape(f,[]).map(h=>[h[0],h[1],h[2]])}catch{return{triangles:l,sound:!1,method:"fan"}}return eo(m,f,r)?{triangles:m,sound:!0,method:"earcut"}:{triangles:m.length>0?m:l,sound:!1,method:m.length>0?"earcut":"fan"}}const da=new Set(["FLOAT","FLOAT2","FLOAT_VECTOR","FLOAT_COLOR","BYTE_COLOR"]);function gn(n){const t=n/255;return t<.04045?t<0?0:t*(1/12.92):((t+.055)*(1/1.055))**2.4}function xn(n,t,o){switch(n){case"FLOAT":{const e=Number(t[o]);return[e,e,e,1]}case"FLOAT2":return[Number(t[o*2]),Number(t[o*2+1]),0,1];case"FLOAT_VECTOR":return[Number(t[o*3]),Number(t[o*3+1]),Number(t[o*3+2]),1];case"BYTE_COLOR":return[gn(Number(t[o*4])),gn(Number(t[o*4+1])),gn(Number(t[o*4+2])),Number(t[o*4+3])/255];default:return[Number(t[o*4]),Number(t[o*4+1]),Number(t[o*4+2]),Number(t[o*4+3])]}}function Do(n,t){return n.filter(o=>da.has(o.type)&&o.domain!=="EDGE"&&!o.name.startsWith(".")&&o.name!=="position"&&o.name!=="custom_normal"&&!(o.type==="FLOAT2"&&o.domain==="CORNER")).map(o=>{const e=t(o.data,o.type),a=[0,0,0,0];return{name:o.name,domain:o.domain,read:(i,s,u)=>o.domain==="POINT"?xn(o.type,e,i):o.domain==="CORNER"?s===void 0?a:xn(o.type,e,s):u===void 0?a:xn(o.type,e,u)}})}function Co(n){const t=n.vertexCount,o=n.starts.length-1,e=n.starts,a=n.cornerVerts,i=e[o];let s=t;for(let x=0;x<o;x++)s+=(e[x+1]-e[x]-2)*3;const u=new Uint32Array(i),c=new Uint8Array(i),f=new Uint8Array(t),r=new Uint32Array(i);let l=!1;for(let x=0;x<o;x++)if(n.smooth(x)){l=!0;break}const m=(x,$)=>t<94906265?Math.min(x,$)*t+Math.max(x,$):`${Math.min(x,$)}:${Math.max(x,$)}`,h=new Map,d=new Set;for(const[x,$]of n.sharp)d.add(m(x,$));if(n.edges)for(const[x,$]of n.edges){if(x===$)throw new Error("Runtime mesh edge needs distinct vertices");h.set(m(x,$),-1)}const _=x=>{for(;r[x]!==x;)r[x]=r[r[x]],x=r[x];return x},p=(x,$)=>{const M=_(x),H=_($);r[Math.max(M,H)]=Math.min(M,H)};for(let x=0;x<o;x++){const $=e[x],M=e[x+1]-$,H=n.smooth(x)?1:0;for(let W=0;W<M;W++){const C=$+W;f[a[C]]=1,u[C]=$+(W+1)%M,c[C]=H,r[C]=C}}for(let x=0;x<i;x++){const $=u[x],M=a[x],H=a[$],W=m(M,H),C=h.get(W);if(C!==void 0&&C>=0&&c[x]&&c[C]&&!d.has(W)){const q=u[C];p(x,a[C]===M?C:q),p($,a[C]===M?q:C)}(C===void 0||C<0||!c[C]&&c[x])&&h.set(W,x)}const v=n.uv,g=new Float32Array(s*3),b=new Float32Array(s*2),P=new Uint32Array(s),D=(n.uvLayers??[]).map(x=>({...x,data:new Float32Array(s*2)})),w=(n.attributeLayers??[]).map(x=>({...x,data:new Float32Array(s*4)})),E=n.orco?new Float32Array(s*3):null,I=new Uint32Array(s),F=new Map,k=[],U=n.normals||n.cornerNormal?new Float32Array(s*3):null;let Q=0,lt=0;const rt=(x,$,M,H,W)=>{const C=Q++;for(const q of w)q.data.set(q.read(x,H,W),C*4);if(E)for(let q=0;q<3;q++)E[C*3+q]=n.orco[x*3+q]*.5+.5;if(P[C]=x,n.co(x).toArray(g,C*3),$&&b.set($,C*2),M&&U.set(M,C*3),H!==void 0)for(const q of D)q.data.set(q.read(H),C*2);return C},xt=(x,$)=>{const M=v?.(x),H=n.cornerNormal?[n.cornerNormal[x*3],n.cornerNormal[x*3+1],n.cornerNormal[x*3+2]]:n.normals?.[x];if(!l)return rt(a[x],M,H,x,$);const W=`${c[x]?_(x):x}${M?`:${M[0]}:${M[1]}`:""}${H?`:n${H.join(":")}`:""}${D.map(q=>":"+q.read(x).join(":")).join("")}${w.map(q=>q.domain==="POINT"?"":":"+Array.from(q.read(a[x],x,$)).join(":")).join("")}`;let C=F.get(W);return C===void 0&&(C=rt(a[x],M,H,x,$),F.set(W,C)),C};for(let x=0;x<o;x++){const $=lt,M=e[x],H=e[x+1]-M,W=[];for(let Lt=0;Lt<H;Lt++)W.push(n.co(a[M+Lt]));for(const Lt of ma(W).triangles)for(const te of Lt)I[lt++]=xt(M+te,x);const C=n.material(x),q=k.at(-1);q?.materialIndex===C?q.count+=lt-$:k.push({start:$,count:lt-$,materialIndex:C})}for(let x=0;x<t;x++)f[x]||rt(x);return{positions:g.slice(0,Q*3),normals:U?.slice(0,Q*3)??null,uv:v?b.slice(0,Q*2):null,uvLayers:D.map(x=>({name:x.name,data:x.data.slice(0,Q*2)})),attributeLayers:w.map(x=>({name:x.name,data:x.data.slice(0,Q*4)})),orco:E?E.slice(0,Q*3):null,indices:I.slice(0,lt),sourceVertex:P.slice(0,Q),groups:k}}function Et(n){return`blenderA_${Array.from(new TextEncoder().encode(n),t=>t.toString(16).padStart(2,"0")).join("")}`}function In(n){const t=new To;t.setAttribute("position",new tt(n.positions,3)),t.setAttribute("uv",new tt(n.uv??new Float32Array(n.positions.length/3*2),2)),t.setIndex(new tt(n.indices,1));const o=Object.create(null);for(const[e,a]of(n.uvLayers??[]).entries()){if(e>=8)throw new Error("A Blender mesh supports at most eight UV maps");o[a.name]=e+1,t.setAttribute(`uv${e+1}`,new tt(a.data,2))}t.userData.blenderUvChannels=o;for(const e of n.attributeLayers??[])t.setAttribute(Et(e.name),new tt(e.data,4));t.userData.blenderAttributes=(n.attributeLayers??[]).map(e=>e.name),n.orco&&(t.setAttribute("blenderOrco",new tt(n.orco,3)),t.userData.blenderOrcoFromDoor=!0);for(const e of n.groups)t.addGroup(e.start,e.count,e.materialIndex);return n.normals?t.setAttribute("normal",new tt(n.normals,3)):t.computeVertexNormals(),n.sourceVertex&&t.setAttribute("blenderVertex",new tt(n.sourceVertex,1)),t}function ha(n,t){const o=n.co.length/3,e=n.attributes.filter(_=>_.type==="FLOAT2"&&_.domain==="CORNER"),a=n.renderUv??n.activeUv??e[0]?.name,i=e.find(_=>_.name===a);if(a&&!i)throw new Error(`Runtime UV map ${a} is missing`);const s=i?i.data:null,u=n.edge.length/2,c=new Array(u);for(let _=0;_<u;_++)c[_]=[n.edge[_*2],n.edge[_*2+1]];const f=[];for(let _=0;_<u;_++)n.edgeSharp[_]===1&&f.push(c[_]);const r=n.cornerNormal?void 0:n.attributes.find(_=>_.name==="custom_normal"),l=r?{v:Array.from({length:o},(_,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:f,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,m=r?{type:r.type,domain:r.domain,data:Array.from({length:r.data.length/vn[r.type].size},(_,p)=>Array.from({length:vn[r.type].size},(v,g)=>Number(r.data[p*vn[r.type].size+g])))}:void 0,h=new y,d={vertexCount:o,normals:l?zo(l,m):null,cornerNormal:n.cornerNormal,orco:n.orco,co:_=>h.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:f,uv:s?_=>[s[_*2],s[_*2+1]]:null,uvLayers:e.map(_=>({name:_.name,read:p=>[Number(_.data[p*2]),Number(_.data[p*2+1])]})),attributeLayers:Do(n.attributes,_=>_)};return{...Co(d),hash:t}}function pa(n){const t=n.v.map(l=>new y(...l)),o=l=>{const m=t[l];if(!m)throw new Error(`Runtime mesh vertex ${l} is missing`);return m},e=new Uint32Array(n.f.length+1);n.f.forEach((l,m)=>{if(l.length<3||new Set(l).size!==l.length)throw new Error("Runtime mesh face needs at least three distinct vertices");e[m+1]=e[m]+l.length});const a=new Uint32Array(e[n.f.length]);n.f.forEach((l,m)=>l.forEach((h,d)=>{o(h),a[e[m]+d]=h}));for(const[l,m]of n.edge_order??n.e??[])o(l),o(m);const i={POINT:t.length,EDGE:(n.edge_order??n.e??[]).length,FACE:n.f.length,CORNER:a.length};for(const l of n.attributes??[])if(l.domain!=="EDGE"&&l.data.length!==i[l.domain])throw new Error(`Runtime attribute ${l.name} has ${l.data.length} values for ${i[l.domain]} ${l.domain} elements`);const s=(n.attributes??[]).filter(l=>l.type==="FLOAT2"&&l.domain==="CORNER"),u=n.render_uv??n.active_uv??s[0]?.name,c=s.find(l=>l.name===u);if(u&&!c)throw new Error(`Runtime UV map ${u} is missing`);const f=c?.data,r={vertexCount:t.length,normals:zo(n,n.attributes?.find(l=>l.name==="custom_normal")),co:o,starts:e,cornerVerts:a,smooth:l=>!!n.s?.[l],material:l=>n.m?.[l]??0,edges:n.edge_order??n.e??null,sharp:n.sharp??[],uv:f?l=>f[l]:null,uvLayers:s.map(l=>({name:l.name,read:m=>l.data[m]})),attributeLayers:Do(n.attributes??[],l=>Array.from(l).flat())};return In(Co(r))}const Kt=1.5707963267948966,Ot=6.283185307179586,ko=.3183098861837067,$o=.0795774715459476,va=.3,ga=$o,xa=3/16*ko,Fn=.8,ao=Fn*Fn,Tt=6371,Lo=100,zn=Tt+Lo,lo=64,ro=64,K=256,bt=64,ba=[1.679,1.828,1.986,1.307],ya=[.006605,.01067,.01842,.03156],wa=[3472e-28,3914e-28,1349e-28,1103e-29],Oa=334.5,Ta=[28722e-28,46168e-28,79706e-28,13578e-27],Pa=[15908e-26,17711e-26,20942e-26,24033e-26],io=13681e16,Aa=2e6,Sa=.73,bn=[[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]],un=n=>n*n,Gt=n=>n<0?0:n>1?1:n,ut=(n,t,o)=>n+o*(t-n),Ea=n=>Math.sqrt(Math.max(n,0)),Vo=n=>[-Math.sqrt(1-n*n),0,n];function Dn(n,t,o,e,a,i,s){const u=n*e+t*a+o*i,c=n*n+t*t+o*o-s*s;if(c>0&&u>0)return-1;const f=u*u-c;return f<0?-1:f>=u*u?-u+Math.sqrt(f):-u-Math.sqrt(f)}const Na=n=>xa*(1+un(n));function Ma(n){const t=1+ao+2*Fn*n;return $o*(1-ao)/(t*Math.sqrt(t))}const Ra=n=>io*(Math.exp(-n/Sa)+Aa/io);function Un(n,t){let o=n%Ot;Math.abs(o)>=Math.PI&&(o-=Math.sign(o)*2*Math.PI);let e=t;return(o>=Kt||o<=-Kt)&&(o=Math.sign(o)*Math.PI-o,e+=Math.PI),e=e%Ot,e<0&&(e+=Ot),e=Ot-e,[o,e]}class Ia{constructor(t,o,e){this.air=t,this.aerosol=o,this.ozone=e,this.lut=new Float32Array(bt*K*4)}coefficients(t,o){const e=Ra(t)*this.aerosol,a=Math.log(Math.max(t,1e-4)),i=378547397e12*Math.exp(-un(a-3.22261)*5.55555555-a),s=Math.exp(-.07771971*t**1.16364243);for(let u=0;u<4;u++)o[u]=Ta[u]*e,o[4+u]=Pa[u]*e,o[8+u]=wa[u]*Oa*i*this.ozone,o[12+u]=ya[u]*s*this.air}transmittance(t,o,e){const[a,i,s]=Vo(t),u=ut(Tt,zn,o),f=Dn(0,0,u,a,i,s,zn)/lo,r=[0,0,0,0],l=new Float64Array(16);for(let m=0;m<lo;m++){const h=(m+.5)*f,d=a*h,_=i*h,p=u+s*h,v=Math.max(Math.hypot(d,_,p)-Tt,0);this.coefficients(v,l);for(let g=0;g<4;g++)r[g]+=(l[g]+l[4+g]+l[8+g]+l[12+g])*f}for(let m=0;m<4;m++)e[m]=Math.exp(-r[m])}precompute(){const t=new Float64Array(4);for(let o=0;o<bt;o++)for(let e=0;e<K;e++){const a=e/(K-1),i=o/(bt-1);this.transmittance(a*2-1,i,t);const s=(o*K+e)*4;for(let u=0;u<4;u++)this.lut[s+u]=t[u]}}lookup(t,o,e){const a=(K-1)*Gt(t*.5+.5),i=(bt-1)*Gt(o),s=Math.trunc(a),u=Math.trunc(i),c=Math.min(s+1,K-1),f=Math.min(u+1,bt-1),r=a-s,l=i-u,m=(u*K+s)*4,h=(u*K+c)*4,d=(f*K+s)*4,_=(f*K+c)*4;for(let p=0;p<4;p++)e[p]=ut(ut(this.lut[m+p],this.lut[h+p],r),ut(this.lut[d+p],this.lut[_+p],r),l)}lookupAtGround(t,o){const e=(K-1)*Gt(t*.5+.5),a=Math.trunc(e),i=Math.min(a+1,K-1),s=e-a;for(let u=0;u<4;u++)o[u]=ut(this.lut[a*4+u],this.lut[i*4+u],s)}lookupToSun(t,o){const e=(bt-1)*Gt(t),a=Math.trunc(e),i=Math.min(a+1,bt-1),s=e-a,u=K-1;for(let c=0;c<4;c++)o[c]=ut(this.lut[(a*K+u)*4+c],this.lut[(i*K+u)*4+c],s)}inscattering(t,o,e,a,i,s,u,c,f){const r=-(i*t[0]+s*t[1]+u*t[2]),l=Na(r),m=Ma(r),h=c/ro,d=new Float64Array(16),_=new Float64Array(4),p=new Float64Array(4),v=new Float64Array(4),g=new Float64Array(4),b=new Float64Array(4),P=[0,0,0,0],D=[1,1,1,1];for(let w=0;w<ro;w++){const E=(w+.5)*h,I=o+i*E,F=e+s*E,k=a+u*E,U=Math.hypot(I,F,k),Q=Math.max(U-Tt,0),lt=Q/Lo,rt=(I*t[0]+F*t[1]+k*t[2])/U;this.coefficients(Q,d),this.lookup(rt,lt,_);const xt=Ot*(1-Ea(1-un(Tt/U)));this.lookupAtGround(rt,v),this.lookupToSun(0,g),this.lookupToSun(lt,b);const x=1/(1+5*Math.exp(-17.92*rt)),$=[.217,.347,.594,1];for(let M=0;M<4;M++){const H=g[M]/b[M],W=ga*xt*(va*ko)*v[M]*H*rt;p[M]=.02*$[M]*x+W}for(let M=0;M<4;M++){const H=d[M]+d[4+M]+d[8+M]+d[12+M],W=ba[M]*(d[12+M]*(l*_[M]+p[M])+d[4+M]*(m*_[M]+p[M])),C=Math.exp(-h*H),q=Math.max(H,1e-7);P[M]+=D[M]*((W-W*C)/q),D[M]*=C}}for(let w=0;w<4;w++)f[w]=P[w]}}const nt=512,Dt=256;function jo(n,t){const o=new Ia(n.airDensity,n.aerosolDensity,n.ozoneDensity);o.precompute();const e=Math.min(Math.max(n.altitude,1),99999)/1e3,a=Vo(Math.cos(Kt-t)),i=new Float32Array(nt*Dt*3),s=nt/2,u=new Float64Array(4);for(let c=0;c<Dt;c++)for(let f=0;f<s;f++){const r=(f+.5)/nt,l=(c+.5)/Dt,m=Ot*r,h=l*2-1,d=Math.sign(h)*un(h)*Kt,_=Math.cos(d)*Math.cos(m),p=Math.cos(d)*Math.sin(m),v=Math.sin(d),g=Tt+e,b=Dn(0,0,g,_,p,v,zn),P=Dn(0,0,g,_,p,v,Tt),D=P<0?b:P;o.inscattering(a,0,0,g,_,p,v,D,u);let w=0,E=0,I=0;for(let U=0;U<4;U++)w+=bn[U][0]*u[U],E+=bn[U][1]*u[U],I+=bn[U][2]*u[U];const F=(c*nt+f)*3;i[F]=w,i[F+1]=E,i[F+2]=I;const k=(c*nt+(nt-f-1))*3;i[k]=w,i[k+1]=E,i[k+2]=I}return i}function Fa(n){const[t]=Un(n.sunElevation,n.sunRotation);return jo(n,t)}function qn(n){const[t]=Un(n.sunElevation,n.sunRotation);return JSON.stringify([t,n.altitude,n.airDensity,n.aerosolDensity,n.ozoneDensity])}const za=6,Ft=new Map;function Da(n){return Ft.has(qn(n))}function Bo(n,t){Ft.set(qn(n),t),Ft.size>za&&Ft.delete(Ft.keys().next().value)}function Ca(n){const[t,o]=Un(n.sunElevation,n.sunRotation),e=qn(n);let a=Ft.get(e);a===void 0&&(a=jo(n,t),Bo(n,a));const i=new y;return s=>{const u=Math.hypot(s.x,s.y),c=Math.atan2(s.z,u);let r=(Math.atan2(s.x,s.y)+Math.PI+o)/Ot;r-=Math.floor(r);const l=Math.abs(c),m=Gt(Math.sqrt(l/Kt)*Math.sign(c)*.5+.5),h=r*nt-.5,d=m*Dt-.5,_=Math.floor(h),p=Math.floor(d),v=h-_,g=d-p,b=k=>(k%nt+nt)%nt,P=k=>k<0?0:k>Dt-1?Dt-1:k,D=b(_),w=b(_+1),E=P(p),I=P(p+1),F=[0,0,0];for(let k=0;k<3;k++){const U=ut(a[(E*nt+D)*3+k],a[(E*nt+w)*3+k],v),Q=ut(a[(I*nt+D)*3+k],a[(I*nt+w)*3+k],v);F[k]=ut(U,Q,g)}return i.set(ct[0][0]*F[0]+ct[0][1]*F[1]+ct[0][2]*F[2],ct[1][0]*F[0]+ct[1][1]*F[1]+ct[1][2]*F[2],ct[2][0]*F[0]+ct[2][1]*F[1]+ct[2][2]*F[2])}}let ht=null,tn=!1,ka=0;const Xt=new Map;function $a(){if(ht||tn)return ht;if(typeof Worker>"u")return tn=!0,null;try{ht=new Worker(new URL("/assets/sky-precompute-worker-ChN7J87v.js",import.meta.url),{type:"module"})}catch{return tn=!0,null}return ht.onmessage=n=>{const{id:t,pixels:o,error:e}=n.data,a=Xt.get(t);a&&(Xt.delete(t),o?a.resolve(o):a.reject(new Error(e??"sky worker returned nothing")))},ht.onerror=n=>{const t=new Error(`sky worker failed: ${n.message||"unknown error"}`);for(const o of Xt.values())o.reject(t);Xt.clear(),ht?.terminate(),ht=null,tn=!0},ht}function La(n){const t=$a();if(!t)return Promise.resolve(Fa(n));const o=ka++,e={id:o,parameters:n};return new Promise((a,i)=>{Xt.set(o,{resolve:a,reject:i}),t.postMessage(e)})}function Va(n,t,o,e={}){switch(e.type??"LINEAR"){case"QUADRATIC":{const a=Math.max(n,0);return a*a}case"EASING":{const a=Math.min(1,Math.max(0,n));return a*a*(3-2*a)}case"DIAGONAL":return(n+t)/2;case"SPHERICAL":return Math.max(.999999-Math.hypot(n,t,o),0);case"QUADRATIC_SPHERE":{const a=Math.max(.999999-Math.hypot(n,t,o),0);return a*a}case"RADIAL":return Math.atan2(t,n)/(2*Math.PI)+.5;default:return n}}const yn=(n,t)=>t!==0?n/t:0,so=n=>Math.min(1,Math.max(-1,n)),fo=(n,t,o)=>{const e=o!==0?Math.max(o-Math.abs(n-t),0)/o:0;return Math.min(n,t)-e*e*e*o/6},Uo={ADD:(n,t)=>n+t,SUBTRACT:(n,t)=>n-t,MULTIPLY:(n,t)=>n*t,DIVIDE:yn,POWER:(n,t)=>t===0?1:n===0||n<0&&!Number.isInteger(t)?0:n**t,LOGARITHM:(n,t)=>n<=0||t<=0?0:yn(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(yn(n,t))*t,WRAP:(n,t,o)=>t!==o?n-(t-o)*Math.floor((n-o)/(t-o)):o,PINGPONG:(n,t)=>{if(t===0)return 0;const o=(n-t)/(t*2);return Math.abs((o-Math.floor(o))*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,o)=>+(n===t||Math.abs(n-t)<=Math.max(o,2**-23)),MULTIPLY_ADD:(n,t,o)=>n*t+o,SMOOTH_MIN:fo,SMOOTH_MAX:(n,t,o)=>-fo(-n,-t,o)};function Z(n,t){if(typeof n=="number")return()=>n;if(Array.isArray(n)){const a=new y(...n);return()=>a}if(n.kind==="direction")return a=>a;if(n.kind==="window"){if(!t)throw new Error("World Window coordinates need a render camera");return t}if(n.kind==="gradient"){const a=Z(n.vector,t),i={type:n.gradient_type},s=new y;return u=>{const c=a(u),f=typeof c=="number"?c:c.x,r=typeof c=="number"?c:c.y,l=typeof c=="number"?c:c.z,m=it.clamp(Va(f,r,l,i),0,1);return n.output==="Fac"?m:s.setScalar(m)}}if(n.kind==="to_float"){const a=Z(n.value,t);return i=>{const s=a(i);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 a=n.inputs.map(u=>Z(u,t)),i=Uo[n.operation],s=(u,c)=>{const f=a[u]?.(c)??0;if(typeof f!="number")throw new Error("World Math needs scalar inputs");return Math.fround(f)};return u=>{const c=Math.fround(i(s(0,u),s(1,u),s(2,u)));return n.clamp?it.clamp(c,0,1):c}}if(n.kind==="mix_color"){const a=Z(n.factor,t),i=Z(n.a,t),s=Z(n.b,t),u=new y,c=new y;return f=>{const r=a(f);if(typeof r!="number")throw new Error("World color Mix needs a scalar factor");const l=i(f);typeof l=="number"?u.setScalar(l):u.copy(l);const m=s(f);return typeof m=="number"?c.setScalar(m):c.copy(m),u.lerp(c,n.clamp_factor?it.clamp(r,0,1):r),n.clamp_result&&u.clampScalar(0,1),u}}if(n.kind==="sky"){const a=Ca({sunElevation:n.sun_elevation,sunRotation:n.sun_rotation,altitude:n.altitude,airDensity:n.air_density,aerosolDensity:n.aerosol_density,ozoneDensity:n.ozone_density});return i=>a(i)}if(n.kind==="mapping"){const a=Z(n.vector,t),i=new y(...n.location),s=new y(...n.scale),u=new ie().setFromEuler(new se(n.rotation[0],n.rotation[1],n.rotation[2],"ZYX")),c=u.clone().invert(),f=new y(...n.scale.map(l=>l===0?0:1/l)),r=new y;return l=>{const m=a(l);switch(typeof m=="number"?r.setScalar(m):r.copy(m),n.vector_type??"POINT"){case"TEXTURE":return r.sub(i).applyQuaternion(c).multiply(f);case"VECTOR":return r.multiply(s).applyQuaternion(u);case"NORMAL":return r.multiply(f).applyQuaternion(u).normalize();case"POINT":return r.multiply(s).applyQuaternion(u).add(i)}}}if(n.kind==="map_range"){const a=Z(n.value,t),i=Z(n.from_min,t),s=Z(n.from_max,t),u=Z(n.to_min,t),c=Z(n.to_max,t),f=Z(n.steps,t),r=(h,d)=>{const _=h(d);if(typeof _!="number")throw new Error("World Map Range needs scalar inputs");return _},l=n.interpolation,m=n.clamp;return h=>{const d=r(a,h),_=r(i,h),p=r(s,h),v=r(u,h),g=r(c,h);if(_===p)return 0;let b;if(l==="STEPPED"){const D=r(f,h),w=(d-_)/(p-_);b=D>0?Math.floor(w*(D+1))/D:0}else if(l==="SMOOTHSTEP"||l==="SMOOTHERSTEP"){const D=it.clamp((d-Math.min(_,p))/(Math.max(_,p)-Math.min(_,p)),0,1),w=l==="SMOOTHSTEP"?D*D*(3-2*D):D*D*D*(D*(D*6-15)+10);b=_>p?1-w:w}else b=(d-_)/(p-_);const P=v+b*(g-v);return m?v>g?it.clamp(P,g,v):it.clamp(P,v,g):P}}if(n.kind==="separate"){const a=Z(n.vector,t);return i=>{const s=a(i);return typeof s=="number"?s:s.getComponent(n.axis)}}const o=Z(n.factor,t),e=new y;return a=>{const i=o(a);if(typeof i!="number")throw new Error("World ColorRamp needs a scalar factor");const s=it.clamp(i,0,1)*256,u=Math.floor(s),c=n.colors[u],f=n.colors[Math.min(u+1,256)],r=n.interpolate?s-u:0;return e.set(it.lerp(c[0],f[0],r),it.lerp(c[1],f[1],r),it.lerp(c[2],f[2],r))}}function ja(n,t,o,e){const a=new Float32Array(t*o*3),i=Z(n,e),s=new y;for(let u=0;u<o;u++){const c=((u+.5)/o-.5)*Math.PI;for(let f=0;f<t;f++){const r=((f+.5)/t-.5)*2*Math.PI;s.set(Math.cos(c)*Math.cos(r),-Math.cos(c)*Math.sin(r),Math.sin(c));const l=i(s),m=(u*t+f)*3;a[m]=typeof l=="number"?l:l.x,a[m+1]=typeof l=="number"?l:l.y,a[m+2]=typeof l=="number"?l:l.z}}return a}function co(n){const t=[],o=e=>{if(!(typeof e=="number"||Array.isArray(e)))switch(e.kind){case"sky":t.push({sunElevation:e.sun_elevation,sunRotation:e.sun_rotation,altitude:e.altitude,airDensity:e.air_density,aerosolDensity:e.aerosol_density,ozoneDensity:e.ozone_density});return;case"mapping":case"gradient":case"separate":o(e.vector);return;case"ramp":o(e.factor);return;case"mix_color":o(e.factor),o(e.a),o(e.b);return;case"math":e.inputs.forEach(o);return;case"to_float":o(e.value);return;case"map_range":o(e.value),o(e.from_min),o(e.from_max),o(e.to_min),o(e.to_max),o(e.steps);return;default:return}};return o(n),t}function vt(n){if(typeof n=="number"||Array.isArray(n))return!1;switch(n.kind){case"window":return!0;case"mapping":case"gradient":case"separate":return vt(n.vector);case"ramp":return vt(n.factor);case"mix_color":return[n.factor,n.a,n.b].some(vt);case"math":return n.inputs.some(vt);case"to_float":return vt(n.value);case"map_range":return[n.value,n.from_min,n.from_max,n.to_min,n.to_max,n.steps].some(vt);default:return!1}}function Ba(n,t,o,e){e.updateMatrixWorld();const a=new Float32Array(t*o*3),i=new y,s=Z(n,()=>i),u=new y,c=e.getWorldPosition(new y),f=e.getWorldDirection(new y);for(let r=0;r<o;r++)for(let l=0;l<t;l++){const m=(l+.5)/t,h=(r+.5)/o;i.set(m,h,0),e.isOrthographicCamera?u.copy(f):u.set(m*2-1,h*2-1,.5).unproject(e).sub(c).normalize(),u.set(u.x,-u.z,u.y);const d=s(u),_=(r*t+l)*3;a[_]=typeof d=="number"?d:d.x,a[_+1]=typeof d=="number"?d:d.y,a[_+2]=typeof d=="number"?d:d.z}return a}const G=R().finite(),Ua=O({type:X(["POINT","SUN","SPOT","AREA"]),color:j([G,G,G]),energy:G,use_shadow:Y().default(!0),radius:G.optional(),spot_size:G.optional(),spot_blend:G.optional(),shape:X(["SQUARE","RECTANGLE","DISK","ELLIPSE"]).optional(),size:G.optional(),size_y:G.optional()}).strict();let Cn;function qa(){return Cn??=Le(async()=>{const{RectAreaLightUniformsLib:n}=await import("./RectAreaLightUniformsLib-u1ciScuw.js");return{RectAreaLightUniformsLib:n}},__vite__mapDeps([0,1])).then(({RectAreaLightUniformsLib:n})=>{n.init(),Jt()}),Cn}function Ha(){return Cn??Promise.resolve()}const Wa=n=>{const t=n.size??0,o=n.size_y??t;if(n.shape==="RECTANGLE")return[t,o];if(n.shape==="DISK"){const e=Math.sqrt(Math.PI*t*t/4);return[e,e]}if(n.shape==="ELLIPSE"){const e=Math.sqrt(Math.PI/4);return[t*e,o*e]}return[t,t]};function Ga(n,t){const o=(s,u)=>t&&u(t)?t:new s;if(n.type==="SUN"){const s=o(So,u=>u.isDirectionalLight);return s.intensity=n.energy,s.color.setRGB(n.color[0],n.color[1],n.color[2],at),s.castShadow=n.use_shadow,s}if(n.type==="POINT"){const s=o(Sn,u=>u.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],at),s.castShadow=n.use_shadow,s}if(n.type==="SPOT"){const s=o(En,u=>u.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],at),s.castShadow=n.use_shadow,s}qa();const e=o(rn,s=>s.isRectAreaLight),[a,i]=Wa(n);return e.width=a,e.height=i,e.intensity=n.energy/(Math.max(a*i,Number.MIN_VALUE)*Math.PI),e.color.setRGB(n.color[0],n.color[1],n.color[2],at),e}function Xa(n,t,o){if(!n.castShadow||o<=0)return;const a=n.getWorldPosition(new y).distanceTo(t),i=n.shadow;if(!i)return;const s=i.camera;s.near=Math.max(o*.001,a-o),s.far=a+o,n.isDirectionalLight&&(s.left=-o,s.right=o,s.top=o,s.bottom=-o),s.updateProjectionMatrix()}function Ya(n,t){n.position.set(0,0,0);const o=n;n.isRectAreaLight||o.target&&o.target.parent!==t&&(o.target.position.set(0,0,-1),t.add(o.target))}const Za=[{direction:[-.352546,.170931,-.920051],diffuse:[.033103,.033103,.033103],smooth:.52662},{direction:[-.408163,.346939,.844415],diffuse:[.521083,.538226,.538226],smooth:0},{direction:[.521739,.826087,.212999],diffuse:[.038403,.034357,.04953],smooth:.478261},{direction:[.624519,-.562067,-.542269],diffuse:[.090838,.08208,.072255],smooth:.2}],uo=.69;class Qa{constructor(){this.group=new _t,this.lights=[],this.group.name="BlenderSolidStudio";const t=new Ao;t.name="BlenderSolidStudioTarget",this.group.add(t);const o=new gt(0,0,0);for(const[a,i]of Za.entries()){const s=(1+i.smooth)**2,u=new So(16777215,Math.PI*uo/s);u.name=`BlenderSolidLight${a}`,u.color.setRGB(i.diffuse[0],i.diffuse[1],i.diffuse[2],at),u.position.set(i.direction[0],i.direction[1],i.direction[2]),u.target=t,this.group.add(u),this.lights.push(u),o.r+=i.diffuse[0]*i.smooth/s,o.g+=i.diffuse[1]*i.smooth/s,o.b+=i.diffuse[2]*i.smooth/s}const e=new fe(16777215,Math.PI*uo);e.name="BlenderSolidWrapFill",e.color.copy(o),this.group.add(e),this.lights.push(e)}setRendered(t){this.group.visible=!t}dispose(){for(const t of this.lights)t.dispose();this.group.clear()}}const It=j([G,G,G]),B=Io(()=>Nt([G,It,O({kind:L("direction")}).strict(),O({kind:L("window")}).strict(),O({kind:L("gradient"),gradient_type:X(["LINEAR","QUADRATIC","EASING","DIAGONAL","SPHERICAL","QUADRATIC_SPHERE","RADIAL"]),output:X(["Fac","Color"]),vector:B}).strict(),O({kind:L("to_float"),source_type:X(["RGBA","VECTOR"]),value:B}).strict(),O({kind:L("math"),operation:X(Object.keys(Uo)),clamp:Y(),inputs:z(B).min(1).max(3)}).strict(),O({kind:L("mix_color"),factor:B,a:B,b:B,clamp_factor:Y(),clamp_result:Y()}).strict(),O({kind:L("mapping"),vector_type:X(["POINT","TEXTURE","VECTOR","NORMAL"]).optional(),vector:B,location:It,rotation:It,scale:It}).strict(),O({kind:L("separate"),vector:B,axis:R().int().min(0).max(2)}).strict(),O({kind:L("ramp"),factor:B,colors:z(It).length(257),interpolate:Y()}).strict(),O({kind:L("map_range"),interpolation:X(["LINEAR","STEPPED","SMOOTHSTEP","SMOOTHERSTEP"]),clamp:Y(),value:B,from_min:B,from_max:B,to_min:B,to_max:B,steps:B}).strict(),O({kind:L("sky"),sun_elevation:G,sun_rotation:G,altitude:G,air_density:G,aerosol_density:G,ozone_density:G}).strict()])),_o=O({color:It,strength:G,shader:B.optional()}),Ka=_o.extend({volume:z(O({kind:X(["absorption","scatter","principled","emission"]),phase:A(),alpha:B,weight:B,color:B,density:B,anisotropy:B,absorption_color:B,emission_color:B,emission_strength:B,blackbody_intensity:B,temperature:B,blackbody_tint:B}).strict()).optional(),lighting:_o.strict().optional()}).strict(),Ja=4,qt=new Map,wn=new Set;function mo(n,t,o){const i=vt(n);if(i&&!o)throw new Error("World Window coordinates need a render camera");o?.updateMatrixWorld();const s=JSON.stringify([n,i?[o.matrixWorld.elements,o.projectionMatrix.elements]:null]),u=qt.get(s);if(u!==void 0)return kn(u,t,256,128);const c=new y,f=new Eo,r=o?new mt().multiplyMatrices(o.projectionMatrix,o.matrixWorldInverse):null,l=o?.getWorldPosition(new y),h=ja(n,256,128,i?d=>(c.set(d.x,d.z,-d.y),o.isPerspectiveCamera&&c.add(l),f.set(c.x,c.y,c.z,1).applyMatrix4(r),f.w===0?c.set(0,0,0):c.set(f.x/f.w*.5+.5,f.y/f.w*.5+.5,0)):void 0);return qt.set(s,h),qt.size>Ja&&qt.delete(qt.keys().next().value),kn(h,t,256,128)}function tl(n,t,o,e){const a=Wt.toHalfFloat(1);for(let i=0;i<e;i++)n[i*4]=Wt.toHalfFloat(t[i*3]*o),n[i*4+1]=Wt.toHalfFloat(t[i*3+1]*o),n[i*4+2]=Wt.toHalfFloat(t[i*3+2]*o),n[i*4+3]=a}function kn(n,t,o,e){const a=new Uint16Array(o*e*4);tl(a,n,t,o*e);const i=new mn(a,o,e,dn,jn);return i.mapping=ue,i.colorSpace=at,i.minFilter=St,i.magFilter=St,i.needsUpdate=!0,i}class Hn{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 o=t;for(;o;){if(o.isScene)return o;o=o.parent}return null}apply(t,o,e){if(this.clear(),this.pending=null,!o)return;const a=Hn.sceneOf(t);if(!a)return;this.applied={scene:a,background:a.background,environment:a.environment};const i=o.shader??o.color,s=this.generation,c=[...co(i),...o.lighting?co(o.lighting.shader??o.lighting.color):[]].filter(r=>!Da(r));if(c.length===0){this.compose(a,o,i,e);return}const f=(async()=>{const r=await Promise.all(c.map(La));c.forEach((l,m)=>{Bo(l,r[m])}),!(this.generation!==s||this.applied?.scene!==a)&&(this.compose(a,o,i,e),Jt())})();this.pending=f,wn.add(f),f.then(()=>wn.delete(f),()=>wn.delete(f))}compose(t,o,e,a){if(this.texture=mo(e,o.strength,a),vt(e)){if(!a)throw new Error("World Window coordinates need a render camera");this.screenTexture=kn(Ba(e,512,512,a),o.strength,512,512),this.screenTexture.mapping=ce,t.background=this.screenTexture}else if(a&&a.isOrthographicCamera){const s=a.getWorldDirection(new y);s.set(s.x,-s.z,s.y);const u=Z(o.shader??o.color)(s);t.background=typeof u=="number"?new gt().setRGB(u,u,u).multiplyScalar(o.strength):new gt().setRGB(u.x,u.y,u.z).multiplyScalar(o.strength)}else t.background=this.texture;const{lighting:i}=o;this.environmentTexture=i?mo(i.shader??i.color,i.strength,a):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 qo(n){return[n.min.x,n.max.x].flatMap(t=>[n.min.y,n.max.y].flatMap(o=>[n.min.z,n.max.z].map(e=>new y(t,o,e))))}function nl(n,t){if(n.isEmpty()||!t.intersectsBox(n))return[];const o=qo(n);if(o.every(r=>t.containsPoint(r)))return o;const e=[...t.planes,new Mt(new y(1,0,0),-n.min.x),new Mt(new y(-1,0,0),n.max.x),new Mt(new y(0,1,0),-n.min.y),new Mt(new y(0,-1,0),n.max.y),new Mt(new y(0,0,1),-n.min.z),new Mt(new y(0,0,-1),n.max.z)],a=[],i=new y,s=new y,u=new y,c=new y,f=Math.max(1,n.min.length(),n.max.length())*1e-8;for(let r=0;r<e.length;r++)for(let l=r+1;l<e.length;l++)for(let m=l+1;m<e.length;m++){const h=e[r],d=e[l],_=e[m];i.crossVectors(d.normal,_.normal);const p=h.normal.dot(i);Math.abs(p)<1e-12||(s.crossVectors(_.normal,h.normal),u.crossVectors(h.normal,d.normal),c.copy(i).multiplyScalar(-h.constant).addScaledVector(s,-d.constant).addScaledVector(u,-_.constant).divideScalar(p),e.every(v=>v.distanceToPoint(c)>=-f)&&a.push(c.clone()))}return a}function ol(n,t,o){if(!n.castShadow||!t.length)return;n.shadow.updateMatrices(n);const e=n.shadow.camera,a=e.matrixWorldInverse,i=new fn().setFromPoints(t.map(m=>m.clone().applyMatrix4(a))),s=i.getSize(new y),u=Math.max(s.length()*1e-6,Number.EPSILON),c=2+2*Math.SQRT2,f=Math.max(s.x,s.y,u)/Math.max(1,Math.min(n.shadow.mapSize.x,n.shadow.mapSize.y)-2*c),r=2*Math.SQRT2*f,l=c*f;i.min.x-=l,i.min.y-=l,i.max.x+=l,i.max.y+=l;for(const m of o){if(m.isEmpty())continue;const h=new fn().setFromPoints(qo(m).map(d=>d.applyMatrix4(a)));h.max.x<i.min.x||h.min.x>i.max.x||h.max.y<i.min.y||h.min.y>i.max.y||(i.min.z=Math.min(i.min.z,h.min.z),i.max.z=Math.max(i.max.z,h.max.z))}e.left=i.min.x,e.right=i.max.x,e.bottom=i.min.y,e.top=i.max.y,e.near=-i.max.z-r-u,e.far=-i.min.z+r+u,e.updateProjectionMatrix(),n.shadow.normalBias=r}const Ct=R().finite(),ho=j([Ct,Ct,Ct]),Ho=O({min:j([R().int(),R().int(),R().int()]),max:j([R().int(),R().int(),R().int()]),density:z(Ct),voxelSize:Ct.positive(),color:ho,emission:ho,densityScale:Ct.nonnegative()}).strict();function el(n){const t=n.max.map((r,l)=>r-n.min[l]+1);if(t.some(r=>r<=0)||t.reduce((r,l)=>r*l,1)!==n.density.length)throw new Error("Volume density dimensions do not match the evaluated grid");const o=new _e(new Float32Array(n.density),t[0],t[1],t[2]);o.format=me,o.type=No,o.minFilter=o.magFilter=St,o.unpackAlignment=1,o.needsUpdate=!0;const e=new y(...n.min).addScalar(-.5).multiplyScalar(n.voxelSize),a=new y(t[0],t[1],t[2]).multiplyScalar(n.voxelSize),i=new de(a.x,a.y,a.z),s=i.getAttribute("position");for(let r=0;r<s.count;r++)s.setXYZ(r,e.x+(s.getX(r)>0?a.x:0),e.y+(s.getY(r)>0?a.y:0),e.z+(s.getZ(r)>0?a.z:0));s.needsUpdate=!0,i.computeBoundingBox(),i.computeBoundingSphere();const u=new Vn({glslVersion:pe,side:he,transparent:!0,depthWrite:!1,premultipliedAlpha:!0,uniforms:{densityGrid:{value:o},minimum:{value:e},extent:{value:a},voxelSize:{value:n.voxelSize},densityScale:{value:n.densityScale},volumeColor:{value:new y(...n.color)},emission:{value:new y(...n.emission)},cameraLocal:{value:new y},rayLocal:{value:new y},orthographic:{value:!1},worldScale:{value:new Oo}},vertexShader:`
19
+ `;function St(o){return new ht().setHex(o,Mt)}function ho(o,t){const n=o.mode==="POSE";let e;return n?t.active&&t.select?e=St(xt.poseActive):t.active?e=St(xt.poseActiveUnsel):t.select?e=St(xt.pose):e=St(xt.wire):e=St(xt.vertex),n&&t.lockedWeight&&e.lerp(St(xt.lockedWeight),xt.lockedWeightFactor),e}function po(o,t){const n=St(xt.solid);return o.mode==="POSE"&&t.lockedWeight&&n.lerp(St(xt.lockedWeight),xt.lockedWeightFactor),n}const Ta=new X,Pa=new x,vo=new qo;function go(o,t){return new X().set(...t.matrix.flat()).premultiply(o).scale(new x().setScalar(t.length))}class Aa{constructor(){this.group=new ot,this.disposables=[],this.signature="",this.group.name="BlenderArmatureOverlay"}apply(t,n){const e=[],r=JSON.stringify(t);if(r===this.signature)return e;this.signature=r,this.clear();for(const a of Object.values(t)){const i=n(a.object);if(i===null)continue;a.displayType!=="OCTAHEDRAL"&&a.displayType!=="STICK"&&e.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"&&e.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 c=a.bones.filter(f=>!f.hide);if(c.length===0)continue;const u=a.displayType==="STICK"?this.buildStick(a,c,i):this.buildOctahedral(a,c,i);a.showInFront&&u.traverse(f=>{const s=f.material;s&&"depthTest"in s&&(s.depthTest=!1),f.renderOrder=10}),this.group.add(u)}return e}buildOctahedral(t,n,e){const r=new ot;r.name=`${t.object}:bones`;const a=[],i=[],c=[],u=[],f=[],s=[],l=[],_=[],h=[],d=[];for(const m of n){const p=go(e,m),v=po(t,m),g=pa(v),b=ho(t,m);vo.setFromMatrix4(p).invert().transpose();for(let T=0;T<_o.length;T++){const A=Pa.set(...va[T]).applyMatrix3(vo).normalize().clone();for(const O of _o[T]){const M=new x(...An[O]).applyMatrix4(p);a.push(M.x,M.y,M.z),i.push(A.x,A.y,A.z),c.push(v.r,v.g,v.b),u.push(g.r,g.g,g.b)}}const w=mo(m)===2?l:f,R=mo(m)===2?_:s;for(const[T,A]of ga){const O=new x(...An[T]).applyMatrix4(p),M=new x(...An[A]).applyMatrix4(p);w.push(O.x,O.y,O.z,M.x,M.y,M.z),R.push(b.r,b.g,b.b,b.r,b.g,b.b)}m.parent!==null&&m.connected||(h.push(p.clone()),d.push(v)),h.push(p.clone().multiply(Ta.makeTranslation(0,1,0))),d.push(v)}r.add(this.solidMesh(a,i,c,u)),f.length&&r.add(this.lines(f,s,1)),l.length&&r.add(this.lines(l,_,2));for(let m=0;m<h.length;m++)r.add(this.point(h[m],d[m]));return r}buildStick(t,n,e){const r=new ot;r.name=`${t.object}:bones`;const a=[],i=[],c=[],u=[];for(const f of n){const s=go(e,f),l=new x().setFromMatrixPosition(s),_=new x(0,1,0).applyMatrix4(s),h=ho(t,f),d=po(t,f);a.push(l.x,l.y,l.z,_.x,_.y,_.z),i.push(h.r,h.g,h.b,h.r,h.g,h.b),c.push(l.x,l.y,l.z,_.x,_.y,_.z),u.push(d.r,d.g,d.b,d.r,d.g,d.b)}return r.add(this.lines(a,i,ba)),r.add(this.lines(c,u,ya)),r}solidMesh(t,n,e,r){const a=new fn;a.setAttribute("position",new bt(t,3)),a.setAttribute("normal",new bt(n,3)),a.setAttribute("aSolid",new bt(e,3)),a.setAttribute("aHint",new bt(r,3));const i=new Kn({vertexShader:wa,fragmentShader:Oa,side:Te});this.disposables.push(a,i);const c=new Tt(a,i);return c.frustumCulled=!1,c}lines(t,n,e){const r=new Uo;r.setPositions(t),r.setColors(n);const a=new Wo({linewidth:e,vertexColors:!0});this.disposables.push(r,a);const i=new Ho(r,a);return i.frustumCulled=!1,i}point(t,n){const e=new Pe(xa,12,8),r=new bn({color:n});this.disposables.push(e,r);const a=new Tt(e,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 Sa="RUNTIME_FRAME_UNKNOWN_GEOMETRY",Qt="RUNTIME_FRAME_UNKNOWN_IMAGE";function Ea(o){const t=Math.fround,n=t(t(t(o[0]*o[0])+t(o[1]*o[1]))+t(o[2]*o[2]));if(n>1e-35){const e=t(Math.sqrt(n)),r=t(1/e);return{unit:[t(o[0]*r),t(o[1]*r),t(o[2]*r)],length:e}}return{unit:[0,0,0],length:0}}const N=Math.fround,wn=N(2*Math.PI),Sn=N(1-1e-4),Ft=(o,t)=>N(N(N(o[0]*t[0])+N(o[1]*t[1]))+N(o[2]*t[2])),rn=(o,t,n=1)=>o.map((e,r)=>N(e+N(t[r]*n))),Ma=(o,t)=>o.map((n,e)=>N(n-t[e]));function Kt(o){const t=N(Math.sqrt(Ft(o,o)));return t>0?o.map(n=>N(n/t)):[0,0,0]}function Jt(o){const t=Math.abs(o)<1?N(1-N(1-Math.abs(o))):1;let n=N(N(.077980478)+N(t*N(-.02164095)));n=N(N(-.213300989)+N(t*n)),n=N(N(1.5707963267)+N(t*n));const e=N(N(Math.sqrt(N(1-t)))*n);return o<0?N(N(Math.PI)-e):e}function Na(o){let t=o.at(-1);const n=[0,0,0];for(const e of o){for(let r=0;r<3;r++){const a=(r+1)%3,i=(r+2)%3;n[r]=N(n[r]+N(N(t[a]-e[a])*N(t[i]+e[i])))}t=e}return n}function Ra(o){const t=[],n=[],e=(d,m)=>d<m?`${d}:${m}`:`${m}:${d}`,r=new Map((o.edge_order??[]).map(([d,m],p)=>[e(d,m),p])),a=new Set((o.sharp??[]).map(([d,m])=>e(d,m))),i=new Map;for(const[d,m]of o.f.entries()){const p=t.length,v=Ea(Na(m.map(g=>o.v[g]))).unit;n.push(v.some(Boolean)?v:[0,0,1]);for(let g=0;g<m.length;g++){const b=e(m[g],m[(g+1)%m.length]);r.has(b)||r.set(b,r.size);const w=o.face_edges?.[d]?.[g]??r.get(b),R=t.length;t.push({vertex:m[g],face:d,edge:w,prev:p+(g+m.length-1)%m.length,next:p+(g+1)%m.length});const T=i.get(w)??[];T.push(R),i.set(w,T)}}const c=new Map,u=new Map;for(const[d,m]of i){if(m.length!==2||o.edge_sharp?.[d])continue;const[p,v]=m,g=t[p],b=t[v];!o.s?.[g.face]||!o.s?.[b.face]||g.vertex!==t[b.next].vertex||b.vertex!==t[g.next].vertex||!o.edge_sharp&&a.has(e(g.vertex,b.vertex))||(u.set(p,b.next),c.set(b.next,p),u.set(v,g.next),c.set(g.next,v))}const f=[],s=[],l=[],_=[],h=(d,m)=>Kt(Ma(o.v[t[t[d][m]].vertex],o.v[t[d].vertex]));for(let d=0;d<t.length;d++){if(s[d]!==void 0)continue;let m=d;const p=new Set([m]);for(;u.has(m)&&!p.has(u.get(m));)m=u.get(m),p.add(m);u.has(m)&&(m=Math.min(...p));const v=[m];for(;c.has(v.at(-1))&&c.get(v.at(-1))!==m;)v.push(c.get(v.at(-1)));let g=[0,0,0];if(v.length===1)g=n[t[m].face];else{for(const M of v)g=rn(g,n[t[M].face],Jt(Ft(h(M,"prev"),h(M,"next"))));g=Kt(g)}const b=h(m,"next"),w=v.at(-1),R=h(w,"prev"),T=Ft(b,g),A=Ft(R,g),O={normal:g,reference:[0,0,0],ortho:[0,0,0],alpha:0,beta:0};if(Math.abs(T)<Sn&&Math.abs(A)<Sn){const M=v.length>1?v.map(pt=>h(pt,"next")):[];M.length&&t[t[w].prev].edge!==t[m].edge&&M.push(R),O.alpha=M.length?N(M.reduce((pt,y)=>N(pt+Jt(Ft(y,g))),0)/M.length):N(N(Jt(T)+Jt(A))/2),O.reference=Kt(rn(b,g,-T));const C=g,V=O.reference;O.ortho=Kt([N(N(C[1]*V[2])-N(C[2]*V[1])),N(N(C[2]*V[0])-N(C[0]*V[2])),N(N(C[0]*V[1])-N(C[1]*V[0]))]);const H=Kt(rn(R,g,-A)),Q=Ft(O.reference,H),tt=Jt(Q);O.beta=Q<Sn?Ft(O.ortho,H)<0?N(wn-tt):tt:wn}O.alpha===0&&(O.normal=[0,0,0]);for(const M of v)s[M]=f.length;f.push(v),l.push(O),_.push(g)}return{corners:t,fans:f,fanOf:s,spaces:l,faceNormals:n,fanNormals:_}}function Ia(o,t){if(!t[0]||o.alpha===0||o.beta===0)return o.normal;const n=N(t[0]/32767),e=N(t[1]/32767),r=N((n>0?o.alpha:N(wn-o.alpha))*n),a=N((e>0?o.beta:N(wn-o.beta))*e);let i=o.normal.map(c=>N(c*N(Math.cos(r))));return i=rn(i,o.reference,N(N(Math.sin(r))*N(Math.cos(a)))),e!==0&&(i=rn(i,o.ortho,N(N(Math.sin(r))*N(Math.sin(a))))),i}function oe(o,t){if(!t)return null;const{corners:n,fans:e,spaces:r}=Ra(o);if(t.type==="INT16_2D"&&t.domain==="CORNER"){const a=new Array(n.length);for(const[i,c]of e.entries()){const u=c.reduce((s,l)=>{const _=t.data[l];return[s[0]+_[0],s[1]+_[1]]},[0,0]),f=Ia(r[i],u.map(s=>Math.trunc(s/c.length)));for(const s of c)a[s]=f}return a}if(t.type==="FLOAT_VECTOR")return n.map((a,i)=>{const c=t.domain==="POINT"?a.vertex:t.domain==="FACE"?a.face:i;return t.data[c]});throw new Error(`Unsupported custom_normal attribute: ${t.type}/${t.domain}`)}const En={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}},za=1e-6;function Fa(o){const t=new x;for(let n=0;n<o.length;n++){const e=o[n],r=o[(n+1)%o.length];t.x+=(e.y-r.y)*(e.z+r.z),t.y+=(e.z-r.z)*(e.x+r.x),t.z+=(e.x-r.x)*(e.y+r.y)}return t.multiplyScalar(.5)}const Da=(o,t,n)=>(t.x-o.x)*(n.y-o.y)-(t.y-o.y)*(n.x-o.x),xo=o=>Array.from({length:o-2},(t,n)=>[0,n+1,n+2]);function Ca(o){let t=0;for(let n=0;n<o.length;n++){const e=o[n],r=o[(n+1)%o.length];t+=e.x*r.y-r.x*e.y}return t}function bo(o,t,n){if(o.length!==t.length-2||!(Math.abs(n)>0))return!1;const e=Math.sign(n);let r=0;for(const[a,i,c]of o){const u=Da(t[a],t[i],t[c]);if(u*e<0)return!1;r+=Math.abs(u)}return Math.abs(r-Math.abs(n))<=za*Math.abs(n)}function ka(o){const t=o.length;if(t<3)return{triangles:[],sound:!1,method:"fan"};if(t===3)return{triangles:[[0,1,2]],sound:!0,method:"fan"};const n=Fa(o),e=n.length();if(!(e>0)||!Number.isFinite(e))return{triangles:xo(t),sound:!1,method:"fan"};const r=n.clone().divideScalar(e),a=Math.abs(r.x)<.9?new x(1,0,0):new x(0,1,0),i=new x().crossVectors(a,r).normalize(),c=new x().crossVectors(r,i),u=o[0],f=o.map(h=>{const d=h.clone().sub(u);return new $t(d.dot(i),d.dot(c))}),s=Ca(f),l=xo(t);if(bo(l,f,s))return{triangles:l,sound:!0,method:"fan"};let _=[];try{_=Ae.triangulateShape(f,[]).map(h=>[h[0],h[1],h[2]])}catch{return{triangles:l,sound:!1,method:"fan"}}return bo(_,f,s)?{triangles:_,sound:!0,method:"earcut"}:{triangles:_.length>0?_:l,sound:!1,method:_.length>0?"earcut":"fan"}}const $a=new Set(["FLOAT","FLOAT2","FLOAT_VECTOR","FLOAT_COLOR","BYTE_COLOR"]);function Mn(o){const t=o/255;return t<.04045?t<0?0:t*(1/12.92):((t+.055)*(1/1.055))**2.4}function Nn(o,t,n){switch(o){case"FLOAT":{const e=Number(t[n]);return[e,e,e,1]}case"FLOAT2":return[Number(t[n*2]),Number(t[n*2+1]),0,1];case"FLOAT_VECTOR":return[Number(t[n*3]),Number(t[n*3+1]),Number(t[n*3+2]),1];case"BYTE_COLOR":return[Mn(Number(t[n*4])),Mn(Number(t[n*4+1])),Mn(Number(t[n*4+2])),Number(t[n*4+3])/255];default:return[Number(t[n*4]),Number(t[n*4+1]),Number(t[n*4+2]),Number(t[n*4+3])]}}function ee(o,t){return o.filter(n=>$a.has(n.type)&&n.domain!=="EDGE"&&!n.name.startsWith(".")&&n.name!=="position"&&n.name!=="custom_normal"&&!(n.type==="FLOAT2"&&n.domain==="CORNER")).map(n=>{const e=t(n.data,n.type),r=[0,0,0,0];return{name:n.name,domain:n.domain,read:(a,i,c)=>n.domain==="POINT"?Nn(n.type,e,a):n.domain==="CORNER"?i===void 0?r:Nn(n.type,e,i):c===void 0?r:Nn(n.type,e,c)}})}function ae(o){const t=o.vertexCount,n=o.starts.length-1,e=o.starts,r=o.cornerVerts,a=e[n];let i=t;for(let y=0;y<n;y++)i+=(e[y+1]-e[y]-2)*3;const c=new Uint32Array(a),u=new Uint8Array(a),f=new Uint8Array(t),s=new Uint32Array(a);let l=!1;for(let y=0;y<n;y++)if(o.smooth(y)){l=!0;break}const _=(y,L)=>t<94906265?Math.min(y,L)*t+Math.max(y,L):`${Math.min(y,L)}:${Math.max(y,L)}`,h=new Map,d=new Set;for(const[y,L]of o.sharp)d.add(_(y,L));if(o.edges)for(const[y,L]of o.edges){if(y===L)throw new Error("Runtime mesh edge needs distinct vertices");h.set(_(y,L),-1)}const m=y=>{for(;s[y]!==y;)s[y]=s[s[y]],y=s[y];return y},p=(y,L)=>{const D=m(y),Y=m(L);s[Math.max(D,Y)]=Math.min(D,Y)};for(let y=0;y<n;y++){const L=e[y],D=e[y+1]-L,Y=o.smooth(y)?1:0;for(let Z=0;Z<D;Z++){const k=L+Z;f[r[k]]=1,c[k]=L+(Z+1)%D,u[k]=Y,s[k]=k}}for(let y=0;y<a;y++){const L=c[y],D=r[y],Y=r[L],Z=_(D,Y),k=h.get(Z);if(k!==void 0&&k>=0&&u[y]&&u[k]&&!d.has(Z)){const G=c[k];p(y,r[k]===D?k:G),p(L,r[k]===D?G:k)}(k===void 0||k<0||!u[k]&&u[y])&&h.set(Z,y)}const v=o.uv,g=new Float32Array(i*3),b=new Float32Array(i*2),w=new Uint32Array(i),R=(o.uvLayers??[]).map(y=>({...y,data:new Float32Array(i*2)})),T=(o.attributeLayers??[]).map(y=>({...y,data:new Float32Array(i*4)})),A=o.orco?new Float32Array(i*3):null,O=new Uint32Array(i),M=new Map,C=[],V=o.normals||o.cornerNormal?new Float32Array(i*3):null;let H=0,Q=0;const tt=(y,L,D,Y,Z)=>{const k=H++;for(const G of T)G.data.set(G.read(y,Y,Z),k*4);if(A)for(let G=0;G<3;G++)A[k*3+G]=o.orco[y*3+G]*.5+.5;if(w[k]=y,o.co(y).toArray(g,k*3),L&&b.set(L,k*2),D&&V.set(D,k*3),Y!==void 0)for(const G of R)G.data.set(G.read(Y),k*2);return k},pt=(y,L)=>{const D=v?.(y),Y=o.cornerNormal?[o.cornerNormal[y*3],o.cornerNormal[y*3+1],o.cornerNormal[y*3+2]]:o.normals?.[y];if(!l)return tt(r[y],D,Y,y,L);const Z=`${u[y]?m(y):y}${D?`:${D[0]}:${D[1]}`:""}${Y?`:n${Y.join(":")}`:""}${R.map(G=>":"+G.read(y).join(":")).join("")}${T.map(G=>G.domain==="POINT"?"":":"+Array.from(G.read(r[y],y,L)).join(":")).join("")}`;let k=M.get(Z);return k===void 0&&(k=tt(r[y],D,Y,y,L),M.set(Z,k)),k};for(let y=0;y<n;y++){const L=Q,D=e[y],Y=e[y+1]-D,Z=[];for(let Yt=0;Yt<Y;Yt++)Z.push(o.co(r[D+Yt]));for(const Yt of ka(Z).triangles)for(const Oe of Yt)O[Q++]=pt(D+Oe,y);const k=o.material(y),G=C.at(-1);G?.materialIndex===k?G.count+=Q-L:C.push({start:L,count:Q-L,materialIndex:k})}for(let y=0;y<t;y++)f[y]||tt(y);return{positions:g.slice(0,H*3),normals:V?.slice(0,H*3)??null,uv:v?b.slice(0,H*2):null,uvLayers:R.map(y=>({name:y.name,data:y.data.slice(0,H*2)})),attributeLayers:T.map(y=>({name:y.name,data:y.data.slice(0,H*4)})),orco:A?A.slice(0,H*3):null,indices:O.slice(0,Q),sourceVertex:w.slice(0,H),groups:C}}function Vt(o){return`blenderA_${Array.from(new TextEncoder().encode(o),t=>t.toString(16).padStart(2,"0")).join("")}`}function Wn(o){const t=new fn;t.setAttribute("position",new it(o.positions,3)),t.setAttribute("uv",new it(o.uv??new Float32Array(o.positions.length/3*2),2)),t.setIndex(new it(o.indices,1));const n=Object.create(null);for(const[e,r]of(o.uvLayers??[]).entries()){if(e>=8)throw new Error("A Blender mesh supports at most eight UV maps");n[r.name]=e+1,t.setAttribute(`uv${e+1}`,new it(r.data,2))}t.userData.blenderUvChannels=n;for(const e of o.attributeLayers??[])t.setAttribute(Vt(e.name),new it(e.data,4));t.userData.blenderAttributes=(o.attributeLayers??[]).map(e=>e.name),o.orco&&(t.setAttribute("blenderOrco",new it(o.orco,3)),t.userData.blenderOrcoFromDoor=!0);for(const e of o.groups)t.addGroup(e.start,e.count,e.materialIndex);return o.normals?t.setAttribute("normal",new it(o.normals,3)):t.computeVertexNormals(),o.sourceVertex&&t.setAttribute("blenderVertex",new it(o.sourceVertex,1)),t}function La(o,t){const n=o.co.length/3,e=o.attributes.filter(m=>m.type==="FLOAT2"&&m.domain==="CORNER"),r=o.renderUv??o.activeUv??e[0]?.name,a=e.find(m=>m.name===r);if(r&&!a)throw new Error(`Runtime UV map ${r} is missing`);const i=a?a.data:null,c=o.edge.length/2,u=new Array(c);for(let m=0;m<c;m++)u[m]=[o.edge[m*2],o.edge[m*2+1]];const f=[];for(let m=0;m<c;m++)o.edgeSharp[m]===1&&f.push(u[m]);const s=o.cornerNormal?void 0:o.attributes.find(m=>m.name==="custom_normal"),l=s?{v:Array.from({length:n},(m,p)=>[o.co[p*3],o.co[p*3+1],o.co[p*3+2]]),f:Array.from({length:o.faceStart.length-1},(m,p)=>Array.from(o.corner.subarray(o.faceStart[p],o.faceStart[p+1]))),s:Array.from(o.smooth,Boolean),edge_order:u,sharp:f,face_edges:Array.from({length:o.faceStart.length-1},(m,p)=>Array.from(o.cornerEdge.subarray(o.faceStart[p],o.faceStart[p+1]))),edge_sharp:Array.from(o.edgeSharp,Boolean)}:null,_=s?{type:s.type,domain:s.domain,data:Array.from({length:s.data.length/En[s.type].size},(m,p)=>Array.from({length:En[s.type].size},(v,g)=>Number(s.data[p*En[s.type].size+g])))}:void 0,h=new x,d={vertexCount:n,normals:l?oe(l,_):null,cornerNormal:o.cornerNormal,orco:o.orco,co:m=>h.set(o.co[m*3],o.co[m*3+1],o.co[m*3+2]).clone(),starts:o.faceStart,cornerVerts:o.corner,smooth:m=>o.smooth[m]===1,material:m=>o.material[m],edges:u,sharp:f,uv:i?m=>[i[m*2],i[m*2+1]]:null,uvLayers:e.map(m=>({name:m.name,read:p=>[Number(m.data[p*2]),Number(m.data[p*2+1])]})),attributeLayers:ee(o.attributes,m=>m)};return{...ae(d),hash:t}}function Va(o){const t=o.v.map(l=>new x(...l)),n=l=>{const _=t[l];if(!_)throw new Error(`Runtime mesh vertex ${l} is missing`);return _},e=new Uint32Array(o.f.length+1);o.f.forEach((l,_)=>{if(l.length<3||new Set(l).size!==l.length)throw new Error("Runtime mesh face needs at least three distinct vertices");e[_+1]=e[_]+l.length});const r=new Uint32Array(e[o.f.length]);o.f.forEach((l,_)=>l.forEach((h,d)=>{n(h),r[e[_]+d]=h}));for(const[l,_]of o.edge_order??o.e??[])n(l),n(_);const a={POINT:t.length,EDGE:(o.edge_order??o.e??[]).length,FACE:o.f.length,CORNER:r.length};for(const l of o.attributes??[])if(l.domain!=="EDGE"&&l.data.length!==a[l.domain])throw new Error(`Runtime attribute ${l.name} has ${l.data.length} values for ${a[l.domain]} ${l.domain} elements`);const i=(o.attributes??[]).filter(l=>l.type==="FLOAT2"&&l.domain==="CORNER"),c=o.render_uv??o.active_uv??i[0]?.name,u=i.find(l=>l.name===c);if(c&&!u)throw new Error(`Runtime UV map ${c} is missing`);const f=u?.data,s={vertexCount:t.length,normals:oe(o,o.attributes?.find(l=>l.name==="custom_normal")),co:n,starts:e,cornerVerts:r,smooth:l=>!!o.s?.[l],material:l=>o.m?.[l]??0,edges:o.edge_order??o.e??null,sharp:o.sharp??[],uv:f?l=>f[l]:null,uvLayers:i.map(l=>({name:l.name,read:_=>l.data[_]})),attributeLayers:ee(o.attributes??[],l=>Array.from(l).flat())};return Wn(ae(s))}const sn=1.5707963267948966,Dt=6.283185307179586,re=.3183098861837067,le=.0795774715459476,ja=.3,Ba=le,Ua=3/16*re,Hn=.8,yo=Hn*Hn,Ct=6371,ie=100,qn=Ct+ie,wo=64,Oo=64,et=256,Nt=64,Wa=[1.679,1.828,1.986,1.307],Ha=[.006605,.01067,.01842,.03156],qa=[3472e-28,3914e-28,1349e-28,1103e-29],Ga=334.5,Xa=[28722e-28,46168e-28,79706e-28,13578e-27],Ya=[15908e-26,17711e-26,20942e-26,24033e-26],To=13681e16,Za=2e6,Qa=.73,Rn=[[53.38691773856467,22.981337506691023,0],[43.90484446636936,71.3477957000534,.10250686796574131],[1.6137278251608962,18.422960591455485,31.742921188390806],[20.762668673810577,2.361421352331437,110.4800964325214]],yt=[[3.2409698963165283,-1.5373831987380981,-.49861079454421997],[-.969243586063385,1.8759675025939941,.041555099189281464],[.05563009902834892,-.20397700369358063,1.056971549987793]],On=o=>o*o,on=o=>o<0?0:o>1?1:o,Ot=(o,t,n)=>o+n*(t-o),Ka=o=>Math.sqrt(Math.max(o,0)),se=o=>[-Math.sqrt(1-o*o),0,o];function Gn(o,t,n,e,r,a,i){const c=o*e+t*r+n*a,u=o*o+t*t+n*n-i*i;if(u>0&&c>0)return-1;const f=c*c-u;return f<0?-1:f>=c*c?-c+Math.sqrt(f):-c-Math.sqrt(f)}const Ja=o=>Ua*(1+On(o));function tr(o){const t=1+yo+2*Hn*o;return le*(1-yo)/(t*Math.sqrt(t))}const nr=o=>To*(Math.exp(-o/Qa)+Za/To);function oo(o,t){let n=o%Dt;Math.abs(n)>=Math.PI&&(n-=Math.sign(n)*2*Math.PI);let e=t;return(n>=sn||n<=-sn)&&(n=Math.sign(n)*Math.PI-n,e+=Math.PI),e=e%Dt,e<0&&(e+=Dt),e=Dt-e,[n,e]}class or{constructor(t,n,e){this.air=t,this.aerosol=n,this.ozone=e,this.lut=new Float32Array(Nt*et*4)}coefficients(t,n){const e=nr(t)*this.aerosol,r=Math.log(Math.max(t,1e-4)),a=378547397e12*Math.exp(-On(r-3.22261)*5.55555555-r),i=Math.exp(-.07771971*t**1.16364243);for(let c=0;c<4;c++)n[c]=Xa[c]*e,n[4+c]=Ya[c]*e,n[8+c]=qa[c]*Ga*a*this.ozone,n[12+c]=Ha[c]*i*this.air}transmittance(t,n,e){const[r,a,i]=se(t),c=Ot(Ct,qn,n),f=Gn(0,0,c,r,a,i,qn)/wo,s=[0,0,0,0],l=new Float64Array(16);for(let _=0;_<wo;_++){const h=(_+.5)*f,d=r*h,m=a*h,p=c+i*h,v=Math.max(Math.hypot(d,m,p)-Ct,0);this.coefficients(v,l);for(let g=0;g<4;g++)s[g]+=(l[g]+l[4+g]+l[8+g]+l[12+g])*f}for(let _=0;_<4;_++)e[_]=Math.exp(-s[_])}precompute(){const t=new Float64Array(4);for(let n=0;n<Nt;n++)for(let e=0;e<et;e++){const r=e/(et-1),a=n/(Nt-1);this.transmittance(r*2-1,a,t);const i=(n*et+e)*4;for(let c=0;c<4;c++)this.lut[i+c]=t[c]}}lookup(t,n,e){const r=(et-1)*on(t*.5+.5),a=(Nt-1)*on(n),i=Math.trunc(r),c=Math.trunc(a),u=Math.min(i+1,et-1),f=Math.min(c+1,Nt-1),s=r-i,l=a-c,_=(c*et+i)*4,h=(c*et+u)*4,d=(f*et+i)*4,m=(f*et+u)*4;for(let p=0;p<4;p++)e[p]=Ot(Ot(this.lut[_+p],this.lut[h+p],s),Ot(this.lut[d+p],this.lut[m+p],s),l)}lookupAtGround(t,n){const e=(et-1)*on(t*.5+.5),r=Math.trunc(e),a=Math.min(r+1,et-1),i=e-r;for(let c=0;c<4;c++)n[c]=Ot(this.lut[r*4+c],this.lut[a*4+c],i)}lookupToSun(t,n){const e=(Nt-1)*on(t),r=Math.trunc(e),a=Math.min(r+1,Nt-1),i=e-r,c=et-1;for(let u=0;u<4;u++)n[u]=Ot(this.lut[(r*et+c)*4+u],this.lut[(a*et+c)*4+u],i)}inscattering(t,n,e,r,a,i,c,u,f){const s=-(a*t[0]+i*t[1]+c*t[2]),l=Ja(s),_=tr(s),h=u/Oo,d=new Float64Array(16),m=new Float64Array(4),p=new Float64Array(4),v=new Float64Array(4),g=new Float64Array(4),b=new Float64Array(4),w=[0,0,0,0],R=[1,1,1,1];for(let T=0;T<Oo;T++){const A=(T+.5)*h,O=n+a*A,M=e+i*A,C=r+c*A,V=Math.hypot(O,M,C),H=Math.max(V-Ct,0),Q=H/ie,tt=(O*t[0]+M*t[1]+C*t[2])/V;this.coefficients(H,d),this.lookup(tt,Q,m);const pt=Dt*(1-Ka(1-On(Ct/V)));this.lookupAtGround(tt,v),this.lookupToSun(0,g),this.lookupToSun(Q,b);const y=1/(1+5*Math.exp(-17.92*tt)),L=[.217,.347,.594,1];for(let D=0;D<4;D++){const Y=g[D]/b[D],Z=Ba*pt*(ja*re)*v[D]*Y*tt;p[D]=.02*L[D]*y+Z}for(let D=0;D<4;D++){const Y=d[D]+d[4+D]+d[8+D]+d[12+D],Z=Wa[D]*(d[12+D]*(l*m[D]+p[D])+d[4+D]*(_*m[D]+p[D])),k=Math.exp(-h*Y),G=Math.max(Y,1e-7);w[D]+=R[D]*((Z-Z*k)/G),R[D]*=k}}for(let T=0;T<4;T++)f[T]=w[T]}}const st=512,qt=256;function fe(o,t){const n=new or(o.airDensity,o.aerosolDensity,o.ozoneDensity);n.precompute();const e=Math.min(Math.max(o.altitude,1),99999)/1e3,r=se(Math.cos(sn-t)),a=new Float32Array(st*qt*3),i=st/2,c=new Float64Array(4);for(let u=0;u<qt;u++)for(let f=0;f<i;f++){const s=(f+.5)/st,l=(u+.5)/qt,_=Dt*s,h=l*2-1,d=Math.sign(h)*On(h)*sn,m=Math.cos(d)*Math.cos(_),p=Math.cos(d)*Math.sin(_),v=Math.sin(d),g=Ct+e,b=Gn(0,0,g,m,p,v,qn),w=Gn(0,0,g,m,p,v,Ct),R=w<0?b:w;n.inscattering(r,0,0,g,m,p,v,R,c);let T=0,A=0,O=0;for(let V=0;V<4;V++)T+=Rn[V][0]*c[V],A+=Rn[V][1]*c[V],O+=Rn[V][2]*c[V];const M=(u*st+f)*3;a[M]=T,a[M+1]=A,a[M+2]=O;const C=(u*st+(st-f-1))*3;a[C]=T,a[C+1]=A,a[C+2]=O}return a}function er(o){const[t]=oo(o.sunElevation,o.sunRotation);return fe(o,t)}function eo(o){const[t]=oo(o.sunElevation,o.sunRotation);return JSON.stringify([t,o.altitude,o.airDensity,o.aerosolDensity,o.ozoneDensity])}const ar=6,Wt=new Map;function rr(o){return Wt.has(eo(o))}function ce(o,t){Wt.set(eo(o),t),Wt.size>ar&&Wt.delete(Wt.keys().next().value)}function lr(o){const[t,n]=oo(o.sunElevation,o.sunRotation),e=eo(o);let r=Wt.get(e);r===void 0&&(r=fe(o,t),ce(o,r));const a=new x;return i=>{const c=Math.hypot(i.x,i.y),u=Math.atan2(i.z,c);let s=(Math.atan2(i.x,i.y)+Math.PI+n)/Dt;s-=Math.floor(s);const l=Math.abs(u),_=on(Math.sqrt(l/sn)*Math.sign(u)*.5+.5),h=s*st-.5,d=_*qt-.5,m=Math.floor(h),p=Math.floor(d),v=h-m,g=d-p,b=C=>(C%st+st)%st,w=C=>C<0?0:C>qt-1?qt-1:C,R=b(m),T=b(m+1),A=w(p),O=w(p+1),M=[0,0,0];for(let C=0;C<3;C++){const V=Ot(r[(A*st+R)*3+C],r[(A*st+T)*3+C],v),H=Ot(r[(O*st+R)*3+C],r[(O*st+T)*3+C],v);M[C]=Ot(V,H,g)}return a.set(yt[0][0]*M[0]+yt[0][1]*M[1]+yt[0][2]*M[2],yt[1][0]*M[0]+yt[1][1]*M[1]+yt[1][2]*M[2],yt[2][0]*M[0]+yt[2][1]*M[1]+yt[2][2]*M[2])}}let At=null,cn=!1,ir=0;const en=new Map;function sr(){if(At||cn)return At;if(typeof Worker>"u")return cn=!0,null;try{At=new Worker(new URL("/assets/sky-precompute-worker-ChN7J87v.js",import.meta.url),{type:"module"})}catch{return cn=!0,null}return At.onmessage=o=>{const{id:t,pixels:n,error:e}=o.data,r=en.get(t);r&&(en.delete(t),n?r.resolve(n):r.reject(new Error(e??"sky worker returned nothing")))},At.onerror=o=>{const t=new Error(`sky worker failed: ${o.message||"unknown error"}`);for(const n of en.values())n.reject(t);en.clear(),At?.terminate(),At=null,cn=!0},At}function fr(o){const t=sr();if(!t)return Promise.resolve(er(o));const n=ir++,e={id:n,parameters:o};return new Promise((r,a)=>{en.set(n,{resolve:r,reject:a}),t.postMessage(e)})}function cr(o,t,n,e={}){switch(e.type??"LINEAR"){case"QUADRATIC":{const r=Math.max(o,0);return r*r}case"EASING":{const r=Math.min(1,Math.max(0,o));return r*r*(3-2*r)}case"DIAGONAL":return(o+t)/2;case"SPHERICAL":return Math.max(.999999-Math.hypot(o,t,n),0);case"QUADRATIC_SPHERE":{const r=Math.max(.999999-Math.hypot(o,t,n),0);return r*r}case"RADIAL":return Math.atan2(t,o)/(2*Math.PI)+.5;default:return o}}const In=(o,t)=>t!==0?o/t:0,Po=o=>Math.min(1,Math.max(-1,o)),Ao=(o,t,n)=>{const e=n!==0?Math.max(n-Math.abs(o-t),0)/n:0;return Math.min(o,t)-e*e*e*n/6},ue={ADD:(o,t)=>o+t,SUBTRACT:(o,t)=>o-t,MULTIPLY:(o,t)=>o*t,DIVIDE:In,POWER:(o,t)=>t===0?1:o===0||o<0&&!Number.isInteger(t)?0:o**t,LOGARITHM:(o,t)=>o<=0||t<=0?0:In(Math.log(o),Math.log(t)),SQRT:o=>Math.sqrt(Math.max(o,0)),INVERSE_SQRT:o=>o>0?1/Math.sqrt(o):0,ABSOLUTE:Math.abs,RADIANS:o=>o*Math.PI/180,DEGREES:o=>o*180/Math.PI,MINIMUM:(o,t)=>Math.min(o,t),MAXIMUM:(o,t)=>Math.max(o,t),LESS_THAN:(o,t)=>+(o<t),GREATER_THAN:(o,t)=>+(o>t),ROUND:o=>Math.floor(o+.5),FLOOR:Math.floor,CEIL:Math.ceil,FRACT:o=>o-Math.floor(o),MODULO:(o,t)=>t!==0?o%t:0,FLOORED_MODULO:(o,t)=>t!==0?o-Math.floor(o/t)*t:0,TRUNC:Math.trunc,SNAP:(o,t)=>Math.floor(In(o,t))*t,WRAP:(o,t,n)=>t!==n?o-(t-n)*Math.floor((o-n)/(t-n)):n,PINGPONG:(o,t)=>{if(t===0)return 0;const n=(o-t)/(t*2);return Math.abs((n-Math.floor(n))*t*2-t)},SINE:Math.sin,COSINE:Math.cos,TANGENT:Math.tan,SINH:Math.sinh,COSH:Math.cosh,TANH:Math.tanh,ARCSINE:o=>Math.asin(Po(o)),ARCCOSINE:o=>Math.acos(Po(o)),ARCTANGENT:Math.atan,ARCTAN2:(o,t)=>o===0&&t===0?0:Math.atan2(o,t),SIGN:Math.sign,EXPONENT:Math.exp,COMPARE:(o,t,n)=>+(o===t||Math.abs(o-t)<=Math.max(n,2**-23)),MULTIPLY_ADD:(o,t,n)=>o*t+n,SMOOTH_MIN:Ao,SMOOTH_MAX:(o,t,n)=>-Ao(-o,-t,n)};function nt(o,t){if(typeof o=="number")return()=>o;if(Array.isArray(o)){const r=new x(...o);return()=>r}if(o.kind==="direction")return r=>r;if(o.kind==="window"){if(!t)throw new Error("World Window coordinates need a render camera");return t}if(o.kind==="gradient"){const r=nt(o.vector,t),a={type:o.gradient_type},i=new x;return c=>{const u=r(c),f=typeof u=="number"?u:u.x,s=typeof u=="number"?u:u.y,l=typeof u=="number"?u:u.z,_=ut.clamp(cr(f,s,l,a),0,1);return o.output==="Fac"?_:i.setScalar(_)}}if(o.kind==="to_float"){const r=nt(o.value,t);return a=>{const i=r(a);return typeof i=="number"?i:Math.fround(o.source_type==="RGBA"?i.x*.212639+i.y*.7151687+i.z*.0721923:(i.x+i.y+i.z)/3)}}if(o.kind==="math"){const r=o.inputs.map(c=>nt(c,t)),a=ue[o.operation],i=(c,u)=>{const f=r[c]?.(u)??0;if(typeof f!="number")throw new Error("World Math needs scalar inputs");return Math.fround(f)};return c=>{const u=Math.fround(a(i(0,c),i(1,c),i(2,c)));return o.clamp?ut.clamp(u,0,1):u}}if(o.kind==="mix_color"){const r=nt(o.factor,t),a=nt(o.a,t),i=nt(o.b,t),c=new x,u=new x;return f=>{const s=r(f);if(typeof s!="number")throw new Error("World color Mix needs a scalar factor");const l=a(f);typeof l=="number"?c.setScalar(l):c.copy(l);const _=i(f);return typeof _=="number"?u.setScalar(_):u.copy(_),c.lerp(u,o.clamp_factor?ut.clamp(s,0,1):s),o.clamp_result&&c.clampScalar(0,1),c}}if(o.kind==="sky"){const r=lr({sunElevation:o.sun_elevation,sunRotation:o.sun_rotation,altitude:o.altitude,airDensity:o.air_density,aerosolDensity:o.aerosol_density,ozoneDensity:o.ozone_density});return a=>r(a)}if(o.kind==="mapping"){const r=nt(o.vector,t),a=new x(...o.location),i=new x(...o.scale),c=new gt().setFromEuler(new Se(o.rotation[0],o.rotation[1],o.rotation[2],"ZYX")),u=c.clone().invert(),f=new x(...o.scale.map(l=>l===0?0:1/l)),s=new x;return l=>{const _=r(l);switch(typeof _=="number"?s.setScalar(_):s.copy(_),o.vector_type??"POINT"){case"TEXTURE":return s.sub(a).applyQuaternion(u).multiply(f);case"VECTOR":return s.multiply(i).applyQuaternion(c);case"NORMAL":return s.multiply(f).applyQuaternion(c).normalize();case"POINT":return s.multiply(i).applyQuaternion(c).add(a)}}}if(o.kind==="map_range"){const r=nt(o.value,t),a=nt(o.from_min,t),i=nt(o.from_max,t),c=nt(o.to_min,t),u=nt(o.to_max,t),f=nt(o.steps,t),s=(h,d)=>{const m=h(d);if(typeof m!="number")throw new Error("World Map Range needs scalar inputs");return m},l=o.interpolation,_=o.clamp;return h=>{const d=s(r,h),m=s(a,h),p=s(i,h),v=s(c,h),g=s(u,h);if(m===p)return 0;let b;if(l==="STEPPED"){const R=s(f,h),T=(d-m)/(p-m);b=R>0?Math.floor(T*(R+1))/R:0}else if(l==="SMOOTHSTEP"||l==="SMOOTHERSTEP"){const R=ut.clamp((d-Math.min(m,p))/(Math.max(m,p)-Math.min(m,p)),0,1),T=l==="SMOOTHSTEP"?R*R*(3-2*R):R*R*R*(R*(R*6-15)+10);b=m>p?1-T:T}else b=(d-m)/(p-m);const w=v+b*(g-v);return _?v>g?ut.clamp(w,g,v):ut.clamp(w,v,g):w}}if(o.kind==="separate"){const r=nt(o.vector,t);return a=>{const i=r(a);return typeof i=="number"?i:i.getComponent(o.axis)}}const n=nt(o.factor,t),e=new x;return r=>{const a=n(r);if(typeof a!="number")throw new Error("World ColorRamp needs a scalar factor");const i=ut.clamp(a,0,1)*256,c=Math.floor(i),u=o.colors[c],f=o.colors[Math.min(c+1,256)],s=o.interpolate?i-c:0;return e.set(ut.lerp(u[0],f[0],s),ut.lerp(u[1],f[1],s),ut.lerp(u[2],f[2],s))}}function ur(o,t,n,e){const r=new Float32Array(t*n*3),a=nt(o,e),i=new x;for(let c=0;c<n;c++){const u=((c+.5)/n-.5)*Math.PI;for(let f=0;f<t;f++){const s=((f+.5)/t-.5)*2*Math.PI;i.set(Math.cos(u)*Math.cos(s),-Math.cos(u)*Math.sin(s),Math.sin(u));const l=a(i),_=(c*t+f)*3;r[_]=typeof l=="number"?l:l.x,r[_+1]=typeof l=="number"?l:l.y,r[_+2]=typeof l=="number"?l:l.z}}return r}function So(o){const t=[],n=e=>{if(!(typeof e=="number"||Array.isArray(e)))switch(e.kind){case"sky":t.push({sunElevation:e.sun_elevation,sunRotation:e.sun_rotation,altitude:e.altitude,airDensity:e.air_density,aerosolDensity:e.aerosol_density,ozoneDensity:e.ozone_density});return;case"mapping":case"gradient":case"separate":n(e.vector);return;case"ramp":n(e.factor);return;case"mix_color":n(e.factor),n(e.a),n(e.b);return;case"math":e.inputs.forEach(n);return;case"to_float":n(e.value);return;case"map_range":n(e.value),n(e.from_min),n(e.from_max),n(e.to_min),n(e.to_max),n(e.steps);return;default:return}};return n(o),t}function Et(o){if(typeof o=="number"||Array.isArray(o))return!1;switch(o.kind){case"window":return!0;case"mapping":case"gradient":case"separate":return Et(o.vector);case"ramp":return Et(o.factor);case"mix_color":return[o.factor,o.a,o.b].some(Et);case"math":return o.inputs.some(Et);case"to_float":return Et(o.value);case"map_range":return[o.value,o.from_min,o.from_max,o.to_min,o.to_max,o.steps].some(Et);default:return!1}}function _r(o,t,n,e){e.updateMatrixWorld();const r=new Float32Array(t*n*3),a=new x,i=nt(o,()=>a),c=new x,u=e.getWorldPosition(new x),f=e.getWorldDirection(new x);for(let s=0;s<n;s++)for(let l=0;l<t;l++){const _=(l+.5)/t,h=(s+.5)/n;a.set(_,h,0),e.isOrthographicCamera?c.copy(f):c.set(_*2-1,h*2-1,.5).unproject(e).sub(u).normalize(),c.set(c.x,-c.z,c.y);const d=i(c),m=(s*t+l)*3;r[m]=typeof d=="number"?d:d.x,r[m+1]=typeof d=="number"?d:d.y,r[m+2]=typeof d=="number"?d:d.z}return r}const J=S().finite(),mr=P({type:W(["POINT","SUN","SPOT","AREA"]),color:$([J,J,J]),energy:J,use_shadow:q().default(!0),radius:J.optional(),spot_size:J.optional(),spot_blend:J.optional(),shape:W(["SQUARE","RECTANGLE","DISK","ELLIPSE"]).optional(),size:J.optional(),size_y:J.optional()}).strict();let Xn;function dr(){return Xn??=fa(async()=>{const{RectAreaLightUniformsLib:o}=await import("./RectAreaLightUniformsLib-Iam8rS8R.js");return{RectAreaLightUniformsLib:o}},__vite__mapDeps([0,1])).then(({RectAreaLightUniformsLib:o})=>{o.init(),vt()}),Xn}function hr(){return Xn??Promise.resolve()}const pr=o=>{const t=o.size??0,n=o.size_y??t;if(o.shape==="RECTANGLE")return[t,n];if(o.shape==="DISK"){const e=Math.sqrt(Math.PI*t*t/4);return[e,e]}if(o.shape==="ELLIPSE"){const e=Math.sqrt(Math.PI/4);return[t*e,n*e]}return[t,t]};function vr(o,t){const n=(i,c)=>t&&c(t)?t:new i;if(o.type==="SUN"){const i=n(Xo,c=>c.isDirectionalLight);return i.intensity=o.energy,i.color.setRGB(o.color[0],o.color[1],o.color[2],ft),i.castShadow=o.use_shadow,i}if(o.type==="POINT"){const i=n(Ln,c=>c.isPointLight);return i.intensity=o.energy/(4*Math.PI),i.distance=0,i.decay=2,i.color.setRGB(o.color[0],o.color[1],o.color[2],ft),i.castShadow=o.use_shadow,i}if(o.type==="SPOT"){const i=n(Vn,c=>c.isSpotLight);return i.intensity=o.energy/(4*Math.PI),i.distance=0,i.decay=2,i.angle=(o.spot_size??0)/2,i.penumbra=o.spot_blend??0,i.color.setRGB(o.color[0],o.color[1],o.color[2],ft),i.castShadow=o.use_shadow,i}dr();const e=n(gn,i=>i.isRectAreaLight),[r,a]=pr(o);return e.width=r,e.height=a,e.intensity=o.energy/(Math.max(r*a,Number.MIN_VALUE)*Math.PI),e.color.setRGB(o.color[0],o.color[1],o.color[2],ft),e}function gr(o,t,n){if(!o.castShadow||n<=0)return;const r=o.getWorldPosition(new x).distanceTo(t),a=o.shadow;if(!a)return;const i=a.camera;i.near=Math.max(n*.001,r-n),i.far=r+n,o.isDirectionalLight&&(i.left=-n,i.right=n,i.top=n,i.bottom=-n),i.updateProjectionMatrix()}function xr(o,t){o.position.set(0,0,0);const n=o;o.isRectAreaLight||n.target&&n.target.parent!==t&&(n.target.position.set(0,0,-1),t.add(n.target))}const ao=[{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}],Eo=.69;class br{constructor(){this.group=new ot,this.lights=[],this.group.name="BlenderSolidStudio";const t=new Go;t.name="BlenderSolidStudioTarget",this.group.add(t);const n=new ht(0,0,0);for(const[r,a]of ao.entries()){const i=(1+a.smooth)**2,c=new Xo(16777215,Math.PI*Eo/i);c.name=`BlenderSolidLight${r}`,c.color.setRGB(a.diffuse[0],a.diffuse[1],a.diffuse[2],ft),c.position.set(a.direction[0],a.direction[1],a.direction[2]),c.target=t,this.group.add(c),this.lights.push(c),n.r+=a.diffuse[0]*a.smooth/i,n.g+=a.diffuse[1]*a.smooth/i,n.b+=a.diffuse[2]*a.smooth/i}const e=new Ee(16777215,Math.PI*Eo);e.name="BlenderSolidWrapFill",e.color.copy(n),this.group.add(e),this.lights.push(e)}setRendered(t){this.group.visible=!t}dispose(){for(const t of this.lights)t.dispose();this.group.clear()}}const Ut=$([J,J,J]),U=te(()=>jt([J,Ut,P({kind:j("direction")}).strict(),P({kind:j("window")}).strict(),P({kind:j("gradient"),gradient_type:W(["LINEAR","QUADRATIC","EASING","DIAGONAL","SPHERICAL","QUADRATIC_SPHERE","RADIAL"]),output:W(["Fac","Color"]),vector:U}).strict(),P({kind:j("to_float"),source_type:W(["RGBA","VECTOR"]),value:U}).strict(),P({kind:j("math"),operation:W(Object.keys(ue)),clamp:q(),inputs:z(U).min(1).max(3)}).strict(),P({kind:j("mix_color"),factor:U,a:U,b:U,clamp_factor:q(),clamp_result:q()}).strict(),P({kind:j("mapping"),vector_type:W(["POINT","TEXTURE","VECTOR","NORMAL"]).optional(),vector:U,location:Ut,rotation:Ut,scale:Ut}).strict(),P({kind:j("separate"),vector:U,axis:S().int().min(0).max(2)}).strict(),P({kind:j("ramp"),factor:U,colors:z(Ut).length(257),interpolate:q()}).strict(),P({kind:j("map_range"),interpolation:W(["LINEAR","STEPPED","SMOOTHSTEP","SMOOTHERSTEP"]),clamp:q(),value:U,from_min:U,from_max:U,to_min:U,to_max:U,steps:U}).strict(),P({kind:j("sky"),sun_elevation:J,sun_rotation:J,altitude:J,air_density:J,aerosol_density:J,ozone_density:J}).strict()])),Mo=P({color:Ut,strength:J,shader:U.optional()}),yr=Mo.extend({volume:z(P({kind:W(["absorption","scatter","principled","emission"]),phase:E(),alpha:U,weight:U,color:U,density:U,anisotropy:U,absorption_color:U,emission_color:U,emission_strength:U,blackbody_intensity:U,temperature:U,blackbody_tint:U}).strict()).optional(),lighting:Mo.strict().optional()}).strict(),wr=4,tn=new Map,zn=new Set;function No(o,t,n){const a=Et(o);if(a&&!n)throw new Error("World Window coordinates need a render camera");n?.updateMatrixWorld();const i=JSON.stringify([o,a?[n.matrixWorld.elements,n.projectionMatrix.elements]:null]),c=tn.get(i);if(c!==void 0)return Yn(c,t,256,128);const u=new x,f=new Jn,s=n?new X().multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse):null,l=n?.getWorldPosition(new x),h=ur(o,256,128,a?d=>(u.set(d.x,d.z,-d.y),n.isPerspectiveCamera&&u.add(l),f.set(u.x,u.y,u.z,1).applyMatrix4(s),f.w===0?u.set(0,0,0):u.set(f.x/f.w*.5+.5,f.y/f.w*.5+.5,0)):void 0);return tn.set(i,h),tn.size>wr&&tn.delete(tn.keys().next().value),Yn(h,t,256,128)}function Or(o,t,n,e){const r=nn.toHalfFloat(1);for(let a=0;a<e;a++)o[a*4]=nn.toHalfFloat(t[a*3]*n),o[a*4+1]=nn.toHalfFloat(t[a*3+1]*n),o[a*4+2]=nn.toHalfFloat(t[a*3+2]*n),o[a*4+3]=r}function Yn(o,t,n,e){const r=new Uint16Array(n*e*4);Or(r,o,t,n*e);const a=new Tn(r,n,e,Pn,to);return a.mapping=Ne,a.colorSpace=ft,a.minFilter=Lt,a.magFilter=Lt,a.needsUpdate=!0,a}class ro{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 n=t;for(;n;){if(n.isScene)return n;n=n.parent}return null}apply(t,n,e){if(this.clear(),this.pending=null,!n)return;const r=ro.sceneOf(t);if(!r)return;this.applied={scene:r,background:r.background,environment:r.environment};const a=n.shader??n.color,i=this.generation,u=[...So(a),...n.lighting?So(n.lighting.shader??n.lighting.color):[]].filter(s=>!rr(s));if(u.length===0){this.compose(r,n,a,e);return}const f=(async()=>{const s=await Promise.all(u.map(fr));u.forEach((l,_)=>{ce(l,s[_])}),!(this.generation!==i||this.applied?.scene!==r)&&(this.compose(r,n,a,e),vt())})();this.pending=f,zn.add(f),f.then(()=>zn.delete(f),()=>zn.delete(f))}compose(t,n,e,r){if(this.texture=No(e,n.strength,r),Et(e)){if(!r)throw new Error("World Window coordinates need a render camera");this.screenTexture=Yn(_r(e,512,512,r),n.strength,512,512),this.screenTexture.mapping=Me,t.background=this.screenTexture}else if(r&&r.isOrthographicCamera){const i=r.getWorldDirection(new x);i.set(i.x,-i.z,i.y);const c=nt(n.shader??n.color)(i);t.background=typeof c=="number"?new ht().setRGB(c,c,c).multiplyScalar(n.strength):new ht().setRGB(c.x,c.y,c.z).multiplyScalar(n.strength)}else t.background=this.texture;const{lighting:a}=n;this.environmentTexture=a?No(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 _e(o){return[o.min.x,o.max.x].flatMap(t=>[o.min.y,o.max.y].flatMap(n=>[o.min.z,o.max.z].map(e=>new x(t,n,e))))}function Tr(o,t){if(o.isEmpty()||!t.intersectsBox(o))return[];const n=_e(o);if(n.every(s=>t.containsPoint(s)))return n;const e=[...t.planes,new It(new x(1,0,0),-o.min.x),new It(new x(-1,0,0),o.max.x),new It(new x(0,1,0),-o.min.y),new It(new x(0,-1,0),o.max.y),new It(new x(0,0,1),-o.min.z),new It(new x(0,0,-1),o.max.z)],r=[],a=new x,i=new x,c=new x,u=new x,f=Math.max(1,o.min.length(),o.max.length())*1e-8;for(let s=0;s<e.length;s++)for(let l=s+1;l<e.length;l++)for(let _=l+1;_<e.length;_++){const h=e[s],d=e[l],m=e[_];a.crossVectors(d.normal,m.normal);const p=h.normal.dot(a);Math.abs(p)<1e-12||(i.crossVectors(m.normal,h.normal),c.crossVectors(h.normal,d.normal),u.copy(a).multiplyScalar(-h.constant).addScaledVector(i,-d.constant).addScaledVector(c,-m.constant).divideScalar(p),e.every(v=>v.distanceToPoint(u)>=-f)&&r.push(u.clone()))}return r}function Pr(o,t,n){if(!o.castShadow||!t.length)return;o.shadow.updateMatrices(o);const e=o.shadow.camera,r=e.matrixWorldInverse,a=new yn().setFromPoints(t.map(_=>_.clone().applyMatrix4(r))),i=a.getSize(new x),c=Math.max(i.length()*1e-6,Number.EPSILON),u=2+2*Math.SQRT2,f=Math.max(i.x,i.y,c)/Math.max(1,Math.min(o.shadow.mapSize.x,o.shadow.mapSize.y)-2*u),s=2*Math.SQRT2*f,l=u*f;a.min.x-=l,a.min.y-=l,a.max.x+=l,a.max.y+=l;for(const _ of n){if(_.isEmpty())continue;const h=new yn().setFromPoints(_e(_).map(d=>d.applyMatrix4(r)));h.max.x<a.min.x||h.min.x>a.max.x||h.max.y<a.min.y||h.min.y>a.max.y||(a.min.z=Math.min(a.min.z,h.min.z),a.max.z=Math.max(a.max.z,h.max.z))}e.left=a.min.x,e.right=a.max.x,e.bottom=a.min.y,e.top=a.max.y,e.near=-a.max.z-s-c,e.far=-a.min.z+s+c,e.updateProjectionMatrix(),o.shadow.normalBias=s}const Gt=S().finite(),Ro=$([Gt,Gt,Gt]),me=P({min:$([S().int(),S().int(),S().int()]),max:$([S().int(),S().int(),S().int()]),density:z(Gt),voxelSize:Gt.positive(),color:Ro,emission:Ro,densityScale:Gt.nonnegative()}).strict();function Ar(o){const t=o.max.map((s,l)=>s-o.min[l]+1);if(t.some(s=>s<=0)||t.reduce((s,l)=>s*l,1)!==o.density.length)throw new Error("Volume density dimensions do not match the evaluated grid");const n=new Re(new Float32Array(o.density),t[0],t[1],t[2]);n.format=Ie,n.type=Yo,n.minFilter=n.magFilter=Lt,n.unpackAlignment=1,n.needsUpdate=!0;const e=new x(...o.min).addScalar(-.5).multiplyScalar(o.voxelSize),r=new x(t[0],t[1],t[2]).multiplyScalar(o.voxelSize),a=new ze(r.x,r.y,r.z),i=a.getAttribute("position");for(let s=0;s<i.count;s++)i.setXYZ(s,e.x+(i.getX(s)>0?r.x:0),e.y+(i.getY(s)>0?r.y:0),e.z+(i.getZ(s)>0?r.z:0));i.needsUpdate=!0,a.computeBoundingBox(),a.computeBoundingSphere();const c=new Kn({glslVersion:De,side:Fe,transparent:!0,depthWrite:!1,premultipliedAlpha:!0,uniforms:{densityGrid:{value:n},minimum:{value:e},extent:{value:r},voxelSize:{value:o.voxelSize},densityScale:{value:o.densityScale},volumeColor:{value:new x(...o.color)},emission:{value:new x(...o.emission)},cameraLocal:{value:new x},rayLocal:{value:new x},orthographic:{value:!1},worldScale:{value:new qo}},vertexShader:`
20
20
  out vec3 localPosition;
21
21
  void main() {
22
22
  localPosition = position;
@@ -58,7 +58,7 @@ import{L as ne,a as oe,b as ee}from"./LineSegments2-C8H20K8w.js";import{aJ as _t
58
58
  outputColor = vec4(radiance, 1.0 - transmission);
59
59
  #include <tonemapping_fragment>
60
60
  #include <colorspace_fragment>
61
- }`}),c=new At(i,u),f=new mt;return c.onBeforeRender=(r,l,m)=>{f.copy(c.matrixWorld).invert(),u.uniforms.cameraLocal.value.setFromMatrixPosition(m.matrixWorld).applyMatrix4(f),m.getWorldDirection(u.uniforms.rayLocal.value).transformDirection(f),u.uniforms.orthographic.value=!!m.isOrthographicCamera,u.uniforms.worldScale.value.setFromMatrix4(c.matrixWorld)},u.addEventListener("dispose",()=>o.dispose()),c}const al=`#define constexpr const
61
+ }`}),u=new Tt(a,c),f=new X;return u.onBeforeRender=(s,l,_)=>{f.copy(u.matrixWorld).invert(),c.uniforms.cameraLocal.value.setFromMatrixPosition(_.matrixWorld).applyMatrix4(f),_.getWorldDirection(c.uniforms.rayLocal.value).transformDirection(f),c.uniforms.orthographic.value=!!_.isOrthographicCamera,c.uniforms.worldScale.value.setFromMatrix4(u.matrixWorld)},c.addEventListener("dispose",()=>n.dispose()),u}const Sr=`#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)`,$n={"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)`,Zn={"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
- }`}},po=R().finite(),On=X(["float","vec2","vec3","vec4"]),Wo=Nt([po,z(po)]),Go=j([A(),R().int().nonnegative()]),sn=Nt([O({value:Wo}).strict(),O({link:Go}).strict()]),ll=["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"],rl=O({type:X(ll),props:st(A(),Fo()),inputs:z(Nt([O({value:Wo,id:A(),gpu:On,enabled:Y()}).strict(),O({link:Go,id:A(),gpu:On,enabled:Y()}).strict()])),outputs:z(O({id:A(),gpu:On.or(L("closure")).nullable()}).strict())}).strict(),Yt=Io(()=>Nt([O({principled:L(!0)}).strict(),O({emission:j([sn,sn])}).strict(),O({transparent:R()}).strict(),O({none:L(!0)}).strict(),O({mix:j([sn,Yt,Yt])}).strict(),O({add:j([Yt,Yt])}).strict()])),il=O({surface:X(["ShaderNodeBsdfPrincipled","ShaderNodeEmission","closure"]),inputs:st(A(),sn),closure:Yt.optional(),nodes:st(A(),rl)}).strict();function sl(n){const t=n.inputs.Alpha,o=e=>"transparent"in e||"mix"in e&&(o(e.mix[1])||o(e.mix[2]))||"add"in e&&(o(e.add[0])||o(e.add[1]));return t!==void 0&&"link"in t||n.closure!==void 0&&o(n.closure)}const Xo="vec3(0.2126729, 0.7151522, 0.0721750)",fl=n=>n==="float"?1:Number(n[3]);function cl(n,t){const o=typeof t=="number"?[t]:t,e=fl(n);return Array.from({length:e},(a,i)=>o[i]??(i===3?1:0))}function ul(n,t,o){if(t===o)return n;const e=i=>i==="float"?"float":`float${i[3]}`,a=t==="vec4"&&o==="float"?`, ${Xo}`:"";return`${e(o)}_from_${e(t)}(${n}${a})`}const _l={INVERSE_SQRT:"math_inversesqrt",FRACT:"math_fraction",SMOOTH_MIN:"math_smoothmin",SMOOTH_MAX:"math_smoothmax"},ml={CROSS_PRODUCT:"vector_math_cross",DOT_PRODUCT:"vector_math_dot"},vo={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"},dl={MULTIFRACTAL:"multi_fractal",FBM:"fbm",HYBRID_MULTIFRACTAL:"hybrid_multi_fractal",RIDGED_MULTIFRACTAL:"ridged_multi_fractal",HETERO_TERRAIN:"hetero_terrain"},hl={F1:"f1",F2:"f2",SMOOTH_F1:"smooth_f1",DISTANCE_TO_EDGE:"distance_to_edge",N_SPHERE_RADIUS:"n_sphere_radius"},pl={EUCLIDEAN:0,MANHATTAN:1,CHEBYCHEV:2,MINKOWSKI:3},vl=(()=>{const n=new Map;for(const[t,o]of Object.entries($n))for(const e of o.code.matchAll(/^(?:void|float\d?)\s+([A-Za-z_]\w*)\s*\(/gm))n.has(e[1])||n.set(e[1],t);return n})();function N(n,t){if(!(t in n.props))throw new Error(`${n.type} arrived without its '${t}' property`);return n.props[t]}const gl=`
6882
+ }`}},Io=S().finite(),Fn=W(["float","vec2","vec3","vec4"]),de=jt([Io,z(Io)]),he=$([E(),S().int().nonnegative()]),xn=jt([P({value:de}).strict(),P({link:he}).strict()]),Er=["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"],Mr=P({type:W(Er),props:_t(E(),ne()),inputs:z(jt([P({value:de,id:E(),gpu:Fn,enabled:q()}).strict(),P({link:he,id:E(),gpu:Fn,enabled:q()}).strict()])),outputs:z(P({id:E(),gpu:Fn.or(j("closure")).nullable()}).strict())}).strict(),an=te(()=>jt([P({principled:j(!0)}).strict(),P({emission:$([xn,xn])}).strict(),P({transparent:S()}).strict(),P({none:j(!0)}).strict(),P({mix:$([xn,an,an])}).strict(),P({add:$([an,an])}).strict()])),Nr=P({surface:W(["ShaderNodeBsdfPrincipled","ShaderNodeEmission","closure"]),inputs:_t(E(),xn),closure:an.optional(),nodes:_t(E(),Mr)}).strict();function Rr(o){const t=o.inputs.Alpha,n=e=>"transparent"in e||"mix"in e&&(n(e.mix[1])||n(e.mix[2]))||"add"in e&&(n(e.add[0])||n(e.add[1]));return t!==void 0&&"link"in t||o.closure!==void 0&&n(o.closure)}const pe="vec3(0.2126729, 0.7151522, 0.0721750)",Ir=o=>o==="float"?1:Number(o[3]);function zr(o,t){const n=typeof t=="number"?[t]:t,e=Ir(o);return Array.from({length:e},(r,a)=>n[a]??(a===3?1:0))}function Fr(o,t,n){if(t===n)return o;const e=a=>a==="float"?"float":`float${a[3]}`,r=t==="vec4"&&n==="float"?`, ${pe}`:"";return`${e(n)}_from_${e(t)}(${o}${r})`}const Dr={INVERSE_SQRT:"math_inversesqrt",FRACT:"math_fraction",SMOOTH_MIN:"math_smoothmin",SMOOTH_MAX:"math_smoothmax"},Cr={CROSS_PRODUCT:"vector_math_cross",DOT_PRODUCT:"vector_math_dot"},zo={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"},kr={MULTIFRACTAL:"multi_fractal",FBM:"fbm",HYBRID_MULTIFRACTAL:"hybrid_multi_fractal",RIDGED_MULTIFRACTAL:"ridged_multi_fractal",HETERO_TERRAIN:"hetero_terrain"},$r={F1:"f1",F2:"f2",SMOOTH_F1:"smooth_f1",DISTANCE_TO_EDGE:"distance_to_edge",N_SPHERE_RADIUS:"n_sphere_radius"},Lr={EUCLIDEAN:0,MANHATTAN:1,CHEBYCHEV:2,MINKOWSKI:3},Vr=(()=>{const o=new Map;for(const[t,n]of Object.entries(Zn))for(const e of n.code.matchAll(/^(?:void|float\d?)\s+([A-Za-z_]\w*)\s*\(/gm))o.has(e[1])||o.set(e[1],t);return o})();function F(o,t){if(!(t in o.props))throw new Error(`${o.type} arrived without its '${t}' property`);return o.props[t]}const jr=`
6883
6883
  #define GPU_FRAGMENT_SHADER
6884
6884
  #define FrontFacing gl_FrontFacing
6885
6885
  uniform mat4 modelMatrix;
@@ -6934,7 +6934,7 @@ void blender_init_globals() {
6934
6934
  g_data.curve_T = vec3(0.0);
6935
6935
  g_data.barycentric_coords = vec2(0.0);
6936
6936
  }
6937
- `,xl=`
6937
+ `,Br=`
6938
6938
  uniform vec2 blenderViewport;
6939
6939
  vec3 blender_orco() {
6940
6940
  // attr_load_orco: the orco attribute (\`orcoAttribute\`), interpolated.
@@ -7017,44 +7017,44 @@ vec3 blender_reflection() {
7017
7017
  : normalize(cameraPosition - vBlenderWorldPosition);
7018
7018
  return blender_from_three * -reflect(incident, normalize(vBlenderWorldNormal));
7019
7019
  }
7020
- `;class Wn{constructor(t,o,e=!1,a="bgN"){this.graph=t,this.derivative=e,this.prefix=a,this.lines=[],this.emitted=new Map,this.s=o??{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,o){const e=`bgU${this.s.uniforms.size}`,a=cl(t,o);return this.s.uniforms.set(e,t==="float"?a[0]:a),this.s.uniformTypes.set(e,t),e}use(t){const o=vl.get(t);if(!o)throw new Error(`Blender's node library has no ${t}`);return this.s.files.add(o),t}source(t,o){if("value"in t)return this.s.structure.push("v"),this.uniform(o,t.value);const[e,a]=t.link,i=this.graph.nodes[e];if(!i)throw new Error(`The graph links to ${e}, which it does not carry`);const u=this.node(e,i)[a];if(!u)throw new Error(`${e} has no output ${a}`);return this.s.structure.push(["l",e,a]),ul(u.name,u.type,o)}input(t,o,e){const a=t.inputs.find(i=>i.id===o)??t.inputs.find(i=>i.id.replace(/_/g," ")===o);if(!a)throw new Error(`${t.type} arrived without its '${o}' input`);return this.source(a,e??a.gpu)}coordinate(t,o){const e=t.inputs[0];return"link"in e?this.source(e,"vec3"):(this.s.structure.push(["default",o]),o==="orco"?this.d("blender_orco()"):(this.s.uvs.add(""),this.d(`vec3(${zt("")}, 0.0)`)))}node(t,o){const e=this.emitted.get(t);if(e)return e;const a=`${this.prefix}${this.emitted.size}`,i=o.outputs.map((l,m)=>({name:`${a}_${m}`,type:l.gpu==="closure"||l.gpu===null?"float":l.gpu}));this.emitted.set(t,i);const s=l=>`${i[l].type} ${i[l].name} = ${i[l].type}(0.0);`,u=i.map((l,m)=>s(m)).join(" "),c=l=>l.map(m=>i[m].name).join(", "),f=(l=[])=>[...o.inputs.map(h=>this.source(h,h.gpu)),...l,...i.map(h=>h.name)].join(", ");this.s.structure.push(["n",o.type,o.props.operation,o.props.blend_type,o.props.data_type,o.props.factor_mode,o.props.clamp_factor,o.props.clamp_result,o.props.use_clamp,o.props.noise_dimensions,o.props.noise_type,o.props.voronoi_dimensions,o.props.feature,o.props.distance,o.props.vector_type,o.props.uv_map,o.props.extension,o.props.interpolation,o.props.image_alpha_mode,o.props.image_is_data,o.props.color_ramp?.elements?.length,o.props.color_ramp?.interpolation]);const r=[u];switch(o.type){case"ShaderNodeValue":case"ShaderNodeRGB":{const l=i[0].type;r.push(`${i[0].name} = ${this.uniform(l,N(o,"value"))};`);break}case"ShaderNodeTexCoord":{this.s.uvs.add(""),["blender_orco()","blender_object_normal()",`vec3(${zt("")}, 0.0)`,"vBlenderObjectPosition","blender_camera()","blender_window()","blender_reflection()"].forEach((m,h)=>{i[h]&&r.push(`${i[h].name} = ${this.d(m)};`)});break}case"ShaderNodeVertexColor":case"ShaderNodeAttribute":{const l=N(o,o.type==="ShaderNodeAttribute"?"attribute_name":"layer_name");this.s.attributes.add(l),this.s.structure.push(["a",l]);const m=o.type==="ShaderNodeAttribute"?"node_attribute":"node_vertex_color";r.push(`${this.use(m)}(${Ln(l)}, ${c(i.map((h,d)=>d))});`);for(const h of i)r.push(`${h.name} = ${this.d(h.name)};`);break}case"ShaderNodeUVMap":{const l=N(o,"uv_map");this.s.uvs.add(l),r.push(`${i[0].name} = ${this.d(`vec3(${zt(l)}, 0.0)`)};`);break}case"ShaderNodeMath":{const l=N(o,"operation"),m=this.use(_l[l]??`math_${l.toLowerCase()}`);r.push(`${m}(${f()});`),N(o,"use_clamp")&&r.push(`${this.use("clamp_value")}(${c([0])}, 0.0, 1.0, ${c([0])});`);break}case"ShaderNodeVectorMath":{const l=N(o,"operation");r.push(`${this.use(ml[l]??`vector_math_${l.toLowerCase()}`)}(${f()});`);break}case"ShaderNodeMapping":r.push(`${this.use(`mapping_${N(o,"vector_type").toLowerCase()}`)}(${f()});`);break;case"ShaderNodeInvert":r.push(`${this.use("invert")}(${f()});`);break;case"ShaderNodeSeparateXYZ":r.push(`${this.use("separate_xyz")}(${f()});`);break;case"ShaderNodeCombineXYZ":r.push(`${this.use("combine_xyz")}(${f()});`);break;case"ShaderNodeMix":{const l=N(o,"data_type"),m=N(o,"factor_mode")==="NON_UNIFORM",h={FLOAT:"Float",VECTOR:"Vector",RGBA:"Color",ROTATION:"Rotation"}[l];if(!h)throw new Error(`Mix has data type ${l}`);const d=l==="VECTOR"&&m;let _=this.input(o,d?"Factor_Vector":"Factor_Float");if(N(o,"clamp_factor")){const g=`${a}_fac`;r.push(d?`vec3 ${g}; ${this.use("node_mix_clamp_vector")}(${_}, vec3(0.0), vec3(1.0), ${g});`:`float ${g}; ${this.use("node_mix_clamp_value")}(${_}, 0.0, 1.0, ${g});`),_=g}const p=l==="FLOAT"?"node_mix_float":l==="VECTOR"?m?"node_mix_vector_non_uniform":"node_mix_vector":l==="RGBA"?`node_mix_${vo[N(o,"blend_type")]}`:"node_mix_rotation",v=o.outputs.findIndex(g=>g.id===`Result_${h}`);r.push(`${this.use(p)}(${_}, ${this.input(o,`A_${h}`)}, ${this.input(o,`B_${h}`)}, ${c([v])});`),l==="RGBA"&&N(o,"clamp_result")&&r.push(`${this.use("node_mix_clamp_color")}(${c([v])}, vec4(0.0), vec4(1.0), ${c([v])});`);break}case"ShaderNodeMixRGB":{const l=`${a}_fac`;r.push(`float ${l}; ${this.use("clamp_value")}(${this.input(o,"Fac")}, 0.0, 1.0, ${l});`);const m=o.inputs.slice(1).map(h=>this.source(h,h.gpu));r.push(`${this.use(`mix_${vo[N(o,"blend_type")]}`)}(${[l,...m,c([0])].join(", ")});`),N(o,"use_clamp")&&r.push(`${this.use("clamp_color")}(${c([0])}, vec4(0.0), vec4(1.0), ${c([0])});`);break}case"ShaderNodeValToRGB":{const l=N(o,"color_ramp"),m=this.input(o,"Fac"),[h,d]=l.elements,_=p=>this.uniform("vec4",p.slice(1,5));if(l.elements.length===1)r.push(`${c([0])} = ${_(h)}; ${c([1])} = ${c([0])}.a;`);else if(l.elements.length===2&&l.color_mode==="RGB"&&d&&l.interpolation!=="B_SPLINE"&&l.interpolation!=="CARDINAL")if(l.interpolation==="CONSTANT")r.push(`${this.use("valtorgb_opti_constant")}(${m}, ${this.uniform("float",Math.max(h[0],d[0]))}, ${_(h)}, ${_(d)}, ${c([0,1])});`);else{const p=1/(d[0]-h[0]),v=l.interpolation==="EASE"?"valtorgb_opti_ease":"valtorgb_opti_linear";r.push(`${this.use(v)}(${m}, ${this.uniform("vec2",[p,-p*h[0]])}, ${_(h)}, ${_(d)}, ${c([0,1])});`)}else{const p=`bgRamp${this.s.ramps.length}`;this.s.ramps.push({uniform:p,table:l.table}),this.s.structure.push(["ramp",l.interpolation==="CONSTANT"]),r.push(l.interpolation==="CONSTANT"?`${c([0])} = texelFetch(${p}, ivec2(int(clamp(${m}, 0.0, 1.0) * 256.0), 0), 0);`:`${c([0])} = texture(${p}, vec2(clamp(${m}, 0.0, 1.0) * (256.0 / 257.0) + 0.5 / 257.0, 0.5));`),r.push(`${c([1])} = ${c([0])}.a;`)}break}case"ShaderNodeRGBCurve":case"ShaderNodeVectorCurve":case"ShaderNodeFloatCurve":{const l=N(o,"curve_mapping"),m=`bgRamp${this.s.ramps.length}`;this.s.ramps.push({uniform:m,table:l.table}),this.s.structure.push(["curve"]);const h=this.input(o,o.inputs.some(d=>d.id==="Factor")?"Factor":"Fac","float");o.type==="ShaderNodeRGBCurve"?r.push(`${this.use("curves_combined_rgb")}(${h}, ${this.input(o,"Color","vec4")}, vec4(0.0, 0.0, 0.0, 1.0), vec4(1.0), ${m}, 0.5, ${this.uniform("vec4",l.minimums)}, ${this.uniform("vec4",l.dividers)}, ${this.uniform("vec4",l.starts)}, ${this.uniform("vec4",l.ends)}, ${c([0])});`):o.type==="ShaderNodeVectorCurve"?r.push(`${this.use("curves_vector_mixed")}(${h}, ${this.input(o,"Vector","vec3")}, ${m}, 0.5, ${this.uniform("vec3",l.minimums.slice(0,3))}, ${this.uniform("vec3",l.dividers.slice(0,3))}, ${this.uniform("vec3",l.starts.slice(0,3))}, ${this.uniform("vec3",l.ends.slice(0,3))}, ${c([0])});`):r.push(`${this.use("curves_float_mixed")}(${h}, ${this.input(o,"Value","float")}, ${m}, 0.5, ${this.uniform("float",l.minimums[0])}, ${this.uniform("float",l.dividers[0])}, ${this.uniform("float",l.starts[0])}, ${this.uniform("float",l.ends[0])}, ${c([0])});`);break}case"ShaderNodeTexNoise":{const l=Number(N(o,"noise_dimensions")[0]),m=this.use(`node_noise_tex_${dl[N(o,"noise_type")]}_${l}d`),h=this.coordinate(o,"orco"),d=o.inputs.slice(1).map(p=>this.source(p,p.gpu)),_=N(o,"normalize")?"1.0":"0.0";r.push(`${m}(${[h,...d,_,"1.0",c(i.map((p,v)=>v))].join(", ")});`);break}case"ShaderNodeTexVoronoi":{const l=Number(N(o,"voronoi_dimensions")[0]),m=this.use(`node_tex_voronoi_${hl[N(o,"feature")]}_${l}d`),h=this.coordinate(o,"orco"),d=o.inputs.slice(1).map(v=>this.source(v,v.gpu)),_=`${pl[N(o,"distance")].toFixed(1)}`,p=N(o,"normalize")?"1.0":"0.0";r.push(`${m}(${[h,...d,_,p,c(i.map((v,g)=>g))].join(", ")});`);break}case"ShaderNodeTexChecker":{const l=this.coordinate(o,"orco"),m=o.inputs.slice(1).map(h=>this.source(h,h.gpu));r.push(`${this.use("node_tex_checker")}(${[l,...m,c(i.map((h,d)=>d))].join(", ")});`);break}case"ShaderNodeTexWhiteNoise":{const l=Number(N(o,"noise_dimensions")[0]);r.push(`${this.use(`node_white_noise_${l}d`)}(${f()});`);break}case"ShaderNodeTexWave":case"ShaderNodeTexGradient":case"ShaderNodeTexMagic":case"ShaderNodeTexBrick":{const l=this.coordinate(o,"orco"),m=o.inputs.slice(1).map(p=>this.source(p,p.gpu)),h=p=>N(o,`${p}#value`).toFixed(1),d=o.type==="ShaderNodeTexWave"?[h("wave_type"),h("bands_direction"),h("rings_direction"),h("wave_profile")]:o.type==="ShaderNodeTexGradient"?[h("gradient_type")]:o.type==="ShaderNodeTexMagic"?[N(o,"turbulence_depth").toFixed(1)]:[this.uniform("float",N(o,"offset")),N(o,"offset_frequency").toFixed(1),this.uniform("float",N(o,"squash")),N(o,"squash_frequency").toFixed(1)],_={ShaderNodeTexWave:"node_tex_wave",ShaderNodeTexGradient:"node_tex_gradient",ShaderNodeTexMagic:"node_tex_magic",ShaderNodeTexBrick:"node_tex_brick"}[o.type];r.push(`${this.use(_)}(${[l,...m,...d,c(i.map((p,v)=>v))].join(", ")});`);break}case"ShaderNodeMapRange":{const l=N(o,"data_type")==="FLOAT_VECTOR",m=N(o,"interpolation_type").toLowerCase(),h=N(o,"clamp");r.push(`${this.use(`${l?"vector_":""}map_range_${m}`)}(${f([h?"1.0":"0.0"])});`),h&&!l&&(m==="linear"||m==="stepped")&&r.push(`${this.use("clamp_range")}(${c([0])}, ${this.input(o,"To Min","float")}, ${this.input(o,"To Max","float")}, ${c([0])});`);break}case"ShaderNodeClamp":r.push(`${this.use(N(o,"clamp_type")==="MINMAX"?"clamp_minmax":"clamp_range")}(${f()});`);break;case"ShaderNodeHueSaturation":r.push(`${this.use("hue_sat")}(${f()});`);break;case"ShaderNodeBrightContrast":r.push(`${this.use("brightness_contrast")}(${f()});`);break;case"ShaderNodeGamma":r.push(`${this.use("node_gamma")}(${f()});`);break;case"ShaderNodeRGBToBW":r.push(`${this.use("rgbtobw")}(${f([Xo])});`);break;case"ShaderNodeSeparateColor":r.push(`${this.use(`separate_color_${N(o,"mode").toLowerCase()}`)}(${f()});`);break;case"ShaderNodeCombineColor":r.push(`${this.use(`combine_color_${N(o,"mode").toLowerCase()}`)}(${f()});`);break;case"ShaderNodeVectorRotate":{const l={AXIS_ANGLE:"axis_angle",X_AXIS:"axis_x",Y_AXIS:"axis_y",Z_AXIS:"axis_z",EULER_XYZ:"euler_xyz"}[N(o,"rotation_type")];r.push(`${this.use(`node_vector_rotate_${l}`)}(${f([N(o,"invert")?"-1.0":"1.0"])});`);break}case"ShaderNodeFresnel":case"ShaderNodeLayerWeight":{const l=o.inputs[1],m="link"in l?this.source(l,"vec3"):"g_data.N";"link"in l||this.s.structure.push("world-normal");const h=this.source(o.inputs[0],"float"),d=o.type==="ShaderNodeFresnel"?"node_fresnel":"node_layer_weight";r.push(`${this.use(d)}(${[h,m,c(i.map((_,p)=>p))].join(", ")});`);break}case"ShaderNodeBump":{const l=o.inputs.find(b=>b.id==="Height"),m=o.inputs.find(b=>b.id==="Normal"),h=m&&"link"in m?this.source(m,"vec3"):"g_data.N";if(!l||!("link"in l)){r.push(`${c([0])} = ${h};`);break}const d=`bgHeight${this.s.functions.length}`;this.s.functions.push("");const _=new Wn(this.graph,this.s,!0,`${d}_`),p=_.source(l,"float");this.s.functions[Number(d.slice(8))]=`float ${d}() {
7021
- ${_.lines.join(`
7020
+ `;class lo{constructor(t,n,e=!1,r="bgN"){this.graph=t,this.derivative=e,this.prefix=r,this.lines=[],this.emitted=new Map,this.s=n??{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,n){const e=`bgU${this.s.uniforms.size}`,r=zr(t,n);return this.s.uniforms.set(e,t==="float"?r[0]:r),this.s.uniformTypes.set(e,t),e}use(t){const n=Vr.get(t);if(!n)throw new Error(`Blender's node library has no ${t}`);return this.s.files.add(n),t}source(t,n){if("value"in t)return this.s.structure.push("v"),this.uniform(n,t.value);const[e,r]=t.link,a=this.graph.nodes[e];if(!a)throw new Error(`The graph links to ${e}, which it does not carry`);const c=this.node(e,a)[r];if(!c)throw new Error(`${e} has no output ${r}`);return this.s.structure.push(["l",e,r]),Fr(c.name,c.type,n)}input(t,n,e){const r=t.inputs.find(a=>a.id===n)??t.inputs.find(a=>a.id.replace(/_/g," ")===n);if(!r)throw new Error(`${t.type} arrived without its '${n}' input`);return this.source(r,e??r.gpu)}coordinate(t,n){const e=t.inputs[0];return"link"in e?this.source(e,"vec3"):(this.s.structure.push(["default",n]),n==="orco"?this.d("blender_orco()"):(this.s.uvs.add(""),this.d(`vec3(${Ht("")}, 0.0)`)))}node(t,n){const e=this.emitted.get(t);if(e)return e;const r=`${this.prefix}${this.emitted.size}`,a=n.outputs.map((l,_)=>({name:`${r}_${_}`,type:l.gpu==="closure"||l.gpu===null?"float":l.gpu}));this.emitted.set(t,a);const i=l=>`${a[l].type} ${a[l].name} = ${a[l].type}(0.0);`,c=a.map((l,_)=>i(_)).join(" "),u=l=>l.map(_=>a[_].name).join(", "),f=(l=[])=>[...n.inputs.map(h=>this.source(h,h.gpu)),...l,...a.map(h=>h.name)].join(", ");this.s.structure.push(["n",n.type,n.props.operation,n.props.blend_type,n.props.data_type,n.props.factor_mode,n.props.clamp_factor,n.props.clamp_result,n.props.use_clamp,n.props.noise_dimensions,n.props.noise_type,n.props.voronoi_dimensions,n.props.feature,n.props.distance,n.props.vector_type,n.props.uv_map,n.props.extension,n.props.interpolation,n.props.image_alpha_mode,n.props.image_is_data,n.props.color_ramp?.elements?.length,n.props.color_ramp?.interpolation]);const s=[c];switch(n.type){case"ShaderNodeValue":case"ShaderNodeRGB":{const l=a[0].type;s.push(`${a[0].name} = ${this.uniform(l,F(n,"value"))};`);break}case"ShaderNodeTexCoord":{this.s.uvs.add(""),["blender_orco()","blender_object_normal()",`vec3(${Ht("")}, 0.0)`,"vBlenderObjectPosition","blender_camera()","blender_window()","blender_reflection()"].forEach((_,h)=>{a[h]&&s.push(`${a[h].name} = ${this.d(_)};`)});break}case"ShaderNodeVertexColor":case"ShaderNodeAttribute":{const l=F(n,n.type==="ShaderNodeAttribute"?"attribute_name":"layer_name");this.s.attributes.add(l),this.s.structure.push(["a",l]);const _=n.type==="ShaderNodeAttribute"?"node_attribute":"node_vertex_color";s.push(`${this.use(_)}(${Qn(l)}, ${u(a.map((h,d)=>d))});`);for(const h of a)s.push(`${h.name} = ${this.d(h.name)};`);break}case"ShaderNodeUVMap":{const l=F(n,"uv_map");this.s.uvs.add(l),s.push(`${a[0].name} = ${this.d(`vec3(${Ht(l)}, 0.0)`)};`);break}case"ShaderNodeMath":{const l=F(n,"operation"),_=this.use(Dr[l]??`math_${l.toLowerCase()}`);s.push(`${_}(${f()});`),F(n,"use_clamp")&&s.push(`${this.use("clamp_value")}(${u([0])}, 0.0, 1.0, ${u([0])});`);break}case"ShaderNodeVectorMath":{const l=F(n,"operation");s.push(`${this.use(Cr[l]??`vector_math_${l.toLowerCase()}`)}(${f()});`);break}case"ShaderNodeMapping":s.push(`${this.use(`mapping_${F(n,"vector_type").toLowerCase()}`)}(${f()});`);break;case"ShaderNodeInvert":s.push(`${this.use("invert")}(${f()});`);break;case"ShaderNodeSeparateXYZ":s.push(`${this.use("separate_xyz")}(${f()});`);break;case"ShaderNodeCombineXYZ":s.push(`${this.use("combine_xyz")}(${f()});`);break;case"ShaderNodeMix":{const l=F(n,"data_type"),_=F(n,"factor_mode")==="NON_UNIFORM",h={FLOAT:"Float",VECTOR:"Vector",RGBA:"Color",ROTATION:"Rotation"}[l];if(!h)throw new Error(`Mix has data type ${l}`);const d=l==="VECTOR"&&_;let m=this.input(n,d?"Factor_Vector":"Factor_Float");if(F(n,"clamp_factor")){const g=`${r}_fac`;s.push(d?`vec3 ${g}; ${this.use("node_mix_clamp_vector")}(${m}, vec3(0.0), vec3(1.0), ${g});`:`float ${g}; ${this.use("node_mix_clamp_value")}(${m}, 0.0, 1.0, ${g});`),m=g}const p=l==="FLOAT"?"node_mix_float":l==="VECTOR"?_?"node_mix_vector_non_uniform":"node_mix_vector":l==="RGBA"?`node_mix_${zo[F(n,"blend_type")]}`:"node_mix_rotation",v=n.outputs.findIndex(g=>g.id===`Result_${h}`);s.push(`${this.use(p)}(${m}, ${this.input(n,`A_${h}`)}, ${this.input(n,`B_${h}`)}, ${u([v])});`),l==="RGBA"&&F(n,"clamp_result")&&s.push(`${this.use("node_mix_clamp_color")}(${u([v])}, vec4(0.0), vec4(1.0), ${u([v])});`);break}case"ShaderNodeMixRGB":{const l=`${r}_fac`;s.push(`float ${l}; ${this.use("clamp_value")}(${this.input(n,"Fac")}, 0.0, 1.0, ${l});`);const _=n.inputs.slice(1).map(h=>this.source(h,h.gpu));s.push(`${this.use(`mix_${zo[F(n,"blend_type")]}`)}(${[l,..._,u([0])].join(", ")});`),F(n,"use_clamp")&&s.push(`${this.use("clamp_color")}(${u([0])}, vec4(0.0), vec4(1.0), ${u([0])});`);break}case"ShaderNodeValToRGB":{const l=F(n,"color_ramp"),_=this.input(n,"Fac"),[h,d]=l.elements,m=p=>this.uniform("vec4",p.slice(1,5));if(l.elements.length===1)s.push(`${u([0])} = ${m(h)}; ${u([1])} = ${u([0])}.a;`);else if(l.elements.length===2&&l.color_mode==="RGB"&&d&&l.interpolation!=="B_SPLINE"&&l.interpolation!=="CARDINAL")if(l.interpolation==="CONSTANT")s.push(`${this.use("valtorgb_opti_constant")}(${_}, ${this.uniform("float",Math.max(h[0],d[0]))}, ${m(h)}, ${m(d)}, ${u([0,1])});`);else{const p=1/(d[0]-h[0]),v=l.interpolation==="EASE"?"valtorgb_opti_ease":"valtorgb_opti_linear";s.push(`${this.use(v)}(${_}, ${this.uniform("vec2",[p,-p*h[0]])}, ${m(h)}, ${m(d)}, ${u([0,1])});`)}else{const p=`bgRamp${this.s.ramps.length}`;this.s.ramps.push({uniform:p,table:l.table}),this.s.structure.push(["ramp",l.interpolation==="CONSTANT"]),s.push(l.interpolation==="CONSTANT"?`${u([0])} = texelFetch(${p}, ivec2(int(clamp(${_}, 0.0, 1.0) * 256.0), 0), 0);`:`${u([0])} = texture(${p}, vec2(clamp(${_}, 0.0, 1.0) * (256.0 / 257.0) + 0.5 / 257.0, 0.5));`),s.push(`${u([1])} = ${u([0])}.a;`)}break}case"ShaderNodeRGBCurve":case"ShaderNodeVectorCurve":case"ShaderNodeFloatCurve":{const l=F(n,"curve_mapping"),_=`bgRamp${this.s.ramps.length}`;this.s.ramps.push({uniform:_,table:l.table}),this.s.structure.push(["curve"]);const h=this.input(n,n.inputs.some(d=>d.id==="Factor")?"Factor":"Fac","float");n.type==="ShaderNodeRGBCurve"?s.push(`${this.use("curves_combined_rgb")}(${h}, ${this.input(n,"Color","vec4")}, vec4(0.0, 0.0, 0.0, 1.0), vec4(1.0), ${_}, 0.5, ${this.uniform("vec4",l.minimums)}, ${this.uniform("vec4",l.dividers)}, ${this.uniform("vec4",l.starts)}, ${this.uniform("vec4",l.ends)}, ${u([0])});`):n.type==="ShaderNodeVectorCurve"?s.push(`${this.use("curves_vector_mixed")}(${h}, ${this.input(n,"Vector","vec3")}, ${_}, 0.5, ${this.uniform("vec3",l.minimums.slice(0,3))}, ${this.uniform("vec3",l.dividers.slice(0,3))}, ${this.uniform("vec3",l.starts.slice(0,3))}, ${this.uniform("vec3",l.ends.slice(0,3))}, ${u([0])});`):s.push(`${this.use("curves_float_mixed")}(${h}, ${this.input(n,"Value","float")}, ${_}, 0.5, ${this.uniform("float",l.minimums[0])}, ${this.uniform("float",l.dividers[0])}, ${this.uniform("float",l.starts[0])}, ${this.uniform("float",l.ends[0])}, ${u([0])});`);break}case"ShaderNodeTexNoise":{const l=Number(F(n,"noise_dimensions")[0]),_=this.use(`node_noise_tex_${kr[F(n,"noise_type")]}_${l}d`),h=this.coordinate(n,"orco"),d=n.inputs.slice(1).map(p=>this.source(p,p.gpu)),m=F(n,"normalize")?"1.0":"0.0";s.push(`${_}(${[h,...d,m,"1.0",u(a.map((p,v)=>v))].join(", ")});`);break}case"ShaderNodeTexVoronoi":{const l=Number(F(n,"voronoi_dimensions")[0]),_=this.use(`node_tex_voronoi_${$r[F(n,"feature")]}_${l}d`),h=this.coordinate(n,"orco"),d=n.inputs.slice(1).map(v=>this.source(v,v.gpu)),m=`${Lr[F(n,"distance")].toFixed(1)}`,p=F(n,"normalize")?"1.0":"0.0";s.push(`${_}(${[h,...d,m,p,u(a.map((v,g)=>g))].join(", ")});`);break}case"ShaderNodeTexChecker":{const l=this.coordinate(n,"orco"),_=n.inputs.slice(1).map(h=>this.source(h,h.gpu));s.push(`${this.use("node_tex_checker")}(${[l,..._,u(a.map((h,d)=>d))].join(", ")});`);break}case"ShaderNodeTexWhiteNoise":{const l=Number(F(n,"noise_dimensions")[0]);s.push(`${this.use(`node_white_noise_${l}d`)}(${f()});`);break}case"ShaderNodeTexWave":case"ShaderNodeTexGradient":case"ShaderNodeTexMagic":case"ShaderNodeTexBrick":{const l=this.coordinate(n,"orco"),_=n.inputs.slice(1).map(p=>this.source(p,p.gpu)),h=p=>F(n,`${p}#value`).toFixed(1),d=n.type==="ShaderNodeTexWave"?[h("wave_type"),h("bands_direction"),h("rings_direction"),h("wave_profile")]:n.type==="ShaderNodeTexGradient"?[h("gradient_type")]:n.type==="ShaderNodeTexMagic"?[F(n,"turbulence_depth").toFixed(1)]:[this.uniform("float",F(n,"offset")),F(n,"offset_frequency").toFixed(1),this.uniform("float",F(n,"squash")),F(n,"squash_frequency").toFixed(1)],m={ShaderNodeTexWave:"node_tex_wave",ShaderNodeTexGradient:"node_tex_gradient",ShaderNodeTexMagic:"node_tex_magic",ShaderNodeTexBrick:"node_tex_brick"}[n.type];s.push(`${this.use(m)}(${[l,..._,...d,u(a.map((p,v)=>v))].join(", ")});`);break}case"ShaderNodeMapRange":{const l=F(n,"data_type")==="FLOAT_VECTOR",_=F(n,"interpolation_type").toLowerCase(),h=F(n,"clamp");s.push(`${this.use(`${l?"vector_":""}map_range_${_}`)}(${f([h?"1.0":"0.0"])});`),h&&!l&&(_==="linear"||_==="stepped")&&s.push(`${this.use("clamp_range")}(${u([0])}, ${this.input(n,"To Min","float")}, ${this.input(n,"To Max","float")}, ${u([0])});`);break}case"ShaderNodeClamp":s.push(`${this.use(F(n,"clamp_type")==="MINMAX"?"clamp_minmax":"clamp_range")}(${f()});`);break;case"ShaderNodeHueSaturation":s.push(`${this.use("hue_sat")}(${f()});`);break;case"ShaderNodeBrightContrast":s.push(`${this.use("brightness_contrast")}(${f()});`);break;case"ShaderNodeGamma":s.push(`${this.use("node_gamma")}(${f()});`);break;case"ShaderNodeRGBToBW":s.push(`${this.use("rgbtobw")}(${f([pe])});`);break;case"ShaderNodeSeparateColor":s.push(`${this.use(`separate_color_${F(n,"mode").toLowerCase()}`)}(${f()});`);break;case"ShaderNodeCombineColor":s.push(`${this.use(`combine_color_${F(n,"mode").toLowerCase()}`)}(${f()});`);break;case"ShaderNodeVectorRotate":{const l={AXIS_ANGLE:"axis_angle",X_AXIS:"axis_x",Y_AXIS:"axis_y",Z_AXIS:"axis_z",EULER_XYZ:"euler_xyz"}[F(n,"rotation_type")];s.push(`${this.use(`node_vector_rotate_${l}`)}(${f([F(n,"invert")?"-1.0":"1.0"])});`);break}case"ShaderNodeFresnel":case"ShaderNodeLayerWeight":{const l=n.inputs[1],_="link"in l?this.source(l,"vec3"):"g_data.N";"link"in l||this.s.structure.push("world-normal");const h=this.source(n.inputs[0],"float"),d=n.type==="ShaderNodeFresnel"?"node_fresnel":"node_layer_weight";s.push(`${this.use(d)}(${[h,_,u(a.map((m,p)=>p))].join(", ")});`);break}case"ShaderNodeBump":{const l=n.inputs.find(b=>b.id==="Height"),_=n.inputs.find(b=>b.id==="Normal"),h=_&&"link"in _?this.source(_,"vec3"):"g_data.N";if(!l||!("link"in l)){s.push(`${u([0])} = ${h};`);break}const d=`bgHeight${this.s.functions.length}`;this.s.functions.push("");const m=new lo(this.graph,this.s,!0,`${d}_`),p=m.source(l,"float");this.s.functions[Number(d.slice(8))]=`float ${d}() {
7021
+ ${m.lines.join(`
7022
7022
  `)}
7023
7023
  return ${p};
7024
- }`;const v=this.input(o,"Filter Width","float");r.push(`float ${a}_h = ${d}();`,`g_derivative_filter_width = ${v} * derivative_scale_get();`,`g_derivative_flag = 1; float ${a}_hx = ${d}();`,`g_derivative_flag = -1; float ${a}_hy = ${d}();`,"g_derivative_flag = 0;");const g=N(o,"invert")?"-1.0":"1.0";r.push(`${this.use("node_bump")}(${this.input(o,"Strength","float")}, ${this.input(o,"Distance","float")}, ${v}, ${a}_h, ${h}, vec2(${a}_hx, ${a}_hy), ${g}, ${c([0])});`);break}case"ShaderNodeNormalMap":{const l=N(o,"space"),m=this.input(o,"Strength","float"),h=this.input(o,"Color","vec3"),d=`${a}_n`;if(r.push(`vec3 ${d}; ${this.use(l.startsWith("BLENDER_")?"color_to_blender_normal_new_shading":"color_to_normal_new_shading")}(${h}, ${d});`),o.props.convention==="DIRECTX"&&r.push(`${this.use("color_invert_green_channel")}(${d}, ${d});`),l==="TANGENT"){const _=N(o,"uv_map");this.s.uvs.add(_),r.push(`${this.use("node_normal_map")}(blender_uv_tangent(${zt(_)}), ${m}, ${d}, g_data.Ni, ${c([0])});`)}else(l==="OBJECT"||l==="BLENDER_OBJECT")&&r.push(`${this.use("normal_transform_object_to_world")}(${d}, ${d});`),r.push(`${this.use("node_normal_map_mix")}(${m}, ${d}, ${c([0])});`);break}case"ShaderNodeNewGeometry":{r.push(`${this.use("node_geometry")}(${["blender_orco()",c(i.map((l,m)=>m))].join(", ")});`),i[0]&&r.push(`${i[0].name} = ${this.d(i[0].name)};`);for(const l of[1,2,4])i[l]&&r.push(`${i[l].name} = normalize(${i[l].name});`);break}case"ShaderNodeTexImage":{const l=N(o,"image");if(l===null){r.push(`${c([0])} = vec4(0.0); ${c([1])} = 0.0;`);break}const m=N(o,"projection"),h=N(o,"interpolation"),d=h==="Cubic"||h==="Smart",_=N(o,"extension"),p=`bgImage${this.s.images.length}`;this.s.images.push({uniform:p,node:t,name:l.name,revision:l.revision,extension:_,closest:h==="Closest",mipmap:m!=="SPHERE"&&m!=="TUBE",tiled:m==="FLAT"&&o.props.image_tiled===!0});const v=this.s.images.at(-1).tiled;this.s.structure.push(["img",m,d,v]);let g=this.coordinate(o,"uv");const b=c([0]),P=c([1]);if(m==="BOX"){const E=`${a}_n`;r.push(`vec3 ${E}; ${this.use("world_normals_get")}(${E}); ${this.use("normal_transform_world_to_object")}(${E}, ${E});`,`vec4 ${a}_c1, ${a}_c2, ${a}_c3;`,`${this.use(d?"tex_box_sample_cubic":"tex_box_sample_linear")}(${g}, ${E}, ${p}, ${a}_c1, ${a}_c2, ${a}_c3);`,`${this.use("tex_box_blend")}(${E}, ${a}_c1, ${a}_c2, ${a}_c3, ${this.uniform("float",N(o,"projection_blend"))}, ${b}, ${P});`)}else if(v)d&&this.use("cubic_bspline_coefficients"),r.push(`${d?"blender_tex_tile_cubic":"blender_tex_tile_linear"}(${g}, ${p}, ${p}Map, ${b}, ${P});`);else{if(m==="SPHERE"||m==="TUBE"){const E=`${a}_co`;r.push(`vec3 ${E}; ${this.use("point_texco_remap_square")}(${g}, ${E});`,`${this.use(m==="SPHERE"?"point_map_to_sphere":"point_map_to_tube")}(${E}, ${E});`),g=E}r.push(`${this.use(d?"node_tex_image_cubic":"node_tex_image_linear")}(${g}, ${p}, ${b}, ${P});`),_==="CLIP"&&r.push(`if (any(lessThan(${g}.xy, vec2(0.0))) || any(greaterThan(${g}.xy, vec2(1.0)))) { ${b} = vec4(0.0); ${P} = 0.0; }`)}const D=N(o,"image_alpha_mode"),w=this.uses(t,1);D==="NONE"||D==="CHANNEL_PACKED"||N(o,"image_is_data")||!w?r.push(`${c([0])}.a = 1.0;`):r.push(`${c([0])} = vec4(${c([0])}.rgb * ${c([0])}.a, 1.0);`);break}}return this.lines.push(...r),i}uses(t,o){const e=i=>"link"in i&&i.link[0]===t&&i.link[1]===o,a=i=>i!==void 0&&("emission"in i?i.emission.some(e):"mix"in i?e(i.mix[0])||a(i.mix[1])||a(i.mix[2]):"add"in i?a(i.add[0])||a(i.add[1]):!1);return Object.values(this.graph.inputs).some(e)||Object.values(this.graph.nodes).some(i=>i.inputs.some(e))||a(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"},o={},e=[];let a=0;for(const[l,m]of Object.entries(t)){const h=this.graph.inputs[l];if(!h||l==="Normal"&&!("link"in h))continue;const d=`bgOut${a++}`;o[l]={global:d,type:m},this.s.structure.push(["out",l]),e.push(`${d} = ${this.source(h,m)};`)}const i=this.graph.closure;if(i){let l=0;const m=(h,d)=>{if("principled"in h)this.s.structure.push("cP"),e.push(`bgClosureP += ${d};`);else if("emission"in h)this.s.structure.push("cE"),e.push(`bgClosureE += ${d} * ${this.source(h.emission[0],"vec4")}.rgb * ${this.source(h.emission[1],"float")};`);else if("transparent"in h)this.s.structure.push("cT"),e.push(`bgClosureT += ${d} * ${this.source({value:h.transparent},"float")};`);else if("mix"in h){this.s.structure.push("cM");const _=`bgClosureF${l++}`;e.push(`float ${_} = clamp(${this.source(h.mix[0],"float")}, 0.0, 1.0);`),m(h.mix[1],`${d} * (1.0 - ${_})`),m(h.mix[2],`${d} * ${_}`)}else"add"in h?(this.s.structure.push("cA"),m(h.add[0],d),m(h.add[1],d)):this.s.structure.push("c0")};e.push("bgClosureP = 0.0;","bgClosureE = vec3(0.0);","bgClosureT = 0.0;"),m(i,"1.0")}const s=[],u=new Set,c=l=>{if(!u.has(l)){u.add(l);for(const m of $n[l].deps)c(m);s.push(l)}};for(const l of this.s.files)c(l);const f=`void blenderGraph() {
7024
+ }`;const v=this.input(n,"Filter Width","float");s.push(`float ${r}_h = ${d}();`,`g_derivative_filter_width = ${v} * derivative_scale_get();`,`g_derivative_flag = 1; float ${r}_hx = ${d}();`,`g_derivative_flag = -1; float ${r}_hy = ${d}();`,"g_derivative_flag = 0;");const g=F(n,"invert")?"-1.0":"1.0";s.push(`${this.use("node_bump")}(${this.input(n,"Strength","float")}, ${this.input(n,"Distance","float")}, ${v}, ${r}_h, ${h}, vec2(${r}_hx, ${r}_hy), ${g}, ${u([0])});`);break}case"ShaderNodeNormalMap":{const l=F(n,"space"),_=this.input(n,"Strength","float"),h=this.input(n,"Color","vec3"),d=`${r}_n`;if(s.push(`vec3 ${d}; ${this.use(l.startsWith("BLENDER_")?"color_to_blender_normal_new_shading":"color_to_normal_new_shading")}(${h}, ${d});`),n.props.convention==="DIRECTX"&&s.push(`${this.use("color_invert_green_channel")}(${d}, ${d});`),l==="TANGENT"){const m=F(n,"uv_map");this.s.uvs.add(m),s.push(`${this.use("node_normal_map")}(blender_uv_tangent(${Ht(m)}), ${_}, ${d}, g_data.Ni, ${u([0])});`)}else(l==="OBJECT"||l==="BLENDER_OBJECT")&&s.push(`${this.use("normal_transform_object_to_world")}(${d}, ${d});`),s.push(`${this.use("node_normal_map_mix")}(${_}, ${d}, ${u([0])});`);break}case"ShaderNodeNewGeometry":{s.push(`${this.use("node_geometry")}(${["blender_orco()",u(a.map((l,_)=>_))].join(", ")});`),a[0]&&s.push(`${a[0].name} = ${this.d(a[0].name)};`);for(const l of[1,2,4])a[l]&&s.push(`${a[l].name} = normalize(${a[l].name});`);break}case"ShaderNodeTexImage":{const l=F(n,"image");if(l===null){s.push(`${u([0])} = vec4(0.0); ${u([1])} = 0.0;`);break}const _=F(n,"projection"),h=F(n,"interpolation"),d=h==="Cubic"||h==="Smart",m=F(n,"extension"),p=`bgImage${this.s.images.length}`;this.s.images.push({uniform:p,node:t,name:l.name,revision:l.revision,extension:m,closest:h==="Closest",mipmap:_!=="SPHERE"&&_!=="TUBE",tiled:_==="FLAT"&&n.props.image_tiled===!0});const v=this.s.images.at(-1).tiled;this.s.structure.push(["img",_,d,v]);let g=this.coordinate(n,"uv");const b=u([0]),w=u([1]);if(_==="BOX"){const O=`${r}_n`;s.push(`vec3 ${O}; ${this.use("world_normals_get")}(${O}); ${this.use("normal_transform_world_to_object")}(${O}, ${O});`,`vec4 ${r}_c1, ${r}_c2, ${r}_c3;`,`${this.use(d?"tex_box_sample_cubic":"tex_box_sample_linear")}(${g}, ${O}, ${p}, ${r}_c1, ${r}_c2, ${r}_c3);`,`${this.use("tex_box_blend")}(${O}, ${r}_c1, ${r}_c2, ${r}_c3, ${this.uniform("float",F(n,"projection_blend"))}, ${b}, ${w});`)}else if(v)d&&this.use("cubic_bspline_coefficients"),s.push(`${d?"blender_tex_tile_cubic":"blender_tex_tile_linear"}(${g}, ${p}, ${p}Map, ${b}, ${w});`);else{if(_==="SPHERE"||_==="TUBE"){const O=`${r}_co`;s.push(`vec3 ${O}; ${this.use("point_texco_remap_square")}(${g}, ${O});`,`${this.use(_==="SPHERE"?"point_map_to_sphere":"point_map_to_tube")}(${O}, ${O});`),g=O}s.push(`${this.use(d?"node_tex_image_cubic":"node_tex_image_linear")}(${g}, ${p}, ${b}, ${w});`),m==="CLIP"&&s.push(`if (any(lessThan(${g}.xy, vec2(0.0))) || any(greaterThan(${g}.xy, vec2(1.0)))) { ${b} = vec4(0.0); ${w} = 0.0; }`)}const R=F(n,"image_alpha_mode"),T=this.uses(t,1),A=u([0]);R==="NONE"||R==="CHANNEL_PACKED"||F(n,"image_is_data")?s.push(`${A}.a = 1.0;`):R==="PREMUL"?s.push(T?`if (${A}.a != 0.0 && ${A}.a != 1.0) ${A}.rgb /= ${A}.a;`:`${A}.a = 1.0;`):s.push(T?`${A}.a = 1.0;`:`${A}.rgb *= ${A}.a;`);break}}return this.lines.push(...s),a}uses(t,n){const e=a=>"link"in a&&a.link[0]===t&&a.link[1]===n,r=a=>a!==void 0&&("emission"in a?a.emission.some(e):"mix"in a?e(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(e)||Object.values(this.graph.nodes).some(a=>a.inputs.some(e))||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"},n={},e=[];let r=0;for(const[l,_]of Object.entries(t)){const h=this.graph.inputs[l];if(!h||l==="Normal"&&!("link"in h))continue;const d=`bgOut${r++}`;n[l]={global:d,type:_},this.s.structure.push(["out",l]),e.push(`${d} = ${this.source(h,_)};`)}const a=this.graph.closure;if(a){let l=0;const _=(h,d)=>{if("principled"in h)this.s.structure.push("cP"),e.push(`bgClosureP += ${d};`);else if("emission"in h)this.s.structure.push("cE"),e.push(`bgClosureE += ${d} * ${this.source(h.emission[0],"vec4")}.rgb * ${this.source(h.emission[1],"float")};`);else if("transparent"in h)this.s.structure.push("cT"),e.push(`bgClosureT += ${d} * ${this.source({value:h.transparent},"float")};`);else if("mix"in h){this.s.structure.push("cM");const m=`bgClosureF${l++}`;e.push(`float ${m} = clamp(${this.source(h.mix[0],"float")}, 0.0, 1.0);`),_(h.mix[1],`${d} * (1.0 - ${m})`),_(h.mix[2],`${d} * ${m}`)}else"add"in h?(this.s.structure.push("cA"),_(h.add[0],d),_(h.add[1],d)):this.s.structure.push("c0")};e.push("bgClosureP = 0.0;","bgClosureE = vec3(0.0);","bgClosureT = 0.0;"),_(a,"1.0")}const i=[],c=new Set,u=l=>{if(!c.has(l)){c.add(l);for(const _ of Zn[l].deps)u(_);i.push(l)}};for(const l of this.s.files)u(l);const f=`void blenderGraph() {
7025
7025
  blender_init_globals();
7026
7026
  ${[...this.lines,...e].join(`
7027
7027
  `)}
7028
- }`,r=[al,bl(gl+s.map(l=>$n[l].code).join(`
7028
+ }`,s=[Sr,Ur(jr+i.map(l=>Zn[l].code).join(`
7029
7029
  `)+`
7030
- `+xl,[...this.s.functions,f].join(`
7031
- `)),...[...this.s.uniformTypes].map(([l,m])=>`uniform ${m} ${l};`),...this.images.map(l=>l.tiled?`uniform highp sampler2DArray ${l.uniform};
7032
- uniform highp sampler2D ${l.uniform}Map;`:`uniform sampler2D ${l.uniform};`),...this.ramps.map(l=>`uniform sampler2D ${l.uniform};`),...Object.values(o).map(l=>`${l.type} ${l.global};`),...i?["float bgClosureP;","vec3 bgClosureE;","float bgClosureT;"]:[],...this.s.functions,f].join(`
7033
- `);return{key:JSON.stringify([this.graph.surface,this.s.structure,[...this.s.uvs].sort()]),declarations:r,uniforms:this.uniforms,images:this.images,ramps:this.ramps,uvs:[...this.s.uvs],attributes:[...this.s.attributes],outputs:o,surface:this.graph.surface,closure:i!==void 0}}}function bl(n,t){const o=[],e=/^[A-Za-z_][\w ]*?\b([A-Za-z_]\w*)\s*\(/gm;let a=0;for(let c;c=e.exec(n);){if(c.index<a)continue;let f=c.index+c[0].length;for(let h=1;f<n.length&&h>0;f++)h+=n[f]==="("?1:n[f]===")"?-1:0;const r=n.slice(f).match(/^\s*(\{|;)/);if(!r||/^\s*#/.test(n.slice(n.lastIndexOf(`
7034
- `,c.index)+1,c.index+1))||n.slice(Math.max(0,c.index-2),c.index).endsWith(`\\
7035
- `))continue;let m=f+r[0].length;if(r[1]==="{")for(let h=1;m<n.length&&h>0;m++)h+=n[m]==="{"?1:n[m]==="}"?-1:0;o.push({text:n.slice(a,c.index),name:null}),o.push({text:n.slice(c.index,m),name:c[1]}),a=m,e.lastIndex=m}o.push({text:n.slice(a),name:null});const i=new Set(o.filter(c=>c.name===null)),s=new Set,u=c=>{for(const f of c.matchAll(/[A-Za-z_]\w*/g))s.add(f[0])};u(t);for(const c of i)u(c.text);for(let c=!0;c;){c=!1;for(const f of o)i.has(f)||f.name===null||!s.has(f.name)||(i.add(f),u(f.text),c=!0)}return o.filter(c=>i.has(c)).map(c=>c.text).join("")}function Ln(n){return`v${Et(n)}`}function zt(n){return n===""?"vBlenderUvRender":`vBlenderUv_${[...n].map(t=>t.charCodeAt(0).toString(16)).join("")}`}function yl(n){return new Wn(n).compile()}function wl(n){const t=new Uint16Array(n.length*4);n.forEach((e,a)=>t.set([e[0]??0,e[1]??0,e[2]??0,e[3]??1].map(i=>Wt.toHalfFloat(i)),a*4));const o=new mn(t,n.length,1,dn,jn);return o.minFilter=o.magFilter=St,o.wrapS=o.wrapT=Mo,o.needsUpdate=!0,o}const et=new WeakMap,Yo=new Set,Pt=new WeakMap,nn=new WeakMap;function on(n){const t=Pt.get(n);if(t){Pt.delete(n);for(const o of t.binding.ramps)o.dispose()}}function Ol(n,t,o,e=!1){const a=et.get(n);if(t&&Yo.has(t.key)&&(t=null),!t){if(on(n),a){for(const u of a.ramps)u.dispose();et.delete(n),n.needsUpdate=!0}return}if(a&&a.compiled.key===t.key){on(n),en(a,t,o);return}if(e){on(n);for(const c of a?.ramps??[])c.dispose();const u={compiled:t,uniforms:{},ramps:[],channels:a?.channels??{}};en(u,t,o),et.set(n,u),n.needsUpdate=!0;return}const i=Pt.get(n);if(i&&i.binding.compiled.key===t.key){en(i.binding,t,o);return}on(n);const s={compiled:t,uniforms:{},ramps:[],channels:a?.channels??{}};en(s,t,o),Pt.set(n,{binding:s,started:!1})}function en(n,t,o){n.compiled=t;for(const[e,a]of t.uniforms){const i=typeof a=="number"?a:a.length===2?new _n(...a):a.length===3?new y(...a):new Eo(...a),s=n.uniforms[e];s?s.value=i:n.uniforms[e]={value:i}}for(const e of n.ramps)e.dispose();n.ramps=t.ramps.map(e=>{const a=wl(e.table);return(n.uniforms[e.uniform]??={value:null}).value=a,a});for(const e of t.images){const a=o(e);if(e.tiled){const i=a!==null&&"tiles"in a?a:null;(n.uniforms[e.uniform]??={value:null}).value=i?.tiles??null,(n.uniforms[`${e.uniform}Map`]??={value:null}).value=i?.map??null}else(n.uniforms[e.uniform]??={value:null}).value=a!==null&&"tiles"in a?null:a}}function Tl(n){const t=et.get(n);return t?`${t.compiled.key}|${JSON.stringify(t.channels)}`:""}function Pl(n){return Object.values(et.get(n)?.channels??{})}function go(n,t){const o=t.userData.blenderUvChannels,e=t.getAttribute("position")?.count??0,a={};for(const i of n.uvs){let s=i===""?0:o?.[i];s===void 0&&(s=9,t.getAttribute("uv9")?.count!==e&&t.setAttribute("uv9",new tt(new Float32Array(e*2),2))),a[i]=s}return a}function Al(n,t,o,e,a,i,s){const u=nn.get(n);u&&++u.draws>1&&(u.shadow.dispose(),nn.delete(n));const c=Pt.get(n);if(c&&!c.started){c.started=!0,c.binding.channels=go(c.binding.compiled,t);const m=s(n);et.set(m,c.binding);const h=new At(t,m);h.castShadow=i.castShadow,h.receiveShadow=i.receiveShadow;const d=()=>{if(Pt.get(n)!==c){m.dispose();return}Pt.delete(n);for(const _ of et.get(n)?.ramps??[])_.dispose();et.set(n,c.binding),n.needsUpdate=!0,nn.get(n)?.shadow.dispose(),nn.set(n,{shadow:m,draws:0}),Jt()};o.compileAsync(h,a,e).then(d,d)}const f=et.get(n);if(!f)return;const r=o.properties.get(n).currentProgram;if(r?.diagnostics?.runnable===!1&&r.cacheKey?.includes(f.compiled.key)){Yo.add(f.compiled.key),et.delete(n),n.needsUpdate=!0;const m=r.diagnostics.fragmentShader.log.split(`
7036
- `).find(h=>h.startsWith("ERROR"))??"";console.warn(`Blender material "${n.name}": its node graph did not compile for WebGL, so it is drawn with its constant values. ${m}`);return}const l=go(f.compiled,t);JSON.stringify(l)!==JSON.stringify(f.channels)&&(f.channels=l,n.needsUpdate=!0)}function Sl(n){const t=Array.isArray(n.material)?n.material:[n.material];if(!t.some(c=>c instanceof Qt&&et.has(c)))return;const o=n.geometry,e=n.userData.blenderTexspace??null,a=o.getAttribute("position"),i=JSON.stringify([e,a?.version??0,a?.count??0]);!o.userData.blenderOrcoFromDoor&&o.userData.blenderOrcoStamp!==i&&(o.setAttribute("blenderOrco",El(o,e)),o.userData.blenderOrcoStamp=i);const s=a?.count??0,u=n.userData.blenderDefaultColor;for(const c of t){const f=c instanceof Qt?et.get(c):void 0;for(const r of f?.compiled.attributes??[]){const l=Et(r),m=r===""?u===void 0?void 0:o.getAttribute(Et(u)):o.getAttribute(l);m&&m.count===s?o.getAttribute(l)!==m&&o.setAttribute(l,m):o.getAttribute(l)?.count!==s&&o.setAttribute(l,new tt(new Float32Array(s*4),4))}}}function El(n,t){const o=n.getAttribute("position");let e,a;if(t)e=[...t[0]],a=[...t[1]];else{n.computeBoundingBox();const s=n.boundingBox;e=[(s.min.x+s.max.x)/2,(s.min.y+s.max.y)/2,(s.min.z+s.max.z)/2],a=[(s.max.x-s.min.x)/2,(s.max.y-s.min.y)/2,(s.max.z-s.min.z)/2]}a=a.map(s=>s===0?1:s);const i=new Float32Array(o.count*3);for(let s=0;s<o.count;s++)i[s*3]=(o.getX(s)-e[0])/a[0]*.5+.5,i[s*3+1]=(o.getY(s)-e[1])/a[1]*.5+.5,i[s*3+2]=(o.getZ(s)-e[2])/a[2]*.5+.5;return new tt(i,3)}function Nl(n,t){const o=et.get(n);if(!o)return;const{compiled:e,channels:a}=o;Object.assign(t.uniforms,o.uniforms,{blenderViewport:{value:Zo}});const i=v=>v===0?"uv":`uv${v}`,s=`varying vec3 vBlenderObjectPosition;
7030
+ `+Br,[...this.s.functions,f].join(`
7031
+ `)),...[...this.s.uniformTypes].map(([l,_])=>`uniform ${_} ${l};`),...this.images.map(l=>l.tiled?`uniform highp sampler2DArray ${l.uniform};
7032
+ uniform highp sampler2D ${l.uniform}Map;`:`uniform sampler2D ${l.uniform};`),...this.ramps.map(l=>`uniform sampler2D ${l.uniform};`),...Object.values(n).map(l=>`${l.type} ${l.global};`),...a?["float bgClosureP;","vec3 bgClosureE;","float bgClosureT;"]:[],...this.s.functions,f].join(`
7033
+ `);return{key:JSON.stringify([this.graph.surface,this.s.structure,[...this.s.uvs].sort()]),declarations:s,uniforms:this.uniforms,images:this.images,ramps:this.ramps,uvs:[...this.s.uvs],attributes:[...this.s.attributes],outputs:n,surface:this.graph.surface,closure:a!==void 0}}}function Ur(o,t){const n=[],e=/^[A-Za-z_][\w ]*?\b([A-Za-z_]\w*)\s*\(/gm;let r=0;for(let u;u=e.exec(o);){if(u.index<r)continue;let f=u.index+u[0].length;for(let h=1;f<o.length&&h>0;f++)h+=o[f]==="("?1:o[f]===")"?-1:0;const s=o.slice(f).match(/^\s*(\{|;)/);if(!s||/^\s*#/.test(o.slice(o.lastIndexOf(`
7034
+ `,u.index)+1,u.index+1))||o.slice(Math.max(0,u.index-2),u.index).endsWith(`\\
7035
+ `))continue;let _=f+s[0].length;if(s[1]==="{")for(let h=1;_<o.length&&h>0;_++)h+=o[_]==="{"?1:o[_]==="}"?-1:0;n.push({text:o.slice(r,u.index),name:null}),n.push({text:o.slice(u.index,_),name:u[1]}),r=_,e.lastIndex=_}n.push({text:o.slice(r),name:null});const a=new Set(n.filter(u=>u.name===null)),i=new Set,c=u=>{for(const f of u.matchAll(/[A-Za-z_]\w*/g))i.add(f[0])};c(t);for(const u of a)c(u.text);for(let u=!0;u;){u=!1;for(const f of n)a.has(f)||f.name===null||!i.has(f.name)||(a.add(f),c(f.text),u=!0)}return n.filter(u=>a.has(u)).map(u=>u.text).join("")}function Qn(o){return`v${Vt(o)}`}function Ht(o){return o===""?"vBlenderUvRender":`vBlenderUv_${[...o].map(t=>t.charCodeAt(0).toString(16)).join("")}`}function Wr(o){return new lo(o).compile()}function Hr(o){const t=new Uint16Array(o.length*4);o.forEach((e,r)=>t.set([e[0]??0,e[1]??0,e[2]??0,e[3]??1].map(a=>nn.toHalfFloat(a)),r*4));const n=new Tn(t,o.length,1,Pn,to);return n.minFilter=n.magFilter=Lt,n.wrapS=n.wrapT=Zo,n.needsUpdate=!0,n}const dt=new WeakMap,ve=new Set,kt=new WeakMap,un=new WeakMap;function _n(o){const t=kt.get(o);if(t){kt.delete(o);for(const n of t.binding.ramps)n.dispose()}}function qr(o,t,n,e=!1){const r=dt.get(o);if(t&&ve.has(t.key)&&(t=null),!t){if(_n(o),r){for(const c of r.ramps)c.dispose();dt.delete(o),o.needsUpdate=!0}return}if(r&&r.compiled.key===t.key){_n(o),mn(r,t,n);return}if(e){_n(o);for(const u of r?.ramps??[])u.dispose();const c={compiled:t,uniforms:{},ramps:[],channels:r?.channels??{}};mn(c,t,n),dt.set(o,c),o.needsUpdate=!0;return}const a=kt.get(o);if(a&&a.binding.compiled.key===t.key){mn(a.binding,t,n);return}_n(o);const i={compiled:t,uniforms:{},ramps:[],channels:r?.channels??{}};mn(i,t,n),kt.set(o,{binding:i,started:!1})}function mn(o,t,n){o.compiled=t;for(const[e,r]of t.uniforms){const a=typeof r=="number"?r:r.length===2?new $t(...r):r.length===3?new x(...r):new Jn(...r),i=o.uniforms[e];i?i.value=a:o.uniforms[e]={value:a}}for(const e of o.ramps)e.dispose();o.ramps=t.ramps.map(e=>{const r=Hr(e.table);return(o.uniforms[e.uniform]??={value:null}).value=r,r});for(const e of t.images){const r=n(e);if(e.tiled){const a=r!==null&&"tiles"in r?r:null;(o.uniforms[e.uniform]??={value:null}).value=a?.tiles??null,(o.uniforms[`${e.uniform}Map`]??={value:null}).value=a?.map??null}else(o.uniforms[e.uniform]??={value:null}).value=r!==null&&"tiles"in r?null:r}}function Gr(o){const t=dt.get(o);return t?`${t.compiled.key}|${JSON.stringify(t.channels)}`:""}function Xr(o){return Object.values(dt.get(o)?.channels??{})}function Fo(o,t){const n=t.userData.blenderUvChannels,e=t.getAttribute("position")?.count??0,r={};for(const a of o.uvs){let i=a===""?0:n?.[a];i===void 0&&(i=9,t.getAttribute("uv9")?.count!==e&&t.setAttribute("uv9",new it(new Float32Array(e*2),2))),r[a]=i}return r}function Yr(o,t,n,e,r,a,i){const c=un.get(o);c&&++c.draws>1&&(c.shadow.dispose(),un.delete(o));const u=kt.get(o);if(u&&!u.started){u.started=!0,u.binding.channels=Fo(u.binding.compiled,t);const _=i(o);dt.set(_,u.binding);const h=new Tt(t,_);h.castShadow=a.castShadow,h.receiveShadow=a.receiveShadow;const d=()=>{if(kt.get(o)!==u){_.dispose();return}kt.delete(o);for(const m of dt.get(o)?.ramps??[])m.dispose();dt.set(o,u.binding),o.needsUpdate=!0,un.get(o)?.shadow.dispose(),un.set(o,{shadow:_,draws:0}),vt()};n.compileAsync(h,r,e).then(d,d)}const f=dt.get(o);if(!f)return;const s=n.properties.get(o).currentProgram;if(s?.diagnostics?.runnable===!1&&s.cacheKey?.includes(f.compiled.key)){ve.add(f.compiled.key),dt.delete(o),o.needsUpdate=!0;const _=s.diagnostics.fragmentShader.log.split(`
7036
+ `).find(h=>h.startsWith("ERROR"))??"";console.warn(`Blender material "${o.name}": its node graph did not compile for WebGL, so it is drawn with its constant values. ${_}`);return}const l=Fo(f.compiled,t);JSON.stringify(l)!==JSON.stringify(f.channels)&&(f.channels=l,o.needsUpdate=!0)}function Zr(o){const t=Array.isArray(o.material)?o.material:[o.material];if(!t.some(u=>u instanceof ln&&dt.has(u)))return;const n=o.geometry,e=o.userData.blenderTexspace??null,r=n.getAttribute("position"),a=JSON.stringify([e,r?.version??0,r?.count??0]);!n.userData.blenderOrcoFromDoor&&n.userData.blenderOrcoStamp!==a&&(n.setAttribute("blenderOrco",Qr(n,e)),n.userData.blenderOrcoStamp=a);const i=r?.count??0,c=o.userData.blenderDefaultColor;for(const u of t){const f=u instanceof ln?dt.get(u):void 0;for(const s of f?.compiled.attributes??[]){const l=Vt(s),_=s===""?c===void 0?void 0:n.getAttribute(Vt(c)):n.getAttribute(l);_&&_.count===i?n.getAttribute(l)!==_&&n.setAttribute(l,_):n.getAttribute(l)?.count!==i&&n.setAttribute(l,new it(new Float32Array(i*4),4))}}}function Qr(o,t){const n=o.getAttribute("position");let e,r;if(t)e=[...t[0]],r=[...t[1]];else{o.computeBoundingBox();const i=o.boundingBox;e=[(i.min.x+i.max.x)/2,(i.min.y+i.max.y)/2,(i.min.z+i.max.z)/2],r=[(i.max.x-i.min.x)/2,(i.max.y-i.min.y)/2,(i.max.z-i.min.z)/2]}r=r.map(i=>i===0?1:i);const a=new Float32Array(n.count*3);for(let i=0;i<n.count;i++)a[i*3]=(n.getX(i)-e[0])/r[0]*.5+.5,a[i*3+1]=(n.getY(i)-e[1])/r[1]*.5+.5,a[i*3+2]=(n.getZ(i)-e[2])/r[2]*.5+.5;return new it(a,3)}function Kr(o,t){const n=dt.get(o);if(!n)return;const{compiled:e,channels:r}=n;Object.assign(t.uniforms,n.uniforms,{blenderViewport:{value:ge}});const a=v=>v===0?"uv":`uv${v}`,i=`varying vec3 vBlenderObjectPosition;
7037
7037
  varying vec3 vBlenderObjectNormal;
7038
7038
  varying vec3 vBlenderWorldPosition;
7039
7039
  varying vec3 vBlenderWorldNormal;
7040
7040
  varying vec3 vBlenderOrco;
7041
- ${e.attributes.map(v=>`varying vec4 ${Ln(v)};`).join(`
7041
+ ${e.attributes.map(v=>`varying vec4 ${Qn(v)};`).join(`
7042
7042
  `)}
7043
- ${e.uvs.map(v=>`varying vec2 ${zt(v)};`).join(`
7044
- `)}`,u=e.attributes.map(v=>`attribute vec4 ${Et(v)};`).join(`
7043
+ ${e.uvs.map(v=>`varying vec2 ${Ht(v)};`).join(`
7044
+ `)}`,c=e.attributes.map(v=>`attribute vec4 ${Vt(v)};`).join(`
7045
7045
  `);t.vertexShader=`attribute vec3 blenderOrco;
7046
- ${u}
7047
- ${s}
7046
+ ${c}
7047
+ ${i}
7048
7048
  ${t.vertexShader}`.replace("#include <project_vertex>",`vBlenderObjectPosition = transformed;
7049
7049
  vBlenderObjectNormal = objectNormal;
7050
7050
  vBlenderWorldPosition = (modelMatrix * vec4(transformed, 1.0)).xyz;
7051
7051
  vBlenderWorldNormal = normalize(transpose(inverse(mat3(modelMatrix))) * objectNormal);
7052
7052
  vBlenderOrco = blenderOrco;
7053
- ${e.attributes.map(v=>`${Ln(v)} = ${Et(v)};`).join(`
7053
+ ${e.attributes.map(v=>`${Qn(v)} = ${Vt(v)};`).join(`
7054
7054
  `)}
7055
- ${e.uvs.map(v=>`${zt(v)} = ${i(a[v]??0)};`).join(`
7055
+ ${e.uvs.map(v=>`${Ht(v)} = ${a(r[v]??0)};`).join(`
7056
7056
  `)}
7057
- #include <project_vertex>`);const c=v=>e.outputs[v]?.global,f=[];e.surface==="ShaderNodeEmission"?(f.push(["#include <color_fragment>","diffuseColor = vec4(0.0, 0.0, 0.0, 1.0);",!1]),f.push(["#include <emissivemap_fragment>",`totalEmissiveRadiance = ${c("Color")}.rgb * ${c("Strength")};`,!1]),f.push(["#include <opaque_fragment>","outgoingLight = totalEmissiveRadiance;",!0])):e.surface==="closure"?(f.push(["#include <color_fragment>","diffuseColor = vec4(0.0, 0.0, 0.0, 1.0);",!1]),f.push(["#include <emissivemap_fragment>","totalEmissiveRadiance = vec3(0.0);",!1])):(f.push(["#include <color_fragment>",`diffuseColor.rgb = ${c("Base Color")}.rgb;`,!1]),f.push(["#include <alphamap_fragment>",`diffuseColor.a = ${c("Alpha")};`,!1]),f.push(["#include <metalnessmap_fragment>",`roughnessFactor = ${c("Roughness")};`,!0]),f.push(["#include <metalnessmap_fragment>",`metalnessFactor = ${c("Metallic")};`,!1]),f.push(["#include <emissivemap_fragment>",`totalEmissiveRadiance = ${c("Emission Color")}.rgb * ${c("Emission Strength")};`,!1]),c("Normal")&&f.push(["#include <clearcoat_normal_fragment_begin>",`normal = normalize((viewMatrix * vec4(transpose(blender_from_three) * ${c("Normal")}, 0.0)).xyz);`,!0])),e.closure&&f.push(["#include <opaque_fragment>",`{
7057
+ #include <project_vertex>`);const u=v=>e.outputs[v]?.global,f=[];e.surface==="ShaderNodeEmission"?(f.push(["#include <color_fragment>","diffuseColor = vec4(0.0, 0.0, 0.0, 1.0);",!1]),f.push(["#include <emissivemap_fragment>",`totalEmissiveRadiance = ${u("Color")}.rgb * ${u("Strength")};`,!1]),f.push(["#include <opaque_fragment>","outgoingLight = totalEmissiveRadiance;",!0])):e.surface==="closure"?(f.push(["#include <color_fragment>","diffuseColor = vec4(0.0, 0.0, 0.0, 1.0);",!1]),f.push(["#include <emissivemap_fragment>","totalEmissiveRadiance = vec3(0.0);",!1])):(f.push(["#include <color_fragment>",`diffuseColor.rgb = ${u("Base Color")}.rgb;`,!1]),f.push(["#include <alphamap_fragment>",`diffuseColor.a = ${u("Alpha")};`,!1]),f.push(["#include <metalnessmap_fragment>",`roughnessFactor = ${u("Roughness")};`,!0]),f.push(["#include <metalnessmap_fragment>",`metalnessFactor = ${u("Metallic")};`,!1]),f.push(["#include <emissivemap_fragment>",`totalEmissiveRadiance = ${u("Emission Color")}.rgb * ${u("Emission Strength")};`,!1]),u("Normal")&&f.push(["#include <clearcoat_normal_fragment_begin>",`normal = normalize((viewMatrix * vec4(transpose(blender_from_three) * ${u("Normal")}, 0.0)).xyz);`,!0])),e.closure&&f.push(["#include <opaque_fragment>",`{
7058
7058
  float blenderCoverage = diffuseColor.a;
7059
7059
  vec3 blenderRadiance = bgClosureP * blenderCoverage * outgoingLight + bgClosureE;
7060
7060
  float blenderAlpha = 1.0 - min(bgClosureT + bgClosureP * (1.0 - blenderCoverage), 1.0);
@@ -7064,17 +7064,17 @@ ${e.uvs.map(v=>`${zt(v)} = ${i(a[v]??0)};`).join(`
7064
7064
  outgoingLight = blenderRadiance / max(blenderAlpha, 1e-4);
7065
7065
  #endif
7066
7066
  diffuseColor.a = blenderAlpha;
7067
- }`,!0]);const r=v=>v.replace(/^[ \t]*#include <(\w+)>/gm,(g,b)=>r(yt[b]??"")),l=r(t.fragmentShader.slice(0,t.fragmentShader.indexOf("void main() {"))),m=new Map([...l.matchAll(/^[ \t]*#define[ \t]+(\w+).*$/gm)].map(v=>[v[1],v[0].trim()])),d=[...new Set([...e.declarations.matchAll(/^[ \t]*#define[ \t]+(\w+)/gm)].map(v=>v[1]))].filter(v=>m.has(v)),_=[...d.map(v=>`#undef ${v}`),e.declarations,...d.flatMap(v=>[`#undef ${v}`,m.get(v)])].join(`
7068
- `);let p=t.fragmentShader.replace("void main() {",`${s}
7069
- ${_}
7067
+ }`,!0]);const s=v=>v.replace(/^[ \t]*#include <(\w+)>/gm,(g,b)=>s(zt[b]??"")),l=s(t.fragmentShader.slice(0,t.fragmentShader.indexOf("void main() {"))),_=new Map([...l.matchAll(/^[ \t]*#define[ \t]+(\w+).*$/gm)].map(v=>[v[1],v[0].trim()])),d=[...new Set([...e.declarations.matchAll(/^[ \t]*#define[ \t]+(\w+)/gm)].map(v=>v[1]))].filter(v=>_.has(v)),m=[...d.map(v=>`#undef ${v}`),e.declarations,...d.flatMap(v=>[`#undef ${v}`,_.get(v)])].join(`
7068
+ `);let p=t.fragmentShader.replace("void main() {",`${i}
7069
+ ${m}
7070
7070
  void main() {`).replace("#include <clipping_planes_fragment>",`#include <clipping_planes_fragment>
7071
7071
  blenderGraph();`);for(const[v,g,b]of f){if(!p.includes(v))throw new Error(`three's physical shader has no ${v}`);p=p.replace(v,b?`${g}
7072
7072
  ${v}`:`${v}
7073
- ${g}`)}t.fragmentShader=p}const Zo=new _n(1,1);function Ml(n){n.getDrawingBufferSize(Zo)}function Rl(n,t){const o=t.userData.blenderUvChannels;for(const e of[n.map,n.roughnessMap,n.normalMap]){if(!e)continue;const a=e.userData.blenderUvName;let i=a?o?.[a]:0;if(i===void 0){i=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 tt(new Float32Array(s*2),2))}e.channel!==i&&(e.channel=i,n.needsUpdate=!0)}}class Il{constructor(){this.bindings=new Map}get(t,o,e,a,i=""){let s=this.bindings.get(t);if(!s||s.source!==o){this.delete(t),s={source:o,texture:o.clone(),version:-1,disposed:!1},this.bindings.set(t,s);const f=s;a&&a.then(()=>{f.disposed||(f.texture.needsUpdate=!0,f.version=o.version,Jt())},()=>{})}const u=e==="REPEAT"?ve:e==="MIRROR"?ge:Mo,c=s.texture.wrapS!==u||s.texture.wrapT!==u;return s.texture.wrapS=s.texture.wrapT=u,s.texture.userData.blenderUvName=i,o.image&&(c||s.version!==o.version)&&(s.texture.needsUpdate=!0,s.version=o.version),s.texture}delete(t){const o=this.bindings.get(t);o&&(o.disposed=!0,o.texture.dispose(),this.bindings.delete(t))}clear(){for(const t of this.bindings.keys())this.delete(t)}}const ot=R().finite(),Tn=j([ot,ot,ot]),Fl=O({coat:ot,coat_roughness:ot,coat_ior:ot,coat_tint:Tn,sheen:ot,sheen_roughness:ot,sheen_tint:Tn,anisotropy:ot,anisotropy_rotation:ot,specular_level:ot,specular_tint:Tn,film_thickness:ot,film_ior:ot}).strict(),zl={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},kt=new WeakMap;function Dl(n,t){kt.has(n)||Gn(n),kt.get(n).blenderWorldExtinction.value.copy(t)}function Cl(n){const t=new Qt,o=kt.get(n);Gn(t),t.copy(n);const e=kt.get(t);return o&&(e.blenderCoatIor.value=o.blenderCoatIor.value,e.blenderCoatTint.value.copy(o.blenderCoatTint.value),e.blenderMapClip.value=o.blenderMapClip.value,e.blenderRoughnessClip.value=o.blenderRoughnessClip.value,e.blenderNormalClip.value=o.blenderNormalClip.value,e.blenderWorldExtinction.value.copy(o.blenderWorldExtinction.value)),t}function Gn(n,t,o={}){const e=t??zl;n.clearcoat=e.coat,n.clearcoatRoughness=e.coat_roughness,n.sheen=e.sheen,n.sheenRoughness=e.sheen_roughness,n.sheenColor.setRGB(...e.sheen_tint,at),n.anisotropy=e.anisotropy,n.anisotropyRotation=e.anisotropy_rotation*Math.PI*2,n.specularIntensity=e.specular_level*2,n.specularColor.setRGB(...e.specular_tint,at),n.iridescence=e.film_thickness>0?1:0,n.iridescenceIOR=e.film_ior,n.iridescenceThicknessRange=[e.film_thickness,e.film_thickness];let a=kt.get(n);if(!a){a={blenderCoatIor:{value:1.5},blenderCoatTint:{value:new gt(1,1,1)},blenderMapClip:{value:!1},blenderRoughnessClip:{value:!1},blenderNormalClip:{value:!1},blenderWorldExtinction:{value:new y}},kt.set(n,a);const i=a;n.customProgramCacheKey=()=>`blender-principled-physical-v5${Tl(n)}`,n.onBeforeRender=(s,u,c,f,r)=>{Rl(n,f),Al(n,f,s,u,c,r,Cl),Ml(s)},n.onBeforeCompile=s=>{const u=new Set([n.map,n.roughnessMap,n.normalMap].flatMap(d=>d?[d.channel]:[]).concat(Pl(n)));s.vertexShader=[...u].filter(d=>d>0).sort((d,_)=>d-_).map(d=>d<=3?`#ifndef USE_UV${d}
7073
+ ${g}`)}t.fragmentShader=p}const ge=new $t(1,1);function Jr(o){o.getDrawingBufferSize(ge)}function tl(o,t){const n=t.userData.blenderUvChannels;for(const e of[o.map,o.roughnessMap,o.normalMap]){if(!e)continue;const r=e.userData.blenderUvName;let a=r?n?.[r]:0;if(a===void 0){a=9;const i=t.getAttribute("position")?.count;if(i===void 0)throw new Error("A textured Blender draw has no positions");t.getAttribute("uv9")?.count!==i&&t.setAttribute("uv9",new it(new Float32Array(i*2),2))}e.channel!==a&&(e.channel=a,o.needsUpdate=!0)}}class nl{constructor(){this.bindings=new Map}get(t,n,e,r,a=""){let i=this.bindings.get(t);if(!i||i.source!==n){this.delete(t),i={source:n,texture:n.clone(),version:-1,disposed:!1},this.bindings.set(t,i);const f=i;r&&r.then(()=>{f.disposed||(f.texture.needsUpdate=!0,f.version=n.version,vt())},()=>{})}const c=e==="REPEAT"?Ce:e==="MIRROR"?ke:Zo,u=i.texture.wrapS!==c||i.texture.wrapT!==c;return i.texture.wrapS=i.texture.wrapT=c,i.texture.userData.blenderUvName=a,n.image&&(u||i.version!==n.version)&&(i.texture.needsUpdate=!0,i.version=n.version),i.texture}delete(t){const n=this.bindings.get(t);n&&(n.disposed=!0,n.texture.dispose(),this.bindings.delete(t))}clear(){for(const t of this.bindings.keys())this.delete(t)}}const mt=S().finite(),Dn=$([mt,mt,mt]),ol=P({coat:mt,coat_roughness:mt,coat_ior:mt,coat_tint:Dn,sheen:mt,sheen_roughness:mt,sheen_tint:Dn,anisotropy:mt,anisotropy_rotation:mt,specular_level:mt,specular_tint:Dn,film_thickness:mt,film_ior:mt}).strict(),el={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},Xt=new WeakMap;function al(o,t){Xt.has(o)||io(o),Xt.get(o).blenderWorldExtinction.value.copy(t)}function rl(o){const t=new ln,n=Xt.get(o);io(t),t.copy(o);const e=Xt.get(t);return n&&(e.blenderCoatIor.value=n.blenderCoatIor.value,e.blenderCoatTint.value.copy(n.blenderCoatTint.value),e.blenderMapClip.value=n.blenderMapClip.value,e.blenderRoughnessClip.value=n.blenderRoughnessClip.value,e.blenderNormalClip.value=n.blenderNormalClip.value,e.blenderWorldExtinction.value.copy(n.blenderWorldExtinction.value)),t}function io(o,t,n={}){const e=t??el;o.clearcoat=e.coat,o.clearcoatRoughness=e.coat_roughness,o.sheen=e.sheen,o.sheenRoughness=e.sheen_roughness,o.sheenColor.setRGB(...e.sheen_tint,ft),o.anisotropy=e.anisotropy,o.anisotropyRotation=e.anisotropy_rotation*Math.PI*2,o.specularIntensity=e.specular_level*2,o.specularColor.setRGB(...e.specular_tint,ft),o.iridescence=e.film_thickness>0?1:0,o.iridescenceIOR=e.film_ior,o.iridescenceThicknessRange=[e.film_thickness,e.film_thickness];let r=Xt.get(o);if(!r){r={blenderCoatIor:{value:1.5},blenderCoatTint:{value:new ht(1,1,1)},blenderMapClip:{value:!1},blenderRoughnessClip:{value:!1},blenderNormalClip:{value:!1},blenderWorldExtinction:{value:new x}},Xt.set(o,r);const a=r;o.customProgramCacheKey=()=>`blender-principled-physical-v5${Gr(o)}`,o.onBeforeRender=(i,c,u,f,s)=>{tl(o,f),Yr(o,f,i,c,u,s,rl),Jr(i)},o.onBeforeCompile=i=>{const c=new Set([o.map,o.roughnessMap,o.normalMap].flatMap(d=>d?[d.channel]:[]).concat(Xr(o)));i.vertexShader=[...c].filter(d=>d>0).sort((d,m)=>d-m).map(d=>d<=3?`#ifndef USE_UV${d}
7074
7074
  attribute vec2 uv${d};
7075
7075
  #endif`:`attribute vec2 uv${d};`).join(`
7076
7076
  `)+`
7077
- `+s.vertexShader,Object.assign(s.uniforms,i),s.fragmentShader=`uniform float blenderCoatIor;
7077
+ `+i.vertexShader,Object.assign(i.uniforms,a),i.fragmentShader=`uniform float blenderCoatIor;
7078
7078
  uniform vec3 blenderWorldExtinction;
7079
7079
  vec3 blenderInfiniteTransmission() { return vec3(
7080
7080
  blenderWorldExtinction.x>0.?0.:1., blenderWorldExtinction.y>0.?0.:1., blenderWorldExtinction.z>0.?0.:1.); }
@@ -7085,36 +7085,36 @@ attribute vec2 uv${d};
7085
7085
  if (clipImage && (any(lessThan(uv, vec2(0.0))) || any(greaterThan(uv, vec2(1.0))))) pixel = vec4(0.0);
7086
7086
  return pixel;
7087
7087
  }
7088
- `+s.fragmentShader;const c=yt.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 ) ) );"),f=yt.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)"),r=yt.map_fragment.replace("texture2D( map, vMapUv )","blenderImageSample(map, vMapUv, blenderMapClip)").replace("diffuseColor *= sampledDiffuseColor;","diffuseColor.rgb *= sampledDiffuseColor.rgb;"),l=yt.roughnessmap_fragment.replace("texture2D( roughnessMap, vRoughnessMapUv )","blenderImageSample(roughnessMap, vRoughnessMapUv, blenderRoughnessClip)"),m=yt.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()"),h=yt.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>",m).replace("#include <lights_fragment_maps>",h).replace("#include <normal_fragment_maps>",f).replace("#include <map_fragment>",r).replace("#include <roughnessmap_fragment>",l).replace("vec3 Fcc = F_Schlick",`
7088
+ `+i.fragmentShader;const u=zt.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 ) ) );"),f=zt.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)"),s=zt.map_fragment.replace("texture2D( map, vMapUv )","blenderImageSample(map, vMapUv, blenderMapClip)").replace("diffuseColor *= sampledDiffuseColor;","diffuseColor.rgb *= sampledDiffuseColor.rgb;"),l=zt.roughnessmap_fragment.replace("texture2D( roughnessMap, vRoughnessMapUv )","blenderImageSample(roughnessMap, vRoughnessMapUv, blenderRoughnessClip)"),_=zt.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()"),h=zt.lights_fragment_maps.replaceAll(/(getIBL(?:Irradiance|Radiance|AnisotropyRadiance)\([^;]+\))/g,"$1 * blenderInfiniteTransmission()");i.fragmentShader=i.fragmentShader.replace("#include <lights_physical_fragment>",u).replace("#include <lights_fragment_begin>",_).replace("#include <lights_fragment_maps>",h).replace("#include <normal_fragment_maps>",f).replace("#include <map_fragment>",s).replace("#include <roughnessmap_fragment>",l).replace("vec3 Fcc = F_Schlick",`
7089
7089
  // Blender's slab_transmittance_at_angle (gpu_shader_material_principled.glsl):
7090
7090
  // Beer-Lambert attenuation through a refracting coat at this view angle.
7091
7091
  float coatPath = blenderCoatIor * inversesqrt(max(1e-8,
7092
7092
  blenderCoatIor * blenderCoatIor - (1.0 - dotNVcc * dotNVcc)));
7093
7093
  outgoingLight *= mix(vec3(1.0), pow(max(blenderCoatTint, vec3(0.0)), vec3(coatPath)), material.clearcoat);
7094
- vec3 Fcc = F_Schlick`),Nl(n,s)},n.needsUpdate=!0}a.blenderCoatIor.value=Math.max(1,e.coat_ior),a.blenderCoatTint.value.setRGB(...e.coat_tint,at),a.blenderMapClip.value=o.map===!0,a.blenderRoughnessClip.value=o.roughness===!0,a.blenderNormalClip.value=o.normal===!0}function Xn(n){const t=a=>{if(!(!a||typeof a!="object")){if("kind"in a&&["direction","window","sky"].includes(String(a.kind)))throw new Error(`World volume spatial input ${a.kind} is not implemented`);for(const i of Object.values(a))t(i)}};t(n);const o=Z(n)(new y);if(!(typeof o=="number"?[o]:o.toArray()).every(Number.isFinite))throw new Error("World volume input is not finite");return o}function Rt(n){const t=Xn(n);if(typeof t!="number")throw new Error("World volume scalar input resolved to a color");return Math.max(0,t)}function an(n){const t=Xn(n);return(typeof t=="number"?new y().setScalar(t):t.clone()).max(new y)}function kl(n){if(n<800)return new y(5.413294490189271,0,0);if(n>=12e3)return new y(.8262954810464208,.9945080501520986,1.566307710274283);const t=[965,1167,1449,1902,3315,6365].filter(i=>n>=i).length,o=[[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],e=[[-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],a=[[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 y(o[0]/n+o[1]*n+o[2],e[0]/n+e[1]*n+e[2],((a[0]*n+a[1])*n+a[2])*n+a[3]).max(new y)}function xo(n){if(!n?.volume?.length)return null;const t={extinction:new y,emission:new y,lobes:[]};for(const o of n.volume){const e=Rt(o.weight);if(e===0)continue;const a=an(o.color),i=Rt(o.density),s=new y,u=new y;if(o.kind==="absorption"&&s.set(1-a.x,1-a.y,1-a.z).max(new y).multiplyScalar(i),o.kind==="scatter"||o.kind==="principled"){u.copy(a).multiplyScalar(i);const c=o.kind==="principled"?"HENYEY_GREENSTEIN":o.phase;if(!["HENYEY_GREENSTEIN","DRAINE","RAYLEIGH"].includes(c))throw new Error(`World volume ${c} phase is not implemented`);const f=Xn(o.anisotropy);if(typeof f!="number")throw new Error("World volume anisotropy must be scalar");t.lobes.push({coefficient:u.clone().multiplyScalar(e),g:c==="RAYLEIGH"?0:it.clamp(f,-.999,.999),alpha:c==="RAYLEIGH"?1:c==="DRAINE"?Rt(o.alpha):0})}if(o.kind==="principled"){const c=an(o.absorption_color);s.set(Math.max(1-a.x,0)*Math.max(1-Math.sqrt(c.x),0),Math.max(1-a.y,0)*Math.max(1-Math.sqrt(c.y),0),Math.max(1-a.z,0)*Math.max(1-Math.sqrt(c.z),0)).multiplyScalar(i);const f=Rt(o.blackbody_intensity);if(f>.001){const r=Rt(o.temperature),l=5670373e-20/Math.PI*(1+f*(r**4-1));t.emission.add(kl(r).multiply(an(o.blackbody_tint)).multiplyScalar(l*e))}}(o.kind==="principled"||o.kind==="emission")&&t.emission.add((o.kind==="emission"?a:an(o.emission_color)).multiplyScalar(Rt(o.emission_strength)*e)),t.extinction.add(s.add(u).multiplyScalar(e))}for(const o of["x","y","z"])if(t.extinction[o]===0&&t.emission[o]>0)throw new Error("Unbounded emissive World volume with zero extinction has divergent radiance");return t}class $l{constructor(t){this.medium=t,this.target=new xe(1,1,{type:jn,depthBuffer:!1}),this.geometry=new be(2,2),this.scene=new ye,this.camera=new we}render(t,o,e,a){if(!o.depthTexture)throw new Error("World volume render requires surface depth");const i={surface:{value:o.texture},depth:{value:o.depthTexture},inverseProjection:{value:a.projectionMatrixInverse},cameraWorld:{value:a.matrixWorld},orthographic:{value:a.isOrthographicCamera===!0},sigma:{value:this.medium.extinction},emission:{value:this.medium.emission}};let s="",u="",c=0,f=2;e.traverseVisible(h=>{if(!(h instanceof Sn||h instanceof En||h instanceof rn))return;const d=h,_=c++,p=d.getWorldPosition(new y);i[`lp${_}`]={value:p},i[`lc${_}`]={value:d.color.clone().multiplyScalar(d.intensity)},s+=`uniform vec3 lp${_}, lc${_};
7095
- `;let v="1.0",g="1.0";if(d instanceof En&&(i[`ld${_}`]={value:d.target.getWorldPosition(new y).sub(p).normalize()},i[`cone${_}`]={value:new _n(Math.cos(d.angle),Math.cos(d.angle*(1-d.penumbra)))},s+=`uniform vec3 ld${_}; uniform vec2 cone${_};
7096
- `,g=`smoothstep(cone${_}.x, max(cone${_}.x+1e-6,cone${_}.y),dot(-L,ld${_}))`),!(d instanceof rn)&&d.castShadow&&d.shadow.map){if(++f>t.capabilities.maxTextures)throw new Error("World volume shadow samplers exceed this GPU texture-unit limit");i[`sm${_}`]={value:d.shadow.map.texture},i[`sx${_}`]={value:d.shadow.matrix},i[`ss${_}`]={value:d.shadow.mapSize},i[`sb${_}`]={value:d.shadow.bias},i[`sn${_}`]={value:d.shadow.camera.near},i[`sf${_}`]={value:d.shadow.camera.far},s+=`uniform sampler2D sm${_}; uniform mat4 sx${_}; uniform vec2 ss${_}; uniform float sb${_},sn${_},sf${_};
7097
- `,v=d instanceof Sn?`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(d instanceof rn){const b=new mt().extractRotation(d.matrixWorld);i[`lx${_}`]={value:new y(d.width,0,0).applyMatrix4(b)},i[`ly${_}`]={value:new y(0,d.height,0).applyMatrix4(b)},i[`ln${_}`]={value:new y(0,0,-1).transformDirection(b)},s+=`uniform vec3 lx${_},ly${_},ln${_};
7098
- `,u+=`for(int ax=0;ax<4;ax++) for(int ay=0;ay<4;ay++) {
7099
- vec3 delta=lp${_}+lx${_}*((float(ax)+.5)/4.-.5)+ly${_}*((float(ay)+.5)/4.-.5)-p;
7094
+ vec3 Fcc = F_Schlick`),Kr(o,i)},o.needsUpdate=!0}r.blenderCoatIor.value=Math.max(1,e.coat_ior),r.blenderCoatTint.value.setRGB(...e.coat_tint,ft),r.blenderMapClip.value=n.map===!0,r.blenderRoughnessClip.value=n.roughness===!0,r.blenderNormalClip.value=n.normal===!0}function so(o){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(o);const n=nt(o)(new x);if(!(typeof n=="number"?[n]:n.toArray()).every(Number.isFinite))throw new Error("World volume input is not finite");return n}function Bt(o){const t=so(o);if(typeof t!="number")throw new Error("World volume scalar input resolved to a color");return Math.max(0,t)}function dn(o){const t=so(o);return(typeof t=="number"?new x().setScalar(t):t.clone()).max(new x)}function ll(o){if(o<800)return new x(5.413294490189271,0,0);if(o>=12e3)return new x(.8262954810464208,.9945080501520986,1.566307710274283);const t=[965,1167,1449,1902,3315,6365].filter(a=>o>=a).length,n=[[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],e=[[-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 x(n[0]/o+n[1]*o+n[2],e[0]/o+e[1]*o+e[2],((r[0]*o+r[1])*o+r[2])*o+r[3]).max(new x)}function Do(o){if(!o?.volume?.length)return null;const t={extinction:new x,emission:new x,lobes:[]};for(const n of o.volume){const e=Bt(n.weight);if(e===0)continue;const r=dn(n.color),a=Bt(n.density),i=new x,c=new x;if(n.kind==="absorption"&&i.set(1-r.x,1-r.y,1-r.z).max(new x).multiplyScalar(a),n.kind==="scatter"||n.kind==="principled"){c.copy(r).multiplyScalar(a);const u=n.kind==="principled"?"HENYEY_GREENSTEIN":n.phase;if(!["HENYEY_GREENSTEIN","DRAINE","RAYLEIGH"].includes(u))throw new Error(`World volume ${u} phase is not implemented`);const f=so(n.anisotropy);if(typeof f!="number")throw new Error("World volume anisotropy must be scalar");t.lobes.push({coefficient:c.clone().multiplyScalar(e),g:u==="RAYLEIGH"?0:ut.clamp(f,-.999,.999),alpha:u==="RAYLEIGH"?1:u==="DRAINE"?Bt(n.alpha):0})}if(n.kind==="principled"){const u=dn(n.absorption_color);i.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 f=Bt(n.blackbody_intensity);if(f>.001){const s=Bt(n.temperature),l=5670373e-20/Math.PI*(1+f*(s**4-1));t.emission.add(ll(s).multiply(dn(n.blackbody_tint)).multiplyScalar(l*e))}}(n.kind==="principled"||n.kind==="emission")&&t.emission.add((n.kind==="emission"?r:dn(n.emission_color)).multiplyScalar(Bt(n.emission_strength)*e)),t.extinction.add(i.add(c).multiplyScalar(e))}for(const n of["x","y","z"])if(t.extinction[n]===0&&t.emission[n]>0)throw new Error("Unbounded emissive World volume with zero extinction has divergent radiance");return t}class il{constructor(t){this.medium=t,this.target=new $e(1,1,{type:to,depthBuffer:!1}),this.geometry=new Qo(2,2),this.scene=new Le,this.camera=new Ve}render(t,n,e,r){if(!n.depthTexture)throw new Error("World volume render requires surface depth");const a={surface:{value:n.texture},depth:{value:n.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 i="",c="",u=0,f=2;e.traverseVisible(h=>{if(!(h instanceof Ln||h instanceof Vn||h instanceof gn))return;const d=h,m=u++,p=d.getWorldPosition(new x);a[`lp${m}`]={value:p},a[`lc${m}`]={value:d.color.clone().multiplyScalar(d.intensity)},i+=`uniform vec3 lp${m}, lc${m};
7095
+ `;let v="1.0",g="1.0";if(d instanceof Vn&&(a[`ld${m}`]={value:d.target.getWorldPosition(new x).sub(p).normalize()},a[`cone${m}`]={value:new $t(Math.cos(d.angle),Math.cos(d.angle*(1-d.penumbra)))},i+=`uniform vec3 ld${m}; uniform vec2 cone${m};
7096
+ `,g=`smoothstep(cone${m}.x, max(cone${m}.x+1e-6,cone${m}.y),dot(-L,ld${m}))`),!(d instanceof gn)&&d.castShadow&&d.shadow.map){if(++f>t.capabilities.maxTextures)throw new Error("World volume shadow samplers exceed this GPU texture-unit limit");a[`sm${m}`]={value:d.shadow.map.texture},a[`sx${m}`]={value:d.shadow.matrix},a[`ss${m}`]={value:d.shadow.mapSize},a[`sb${m}`]={value:d.shadow.bias},a[`sn${m}`]={value:d.shadow.camera.near},a[`sf${m}`]={value:d.shadow.camera.far},i+=`uniform sampler2D sm${m}; uniform mat4 sx${m}; uniform vec2 ss${m}; uniform float sb${m},sn${m},sf${m};
7097
+ `,v=d instanceof Ln?`getPointShadow(sm${m},ss${m},1.0,sb${m},1.0,sx${m}*vec4(p,1.0),sn${m},sf${m})`:`getShadow(sm${m},ss${m},1.0,sb${m},1.0,sx${m}*vec4(p,1.0))`}if(d instanceof gn){const b=new X().extractRotation(d.matrixWorld);a[`lx${m}`]={value:new x(d.width,0,0).applyMatrix4(b)},a[`ly${m}`]={value:new x(0,d.height,0).applyMatrix4(b)},a[`ln${m}`]={value:new x(0,0,-1).transformDirection(b)},i+=`uniform vec3 lx${m},ly${m},ln${m};
7098
+ `,c+=`for(int ax=0;ax<4;ax++) for(int ay=0;ay<4;ay++) {
7099
+ vec3 delta=lp${m}+lx${m}*((float(ax)+.5)/4.-.5)+ly${m}*((float(ay)+.5)/4.-.5)-p;
7100
7100
  float d=length(delta); vec3 L=delta/max(d,1e-6);
7101
- sum+=lc${_}*exp(-sigma*d)*phase(dot(L,ray))*max(dot(-L,ln${_}),0.)*
7102
- length(lx${_})*length(ly${_})/(16.*max(d*d,1e-4)); }
7103
- `}else i[`cut${_}`]={value:d.distance},i[`decay${_}`]={value:d.decay},s+=`uniform float cut${_},decay${_};
7104
- `,u+=`{ vec3 delta=lp${_}-p; float d=length(delta); vec3 L=delta/max(d,1e-6);
7105
- float cutoff=cut${_}>0.?pow(clamp(1.-pow(d/cut${_},4.),0.,1.),2.):1.;
7106
- sum+=lc${_}*exp(-sigma*d)*phase(dot(L,ray))*${g}*${v}*cutoff/max(pow(d,decay${_}),.01); }
7107
- `});let r="vec3 result=vec3(0.);";this.medium.lobes.forEach((h,d)=>{i[`scatter${d}`]={value:h.coefficient},i[`g${d}`]={value:h.g},i[`a${d}`]={value:h.alpha},s+=`uniform vec3 scatter${d}; uniform float g${d},a${d};
7108
- `,r+=`result+=scatter${d}*(1.-g${d}*g${d})*(1.+a${d}*c*c)/(12.56637061436*(1.+a${d}*(1.+2.*g${d}*g${d})/3.)*pow(1.+g${d}*g${d}-2.*g${d}*c,1.5));`});const l=this.medium.extinction.toArray().filter(h=>h>0);i.range={value:l.length?20/Math.min(...l):1},this.material?.dispose(),this.material=new Vn({uniforms:i,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:`
7101
+ sum+=lc${m}*exp(-sigma*d)*phase(dot(L,ray))*max(dot(-L,ln${m}),0.)*
7102
+ length(lx${m})*length(ly${m})/(16.*max(d*d,1e-4)); }
7103
+ `}else a[`cut${m}`]={value:d.distance},a[`decay${m}`]={value:d.decay},i+=`uniform float cut${m},decay${m};
7104
+ `,c+=`{ vec3 delta=lp${m}-p; float d=length(delta); vec3 L=delta/max(d,1e-6);
7105
+ float cutoff=cut${m}>0.?pow(clamp(1.-pow(d/cut${m},4.),0.,1.),2.):1.;
7106
+ sum+=lc${m}*exp(-sigma*d)*phase(dot(L,ray))*${g}*${v}*cutoff/max(pow(d,decay${m}),.01); }
7107
+ `});let s="vec3 result=vec3(0.);";this.medium.lobes.forEach((h,d)=>{a[`scatter${d}`]={value:h.coefficient},a[`g${d}`]={value:h.g},a[`a${d}`]={value:h.alpha},i+=`uniform vec3 scatter${d}; uniform float g${d},a${d};
7108
+ `,s+=`result+=scatter${d}*(1.-g${d}*g${d})*(1.+a${d}*c*c)/(12.56637061436*(1.+a${d}*(1.+2.*g${d}*g${d})/3.)*pow(1.+g${d}*g${d}-2.*g${d}*c,1.5));`});const l=this.medium.extinction.toArray().filter(h=>h>0);a.range={value:l.length?20/Math.min(...l):1},this.material?.dispose(),this.material=new Kn({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:`
7109
7109
  #include <common>
7110
7110
  #include <packing>
7111
7111
  #include <shadowmap_pars_fragment>
7112
7112
  varying vec2 vUv; uniform sampler2D surface,depth;
7113
7113
  uniform mat4 inverseProjection,cameraWorld; uniform bool orthographic;
7114
7114
  uniform vec3 sigma,emission; uniform float range;
7115
- ${s}
7116
- vec3 phase(float c){${r} return result;}
7117
- vec3 incident(vec3 p,vec3 ray){vec3 sum=vec3(0.);${u}return sum;}
7115
+ ${i}
7116
+ vec3 phase(float c){${s} return result;}
7117
+ vec3 incident(vec3 p,vec3 ray){vec3 sum=vec3(0.);${c}return sum;}
7118
7118
  float integral(float s,float d){float x=s*d;return x<.001 ? d*(1.-x*.5+x*x/6.) : (1.-exp(-x))/s;}
7119
7119
  void main(){
7120
7120
  float z=texture2D(depth,vUv).r; vec4 base=texture2D(surface,vUv);
@@ -7135,4 +7135,51 @@ attribute vec2 uv${d};
7135
7135
  radiance+=incident(origin+ray*t,ray)*exp(-sigma*t)*(hi-lo);
7136
7136
  }
7137
7137
  gl_FragColor=vec4(radiance,base.a+(1.-base.a)*(1.-dot(tr,vec3(1./3.))));
7138
- }`}),this.scene.clear(),this.scene.add(new At(this.geometry,this.material)),this.target.setSize(o.width,o.height);const m=t.getRenderTarget();try{t.setRenderTarget(this.target),t.render(this.scene,this.camera)}finally{t.setRenderTarget(m)}return this.target}dispose(){this.material?.dispose(),this.geometry.dispose(),this.target.dispose(),this.scene.clear()}}const Ll=O({object:A(),group:A(),groupIndex:R().int().nonnegative(),count:R().int().nonnegative(),digest:A(),alertMode:X(["NONE","ACTIVE","ALL"]),unchanged:L(!0).optional(),weightsBase64:A().optional(),alertBase64:A().optional()}).strict();function Vl(n){const o=n<0?0:n>1?1:n,e=(.5+.5*o)**1.5,[a,i,s]=jl(2/3*(1-o)),u=new gt;return u.setRGB((a*e)**(1/1.5),(i*e)**(1/1.5),(s*e)**(1/1.5),$t),u}function jl(n){const t=(n%1+1)%1,o=Math.floor(t*6),e=t*6-o;switch(o%6){case 0:return[1,e,0];case 1:return[1-e,1,0];case 2:return[0,1,e];case 3:return[0,1-e,1];case 4:return[e,0,1];default:return[1,0,1-e]}}const Bl=0;function bo(n){const t=atob(n),o=new Uint8Array(t.length);for(let e=0;e<t.length;e++)o[e]=t.charCodeAt(e);return o}class Ul{constructor(){this.group=new _t,this.mesh=null,this.material=null,this.geometry=null,this.held=null,this.signature="",this.group.name="BlenderWeightOverlay"}apply(t,o,e){if(t===null||o===null||!o.isMesh||e===null)return this.clear(),this.signature="",null;const a=`${t.object}:${t.group}`;if(t.unchanged===!0){if(this.held?.key!==a)return this.clear(),`weights: the session sent a reference to ${a} 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: ${a} carried neither an array nor a reference`;const d=bo(t.weightsBase64);this.held={key:a,weights:new Float32Array(d.buffer,d.byteOffset,t.count),alerts:bo(t.alertBase64)}}const i=this.held;if(i===null)return null;const s=`${a}:${t.digest}:${o.geometry.uuid}:${t.alertMode}:${e.elements.join(",")}`;if(s===this.signature&&this.mesh!==null)return null;this.signature=s,this.clear();const u=o.geometry.clone(),c=u.getAttribute("position"),f=u.getAttribute("blenderVertex");if(f===void 0)return u.dispose(),"weights: the presented geometry carries no per-vertex Blender index (`blenderVertex`), so the weights cannot be laid over it";const r=new Float32Array(c.count*3),l=new gt().setHex(Bl,$t);for(let d=0;d<c.count;d++){const _=f.getX(d),v=t.alertMode!=="NONE"&&i.alerts[_]===1?l:Vl(i.weights[_]??0);r[d*3]=v.r,r[d*3+1]=v.g,r[d*3+2]=v.b}u.setAttribute("color",new tt(r,3)),u.deleteAttribute("blenderVertex");const m=new Po({vertexColors:!0,polygonOffset:!0,polygonOffsetFactor:-1,polygonOffsetUnits:-1}),h=new At(u,m);return h.name=`${t.object}:weights`,h.frustumCulled=!1,h.matrixAutoUpdate=!1,h.matrix.copy(e),h.matrix.decompose(h.position,h.quaternion,h.scale),this.geometry=u,this.material=m,this.mesh=h,this.group.add(h),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 S=R().finite(),Qo=j([S,S,S]),ln=j([R().int().nonnegative(),R().int().nonnegative()]),J={name:A(),domain:X(["POINT","EDGE","FACE","CORNER"])},ql=Ve("type",[O({...J,type:L("FLOAT2"),data:z(j([S,S]))}).strict(),O({...J,type:L("FLOAT_VECTOR"),data:z(Qo)}).strict(),O({...J,type:L("FLOAT_COLOR"),data:z(j([S,S,S,S]))}).strict(),O({...J,type:L("BYTE_COLOR"),data:z(j([S,S,S,S]))}).strict(),O({...J,type:L("QUATERNION"),data:z(j([S,S,S,S]))}).strict(),O({...J,type:L("FLOAT4"),data:z(j([S,S,S,S]))}).strict(),O({...J,type:L("FLOAT4X4"),data:z(z(S).length(16))}).strict(),O({...J,type:L("INT16_2D"),data:z(j([R().int(),R().int()]))}).strict(),O({...J,type:L("INT32_2D"),data:z(j([R().int(),R().int()]))}).strict(),O({...J,type:L("FLOAT"),data:z(S)}).strict(),O({...J,type:L("INT"),data:z(R().int())}).strict(),O({...J,type:L("INT8"),data:z(R().int())}).strict(),O({...J,type:L("BOOLEAN"),data:z(Y())}).strict(),O({...J,type:L("STRING"),data:z(A())}).strict()]),Hl=O({positions:V(Float32Array),normals:V(Float32Array).nullable(),uv:V(Float32Array).nullable(),uvLayers:z(O({name:A(),data:V(Float32Array)}).strict()).optional(),attributeLayers:z(O({name:A(),data:V(Float32Array)}).strict()).optional(),orco:V(Float32Array).nullable().optional(),indices:V(Uint32Array),groups:z(O({start:R().int().nonnegative(),count:R().int().nonnegative(),materialIndex:R().int().nonnegative()}).strict()),hash:A()}).strict(),Wl=O({v:z(Qo),f:z(z(R().int().nonnegative())),e:z(ln).optional(),edge_order:z(ln).optional(),m:z(R().int().nonnegative()).optional(),s:z(Y()).optional(),sharp:z(ln).optional(),seams:z(ln).optional(),creases:z(j([S,S,S])).optional(),attributes:z(ql).optional(),active_uv:A().nullable().optional(),render_uv:A().nullable().optional()}).strict(),Gl=O({store:R().int().optional(),revision:R().int(),unchanged:L(!0)}).strict(),Xl=O({co:V(Float64Array),cornerNormal:V(Float32Array).optional(),orco:V(Float32Array).optional(),faceStart:V(Uint32Array),corner:V(Uint32Array),cornerEdge:V(Int32Array),edge:V(Uint32Array),edgeSharp:V(Uint8Array),edgeSeam:V(Uint8Array),edgeCrease:V(Float32Array),material:V(Uint32Array),smooth:V(Uint8Array),vertSelect:V(Uint8Array),vertHide:V(Uint8Array),edgeSelect:V(Uint8Array),edgeHide:V(Uint8Array),faceSelect:V(Uint8Array),faceHide:V(Uint8Array)}).strict(),Yl=O({name:A(),domain:X(["POINT","EDGE","FACE","CORNER"]),type:A(),data:je(n=>ArrayBuffer.isView(n))}).strict(),Zl=O({columns:Xl,attributes:z(Yl),activeUv:A().nullable(),renderUv:A().nullable(),counts:O({verts:R().int().nonnegative(),edges:R().int().nonnegative(),faces:R().int().nonnegative(),corners:R().int().nonnegative()}).strict(),revision:R().int().nonnegative()}).strict(),Ql=Nt([Hl,Zl,Wl,Gl]),yo=new Set;function Kl(n){const t=new Blob([n],{type:"image/png"}),o=new Ne;let e=!1;o.addEventListener("dispose",()=>{e=!0,o.image?.close?.()});const a=createImageBitmap(t,{imageOrientation:"flipY"}).then(i=>{if(e){i.close();return}o.image=i,o.needsUpdate=!0,Jt()}).finally(()=>{yo.delete(a)});return yo.add(a),a.catch(()=>{}),{texture:o,ready:a}}function Jl(n,t,o,e){const a=new mn(n,t,o,dn,Ee);return a.flipY=!1,a.colorSpace=e==="data"?Bn:$t,a.needsUpdate=!0,a}function tr(n,t,o){if(t.length===0)throw new Error(`Runtime image ${n} is tiled with no tiles`);const e=Math.max(...t.map(r=>r.width)),a=Math.max(...t.map(r=>r.height)),i=new Uint8Array(e*a*4*t.length),s=Math.max(...t.map(r=>r.number-1001))+1,u=new Float32Array(s*2*4);for(let r=0;r<s;r++)u[r*4]=-1;t.forEach((r,l)=>{const m=r.rgba??(r.rgbaBase64?Rn(r.rgbaBase64):void 0);if(!m)throw new Error(`Runtime image ${n} tile ${r.number} carries no raster`);for(let d=0;d<r.height;d++)i.set(m.subarray(d*r.width*4,(d+1)*r.width*4),(l*a+d)*e*4);const h=r.number-1001;u[h*4]=l,u.set([0,0,r.width/e,r.height/a],(s+h)*4)});const c=new Se(i,e,a,t.length);c.colorSpace=o==="data"?Bn:$t,c.magFilter=St,c.minFilter=Ro,c.generateMipmaps=!0,c.needsUpdate=!0;const f=new mn(u,s,2,dn,No);return f.magFilter=f.minFilter=Nn,f.needsUpdate=!0,{tiles:c,map:f,frame:t}}const nr=O({width:R().int().positive(),height:R().int().positive(),revision:R().int().nonnegative(),rgba:V(Uint8Array).optional(),rgbaBase64:A().optional(),colorspace:X(["sRGB","data"]).optional(),tiles:z(O({number:R().int().min(1001),width:R().int().positive(),height:R().int().positive(),rgba:V(Uint8Array).optional(),rgbaBase64:A().optional()}).strict()).optional()}).strict(),or=O({revision:R().int().nonnegative(),png:V(Uint8Array).optional(),pngBase64:A().optional()}).strict(),er=Nt([nr,or]),Pn=O({image:O({name:A(),revision:R().int().nonnegative()}).strict(),extension:X(["REPEAT","EXTEND","MIRROR","CLIP"]).default("REPEAT"),uv:A(),tint:j([S,S,S]).optional()}).strict(),ar=O({name:A(),color:j([S,S,S,S]),roughness:S,metallic:S,transmission:S,ior:S,physical:Fl.optional(),normal_texture:Pn.optional(),normal_strength:S.default(1),normal_space:X(["TANGENT","OBJECT"]).default("TANGENT"),normal_directx:Y().default(!1),texture:Pn.optional(),roughness_texture:Pn.optional(),emission:O({color:j([S,S,S]),strength:S}).strict().optional(),graph:il.optional()}).strict(),lr=O({session:A(),revision:R().int().nonnegative(),volumes:st(A(),Ho).default({}),lights:st(A(),Ua).default({}),world:Ka.nullable().default(null),meshes:st(A(),Ql),materials:st(A(),ar),images:st(A(),er).default({}),objects:z(O({id:A(),name:A(),type:X(["MESH","CURVE","SURFACE","FONT","META","ARMATURE","LATTICE","VOLUME","EMPTY","CAMERA","LIGHT","SPEAKER","GREASEPENCIL","POINTCLOUD","LIGHT_PROBE"]),mesh:A().nullable(),volume:A().nullable().optional(),light:A().nullable().optional(),materials:z(A().nullable()),matrix:z(j([S,S,S,S])).length(4),visible:Y(),render_visible:Y().default(!0),selected:Y(),parent:A().nullable(),texspace:j([j([S,S,S]),j([S,S,S])]).optional(),default_color:A().optional()}).strict()),active:A().nullable(),mode:A(),cameras:st(A(),st(A(),Fo())).default({}),warnings:z(A()).default([]),updated:z(A()).default([]),frame:R().int().default(0),armatures:st(A(),He).default({}),weights:Ll.nullable().default(null)}).strict();class Yn{constructor(){this.root=new _t,this.objects=new Map,this.meshes=new Map,this.volumes=new Map,this.materials=new Map,this.lights=new Map,this.lighting=new Qa,this.world=new Hn,this.armatureOverlay=new oa,this.weightOverlay=new Ul,this.armatureRoot=new _t,this.weightRoot=new _t,this.rendered=!1,this.fallback=new Qt({color:12172998,roughness:.72}),this.textures=new Map,this.textureNames=new Map,this.roughnessTextureNames=new Map,this.textureSamplers=new Il,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.mode=null,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[t,o]of[[this.armatureRoot,this.armatureOverlay.group],[this.weightRoot,this.weightOverlay.group]])t.matrixAutoUpdate=!1,t.matrix.copy(this.root.matrix),t.add(o),t.updateMatrixWorld(!0);this.armatureRoot.name="BlenderBones",this.weightRoot.name="BlenderWeights"}compiledGraph(t){const o=JSON.stringify(t);let e=this.graphs.get(o);return e||(e=yl(t),this.graphs.size>256&&this.graphs.clear(),this.graphs.set(o,e)),e}subscribeFrames(t){return this.frameListeners.add(t),()=>{this.frameListeners.delete(t)}}onChange(t){const o=this.subscribeFrames(t),e=Ue(t);return()=>{o(),e()}}blenderObjectName(t){for(const[o,e]of this.objects)if(e===t)return this.frame?.objects.find(a=>a.id===o)?.name??null;return null}blenderSelection(){const t=this.frame;return t===null?{selected:[],active:null}:{selected:t.objects.filter(o=>o.selected).map(o=>o.name),active:t.active}}setStageMode(t){this.mode=t}stageMode(){return this.mode}objectForBlenderName(t){const o=this.frame?.objects.find(e=>e.name===t);return o===void 0?null:this.objects.get(o.id)??null}replacePresentedObject(t,o){for(const[e,a]of this.objects)if(a===t){const i=t.parent,s=[...t.children];t.removeFromParent();for(const u of s)o.add(u);i?.add(o),this.objects.set(e,o);return}}studioLights(){return this.lighting.group}overlayGroups(){return[{kind:"skeletons",object:this.armatureRoot},{kind:"weights",object:this.weightRoot}]}async setRendered(t,o){const e=(t?xo(this.frame?.world)?.extinction:null)??new y;for(const a of[...this.materials.values(),this.fallback])Dl(a,e);this.rendered=t,this.lighting.setRendered(t),t?this.world.apply(this.root,this.frame?.world??null,o):this.world.clear(),this.applyVisibility(),this.applyShadows(t,o),t&&(await Ha(),await Promise.all([...this.textures.values()].map(a=>a.ready)),await this.world.ready())}applyShadows(t,o){this.root.updateMatrixWorld(!0);const e=[];for(const c of this.objects.values()){const f=c;if(f.isMesh&&(f.castShadow=t,f.receiveShadow=t,t&&f.visible)){const r=new fn().setFromObject(f);r.isEmpty()||e.push(r)}}if(!t||!e.length)return;const i=e.reduce((c,f)=>c.union(f),new fn).getBoundingSphere(new Oe),s=o?new Te().setFromProjectionMatrix(new mt().multiplyMatrices(o.projectionMatrix,o.matrixWorldInverse)):null,u=s?e.flatMap(c=>nl(c,s)):[];for(const c of this.lights.values())c.isDirectionalLight&&o?ol(c,u,e):Xa(c,i.center,i.radius)}applyOverlays(t){const o=s=>{const u=t.objects.find(c=>c.name===s);return u===void 0?null:new mt().set(...u.matrix.flat())},e=[...this.armatureOverlay.apply(t.armatures,o)],a=t.weights?this.objects.get(t.objects.find(s=>s.name===t.weights?.object)?.id??""):void 0,i=this.weightOverlay.apply(t.weights,a??null,t.weights?o(t.weights.object):null);return i!==null&&e.push(i),e}applyVisibility(){for(const t of this.frame?.objects??[]){const o=this.objects.get(t.id);if(o&&(o.visible=this.rendered?t.render_visible:t.visible),!t.light)continue;const e=this.lights.get(t.light);e&&(e.visible=this.rendered&&t.render_visible)}this.armatureOverlay.group.visible=!this.rendered,this.weightOverlay.group.visible=!this.rendered}applyFrame(t){const o=this.frame===null?null:{session:this.frame.session,revision:this.frame.revision},e=lr.parse(t);if(this.retiredSessions.has(e.session))throw new Error("The runtime session was replaced; its delayed frame cannot overwrite the active model");if(this.frame?.session===e.session&&e.revision<this.frame.revision)throw new Error("The runtime frame is older than the displayed model");const a=new Set(e.objects.map(f=>f.id));if(a.size!==e.objects.length)throw new Error("Runtime object IDs must be unique");const i=new Map(e.objects.map(f=>[f.id,f]));for(const f of e.objects){if(f.mesh!==null&&!e.meshes[f.mesh])throw new Error(`Missing runtime mesh ${f.mesh}`);if(f.volume&&(!e.volumes[f.volume]||f.mesh!==null))throw new Error(`Invalid runtime volume ${f.volume}`);if(f.light&&(!e.lights[f.light]||f.mesh!==null))throw new Error(`Invalid runtime light ${f.light}`);for(const m of f.materials)if(m!==null&&!e.materials[m])throw new Error(`Missing runtime material ${m}`);const r=new Set([f.id]);let l=f.parent;for(;l!==null;){if(r.has(l))throw new Error("Runtime parent cycle");r.add(l);const m=i.get(l);if(!m)throw new Error(`Missing runtime parent ${l}`);l=m.parent}}const s=new Map,u=new Map;try{for(const[f,r]of Object.entries(e.volumes)){const l=JSON.stringify(r);this.frame?.session===e.session&&this.volumes.get(f)?.signature===l||u.set(f,{signature:l,mesh:el(r)})}for(const[f,r]of Object.entries(e.meshes)){if("unchanged"in r){if(this.frame?.session===e.session&&this.meshes.has(f))continue;throw new Error(`${ea}: the presenter does not hold runtime mesh ${f} (store ${r.store}, revision ${r.revision})`)}const l="hash"in r,m="columns"in r,h=m?`revision:${r.revision}`:l?r.hash:JSON.stringify(r);this.frame?.session===e.session&&this.meshes.get(f)?.signature===h||s.set(f,{signature:h,geometry:m?In(ha({...r.columns,attributes:r.attributes,activeUv:r.activeUv,renderUv:r.renderUv},h)):l?In(r):pa(r)})}}catch(f){for(const r of s.values())r.geometry.dispose();for(const{mesh:r}of u.values())r.geometry.dispose(),r.material.dispose();throw f}this.frame?.session!==e.session&&(this.frame&&this.retiredSessions.add(this.frame.session),this.clear());for(const[f,r]of u){const l=this.volumes.get(f)?.mesh;l&&(l.removeFromParent(),l.geometry.dispose(),l.material.dispose()),this.volumes.set(f,r)}for(const[f,r]of s)this.meshes.get(f)?.geometry.dispose(),this.meshes.set(f,r),this.geometryBuilds++;for(const[f,r]of Object.entries(e.images)){const l=this.textures.get(f);if("width"in r){const _=r.rgba??(r.rgbaBase64?Rn(r.rgbaBase64):void 0);if(!_)throw new Error(`Runtime image ${f} carries no raster`);const p=r.tiles?tr(f,r.tiles,r.colorspace??"sRGB"):void 0;if(l?.udim&&(l.udim.tiles.dispose(),l.udim.map.dispose(),delete l.udim),l&&l.width===r.width&&l.height===r.height){const v=l.texture.image;if(v.data){v.data.set(_),l.texture.needsUpdate=!0,l.revision=r.revision,p&&(l.udim=p);continue}}l?.texture.dispose(),this.textures.set(f,{texture:Jl(_,r.width,r.height,r.colorspace??"sRGB"),width:r.width,height:r.height,revision:r.revision,...p?{udim:p}:{}});continue}const m=r.png??(r.pngBase64?Rn(r.pngBase64):void 0);if(!m)throw new Error(`Runtime image ${f} carries no bytes`);l?.texture.dispose(),l?.udim?.tiles.dispose(),l?.udim?.map.dispose();const{texture:h,ready:d}=Kl(m);h.colorSpace=$t,this.textures.set(f,{texture:h,ready:d,width:0,height:0,revision:r.revision,png:m.slice()})}for(const[f,r]of Object.entries(e.materials)){const l=this.materials.get(f)??new Qt;l.name=r.name;const m=r.texture?.tint;r.texture!==void 0?l.color.setRGB(m?.[0]??1,m?.[1]??1,m?.[2]??1,at):l.color.setRGB(r.color[0],r.color[1],r.color[2],at),l.opacity=r.color[3];const h=l.opacity<1||r.graph!==void 0&&sl(r.graph);l.transparent!==h&&(l.transparent=h,l.needsUpdate=!0),l.roughness=r.roughness,l.metalness=r.metallic,l.transmission=r.transmission,l.ior=r.ior,Gn(l,r.physical,{map:r.texture?.extension==="CLIP",roughness:r.roughness_texture?.extension==="CLIP",normal:r.normal_texture?.extension==="CLIP"});const d=r.normal_texture?.image.name;if(d===void 0)l.normalMap&&(this.textureSamplers.delete(`${f}:normal`),l.normalMap=null,l.needsUpdate=!0);else{const b=this.textures.get(d);if(!b)throw new Error(`${jt}: missing normal image ${d}`);const P=this.textureSamplers.get(`${f}:normal`,b.texture,r.normal_texture.extension,b.ready,r.normal_texture.uv);l.normalMap!==P&&(l.normalMap=P,l.needsUpdate=!0);const D=r.normal_space==="OBJECT"?Pe:Ae;l.normalMapType!==D&&(l.normalMapType=D,l.needsUpdate=!0),l.normalScale.set(r.normal_strength,r.normal_strength*(r.normal_directx?-1:1))}r.emission?(l.emissive.setRGB(r.emission.color[0],r.emission.color[1],r.emission.color[2],at),l.emissiveIntensity=r.emission.strength):(l.emissive.setRGB(0,0,0),l.emissiveIntensity=1);const _=r.roughness_texture?.image.name??null;if(_===null)this.roughnessTextureNames.has(f)&&(this.textureSamplers.delete(`${f}:roughness`),l.roughnessMap=null,this.roughnessTextureNames.delete(f),l.needsUpdate=!0);else{const b=this.textures.get(_);if(!b)throw new Error(`${jt}: the presenter does not hold runtime image ${_} (revision ${r.roughness_texture.image.revision})`);const P=this.textureSamplers.get(`${f}:roughness`,b.texture,r.roughness_texture.extension,b.ready,r.roughness_texture.uv);l.roughnessMap!==P&&(l.roughnessMap=P,this.roughnessTextureNames.set(f,_),l.needsUpdate=!0)}const p=r.texture?.image.name??null;if(p===null)this.textureNames.has(f)&&(this.textureSamplers.delete(`${f}:color`),l.map=null,this.textureNames.delete(f),l.needsUpdate=!0);else{const b=this.textures.get(p);if(!b)throw new Error(`${jt}: the presenter does not hold runtime image ${p} (revision ${r.texture.image.revision})`);const P=this.textureSamplers.get(`${f}:color`,b.texture,r.texture.extension,b.ready,r.texture.uv);l.map!==P&&(l.map=P,this.textureNames.set(f,p),l.needsUpdate=!0)}const v=r.graph?this.compiledGraph(r.graph):null,g=new Set;Ol(l,v,b=>{const P=this.textures.get(b.name);if(!P)throw new Error(`${jt}: the presenter does not hold runtime image ${b.name} (revision ${b.revision})`);if(b.tiled){if(!P.udim)throw new Error(`${jt}: runtime image ${b.name} arrived without its UDIM tiles`);return P.udim}const D=`${f}:graph:${b.node}`;g.add(D);const w=this.textureSamplers.get(D,P.texture,b.extension,P.ready),E=b.closest?Nn:St,I=b.closest?Nn:b.mipmap?Ro:St;return(w.magFilter!==E||w.minFilter!==I)&&(w.magFilter=E,w.minFilter=I,w.needsUpdate=!0),w},this.photograph);for(const b of this.graphSamplers.get(f)??[])g.has(b)||this.textureSamplers.delete(b);this.graphSamplers.set(f,g),this.materials.set(f,l)}for(const f of e.objects){let r=this.objects.get(f.id);const l=f.volume?this.volumes.get(f.volume).mesh:null;if((!r||(l?r!==l:!!r.isMesh!=(f.mesh!==null)))&&(r?.removeFromParent(),r=l??(f.mesh!==null?new At(this.meshes.get(f.mesh).geometry,this.fallback):new Ao),this.objects.set(f.id,r)),r.name=f.name,r.matrixAutoUpdate=!1,r.matrix.set(...f.matrix.flat()),f.parent){const m=new mt().set(...i.get(f.parent).matrix.flat());r.matrix.premultiply(m.invert())}if(r.matrix.decompose(r.position,r.quaternion,r.scale),f.texspace?r.userData.blenderTexspace=f.texspace:delete r.userData.blenderTexspace,f.default_color!==void 0?r.userData.blenderDefaultColor=f.default_color:delete r.userData.blenderDefaultColor,f.mesh!==null){const m=r;m.geometry=this.meshes.get(f.mesh).geometry,m.material=f.materials.length?f.materials.map(h=>h===null?this.fallback:this.materials.get(h)):this.fallback,Sl(m)}if(f.light){const m=this.lights.get(f.light)??null,h=Ga(e.lights[f.light],m);m&&m!==h&&(m.removeFromParent(),m.dispose()),h.parent!==r&&r.add(h),Ya(h,r),this.lights.set(f.light,h)}}for(const f of e.objects){const r=this.objects.get(f.id),l=f.parent===null?this.root:this.objects.get(f.parent);r.parent!==l&&l.add(r)}for(const[f,r]of this.objects)a.has(f)||(r.removeFromParent(),this.objects.delete(f));for(const[f,r]of this.volumes)e.volumes[f]||(r.mesh.geometry.dispose(),r.mesh.material.dispose(),this.volumes.delete(f));for(const[f,r]of this.meshes)e.meshes[f]||(r.geometry.dispose(),this.meshes.delete(f));for(const[f,r]of this.materials)if(!e.materials[f]){for(const l of["normal","roughness","color"])this.textureSamplers.delete(`${f}:${l}`);for(const l of this.graphSamplers.get(f)??[])this.textureSamplers.delete(l);this.graphSamplers.delete(f),r.dispose(),this.materials.delete(f)}for(const[f,r]of this.lights)e.lights[f]||(r.removeFromParent(),r.dispose(),this.lights.delete(f));this.root.updateMatrixWorld(!0),this.frame={...e,meshes:{},volumes:{}};const c=this.applyOverlays(e);c.length&&(this.frame={...this.frame,warnings:[...this.frame.warnings,...c]}),this.applyVisibility();for(const f of[...this.frameListeners])f();return{...this.inspect(),held:o}}inspect(){return{session:this.frame?.session,revision:this.frame?.revision,active:this.frame?.active,mode:this.frame?.mode,geometryBuilds:this.geometryBuilds,objects:[...this.objects].map(([t,o])=>({id:t,name:o.name,uuid:o.uuid,geometry:o.geometry?.uuid,visible:o.visible}))}}snapshot(){return this.frame}captureSnapshot(){const t=this.frame;if(!t)throw new Error("Blender capture requires a presented frame");const o=structuredClone({...t,images:{},armatures:{},weights:null});for(const[c,{signature:f,geometry:r}]of this.meshes){const l=d=>{const _=r.getAttribute(d);if(!_)return null;if(!(_ instanceof tt))throw new Error(`Blender capture cannot copy interleaved ${d}`);return new Float32Array(_.array)},m=l("position");if(!m)throw new Error(`Blender capture mesh ${c} has no positions`);const h=r.getIndex();o.meshes[c]={hash:f,positions:m,normals:l("normal"),uv:l("uv"),uvLayers:Object.entries(r.userData.blenderUvChannels??{}).map(([d,_])=>{const p=l(`uv${_}`);if(!p)throw new Error(`Blender capture mesh ${c} is missing UV layer ${d}`);return{name:d,data:p}}),orco:r.userData.blenderOrcoFromDoor?l("blenderOrco"):null,attributeLayers:(r.userData.blenderAttributes??[]).map(d=>{const _=l(Et(d));if(!_)throw new Error(`Blender capture mesh ${c} is missing attribute ${d}`);return{name:d,data:_}}),indices:h?new Uint32Array(h.array):Uint32Array.from({length:m.length/3},(d,_)=>_),groups:r.groups.map(d=>({start:d.start,count:d.count,materialIndex:d.materialIndex??0}))}}for(const[c,{signature:f}]of this.volumes)o.volumes[c]=Ho.parse(JSON.parse(f));const e=new Set(Object.values(o.materials).flatMap(c=>[c.texture?.image.name,c.roughness_texture?.image.name,c.normal_texture?.image.name,...Object.values(c.graph?.nodes??{}).map(f=>f.props.image?.name)].filter(f=>f!==void 0)));for(const c of e){const f=this.textures.get(c);if(!f)throw new Error(`Blender capture image ${c} is not resident`);if(f.png)o.images[c]={revision:f.revision,png:f.png.slice()};else{const r=f.texture.image?.data;if(!(r instanceof Uint8Array))throw new Error(`Blender capture image ${c} has no resident raster`);o.images[c]={revision:f.revision,width:f.width,height:f.height,rgba:r.slice(),colorspace:f.texture.colorSpace===Bn?"data":"sRGB",...f.udim?{tiles:f.udim.frame}:{}}}}const a=this.createWorldVolumePass(),i=new Yn;i.photograph=!0;let s=!1;const u=()=>{s||(s=!0,a?.dispose(),i.dispose(),i.root.removeFromParent())};try{i.applyFrame(o),this.root.updateWorldMatrix(!0,!1),i.root.matrix.copy(this.root.matrixWorld),i.root.updateMatrixWorld(!0)}catch(c){throw u(),c}return{effect:a,root:i.root,session:t.session,revision:t.revision,prepare:c=>{if(s)throw new Error("Blender capture snapshot is disposed");return i.setRendered(!0,c)},dispose:u}}createWorldVolumePass(){const t=xo(this.frame?.world);return t?new $l(t):void 0}recordPresentation(t){if(typeof t!="object"||t===null)return;const o=t,e=o.meshes;if(typeof e!="object"||e===null)return;const a=typeof o.session=="string"?o.session:null;a!==this.submittedSession&&(this.submittedMeshes.clear(),this.photographs.length=0,this.submittedSession=a);const i=e;for(const[s,u]of Object.entries(i))typeof u=="object"&&u!==null&&!("unchanged"in u)&&this.submittedMeshes.set(s,u);for(const s of[...this.submittedMeshes.keys()])s in i||this.submittedMeshes.delete(s);this.submitted={...o,meshes:Object.fromEntries(this.submittedMeshes)}}recordPhotograph(t){this.photographs.push(t)}observations(){return{presentation:this.submitted,photographs:this.photographs}}clear(){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:o}of this.textures.values())t.dispose(),o?.tiles.dispose(),o?.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.frame=null,this.retiredSessions.clear(),this.submittedMeshes.clear(),this.submitted=null,this.submittedSession=null,this.photographs.length=0}}const mr=new Yn;function Ko(n){const t=atob(n),o=new Uint8Array(t.length);for(let e=0;e<t.length;e++)o[e]=t.charCodeAt(e);return o}function An(n){const t=Ko(n);return new Float32Array(t.buffer,t.byteOffset,t.byteLength>>2)}function rr(n){const t=Ko(n);return new Uint16Array(t.buffer,t.byteOffset,t.byteLength>>1)}function ir(n){return new mt().set(...n.flat())}function wo(n,t){return[n.object,n.mesh,n.armature,n.vertexCount,n.bones.length,t].join("|")}class sr{#n=new Map;#o=null;#a=null;#t=null;#i=null;#e=null;#r=null;#s=new Set;#u=0;#_=[];#l=0;get version(){return this.#u}get engineCalls(){return this.#l}subscribe(t){return this.#s.add(t),()=>this.#s.delete(t)}#f(){this.#u++;for(const t of[...this.#s])t()}state(){const t=this.#t,o=t?.frameStart??1,e=t?.frameEnd??250,a=t?.fps??24;return{frame:this.frame(),start:o,end:e,fps:a,action:t?.action??null,object:t?.object??null,armature:t?.armature??null,bones:[...this.#n.values()].reduce((i,s)=>i+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.#n.keys()],warnings:this.#_,engineCalls:this.#l,blenderFrame:t?.frameCurrent??null}}frame(){const t=this.#t;return!t||!this.#a||t.clipStart===void 0?t?.frameCurrent??1:this.#i!==null?this.#i:t.clipStart+this.#a.time*t.fps}get playable(){return this.#a!==null}async bind(t,o){this.#l++;const e=await o.rig();if(!e)return;const a=[],i=new Set;let s=!1;for(const l of e.rigs){if(!l.object||!l.armature||!l.skinIndexBase64||!l.skinWeightBase64){l.reason&&a.push(l.reason);continue}i.add(l.object);const m=wo(l,e.frame);if(this.#n.get(l.object)?.signature===m)continue;const h=this.#d(t,l,e.frame,a);h&&(this.#n.get(l.object)?.skeleton.dispose(),this.#n.set(l.object,h),s=!0)}for(const[l,m]of[...this.#n])i.has(l)||(m.skeleton.dispose(),m.boneRoot.removeFromParent(),this.#n.delete(l),s=!0);this.#l++;const u=await o.clip(),c=this.#t,f=u?.action!==c?.action||u?.tracks.length!==c?.tracks.length||u?.clipStart!==c?.clipStart||u?.clipEnd!==c?.clipEnd;this.#t=u??null,u?.reason&&a.push(u.reason),u&&(f||s)&&this.#h(t,u,a);const r=this.#e?.snapshot().playbackState==="playing";u&&!r&&c?.frameCurrent!==u.frameCurrent&&(this.#c(u.frameCurrent),this.#e&&u.fps>0&&this.#e.seek(u.frameCurrent/u.fps)),this.#_=a,this.#f()}#d(t,o,e,a){const i=t.objectForBlenderName(o.object??""),s=t.objectForBlenderName(o.armature??"");if(!i||!s)return null;const u=i,c=u.geometry;if(!c)return null;const f=c.getAttribute("blenderVertex");if(!f)return a.push(`"${o.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(o.vertexCount===0)return null;let r=0;for(let w=0;w<f.count;w++)r=Math.max(r,f.getX(w));if(r>=o.vertexCount)return a.push(`"${o.object}" is not skinned here: its presented geometry references Blender vertex ${r} while the mesh declares ${o.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 l=rr(o.skinIndexBase64??""),m=An(o.skinWeightBase64??""),h=f.count,d=new Uint16Array(h*4),_=new Float32Array(h*4);for(let w=0;w<h;w++){const E=f.getX(w);for(let I=0;I<4;I++)d[w*4+I]=l[E*4+I]??0,_[w*4+I]=m[E*4+I]??0}c.setAttribute("skinIndex",new Me(d,4)),c.setAttribute("skinWeight",new Ht(_,4));const p=new _t;p.name=`${o.armature}:bones`;const v=[],g=o.bones.map(w=>ir(w.pose)),b=new Map(o.bones.map((w,E)=>[w.name,E]));o.bones.forEach((w,E)=>{const I=new Re;I.name=w.name,v.push(I);const F=w.parent===null?void 0:b.get(w.parent);(F===void 0?g[E].clone():g[F].clone().invert().multiply(g[E])).decompose(I.position,I.quaternion,I.scale),(F===void 0?p:v[F]).add(I)}),s.add(p);const P=new Ie(c,u.material);P.name=u.name,P.matrixAutoUpdate=!1,P.matrix.copy(u.matrix),P.matrix.decompose(P.position,P.quaternion,P.scale),P.userData=u.userData,P.frustumCulled=!1,t.replacePresentedObject(u,P),t.root.updateMatrixWorld(!0);const D=new Fe(v);return P.bind(D,P.matrixWorld.clone()),o.constrainedBones?.length&&a.push(`Bone constraints on ${o.constrainedBones.join(", ")}: the clip is derived from the F-Curves alone, so those bones play their channels rather than Blender's solved pose.`),o.unmappedGroups?.length&&a.push(`${o.object} carries vertex groups no bone is named for (${o.unmappedGroups.join(", ")}); they weight nothing here, exactly as they deform nothing in Blender.`),{object:o.object??"",armature:o.armature??"",mesh:P,boneRoot:p,bones:v,skeleton:D,frame:e,signature:wo(o,e)}}#h(t,o,e){if(this.#o?.stopAllAction(),this.#o=null,this.#a=null,!o.tracks.length||o.clipStart===void 0||o.clipEnd===void 0)return;const a=o.armature?t.objectForBlenderName(o.armature):null;if(!a)return;const i=new Map;for(const l of this.#n.values())if(l.armature===o.armature)for(const m of l.bones)i.set(m.name,m);const s=[],u=new Set;for(const l of o.tracks){const m=i.get(l.bone);if(!m){u.add(l.bone);continue}const h=An(l.timeBase64),d=An(l.valueBase64),_=`${m.uuid}.${l.property}`;s.push(l.property==="quaternion"?new ze(_,Array.from(h),Array.from(d)):new De(_,Array.from(h),Array.from(d)))}if(u.size&&e.push(`${o.action} animates ${[...u].join(", ")}, which this binding has no bone for.`),!s.length)return;const c=o.duration??(o.clipEnd-o.clipStart)/o.fps,f=new Ce(a),r=f.clipAction(new ke(o.action??"action",c,s));r.setLoop($e,Number.POSITIVE_INFINITY),r.play(),this.#o=f,this.#a=r,this.#c(o.frameCurrent),this.#m()}#c(t){const o=this.#t;if(!o||!this.#o||o.clipStart===void 0||o.clipEnd===void 0)return;const e=Math.min(o.clipEnd,Math.max(o.clipStart,t));this.#i=e;const a=(o.clipEnd-o.clipStart)/o.fps;this.#o.setTime(Math.min(a-1e-4,(e-o.clipStart)/o.fps)),this.#m()}#m(){for(const t of this.#n.values())t.boneRoot.updateMatrixWorld(!0),t.skeleton.update()}get scene(){return this.#t?.scene??null}async writeBookmark(){const t=Math.round(this.frame()),o=this.#t;if(!o)return t;const e=o.scene;return!e||o.frameCurrent===t||(this.#l++,await Be(`bpy.data.scenes[${JSON.stringify(e)}]`,"frame_current",t,void 0,!1),this.#t={...o,frameCurrent:t},this.#f()),t}get transport(){return this.#e}attachTo(t){this.#r?.(),this.#e=t;const o=t.attach({id:this.#t?.action??"blender-action",label:this.#t?.action??"Action",range:()=>{const s=this.#t,u=s?.fps||24;return{start:(s?.frameStart??1)/u,end:(s?.frameEnd??250)/u,fps:u}},seek:s=>this.seekSeconds(s)}),e=t.onSettled(()=>{this.writeBookmark()}),a=()=>{e(),o(),this.#e===t&&(this.#e=null),this.#r=null};this.#r=a;const i=this.#t;return i&&i.fps>0&&t.seek(i.frameCurrent/i.fps),a}seekSeconds(t){const o=this.#t?.fps||24;this.#c(Math.round(t*o)),this.#f()}keyframes(){return(this.#t?.keyframes??[]).map(t=>t.frame)}dispose(){this.#r?.(),this.#o?.stopAllAction(),this.#o=null,this.#a=null;for(const t of this.#n.values())t.skeleton.dispose(),t.boneRoot.removeFromParent();this.#n.clear()}}const Jo=new sr;function dr(n){return Jo.subscribe(n)}function hr(){return Jo.version}export{Jo as a,hr as b,mr as c,dr as s};
7138
+ }`}),this.scene.clear(),this.scene.add(new Tt(this.geometry,this.material)),this.target.setSize(n.width,n.height);const _=t.getRenderTarget();try{t.setRenderTarget(this.target),t.render(this.scene,this.camera)}finally{t.setRenderTarget(_)}return this.target}dispose(){this.material?.dispose(),this.geometry.dispose(),this.target.dispose(),this.scene.clear()}}const sl=P({object:E(),group:E(),groupIndex:S().int().nonnegative(),count:S().int().nonnegative(),digest:E(),alertMode:W(["NONE","ACTIVE","ALL"]),unchanged:j(!0).optional(),weightsBase64:E().optional(),alertBase64:E().optional()}).strict();function fl(o){const n=o<0?0:o>1?1:o,e=(.5+.5*n)**1.5,[r,a,i]=cl(2/3*(1-n)),c=new ht;return c.setRGB((r*e)**(1/1.5),(a*e)**(1/1.5),(i*e)**(1/1.5),Mt),c}function cl(o){const t=(o%1+1)%1,n=Math.floor(t*6),e=t*6-n;switch(n%6){case 0:return[1,e,0];case 1:return[1-e,1,0];case 2:return[0,1,e];case 3:return[0,1-e,1];case 4:return[e,0,1];default:return[1,0,1-e]}}const ul=0;function Co(o){const t=atob(o),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}class _l{constructor(){this.group=new ot,this.mesh=null,this.material=null,this.geometry=null,this.held=null,this.signature="",this.group.name="BlenderWeightOverlay"}apply(t,n,e){if(t===null||n===null||!n.isMesh||e===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 d=Co(t.weightsBase64);this.held={key:r,weights:new Float32Array(d.buffer,d.byteOffset,t.count),alerts:Co(t.alertBase64)}}const a=this.held;if(a===null)return null;const i=`${r}:${t.digest}:${n.geometry.uuid}:${t.alertMode}:${e.elements.join(",")}`;if(i===this.signature&&this.mesh!==null)return null;this.signature=i,this.clear();const c=n.geometry.clone(),u=c.getAttribute("position"),f=c.getAttribute("blenderVertex");if(f===void 0)return c.dispose(),"weights: the presented geometry carries no per-vertex Blender index (`blenderVertex`), so the weights cannot be laid over it";const s=new Float32Array(u.count*3),l=new ht().setHex(ul,Mt);for(let d=0;d<u.count;d++){const m=f.getX(d),v=t.alertMode!=="NONE"&&a.alerts[m]===1?l:fl(a.weights[m]??0);s[d*3]=v.r,s[d*3+1]=v.g,s[d*3+2]=v.b}c.setAttribute("color",new it(s,3)),c.deleteAttribute("blenderVertex");const _=new bn({vertexColors:!0,polygonOffset:!0,polygonOffsetFactor:-1,polygonOffsetUnits:-1}),h=new Tt(c,_);return h.name=`${t.object}:weights`,h.frustumCulled=!1,h.matrixAutoUpdate=!1,h.matrix.copy(e),h.matrix.decompose(h.position,h.quaternion,h.scale),this.geometry=c,this.material=_,this.mesh=h,this.group.add(h),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 hn=S().finite(),ml=z($([hn,hn,hn,hn])).length(4),dl=20,ko=[16724818,9165824,2658559];function hl(o){const t=n=>Math.min(255,Math.max(0,Math.floor(.75*n+63.75)-60))/255;return new ht().setRGB(t(o>>16&255),t(o>>8&255),t(o&255),Mt)}function xe(){return new Be({vertexColors:!0,depthTest:!1,depthWrite:!1,transparent:!0,toneMapped:!1})}function pl(){const o=[],t=[],n=new ht(0,0,0),e=(a,i,c,u,f)=>{for(const s of[a,i]){const l=[0,0,0];l[c]=s*u,o.push(...l),t.push(f.r,f.g,f.b)}};for(let a=0;a<3;a++){const i=new ht().setHex(ko[a],Mt);e(1,.85,a,1,i),e(.85,.25,a,1,n),e(1,.85,a,-1,hl(ko[a])),e(.85,.25,a,-1,n)}const r=new fn;return r.setAttribute("position",new bt(o,3)),r.setAttribute("color",new bt(t,3)),new Ko(r,xe())}function vl(){const t=[],n=[],e=new ht(1,0,0),r=new ht(1,1,1);for(let i=0;i<12;i++){const c=(i+1)%2===0?r:e;for(const u of[i,i+1]){const f=2*Math.PI*u/12;t.push(.5*Math.cos(f),.5*Math.sin(f),0),n.push(c.r,c.g,c.b)}}const a=new fn;return a.setAttribute("position",new bt(t,3)),a.setAttribute("color",new bt(n,3)),new Ko(a,xe())}class gl{constructor(){this.group=new ot,this.anchor=new ot,this.lines=pl(),this.circle=vl(),this.seen=null,this.size=new $t,this.scratch=new x,this.parentQuat=new gt,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,n,e)=>this.fit(t,e),this.circle.onBeforeRender=(t,n,e)=>this.fit(t,e)}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[n,e,r,a]=t.rotation;this.anchor.matrix.compose(new x(...t.location),new gt(e,r,a,n),new x(1,1,1)),this.anchor.updateMatrixWorld(!0),this.present(!0)}fit(t,n){this.seen={camera:n,canvas:t.domElement},t.getSize(this.size);const e=Math.max(this.size.y,1),r=this.scratch.setFromMatrixPosition(this.anchor.matrixWorld);let a;if(n.isOrthographicCamera){const c=n;a=(c.top-c.bottom)/c.zoom/e}else{const c=n;a=2*Math.max(-r.applyMatrix4(n.matrixWorldInverse).z,1e-6)*Math.tan(ut.degToRad(c.fov)/2)/c.zoom/e}const i=a*dl;this.lines.scale.setScalar(i),this.lines.updateMatrixWorld(!0),this.circle.position.setFromMatrixPosition(this.anchor.matrix),this.group.getWorldQuaternion(this.parentQuat).invert(),n.getWorldQuaternion(this.circle.quaternion).premultiply(this.parentQuat),this.circle.scale.setScalar(i),this.circle.updateMatrixWorld(!0)}placementAt(t,n,e,r,a){const i=this.seen;if(i===null||e!==i.canvas)return null;const c=i.canvas.getBoundingClientRect(),u=new $t((t-c.left)/Math.max(c.width,1)*2-1,-((n-c.top)/Math.max(c.height,1))*2+1),f=new je;f.setFromCamera(u,i.camera);const s=m=>{for(let p=m;p!==null;p=p.parent)if(!p.visible)return!1;return!0},l=f.intersectObject(r,!0).find(m=>m.object.isMesh&&a(m.object)&&s(m.object));let _=l?l.point.clone():null;if(_===null){const m=new x().setFromMatrixPosition(this.anchor.matrixWorld),p=i.camera.getWorldDirection(new x),v=i.camera.getWorldPosition(new x),g=m.clone().sub(v).dot(p);g<=0&&m.addScaledVector(p,-2*g+(g===0?1:0)),_=f.ray.intersectPlane(new It().setFromNormalAndCoplanarPoint(p,m),new x)}if(_===null)return null;r.updateWorldMatrix(!0,!1);const h=r.worldToLocal(_),d=r.getWorldQuaternion(new gt).invert().multiply(i.camera.getWorldQuaternion(new gt));return{location:[h.x,h.y,h.z],rotation:[d.w,d.x,d.y,d.z]}}dispose(){for(const t of[this.lines,this.circle])t.geometry.dispose(),t.material.dispose();this.seen=null}}const Rt=S().finite(),xl=P({display:W(["PLAIN_AXES","ARROWS","SINGLE_ARROW","CIRCLE","CUBE","SPHERE","CONE","IMAGE"]),size:Rt,image:P({name:E().nullable(),offset:$([Rt,Rt]),depth:W(["DEFAULT","FRONT","BACK"]),side:W(["DOUBLE_SIDED","FRONT","BACK"]),perspective:q(),orthographic:q(),axis_aligned:q(),opacity:Rt.nullable(),tint:$([Rt,Rt,Rt]).default([1,1,1]),premultiplied:q().default(!1)}).optional()}),wt={selected:15554304,active:16752680,camera:0,light:0,lightAlpha:80/255,empty:0},bl=1,K=(o,t,n)=>o.push(t[0],t[1],t[2],n[0],n[1],n[2]);function at(o,t){return Array.from({length:t},(n,e)=>{const r=2*Math.PI*e/t;return[o*Math.cos(r),o*Math.sin(r)]})}function ct(o,t,n=0,e=!1){const r=e?2:1;for(let a=0;a<Math.floor(t.length/r);a++){const i=t[a*r%t.length],c=t[(a*r+1)%t.length];K(o,[i[0],i[1],n],[c[0],c[1],n])}}function yl(o){if(!o.isMesh||o.userData.vgaiOverrideStandDown)return;o.userData.vgaiOverrideStandDown=!0;const t=o.onBeforeRender.bind(o),n=o.onAfterRender.bind(o),e=new X;let r=!1;o.onBeforeRender=(a,i,c,u,f,s)=>{t(a,i,c,u,f,s),i.overrideMaterial&&(e.copy(o.matrixWorld),o.matrixWorld.makeScale(0,0,0),r=!0)},o.onAfterRender=(a,i,c,u,f,s)=>{r&&(o.matrixWorld.copy(e),r=!1),n(a,i,c,u,f,s)}}class wl{constructor(){this.cameras=new ot,this.lights=new ot,this.empties=new ot,this.lineMaterials=new Map,this.drawn=new Map,this.fillMaterials=new Map,this.scratch=new x,this.size=new $t,this.parentQuat=new gt,this.cameras.name="BlenderCameras",this.lights.name="BlenderLights",this.empties.name="BlenderEmpties"}apply(t){const n=new Set;for(const e of t.objects){const r=e.selected?e.name===t.active?wt.active:wt.selected:e.type==="CAMERA"?wt.camera:e.type==="LIGHT"?wt.light:wt.empty,a=e.type==="CAMERA"&&e.name!==t.lookingThrough?t.cameras[e.name]:void 0,i=e.type==="LIGHT"&&e.light?t.lights[e.light]:void 0,c=e.type==="EMPTY"?t.empties[e.name]:void 0;if(!a&&!i&&!c)continue;n.add(e.name);const u=i&&e.light?t.lightDistances[e.light]??null:null,f=c?.image?.name?t.image(c.image.name):null,s=JSON.stringify([f?[f.texture.uuid,f.width,f.height]:null,e.matrix,r,a,i,u,c,a?[e.name===t.sceneCamera,t.renderAspect]:null]),l=this.drawn.get(e.name),_=t.presented(e.name);if(l?.key===s){for(const v of l.parts)v.userData.vgaiPicksAs=_;continue}l&&this.remove(l.parts);const h=new X().set(...e.matrix.flat()),d=a?this.cameras:i?this.lights:this.empties,m=new Set(d.children);a?this.camera(a,h,r,e.name===t.sceneCamera,t.renderAspect):i?this.light(i,h,r,u):c&&this.empty(c,h,r,f);const p=d.children.filter(v=>!m.has(v));for(const v of p)v.userData.vgaiPicksAs=_,v.traverse(yl);this.drawn.set(e.name,{key:s,parts:p})}for(const[e,r]of this.drawn)n.has(e)||(this.remove(r.parts),this.drawn.delete(e))}remove(t){for(const n of t)n.removeFromParent(),n.geometry?.dispose(),n.userData.vgaiOwnMaterial&&n.material.dispose()}camera(t,n,e,r,a){const i=t.display_size,u=(t.sensor_fit==="AUTO"?a>=1:t.sensor_fit==="HORIZONTAL")?[1,1/a]:[a,1];let f,s,l,_;if(t.type==="ORTHO")l=[.5*t.ortho_scale*u[0],.5*t.ortho_scale*u[1]],_=[t.shift_x*t.ortho_scale,t.shift_y*t.ortho_scale],s=-i,f=.5*t.ortho_scale;else{const A=.5*(t.sensor_fit==="VERTICAL"?t.sensor_height:t.sensor_width),O=new x().setFromMatrixScale(n);if(O.x===0||O.y===0||O.z===0)return;f=i/2/((1/O.x+1/O.y+1/O.z)/3),s=f*t.lens/-A,l=[f*u[0],f*u[1]],_=[t.shift_x*f*2,t.shift_y*f*2]}const h=[[_[0]+l[0],_[1]+l[1],s],[_[0]+l[0],_[1]-l[1],s],[_[0]-l[0],_[1]-l[1],s],[_[0]-l[0],_[1]+l[1],s]],d=[];for(let A=0;A<4;A++)K(d,h[A],h[(A+1)%4]),K(d,h[A],[0,0,0]);const m=.7*f,p=.1*f,v=_[1]+l[1]+p,g=[[_[0]-m,v,s],[_[0]+m,v,s],[_[0],v+m,s]],b=Cn(n);this.cameras.add(this.lines(d,e,1,b));let w;if(r){const A=new fn;A.setAttribute("position",new bt(g.flat(),3)),w=new Tt(A,this.fill(e)),w.matrixAutoUpdate=!1,w.matrix.copy(b)}else{const A=[];for(let O=0;O<3;O++)K(A,g[O],g[(O+1)%3]);w=this.lines(A,e,1,b)}const R=new x,T=w.onBeforeRender.bind(w);w.onBeforeRender=(A,O,M,C,V,H)=>{R.setFromMatrixPosition(b).applyMatrix4(this.cameras.matrixWorld);const Q=M.getWorldPosition(this.scratch).distanceToSquared(R)>1e-8;w.matrix.copy(b),Q||w.matrix.scale(new x(0,0,0)),w.updateMatrixWorld(!0),T(A,O,M,C,V,H)},this.cameras.add(w)}light(t,n,e,r){const a=new x().setFromMatrixPosition(n),i=[];K(i,[a.x,a.y,a.z],[a.x,a.y,0]),this.lights.add(this.lines(i,wt.light,wt.lightAlpha,new X));const c=[];ct(c,at(1.35,4)),this.lights.add(this.screen(c,wt.light,wt.lightAlpha,new x(a.x,a.y,0)));const u=[],f=9;if(ct(u,at(f*.3,4)),ct(u,at(f,16),0,!0),ct(u,at(f*1.33,20),0,!0),t.type==="SUN")for(const[_,h]of at(f,8))K(u,[_*1.6,h*1.6,0],[_*1.9,h*1.9,0]),K(u,[_*2.2,h*2.2,0],[_*2.5,h*2.5,0]);this.lights.add(this.screen(u,e,1,a));const s=Cn(n),l=[];if(t.type==="SUN")K(l,[0,0,0],[0,0,-20]);else if(t.type==="AREA"){const _=(t.size??1)/2,h=(t.shape==="RECTANGLE"||t.shape==="ELLIPSE"?t.size_y??t.size??1:t.size??1)/2;t.shape==="DISK"||t.shape==="ELLIPSE"?ct(l,at(1,32).map(([d,m])=>[d*_,m*h])):ct(l,[[_,h],[-_,h],[-_,-h],[_,-h]])}if(l.length>0&&this.lights.add(this.lines(l,e,1,n.clone())),r&&(t.type==="SPOT"||t.type==="AREA")){const _=new x(0,0,-1).transformDirection(n),h=v=>a.clone().addScaledVector(_,v),[d,m]=r,p=[];K(p,h(d).toArray(),h(m).toArray()),this.lights.add(this.lines(p,e,1,new X));for(const v of[d,m]){const g=[];ct(g,at(1.2,4)),this.lights.add(this.screen(g,e,1,h(v)))}}if(t.type==="SPOT"){const _=(t.spot_size??Math.PI/4)/2,h=Math.cos(_),d=t.spot_blend??.15,m=h*d-h-d,p=Math.sqrt((h*h-h*h*m*m)/(m*m-h*h*m*m)),v=Math.sqrt(1-h*h),g=Cn(n).multiply(new X().makeScale(10,10,10)),b=[];ct(b,at(v,32),-h),ct(b,at(v*p,32),-h),this.lights.add(this.lines(b,e,1,g.clone())),this.lights.add(this.silhouette(v,h,e,g))}if((t.type==="POINT"||t.type==="SPOT")&&(t.radius??0)>0){const _=[];ct(_,at(t.radius,32)),this.lights.add(this.facing(_,e,new x().setFromMatrixPosition(s)))}}empty(t,n,e,r){const a=t.size,i=[],c=(f,s)=>{const l=at(1,s);for(let _=0;_<s;_++){const[h,d]=l[_],[m,p]=l[(_+1)%s],v=(g,b)=>f==="xy"?[g,b,0]:f==="xz"?[g,0,b]:[0,g,b];K(i,v(h,d),v(m,p))}};switch(t.display){case"PLAIN_AXES":K(i,[0,-1,0],[0,1,0]),K(i,[-1,0,0],[1,0,0]),K(i,[0,0,-1],[0,0,1]);break;case"SINGLE_ARROW":{K(i,[0,0,0],[0,0,.75]);for(const[f,s]of[[.035,.035],[-.035,.035],[-.035,-.035],[.035,-.035]])K(i,[0,0,1],[f,s,.75]);ct(i,[[.035,.035],[-.035,.035],[-.035,-.035],[.035,-.035]],.75);break}case"CUBE":for(const[f,s]of Ol)K(i,$o[f],$o[s]);break;case"CIRCLE":c("xz",64);break;case"SPHERE":c("xy",32),c("xz",32),c("yz",32);break;case"CONE":{const f=at(1,8);for(let s=0;s<8;s++){const[l,_]=f[s],[h,d]=f[(s+1)%8];K(i,[l,0,_],[0,2,0]),K(i,[l,0,_],[h,0,d])}break}case"ARROWS":for(let f=0;f<3;f++){const s=[0,0,0];s[f]=1,K(i,[0,0,0],s)}break;case"IMAGE":this.imageEmpty(t,n,e,r);return}const u=n.clone().multiply(new X().makeScale(a,a,a));this.empties.add(this.lines(i,e,1,u)),t.display==="ARROWS"&&this.axisNames(n,a,e)}silhouette(t,n,e,r){const a=this.lines(new Array(192).fill(0),e,1,r);a.frustumCulled=!1;const i=a.geometry.getAttribute("instanceStart").data,c=at(1,32).map(([h,d])=>new x(h*t,d*t,-n)),u=new x,f=new X,s=new x,l=new x,_=new x;return this.onDraw(a,(h,d)=>{f.copy(a.matrixWorld).invert();const m=d.isOrthographicCamera;m?d.getWorldDirection(u).negate().transformDirection(f):u.setFromMatrixPosition(d.matrixWorld).applyMatrix4(f);const p=i.array;let v=!1;for(let g=0;g<32;g++){const b=c[g];s.crossVectors(b,c[(g+31)%32]),l.crossVectors(c[(g+1)%32],b),m?_.copy(u):_.copy(u).sub(b);const w=s.dot(_)>0!=l.dot(_)>0;(p[g*6+3]!==0||p[g*6+5]!==0)!==w&&(v=!0),p.set([0,0,0,w?b.x:0,w?b.y:0,w?b.z:0],g*6)}v&&(i.needsUpdate=!0,vt())}),a}imageEmpty(t,n,e,r){const a=t.image;if(!a)return;const i=r?.width??0,c=r?.height??0,u=i>0&&c>0?i>=c?[1,c/i]:[i/c,1]:[1,1],f=new x,s=new x,l=new x;n.extractBasis(f,s,l),f.multiplyScalar(u[0]*.5*t.size),s.multiplyScalar(u[1]*.5*t.size);const _=new x().setFromMatrixPosition(n).addScaledVector(f,a.offset[0]*2+1).addScaledVector(s,a.offset[1]*2+1),h=new X().makeBasis(f,s,l.clone()).setPosition(_),d=[];ct(d,[[-1,-1],[1,-1],[1,1],[-1,1]]);const m=this.lines(d,e,1,h),p=l.clone().normalize(),v=new x,g=new x,b=(M,C)=>{const V=M.isOrthographicCamera===!0;if(V?!a.orthographic:!a.perspective)return!1;if(!C)return!0;const H=p.clone().transformDirection(this.empties.matrixWorld);M.getWorldDirection(g);let Q,tt;if(V)Q=H.dot(g.clone().negate()),tt=1e-5;else{const pt=_.clone().applyMatrix4(this.empties.matrixWorld);Q=H.dot(v.setFromMatrixPosition(M.matrixWorld).sub(pt)),tt=0}return!(a.side==="FRONT"&&Q<tt||a.side==="BACK"&&Q>-tt||a.axis_aligned&&H.clone().projectOnPlane(g).lengthSq()>1e-5)},w=(M,C)=>{const V=M.onBeforeRender.bind(M);M.onBeforeRender=(H,Q,tt,pt,y,L)=>{M.matrix.copy(h),b(tt,C)||M.matrix.scale(new x(0,0,0)),M.updateMatrixWorld(!0),V(H,Q,tt,pt,y,L)}};if(w(m,!1),this.empties.add(m),!r||a.opacity!==null&&a.opacity<=0)return;const R=a.opacity!==null,T=a.depth==="BACK",A=new bn({map:r.texture,side:uo,transparent:R&&!T,opacity:a.opacity??1,alphaTest:R?0:.05,toneMapped:!1,depthTest:a.depth==="DEFAULT",depthWrite:a.depth==="DEFAULT"&&!R});A.color.setRGB(...a.tint,ft),R&&T&&(A.blending=Ue,A.blendSrc=We,A.blendDst=He),A.onBeforeCompile=M=>{const C=a.premultiplied?`if ( sampledDiffuseColor.a > 0.0 && sampledDiffuseColor.a < 1.0 ) sampledDiffuseColor.rgb /= sampledDiffuseColor.a;
7139
+ `:"";M.fragmentShader=M.fragmentShader.replace("#include <map_fragment>",`vec4 sampledDiffuseColor = texture2D( map, vMapUv );
7140
+ ${C}diffuseColor *= sampledDiffuseColor;`).replace("#include <alphatest_fragment>",R?"#include <alphatest_fragment>":`#include <alphatest_fragment>
7141
+ diffuseColor.a = 1.0;`)},A.customProgramCacheKey=()=>`vgai-blender-image:${a.premultiplied}:${R}`;const O=new Tt(new Qo(2,2),A);O.matrixAutoUpdate=!1,O.matrix.copy(h),O.renderOrder=a.depth==="FRONT"?1e3:a.depth==="BACK"?-1e3:0,O.userData.vgaiOwnMaterial=!0,w(O,!0),this.empties.add(O)}axisNames(t,n,e){const r=[new x,new x,new x];t.extractBasis(r[0],r[1],r[2]);for(let a=0;a<3;a++){const i=r[a].length()*n,c=new x(0,0,0);c.setComponent(a,1.25*n),c.applyMatrix4(t);const u=new x(0,0,0);u.setComponent(a,n),u.applyMatrix4(t);const f=[];for(let _=1;_<=6;_++)ct(f,at(.007*(4*_/6)*i,4));this.empties.add(this.facing(f,e,u));const s=Tl[a],l=[];for(let _=0;_+1<s.length;_+=2){const[h,d]=s[_],[m,p]=s[_+1];K(l,[h*4*i,d*4*i,0],[m*4*i,p*4*i,0])}this.empties.add(this.facing(l,e,c))}}material(t,n){const e=`${t}:${n}`;let r=this.lineMaterials.get(e);return r||(r=new Wo({color:t,linewidth:bl,transparent:n<1,opacity:n,depthTest:!0,depthWrite:n>=1,toneMapped:!1}),this.lineMaterials.set(e,r)),r}fill(t){let n=this.fillMaterials.get(t);return n||(n=new bn({color:t,side:uo,toneMapped:!1}),this.fillMaterials.set(t,n)),n}lines(t,n,e,r){const a=new Uo().setPositions(t),i=new Ho(a,this.material(n,e));return i.matrixAutoUpdate=!1,i.matrix.copy(r),i.computeLineDistances(),i}screen(t,n,e,r){const a=this.lines(t,n,e,new X);return a.matrixAutoUpdate=!0,a.position.copy(r),a.scale.setScalar(0),a.frustumCulled=!1,this.onDraw(a,(i,c)=>this.face(a,i,c,!0)),a}facing(t,n,e){const r=this.lines(t,n,1,new X);return r.matrixAutoUpdate=!0,r.position.copy(e),this.onDraw(r,(a,i)=>this.face(r,a,i,!1)),r}onDraw(t,n){const e=t,r=e.onBeforeRender.bind(e);e.onBeforeRender=(a,i,c,u,f,s)=>{n(a,c),r(a,i,c,u,f,s)}}face(t,n,e,r){t.parent?.getWorldQuaternion(this.parentQuat).invert(),e.getWorldQuaternion(t.quaternion).premultiply(this.parentQuat);let a=1;if(r){n.getSize(this.size);const i=Math.max(this.size.y,1),c=this.scratch.setFromMatrixPosition(t.matrixWorld);if(e.isOrthographicCamera){const u=e;a=(u.top-u.bottom)/u.zoom/i}else{const u=e;a=2*Math.max(-c.applyMatrix4(e.matrixWorldInverse).z,1e-6)*Math.tan(ut.degToRad(u.fov)/2)/u.zoom/i}}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 Cn(o){const t=new x,n=new gt;return o.decompose(t,n,new x),new X().compose(t,n,new x(1,1,1))}const $o=[[-1,-1,-1],[1,-1,-1],[1,1,-1],[-1,1,-1],[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],Ol=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]],Tl=[[[.9,1],[-1,-1],[-.9,1],[1,-1]].map(([o,t])=>[o*.0215,t*.025]),[[-1,1],[0,-.1],[1,1],[0,-.1],[0,-.1],[0,-1]].map(([o,t])=>[o*.0175,t*.025]),[[-.95,1],[.95,1],[.95,1],[.95,.9],[.95,.9],[-1,-.9],[-1,-.9],[-1,-1],[-1,-1],[1,-1]].map(([o,t])=>[o*.02,t*.025])],rt=S().finite(),Lo=P({name:E(),type:E(),lens:rt,sensor_width:rt,sensor_height:rt,sensor_fit:W(["AUTO","HORIZONTAL","VERTICAL"]),ortho_scale:rt,clip_start:rt,clip_end:rt,shift_x:rt,shift_y:rt,matrix:z($([rt,rt,rt,rt])).length(4),passepartout:rt.default(0),display_size:rt.default(1)}),Pl={opening:.5,min:.1657359312880715,max:44.98528137423857},pn={passepartout:"#000000",back:"#3d3d3d",overlay:"#000000",redalert:"#991616"};function Al(o,t,n,e){const r=a=>Math.min(1,Math.max(-1,a));return[r(o[0]-n/(2*t)),r(o[1]+e/(2*t))]}function Vo(o,t,n,e){const r=o.type==="ORTHO",a=o.sensor_fit==="VERTICAL"?o.sensor_height:o.sensor_width,i=o.sensor_fit==="AUTO"?t>=n:o.sensor_fit==="HORIZONTAL",c=(r?o.ortho_scale:a/o.lens)/2*e;return i?[c,c*n/t]:[c*t/n,c]}function Sl(o,t,n,e,r,a){const i=Math.max(n.width,1),c=Math.max(n.height,1),[u,f]=Vo(o,i,c,1/e),[s,l]=Vo(o,a,1,1),h=2*((o.sensor_fit==="AUTO"?a>=1:o.sensor_fit==="HORIZONTAL")?s:l),d=s/u,m=l/f,p=-2*r[0]*e,v=2*r[1]*e,g=o.shift_x*h-p*2*u,b=o.shift_y*h+v*2*f,w=new X().set(...o.matrix.flat()).premultiply(t),R=new x,T=new gt;return w.decompose(R,T,new x),{name:o.name,position:R.toArray(),quaternion:[T.x,T.y,T.z,T.w],projection:o.type==="ORTHO"?"orthographic":"perspective",window:{left:g-u,right:g+u,top:b+f,bottom:b-f},near:o.clip_start,far:o.clip_end,frame:{left:.5-d/2+p,top:.5-m/2+v,width:d,height:m},passepartout:{color:pn.passepartout,opacity:o.passepartout},border:{solid:pn.back,dashed:pn.overlay,locked:pn.redalert}}}const El={color:[.8,.8,.8,1],roughness:.5,metallic:0},Ml=`
7142
+ uniform vec3 wbDir[4];
7143
+ uniform vec3 wbDiffuse[4];
7144
+ uniform vec3 wbSpecular[4];
7145
+ uniform vec4 wbWrap;
7146
+ uniform float wbRoughness;
7147
+ uniform float wbMetallic;
7148
+
7149
+ vec4 wbWrapped(vec4 NL, vec4 w) {
7150
+ vec4 w1 = w + 1.0;
7151
+ return clamp((NL + w) / (w1 * w1), 0.0, 1.0);
7152
+ }
7153
+
7154
+ vec3 vgaiWorkbenchLighting(vec3 baseColor, vec3 N, vec3 I) {
7155
+ vec3 diffuseColor = mix(baseColor, vec3(0.0), wbMetallic);
7156
+ vec3 specularColor = mix(vec3(0.05), baseColor, wbMetallic);
7157
+ vec3 R = -reflect(I, N);
7158
+ vec4 wrapNL = vec4(dot(wbDir[0], R), dot(wbDir[1], R), dot(wbDir[2], R), dot(wbDir[3], R));
7159
+ vec4 specAngle = clamp(vec4(
7160
+ dot(normalize(wbDir[0] + I), N), dot(normalize(wbDir[1] + I), N),
7161
+ dot(normalize(wbDir[2] + I), N), dot(normalize(wbDir[3] + I), N)), 0.0, 1.0);
7162
+ vec4 specNL = clamp(vec4(dot(wbDir[0], N), dot(wbDir[1], N), dot(wbDir[2], N), dot(wbDir[3], N)), 0.0, 1.0);
7163
+ vec4 gloss = vec4(1.0 - wbRoughness) * (1.0 - wbWrap);
7164
+ vec4 shininess = exp2(10.0 * gloss + 1.0);
7165
+ vec4 specLight = pow(specAngle, shininess) * specNL * (shininess * 0.125 + 1.0);
7166
+ vec4 envW = mix(wbWrap, vec4(1.0), wbRoughness);
7167
+ vec4 specEnv = wbWrapped(wrapNL, envW);
7168
+ specLight = mix(specLight, specEnv, wbWrap * wbWrap);
7169
+ vec3 specularLight = specLight.x * wbSpecular[0] + specLight.y * wbSpecular[1] +
7170
+ specLight.z * wbSpecular[2] + specLight.w * wbSpecular[3];
7171
+ float NV = clamp(dot(N, I), 0.0, 1.0);
7172
+ float fresnel = exp2(-8.35 * NV) * (1.0 - wbRoughness);
7173
+ specularColor = mix(specularColor, vec3(1.0), fresnel);
7174
+ specularLight *= specularColor;
7175
+ vec4 diffNL = vec4(dot(wbDir[0], N), dot(wbDir[1], N), dot(wbDir[2], N), dot(wbDir[3], N));
7176
+ vec4 diffLight = wbWrapped(diffNL, wbWrap);
7177
+ vec3 diffuseLight = diffLight.x * wbDiffuse[0] + diffLight.y * wbDiffuse[1] +
7178
+ diffLight.z * wbDiffuse[2] + diffLight.w * wbDiffuse[3];
7179
+ float specEnergy = dot(specularColor, vec3(0.33333));
7180
+ diffuseLight *= diffuseColor * (1.0 - specEnergy);
7181
+ return diffuseLight + specularLight;
7182
+ }
7183
+ `,fo=o=>ao.map(t=>{const[n=0,e=0,r=0]=o(t);return new x(n,e,r)}),Nl=fo(o=>o.direction).map(o=>o.normalize()),Rl=fo(o=>o.diffuse),Il=fo(o=>o.specular),zl=new Jn(...ao.map(o=>o.smooth));function Fl(o,t){const[n,e,r]=o.color,a=new qe({side:t});return a.color.setRGB(n,e,r,ft),a.name="vgai:blender-solid",a.onBeforeCompile=i=>{i.uniforms.wbDir={value:Nl},i.uniforms.wbDiffuse={value:Rl},i.uniforms.wbSpecular={value:Il},i.uniforms.wbWrap={value:zl},i.uniforms.wbRoughness={value:o.roughness},i.uniforms.wbMetallic={value:o.metallic},i.fragmentShader=i.fragmentShader.replace("void main() {",`${Ml}
7184
+ void main() {`).replace("#include <opaque_fragment>",`outgoingLight = vgaiWorkbenchLighting(diffuseColor.rgb, normal, isOrthographic ? vec3(0.0, 0.0, 1.0) : normalize(vViewPosition));
7185
+ #include <opaque_fragment>`)},a.customProgramCacheKey=()=>"vgai-blender-workbench",a}const I=S().finite(),be=$([I,I,I]),vn=$([S().int().nonnegative(),S().int().nonnegative()]),lt={name:E(),domain:W(["POINT","EDGE","FACE","CORNER"])},Dl=ca("type",[P({...lt,type:j("FLOAT2"),data:z($([I,I]))}).strict(),P({...lt,type:j("FLOAT_VECTOR"),data:z(be)}).strict(),P({...lt,type:j("FLOAT_COLOR"),data:z($([I,I,I,I]))}).strict(),P({...lt,type:j("BYTE_COLOR"),data:z($([I,I,I,I]))}).strict(),P({...lt,type:j("QUATERNION"),data:z($([I,I,I,I]))}).strict(),P({...lt,type:j("FLOAT4"),data:z($([I,I,I,I]))}).strict(),P({...lt,type:j("FLOAT4X4"),data:z(z(I).length(16))}).strict(),P({...lt,type:j("INT16_2D"),data:z($([S().int(),S().int()]))}).strict(),P({...lt,type:j("INT32_2D"),data:z($([S().int(),S().int()]))}).strict(),P({...lt,type:j("FLOAT"),data:z(I)}).strict(),P({...lt,type:j("INT"),data:z(S().int())}).strict(),P({...lt,type:j("INT8"),data:z(S().int())}).strict(),P({...lt,type:j("BOOLEAN"),data:z(q())}).strict(),P({...lt,type:j("STRING"),data:z(E())}).strict()]),Cl=P({positions:B(Float32Array),normals:B(Float32Array).nullable(),uv:B(Float32Array).nullable(),uvLayers:z(P({name:E(),data:B(Float32Array)}).strict()).optional(),attributeLayers:z(P({name:E(),data:B(Float32Array)}).strict()).optional(),orco:B(Float32Array).nullable().optional(),indices:B(Uint32Array),groups:z(P({start:S().int().nonnegative(),count:S().int().nonnegative(),materialIndex:S().int().nonnegative()}).strict()),hash:E()}).strict(),kl=P({v:z(be),f:z(z(S().int().nonnegative())),e:z(vn).optional(),edge_order:z(vn).optional(),m:z(S().int().nonnegative()).optional(),s:z(q()).optional(),sharp:z(vn).optional(),seams:z(vn).optional(),creases:z($([I,I,I])).optional(),attributes:z(Dl).optional(),active_uv:E().nullable().optional(),render_uv:E().nullable().optional()}).strict(),$l=P({store:S().int().optional(),revision:S().int(),unchanged:j(!0)}).strict(),Ll=P({co:B(Float64Array),cornerNormal:B(Float32Array).optional(),orco:B(Float32Array).optional(),faceStart:B(Uint32Array),corner:B(Uint32Array),cornerEdge:B(Int32Array),edge:B(Uint32Array),edgeSharp:B(Uint8Array),edgeSeam:B(Uint8Array),edgeCrease:B(Float32Array),material:B(Uint32Array),smooth:B(Uint8Array),vertSelect:B(Uint8Array),vertHide:B(Uint8Array),edgeSelect:B(Uint8Array),edgeHide:B(Uint8Array),faceSelect:B(Uint8Array),faceHide:B(Uint8Array)}).strict(),Vl=P({name:E(),domain:W(["POINT","EDGE","FACE","CORNER"]),type:E(),data:ua(o=>ArrayBuffer.isView(o))}).strict(),jl=P({columns:Ll,attributes:z(Vl),activeUv:E().nullable(),renderUv:E().nullable(),counts:P({verts:S().int().nonnegative(),edges:S().int().nonnegative(),faces:S().int().nonnegative(),corners:S().int().nonnegative()}).strict(),revision:S().int().nonnegative()}).strict(),Bl=jt([Cl,jl,kl,$l]),jo=new Set;function Ul(o){const t=new Blob([o],{type:"image/png"}),n=new Je;let e=!1;n.addEventListener("dispose",()=>{e=!0,n.image?.close?.()});const r=createImageBitmap(t,{imageOrientation:"flipY",premultiplyAlpha:"none"}).then(a=>{if(e){a.close();return}n.image=a,n.needsUpdate=!0,vt()}).finally(()=>{jo.delete(r)});return jo.add(r),r.catch(()=>{}),{texture:n,ready:r}}function Wl(o,t,n,e){const r=new Tn(o,t,n,Pn,Ke);return r.flipY=!1,r.colorSpace=e==="data"?no:Mt,r.needsUpdate=!0,r}function Hl(o,t,n){if(t.length===0)throw new Error(`Runtime image ${o} is tiled with no tiles`);const e=Math.max(...t.map(s=>s.width)),r=Math.max(...t.map(s=>s.height)),a=new Uint8Array(e*r*4*t.length),i=Math.max(...t.map(s=>s.number-1001))+1,c=new Float32Array(i*2*4);for(let s=0;s<i;s++)c[s*4]=-1;t.forEach((s,l)=>{const _=s.rgba??(s.rgbaBase64?Un(s.rgbaBase64):void 0);if(!_)throw new Error(`Runtime image ${o} tile ${s.number} carries no raster`);for(let d=0;d<s.height;d++)a.set(_.subarray(d*s.width*4,(d+1)*s.width*4),(l*r+d)*e*4);const h=s.number-1001;c[h*4]=l,c.set([0,0,s.width/e,s.height/r],(i+h)*4)});const u=new Qe(a,e,r,t.length);u.colorSpace=n==="data"?no:Mt,u.magFilter=Lt,u.minFilter=Jo,u.generateMipmaps=!0,u.needsUpdate=!0;const f=new Tn(c,i,2,Pn,Yo);return f.magFilter=f.minFilter=jn,f.needsUpdate=!0,{tiles:u,map:f,frame:t}}const ql=P({width:S().int().positive(),height:S().int().positive(),revision:S().int().nonnegative(),rgba:B(Uint8Array).optional(),rgbaBase64:E().optional(),colorspace:W(["sRGB","data"]).optional(),tiles:z(P({number:S().int().min(1001),width:S().int().positive(),height:S().int().positive(),rgba:B(Uint8Array).optional(),rgbaBase64:E().optional()}).strict()).optional()}).strict(),Gl=P({revision:S().int().nonnegative(),png:B(Uint8Array).optional(),pngBase64:E().optional()}).strict(),Xl=jt([ql,Gl]),kn=P({image:P({name:E(),revision:S().int().nonnegative()}).strict(),extension:W(["REPEAT","EXTEND","MIRROR","CLIP"]).default("REPEAT"),uv:E(),tint:$([I,I,I]).optional()}).strict(),Yl=P({name:E(),color:$([I,I,I,I]),roughness:I,metallic:I,transmission:I,ior:I,physical:ol.optional(),normal_texture:kn.optional(),normal_strength:I.default(1),normal_space:W(["TANGENT","OBJECT"]).default("TANGENT"),normal_directx:q().default(!1),texture:kn.optional(),roughness_texture:kn.optional(),emission:P({color:$([I,I,I]),strength:I}).strict().optional(),graph:Nr.optional(),viewport:P({color:$([I,I,I,I]),roughness:I,metallic:I}).strict().optional()}).strict(),Zl=P({session:E(),revision:S().int().nonnegative(),volumes:_t(E(),me).default({}),lights:_t(E(),mr).default({}),world:yr.nullable().default(null),meshes:_t(E(),Bl),materials:_t(E(),Yl),images:_t(E(),Xl).default({}),objects:z(P({id:E(),name:E(),type:W(["MESH","CURVE","SURFACE","FONT","META","ARMATURE","LATTICE","VOLUME","EMPTY","CAMERA","LIGHT","SPEAKER","GREASEPENCIL","POINTCLOUD","LIGHT_PROBE"]),mesh:E().nullable(),volume:E().nullable().optional(),light:E().nullable().optional(),materials:z(E().nullable()),matrix:z($([I,I,I,I])).length(4),visible:q(),render_visible:q().default(!0),selected:q(),parent:E().nullable(),texspace:$([$([I,I,I]),$([I,I,I])]).optional(),default_color:E().optional()}).strict()),active:E().nullable(),mode:E(),cameras:_t(E(),_t(E(),ne())).default({}),warnings:z(E()).default([]),updated:z(E()).default([]),frame:S().int().default(0),armatures:_t(E(),ha).default({}),weights:sl.nullable().default(null),cursor:ml.optional(),camera_view:P({scene_camera:E().nullable(),view_layer_cameras:z(E()),aspect:S().finite().positive()}).optional(),light_distances:_t(E(),$([S().finite(),S().finite()])).default({}),empties:_t(E(),xl).default({}),view:P({location:$([S(),S(),S()]),rotation:$([S(),S(),S(),S()]),distance:S().finite(),perspective:W(["PERSP","ORTHO","CAMERA"]),lens:S().finite().positive().default(50)}).nullable().optional(),subject:P({frame:S().int(),body:E(),markers:z($([S().int(),E()]))}).optional(),units:P({system:W(["NONE","METRIC","IMPERIAL"]),scale_length:S().finite()}).optional()}).strict();function Ql(o,t){for(let n=0,e=o.length-1;n<o.length&&e>=0;n++,e--){if(o[n][0]===t)return o[n][1];if(n===e)break;if(o[e][0]===t)return o[e][1]}return null}const Kl={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 co{constructor(){this.root=new ot,this.objects=new Map,this.meshes=new Map,this.volumes=new Map,this.materials=new Map,this.lights=new Map,this.lighting=new br,this.world=new ro,this.armatureOverlay=new Aa,this.weightOverlay=new _l,this.cursorOverlay=new gl,this.extrasOverlay=new wl,this.armatureRoot=new ot,this.weightRoot=new ot,this.cursorRoot=new ot,this.cameraExtrasRoot=new ot,this.lightExtrasRoot=new ot,this.emptyExtrasRoot=new ot,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 ln({color:12172998,roughness:.72}),this.textures=new Map,this.textureNames=new Map,this.roughnessTextureNames=new Map,this.textureSamplers=new nl,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.cameraViewZoom=Pl,this.cameraViewPan=Al,this.mode=null,this.awaitedImages=new Set,this.lookingThrough=null,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[t,n]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]])t.matrixAutoUpdate=!1,t.matrix.copy(this.root.matrix),t.add(n),t.updateMatrixWorld(!0);this.armatureRoot.name="BlenderBones",this.weightRoot.name="BlenderWeights",this.cursorRoot.name="Blender3DCursor",this.cameraExtrasRoot.name="BlenderCameraExtras";for(const t of[this.cameraExtrasRoot,this.lightExtrasRoot,this.emptyExtrasRoot])t.userData.vgaiPickable=!0;this.lightExtrasRoot.name="BlenderLightExtras",this.emptyExtrasRoot.name="BlenderEmptyExtras"}compiledGraph(t){const n=JSON.stringify(t);let e=this.graphs.get(n);return e||(e=Wr(t),this.graphs.size>256&&this.graphs.clear(),this.graphs.set(n,e)),e}subscribeFrames(t){return this.frameListeners.add(t),()=>{this.frameListeners.delete(t)}}onChange(t){const n=this.subscribeFrames(t),e=ma(t);return()=>{n(),e()}}blenderObjectName(t){for(const[n,e]of this.objects)if(e===t)return this.frame?.objects.find(r=>r.id===n)?.name??null;return null}savedView(){const t=this.frame?.view;if(!t)return null;const[n,e,r,a]=t.rotation,i=new gt(e,r,a,n),c=new x(...t.location).applyMatrix4(this.root.matrix),u=f=>f.applyQuaternion(i).applyMatrix4(this.root.matrix).normalize();return{target:c.toArray(),direction:u(new x(0,0,1)).toArray(),up:u(new x(0,1,0)).toArray(),distance:t.distance,projection:t.perspective==="ORTHO"?"orthographic":"perspective",lens:t.lens}}cameraViewCamera(){const t=this.frame,n=t?.camera_view;return!t||!n?null:n.scene_camera!==null&&t.cameras[n.scene_camera]?n.scene_camera:t.active!==null&&t.cameras[t.active]?t.active:n.view_layer_cameras.find(e=>t.cameras[e])??null}blenderPose(t,n){const e=new X().copy(this.root.matrix).invert(),r=new X().compose(new x(...t),new gt(...n),new x(1,1,1)).premultiply(e),a=new x,i=new gt;return r.decompose(a,i,new x),{location:a.toArray(),rotation:[i.w,i.x,i.y,i.z]}}cameraView(t,n,e,r){const a=this.frame,i=Lo.safeParse(a?.cameras[t]);return!a?.camera_view||!i.success?null:Sl(i.data,this.root.matrix,n,e,r,a.camera_view.aspect)}subjectLine(t){const n=this.frame?.subject;if(n===void 0)return null;const e=t??n.frame,r=Ql(n.markers,e);return`(${e})${n.body}${r===null?"":` <${r}>`}`}gridUnitName(t){const n=this.frame?.units;if(n===void 0||n.system==="NONE")return null;const e=Kl[n.system],r=6*t,a=1/(n.scale_length||1);return(e.find(([c])=>c*a>r)??e[e.length-1])[1]}blenderSelection(){const t=this.frame;return t===null?{selected:[],active:null}:{selected:t.objects.filter(n=>n.selected).map(n=>n.name),active:t.active}}setStageMode(t){this.mode=t}stageMode(){return this.mode}objectForBlenderName(t){const n=this.frame?.objects.find(e=>e.name===t);return n===void 0?null:this.objects.get(n.id)??null}replacePresentedObject(t,n){for(const[e,r]of this.objects)if(r===t){const a=t.parent,i=[...t.children];t.removeFromParent();for(const c of i)n.add(c);a?.add(n),this.objects.set(e,n);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,n,e){const r=new Set(this.objects.values()),a=this.cursorOverlay.placementAt(t,n,e,this.root,i=>r.has(i));return a!==null&&(this.cursorOverlay.show(a),vt()),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 e=t.isOrthographicCamera?t.getWorldDirection(new x).toArray().map(r=>r.toFixed(1)).join(","):"";return`${t.uuid}:${e}:${this.worldKey}`}report(t){t.then(vt,n=>console.error(`Rendered shading could not be applied: ${n instanceof Error?n.message:String(n)}`))}setWorkbench(t){t!==this.workbench&&(this.workbench=t,this.applyWorkbench(),vt())}applyWorkbench(){const t=this.workbench&&!this.rendered,n=new Set;for(const e of this.frame?.objects??[]){if(e.mesh===null||e.volume)continue;const r=this.objects.get(e.id);if(!r?.isMesh)continue;const i=(e.materials.length?e.materials:[null]).map(c=>{const u=c===null?this.fallback:this.materials.get(c)??this.fallback;return t?this.workbenchFor(c,u.side,n):u});r.material=e.materials.length?i:i[0]}for(const[e,r]of this.workbenchMaterials)n.has(e)||(r.dispose(),this.workbenchMaterials.delete(e))}workbenchFor(t,n,e){const r=(t!==null?this.frame?.materials[t]?.viewport:void 0)??El,a=`${r.color.join(",")}|${r.roughness}|${r.metallic}|${n}`;e.add(a);let i=this.workbenchMaterials.get(a);return i||(i=Fl(r,n),this.workbenchMaterials.set(a,i)),i}renderedHeld(){return this.heldRendered!==null}async setRendered(t,n){return this.capturing=t,!t&&this.heldRendered!==null?this.applyRendered(!0,this.heldRendered()):this.applyRendered(t,n)}async applyRendered(t,n){const e=(t?Do(this.frame?.world)?.extinction:null)??new x;for(const a of[...this.materials.values(),this.fallback])al(a,e);this.rendered=t,this.lighting.setRendered(t);const r=t&&n?this.worldKeyFor(n):null;t?(this.capturing||r!==this.worldApplied)&&this.world.apply(this.root,this.frame?.world??null,n):this.world.clear(),this.worldApplied=this.capturing?null:r,this.applyVisibility(),this.applyWorkbench(),this.applyShadows(t,n),t&&(await hr(),await Promise.all([...this.textures.values()].map(a=>a.ready)),await this.world.ready())}applyShadows(t,n){this.root.updateMatrixWorld(!0);const e=[];for(const u of this.objects.values()){const f=u;if(f.isMesh&&(f.castShadow=t,f.receiveShadow=t,t&&f.visible)){const s=new yn().setFromObject(f);s.isEmpty()||e.push(s)}}if(!t||!e.length)return;const a=e.reduce((u,f)=>u.union(f),new yn).getBoundingSphere(new Ge),i=n?new Xe().setFromProjectionMatrix(new X().multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse)):null,c=i?e.flatMap(u=>Tr(u,i)):[];for(const u of this.lights.values())u.isDirectionalLight&&n?Pr(u,c,e):gr(u,a.center,a.radius)}applyOverlays(t){const n=i=>{const c=t.objects.find(u=>u.name===i);return c===void 0?null:new X().set(...c.matrix.flat())},e=[...this.armatureOverlay.apply(t.armatures,n)],r=t.weights?this.objects.get(t.objects.find(i=>i.name===t.weights?.object)?.id??""):void 0,a=this.weightOverlay.apply(t.weights,r??null,t.weights?n(t.weights.object):null);return a!==null&&e.push(a),this.cursorOverlay.apply(t.cursor),this.applyExtras(t),e}setCameraViewShowing(t){this.lookingThrough!==t&&(this.lookingThrough=t,this.frame&&this.applyExtras(this.frame),vt())}applyExtras(t){const n={};for(const[e,r]of Object.entries(t.cameras)){const a=Lo.safeParse(r);a.success&&(n[e]=a.data)}this.extrasOverlay.apply({lookingThrough:this.lookingThrough,lightDistances:t.light_distances,objects:t.objects.filter(e=>e.visible),active:t.active,cameras:n,lights:t.lights,empties:t.empties,sceneCamera:t.camera_view?.scene_camera??null,renderAspect:t.camera_view?.aspect??1,presented:e=>{const r=t.objects.find(a=>a.name===e);return r?this.objects.get(r.id)??null:null},image:e=>{const r=this.textures.get(e);if(!r)return null;const a=r.texture.image,i=r.width||a?.width||0,c=r.height||a?.height||0;return(i===0||c===0)&&r.ready&&!this.awaitedImages.has(e)&&(this.awaitedImages.add(e),r.ready.then(()=>{this.awaitedImages.delete(e),this.frame&&this.applyExtras(this.frame),vt()},()=>this.awaitedImages.delete(e))),{texture:r.texture,width:i,height:c}}})}applyVisibility(){for(const t of this.frame?.objects??[]){const n=this.objects.get(t.id);if(n&&(n.visible=this.rendered?t.render_visible:t.visible),!t.light)continue;const e=this.lights.get(t.light);e&&(e.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}applyFrame(t){const n=this.frame===null?null:{session:this.frame.session,revision:this.frame.revision},e=Zl.parse(t);if(this.retiredSessions.has(e.session))throw new Error("The runtime session was replaced; its delayed frame cannot overwrite the active model");if(this.frame?.session===e.session&&e.revision<this.frame.revision)throw new Error("The runtime frame is older than the displayed model");const r=new Set(e.objects.map(f=>f.id));if(r.size!==e.objects.length)throw new Error("Runtime object IDs must be unique");const a=new Map(e.objects.map(f=>[f.id,f]));for(const f of e.objects){if(f.mesh!==null&&!e.meshes[f.mesh])throw new Error(`Missing runtime mesh ${f.mesh}`);if(f.volume&&(!e.volumes[f.volume]||f.mesh!==null))throw new Error(`Invalid runtime volume ${f.volume}`);if(f.light&&(!e.lights[f.light]||f.mesh!==null))throw new Error(`Invalid runtime light ${f.light}`);for(const _ of f.materials)if(_!==null&&!e.materials[_])throw new Error(`Missing runtime material ${_}`);const s=new Set([f.id]);let l=f.parent;for(;l!==null;){if(s.has(l))throw new Error("Runtime parent cycle");s.add(l);const _=a.get(l);if(!_)throw new Error(`Missing runtime parent ${l}`);l=_.parent}}const i=new Map,c=new Map;try{for(const[f,s]of Object.entries(e.volumes)){const l=JSON.stringify(s);this.frame?.session===e.session&&this.volumes.get(f)?.signature===l||c.set(f,{signature:l,mesh:Ar(s)})}for(const[f,s]of Object.entries(e.meshes)){if("unchanged"in s){if(this.frame?.session===e.session&&this.meshes.has(f))continue;throw new Error(`${Sa}: the presenter does not hold runtime mesh ${f} (store ${s.store}, revision ${s.revision})`)}const l="hash"in s,_="columns"in s,h=_?`revision:${s.revision}`:l?s.hash:JSON.stringify(s);this.frame?.session===e.session&&this.meshes.get(f)?.signature===h||i.set(f,{signature:h,geometry:_?Wn(La({...s.columns,attributes:s.attributes,activeUv:s.activeUv,renderUv:s.renderUv},h)):l?Wn(s):Va(s)})}}catch(f){for(const s of i.values())s.geometry.dispose();for(const{mesh:s}of c.values())s.geometry.dispose(),s.material.dispose();throw f}this.frame?.session!==e.session&&(this.frame&&this.retiredSessions.add(this.frame.session),this.clear());for(const[f,s]of c){const l=this.volumes.get(f)?.mesh;l&&(l.removeFromParent(),l.geometry.dispose(),l.material.dispose()),this.volumes.set(f,s)}for(const[f,s]of i)this.meshes.get(f)?.geometry.dispose(),this.meshes.set(f,s),this.geometryBuilds++;for(const[f,s]of Object.entries(e.images)){const l=this.textures.get(f);if("width"in s){const m=s.rgba??(s.rgbaBase64?Un(s.rgbaBase64):void 0);if(!m)throw new Error(`Runtime image ${f} carries no raster`);const p=s.tiles?Hl(f,s.tiles,s.colorspace??"sRGB"):void 0;if(l?.udim&&(l.udim.tiles.dispose(),l.udim.map.dispose(),delete l.udim),l&&l.width===s.width&&l.height===s.height){const v=l.texture.image;if(v.data){v.data.set(m),l.texture.needsUpdate=!0,l.revision=s.revision,p&&(l.udim=p);continue}}l?.texture.dispose(),this.textures.set(f,{texture:Wl(m,s.width,s.height,s.colorspace??"sRGB"),width:s.width,height:s.height,revision:s.revision,...p?{udim:p}:{}});continue}const _=s.png??(s.pngBase64?Un(s.pngBase64):void 0);if(!_)throw new Error(`Runtime image ${f} carries no bytes`);l?.texture.dispose(),l?.udim?.tiles.dispose(),l?.udim?.map.dispose();const{texture:h,ready:d}=Ul(_);h.colorSpace=Mt,this.textures.set(f,{texture:h,ready:d,width:0,height:0,revision:s.revision,png:_.slice()})}for(const[f,s]of Object.entries(e.materials)){const l=this.materials.get(f)??new ln;l.name=s.name;const _=s.texture?.tint;s.texture!==void 0?l.color.setRGB(_?.[0]??1,_?.[1]??1,_?.[2]??1,ft):l.color.setRGB(s.color[0],s.color[1],s.color[2],ft),l.opacity=s.color[3];const h=l.opacity<1||s.graph!==void 0&&Rr(s.graph);l.transparent!==h&&(l.transparent=h,l.needsUpdate=!0),l.roughness=s.roughness,l.metalness=s.metallic,l.transmission=s.transmission,l.ior=s.ior,io(l,s.physical,{map:s.texture?.extension==="CLIP",roughness:s.roughness_texture?.extension==="CLIP",normal:s.normal_texture?.extension==="CLIP"});const d=s.normal_texture?.image.name;if(d===void 0)l.normalMap&&(this.textureSamplers.delete(`${f}:normal`),l.normalMap=null,l.needsUpdate=!0);else{const b=this.textures.get(d);if(!b)throw new Error(`${Qt}: missing normal image ${d}`);const w=this.textureSamplers.get(`${f}:normal`,b.texture,s.normal_texture.extension,b.ready,s.normal_texture.uv);l.normalMap!==w&&(l.normalMap=w,l.needsUpdate=!0);const R=s.normal_space==="OBJECT"?Ye:Ze;l.normalMapType!==R&&(l.normalMapType=R,l.needsUpdate=!0),l.normalScale.set(s.normal_strength,s.normal_strength*(s.normal_directx?-1:1))}s.emission?(l.emissive.setRGB(s.emission.color[0],s.emission.color[1],s.emission.color[2],ft),l.emissiveIntensity=s.emission.strength):(l.emissive.setRGB(0,0,0),l.emissiveIntensity=1);const m=s.roughness_texture?.image.name??null;if(m===null)this.roughnessTextureNames.has(f)&&(this.textureSamplers.delete(`${f}:roughness`),l.roughnessMap=null,this.roughnessTextureNames.delete(f),l.needsUpdate=!0);else{const b=this.textures.get(m);if(!b)throw new Error(`${Qt}: the presenter does not hold runtime image ${m} (revision ${s.roughness_texture.image.revision})`);const w=this.textureSamplers.get(`${f}:roughness`,b.texture,s.roughness_texture.extension,b.ready,s.roughness_texture.uv);l.roughnessMap!==w&&(l.roughnessMap=w,this.roughnessTextureNames.set(f,m),l.needsUpdate=!0)}const p=s.texture?.image.name??null;if(p===null)this.textureNames.has(f)&&(this.textureSamplers.delete(`${f}:color`),l.map=null,this.textureNames.delete(f),l.needsUpdate=!0);else{const b=this.textures.get(p);if(!b)throw new Error(`${Qt}: the presenter does not hold runtime image ${p} (revision ${s.texture.image.revision})`);const w=this.textureSamplers.get(`${f}:color`,b.texture,s.texture.extension,b.ready,s.texture.uv);l.map!==w&&(l.map=w,this.textureNames.set(f,p),l.needsUpdate=!0)}const v=s.graph?this.compiledGraph(s.graph):null,g=new Set;qr(l,v,b=>{const w=this.textures.get(b.name);if(!w)throw new Error(`${Qt}: the presenter does not hold runtime image ${b.name} (revision ${b.revision})`);if(b.tiled){if(!w.udim)throw new Error(`${Qt}: runtime image ${b.name} arrived without its UDIM tiles`);return w.udim}const R=`${f}:graph:${b.node}`;g.add(R);const T=this.textureSamplers.get(R,w.texture,b.extension,w.ready),A=b.closest?jn:Lt,O=b.closest?jn:b.mipmap?Jo:Lt;return(T.magFilter!==A||T.minFilter!==O)&&(T.magFilter=A,T.minFilter=O,T.needsUpdate=!0),T},this.photograph);for(const b of this.graphSamplers.get(f)??[])g.has(b)||this.textureSamplers.delete(b);this.graphSamplers.set(f,g),this.materials.set(f,l)}for(const f of e.objects){let s=this.objects.get(f.id);const l=f.volume?this.volumes.get(f.volume).mesh:null;if((!s||(l?s!==l:!!s.isMesh!=(f.mesh!==null)))&&(s?.removeFromParent(),s=l??(f.mesh!==null?new Tt(this.meshes.get(f.mesh).geometry,this.fallback):new Go),this.objects.set(f.id,s)),s.name=f.name,f.type==="CAMERA"||f.type==="LIGHT"||f.type==="EMPTY"?s.userData.vgaiOwnOverlay=!0:delete s.userData.vgaiOwnOverlay,s.matrixAutoUpdate=!1,s.matrix.set(...f.matrix.flat()),f.parent){const _=new X().set(...a.get(f.parent).matrix.flat());s.matrix.premultiply(_.invert())}if(s.matrix.decompose(s.position,s.quaternion,s.scale),f.texspace?s.userData.blenderTexspace=f.texspace:delete s.userData.blenderTexspace,f.default_color!==void 0?s.userData.blenderDefaultColor=f.default_color:delete s.userData.blenderDefaultColor,f.mesh!==null){const _=s;_.geometry=this.meshes.get(f.mesh).geometry,_.material=f.materials.length?f.materials.map(h=>h===null?this.fallback:this.materials.get(h)):this.fallback,Zr(_)}if(f.light){const _=this.lights.get(f.light)??null,h=vr(e.lights[f.light],_);_&&_!==h&&(_.removeFromParent(),_.dispose()),h.parent!==s&&s.add(h),h.userData.vgaiOwnOverlay=!0,xr(h,s),this.lights.set(f.light,h)}}for(const f of e.objects){const s=this.objects.get(f.id),l=f.parent===null?this.root:this.objects.get(f.parent);s.parent!==l&&l.add(s)}for(const[f,s]of this.objects)r.has(f)||(s.removeFromParent(),this.objects.delete(f));for(const[f,s]of this.volumes)e.volumes[f]||(s.mesh.geometry.dispose(),s.mesh.material.dispose(),this.volumes.delete(f));for(const[f,s]of this.meshes)e.meshes[f]||(s.geometry.dispose(),this.meshes.delete(f));for(const[f,s]of this.materials)if(!e.materials[f]){for(const l of["normal","roughness","color"])this.textureSamplers.delete(`${f}:${l}`);for(const l of this.graphSamplers.get(f)??[])this.textureSamplers.delete(l);this.graphSamplers.delete(f),s.dispose(),this.materials.delete(f)}for(const[f,s]of this.lights)e.lights[f]||(s.removeFromParent(),s.dispose(),this.lights.delete(f));this.root.updateMatrixWorld(!0),this.frame={...e,meshes:{},volumes:{}},this.worldKey=JSON.stringify(e.world??null);const u=this.applyOverlays(e);u.length&&(this.frame={...this.frame,warnings:[...this.frame.warnings,...u]}),this.applyVisibility(),this.applyWorkbench(),this.heldRendered!==null&&!this.capturing&&this.report(this.applyRendered(!0,this.heldRendered()));for(const f of[...this.frameListeners])f();return{...this.inspect(),held:n}}inspect(){return{session:this.frame?.session,revision:this.frame?.revision,active:this.frame?.active,mode:this.frame?.mode,geometryBuilds:this.geometryBuilds,objects:[...this.objects].map(([t,n])=>({id:t,name:n.name,uuid:n.uuid,geometry:n.geometry?.uuid,visible:n.visible}))}}snapshot(){return this.frame}captureSnapshot(){const t=this.frame;if(!t)throw new Error("Blender capture requires a presented frame");const n=structuredClone({...t,images:{},armatures:{},weights:null});for(const[u,{signature:f,geometry:s}]of this.meshes){const l=d=>{const m=s.getAttribute(d);if(!m)return null;if(!(m instanceof it))throw new Error(`Blender capture cannot copy interleaved ${d}`);return new Float32Array(m.array)},_=l("position");if(!_)throw new Error(`Blender capture mesh ${u} has no positions`);const h=s.getIndex();n.meshes[u]={hash:f,positions:_,normals:l("normal"),uv:l("uv"),uvLayers:Object.entries(s.userData.blenderUvChannels??{}).map(([d,m])=>{const p=l(`uv${m}`);if(!p)throw new Error(`Blender capture mesh ${u} is missing UV layer ${d}`);return{name:d,data:p}}),orco:s.userData.blenderOrcoFromDoor?l("blenderOrco"):null,attributeLayers:(s.userData.blenderAttributes??[]).map(d=>{const m=l(Vt(d));if(!m)throw new Error(`Blender capture mesh ${u} is missing attribute ${d}`);return{name:d,data:m}}),indices:h?new Uint32Array(h.array):Uint32Array.from({length:_.length/3},(d,m)=>m),groups:s.groups.map(d=>({start:d.start,count:d.count,materialIndex:d.materialIndex??0}))}}for(const[u,{signature:f}]of this.volumes)n.volumes[u]=me.parse(JSON.parse(f));const e=new Set(Object.values(n.materials).flatMap(u=>[u.texture?.image.name,u.roughness_texture?.image.name,u.normal_texture?.image.name,...Object.values(u.graph?.nodes??{}).map(f=>f.props.image?.name)].filter(f=>f!==void 0)));for(const u of e){const f=this.textures.get(u);if(!f)throw new Error(`Blender capture image ${u} is not resident`);if(f.png)n.images[u]={revision:f.revision,png:f.png.slice()};else{const s=f.texture.image?.data;if(!(s instanceof Uint8Array))throw new Error(`Blender capture image ${u} has no resident raster`);n.images[u]={revision:f.revision,width:f.width,height:f.height,rgba:s.slice(),colorspace:f.texture.colorSpace===no?"data":"sRGB",...f.udim?{tiles:f.udim.frame}:{}}}}const r=this.createWorldVolumePass(),a=new co;a.photograph=!0;let i=!1;const c=()=>{i||(i=!0,r?.dispose(),a.dispose(),a.root.removeFromParent())};try{a.applyFrame(n),this.root.updateWorldMatrix(!0,!1),a.root.matrix.copy(this.root.matrixWorld),a.root.updateMatrixWorld(!0)}catch(u){throw c(),u}return{effect:r,root:a.root,session:t.session,revision:t.revision,prepare:u=>{if(i)throw new Error("Blender capture snapshot is disposed");return a.setRendered(!0,u)},dispose:c}}createWorldVolumePass(){const t=Do(this.frame?.world);return t?new il(t):void 0}recordPresentation(t){if(typeof t!="object"||t===null)return;const n=t,e=n.meshes;if(typeof e!="object"||e===null)return;const r=typeof n.session=="string"?n.session:null;r!==this.submittedSession&&(this.submittedMeshes.clear(),this.photographs.length=0,this.submittedSession=r);const a=e;for(const[i,c]of Object.entries(a))typeof c=="object"&&c!==null&&!("unchanged"in c)&&this.submittedMeshes.set(i,c);for(const i of[...this.submittedMeshes.keys()])i in a||this.submittedMeshes.delete(i);this.submitted={...n,meshes:Object.fromEntries(this.submittedMeshes)}}recordPhotograph(t){this.photographs.push(t)}observations(){return{presentation:this.submitted,photographs:this.photographs}}clear(){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:n}of this.textures.values())t.dispose(),n?.tiles.dispose(),n?.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 li=new co;function ye(o){const t=atob(o),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function $n(o){const t=ye(o);return new Float32Array(t.buffer,t.byteOffset,t.byteLength>>2)}function Jl(o){const t=ye(o);return new Uint16Array(t.buffer,t.byteOffset,t.byteLength>>1)}function ti(o){return new X().set(...o.flat())}function Bo(o,t){return[o.object,o.mesh,o.armature,o.vertexCount,o.bones.length,t].join("|")}class ni{#n=new Map;#o=null;#a=null;#t=null;#i=null;#e=null;#l=null;#s=new Set;#u=0;#_=[];#r=0;get version(){return this.#u}get engineCalls(){return this.#r}subscribe(t){return this.#s.add(t),()=>this.#s.delete(t)}#f(){this.#u++;for(const t of[...this.#s])t()}state(){const t=this.#t,n=t?.frameStart??1,e=t?.frameEnd??250,r=t?.fps??24;return{frame:this.frame(),start:n,end:e,fps:r,action:t?.action??null,object:t?.object??null,armature:t?.armature??null,bones:[...this.#n.values()].reduce((a,i)=>a+i.bones.length,0),keyframes:t?.keyframes??[],summary:t?.summary??[],clipStart:t?.clipStart??null,clipEnd:t?.clipEnd??null,tracks:t?.tracks.length??0,bound:[...this.#n.keys()],warnings:this.#_,engineCalls:this.#r,blenderFrame:t?.frameCurrent??null}}playhead(){return this.#t?this.frame():null}frame(){const t=this.#t;return!t||!this.#a||t.clipStart===void 0?t?.frameCurrent??1:this.#i!==null?this.#i:t.clipStart+this.#a.time*t.fps}get playable(){return this.#a!==null}async bind(t,n){this.#r++;const e=await n.rig();if(!e)return;const r=[],a=new Set;let i=!1;for(const l of e.rigs){if(!l.object||!l.armature||!l.skinIndexBase64||!l.skinWeightBase64){l.reason&&r.push(l.reason);continue}a.add(l.object);const _=Bo(l,e.frame);if(this.#n.get(l.object)?.signature===_)continue;const h=this.#d(t,l,e.frame,r);h&&(this.#n.get(l.object)?.skeleton.dispose(),this.#n.set(l.object,h),i=!0)}for(const[l,_]of[...this.#n])a.has(l)||(_.skeleton.dispose(),_.boneRoot.removeFromParent(),this.#n.delete(l),i=!0);this.#r++;const c=await n.clip(),u=this.#t,f=c?.action!==u?.action||c?.tracks.length!==u?.tracks.length||c?.clipStart!==u?.clipStart||c?.clipEnd!==u?.clipEnd;this.#t=c??null,c?.reason&&r.push(c.reason),c&&(f||i)&&this.#h(t,c,r);const s=this.#e?.snapshot().playbackState==="playing";c&&!s&&u?.frameCurrent!==c.frameCurrent&&(this.#c(c.frameCurrent),this.#e&&c.fps>0&&this.#e.seek(c.frameCurrent/c.fps)),this.#_=r,this.#f()}#d(t,n,e,r){const a=t.objectForBlenderName(n.object??""),i=t.objectForBlenderName(n.armature??"");if(!a||!i)return null;const c=a,u=c.geometry;if(!u)return null;const f=u.getAttribute("blenderVertex");if(!f)return r.push(`"${n.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(n.vertexCount===0)return null;let s=0;for(let T=0;T<f.count;T++)s=Math.max(s,f.getX(T));if(s>=n.vertexCount)return r.push(`"${n.object}" is not skinned here: its presented geometry references Blender vertex ${s} while the mesh declares ${n.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 l=Jl(n.skinIndexBase64??""),_=$n(n.skinWeightBase64??""),h=f.count,d=new Uint16Array(h*4),m=new Float32Array(h*4);for(let T=0;T<h;T++){const A=f.getX(T);for(let O=0;O<4;O++)d[T*4+O]=l[A*4+O]??0,m[T*4+O]=_[A*4+O]??0}u.setAttribute("skinIndex",new ta(d,4)),u.setAttribute("skinWeight",new bt(m,4));const p=new ot;p.name=`${n.armature}:bones`;const v=[],g=n.bones.map(T=>ti(T.pose)),b=new Map(n.bones.map((T,A)=>[T.name,A]));n.bones.forEach((T,A)=>{const O=new na;O.name=T.name,v.push(O);const M=T.parent===null?void 0:b.get(T.parent);(M===void 0?g[A].clone():g[M].clone().invert().multiply(g[A])).decompose(O.position,O.quaternion,O.scale),(M===void 0?p:v[M]).add(O)}),i.add(p);const w=new oa(u,c.material);w.name=c.name,w.matrixAutoUpdate=!1,w.matrix.copy(c.matrix),w.matrix.decompose(w.position,w.quaternion,w.scale),w.userData=c.userData,w.frustumCulled=!1,t.replacePresentedObject(c,w),t.root.updateMatrixWorld(!0);const R=new ea(v);return w.bind(R,w.matrixWorld.clone()),n.constrainedBones?.length&&r.push(`Bone constraints on ${n.constrainedBones.join(", ")}: the clip is derived from the F-Curves alone, so those bones play their channels rather than Blender's solved pose.`),n.unmappedGroups?.length&&r.push(`${n.object} carries vertex groups no bone is named for (${n.unmappedGroups.join(", ")}); they weight nothing here, exactly as they deform nothing in Blender.`),{object:n.object??"",armature:n.armature??"",mesh:w,boneRoot:p,bones:v,skeleton:R,frame:e,signature:Bo(n,e)}}#h(t,n,e){if(this.#o?.stopAllAction(),this.#o=null,this.#a=null,!n.tracks.length||n.clipStart===void 0||n.clipEnd===void 0)return;const r=n.armature?t.objectForBlenderName(n.armature):null;if(!r)return;const a=new Map;for(const l of this.#n.values())if(l.armature===n.armature)for(const _ of l.bones)a.set(_.name,_);const i=[],c=new Set;for(const l of n.tracks){const _=a.get(l.bone);if(!_){c.add(l.bone);continue}const h=$n(l.timeBase64),d=$n(l.valueBase64),m=`${_.uuid}.${l.property}`;i.push(l.property==="quaternion"?new aa(m,Array.from(h),Array.from(d)):new ra(m,Array.from(h),Array.from(d)))}if(c.size&&e.push(`${n.action} animates ${[...c].join(", ")}, which this binding has no bone for.`),!i.length)return;const u=n.duration??(n.clipEnd-n.clipStart)/n.fps,f=new la(r),s=f.clipAction(new ia(n.action??"action",u,i));s.setLoop(sa,Number.POSITIVE_INFINITY),s.play(),this.#o=f,this.#a=s,this.#c(n.frameCurrent),this.#m()}#c(t){const n=this.#t;if(!n||!this.#o||n.clipStart===void 0||n.clipEnd===void 0)return;const e=Math.min(n.clipEnd,Math.max(n.clipStart,t));this.#i=e;const r=(n.clipEnd-n.clipStart)/n.fps;this.#o.setTime(Math.min(r-1e-4,(e-n.clipStart)/n.fps)),this.#m()}#m(){for(const t of this.#n.values())t.boneRoot.updateMatrixWorld(!0),t.skeleton.update()}get scene(){return this.#t?.scene??null}async writeBookmark(){const t=Math.round(this.frame()),n=this.#t;if(!n)return t;const e=n.scene;return!e||n.frameCurrent===t||(this.#r++,await _a(`bpy.data.scenes[${JSON.stringify(e)}]`,"frame_current",t,void 0,!1),this.#t={...n,frameCurrent:t},this.#f()),t}get transport(){return this.#e}attachTo(t){this.#l?.(),this.#e=t;const n=t.attach({id:this.#t?.action??"blender-action",label:this.#t?.action??"Action",range:()=>{const i=this.#t,c=i?.fps||24;return{start:(i?.frameStart??1)/c,end:(i?.frameEnd??250)/c,fps:c}},seek:i=>this.seekSeconds(i)}),e=t.onSettled(()=>{this.writeBookmark()}),r=()=>{e(),n(),this.#e===t&&(this.#e=null),this.#l=null};this.#l=r;const a=this.#t;return a&&a.fps>0&&t.seek(a.frameCurrent/a.fps),r}seekSeconds(t){const n=this.#t?.fps||24;this.#c(Math.round(t*n)),this.#f()}keyframes(){return(this.#t?.keyframes??[]).map(t=>t.frame)}dispose(){this.#l?.(),this.#o?.stopAllAction(),this.#o=null,this.#a=null;for(const t of this.#n.values())t.skeleton.dispose(),t.boneRoot.removeFromParent();this.#n.clear()}}const we=new ni;function ii(o){return we.subscribe(o)}function si(){return we.version}export{we as a,si as b,li as c,ii as s};